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

fix: defer scene-0 render until seeded reference frame settles (#1929)

Adam Eivyc1af3f0141e5
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index d38bcb797b..9e0b9bc121 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -137,4 +137,6 @@
- **Branch & PR reconciliation now runs on any managed app as a Chief-of-Staff scheduled task — not just PortOS.** The branch reconciler (finish this machine's unfinished local git work: delete fully-merged orphaned branches + their worktrees, open PRs for pushed-but-unopened work, resolve merge conflicts, drive the review loop, and auto-merge when a PR is green) used to be a PortOS-only feature with its own daily cron, `/api/branch-reconcile` route, `settings.branchReconcile` toggle, and a dedicated Settings tab — hardwired to the PortOS checkout. It is now a first-class per-app CoS task type, **`branch-reconcile`**, configured like every other improvement task (per-app enable, provider/model, cadence, cooldown, budget) under Chief of Staff → task scheduling. It runs `perpetual` (drain-until-done): each dispatch runs the deterministic, peer-safe cleanup + classification against the *app's* repo, dispatches the coordinator agent only while actionable in-flight branches remain, then parks on a daily recheck — so no agent is burned on a no-op run. A progress-signature convergence guard ensures the drain only re-dispatches when the actionable set actually *changed* since the last run (a branch advanced NEEDS_PR→IN_REVIEW→merged, or a new/removed branch): a cycle that leaves the same branches in the same states (a branch judged "not ready", a PR blocked on human review or red CI) parks instead of re-spawning an identical coordinator back-to-back. The peer-safety guarantee is unchanged (only local `refs/heads/` are ever touched; a federated peer's branch exists here only as a remote-tracking ref and is structurally invisible), and the per-behavior toggles (`cleanupMerged` / `openPr` / `resolveConflicts` / `autoMerge`) are now per-app task-metadata overrides. Off by default; enabling it on an app is the user's explicit consent to let it drive PRs on a schedule. The old dedicated scheduler, route, settings key, and Settings tab are removed; a migration (`scripts/migrations/170-branch-reconcile-to-cos-task.js`) carries a previously-enabled `branchReconcile` opt-in into the new task (cron→recheckCron, actions→per-app metadata) scoped to the PortOS app, and drops the dead settings key — so an install that had it on keeps reconciling instead of silently stopping. (`server/services/branchReconcile.js`, `server/services/cosTaskGenerator.js`, `server/services/taskSchedule.js`, `server/services/taskPromptDefaults/prompts.js`)
+- **[issue-1929] Creative Director scene-0 render no longer races its seeded reference frame.** When first-pass gen is on (#1867), the treatment handler enqueues a fire-and-forget image-gen job per scene to seed `scene.sourceImageFile`; but `advanceAfterSceneSettled` fired the instant the treatment task settled and called `runSceneRender` for the lowest-order pending scene, which reads `sourceImageFile` synchronously — so scene-0 almost always rendered text-to-video before its just-queued seed frame landed, silently degrading the establishing shot. The "find next pending scene" branch now checks whether `project.generateFirstPass && !scene.sourceImageFile` and a `creativeDirector`-tagged image job for that scene is still queued/running on the media-job queue; if so it defers the render, re-firing `advanceAfterSceneSettled` once the seed job settles (with a short bounded poll for the scene-image hook to file `sourceImageFile`, since both handlers run off the same `completed` event). If the seed job fails/cancels the scene renders text-to-video exactly as the fire-and-forget contract always allowed. Later scenes are unaffected (they already have a multi-minute buffer). (`server/services/creativeDirector/completionHook.js`)
+
- **[issue-2175] Generation-side character framework + structure doctrine (CWQE Phase 10 remainder).** Following the worldbuilding-doctrine slice (#2219), the character-generation and structure-planning prompts now teach the craft up front. The character bible gains the Ghost → Wound → Lie → Want → Need chain (with interlock checks: state the Lie in one sentence; the Need/Truth is its direct opposite; the Ghost causally explains the Lie), a declared arc type (positive/negative/flat), the Three Sliders (proactivity/likability/competence 1–10, rule: HIGH on ≥2 or one-with-growth; all-low = boring, all-high = Mary Sue), and a secrets list — all OPTIONAL so pre-#2175 records round-trip unchanged (`server/lib/storyBible.js` sanitizer + Zod-shape parity via the existing `canonArrayField` sanitize-on-write, client mirror in `client/src/lib/bibleLimits.js`, character-sheet UI in `CharacterDetailEditor.jsx` with `htmlFor`/`id` pairing, and no-clobber merge in `universeCharacterExpand.js` for the AI-expand path). The `character.consistency` / `arc.*` editorial checks now receive the authored Lie/Want/Need/arc-type when present (via `canonCharacterTraitsSummary`) so they reconcile plan-vs-delivery instead of inferring both. Structure prompts gain lean doctrine: `pipeline-season-episodes.md` a try-fail mandate (60%+ of middle episodes end "Yes, but"/"No, and"), beat rules (Catalyst external; Break Into Two a protagonist choice; All Is Lost includes a death — literal or of a hope/relationship/identity) and an active-climax rule; `pipeline-arc-overview.md` MICE-style thread nesting (threads close in reverse order of opening; name the opening/closing thread per season). Shipped-template edits ship to existing installs via hash-keyed migrations 171/172/173 (with the drift-cross-sync of prior owners 003/005/019/027/166). Remaining Phase 10 items (Le Guin style doctrine into the style-guide flow) stay tracked on #2175.
diff --git a/server/services/creativeDirector/completionHook.js b/server/services/creativeDirector/completionHook.js
index 3da4010335..fba6a2948e 100644
--- a/server/services/creativeDirector/completionHook.js
+++ b/server/services/creativeDirector/completionHook.js
@@ -30,6 +30,7 @@ import { dispatchSceneEvaluation } from './sceneEvaluator.js';
import { runSceneRender } from './sceneRunner.js';
import { runStitch } from './stitchRunner.js';
import { sampleEvaluationFrames } from '../videoGen/local.js';
+import { listJobs, mediaJobEvents } from '../mediaJobQueue/index.js';
import { PATHS } from '../../lib/fileUtils.js';
export async function handleCreativeDirectorCompletion(task, agentId, success) {
@@ -110,6 +111,64 @@ const inflightStitch = new Set();
// scene as orphaned and double-enqueue. Per-projectId+sceneId set
// closes that window in the same way inflightTreatment/inflightStitch do.
const inflightEvaluator = new Set();
+// #1929: scenes we're deferring the first render for while their seeded
+// first-pass reference frame is still generating on the media-job queue.
+// Keyed `${projectId}:${sceneId}` so a second advance() while a defer
+// listener is already armed doesn't register a duplicate listener (which
+// would re-fire advanceAfterSceneSettled twice on the same job settle).
+const inflightSeedDefer = new Set();
+
+/**
+ * #1929 — find the still-in-flight first-pass reference-frame job seeded for
+ * `sceneId` on `projectId`. `enqueueFirstPassSceneFrames` (firstPassGen.js)
+ * queues one `image` job per scene tagged `params.creativeDirector` (no
+ * `owner`), which `creativeDirectorSceneImageHook` files onto the scene's
+ * `sourceImageFile` when it completes. Returns the queued/running job (so the
+ * caller can wait on its settle) or null if none is pending.
+ *
+ * Pure over an injected `jobs` array so it can be unit-tested without the
+ * live queue; the module wrapper below passes `listJobs({ kind: 'image' })`.
+ */
+export function findPendingSeedFrameJob(jobs, projectId, sceneId) {
+ if (!Array.isArray(jobs)) return null;
+ return jobs.find((j) => {
+ if (j?.kind !== 'image') return false;
+ if (j.status !== 'queued' && j.status !== 'running') return false;
+ const tag = j.params?.creativeDirector;
+ return tag?.projectId === projectId && tag?.sceneId === sceneId;
+ }) || null;
+}
+
+// #1929 — how long to poll for the seed frame's `sourceImageFile` to land
+// after its media job completes. The scene-image hook (creativeDirectorScene
+// ImageHook) files it on the SAME 'completed' event our defer listener sees,
+// but both handlers run async so the write may still be in flight when we
+// re-advance. A short bounded poll lets scene-0 pick up the seeded frame
+// without wedging the pipeline if the attach failed (frame simply won't be
+// there and the scene renders text-to-video, per the fire-and-forget contract).
+const SEED_FRAME_ATTACH_POLL_MS = 250;
+const SEED_FRAME_ATTACH_MAX_WAIT_MS = 3000;
+
+async function waitForSeedFrameThenAdvance(projectId, sceneId) {
+ const deadline = Date.now() + SEED_FRAME_ATTACH_MAX_WAIT_MS;
+ // Poll until the scene-image hook has filed sourceImageFile, the project
+ // leaves a runnable state (paused/failed/deleted), the scene stops being
+ // pending, or we hit the deadline.
+ for (;;) {
+ const fresh = await getProject(projectId).catch(() => null);
+ if (!fresh || fresh.status === 'paused' || fresh.status === 'failed') return;
+ const scene = fresh.treatment?.scenes?.find((s) => s.sceneId === sceneId);
+ // Scene gone, no longer pending (something else advanced it), or the
+ // reference frame has landed → stop waiting and let advance() take over.
+ if (!scene || scene.status !== 'pending' || scene.sourceImageFile) break;
+ if (Date.now() >= deadline) {
+ console.log(`⏳ CD scene ${sceneId} on ${projectId}: seed frame did not attach within ${SEED_FRAME_ATTACH_MAX_WAIT_MS}ms — rendering without it (text-to-video).`);
+ break;
+ }
+ await new Promise((r) => setTimeout(r, SEED_FRAME_ATTACH_POLL_MS));
+ }
+ return advanceAfterSceneSettled(projectId);
+}
export async function advanceAfterSceneSettled(projectId) {
const project = await getProject(projectId);
@@ -296,6 +355,67 @@ export async function advanceAfterSceneSettled(projectId) {
// re-requested by the evaluator).
const nextPending = scenes.find((s) => s.status === 'pending');
if (nextPending) {
+ // #1929: first-pass seeded reference frames are enqueued fire-and-forget
+ // right after the treatment is written (firstPassGen.js), and this hook
+ // fires the moment the treatment task settles. For the very first scene
+ // that renders after auto-compose, this almost always beats the just-
+ // queued image-gen job — so runSceneRender would read an empty
+ // sourceImageFile and render text-to-video instead of picking up the
+ // seeded frame (silently degrading the establishing shot). If the project
+ // opted into first-pass gen, the scene has no reference frame yet, AND its
+ // seed job is still queued/running on the media-job queue, defer this
+ // render: re-fire advanceAfterSceneSettled once the seed job settles
+ // (creativeDirectorSceneImageHook will have filed sourceImageFile by then,
+ // since it's serialized on the same 'completed' event). Later scenes have
+ // a natural multi-minute buffer (each renders only after the prior scene's
+ // full video render + evaluation), so this only matters for scene-0.
+ if (project.generateFirstPass && !nextPending.sourceImageFile) {
+ const seedJob = findPendingSeedFrameJob(
+ listJobs({ kind: 'image' }), project.id, nextPending.sceneId,
+ );
+ if (seedJob) {
+ const deferKey = `${project.id}:${nextPending.sceneId}`;
+ if (inflightSeedDefer.has(deferKey)) {
+ console.log(`⏳ CD scene ${nextPending.sceneId} on ${project.id}: seed frame still generating — defer already armed, waiting.`);
+ return;
+ }
+ inflightSeedDefer.add(deferKey);
+ console.log(`⏳ CD scene ${nextPending.sceneId} on ${project.id}: deferring render until seeded reference frame job ${seedJob.id.slice(0, 8)} settles.`);
+ let fired = false;
+ const fireOnce = () => {
+ if (fired) return;
+ fired = true;
+ mediaJobEvents.off('completed', onSeedSettled);
+ mediaJobEvents.off('failed', onSeedSettled);
+ mediaJobEvents.off('canceled', onSeedSettled);
+ inflightSeedDefer.delete(deferKey);
+ // Re-advance once the seed job is terminal. On success the
+ // scene-image hook (creativeDirectorSceneImageHook) fires on the
+ // SAME 'completed' event to file sourceImageFile — but both handlers
+ // run async, so the write can still be in flight when we re-read.
+ // Poll briefly for sourceImageFile before falling through to
+ // runSceneRender so scene-0 reliably picks up its seeded frame. On
+ // failure/cancel the frame never lands and the scene renders
+ // text-to-video, exactly as the fire-and-forget contract allowed.
+ // Runs outside the request lifecycle — never throw.
+ waitForSeedFrameThenAdvance(project.id, nextPending.sceneId)
+ .catch((e) => console.log(`⚠️ CD deferred advance for ${project.id}/${nextPending.sceneId} failed: ${e.message}`));
+ };
+ const onSeedSettled = (job) => { if (job?.id === seedJob.id) fireOnce(); };
+ mediaJobEvents.on('completed', onSeedSettled);
+ mediaJobEvents.on('failed', onSeedSettled);
+ mediaJobEvents.on('canceled', onSeedSettled);
+ // Close the race where the job settled between the listJobs() read
+ // above and attaching the listeners — its terminal event already
+ // fired and would never fire again, wedging the scene in 'pending'
+ // forever. Re-check now that we're listening; if it's already gone,
+ // fire immediately.
+ if (!findPendingSeedFrameJob(listJobs({ kind: 'image' }), project.id, nextPending.sceneId)) {
+ fireOnce();
+ }
+ return;
+ }
+ }
if (project.status !== 'rendering') {
await updateProject(project.id, { status: 'rendering' });
}
diff --git a/server/services/creativeDirector/orchestrator.test.js b/server/services/creativeDirector/orchestrator.test.js
index d51558873f..b39bd92197 100644
--- a/server/services/creativeDirector/orchestrator.test.js
+++ b/server/services/creativeDirector/orchestrator.test.js
@@ -38,13 +38,35 @@ vi.mock('../videoGen/local.js', () => ({
sampleEvaluationFrames: (...args) => mockSampleEvaluationFrames(...args),
}));
+// #1929 first-pass seed-frame defer: completionHook now consults the media-job
+// queue for an in-flight seeded reference-frame job before rendering the first
+// pending scene. Mock the queue so tests can control the listJobs snapshot and
+// drive the settle event. `mediaJobEvents` is a real EventEmitter so the defer
+// listener can be exercised end-to-end.
+const { mockListJobs, mockMediaJobEvents } = vi.hoisted(() => {
+ // Minimal EventEmitter-shaped stub (on/off/emit) — enough for the defer
+ // listener the completionHook registers. Kept dependency-free so it can live
+ // in the hoisted block (runs before imports).
+ const handlers = { completed: [], failed: [], canceled: [] };
+ const emitter = {
+ on: (ev, fn) => { (handlers[ev] ||= []).push(fn); },
+ off: (ev, fn) => { handlers[ev] = (handlers[ev] || []).filter((h) => h !== fn); },
+ emit: (ev, payload) => { (handlers[ev] || []).slice().forEach((h) => h(payload)); },
+ };
+ return { mockListJobs: vi.fn(() => []), mockMediaJobEvents: emitter };
+});
+vi.mock('../mediaJobQueue/index.js', () => ({
+ listJobs: (...args) => mockListJobs(...args),
+ mediaJobEvents: mockMediaJobEvents,
+}));
+
vi.mock('fs', async () => {
const actual = await vi.importActual('fs');
return { ...actual, existsSync: (...args) => mockExistsSync(...args) };
});
import * as localMod from './local.js';
-import { advanceAfterSceneSettled } from './completionHook.js';
+import { advanceAfterSceneSettled, findPendingSeedFrameJob } from './completionHook.js';
const baseProject = {
id: 'cd-1',
@@ -247,6 +269,7 @@ describe('advanceAfterSceneSettled', () => {
mockEnqueueEvaluateTask.mockClear();
mockSampleEvaluationFrames.mockReset().mockResolvedValue([]);
mockExistsSync.mockReset().mockReturnValue(false);
+ mockListJobs.mockReset().mockReturnValue([]);
});
it('picks scene-2 (lowest-order pending) when scene-1 is accepted and scenes 2-6 are pending', async () => {
@@ -596,4 +619,157 @@ describe('advanceAfterSceneSettled', () => {
expect(mockRunSceneRender).toHaveBeenCalledTimes(1);
expect(mockRunSceneRender.mock.calls[0][1].sceneId).toBe('scene-3');
});
+
+ // #1929 — defer scene-0 render until its seeded reference frame settles.
+ describe('first-pass seed-frame defer (#1929)', () => {
+ // Each test uses a UNIQUE projectId: the completionHook's in-memory
+ // `inflightSeedDefer` set persists across tests, so a test that defers but
+ // never fires the settle event would otherwise leak its deferKey and wedge
+ // a later same-id test into the "already armed" early-return.
+ const seedProject = (id, overrides = {}) => ({
+ id,
+ status: 'rendering',
+ finalVideoId: null,
+ generateFirstPass: true,
+ treatment: {
+ scenes: [
+ { sceneId: 'scene-1', order: 0, status: 'pending' },
+ { sceneId: 'scene-2', order: 1, status: 'pending' },
+ ],
+ },
+ ...overrides,
+ });
+ const seedJob = (projectId, sceneId, status = 'running') => ({
+ id: `${projectId}-job`,
+ kind: 'image',
+ status,
+ params: { creativeDirector: { projectId, sceneId } },
+ });
+
+ it('defers runSceneRender for the first scene while its seed frame job is in-flight', async () => {
+ const project = seedProject('cd-seed-defer');
+ localMod.getProject.mockResolvedValue(project);
+ mockListJobs.mockReturnValue([seedJob(project.id, 'scene-1')]);
+
+ await advanceAfterSceneSettled(project.id);
+
+ // The render must NOT fire yet — the seeded reference frame is still
+ // generating.
+ expect(mockRunSceneRender).not.toHaveBeenCalled();
+ });
+
+ it('renders after the seed frame job completes and sourceImageFile lands', async () => {
+ const project = seedProject('cd-seed-completes');
+ const projectWithFrame = seedProject('cd-seed-completes', {
+ treatment: {
+ scenes: [
+ { sceneId: 'scene-1', order: 0, status: 'pending', sourceImageFile: 'seed.png' },
+ { sceneId: 'scene-2', order: 1, status: 'pending' },
+ ],
+ },
+ });
+ // 1st advance: no frame → defers. After the seed job completes, the
+ // scene-image hook has filed sourceImageFile, so every subsequent read
+ // returns the framed project.
+ localMod.getProject
+ .mockResolvedValueOnce(project)
+ .mockResolvedValue(projectWithFrame);
+ // Job is in-flight on the first list check; on the re-check (after
+ // listeners attach) it's still in-flight, so we truly wait for the event.
+ mockListJobs.mockReturnValue([seedJob(project.id, 'scene-1')]);
+
+ await advanceAfterSceneSettled(project.id);
+ expect(mockRunSceneRender).not.toHaveBeenCalled();
+
+ // Fire the completion event — the defer listener re-advances.
+ mockMediaJobEvents.emit('completed', seedJob(project.id, 'scene-1', 'completed'));
+ // Let the async poll + re-advance settle.
+ await new Promise((r) => setTimeout(r, 400));
+
+ expect(mockRunSceneRender).toHaveBeenCalledTimes(1);
+ const [, sceneArg] = mockRunSceneRender.mock.calls[0];
+ expect(sceneArg.sceneId).toBe('scene-1');
+ expect(sceneArg.sourceImageFile).toBe('seed.png');
+ });
+
+ it('renders text-to-video when the seed frame job fails (frame never lands)', async () => {
+ const project = seedProject('cd-seed-fails');
+ localMod.getProject.mockResolvedValue(project);
+ mockListJobs.mockReturnValue([seedJob(project.id, 'scene-1')]);
+
+ await advanceAfterSceneSettled(project.id);
+ expect(mockRunSceneRender).not.toHaveBeenCalled();
+
+ // Once the job fails it's terminal — the queue no longer reports it as
+ // queued/running, so the re-advance won't re-defer.
+ mockListJobs.mockReturnValue([seedJob(project.id, 'scene-1', 'failed')]);
+ mockMediaJobEvents.emit('failed', seedJob(project.id, 'scene-1', 'failed'));
+ // Poll runs to the deadline (no sourceImageFile ever) then renders.
+ await new Promise((r) => setTimeout(r, 3200));
+
+ expect(mockRunSceneRender).toHaveBeenCalledTimes(1);
+ expect(mockRunSceneRender.mock.calls[0][1].sceneId).toBe('scene-1');
+ });
+
+ it('does NOT defer when generateFirstPass is off', async () => {
+ const project = seedProject('cd-seed-noflag', { generateFirstPass: false });
+ localMod.getProject.mockResolvedValue(project);
+ // Even if a stray matching job exists, no defer without the flag.
+ mockListJobs.mockReturnValue([seedJob(project.id, 'scene-1')]);
+
+ await advanceAfterSceneSettled(project.id);
+
+ expect(mockRunSceneRender).toHaveBeenCalledTimes(1);
+ expect(mockRunSceneRender.mock.calls[0][1].sceneId).toBe('scene-1');
+ });
+
+ it('does NOT defer when the scene already has a sourceImageFile', async () => {
+ const project = seedProject('cd-seed-hasframe', {
+ treatment: {
+ scenes: [
+ { sceneId: 'scene-1', order: 0, status: 'pending', sourceImageFile: 'existing.png' },
+ { sceneId: 'scene-2', order: 1, status: 'pending' },
+ ],
+ },
+ });
+ localMod.getProject.mockResolvedValue(project);
+ mockListJobs.mockReturnValue([seedJob(project.id, 'scene-1')]);
+
+ await advanceAfterSceneSettled(project.id);
+
+ expect(mockRunSceneRender).toHaveBeenCalledTimes(1);
+ });
+
+ it('does NOT defer when no seed job is in-flight for the scene (renders immediately)', async () => {
+ const project = seedProject('cd-seed-nojob');
+ localMod.getProject.mockResolvedValue(project);
+ // Job list has only a job for a DIFFERENT scene.
+ mockListJobs.mockReturnValue([seedJob(project.id, 'scene-2')]);
+
+ await advanceAfterSceneSettled(project.id);
+
+ expect(mockRunSceneRender).toHaveBeenCalledTimes(1);
+ expect(mockRunSceneRender.mock.calls[0][1].sceneId).toBe('scene-1');
+ });
+ });
+
+ describe('findPendingSeedFrameJob (#1929)', () => {
+ const job = (over) => ({ id: 'j1', kind: 'image', status: 'running', params: { creativeDirector: { projectId: 'p1', sceneId: 's1' } }, ...over });
+
+ it('matches a queued/running image job tagged for the project+scene', () => {
+ expect(findPendingSeedFrameJob([job()], 'p1', 's1')?.id).toBe('j1');
+ expect(findPendingSeedFrameJob([job({ status: 'queued' })], 'p1', 's1')?.id).toBe('j1');
+ });
+ it('ignores terminal, wrong-kind, wrong-scene, and untagged jobs', () => {
+ expect(findPendingSeedFrameJob([job({ status: 'completed' })], 'p1', 's1')).toBeNull();
+ expect(findPendingSeedFrameJob([job({ status: 'failed' })], 'p1', 's1')).toBeNull();
+ expect(findPendingSeedFrameJob([job({ kind: 'video' })], 'p1', 's1')).toBeNull();
+ expect(findPendingSeedFrameJob([job()], 'p1', 's2')).toBeNull();
+ expect(findPendingSeedFrameJob([job()], 'p2', 's1')).toBeNull();
+ expect(findPendingSeedFrameJob([{ kind: 'image', status: 'running', params: {} }], 'p1', 's1')).toBeNull();
+ });
+ it('handles a non-array input defensively', () => {
+ expect(findPendingSeedFrameJob(null, 'p1', 's1')).toBeNull();
+ });
+ });
});