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
review (codex): stop backstop re-arming on stalled seed job; match settle by scene tag; teardown defers on reset (#1929)
Adam Eivye9743c5c89e4
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 73d96e061e..19316e2044 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. 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-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; the backstopped re-advance renders the scene directly (via a `skipSeedDeferSceneId` gate) instead of re-arming a fresh defer on the same stalled job, and the settle listener matches by scene tag so a duplicate/re-queued seed job for the same scene wakes it too. 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.jsindex cee978fbf0..68211dc5a4 100644--- a/server/services/creativeDirector/completionHook.js+++ b/server/services/creativeDirector/completionHook.js@@ -117,6 +117,11 @@ const inflightEvaluator = new Set();// 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: cleanup callbacks for every currently-armed seed-frame defer, keyed+// by deferKey — lets __resetInflightState() (tests) tear down real listeners ++// backstop timers, not just the dedup set, so a deferred-but-never-settled test+// can't leak a live listener that later fires a stray advance.+const seedDeferCleanups = new Map();/*** #1929 — find the still-in-flight first-pass reference-frame job seeded for@@ -178,10 +183,18 @@ async function waitForSeedFrameThenAdvance(projectId, sceneId) {}await new Promise((r) => setTimeout(r, SEED_FRAME_ATTACH_POLL_SCHEDULE_MS[i]));}- return advanceAfterSceneSettled(projectId);+ // Force past the seed-defer gate for THIS scene: the job we were waiting on+ // is terminal (or backstopped), so if a stale/duplicate seed job for the+ // same scene is still sitting queued/running we must not re-arm another+ // defer on it — that would loop forever on a stalled queue (codex review).+ return advanceAfterSceneSettled(projectId, { skipSeedDeferSceneId: sceneId });}-export async function advanceAfterSceneSettled(projectId) {+export async function advanceAfterSceneSettled(projectId, opts = {}) {+ // #1929: when a seed-frame defer's wait resolves, the re-advance passes the+ // scene id here so this pass renders it immediately instead of re-arming a+ // fresh defer on a stale/stalled duplicate seed job (which would loop).+ const skipSeedDeferSceneId = opts.skipSeedDeferSceneId || null;const project = await getProject(projectId);if (!project) return;if (project.status === 'paused' || project.status === 'failed') return;@@ -380,7 +393,8 @@ export async function advanceAfterSceneSettled(projectId) {// 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) {+ if (project.generateFirstPass && !nextPending.sourceImageFile+ && nextPending.sceneId !== skipSeedDeferSceneId) {const seedJob = findPendingSeedFrameJob(listJobs({ kind: 'image' }), project.id, nextPending.sceneId,);@@ -392,6 +406,7 @@ export async function advanceAfterSceneSettled(projectId) {}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.`);+ const sceneId = nextPending.sceneId;let fired = false;const fireOnce = () => {if (fired) return;@@ -401,8 +416,9 @@ export async function advanceAfterSceneSettled(projectId) {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+ seedDeferCleanups.delete(deferKey);+ // Re-advance once a seed job for this scene 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@@ -410,32 +426,48 @@ export async function advanceAfterSceneSettled(projectId) {// 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}`));+ waitForSeedFrameThenAdvance(project.id, sceneId)+ .catch((e) => console.log(`⚠️ CD deferred advance for ${project.id}/${sceneId} failed: ${e.message}`));+ };+ // Match by scene TAG, not the single job id we happened to sample: if+ // a duplicate/re-queued seed job for the same scene completes first and+ // attaches sourceImageFile, that's just as good — wake on it rather+ // than waiting for the specific job we first saw (codex review).+ const onSeedSettled = (job) => {+ const tag = job?.params?.creativeDirector;+ if (job?.kind === 'image' && tag?.projectId === project.id && tag?.sceneId === sceneId) fireOnce();};- const onSeedSettled = (job) => { if (job?.id === seedJob.id) fireOnce(); };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.+ // attached forever, wedging the scene in 'pending' permanently. Force+ // a fall-through after the backstop; the re-advance passes+ // skipSeedDeferSceneId so it renders this scene instead of re-arming a+ // fresh defer on the same stalled job (which would loop). 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.`);+ console.log(`⏳ CD scene ${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?.();+ // Record a teardown so tests (and future callers) can cancel an armed+ // defer cleanly — clears the listeners, timer, and dedup entry without+ // firing the advance.+ seedDeferCleanups.set(deferKey, () => {+ clearTimeout(backstopTimer);+ mediaJobEvents.off('completed', onSeedSettled);+ mediaJobEvents.off('failed', onSeedSettled);+ mediaJobEvents.off('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)) {+ if (!findPendingSeedFrameJob(listJobs({ kind: 'image' }), project.id, sceneId)) {fireOnce();}return;@@ -501,6 +533,11 @@ export async function startCreativeDirectorProject(projectId) {// 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() {+ // Tear down any armed seed-frame defers (real listeners + backstop timers),+ // not just the dedup set — a deferred-but-never-settled test would otherwise+ // leak a live listener that fires a stray advance into a later test.+ for (const cleanup of seedDeferCleanups.values()) cleanup();+ seedDeferCleanups.clear();inflightTreatment.clear();inflightStitch.clear();inflightEvaluator.clear();diff --git a/server/services/creativeDirector/orchestrator.test.js b/server/services/creativeDirector/orchestrator.test.jsindex addc55f715..4717e85b44 100644--- a/server/services/creativeDirector/orchestrator.test.js+++ b/server/services/creativeDirector/orchestrator.test.js@@ -755,6 +755,21 @@ describe('advanceAfterSceneSettled', () => {expect(mockRunSceneRender.mock.calls[0][1].sceneId).toBe('scene-1');});+ it('does NOT re-arm a defer (infinite-loop guard) when re-advanced with skipSeedDeferSceneId even if a seed job is still in-flight', async () => {+ // Reproduces the codex-flagged stall: the backstop fires, re-advances,+ // and the SAME stalled seed job is still queued/running. Without the+ // skip flag this would re-arm another defer forever. With it, the scene+ // renders (text-to-video) instead.+ const project = seedProject('cd-seed-stall');+ localMod.getProject.mockResolvedValue(project);+ mockListJobs.mockReturnValue([seedJob(project.id, 'scene-1')]); // still in-flight++ await advanceAfterSceneSettled(project.id, { skipSeedDeferSceneId: 'scene-1' });++ 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', {