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: record backup snapshot consistency and admit media recovery and CD frames (#9982)
Adam Eivy06903b4bd8ad
diff --git a/docs/BACKUP.md b/docs/BACKUP.mdindex 0171acb3f7..7c56ebcd2c 100644--- a/docs/BACKUP.md+++ b/docs/BACKUP.md@@ -28,7 +28,11 @@ finished file is an unreferenced extra, never a dangling reference) andpublishes once the cut releases; the lane stays occupied meanwhile, but therenderer is not stopped and cancellation is unchanged. A terminal write thatfails inside the admission is retried inside it and releases it when it gives-up.+up. Only a queue snapshot written inside an admission lease commits a staged+completion: once storage recovers, an unrelated queue write (progress, a new+job, the shutdown flush) keeps that job `running` on disk and hands it to a+recovery commit that takes its own lease, waiting out any open cut, so the+terminal row and its attach hooks still publish together.Database maintenance shares the same boundary and never terminates a render orstops PM2 to obtain it:@@ -60,9 +64,11 @@ Admission inventory (`withBackupAssetPublication`):| Media-job completion: queue terminal row + `completed` fan-out (`mediaJobQueue/index.js`) | Covered || Attach hooks on `completed` via `mediaJobImageHook.js` (writers-room, catalog, music-video scene image/video/cast-sets, CD scene image/music bed, FableLoom scene image/video, sprite references, deck cards, music studio) | Covered || Pipeline filename hooks (`filenameHookFactory.js` comic pages and storyboards, `seasonCoverFilenameHook.js`) | Covered |-| Recovery commit of a completion whose terminal write failed (the next queue write acknowledges it outside any admission) | Outstanding |+| Recovery commit of a completion whose terminal write failed (`mediaJobQueue/index.js`) | Covered: only an admitted snapshot commits it (#9982 partial) || Universe Builder completion listeners: collection filing, canon entry-ref append, and sidecar enrichment (`universeBuilderCollectionHook.js`); character reference sheet copy and pointer stamp (`universeCharacterSheet.js`) | Covered (#9982 partial) |-| Other `mediaJobEvents` `completed` subscribers that write rows (sprite animation, Creative Director scene runner/plan advance/seed settle, music-video production) | Outstanding |+| 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`) | Outstanding (#9982) || 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) |@@ -70,8 +76,9 @@ Admission inventory (`withBackupAssetPublication`):| Voice Studio audition and character assignment (`voice/studio.js`) | Covered from source-file write/copy through profile-row commit and failed-write cleanup (#9982 partial) || Music Video development artifact import/generated save and vocal-stem attachment (`musicVideo/devArtifactService.js`, `musicVideo/vocalStem.js`) | Covered from final file copy/write through project-record commit and failed-write cleanup (#9982 partial) || Music-library deletion (`pipeline/musicLibrary.js`) | Outstanding: its route intentionally leaves existing issue/project references to the removed file (#9982) |-| Other voice artifact owners (fine-tune and benchmark outputs) and Music Video asset workflows | Outstanding (#9982) |-| Other durable replacement/deletion owners and final global readiness/invariant check | Outstanding (#9982) |+| Voice fine-tune and benchmark outputs (`voice/fineTuning.js`, `voice/profileBenchmarks.js`) and other Music Video asset workflows | Outstanding (#9982) |+| 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) |Direct gallery uploads encode before admission, then publish the final image,@@ -118,19 +125,34 @@ so it cannot drop a concurrent prompt or visibility edit. Records outsideuniverse canon that named a deleted image (media-collection items, for example)keep their references; only universe canon references are purged with it.-The remaining inventory includes music-library deletion, other voice artifacts,-direct render/index completion listeners, and the other completion paths above.-Their persistence adapters and direct filesystem calls still need workflow-level classification;-independently locking `fileCore` or SQL primitives would not cover the gap-between writes. No domain is newly excluded by this slice, and the final global-readiness check is still pending.+Creative Director frame sampling holds its lease while ffmpeg decodes the+clip, a few seconds for a typical scene; the evaluator dispatch that follows+stays outside it.++**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+takes the lease is missing from the inventory. Every snapshot records the claim+derived from it as `assetConsistency` in its `manifest.json`, the backup status+(`GET /api/backup/status`) and the run result. `scope: "global"` is reported+only when no owner is outstanding; until then the scope is `admitted-owners`+and `outstanding` lists the owner ids still outside admission. An unrecognized+status counts as outstanding, never as covered. Snapshots written before this+field existed carry no claim and must be treated as partial.++The remaining inventory includes sprite animation completion, music-library+deletion, voice fine-tune and benchmark outputs, other Music Video asset+workflows, and owners not yet classified. Their persistence adapters and direct+filesystem calls still need workflow-level classification; independently+locking `fileCore` or SQL primitives would not cover the gap between writes.+No domain is excluded from the snapshot to satisfy the claim.This is part of [the cross-store consistency work](https://github.com/atomantic/PortOS/issues/9923).-Until every owner is covered, `status: ok` reports that the file-copy, manifest, and database dump completed; it does not assert that every-database asset reference resolves to the captured filesystem bytes. A restore-operator should verify affected assets before treating a snapshot as a complete-recovery point.+While `assetConsistency.scope` is `admitted-owners`, `status: ok` reports that+the file copy, manifest, and database dump completed; it does not assert that+every database asset reference resolves to the captured filesystem bytes. A+restore operator should verify the outstanding owners' assets before treating+a snapshot as a complete recovery point.Now that PostgreSQL is a **required** dependency (it owns the creative catalog, memory, and a growing set of app-native records — see [Storage Classification Contract](./STORAGE.md)), **the database dump is part of required system state, not an optional extra.** A snapshot that captured `data/` but failed to capture the DB is incomplete, and PortOS surfaces that explicitly.diff --git a/scripts/ci-test-plan.js b/scripts/ci-test-plan.jsindex e10d7888e9..18f65f6c38 100644--- a/scripts/ci-test-plan.js+++ b/scripts/ci-test-plan.js@@ -255,6 +255,9 @@ export const ALWAYS_RUN_TESTS = [// walkers (#8723): the offending file is never imported by the guard, so// impact selection only reaches them when the guard itself changes.'server/lib/apiRouteGraph.test.js',+ // Whole-tree scanner (#9982): any server module can start taking backup+ // admission with no import edge back to the owner inventory it must join.+ 'server/lib/backupAssetOwners.test.js','server/lib/childProcess.guards.test.js','server/lib/cliChildEnv.test.js','server/lib/editorial/proseTics.test.js',diff --git a/server/lib/README.md b/server/lib/README.mdindex 42a73eb158..a7a65c1dda 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -621,7 +621,8 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| Module | Purpose ||---|---|-| `backupSnapshotBoundary.js` | `withBackupAssetPublication(work)` admits a complete durable file-plus-row mutation; `acquireBackupSnapshotCut()` drains admitted work and pauses new publication through backup's file copy, database dump, and manifest. Nested mutation calls reuse their lease; `runOutsideBackupAssetPublication(work)` lets a synchronous event fan-out give each listener its own lease. |+| `backupAssetOwners.js` | `BACKUP_ASSET_OWNERS` inventories every durable file-plus-row owner as `admitted`, `reference-only`, or `outstanding`; `backupAssetConsistency()` derives the consistency a backup snapshot may claim (`global` only when nothing is outstanding, otherwise `admitted-owners` with the outstanding ids). Its test keeps admitted entries and `withBackupAssetPublication` call sites in step. |+| `backupSnapshotBoundary.js` | `withBackupAssetPublication(work)` admits a complete durable file-plus-row mutation; `acquireBackupSnapshotCut()` drains admitted work and pauses new publication through backup's file copy, database dump, and manifest. Nested mutation calls reuse their lease; `runOutsideBackupAssetPublication(work)` lets a synchronous event fan-out give each listener its own lease; `holdsBackupAssetPublication()` tells a writer whether it runs inside an active lease. || `backupConfig.js` | `resolveBackupConfig(settings.backup)` + `DEFAULT_BACKUP_CRON` — the single declaring module for how a SPARSE backup settings slice resolves (#6632): an omitted `enabled` means enabled, a missing/blank `cronExpression` means midnight (`0 0 * * *`), and `scheduled` additionally requires a `destPath`. Also `resolveRetentionCount(settings.backup)` + `DEFAULT_RETENTION_COUNT`/`MIN_RETENTION_COUNT`/`MAX_RETENTION_COUNT` (#8334): per-source completed-snapshot retention, where an omitted or `null` `retentionCount` means unlimited — a NEW install ships the `30` default on disk via `data.reference/settings.json`, never invented here for an absent value. Read-time resolution only — nothing on disk changes. Shared by `services/backupScheduler.js` (registration + handler eligibility, and the retention count `services/backup.js#runBackup` prunes with) and `routes/settings.js` (the GET projects effective values), so the Settings screen can render what the scheduler will actually do instead of inventing its own defaults. || `systemIdle.js` | `summarizeSystemActivity(processingSnapshot)` → `{ idle, activeCount, queuedCount, blockers[] }` + `describeActivityBlockers` — the ONE definition of "is this install doing anything", derived from the `/api/system/processing` snapshot. Queued work counts as active. Rendered by the dashboard's Live activity widget and refused on by the unattended auto-updater, so the two can never disagree about a window in which PortOS may restart itself. Every blocker label is generated prose (a count and a noun); no snapshot content is echoed. || `browserConfig.js` | Shared custom browser path helpers for deriving macOS app bundles, detecting configured browser choices, normalizing browser config, and validating Chrome-compatible binary paths. |diff --git a/server/lib/backupAssetOwners.js b/server/lib/backupAssetOwners.jsnew file mode 100644index 0000000000..61b704a33f--- /dev/null+++ b/server/lib/backupAssetOwners.js@@ -0,0 +1,86 @@+/**+ * Inventory of durable asset owners for backup snapshot consistency (#9923).+ * An owner is one workflow that writes, replaces or deletes bytes under `data/`+ * together with a row (PostgreSQL or a `data/` record) that names them.+ *+ * - `admitted`: holds `withBackupAssetPublication` from its first byte change+ * through the row that names (or stops naming) those bytes. Every listed+ * module calls it; `backupAssetOwners.test.js` keeps this list and the code+ * in step in both directions.+ * - `reference-only`: writes rows naming bytes that were already durable before+ * its trigger was published, and writes no bytes itself, so there is no gap+ * for a cut to land in.+ * - `outstanding`: still changes bytes and rows outside admission.+ *+ * A snapshot claims global file-and-row consistency only when nothing is+ * outstanding (`backupAssetConsistency`). Module paths are relative to `server/`.+ */++export const BACKUP_ASSET_OWNERS = Object.freeze([+ { id: 'music-take-publication', status: 'admitted', modules: ['services/musicTakePublication.js'] },+ { id: 'media-job-completion', status: 'admitted', modules: ['services/mediaJobQueue/index.js'] },+ { id: 'media-job-attach-hooks', status: 'admitted', modules: ['services/mediaJobImageHook.js'] },+ {+ id: 'pipeline-filename-hooks',+ status: 'admitted',+ modules: ['services/pipeline/filenameHookFactory.js', 'services/pipeline/seasonCoverFilenameHook.js'],+ },+ {+ id: 'universe-builder-render-listeners',+ status: 'admitted',+ modules: ['services/universeBuilderCollectionHook.js', 'services/universeCharacterSheet.js'],+ },+ { id: 'gallery-image-workflows', status: 'admitted', modules: ['services/imageGen/local.js'] },+ { id: 'gallery-image-deletion-canon-purge', status: 'admitted', modules: ['services/galleryImageDeletion.js'] },+ { id: 'video-history-deletion', status: 'admitted', modules: ['services/videoGen/historyOps.js'] },+ {+ id: 'lora-dataset-workflows',+ status: 'admitted',+ modules: ['services/loraDatasets.js', 'services/loraDatasetGenerate.js'],+ },+ { id: 'voice-studio', status: 'admitted', modules: ['services/voice/studio.js'] },+ {+ id: 'music-video-development-artifacts',+ status: 'admitted',+ modules: ['services/musicVideo/devArtifactService.js', 'services/musicVideo/vocalStem.js'],+ },+ {+ id: 'creative-director-evaluation-frames',+ status: 'admitted',+ modules: ['services/creativeDirector/sceneRunner.js', 'services/creativeDirector/completionHook.js'],+ },+ {+ // Scene status/auto-accept, plan-step settlement and the seed-frame wait+ // record a finished render's job id; its file was written before the+ // queue's admitted completion published that job.+ id: 'creative-director-render-settlement',+ status: 'reference-only',+ modules: [+ 'services/creativeDirector/sceneRunner.js',+ 'services/creativeDirector/planAdvance.js',+ 'services/creativeDirector/completionHook.js',+ ],+ },+ { id: 'music-video-production-settlement', status: 'reference-only', modules: ['services/musicVideo/productionService.js'] },+ { id: 'sprite-animation-completion', status: 'outstanding', modules: ['services/sprites/localAnimationJobHook.js'] },+ { id: 'music-library-deletion', status: 'outstanding', modules: ['services/pipeline/musicLibrary.js'] },+ {+ id: 'voice-training-artifacts',+ status: 'outstanding',+ modules: ['services/voice/fineTuning.js', 'services/voice/profileBenchmarks.js'],+ },+ // Music Video asset workflows beyond development artifacts and vocal stems,+ // and every replacement/deletion owner this inventory has not classified yet.+ { id: 'music-video-asset-workflows', status: 'outstanding', modules: [] },+ { id: 'unclassified-durable-owners', status: 'outstanding', modules: [] },+]);++/**+ * The consistency a snapshot taken now may claim: `global` only when no owner+ * is outstanding, otherwise `admitted-owners` naming what is still outside.+ */+export function backupAssetConsistency(owners = BACKUP_ASSET_OWNERS) {+ const outstanding = owners.filter(owner => owner.status !== 'admitted' && owner.status !== 'reference-only')+ .map(owner => owner.id);+ return { scope: outstanding.length ? 'admitted-owners' : 'global', outstanding };+}diff --git a/server/lib/backupAssetOwners.test.js b/server/lib/backupAssetOwners.test.jsnew file mode 100644index 0000000000..5d2056d115--- /dev/null+++ b/server/lib/backupAssetOwners.test.js@@ -0,0 +1,72 @@+/**+ * The owner inventory decides what consistency a backup snapshot may claim, so+ * it must agree with the code in both directions (#9982): every module it calls+ * admitted really holds the admission lease, and every module that takes the+ * lease is inventoried. Otherwise a stale entry could let a snapshot claim+ * global consistency, or a newly admitted workflow could go unrecorded.+ */+import { describe, expect, it } from 'vitest';+import { execFileSync } from 'child_process';+import { existsSync, readFileSync } from 'fs';+import { dirname, join } from 'path';+import { fileURLToPath } from 'url';+import { BACKUP_ASSET_OWNERS, backupAssetConsistency } from './backupAssetOwners.js';+import { blankComments } from './sourceScan.js';++const SERVER_ROOT = dirname(dirname(fileURLToPath(import.meta.url)));+const BOUNDARY_MODULE = 'lib/backupSnapshotBoundary.js';+const STATUSES = new Set(['admitted', 'reference-only', 'outstanding']);+const takesAdmission = (path) => /\bwithBackupAssetPublication\s*\(/+ .test(blankComments(readFileSync(join(SERVER_ROOT, path), 'utf8')));+const admittedModules = new Set(BACKUP_ASSET_OWNERS+ .filter(owner => owner.status === 'admitted')+ .flatMap(owner => owner.modules));++describe('backup asset owner inventory', () => {+ it('names each owner once, with a known status and modules that exist', () => {+ expect(new Set(BACKUP_ASSET_OWNERS.map(owner => owner.id)).size).toBe(BACKUP_ASSET_OWNERS.length);+ for (const owner of BACKUP_ASSET_OWNERS) {+ expect(STATUSES.has(owner.status), owner.id).toBe(true);+ for (const path of owner.modules) expect(existsSync(join(SERVER_ROOT, path)), path).toBe(true);+ }+ });++ it('lists only modules that hold the admission lease as admitted', () => {+ for (const path of admittedModules) expect(takesAdmission(path), path).toBe(true);+ });++ it('inventories every module that takes the admission lease', () => {+ const sources = execFileSync('git', ['ls-files', '*.js', '*.mjs'], { cwd: SERVER_ROOT, encoding: 'utf8' })+ .split('\n')+ .filter(path => path && !path.includes('.test.') && path !== BOUNDARY_MODULE && !path.startsWith('node_modules/'));+ // A broken `git ls-files` would otherwise pass by scanning nothing.+ expect(sources.length).toBeGreaterThan(200);+ const admitting = sources.filter(takesAdmission);+ expect(admitting.length).toBeGreaterThan(0);+ expect(admitting.filter(path => !admittedModules.has(path))).toEqual([]);+ });+});++describe('backupAssetConsistency', () => {+ it('claims global consistency only when no owner is outstanding', () => {+ expect(backupAssetConsistency([+ { id: 'example-admitted', status: 'admitted', modules: [] },+ { id: 'example-reference', status: 'reference-only', modules: [] },+ ])).toEqual({ scope: 'global', outstanding: [] });+ expect(backupAssetConsistency([+ { id: 'example-admitted', status: 'admitted', modules: [] },+ { id: 'example-outstanding', status: 'outstanding', modules: [] },+ ])).toEqual({ scope: 'admitted-owners', outstanding: ['example-outstanding'] });+ });++ it('treats an unrecognized status as outstanding rather than covered', () => {+ expect(backupAssetConsistency([{ id: 'example-typo', status: 'admited', modules: [] }]))+ .toEqual({ scope: 'admitted-owners', outstanding: ['example-typo'] });+ });++ it('reports the shipped inventory as partial while owners remain outside admission', () => {+ const outstanding = BACKUP_ASSET_OWNERS.filter(owner => owner.status === 'outstanding').map(owner => owner.id);+ expect(outstanding.length).toBeGreaterThan(0);+ expect(backupAssetConsistency()).toEqual({ scope: 'admitted-owners', outstanding });+ });+});diff --git a/server/lib/backupSnapshotBoundary.js b/server/lib/backupSnapshotBoundary.jsindex f3c4ef0fba..75efcae6c7 100644--- a/server/lib/backupSnapshotBoundary.js+++ b/server/lib/backupSnapshotBoundary.js@@ -53,6 +53,15 @@ export async function withBackupAssetPublication(work) {}}+/**+ * Whether the caller runs inside an active admission lease, so no cut can be+ * active until its work settles. A listener scope created by+ * runOutsideBackupAssetPublication is not a lease of its own.+ */+export function holdsBackupAssetPublication() {+ return publicationScope.getStore()?.active === true;+}+/** Wait for already admitted workflows to settle, or reject when they do not. */async function awaitDrain(timeoutMs) {let timer;diff --git a/server/lib/index.js b/server/lib/index.jsindex 4b693c0681..041a283767 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -605,6 +605,7 @@ export * from './textUtils.js';export * from './vaultCrypto.js';// === Model & config ===+export * from './backupAssetOwners.js';export * from './backupConfig.js';export * from './backupSnapshotBoundary.js';export * from './systemIdle.js';diff --git a/server/services/backup.js b/server/services/backup.jsindex 790007ccd8..a026797bd8 100644--- a/server/services/backup.js+++ b/server/services/backup.js@@ -17,6 +17,7 @@ import { basename, join, resolve, relative, isAbsolute } from 'path';import { PATHS, ensureDir, readJSONFile, readJSONFileStrict, atomicWrite, sha256File } from '../lib/fileUtils.js';import { createFileWriteQueue } from '../lib/fileWriteQueue.js';import { acquireBackupSnapshotCut } from '../lib/backupSnapshotBoundary.js';+import { backupAssetConsistency } from '../lib/backupAssetOwners.js';import { assertDatabaseAdmission } from '../lib/databaseMaintenanceJournal.js';import { createLineReader } from '../lib/streamLines.js';import { getEvent } from './eventScheduler.js';@@ -635,6 +636,9 @@ export async function runBackup(destPath, io = null, { excludePaths = [], disabl// that started first drains completely; new writers wait until the dump// and manifest are published. Rendering/provider work is outside admission.const releaseSnapshotCut = await acquireBackupSnapshotCut();+ // The snapshot records how far that guarantee reaches: `global` only once+ // no durable asset owner remains outside admission.+ const assetConsistency = backupAssetConsistency();let pgResult;try {const excludeFlags = effectiveExcludes.flatMap(p => ['--exclude', p]);@@ -645,7 +649,8 @@ export async function runBackup(destPath, io = null, { excludePaths = [], disablconst pgDumpPath = join(snapshotDir, 'portos-db.sql');pgResult = await dumpPostgres(pgDumpPath);manifest = await generateManifest(dataDestDir, join(snapshotDir, 'manifest.json'), pgDumpPath, {- allowMissingDump: pgResult.status === 'skipped' || pgResult.status === 'failed'+ allowMissingDump: pgResult.status === 'skipped' || pgResult.status === 'failed',+ assetConsistency,});} finally {releaseSnapshotCut();@@ -659,6 +664,7 @@ export async function runBackup(destPath, io = null, { excludePaths = [], disablstatus,filesChanged: changedFiles.length,pgBackup: pgResult,+ assetConsistency,error: pgResult.status === 'failed' ? `DB dump ${pgResult.reason}` : null});@@ -677,7 +683,7 @@ export async function runBackup(destPath, io = null, { excludePaths = [], disabl}}- const result = await complete({ snapshotId, filesChanged: changedFiles.length, status, lastRun, manifest, pgBackup: pgResult });+ const result = await complete({ snapshotId, filesChanged: changedFiles.length, status, lastRun, manifest, pgBackup: pgResult, assetConsistency });// Prune only after `complete()` has cleared this snapshot's own// `.in-progress` marker and released `activeSnapshotId` — pruning any@@ -859,8 +865,9 @@ function manifestReadFailure(operation, err) {* @param {string|null} [pgDumpPath=null] - Sibling SQL dump to also hash* @param {object} [options] - Dump inventory expectations* @param {boolean} [options.allowMissingDump=false] - Only for skipped/failed dumps+ * @param {object} [options.assetConsistency] - The file-and-row consistency this snapshot claims*/-export async function generateManifest(snapshotDataDir, manifestPath, pgDumpPath = null, { allowMissingDump = false } = {}) {+export async function generateManifest(snapshotDataDir, manifestPath, pgDumpPath = null, { allowMissingDump = false, assetConsistency } = {}) {const entries = await readdir(snapshotDataDir, { recursive: true }).catch(err => { throw manifestReadFailure('data readdir', err); });const files = {};@@ -902,7 +909,8 @@ export async function generateManifest(snapshotDataDir, manifestPath, pgDumpPathconst manifest = {generatedAt: new Date().toISOString(),fileCount: Object.keys(files).length,- files+ files,+ ...(assetConsistency ? { assetConsistency } : {}),};await atomicWrite(manifestPath, manifest);diff --git a/server/services/backup.test.js b/server/services/backup.test.jsindex f02369d3f9..d2db3d8d17 100644--- a/server/services/backup.test.js+++ b/server/services/backup.test.js@@ -3468,6 +3468,13 @@ describe('runBackup lifecycle', () => {expect(manifest.fileCount).toBe(1);expect(manifest.files['settings.json']).toMatch(/^[0-9a-f]{64}$/);expect(result.manifest).toEqual(manifest);+ // The snapshot never claims global file-and-row consistency while the+ // owner inventory still lists owners outside admission (#9982).+ const { backupAssetConsistency } = await import('../lib/backupAssetOwners.js');+ const claimed = backupAssetConsistency();+ expect(claimed.scope).toBe('admitted-owners');+ expect(manifest.assetConsistency).toEqual(claimed);+ expect(result.assetConsistency).toEqual(claimed);// --- persisted state --------------------------------------------------const state = await readJson(joinPath(dataRoot, 'backup', 'state.json'));@@ -3477,6 +3484,7 @@ describe('runBackup lifecycle', () => {status: 'ok',filesChanged: 2,pgBackup: SKIPPED_PG,+ assetConsistency: claimed,error: null,});diff --git a/server/services/creativeDirector/completionHook.js b/server/services/creativeDirector/completionHook.jsindex a52df36a15..7544a9a36a 100644--- a/server/services/creativeDirector/completionHook.js+++ b/server/services/creativeDirector/completionHook.js@@ -34,6 +34,7 @@ import { runStitch } from './stitchRunner.js';import { sampleEvaluationFrames } from '../videoGen/local.js';import { listJobs, mediaJobEvents } from '../mediaJobQueue/index.js';import { PATHS, sleep } from '../../lib/fileUtils.js';+import { withBackupAssetPublication } from '../../lib/backupSnapshotBoundary.js';import { PROJECT_TERMINAL_STATUSES, RUN_TERMINAL_STATUSES } from '../../lib/creativeDirectorPresets.js';import {DELIVERABLE_KINDS,@@ -429,21 +430,27 @@ export async function advanceAfterSceneSettled(projectId, opts = {}) {let frames = orphanedEvaluating.evaluationFrames || [];const allFramesExist = frames.length > 0 && frames.every((f) => existsSync(join(PATHS.videoThumbnails, f)));if (!allFramesExist) {- frames = await sampleEvaluationFrames(orphanedEvaluating.renderedJobId)- .catch((err) => {- console.error(`❌ CD resume sampleEvaluationFrames failed for ${orphanedEvaluating.renderedJobId.slice(0, 8)}: ${err.message}`);- return [];- });- // sampleEvaluationFrames can return [] for non-fatal reasons- // (ffmpeg missing on PATH, ffprobe miscount, transient I/O). The- // video file is still on disk (we checked above), so the- // evaluator template's single-thumbnail fallback path- // (`{{^multiFrame}}` in cd-evaluate.md) can still produce a- // verdict against `/data/video-thumbnails/{renderedJobId}.jpg`.- // Mirror the normal render-completion path (sceneRunner.js): hand- // off whatever frames we got, even an empty array, rather than- // bailing here and leaving the project wedged in `rendering`.- await updateScene(project.id, orphanedEvaluating.sceneId, { evaluationFrames: frames });+ // Re-sampling overwrites `${jobId}-fN.jpg` in place, replacing bytes+ // the persisted row may already name. Hold one backup admission from+ // the first frame write through the row update (as sceneRunner does).+ frames = await withBackupAssetPublication(async () => {+ const sampled = await sampleEvaluationFrames(orphanedEvaluating.renderedJobId)+ .catch((err) => {+ console.error(`❌ CD resume sampleEvaluationFrames failed for ${orphanedEvaluating.renderedJobId.slice(0, 8)}: ${err.message}`);+ return [];+ });+ // sampleEvaluationFrames can return [] for non-fatal reasons+ // (ffmpeg missing on PATH, ffprobe miscount, transient I/O). The+ // video file is still on disk (we checked above), so the+ // evaluator template's single-thumbnail fallback path+ // (`{{^multiFrame}}` in cd-evaluate.md) can still produce a+ // verdict against `/data/video-thumbnails/{renderedJobId}.jpg`.+ // Mirror the normal render-completion path (sceneRunner.js): hand+ // off whatever frames we got, even an empty array, rather than+ // bailing here and leaving the project wedged in `rendering`.+ await updateScene(project.id, orphanedEvaluating.sceneId, { evaluationFrames: sampled });+ return sampled;+ });}// Pause race re-check after the expensive frame-sampling step. The// user could re-pause the project mid-resume; without this thediff --git a/server/services/creativeDirector/evaluationFramesBackupAdmission.test.js b/server/services/creativeDirector/evaluationFramesBackupAdmission.test.jsnew file mode 100644index 0000000000..beb2f69d3e--- /dev/null+++ b/server/services/creativeDirector/evaluationFramesBackupAdmission.test.js@@ -0,0 +1,147 @@+/** Creative Director evaluation frames over real files, with the scene row+ * write held at its commit seam. A backup cut must never land between writing+ * `${jobId}-fN.jpg` and the scene row that names those frames (#9982). */+import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';+import { mkdir, readdir, rm, writeFile } from 'node:fs/promises';+import { join } from 'node:path';+import { cleanupTempDataRoots, lazyTempDataRoot, makePathsProxy } from '../../lib/mockPathsDataRoot.js';++vi.mock('../../lib/fileUtils.js', async importOriginal => makePathsProxy(await importOriginal(), {+ dataRoot: () => lazyTempDataRoot('portos-cd-frames-'),+}));++// In-memory project rows standing in for the store. Every scene write awaits+// `beforeRowWrite`, so a test can hold the commit after the frames landed.+let project;+let beforeRowWrite = async () => {};+vi.mock('./local.js', () => ({+ getProject: async () => structuredClone(project),+ updateProject: async (_id, patch) => { project = { ...project, ...patch }; },+ updateScene: async (_id, sceneId, patch) => {+ await beforeRowWrite();+ const scenes = project.treatment.scenes.map(scene => (scene.sceneId === sceneId ? { ...scene, ...patch } : scene));+ project = { ...project, treatment: { ...project.treatment, scenes } };+ },+ updateRun: async () => ({}),+ recordRun: async () => ({}),+}));++// The sampler writes its frames with ffmpeg; this one writes a placeholder file.+let framesDir;+vi.mock('../videoGen/local.js', () => ({+ extractLastFrame: async () => null,+ sampleEvaluationFrames: async (jobId) => {+ await mkdir(framesDir, { recursive: true });+ await writeFile(join(framesDir, `${jobId}-f1.jpg`), 'synthetic frame');+ return [`${jobId}-f1.jpg`];+ },+}));+vi.mock('../mediaJobQueue/index.js', async () => {+ const { EventEmitter } = await import('node:events');+ return {+ mediaJobEvents: new EventEmitter(),+ enqueueJob: async () => ({ jobId: '00000000-0000-4000-8000-000000000001', position: 1 }),+ getJob: () => null,+ listJobs: () => [],+ };+});+vi.mock('../settings.js', () => ({+ getSettings: async () => ({ imageGen: { local: { pythonPath: '/usr/bin/python3' } } }),+ getSettingsWithStatus: async () => ({ corrupt: false, settings: { imageGen: { local: { pythonPath: '/usr/bin/python3' } } } }),+}));+vi.mock('../instanceIdentity.js', () => ({ getInstanceId: async () => 'example-owner' }));+vi.mock('./sceneEvaluator.js', () => ({ dispatchSceneEvaluation: vi.fn(async () => {}) }));+vi.mock('./agentBridge.js', () => ({ enqueueTreatmentTask: async () => {} }));+vi.mock('./planAdvance.js', () => ({ advanceAfterPlanStepSettled: async () => {} }));+vi.mock('./stitchRunner.js', () => ({ runStitch: async () => {} }));++const { PATHS } = await import('../../lib/fileUtils.js');+const { acquireBackupSnapshotCut } = await import('../../lib/backupSnapshotBoundary.js');+const { mediaJobEvents } = await import('../mediaJobQueue/index.js');+const { dispatchSceneEvaluation } = await import('./sceneEvaluator.js');+const { runSceneRender } = await import('./sceneRunner.js');+const { advanceAfterSceneSettled } = await import('./completionHook.js');++const JOB = '00000000-0000-4000-8000-000000000001';+const FRAME = `${JOB}-f1.jpg`;+const deferred = () => {+ let resolve;+ const promise = new Promise(done => { resolve = done; });+ return { promise, resolve };+};+const holdRowWrite = () => {+ const reached = deferred();+ const commit = deferred();+ beforeRowWrite = async () => { reached.resolve(); await commit.promise; };+ return { reached: reached.promise, commit: commit.resolve };+};+const settle = () => new Promise(resolve => setImmediate(resolve));+// What a snapshot holds: the frames copied and the frames the scene row names.+const capture = async () => ({+ files: await readdir(framesDir).catch(() => []),+ row: project.treatment.scenes[0].evaluationFrames,+});+const makeProject = scene => ({+ id: 'project-1', status: 'rendering', aspectRatio: '16:9', quality: 'standard', modelId: 'example-model', runs: [],+ treatment: { scenes: [{ sceneId: 'scene-1', order: 0, prompt: 'an example scene', durationSeconds: 4, ...scene }] },+});++// Both writers of evaluation frames: the render's completion listener, and+// the resume pass that re-samples frames missing from disk in place.+const WRITERS = [+ {+ name: 'render completion',+ project: () => makeProject({ status: 'pending' }),+ start: async () => {+ await runSceneRender(project, project.treatment.scenes[0]);+ return () => mediaJobEvents.emit('completed', { id: JOB });+ },+ },+ {+ name: 'resume re-sample',+ project: () => makeProject({ status: 'evaluating', renderedJobId: JOB, evaluationFrames: ['missing-frame.jpg'] }),+ start: async () => () => { void advanceAfterSceneSettled('project-1'); },+ },+];++afterAll(cleanupTempDataRoots);+beforeEach(async () => {+ beforeRowWrite = async () => {};+ framesDir = PATHS.videoThumbnails;+ await rm(PATHS.data, { recursive: true, force: true });+ await mkdir(PATHS.videos, { recursive: true });+ await writeFile(join(PATHS.videos, `${JOB}.mp4`), 'synthetic clip');+ mediaJobEvents.removeAllListeners();+ vi.mocked(dispatchSceneEvaluation).mockClear();+});++describe.each(WRITERS)('$name evaluation frames', ({ project: fixture, start }) => {+ beforeEach(() => { project = fixture(); });++ it('drains a frame write already in progress through the scene row that names it', async () => {+ const write = await start();+ const hold = holdRowWrite();+ write();+ await hold.reached;+ let cutReady = false;+ const cut = acquireBackupSnapshotCut().then(release => { cutReady = true; return release; });+ await settle();+ expect(cutReady).toBe(false);+ hold.commit();+ const release = await cut;+ expect(await capture()).toEqual({ files: [FRAME], row: [FRAME] });+ release();+ await vi.waitFor(() => expect(dispatchSceneEvaluation).toHaveBeenCalledTimes(1));+ });++ it('writes no frame while a cut is open, then publishes frames and row together', async () => {+ const write = await start();+ const rowBefore = project.treatment.scenes[0].evaluationFrames;+ const release = await acquireBackupSnapshotCut();+ write();+ for (let i = 0; i < 5; i += 1) await settle();+ expect(await capture()).toEqual({ files: [], row: rowBefore });+ release();+ await vi.waitFor(async () => expect(await capture()).toEqual({ files: [FRAME], row: [FRAME] }));+ });+});diff --git a/server/services/creativeDirector/sceneRunner.js b/server/services/creativeDirector/sceneRunner.jsindex 97d8bac3cb..50b7c5af77 100644--- a/server/services/creativeDirector/sceneRunner.js+++ b/server/services/creativeDirector/sceneRunner.js@@ -30,6 +30,7 @@import { join } from 'path';import { PATHS, resolveGalleryImage } from '../../lib/fileUtils.js';+import { withBackupAssetPublication } from '../../lib/backupSnapshotBoundary.js';import { verifyVideoPlayable } from '../../lib/ffmpeg.js';import { presetToRenderParams } from '../../lib/creativeDirectorPresets.js';import { CD_MAX_SCENE_RETRIES } from '../creativeDirectorPrompts.js';@@ -442,25 +443,34 @@ async function handleRenderCompleted(projectId, sceneId, jobId, opts = {}) {await skipEvaluatorForPause(preFrames.status, []);return;}- const evaluationFrames = await sampleEvaluationFrames(jobId).catch((err) => {- console.error(`❌ CD sampleEvaluationFrames failed for ${jobId.slice(0, 8)}: ${err.message}`);- return [];- });- // Re-check immediately before the agent-task enqueue. Single-user- // single-instance app per AGENTS.md, but pause IS a real user action- // and the API roundtrip can land between this read and the enqueue- // below. The cost of one extra read is trivial vs. spending an agent- // run on work the user explicitly canceled.- const postFrames = await getProject(projectId);- if (postFrames?.status === 'paused' || postFrames?.status === 'failed') {- await skipEvaluatorForPause(postFrames.status, evaluationFrames);- return;- }- await updateScene(projectId, sceneId, { ...(opts.workRevision === undefined ? {} : { expectedWorkRevision: opts.workRevision }),- status: 'evaluating',- renderedJobId: jobId,- evaluationFrames,+ // The sampled `${jobId}-fN.jpg` frames and the scene row that names them are+ // one durable publication: hold backup admission from the first frame write+ // through that row, so a snapshot never dumps a row naming frames its file+ // copy missed. The evaluator dispatch below stays outside the lease. Resolves+ // null when a pause landed during sampling (its frames are persisted then).+ const evaluationFrames = await withBackupAssetPublication(async () => {+ const frames = await sampleEvaluationFrames(jobId).catch((err) => {+ console.error(`❌ CD sampleEvaluationFrames failed for ${jobId.slice(0, 8)}: ${err.message}`);+ return [];+ });+ // Re-check immediately before the agent-task enqueue. Single-user+ // single-instance app per AGENTS.md, but pause IS a real user action+ // and the API roundtrip can land between this read and the enqueue+ // below. The cost of one extra read is trivial vs. spending an agent+ // run on work the user explicitly canceled.+ const postFrames = await getProject(projectId);+ if (postFrames?.status === 'paused' || postFrames?.status === 'failed') {+ await skipEvaluatorForPause(postFrames.status, frames);+ return null;+ }+ await updateScene(projectId, sceneId, { ...(opts.workRevision === undefined ? {} : { expectedWorkRevision: opts.workRevision }),+ status: 'evaluating',+ renderedJobId: jobId,+ evaluationFrames: frames,+ });+ return frames;});+ if (!evaluationFrames) return;// Final pause guard: close the async gap between the postFrames check above// and the enqueue below. The scene is already persisted in 'evaluating' with// renderedJobId set, so advanceAfterSceneSettled's resume path will pick itdiff --git a/server/services/mediaJobQueue/index.js b/server/services/mediaJobQueue/index.jsindex b174f5a13e..2d2dc3df58 100644--- a/server/services/mediaJobQueue/index.js+++ b/server/services/mediaJobQueue/index.js@@ -33,7 +33,7 @@ import { unlink } from 'fs/promises';import { join, resolve as pathResolve, sep as PATH_SEP } from 'path';import { PATHS, readJSONFileStrict, atomicWrite, ensureDir, sleep } from '../../lib/fileUtils.js';import { SSE_HEADERS } from '../../lib/sseHeaders.js';-import { runOutsideBackupAssetPublication, withBackupAssetPublication } from '../../lib/backupSnapshotBoundary.js';+import { holdsBackupAssetPublication, runOutsideBackupAssetPublication, withBackupAssetPublication } from '../../lib/backupSnapshotBoundary.js';import { ServerError } from '../../lib/errorHandler.js';import { reapAndCleanDetachedDirs } from '../../lib/detachedSpawn.js';import {@@ -472,6 +472,11 @@ let persistChain = Promise.resolve();// Terminal outcomes stay private until the snapshot containing them succeeds.// Recovery commits storage only; it never invokes a generator again.const pendingTransitions = new Map();+// Only a completion publishes durable output. Its commit holds backup admission+// from staging the terminal row through the hook fan-out, never while rendering+// or waiting in the queue; failures and cancellations stay unadmitted so a+// backup never delays them.+const admitCompletion = (state, commit) => (state === 'completed' ? withBackupAssetPublication(commit) : commit());function stageTerminalTransition(job, apply, acknowledge) {job.terminating = true;const target = { ...job };@@ -536,11 +541,19 @@ async function persistImpl() {...queue,...archive,];+ // A completion's terminal row and its `completed` fan-out publish together,+ // so only a snapshot written inside a backup admission lease commits one. Any+ // other write (progress, enqueue, the shutdown flush, or one landing after a+ // completion's own retries gave up) keeps it `running` on disk and leaves it+ // to an admitted recovery commit, never publishing it in the middle of a cut.+ const admitted = holdsBackupAssetPublication();+ const commits = (job) => admitted || job.durabilityPending?.status !== 'completed';+ const deferredCompletion = [...pendingTransitions.keys()].some((job) => !commits(job));// Strip non-serializable bits.- const serializable = live.map((job) => ({ ...job, ...job.durabilityPending })).map(({ id, kind, owner, status, queuedAt, startedAt, completedAt, params, result, error, position, progress, statusMsg, etaMs }) =>+ const serializable = live.map((job) => (commits(job) ? { ...job, ...job.durabilityPending } : job)).map(({ id, kind, owner, status, queuedAt, startedAt, completedAt, params, result, error, position, progress, statusMsg, etaMs }) =>({ id, kind, owner, status, queuedAt, startedAt, completedAt, params, result, error, position, progress, statusMsg, etaMs }),);- const transitions = [...pendingTransitions];+ const transitions = [...pendingTransitions].filter(([job]) => commits(job));await atomicWrite(JOBS_FILE, { jobs: serializable, videoHolds: videoHolds.snapshot() });for (const [job, acknowledge] of transitions) {if (pendingTransitions.get(job) !== acknowledge) continue;@@ -550,6 +563,19 @@ async function persistImpl() {delete job.persistenceError;await acknowledge();}+ if (deferredCompletion) recoverCompletionsUnderAdmission();+}++// Storage is writable again, but a completion is still staged. Commit it from+// its own admission lease: it waits out an active backup cut, and its attach+// hooks join the lease from the fan-out. Never awaited inside the persist+// chain, so a cut draining an admitted write cannot deadlock on it.+let completionRecovery = null;+function recoverCompletionsUnderAdmission() {+ if (completionRecovery) return;+ completionRecovery = withBackupAssetPublication(() => persist())+ .catch((error) => console.error(`❌ media-job completion recovery commit failed: ${error.message}`))+ .finally(() => { completionRecovery = null; });}export async function initMediaJobQueue() {@@ -1150,12 +1176,7 @@ async function runJobLifecycle(job, markDispatched) {emitter.off?.('activity', onActivity);emitter.off?.('progress', onActivity);await drainProgressPersist();- // Only a completion publishes durable output. It holds backup admission from- // staging the terminal row through the hook fan-out, never while rendering- // or waiting in the queue; failures and cancellations stay unadmitted so a- // backup never delays them.- const publish = () => publishTerminalTransition(state, apply);- await (state === 'completed' ? withBackupAssetPublication(publish) : publish());+ await admitCompletion(state, () => publishTerminalTransition(state, apply));}async function publishTerminalTransition(state, apply) {@@ -1591,7 +1612,7 @@ export async function cancelQueuedJobs({ kind } = {}) {export async function cancelJob(jobId) {const pending = findJob(jobId);if (pending?.durabilityPending) {- await persistTerminalTransition(pending);+ await admitCompletion(pending.durabilityPending.status, () => persistTerminalTransition(pending));return pending.status === 'canceled' ? { ok: true, status: 'canceled' }: { ok: false, code: 'ALREADY_TERMINAL', status: pending.status, error: 'Job is already finishing' };}diff --git a/server/services/mediaJobQueue/index.test.js b/server/services/mediaJobQueue/index.test.jsindex 2fd0e395a7..68b022cf67 100644--- a/server/services/mediaJobQueue/index.test.js+++ b/server/services/mediaJobQueue/index.test.js@@ -3084,4 +3084,23 @@ describe('backup snapshot admission for media completion', () => {expect(capture(failed)).toEqual({ files: [`${failed}.mp4`], queueStatus: 'running', rows: new Map() });release();});++ it('recovers an abandoned completion only under admission, never from a write landing mid-cut', async () => {+ const recovered = await startJob();+ const failures = failTerminalWrites(3);+ renderFinishes(recovered);+ await waitFor(() => failures.count === 3);+ await settle();+ const release = await boundary.acquireBackupSnapshotCut({ timeoutMs: 50 });+ // Storage is writable again and an unrelated queue write lands during the cut.+ await mediaJobQueue.enqueueJob({ kind: 'video', params: { prompt: 'unrelated' } });+ await new Promise((resolve) => setTimeout(resolve, 150));+ expect(mediaJobQueue.getJob(recovered).status).toBe('running');+ expect(capture(recovered)).toEqual({ files: [`${recovered}.mp4`], queueStatus: 'running', rows: new Map() });+ release();+ await waitFor(() => rows.has(recovered));+ expect(capture(recovered)).toEqual({+ files: [`${recovered}.mp4`], queueStatus: 'completed', rows: new Map([[recovered, `${recovered}.mp4`]]),+ });+ });});