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
address review (codex): stopped projects could not resume, and two job kinds escaped the stop
[._.]/ Adam Eivyc6682cd62e7c
diff --git a/server/lib/creativeDirectorValidation.js b/server/lib/creativeDirectorValidation.jsindex f160a2a87a..f3527670d0 100644--- a/server/lib/creativeDirectorValidation.js+++ b/server/lib/creativeDirectorValidation.js@@ -153,11 +153,6 @@ export const creativeDirectorProjectCreateSchema = z.object({// used by the stitch step to mix in audio-stage music. Bare CD projects// (no pipeline origin) leave this null.sourceIssueId: z.string().min(1).max(64).nullable().optional(),- // Optional back-pointer to the Creative Commission that spawned this project —- // how the commission finds this work to stop it, and how the dispatch path- // resolves the commission's live provider pin. Schema-parity with- // buildProjectRecord's `commissionId`.- commissionId: z.string().min(1).max(128).nullable().optional(),// Production directive (CDO Phase 2, #2184). When present the project is// PLAN-driven: the planner agent turns this brief into a validated step list// the generalized advance loop executes through the gated creative tooldiff --git a/server/services/creativeCommissions/projectControl.js b/server/services/creativeCommissions/projectControl.jsindex 6f3ecab1f2..7156304ede 100644--- a/server/services/creativeCommissions/projectControl.js+++ b/server/services/creativeCommissions/projectControl.js@@ -277,23 +277,35 @@ export function registerCommissionProjectReconciler() {* already evicted stays unlinked (nothing else can recover it, and a fresh fire* mints a correctly-stamped project with no snapshot at all).*- * Pure data movement, no LLM. Idempotent: a project that already carries the- * back-pointer is skipped, so a re-run writes nothing. Best-effort — a failure- * leaves the install exactly as it was.+ * Finally, a commission that was PAUSED or DELETED before the upgrade gets its+ * newly-linked projects stopped here. Its `commission:changed` event fired on the+ * old build, which had no reconciler — so nothing ever stopped that work, and+ * without this pass it keeps re-dispatching after the user already asked for it to+ * stop. That is the exact complaint this whole change exists to answer, and on an+ * upgrading install it is the projects reachable ONLY through this backfill that+ * are still stuck.*- * @returns {Promise<{stamped: number}>}+ * Pure data movement, no LLM (a stop kills processes and cancels renders; it never+ * calls a provider), so this is compliant with the no-cold-bootstrap-LLM rule.+ * Idempotent: a project that already carries the back-pointer is skipped, so a+ * re-run writes nothing and stops nothing. Best-effort — a failure leaves the+ * install exactly as it was.+ *+ * @returns {Promise<{stamped: number, stopped: number}>}*/export async function backfillProjectCommissionIds() {const ids = await commissionStore().listIds({ includeDeleted: true }).catch(() => []);- if (!ids.length) return { stamped: 0 };+ if (!ids.length) return { stamped: 0, stopped: 0 };const { getProjectsByIds, updateProject } = await import('../creativeDirector/local.js');let stamped = 0;+ let stopped = 0;for (const commissionId of ids) {const commission = await readCommission(commissionId);const legacyIds = ledgerProjectIds(commission);if (!legacyIds.length) continue;const projects = await getProjectsByIds(legacyIds).catch(() => []);+ const linked = [];for (const project of projects) {if (!project || project.commissionId) continue;// Drop only the stages the old fire path owned; a hand-set `evaluation` pin@@ -303,9 +315,22 @@ export async function backfillProjectCommissionIds() {const ok = await updateProject(project.id, { commissionId, modelOverrides: overrides }).then(() => true).catch((e) => { console.error(`❌ Commission back-pointer backfill: ${project.id} failed: ${e.message}`); return false; });- if (ok) stamped += 1;+ if (ok) { stamped += 1; linked.push(project); }+ }+ // A commission stopped BEFORE this build shipped never had its work stopped —+ // the reconciler didn't exist when its pause/delete event fired. Catch up now,+ // or the projects we just linked keep retrying forever.+ if (!linked.length || (!commission.deleted && commission.enabled !== false)) continue;+ const { stopProject } = await import('../creativeDirector/stopProject.js');+ const reason = commission.deleted+ ? 'Creative commission deleted' : 'Creative commission paused';+ for (const project of linked) {+ if (PROJECT_TERMINAL_STATUSES.has(project.status)) continue;+ const result = await stopProject(project.id, { reason })+ .catch((e) => { console.error(`❌ Commission back-pointer backfill: stop ${project.id} failed: ${e.message}`); return null; });+ if (result?.stopped) stopped += 1;}}- if (stamped) console.log(`🎯 Commission back-pointer backfill: stamped ${stamped} pre-existing project(s)`);- return { stamped };+ if (stamped) console.log(`🎯 Commission back-pointer backfill: stamped ${stamped} pre-existing project(s), stopped ${stopped} orphaned by an earlier pause/delete`);+ return { stamped, stopped };}diff --git a/server/services/creativeCommissions/projectControl.test.js b/server/services/creativeCommissions/projectControl.test.jsindex 5a0f72fea9..c0f04195f0 100644--- a/server/services/creativeCommissions/projectControl.test.js+++ b/server/services/creativeCommissions/projectControl.test.js@@ -387,7 +387,7 @@ describe('backfillProjectCommissionIds', () => {commissionId: 'commission-1',modelOverrides: { evaluation: { providerId: 'vision-api' } },});- expect(result).toEqual({ stamped: 1 });+ expect(result).toEqual({ stamped: 1, stopped: 0 });});it('includes tombstoned commissions — their wedged projects still need stopping', async () => {@@ -401,14 +401,41 @@ describe('backfillProjectCommissionIds', () => {expect(updateProjectMock).toHaveBeenCalled();});+ it.each([+ ['deleted', { deleted: true }, 'Creative commission deleted'],+ ['paused', { enabled: false }, 'Creative commission paused'],+ ])('stops the projects of a commission %s BEFORE this build shipped', async (_label, over, reason) => {+ // Its pause/delete event fired on a build with no reconciler, so nothing ever+ // stopped that work — and it is exactly the work still retrying on upgrade.+ listIdsMock.mockResolvedValue(['commission-1']);+ readRawMock.mockResolvedValue(commission({ ...over, runs: [{ projectId: 'cd-orphan' }] }));+ getProjectsByIdsMock.mockResolvedValue([{ id: 'cd-orphan', status: 'planning' }]);++ const result = await backfillProjectCommissionIds();++ expect(stopProjectMock).toHaveBeenCalledExactlyOnceWith('cd-orphan', { reason });+ expect(result).toEqual({ stamped: 1, stopped: 1 });+ });++ it('does NOT stop the projects of a live, enabled commission', async () => {+ listIdsMock.mockResolvedValue(['commission-1']);+ readRawMock.mockResolvedValue(commission({ runs: [{ projectId: 'cd-live' }] }));+ getProjectsByIdsMock.mockResolvedValue([{ id: 'cd-live', status: 'planning' }]);++ const result = await backfillProjectCommissionIds();++ expect(stopProjectMock).not.toHaveBeenCalled();+ expect(result).toEqual({ stamped: 1, stopped: 0 });+ });+it('is a no-op on a fresh install and on a re-run', async () => {- expect(await backfillProjectCommissionIds()).toEqual({ stamped: 0 });+ expect(await backfillProjectCommissionIds()).toEqual({ stamped: 0, stopped: 0 });expect(updateProjectMock).not.toHaveBeenCalled();listIdsMock.mockResolvedValue(['commission-1']);readRawMock.mockResolvedValue(commission({ runs: [{ projectId: 'cd-1' }] }));getProjectsByIdsMock.mockResolvedValue([{ id: 'cd-1', commissionId: 'commission-1' }]);- expect(await backfillProjectCommissionIds()).toEqual({ stamped: 0 });+ expect(await backfillProjectCommissionIds()).toEqual({ stamped: 0, stopped: 0 });expect(updateProjectMock).not.toHaveBeenCalled();});});diff --git a/server/services/creativeDirector/projectsLogic.js b/server/services/creativeDirector/projectsLogic.jsindex cdb9a6a748..b68ee917aa 100644--- a/server/services/creativeDirector/projectsLogic.js+++ b/server/services/creativeDirector/projectsLogic.js@@ -194,6 +194,12 @@ export function buildProjectRecord(input, { id, now, collectionId }) {// snapshot frozen at fire time. The run ledger cannot serve that role — it is// capped at MAX_PERSISTED_RUNS, so a long-wedged project falls out of it, and// a project a plan step spawns INDIRECTLY (bridgeFromIssue) never enters it.+ // SERVER-MANAGED — deliberately NOT in the public create/update schema (same+ // rule as `generateFirstPass` above). `POST /api/creative-director` would+ // otherwise let any caller bind an unrelated project to an existing+ // commission, inheriting that commission's provider pin and getting stopped+ // when it is paused or deleted. Only the scheduler's fire and the+ // bridgeFromIssue teaser path set it, and both call the service directly.// Additive: the whole record round-trips through the JSONB column verbatim// (sanitizeProjectForSync / mergeProjectRecord), so no schema-version bump.commissionId,diff --git a/server/services/creativeDirector/stopProject.js b/server/services/creativeDirector/stopProject.jsindex 3c4a803849..f27075f373 100644--- a/server/services/creativeDirector/stopProject.js+++ b/server/services/creativeDirector/stopProject.js@@ -22,7 +22,9 @@* 4. Retire the underlying internal CoS tasks, so the orphan sweeps can't* respawn them (same reasoning + same `'internal'` / `'completed'`* constraints as recovery.js — see the comment there).- * 5. Cancel every queued/running media job the project owns, so a doomed render+ * 5. Reset the scene / plan-step state the stop invalidated, so Resume has+ * something runnable to pick up instead of waiting on a worker that is gone.+ * 6. Cancel every queued/running media job the project owns, so a doomed render* isn't left holding the GPU.** Steps 2-4 are also exported on their own as `retireRuns`, because a caller that@@ -33,7 +35,7 @@* store's change bus) — every step is individually caught and no path throws out.*/-import { getProject, updateProject, updateRun } from './local.js';+import { getProject, updateProject, updateRun, updateScene, updatePlanStep } from './local.js';import { PROJECT_TERMINAL_STATUSES, RUN_TERMINAL_STATUSES } from '../../lib/creativeDirectorPresets.js';const nowISO = () => new Date().toISOString();@@ -73,11 +75,15 @@ export function inflightRuns(project, kinds = null) {* this is the tag completionHook's findPendingSeedFrameJob keys on. A* 10-scene project enqueues ten of these up front, so omitting them is the* difference between "Stop" cancelling the queue and cancelling nothing.+ * - `params.creativeDirectorMusicBed.projectId` — the first-pass / planner music+ * bed (firstPassMusicGen.js, creative/tools/media.js), also owner-less. A+ * music commission's whole deliverable is one of these.*/export function ownedLiveJobs(jobs, projectId) {const ownedBy = (j) => (typeof j?.owner === 'string'&& (j.owner.startsWith(`cd:${projectId}:`) || j.owner === `creative-director:${projectId}`))- || j?.params?.creativeDirector?.projectId === projectId;+ || j?.params?.creativeDirector?.projectId === projectId+ || j?.params?.creativeDirectorMusicBed?.projectId === projectId;return (jobs || []).filter((j) => ownedBy(j) && (j.status === 'queued' || j.status === 'running'));}@@ -171,7 +177,27 @@ export async function stopProject(projectId, { reason = 'Stopped', project: prerconst retired = await retireRuns(projectId, { runs: inflightRuns(project), reason });- // 5. Cancel the project's live media jobs — nothing downstream will consume them.+ // 5. Reset the stage state the stop just invalidated. Without this a stopped+ // project can never be RESUMED: a plan step left `running` makes+ // deriveNextPlanAction return `waiting` forever (it reads that as "a worker owns+ // this"), and a scene left `rendering`/`evaluating` points at a job we are about+ // to cancel. Boot recovery performs exactly this reset for paused projects — but+ // only at boot, so without it here Resume is dead until the next restart. A scene+ // whose render already landed (`renderedJobId` set) keeps its `evaluating`+ // status, the same carve-out recovery.js makes: resetting it would throw away a+ // finished video.+ for (const step of (project.plan?.steps || []).filter((st) => st.status === 'running')) {+ await updatePlanStep(projectId, step.stepId, { status: 'pending' })+ .catch((e) => console.log(`⚠️ CD stop ${projectId}: reset plan step ${step.stepId} failed: ${e.message}`));+ }+ for (const scene of (project.treatment?.scenes || [])) {+ if (scene.status !== 'rendering' && scene.status !== 'evaluating') continue;+ if (scene.renderedJobId) continue;+ await updateScene(projectId, scene.sceneId, { status: 'pending' })+ .catch((e) => console.log(`⚠️ CD stop ${projectId}: reset scene ${scene.sceneId} failed: ${e.message}`));+ }++ // 6. Cancel the project's live media jobs — nothing downstream will consume them.let jobs = 0;const queue = await loadOrEmpty(() => import('../mediaJobQueue/index.js'), 'media queue', projectId);if (queue.listJobs && queue.cancelJob) {diff --git a/server/services/creativeDirector/stopProject.test.js b/server/services/creativeDirector/stopProject.test.jsindex 4e04742bc2..a12e6e5cab 100644--- a/server/services/creativeDirector/stopProject.test.js+++ b/server/services/creativeDirector/stopProject.test.js@@ -3,10 +3,14 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';const getProjectMock = vi.fn();const updateProjectMock = vi.fn(async () => ({}));const updateRunMock = vi.fn(async () => ({}));+const updateSceneMock = vi.fn(async () => ({}));+const updatePlanStepMock = vi.fn(async () => ({}));vi.mock('./local.js', () => ({getProject: (...a) => getProjectMock(...a),updateProject: (...a) => updateProjectMock(...a),updateRun: (...a) => updateRunMock(...a),+ updateScene: (...a) => updateSceneMock(...a),+ updatePlanStep: (...a) => updatePlanStepMock(...a),}));const getActiveAgentsMock = vi.fn(() => []);@@ -110,8 +114,12 @@ describe('ownedLiveJobs', () => {{ id: 'j7', status: 'queued', params: { creativeDirector: { projectId: 'cd-1', sceneId: 's1' } } },{ id: 'j8', status: 'running', params: { creativeDirector: { projectId: 'cd-2' } } }, // other project{ id: 'j9', status: 'completed', params: { creativeDirector: { projectId: 'cd-1' } } }, // terminal+ // The music bed uses a THIRD tag and is a music commission's entire+ // deliverable — missing it means Stop cancels nothing on those projects.+ { id: 'j10', status: 'running', params: { creativeDirectorMusicBed: { projectId: 'cd-1' } } },+ { id: 'j11', status: 'queued', params: { creativeDirectorMusicBed: { projectId: 'cd-2' } } },];- expect(ownedLiveJobs(jobs, 'cd-1').map((j) => j.id)).toEqual(['j2', 'j3', 'j7']);+ expect(ownedLiveJobs(jobs, 'cd-1').map((j) => j.id)).toEqual(['j2', 'j3', 'j7', 'j10']);});});@@ -180,6 +188,30 @@ describe('stopProject', () => {expect(result).toMatchObject({ stopped: true, runs: 1, tasks: 1, agents: 1, jobs: 1 });});+ it('resets the stage state it cancelled, so the project is actually Resumable', async () => {+ // A plan step left `running` makes deriveNextPlanAction return `waiting`+ // forever; a scene left `rendering` points at a job we just cancelled. Without+ // the reset, Resume is dead until the next server restart.+ getProjectMock.mockResolvedValue(project({+ plan: { steps: [+ { stepId: 's-run', status: 'running' },+ { stepId: 's-done', status: 'done' },+ ] },+ treatment: { scenes: [+ { sceneId: 'sc-1', status: 'rendering' },+ { sceneId: 'sc-2', status: 'evaluating', renderedJobId: 'job-9' }, // finished render — keep+ { sceneId: 'sc-3', status: 'accepted' },+ ] },+ }));++ await stopProject('cd-1');++ expect(updatePlanStepMock).toHaveBeenCalledExactlyOnceWith('cd-1', 's-run', { status: 'pending' });+ // Only the scene with no landed render is reset — resetting sc-2 would throw+ // away a finished video (same carve-out recovery.js makes).+ expect(updateSceneMock).toHaveBeenCalledExactlyOnceWith('cd-1', 'sc-1', { status: 'pending' });+ });+it('completes the stop when a single step fails', async () => {getProjectMock.mockResolvedValue(project({ runs: [{ runId: 'r1', taskId: 't1', status: 'running' }] }));getActiveAgentsMock.mockReturnValue([{ id: 'agent-live', taskId: 't1' }]);