Skip to content

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

Orchestrator review fixes: keep revisions across a Retry, fail a broken re-plan

Claude6371a0ca731a
diff --git a/docs/features/music-video-autonomous.md b/docs/features/music-video-autonomous.md
index ce560ab567..a89b27a348 100644
--- a/docs/features/music-video-autonomous.md
+++ b/docs/features/music-video-autonomous.md
@@ -106,7 +106,7 @@ Choose **Who reviews each step → Orchestrator** in the start drawer to let a m
| Storyboard | **Produce** | Anchors shots to the lyric lines they overlap, fills blank fields, approves or files change requests that re-plan the named shots, then resolves them |
| Final video | after the final render | Looks at 24 frames sampled across the film (when the model can see) and logs a verdict with timecoded issues; nothing is re-rendered |
-Production's plate and draft reviews use the orchestrator too. Each decision lands in `run.orchestration.reviews` (`checkpoint`, `verdict` of `approve`/`revise`/`retake`/`noted`, `score`, `notes`, `changes`, `issues`, `route`), which the run panel shows as a decision log. When the revision limit is reached the latest version is accepted and the note says so. A readiness problem the orchestrator cannot fix still parks the run for a human, with the problem named. The orchestrator never publishes.
+Production's plate and draft reviews use the orchestrator too. Each decision lands in `run.orchestration.reviews` (`checkpoint`, `verdict` of `approve`/`revise`/`retake`/`noted`, `score`, `notes`, `changes`, `issues`, `route`), which the run panel shows as a decision log. When the revision limit is reached the latest version is accepted and the note says so. Each revision is stored with its log entry (`output.lyricsForReview`, `output.styleDraft`), so a Retry after a failed review judges the latest revision rather than the first draft. A storyboard re-plan that fails fails the stage (`ORCHESTRATOR_REVISION_FAILED`) instead of approving the unchanged shot; Retry asks the orchestrator again. A readiness problem the orchestrator cannot fix still parks the run for a human, with the problem named. The orchestrator never publishes.
## Local song source
diff --git a/server/services/musicVideo/autonomousService.js b/server/services/musicVideo/autonomousService.js
index dfa88a4abb..02609fb60e 100644
--- a/server/services/musicVideo/autonomousService.js
+++ b/server/services/musicVideo/autonomousService.js
@@ -235,10 +235,14 @@ const orchestratorIdentity = (run, route) => ({ kind: 'orchestrator', runId: run
providerId: route?.providerId || run.brief.orchestrator.providerId, model: route?.model || run.brief.orchestrator.model || null,
authorizedBy: run.brief.orchestratorAuthorizedBy || null });
-/** Append one decision to the run's review log (oldest dropped past the cap). */
-async function recordReview(projectId, entry) {
+/**
+ * Append one decision to the run's review log (oldest dropped past the cap).
+ * `output` lands in the same write, so a revision is never logged without the
+ * revised value a retry resumes from.
+ */
+async function recordReview(projectId, entry, output) {
const at = new Date().toISOString();
- const { run } = await patchRun(projectId, (r) => ({ orchestration: { ...r.orchestration,
+ const { run } = await patchRun(projectId, (r) => ({ ...(output ? { output } : {}), orchestration: { ...r.orchestration,
reviews: [...(r.orchestration?.reviews || []), { id: randomUUID(), at, ...entry }].slice(-ORCHESTRATOR_REVIEW_LOG_MAX) } }));
console.log(`🎬 Autonomous music video ${short(run.id)} orchestrator ${entry.verdict} ${entry.checkpoint}${entry.score ? ` (${entry.score}/10)` : ''}`);
return run;
@@ -258,16 +262,17 @@ const reviewEntry = (checkpoint, review, overrides = {}) => ({
/**
* Review a text checkpoint until it is approved: `apply(review)` returns the
- * revised value, or null when the review carried nothing to apply. Returns the
- * accepted value.
+ * revised value, or null when the review carried nothing to apply. `persist(value)`
+ * names the run output that holds the value under review, written with each
+ * revision so a retry judges the latest one. Returns the accepted value.
*/
-async function reviewUntilApproved(projectId, run, checkpoint, { value, prompt, apply }) {
+async function reviewUntilApproved(projectId, run, checkpoint, { value, prompt, apply, persist }) {
let current = value;
for (;;) {
const review = await askReview(run, checkpoint, prompt(current));
const revised = review.verdict === 'revise' ? apply(review, current) : null;
if (revised !== null && revisionsSpent(await latestRun(projectId), checkpoint) < reviewLimit(run)) {
- await recordReview(projectId, reviewEntry(checkpoint, review, { verdict: 'revise' }));
+ await recordReview(projectId, reviewEntry(checkpoint, review, { verdict: 'revise' }), persist(revised));
current = revised;
continue;
}
@@ -283,13 +288,15 @@ async function orchestrateLyrics(projectId, run, lyrics) {
value: lyrics,
prompt: (current) => buildLyricsReviewPrompt({ ...ideaOf(run), title: run.output.title, description: run.output.musicalDescription, lyrics: current }),
apply: (review) => review.lyrics || null,
+ persist: (revised) => ({ lyricsForReview: revised }),
});
}
/** The sound & look, judged before the song is made and the mood board created from it. */
async function orchestrateStyle(projectId, run) {
const { buildStyleReviewPrompt } = await reviewModule();
- const value = { sunoStyle: run.output.sunoStyle, concept: run.output.concept || {}, moodBoard: run.output.moodBoard || {} };
+ // A retried review resumes from the last revision rather than the first draft.
+ const value = run.output.styleDraft || { sunoStyle: run.output.sunoStyle, concept: run.output.concept || {}, moodBoard: run.output.moodBoard || {} };
return reviewUntilApproved(projectId, run, 'style', {
value,
prompt: (current) => buildStyleReviewPrompt({ ...ideaOf(run), title: run.output.title, description: run.output.musicalDescription, ...current }),
@@ -298,6 +305,7 @@ async function orchestrateStyle(projectId, run) {
concept: { ...current.concept, ...(review.conceptStyle ? { style: review.conceptStyle } : {}) },
moodBoard: { ...current.moodBoard, ...(review.lookPrompt ? { stylePrompt: review.lookPrompt } : {}) },
} : null),
+ persist: (revised) => ({ styleDraft: revised }),
});
}
@@ -467,7 +475,9 @@ async function reviewArt(run, project) {
const draft = project.productionReview?.draft || {};
const guide = project.devArtifacts?.find((a) => a.id === draft.guideArtifactId && !a.deleted);
const image = guide?.mimeType?.startsWith('image/') ? await deps.guideImagePath(guide).catch(() => null) : null;
- return askReview(run, 'art', buildArtReviewPrompt({ ...ideaOf(run), concept: project.concept, draft, hasImage: !!image }), image ? [image] : []);
+ // The guide sheet is not redrawn after a text revision, so a re-review is told it shows the earlier text.
+ const sheetPredatesEdits = !!image && revisionsSpent(await latestRun(project.id), 'art') > 0;
+ return askReview(run, 'art', buildArtReviewPrompt({ ...ideaOf(run), concept: project.concept, draft, hasImage: !!image, sheetPredatesEdits }), image ? [image] : []);
}
async function reviewStoryboard(run, project) {
@@ -484,7 +494,11 @@ async function reviewStoryboard(run, project) {
return askReview(run, 'storyboard', buildStoryboardReviewPrompt({ ...ideaOf(run), concept: project.concept, shots, incomplete }));
}
-/** Apply a revise verdict to a production stage; returns false when nothing could be applied. */
+/**
+ * Apply a revise verdict to a production stage; returns false when nothing could
+ * be applied. A storyboard re-plan that fails throws, so the stage fails and a
+ * Retry asks again rather than approving shots the orchestrator asked to change.
+ */
async function applyProductionRevision(projectId, run, stage, review) {
if (stage === 'art') {
if (!review.changes.length) return false;
@@ -504,11 +518,14 @@ async function applyProductionRevision(projectId, run, stage, review) {
const { route, ...plan } = await llmOf(run, 'plan');
const failure = await deps.reviseFromFeedback(projectId, { stage, ...plan }).then(() => null, (err) => err);
const created = ((await getProject(projectId)).productionReview?.feedback || []).filter((f) => !before.has(f.id) && !f.resolvedAt);
- const resolution = failure ? `The re-plan failed (${trimTo(failure.message, 200)}); kept the shot.` : 'Revised by the orchestrator.';
+ const resolution = failure ? `The re-plan failed (${trimTo(failure.message, 200)}); the orchestrator will ask again on Retry.` : 'Revised by the orchestrator.';
for (const entry of created) {
await deps.closeFeedback(projectId, { feedbackId: entry.id, resolution, reviewer: orchestratorIdentity(run, review.route) });
}
- return !failure;
+ if (failure) {
+ throw runError(502, 'ORCHESTRATOR_REVISION_FAILED', `The storyboard re-plan failed: ${trimTo(failure.message, 200)}`);
+ }
+ return true;
}
/**
@@ -715,7 +732,7 @@ const STAGES = {
// The orchestrator judges the sound & look before the mood board is made from it.
if (isOrchestratedRun(run) && !run.output.styleReviewed) {
const reviewed = await orchestrateStyle(project.id, run);
- ({ run } = await save({ output: { ...reviewed, styleReviewed: true } }));
+ ({ run } = await save({ output: { ...reviewed, styleDraft: null, styleReviewed: true } }));
}
return createRunStyle({ project, run });
},
diff --git a/server/services/musicVideo/autonomousService.test.js b/server/services/musicVideo/autonomousService.test.js
index f5aabe1be4..8602cb23fd 100644
--- a/server/services/musicVideo/autonomousService.test.js
+++ b/server/services/musicVideo/autonomousService.test.js
@@ -889,6 +889,7 @@ describe('orchestrated mode (brief.orchestrator)', () => {
doubles.orchestrate = vi.fn(async ({ prompt }) => {
const checkpoint = checkpointOf(prompt);
const answer = (answers[checkpoint] || []).shift() || { verdict: 'approve', score: 8, notes: 'Ready.' };
+ if (answer instanceof Error) throw answer;
return { text: `Here is my call:\n${JSON.stringify(answer)}`, route: { providerId: 'orch', model: 'judge' }, visual: false };
});
doubles.alignLyrics = stub('align', async () => {});
@@ -932,6 +933,26 @@ describe('orchestrated mode (brief.orchestrator)', () => {
expect(runOf().orchestration.reviews.find((r) => r.checkpoint === 'song')).toMatchObject({ verdict: 'approve', notes: expect.stringMatching(/spends credits/) });
});
+ it('resumes a retried review from the latest revision instead of the first draft', async () => {
+ answers.lyrics = [{ verdict: 'revise', notes: 'Sharper hook.', lyrics: 'take 2' }, new Error('provider timed out')];
+ answers.style = [{ verdict: 'revise', notes: 'Name the tempo.', sunoStyle: 'synthwave, 96 bpm' }, new Error('provider timed out')];
+ await service.startAutonomousVideo({ prompt: 'p', tools: ['image:local'], songSource: 'local', orchestrator: ORCHESTRATOR }, { autoApproveAuthorized: true });
+ await settled('failed');
+ expect(runOf().output.lyricsForReview).toBe('take 2');
+
+ await service.resumeAutonomousVideo('mv-auto');
+ await settled('failed');
+ expect(runOf().output).toMatchObject({ lyrics: 'take 2', styleDraft: expect.objectContaining({ sunoStyle: 'synthwave, 96 bpm' }) });
+ const judged = doubles.orchestrate.mock.calls.map(([{ prompt }]) => prompt);
+ expect(judged.filter((prompt) => checkpointOf(prompt) === 'lyrics').at(-1)).toContain('take 2');
+
+ await service.resumeAutonomousVideo('mv-auto');
+ await vi.waitFor(() => expect(doubles.startProduction).toHaveBeenCalledOnce());
+ expect(doubles.orchestrate.mock.calls.map(([{ prompt }]) => prompt).filter((prompt) => checkpointOf(prompt) === 'style').at(-1)).toContain('96 bpm');
+ expect(runOf().output).toMatchObject({ sunoStyle: 'synthwave, 96 bpm', styleDraft: null, lyricsForReview: null });
+ expect(reviews()).toEqual(['lyrics:revise', 'lyrics:approve', 'style:revise', 'style:approve', 'song:approve']);
+ });
+
it('clears art, lyric timing and storyboard like a director, then logs its look at the final video', async () => {
creativeReview.real = true;
const actual = await vi.importActual('./productionReview.js');
@@ -952,6 +973,8 @@ describe('orchestrated mode (brief.orchestrator)', () => {
project.scenes = project.scenes.map((scene) => ({ ...scene, prompt: 'Close on the scarf' }));
project.productionReview.draft.storyboard = project.productionReview.draft.storyboard.map((shot) => ({ ...shot, action: 'Close on the scarf' }));
});
+ // The first re-plan fails: the stage fails for a Retry instead of approving the unchanged shot.
+ doubles.reviseFromFeedback.mockRejectedValueOnce(new Error('planner offline'));
service.__setAutonomousDepsForTests(doubles);
doubles.analyzeSong.mockImplementation(async () => {
Object.assign(store.get('mv-auto'), {
@@ -972,20 +995,24 @@ describe('orchestrated mode (brief.orchestrator)', () => {
});
});
answers.art = [{ verdict: 'revise', notes: 'The cast is too vague to draw twice.', changes: [{ field: 'cast', text: 'A paper dancer in a red scarf' }] }];
- answers.storyboard = [
- { verdict: 'revise', notes: 'The chorus needs a closer shot.', changes: [{ sceneId: 'shot', text: 'Tighter on the scarf' }], fill: [{ sceneId: 'shot', camera: 'Slow push-in' }] },
- { verdict: 'approve', notes: 'Clear.' },
- ];
+ const closer = { verdict: 'revise', notes: 'The chorus needs a closer shot.', changes: [{ sceneId: 'shot', text: 'Tighter on the scarf' }], fill: [{ sceneId: 'shot', camera: 'Slow push-in' }] };
+ answers.storyboard = [closer, closer, { verdict: 'approve', notes: 'Clear.' }];
answers.final = [{ verdict: 'revise', score: 6, notes: 'The ending drags.', issues: [{ atSec: 18, text: 'Static hold' }] }];
await service.startAutonomousVideo({ prompt: 'p', tools: ['code:render'], authoring: { providerId: 'example', model: 'example-code' }, orchestrator: ORCHESTRATOR },
{ autoApproveAuthorized: true });
+ await settled('failed');
+ expect(runOf()).toMatchObject({ errorCode: 'ORCHESTRATOR_REVISION_FAILED', error: expect.stringContaining('planner offline') });
+ expect(store.get('mv-auto').productionReview.approvals?.storyboard).toBeFalsy();
+ expect(store.get('mv-auto').productionReview.feedback).toEqual([expect.objectContaining({ resolution: expect.stringContaining('ask again on Retry') })]);
+
+ await service.resumeAutonomousVideo('mv-auto');
await vi.waitFor(() => expect(runOf()?.output.renderJobId).toBe('render-1'));
const project = store.get('mv-auto');
expect(project.productionReview.draft).toMatchObject({ cast: 'A paper dancer in a red scarf', timingStatus: 'verified',
storyboard: [{ camera: 'Slow push-in', action: 'Close on the scarf', lyricCueIds: ['c1', 'c2'] }] });
// The orchestrator's change request was acted on and closed, so it no longer blocks approval.
- expect(project.productionReview.feedback).toEqual([expect.objectContaining({ stage: 'storyboard', target: 'shot', resolution: 'Revised by the orchestrator.', resolvedAt: expect.any(String) })]);
+ expect(project.productionReview.feedback.at(-1)).toEqual(expect.objectContaining({ stage: 'storyboard', target: 'shot', resolution: 'Revised by the orchestrator.', resolvedAt: expect.any(String) }));
expect(project.lyricCues[1]).toMatchObject({ startSec: 4, endSec: 20, words: [{ w: 'neon', conf: 'interpolated' }, { w: 'home', endSec: 20 }] });
expect(project.productionReview.approvals).toMatchObject({ art: { approvedBy: 'orchestrator', reviewer: { kind: 'orchestrator', providerId: 'orch' } },
storyboard: { approvedBy: 'orchestrator' } });
diff --git a/server/services/musicVideo/orchestratorReview.js b/server/services/musicVideo/orchestratorReview.js
index 3b0e22b2d3..dc3b9e49b8 100644
--- a/server/services/musicVideo/orchestratorReview.js
+++ b/server/services/musicVideo/orchestratorReview.js
@@ -77,14 +77,14 @@ Return JSON only:
{"verdict":"approve|retake","score":1-10,"notes":"why"}`;
}
-export function buildArtReviewPrompt({ prompt, guidance, concept, draft, hasImage }) {
- return `You are the director reviewing the ART DIRECTION for a music video before any shot is planned or rendered. ${UNTRUSTED}${hasImage ? ' The attached image is the cast and environment sheet.' : ''}
+export function buildArtReviewPrompt({ prompt, guidance, concept, draft, hasImage, sheetPredatesEdits = false }) {
+ return `You are the director reviewing the ART DIRECTION for a music video before any shot is planned or rendered. ${UNTRUSTED}${hasImage ? ` The attached image is the cast and environment sheet.${sheetPredatesEdits ? ' It was drawn before your earlier text revisions, so judge the text on its own and do not ask it to match the sheet.' : ''}` : ''}
${ideaBlock({ prompt, guidance })}
${block('VISUAL CONCEPT', [concept?.prompt, concept?.style].filter(Boolean).join('\n'))}
${ORCHESTRATOR_ART_FIELDS.map((key) => block(key.toUpperCase(), draft?.[key])).join('\n')}
-Judge: is the cast specific and consistent enough to draw the same subject in every shot, do environments, visual language and motion language fit the concept and each other${hasImage ? ', and does the sheet match the text' : ''}? ${RULES}
+Judge: is the cast specific and consistent enough to draw the same subject in every shot, do environments, visual language and motion language fit the concept and each other${hasImage && !sheetPredatesEdits ? ', and does the sheet match the text' : ''}? ${RULES}
Return JSON only:
{"verdict":"approve|revise","score":1-10,"notes":"why","changes":[{"field":"cast|environments|visualLanguage|motionLanguage","text":"the COMPLETE replacement text for that field"}]}
List changes only when verdict is revise.`;
diff --git a/server/services/musicVideo/orchestratorReview.test.js b/server/services/musicVideo/orchestratorReview.test.js
index 2258f9ed15..70a32bba88 100644
--- a/server/services/musicVideo/orchestratorReview.test.js
+++ b/server/services/musicVideo/orchestratorReview.test.js
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest';
-import { parseOrchestratorVerdict } from './orchestratorReview.js';
+import { buildArtReviewPrompt, parseOrchestratorVerdict } from './orchestratorReview.js';
// The verdict parser is the boundary between free model prose and what an
// orchestrated run applies to the project, so its refusals are pinned here.
@@ -25,3 +25,15 @@ describe('parseOrchestratorVerdict', () => {
.toMatchObject({ changes: [{ sceneId: 's1', text: 'Tighter' }], fill: [{ sceneId: 's1', camera: 'Push-in' }] });
});
});
+
+// After a text revision the guide sheet is not redrawn, so a re-review must not
+// keep asking the text to match a sheet drawn from the earlier text.
+describe('buildArtReviewPrompt', () => {
+ it('tells a re-review that the sheet predates its text revisions', () => {
+ const base = { prompt: 'p', concept: {}, draft: { cast: 'A dancer' }, hasImage: true };
+ expect(buildArtReviewPrompt(base)).toContain('does the sheet match the text');
+ const again = buildArtReviewPrompt({ ...base, sheetPredatesEdits: true });
+ expect(again).toContain('drawn before your earlier text revisions');
+ expect(again).not.toContain('does the sheet match the text');
+ });
+});