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([issue-2657]): Phase 2 — feedback loop + preference conditioning
[._.]/ Adam Eivyec254a0f25fb
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex accc67f51c..c89595efb7 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -138,4 +138,5 @@- **Fix Element Flash: pressing Enter/Return after answering now advances to the next question.** In the Element Flash recall test (`ElementsSong.jsx`), the Enter-to-submit handler lived only on the answer `<input>`, which unmounts once the result is shown — so a second Enter did nothing and the user had to click "Next" to continue. `ElementFlashMode` now binds a window `keydown` listener while a result is showing (input unmounted) that advances on Enter/Return, mirroring the "Next" button; the `next()` handler was hoisted above the completion early-return so the effect can reference it without breaking hook order. The listener ignores auto-repeat (`e.repeat`) and any Enter that a focused control or open overlay already owns (`e.target.closest('button, a, input, textarea, select, [role="dialog"], [role="menu"], [contenteditable]')`) — so a keyboard user tabbed to the Back/Next button doesn't double-advance, and an Enter meant for the command palette doesn't leak through to the quiz. Tests drive answer → Enter (submit) → Enter (advance) asserting the counter increments, and pin that an Enter fired from the focused Next button is not hijacked by the window listener.- **[issue-2657] Autonomous Creation Engine (Phase 1) — schedule the Creative Director with a recurring, feedback-ready creative brief.** New first-class `CreativeCommission` entity: a standing brief (`{ name, enabled, targetAbility, brief, schedule, generation }`) that fires on a cron cadence and drives the existing Creative Director *directive* pipeline unattended — "every night at 2am, make me something surreal." Commissions are `db-primary` (per `docs/STORAGE.md`): one row per commission in the machine-local `creative_commissions` PostgreSQL table (full record in `data` JSONB, adapter `server/services/creativeCommissions/db.js`, selected pg-vs-file exactly like universeBuilder so a `NODE_ENV=test`/`MEMORY_BACKEND=file` install keeps a file escape hatch). No `sync_sequence`/tombstone — deletes are hard deletes, mirroring `tribe`. They are deliberately **not** federated in Phase 1 — the same rationale as `seriesAutopilotScheduler`'s settings-based schedules, since a schedule that synced across peers would double-run on every machine (federation with a per-peer "home" gate is Phase 2). A new `commissionScheduler.js` (modeled on `seriesAutopilotScheduler`) arms one `eventScheduler` cron per enabled commission; on fire it re-reads the commission + creative-autonomy config, builds a CD directive from the brief via the pure `buildCommissionDirective` (which already folds a last-N feedback digest so Phase 2 only needs the rate surface), mints a directive-driven CD video project, and nudges `advanceAfterPlanStepSettled` so each plan step runs through the gated `dispatchCreativeTool`. Cold-bootstrap compliant per the AI Provider Usage Policy: boot only *arms* crons (nothing fires until a cadence elapses), and every fire gates on creative autonomy `execute` **and** the daily `cos` budget before spawning anything — an `off`/`dry-run` or over-budget install records a `skipped` run and generates nothing. Full REST CRUD at `/api/creative-commission` (Zod-validated create/update, DAILY/WEEKLY/CUSTOM schedules composed to cron with an authoritative `isValidCron` check in the service, `generation` schema with no object-level default so an empty PATCH still 400s the "at least one field" refine), a scheduler re-sync after every mutation, and a new `/creative-commission` Create-suite page: list + deep-linked create/edit Drawer (`/creative-commission/:id`, `/new`) with pause/resume, inline-confirm delete, and per-run history — registered in `NAV_COMMANDS` (⌘K + voice) and the sidebar. Phase 1 restricts `targetAbility` to `video` (the enum widens with the ability adapter in Phase 3/4) so a user can't create a commission that silently never runs. Refs #2657 — Phases 2–5 (feedback loop, all-ability adapter, music tool, genre taxonomy) remain. New unit + route + PG-adapter tests cover cron composition, the feedback digest, the store CRUD/sanitizer, the autonomy/budget gates, the no-boot-generation guarantee, the route contract, and the `creative_commissions` row round-trip (verbatim readback / upsert with created_at preserved / list order / hard delete). Scheduler-vs-request writes serialize on the facade's shared per-id write queue (`createRecordWriteQueue`), identical to universeBuilder/storyBuilder.+- **[issue-2657] Autonomous Creation Engine (Phase 2) — the taste feedback loop closes.** Each commission run's output is now rateable, and your reactions steer the next run. A new per-run **rate/annotate control** in the Creative Commissions run history (👍/👎 + an optional note like "less horror, more Magritte", keyboard-accessible, mobile-responsive, reactive) records a `CommissionFeedback` reaction against that specific run; the next scheduled fire's `buildCommissionDirective` folds the last **N** reactions (a configurable **feedback window**, now editable in the drawer — 0 disables conditioning) into the directive's goal as a "Recent likes / Recent dislikes — steer toward the likes, away from the dislikes" digest, so the run visibly drifts toward what you actually like (the digest shows up in the run's `promptUsed`). Feedback lives inline on the commission record — Phase 1 reserved `feedback[]` for exactly this, so no schema/table change was needed; reactions are deep-sanitized (a 👍/👎 or non-zero score is required, numeric ratings preserved verbatim, capped at 100) and appended on the same shared per-id write queue as run-recording so a rating submitted mid-fire can't clobber a run append. New `POST /api/creative-commission/:id/feedback` (Zod-validated `commissionFeedbackSchema` — `runId` required and verified against the record's runs, a zero rating rejected as meaningless, → 400/404 on bad input/unknown id) returns the full updated commission for reactive state. When a commission fires it now also **surfaces** the run — a low-priority notification (new `creative_commission` type, deep-linked to the commission) and a **brain inbox** entry inviting you to rate it; the inbox entry is created without AI-classification metadata, so surfacing never triggers a cold classifier LLM call (AI Provider Usage Policy). Commissions stay machine-local as in Phase 1 — since feedback lives on the never-federated commission it is also machine-local; the split-record federation the epic sketches (feedback federates, `schedule` stays per-machine to avoid double-runs) is genuinely larger and tracked as follow-up. Refs #2657 — Phases 3–5 (all-ability adapter, music tool, genre taxonomy) remain. New/updated unit + route tests cover the feedback sanitizer, `submitCommissionFeedback` (append / runId verification / NOT_FOUND / the full loop where a reaction folds into the next directive), the feedback route contract, the surfacing helper (notification + no-AI inbox entry + best-effort resilience), and the scheduler surfacing a successful fire but not a skipped one.- **Fix the Dev-UI "Vite host will be blocked" warning firing for apps whose vite config lives in an unlisted subdir.** `findViteConfig` only probed a hardcoded subdir allowlist (`client/`, `frontend/`, `web/`, …) plus each managed process's `cwd`. Apps that keep their Vite client elsewhere — e.g. an `admin/` dir — and whose stored process records carry no `cwd` produced a false "no vite.config was found" banner even though the config already set `allowedHosts: true` and the Dev UI opened fine over Tailscale. `findViteConfig` now falls back to a bounded breadth-first scan of the repo (depth ≤3, skipping `node_modules`/`.git`/build/vendor dirs, shallowest match wins) when the fast-path subdirs miss, so a config in any reasonable location is detected and the host-allow check reflects reality. `admin` also added to the fast-path list. New tests cover root, unlisted-subdir (`admin/`), nested, `node_modules`-ignore, and the end-to-end host-allowed status.diff --git a/client/src/pages/CreativeCommissions.jsx b/client/src/pages/CreativeCommissions.jsxindex 6508d0a5e0..55e69ef690 100644--- a/client/src/pages/CreativeCommissions.jsx+++ b/client/src/pages/CreativeCommissions.jsx@@ -14,7 +14,7 @@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 { Plus, Sparkles, Trash2, Clock, Pause, Play, ThumbsUp, ThumbsDown } from 'lucide-react';import toast from '../components/ui/Toast';import Drawer from '../components/Drawer';import ConfirmButtonPair from '../components/ui/ConfirmButtonPair';@@ -22,6 +22,7 @@ import { timeAgo } from '../utils/formatters';import { useConfirmDelete } from '../hooks/useConfirmDelete';import {listCommissions, createCommission, updateCommission, deleteCommission,+ submitCommissionFeedback,} from '../services/api';const WEEKDAYS = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];@@ -62,6 +63,8 @@ function toForm(c) {aspectRatio: c.generation?.aspectRatio || '16:9',targetDurationSeconds: c.generation?.targetDurationSeconds || 10,},+ // How many recent reactions steer the next run (0 disables conditioning).+ feedbackWindow: Number.isInteger(c.feedbackWindow) ? c.feedbackWindow : 5,};}@@ -90,6 +93,7 @@ function toPayload(form) {aspectRatio: form.generation.aspectRatio,targetDurationSeconds: Number(form.generation.targetDurationSeconds),},+ feedbackWindow: Number(form.feedbackWindow),};}@@ -174,6 +178,22 @@ export default function CreativeCommissions() {}};+ // Rate/annotate a specific run's output (#2657, Phase 2). The reaction folds+ // into the next scheduled run's directive. Reactive: swap the returned record+ // into local state so the run immediately reflects its rating.+ const handleRate = useCallback(async (runId, rating, note) => {+ if (!editing) return;+ try {+ const updated = await submitCommissionFeedback(+ editing.id, { runId, rating, note: note || '' }, { silent: true },+ );+ setCommissions((prev) => prev.map((c) => (c.id === updated.id ? updated : c)));+ toast.success('Feedback saved — it steers the next run');+ } catch (err) {+ toast.error(err?.message || 'Failed to save feedback');+ }+ }, [editing]);+const toggleEnabled = async (commission) => {const next = !commission.enabled;setCommissions((prev) => prev.map((c) => (c.id === commission.id ? { ...c, enabled: next } : c)));@@ -304,6 +324,8 @@ export default function CreativeCommissions() {form={form}patchForm={patchForm}runs={editing?.runs || []}+ feedback={editing?.feedback || []}+ onRate={editing ? handleRate : null}saving={saving}onSave={handleSave}onCancel={closeDrawer}@@ -313,9 +335,16 @@ export default function CreativeCommissions() {);}-function CommissionForm({ form, patchForm, runs, saving, onSave, onCancel }) {+function CommissionForm({ form, patchForm, runs, feedback, onRate, saving, onSave, onCancel }) {// Newest-first, memoized so the copy+reverse doesn't run on every keystroke.const orderedRuns = useMemo(() => [...runs].reverse(), [runs]);+ // Latest reaction per run (last write wins), so the run row reflects the most+ // recent rating the user gave it.+ const feedbackByRun = useMemo(() => {+ const map = {};+ for (const f of feedback || []) { if (f?.runId) map[f.runId] = f; }+ return map;+ }, [feedback]);return (<div className="space-y-5">{/* Identity */}@@ -495,21 +524,47 @@ function CommissionForm({ form, patchForm, runs, saving, onSave, onCancel }) {</div></section>+ {/* Feedback conditioning */}+ <section className="space-y-2 border-t border-port-border pt-4">+ <h3 className="text-sm font-semibold text-gray-200">Feedback conditioning</h3>+ <div className="flex items-center gap-3">+ <label className={`${labelCls} mb-0`} htmlFor="commission-feedback-window">Recent reactions to steer by</label>+ <input+ id="commission-feedback-window"+ type="number"+ min={0}+ max={50}+ className={`${inputCls} w-20`}+ value={form.feedbackWindow}+ onChange={(e) => patchForm(['feedbackWindow'], e.target.value)}+ />+ </div>+ <p className="text-xs text-gray-500">+ The last N ratings + notes are folded into the next run's brief. 0 disables conditioning.+ </p>+ </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">+ <div className="space-y-1 max-h-72 overflow-y-auto">{orderedRuns.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 key={r.id} className="text-xs bg-port-bg border border-port-border rounded px-2 py-1.5">+ <div className="flex items-center justify-between gap-2">+ <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>+ {/* Rate/annotate a run that actually produced output. */}+ {r.projectId && onRate && (+ <RunFeedback runId={r.id} current={feedbackByRun[r.id]} onRate={onRate} />+ )}</div>))}</div>@@ -529,3 +584,55 @@ function CommissionForm({ form, patchForm, runs, saving, onSave, onCancel }) {</div>);}++// Per-run rate/annotate control (#2657, Phase 2). Thumbs submit immediately,+// carrying whatever note is in the field; the current rating (if any) is shown+// highlighted. Note state is local so typing doesn't re-render the whole form.+function RunFeedback({ runId, current, onRate }) {+ const [note, setNote] = useState(current?.note || '');+ const [busy, setBusy] = useState(false);+ const rating = current?.rating;+ const isUp = rating === 'up' || (typeof rating === 'number' && rating > 0);+ const isDown = rating === 'down' || (typeof rating === 'number' && rating < 0);++ const submit = async (value) => {+ setBusy(true);+ try { await onRate(runId, value, note.trim()); }+ finally { setBusy(false); }+ };++ return (+ <div className="mt-1.5 flex items-center gap-1.5">+ <button+ type="button"+ disabled={busy}+ onClick={() => submit('up')}+ aria-label="Like this result"+ aria-pressed={isUp}+ title="Like — steer future runs toward this"+ className={`p-1 rounded disabled:opacity-50 ${isUp ? 'text-port-success' : 'text-gray-500 hover:text-gray-300'}`}+ >+ <ThumbsUp className="w-3.5 h-3.5" />+ </button>+ <button+ type="button"+ disabled={busy}+ onClick={() => submit('down')}+ aria-label="Dislike this result"+ aria-pressed={isDown}+ title="Dislike — steer future runs away from this"+ className={`p-1 rounded disabled:opacity-50 ${isDown ? 'text-port-error' : 'text-gray-500 hover:text-gray-300'}`}+ >+ <ThumbsDown className="w-3.5 h-3.5" />+ </button>+ <input+ className="flex-1 min-w-0 bg-port-card border border-port-border rounded px-2 py-1 text-xs text-gray-200 focus:outline-none focus:border-port-accent"+ value={note}+ maxLength={1000}+ placeholder="note (e.g. less horror, more Magritte)"+ aria-label={`Feedback note for run ${runId}`}+ onChange={(e) => setNote(e.target.value)}+ />+ </div>+ );+}diff --git a/client/src/services/apiCreativeCommission.js b/client/src/services/apiCreativeCommission.jsindex 2962fd3dc2..37f0746b5e 100644--- a/client/src/services/apiCreativeCommission.js+++ b/client/src/services/apiCreativeCommission.js@@ -30,3 +30,13 @@ export const deleteCommission = (id, options = {}) =>method: 'DELETE',...options,});++// Rate/annotate a specific run's output (#2657, Phase 2). `feedback` is+// `{ runId, rating: 'up'|'down'|number, note?, tags? }`. Resolves to the full+// updated commission (with the new reaction in `feedback[]`) for reactive state.+export const submitCommissionFeedback = (id, feedback, options = {}) =>+ request(`/creative-commission/${encodeURIComponent(id)}/feedback`, {+ method: 'POST',+ body: JSON.stringify(feedback),+ ...options,+ });diff --git a/server/lib/creativeCommissionValidation.js b/server/lib/creativeCommissionValidation.jsindex f584e5797d..2a14348231 100644--- a/server/lib/creativeCommissionValidation.js+++ b/server/lib/creativeCommissionValidation.js@@ -146,6 +146,25 @@ export const creativeCommissionBriefUpdateSchema = z.object({seedRefs: z.array(z.string().trim().max(64)).max(50).optional(),});+// A user reaction to a specific commission run (#2657, Phase 2 — the taste+// feedback loop). `runId` is required: the UI always rates a specific run, and+// the service verifies the run exists on the record. `rating` is 'up'/'down' or+// a non-zero score (numeric ratings are preserved verbatim so the directive+// digest's >0/<0 test still applies); a 0 score is rejected as meaningless. The+// note is the steering signal ("less horror, more Magritte") folded into the+// next run's prompt.+export const COMMISSION_FEEDBACK_NOTE_MAX = 1000;+export const commissionFeedbackSchema = z.object({+ runId: z.string().trim().min(1).max(120),+ rating: z.union([z.enum(['up', 'down']), z.number().int().min(-5).max(5)]),+ note: z.string().trim().max(COMMISSION_FEEDBACK_NOTE_MAX).default(''),+ tags: z.array(z.string().trim().min(1).max(40)).max(20).default([]),+}).superRefine((val, ctx) => {+ if (typeof val.rating === 'number' && val.rating === 0) {+ ctx.addIssue({ code: z.ZodIssueCode.custom, path: ['rating'], message: 'rating must be non-zero (up/down)' });+ }+});+// 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.diff --git a/server/routes/creativeCommissions.js b/server/routes/creativeCommissions.jsindex 6ee24d67e7..f4ff735451 100644--- a/server/routes/creativeCommissions.js+++ b/server/routes/creativeCommissions.js@@ -16,6 +16,7 @@ import {validateRequest,creativeCommissionCreateSchema,creativeCommissionUpdateSchema,+ commissionFeedbackSchema,isPaginationRequested,paginateArray,} from '../lib/validation.js';@@ -52,6 +53,15 @@ router.patch('/:id', asyncHandler(async (req, res) => {res.json(rec);}));+// Rate/annotate a specific run's output (#2657, Phase 2). The reaction is folded+// into the next scheduled fire's directive via buildCommissionDirective. Returns+// the full updated commission so the client updates its feedback state reactively.+router.post('/:id/feedback', asyncHandler(async (req, res) => {+ const body = validateRequest(commissionFeedbackSchema, req.body ?? {});+ const rec = await svc.submitCommissionFeedback(req.params.id, body).catch((err) => { throw mapServiceError(err); });+ res.status(201).json(rec);+}));+router.delete('/:id', asyncHandler(async (req, res) => {const r = await svc.deleteCommission(req.params.id).catch((err) => { throw mapServiceError(err); });res.json(r);diff --git a/server/routes/creativeCommissions.test.js b/server/routes/creativeCommissions.test.jsindex ce5e0a7454..f2309905d1 100644--- a/server/routes/creativeCommissions.test.js+++ b/server/routes/creativeCommissions.test.js@@ -14,6 +14,7 @@ const svc = {createCommission: vi.fn(),updateCommission: vi.fn(),deleteCommission: vi.fn(),+ submitCommissionFeedback: vi.fn(),};vi.mock('../services/creativeCommissions/store.js', () => svc);@@ -112,6 +113,43 @@ describe('PATCH /api/creative-commission/:id', () => {});});+describe('POST /api/creative-commission/:id/feedback', () => {+ it('validates and forwards the reaction to the service', async () => {+ svc.submitCommissionFeedback.mockResolvedValue({ id: 'commission-1', feedback: [{ runId: 'run-A', rating: 'up' }] });+ const res = await request(buildApp())+ .post('/api/creative-commission/commission-1/feedback')+ .send({ runId: 'run-A', rating: 'up', note: 'more Magritte' });+ expect(res.status).toBe(201);+ expect(svc.submitCommissionFeedback).toHaveBeenCalledWith('commission-1', expect.objectContaining({+ runId: 'run-A', rating: 'up', note: 'more Magritte',+ }));+ });++ it('rejects a body missing runId with 400 (service not called)', async () => {+ const res = await request(buildApp())+ .post('/api/creative-commission/commission-1/feedback')+ .send({ rating: 'up' });+ expect(res.status).toBe(400);+ expect(svc.submitCommissionFeedback).not.toHaveBeenCalled();+ });++ it('rejects a zero numeric rating with 400 (meaningless)', async () => {+ const res = await request(buildApp())+ .post('/api/creative-commission/commission-1/feedback')+ .send({ runId: 'run-A', rating: 0 });+ expect(res.status).toBe(400);+ expect(svc.submitCommissionFeedback).not.toHaveBeenCalled();+ });++ it('maps a service NOT_FOUND to 404', async () => {+ svc.submitCommissionFeedback.mockRejectedValue(Object.assign(new Error('gone'), { code: 'NOT_FOUND' }));+ const res = await request(buildApp())+ .post('/api/creative-commission/missing/feedback')+ .send({ runId: 'run-A', rating: 'down' });+ expect(res.status).toBe(404);+ });+});+describe('DELETE /api/creative-commission/:id', () => {it('deletes the commission', async () => {svc.deleteCommission.mockResolvedValue({ id: 'commission-1', deleted: true });diff --git a/server/services/creativeCommissions/scheduler.js b/server/services/creativeCommissions/scheduler.jsindex bdd29e1c32..deadf79eb7 100644--- a/server/services/creativeCommissions/scheduler.js+++ b/server/services/creativeCommissions/scheduler.js@@ -27,6 +27,7 @@ import { getUserTimezone } from '../../lib/timezone.js';import { settingsEvents } from '../settings.js';import { listCommissions, getCommission, recordCommissionRun, commissionEvents } from './store.js';import { commissionToCron, buildCommissionDirective } from './directive.js';+import { surfaceCommissionRun } from './surface.js';const eventId = (commissionId) => `creative-commission-${commissionId}`;const registered = new Set();@@ -216,11 +217,18 @@ export async function runScheduledCommission(commissionId) {directive,});- await recordCommissionRun(commissionId, {+ const run = await recordCommissionRun(commissionId, {status: 'started',projectId: project.id,promptUsed: directive.goal,- }).catch(() => {});+ }).catch(() => null);++ // Surface the fire (notification + brain inbox) so the user can rate the+ // result once it lands — the reaction feeds the next run via+ // buildCommissionDirective. Best-effort; surface.js swallows its own errors,+ // and the outer catch backstops anything unexpected (we're outside the+ // request lifecycle). Only surface real runs (a run row was persisted).+ if (run) await surfaceCommissionRun(commission, run).catch(() => {});// Kick the planner → plan → execute loop. Fire-and-forget within this// try/catch (already outside the request lifecycle).diff --git a/server/services/creativeCommissions/scheduler.test.js b/server/services/creativeCommissions/scheduler.test.jsindex aaf5c19596..c6041a576c 100644--- a/server/services/creativeCommissions/scheduler.test.js+++ b/server/services/creativeCommissions/scheduler.test.js@@ -26,6 +26,11 @@ vi.mock('./store.js', () => ({commissionEvents,}));+// Surfacing (notification + brain inbox) is mocked so the fire handler stays+// hermetic — the real surface.js lazy-imports notifications/brainStorage.+const surfaceMock = vi.fn(async () => {});+vi.mock('./surface.js', () => ({ surfaceCommissionRun: (...a) => surfaceMock(...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 () => {});@@ -139,11 +144,21 @@ describe('runScheduledCommission gates', () => {}));expect(advanceMock).toHaveBeenCalledWith('cd-xyz');expect(recordRunMock).toHaveBeenCalledWith('commission-1', expect.objectContaining({ status: 'started', projectId: 'cd-xyz' }));+ // Phase 2: a successful fire surfaces the run (notification + brain inbox) so+ // the user can rate it — the reaction steers the next fire.+ expect(surfaceMock).toHaveBeenCalledTimes(1);// The planner's cos action is accounted by completeAgent on completion — the// fire handler must NOT pre-charge (that would double-count).expect(recordUsageMock).not.toHaveBeenCalled();});+ it('does NOT surface when the fire is skipped (nothing was generated)', async () => {+ creativeModeMock.mockReturnValue('off');+ getCommissionMock.mockResolvedValue(videoCommission());+ await runScheduledCommission('commission-1');+ expect(surfaceMock).not.toHaveBeenCalled();+ });+it('caps the derived project name so createCollection (80-char limit) never fails', async () => {getCommissionMock.mockResolvedValue(videoCommission({ name: 'X'.repeat(200) }));await runScheduledCommission('commission-1');diff --git a/server/services/creativeCommissions/store.js b/server/services/creativeCommissions/store.jsindex de57b44542..0137d358b0 100644--- a/server/services/creativeCommissions/store.js+++ b/server/services/creativeCommissions/store.js@@ -52,6 +52,12 @@ export const commissionEvents = new EventEmitter();export const TYPE = 'creative-commissions';export const COMMISSIONS_SCHEMA_VERSION = 1;export const MAX_PERSISTED_RUNS = 50;+// Feedback is kept inline on the commission record (not a separate federated+// store) — Phase 1's store shape reserved `feedback[]` precisely so Phase 2 adds+// the rate surface without a schema change. Capped like runs so a long-lived+// nightly commission can't grow the row unbounded; the directive builder only+// ever reads the last `feedbackWindow` reactions anyway.+export const MAX_PERSISTED_FEEDBACK = 100;// Service-layer error codes (mapped to HTTP status by the route via// createServiceErrorMapper), mirroring the universeBuilder convention.@@ -61,6 +67,30 @@ export const makeErr = (message, code) => Object.assign(new Error(message), { coconst isStr = (v) => typeof v === 'string';+/**+ * Normalize a single feedback reaction (#2657, Phase 2). A reaction MUST carry a+ * meaningful rating — 'up'/'down' or a non-zero number (numeric ratings are+ * preserved verbatim so `renderFeedbackDigest`'s >0/<0 test still works). Returns+ * null for anything without a usable rating so a malformed/id-less entry can't+ * pollute the digest. Applied inside `sanitizeCommission` on every read/write, so+ * both backends return an identical, already-sanitized `feedback[]`.+ */+export function sanitizeFeedbackEntry(raw) {+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;+ const isUp = raw.rating === 'up' || (typeof raw.rating === 'number' && raw.rating > 0);+ const isDown = raw.rating === 'down' || (typeof raw.rating === 'number' && raw.rating < 0);+ if (!isUp && !isDown) return null;+ const rating = typeof raw.rating === 'number' ? raw.rating : (isUp ? 'up' : 'down');+ return {+ id: isStr(raw.id) && raw.id ? raw.id : `feedback-${randomUUID()}`,+ runId: isStr(raw.runId) ? raw.runId : null,+ rating,+ note: isStr(raw.note) ? raw.note : '',+ tags: Array.isArray(raw.tags) ? raw.tags.filter(isStr).slice(0, 20) : [],+ at: isStr(raw.at) ? raw.at : new Date().toISOString(),+ };+}+/*** Normalize a raw record into the canonical stored shape. Returns null for a* non-object / id-less record (so a malformed on-disk / on-row record can't@@ -101,8 +131,12 @@ export function sanitizeCommission(raw) {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 : [],+ // Phase 2: deep-sanitize each reaction (drop ratingless/malformed entries)+ // and cap history. Phase 1 records carry an empty array, so this is a no-op+ // for them and preserves stored, already-id'd feedback idempotently.+ feedback: Array.isArray(raw.feedback)+ ? raw.feedback.map(sanitizeFeedbackEntry).filter(Boolean).slice(-MAX_PERSISTED_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,@@ -328,3 +362,48 @@ export async function recordCommissionRun(id, runEntry) {return run;});}++/**+ * Record a user reaction to a commission run (#2657, Phase 2 — the taste+ * feedback loop). Appends a sanitized `CommissionFeedback` entry onto the+ * commission's inline `feedback[]`, keyed to the run being rated. The next+ * scheduled fire's `buildCommissionDirective` folds the last `feedbackWindow`+ * reactions into the directive, so a 👍/👎 + note demonstrably steers the next+ * run (the epic's core acceptance criterion).+ *+ * Serialized per-record on the SAME write queue as recordCommissionRun/+ * updateCommission, so a rating submitted while the scheduler is appending a run+ * can't clobber it (load→merge→save merges against the freshest persisted row).+ * Throws ERR_NOT_FOUND (→404) for an unknown commission and ERR_VALIDATION+ * (→400) when the referenced run isn't on the commission or the rating is+ * unusable. Returns the full updated commission so the UI updates reactively.+ *+ * Does NOT emit `commission:changed`: feedback never alters the schedule+ * signature, so a scheduler re-sync would be a pure no-op (mirrors+ * recordCommissionRun, which also stays silent).+ */+export async function submitCommissionFeedback(id, input) {+ const store = commissionStore();+ const result = await store.queueRecordWrite(id, async () => {+ const currentRaw = await store.readRaw(id);+ if (!currentRaw) return { notFound: true };+ const current = sanitizeCommission(currentRaw);+ // The UI always rates a specific run; reject a runId that isn't on the record+ // so feedback can't dangle against a non-existent run.+ if (input?.runId && !current.runs.some((r) => r.id === input.runId)) {+ throw makeErr(`Run not found on commission: ${input.runId}`, ERR_VALIDATION);+ }+ const entry = sanitizeFeedbackEntry({+ ...input,+ id: `feedback-${randomUUID()}`,+ at: new Date().toISOString(),+ });+ if (!entry) throw makeErr('Invalid feedback: a non-zero rating (up/down) is required', ERR_VALIDATION);+ const feedback = [...(current.feedback || []), entry].slice(-MAX_PERSISTED_FEEDBACK);+ const next = { ...current, feedback, updatedAt: new Date().toISOString() };+ await store.writeRaw(id, next);+ return { record: next };+ });+ if (result?.notFound) throw makeErr(`Commission not found: ${id}`, ERR_NOT_FOUND);+ return result.record;+}diff --git a/server/services/creativeCommissions/store.test.js b/server/services/creativeCommissions/store.test.jsindex d88e710c17..21130b8443 100644--- a/server/services/creativeCommissions/store.test.js+++ b/server/services/creativeCommissions/store.test.js@@ -18,15 +18,18 @@ vi.mock('../../lib/fileUtils.js', () => ({ PATHS: { data: '/tmp/portos-test-dataconst {sanitizeCommission,+ sanitizeFeedbackEntry,assertValidSchedule,createCommission,updateCommission,deleteCommission,getCommission,recordCommissionRun,+ submitCommissionFeedback,ERR_VALIDATION,ERR_NOT_FOUND,} = await import('./store.js');+const { buildCommissionDirective } = await import('./directive.js');beforeEach(() => records.clear());@@ -156,3 +159,71 @@ describe('deleteCommission', () => {expect(records.has(created.id)).toBe(false);});});++describe('sanitizeFeedbackEntry', () => {+ it('normalizes an up/down reaction and mints an id', () => {+ const e = sanitizeFeedbackEntry({ runId: 'run-1', rating: 'up', note: 'more Magritte' });+ expect(e).toMatchObject({ runId: 'run-1', rating: 'up', note: 'more Magritte' });+ expect(e.id).toMatch(/^feedback-/);+ expect(typeof e.at).toBe('string');+ });++ it('preserves a non-zero numeric rating verbatim', () => {+ expect(sanitizeFeedbackEntry({ rating: 2 }).rating).toBe(2);+ expect(sanitizeFeedbackEntry({ rating: -3 }).rating).toBe(-3);+ });++ it('drops a reaction with no usable rating (null/0/garbage)', () => {+ expect(sanitizeFeedbackEntry({ note: 'x' })).toBeNull();+ expect(sanitizeFeedbackEntry({ rating: 0 })).toBeNull();+ expect(sanitizeFeedbackEntry({ rating: 'meh' })).toBeNull();+ expect(sanitizeFeedbackEntry(null)).toBeNull();+ });+});++describe('sanitizeCommission (feedback)', () => {+ it('deep-sanitizes and caps feedback, dropping ratingless entries', () => {+ const feedback = [+ { id: 'f-keep', runId: 'r1', rating: 'up', note: 'keep' },+ { note: 'no rating — dropped' },+ ...Array.from({ length: 120 }, (_, i) => ({ id: `f-${i}`, rating: 'down' })),+ ];+ const rec = sanitizeCommission({ id: 'c1', feedback });+ expect(rec.feedback).toHaveLength(100); // MAX_PERSISTED_FEEDBACK+ // The ratingless entry is filtered before capping.+ expect(rec.feedback.every((f) => f.rating === 'up' || f.rating === 'down')).toBe(true);+ });+});++describe('submitCommissionFeedback', () => {+ it('appends a reaction keyed to an existing run and returns the updated commission', async () => {+ const created = await createCommission(validInput());+ await recordCommissionRun(created.id, { id: 'run-A', status: 'started', projectId: 'cd-1' });+ const updated = await submitCommissionFeedback(created.id, { runId: 'run-A', rating: 'up', note: 'more Magritte' });+ expect(updated.feedback).toHaveLength(1);+ expect(updated.feedback[0]).toMatchObject({ runId: 'run-A', rating: 'up', note: 'more Magritte' });+ expect(updated.feedback[0].id).toMatch(/^feedback-/);+ });++ it('closes the loop: the reaction folds into the next directive', async () => {+ const created = await createCommission(validInput());+ await recordCommissionRun(created.id, { id: 'run-A', status: 'started', projectId: 'cd-1' });+ await submitCommissionFeedback(created.id, { runId: 'run-A', rating: 'down', note: 'less horror' });+ const after = await getCommission(created.id);+ const directive = buildCommissionDirective(after);+ expect(directive.goal).toContain('Recent dislikes: less horror.');+ });++ it('rejects a reaction referencing a run not on the commission (VALIDATION)', async () => {+ const created = await createCommission(validInput());+ await expect(+ submitCommissionFeedback(created.id, { runId: 'ghost', rating: 'up' }),+ ).rejects.toMatchObject({ code: ERR_VALIDATION });+ });++ it('throws NOT_FOUND for an unknown commission', async () => {+ await expect(+ submitCommissionFeedback('nope', { runId: 'r', rating: 'up' }),+ ).rejects.toMatchObject({ code: ERR_NOT_FOUND });+ });+});diff --git a/server/services/creativeCommissions/surface.js b/server/services/creativeCommissions/surface.jsnew file mode 100644index 0000000000..697776b4eb--- /dev/null+++ b/server/services/creativeCommissions/surface.js@@ -0,0 +1,58 @@+/**+ * Creative Commission — output surfacing (#2657, Phase 2 — Autonomous Creation+ * Engine feedback loop).+ *+ * When a scheduled commission fires and mints a run, surface it so the user+ * knows a new piece is being created and can rate it once it lands: a+ * notification (deep-linked to the commission, where the run's rate/annotate+ * control lives) plus a brain inbox entry. Both are BEST-EFFORT and MUST NOT+ * throw into the scheduler's fire handler — that handler runs outside the+ * Express request lifecycle, where an uncaught throw crashes Node.+ *+ * Policy note (CLAUDE.md AI Provider Usage Policy): the brain entry is created+ * with `createInboxLog` directly and NO `ai` metadata, so it lands in the inbox+ * for manual review WITHOUT triggering a background classifier LLM call. The+ * commission generation itself is the sanctioned scheduled trigger; surfacing it+ * must not tack on an unrequested provider call.+ *+ * The heavy deps (notifications, brainStorage) are lazy-imported so this stays a+ * light leaf that a mocked test suite can stub without dragging their graphs in.+ */++/**+ * Surface a freshly-fired commission run via notification + brain inbox.+ * @param {object} commission sanitized commission record+ * @param {object} run the run entry just recorded (from recordCommissionRun)+ */+export async function surfaceCommissionRun(commission, run) {+ if (!commission?.id || !run) return;+ const link = `/creative-commission/${encodeURIComponent(commission.id)}`;+ const ability = commission.targetAbility || 'video';+ const name = commission.name || 'Commission';++ try {+ const { addNotification, NOTIFICATION_TYPES, PRIORITY_LEVELS } = await import('../notifications.js');+ await addNotification({+ type: NOTIFICATION_TYPES.CREATIVE_COMMISSION,+ title: `New ${ability} from “${name}”`,+ description: 'Your standing commission fired — rate the result to steer the next run.',+ priority: PRIORITY_LEVELS.LOW,+ link,+ metadata: { commissionId: commission.id, runId: run.id, projectId: run.projectId || null },+ });+ } catch (err) {+ console.error(`❌ Commission notification surface failed (${commission.id}): ${err?.message || err}`);+ }++ try {+ const { createInboxLog } = await import('../brainStorage.js');+ await createInboxLog({+ capturedText: `Creative commission “${name}” created a new ${ability}. Rate it to steer the next run: ${link}`,+ source: 'creative_commission',+ creative: true,+ status: 'needs_review',+ });+ } catch (err) {+ console.error(`❌ Commission brain-inbox surface failed (${commission.id}): ${err?.message || err}`);+ }+}diff --git a/server/services/creativeCommissions/surface.test.js b/server/services/creativeCommissions/surface.test.jsnew file mode 100644index 0000000000..bb657aa623--- /dev/null+++ b/server/services/creativeCommissions/surface.test.js@@ -0,0 +1,55 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';++// notifications + brainStorage are lazy-imported inside surfaceCommissionRun, so+// mock both. The mocks let us assert the surfacing shape without file/DB I/O.+const addNotificationMock = vi.fn(async () => {});+vi.mock('../notifications.js', () => ({+ addNotification: (...a) => addNotificationMock(...a),+ NOTIFICATION_TYPES: { CREATIVE_COMMISSION: 'creative_commission' },+ PRIORITY_LEVELS: { LOW: 'low' },+}));++const createInboxLogMock = vi.fn(async () => ({ id: 'inbox-1' }));+vi.mock('../brainStorage.js', () => ({ createInboxLog: (...a) => createInboxLogMock(...a) }));++const { surfaceCommissionRun } = await import('./surface.js');++const commission = { id: 'commission-1', name: 'Nightly Surreal', targetAbility: 'video' };+const run = { id: 'run-A', projectId: 'cd-1' };++beforeEach(() => vi.clearAllMocks());++describe('surfaceCommissionRun', () => {+ it('emits a deep-linked notification and a brain inbox entry', async () => {+ await surfaceCommissionRun(commission, run);+ expect(addNotificationMock).toHaveBeenCalledWith(expect.objectContaining({+ type: 'creative_commission',+ link: '/creative-commission/commission-1',+ metadata: expect.objectContaining({ commissionId: 'commission-1', runId: 'run-A', projectId: 'cd-1' }),+ }));+ expect(createInboxLogMock).toHaveBeenCalledWith(expect.objectContaining({+ source: 'creative_commission',+ status: 'needs_review',+ creative: true,+ }));+ });++ it('creates the brain entry WITHOUT ai metadata (no cold classifier LLM call)', async () => {+ await surfaceCommissionRun(commission, run);+ const entry = createInboxLogMock.mock.calls[0][0];+ expect(entry.ai).toBeUndefined();+ });++ it('is a no-op for a missing commission/run', async () => {+ await surfaceCommissionRun(null, run);+ await surfaceCommissionRun(commission, null);+ expect(addNotificationMock).not.toHaveBeenCalled();+ expect(createInboxLogMock).not.toHaveBeenCalled();+ });++ it('never throws, and still tries the inbox even if the notification fails', async () => {+ addNotificationMock.mockRejectedValueOnce(new Error('notif store down'));+ await expect(surfaceCommissionRun(commission, run)).resolves.toBeUndefined();+ expect(createInboxLogMock).toHaveBeenCalledTimes(1); // second surface still attempted+ });+});diff --git a/server/services/notifications.js b/server/services/notifications.jsindex 5a8b6c3807..06973cdb84 100644--- a/server/services/notifications.js+++ b/server/services/notifications.js@@ -36,7 +36,8 @@ export const NOTIFICATION_TYPES = {PLAN_QUESTION: 'plan_question',AGENT_WARNING: 'agent_warning',AUTOPILOT_PAUSED: 'autopilot_paused',- DAILY_POST_REMINDER: 'daily_post_reminder'+ DAILY_POST_REMINDER: 'daily_post_reminder',+ CREATIVE_COMMISSION: 'creative_commission'};// Priority levels