Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix six defects the pre-PR review found in the commission-stop change
[._.]/ Adam Eivy7ac2c72e3fd4
diff --git a/client/src/pages/CreativeDirectorDetail.jsx b/client/src/pages/CreativeDirectorDetail.jsxindex cceed6a2ad..fa4e9f9441 100644--- a/client/src/pages/CreativeDirectorDetail.jsx+++ b/client/src/pages/CreativeDirectorDetail.jsx@@ -3,6 +3,8 @@ import { useParams, useNavigate, useSearchParams, Link } from 'react-router';import { ArrowLeft, Play, Pause, RefreshCw, SlidersHorizontal, Square } from 'lucide-react';import PageSkeleton from '../components/ui/PageSkeleton';import toast from '../components/ui/Toast';+import ConfirmButtonPair from '../components/ui/ConfirmButtonPair';+import { useConfirmDelete } from '../hooks/useConfirmDelete';import {getCreativeDirectorProject,startCreativeDirectorProject,@@ -153,6 +155,11 @@ export default function CreativeDirectorDetail() {refetchPoll();}, [id, refetchPoll]);+ // Stop is destructive and irreversible (SIGKILLs a live agent, cancels queued+ // GPU renders) and sits beside Pause, so it takes the same two-step confirm+ // every other destructive action in the app uses.+ const { isConfirming, requestDelete, cancelDelete, confirmDelete } = useConfirmDelete();+const handleAction = async (kind) => {// Map action → past-tense label and optimistic status up-front.const successMessages = {@@ -237,13 +244,25 @@ export default function CreativeDirectorDetail() {</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>+ isConfirming(project.id) ? (+ <ConfirmButtonPair+ prompt="Stop?"+ confirmText="Stop"+ ariaLabel={`Confirm stop project ${project.name}`}+ onConfirm={() => confirmDelete(() => handleAction('stop'))}+ onCancel={cancelDelete}+ />+ ) : (+ <button+ type="button"+ onClick={() => requestDelete(project.id)}+ title="Stop: kill the running agent, retire its queued tasks, and cancel pending renders. Pause only stops NEW work being queued."+ aria-label={`Stop project ${project.name}`}+ 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>diff --git a/client/src/services/apiCreativeDirector.test.js b/client/src/services/apiCreativeDirector.test.jsindex 2cf023bc72..29237876ef 100644--- a/client/src/services/apiCreativeDirector.test.js+++ b/client/src/services/apiCreativeDirector.test.js@@ -1,3 +1,4 @@+// @vitest-environment node/*** Creative Director API wrapper — batch-by-id fetch (#4148).*@@ -76,7 +77,6 @@ describe('getCreativeDirectorProjectsByIds', () => {expect(request.mock.calls[0][1]).toEqual({ silent: true });});});-// @vitest-environment nodedescribe('stopCreativeDirectorProject', () => {it('POSTs the stop route — the hard counterpart to pause', async () => {diff --git a/server/lib/syncWire.js b/server/lib/syncWire.jsindex 16e7f2f704..651feb020f 100644--- a/server/lib/syncWire.js+++ b/server/lib/syncWire.js@@ -207,19 +207,34 @@ export function sanitizeRecordForWire(kind, record) {case 'artist':case 'album':case 'track':- case 'creativeDirectorProject':+ case 'creativeDirectorProject': {+ // Whole-record LWW like the group below, with ONE machine-local field+ // stripped: `commissionId`, the back-pointer to the Creative Commission+ // whose fire minted this project. It must not travel, for the same reason+ // the commission's own `schedule`/`runs`/`assignment` don't (see the+ // creativeCommission case): a commission federates its BRIEF only and lands+ // DORMANT on the receiver, so only the minting machine runs it. If the+ // back-pointer rode the wire, a peer holding a synced copy of both records+ // would resolve the commission's projects to ANOTHER machine's live work —+ // and pausing or deleting the commission there would park a project whose+ // agent, CoS task, and queued renders are running on the other machine,+ // with no local process to actually stop. Stripping keeps the fan-out+ // machine-local by construction. `mergeProjectRecord` re-attaches the+ // receiver's own value so a remote LWW win can't erase it.+ const { deleted: _d, deletedAt: _da, commissionId: _c, ...rest } = record;+ return { ...rest, ...sanitizeSoftDeleteFields(record) };+ }case 'moodBoard':case 'writersRoomFolder':case 'writersRoomExercise':case 'commissionFeedback': {- // Persona/music/creative-director/mood-board records: like mediaCollection,+ // Persona/music/mood-board records: like mediaCollection,// no `ephemeral` flag — always wire-syncable when present. Strip-then-tail-// re-add the soft-delete pair for byte-stable checksums. The whole record// is LWW-overwritten on merge (no item-union), so the wire form converges// byte-for-byte and feeds the conflict-journal content hash directly (no- // scalar narrowing in contentHashForRecord). A creativeDirectorProject is- // larger than a persona (treatment/scenes/runs) but follows the same whole-- // record LWW contract; a moodBoard (name/description/items) is the same.+ // scalar narrowing in contentHashForRecord). A moodBoard+ // (name/description/items) follows the same whole-record LWW contract.// Writers Room folders + exercises (#1645) are also body-less whole-record// LWW kinds with no ephemeral counters — they wire identically (no liveMode// A commissionFeedback (#2686: one reaction — commissionId/runId/rating/diff --git a/server/lib/syncWire.test.js b/server/lib/syncWire.test.jsindex 16732e40b0..1c5ad63cbb 100644--- a/server/lib/syncWire.test.js+++ b/server/lib/syncWire.test.js@@ -45,6 +45,28 @@ describe('syncWire', () => {});});+ describe('creativeDirectorProject — machine-local commissionId', () => {+ it('strips commissionId from the wire so a peer never resolves another machine\'s projects', () => {+ // A commission federates its BRIEF only and lands DORMANT on the receiver;+ // only the minting machine runs it. If the project's back-pointer travelled,+ // pausing/deleting that dormant commission on the peer would park a project+ // whose agent, CoS task and queued renders live on the OTHER machine — with+ // no local process able to stop them.+ const wire = sanitizeRecordForWire('creativeDirectorProject', {+ id: 'cd-1', name: 'P', status: 'planning', commissionId: 'commission-1',+ });+ expect(wire).not.toHaveProperty('commissionId');+ expect(wire).toMatchObject({ id: 'cd-1', name: 'P', status: 'planning' });+ });++ it('still carries the rest of the record', () => {+ const wire = sanitizeRecordForWire('creativeDirectorProject', {+ id: 'cd-1', name: 'P', treatment: { logline: 'l' }, deleted: false,+ });+ expect(wire).toMatchObject({ id: 'cd-1', name: 'P', treatment: { logline: 'l' } });+ });+ });+describe('sanitizeRecordForWire', () => {it('returns null for non-objects', () => {expect(sanitizeRecordForWire('universe', null)).toBeNull();diff --git a/server/routes/creativeDirector.js b/server/routes/creativeDirector.jsindex 24889add34..684f080b29 100644--- a/server/routes/creativeDirector.js+++ b/server/routes/creativeDirector.js@@ -412,7 +412,12 @@ router.post('/:id/resume', asyncHandler(async (req, res) => {throw new ServerError('Project is not paused', { status: 400, code: 'INVALID_STATE' });}const restored = project.treatment ? 'rendering' : 'planning';- await updateProject(project.id, { status: restored });+ // Clear the reason too. A stop parks the project as `paused` WITH a+ // `failureReason` (that's what explains why it stopped), and the overview/plan+ // tabs render any non-empty failureReason in a red "FAILURE REASON" box — so+ // without this the resumed project runs its whole next pass under a banner+ // reporting the stop the user just undid.+ await updateProject(project.id, { status: restored, failureReason: null });startCreativeDirectorProject(project.id).catch((e) => console.log(`⚠️ CD resume failed: ${e.message}`));res.json({ ok: true });}));diff --git a/server/routes/creativeDirector.test.js b/server/routes/creativeDirector.test.jsindex 34909361c6..1d9d97b314 100644--- a/server/routes/creativeDirector.test.js+++ b/server/routes/creativeDirector.test.js@@ -353,7 +353,9 @@ describe('creativeDirector routes', () => {const r = await request(app).post('/api/creative-director/cd-1/resume');expect(r.status).toBe(200);expect(r.body.ok).toBe(true);- expect(cdService.updateProject).toHaveBeenCalledWith('cd-1', { status: 'rendering' });+ // Resume must also CLEAR the reason: a stop parks the project with one, and+ // the overview/plan tabs render any non-empty failureReason in a red banner.+ expect(cdService.updateProject).toHaveBeenCalledWith('cd-1', { status: 'rendering', failureReason: null });expect(hook.startCreativeDirectorProject).toHaveBeenCalledWith('cd-1');});});diff --git a/server/services/creativeCommissions/projectControl.js b/server/services/creativeCommissions/projectControl.jsindex 8eabbf32cb..6f3ecab1f2 100644--- a/server/services/creativeCommissions/projectControl.js+++ b/server/services/creativeCommissions/projectControl.js@@ -138,10 +138,22 @@ 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([+ const [{ inflightRuns, retireRuns }, { advanceAfterPlanStepSettled }, { advanceAfterSceneSettled }] = await Promise.all([import('../creativeDirector/stopProject.js'),import('../creativeDirector/planAdvance.js'),+ import('../creativeDirector/completionHook.js'),]);+ // Which advance loop owns a project depends on its shape, and BOTH shapes can+ // carry a commissionId: a commission fire mints a directive project, but a plan+ // step's `cd_produceVideoFromIssue` mints a legacy scene-loop teaser that+ // inherits the same back-pointer. Handing a directive-less project to+ // advanceAfterPlanStepSettled is a silent no-op (it returns on `!project.directive`),+ // which would leave the stage we just retired with nothing to re-dispatch it —+ // wedged until a manual Resume. Same branch as recovery.js and+ // agentManagement.js#settleOrphanedCreativeDirectorRun.+ const advance = (project) => (project.directive+ ? advanceAfterPlanStepSettled(project.id)+ : advanceAfterSceneSettled(project.id));const reason = 'Creative commission provider changed';const restarted = [];for (const project of projects) {@@ -151,7 +163,7 @@ export async function restartCommissionStages(commissionId, commission) {.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)+ await advance(project).catch((e) => console.error(`❌ Commission ${commissionId}: advance ${project.id} failed: ${e.message}`));}if (restarted.length) {@@ -241,16 +253,29 @@ export function registerCommissionProjectReconciler() {}/**- * One-shot boot backfill: stamp `commissionId` onto the projects a commission- * spawned BEFORE the back-pointer existed, reading it out of the run ledger.+ * One-shot boot backfill for projects minted BEFORE the back-pointer existed.+ * Reads the commission's run ledger and, for each project it still names:*- * 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).+ * 1. stamps `commissionId`, and+ * 2. CLEARS the `modelOverrides.{treatment,plan}` snapshot the old fire path+ * wrote onto it.+ *+ * Both halves are needed, and (2) is the one that actually unsticks the user's+ * problem. The dispatch path only consults a commission when the project names+ * one — so without (1) a wedged project keeps its frozen provider forever. But a+ * per-project pin now outranks the commission's (it means "the user chose this in+ * the models drawer"), and every pre-change project carries one purely because+ * the fire wrote it — so without (2) the stamp would land and the stale snapshot+ * would still win, leaving the project exactly as stuck as before.+ *+ * The trade-off is deliberate: on a pre-change project we cannot distinguish the+ * machine-written snapshot from a drawer edit made on top of it, and clearing is+ * the only choice that honors the commission going forward. A user who wants a+ * per-project override can re-set it in the drawer, where it will now stick.+ *+ * 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 with no snapshot at all).** Pure data movement, no LLM. Idempotent: a project that already carries the* back-pointer is skipped, so a re-run writes nothing. Best-effort — a failure@@ -271,7 +296,11 @@ export async function backfillProjectCommissionIds() {const projects = await getProjectsByIds(legacyIds).catch(() => []);for (const project of projects) {if (!project || project.commissionId) continue;- const ok = await updateProject(project.id, { commissionId })+ // Drop only the stages the old fire path owned; a hand-set `evaluation` pin+ // was never written by it, so it survives.+ const overrides = { ...(project.modelOverrides || {}) };+ for (const stage of COMMISSION_PINNED_STAGES) delete overrides[stage];+ const ok = await updateProject(project.id, { commissionId, modelOverrides: overrides }).then(() => true).catch((e) => { console.error(`❌ Commission back-pointer backfill: ${project.id} failed: ${e.message}`); return false; });if (ok) stamped += 1;diff --git a/server/services/creativeCommissions/projectControl.test.js b/server/services/creativeCommissions/projectControl.test.jsindex d2fcb4465a..5a0f72fea9 100644--- a/server/services/creativeCommissions/projectControl.test.js+++ b/server/services/creativeCommissions/projectControl.test.js@@ -1,5 +1,6 @@import { describe, it, expect, vi, beforeEach } from 'vitest';import { EventEmitter } from 'events';+import { RUN_TERMINAL_STATUSES } from '../../lib/creativeDirectorPresets.js';// The raw store read (tombstone-inclusive) these paths run on.const readRawMock = vi.fn(async () => null);@@ -31,15 +32,23 @@ 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.+ // A stand-in for the real pure filter — the restart path must narrow to the LLM+ // stages, and a pass-through stub would hide it sweeping up plan-step render+ // runs. It reads the terminal set from the same presets leaf the real one does,+ // so it cannot drift if RUN_TERMINAL_STATUSES gains a value. (Importing the real+ // module here isn't an option: stopProject.js pulls in creativeDirector/local.js+ // and with it the whole provider graph this suite deliberately mocks away.)inflightRuns: (project, kinds) => (project?.runs || []).filter((r) => r- && r.status !== 'completed' && r.status !== 'failed'+ && !RUN_TERMINAL_STATUSES.has(r.status)&& (!kinds || kinds.includes(r.kind))),}));const advanceMock = vi.fn(async () => {});vi.mock('../creativeDirector/planAdvance.js', () => ({ advanceAfterPlanStepSettled: (...a) => advanceMock(...a) }));+// The legacy scene-loop counterpart. A directive-less project (a teaser a plan+// step spawned) must go here instead — advanceAfterPlanStepSettled no-ops on it.+const advanceSceneMock = vi.fn(async () => {});+vi.mock('../creativeDirector/completionHook.js', () => ({ advanceAfterSceneSettled: (...a) => advanceSceneMock(...a) }));const {ledgerProjectIds,@@ -58,7 +67,12 @@ const commission = (over = {}) => ({...over,});-const project = (over = {}) => ({ id: 'cd-1', status: 'planning', runs: [], ...over });+// A commission fire always mints a directive-driven project; the legacy+// scene-loop shape reaches this module only via a plan step's teaser (which+// inherits the same commissionId), so it gets its own fixture below.+const project = (over = {}) => ({+ id: 'cd-1', status: 'planning', runs: [], directive: { goal: 'g' }, ...over,+});beforeEach(() => {vi.clearAllMocks();@@ -71,15 +85,19 @@ beforeEach(() => {describe('ledgerProjectIds', () => {it('returns distinct ids newest-first and drops run rows that minted nothing', () => {+ // Three DISTINCT ids in ledger (oldest→newest) order, so the expectation is+ // asymmetric: a forward walk would yield ['cd-a','cd-b','cd-c'] and fail. A+ // two-id fixture reads the same in both directions and pins 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+ { projectId: 'cd-a' }, // a re-run against the same project — dedupes+ { projectId: 'cd-c' },],});- expect(ids).toEqual(['cd-a', 'cd-b']);+ expect(ids).toEqual(['cd-c', 'cd-a', 'cd-b']);});it('tolerates a commission with no run history', () => {@@ -100,6 +118,11 @@ describe('commissionStagePin', () => {expect(getProviderByIdMock).not.toHaveBeenCalled();});+ it('omits the model when only a provider is pinned — never ships model:null into task metadata', async () => {+ readRawMock.mockResolvedValue(commission({ assignment: { providerId: 'lmstudio-tui', model: null } }));+ expect(await commissionStagePin('commission-1')).toEqual({ providerId: 'lmstudio-tui' });+ });+it('inherits the default for an unknown commission', async () => {readRawMock.mockResolvedValue(null);expect(await commissionStagePin('commission-gone')).toBeNull();@@ -225,6 +248,25 @@ describe('restartCommissionStages', () => {expect(result.restarted).toEqual(['cd-1']);});+ it('hands a directive-LESS project to the scene loop — the plan loop no-ops on it and would strand the retired stage', async () => {+ // A plan step's `cd_produceVideoFromIssue` teaser inherits commissionId but has+ // no directive. advanceAfterPlanStepSettled returns immediately on such a+ // project, so routing it there would retire the stage and re-dispatch nothing.+ readRawMock.mockResolvedValue(commission());+ listProjectsByCommissionIdMock.mockResolvedValue([{+ id: 'cd-teaser',+ status: 'rendering',+ directive: null,+ runs: [{ runId: 'r1', kind: 'treatment', taskId: 't1', status: 'running' }],+ }]);++ await restartCommissionStages('commission-1');++ expect(retireRunsMock).toHaveBeenCalled();+ expect(advanceSceneMock).toHaveBeenCalledExactlyOnceWith('cd-teaser');+ expect(advanceMock).not.toHaveBeenCalled();+ });+it('restarts a PAUSED project’s stage but never auto-resumes the project', async () => {readRawMock.mockResolvedValue(commission());listProjectsByCommissionIdMock.mockResolvedValue([project({@@ -322,13 +364,29 @@ describe('backfillProjectCommissionIds', () => {listIdsMock.mockResolvedValue(['commission-1']);readRawMock.mockResolvedValue(commission({ runs: [{ projectId: 'cd-old' }, { projectId: 'cd-new' }] }));getProjectsByIdsMock.mockResolvedValue([- { id: 'cd-old', status: 'planning' },+ {+ id: 'cd-old',+ status: 'planning',+ // What the OLD fire path wrote, plus a hand-set evaluation pin.+ modelOverrides: {+ treatment: { providerId: 'claude-ollama-tui' },+ plan: { providerId: 'claude-ollama-tui' },+ evaluation: { providerId: 'vision-api' },+ },+ },{ id: 'cd-new', status: 'planning', commissionId: 'commission-1' }, // already stamped]);const result = await backfillProjectCommissionIds();- expect(updateProjectMock).toHaveBeenCalledExactlyOnceWith('cd-old', { commissionId: 'commission-1' });+ // Stamps the back-pointer AND drops the stale snapshot — a per-project pin now+ // outranks the commission's, so leaving it would keep the project stuck on the+ // provider it was minted with, which is the whole bug. `evaluation` survives:+ // the commission never wrote it.+ expect(updateProjectMock).toHaveBeenCalledExactlyOnceWith('cd-old', {+ commissionId: 'commission-1',+ modelOverrides: { evaluation: { providerId: 'vision-api' } },+ });expect(result).toEqual({ stamped: 1 });});diff --git a/server/services/creativeCommissions/store.js b/server/services/creativeCommissions/store.jsindex 700bf3a58b..abd3e49710 100644--- a/server/services/creativeCommissions/store.js+++ b/server/services/creativeCommissions/store.js@@ -690,18 +690,28 @@ export async function updateCommission(id, patch) {? nowIso : current.briefUpdatedAt,});await store.writeRaw(id, next);- return next;+ // The keys whose VALUE actually changed — not the keys the patch mentioned.+ // The commission editor posts the whole form on every save (its `assignment`+ // rides along even when the user only fixed a typo in the brief), so a+ // patch-key list would tell the project reconciler "the provider changed" on+ // every single save and it would kill a healthy in-flight agent each time.+ const changedFields = Object.keys(next).filter(+ (k) => JSON.stringify(next[k]) !== JSON.stringify(current[k]),+ );+ return { next, changedFields };});if (!merged) throw makeErr(`Commission not found: ${id}`, ERR_NOT_FOUND);- // 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) });+ const { next: mergedRecord, changedFields } = merged;+ // Carry the CHANGED key set: the project reconciler only cares about `enabled`+ // and `assignment`, so an edit that touched neither skips its project lookup —+ // and, more importantly, never tears down a healthy in-flight agent stage.+ // Absent (other emitters) must mean "reconcile" — we cannot prove a change was+ // irrelevant — never "skip".+ commissionEvents.emit('commission:changed', { id, action: 'update', fields: changedFields });// 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);- return merged;+ return mergedRecord;}export async function deleteCommission(id) {diff --git a/server/services/creativeCommissions/store.test.js b/server/services/creativeCommissions/store.test.jsindex 6458e1e870..e89d4b3ebc 100644--- a/server/services/creativeCommissions/store.test.js+++ b/server/services/creativeCommissions/store.test.js@@ -57,6 +57,7 @@ const {mergeCommissionsFromSync,pruneTombstonedCommissions,commissionStore,+ commissionEvents,MAX_RUN_PROMPT_LEN,ERR_VALIDATION,ERR_NOT_FOUND,@@ -221,6 +222,51 @@ describe('createCommission', () => {});});+describe('updateCommission — changed-field event payload', () => {+ // The project reconciler (creativeCommissions/projectControl.js) keys on this+ // payload to decide whether to tear down a commission's in-flight LLM stages.+ // The commission editor posts the WHOLE form on every save — its `assignment`+ // rides along even when the user only fixed a typo — so a patch-key list here+ // would read as "the provider changed" on every save and SIGKILL a healthy+ // planner agent mid-run, every time.+ const captureFields = async (id, patch) => {+ let fields;+ const onChange = (e) => { if (e?.action === 'update') fields = e.fields; };+ commissionEvents.on('commission:changed', onChange);+ try { await updateCommission(id, patch); } finally { commissionEvents.off('commission:changed', onChange); }+ return fields;+ };++ it('omits assignment when the patch resends the SAME pin', async () => {+ const created = await createCommission(validInput());+ await updateCommission(created.id, { assignment: { providerId: 'claude-tui', model: 'sonnet' } });+ // Exactly what the editor sends when the user edits only the brief.+ const fields = await captureFields(created.id, {+ name: created.name,+ brief: { intent: 'a typo fix' },+ assignment: { providerId: 'claude-tui', model: 'sonnet' },+ });+ expect(fields).toContain('brief');+ expect(fields).not.toContain('assignment');+ expect(fields).not.toContain('enabled');+ });++ it('reports assignment when the pin genuinely changes', async () => {+ const created = await createCommission(validInput());+ await updateCommission(created.id, { assignment: { providerId: 'claude-tui', model: 'sonnet' } });+ const fields = await captureFields(created.id, {+ assignment: { providerId: 'lmstudio-tui', model: 'qwen3' },+ });+ expect(fields).toContain('assignment');+ });++ it('reports enabled when the commission is paused', async () => {+ const created = await createCommission(validInput());+ const fields = await captureFields(created.id, { enabled: false });+ expect(fields).toContain('enabled');+ });+});+describe('updateCommission', () => {it('deep-merges a partial brief without wiping other fields', async () => {const created = await createCommission(validInput());diff --git a/server/services/creativeDirector/agentBridge.js b/server/services/creativeDirector/agentBridge.jsindex f5c04bc7fa..ac5df6e4b6 100644--- a/server/services/creativeDirector/agentBridge.js+++ b/server/services/creativeDirector/agentBridge.js@@ -26,18 +26,23 @@ 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 order://-// 1. The OWNING CREATIVE COMMISSION's current pin, read live. A commission is a+// 1. The project's OWN `modelOverrides.<kind>` pin — a deliberate per-project+// choice the user made in the CD models drawer. Most specific, so it wins.+// 2. 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`.+// wedged project keep handing its planner task to the old one forever — AND+// it occupied tier 1, so a later drawer edit could never be distinguished+// from the machine-written snapshot. The fire no longer writes that snapshot+// (and the boot backfill clears the ones it already wrote), so a value in+// tier 1 now means "the user chose this", nothing else.+// 3. The global `settings.creativeDirector.<kind>` AI Assignment.//// 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.+// existing installations. A commission lookup failure falls through 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@@ -46,11 +51,14 @@ async function getStageAssignment(kind, project) {// `creativeDirector.evaluate` settings key; the eval pin lives under// `creativeDirector.evaluation`.)if (kind === 'evaluate') return {};+ // Only consult the commission when the project does NOT carry its own pin for+ // this stage — a drawer choice is the user's explicit override and must win.+ const projectPin = project?.modelOverrides?.[kind]?.providerId ? project.modelOverrides[kind] : null;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+ (!projectPin && project?.commissionId)? import('../creativeCommissions/projectControl.js').then(({ commissionStagePin }) => commissionStagePin(project.commissionId)).catch(() => null)diff --git a/server/services/creativeDirector/agentBridge.test.js b/server/services/creativeDirector/agentBridge.test.jsindex ed06601c3c..7b66117efe 100644--- a/server/services/creativeDirector/agentBridge.test.js+++ b/server/services/creativeDirector/agentBridge.test.js@@ -44,16 +44,12 @@ beforeEach(() => {});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 () => {+ // A project minted by a commission fire carries NO modelOverrides — the fire+ // stamps only the back-pointer, and the boot backfill strips the snapshot the+ // old fire path used to write. So the commission's live pin is what applies.+ const commissioned = { ...project, commissionId: 'commission-1', modelOverrides: {} };++ it("resolves the owning commission's pin LIVE, so an edited provider reaches a project already in flight", async () => {mocks.commissionStagePin.mockResolvedValue({ providerId: 'lmstudio-tui', model: 'qwen3.6:35b' });await enqueuePlanTask(commissioned);@@ -65,11 +61,32 @@ describe('Creative Director agent bridge — commission-owned projects', () => {});});+ it("lets a hand-set per-project pin BEAT the commission's — the models drawer must not be a silent no-op", async () => {+ mocks.commissionStagePin.mockResolvedValue({ providerId: 'lmstudio-tui', model: 'qwen3.6:35b' });++ await enqueuePlanTask({ ...commissioned, modelOverrides: { plan: { providerId: 'drawer-choice-tui' } } });++ const [task] = mocks.addTask.mock.calls[0];+ expect(task.metadata).toMatchObject({ providerId: 'drawer-choice-tui' });+ // And it doesn't even pay for the lookup it isn't going to use.+ expect(mocks.commissionStagePin).not.toHaveBeenCalled();+ });++ it('consults the commission when the project pins a DIFFERENT stage', async () => {+ mocks.commissionStagePin.mockResolvedValue({ providerId: 'lmstudio-tui' });++ // An evaluation-only override leaves `plan` to the commission.+ await enqueuePlanTask({ ...commissioned, modelOverrides: { evaluation: { providerId: 'vision-api' } } });++ const [task] = mocks.addTask.mock.calls[0];+ expect(task.metadata).toMatchObject({ providerId: 'lmstudio-tui' });+ });+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: {} });+ await enqueuePlanTask(commissioned);const [task] = mocks.addTask.mock.calls[0];expect(task.metadata).toMatchObject({ providerId: 'global-agent' });@@ -82,11 +99,12 @@ describe('Creative Director agent bridge — commission-owned projects', () => {it('does not stall the dispatch when the commission lookup fails', async () => {mocks.commissionStagePin.mockRejectedValue(new Error('store down'));+ mocks.getSettings.mockResolvedValue({ creativeDirector: { plan: { providerId: 'global-agent' } } });await enqueuePlanTask(commissioned);const [task] = mocks.addTask.mock.calls[0];- expect(task.metadata).toMatchObject({ providerId: 'claude-ollama-tui' });+ expect(task.metadata).toMatchObject({ providerId: 'global-agent' });});});diff --git a/server/services/creativeDirector/completionHook.test.js b/server/services/creativeDirector/completionHook.test.jsindex 9888af16e5..22193c7b74 100644--- a/server/services/creativeDirector/completionHook.test.js+++ b/server/services/creativeDirector/completionHook.test.js@@ -93,19 +93,6 @@ describe('handleCreativeDirectorCompletion — plan deliverable', () => {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 Killdiff --git a/server/services/creativeDirector/projectsLogic.js b/server/services/creativeDirector/projectsLogic.jsindex 3a2a21a8df..cdb9a6a748 100644--- a/server/services/creativeDirector/projectsLogic.js+++ b/server/services/creativeDirector/projectsLogic.js@@ -288,7 +288,14 @@ export function mergeProjectRecord(local, remoteRaw) {if (!remote) return { next: null, inserted: false, remoteWins: false, changed: false };if (!local) return { next: remote, inserted: true, remoteWins: true, changed: true };const remoteWins = compareNewerWins(remote.updatedAt, local.updatedAt);- const next = remoteWins ? remote : local;+ // `commissionId` is machine-local — syncWire strips it, so a winning remote+ // never carries one. Re-attach the receiver's own value (mirrors+ // preserveLocalCommissionFields) or a peer's edit would silently orphan this+ // project from the commission that owns it, leaving it unstoppable from the+ // commission page and stuck on the provider it was dispatched with.+ const next = remoteWins+ ? { ...remote, ...(local.commissionId ? { commissionId: local.commissionId } : {}) }+ : local;const changed = JSON.stringify(next) !== JSON.stringify(local);return { next, inserted: false, remoteWins, changed };}diff --git a/server/services/creativeDirector/projectsLogic.test.js b/server/services/creativeDirector/projectsLogic.test.jsindex 8250b51c2b..ee74f29f93 100644--- a/server/services/creativeDirector/projectsLogic.test.js+++ b/server/services/creativeDirector/projectsLogic.test.js@@ -352,6 +352,26 @@ describe('sanitizeProjectForSync', () => {});describe('mergeProjectRecord (LWW, tombstone-aware)', () => {+ it('re-attaches the local commissionId when a remote wins — the wire never carries one', () => {+ // syncWire strips commissionId, so every inbound record lacks it. Without the+ // re-attach, a peer's edit winning the LWW would silently orphan the project+ // from the commission that owns it: unstoppable from the commission page and+ // stuck on whatever provider it was dispatched with.+ const local = { id: 'cd-1', updatedAt: '2026-01-01T00:00:00.000Z', commissionId: 'commission-1' };+ const remote = { id: 'cd-1', updatedAt: '2026-06-01T00:00:00.000Z', name: 'Renamed' };+ const { next, remoteWins } = mergeProjectRecord(local, remote);+ expect(remoteWins).toBe(true);+ expect(next.name).toBe('Renamed');+ expect(next.commissionId).toBe('commission-1');+ });++ it('does not invent a commissionId when the local record has none', () => {+ const local = { id: 'cd-1', updatedAt: '2026-01-01T00:00:00.000Z' };+ const remote = { id: 'cd-1', updatedAt: '2026-06-01T00:00:00.000Z', name: 'Renamed' };+ const { next } = mergeProjectRecord(local, remote);+ expect(next).not.toHaveProperty('commissionId');+ });+const at = (iso, extra = {}) => ({ id: 'cd-1', name: 'P', updatedAt: iso, ...extra });it('inserts when there is no local counterpart', () => {const { next, inserted, remoteWins } = mergeProjectRecord(null, at('2026-06-23T00:00:00.000Z'));diff --git a/server/services/creativeDirector/stopProject.js b/server/services/creativeDirector/stopProject.jsindex 0657c4a4ec..3c4a803849 100644--- a/server/services/creativeDirector/stopProject.js+++ b/server/services/creativeDirector/stopProject.js@@ -63,14 +63,22 @@ export function inflightRuns(project, kinds = null) {/*** 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>`.+ *+ * A CD project claims its media jobs three different ways, and a stop that misses+ * one leaves that render burning GPU after the user asked it to stop:+ * - `owner: "cd:<projectId>:<sceneId>"` — the scene loop's per-scene render+ * - `owner: "creative-director:<projectId>"` — a Phase-2 plan render step+ * - `params.creativeDirector.projectId` — first-pass seed frames+ * (firstPassGen.js#enqueueFirstPassSceneFrames), which carry NO owner at all;+ * this is the tag completionHook's findPendingSeedFrameJob keys on. A+ * 10-scene project enqueues ten of these up front, so omitting them is the+ * difference between "Stop" cancelling the queue and cancelling nothing.*/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'));+ const ownedBy = (j) => (typeof j?.owner === 'string'+ && (j.owner.startsWith(`cd:${projectId}:`) || j.owner === `creative-director:${projectId}`))+ || j?.params?.creativeDirector?.projectId === projectId;+ return (jobs || []).filter((j) => ownedBy(j) && (j.status === 'queued' || j.status === 'running'));}/**diff --git a/server/services/creativeDirector/stopProject.test.js b/server/services/creativeDirector/stopProject.test.jsindex 8f49efa2a4..4e04742bc2 100644--- a/server/services/creativeDirector/stopProject.test.js+++ b/server/services/creativeDirector/stopProject.test.js@@ -96,16 +96,22 @@ describe('retireRuns', () => {});describe('ownedLiveJobs', () => {- it('matches both owner conventions and only live jobs', () => {+ it('matches all three ownership 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+ { id: 'j6', status: 'queued' }, // ownerless, untagged+ // First-pass seed frames carry NO owner — they're tagged in params. A+ // 10-scene project enqueues ten of these up front, so missing them means+ // "Stop" cancels nothing on exactly the projects with the most queued work.+ { id: 'j7', status: 'queued', params: { creativeDirector: { projectId: 'cd-1', sceneId: 's1' } } },+ { id: 'j8', status: 'running', params: { creativeDirector: { projectId: 'cd-2' } } }, // other project+ { id: 'j9', status: 'completed', params: { creativeDirector: { projectId: 'cd-1' } } }, // terminal];- expect(ownedLiveJobs(jobs, 'cd-1').map((j) => j.id)).toEqual(['j2', 'j3']);+ expect(ownedLiveJobs(jobs, 'cd-1').map((j) => j.id)).toEqual(['j2', 'j3', 'j7']);});});