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

make pausing or deleting a creative commission actually stop the work it spawned

[._.]/ Adam Eivy6f7ee0d74882
diff --git a/client/src/components/creative-commission/commissionForm.js b/client/src/components/creative-commission/commissionForm.js
index ce5b3ddbdc..b378164fc1 100644
--- a/client/src/components/creative-commission/commissionForm.js
+++ b/client/src/components/creative-commission/commissionForm.js
@@ -18,6 +18,20 @@ export const COMMISSION_INTENT_MAX = 20000;
export const COMMISSION_STYLE_SPEC_MAX = 5000;
export const COMMISSION_BRIEF_TAG_MAX = 120;
+// Pause and Delete are real STOPS, not just "skip the next tick": the server also
+// tears down the Creative Director projects the commission already spawned
+// (server/services/creativeCommissions/projectControl.js). Both surfaces must say
+// so — a user watching a retry loop has no other way to know it just ended — and
+// both must say it the same way, which is why the strings live here.
+export const COMMISSION_STOP_COPY = Object.freeze({
+ pausedToast: 'Commission paused — stopping any generation still in flight',
+ resumedToast: 'Schedule resumed',
+ deletedToast: 'Commission deleted — stopping any generation still in flight',
+ pauseTitle: 'Pause — stops the schedule and any generation still in flight',
+ resumeTitle: 'Resume the schedule',
+ deleteTitle: 'Delete commission — also stops any generation still in flight',
+});
+
export const WEEKDAYS = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
export const inputCls = 'w-full bg-port-bg border border-port-border rounded px-3 py-2 text-sm text-gray-100 focus:outline-none focus:border-port-accent';
diff --git a/client/src/pages/CreativeCommissionDetail.jsx b/client/src/pages/CreativeCommissionDetail.jsx
index 9958561603..8d5a2dd876 100644
--- a/client/src/pages/CreativeCommissionDetail.jsx
+++ b/client/src/pages/CreativeCommissionDetail.jsx
@@ -31,6 +31,7 @@ import CommissionConfigForm from '../components/creative-commission/CommissionCo
import RenderHistory from '../components/creative-commission/RenderHistory.jsx';
import {
toForm, toPayload, patchFormState, validateForm, describeSchedule, describeAssignment,
+ COMMISSION_STOP_COPY,
} from '../components/creative-commission/commissionForm.js';
import {
getCommission, updateCommission, deleteCommission,
@@ -230,7 +231,7 @@ export default function CreativeCommissionDetail() {
const handleDelete = async () => {
try {
await deleteCommission(id, { silent: true });
- toast.success('Commission deleted');
+ toast.success(COMMISSION_STOP_COPY.deletedToast);
navigate('/creative-commission');
} catch (e) {
toast.error(e?.message || 'Delete failed');
@@ -278,6 +279,7 @@ export default function CreativeCommissionDetail() {
setForm((prev) => ({ ...prev, enabled: next }));
try {
await updateCommission(id, { enabled: next }, { silent: true });
+ toast.success(next ? COMMISSION_STOP_COPY.resumedToast : COMMISSION_STOP_COPY.pausedToast);
} catch (e) {
setCommission((prev) => ({ ...prev, enabled: !next }));
setForm((prev) => ({ ...prev, enabled: !next }));
@@ -367,7 +369,7 @@ export default function CreativeCommissionDetail() {
</button>
<button
onClick={toggleEnabled}
- title={commission.enabled ? 'Pause' : 'Resume'}
+ title={commission.enabled ? COMMISSION_STOP_COPY.pauseTitle : COMMISSION_STOP_COPY.resumeTitle}
aria-label={commission.enabled ? 'Pause commission' : 'Resume commission'}
className="p-2 text-gray-400 hover:text-gray-100"
>
@@ -384,7 +386,7 @@ export default function CreativeCommissionDetail() {
<button
type="button"
onClick={() => requestDelete(commission.id)}
- title="Delete commission"
+ title={COMMISSION_STOP_COPY.deleteTitle}
aria-label={`Delete commission ${commission.name}`}
className="p-2 text-gray-400 hover:text-port-error"
>
diff --git a/client/src/pages/CreativeCommissionDetail.test.jsx b/client/src/pages/CreativeCommissionDetail.test.jsx
index db8f3fa242..89d6c85e39 100644
--- a/client/src/pages/CreativeCommissionDetail.test.jsx
+++ b/client/src/pages/CreativeCommissionDetail.test.jsx
@@ -10,7 +10,7 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { render, screen, waitFor, act, fireEvent } from '@testing-library/react';
-import { MemoryRouter } from 'react-router';
+import { MemoryRouter, Route, Routes } from 'react-router';
vi.mock('../services/api', async (importOriginal) => ({
...(await importOriginal()),
@@ -234,3 +234,62 @@ describe('CreativeCommissionDetail live render refresh (#4149)', () => {
expect(toast.success).toHaveBeenCalledWith(expect.not.stringContaining('reload'));
});
});
+
+describe('CreativeCommissionDetail stop controls', () => {
+ // These assert the id the page sends, so mount it behind its real route rather
+ // than the bare-element helper above (which leaves useParams() empty).
+ const renderRouted = async () => {
+ render(
+ <MemoryRouter initialEntries={['/creative-commission/cc-1']}>
+ <Routes>
+ <Route path="/creative-commission/:id" element={<CreativeCommissionDetail />} />
+ </Routes>
+ </MemoryRouter>,
+ );
+ await screen.findByRole('heading', { name: COMMISSION.name });
+ };
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ api.getCommission.mockResolvedValue(COMMISSION);
+ api.getCreativeDirectorProjectsByIds.mockResolvedValue([]);
+ api.updateCommission.mockResolvedValue({ ...COMMISSION, enabled: false });
+ api.deleteCommission.mockResolvedValue({ ok: true });
+ });
+
+ it('tells the user that pausing also stops generation already in flight', async () => {
+ await renderRouted();
+
+ await act(async () => {
+ fireEvent.click(screen.getByRole('button', { name: /Pause commission/i }));
+ });
+
+ expect(api.updateCommission).toHaveBeenCalledWith('cc-1', { enabled: false }, { silent: true });
+ expect(toast.success).toHaveBeenCalledWith(expect.stringContaining('still in flight'));
+ });
+
+ it('says nothing about in-flight work when RESUMING the schedule', async () => {
+ api.getCommission.mockResolvedValue({ ...COMMISSION, enabled: false });
+ await renderRouted();
+
+ await act(async () => {
+ fireEvent.click(screen.getByRole('button', { name: /Resume commission/i }));
+ });
+
+ expect(toast.success).toHaveBeenCalledWith('Schedule resumed');
+ });
+
+ it('reports the stop when the commission is deleted', async () => {
+ await renderRouted();
+
+ await act(async () => {
+ fireEvent.click(screen.getByRole('button', { name: /^Delete commission/i }));
+ });
+ await act(async () => {
+ fireEvent.click(screen.getByRole('button', { name: 'Delete' }));
+ });
+
+ expect(api.deleteCommission).toHaveBeenCalledWith('cc-1', { silent: true });
+ expect(toast.success).toHaveBeenCalledWith(expect.stringContaining('still in flight'));
+ });
+});
diff --git a/client/src/pages/CreativeCommissions.jsx b/client/src/pages/CreativeCommissions.jsx
index 19eee95b2a..867fcbb51d 100644
--- a/client/src/pages/CreativeCommissions.jsx
+++ b/client/src/pages/CreativeCommissions.jsx
@@ -26,6 +26,7 @@ import { useConfirmDelete } from '../hooks/useConfirmDelete';
import CommissionConfigForm from '../components/creative-commission/CommissionConfigForm.jsx';
import {
blankForm, toPayload, patchFormState, validateForm, describeSchedule, describeAssignment,
+ COMMISSION_STOP_COPY,
} from '../components/creative-commission/commissionForm.js';
import {
listCommissions, createCommission, updateCommission, deleteCommission, runCommissionNow,
@@ -81,7 +82,7 @@ export default function CreativeCommissions() {
setCommissions((cur) => cur.filter((c) => c.id !== commission.id));
try {
await deleteCommission(commission.id, { silent: true });
- toast.success('Commission deleted');
+ toast.success(COMMISSION_STOP_COPY.deletedToast);
} catch (err) {
setCommissions(prev); // rollback
toast.error(err?.message || 'Delete failed');
@@ -114,6 +115,7 @@ export default function CreativeCommissions() {
setCommissions((prev) => prev.map((c) => (c.id === commission.id ? { ...c, enabled: next } : c)));
try {
await updateCommission(commission.id, { enabled: next }, { silent: true });
+ toast.success(next ? COMMISSION_STOP_COPY.resumedToast : COMMISSION_STOP_COPY.pausedToast);
} catch (err) {
setCommissions((prev) => prev.map((c) => (c.id === commission.id ? { ...c, enabled: commission.enabled } : c)));
toast.error(err?.message || 'Update failed');
@@ -198,7 +200,8 @@ export default function CreativeCommissions() {
</button>
<button
onClick={() => toggleEnabled(c)}
- title={c.enabled ? 'Pause' : 'Resume'} aria-label={c.enabled ? 'Pause' : 'Resume'}
+ title={c.enabled ? COMMISSION_STOP_COPY.pauseTitle : COMMISSION_STOP_COPY.resumeTitle}
+ aria-label={c.enabled ? 'Pause' : 'Resume'}
className="p-2 text-gray-400 hover:text-gray-100"
>
{c.enabled ? <Pause className="w-4 h-4" /> : <Play className="w-4 h-4" />}
@@ -214,7 +217,7 @@ export default function CreativeCommissions() {
<button
type="button"
onClick={() => requestDelete(c.id)}
- title="Delete commission"
+ title={COMMISSION_STOP_COPY.deleteTitle}
aria-label={`Delete commission ${c.name}`}
className="p-2 text-gray-400 hover:text-port-error"
>
diff --git a/client/src/pages/CreativeDirectorDetail.jsx b/client/src/pages/CreativeDirectorDetail.jsx
index 59cd93c835..cceed6a2ad 100644
--- a/client/src/pages/CreativeDirectorDetail.jsx
+++ b/client/src/pages/CreativeDirectorDetail.jsx
@@ -1,12 +1,13 @@
import { useEffect, useState, useCallback, useRef } from 'react';
import { useParams, useNavigate, useSearchParams, Link } from 'react-router';
-import { ArrowLeft, Play, Pause, RefreshCw, SlidersHorizontal } from 'lucide-react';
+import { ArrowLeft, Play, Pause, RefreshCw, SlidersHorizontal, Square } from 'lucide-react';
import PageSkeleton from '../components/ui/PageSkeleton';
import toast from '../components/ui/Toast';
import {
getCreativeDirectorProject,
startCreativeDirectorProject,
pauseCreativeDirectorProject,
+ stopCreativeDirectorProject,
resumeCreativeDirectorProject,
} from '../services/apiCreativeDirector.js';
import OverviewTab from '../components/creative-director/OverviewTab.jsx';
@@ -154,11 +155,14 @@ export default function CreativeDirectorDetail() {
const handleAction = async (kind) => {
// Map action → past-tense label and optimistic status up-front.
- const successMessages = { start: 'Started', pause: 'Paused', resume: 'Resumed' };
+ const successMessages = {
+ start: 'Started', pause: 'Paused', resume: 'Resumed',
+ stop: 'Stopped — agent, tasks and queued renders torn down',
+ };
// Optimistic status: start kicks off planning or rendering depending on
// whether a treatment exists; the 5s poll will correct it if the server
// resolves to a different status (e.g. planning → rendering).
- const optimisticStatus = kind === 'pause' ? 'paused'
+ const optimisticStatus = (kind === 'pause' || kind === 'stop') ? 'paused'
: kind === 'resume' ? (project?.treatment ? 'rendering' : 'planning')
: kind === 'start' ? (project?.treatment ? 'rendering' : 'planning')
: null;
@@ -166,6 +170,7 @@ export default function CreativeDirectorDetail() {
if (kind === 'start') await startCreativeDirectorProject(id, { silent: true });
else if (kind === 'pause') await pauseCreativeDirectorProject(id, { silent: true });
else if (kind === 'resume') await resumeCreativeDirectorProject(id, { silent: true });
+ else if (kind === 'stop') await stopCreativeDirectorProject(id, { silent: true });
toast.success(successMessages[kind] || kind);
if (optimisticStatus) setProject((p) => p ? { ...p, status: optimisticStatus } : p);
} catch (err) {
@@ -231,6 +236,15 @@ export default function CreativeDirectorDetail() {
<Pause className="w-3 h-3" /> Pause
</button>
)}
+ {!['complete', 'failed', 'draft'].includes(project.status) && (
+ <button
+ onClick={() => handleAction('stop')}
+ title="Stop: kill the running agent, retire its queued tasks, and cancel pending renders. Pause only stops NEW work being queued."
+ className="flex items-center gap-1 px-2 py-1 bg-port-card border border-port-border rounded text-xs hover:text-port-error"
+ >
+ <Square className="w-3 h-3" /> Stop
+ </button>
+ )}
</div>
</div>
<div className="flex gap-1 mt-3">
diff --git a/client/src/services/apiCreativeDirector.js b/client/src/services/apiCreativeDirector.js
index 00e77d3e3a..e8fc44f4e3 100644
--- a/client/src/services/apiCreativeDirector.js
+++ b/client/src/services/apiCreativeDirector.js
@@ -37,6 +37,13 @@ export const pauseCreativeDirectorProject = (id, options = {}) => request(`/crea
method: 'POST',
...options,
});
+// The hard counterpart to pause: kills the live agent, retires the CoS tasks
+// behind the in-flight runs (the orphan sweep respawns them otherwise), settles
+// the runs, and cancels the queued renders. Resolves to the teardown counts.
+export const stopCreativeDirectorProject = (id, options = {}) => request(`/creative-director/${encodeURIComponent(id)}/stop`, {
+ method: 'POST',
+ ...options,
+});
export const resumeCreativeDirectorProject = (id, options = {}) => request(`/creative-director/${encodeURIComponent(id)}/resume`, {
method: 'POST',
...options,
diff --git a/client/src/services/apiCreativeDirector.test.js b/client/src/services/apiCreativeDirector.test.js
index 254accb801..2cf023bc72 100644
--- a/client/src/services/apiCreativeDirector.test.js
+++ b/client/src/services/apiCreativeDirector.test.js
@@ -77,3 +77,22 @@ describe('getCreativeDirectorProjectsByIds', () => {
});
});
// @vitest-environment node
+
+describe('stopCreativeDirectorProject', () => {
+ it('POSTs the stop route — the hard counterpart to pause', async () => {
+ const { stopCreativeDirectorProject } = await import('./apiCreativeDirector.js');
+ request.mockResolvedValue({ stopped: true, runs: 1, tasks: 1, agents: 1, jobs: 0 });
+
+ const out = await stopCreativeDirectorProject('cd-1', { silent: true });
+
+ expect(request).toHaveBeenCalledWith('/creative-director/cd-1/stop', { method: 'POST', silent: true });
+ expect(out.stopped).toBe(true);
+ });
+
+ it('encodes the id', async () => {
+ const { stopCreativeDirectorProject } = await import('./apiCreativeDirector.js');
+ request.mockResolvedValue({});
+ await stopCreativeDirectorProject('cd/../1');
+ expect(request.mock.calls[0][0]).toBe('/creative-director/cd%2F..%2F1/stop');
+ });
+});
diff --git a/scripts/migrations/282-cd-project-commission-backpointer.js b/scripts/migrations/282-cd-project-commission-backpointer.js
new file mode 100644
index 0000000000..5b0d2756fe
--- /dev/null
+++ b/scripts/migrations/282-cd-project-commission-backpointer.js
@@ -0,0 +1,51 @@
+/**
+ * Registration stub for the Creative Director project → Creative Commission
+ * back-pointer (`project.commissionId`).
+ *
+ * Why the field exists: a commission fire used to SNAPSHOT the commission's LLM
+ * pin onto the project it minted (`modelOverrides.{treatment,plan}`). That froze
+ * the provider for the life of the project — switch the commission from one agent
+ * harness to another and a project already in flight kept handing its planner
+ * task to the old one, forever, because the orphan sweep
+ * (`cos.js#resetOrphanedTasks`, boot AND every 15 minutes) respawns the stale
+ * task verbatim. And because nothing linked a project back to its commission,
+ * pausing or deleting the commission cancelled only the CRON: the work already
+ * spawned kept retrying with no way to stop it.
+ *
+ * The pin is now resolved LIVE at dispatch from this id
+ * (`creativeCommissions/projectControl.js#commissionStagePin`, consumed by
+ * `creativeDirector/agentBridge.js`), and the same id is how pause/delete finds
+ * the projects to stop.
+ *
+ * Nothing to do in the file runner:
+ *
+ * 1. **No DDL.** The field lives inside the existing `creative_director_projects`
+ * `data` JSONB column and round-trips verbatim through
+ * `sanitizeProjectForSync` / `mergeProjectRecord`, so there is no column to
+ * add and no `PORTOS_SCHEMA_VERSIONS` bump (purely additive — an older peer
+ * preserves the key it doesn't understand).
+ *
+ * 2. **The backfill needs the DB pool.** This runner executes BEFORE the pool is
+ * initialized (the same reason migrations 048–052, 108, 160–162, 176, 178,
+ * and 194 are boot-time + stub-registered), so stamping `commissionId` onto
+ * projects minted before the field existed runs at boot instead:
+ * `backfillProjectCommissionIds()` in `services/creativeCommissions/projectControl.js`,
+ * invoked from `bootstrapSequence.js#armCommissionScheduler` just before the
+ * crons arm. It reads each commission's run ledger, is pure data movement
+ * (no LLM call), and is idempotent — a project that already carries the
+ * back-pointer is skipped, so a re-run writes nothing.
+ *
+ * Recovery is best-effort by construction: the run ledger is capped at
+ * MAX_PERSISTED_RUNS, so a project evicted from it stays unlinked. Nothing else
+ * can recover that association, and the next fire mints a correctly-stamped
+ * project — an unlinked one keeps exactly its pre-change behavior.
+ *
+ * This stub exists so the change lands in `data/migrations.applied.json` and the
+ * migration ledger records when the back-pointer began shipping.
+ */
+
+export default {
+ async up() {
+ console.log('🎯 CD project commissionId: additive JSONB field (no DDL); the ledger backfill runs at boot via backfillProjectCommissionIds — nothing to do in the file runner');
+ },
+};
diff --git a/server/lib/creativeDirectorPresets.js b/server/lib/creativeDirectorPresets.js
index 615d9264d2..5b374e7a8a 100644
--- a/server/lib/creativeDirectorPresets.js
+++ b/server/lib/creativeDirectorPresets.js
@@ -52,6 +52,16 @@ export const PROJECT_STATUSES = Object.freeze([
'draft', 'planning', 'rendering', 'stitching', 'complete', 'paused', 'failed',
]);
+// Project states that are FINISHED — a stop, a re-pin, or any other "act on
+// work still in flight" sweep must skip them (and must never rewrite a
+// `complete` project's status). Derived vocabulary over PROJECT_STATUSES.
+export const PROJECT_TERMINAL_STATUSES = Object.freeze(new Set(['complete', 'failed']));
+
+// Agent-run states that are SETTLED. Anything else is in flight — which is what
+// every re-dispatch guard, the boot-recovery reaper, and the stop path all key
+// on, so they must agree on the vocabulary rather than each open-coding it.
+export const RUN_TERMINAL_STATUSES = Object.freeze(new Set(['completed', 'failed']));
+
// Per-scene lifecycle states. Used by the validation schemas + the
// orchestrator's "next pending scene" logic.
export const SCENE_STATUSES = Object.freeze([
diff --git a/server/lib/creativeDirectorValidation.js b/server/lib/creativeDirectorValidation.js
index f3527670d0..f160a2a87a 100644
--- a/server/lib/creativeDirectorValidation.js
+++ b/server/lib/creativeDirectorValidation.js
@@ -153,6 +153,11 @@ 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 tool
diff --git a/server/routes/creativeDirector.js b/server/routes/creativeDirector.js
index a0226c416d..24889add34 100644
--- a/server/routes/creativeDirector.js
+++ b/server/routes/creativeDirector.js
@@ -41,6 +41,7 @@ import { enqueueFirstPassPortraits } from '../services/creativeDirector/firstPas
import { enqueueFirstPassMusicBed } from '../services/creativeDirector/firstPassMusicGen.js';
import { startCreativeDirectorProject } from '../services/creativeDirector/completionHook.js';
import { createSmokeTestProject } from '../services/creativeDirector/smokeTest.js';
+import { stopProject } from '../services/creativeDirector/stopProject.js';
const router = Router();
@@ -141,7 +142,24 @@ router.patch('/:id', asyncHandler(async (req, res) => {
res.json(updated);
}));
+// Stop: the hard counterpart to pause. Kills the live agent, retires the CoS
+// tasks behind the in-flight runs (otherwise the orphan sweep respawns them
+// every 15 minutes, forever), settles the run rows, and cancels the queued
+// renders — then parks the project as `paused` with the reason. Pause is still
+// the soft gesture ("stop queueing more, let the current render finish"); this
+// is the one to reach for when a project is wedged in a re-dispatch loop.
+router.post('/:id/stop', asyncHandler(async (req, res) => {
+ const project = await getProject(req.params.id);
+ if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });
+ const result = await stopProject(project.id, { reason: 'Stopped by user' });
+ res.json(result);
+}));
+
router.delete('/:id', asyncHandler(async (req, res) => {
+ // Stop before tombstoning. A tombstoned project keeps its `in_progress` CoS
+ // tasks and queued renders, and the orphan sweep happily respawns agents for a
+ // project the user just deleted.
+ await stopProject(req.params.id, { reason: 'Project deleted' });
await deleteProject(req.params.id);
res.json({ ok: true });
}));
diff --git a/server/routes/creativeDirector.test.js b/server/routes/creativeDirector.test.js
index 7989a7778f..34909361c6 100644
--- a/server/routes/creativeDirector.test.js
+++ b/server/routes/creativeDirector.test.js
@@ -15,6 +15,10 @@ vi.mock('../services/creativeDirector/local.js', () => ({
updateScene: vi.fn(),
}));
+vi.mock('../services/creativeDirector/stopProject.js', () => ({
+ stopProject: vi.fn(async (id) => ({ projectId: id, stopped: true, runs: 1, tasks: 1, agents: 1, jobs: 2 })),
+}));
+
vi.mock('../services/creativeDirector/completionHook.js', () => ({
startCreativeDirectorProject: vi.fn(async () => undefined),
advanceAfterSceneSettled: vi.fn(async () => undefined),
@@ -58,6 +62,7 @@ vi.mock('../services/creativeDirector/firstPassMusicGen.js', () => ({
import * as cdService from '../services/creativeDirector/local.js';
import * as autoCast from '../services/creativeDirector/autoCast.js';
import * as hook from '../services/creativeDirector/completionHook.js';
+import * as stop from '../services/creativeDirector/stopProject.js';
import * as firstPass from '../services/creativeDirector/firstPassGen.js';
import * as firstPassMusicBed from '../services/creativeDirector/firstPassMusicGen.js';
import * as creativeTools from '../services/creative/toolRegistry.js';
@@ -74,6 +79,34 @@ describe('creativeDirector routes', () => {
vi.clearAllMocks();
});
+ describe('stop', () => {
+ it('POST /:id/stop tears down the in-flight work and reports the counts', async () => {
+ cdService.getProject.mockResolvedValueOnce({ id: 'cd-1', status: 'planning' });
+ const r = await request(app).post('/api/creative-director/cd-1/stop');
+ expect(r.status).toBe(200);
+ expect(stop.stopProject).toHaveBeenCalledWith('cd-1', { reason: 'Stopped by user' });
+ expect(r.body).toMatchObject({ stopped: true, tasks: 1, jobs: 2 });
+ });
+
+ it('POST /:id/stop 404s for an unknown project', async () => {
+ cdService.getProject.mockResolvedValueOnce(null);
+ const r = await request(app).post('/api/creative-director/nope/stop');
+ expect(r.status).toBe(404);
+ expect(stop.stopProject).not.toHaveBeenCalled();
+ });
+
+ it('DELETE /:id stops BEFORE tombstoning — otherwise the orphan sweep respawns agents for a deleted project', async () => {
+ const order = [];
+ stop.stopProject.mockImplementationOnce(async () => { order.push('stop'); return { stopped: true }; });
+ cdService.deleteProject.mockImplementationOnce(async () => { order.push('delete'); return { ok: true }; });
+
+ const r = await request(app).delete('/api/creative-director/cd-1');
+
+ expect(r.status).toBe(200);
+ expect(order).toEqual(['stop', 'delete']);
+ });
+ });
+
describe('GET /', () => {
it('returns all projects', async () => {
const r = await request(app).get('/api/creative-director');
diff --git a/server/services/bootstrap.js b/server/services/bootstrap.js
index 2ed9e7b202..5daeb9f58e 100644
--- a/server/services/bootstrap.js
+++ b/server/services/bootstrap.js
@@ -135,6 +135,7 @@ import { writersRoomStore } from './writersRoom/store.js';
import { mediaCollectionStore } from './mediaCollections.js';
import { loraDatasetStore } from './loraDatasets.js';
import { commissionStore, backfillAllCommissionFeedback } from './creativeCommissions/store.js';
+import { backfillProjectCommissionIds } from './creativeCommissions/projectControl.js';
import { outcomesStore as liOutcomesStore } from './layeredIntelligenceOutcomes.js';
import * as gameStore from './games/store.js';
@@ -372,6 +373,7 @@ const startBackgroundServices = ({ spawnerReady }) => {
// bootstrapSequence.js.
armCommissionScheduler({
backfillCommissionFeedback: backfillAllCommissionFeedback,
+ backfillProjectCommissionIds,
startCommissionScheduler
});
// Initialize OpenWorld snapshot scheduler — records periodic city-state frames
diff --git a/server/services/bootstrapSequence.js b/server/services/bootstrapSequence.js
index 56dd3eaa57..e37c25d2fc 100644
--- a/server/services/bootstrapSequence.js
+++ b/server/services/bootstrapSequence.js
@@ -98,10 +98,18 @@ export const initCosAfterSpawner = ({ spawnerReady, initCos }) =>
/**
* Legacy INLINE commission feedback is split into the federated store BEFORE the
* per-commission crons are armed (#2686), so a fire reads the federated view.
- * Both are best-effort and neither blocks boot.
+ * The commission→project back-pointer is backfilled here too: the dispatch path
+ * only consults a commission when the project names one, so a project minted
+ * before the back-pointer existed would keep running on the provider frozen at
+ * its fire — and would be invisible to the commission's stop.
+ *
+ * All best-effort; none of them blocks boot, and none makes an LLM call.
*/
-export const armCommissionScheduler = ({ backfillCommissionFeedback, startCommissionScheduler }) => {
+export const armCommissionScheduler = ({
+ backfillCommissionFeedback, backfillProjectCommissionIds, startCommissionScheduler,
+}) => {
bestEffort(backfillCommissionFeedback(), logFailure('Commission feedback backfill failed'));
+ bestEffort(backfillProjectCommissionIds(), logFailure('Commission back-pointer backfill failed'));
bestEffort(startCommissionScheduler(), logFailure('Creative Commission scheduler init failed'));
};
diff --git a/server/services/bootstrapSequence.test.js b/server/services/bootstrapSequence.test.js
index 0f584c5681..e4fb3281e4 100644
--- a/server/services/bootstrapSequence.test.js
+++ b/server/services/bootstrapSequence.test.js
@@ -209,24 +209,27 @@ describe('initCosAfterSpawner', () => {
});
describe('armCommissionScheduler', () => {
- it('splits legacy inline feedback before arming the per-commission crons', () => {
+ it('runs both backfills before arming the per-commission crons', () => {
const { calls, step } = createRecorder();
armCommissionScheduler({
- backfillCommissionFeedback: step('backfill', () => Promise.resolve()),
+ backfillCommissionFeedback: step('feedback', () => Promise.resolve()),
+ backfillProjectCommissionIds: step('backpointer', () => Promise.resolve()),
startCommissionScheduler: step('arm', () => Promise.resolve())
});
- expect(calls).toEqual(['backfill', 'arm']);
+ expect(calls).toEqual(['feedback', 'backpointer', 'arm']);
});
- it('arms the scheduler even if the backfill fails, and logs both', async () => {
+ it('arms the scheduler even if both backfills fail, and logs each', async () => {
const arm = vi.fn(() => Promise.reject(new Error('cron boom')));
armCommissionScheduler({
backfillCommissionFeedback: () => Promise.reject(new Error('backfill boom')),
+ backfillProjectCommissionIds: () => Promise.reject(new Error('backpointer boom')),
startCommissionScheduler: arm
});
await flush();
expect(arm).toHaveBeenCalledTimes(1);
expect(console.error).toHaveBeenCalledWith(expect.stringContaining('Commission feedback backfill failed'));
+ expect(console.error).toHaveBeenCalledWith(expect.stringContaining('Commission back-pointer backfill failed'));
expect(console.error).toHaveBeenCalledWith(expect.stringContaining('Creative Commission scheduler init failed'));
});
});
diff --git a/server/services/creative/tools/cd.js b/server/services/creative/tools/cd.js
index 960d16175b..09b792136b 100644
--- a/server/services/creative/tools/cd.js
+++ b/server/services/creative/tools/cd.js
@@ -12,11 +12,17 @@ import { getProject } from '../../creativeDirector/local.js';
import { COST_LLM } from './shared.js';
/**
- * The calling project's render pin (#3135), inherited by the teaser this tool
- * mints. A creative commission stamps its `generation.videoMode`/`.videoModelId`
- * onto the project it runs in (creativeCommissions/abilityAdapters.js), but the
- * teaser is a SEPARATE project — without this the pin stops at that boundary and
- * the teaser renders on the install default.
+ * What the teaser this tool mints inherits from the project that called it: the
+ * render pin (#3135) and the owning commission.
+ *
+ * A creative commission stamps its `generation.videoMode`/`.videoModelId` onto
+ * the project it runs in (creativeCommissions/abilityAdapters.js), but the teaser
+ * is a SEPARATE project — without this the pin stops at that boundary and the
+ * teaser renders on the install default. `commissionId` carries for the same
+ * reason and one more: it is how the commission finds this project to STOP it,
+ * and how the teaser's own cognitive stages resolve the commission's live
+ * provider. An orphaned teaser would keep generating after the commission that
+ * asked for it was paused or deleted.
*
* Deliberately NOT in the tool schema: the planner LLM must not be able to pick
* a render backend. The pin is the user's configured choice, so it's read from
@@ -33,6 +39,7 @@ async function inheritedRenderSettings(ctx) {
return {
...(project.renderBackend ? { renderBackend: project.renderBackend } : {}),
...(project.modelId ? { modelId: project.modelId } : {}),
+ ...(project.commissionId ? { commissionId: project.commissionId } : {}),
};
}
diff --git a/server/services/creative/tools/cd.test.js b/server/services/creative/tools/cd.test.js
index 1411a653ee..7734251699 100644
--- a/server/services/creative/tools/cd.test.js
+++ b/server/services/creative/tools/cd.test.js
@@ -35,6 +35,15 @@ describe('cd_produceVideoFromIssue — render pin inheritance', () => {
expect(options()).toEqual({ renderBackend: { video: { mode: 'grok' } }, modelId: 'wan-2.2' });
});
+ it("inherits the calling project's owning commission, so the teaser is stoppable with it", async () => {
+ // The teaser is a SEPARATE project. Without the back-pointer it is invisible
+ // to the commission's stop, and would keep generating after the user paused
+ // or deleted the commission that asked for it.
+ getProject.mockResolvedValue({ id: 'cd-1', commissionId: 'commission-1' });
+ await run({ issueId: 'iss-1' }, { projectId: 'cd-1' });
+ expect(options()).toEqual({ commissionId: 'commission-1' });
+ });
+
it('an unpinned calling project contributes nothing (byte-identical to before)', async () => {
getProject.mockResolvedValue({ id: 'cd-1' });
await run({ issueId: 'iss-1' }, { projectId: 'cd-1' });
diff --git a/server/services/creativeCommissions/projectControl.js b/server/services/creativeCommissions/projectControl.js
new file mode 100644
index 0000000000..8eabbf32cb
--- /dev/null
+++ b/server/services/creativeCommissions/projectControl.js
@@ -0,0 +1,282 @@
+/**
+ * Creative Commission → Creative Director project control.
+ *
+ * A commission fire mints a CD project and the advance loop drives it from
+ * there. Two things the commission must still be able to do to that work, and
+ * the seam both run on:
+ *
+ * - **Stop it.** Pausing or deleting a commission used to cancel only the CRON.
+ * The projects already spawned kept re-dispatching their cognitive stages,
+ * and the orphan sweeps (boot + the 15-minute health check in cos.js) kept
+ * respawning the agent tasks behind them — so a commission with a bad brief
+ * could not actually be stopped. `stopCommissionProjects` runs the CD hard
+ * stop over everything the commission spawned.
+ *
+ * - **Re-provider it.** The commission's LLM pin is resolved at DISPATCH time
+ * (agentBridge → `commissionStagePin` below), so an edit reaches every
+ * not-yet-dispatched stage with no write and no sweep. The one thing a live
+ * read cannot fix is a task ALREADY handed to the runner: its provider is
+ * frozen in the task's own metadata, and the orphan sweep respawns it
+ * verbatim. `restartCommissionStages` retires exactly those.
+ *
+ * The link is `project.commissionId`, stamped at fire time. The commission's run
+ * ledger is NOT the link: it is capped at MAX_PERSISTED_RUNS, so a project still
+ * wedged after that many fires — the precise case this module exists for — has
+ * already fallen out of it, and a project a plan step spawns indirectly
+ * (bridgeFromIssue) never enters it at all. The ledger is still unioned in as a
+ * compatibility path for projects minted before the back-pointer existed.
+ *
+ * Everything here runs OUTSIDE the Express request lifecycle (the store's
+ * `commission:changed` bus) — no path throws out.
+ */
+
+import { commissionStore, sanitizeCommission, commissionEvents } from './store.js';
+import { PROJECT_TERMINAL_STATUSES } from '../../lib/creativeDirectorPresets.js';
+
+// The CD cognitive stages a commission's single pin drives. `evaluation` is
+// deliberately absent — it is a vision API call, not a CoS agent, and pinning it
+// to a CLI/TUI provider would trip agentBridge's harness-boundary guard.
+export const COMMISSION_PINNED_STAGES = ['treatment', 'plan'];
+
+// Statuses in which a project is still being driven by the advance loop, so a
+// stage restart should hand it straight back. A `paused` project keeps the fresh
+// provider but is NOT auto-resumed — the user parked it, and Resume is theirs.
+const ADVANCING_PROJECT_STATUSES = new Set(['planning', 'rendering', 'stitching']);
+
+/**
+ * Read a commission by id INCLUDING a tombstoned one — the delete path runs
+ * AFTER the tombstone lands and still needs the record. Reads raw (not
+ * `getCommission`) deliberately: these paths only need the machine-local
+ * assignment, and must not drag the federated feedback hydration onto an
+ * event-bus handler or onto every agent dispatch.
+ */
+async function readCommission(id) {
+ if (!id) return null;
+ const raw = await commissionStore().readRaw(id, { includeDeleted: true }).catch(() => null);
+ return raw ? sanitizeCommission(raw) : null;
+}
+
+/**
+ * The commission's live `{ providerId, model }` pin for its CD cognitive stages,
+ * or `null` to inherit the install's AI Assignment. Resolved at DISPATCH, so an
+ * edit to the commission reaches work already in flight without rewriting a
+ * single project record.
+ *
+ * A pin becomes unusable three ways — an api-type provider (trips agentBridge's
+ * harness-boundary guard), a removed provider, or a provider the user later
+ * DISABLED (the agent runner honors an explicit task pin without re-checking
+ * `enabled`, so a disabled provider would keep launching commissions and defeat
+ * the disable control). The UI only offers enabled agent-harness providers, but a
+ * direct REST write, a provider whose type later changed to `api`, or a post-pin
+ * disable could slip a bad pin past it. An unusable pin is DROPPED so the stage
+ * falls back to the install default and the commission still generates rather
+ * than stalling. Fail open: an unresolvable provider (toolkit hiccup) also falls
+ * back.
+ */
+export async function commissionStagePin(commissionId) {
+ const commission = await readCommission(commissionId);
+ const providerId = commission?.assignment?.providerId;
+ if (!providerId) return null;
+ const [{ getProviderById }, { PROVIDER_TYPES }] = await Promise.all([
+ import('../providers.js'),
+ import('../../lib/aiToolkit/constants.js'),
+ ]);
+ const provider = await getProviderById(providerId).catch(() => null);
+ const isAgentHarness = provider?.type === PROVIDER_TYPES.CLI || provider?.type === PROVIDER_TYPES.TUI;
+ if (!isAgentHarness || provider?.enabled === false) {
+ const reason = !provider ? 'missing' : (!isAgentHarness ? `non-agent:${provider.type}` : 'disabled');
+ console.warn(`⚠️ Creative commission ${commissionId} pins unusable provider '${providerId}' (${reason}) — falling back to the default CD assignment`);
+ return null;
+ }
+ return { providerId, ...(commission.assignment.model ? { model: commission.assignment.model } : {}) };
+}
+
+/**
+ * Distinct CD project ids named by a commission's run ledger, newest first. Pure.
+ * The compatibility half of the lookup — see `commissionProjects`.
+ */
+export function ledgerProjectIds(commission) {
+ const seen = new Set();
+ const runs = Array.isArray(commission?.runs) ? commission.runs : [];
+ for (let i = runs.length - 1; i >= 0; i -= 1) {
+ const id = runs[i]?.projectId;
+ if (typeof id === 'string' && id && !seen.has(id)) seen.add(id);
+ }
+ return [...seen];
+}
+
+/**
+ * Every live, non-terminal project a commission owns. Unions the authoritative
+ * `commissionId` query with the run ledger, so projects minted before the
+ * back-pointer existed are still reachable on an install that just upgraded.
+ */
+async function commissionProjects(commissionId, preread) {
+ const { listProjectsByCommissionId, getProjectsByIds } = await import('../creativeDirector/local.js');
+ const owned = await listProjectsByCommissionId(commissionId).catch(() => []);
+ // The ledger fallback needs the record. Callers that already hold it pass it
+ // in; the delete path does not, and reading it here (rather than making every
+ // caller remember) is what keeps pre-back-pointer projects reachable on a
+ // delete as well as a pause.
+ const commission = preread || await readCommission(commissionId);
+ const known = new Set(owned.map((p) => p.id));
+ const legacyIds = ledgerProjectIds(commission).filter((id) => !known.has(id));
+ const legacy = legacyIds.length ? await getProjectsByIds(legacyIds).catch(() => []) : [];
+ return [...owned, ...legacy].filter((p) => p && !PROJECT_TERMINAL_STATUSES.has(p.status));
+}
+
+/**
+ * Retire the stages a commission's projects have ALREADY dispatched, so the next
+ * dispatch picks up the commission's current provider instead of the one frozen
+ * in the live task's metadata, then hand each project back to the advance loop.
+ *
+ * Only the LLM stages are torn down — a `plan-step` run is a tool dispatch (often
+ * a render already burning GPU time) and has nothing to do with the LLM pin.
+ *
+ * @returns {Promise<{restarted: string[], checked: number}>}
+ */
+export async function restartCommissionStages(commissionId, commission) {
+ const projects = await commissionProjects(commissionId, commission);
+ if (!projects.length) return { restarted: [], checked: 0 };
+
+ const [{ inflightRuns, retireRuns }, { advanceAfterPlanStepSettled }] = await Promise.all([
+ import('../creativeDirector/stopProject.js'),
+ import('../creativeDirector/planAdvance.js'),
+ ]);
+ const reason = 'Creative commission provider changed';
+ const restarted = [];
+ for (const project of projects) {
+ const stale = inflightRuns(project, COMMISSION_PINNED_STAGES);
+ if (!stale.length) continue;
+ await retireRuns(project.id, { runs: stale, reason })
+ .catch((e) => console.error(`❌ Commission ${commissionId}: retire runs on ${project.id} failed: ${e.message}`));
+ restarted.push(project.id);
+ if (!ADVANCING_PROJECT_STATUSES.has(project.status)) continue;
+ await advanceAfterPlanStepSettled(project.id)
+ .catch((e) => console.error(`❌ Commission ${commissionId}: advance ${project.id} failed: ${e.message}`));
+ }
+ if (restarted.length) {
+ console.log(`🎯 Commission ${commissionId} restarted ${restarted.length} in-flight stage(s) under its current provider`);
+ }
+ return { restarted, checked: projects.length };
+}
+
+/**
+ * Hard-stop every project this commission spawned — the missing half of pausing
+ * or deleting a commission. Cancelling the cron stops FUTURE fires; this stops
+ * the work already running (agent processes, CoS tasks, run rows, media jobs).
+ *
+ * Stopped projects are parked as `paused` with the reason, NOT deleted: the
+ * outputs already produced stay browsable, and the user can Resume an individual
+ * project from the CD detail page if they only wanted to change the provider.
+ *
+ * @returns {Promise<{stopped: string[], checked: number}>}
+ */
+export async function stopCommissionProjects(commissionId, { reason = 'Commission stopped', commission } = {}) {
+ const projects = await commissionProjects(commissionId, commission);
+ if (!projects.length) return { stopped: [], checked: 0 };
+
+ const { stopProject } = await import('../creativeDirector/stopProject.js');
+ const stopped = [];
+ for (const project of projects) {
+ const result = await stopProject(project.id, { reason, project })
+ .catch((e) => { console.error(`❌ Commission ${commissionId}: stop ${project.id} failed: ${e.message}`); return null; });
+ if (result?.stopped) stopped.push(project.id);
+ }
+ if (stopped.length) {
+ console.log(`🛑 Commission ${commissionId} stopped ${stopped.length} in-flight project(s): ${reason}`);
+ }
+ return { stopped, checked: projects.length };
+}
+
+// A commission mutation that cannot possibly change what its in-flight work
+// should be doing. `fields` is the patched key set, absent on emitters that don't
+// report one — and absent must mean "reconcile" (we cannot prove it was
+// irrelevant), never "skip".
+const RECONCILABLE_FIELDS = ['enabled', 'assignment'];
+
+/**
+ * The `commission:changed` reconciler — the single decision table for what a
+ * commission mutation must do to the work it already spawned:
+ *
+ * delete → stop everything (the user removed the job).
+ * update + disabled → stop everything (Pause means STOP, not "let it keep
+ * retrying with no way to intervene").
+ * update + enabled → restart the stages already dispatched, so they pick up
+ * restore the commission's current provider on re-dispatch.
+ * create → nothing; a brand-new commission has spawned nothing.
+ * merge (no id) → nothing; a peer merge only carries the federated brief,
+ * never the machine-local schedule/assignment/runs.
+ *
+ * Never throws — it runs on an EventEmitter callback, outside any request.
+ */
+export async function reconcileCommissionProjects({ id, action, fields } = {}) {
+ if (!id || action === 'create') return { action: 'noop' };
+ if (action === 'delete') {
+ await stopCommissionProjects(id, { reason: 'Creative commission deleted' });
+ return { action: 'stopped' };
+ }
+ if (Array.isArray(fields) && !fields.some((f) => RECONCILABLE_FIELDS.includes(f))) {
+ return { action: 'noop' };
+ }
+ const commission = await readCommission(id);
+ if (!commission) return { action: 'noop' };
+ if (commission.enabled === false) {
+ await stopCommissionProjects(id, { reason: 'Creative commission paused', commission });
+ return { action: 'stopped' };
+ }
+ await restartCommissionStages(id, commission);
+ return { action: 'restarted' };
+}
+
+/**
+ * Subscribe the reconciler to every commission write. Lives here rather than in
+ * the cron scheduler so that module stays about arming crons; called once at
+ * import by whoever pulls this module into the boot graph.
+ */
+export function registerCommissionProjectReconciler() {
+ commissionEvents.on('commission:changed', (change) => {
+ reconcileCommissionProjects(change).catch((err) =>
+ console.error(`❌ Creative commission project reconcile failed: ${err.message}`));
+ });
+}
+
+/**
+ * One-shot boot backfill: stamp `commissionId` onto the projects a commission
+ * spawned BEFORE the back-pointer existed, reading it out of the run ledger.
+ *
+ * Without this, an install upgrading with a project already wedged keeps the old
+ * behavior for exactly the projects that need the fix most — the dispatch path
+ * only consults a commission when the project names one, so a stuck project would
+ * go on handing its planner task to the provider frozen at fire time even after
+ * the user re-pointed the commission. The ledger is capped, so this recovers what
+ * it still remembers; anything already evicted stays unlinked (nothing else can
+ * recover it, and a fresh fire mints a correctly-stamped project).
+ *
+ * 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.
+ *
+ * @returns {Promise<{stamped: number}>}
+ */
+export async function backfillProjectCommissionIds() {
+ const ids = await commissionStore().listIds({ includeDeleted: true }).catch(() => []);
+ if (!ids.length) return { stamped: 0 };
+
+ const { getProjectsByIds, updateProject } = await import('../creativeDirector/local.js');
+ let stamped = 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(() => []);
+ for (const project of projects) {
+ if (!project || project.commissionId) continue;
+ const ok = await updateProject(project.id, { commissionId })
+ .then(() => true)
+ .catch((e) => { console.error(`❌ Commission back-pointer backfill: ${project.id} failed: ${e.message}`); return false; });
+ if (ok) stamped += 1;
+ }
+ }
+ if (stamped) console.log(`🎯 Commission back-pointer backfill: stamped ${stamped} pre-existing project(s)`);
+ return { stamped };
+}
diff --git a/server/services/creativeCommissions/projectControl.test.js b/server/services/creativeCommissions/projectControl.test.js
new file mode 100644
index 0000000000..d2fcb4465a
--- /dev/null
+++ b/server/services/creativeCommissions/projectControl.test.js
@@ -0,0 +1,356 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { EventEmitter } from 'events';
+
+// The raw store read (tombstone-inclusive) these paths run on.
+const readRawMock = vi.fn(async () => null);
+const listIdsMock = vi.fn(async () => []);
+const commissionEvents = new EventEmitter();
+vi.mock('./store.js', () => ({
+ commissionStore: () => ({ readRaw: (...a) => readRawMock(...a), listIds: (...a) => listIdsMock(...a) }),
+ commissionEvents,
+ // The real sanitizer only needs to preserve the fields this module reads;
+ // identity keeps the fixtures readable and store.test.js owns sanitizer coverage.
+ sanitizeCommission: (raw) => raw,
+}));
+
+const getProviderByIdMock = vi.fn(async (id) => ({ id, type: 'tui' }));
+vi.mock('../providers.js', () => ({ getProviderById: (...a) => getProviderByIdMock(...a) }));
+vi.mock('../../lib/aiToolkit/constants.js', () => ({ PROVIDER_TYPES: { CLI: 'cli', TUI: 'tui', API: 'api' } }));
+
+const listProjectsByCommissionIdMock = vi.fn(async () => []);
+const getProjectsByIdsMock = vi.fn(async () => []);
+const updateProjectMock = vi.fn(async () => ({}));
+vi.mock('../creativeDirector/local.js', () => ({
+ listProjectsByCommissionId: (...a) => listProjectsByCommissionIdMock(...a),
+ getProjectsByIds: (...a) => getProjectsByIdsMock(...a),
+ updateProject: (...a) => updateProjectMock(...a),
+}));
+
+const stopProjectMock = vi.fn(async (id) => ({ projectId: id, stopped: true }));
+const retireRunsMock = vi.fn(async () => ({ runs: 1, tasks: 1, agents: 1 }));
+vi.mock('../creativeDirector/stopProject.js', () => ({
+ stopProject: (...a) => stopProjectMock(...a),
+ retireRuns: (...a) => retireRunsMock(...a),
+ // The real (pure) filter — the restart path must narrow to the LLM stages, and a
+ // stubbed pass-through would hide it sweeping up plan-step render runs too.
+ inflightRuns: (project, kinds) => (project?.runs || []).filter((r) => r
+ && r.status !== 'completed' && r.status !== 'failed'
+ && (!kinds || kinds.includes(r.kind))),
+}));
+
+const advanceMock = vi.fn(async () => {});
+vi.mock('../creativeDirector/planAdvance.js', () => ({ advanceAfterPlanStepSettled: (...a) => advanceMock(...a) }));
+
+const {
+ ledgerProjectIds,
+ commissionStagePin,
+ backfillProjectCommissionIds,
+ restartCommissionStages,
+ stopCommissionProjects,
+ reconcileCommissionProjects,
+} = await import('./projectControl.js');
+
+const commission = (over = {}) => ({
+ id: 'commission-1',
+ enabled: true,
+ assignment: { providerId: 'lmstudio-tui', model: 'qwen3.6:35b' },
+ runs: [],
+ ...over,
+});
+
+const project = (over = {}) => ({ id: 'cd-1', status: 'planning', runs: [], ...over });
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ getProviderByIdMock.mockImplementation(async (id) => ({ id, type: 'tui' }));
+ readRawMock.mockResolvedValue(null);
+ listIdsMock.mockResolvedValue([]);
+ listProjectsByCommissionIdMock.mockResolvedValue([]);
+ getProjectsByIdsMock.mockResolvedValue([]);
+});
+
+describe('ledgerProjectIds', () => {
+ it('returns distinct ids newest-first and drops run rows that minted nothing', () => {
+ const ids = ledgerProjectIds({
+ runs: [
+ { projectId: 'cd-a' },
+ { status: 'skipped', projectId: null },
+ { projectId: 'cd-b' },
+ { projectId: 'cd-a' }, // a re-run against the same project
+ ],
+ });
+ expect(ids).toEqual(['cd-a', 'cd-b']);
+ });
+
+ it('tolerates a commission with no run history', () => {
+ expect(ledgerProjectIds(null)).toEqual([]);
+ expect(ledgerProjectIds({ runs: 'nope' })).toEqual([]);
+ });
+});
+
+describe('commissionStagePin', () => {
+ it('resolves the commission LIVE, so a dispatch picks up an edited provider', async () => {
+ readRawMock.mockResolvedValue(commission());
+ expect(await commissionStagePin('commission-1')).toEqual({ providerId: 'lmstudio-tui', model: 'qwen3.6:35b' });
+ });
+
+ it('inherits the default when nothing is pinned', async () => {
+ readRawMock.mockResolvedValue(commission({ assignment: {} }));
+ expect(await commissionStagePin('commission-1')).toBeNull();
+ expect(getProviderByIdMock).not.toHaveBeenCalled();
+ });
+
+ it('inherits the default for an unknown commission', async () => {
+ readRawMock.mockResolvedValue(null);
+ expect(await commissionStagePin('commission-gone')).toBeNull();
+ });
+
+ it.each([
+ ['an api-type provider (no agent harness)', { id: 'gpt-4o', type: 'api' }],
+ ['a removed provider', null],
+ ['a disabled provider', { id: 'lmstudio-tui', type: 'tui', enabled: false }],
+ ])('drops the pin for %s', async (_label, provider) => {
+ readRawMock.mockResolvedValue(commission());
+ getProviderByIdMock.mockResolvedValue(provider);
+ expect(await commissionStagePin('commission-1')).toBeNull();
+ });
+
+ it('fails open when provider resolution throws', async () => {
+ readRawMock.mockResolvedValue(commission());
+ getProviderByIdMock.mockRejectedValue(new Error('toolkit hiccup'));
+ expect(await commissionStagePin('commission-1')).toBeNull();
+ });
+});
+
+describe('project lookup', () => {
+ it('finds projects by the commissionId back-pointer, not the capped run ledger', async () => {
+ // The ledger has evicted this project (the case the whole module exists for).
+ readRawMock.mockResolvedValue(commission({ runs: [] }));
+ listProjectsByCommissionIdMock.mockResolvedValue([project({ id: 'cd-wedged' })]);
+
+ await stopCommissionProjects('commission-1');
+
+ expect(stopProjectMock).toHaveBeenCalledWith('cd-wedged', expect.objectContaining({ reason: expect.any(String) }));
+ });
+
+ it('still reaches projects minted before the back-pointer existed, via the ledger', async () => {
+ readRawMock.mockResolvedValue(commission({ runs: [{ projectId: 'cd-legacy' }] }));
+ listProjectsByCommissionIdMock.mockResolvedValue([]);
+ getProjectsByIdsMock.mockResolvedValue([project({ id: 'cd-legacy' })]);
+
+ await stopCommissionProjects('commission-1');
+
+ expect(getProjectsByIdsMock).toHaveBeenCalledWith(['cd-legacy']);
+ expect(stopProjectMock).toHaveBeenCalledWith('cd-legacy', expect.anything());
+ });
+
+ it('does not re-fetch a ledger id the back-pointer query already returned', async () => {
+ readRawMock.mockResolvedValue(commission({ runs: [{ projectId: 'cd-1' }] }));
+ listProjectsByCommissionIdMock.mockResolvedValue([project({ id: 'cd-1' })]);
+
+ await stopCommissionProjects('commission-1');
+
+ expect(getProjectsByIdsMock).not.toHaveBeenCalled();
+ expect(stopProjectMock).toHaveBeenCalledTimes(1);
+ });
+
+ it('leaves finished projects alone', async () => {
+ readRawMock.mockResolvedValue(commission());
+ listProjectsByCommissionIdMock.mockResolvedValue([
+ project({ id: 'cd-done', status: 'complete' }),
+ project({ id: 'cd-dead', status: 'failed' }),
+ ]);
+
+ await stopCommissionProjects('commission-1');
+
+ expect(stopProjectMock).not.toHaveBeenCalled();
+ });
+});
+
+describe('stopCommissionProjects', () => {
+ it('stops every live project, passing the pre-read record so stopProject skips a re-read', async () => {
+ readRawMock.mockResolvedValue(commission());
+ const p1 = project({ id: 'cd-1' });
+ const p2 = project({ id: 'cd-2' });
+ listProjectsByCommissionIdMock.mockResolvedValue([p1, p2]);
+
+ const result = await stopCommissionProjects('commission-1', { reason: 'Creative commission deleted' });
+
+ expect(stopProjectMock).toHaveBeenCalledWith('cd-1', { reason: 'Creative commission deleted', project: p1 });
+ expect(result.stopped).toEqual(['cd-1', 'cd-2']);
+ });
+
+ it('reads the TOMBSTONED record so a delete can still find its projects', async () => {
+ readRawMock.mockResolvedValue(commission({ deleted: true, runs: [{ projectId: 'cd-1' }] }));
+ getProjectsByIdsMock.mockResolvedValue([project()]);
+ await stopCommissionProjects('commission-1');
+ expect(readRawMock).toHaveBeenCalledWith('commission-1', { includeDeleted: true });
+ expect(stopProjectMock).toHaveBeenCalledWith('cd-1', expect.anything());
+ });
+
+ it('keeps going when one project fails to stop', async () => {
+ readRawMock.mockResolvedValue(commission());
+ listProjectsByCommissionIdMock.mockResolvedValue([project({ id: 'cd-1' }), project({ id: 'cd-2' })]);
+ stopProjectMock.mockRejectedValueOnce(new Error('boom'));
+
+ const result = await stopCommissionProjects('commission-1');
+
+ expect(stopProjectMock).toHaveBeenCalledTimes(2);
+ expect(result).toMatchObject({ stopped: ['cd-2'], checked: 2 });
+ });
+});
+
+describe('restartCommissionStages', () => {
+ it('retires the wedged stage task and re-advances — the task metadata still holds the OLD provider', async () => {
+ const order = [];
+ retireRunsMock.mockImplementation(async () => { order.push('retire'); return { runs: 1, tasks: 1, agents: 1 }; });
+ advanceMock.mockImplementation(async () => { order.push('advance'); });
+ readRawMock.mockResolvedValue(commission());
+ listProjectsByCommissionIdMock.mockResolvedValue([project({
+ runs: [
+ { runId: 'r1', kind: 'plan', taskId: 'cd-1-plan-a', status: 'running' },
+ { runId: 'r2', kind: 'plan-step', status: 'running' }, // a render — not an LLM stage
+ { runId: 'r3', kind: 'plan', status: 'completed' },
+ ],
+ })]);
+
+ const result = await restartCommissionStages('commission-1');
+
+ expect(order).toEqual(['retire', 'advance']);
+ // Only the LLM stage is retired — the in-flight render step is left alone.
+ expect(retireRunsMock).toHaveBeenCalledExactlyOnceWith('cd-1', {
+ runs: [expect.objectContaining({ runId: 'r1' })],
+ reason: 'Creative commission provider changed',
+ });
+ expect(result.restarted).toEqual(['cd-1']);
+ });
+
+ it('restarts a PAUSED project’s stage but never auto-resumes the project', async () => {
+ readRawMock.mockResolvedValue(commission());
+ listProjectsByCommissionIdMock.mockResolvedValue([project({
+ status: 'paused',
+ runs: [{ runId: 'r1', kind: 'plan', taskId: 't1', status: 'running' }],
+ })]);
+
+ const result = await restartCommissionStages('commission-1');
+
+ expect(retireRunsMock).toHaveBeenCalled();
+ expect(advanceMock).not.toHaveBeenCalled();
+ expect(result.restarted).toEqual(['cd-1']);
+ });
+
+ it('does nothing when no stage is in flight — a live pin needs no teardown', async () => {
+ readRawMock.mockResolvedValue(commission());
+ listProjectsByCommissionIdMock.mockResolvedValue([project({
+ runs: [{ runId: 'r1', kind: 'plan', status: 'completed' }],
+ })]);
+
+ const result = await restartCommissionStages('commission-1');
+
+ expect(retireRunsMock).not.toHaveBeenCalled();
+ expect(advanceMock).not.toHaveBeenCalled();
+ expect(result.restarted).toEqual([]);
+ });
+});
+
+describe('reconcileCommissionProjects', () => {
+ const wedged = () => project({ runs: [{ runId: 'r1', kind: 'plan', taskId: 't1', status: 'running' }] });
+
+ it('stops in-flight work on delete', async () => {
+ readRawMock.mockResolvedValue(commission({ deleted: true }));
+ listProjectsByCommissionIdMock.mockResolvedValue([project()]);
+ const result = await reconcileCommissionProjects({ id: 'commission-1', action: 'delete' });
+ expect(result).toEqual({ action: 'stopped' });
+ expect(stopProjectMock).toHaveBeenCalledWith('cd-1', expect.objectContaining({ reason: 'Creative commission deleted' }));
+ });
+
+ it('stops in-flight work when the commission is PAUSED — pause means stop, not "skip the next tick"', async () => {
+ readRawMock.mockResolvedValue(commission({ enabled: false }));
+ listProjectsByCommissionIdMock.mockResolvedValue([project()]);
+ const result = await reconcileCommissionProjects({ id: 'commission-1', action: 'update' });
+ expect(result).toEqual({ action: 'stopped' });
+ expect(stopProjectMock).toHaveBeenCalledWith('cd-1', expect.objectContaining({ reason: 'Creative commission paused' }));
+ expect(retireRunsMock).not.toHaveBeenCalled();
+ });
+
+ it('restarts (never stops) the stages of an enabled commission whose provider changed', async () => {
+ readRawMock.mockResolvedValue(commission());
+ listProjectsByCommissionIdMock.mockResolvedValue([wedged()]);
+
+ const result = await reconcileCommissionProjects({ id: 'commission-1', action: 'update', fields: ['assignment'] });
+
+ expect(result).toEqual({ action: 'restarted' });
+ expect(stopProjectMock).not.toHaveBeenCalled();
+ expect(retireRunsMock).toHaveBeenCalled();
+ });
+
+ it('skips the project lookup for an edit that cannot affect in-flight work', async () => {
+ const result = await reconcileCommissionProjects({ id: 'commission-1', action: 'update', fields: ['brief', 'schedule'] });
+ expect(result).toEqual({ action: 'noop' });
+ expect(readRawMock).not.toHaveBeenCalled();
+ expect(listProjectsByCommissionIdMock).not.toHaveBeenCalled();
+ });
+
+ it('reconciles when the emitter reports NO field set — absent must not read as irrelevant', async () => {
+ readRawMock.mockResolvedValue(commission({ enabled: false }));
+ listProjectsByCommissionIdMock.mockResolvedValue([project()]);
+ const result = await reconcileCommissionProjects({ id: 'commission-1', action: 'update' });
+ expect(result).toEqual({ action: 'stopped' });
+ });
+
+ it.each([['create'], [undefined]])('ignores %s (nothing spawned / no id)', async (action) => {
+ const result = await reconcileCommissionProjects(action === 'create'
+ ? { id: 'commission-1', action: 'create' }
+ : { action: 'merge' });
+ expect(result).toEqual({ action: 'noop' });
+ expect(readRawMock).not.toHaveBeenCalled();
+ expect(stopProjectMock).not.toHaveBeenCalled();
+ });
+
+ it('ignores a vanished commission', async () => {
+ readRawMock.mockResolvedValue(null);
+ expect(await reconcileCommissionProjects({ id: 'commission-gone', action: 'update' })).toEqual({ action: 'noop' });
+ expect(stopProjectMock).not.toHaveBeenCalled();
+ });
+});
+
+describe('backfillProjectCommissionIds', () => {
+ it('stamps the back-pointer onto projects minted before the field existed', async () => {
+ // Without this, an install upgrading with a project ALREADY wedged keeps the
+ // old behavior for exactly the project that needs the fix: the dispatch path
+ // only consults a commission when the project names one.
+ listIdsMock.mockResolvedValue(['commission-1']);
+ readRawMock.mockResolvedValue(commission({ runs: [{ projectId: 'cd-old' }, { projectId: 'cd-new' }] }));
+ getProjectsByIdsMock.mockResolvedValue([
+ { id: 'cd-old', status: 'planning' },
+ { id: 'cd-new', status: 'planning', commissionId: 'commission-1' }, // already stamped
+ ]);
+
+ const result = await backfillProjectCommissionIds();
+
+ expect(updateProjectMock).toHaveBeenCalledExactlyOnceWith('cd-old', { commissionId: 'commission-1' });
+ expect(result).toEqual({ stamped: 1 });
+ });
+
+ it('includes tombstoned commissions — their wedged projects still need stopping', async () => {
+ listIdsMock.mockResolvedValue(['commission-1']);
+ readRawMock.mockResolvedValue(commission({ deleted: true, runs: [{ projectId: 'cd-old' }] }));
+ getProjectsByIdsMock.mockResolvedValue([{ id: 'cd-old', status: 'planning' }]);
+
+ await backfillProjectCommissionIds();
+
+ expect(listIdsMock).toHaveBeenCalledWith({ includeDeleted: true });
+ expect(updateProjectMock).toHaveBeenCalled();
+ });
+
+ it('is a no-op on a fresh install and on a re-run', async () => {
+ expect(await backfillProjectCommissionIds()).toEqual({ stamped: 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(updateProjectMock).not.toHaveBeenCalled();
+ });
+});
diff --git a/server/services/creativeCommissions/scheduler.js b/server/services/creativeCommissions/scheduler.js
index b7bc065b3c..cd0a719907 100644
--- a/server/services/creativeCommissions/scheduler.js
+++ b/server/services/creativeCommissions/scheduler.js
@@ -33,6 +33,7 @@ import { commissionToCron } from './directive.js';
import { buildCommissionDirective, getAbilityAdapter } from './abilityAdapters.js';
import { buildMusicTasteRecipe } from './musicTasteRecipe.js';
import { surfaceCommissionRun } from './surface.js';
+import { registerCommissionProjectReconciler } from './projectControl.js';
const eventId = (commissionId) => `creative-commission-${commissionId}`;
const registered = new Set();
@@ -47,6 +48,11 @@ function triggerResync() {
// Re-arm crons whenever a commission is created/updated/deleted through ANY
// writer, not just the REST route — decoupled from the HTTP handler.
commissionEvents.on('commission:changed', triggerResync);
+// Cancelling the cron only stops FUTURE fires. projectControl owns the other half
+// — reconciling the work a commission ALREADY spawned when it is paused, deleted,
+// or re-providered. Registered from here because this module is already the one
+// the boot sequence pulls in; the logic itself stays out of the cron concern.
+registerCommissionProjectReconciler();
// Also re-sync on a settings save so a global timezone change re-registers the
// crons of commissions that use the fallback tz (schedule.timezone == null) —
// same reason seriesAutopilotScheduler subscribes here. The signature guard
@@ -297,45 +303,6 @@ async function fireCommission(commission, trigger) {
effectiveVideoMode,
effectiveVideoModelId,
});
- // Fan the commission's single LLM pin onto BOTH CD cognitive stages
- // (treatment + plan) as the project's `modelOverrides`, so the scheduled
- // fire is processed by the provider/model the user chose rather than the
- // install default. An unset pin yields `{}` → each stage inherits the global
- // AI Assignment (createProject.normalizeModelOverrides drops empty stages).
- // Evaluation is deliberately left inheriting the default: it's a vision API
- // call, not a CoS agent, and pinning it to a CLI/TUI agent provider would
- // trip agentBridge's harness-boundary guard.
- //
- // Guard the pin at fire time: treatment/plan run as CoS agent tasks, which
- // only accept an ENABLED agent-harness (cli/tui) provider. A pin becomes
- // unusable three ways — an api-type provider (trips agentBridge's
- // harness-boundary guard), a removed provider, or a provider the user later
- // DISABLED (the agent runner honors an explicit task pin without re-checking
- // `enabled`, so a disabled provider would keep launching commissions and
- // defeat the disable control). The UI only offers enabled agent-harness
- // providers, but a direct REST write, a provider whose type later changed to
- // `api`, or a post-pin disable could slip a bad pin past it. Resolve the
- // provider now and DROP an unusable pin (falling back to the install default)
- // so the commission still generates rather than stalling or running through a
- // disabled provider. Fail open: an unresolvable provider (toolkit hiccup)
- // also falls back.
- let modelOverrides = {};
- if (commission.assignment?.providerId) {
- const [{ getProviderById }, { PROVIDER_TYPES }] = await Promise.all([
- import('../providers.js'),
- import('../../lib/aiToolkit/constants.js'),
- ]);
- const provider = await getProviderById(commission.assignment.providerId).catch(() => null);
- const isAgentHarness = provider?.type === PROVIDER_TYPES.CLI || provider?.type === PROVIDER_TYPES.TUI;
- const agentCapable = isAgentHarness && provider?.enabled !== false;
- if (agentCapable) {
- const pin = { providerId: commission.assignment.providerId, ...(commission.assignment.model ? { model: commission.assignment.model } : {}) };
- modelOverrides = { treatment: pin, plan: pin };
- } else {
- const reason = !provider ? 'missing' : (!isAgentHarness ? `non-agent:${provider.type}` : 'disabled');
- console.warn(`⚠️ Creative commission ${commissionId} pins unusable provider '${commission.assignment.providerId}' (${reason}) — falling back to the default CD assignment`);
- }
- }
// createProject prefixes "Creative Director: " (19 chars) before a
// mediaCollections name capped at 80, so cap our derived name at 61 — a long
// commission name would otherwise fail the collection create on every run.
@@ -354,7 +321,12 @@ async function fireCommission(commission, trigger) {
...projectParams,
styleSpec: commission.brief?.styleSpec || '',
directive,
- modelOverrides,
+ // The back-pointer, NOT a copy of the commission's provider pin. agentBridge
+ // resolves that pin live from this id at every dispatch, so an edit to the
+ // commission reaches a project already in flight; a snapshot written here
+ // would freeze the provider for the life of the project. It is also how
+ // pause/delete finds this project in order to stop it.
+ commissionId,
});
startedProjectId = project.id;
diff --git a/server/services/creativeCommissions/scheduler.test.js b/server/services/creativeCommissions/scheduler.test.js
index 2981fe95f4..c706979216 100644
--- a/server/services/creativeCommissions/scheduler.test.js
+++ b/server/services/creativeCommissions/scheduler.test.js
@@ -24,6 +24,12 @@ vi.mock('./store.js', () => ({
getCommission: (...a) => getCommissionMock(...a),
recordCommissionRun: (...a) => recordRunMock(...a),
commissionEvents,
+ // projectControl (the commission:changed reconciler the scheduler subscribes)
+ // reads the raw record to find the projects a commission spawned. Empty here —
+ // the reconciler is covered by projectControl.test.js; these tests are about
+ // cron arming + the fire path.
+ commissionStore: () => ({ readRaw: async () => null }),
+ sanitizeCommission: (raw) => raw,
}));
// Surfacing (notification + brain inbox) is mocked so the fire handler stays
@@ -177,9 +183,6 @@ describe('runScheduledCommission gates', () => {
expect(createProjectMock).toHaveBeenCalledWith(expect.objectContaining({
aspectRatio: '16:9', quality: 'standard', modelId: 'ltx-default', targetDurationSeconds: 10,
directive: expect.objectContaining({ goal: expect.stringContaining('surreal') }),
- // An unset LLM assignment leaves modelOverrides empty → the CD stages
- // inherit the install's default AI Assignment (pre-#2657 behavior).
- modelOverrides: {},
}));
expect(advanceMock).toHaveBeenCalledWith('cd-xyz');
expect(recordRunMock).toHaveBeenCalledWith('commission-1', expect.objectContaining({ status: 'started', projectId: 'cd-xyz' }));
@@ -191,61 +194,20 @@ describe('runScheduledCommission gates', () => {
expect(recordUsageMock).not.toHaveBeenCalled();
});
- it('fans the LLM assignment pin onto both CD cognitive stages (treatment + plan)', async () => {
+ it('stamps the commission BACK-POINTER on the project, never a copy of its provider pin', async () => {
+ // The pin is resolved live at dispatch from this id (agentBridge →
+ // commissionStagePin), so an edit to the commission reaches a project already
+ // in flight. Writing a snapshot here is what used to freeze a wedged project
+ // on the provider it was minted with, forever.
getCommissionMock.mockResolvedValue(videoCommission({
assignment: { providerId: 'claude-tui', model: 'sonnet' },
}));
await runScheduledCommission('commission-1');
- const pin = { providerId: 'claude-tui', model: 'sonnet' };
- expect(createProjectMock).toHaveBeenCalledWith(expect.objectContaining({
- modelOverrides: { treatment: pin, plan: pin },
- }));
- });
-
- it('omits the model from the pin when only a provider is chosen', async () => {
- getCommissionMock.mockResolvedValue(videoCommission({
- assignment: { providerId: 'claude-tui', model: null },
- }));
- await runScheduledCommission('commission-1');
- const pin = { providerId: 'claude-tui' };
- expect(createProjectMock).toHaveBeenCalledWith(expect.objectContaining({
- modelOverrides: { treatment: pin, plan: pin },
- }));
- });
-
- it('drops a pin to a non-agent (api) provider and still generates on the default', async () => {
- // A CoS treatment/plan task only accepts a cli/tui provider; an api pin
- // would be rejected by the harness-boundary guard mid-fire. The guard drops
- // it so the run proceeds on the install default instead of stalling.
- getProviderByIdMock.mockResolvedValueOnce({ id: 'gpt-4o', type: 'api' });
- getCommissionMock.mockResolvedValue(videoCommission({
- assignment: { providerId: 'gpt-4o', model: 'gpt-4o' },
- }));
- await runScheduledCommission('commission-1');
- expect(createProjectMock).toHaveBeenCalledWith(expect.objectContaining({ modelOverrides: {} }));
- // The commission still fires (falls back to default), it doesn't skip.
- expect(advanceMock).toHaveBeenCalledWith('cd-xyz');
- });
-
- it('drops a pin to a removed/unresolvable provider (fails open to the default)', async () => {
- getProviderByIdMock.mockResolvedValueOnce(null);
- getCommissionMock.mockResolvedValue(videoCommission({
- assignment: { providerId: 'ghost-provider', model: null },
- }));
- await runScheduledCommission('commission-1');
- expect(createProjectMock).toHaveBeenCalledWith(expect.objectContaining({ modelOverrides: {} }));
- });
-
- it('drops a pin to a DISABLED agent provider (respects the provider disable control)', async () => {
- // The agent runner honors an explicit task pin without re-checking `enabled`,
- // so a commission pinned to a provider the user later disabled would keep
- // launching through it. The guard drops the pin and falls back to the default.
- getProviderByIdMock.mockResolvedValueOnce({ id: 'claude-tui', type: 'tui', enabled: false });
- getCommissionMock.mockResolvedValue(videoCommission({
- assignment: { providerId: 'claude-tui', model: 'sonnet' },
- }));
- await runScheduledCommission('commission-1');
- expect(createProjectMock).toHaveBeenCalledWith(expect.objectContaining({ modelOverrides: {} }));
+ const [params] = createProjectMock.mock.calls[0];
+ expect(params.commissionId).toBe('commission-1');
+ expect(params).not.toHaveProperty('modelOverrides');
+ // Resolving the pin is not this path's job any more — it must not even look.
+ expect(getProviderByIdMock).not.toHaveBeenCalled();
});
it('does NOT surface when the fire is skipped (nothing was generated)', async () => {
diff --git a/server/services/creativeCommissions/store.js b/server/services/creativeCommissions/store.js
index 745686cf2d..700bf3a58b 100644
--- a/server/services/creativeCommissions/store.js
+++ b/server/services/creativeCommissions/store.js
@@ -693,7 +693,11 @@ export async function updateCommission(id, patch) {
return next;
});
if (!merged) throw makeErr(`Commission not found: ${id}`, ERR_NOT_FOUND);
- commissionEvents.emit('commission:changed', { id, action: 'update' });
+ // Carry the patched key set: the project reconciler only cares about
+ // `enabled` and `assignment`, so a brief/schedule edit skips its project
+ // lookup entirely. Absent (other emitters) must mean "reconcile" — we cannot
+ // prove a change was irrelevant — never "skip".
+ commissionEvents.emit('commission:changed', { id, action: 'update', fields: Object.keys(patch) });
// Push the brief change to subscribed peers (the schedule/runs/assignment are
// stripped from the wire, so only the brief travels).
emitRecordUpdated(CREATIVE_COMMISSION_KIND, id);
diff --git a/server/services/creativeDirector/agentBridge.js b/server/services/creativeDirector/agentBridge.js
index 0d021998cf..f5c04bc7fa 100644
--- a/server/services/creativeDirector/agentBridge.js
+++ b/server/services/creativeDirector/agentBridge.js
@@ -24,11 +24,20 @@ import { recordRun } from './local.js';
import { DELIVERABLE_KINDS, deliverableMark } from './deliverableGate.js';
// Treatment and production planning are CoS tasks, so unlike scene evaluation
-// they need a CLI/TUI provider with an agent harness. Resolution prefers the
-// project's own `modelOverrides.<kind>` pin (per-project CD provider/model
-// pins) and falls back to the global `settings.creativeDirector.<kind>` AI
-// Assignment — only adding a pin when one is set, preserving the system-default
-// behavior for existing installations.
+// they need a CLI/TUI provider with an agent harness. Resolution order:
+//
+// 1. The OWNING CREATIVE COMMISSION's current pin, read live. A commission is a
+// standing job definition and its project is one execution of it, so an edit
+// to the commission has to reach the executions still running. Snapshotting
+// the pin onto the project at fire time (what this used to do) froze it: the
+// user could switch the commission to a different provider and watch the
+// wedged project keep handing its planner task to the old one forever.
+// 2. The project's own `modelOverrides.<kind>` pin, then the global
+// `settings.creativeDirector.<kind>` AI Assignment — `resolveStagePin`.
+//
+// Only adds a pin when one is set, preserving the system-default behavior for
+// existing installations. A commission lookup failure falls through to (2)
+// rather than stalling the dispatch.
async function getStageAssignment(kind, project) {
// Scene evaluation is a direct vision API call (apiProviderTypes) resolved
// separately, NOT a CoS agent pin — injecting its api-type provider into the
@@ -37,8 +46,17 @@ async function getStageAssignment(kind, project) {
// `creativeDirector.evaluate` settings key; the eval pin lives under
// `creativeDirector.evaluation`.)
if (kind === 'evaluate') return {};
- const settings = await getSettings().catch(() => ({}));
- const assignment = resolveStagePin(kind, project, settings);
+ const [settings, commissionPin] = await Promise.all([
+ getSettings().catch(() => ({})),
+ // Lazy + only for a commission-owned project, so the CD graph doesn't take a
+ // static dependency on the commission store for the common bare project.
+ project?.commissionId
+ ? import('../creativeCommissions/projectControl.js')
+ .then(({ commissionStagePin }) => commissionStagePin(project.commissionId))
+ .catch(() => null)
+ : null,
+ ]);
+ const assignment = commissionPin || resolveStagePin(kind, project, settings);
if (!assignment.providerId && !assignment.model) return {};
return {
...(assignment.providerId ? { provider: assignment.providerId, providerId: assignment.providerId } : {}),
diff --git a/server/services/creativeDirector/agentBridge.test.js b/server/services/creativeDirector/agentBridge.test.js
index 91d3b37d80..ed06601c3c 100644
--- a/server/services/creativeDirector/agentBridge.test.js
+++ b/server/services/creativeDirector/agentBridge.test.js
@@ -10,6 +10,7 @@ const mocks = vi.hoisted(() => ({
getToolSpecs: vi.fn(),
getSettings: vi.fn(),
recordRun: vi.fn(),
+ commissionStagePin: vi.fn(),
}));
vi.mock('../cos.js', () => ({
@@ -25,6 +26,7 @@ vi.mock('../../lib/creativeDirectorPrompts.js', () => ({
vi.mock('../creative/toolRegistry.js', () => ({ getToolSpecs: mocks.getToolSpecs }));
vi.mock('../settings.js', () => ({ getSettings: mocks.getSettings }));
vi.mock('./local.js', () => ({ recordRun: mocks.recordRun }));
+vi.mock('../creativeCommissions/projectControl.js', () => ({ commissionStagePin: mocks.commissionStagePin }));
const { enqueueTreatmentTask, enqueuePlanTask, enqueueEvaluateTask } = await import('./agentBridge.js');
@@ -38,6 +40,54 @@ beforeEach(() => {
mocks.recordRun.mockResolvedValue();
mocks.addTask.mockResolvedValue();
mocks.getSettings.mockResolvedValue({});
+ mocks.commissionStagePin.mockResolvedValue(null);
+});
+
+describe('Creative Director agent bridge — commission-owned projects', () => {
+ const commissioned = { ...project, commissionId: 'commission-1', modelOverrides: {
+ // The stale snapshot a pre-change fire froze onto the project. The commission
+ // is the standing job definition, so its CURRENT pin must win over it —
+ // otherwise switching the commission's provider leaves a wedged project
+ // handing its planner task to the old one forever.
+ plan: { providerId: 'claude-ollama-tui', model: 'qwen3.6:35b' },
+ treatment: { providerId: 'claude-ollama-tui', model: 'qwen3.6:35b' },
+ } };
+
+ it("resolves the owning commission's pin LIVE, overriding the snapshot on the project", async () => {
+ mocks.commissionStagePin.mockResolvedValue({ providerId: 'lmstudio-tui', model: 'qwen3.6:35b' });
+
+ await enqueuePlanTask(commissioned);
+
+ expect(mocks.commissionStagePin).toHaveBeenCalledWith('commission-1');
+ const [task] = mocks.addTask.mock.calls[0];
+ expect(task.metadata).toMatchObject({
+ provider: 'lmstudio-tui', providerId: 'lmstudio-tui', model: 'qwen3.6:35b',
+ });
+ });
+
+ it('falls back to the project/global assignment when the commission pins nothing', async () => {
+ mocks.commissionStagePin.mockResolvedValue(null);
+ mocks.getSettings.mockResolvedValue({ creativeDirector: { plan: { providerId: 'global-agent' } } });
+
+ await enqueuePlanTask({ ...commissioned, modelOverrides: {} });
+
+ const [task] = mocks.addTask.mock.calls[0];
+ expect(task.metadata).toMatchObject({ providerId: 'global-agent' });
+ });
+
+ it('never looks up a commission for a bare project', async () => {
+ await enqueuePlanTask(project);
+ expect(mocks.commissionStagePin).not.toHaveBeenCalled();
+ });
+
+ it('does not stall the dispatch when the commission lookup fails', async () => {
+ mocks.commissionStagePin.mockRejectedValue(new Error('store down'));
+
+ await enqueuePlanTask(commissioned);
+
+ const [task] = mocks.addTask.mock.calls[0];
+ expect(task.metadata).toMatchObject({ providerId: 'claude-ollama-tui' });
+ });
});
describe('Creative Director agent bridge model assignments', () => {
diff --git a/server/services/creativeDirector/bridgeFromIssue.js b/server/services/creativeDirector/bridgeFromIssue.js
index 8caef82e1c..6743a9591c 100644
--- a/server/services/creativeDirector/bridgeFromIssue.js
+++ b/server/services/creativeDirector/bridgeFromIssue.js
@@ -137,6 +137,12 @@ export async function produceVideoFromIssue(issueId, options = {}) {
// pin at the project boundary. Absent ⇒ null, i.e. today's behavior for the
// manual writers-room / pipeline send paths.
renderBackend: options.renderBackend || null,
+ // Same boundary problem as the render pin above, for the OTHER half: the
+ // teaser is a separate project, so without the owning commission's id it is
+ // invisible to that commission's stop and its live provider resolution — a
+ // paused or deleted commission would leave this project running. Absent ⇒
+ // null, i.e. today's behavior for the manual writers-room / pipeline paths.
+ commissionId: options.commissionId || null,
});
let started;
diff --git a/server/services/creativeDirector/completionHook.js b/server/services/creativeDirector/completionHook.js
index 9fe7b9af49..2e9d88f963 100644
--- a/server/services/creativeDirector/completionHook.js
+++ b/server/services/creativeDirector/completionHook.js
@@ -33,6 +33,7 @@ import { runStitch } from './stitchRunner.js';
import { sampleEvaluationFrames } from '../videoGen/local.js';
import { listJobs, mediaJobEvents } from '../mediaJobQueue/index.js';
import { PATHS } from '../../lib/fileUtils.js';
+import { PROJECT_TERMINAL_STATUSES, RUN_TERMINAL_STATUSES } from '../../lib/creativeDirectorPresets.js';
import {
DELIVERABLE_KINDS,
blockedStageReason,
@@ -61,6 +62,17 @@ export async function handleCreativeDirectorCompletion(task, agentId, success) {
// the guard reaps it LIVE instead of waiting for boot recovery.
const runId = meta.runId;
const priorRun = runId ? (project.runs || []).find((r) => r.runId === runId) : null;
+
+ // A run row that is ALREADY terminal was settled by somebody else — boot
+ // recovery, or a deliberate stop/restart (see creativeDirector/stopProject.js,
+ // which settles the row and then SIGKILLs the agent, in that order). This
+ // completion is the echo of a kill we asked for; re-settling it would overwrite
+ // the stop's explanatory reason with a generic one.
+ if (priorRun && RUN_TERMINAL_STATUSES.has(priorRun.status)) {
+ console.log(`↩️ CD completion for ${meta.kind} run ${runId} on ${project.id} ignored — run already settled (${priorRun.status})`);
+ return;
+ }
+
const deliverableKind = DELIVERABLE_KINDS.has(meta.kind) ? meta.kind : null;
const missedDeliverable = Boolean(success && deliverableKind
&& !deliverableLanded(project, deliverableKind, priorRun?.deliverableMark));
@@ -104,6 +116,17 @@ export async function handleCreativeDirectorCompletion(task, agentId, success) {
}
if (!success) {
+ // Record the run, but never OVERWRITE a status the user (or a stop) already
+ // chose. A failed agent exit is not always the project's verdict: the exit
+ // may be the echo of a deliberate kill — the CoS Kill button, the idle/
+ // max-runtime reapers, `stopProject` — fired at a project that is already
+ // `paused` (the user pressed Pause, or a commission stopped it) or already
+ // terminal. Flipping those to `failed` clobbers the explanatory reason the
+ // user is looking at and makes a paused project un-Resumable.
+ if (PROJECT_TERMINAL_STATUSES.has(project.status) || project.status === 'paused') {
+ console.log(`↩️ CD ${meta.kind} agent failure on ${project.id} recorded on the run only — project is already ${project.status}`);
+ return;
+ }
// Surface a concrete reason on the project so the UI's failure banner
// has actionable context. Without this, a project flips to 'failed'
// with whatever stale failureReason it had before (often null), and
diff --git a/server/services/creativeDirector/completionHook.test.js b/server/services/creativeDirector/completionHook.test.js
index 949f19f41c..9888af16e5 100644
--- a/server/services/creativeDirector/completionHook.test.js
+++ b/server/services/creativeDirector/completionHook.test.js
@@ -78,6 +78,45 @@ describe('handleCreativeDirectorCompletion — plan deliverable', () => {
expect(mockAdvancePlan).toHaveBeenCalledWith('cd-1');
});
+ it.each([['failed'], ['completed']])('ignores a completion whose run row is already %s', async (status) => {
+ // The echo of a deliberate kill: stopProject/retireRuns settles the row and
+ // THEN SIGKILLs the agent. Without the guard the `!success` branch below would
+ // flip the whole project to `failed`, clobbering the stop's `paused` + reason
+ // (or killing a project being restarted under a new provider).
+ mockGetProject.mockResolvedValue(planProject({
+ runs: [{ runId: 'run-1', kind: 'plan', status, failureReason: 'Creative commission paused' }],
+ }));
+ await handleCreativeDirectorCompletion(planTask(), 'agent-1', false);
+ expect(mockUpdateRun).not.toHaveBeenCalled();
+ expect(mockRecordRun).not.toHaveBeenCalled();
+ expect(mockUpdateProject).not.toHaveBeenCalled();
+ expect(mockAdvancePlan).not.toHaveBeenCalled();
+ });
+
+ it.each([['failed'], ['completed']])('ignores a completion whose run row is already %s', async (status) => {
+ // The echo of a deliberate kill: stopProject/retireRuns settles the row and
+ // THEN SIGKILLs the agent. Re-settling would overwrite the stop's reason.
+ mockGetProject.mockResolvedValue(planProject({
+ runs: [{ runId: 'run-1', kind: 'plan', status, failureReason: 'Creative commission paused' }],
+ }));
+ await handleCreativeDirectorCompletion(planTask(), 'agent-1', false);
+ expect(mockUpdateRun).not.toHaveBeenCalled();
+ expect(mockRecordRun).not.toHaveBeenCalled();
+ expect(mockUpdateProject).not.toHaveBeenCalled();
+ expect(mockAdvancePlan).not.toHaveBeenCalled();
+ });
+
+ it.each([['paused'], ['complete'], ['failed']])('records the run but never re-stamps a project that is already %s', async (status) => {
+ // A failed agent exit is not the project's verdict when the project already
+ // has one: the exit may be the echo of any deliberate kill (the CoS Kill
+ // button, the idle/max-runtime reapers, a stop). Flipping a paused project to
+ // `failed` here would clobber its reason and make it un-Resumable.
+ mockGetProject.mockResolvedValue(planProject({ status }));
+ await handleCreativeDirectorCompletion(planTask(), 'agent-1', false);
+ expect(mockUpdateRun).toHaveBeenCalledWith('cd-1', 'run-1', expect.objectContaining({ status: 'failed' }));
+ expect(mockUpdateProject).not.toHaveBeenCalled();
+ });
+
it('marks a plan run COMPLETED when the plan did land', async () => {
mockGetProject.mockResolvedValue(planProject({ plan: { steps: [{ stepId: 'a' }], replanRounds: 0 } }));
await handleCreativeDirectorCompletion(planTask(), 'agent-1', true);
diff --git a/server/services/creativeDirector/local.js b/server/services/creativeDirector/local.js
index dca7042799..73fcc9b081 100644
--- a/server/services/creativeDirector/local.js
+++ b/server/services/creativeDirector/local.js
@@ -80,6 +80,11 @@ export async function getProjectsByIds(ids, options = {}) {
return (await selectBackend()).getProjectsByIds(ids, options);
}
+/** Every LIVE project a Creative Commission spawned — see the backends. */
+export async function listProjectsByCommissionId(commissionId) {
+ return (await selectBackend()).listProjectsByCommissionId(commissionId);
+}
+
/** Live project ids (or all when includeDeleted) — used by tombstone GC sweeps. */
export async function listProjectIds(options = {}) {
return (await selectBackend()).listProjectIds(options);
diff --git a/server/services/creativeDirector/projectsDB.js b/server/services/creativeDirector/projectsDB.js
index 35f0fff4dc..1ea65288fd 100644
--- a/server/services/creativeDirector/projectsDB.js
+++ b/server/services/creativeDirector/projectsDB.js
@@ -128,6 +128,22 @@ export async function getProjectsByIds(ids, { includeDeleted = false } = {}) {
return result.rows.map(rowToProject);
}
+/**
+ * Every LIVE project a given Creative Commission spawned, oldest first. The
+ * commission↔project link the stop/re-pin paths run on: the commission's own run
+ * ledger is capped (MAX_PERSISTED_RUNS) and never sees a project a plan step
+ * spawned indirectly, so a wedged project can fall out of it entirely.
+ */
+export async function listProjectsByCommissionId(commissionId) {
+ if (!commissionId) return [];
+ const result = await query(
+ `SELECT id, data FROM creative_director_projects
+ WHERE deleted = FALSE AND data->>'commissionId' = $1 ORDER BY created_at ASC`,
+ [commissionId],
+ );
+ return result.rows.map(rowToProject);
+}
+
/** Live project ids (or all when includeDeleted) — used by tombstone GC sweeps. */
export async function listProjectIds({ includeDeleted = false } = {}) {
const result = includeDeleted
diff --git a/server/services/creativeDirector/projectsFile.js b/server/services/creativeDirector/projectsFile.js
index 9813db7942..eec4a2fde4 100644
--- a/server/services/creativeDirector/projectsFile.js
+++ b/server/services/creativeDirector/projectsFile.js
@@ -75,6 +75,13 @@ export async function getProjectsByIds(ids, { includeDeleted = false } = {}) {
return all.filter((p) => wanted.has(p.id) && (includeDeleted || !p.deleted));
}
+/** Every LIVE project a given Creative Commission spawned — mirrors the PG backend. */
+export async function listProjectsByCommissionId(commissionId) {
+ if (!commissionId) return [];
+ const all = await loadAll();
+ return all.filter((p) => !p.deleted && p.commissionId === commissionId);
+}
+
/** Live project ids (or all when includeDeleted) — used by tombstone GC sweeps. */
export async function listProjectIds({ includeDeleted = false } = {}) {
const all = await loadAll();
diff --git a/server/services/creativeDirector/projectsLogic.js b/server/services/creativeDirector/projectsLogic.js
index c173b2e0ba..3a2a21a8df 100644
--- a/server/services/creativeDirector/projectsLogic.js
+++ b/server/services/creativeDirector/projectsLogic.js
@@ -151,7 +151,7 @@ export function buildProjectRecord(input, { id, now, collectionId }) {
const {
name, aspectRatio, quality, modelId, targetDurationSeconds,
styleSpec = '', startingImageFile = null, userStory = null,
- disableAudio = true, autoAcceptScenes = false, sourceIssueId = null,
+ disableAudio = true, autoAcceptScenes = false, sourceIssueId = null, commissionId = null,
cast = [], generateFirstPass = false, directive = null,
modelOverrides = {}, renderBackend = null,
} = input;
@@ -187,6 +187,16 @@ export function buildProjectRecord(input, { id, now, collectionId }) {
// The stitch step uses it to look up `stages.audio.music` and mix it into
// the final cut. Bare CD projects leave this null and skip the audio-mux.
sourceIssueId,
+ // Optional back-pointer to the Creative Commission whose fire minted this
+ // project. Load-bearing, not decorative: it is how a commission finds the
+ // work it spawned in order to STOP it (pause/delete) and how agentBridge
+ // resolves the commission's CURRENT provider pin at dispatch instead of a
+ // 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.
+ // Additive: the whole record round-trips through the JSONB column verbatim
+ // (sanitizeProjectForSync / mergeProjectRecord), so no schema-version bump.
+ commissionId,
collectionId,
timelineProjectId: null,
finalVideoId: null,
diff --git a/server/services/creativeDirector/recovery.js b/server/services/creativeDirector/recovery.js
index edeb0b97f6..0cdbeea321 100644
--- a/server/services/creativeDirector/recovery.js
+++ b/server/services/creativeDirector/recovery.js
@@ -25,14 +25,14 @@
* fresh evaluate task, runs the stitch, etc.
*/
-import { listProjects, updateScene, updatePlanStep, updateRun, updateProject } from './local.js';
+import { listProjects, updateScene, updatePlanStep, updateProject } from './local.js';
import { listJobs, cancelJob } from '../mediaJobQueue/index.js';
-import { updateTask } from '../cos.js';
+import { inflightRuns, ownedLiveJobs, retireRuns } from './stopProject.js';
// Boot-time coordination: cos.start() (entered from cos.init() when
// alwaysOn/autoStart is configured) calls resetOrphanedTasks(), which
// would respawn stale CD treatment/evaluate tasks BEFORE
-// recoverInFlightProjects() has had a chance to retire them via updateTask.
+// recoverInFlightProjects() has had a chance to retire them via retireRuns.
// Two concurrent agents would then race on the same project. Expose a
// promise that cos.start() awaits before its resetOrphanedTasks call,
// so the order is always:
@@ -111,42 +111,21 @@ export async function recoverInFlightProjects() {
if (resetCount) {
console.log(`🔄 CD recovery: ${project.id} reset ${resetCount} stuck scene(s) to pending`);
}
- // Reap stale `running` agent-run rows AND retire the underlying CoS
- // task. The agent task behind each run died with the previous process,
- // but cos.js#resetOrphanedTasks would otherwise see `in_progress` task
- // rows on boot and respawn them — racing the fresh treatment/evaluate
- // task this recovery path will cause to enqueue. Mark the task failed
- // first so the orphan-task reset finds nothing to retry.
- //
- // taskType MUST be 'internal' here — CD treatment/evaluate tasks are
- // added by agentBridge#persistAndEmit via `addTask(record, 'internal',
- // …)`. Passing 'cos' would write to the wrong file AND, per
- // cos.js#updateTask, strip approval flags from internal task entries
- // (only 'internal' preserves them), silently auto-approving unrelated
- // internal tasks across a CD recovery cycle.
- //
- // status MUST be one of generateTasksMarkdown's supported terminal
- // values (pending/in_progress/blocked/completed) — writing 'failed'
- // would make the parser drop the task from COS-TASKS.md entirely on
- // the next write. Use 'completed' with a metadata audit note so the
- // task is properly retired (preventing orphan re-spawn) without
- // being silently deleted.
- const staleRuns = (project.runs || []).filter((r) => r.status === 'running');
- for (const run of staleRuns) {
- if (run.taskId) {
- await updateTask(run.taskId, {
- status: 'completed',
- metadata: { interruptedByRestart: 'true', recoveredAt: completedAt },
- }, 'internal')
- .catch((e) => console.log(`⚠️ CD recovery: retire internal task ${run.taskId} for ${project.id} failed: ${e.message}`));
- }
- await updateRun(project.id, run.runId, {
- status: 'failed',
- completedAt,
- failureReason: 'interrupted by restart',
- }).catch((e) => console.log(`⚠️ CD recovery: reap run ${run.runId} of ${project.id} failed: ${e.message}`));
- }
+ // Reap stale `running` agent-run rows AND retire the underlying CoS task.
+ // The agent task behind each run died with the previous process, but
+ // cos.js#resetOrphanedTasks would otherwise see `in_progress` task rows on
+ // boot and respawn them — racing the fresh treatment/evaluate task this
+ // recovery path will cause to enqueue. `retireRuns` owns that contract (the
+ // `'internal'` taskType and the supported terminal status are load-bearing —
+ // its comments carry the why); we only supply the audit stamp. Nothing can be
+ // alive to kill here: this runs at boot, in a process that just started.
+ const staleRuns = inflightRuns(project).filter((r) => r.status === 'running');
if (staleRuns.length) {
+ await retireRuns(project.id, {
+ runs: staleRuns,
+ reason: 'interrupted by restart',
+ taskMetadata: { interruptedByRestart: 'true', recoveredAt: completedAt },
+ });
console.log(`🔄 CD recovery: ${project.id} reaped ${staleRuns.length} stale running run(s)`);
}
// Cancel any media-queue jobs owned by this project that
@@ -179,10 +158,7 @@ export async function recoverInFlightProjects() {
// a Phase-2 plan render step tags media jobs `creative-director:<id>` (the
// registry's resolveOwner). Both must be canceled so the reset step's fresh
// dispatch doesn't race a doomed sibling for the same output.
- const orphaned = listJobs()
- .filter((j) => typeof j.owner === 'string'
- && (j.owner.startsWith(`cd:${project.id}:`) || j.owner === `creative-director:${project.id}`))
- .filter((j) => j.status === 'queued' || j.status === 'running')
+ const orphaned = ownedLiveJobs(listJobs(), project.id)
.filter((j) => {
const qa = new Date(j.queuedAt || 0).getTime();
return qa > 0 && qa < recoveryStartedAt;
diff --git a/server/services/creativeDirector/stopProject.js b/server/services/creativeDirector/stopProject.js
new file mode 100644
index 0000000000..0657c4a4ec
--- /dev/null
+++ b/server/services/creativeDirector/stopProject.js
@@ -0,0 +1,177 @@
+/**
+ * Creative Director — hard stop for an in-flight project.
+ *
+ * Pausing a project (`POST /:id/pause`) only flips `status`; it deliberately
+ * leaves the in-flight render running and never touches the CoS agent tasks the
+ * cognitive stages spawned. That is the right gesture for "let this finish, just
+ * don't queue more" — but it is NOT enough when the caller wants the project to
+ * STOP: an agent task already handed to the runner keeps burning the provider,
+ * and a `running` run row left behind is respawned by the orphan sweeps —
+ * `resetOrphanedTasks` on boot AND on the 15-minute health-check interval — so
+ * the same stage is handed to the same model again and again.
+ *
+ * `stopProject` is the full stop. In order (the order matters):
+ *
+ * 1. Park the project as `paused` FIRST, so any completion / media-job event
+ * that lands mid-stop finds a paused project and returns early instead of
+ * dispatching the next step behind us.
+ * 2. Mark the in-flight run rows `failed`, so the re-dispatch guards in
+ * planAdvance / completionHook don't treat a dead run as "a worker is on it"
+ * — and so the completion the next step provokes reads as stale.
+ * 3. Kill any live agent process attached to those runs.
+ * 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
+ * isn't left holding the GPU.
+ *
+ * Steps 2-4 are also exported on their own as `retireRuns`, because a caller that
+ * wants the project to keep going under a DIFFERENT provider needs exactly that
+ * teardown and none of the parking (see creativeCommissions/projectControl.js).
+ *
+ * Runs OUTSIDE the Express request lifecycle (callers include the commission
+ * store's change bus) — every step is individually caught and no path throws out.
+ */
+
+import { getProject, updateProject, updateRun } from './local.js';
+import { PROJECT_TERMINAL_STATUSES, RUN_TERMINAL_STATUSES } from '../../lib/creativeDirectorPresets.js';
+
+const nowISO = () => new Date().toISOString();
+
+// Every teardown step is best-effort: this runs outside the request lifecycle, so
+// one failed kill must not abort the rest of the stop. These two collapse the
+// shape that would otherwise be written out once per step.
+
+/** Import a module, or an empty object when it can't load. Callers feature-detect. */
+const loadOrEmpty = (loader, what, projectId) => loader()
+ .catch((e) => { console.error(`❌ CD teardown ${projectId}: ${what} module load failed: ${e.message}`); return {}; });
+
+/** Await one teardown call; return 1 on success, 0 (logged) on failure. */
+const tally = (promise, what, projectId) => promise
+ .then(() => 1)
+ .catch((e) => { console.log(`⚠️ CD teardown ${projectId}: ${what} failed: ${e.message}`); return 0; });
+
+/**
+ * In-flight (non-terminal) run rows on a project, optionally narrowed to a set of
+ * run kinds ('treatment' | 'plan' | 'evaluate' | 'plan-step'). Pure.
+ */
+export function inflightRuns(project, kinds = null) {
+ return (project?.runs || []).filter((r) => r
+ && !RUN_TERMINAL_STATUSES.has(r.status)
+ && (!kinds || kinds.includes(r.kind)));
+}
+
+/**
+ * Media jobs this project owns that are still live. Pure over the passed-in list.
+ * Matches BOTH owner conventions, exactly like recovery.js: the scene loop tags
+ * renders `cd:<projectId>:<sceneId>`, a Phase-2 plan render step tags them
+ * `creative-director:<projectId>`.
+ */
+export function ownedLiveJobs(jobs, projectId) {
+ return (jobs || []).filter((j) => typeof j?.owner === 'string'
+ && (j.owner.startsWith(`cd:${projectId}:`) || j.owner === `creative-director:${projectId}`)
+ && (j.status === 'queued' || j.status === 'running'));
+}
+
+/**
+ * Tear down the agent side of a set of in-flight runs: kill the live agent
+ * process, retire the underlying internal CoS task, settle the run row. Does NOT
+ * touch the project's status and does NOT cancel media jobs.
+ *
+ * Retiring the TASK — not just the run row — is the load-bearing part. A task
+ * already handed to the runner carries the provider/model resolved at dispatch
+ * frozen into its metadata, and the orphan sweep respawns it verbatim; so a
+ * caller that re-pins the project must retire the task too, or the sweep keeps
+ * re-launching the stale provider every 15 minutes.
+ *
+ * @param {string} projectId
+ * @param {{runs?: Array<object>, reason?: string, taskMetadata?: object}} options —
+ * `runs` is the exact set of in-flight run rows to retire (callers narrow it by
+ * kind); `taskMetadata` is the audit stamp merged onto each retired task, so a
+ * caller can record WHY without changing the retirement contract.
+ */
+export async function retireRuns(projectId, { runs = [], reason = 'Stopped', taskMetadata = { retiredByPortos: 'true' } } = {}) {
+ const taskIds = new Set(runs.map((r) => r.taskId).filter(Boolean));
+ let agents = 0;
+ let tasks = 0;
+
+ // Settle the run rows BEFORE killing anything. The kill fires the agent
+ // completion path, and completionHook's `!success` branch would flip the whole
+ // project to `failed` — clobbering the stop's `paused`, or killing a project we
+ // are restarting under a new provider. A terminal row is completionHook's
+ // stale-completion guard, so settling first makes the echo a no-op. (A lingering
+ // `running` row is also what every re-dispatch guard reads as "another worker
+ // owns this stage", and what boot recovery revives.)
+ const completedAt = nowISO();
+ for (const run of runs) {
+ await tally(
+ updateRun(projectId, run.runId, { status: 'failed', completedAt, failureReason: reason }),
+ `settle run ${run.runId}`, projectId,
+ );
+ }
+
+ if (!taskIds.size) return { runs: runs.length, tasks: 0, agents: 0 };
+
+ // An agent that already exited is simply absent from the active list
+ // (killAgent 404s), which is not an error for us.
+ const { getActiveAgents, killAgent } = await loadOrEmpty(() => import('../agentManagement.js'), 'agent', projectId);
+ if (getActiveAgents && killAgent) {
+ for (const agent of getActiveAgents().filter((a) => taskIds.has(a.taskId))) {
+ agents += await tally(killAgent(agent.id), `kill agent ${agent.id}`, projectId);
+ }
+ }
+
+ // taskType MUST be 'internal' and status MUST be a value generateTasksMarkdown
+ // supports — see the long-form rationale in recovery.js#recoverInFlightProjects,
+ // which retires the same task rows.
+ const { updateTask } = await loadOrEmpty(() => import('../cos.js'), 'cos', projectId);
+ if (updateTask) {
+ for (const taskId of taskIds) {
+ tasks += await tally(updateTask(taskId, {
+ status: 'completed',
+ metadata: { ...taskMetadata, retiredReason: reason, retiredAt: nowISO() },
+ }, 'internal'), `retire task ${taskId}`, projectId);
+ }
+ }
+
+ return { runs: runs.length, tasks, agents };
+}
+
+/**
+ * Stop a Creative Director project and everything it has in flight.
+ *
+ * @param {string} projectId
+ * @param {{reason?: string}} options — `reason` is stamped on the project's
+ * `failureReason` and on each retired run, so the CD detail page explains why
+ * the project stopped rather than showing a bare pause.
+ * @returns {Promise<{projectId: string, stopped: boolean, skipped?: string,
+ * runs: number, tasks: number, agents: number, jobs: number}>}
+ */
+export async function stopProject(projectId, { reason = 'Stopped', project: preread } = {}) {
+ // `project` lets a caller that already listed its projects skip the re-read —
+ // a fan-out over one commission's projects would otherwise cost a single-row
+ // query per project just to rediscover what it already holds.
+ const project = preread || await getProject(projectId).catch(() => null);
+ if (!project) return { projectId, stopped: false, skipped: 'missing', runs: 0, tasks: 0, agents: 0, jobs: 0 };
+ if (PROJECT_TERMINAL_STATUSES.has(project.status)) {
+ return { projectId, stopped: false, skipped: 'terminal', runs: 0, tasks: 0, agents: 0, jobs: 0 };
+ }
+
+ // 1. Park first — a settle event racing us must find `paused` and bail.
+ await updateProject(projectId, { status: 'paused', failureReason: reason })
+ .catch((e) => console.error(`❌ CD stop ${projectId}: park failed: ${e.message}`));
+
+ const retired = await retireRuns(projectId, { runs: inflightRuns(project), reason });
+
+ // 5. 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) {
+ for (const job of ownedLiveJobs(queue.listJobs(), projectId)) {
+ jobs += await tally(queue.cancelJob(job.id), `cancel job ${job.id}`, projectId);
+ }
+ }
+
+ console.log(`🛑 CD project ${projectId} stopped: ${reason} (${retired.runs} run(s), ${retired.tasks} task(s), ${retired.agents} agent(s), ${jobs} job(s))`);
+ return { projectId, stopped: true, ...retired, jobs };
+}
diff --git a/server/services/creativeDirector/stopProject.test.js b/server/services/creativeDirector/stopProject.test.js
new file mode 100644
index 0000000000..8f49efa2a4
--- /dev/null
+++ b/server/services/creativeDirector/stopProject.test.js
@@ -0,0 +1,199 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+const getProjectMock = vi.fn();
+const updateProjectMock = vi.fn(async () => ({}));
+const updateRunMock = vi.fn(async () => ({}));
+vi.mock('./local.js', () => ({
+ getProject: (...a) => getProjectMock(...a),
+ updateProject: (...a) => updateProjectMock(...a),
+ updateRun: (...a) => updateRunMock(...a),
+}));
+
+const getActiveAgentsMock = vi.fn(() => []);
+const killAgentMock = vi.fn(async () => ({ success: true }));
+vi.mock('../agentManagement.js', () => ({
+ getActiveAgents: (...a) => getActiveAgentsMock(...a),
+ killAgent: (...a) => killAgentMock(...a),
+}));
+
+const updateTaskMock = vi.fn(async () => ({}));
+vi.mock('../cos.js', () => ({ updateTask: (...a) => updateTaskMock(...a) }));
+
+const listJobsMock = vi.fn(() => []);
+const cancelJobMock = vi.fn(async () => ({}));
+vi.mock('../mediaJobQueue/index.js', () => ({
+ listJobs: (...a) => listJobsMock(...a),
+ cancelJob: (...a) => cancelJobMock(...a),
+}));
+
+const { stopProject, retireRuns, inflightRuns, ownedLiveJobs } = await import('./stopProject.js');
+
+const project = (over = {}) => ({ id: 'cd-1', status: 'planning', runs: [], ...over });
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ getActiveAgentsMock.mockReturnValue([]);
+ listJobsMock.mockReturnValue([]);
+});
+
+describe('inflightRuns', () => {
+ it('keeps only non-terminal run rows', () => {
+ const runs = [
+ { runId: 'a', status: 'completed' },
+ { runId: 'b', status: 'failed' },
+ { runId: 'c', status: 'running' },
+ { runId: 'd' },
+ ];
+ expect(inflightRuns({ runs }).map((r) => r.runId)).toEqual(['c', 'd']);
+ });
+
+ it('tolerates a project with no runs', () => {
+ expect(inflightRuns(null)).toEqual([]);
+ expect(inflightRuns({})).toEqual([]);
+ });
+
+ it('narrows to the requested kinds — an LLM-stage caller must not sweep up a render step', () => {
+ const runs = [
+ { runId: 'a', kind: 'plan', status: 'running' },
+ { runId: 'b', kind: 'plan-step', status: 'running' },
+ { runId: 'c', kind: 'treatment', status: 'running' },
+ { runId: 'd', kind: 'plan', status: 'completed' },
+ ];
+ expect(inflightRuns({ runs }, ['treatment', 'plan']).map((r) => r.runId)).toEqual(['a', 'c']);
+ });
+});
+
+describe('retireRuns', () => {
+ it('kills the agent, retires the internal task, and settles the run — without touching the project or its jobs', async () => {
+ getActiveAgentsMock.mockReturnValue([{ id: 'agent-live', taskId: 't1' }]);
+
+ const result = await retireRuns('cd-1', {
+ runs: [{ runId: 'r1', taskId: 't1', status: 'running' }],
+ reason: 'Commission provider changed to lmstudio-tui',
+ });
+
+ expect(killAgentMock).toHaveBeenCalledExactlyOnceWith('agent-live');
+ expect(updateTaskMock).toHaveBeenCalledExactlyOnceWith(
+ 't1',
+ expect.objectContaining({ status: 'completed' }),
+ 'internal',
+ );
+ expect(updateRunMock).toHaveBeenCalledExactlyOnceWith('cd-1', 'r1', expect.objectContaining({
+ status: 'failed', failureReason: 'Commission provider changed to lmstudio-tui',
+ }));
+ // The restart path re-advances the project itself — retireRuns must not park it.
+ expect(updateProjectMock).not.toHaveBeenCalled();
+ expect(cancelJobMock).not.toHaveBeenCalled();
+ expect(result).toEqual({ runs: 1, tasks: 1, agents: 1 });
+ });
+
+ it('is a no-op with nothing to retire', async () => {
+ const result = await retireRuns('cd-1', { runs: [] });
+ expect(getActiveAgentsMock).not.toHaveBeenCalled();
+ expect(updateRunMock).not.toHaveBeenCalled();
+ expect(result).toEqual({ runs: 0, tasks: 0, agents: 0 });
+ });
+});
+
+describe('ownedLiveJobs', () => {
+ it('matches both owner conventions and only live jobs', () => {
+ const jobs = [
+ { id: 'j1', owner: 'cd-1', status: 'queued' }, // not an owner form
+ { id: 'j2', owner: 'cd:cd-1:scene-1', status: 'queued' },
+ { id: 'j3', owner: 'creative-director:cd-1', status: 'running' },
+ { id: 'j4', owner: 'cd:cd-1:scene-2', status: 'completed' }, // terminal
+ { id: 'j5', owner: 'cd:cd-2:scene-1', status: 'queued' }, // other project
+ { id: 'j6', status: 'queued' }, // ownerless
+ ];
+ expect(ownedLiveJobs(jobs, 'cd-1').map((j) => j.id)).toEqual(['j2', 'j3']);
+ });
+});
+
+describe('stopProject', () => {
+ it('is a no-op for a missing project', async () => {
+ getProjectMock.mockResolvedValue(null);
+ const result = await stopProject('cd-gone');
+ expect(result).toMatchObject({ stopped: false, skipped: 'missing' });
+ expect(updateProjectMock).not.toHaveBeenCalled();
+ });
+
+ it('never rewrites a terminal project', async () => {
+ getProjectMock.mockResolvedValue(project({ status: 'complete' }));
+ const result = await stopProject('cd-1');
+ expect(result).toMatchObject({ stopped: false, skipped: 'terminal' });
+ expect(updateProjectMock).not.toHaveBeenCalled();
+ });
+
+ it('parks the project, then settles the run, then kills — so neither the settle nor the kill echo can un-park it', async () => {
+ const order = [];
+ updateProjectMock.mockImplementation(async () => { order.push('park'); });
+ updateRunMock.mockImplementation(async () => { order.push('settle-run'); });
+ killAgentMock.mockImplementation(async () => { order.push('kill'); return { success: true }; });
+ getProjectMock.mockResolvedValue(project({ runs: [{ runId: 'r1', taskId: 't1', status: 'running' }] }));
+ getActiveAgentsMock.mockReturnValue([{ id: 'agent-live', taskId: 't1' }]);
+
+ await stopProject('cd-1', { reason: 'Commission deleted' });
+
+ // The run must be terminal before the kill: killAgent fires the agent
+ // completion path, whose `!success` branch would otherwise flip the project to
+ // `failed`. completionHook's stale-completion guard keys on that terminal row.
+ expect(order).toEqual(['park', 'settle-run', 'kill']);
+ expect(updateProjectMock).toHaveBeenCalledExactlyOnceWith('cd-1', { status: 'paused', failureReason: 'Commission deleted' });
+ });
+
+ it('kills live agents, retires the internal tasks, settles runs, and cancels media jobs', async () => {
+ getProjectMock.mockResolvedValue(project({
+ runs: [
+ { runId: 'r1', taskId: 'cd-1-plan-a', status: 'running' },
+ { runId: 'r2', taskId: 'cd-1-plan-old', status: 'completed' },
+ ],
+ }));
+ getActiveAgentsMock.mockReturnValue([
+ { id: 'agent-live', taskId: 'cd-1-plan-a' },
+ { id: 'agent-other', taskId: 'unrelated-task' },
+ ]);
+ listJobsMock.mockReturnValue([
+ { id: 'j2', owner: 'cd:cd-1:scene-1', status: 'running' },
+ { id: 'j5', owner: 'cd:cd-2:scene-1', status: 'queued' },
+ ]);
+
+ const result = await stopProject('cd-1', { reason: 'Creative commission paused' });
+
+ expect(killAgentMock).toHaveBeenCalledExactlyOnceWith('agent-live');
+ // 'internal' + a supported terminal status — see recovery.js for why both matter.
+ expect(updateTaskMock).toHaveBeenCalledExactlyOnceWith(
+ 'cd-1-plan-a',
+ expect.objectContaining({ status: 'completed' }),
+ 'internal',
+ );
+ // Only the in-flight run is settled; the already-completed one is untouched.
+ expect(updateRunMock).toHaveBeenCalledExactlyOnceWith('cd-1', 'r1', expect.objectContaining({
+ status: 'failed', failureReason: 'Creative commission paused',
+ }));
+ expect(cancelJobMock).toHaveBeenCalledExactlyOnceWith('j2');
+ expect(result).toMatchObject({ stopped: true, runs: 1, tasks: 1, agents: 1, jobs: 1 });
+ });
+
+ 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' }]);
+ killAgentMock.mockRejectedValue(new Error('agent gone'));
+ updateTaskMock.mockRejectedValue(new Error('task file busy'));
+ listJobsMock.mockReturnValue([{ id: 'j2', owner: 'creative-director:cd-1', status: 'queued' }]);
+
+ const result = await stopProject('cd-1');
+
+ // A failed kill/retire must not abort the rest of the teardown.
+ expect(updateRunMock).toHaveBeenCalled();
+ expect(cancelJobMock).toHaveBeenCalledWith('j2');
+ expect(result).toMatchObject({ stopped: true, agents: 0, tasks: 0, jobs: 1 });
+ });
+
+ it('skips the agent/task teardown entirely when no run carries a taskId', async () => {
+ getProjectMock.mockResolvedValue(project({ runs: [{ runId: 'r1', kind: 'plan-step', status: 'running' }] }));
+ await stopProject('cd-1');
+ expect(getActiveAgentsMock).not.toHaveBeenCalled();
+ expect(updateTaskMock).not.toHaveBeenCalled();
+ expect(updateRunMock).toHaveBeenCalledWith('cd-1', 'r1', expect.objectContaining({ status: 'failed' }));
+ });
+});