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

feat(creative-commissions): let commissions choose the AI provider/model that processes them

Adam Eivyb3f7d68e0aed
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index aeb32cf24b..aefc953392 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -155,4 +155,5 @@
- **Fix Element Flash: pressing Enter/Return after answering now advances to the next question.** In the Element Flash recall test (`ElementsSong.jsx`), the Enter-to-submit handler lived only on the answer `<input>`, which unmounts once the result is shown — so a second Enter did nothing and the user had to click "Next" to continue. `ElementFlashMode` now binds a window `keydown` listener while a result is showing (input unmounted) that advances on Enter/Return, mirroring the "Next" button; the `next()` handler was hoisted above the completion early-return so the effect can reference it without breaking hook order. The listener ignores auto-repeat (`e.repeat`) and any Enter that a focused control or open overlay already owns (`e.target.closest('button, a, input, textarea, select, [role="dialog"], [role="menu"], [contenteditable]')`) — so a keyboard user tabbed to the Back/Next button doesn't double-advance, and an Enter meant for the command palette doesn't leak through to the quiz. Tests drive answer → Enter (submit) → Enter (advance) asserting the counter increments, and pin that an Enter fired from the focused Next button is not hijacked by the window listener.
- **[issue-2657] Autonomous Creation Engine (Phase 1) — schedule the Creative Director with a recurring, feedback-ready creative brief.** New first-class `CreativeCommission` entity: a standing brief (`{ name, enabled, targetAbility, brief, schedule, generation }`) that fires on a cron cadence and drives the existing Creative Director *directive* pipeline unattended — "every night at 2am, make me something surreal." Commissions are `db-primary` (per `docs/STORAGE.md`): one row per commission in the machine-local `creative_commissions` PostgreSQL table (full record in `data` JSONB, adapter `server/services/creativeCommissions/db.js`, selected pg-vs-file exactly like universeBuilder so a `NODE_ENV=test`/`MEMORY_BACKEND=file` install keeps a file escape hatch). No `sync_sequence`/tombstone — deletes are hard deletes, mirroring `tribe`. They are deliberately **not** federated in Phase 1 — the same rationale as `seriesAutopilotScheduler`'s settings-based schedules, since a schedule that synced across peers would double-run on every machine (federation with a per-peer "home" gate is Phase 2). A new `commissionScheduler.js` (modeled on `seriesAutopilotScheduler`) arms one `eventScheduler` cron per enabled commission; on fire it re-reads the commission + creative-autonomy config, builds a CD directive from the brief via the pure `buildCommissionDirective` (which already folds a last-N feedback digest so Phase 2 only needs the rate surface), mints a directive-driven CD video project, and nudges `advanceAfterPlanStepSettled` so each plan step runs through the gated `dispatchCreativeTool`. Cold-bootstrap compliant per the AI Provider Usage Policy: boot only *arms* crons (nothing fires until a cadence elapses), and every fire gates on creative autonomy `execute` **and** the daily `cos` budget before spawning anything — an `off`/`dry-run` or over-budget install records a `skipped` run and generates nothing. Full REST CRUD at `/api/creative-commission` (Zod-validated create/update, DAILY/WEEKLY/CUSTOM schedules composed to cron with an authoritative `isValidCron` check in the service, `generation` schema with no object-level default so an empty PATCH still 400s the "at least one field" refine), a scheduler re-sync after every mutation, and a new `/creative-commission` Create-suite page: list + deep-linked create/edit Drawer (`/creative-commission/:id`, `/new`) with pause/resume, inline-confirm delete, and per-run history — registered in `NAV_COMMANDS` (⌘K + voice) and the sidebar. Phase 1 restricts `targetAbility` to `video` (the enum widens with the ability adapter in Phase 3/4) so a user can't create a commission that silently never runs. Refs #2657 — Phases 2–5 (feedback loop, all-ability adapter, music tool, genre taxonomy) remain. New unit + route + PG-adapter tests cover cron composition, the feedback digest, the store CRUD/sanitizer, the autonomy/budget gates, the no-boot-generation guarantee, the route contract, and the `creative_commissions` row round-trip (verbatim readback / upsert with created_at preserved / list order / hard delete). Scheduler-vs-request writes serialize on the facade's shared per-id write queue (`createRecordWriteQueue`), identical to universeBuilder/storyBuilder.
- **[issue-2657] Autonomous Creation Engine (Phase 2) — the taste feedback loop closes.** Each commission run's output is now rateable, and your reactions steer the next run. A new per-run **rate/annotate control** in the Creative Commissions run history (👍/👎 + an optional note like "less horror, more Magritte", keyboard-accessible, mobile-responsive, reactive) records a `CommissionFeedback` reaction against that specific run; the next scheduled fire's `buildCommissionDirective` folds the last **N** reactions (a configurable **feedback window**, now editable in the drawer — 0 disables conditioning) into the directive's goal as a "Recent likes / Recent dislikes — steer toward the likes, away from the dislikes" digest, so the run visibly drifts toward what you actually like (the digest shows up in the run's `promptUsed`). Feedback lives inline on the commission record — Phase 1 reserved `feedback[]` for exactly this, so no schema/table change was needed; reactions are deep-sanitized (a 👍/👎 or non-zero score is required, numeric ratings preserved verbatim, capped at 100) and **upserted by run** (re-rating a run replaces its prior reaction rather than stacking a contradictory second one) on the same shared per-id write queue as run-recording so a rating submitted mid-fire can't clobber a run append. The composed directive goal is length-clamped (per-note + overall) so a large feedback window can't push it past the Creative Director's 5000-char goal limit on the scheduler path (which skips the route's input validation). New `POST /api/creative-commission/:id/feedback` (Zod-validated `commissionFeedbackSchema` — `runId` required and verified against the record's runs, a zero rating rejected as meaningless, → 400/404 on bad input/unknown id) returns the full updated commission for reactive state; the edit drawer preserves unsaved field edits when a rating lands (the form re-syncs only on a genuine target change, not on every in-place record update). When a commission fires it also **surfaces** the run as a low-priority, machine-local notification (new `creative_commission` type, deep-linked to the commission) worded to reflect that the piece is *being created* — "rate the result once it lands." Surfacing stays notification-only for now: the brain inbox is federated (`inbox` ∈ `BRAIN_ENTITY_TYPES`), so a reminder there would propagate a peer-useless `needs_review` item pointing at a machine-local commission — brain-inbox surfacing (and completion-triggered surfacing) rejoin once commissions themselves federate. Commissions stay machine-local as in Phase 1 — since feedback lives on the never-federated commission it is also machine-local; the split-record federation the epic sketches (feedback federates, `schedule` stays per-machine to avoid double-runs) is genuinely larger and tracked as follow-up. Refs #2657 — Phases 3–5 (all-ability adapter, music tool, genre taxonomy) remain. New/updated unit + route tests cover the feedback sanitizer, `submitCommissionFeedback` (upsert-by-run / runId verification / NOT_FOUND / the full loop where a reaction folds into the next directive), the goal clamp, the feedback route contract, the notification-only surfacing helper (deep link + no federated-inbox write + best-effort resilience), and the scheduler surfacing a successful fire but not a skipped one.
+- **[issue-2657] Creative Commissions now show — and let you choose — which AI processes them.** A commission used to silently inherit the install's default Creative Director AI Assignment, so it wasn't clear what provider/model would write each run's treatment and production plan. The edit drawer gains an **AI provider & model** picker (the shared `ProviderModelSelector`, filtered to agent-harness CLI/TUI providers since an API-type provider injected into a CoS agent task trips the harness-boundary guard), and the list card shows the chosen processor at a glance (an unset pin reads "Install default AI"; the picker's default option names the actual active provider so "default" is never opaque). The choice is stored as a new `assignment: { providerId, model }` on the commission record (additive; `providerId: null` = inherit the default, preserving prior behavior); at fire time the scheduler fans that single pin onto **both** CD cognitive stages (`modelOverrides.{treatment,plan}`) so the run is processed by the provider/model you picked. Evaluation is deliberately left inheriting the default — it's a vision API call, not a CoS agent, and pinning it to a CLI/TUI provider would trip the same harness boundary. A provider-less model is dropped by the sanitizer (the runtime keys on the provider first) so the stored pin can never dangle, and a PATCH that omits `assignment` preserves it while an explicit `{ providerId: null, model: null }` clears it back to the default. Zod-validated on create/update via the new `creativeCommissionAssignmentSchema`. New unit tests cover the sanitizer normalization/trim/provider-less-drop, the update replace-and-clear + preserve-on-omit semantics, and the scheduler fanning the pin onto both stages (and omitting the model when only a provider is chosen).
- **Fix the Dev-UI "Vite host will be blocked" warning firing for apps whose vite config lives in an unlisted subdir.** `findViteConfig` only probed a hardcoded subdir allowlist (`client/`, `frontend/`, `web/`, …) plus each managed process's `cwd`. Apps that keep their Vite client elsewhere — e.g. an `admin/` dir — and whose stored process records carry no `cwd` produced a false "no vite.config was found" banner even though the config already set `allowedHosts: true` and the Dev UI opened fine over Tailscale. `findViteConfig` now falls back to a bounded breadth-first scan of the repo (depth ≤3, skipping `node_modules`/`.git`/build/vendor dirs, shallowest match wins) when the fast-path subdirs miss, so a config in any reasonable location is detected and the host-allow check reflects reality. `admin` also added to the fast-path list. New tests cover root, unlisted-subdir (`admin/`), nested, `node_modules`-ignore, and the end-to-end host-allowed status.
diff --git a/client/src/pages/CreativeCommissions.jsx b/client/src/pages/CreativeCommissions.jsx
index d7b4a1e8ca..411ddec487 100644
--- a/client/src/pages/CreativeCommissions.jsx
+++ b/client/src/pages/CreativeCommissions.jsx
@@ -14,15 +14,17 @@
import { useEffect, useMemo, useState, useCallback, useRef } from 'react';
import { useNavigate, useParams, useLocation, Link } from 'react-router-dom';
-import { Plus, Sparkles, Trash2, Clock, Pause, Play, ThumbsUp, ThumbsDown, ExternalLink } from 'lucide-react';
+import { Plus, Sparkles, Trash2, Clock, Cpu, Pause, Play, ThumbsUp, ThumbsDown, ExternalLink } from 'lucide-react';
import toast from '../components/ui/Toast';
import Drawer from '../components/Drawer';
import ConfirmButtonPair from '../components/ui/ConfirmButtonPair';
import { timeAgo } from '../utils/formatters';
import { useConfirmDelete } from '../hooks/useConfirmDelete';
+import { isProcessProvider } from '../utils/providers';
+import ProviderModelSelector from '../components/ProviderModelSelector';
import {
listCommissions, getCommission, createCommission, updateCommission, deleteCommission,
- submitCommissionFeedback,
+ submitCommissionFeedback, getProviders,
} from '../services/api';
const WEEKDAYS = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
@@ -37,6 +39,14 @@ function describeSchedule(schedule) {
return kind || 'No schedule';
}
+// Compact "who processes this" summary for the list card. Unset → the install
+// default assignment; set → the pinned provider (and model, when chosen).
+function describeAssignment(assignment) {
+ const providerId = assignment?.providerId;
+ if (!providerId) return 'Install default AI';
+ return assignment.model ? `${providerId} · ${assignment.model}` : providerId;
+}
+
// A blank form is just the editable projection of an empty record.
const blankForm = () => toForm({});
@@ -63,6 +73,12 @@ function toForm(c) {
aspectRatio: c.generation?.aspectRatio || '16:9',
targetDurationSeconds: c.generation?.targetDurationSeconds || 10,
},
+ // Which AI provider/model processes the commission's CD stages. Empty
+ // providerId → the install's default AI Assignment.
+ assignment: {
+ providerId: c.assignment?.providerId || '',
+ model: c.assignment?.model || '',
+ },
// How many recent reactions steer the next run (0 disables conditioning).
feedbackWindow: Number.isInteger(c.feedbackWindow) ? c.feedbackWindow : 5,
};
@@ -93,6 +109,13 @@ function toPayload(form) {
aspectRatio: form.generation.aspectRatio,
targetDurationSeconds: Number(form.generation.targetDurationSeconds),
},
+ // Send the full pin every save; a provider-less choice clears the model too
+ // (the server drops a dangling model, but keeping the payload clean avoids a
+ // pointless round-trip through the sanitizer's normalization).
+ assignment: {
+ providerId: form.assignment.providerId || null,
+ model: form.assignment.providerId ? (form.assignment.model || null) : null,
+ },
feedbackWindow: Number(form.feedbackWindow),
};
}
@@ -315,6 +338,9 @@ export default function CreativeCommissions() {
</div>
<div className="flex items-center gap-3 mt-1 text-xs text-gray-500">
<span className="flex items-center gap-1"><Clock className="w-3 h-3" /> {describeSchedule(c.schedule)}</span>
+ <span className="flex items-center gap-1" title="AI provider that writes the treatment & plan">
+ <Cpu className="w-3 h-3" /> {describeAssignment(c.assignment)}
+ </span>
{Array.isArray(c.runs) && c.runs.length > 0 && (
<span>Last run {timeAgo(c.runs[c.runs.length - 1].ranAt)}</span>
)}
@@ -572,6 +598,19 @@ function CommissionForm({ form, patchForm, runs, feedback, onRate, saving, onSav
</div>
</section>
+ {/* AI provider & model — who processes this commission */}
+ <section className="space-y-2 border-t border-port-border pt-4">
+ <h3 className="text-sm font-semibold text-gray-200">AI provider &amp; model</h3>
+ <p className="text-xs text-gray-500">
+ Which AI writes the treatment and production plan each time this commission runs. Leave on the
+ default to use your install&apos;s configured Creative Director assignment.
+ </p>
+ <AssignmentPicker
+ assignment={form.assignment}
+ onChange={(next) => patchForm(['assignment'], next)}
+ />
+ </section>
+
{/* Feedback conditioning */}
<section className="space-y-2 border-t border-port-border pt-4">
<h3 className="text-sm font-semibold text-gray-200">Feedback conditioning</h3>
@@ -644,6 +683,49 @@ function CommissionForm({ form, patchForm, runs, feedback, onRate, saving, onSav
);
}
+// AI provider/model picker for the commission's CD cognitive stages (treatment +
+// plan). Mirrors SeriesLlmPicker: fetches the provider list, drives the shared
+// ProviderModelSelector, and reports changes up to form state via `onChange`.
+// Only agent-harness (CLI/TUI) providers are offered — an API-type provider
+// injected into a CoS agent task trips the server's harness-boundary guard. The
+// empty option names the actual active provider so an unset pin makes it clear
+// what will process the run, rather than an opaque "default".
+function AssignmentPicker({ assignment, onChange }) {
+ const [providers, setProviders] = useState([]);
+ const [activeProviderId, setActiveProviderId] = useState(null);
+
+ useEffect(() => {
+ getProviders({ silent: true })
+ .then((data) => {
+ setProviders((data?.providers || []).filter(isProcessProvider));
+ setActiveProviderId(data?.activeProvider || null);
+ })
+ .catch(() => { /* dropdowns fall back to the "default provider" option */ });
+ }, []);
+
+ const providerLabel = (pid) => providers.find((p) => p.id === pid)?.name || pid || 'auto-resolved';
+ const availableModels = useMemo(() => {
+ const p = providers.find((x) => x.id === assignment.providerId);
+ return p?.models || [];
+ }, [providers, assignment.providerId]);
+
+ return (
+ <ProviderModelSelector
+ providers={providers}
+ selectedProviderId={assignment.providerId || ''}
+ selectedModel={assignment.model || ''}
+ availableModels={availableModels}
+ onProviderChange={(id) => onChange({ providerId: id || '', model: '' })}
+ onModelChange={(model) => onChange({ ...assignment, model: model || '' })}
+ label="Provider"
+ modelDisabled={availableModels.length === 0}
+ alwaysShowModel
+ emptyProviderOption={`Install default (${providerLabel(activeProviderId)})`}
+ emptyModelOption="Default model"
+ />
+ );
+}
+
// Per-run rate/annotate control (#2657, Phase 2). Thumbs submit immediately,
// carrying whatever note is in the field; the current rating (if any) is shown
// highlighted. Note state is local so typing doesn't re-render the whole form.
diff --git a/server/lib/creativeCommissionValidation.js b/server/lib/creativeCommissionValidation.js
index 2a14348231..391163cf52 100644
--- a/server/lib/creativeCommissionValidation.js
+++ b/server/lib/creativeCommissionValidation.js
@@ -114,6 +114,21 @@ export const creativeCommissionGenerationUpdateSchema = z.object({
targetDurationSeconds: z.number().int().min(5).max(600).optional(),
});
+// The LLM provider/model that PROCESSES the commission — i.e. the Creative
+// Director cognitive stages (treatment + production plan) the scheduled fire
+// runs as CoS agent tasks. `providerId`/`model` are the same shape the CD
+// project carries as `modelOverrides.{treatment,plan}` (a `{ providerId, model }`
+// pin); the scheduler fans this single pin onto both cognitive stages at fire
+// time. Both keys nullable/optional — an unset `providerId` means "inherit the
+// install's default AI Assignment" (preserving the pre-#2657 system-default
+// behavior). The picker only shows agent-harness (CLI/TUI) providers because an
+// API-type provider injected into an agent task trips the harness-boundary guard
+// (see agentBridge.js). Bounded to 120 chars like the CD project pin.
+export const creativeCommissionAssignmentSchema = z.object({
+ providerId: z.string().trim().max(120).nullable().optional(),
+ model: z.string().trim().max(120).nullable().optional(),
+});
+
export const creativeCommissionCreateSchema = z.object({
name: z.string().trim().min(1).max(COMMISSION_NAME_MAX),
enabled: z.boolean().default(true),
@@ -121,6 +136,9 @@ export const creativeCommissionCreateSchema = z.object({
brief: creativeCommissionBriefSchema,
schedule: creativeCommissionScheduleSchema,
generation: creativeCommissionGenerationSchema.optional(),
+ // Optional LLM provider/model pin for the CD cognitive stages. Absent → the
+ // install default AI Assignment processes the commission.
+ assignment: creativeCommissionAssignmentSchema.optional(),
// How many recent feedback reactions the directive builder folds into the next
// run's prompt (Phase 2 populates `feedback`; kept here so the field is stable
// and editable from creation). 0 disables conditioning.
@@ -175,5 +193,8 @@ export const creativeCommissionUpdateSchema = z.object({
brief: creativeCommissionBriefUpdateSchema.optional(),
schedule: creativeCommissionScheduleSchema.optional(),
generation: creativeCommissionGenerationUpdateSchema.optional(),
+ // Whole-object replace on the service side (a clear sends `{ providerId: null,
+ // model: null }`), so no separate no-defaults update variant is needed.
+ assignment: creativeCommissionAssignmentSchema.optional(),
feedbackWindow: z.number().int().min(0).max(50).optional(),
}).refine((p) => Object.keys(p).length > 0, { message: 'patch must include at least one field' });
diff --git a/server/services/creativeCommissions/scheduler.js b/server/services/creativeCommissions/scheduler.js
index deadf79eb7..78ec487e1e 100644
--- a/server/services/creativeCommissions/scheduler.js
+++ b/server/services/creativeCommissions/scheduler.js
@@ -199,6 +199,18 @@ export async function runScheduledCommission(commissionId) {
const directive = buildCommissionDirective(commission);
const gen = commission.generation || {};
+ // 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.
+ const pin = commission.assignment?.providerId
+ ? { providerId: commission.assignment.providerId, ...(commission.assignment.model ? { model: commission.assignment.model } : {}) }
+ : null;
+ const modelOverrides = pin ? { treatment: pin, plan: pin } : {};
// 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.
@@ -215,6 +227,7 @@ export async function runScheduledCommission(commissionId) {
targetDurationSeconds: gen.targetDurationSeconds || 10,
styleSpec: commission.brief?.styleSpec || '',
directive,
+ modelOverrides,
});
const run = await recordCommissionRun(commissionId, {
diff --git a/server/services/creativeCommissions/scheduler.test.js b/server/services/creativeCommissions/scheduler.test.js
index c6041a576c..57a28cff1e 100644
--- a/server/services/creativeCommissions/scheduler.test.js
+++ b/server/services/creativeCommissions/scheduler.test.js
@@ -141,6 +141,9 @@ 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' }));
@@ -152,6 +155,28 @@ describe('runScheduledCommission gates', () => {
expect(recordUsageMock).not.toHaveBeenCalled();
});
+ it('fans the LLM assignment pin onto both CD cognitive stages (treatment + plan)', async () => {
+ 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('does NOT surface when the fire is skipped (nothing was generated)', async () => {
creativeModeMock.mockReturnValue('off');
getCommissionMock.mockResolvedValue(videoCommission());
diff --git a/server/services/creativeCommissions/store.js b/server/services/creativeCommissions/store.js
index 1ac9e2b985..7819af0421 100644
--- a/server/services/creativeCommissions/store.js
+++ b/server/services/creativeCommissions/store.js
@@ -104,6 +104,16 @@ export function sanitizeCommission(raw) {
const brief = raw.brief && typeof raw.brief === 'object' ? raw.brief : {};
const schedule = raw.schedule && typeof raw.schedule === 'object' ? raw.schedule : {};
const generation = raw.generation && typeof raw.generation === 'object' ? raw.generation : {};
+ const assignment = raw.assignment && typeof raw.assignment === 'object' && !Array.isArray(raw.assignment)
+ ? raw.assignment : {};
+ // The LLM pin that processes the commission (CD treatment + plan stages). A
+ // model without a provider can't be resolved (the runtime keys on the provider
+ // first), so a provider-less pin drops the model too — matching
+ // normalizeModelOverrides so a stored assignment can't carry a dangling model.
+ const assignmentProviderId = isStr(assignment.providerId) && assignment.providerId.trim()
+ ? assignment.providerId.trim() : null;
+ const assignmentModel = assignmentProviderId && isStr(assignment.model) && assignment.model.trim()
+ ? assignment.model.trim() : null;
return {
id: raw.id,
name: isStr(raw.name) ? raw.name : 'Untitled Commission',
@@ -131,6 +141,12 @@ export function sanitizeCommission(raw) {
aspectRatio: isStr(generation.aspectRatio) ? generation.aspectRatio : '16:9',
targetDurationSeconds: Number.isInteger(generation.targetDurationSeconds) ? generation.targetDurationSeconds : 10,
},
+ // Which AI provider/model processes this commission's CD cognitive stages.
+ // `providerId: null` = inherit the install's default AI Assignment.
+ assignment: {
+ providerId: assignmentProviderId,
+ model: assignmentModel,
+ },
// Phase 2: deep-sanitize each reaction (drop ratingless/malformed entries)
// and cap history. Phase 1 records carry an empty array, so this is a no-op
// for them and preserves stored, already-id'd feedback idempotently.
@@ -316,6 +332,11 @@ export async function updateCommission(id, patch) {
} : current.brief,
schedule: patch.schedule ? { ...current.schedule, ...patch.schedule } : current.schedule,
generation: patch.generation ? { ...current.generation, ...patch.generation } : current.generation,
+ // Whole-object replace (not a deep merge): the client always sends the full
+ // { providerId, model } pin, and a clear sends both null. Merging would keep
+ // a stale `model` when the provider is cleared. sanitizeCommission then drops
+ // a provider-less model, so the stored pin can never dangle.
+ assignment: patch.assignment ? patch.assignment : current.assignment,
id,
createdAt: current.createdAt,
updatedAt: new Date().toISOString(),
diff --git a/server/services/creativeCommissions/store.test.js b/server/services/creativeCommissions/store.test.js
index 2440072373..a78fd6e49b 100644
--- a/server/services/creativeCommissions/store.test.js
+++ b/server/services/creativeCommissions/store.test.js
@@ -66,6 +66,21 @@ describe('sanitizeCommission', () => {
expect(rec.runs).toHaveLength(50);
expect(rec.runs[0].id).toBe('run-30');
});
+
+ it('defaults the LLM assignment to unset (install default)', () => {
+ const rec = sanitizeCommission({ id: 'c1' });
+ expect(rec.assignment).toEqual({ providerId: null, model: null });
+ });
+
+ it('normalizes and trims a set assignment pin', () => {
+ const rec = sanitizeCommission({ id: 'c1', assignment: { providerId: ' claude-tui ', model: ' sonnet ' } });
+ expect(rec.assignment).toEqual({ providerId: 'claude-tui', model: 'sonnet' });
+ });
+
+ it('drops a provider-less model so the pin can never dangle', () => {
+ const rec = sanitizeCommission({ id: 'c1', assignment: { model: 'sonnet' } });
+ expect(rec.assignment).toEqual({ providerId: null, model: null });
+ });
});
describe('assertValidSchedule', () => {
@@ -105,6 +120,22 @@ describe('updateCommission', () => {
expect(updated.createdAt).toBe(created.createdAt);
});
+ it('replaces the assignment pin on patch and clears it with a null provider', async () => {
+ const created = await createCommission(validInput());
+ const pinned = await updateCommission(created.id, { assignment: { providerId: 'claude-tui', model: 'sonnet' } });
+ expect(pinned.assignment).toEqual({ providerId: 'claude-tui', model: 'sonnet' });
+ // A clear (null provider) resets to the install default and drops the model.
+ const cleared = await updateCommission(created.id, { assignment: { providerId: null, model: null } });
+ expect(cleared.assignment).toEqual({ providerId: null, model: null });
+ });
+
+ it('preserves the assignment pin when a patch omits it', async () => {
+ const created = await createCommission(validInput());
+ await updateCommission(created.id, { assignment: { providerId: 'claude-tui', model: 'sonnet' } });
+ const updated = await updateCommission(created.id, { name: 'Renamed' });
+ expect(updated.assignment).toEqual({ providerId: 'claude-tui', model: 'sonnet' });
+ });
+
it('preserves brief.constraints when a partial brief patch omits them', async () => {
// Regression: the create-path brief schema defaults constraints/seedRefs, so
// a PATCH that omitted them used to wipe a stored universeId. The update-path