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
address review (claude, codex): feedback upsert, goal clamp, form-edit preservation, local surfacing
[._.]/ Adam Eivy12977f9c6df0
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex c89595efb7..b3b2f8814c 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -138,5 +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.+- **[issue-2657] Autonomous Creation Engine (Phase 2) — the taste feedback loop closes.** Each commission run's output is now rateable, and your reactions steer the next run. A new per-run **rate/annotate control** in the Creative Commissions run history (👍/👎 + an optional note like "less horror, more Magritte", keyboard-accessible, mobile-responsive, reactive) records a `CommissionFeedback` reaction against that specific run; the next scheduled fire's `buildCommissionDirective` folds the last **N** reactions (a configurable **feedback window**, now editable in the drawer — 0 disables conditioning) into the directive's goal as a "Recent likes / Recent dislikes — steer toward the likes, away from the dislikes" digest, so the run visibly drifts toward what you actually like (the digest shows up in the run's `promptUsed`). Feedback lives inline on the commission record — Phase 1 reserved `feedback[]` for exactly this, so no schema/table change was needed; reactions are deep-sanitized (a 👍/👎 or non-zero score is required, numeric ratings preserved verbatim, capped at 100) and **upserted by run** (re-rating a run replaces its prior reaction rather than stacking a contradictory second one) on the same shared per-id write queue as run-recording so a rating submitted mid-fire can't clobber a run append. The composed directive goal is length-clamped (per-note + overall) so a large feedback window can't push it past the Creative Director's 5000-char goal limit on the scheduler path (which skips the route's input validation). New `POST /api/creative-commission/:id/feedback` (Zod-validated `commissionFeedbackSchema` — `runId` required and verified against the record's runs, a zero rating rejected as meaningless, → 400/404 on bad input/unknown id) returns the full updated commission for reactive state; the edit drawer preserves unsaved field edits when a rating lands (the form re-syncs only on a genuine target change, not on every in-place record update). When a commission fires it also **surfaces** the run as a low-priority, machine-local notification (new `creative_commission` type, deep-linked to the commission) worded to reflect that the piece is *being created* — "rate the result once it lands." Surfacing stays notification-only for now: the brain inbox is federated (`inbox` ∈ `BRAIN_ENTITY_TYPES`), so a reminder there would propagate a peer-useless `needs_review` item pointing at a machine-local commission — brain-inbox surfacing (and completion-triggered surfacing) rejoin once commissions themselves federate. Commissions stay machine-local as in Phase 1 — since feedback lives on the never-federated commission it is also machine-local; the split-record federation the epic sketches (feedback federates, `schedule` stays per-machine to avoid double-runs) is genuinely larger and tracked as follow-up. Refs #2657 — Phases 3–5 (all-ability adapter, music tool, genre taxonomy) remain. New/updated unit + route tests cover the feedback sanitizer, `submitCommissionFeedback` (upsert-by-run / runId verification / NOT_FOUND / the full loop where a reaction folds into the next directive), the goal clamp, the feedback route contract, the notification-only surfacing helper (deep link + no federated-inbox write + best-effort resilience), and the scheduler surfacing a successful fire but not a skipped one.- **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 55e69ef690..b845ee0283 100644--- a/client/src/pages/CreativeCommissions.jsx+++ b/client/src/pages/CreativeCommissions.jsx@@ -12,7 +12,7 @@* rule. Mutations update local state directly (no full refetch).*/-import { useEffect, useMemo, useState, useCallback } from 'react';+import { useEffect, useMemo, useState, useCallback, useRef } from 'react';import { useNavigate, useParams } from 'react-router-dom';import { Plus, Sparkles, Trash2, Clock, Pause, Play, ThumbsUp, ThumbsDown } from 'lucide-react';import toast from '../components/ui/Toast';@@ -127,10 +127,24 @@ export default function CreativeCommissions() {return () => { cancelled = true; };}, []);- // Sync the form to the deep-linked record whenever the drawer target changes.+ // Sync the form to the deep-linked record — but ONLY when the drawer TARGET+ // changes (a new id / the create form / a first populate after load), never on+ // every `editing` object-identity change. `handleRate`/`toggleEnabled` swap the+ // record in local state, which changes `editing`'s reference; re-running+ // `setForm(toForm(editing))` on that would silently discard any unsaved edits+ // the user typed in the drawer. Keying on the last-synced id fixes that: an+ // in-place update of the same id is a no-op here, while closing the drawer+ // (id → null) resets the guard so reopening the same id re-syncs to the freshest+ // persisted values.+ const syncedTargetRef = useRef(null);useEffect(() => {- if (creating) setForm(blankForm());- else if (editing) setForm(toForm(editing));+ if (creating) {+ if (syncedTargetRef.current !== 'new') { setForm(blankForm()); syncedTargetRef.current = 'new'; }+ } else if (editing) {+ if (syncedTargetRef.current !== editing.id) { setForm(toForm(editing)); syncedTargetRef.current = editing.id; }+ } else {+ syncedTargetRef.current = null; // drawer closed / target not yet loaded+ }}, [id, creating, editing]);const closeDrawer = useCallback(() => navigate('/creative-commission'), [navigate]);diff --git a/server/services/creativeCommissions/directive.js b/server/services/creativeCommissions/directive.jsindex 7bf946057f..5259b562c8 100644--- a/server/services/creativeCommissions/directive.js+++ b/server/services/creativeCommissions/directive.js@@ -9,6 +9,19 @@* authoritative cron-VALIDITY check (isValidCron) lives in the scheduler/service.*/+// The CD directive `goal` this composes is fed straight into `createProject` by+// the scheduler, which does NOT re-validate it against the route's+// `creativeDirectorDirectiveSchema` (that 5000-char cap only guards HTTP input).+// A commission with the max `feedbackWindow` (50) and long notes could otherwise+// balloon the goal past what the planner should ever see. Clamp defensively: cap+// each note's contribution to the digest, and hard-cap the final goal with+// headroom under the CD schema limit.+export const MAX_DIGEST_NOTE_LEN = 300;+export const MAX_DIRECTIVE_GOAL_LEN = 4500;++const clampNote = (note) =>+ note.length > MAX_DIGEST_NOTE_LEN ? `${note.slice(0, MAX_DIGEST_NOTE_LEN - 1)}…` : note;+/*** Compose a 5-field cron (`minute hour dayOfMonth month dayOfWeek`) from a* commission schedule. Returns the raw string, or null when the schedule is@@ -58,8 +71,8 @@ export function renderFeedbackDigest(feedback, windowSize = 5) {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);+ if (up && note) likes.push(clampNote(note));+ else if (down && note) dislikes.push(clampNote(note));else if (up) likes.push('(liked, no note)');else if (down) dislikes.push('(disliked, no note)');}@@ -94,8 +107,14 @@ export function buildCommissionDirective(commission) {if (brief.constraints?.universeId) constraints.universeId = brief.constraints.universeId;if (brief.constraints?.seriesId) constraints.seriesId = brief.constraints.seriesId;+ // Hard-cap the goal so an internally-composed directive (scheduler path, which+ // skips the route's 5000-char validation) can never exceed what the CD planner+ // should receive.+ let goal = lines.join(' ');+ if (goal.length > MAX_DIRECTIVE_GOAL_LEN) goal = `${goal.slice(0, MAX_DIRECTIVE_GOAL_LEN - 1)}…`;+return {- goal: lines.join(' '),+ goal,deliverables: [`One ${ability} artifact matching the brief`],constraints,};diff --git a/server/services/creativeCommissions/directive.test.js b/server/services/creativeCommissions/directive.test.jsindex db944c0532..727bf2848e 100644--- a/server/services/creativeCommissions/directive.test.js+++ b/server/services/creativeCommissions/directive.test.js@@ -111,4 +111,21 @@ describe('buildCommissionDirective', () => {const directive = buildCommissionDirective({ targetAbility: 'video', brief: { intent: 'x' } });expect(directive.constraints).toEqual({});});++ it('clamps the goal so a large feedback window + long notes stay under the CD 5000-char cap', () => {+ // 50 reactions × 1000-char notes would blow well past the CD directive goal+ // limit; the scheduler feeds this goal straight into createProject without the+ // route's validation, so the builder must bound it itself.+ const feedback = Array.from({ length: 50 }, (_, i) => ({+ rating: i % 2 === 0 ? 'up' : 'down',+ note: 'z'.repeat(1000),+ }));+ const directive = buildCommissionDirective({+ targetAbility: 'video',+ brief: { intent: 'surreal' },+ feedback,+ feedbackWindow: 50,+ });+ expect(directive.goal.length).toBeLessThanOrEqual(4500);+ });});diff --git a/server/services/creativeCommissions/store.js b/server/services/creativeCommissions/store.jsindex 0137d358b0..db22a43299 100644--- a/server/services/creativeCommissions/store.js+++ b/server/services/creativeCommissions/store.js@@ -399,7 +399,15 @@ export async function submitCommissionFeedback(id, input) {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);+ // UPSERT by runId, don't append: re-rating a run must REPLACE its prior+ // reaction, not stack a second one. The UI shows only the latest reaction per+ // run, but `renderFeedbackDigest` consumes every entry — so a stacked+ // like-then-dislike for the same run would fold BOTH a "like" and a "dislike"+ // for one output into the next directive, and repeated votes would each burn a+ // `feedbackWindow` slot. Dropping the prior same-runId entry keeps one reaction+ // per run and moves the re-rated run to the most-recent position.+ const prior = (current.feedback || []).filter((f) => !f.runId || f.runId !== entry.runId);+ const feedback = [...prior, entry].slice(-MAX_PERSISTED_FEEDBACK);const next = { ...current, feedback, updatedAt: new Date().toISOString() };await store.writeRaw(id, next);return { record: next };diff --git a/server/services/creativeCommissions/store.test.js b/server/services/creativeCommissions/store.test.jsindex 21130b8443..2440072373 100644--- a/server/services/creativeCommissions/store.test.js+++ b/server/services/creativeCommissions/store.test.js@@ -214,6 +214,21 @@ describe('submitCommissionFeedback', () => {expect(directive.goal).toContain('Recent dislikes: less horror.');});+ it('re-rating a run REPLACES its prior reaction (no contradictory stacking)', 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: 'up', note: 'first take' });+ const updated = await submitCommissionFeedback(created.id, { runId: 'run-A', rating: 'down', note: 'changed my mind' });+ // Exactly one reaction for the run — the latest — not two.+ const forRun = updated.feedback.filter((f) => f.runId === 'run-A');+ expect(forRun).toHaveLength(1);+ expect(forRun[0]).toMatchObject({ rating: 'down', note: 'changed my mind' });+ // And the digest reflects only the latest vote, not both.+ const directive = buildCommissionDirective(await getCommission(created.id));+ expect(directive.goal).toContain('Recent dislikes: changed my mind.');+ expect(directive.goal).not.toContain('first take');+ });+it('rejects a reaction referencing a run not on the commission (VALIDATION)', async () => {const created = await createCommission(validInput());await expect(diff --git a/server/services/creativeCommissions/surface.js b/server/services/creativeCommissions/surface.jsindex 697776b4eb..86edf0d500 100644--- a/server/services/creativeCommissions/surface.js+++ b/server/services/creativeCommissions/surface.js@@ -3,24 +3,34 @@* 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.+ * knows a new piece is being created and can rate it once it lands. Surfacing is+ * 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.+ * WHY NOTIFICATION-ONLY (not the brain inbox). Commissions are machine-local in+ * Phase 1/2 (a synced schedule would double-run on every peer — see store.js).+ * The `notifications` store is a local file (never federated), so a+ * commission-scoped, machine-local `/creative-commission/:id` deep link belongs+ * there. The brain inbox, by contrast, IS federated (`inbox` ∈+ * `BRAIN_ENTITY_TYPES`) — writing a reminder there would propagate a+ * `needs_review` item pointing at a commission that doesn't exist on the peer,+ * polluting its backlog. Brain-inbox surfacing rejoins once commissions+ * themselves federate (the split-record follow-up, #2686).*- * 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.+ * WHY "fired / generating" wording (not "created a result"). Surfacing happens+ * at fire time — the CD project has only just been created; generation runs+ * asynchronously afterward. The copy therefore describes a run that is *being+ * created* and invites the user to rate it once it lands, rather than claiming a+ * finished artifact already exists. (Completion-triggered surfacing + catalog+ * seeding is the Phase 3 completion flow.)+ *+ * The notifications module is lazy-imported so this stays a light leaf a mocked+ * test suite can stub without dragging its graph in.*//**- * Surface a freshly-fired commission run via notification + brain inbox.+ * Surface a freshly-fired commission run via a local notification.* @param {object} commission sanitized commission record* @param {object} run the run entry just recorded (from recordCommissionRun)*/@@ -34,8 +44,8 @@ export async function surfaceCommissionRun(commission, run) {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.',+ title: `“${name}” is creating a new ${ability}`,+ description: 'Your standing commission fired — rate the result once it lands to steer the next run.',priority: PRIORITY_LEVELS.LOW,link,metadata: { commissionId: commission.id, runId: run.id, projectId: run.projectId || null },@@ -43,16 +53,4 @@ export async function surfaceCommissionRun(commission, run) {} 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.jsindex bb657aa623..3b83503f94 100644--- a/server/services/creativeCommissions/surface.test.js+++ b/server/services/creativeCommissions/surface.test.js@@ -1,7 +1,7 @@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.+// notifications is lazy-imported inside surfaceCommissionRun, so mock it. The+// mock lets us assert the surfacing shape without file I/O.const addNotificationMock = vi.fn(async () => {});vi.mock('../notifications.js', () => ({addNotification: (...a) => addNotificationMock(...a),@@ -9,9 +9,6 @@ vi.mock('../notifications.js', () => ({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' };@@ -20,36 +17,31 @@ 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 () => {+ it('emits a deep-linked, machine-local notification', 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('does NOT write to the (federated) brain inbox for a machine-local commission', async () => {+ // A brain inbox entry federates to peers where the commission does not exist;+ // surfacing must stay to the local notifications store only. Guard: importing+ // brainStorage would throw here (not mocked), so surfacing must never touch it.+ await expect(surfaceCommissionRun(commission, run)).resolves.toBeUndefined();+ expect(addNotificationMock).toHaveBeenCalledTimes(1);});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 () => {+ it('never throws even if the notification store fails', async () => {addNotificationMock.mockRejectedValueOnce(new Error('notif store down'));await expect(surfaceCommissionRun(commission, run)).resolves.toBeUndefined();- expect(createInboxLogMock).toHaveBeenCalledTimes(1); // second surface still attempted});});