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: resume local document authoring from completed batches (#10528)
[._.]/ Adam Eivy70c6824dc947
diff --git a/docs/STORAGE.md b/docs/STORAGE.mdindex 65caeed74f..f1bfed7d5e 100644--- a/docs/STORAGE.md+++ b/docs/STORAGE.md@@ -918,3 +918,15 @@ journal; do not delete unresolved evidence. Status reconciliation re-reads exactterminal proof before settling the current claim. A crash after ledger completionbut before journal settlement or hold release is recoverable without relaunch.See [peer administration](features/peer-administration.md) for supported actions.++### Music Video authoring checkpoint++`data/cache/music-video-authoring/<project-id>.json` is `ephemeral-file`: one+versioned, atomic checkpoint per project holds validated section functions while+a local document authoring attempt is unfinished. Same-project authoring requests+serialize; retries read the checkpoint from disk. Its key includes the authoring+basis, exact prompt, resolved provider/model/effort, and active/candidate document+pointers, so edits replace staged work. Successful document publication removes+the checkpoint. It is regenerable runtime state rather than searchable project+metadata, never federates, and the existing anchored `/cache/` backup exclusion+covers it. An absent checkpoint starts empty; no seed or migration is required.diff --git a/server/services/musicVideo/documentGeneration.js b/server/services/musicVideo/documentGeneration.jsindex 436f4e2b96..7d720bb910 100644--- a/server/services/musicVideo/documentGeneration.js+++ b/server/services/musicVideo/documentGeneration.js@@ -3,6 +3,11 @@ import { assertProductionApproval } from './productionReview.js';/** User-triggered mixed-media document authoring. No provider runs on read or boot. */import { createHash } from 'node:crypto';import { readFile } from 'node:fs/promises';+import { join } from 'node:path';+import { atomicWrite, rmGuarded } from '../../lib/fileCore.js';+import { readJSONFileStrict } from '../../lib/jsonIo.js';+import { PATHS } from '../../lib/paths.js';+import { createKeyCachedQueue } from '../../lib/createKeyCachedQueue.js';import { parse } from '@babel/parser';import { ServerError } from '../../lib/errorHandler.js';import { getFilmStyleGrammar, renderFilmStyleGrammarPrompt } from '../../lib/filmStyleGrammars.js';@@ -20,6 +25,7 @@ import { buildDocumentData, documentAspect, documentRenderClock, documentSongDurimport { acceptGeneratedDocument, readDocumentFiles, stageGeneratedDocument } from './compositionDocument.js';const fail = (message, code = 'COMPOSITION_AUTHORING_INVALID', status = 422) => new ServerError(message, { code, status });+const queueAuthoring = createKeyCachedQueue();const jsonForScript = (value) => JSON.stringify(value).replace(/</g, '\\u003c');const FORBIDDEN_GLOBALS = new Set(['window', 'document', 'globalThis', 'self', 'fetch', 'XMLHttpRequest', 'WebSocket','Date', 'performance', 'crypto', 'Function', 'eval', 'setTimeout', 'setInterval', 'requestAnimationFrame']);@@ -333,11 +339,23 @@ async function runAuthoring(projectId, { providerId, model, effort, sectionId =};// Resolve the provider only when there is something to split, so single-section runs are unchanged.const fullPrompt = withFeedback(promptFor(ids));- const batches = ids.length > 1 && fullPrompt.length > promptBudgetChars- && isLocalProvider((await resolveMusicVideoLlm({ providerId, model, effort, automation: project.automation, stage: 'authoring' })).provider)+ const resolved = ids.length > 1 && fullPrompt.length > promptBudgetChars+ ? await resolveMusicVideoLlm({ providerId, model, effort, automation: project.automation, stage: 'authoring' }) : null;+ const batches = resolved && isLocalProvider(resolved.provider)? batchSectionIds(ids, (batchIds) => withFeedback(promptFor(batchIds)), promptBudgetChars) : null;+ // Regenerable, machine-local runtime checkpoint, separate from published documents.+ // Include the exact prompt as well as the project basis: approved cast/style inputs+ // and review feedback can change without changing the structural timeline.+ const stagingPath = join(PATHS.data, 'cache', 'music-video-authoring', `${project.id}.json`);+ const stagingBasis = createHash('sha256').update(JSON.stringify({+ basis: context.basis, prompt: fullPrompt, route: resolved?.route,+ active: project.composition?.document?.directory || null,+ draft: project.composition?.documentDraft?.directory || null,+ })).digest('hex');const updated = new Map();let run;+ // Replaced with a checkpoint writer for batched local runs.+ let persist = async () => {};// Keep what an answer got right, then ask once more for each missing or rejected section// on its own, telling the model why (a local model often drops a section, breaks the JSON// of a multi-section answer, or reaches for Math.random despite the rules).@@ -354,18 +372,48 @@ async function runAuthoring(projectId, { providerId, model, effort, sectionId =if (!returned.size) acceptedSections(run.text, askedIds);}for (const [id, source] of returned) updated.set(id, source);+ // Save valid sections before retrying a missing/invalid one, so a failed+ // single-section repair cannot discard the rest of this accepted batch.+ await persist();for (const id of askedIds.filter((sectionId) => !returned.has(sectionId))) {const reason = rejected.get(id) || 'it was missing from the answer or its JSON did not parse';console.log(`🎬 Music-video document: re-authoring section ${id} on its own (${reason})`);run = await runBatch(`${withFeedback(promptFor([id]))}\n\nYour previous answer for section ${JSON.stringify(id)} was rejected: ${reason}. Return that one section again, corrected, keeping every determinism rule above.`);for (const [sectionId, source] of acceptedSections(run.text, [id])) updated.set(sectionId, source);+ await persist();}};if (batches) {- console.log(`🎬 Music-video document prompt is ${fullPrompt.length} chars; authoring ${ids.length} sections in ${batches.length} batches on a local model`);+ const checkpoint = await readJSONFileStrict(stagingPath, null, { logError: false });+ if (!checkpoint.ok) throw fail('The saved authoring checkpoint could not be read', 'COMPOSITION_CHECKPOINT_INVALID', 409);+ const staged = checkpoint.value;+ if (staged && staged.version !== 1) throw fail('The saved authoring checkpoint has an unsupported version', 'COMPOSITION_CHECKPOINT_INVALID', 409);+ if (staged?.basis === stagingBasis) {+ if (!Array.isArray(staged.sections) || (staged.sections.length && !staged.run?.providerId)) {+ throw fail('The saved authoring checkpoint is invalid', 'COMPOSITION_CHECKPOINT_INVALID', 409);+ }+ for (const { id, source } of staged.sections) if (ids.includes(id)) updated.set(id, checkedFunction(source));+ run = staged.run;+ }+ const saveProgress = () => atomicWrite(stagingPath, {+ version: 1, basis: stagingBasis,+ sections: [...updated].map(([id, source]) => ({ id, source })),+ run: run ? { providerId: run.providerId, model: run.model } : null,+ });+ persist = saveProgress;+ // Replace a checkpoint from another basis before any new provider work.+ await saveProgress();+ console.log(`🎬 Music-video document prompt is ${fullPrompt.length} chars; authoring ${ids.length} sections in ${batches.length} batches on a local model (${updated.size} staged)`);+ if (updated.size === ids.length) {+ // Publication still needs the production caller's reservation/current-step guard+ // when a previous attempt finished authoring but failed before staging the document.+ await guardedBeforeSubmit({ provider: resolved.provider, model: resolved.selectedModel });+ }for (const batch of batches) {- run = await runBatch(withFeedback(promptFor(batch)));- await takeAnswer(batch);+ const remaining = batch.filter((id) => !updated.has(id));+ if (!remaining.length) continue;+ run = await runBatch(withFeedback(promptFor(remaining)));+ await takeAnswer(remaining);}} else {run = await runBatch(fullPrompt);@@ -395,12 +443,15 @@ async function runAuthoring(projectId, { providerId, model, effort, sectionId =}},});+ await rmGuarded(stagingPath, { force: true }).catch((err) => {+ console.warn(`⚠️ Music-video authoring checkpoint cleanup failed: ${err.message}`);+ });return { ...result, providerId: run.providerId, model: run.model };}-export const generateMixedMediaDocument = (projectId, input = {}) => runAuthoring(projectId, input);-export const regenerateMixedMediaSection = (projectId, sectionId, input = {}) => runAuthoring(projectId, { ...input, sectionId });-export const reviseMixedMediaEvents = (projectId, input = {}) => runAuthoring(projectId, { ...input, eventRevision: true });+export const generateMixedMediaDocument = (projectId, input = {}) => queueAuthoring(projectId, () => runAuthoring(projectId, input));+export const regenerateMixedMediaSection = (projectId, sectionId, input = {}) => queueAuthoring(projectId, () => runAuthoring(projectId, { ...input, sectionId }));+export const reviseMixedMediaEvents = (projectId, input = {}) => queueAuthoring(projectId, () => runAuthoring(projectId, { ...input, eventRevision: true }));export async function acceptMixedMediaDocument(projectId, directory, { verifyCurrent = () => {} } = {}) {const project = await getProject(projectId);diff --git a/server/services/musicVideo/documentGeneration.test.js b/server/services/musicVideo/documentGeneration.test.jsindex d30bb1b133..ab87b3afdd 100644--- a/server/services/musicVideo/documentGeneration.test.js+++ b/server/services/musicVideo/documentGeneration.test.js@@ -195,6 +195,87 @@ describe('treatment-driven mixed-media document authoring', () => {expect(h.prompt).toContain('contained no usable section functions');});+ it('resumes a failed later local batch from durable sections after a module restart (#10528)', async () => {+ const id = await fixture();+ await generateMixedMediaDocument(id, { providerId: 'stub-provider' });+ const budget = h.prompt.length - 200;+ h.provider = { id: 'ollama', type: 'api' };+ const asked = [];+ h.onSubmit = async () => {+ asked.push(['intro', 'still', 'clip'].filter((section) => h.prompt.includes(`"id":"${section}"`)));+ if (asked.length === 2) throw new Error('Later batch failed');+ h.response = response(Object.fromEntries(asked.at(-1).map((section) => [section, '#010203'])));+ };+ await expect(generateMixedMediaDocument(id, { providerId: 'ollama', promptBudgetChars: budget })).rejects.toThrow('Later batch failed');+ const finished = asked[0];+ const checkpoint = JSON.parse(await readFile(join(PATHS.data, 'cache', 'music-video-authoring', `${id}.json`), 'utf8'));+ expect(checkpoint.sections.map((section) => section.id)).toEqual(finished);+ // Matching metadata never bypasses the normal deterministic-source admission.+ await writeFile(join(PATHS.data, 'cache', 'music-video-authoring', `${id}.json`), JSON.stringify({ ...checkpoint,+ sections: [{ ...checkpoint.sections[0], source: 'function render(ctx, env) { ctx.fillRect(Math.random(), 0, 1, 1); }' }],+ }));+ const callsBeforeCorruption = h.calls;+ await expect(generateMixedMediaDocument(id, { providerId: 'ollama', promptBudgetChars: budget })).rejects.toMatchObject({ code: 'NONDETERMINISTIC_SECTION' });+ expect(h.calls).toBe(callsBeforeCorruption);+ await writeFile(join(PATHS.data, 'cache', 'music-video-authoring', `${id}.json`), JSON.stringify(checkpoint));+ vi.resetModules();+ const resumedAuthor = (await import('./documentGeneration.js')).generateMixedMediaDocument;+ asked.length = 0;+ h.onSubmit = async () => {+ asked.push(['intro', 'still', 'clip'].filter((section) => h.prompt.includes(`"id":"${section}"`)));+ h.response = response(Object.fromEntries(asked.at(-1).map((section) => [section, '#aabbcc'])));+ };+ const { document } = await resumedAuthor(id, { providerId: 'ollama', promptBudgetChars: budget });+ expect(asked.flat()).toEqual(['intro', 'still', 'clip'].filter((section) => !finished.includes(section)));+ const manifest = await manifestAt(document);+ expect(manifest.sections.filter((section) => finished.includes(section.id)).map((section) => section.source))+ .toEqual(finished.map(() => source('#010203')));+ await expect(readFile(join(PATHS.data, 'cache', 'music-video-authoring', `${id}.json`))).rejects.toMatchObject({ code: 'ENOENT' });+ });++ it.each(['treatment', 'media', 'storyboard'])('discards staged local sections after a %s basis edit (#10528)', async (change) => {+ const id = await fixture();+ await generateMixedMediaDocument(id, { providerId: 'stub-provider' });+ const budget = h.prompt.length - 200;+ h.provider = { id: 'ollama', type: 'api' };+ let calls = 0;+ h.onSubmit = async () => {+ if (++calls === 2) throw new Error('Later batch failed');+ h.response = response({ intro: '#010203', still: '#010203', clip: '#010203' });+ };+ await expect(generateMixedMediaDocument(id, { providerId: 'ollama', promptBudgetChars: budget })).rejects.toThrow('Later batch failed');+ await projects.mutateProjectRecord(id, (current) => ({ project: {+ ...current,+ ...(change === 'treatment' ? { treatment: { ...current.treatment, revision: 2 } } : {}),+ ...(change === 'media' ? { scenes: current.scenes.map((scene) => scene.sceneId === 's-clip' ? { ...scene, takes: [{ ...scene.takes[0], shotInstruction: { shotMode: 'performance', edit: { inSec: 2, outSec: 8 } } }] } : scene) } : {}),+ ...(change === 'storyboard' ? { productionReview: { draft: { storyboard: [{ sceneId: 's-intro', action: 'Revised movement' }] } } } : {}),+ } }));+ const asked = [];+ h.onSubmit = async () => {+ asked.push(...['intro', 'still', 'clip'].filter((section) => h.prompt.includes(`"id":"${section}"`)));+ h.response = response({ intro: '#aabbcc', still: '#aabbcc', clip: '#aabbcc' });+ };+ const { document } = await generateMixedMediaDocument(id, { providerId: 'ollama', promptBudgetChars: budget });+ expect(asked).toEqual(['intro', 'still', 'clip']);+ expect((await manifestAt(document)).sections.map((section) => section.source)).toEqual(['intro', 'still', 'clip'].map(() => source('#aabbcc')));+ });++ it('rechecks the production reservation when all local sections were staged before publication failed', async () => {+ const id = await fixture();+ await generateMixedMediaDocument(id, { providerId: 'stub-provider' });+ const budget = h.prompt.length - 200;+ h.provider = { id: 'ollama', type: 'api' };+ let active = true;+ h.onSubmit = async () => { if (h.prompt.includes('"id":"clip"')) active = false; };+ const verifyCurrent = () => { if (!active) throw Object.assign(new Error('Production closed'), { code: 'PRODUCTION_STEP_CLOSED' }); };+ await expect(generateMixedMediaDocument(id, { providerId: 'ollama', promptBudgetChars: budget, verifyCurrent })).rejects.toMatchObject({ code: 'PRODUCTION_STEP_CLOSED' });+ active = true; h.onSubmit = null; h.calls = 0;+ const beforeSubmit = vi.fn();+ await generateMixedMediaDocument(id, { providerId: 'ollama', promptBudgetChars: budget, verifyCurrent, beforeSubmit });+ expect(h.calls).toBe(0);+ expect(beforeSubmit).toHaveBeenCalledWith(expect.objectContaining({ provider: { id: 'ollama', type: 'api' }, model: 'fixture-model' }));+ });+it('names the prompt size when authoring times out with no output (#10515)', async () => {const id = await fixture();h.onSubmit = async () => { throw new Error('API execution timed out after 600000ms with no stream progress'); };diff --git a/server/services/musicVideo/productionService.test.js b/server/services/musicVideo/productionService.test.jsindex 712c888750..9240235b6d 100644--- a/server/services/musicVideo/productionService.test.js+++ b/server/services/musicVideo/productionService.test.js@@ -1,3 +1,16 @@+import { readFile } from 'node:fs/promises';+import { join } from 'node:path';+import { cleanupTempDataRoots, lazyTempDataRoot, makePathsProxy } from '../../lib/mockPathsDataRoot.js';+vi.mock('../../lib/paths.js', async (load) => makePathsProxy(await load(), { dataRoot: () => lazyTempDataRoot('portos-production-authoring-') }));+const localAuthor = vi.hoisted(() => ({ submit: null }));+vi.mock('../promptRunner.js', () => ({+ assertProvider: () => {},+ resolveProviderAndModel: async () => ({ provider: { id: 'local-fixture', type: 'api', endpoint: 'http://localhost:11434' }, selectedModel: 'fixture-model' }),+ runPromptThroughProvider: async ({ prompt, beforeExecute }) => {+ await beforeExecute?.({ provider: { id: 'local-fixture', type: 'api', endpoint: 'http://localhost:11434' }, model: 'fixture-model' });+ return localAuthor.submit(prompt);+ },+}));// Existing engine cases isolate the creative review boundary; explicit approval-flow// cases below switch to the real model and verify pause/resume without providers.const creativeReview = vi.hoisted(() => ({ real: false }));@@ -29,7 +42,7 @@ import { captureMusicVideoEvidence } from '../../lib/musicVideoDependencies.js';* rules (productionPool.js) are real.*/-import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import { describe, it, expect, vi, beforeEach, afterEach, afterAll } from 'vitest';import { EventEmitter } from 'events';import { canonicalSnapshotChecksum } from '../../lib/snapshotChecksum.js';@@ -39,6 +52,7 @@ let writeTail = Promise.resolve();const clone = (v) => JSON.parse(JSON.stringify(v));vi.mock('./projects.js', () => ({getProject: async (id) => (store.has(id) ? clone(store.get(id)) : null),+ listProjects: async () => [...store.values()].map(clone),mutateProjectRecord: (id, transform) => {const run = writeTail.then(() => {if (!store.has(id)) throw Object.assign(new Error('Project not found'), { status: 404 });@@ -182,6 +196,7 @@ beforeEach(() => {// A test's background advances finish before the next test resets the doubles.afterEach(settle);+afterAll(cleanupTempDataRoots);describe('music video production run (#9066)', () => {it('refuses mutable peer placement before starting an immutable production budget', async () => {@@ -661,7 +676,7 @@ function seedCodeFirst({ scenes, directions, percent = 0, ...patch } = {}) {treatment: { revision: 1, appliedRevision: 1, shotDirections: directions || [{ sceneId: 'mvs-code', medium: 'procedural', mediumRationale: 'Typography' }] }, ...patch,});}-function documentDoubles() {+function documentDoubles(realDocuments = null) {let version = 0;const author = vi.fn(async (_id, input) => {await input.beforeSubmit({ provider: authorProvider, model: AUTHORING.model });@@ -686,7 +701,7 @@ function documentDoubles() {const render = vi.fn(async (_id, options) => { options.verifyCurrent(current()); return { jobId: 'final-render' }; });const cancelRender = vi.fn();service.__setProductionDepsForTests({ loadEnv: async () => env, dispatch, queue: async () => queue,- autoReview: async () => autoReview, documents: async () => documents,+ autoReview: async () => autoReview, documents: async () => realDocuments || documents,render: async () => ({ renderMusicVideo: render, cancelRender }),resolveAuthoring: async (input) => {if (!input?.providerId) throw Object.assign(new Error('Select an authoring model'), { code: 'PRODUCTION_AUTHORING_REQUIRED' });@@ -709,6 +724,43 @@ function failOwnedReview(atSec = 6) {}describe('code-first production execution (#9301)', () => {+ it('resumes production after a later local author batch fails without repeating completed sections (#10528)', async () => {+ const ids = ['intro', 'verse', 'hook'];+ const scenes = ids.map((id, i) => ({ sceneId: `mvs-${id}`, label: id, startSec: i * 10, endSec: (i + 1) * 10 }));+ seedCodeFirst({ scenes, directions: scenes.map((scene) => ({ sceneId: scene.sceneId, medium: 'procedural', mediumRationale: 'Draw the approved geometry' })),+ audioAnalysis: { durationSec: 30, sections: ids.map((id, i) => ({ id, label: id, startSec: i * 10, endSec: (i + 1) * 10 })) },+ productionReview: { draft: { storyboard: scenes.map((scene) => ({ sceneId: scene.sceneId, action: 'Planned choreography. '.repeat(2000) })) } },+ });+ const documents = await import('./documentGeneration.js');+ documentDoubles(documents);+ const asked = [];+ localAuthor.submit = async (prompt) => {+ const sections = ids.filter((id) => prompt.includes(`"id":"${id}"`));+ asked.push(sections);+ if (asked.length === 2) throw new Error('Later local batch timed out');+ return { text: JSON.stringify({ sections: sections.map((id) => ({ id, source: 'function render(ctx, env) { ctx.fillStyle = "#112233"; }' })) }) };+ };+ await start({ pool: [], authoring: AUTHORING });+ expect(theRun().steps.filter((step) => step.kind === 'author')).toEqual([expect.objectContaining({ status: 'failed' })]);+ const finished = asked[0];+ expect(finished.length).toBeGreaterThan(0);+ expect(finished.length).toBeLessThan(ids.length);+ asked.length = 0;+ localAuthor.submit = async (prompt) => {+ const sections = ids.filter((id) => prompt.includes(`"id":"${id}"`));+ asked.push(sections);+ return { text: JSON.stringify({ sections: sections.map((id) => ({ id, source: 'function render(ctx, env) { ctx.fillStyle = "#aabbcc"; }' })) }) };+ };+ await service.resumeProduction('mv-example', theRun().id);+ await settle();+ expect(asked.flat()).toEqual(ids.filter((id) => !finished.includes(id)));+ const { PATHS } = await import('../../lib/paths.js');+ const manifest = JSON.parse(await readFile(join(PATHS.data, current().composition.document.directory, 'manifest.json'), 'utf8'));+ expect(manifest.sections.filter((section) => finished.includes(section.id)).every((section) => section.source.includes('#112233'))).toBe(true);+ expect(theRun().documentCheckpoint.directory).toBe(current().composition.document.directory);+ expect(theRun().steps.filter((step) => step.kind === 'author').map((step) => step.status)).toEqual(['failed', 'completed']);+ });+it('reserves one author step for a document authored in several local batches', async () => {seedCodeFirst(); const { author } = documentDoubles();const single = author.getMockImplementation();