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
feat: Autonomous Creation Engine Phase 1 — recurring Creative Commissions (#2657)
[._.]/ Adam Eivye4bbc1490c62
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 68a29cdcd2..57371c7dfc 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -124,3 +124,4 @@- **[issue-2654] Lift the CoS actionable-insights fetch into `ChiefOfStaff.fetchData` so the banner refreshes for the whole staleness class.** `ActionableInsightsBanner` owned its own `/cos/actionable-insights` fetch on a 60s `useAutoRefetch` poll, decoupled from the parent's 30s task poll, so its server-derived counts (blocked, approvals, "N health issues") lagged any parent-owned data change until that poll. A prior fix bridged only the TasksTab mutation path via an `insightsRefreshKey` counter; socket-driven task changes, agent spawn/completion, and health checks stayed stale. Insights are now fetched inside `ChiefOfStaff.fetchData`'s `Promise.all` and passed down as an `insights` prop, making the banner presentational (it keeps only dismiss/expand/unblock UI state); its unblock path calls `onRefresh` up instead of owning a `refetch()`. The banner's counts refresh **only** through `fetchData`: the 30s poll, task mutations (TasksTab `onRefresh`), the unblock-up path, and agent spawn/completion (which already call `fetchData`). There is deliberately no on-demand "refresh just the insights" path, because `/cos/actionable-insights` runs a health check that **auto-restarts errored PM2 processes** (`server/services/cosHealthMonitor.js`) and re-emits `cos:health:check` — so refreshing from the `cos:health:check` socket handler would loop, and refreshing from the manual "Run Check" button would fire a second process-restart ~1s after the button's own check. Daemon/manual health changes therefore refresh the banner on the next `fetchData` poll (a 2× improvement over the retired 60s self-poll, and the cadence skew is gone). A failed/transient insights fetch (`null`) preserves the last-good array; a legitimately-empty `[]` clears the banner. Because that same insights call triggers a fresh server health check whose `cos:health:check` socket emit can land before `fetchData`'s own (pre-check) `getCosHealth` read resolves, `fetchData` keeps whichever health check is newer by `lastCheck` (`Date.parse`-normalized), and preserves the last-good health when its own read fails — instead of blanking a fresher socket-delivered result. Retires `insightsRefreshKey`, `refreshTasks`'s signal bump, the banner's `refreshKey` prop, its `didMountRef` skip-mount effect, and its `useAutoRefetch` self-poll. Tests cover the prop-driven render, null/empty gating, the unblock-up path, guards asserting neither the `cos:health:check` socket handler nor the manual button re-fetches insights (no loop, no second restart), and the stale/failed-read health-overwrite guards.- **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 persist in a machine-local `createCollectionStore` collection at `data/creative-commissions/` (schemaVersion 1, stamped by migration 191 + a `data.reference/` seed); 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 + migration tests cover cron composition, the feedback digest, the store CRUD/sanitizer, the autonomy/budget gates, the no-boot-generation guarantee, and the route contract.diff --git a/client/src/App.jsx b/client/src/App.jsxindex 6e44c26c53..6c9dfea9e5 100644--- a/client/src/App.jsx+++ b/client/src/App.jsx@@ -70,6 +70,7 @@ const VideoTimeline = lazyWithReload(() => import('./pages/VideoTimeline'));const VideoTimelineEditor = lazyWithReload(() => import('./pages/VideoTimelineEditor'));const CreativeDirector = lazyWithReload(() => import('./pages/CreativeDirector'));const CreativeDirectorDetail = lazyWithReload(() => import('./pages/CreativeDirectorDetail'));+const CreativeCommissions = lazyWithReload(() => import('./pages/CreativeCommissions'));const MusicVideo = lazyWithReload(() => import('./pages/MusicVideo'));const MoodBoards = lazyWithReload(() => import('./pages/MoodBoards'));const MoodBoardDetail = lazyWithReload(() => import('./pages/MoodBoardDetail'));@@ -345,6 +346,9 @@ export default function App() {<Route path="creative-director" element={<CreativeDirector />} /><Route path="creative-director/:id" element={<CreativeDirectorOverviewRedirect />} /><Route path="creative-director/:id/:tab" element={<CreativeDirectorDetail />} />+ <Route path="creative-commission" element={<CreativeCommissions />} />+ <Route path="creative-commission/new" element={<CreativeCommissions />} />+ <Route path="creative-commission/:id" element={<CreativeCommissions />} /><Route path="image-gen" element={<RedirectWithSearch to="/media/image" />} /><Route path="video-gen" element={<RedirectWithSearch to="/media/video" />} /><Route path="media-history" element={<RedirectWithSearch to="/media/history" />} />diff --git a/client/src/components/Layout.jsx b/client/src/components/Layout.jsxindex bcaaffe8dd..03df78ed0e 100644--- a/client/src/components/Layout.jsx+++ b/client/src/components/Layout.jsx@@ -218,6 +218,7 @@ const navItems = [children: [{ to: '/authors', label: 'Authors', icon: FilePen },{ to: '/catalog', label: 'Catalog', icon: Sparkles },+ { to: '/creative-commission', label: 'Creative Commissions', icon: CalendarClock },{ to: '/creative-director', label: 'Creative Director', icon: Clapperboard },{ to: '/pipeline/editorial-checks', label: 'Editorial Checks', icon: ListChecks },{ to: '/importer', label: 'Importer', icon: FileInput },diff --git a/client/src/pages/CreativeCommissions.jsx b/client/src/pages/CreativeCommissions.jsxnew file mode 100644index 0000000000..7493c3dbdb--- /dev/null+++ b/client/src/pages/CreativeCommissions.jsx@@ -0,0 +1,530 @@+/**+ * Creative Commissions page — the Autonomous Creation Engine index (#2657).+ *+ * A Creative Commission is a standing, recurring creative brief the server fires+ * on a schedule through the Creative Director directive pipeline. This page lists+ * every commission and hosts a deep-linked create/edit Drawer:+ * /creative-commission → index (list)+ * /creative-commission/new → create drawer+ * /creative-commission/:id → edit drawer (with run history)+ *+ * The URL is the source of truth for what's open, per the ID-based deep-linking+ * rule. Mutations update local state directly (no full refetch).+ */++import { useEffect, useMemo, useState, useCallback } from 'react';+import { useNavigate, useParams } from 'react-router-dom';+import { Plus, Sparkles, Trash2, Clock, Pause, Play } 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 {+ listCommissions, createCommission, updateCommission, deleteCommission,+} from '../services/api';++const WEEKDAYS = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];++// Human-readable cadence summary for the list + drawer header.+function describeSchedule(schedule) {+ if (!schedule) return 'No schedule';+ const { kind, atLocalTime, weekday, weekdaysOnly, cron } = schedule;+ if (kind === 'CUSTOM') return `Custom · ${cron || '—'}`;+ if (kind === 'WEEKLY') return `Weekly · ${WEEKDAYS[weekday] ?? '—'} at ${atLocalTime || '—'}`;+ if (kind === 'DAILY') return `Daily${weekdaysOnly ? ' (weekdays)' : ''} at ${atLocalTime || '—'}`;+ return kind || 'No schedule';+}++const blankForm = () => ({+ name: '',+ enabled: true,+ targetAbility: 'video',+ brief: { intent: '', genre: '', styleSpec: '' },+ schedule: { kind: 'DAILY', atLocalTime: '02:00', weekday: 0, weekdaysOnly: false, cron: '' },+ generation: { quality: 'standard', aspectRatio: '16:9', targetDurationSeconds: 10 },+});++// Map a stored record → editable form state (fills gaps so inputs stay controlled).+function toForm(c) {+ return {+ name: c.name || '',+ enabled: c.enabled !== false,+ targetAbility: c.targetAbility || 'video',+ brief: {+ intent: c.brief?.intent || '',+ genre: c.brief?.genre || '',+ styleSpec: c.brief?.styleSpec || '',+ },+ schedule: {+ kind: c.schedule?.kind || 'DAILY',+ atLocalTime: c.schedule?.atLocalTime || '02:00',+ weekday: Number.isInteger(c.schedule?.weekday) ? c.schedule.weekday : 0,+ weekdaysOnly: c.schedule?.weekdaysOnly === true,+ cron: c.schedule?.cron || '',+ },+ generation: {+ quality: c.generation?.quality || 'standard',+ aspectRatio: c.generation?.aspectRatio || '16:9',+ targetDurationSeconds: c.generation?.targetDurationSeconds || 10,+ },+ };+}++// Build the API payload from form state, dropping fields the schedule kind doesn't use.+function toPayload(form) {+ const s = { kind: form.schedule.kind };+ if (form.schedule.kind === 'CUSTOM') {+ s.cron = form.schedule.cron.trim();+ } else {+ s.atLocalTime = form.schedule.atLocalTime;+ if (form.schedule.kind === 'WEEKLY') s.weekday = Number(form.schedule.weekday);+ if (form.schedule.kind === 'DAILY') s.weekdaysOnly = !!form.schedule.weekdaysOnly;+ }+ return {+ name: form.name.trim(),+ enabled: !!form.enabled,+ targetAbility: form.targetAbility,+ brief: {+ intent: form.brief.intent.trim(),+ genre: form.brief.genre.trim() || null,+ styleSpec: form.brief.styleSpec,+ },+ schedule: s,+ generation: {+ quality: form.generation.quality,+ aspectRatio: form.generation.aspectRatio,+ targetDurationSeconds: Number(form.generation.targetDurationSeconds),+ },+ };+}++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';+const labelCls = 'block text-xs font-medium text-gray-400 mb-1';++export default function CreativeCommissions() {+ const navigate = useNavigate();+ const { id } = useParams();+ const [commissions, setCommissions] = useState([]);+ const [loading, setLoading] = useState(true);+ const [form, setForm] = useState(blankForm());+ const [saving, setSaving] = useState(false);+ const { isConfirming, requestDelete, cancelDelete, confirmDelete } = useConfirmDelete();++ const drawerOpen = id != null; // '/new' or an id+ const creating = id === 'new';+ const editing = drawerOpen && !creating ? commissions.find((c) => c.id === id) : null;++ useEffect(() => {+ let cancelled = false;+ listCommissions({ silent: true })+ .then((data) => { if (!cancelled) setCommissions(Array.isArray(data) ? data : []); })+ .catch(() => { if (!cancelled) toast.error('Failed to load commissions'); })+ .finally(() => { if (!cancelled) setLoading(false); });+ return () => { cancelled = true; };+ }, []);++ // Sync the form to the deep-linked record whenever the drawer target changes.+ useEffect(() => {+ if (creating) setForm(blankForm());+ else if (editing) setForm(toForm(editing));+ }, [id, creating, editing]);++ const closeDrawer = useCallback(() => navigate('/creative-commission'), [navigate]);++ const patchForm = (path, value) => setForm((prev) => {+ const next = { ...prev };+ if (path.length === 1) next[path[0]] = value;+ else { next[path[0]] = { ...prev[path[0]], [path[1]]: value }; }+ return next;+ });++ const handleSave = async () => {+ if (!form.name.trim()) { toast.error('Name is required'); return; }+ if (!form.brief.intent.trim()) { toast.error('Brief intent is required'); return; }+ const payload = toPayload(form);+ setSaving(true);+ try {+ if (creating) {+ const created = await createCommission(payload, { silent: true });+ setCommissions((prev) => [...prev, created]);+ toast.success('Commission created');+ } else if (editing) {+ const updated = await updateCommission(editing.id, payload, { silent: true });+ setCommissions((prev) => prev.map((c) => (c.id === updated.id ? updated : c)));+ toast.success('Commission updated');+ }+ navigate('/creative-commission');+ } catch (err) {+ toast.error(err?.message || 'Save failed');+ } finally {+ setSaving(false);+ }+ };++ const handleDelete = async (commission) => {+ const prev = commissions;+ setCommissions((cur) => cur.filter((c) => c.id !== commission.id));+ try {+ await deleteCommission(commission.id, { silent: true });+ toast.success('Commission deleted');+ if (id === commission.id) navigate('/creative-commission');+ } catch (err) {+ setCommissions(prev); // rollback+ toast.error(err?.message || 'Delete failed');+ }+ };++ const toggleEnabled = async (commission) => {+ const next = !commission.enabled;+ setCommissions((prev) => prev.map((c) => (c.id === commission.id ? { ...c, enabled: next } : c)));+ try {+ await updateCommission(commission.id, { enabled: next }, { silent: true });+ } catch (err) {+ setCommissions((prev) => prev.map((c) => (c.id === commission.id ? { ...c, enabled: commission.enabled } : c)));+ toast.error(err?.message || 'Update failed');+ }+ };++ const sorted = useMemo(+ () => [...commissions].sort((a, b) => (a.name || '').localeCompare(b.name || '')),+ [commissions],+ );++ // Deep link to a deleted/unknown id → not-found fallback (URL is source of truth).+ const notFound = drawerOpen && !creating && !editing && !loading;++ return (+ <div className="max-w-5xl mx-auto">+ <div className="flex items-center justify-between mb-6">+ <div className="flex items-center gap-3">+ <Sparkles className="w-6 h-6 text-port-accent" />+ <div>+ <h1 className="text-xl font-semibold text-gray-100">Creative Commissions</h1>+ <p className="text-sm text-gray-500">Standing briefs that create on a schedule and steer by your taste</p>+ </div>+ </div>+ <button+ onClick={() => navigate('/creative-commission/new')}+ className="flex items-center gap-2 bg-port-accent hover:bg-blue-600 text-white px-3 py-2 rounded text-sm font-medium"+ >+ <Plus className="w-4 h-4" /> New Commission+ </button>+ </div>++ {loading ? (+ <div className="text-gray-500 text-sm">Loading…</div>+ ) : sorted.length === 0 ? (+ <div className="border border-dashed border-port-border rounded-lg p-10 text-center">+ <Sparkles className="w-8 h-8 text-gray-600 mx-auto mb-3" />+ <p className="text-gray-400 mb-1">No commissions yet</p>+ <p className="text-gray-600 text-sm mb-4">+ Create a standing brief like “every night at 2am, make me something surreal” and it runs unattended.+ </p>+ <button+ onClick={() => navigate('/creative-commission/new')}+ className="inline-flex items-center gap-2 bg-port-accent hover:bg-blue-600 text-white px-3 py-2 rounded text-sm font-medium"+ >+ <Plus className="w-4 h-4" /> New Commission+ </button>+ </div>+ ) : (+ <div className="space-y-2">+ {sorted.map((c) => (+ <div+ key={c.id}+ className="flex items-center gap-3 bg-port-card border border-port-border rounded-lg p-3 hover:border-port-accent/50 transition-colors"+ >+ <button+ className="flex-1 text-left min-w-0"+ onClick={() => navigate(`/creative-commission/${encodeURIComponent(c.id)}`)}+ >+ <div className="flex items-center gap-2">+ <span className="text-gray-100 font-medium truncate">{c.name}</span>+ <span className={`text-[10px] uppercase px-1.5 py-0.5 rounded ${c.enabled ? 'bg-port-success/20 text-port-success' : 'bg-gray-700 text-gray-400'}`}>+ {c.enabled ? 'Active' : 'Paused'}+ </span>+ <span className="text-[10px] uppercase px-1.5 py-0.5 rounded bg-port-accent/20 text-port-accent">{c.targetAbility}</span>+ </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>+ {Array.isArray(c.runs) && c.runs.length > 0 && (+ <span>Last run {timeAgo(c.runs[c.runs.length - 1].ranAt)}</span>+ )}+ </div>+ </button>+ <button+ onClick={() => toggleEnabled(c)}+ title={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" />}+ </button>+ {isConfirming(c.id) ? (+ <ConfirmButtonPair+ prompt="Delete?"+ ariaLabel={`Confirm delete commission ${c.name}`}+ onConfirm={() => confirmDelete(() => handleDelete(c))}+ onCancel={cancelDelete}+ />+ ) : (+ <button+ type="button"+ onClick={() => requestDelete(c.id)}+ title="Delete commission"+ aria-label={`Delete commission ${c.name}`}+ className="p-2 text-gray-400 hover:text-port-error"+ >+ <Trash2 className="w-4 h-4" />+ </button>+ )}+ </div>+ ))}+ </div>+ )}++ {notFound && (+ <div className="fixed inset-0 z-40 flex items-center justify-center bg-black/50" onClick={closeDrawer}>+ <div className="bg-port-card border border-port-border rounded-lg p-6 text-center" onClick={(e) => e.stopPropagation()}>+ <p className="text-gray-300 mb-3">That commission no longer exists.</p>+ <button onClick={closeDrawer} className="bg-port-accent text-white px-3 py-1.5 rounded text-sm">Back to list</button>+ </div>+ </div>+ )}++ <Drawer+ open={drawerOpen && (creating || !!editing)}+ onClose={closeDrawer}+ title={creating ? 'New Commission' : 'Edit Commission'}+ subtitle={!creating && editing ? editing.name : undefined}+ size="md"+ closeOnEsc={false}+ closeOnBackdrop={false}+ >+ <CommissionForm+ form={form}+ patchForm={patchForm}+ runs={editing?.runs || []}+ saving={saving}+ onSave={handleSave}+ onCancel={closeDrawer}+ />+ </Drawer>+ </div>+ );+}++function CommissionForm({ form, patchForm, runs, saving, onSave, onCancel }) {+ return (+ <div className="space-y-5">+ {/* Identity */}+ <section className="space-y-3">+ <div>+ <label className={labelCls} htmlFor="commission-name">Name</label>+ <input+ id="commission-name"+ className={inputCls}+ value={form.name}+ maxLength={200}+ onChange={(e) => patchForm(['name'], e.target.value)}+ placeholder="Nightly Surreal"+ />+ </div>+ <label className="flex items-center gap-2 text-sm text-gray-300">+ <input+ type="checkbox"+ checked={form.enabled}+ onChange={(e) => patchForm(['enabled'], e.target.checked)}+ />+ Enabled (fires on schedule)+ </label>+ </section>++ {/* Brief */}+ <section className="space-y-3 border-t border-port-border pt-4">+ <h3 className="text-sm font-semibold text-gray-200">Brief</h3>+ <div>+ <label className={labelCls} htmlFor="commission-intent">Intent</label>+ <textarea+ id="commission-intent"+ className={`${inputCls} min-h-[70px]`}+ value={form.brief.intent}+ maxLength={2000}+ onChange={(e) => patchForm(['brief', 'intent'], e.target.value)}+ placeholder="something surreal, dreamlike, unsettlingly beautiful"+ />+ </div>+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">+ <div>+ <label className={labelCls} htmlFor="commission-genre">Genre (optional)</label>+ <input+ id="commission-genre"+ className={inputCls}+ value={form.brief.genre}+ maxLength={120}+ onChange={(e) => patchForm(['brief', 'genre'], e.target.value)}+ placeholder="surrealism"+ />+ </div>+ <div>+ <label className={labelCls} htmlFor="commission-style">Style notes (optional)</label>+ <input+ id="commission-style"+ className={inputCls}+ value={form.brief.styleSpec}+ maxLength={5000}+ onChange={(e) => patchForm(['brief', 'styleSpec'], e.target.value)}+ placeholder="flat color, Magritte"+ />+ </div>+ </div>+ </section>++ {/* Schedule */}+ <section className="space-y-3 border-t border-port-border pt-4">+ <h3 className="text-sm font-semibold text-gray-200">Schedule</h3>+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">+ <div>+ <label className={labelCls} htmlFor="commission-kind">Cadence</label>+ <select+ id="commission-kind"+ className={inputCls}+ value={form.schedule.kind}+ onChange={(e) => patchForm(['schedule', 'kind'], e.target.value)}+ >+ <option value="DAILY">Daily</option>+ <option value="WEEKLY">Weekly</option>+ <option value="CUSTOM">Custom (cron)</option>+ </select>+ </div>+ {form.schedule.kind !== 'CUSTOM' && (+ <div>+ <label className={labelCls} htmlFor="commission-time">Time (24h, local)</label>+ <input+ id="commission-time"+ type="time"+ className={inputCls}+ value={form.schedule.atLocalTime}+ onChange={(e) => patchForm(['schedule', 'atLocalTime'], e.target.value)}+ />+ </div>+ )}+ {form.schedule.kind === 'WEEKLY' && (+ <div>+ <label className={labelCls} htmlFor="commission-weekday">Day of week</label>+ <select+ id="commission-weekday"+ className={inputCls}+ value={form.schedule.weekday}+ onChange={(e) => patchForm(['schedule', 'weekday'], Number(e.target.value))}+ >+ {WEEKDAYS.map((d, i) => <option key={i} value={i}>{d}</option>)}+ </select>+ </div>+ )}+ {form.schedule.kind === 'CUSTOM' && (+ <div>+ <label className={labelCls} htmlFor="commission-cron">Cron (5-field)</label>+ <input+ id="commission-cron"+ className={inputCls}+ value={form.schedule.cron}+ maxLength={120}+ onChange={(e) => patchForm(['schedule', 'cron'], e.target.value)}+ placeholder="0 2 * * *"+ />+ </div>+ )}+ </div>+ {form.schedule.kind === 'DAILY' && (+ <label className="flex items-center gap-2 text-sm text-gray-300">+ <input+ type="checkbox"+ checked={form.schedule.weekdaysOnly}+ onChange={(e) => patchForm(['schedule', 'weekdaysOnly'], e.target.checked)}+ />+ Weekdays only (Mon–Fri)+ </label>+ )}+ <p className="text-xs text-gray-500">{describeSchedule(form.schedule)}</p>+ </section>++ {/* Generation */}+ <section className="space-y-3 border-t border-port-border pt-4">+ <h3 className="text-sm font-semibold text-gray-200">Generation (video)</h3>+ <div className="grid grid-cols-1 sm:grid-cols-3 gap-3">+ <div>+ <label className={labelCls} htmlFor="commission-quality">Quality</label>+ <select+ id="commission-quality"+ className={inputCls}+ value={form.generation.quality}+ onChange={(e) => patchForm(['generation', 'quality'], e.target.value)}+ >+ <option value="draft">Draft</option>+ <option value="standard">Standard</option>+ <option value="high">High</option>+ </select>+ </div>+ <div>+ <label className={labelCls} htmlFor="commission-aspect">Aspect ratio</label>+ <select+ id="commission-aspect"+ className={inputCls}+ value={form.generation.aspectRatio}+ onChange={(e) => patchForm(['generation', 'aspectRatio'], e.target.value)}+ >+ <option value="16:9">16:9</option>+ <option value="9:16">9:16</option>+ <option value="1:1">1:1</option>+ </select>+ </div>+ <div>+ <label className={labelCls} htmlFor="commission-duration">Duration (sec)</label>+ <input+ id="commission-duration"+ type="number"+ min={5}+ max={600}+ className={inputCls}+ value={form.generation.targetDurationSeconds}+ onChange={(e) => patchForm(['generation', 'targetDurationSeconds'], e.target.value)}+ />+ </div>+ </div>+ </section>++ {/* Run history (edit only) */}+ {runs.length > 0 && (+ <section className="space-y-2 border-t border-port-border pt-4">+ <h3 className="text-sm font-semibold text-gray-200">Run history</h3>+ <div className="space-y-1 max-h-52 overflow-y-auto">+ {[...runs].reverse().map((r) => (+ <div key={r.id} className="flex items-center justify-between text-xs bg-port-bg border border-port-border rounded px-2 py-1.5">+ <span className="text-gray-400">{timeAgo(r.ranAt)}</span>+ <span className={+ r.status === 'started' ? 'text-port-accent'+ : r.status === 'skipped' ? 'text-port-warning'+ : r.status === 'failed' ? 'text-port-error' : 'text-gray-400'+ }>+ {r.status}{r.reason ? ` · ${r.reason}` : ''}{r.error ? ` · ${r.error}` : ''}+ </span>+ </div>+ ))}+ </div>+ </section>+ )}++ <div className="flex items-center gap-2 border-t border-port-border pt-4">+ <button+ onClick={onSave}+ disabled={saving}+ className="bg-port-accent hover:bg-blue-600 disabled:opacity-50 text-white px-4 py-2 rounded text-sm font-medium"+ >+ {saving ? 'Saving…' : 'Save'}+ </button>+ <button onClick={onCancel} className="text-gray-400 hover:text-gray-200 px-4 py-2 text-sm">Cancel</button>+ </div>+ </div>+ );+}diff --git a/client/src/services/README.md b/client/src/services/README.mdindex 9e775132af..956e098e37 100644--- a/client/src/services/README.md+++ b/client/src/services/README.md@@ -93,6 +93,7 @@ toasts on throw). **Custom catch ⇒ `silent: true`** — otherwise toasts fire| `apiMedia.js` | Screenshots + media assets. || `apiMediaJobs.js` | Media generation job tracking. || `apiCreativeDirector.js` | Creative Director (video production). |+| `apiCreativeCommission.js` | Creative Commissions (Autonomous Creation Engine — standing recurring briefs). || `apiMusicVideo.js` | Music Video projects + scene board + audio analysis. || `apiPipeline.js` | Pipeline (issues + stages + canon). || `apiUniverseBuilder.js` | Universe Builder (generate + edit + commit). |diff --git a/client/src/services/api.js b/client/src/services/api.jsindex 03acda67c3..592594db7c 100644--- a/client/src/services/api.js+++ b/client/src/services/api.js@@ -67,6 +67,7 @@ export * from './apiSongbook.js';export * from './apiPeerSync.js';export * from './apiSyncReview.js';export * from './apiCreativeDirector.js';+export * from './apiCreativeCommission.js';export * from './apiMusicVideo.js';export * from './apiMoodBoard.js';export * from './apiImporter.js';diff --git a/client/src/services/apiCreativeCommission.js b/client/src/services/apiCreativeCommission.jsnew file mode 100644index 0000000000..2962fd3dc2--- /dev/null+++ b/client/src/services/apiCreativeCommission.js@@ -0,0 +1,32 @@+import { request } from './apiCore.js';++// Client API for the Autonomous Creation Engine (#2657) — standing, recurring+// creative briefs the server fires on a schedule through the Creative Director+// directive pipeline.+//+// `options` lets a caller that owns its own error toast pass `{ silent: true }`+// so request() doesn't also toast — see CLAUDE.md "Custom catch ⇒ silent: true".++export const listCommissions = (options = {}) => request('/creative-commission', options);++export const getCommission = (id, options = {}) =>+ request(`/creative-commission/${encodeURIComponent(id)}`, options);++export const createCommission = (data, options = {}) => request('/creative-commission', {+ method: 'POST',+ body: JSON.stringify(data),+ ...options,+});++export const updateCommission = (id, patch, options = {}) =>+ request(`/creative-commission/${encodeURIComponent(id)}`, {+ method: 'PATCH',+ body: JSON.stringify(patch),+ ...options,+ });++export const deleteCommission = (id, options = {}) =>+ request(`/creative-commission/${encodeURIComponent(id)}`, {+ method: 'DELETE',+ ...options,+ });diff --git a/data.reference/creative-commissions/index.json b/data.reference/creative-commissions/index.jsonnew file mode 100644index 0000000000..ea34df52e9--- /dev/null+++ b/data.reference/creative-commissions/index.json@@ -0,0 +1,5 @@+{+ "schemaVersion": 1,+ "type": "creative-commissions",+ "config": {}+}diff --git a/scripts/migrations/191-creative-commissions.js b/scripts/migrations/191-creative-commissions.jsnew file mode 100644index 0000000000..d5292958fc--- /dev/null+++ b/scripts/migrations/191-creative-commissions.js@@ -0,0 +1,56 @@+/**+ * Stamp the Creative Commission collection's type-level index at schemaVersion 1+ * (issue #2657, Autonomous Creation Engine — Phase 1).+ *+ * The commissions live in a `createCollectionStore` collection at+ * `data/creative-commissions/`. A fresh collection has no records and no+ * `index.json`; the boot verifier tolerates a missing index (treats it as a+ * fresh install), and the store stamps the index on its first write. But to keep+ * the on-disk shape explicit and let a future schemaVersion bump detect existing+ * v1 data, this migration creates the type index up front if it's absent.+ *+ * There is NO legacy monolith to split — commissions are a brand-new record kind+ * — so this is a pure stamp, not a data transform.+ *+ * Idempotent: a second run finds an index at version ≥ 1 and writes nothing.+ * Forward-only: never downgrades an index the code already advanced past 1.+ */++import { readFile, writeFile, mkdir } from 'fs/promises';+import { join } from 'path';++const TYPE = 'creative-commissions';+const SCHEMA_VERSION = 1;++const readJson = async (path) => {+ const raw = await readFile(path, 'utf-8').catch((err) => {+ if (err.code === 'ENOENT') return null;+ throw err;+ });+ if (raw == null) return null;+ try { return JSON.parse(raw); } catch { return null; }+};++export async function up({ rootDir }) {+ const dir = join(rootDir, 'data', TYPE);+ const indexPath = join(dir, 'index.json');+ const existing = await readJson(indexPath);++ if (existing && typeof existing.schemaVersion === 'number' && existing.schemaVersion >= SCHEMA_VERSION) {+ console.log(`✅ creative-commissions: type index already at v${existing.schemaVersion} — no changes`);+ return { migrated: false };+ }++ await mkdir(dir, { recursive: true });+ const index = {+ schemaVersion: SCHEMA_VERSION,+ type: TYPE,+ updatedAt: new Date().toISOString(),+ config: {},+ };+ await writeFile(indexPath, JSON.stringify(index, null, 2) + '\n');+ console.log(`🎬 creative-commissions: stamped type index → v${SCHEMA_VERSION}`);+ return { migrated: true };+}++export default { up };diff --git a/scripts/migrations/191-creative-commissions.test.js b/scripts/migrations/191-creative-commissions.test.jsnew file mode 100644index 0000000000..12531c53be--- /dev/null+++ b/scripts/migrations/191-creative-commissions.test.js@@ -0,0 +1,41 @@+import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import { mkdtemp, rm, readFile, mkdir, writeFile } from 'fs/promises';+import { tmpdir } from 'os';+import { join } from 'path';+import { up } from './191-creative-commissions.js';++let rootDir;++beforeEach(async () => { rootDir = await mkdtemp(join(tmpdir(), 'portos-mig191-')); });+afterEach(async () => { await rm(rootDir, { recursive: true, force: true }); });++const indexPath = () => join(rootDir, 'data', 'creative-commissions', 'index.json');++describe('migration 191 — creative-commissions type index stamp', () => {+ it('creates the type index at schemaVersion 1 on a fresh install', async () => {+ const res = await up({ rootDir });+ expect(res.migrated).toBe(true);+ const idx = JSON.parse(await readFile(indexPath(), 'utf-8'));+ expect(idx.schemaVersion).toBe(1);+ expect(idx.type).toBe('creative-commissions');+ expect(idx.config).toEqual({});+ });++ it('is idempotent — a second run writes nothing', async () => {+ await up({ rootDir });+ const first = await readFile(indexPath(), 'utf-8');+ const res = await up({ rootDir });+ expect(res.migrated).toBe(false);+ expect(await readFile(indexPath(), 'utf-8')).toBe(first);+ });++ it('does not downgrade an index already past v1', async () => {+ await mkdir(join(rootDir, 'data', 'creative-commissions'), { recursive: true });+ await writeFile(indexPath(), JSON.stringify({ schemaVersion: 3, type: 'creative-commissions', config: { x: 1 } }));+ const res = await up({ rootDir });+ expect(res.migrated).toBe(false);+ const idx = JSON.parse(await readFile(indexPath(), 'utf-8'));+ expect(idx.schemaVersion).toBe(3);+ expect(idx.config).toEqual({ x: 1 });+ });+});diff --git a/server/index.js b/server/index.jsindex cbacc3ae28..2d22237a39 100644--- a/server/index.js+++ b/server/index.js@@ -117,6 +117,7 @@ import videoDownloadRoutes from './routes/videoDownload.js';import videoTimelineRoutes from './routes/videoTimeline.js';import mediaJobsRoutes from './routes/mediaJobs.js';import creativeDirectorRoutes from './routes/creativeDirector.js';+import creativeCommissionRoutes from './routes/creativeCommissions.js';import musicVideoRoutes from './routes/musicVideo.js';import moodBoardRoutes from './routes/moodBoard.js';import privacyRoutes from './routes/privacy.js';@@ -177,6 +178,7 @@ import * as cos from './services/cos.js';import { startBackupScheduler } from './services/backupScheduler.js';import { startPrivacyRecheckScheduler } from './services/privacyRecheckScheduler.js';import { startSeriesAutopilotScheduler } from './services/seriesAutopilotScheduler.js';+import { startCommissionScheduler } from './services/creativeCommissions/scheduler.js';import { startCitySnapshotScheduler } from './services/citySnapshotScheduler.js';import { startImessageScheduler } from './services/imessageScheduler.js';import { startSignalScheduler } from './services/signalScheduler.js';@@ -209,6 +211,7 @@ import { verifyCollectionVersions } from './lib/collectionStore.js';import { conflictJournalStore } from './lib/conflictJournal.js';import { universeStore } from './services/universeBuilder.js';import { seriesStore } from './services/pipeline/series.js';+import { commissionStore } from './services/creativeCommissions/store.js';import { issueStore } from './services/pipeline/issues.js';import { storyBuilderStore } from './services/storyBuilder.js';import { writersRoomStore } from './services/writersRoom/store.js';@@ -279,7 +282,7 @@ await runMigrations({ rootDir: resolveInstallRoot(join(__dirname, '..')) }).catc// but DO NOT crash the server. PortOS is single-user (CLAUDE.md "Security// Model"); a hard exit on startup is worse than a noisy log the user can act// on. Returns per-store statuses for downstream telemetry; we discard them.-await verifyCollectionVersions([universeStore(), seriesStore(), issueStore(), conflictJournalStore(), storyBuilderStore(), mediaCollectionStore(), loraDatasetStore, liOutcomesStore()]).catch(err => {+await verifyCollectionVersions([universeStore(), seriesStore(), issueStore(), conflictJournalStore(), storyBuilderStore(), mediaCollectionStore(), loraDatasetStore, liOutcomesStore(), commissionStore()]).catch(err => {console.error(`❌ Collection version check failed at startup: ${err?.stack ?? err}`);});@@ -547,6 +550,7 @@ app.use('/api/devtools/video-download', videoDownloadRoutes);app.use('/api/video-timeline', videoTimelineRoutes);app.use('/api/media-jobs', mediaJobsRoutes);app.use('/api/creative-director', creativeDirectorRoutes);+app.use('/api/creative-commission', creativeCommissionRoutes);app.use('/api/music-video', musicVideoRoutes);app.use('/api/mood-boards', moodBoardRoutes);app.use('/api/privacy', privacyRoutes);@@ -638,6 +642,11 @@ startPrivacyRecheckScheduler().catch(err => console.error(`❌ Privacy recheck s// Autopilot. Each scheduled run still passes through the cos autonomy gate +// daily budget (sanctioned scheduled-automation exception) (#2174).startSeriesAutopilotScheduler().catch(err => console.error(`❌ Series Autopilot scheduler init failed: ${err.message}`));+// Autonomous Creation Engine (#2657) — arm a cron per enabled Creative+// Commission. Boot only ARMS timers; nothing fires until a cadence elapses, and+// each fire gates on creative autonomy `execute` + the daily cos budget (so an+// `off`/`dry-run` install generates nothing). Sanctioned scheduled-automation.+startCommissionScheduler().catch(err => console.error(`❌ Creative Commission scheduler init failed: ${err.message}`));// Initialize CyberCity snapshot scheduler — records periodic city-state frames// for the historical timeline scrubber (issue #877).startCitySnapshotScheduler().catch(err => console.error(`❌ City snapshot scheduler init failed: ${err.message}`));diff --git a/server/lib/README.md b/server/lib/README.mdindex 6536bb0557..4801f454b3 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -30,6 +30,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `brainValidation.js` | Brain/memory route schemas (search, ingest, edit). || `catalogValidation.js` | Creative ingredients catalog route schemas (scraps, ingredients, links, relations, tags, revisions, sync envelope). || `cosValidation.js` | Chief-of-Staff task/job/loop/learning schemas, the Review-Loop reviewer vocabulary + helpers (`normalizeReviewers`/`buildReviewWithArgs`), the Code-Review settings slice, and the task-metadata sanitizer. |+| `creativeCommissionValidation.js` | Creative Commission (Autonomous Creation Engine) create/update + brief/schedule/generation schemas. || `creativeDirectorValidation.js` | Creative Director project/treatment/scene + Create-Suite importer schemas. || `digitalTwinValidation.js` | Digital twin document/category schemas. || `genomeValidation.js` | Genome upload + search schemas. |diff --git a/server/lib/creativeCommissionValidation.js b/server/lib/creativeCommissionValidation.jsnew file mode 100644index 0000000000..70f94153a4--- /dev/null+++ b/server/lib/creativeCommissionValidation.js@@ -0,0 +1,122 @@+import { z } from 'zod';++// =============================================================================+// CREATIVE COMMISSION SCHEMAS (Autonomous Creation Engine — #2657, Phase 1)+// =============================================================================+// A CreativeCommission is a *standing, recurring creative brief* that fires on a+// schedule and drives the Creative Director's directive pipeline unattended. It+// is the sanctioned scheduled-automation exception to the "no cold LLM calls"+// policy: it only ever runs because the user created it, and it never generates+// at boot (the scheduler arms a cron; nothing fires until the cadence elapses).+//+// This module is a leaf (like creativeDirectorValidation.js): it must NOT import+// back from validation.js — validation.js re-exports it, and ESM hoists+// `export * from`, so a read-back here would hit the TDZ. It also stays free of+// heavy service imports (eventScheduler, etc.) so pulling it into a mocked test+// suite doesn't drag the scheduler graph along. The authoritative cron-validity+// check (isValidCron) lives in the service layer, not here.++// Phase 1 supports `video` only. The enum is deliberately narrow so a user can't+// create a commission that silently never runs — Phase 3/4 widen it (image,+// universe, series, story, writers-room, music) alongside the ability adapter.+export const CREATIVE_COMMISSION_ABILITIES = Object.freeze(['video']);++// Schedule cadence kinds. DAILY/WEEKLY are composed into a cron by the service;+// CUSTOM carries a raw 5-field cron the service validates via isValidCron.+export const CREATIVE_COMMISSION_SCHEDULE_KINDS = Object.freeze(['DAILY', 'WEEKLY', 'CUSTOM']);++export const CREATIVE_COMMISSION_QUALITIES = Object.freeze(['draft', 'standard', 'high']);+export const CREATIVE_COMMISSION_ASPECT_RATIOS = Object.freeze(['16:9', '9:16', '1:1']);++export const COMMISSION_NAME_MAX = 200;+export const COMMISSION_INTENT_MAX = 2000;++// The brief the commission steers by. `intent` is the free-text core ("something+// surreal, dreamlike, unsettlingly beautiful"); `genre`/`category` are optional+// lightweight tags (a real taxonomy arrives in Phase 5); `styleSpec` maps to the+// CD project's styleSpec; `constraints` scopes the run to a universe/series.+export const creativeCommissionBriefSchema = z.object({+ intent: z.string().trim().min(1).max(COMMISSION_INTENT_MAX),+ genre: z.string().trim().max(120).nullable().optional(),+ category: z.string().trim().max(120).nullable().optional(),+ styleSpec: z.string().max(5000).default(''),+ constraints: z.object({+ universeId: z.string().max(120).nullable().optional(),+ seriesId: z.string().max(120).nullable().optional(),+ }).default({}),+ // Catalog ingredient ids to seed future generations from (Phase 3+ folds these+ // into the CD cast). Accepted now so the record shape is forward-stable.+ seedRefs: z.array(z.string().trim().max(64)).max(50).default([]),+});++// A cadence descriptor. Per-kind fields are validated in `superRefine` so a+// DAILY schedule can't omit its time and a CUSTOM one can't omit its cron. The+// resulting cron string (and its final isValidCron check) is computed in the+// service; here we only assert the shape is internally consistent.+export const creativeCommissionScheduleSchema = z.object({+ kind: z.enum(CREATIVE_COMMISSION_SCHEDULE_KINDS),+ // 'HH:MM' 24h local time for DAILY/WEEKLY.+ atLocalTime: z.string().regex(/^([01]\d|2[0-3]):[0-5]\d$/, 'must be HH:MM (24h)').optional(),+ // 0 (Sunday) .. 6 (Saturday) for WEEKLY.+ weekday: z.number().int().min(0).max(6).nullable().optional(),+ // DAILY only: restrict to Mon–Fri.+ weekdaysOnly: z.boolean().optional().default(false),+ // CUSTOM only: a raw 5-field cron. Loosely bounded here; isValidCron is the+ // authority (service layer).+ cron: z.string().trim().max(120).optional(),+ // IANA tz; null/absent falls back to the user's configured timezone at fire.+ timezone: z.string().max(64).nullable().optional(),+}).superRefine((val, ctx) => {+ if (val.kind === 'DAILY' && !val.atLocalTime) {+ ctx.addIssue({ code: z.ZodIssueCode.custom, path: ['atLocalTime'], message: 'DAILY schedule requires atLocalTime' });+ }+ if (val.kind === 'WEEKLY') {+ if (!val.atLocalTime) ctx.addIssue({ code: z.ZodIssueCode.custom, path: ['atLocalTime'], message: 'WEEKLY schedule requires atLocalTime' });+ if (val.weekday == null) ctx.addIssue({ code: z.ZodIssueCode.custom, path: ['weekday'], message: 'WEEKLY schedule requires weekday (0–6)' });+ }+ if (val.kind === 'CUSTOM' && !val.cron) {+ ctx.addIssue({ code: z.ZodIssueCode.custom, path: ['cron'], message: 'CUSTOM schedule requires a cron expression' });+ }+});++// Render knobs handed to the CD project the commission mints each fire. `model`+// is the CD video modelId (an LTX variant); absent → the install's default video+// model at fire time.+// No object-level `.default({})` here: it would inject a `generation: {}` key+// even when the caller omits generation, which makes an empty PATCH body parse+// non-empty (defeating the update schema's "at least one field" refine) and+// forces every update to rewrite generation. sanitizeCommission fills the+// generation defaults instead; the per-field defaults still apply when the+// object IS present but partial.+export const creativeCommissionGenerationSchema = z.object({+ model: z.string().trim().max(64).nullable().optional(),+ quality: z.enum(CREATIVE_COMMISSION_QUALITIES).default('standard'),+ aspectRatio: z.enum(CREATIVE_COMMISSION_ASPECT_RATIOS).default('16:9'),+ targetDurationSeconds: z.number().int().min(5).max(600).default(10),+});++export const creativeCommissionCreateSchema = z.object({+ name: z.string().trim().min(1).max(COMMISSION_NAME_MAX),+ enabled: z.boolean().default(true),+ targetAbility: z.enum(CREATIVE_COMMISSION_ABILITIES).default('video'),+ brief: creativeCommissionBriefSchema,+ schedule: creativeCommissionScheduleSchema,+ generation: creativeCommissionGenerationSchema.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.+ feedbackWindow: z.number().int().min(0).max(50).default(5),+});++// PATCH: every field optional; at least one must be present. `.partial()` on a+// ZodEffects (the schedule uses superRefine) isn't available, so we rebuild the+// object rather than call `.partial()` on the whole create schema.+export const creativeCommissionUpdateSchema = z.object({+ name: z.string().trim().min(1).max(COMMISSION_NAME_MAX).optional(),+ enabled: z.boolean().optional(),+ targetAbility: z.enum(CREATIVE_COMMISSION_ABILITIES).optional(),+ brief: creativeCommissionBriefSchema.optional(),+ schedule: creativeCommissionScheduleSchema.optional(),+ generation: creativeCommissionGenerationSchema.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/lib/index.js b/server/lib/index.jsindex f0e6440e4c..1f6bab50b5 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -21,6 +21,7 @@ export * as appleHealthValidation from './appleHealthValidation.js';export * as brainValidation from './brainValidation.js';export * as catalogValidation from './catalogValidation.js';export * as cosValidation from './cosValidation.js';+export * as creativeCommissionValidation from './creativeCommissionValidation.js';export * as creativeDirectorValidation from './creativeDirectorValidation.js';export * as digitalTwinValidation from './digitalTwinValidation.js';export * as genomeValidation from './genomeValidation.js';diff --git a/server/lib/navManifest.js b/server/lib/navManifest.jsindex 528bcfc26b..da5c573213 100644--- a/server/lib/navManifest.js+++ b/server/lib/navManifest.js@@ -20,6 +20,7 @@ export const NAV_COMMANDS = [{ id: 'nav.media.annotate', path: '/media/annotate', label: 'Annotate', section: 'Create', aliases: ['annotate', 'media-annotate', 'sketch', 'draw-over', 'markup'], keywords: ['annotation', 'sketch', 'draw', 'markup', 'scribble', 'label', 'canvas', 'overlay', 'stroke'] },{ id: 'nav.media.collections', path: '/media/collections', label: 'Collections', section: 'Create', aliases: ['collections', 'media-collections', 'stacks', 'projects'], keywords: ['bucket', 'group', 'project', 'album', 'organize'] },{ id: 'nav.create.creative-director', path: '/creative-director', label: 'Creative Director', section: 'Create', aliases: ['creative-director', 'creative', 'director', 'producer', 'orchestrator', 'long-form', 'episode'], keywords: ['story', 'episode', 'narrative', 'agent', 'auto-video', 'long-form', 'directive', 'production plan', 'plan board', 'orchestrator', 'studio', 'producer'] },+ { id: 'nav.create.creative-commission', path: '/creative-commission', label: 'Creative Commissions', section: 'Create', aliases: ['creative-commission', 'commissions', 'commission', 'creation-engine', 'autonomous-creation', 'standing-brief', 'recurring-brief'], keywords: ['schedule', 'recurring', 'nightly', 'brief', 'autonomous', 'creation engine', 'cron', 'feedback', 'taste', 'standing commission', 'auto-generate'] },{ id: 'nav.media.music-video', path: '/media/music-video', label: 'Music Video', section: 'Create', aliases: ['music-video', 'musicvideo', 'music video', 'mv', 'sync-to-beat'], keywords: ['music', 'beat', 'sync', 'audio-reactive', 'director', 'scene board', 'tempo', 'choreography'] },{ id: 'nav.create.mood-boards', path: '/mood-boards', label: 'Mood Boards', section: 'Create', aliases: ['mood-boards', 'mood-board', 'moodboard', 'mood', 'inspiration', 'references'], keywords: ['inspiration', 'reference', 'pin', 'visual', 'canvas', 'collect', 'pinboard', 'palette', 'ideas'] },{ id: 'nav.media.timeline', path: '/media/timeline', label: 'Timeline', section: 'Create', aliases: ['timeline', 'video-timeline', 'editor'], keywords: ['edit', 'trim', 'composite', 'stitch', 'cut', 'compose'] },diff --git a/server/lib/navManifest.test.js b/server/lib/navManifest.test.jsindex 3dca30bb20..d69a6a179b 100644--- a/server/lib/navManifest.test.js+++ b/server/lib/navManifest.test.js@@ -314,6 +314,7 @@ const NAV_COVERAGE_OPT_OUT = new Map([['/login', 'auth gate — surfaced only when settings.secrets.auth is enabled, reached via 401 redirect'],['/songbook/import', 'import-song form, reached via the "Import" button on /songbook'],['/universes/new', 'create-mode sentinel for the Universe Builder editor'],+ ['/creative-commission/new', 'create-mode sentinel for the Creative Commission drawer'],]);// Element wrappers that forward to another route rather than render a page. Adiff --git a/server/lib/validation.js b/server/lib/validation.jsindex 737938ca1d..d04664c178 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -929,6 +929,7 @@ export const videoDownloadSchema = z.object({// (e.g. `emptyToUndefined`) live in zodCompat.js.export * from './peerSyncValidation.js';export * from './creativeDirectorValidation.js';+export * from './creativeCommissionValidation.js';export * from './musicVideoValidation.js';export * from './storyBuilderValidation.js';export * from './moodBoardValidation.js';diff --git a/server/routes/creativeCommissions.js b/server/routes/creativeCommissions.jsnew file mode 100644index 0000000000..96ff7ff0a6--- /dev/null+++ b/server/routes/creativeCommissions.js@@ -0,0 +1,69 @@+/**+ * Creative Commission routes — REST CRUD for the Autonomous Creation Engine+ * (#2657, Phase 1). A commission is a standing, recurring creative brief the+ * scheduler fires on a cadence. After any mutation we re-sync the scheduler so a+ * newly enabled/edited/deleted commission's cron takes effect immediately.+ *+ * No try/catch — errors bubble to the centralized error middleware. Service+ * errors carry a `code` mapped to an HTTP status via createServiceErrorMapper.+ */++import { Router } from 'express';+import { asyncHandler, createServiceErrorMapper } from '../lib/errorHandler.js';+import {+ validateRequest,+ creativeCommissionCreateSchema,+ creativeCommissionUpdateSchema,+ isPaginationRequested,+ paginateArray,+} from '../lib/validation.js';+import * as svc from '../services/creativeCommissions/store.js';+import { syncCommissionSchedules } from '../services/creativeCommissions/scheduler.js';++const router = Router();++const SERVICE_ERROR_STATUS = {+ [svc.ERR_NOT_FOUND]: 404,+ [svc.ERR_VALIDATION]: 400,+};+const mapServiceError = createServiceErrorMapper(SERVICE_ERROR_STATUS);++// Fire-and-forget scheduler re-sync after a mutation — the HTTP response doesn't+// wait on it, and a re-sync failure must not fail the request.+function resyncScheduler() {+ syncCommissionSchedules().catch((err) =>+ console.error(`❌ Creative commission schedule re-sync failed: ${err.message}`));+}++router.get('/', asyncHandler(async (req, res) => {+ const items = await svc.listCommissions();+ if (!isPaginationRequested(req.query)) return res.json(items);+ res.json(paginateArray(items, req.query, { defaultLimit: 50, maxLimit: 500 }));+}));++router.post('/', asyncHandler(async (req, res) => {+ const body = validateRequest(creativeCommissionCreateSchema, req.body ?? {});+ const created = await svc.createCommission(body).catch((err) => { throw mapServiceError(err); });+ resyncScheduler();+ res.status(201).json(created);+}));++router.get('/:id', asyncHandler(async (req, res) => {+ const rec = await svc.getCommission(req.params.id).catch((err) => { throw mapServiceError(err); });+ res.json(rec);+}));++router.patch('/:id', asyncHandler(async (req, res) => {+ const body = validateRequest(creativeCommissionUpdateSchema, req.body ?? {});+ const rec = await svc.updateCommission(req.params.id, body).catch((err) => { throw mapServiceError(err); });+ resyncScheduler();+ res.json(rec);+}));++router.delete('/:id', asyncHandler(async (req, res) => {+ const r = await svc.deleteCommission(req.params.id).catch((err) => { throw mapServiceError(err); });+ resyncScheduler();+ res.json(r);+}));++export default router;diff --git a/server/routes/creativeCommissions.test.js b/server/routes/creativeCommissions.test.jsnew file mode 100644index 0000000000..6f3723c768--- /dev/null+++ b/server/routes/creativeCommissions.test.js@@ -0,0 +1,119 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import express from 'express';+import { request } from '../lib/testHelper.js';+import { errorMiddleware } from '../lib/errorHandler.js';++// Service + scheduler are mocked so the route test asserts exact call args+// without touching the collectionStore or arming real crons.+const svc = {+ ERR_NOT_FOUND: 'NOT_FOUND',+ ERR_VALIDATION: 'VALIDATION_ERROR',+ listCommissions: vi.fn(),+ getCommission: vi.fn(),+ createCommission: vi.fn(),+ updateCommission: vi.fn(),+ deleteCommission: vi.fn(),+};+vi.mock('../services/creativeCommissions/store.js', () => svc);+const syncMock = vi.fn(() => Promise.resolve());+vi.mock('../services/creativeCommissions/scheduler.js', () => ({ syncCommissionSchedules: syncMock }));++const routes = (await import('./creativeCommissions.js')).default;++const buildApp = () => {+ const app = express();+ app.use(express.json());+ app.use('/api/creative-commission', routes);+ app.use(errorMiddleware);+ return app;+};++const validBody = () => ({+ name: 'Nightly Surreal',+ brief: { intent: 'something surreal, dreamlike' },+ schedule: { kind: 'DAILY', atLocalTime: '02:00' },+});++beforeEach(() => vi.clearAllMocks());++describe('GET /api/creative-commission', () => {+ it('returns the full list by default', async () => {+ svc.listCommissions.mockResolvedValue([{ id: 'commission-1' }]);+ const res = await request(buildApp()).get('/api/creative-commission');+ expect(res.status).toBe(200);+ expect(res.body).toEqual([{ id: 'commission-1' }]);+ });+});++describe('POST /api/creative-commission', () => {+ it('validates + creates + re-syncs the scheduler', async () => {+ svc.createCommission.mockResolvedValue({ id: 'commission-1', name: 'Nightly Surreal' });+ const res = await request(buildApp()).post('/api/creative-commission').send(validBody());+ expect(res.status).toBe(201);+ expect(svc.createCommission).toHaveBeenCalledWith(expect.objectContaining({+ name: 'Nightly Surreal',+ targetAbility: 'video',+ brief: expect.objectContaining({ intent: 'something surreal, dreamlike' }),+ schedule: expect.objectContaining({ kind: 'DAILY', atLocalTime: '02:00' }),+ }));+ expect(syncMock).toHaveBeenCalledTimes(1);+ });++ it('rejects a body missing the brief with 400 (service not called)', async () => {+ const res = await request(buildApp()).post('/api/creative-commission').send({ name: 'x', schedule: { kind: 'DAILY', atLocalTime: '02:00' } });+ expect(res.status).toBe(400);+ expect(svc.createCommission).not.toHaveBeenCalled();+ });++ it('rejects a DAILY schedule missing atLocalTime with 400', async () => {+ const res = await request(buildApp()).post('/api/creative-commission').send({ ...validBody(), schedule: { kind: 'DAILY' } });+ expect(res.status).toBe(400);+ expect(svc.createCommission).not.toHaveBeenCalled();+ });++ it('rejects an unsupported target ability with 400 (Phase 1 is video-only)', async () => {+ const res = await request(buildApp()).post('/api/creative-commission').send({ ...validBody(), targetAbility: 'music' });+ expect(res.status).toBe(400);+ expect(svc.createCommission).not.toHaveBeenCalled();+ });++ it('maps a service VALIDATION_ERROR to 400', async () => {+ svc.createCommission.mockRejectedValue(Object.assign(new Error('bad cron'), { code: 'VALIDATION_ERROR' }));+ const res = await request(buildApp()).post('/api/creative-commission').send(validBody());+ expect(res.status).toBe(400);+ });+});++describe('GET /api/creative-commission/:id', () => {+ it('maps a service NOT_FOUND to 404', async () => {+ svc.getCommission.mockRejectedValue(Object.assign(new Error('nope'), { code: 'NOT_FOUND' }));+ const res = await request(buildApp()).get('/api/creative-commission/missing');+ expect(res.status).toBe(404);+ });+});++describe('PATCH /api/creative-commission/:id', () => {+ it('updates + re-syncs', async () => {+ svc.updateCommission.mockResolvedValue({ id: 'commission-1', enabled: false });+ const res = await request(buildApp()).patch('/api/creative-commission/commission-1').send({ enabled: false });+ expect(res.status).toBe(200);+ expect(svc.updateCommission).toHaveBeenCalledWith('commission-1', { enabled: false });+ expect(syncMock).toHaveBeenCalledTimes(1);+ });++ it('rejects an empty patch with 400', async () => {+ const res = await request(buildApp()).patch('/api/creative-commission/commission-1').send({});+ expect(res.status).toBe(400);+ expect(svc.updateCommission).not.toHaveBeenCalled();+ });+});++describe('DELETE /api/creative-commission/:id', () => {+ it('deletes + re-syncs', async () => {+ svc.deleteCommission.mockResolvedValue({ id: 'commission-1', deleted: true });+ const res = await request(buildApp()).delete('/api/creative-commission/commission-1');+ expect(res.status).toBe(200);+ expect(svc.deleteCommission).toHaveBeenCalledWith('commission-1');+ expect(syncMock).toHaveBeenCalledTimes(1);+ });+});diff --git a/server/services/creativeCommissions/directive.js b/server/services/creativeCommissions/directive.jsnew file mode 100644index 0000000000..7bf946057f--- /dev/null+++ b/server/services/creativeCommissions/directive.js@@ -0,0 +1,102 @@+/**+ * Creative Commission — pure directive + cron composition (#2657, Phase 1).+ *+ * These are side-effect-free helpers: `commissionToCron` turns a schedule+ * descriptor into a 5-field cron string, and `buildCommissionDirective` composes+ * the CD directive (goal + deliverables + constraints) the planner turns into a+ * plan. Kept pure and dependency-free so they're trivially unit-testable and can+ * be imported anywhere without dragging the scheduler graph along. The+ * authoritative cron-VALIDITY check (isValidCron) lives in the scheduler/service.+ */++/**+ * Compose a 5-field cron (`minute hour dayOfMonth month dayOfWeek`) from a+ * commission schedule. Returns the raw string, or null when the schedule is+ * missing the fields its kind requires (the caller then rejects it). Does NOT+ * assert cron validity — that's isValidCron's job at the service boundary.+ */+export function commissionToCron(schedule) {+ if (!schedule || typeof schedule !== 'object') return null;+ const { kind, atLocalTime, weekday, weekdaysOnly, cron } = schedule;++ if (kind === 'CUSTOM') {+ return typeof cron === 'string' && cron.trim() ? cron.trim() : null;+ }++ // DAILY / WEEKLY compose from HH:MM.+ const m = typeof atLocalTime === 'string' ? atLocalTime.match(/^([01]\d|2[0-3]):([0-5]\d)$/) : null;+ if (!m) return null;+ const hour = String(Number(m[1]));+ const minute = String(Number(m[2]));++ if (kind === 'DAILY') {+ return `${minute} ${hour} * * ${weekdaysOnly ? '1-5' : '*'}`;+ }+ if (kind === 'WEEKLY') {+ if (!Number.isInteger(weekday) || weekday < 0 || weekday > 6) return null;+ return `${minute} ${hour} * * ${weekday}`;+ }+ return null;+}++/**+ * Render the last N feedback reactions into a compact steering digest the+ * planner can act on. Phase 2 populates `commission.feedback`; Phase 1 always+ * yields an empty digest (no feedback exists yet), but the fold is implemented+ * now so Phase 2 only needs the rate/annotate surface — not a directive change.+ *+ * Distinguishes "no feedback" (returns '') from "feedback with empty notes"+ * (still surfaces the up/down tallies) per the absent-vs-empty rule.+ */+export function renderFeedbackDigest(feedback, windowSize = 5) {+ if (!Array.isArray(feedback) || feedback.length === 0 || windowSize <= 0) return '';+ const recent = feedback.slice(-windowSize);+ const likes = [];+ const dislikes = [];+ for (const f of recent) {+ if (!f || typeof f !== 'object') continue;+ const note = typeof f.note === 'string' ? f.note.trim() : '';+ const up = f.rating === 'up' || (typeof f.rating === 'number' && f.rating > 0);+ const down = f.rating === 'down' || (typeof f.rating === 'number' && f.rating < 0);+ if (up && note) likes.push(note);+ else if (down && note) dislikes.push(note);+ else if (up) likes.push('(liked, no note)');+ else if (down) dislikes.push('(disliked, no note)');+ }+ if (likes.length === 0 && dislikes.length === 0) return '';+ const parts = [];+ if (likes.length) parts.push(`Recent likes: ${likes.join('; ')}.`);+ if (dislikes.length) parts.push(`Recent dislikes: ${dislikes.join('; ')}.`);+ parts.push('Steer toward the likes and away from the dislikes.');+ return parts.join(' ');+}++/**+ * Build the CD directive for a commission's next fire. Folds the brief (intent ++ * genre/category/style) and the accumulated feedback digest into `goal`, and+ * maps the brief's constraints (universe/series) onto the directive constraints.+ * Shape matches `creativeDirectorDirectiveSchema` (goal/deliverables/constraints)+ * so it round-trips straight into `createProject({ directive })`.+ */+export function buildCommissionDirective(commission) {+ const brief = commission?.brief || {};+ const ability = commission?.targetAbility || 'video';+ const lines = [];+ lines.push(`Create a ${ability} piece. ${String(brief.intent || '').trim()}`.trim());+ if (brief.genre) lines.push(`Genre: ${brief.genre}.`);+ if (brief.category) lines.push(`Category: ${brief.category}.`);+ if (brief.styleSpec) lines.push(`Style: ${brief.styleSpec}.`);++ const digest = renderFeedbackDigest(commission?.feedback, commission?.feedbackWindow ?? 5);+ if (digest) lines.push(digest);++ const constraints = {};+ if (brief.constraints?.universeId) constraints.universeId = brief.constraints.universeId;+ if (brief.constraints?.seriesId) constraints.seriesId = brief.constraints.seriesId;++ return {+ goal: lines.join(' '),+ deliverables: [`One ${ability} artifact matching the brief`],+ constraints,+ };+}diff --git a/server/services/creativeCommissions/directive.test.js b/server/services/creativeCommissions/directive.test.jsnew file mode 100644index 0000000000..db944c0532--- /dev/null+++ b/server/services/creativeCommissions/directive.test.js@@ -0,0 +1,114 @@+import { describe, it, expect } from 'vitest';+import { commissionToCron, renderFeedbackDigest, buildCommissionDirective } from './directive.js';++describe('commissionToCron', () => {+ it('composes a DAILY cron from HH:MM', () => {+ expect(commissionToCron({ kind: 'DAILY', atLocalTime: '02:00' })).toBe('0 2 * * *');+ expect(commissionToCron({ kind: 'DAILY', atLocalTime: '23:45' })).toBe('45 23 * * *');+ });++ it('restricts DAILY to weekdays when weekdaysOnly', () => {+ expect(commissionToCron({ kind: 'DAILY', atLocalTime: '09:30', weekdaysOnly: true })).toBe('30 9 * * 1-5');+ });++ it('composes a WEEKLY cron with a weekday', () => {+ expect(commissionToCron({ kind: 'WEEKLY', atLocalTime: '06:15', weekday: 0 })).toBe('15 6 * * 0');+ expect(commissionToCron({ kind: 'WEEKLY', atLocalTime: '18:00', weekday: 6 })).toBe('0 18 * * 6');+ });++ it('passes through a CUSTOM cron (trimmed)', () => {+ expect(commissionToCron({ kind: 'CUSTOM', cron: ' */15 * * * * ' })).toBe('*/15 * * * *');+ });++ it('returns null when required fields are missing', () => {+ expect(commissionToCron(null)).toBeNull();+ expect(commissionToCron({ kind: 'DAILY' })).toBeNull();+ expect(commissionToCron({ kind: 'DAILY', atLocalTime: '99:99' })).toBeNull();+ expect(commissionToCron({ kind: 'WEEKLY', atLocalTime: '02:00' })).toBeNull(); // no weekday+ expect(commissionToCron({ kind: 'WEEKLY', atLocalTime: '02:00', weekday: 7 })).toBeNull(); // out of range+ expect(commissionToCron({ kind: 'CUSTOM' })).toBeNull();+ expect(commissionToCron({ kind: 'NOPE', atLocalTime: '02:00' })).toBeNull();+ });+});++describe('renderFeedbackDigest', () => {+ it('returns empty string when there is no feedback (absent, not empty)', () => {+ expect(renderFeedbackDigest(undefined)).toBe('');+ expect(renderFeedbackDigest([])).toBe('');+ expect(renderFeedbackDigest(null, 5)).toBe('');+ });++ it('folds likes and dislikes with notes into a steering digest', () => {+ const digest = renderFeedbackDigest([+ { rating: 'up', note: 'dreamlike, Magritte-flat color' },+ { rating: 'down', note: 'horror, gore' },+ ]);+ expect(digest).toContain('Recent likes: dreamlike, Magritte-flat color.');+ expect(digest).toContain('Recent dislikes: horror, gore.');+ expect(digest).toContain('Steer toward the likes');+ });++ it('surfaces up/down tallies even when notes are empty (empty note is not absent feedback)', () => {+ const digest = renderFeedbackDigest([{ rating: 'up' }, { rating: 'down', note: '' }]);+ expect(digest).toContain('(liked, no note)');+ expect(digest).toContain('(disliked, no note)');+ });++ it('honors the window size (only the last N reactions)', () => {+ const feedback = [+ { rating: 'down', note: 'old dislike' },+ { rating: 'up', note: 'recent like' },+ ];+ const digest = renderFeedbackDigest(feedback, 1);+ expect(digest).toContain('recent like');+ expect(digest).not.toContain('old dislike');+ });++ it('returns empty string when windowSize is 0 (conditioning disabled)', () => {+ expect(renderFeedbackDigest([{ rating: 'up', note: 'x' }], 0)).toBe('');+ });++ it('treats numeric ratings as up (>0) / down (<0)', () => {+ const digest = renderFeedbackDigest([{ rating: 1, note: 'plus' }, { rating: -1, note: 'minus' }]);+ expect(digest).toContain('Recent likes: plus.');+ expect(digest).toContain('Recent dislikes: minus.');+ });+});++describe('buildCommissionDirective', () => {+ it('composes goal + deliverables + constraints from the brief', () => {+ const directive = buildCommissionDirective({+ name: 'Nightly Surreal',+ targetAbility: 'video',+ brief: {+ intent: 'something surreal, dreamlike, unsettlingly beautiful',+ genre: 'surrealism',+ styleSpec: 'flat color, Magritte',+ constraints: { universeId: 'u-123' },+ },+ feedbackWindow: 5,+ });+ expect(directive.goal).toContain('Create a video piece.');+ expect(directive.goal).toContain('something surreal');+ expect(directive.goal).toContain('Genre: surrealism.');+ expect(directive.goal).toContain('Style: flat color, Magritte.');+ expect(directive.deliverables).toEqual(['One video artifact matching the brief']);+ expect(directive.constraints).toEqual({ universeId: 'u-123' });+ });++ it('folds recent feedback into the goal', () => {+ const directive = buildCommissionDirective({+ targetAbility: 'video',+ brief: { intent: 'surreal' },+ feedback: [{ rating: 'down', note: 'less horror' }, { rating: 'up', note: 'more Magritte' }],+ feedbackWindow: 5,+ });+ expect(directive.goal).toContain('Recent likes: more Magritte.');+ expect(directive.goal).toContain('Recent dislikes: less horror.');+ });++ it('omits absent constraints', () => {+ const directive = buildCommissionDirective({ targetAbility: 'video', brief: { intent: 'x' } });+ expect(directive.constraints).toEqual({});+ });+});diff --git a/server/services/creativeCommissions/scheduler.js b/server/services/creativeCommissions/scheduler.jsnew file mode 100644index 0000000000..77ad7f5e84--- /dev/null+++ b/server/services/creativeCommissions/scheduler.js@@ -0,0 +1,175 @@+/**+ * Creative Commission scheduler (#2657, Phase 1 — Autonomous Creation Engine).+ *+ * A per-commission cron that fires the Creative Director's directive pipeline on+ * the user's cadence. Modeled directly on `seriesAutopilotScheduler.js`:+ * - one eventScheduler cron per enabled commission (id namespace below),+ * - a `registered` set + `lastSignature` guard so re-syncs are cheap no-ops,+ * - a fire handler that runs OUTSIDE the Express request lifecycle (whole body+ * in try/catch — a throw here would crash the process),+ * - re-reads the commission + autonomy config on every fire (only the cron is+ * captured at registration).+ *+ * Cold-bootstrap compliance (CLAUDE.md AI Provider Usage Policy): a commission is+ * a user-configured scheduled automation — the sanctioned exception. `start…()`+ * only ARMS crons; nothing fires until the cadence elapses. The fire handler+ * additionally gates on creative autonomy mode === 'execute' AND the daily cos+ * budget, so an `off`/`dry-run` install (or an over-budget one) generates nothing+ * and simply records a skipped run.+ *+ * Commissions are machine-local (not federated), so — unlike series autopilot —+ * the scheduler re-syncs when the commission STORE changes (routes call+ * `syncCommissionSchedules` after a mutation), not on settings:updated.+ */++import { schedule, cancel, isValidCron } from '../eventScheduler.js';+import { getUserTimezone } from '../../lib/timezone.js';+import { listCommissions, recordCommissionRun } from './store.js';+import { commissionToCron, buildCommissionDirective } from './directive.js';++const eventId = (commissionId) => `creative-commission-${commissionId}`;+const registered = new Set();+let lastSignature = null;++/**+ * Enabled commissions whose schedule composes into a cron the scheduler honors.+ * Pure over the passed-in list.+ */+export function activeCommissions(commissions) {+ const out = [];+ for (const c of commissions || []) {+ if (!c || c.enabled === false || !c.id) continue;+ const cron = commissionToCron(c.schedule);+ if (!cron || !isValidCron(cron)) continue;+ out.push({ id: c.id, cron, timezone: c.schedule?.timezone || null });+ }+ return out;+}++function signatureOf(active, fallbackTz) {+ return JSON.stringify({+ tz: fallbackTz || null,+ s: active.map((e) => [e.id, e.cron, e.timezone ?? null]),+ });+}++function registerSchedule(entry, timezone) {+ schedule({+ id: eventId(entry.id),+ type: 'cron',+ cron: entry.cron,+ timezone: entry.timezone || timezone,+ handler: () => runScheduledCommission(entry.id),+ metadata: { source: 'creativeCommissionScheduler', commissionId: entry.id },+ });+ registered.add(entry.id);+}++/**+ * (Re)sync the registered crons to the current commission set. Idempotent and+ * safe at boot and after every store mutation. The signature guard makes an+ * unrelated re-sync a cheap no-op.+ */+export async function syncCommissionSchedules(commissions) {+ const list = commissions || await listCommissions().catch(() => []);+ const active = activeCommissions(list);+ const timezone = await getUserTimezone().catch(() => 'UTC');++ const signature = signatureOf(active, timezone);+ if (signature === lastSignature) return active.length;+ lastSignature = signature;++ const activeIds = new Set(active.map((e) => e.id));+ for (const id of [...registered]) {+ if (!activeIds.has(id)) { cancel(eventId(id)); registered.delete(id); }+ }+ for (const entry of active) registerSchedule(entry, timezone);+ return active.length;+}++/** Boot entry point — arms crons for existing commissions. Fires nothing now. */+export async function startCommissionScheduler() {+ return syncCommissionSchedules();+}++/** Cancel every registered cron (test teardown / shutdown). */+export function stopCommissionScheduler() {+ for (const id of [...registered]) { cancel(eventId(id)); registered.delete(id); }+ lastSignature = null;+}++/**+ * The fire handler. Runs outside the Express request lifecycle, so the whole+ * body is wrapped — a throw here would crash Node. Re-reads the commission and+ * the creative autonomy config every fire; gates on execute-mode + budget; then+ * mints a directive-driven CD project and nudges the advance loop (which runs+ * each plan step through the gated `dispatchCreativeTool`).+ */+export async function runScheduledCommission(commissionId) {+ try {+ const { getCommission } = await import('./store.js');+ const commission = await getCommission(commissionId).catch(() => null);+ if (!commission || commission.enabled === false) return;++ const cron = commissionToCron(commission.schedule);+ if (!cron || !isValidCron(cron)) return; // schedule became invalid since registration++ // Gate on creative autonomy mode + daily cos budget BEFORE spawning anything+ // (the planner is itself an LLM call) — honors "off ⇒ no generation" and the+ // no-cold-LLM policy.+ const [{ loadState }, { getCreativeAutonomyMode }, { getDomainBudgetStatus }] = await Promise.all([+ import('../cosState.js'),+ import('../../lib/domainAutonomy.js'),+ import('../domainUsage.js'),+ ]);+ const state = await loadState().catch(() => ({ config: {} }));+ const mode = getCreativeAutonomyMode(state.config);+ if (mode !== 'execute') {+ await recordCommissionRun(commissionId, { status: 'skipped', reason: `autonomy-${mode}` }).catch(() => {});+ return;+ }+ const budget = await getDomainBudgetStatus('cos').catch(() => ({ withinBudget: true }));+ if (!budget.withinBudget) {+ await recordCommissionRun(commissionId, { status: 'skipped', reason: 'budget' }).catch(() => {});+ return;+ }++ // Phase 1 supports video only. A non-video commission can't be created via+ // the UI (schema restricts the enum), but a hand-edited record is possible.+ if (commission.targetAbility !== 'video') {+ await recordCommissionRun(commissionId, { status: 'skipped', reason: 'unsupported-ability' }).catch(() => {});+ return;+ }++ const [{ createProject }, { advanceAfterPlanStepSettled }, { defaultVideoModelId }] = await Promise.all([+ import('../creativeDirector/local.js'),+ import('../creativeDirector/planAdvance.js'),+ import('../videoGen/local.js'),+ ]);++ const directive = buildCommissionDirective(commission);+ const gen = commission.generation || {};+ const project = await createProject({+ name: `${commission.name} — ${new Date().toISOString().slice(0, 10)}`,+ aspectRatio: gen.aspectRatio || '16:9',+ quality: gen.quality || 'standard',+ modelId: gen.model || defaultVideoModelId(),+ targetDurationSeconds: gen.targetDurationSeconds || 10,+ styleSpec: commission.brief?.styleSpec || '',+ directive,+ });++ await recordCommissionRun(commissionId, {+ status: 'started',+ projectId: project.id,+ promptUsed: directive.goal,+ }).catch(() => {});++ // Kick the planner → plan → execute loop. Fire-and-forget within this+ // try/catch (already outside the request lifecycle).+ await advanceAfterPlanStepSettled(project.id);+ } catch (err) {+ console.error(`❌ Creative commission ${commissionId} fire failed: ${err?.message || err}`);+ await recordCommissionRun(commissionId, { status: 'failed', error: err?.message || String(err) }).catch(() => {});+ }+}diff --git a/server/services/creativeCommissions/scheduler.test.js b/server/services/creativeCommissions/scheduler.test.jsnew file mode 100644index 0000000000..b4adc30828--- /dev/null+++ b/server/services/creativeCommissions/scheduler.test.js@@ -0,0 +1,146 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';++// eventScheduler is mocked so no real timers arm and isValidCron is deterministic.+const scheduleMock = vi.fn();+const cancelMock = vi.fn();+vi.mock('../eventScheduler.js', () => ({+ schedule: (...a) => scheduleMock(...a),+ cancel: (...a) => cancelMock(...a),+ isValidCron: (expr) => typeof expr === 'string' && expr.trim().split(/\s+/).length === 5,+}));++vi.mock('../../lib/timezone.js', () => ({ getUserTimezone: async () => 'UTC' }));++const listCommissionsMock = vi.fn();+const getCommissionMock = vi.fn();+const recordRunMock = vi.fn(async () => ({}));+vi.mock('./store.js', () => ({+ listCommissions: (...a) => listCommissionsMock(...a),+ getCommission: (...a) => getCommissionMock(...a),+ recordCommissionRun: (...a) => recordRunMock(...a),+}));++// CD graph + autonomy/budget mocks (dynamic-imported inside the fire handler).+const createProjectMock = vi.fn(async () => ({ id: 'cd-xyz' }));+const advanceMock = vi.fn(async () => {});+vi.mock('../creativeDirector/local.js', () => ({ createProject: (...a) => createProjectMock(...a) }));+vi.mock('../creativeDirector/planAdvance.js', () => ({ advanceAfterPlanStepSettled: (...a) => advanceMock(...a) }));+vi.mock('../videoGen/local.js', () => ({ defaultVideoModelId: () => 'ltx-default' }));++const loadStateMock = vi.fn(async () => ({ config: {} }));+vi.mock('../cosState.js', () => ({ loadState: (...a) => loadStateMock(...a) }));+const creativeModeMock = vi.fn(() => 'execute');+vi.mock('../../lib/domainAutonomy.js', () => ({ getCreativeAutonomyMode: (...a) => creativeModeMock(...a) }));+const budgetMock = vi.fn(async () => ({ withinBudget: true }));+vi.mock('../domainUsage.js', () => ({ getDomainBudgetStatus: (...a) => budgetMock(...a) }));++const {+ activeCommissions,+ syncCommissionSchedules,+ startCommissionScheduler,+ stopCommissionScheduler,+ runScheduledCommission,+} = await import('./scheduler.js');++const videoCommission = (over = {}) => ({+ id: 'commission-1',+ name: 'Nightly Surreal',+ enabled: true,+ targetAbility: 'video',+ brief: { intent: 'surreal', styleSpec: 'flat', constraints: {} },+ schedule: { kind: 'DAILY', atLocalTime: '02:00', timezone: null },+ generation: { quality: 'standard', aspectRatio: '16:9', targetDurationSeconds: 10, model: null },+ feedback: [],+ feedbackWindow: 5,+ ...over,+});++beforeEach(() => {+ vi.clearAllMocks();+ stopCommissionScheduler();+ creativeModeMock.mockReturnValue('execute');+ budgetMock.mockResolvedValue({ withinBudget: true });+ loadStateMock.mockResolvedValue({ config: {} });+});++describe('activeCommissions', () => {+ it('keeps enabled commissions with a valid derivable cron', () => {+ const active = activeCommissions([videoCommission()]);+ expect(active).toEqual([{ id: 'commission-1', cron: '0 2 * * *', timezone: null }]);+ });++ it('drops disabled commissions and ones with an underivable schedule', () => {+ const active = activeCommissions([+ videoCommission({ id: 'a', enabled: false }),+ videoCommission({ id: 'b', schedule: { kind: 'DAILY' } }), // no time → no cron+ videoCommission({ id: 'c' }),+ ]);+ expect(active.map((e) => e.id)).toEqual(['c']);+ });+});++describe('startCommissionScheduler (no cold-boot generation)', () => {+ it('arms crons but never generates at boot', async () => {+ listCommissionsMock.mockResolvedValue([videoCommission()]);+ const count = await startCommissionScheduler();+ expect(count).toBe(1);+ expect(scheduleMock).toHaveBeenCalledTimes(1);+ expect(scheduleMock).toHaveBeenCalledWith(expect.objectContaining({+ id: 'creative-commission-commission-1', type: 'cron', cron: '0 2 * * *',+ }));+ // The load-bearing guarantee: arming a schedule fires NO LLM/generation.+ expect(createProjectMock).not.toHaveBeenCalled();+ expect(advanceMock).not.toHaveBeenCalled();+ });++ it('cancels crons whose commission was removed on the next sync', async () => {+ listCommissionsMock.mockResolvedValueOnce([videoCommission()]);+ await syncCommissionSchedules();+ listCommissionsMock.mockResolvedValueOnce([]);+ await syncCommissionSchedules();+ expect(cancelMock).toHaveBeenCalledWith('creative-commission-commission-1');+ });+});++describe('runScheduledCommission gates', () => {+ it('generates through the CD directive pipeline when autonomy is execute + within budget', async () => {+ getCommissionMock.mockResolvedValue(videoCommission());+ await runScheduledCommission('commission-1');+ expect(createProjectMock).toHaveBeenCalledWith(expect.objectContaining({+ aspectRatio: '16:9', quality: 'standard', modelId: 'ltx-default', targetDurationSeconds: 10,+ directive: expect.objectContaining({ goal: expect.stringContaining('surreal') }),+ }));+ expect(advanceMock).toHaveBeenCalledWith('cd-xyz');+ expect(recordRunMock).toHaveBeenCalledWith('commission-1', expect.objectContaining({ status: 'started', projectId: 'cd-xyz' }));+ });++ it('skips generation (records skipped) when creative autonomy is off', async () => {+ creativeModeMock.mockReturnValue('off');+ getCommissionMock.mockResolvedValue(videoCommission());+ await runScheduledCommission('commission-1');+ expect(createProjectMock).not.toHaveBeenCalled();+ expect(recordRunMock).toHaveBeenCalledWith('commission-1', expect.objectContaining({ status: 'skipped', reason: 'autonomy-off' }));+ });++ it('skips generation when over the daily budget', async () => {+ budgetMock.mockResolvedValue({ withinBudget: false });+ getCommissionMock.mockResolvedValue(videoCommission());+ await runScheduledCommission('commission-1');+ expect(createProjectMock).not.toHaveBeenCalled();+ expect(recordRunMock).toHaveBeenCalledWith('commission-1', expect.objectContaining({ status: 'skipped', reason: 'budget' }));+ });++ it('does nothing when the commission is missing or disabled', async () => {+ getCommissionMock.mockResolvedValue(null);+ await runScheduledCommission('gone');+ expect(createProjectMock).not.toHaveBeenCalled();+ expect(recordRunMock).not.toHaveBeenCalled();+ });++ it('skips a non-video target ability (Phase 1 supports video only)', async () => {+ getCommissionMock.mockResolvedValue(videoCommission({ targetAbility: 'music' }));+ await runScheduledCommission('commission-1');+ expect(createProjectMock).not.toHaveBeenCalled();+ expect(recordRunMock).toHaveBeenCalledWith('commission-1', expect.objectContaining({ status: 'skipped', reason: 'unsupported-ability' }));+ });+});diff --git a/server/services/creativeCommissions/store.js b/server/services/creativeCommissions/store.jsnew file mode 100644index 0000000000..ebaa38c8e8--- /dev/null+++ b/server/services/creativeCommissions/store.js@@ -0,0 +1,197 @@+/**+ * Creative Commission store + service (#2657, Phase 1 — Autonomous Creation Engine).+ *+ * A CreativeCommission is a standing, recurring creative brief that fires on a+ * schedule and drives the Creative Director's directive pipeline unattended.+ *+ * Storage: a `createCollectionStore` collection at `data/creative-commissions/`,+ * one record per commission. Commissions are MACHINE-LOCAL and NOT federated in+ * Phase 1 — the same rationale as `seriesAutopilotScheduler`'s settings-based+ * schedules: a schedule that federated across sync peers would double-run on+ * every machine. Federation (with a per-peer "home" gate) is Phase 2 work.+ *+ * The record shape is stable/forward-looking: `feedback[]` + `feedbackWindow`+ * exist now (Phase 1 leaves feedback empty) so Phase 2 only needs the rate+ * surface, not a schema change.+ */++import { join } from 'path';+import { randomUUID } from 'crypto';+import { PATHS } from '../../lib/fileUtils.js';+import { createCollectionStore } from '../../lib/collectionStore.js';+import { isValidCron } from '../eventScheduler.js';+import { commissionToCron } from './directive.js';++export const TYPE = 'creative-commissions';+export const COMMISSIONS_SCHEMA_VERSION = 1;+export const MAX_PERSISTED_RUNS = 50;++// Service-layer error codes (mapped to HTTP status by the route via+// createServiceErrorMapper), mirroring the universeBuilder convention.+export const ERR_NOT_FOUND = 'NOT_FOUND';+export const ERR_VALIDATION = 'VALIDATION_ERROR';+export const makeErr = (message, code) => Object.assign(new Error(message), { code });++const isStr = (v) => typeof v === 'string';++/**+ * Normalize a raw record into the canonical stored shape. Returns null for a+ * non-object / id-less record (collectionStore drops nulls), so a malformed+ * on-disk file can't surface. Passed to every `loadOne`.+ */+export function sanitizeCommission(raw) {+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;+ if (!isStr(raw.id) || !raw.id) return null;+ const now = new Date().toISOString();+ 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 : {};+ return {+ id: raw.id,+ name: isStr(raw.name) ? raw.name : 'Untitled Commission',+ enabled: raw.enabled !== false,+ targetAbility: isStr(raw.targetAbility) ? raw.targetAbility : 'video',+ brief: {+ intent: isStr(brief.intent) ? brief.intent : '',+ genre: isStr(brief.genre) ? brief.genre : null,+ category: isStr(brief.category) ? brief.category : null,+ styleSpec: isStr(brief.styleSpec) ? brief.styleSpec : '',+ constraints: brief.constraints && typeof brief.constraints === 'object' ? brief.constraints : {},+ seedRefs: Array.isArray(brief.seedRefs) ? brief.seedRefs : [],+ },+ schedule: {+ kind: isStr(schedule.kind) ? schedule.kind : 'DAILY',+ atLocalTime: isStr(schedule.atLocalTime) ? schedule.atLocalTime : null,+ weekday: Number.isInteger(schedule.weekday) ? schedule.weekday : null,+ weekdaysOnly: schedule.weekdaysOnly === true,+ cron: isStr(schedule.cron) ? schedule.cron : null,+ timezone: isStr(schedule.timezone) ? schedule.timezone : null,+ },+ generation: {+ model: isStr(generation.model) ? generation.model : null,+ quality: isStr(generation.quality) ? generation.quality : 'standard',+ aspectRatio: isStr(generation.aspectRatio) ? generation.aspectRatio : '16:9',+ targetDurationSeconds: Number.isInteger(generation.targetDurationSeconds) ? generation.targetDurationSeconds : 10,+ },+ // Phase 2 populates these; kept stable now.+ feedback: Array.isArray(raw.feedback) ? raw.feedback : [],+ feedbackWindow: Number.isInteger(raw.feedbackWindow) ? raw.feedbackWindow : 5,+ runs: Array.isArray(raw.runs) ? raw.runs.slice(-MAX_PERSISTED_RUNS) : [],+ createdAt: isStr(raw.createdAt) ? raw.createdAt : now,+ updatedAt: isStr(raw.updatedAt) ? raw.updatedAt : (isStr(raw.createdAt) ? raw.createdAt : now),+ };+}++let _store = null;+/** Lazily construct the singleton commission store (avoids touching PATHS at import). */+export function commissionStore() {+ if (!_store) {+ _store = createCollectionStore({+ dir: join(PATHS.data, TYPE),+ type: TYPE,+ schemaVersion: COMMISSIONS_SCHEMA_VERSION,+ sanitizeRecord: sanitizeCommission,+ });+ }+ return _store;+}++// `saveOne` writes only the per-record file, never the type-level index.json+// (which stamps schemaVersion). Stamp it once per process on first write so the+// boot verifier reports the real version and a future bump can detect v1 data.+const _stamped = new WeakSet();+async function ensureTypeIndex(store) {+ if (_stamped.has(store)) return;+ _stamped.add(store);+ await store.saveTypeIndex({}).catch(() => { _stamped.delete(store); });+}++/**+ * Assert a schedule composes into a cron the scheduler will honor. Throws+ * ERR_VALIDATION otherwise (surfaced as HTTP 400). Kept here — not in the Zod+ * schema — so validation.js stays a leaf free of the eventScheduler import.+ */+export function assertValidSchedule(schedule) {+ const cron = commissionToCron(schedule);+ if (!cron || !isValidCron(cron)) {+ throw makeErr('Invalid schedule: could not derive a valid cron expression', ERR_VALIDATION);+ }+ return cron;+}++export async function listCommissions() {+ return commissionStore().loadAll();+}++export async function getCommission(id) {+ const rec = await commissionStore().loadOne(id);+ if (!rec) throw makeErr(`Commission not found: ${id}`, ERR_NOT_FOUND);+ return rec;+}++export async function createCommission(input) {+ assertValidSchedule(input.schedule);+ const store = commissionStore();+ const now = new Date().toISOString();+ const id = `commission-${randomUUID()}`;+ const record = sanitizeCommission({ ...input, id, createdAt: now, updatedAt: now, runs: [], feedback: [] });+ await ensureTypeIndex(store);+ await store.saveOne(id, record);+ return record;+}++export async function updateCommission(id, patch) {+ const store = commissionStore();+ const current = await store.loadOne(id);+ if (!current) throw makeErr(`Commission not found: ${id}`, ERR_NOT_FOUND);+ const nextSchedule = patch.schedule ?? current.schedule;+ if (patch.schedule) assertValidSchedule(nextSchedule);+ const merged = sanitizeCommission({+ ...current,+ ...patch,+ // Deep-merge the nested objects so a partial brief/generation patch doesn't+ // wipe unspecified fields.+ brief: patch.brief ? { ...current.brief, ...patch.brief } : current.brief,+ schedule: patch.schedule ? { ...current.schedule, ...patch.schedule } : current.schedule,+ generation: patch.generation ? { ...current.generation, ...patch.generation } : current.generation,+ id,+ createdAt: current.createdAt,+ updatedAt: new Date().toISOString(),+ });+ await store.saveOne(id, merged);+ return merged;+}++export async function deleteCommission(id) {+ const store = commissionStore();+ const current = await store.loadOne(id);+ if (!current) throw makeErr(`Commission not found: ${id}`, ERR_NOT_FOUND);+ await store.deleteOne(id);+ return { id, deleted: true };+}++/**+ * Append a run entry to a commission (fire history). Runs are capped to the last+ * MAX_PERSISTED_RUNS. Serialized per-id by the collectionStore write queue.+ * Best-effort: called from the scheduler's fire handler (outside the request+ * lifecycle) — the caller wraps errors.+ */+export async function recordCommissionRun(id, runEntry) {+ const store = commissionStore();+ return store.queueRecordWrite(id, async () => {+ const current = await store.loadOne(id);+ if (!current) return null;+ const run = {+ id: runEntry.id || `run-${randomUUID()}`,+ ranAt: runEntry.ranAt || new Date().toISOString(),+ status: runEntry.status || 'started',+ projectId: runEntry.projectId || null,+ promptUsed: isStr(runEntry.promptUsed) ? runEntry.promptUsed : null,+ reason: isStr(runEntry.reason) ? runEntry.reason : null,+ error: isStr(runEntry.error) ? runEntry.error : null,+ };+ const runs = [...(current.runs || []), run].slice(-MAX_PERSISTED_RUNS);+ await store.saveOneNow(id, { ...current, runs, updatedAt: new Date().toISOString() });+ return run;+ });+}diff --git a/server/services/creativeCommissions/store.test.js b/server/services/creativeCommissions/store.test.jsnew file mode 100644index 0000000000..347071466c--- /dev/null+++ b/server/services/creativeCommissions/store.test.js@@ -0,0 +1,127 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';++// In-memory collectionStore so CRUD is exercised without touching the filesystem.+const records = new Map();+const makeMemStore = () => ({+ loadAll: async () => [...records.values()],+ loadOne: async (id) => records.get(id) || null,+ saveOne: async (id, rec) => { records.set(id, rec); },+ saveOneNow: async (id, rec) => { records.set(id, rec); },+ deleteOne: async (id) => { records.delete(id); },+ saveTypeIndex: async () => {},+ queueRecordWrite: async (_id, fn) => fn(),+});+vi.mock('../../lib/collectionStore.js', () => ({ createCollectionStore: () => makeMemStore() }));+vi.mock('../../lib/fileUtils.js', () => ({ PATHS: { data: '/tmp/portos-test-data' } }));++const {+ sanitizeCommission,+ assertValidSchedule,+ createCommission,+ updateCommission,+ deleteCommission,+ getCommission,+ recordCommissionRun,+ ERR_VALIDATION,+ ERR_NOT_FOUND,+} = await import('./store.js');++beforeEach(() => records.clear());++const validInput = () => ({+ name: 'Nightly Surreal',+ enabled: true,+ targetAbility: 'video',+ brief: { intent: 'surreal', styleSpec: 'flat', constraints: { universeId: 'u-1' }, seedRefs: [] },+ schedule: { kind: 'DAILY', atLocalTime: '02:00', timezone: null },+ generation: { quality: 'high', aspectRatio: '9:16', targetDurationSeconds: 20 },+ feedbackWindow: 3,+});++describe('sanitizeCommission', () => {+ it('drops a null / id-less record', () => {+ expect(sanitizeCommission(null)).toBeNull();+ expect(sanitizeCommission({ name: 'no id' })).toBeNull();+ });++ it('normalizes a partial record to the canonical shape', () => {+ const rec = sanitizeCommission({ id: 'c1' });+ expect(rec.name).toBe('Untitled Commission');+ expect(rec.enabled).toBe(true);+ expect(rec.targetAbility).toBe('video');+ expect(rec.brief).toMatchObject({ intent: '', styleSpec: '', seedRefs: [] });+ expect(rec.generation).toMatchObject({ quality: 'standard', aspectRatio: '16:9', targetDurationSeconds: 10 });+ expect(rec.runs).toEqual([]);+ expect(rec.feedback).toEqual([]);+ });++ it('caps runs to the last MAX_PERSISTED_RUNS', () => {+ const runs = Array.from({ length: 80 }, (_, i) => ({ id: `run-${i}` }));+ const rec = sanitizeCommission({ id: 'c1', runs });+ expect(rec.runs).toHaveLength(50);+ expect(rec.runs[0].id).toBe('run-30');+ });+});++describe('assertValidSchedule', () => {+ it('returns the derived cron for a valid schedule', () => {+ expect(assertValidSchedule({ kind: 'DAILY', atLocalTime: '02:00' })).toBe('0 2 * * *');+ });++ it('throws ERR_VALIDATION for an underivable/invalid schedule', () => {+ expect(() => assertValidSchedule({ kind: 'DAILY' })).toThrow();+ try { assertValidSchedule({ kind: 'CUSTOM', cron: 'not a cron' }); }+ catch (e) { expect(e.code).toBe(ERR_VALIDATION); }+ });+});++describe('createCommission', () => {+ it('mints an id, sanitizes, and persists', async () => {+ const rec = await createCommission(validInput());+ expect(rec.id).toMatch(/^commission-/);+ expect(rec.name).toBe('Nightly Surreal');+ expect(rec.generation.quality).toBe('high');+ expect(rec.brief.constraints).toEqual({ universeId: 'u-1' });+ expect(records.get(rec.id)).toEqual(rec);+ });++ it('rejects an invalid schedule before persisting', async () => {+ await expect(createCommission({ ...validInput(), schedule: { kind: 'DAILY' } })).rejects.toThrow();+ expect(records.size).toBe(0);+ });+});++describe('updateCommission', () => {+ it('deep-merges a partial brief without wiping other fields', async () => {+ const created = await createCommission(validInput());+ const updated = await updateCommission(created.id, { brief: { intent: 'new intent' } });+ expect(updated.brief.intent).toBe('new intent');+ expect(updated.brief.styleSpec).toBe('flat'); // preserved+ expect(updated.createdAt).toBe(created.createdAt);+ });++ it('throws NOT_FOUND for an unknown id', async () => {+ try { await updateCommission('nope', { enabled: false }); }+ catch (e) { expect(e.code).toBe(ERR_NOT_FOUND); }+ });+});++describe('recordCommissionRun', () => {+ it('appends a run and caps history', async () => {+ const created = await createCommission(validInput());+ await recordCommissionRun(created.id, { status: 'started', projectId: 'cd-1', promptUsed: 'g' });+ const after = await getCommission(created.id);+ expect(after.runs).toHaveLength(1);+ expect(after.runs[0]).toMatchObject({ status: 'started', projectId: 'cd-1', promptUsed: 'g' });+ expect(after.runs[0].id).toMatch(/^run-/);+ });+});++describe('deleteCommission', () => {+ it('removes the record', async () => {+ const created = await createCommission(validInput());+ const r = await deleteCommission(created.id);+ expect(r).toEqual({ id: created.id, deleted: true });+ expect(records.has(created.id)).toBe(false);+ });+});