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

review (claude): backstop stuck seed jobs, tiered poll, test-state reset (#1929)

Adam Eivy331eccdff87b
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 9e0b9bc121..73d96e061e 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -137,6 +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-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. A 5-minute backstop timer force-proceeds if the seed job never emits a terminal event (worker crash / queue stall / restart that drops the in-memory job), so a stuck seed can't wedge the scene in `pending` forever. 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 fba6a2948e..cee978fbf0 100644
--- a/server/services/creativeDirector/completionHook.js
+++ b/server/services/creativeDirector/completionHook.js
@@ -146,26 +146,37 @@ export function findPendingSeedFrameJob(jobs, projectId, sceneId) {
// 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;
+// Poll fast at first (the scene-image hook usually files sourceImageFile
+// within a tick or two of the same 'completed' event), then back off — so a
+// successful attach is picked up almost immediately, while a genuinely failed
+// attach still gives up promptly instead of blocking scene-0 for the full
+// window. Values are the delay BEFORE each successive re-read.
+const SEED_FRAME_ATTACH_POLL_SCHEDULE_MS = [25, 50, 100, 250, 250, 500, 500];
+const SEED_FRAME_ATTACH_MAX_WAIT_MS = SEED_FRAME_ATTACH_POLL_SCHEDULE_MS.reduce((a, b) => a + b, 0);
+
+// Backstop for a seed job that never emits a terminal event (worker crash,
+// queue stall, a pm2 restart that drops the in-memory job). Without it the
+// defer listeners + inflightSeedDefer entry would leak forever and wedge the
+// scene in 'pending'. Generous — a real image render can take a while — but
+// finite so the pipeline always makes progress.
+const SEED_DEFER_BACKSTOP_MS = 5 * 60 * 1000;
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 (;;) {
+ // pending, or we exhaust the schedule.
+ for (let i = 0; ; i += 1) {
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) {
+ if (i >= SEED_FRAME_ATTACH_POLL_SCHEDULE_MS.length) {
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));
+ await new Promise((r) => setTimeout(r, SEED_FRAME_ATTACH_POLL_SCHEDULE_MS[i]));
}
return advanceAfterSceneSettled(projectId);
}
@@ -385,6 +396,7 @@ export async function advanceAfterSceneSettled(projectId) {
const fireOnce = () => {
if (fired) return;
fired = true;
+ clearTimeout(backstopTimer);
mediaJobEvents.off('completed', onSeedSettled);
mediaJobEvents.off('failed', onSeedSettled);
mediaJobEvents.off('canceled', onSeedSettled);
@@ -405,6 +417,19 @@ export async function advanceAfterSceneSettled(projectId) {
mediaJobEvents.on('completed', onSeedSettled);
mediaJobEvents.on('failed', onSeedSettled);
mediaJobEvents.on('canceled', onSeedSettled);
+ // Backstop: a seed job that never emits a terminal event (worker
+ // crash, queue stall, restart that drops the in-memory job) would
+ // otherwise leave these listeners + the inflightSeedDefer entry
+ // attached forever, and every future advance for this scene would hit
+ // the "already armed" early-return above — wedging the scene in
+ // 'pending' permanently. Force a fall-through after the backstop so
+ // the scene renders (text-to-video if the frame never landed) rather
+ // than hanging. Unref so the timer can't hold the process open.
+ const backstopTimer = setTimeout(() => {
+ console.log(`⏳ CD scene ${nextPending.sceneId} on ${project.id}: seed frame job ${seedJob.id.slice(0, 8)} never settled within ${SEED_DEFER_BACKSTOP_MS}ms — proceeding without waiting.`);
+ fireOnce();
+ }, SEED_DEFER_BACKSTOP_MS);
+ backstopTimer.unref?.();
// 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'
@@ -471,3 +496,13 @@ export async function advanceAfterSceneSettled(projectId) {
export async function startCreativeDirectorProject(projectId) {
return advanceAfterSceneSettled(projectId);
}
+
+// Test-only: clear the module-level in-memory dedup sets so suites that leave
+// a seed-frame defer armed (deferred but never fired the settle event) don't
+// bleed the deferKey into a later test that reuses the same projectId.
+export function __resetInflightState() {
+ inflightTreatment.clear();
+ inflightStitch.clear();
+ inflightEvaluator.clear();
+ inflightSeedDefer.clear();
+}
diff --git a/server/services/creativeDirector/orchestrator.test.js b/server/services/creativeDirector/orchestrator.test.js
index b39bd92197..addc55f715 100644
--- a/server/services/creativeDirector/orchestrator.test.js
+++ b/server/services/creativeDirector/orchestrator.test.js
@@ -66,7 +66,7 @@ vi.mock('fs', async () => {
});
import * as localMod from './local.js';
-import { advanceAfterSceneSettled, findPendingSeedFrameJob } from './completionHook.js';
+import { advanceAfterSceneSettled, findPendingSeedFrameJob, __resetInflightState } from './completionHook.js';
const baseProject = {
id: 'cd-1',
@@ -270,6 +270,9 @@ describe('advanceAfterSceneSettled', () => {
mockSampleEvaluationFrames.mockReset().mockResolvedValue([]);
mockExistsSync.mockReset().mockReturnValue(false);
mockListJobs.mockReset().mockReturnValue([]);
+ // Clear the module-level dedup sets so a test that leaves a seed-frame
+ // defer armed can't bleed its deferKey into a later test.
+ __resetInflightState();
});
it('picks scene-2 (lowest-order pending) when scene-1 is accepted and scenes 2-6 are pending', async () => {
@@ -751,6 +754,37 @@ describe('advanceAfterSceneSettled', () => {
expect(mockRunSceneRender).toHaveBeenCalledTimes(1);
expect(mockRunSceneRender.mock.calls[0][1].sceneId).toBe('scene-1');
});
+
+ it('a second advance while a defer is already armed does not double-register or render', async () => {
+ const project = seedProject('cd-seed-dedup');
+ const framed = seedProject('cd-seed-dedup', {
+ treatment: {
+ scenes: [
+ { sceneId: 'scene-1', order: 0, status: 'pending', sourceImageFile: 'seed.png' },
+ { sceneId: 'scene-2', order: 1, status: 'pending' },
+ ],
+ },
+ });
+ // First two advances see the frameless project (arm + early-return);
+ // after the seed job completes the frame has landed.
+ localMod.getProject
+ .mockResolvedValueOnce(project)
+ .mockResolvedValueOnce(project)
+ .mockResolvedValue(framed);
+ mockListJobs.mockReturnValue([seedJob(project.id, 'scene-1')]);
+
+ await advanceAfterSceneSettled(project.id); // arms the defer
+ await advanceAfterSceneSettled(project.id); // should early-return
+ expect(mockRunSceneRender).not.toHaveBeenCalled();
+
+ // A single settle re-advances exactly once (not twice), proving the
+ // second advance didn't register a duplicate listener.
+ mockListJobs.mockReturnValue([seedJob(project.id, 'scene-1', 'completed')]);
+ mockMediaJobEvents.emit('completed', seedJob(project.id, 'scene-1', 'completed'));
+ await new Promise((r) => setTimeout(r, 200));
+
+ expect(mockRunSceneRender).toHaveBeenCalledTimes(1);
+ });
});
describe('findPendingSeedFrameJob (#1929)', () => {