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
refactor: notify on a lost commission run-history write instead of only logging it (#7529)
[._.]/ Adam Eivy425b465e847d
diff --git a/client/src/components/creative-commission/runOutcomeToast.jsx b/client/src/components/creative-commission/runOutcomeToast.jsxindex 81f33b5c4e..63507048f2 100644--- a/client/src/components/creative-commission/runOutcomeToast.jsx+++ b/client/src/components/creative-commission/runOutcomeToast.jsx@@ -25,9 +25,8 @@ const WARNING_DURATION_MS = 12000;const WARNING_LABEL = 'Run history not saved';-/** The primary outcome line — the same information the plain toasts carry. */-function outcomeSummary(result, startedMessage) {- if (result?.status === 'started') return startedMessage;+/** The failure line for a non-started outcome — what the plain toasts carried. */+function failureSummary(result) {if (result?.status === 'skipped') return `Run skipped: ${result.reason}`;return `Run failed: ${result?.error || 'unknown error'}`;}@@ -74,11 +73,11 @@ export function toastRunOutcome(result, startedMessage) {const warning = result?.historyWarning;if (!warning) {if (result?.status === 'started') toast.success(startedMessage);- else toast.error(outcomeSummary(result, startedMessage));+ else toast.error(failureSummary(result));return;}// The reason a skip/fail happened is not what the ledger lost — keep it.- if (result?.status !== 'started') toast.error(outcomeSummary(result, startedMessage));+ if (result?.status !== 'started') toast.error(failureSummary(result));toast((t) => (<HistoryWarningToastt={t}diff --git a/client/src/pages/CreativeCommissionDetail.test.jsx b/client/src/pages/CreativeCommissionDetail.test.jsxindex 8273d5b72e..de09d107ad 100644--- a/client/src/pages/CreativeCommissionDetail.test.jsx+++ b/client/src/pages/CreativeCommissionDetail.test.jsx@@ -261,12 +261,11 @@ describe('CreativeCommissionDetail live render refresh (#4149)', () => {fireEvent.click(screen.getByRole('button', { name: /Run commission .* now/i }));});+ // Only the WIRING is under test here — that the page hands the server's+ // response to toastRunOutcome instead of branching on status itself.+ // runOutcomeToast.test.jsx owns what the warning toast renders.await waitFor(() => expect(toast).toHaveBeenCalled());expect(toast.success).not.toHaveBeenCalledWith(expect.stringContaining('appears below'));- const [content] = toast.mock.calls[0];- render(<MemoryRouter>{content({ id: 't1' })}</MemoryRouter>);- expect(screen.getByRole('link', { name: /open the project/i }))- .toHaveAttribute('href', '/creative-director/cd-orphan');});});diff --git a/server/services/creativeCommissions/scheduler.js b/server/services/creativeCommissions/scheduler.jsindex 669f7ec656..95bd41b97a 100644--- a/server/services/creativeCommissions/scheduler.js+++ b/server/services/creativeCommissions/scheduler.js@@ -36,7 +36,7 @@ import { listCommissions, getCommission, recordCommissionRun, commissionEvents,import { commissionToCron, commissionToRecurrence } from './directive.js';import { buildCommissionDirective, getAbilityAdapter } from './abilityAdapters.js';import { buildMusicTasteRecipe } from './musicTasteRecipe.js';-import { surfaceCommissionRun } from './surface.js';+import { surfaceCommissionRun, surfaceCommissionHistoryLoss } from './surface.js';import { registerCommissionProjectReconciler } from './projectControl.js';const eventId = (commissionId) => `creative-commission-${commissionId}`;@@ -207,38 +207,29 @@ export function stopCommissionScheduler() {clearReconcileRetry();}-// Sentinel + validate (AGENTS.md): a pre-fire read failure must never persist-// with the same shape as a legitimately-empty one. Never store the raw error-// message — it can originate from a DB driver and, per this fix's acceptance-// criteria, run history must exclude record contents, prompts and private-// feedback. A short, bounded classification (an error `code` when the failure-// supplies one, else its constructor name) is enough to distinguish outage-// types on the commission's run history without repeating this file's log.-function classifyPrefireReadError(err) {- if (typeof err?.code === 'string' && err.code) return `read-failed:${err.code}`;- if (typeof err?.name === 'string' && err.name) return `read-failed:${err.name}`;- return 'read-failed';+// Sentinel + validate (AGENTS.md): a storage failure must never persist with the+// same shape as a legitimately-empty result. Never store the raw error message —+// it can originate from a DB driver and, per #7529's acceptance criteria, run+// history and any client-visible warning must exclude record contents, prompts+// and private feedback. A short, bounded classification (an error `code` when the+// failure supplies one, else its constructor name) is enough to distinguish+// outage types without repeating this file's log.+function classifyBoundedError(err, prefix) {+ if (typeof err?.code === 'string' && err.code) return `${prefix}:${err.code}`;+ if (typeof err?.name === 'string' && err.name) return `${prefix}:${err.name}`;+ return prefix;}// The machine-readable code every degraded-history outcome carries. A caller// branches on this, never on prose.export const HISTORY_UNAVAILABLE = 'run-history-unavailable';-// Same bounded classification as classifyPrefireReadError, for the opposite-// direction: a WRITE that failed. Never the raw driver message — it can quote-// record contents, and a history warning travels to the client.-function classifyHistoryWriteError(err) {- if (typeof err?.code === 'string' && err.code) return `write-failed:${err.code}`;- if (typeof err?.name === 'string' && err.name) return `write-failed:${err.name}`;- return 'write-failed';-}-/*** Persist one run entry, separating three outcomes that a bare* `.catch(() => null)` used to collapse into one (#7529, AGENTS.md's* sentinel + validate rule):*- * - written → { run, historyWarning: null }+ * - written → { run } (no warning key)* - commission gone → { run: null, historyWarning: null } (honest absence)* - write FAILED → { run: null, historyWarning: {...} } (degradation)*@@ -254,20 +245,19 @@ function classifyHistoryWriteError(err) {* ledger that just failed. It carries only local ids and a bounded class, never* names, prompts or feedback.*/-async function persistRun(commissionId, entry, trigger) {+async function persistRun(commissionId, entry) {try {- const run = await recordCommissionRun(commissionId, entry);- return { run, historyWarning: null };+ return { run: await recordCommissionRun(commissionId, entry) };} catch (err) {- const detail = classifyHistoryWriteError(err);+ const detail = classifyBoundedError(err, 'write-failed');const projectNote = entry.projectId ? ` — project ${entry.projectId} is running unrecorded` : '';- console.error(`❌ Creative commission ${commissionId} ${trigger} ${entry.status} run history write failed (${detail})${projectNote}`);+ console.error(`❌ Creative commission ${commissionId} ${entry.trigger} ${entry.status} run history write failed (${detail})${projectNote}`);return {run: null,historyWarning: {code: HISTORY_UNAVAILABLE,outcome: entry.status,- trigger,+ trigger: entry.trigger,commissionId,projectId: entry.projectId || null,detail,@@ -297,16 +287,20 @@ export async function runScheduledCommission(commissionId) {} catch (err) {if (err?.code === ERR_NOT_FOUND) return; // confirmed deletion — quiet no-opconsole.error(`❌ Creative commission ${commissionId} pre-fire read failed: ${err?.message || err}`);- await recordCommissionRun(commissionId, {+ const { historyWarning } = await persistRun(commissionId, {status: 'failed',trigger: 'schedule',- error: classifyPrefireReadError(err),- }).catch((ledgerErr) => {- // The failed-run write above ITSELF failed — nothing landed on the- // commission's history, so this is the only surviving record of the- // outage. Its own diagnostic, per this fix's acceptance criteria.- console.error(`❌ Creative commission ${commissionId} pre-fire read failed AND its failure could not be recorded: ${ledgerErr?.message || ledgerErr}`);+ error: classifyBoundedError(err, 'read-failed'),});+ if (historyWarning) {+ // The failed-run write above ITSELF failed — nothing landed on the+ // commission's history, so these two lines are the only surviving record+ // of the outage. The joint one names the compound failure that neither+ // half states on its own; the notification is what actually reaches a+ // user who was not watching the logs at 02:00.+ console.error(`❌ Creative commission ${commissionId} pre-fire read failed AND its failure could not be recorded: ${historyWarning.detail}`);+ await surfaceCommissionHistoryLoss({ id: commissionId }, historyWarning);+ }throw err; // propagate to eventScheduler's runEvent, which contains it}if (commission.enabled === false) return; // paused — quiet no-op@@ -385,10 +379,16 @@ async function fireCommission(commission, trigger) {let startedProjectId = null;let startedTasteRecipe = null;let startedMusicGeneration = null;- const skip = async (reason) => {- const { run, historyWarning } = await persistRun(commissionId, { status: 'skipped', reason, trigger }, trigger);- return { status: 'skipped', reason, run, ...(historyWarning ? { historyWarning } : {}) };+ // Every degraded ledger write raises the SAME persisted notification, whatever+ // the trigger. A cron tick has no HTTP response to carry `historyWarning` home+ // in, so without this the unattended case — the one this fix is actually about+ // — would be a console line nobody reads. Manual callers get both.+ const outcome = async (base, persisted) => {+ if (persisted.historyWarning) await surfaceCommissionHistoryLoss(commission, persisted.historyWarning);+ return { ...base, ...persisted };};+ const skip = async (reason) =>+ outcome({ status: 'skipped', reason }, await persistRun(commissionId, { status: 'skipped', reason, trigger }));try {// Gate on creative autonomy mode + daily cos budget BEFORE spawning anything// (the planner is itself an LLM call) — honors "off ⇒ no generation" and the@@ -487,14 +487,15 @@ async function fireCommission(commission, trigger) {});startedProjectId = project.id;- const { run, historyWarning } = await persistRun(commissionId, {+ const persisted = await persistRun(commissionId, {status: 'started',trigger,projectId: project.id,promptUsed: directive.goal,...(startedTasteRecipe ? { tasteRecipe: startedTasteRecipe } : {}),...(startedMusicGeneration ? { musicGeneration: startedMusicGeneration } : {}),- }, trigger);+ });+ const { run } = persisted;// A taste-aware audio enqueue resolves its authoritative prompt/renderer// from this local run. If the write failed, advancing would make that lookup// look legitimately absent and silently release planner defaults instead.@@ -513,15 +514,15 @@ async function fireCommission(commission, trigger) {// The project IS running and its id is authoritative — the warning says only// that this fire's bookkeeping was lost, so a caller reports degraded history// instead of promising the render will appear in the commission's gallery.- return { status: 'started', projectId: project.id, run, ...(historyWarning ? { historyWarning } : {}) };+ return outcome({ status: 'started', projectId: project.id }, persisted);} catch (err) {console.error(`❌ Creative commission ${commissionId} ${trigger} fire failed: ${err?.message || err}`);const error = err?.message || String(err);- const { run, historyWarning } = await persistRun(commissionId, {+ const persisted = await persistRun(commissionId, {status: 'failed', error, trigger, projectId: startedProjectId,...(startedTasteRecipe ? { tasteRecipe: startedTasteRecipe } : {}),...(startedMusicGeneration ? { musicGeneration: startedMusicGeneration } : {}),- }, trigger);- return { status: 'failed', error, projectId: startedProjectId, run, ...(historyWarning ? { historyWarning } : {}) };+ });+ return outcome({ status: 'failed', error, projectId: startedProjectId }, persisted);}}diff --git a/server/services/creativeCommissions/scheduler.test.js b/server/services/creativeCommissions/scheduler.test.jsindex 4c42d7c1bd..4ad7a30d57 100644--- a/server/services/creativeCommissions/scheduler.test.js+++ b/server/services/creativeCommissions/scheduler.test.js@@ -41,7 +41,11 @@ vi.mock('./store.js', () => ({// 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) }));+const surfaceLossMock = vi.fn(async () => {});+vi.mock('./surface.js', () => ({+ surfaceCommissionRun: (...a) => surfaceMock(...a),+ surfaceCommissionHistoryLoss: (...a) => surfaceLossMock(...a),+}));// CD graph + autonomy/budget mocks (dynamic-imported inside the fire handler).const createProjectMock = vi.fn(async () => ({ id: 'cd-xyz' }));@@ -586,12 +590,6 @@ describe('run-history write failures are observable (#7529)', () => {expect(outcome.historyWarning).toBeUndefined();});- it('omits the warning entirely on a clean fire', async () => {- recordRunMock.mockResolvedValueOnce({ id: 'run-1', status: 'started' });- const outcome = await runCommissionNow('commission-1');- expect(outcome.historyWarning).toBeUndefined();- });-it('emits a scheduled diagnostic naming trigger and local ids, never the prompt or the raw driver message', async () => {recordRunMock.mockRejectedValueOnce(Object.assign(new Error('relation "commissions" does not exist'), { code: '42P01' }));await runScheduledCommission('commission-1');@@ -639,3 +637,49 @@ describe('run-history write failures are observable (#7529)', () => {expect(advanceMock).not.toHaveBeenCalled();});});++// The scheduled trigger is the case #7529 is really about, and it has no HTTP+// response to carry `historyWarning` home in. Its signal has to be the persisted+// notification, not a console line nobody reads at 02:00.+describe('a lost run-history write reaches an unattended user (#7529)', () => {+ let consoleErrorSpy;+ beforeEach(() => {+ getCommissionMock.mockResolvedValue(videoCommission());+ consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});+ });+ afterEach(() => { consoleErrorSpy.mockRestore(); });++ it('notifies on a SCHEDULED fire whose started row was lost, linking the project that is still running', async () => {+ recordRunMock.mockRejectedValueOnce(Object.assign(new Error('write timeout'), { code: 'ETIMEDOUT' }));+ await runScheduledCommission('commission-1');+ expect(surfaceLossMock).toHaveBeenCalledTimes(1);+ const [commission, warning] = surfaceLossMock.mock.calls[0];+ expect(commission.id).toBe('commission-1');+ expect(warning).toMatchObject({+ code: HISTORY_UNAVAILABLE, outcome: 'started', trigger: 'schedule', projectId: 'cd-xyz',+ });+ // The normal fired-run notification is gated on a real run and cannot fire here.+ expect(surfaceMock).not.toHaveBeenCalled();+ });++ it('notifies when the PRE-FIRE failure row is also lost, and still propagates the original read error', async () => {+ const readErr = Object.assign(new Error('storage timeout'), { code: 'ETIMEDOUT' });+ getCommissionMock.mockRejectedValue(readErr);+ recordRunMock.mockRejectedValueOnce(new Error('ledger write timeout'));++ await expect(runScheduledCommission('commission-1')).rejects.toBe(readErr);++ expect(consoleErrorSpy.mock.calls.some(([line]) => line.includes('pre-fire read failed AND its failure could not be recorded'))).toBe(true);+ // The record was unreadable, so only its id is available to name it by.+ expect(surfaceLossMock).toHaveBeenCalledWith({ id: 'commission-1' }, expect.objectContaining({+ code: HISTORY_UNAVAILABLE, outcome: 'failed', trigger: 'schedule',+ }));+ });++ it('raises no history notification when the write succeeded', async () => {+ recordRunMock.mockResolvedValueOnce({ id: 'run-1', status: 'started', projectId: 'cd-xyz' });+ await runScheduledCommission('commission-1');+ expect(surfaceLossMock).not.toHaveBeenCalled();+ expect(surfaceMock).toHaveBeenCalledTimes(1);+ });+});diff --git a/server/services/creativeCommissions/surface.js b/server/services/creativeCommissions/surface.jsindex b01b102039..a2882ac237 100644--- a/server/services/creativeCommissions/surface.js+++ b/server/services/creativeCommissions/surface.js@@ -60,3 +60,58 @@ export async function surfaceCommissionRun(commission, run) {console.error(`❌ Commission notification surface failed (${commission.id}): ${err?.message || err}`);}}++/**+ * Surface a run-history write that FAILED (#7529) — the degraded twin of+ * surfaceCommissionRun above.+ *+ * Why this exists rather than the console line alone: a cron tick has no HTTP+ * response to carry the outcome's `historyWarning` home in, so for the+ * unattended case this fix is actually about, a log entry nobody reads would be+ * the only signal. `surfaceCommissionRun` is already the persisted, machine-local+ * channel for "your commission did something while you weren't looking" — it is+ * just gated on a real run, which is precisely what a lost write does not have.+ *+ * MEDIUM rather than the fired-run LOW: this one needs a human. Nothing will+ * retry it and the run row is gone for good, so the deep link to the Creative+ * Director project is the only remaining route to work that is genuinely running.+ *+ * Same best-effort contract: never throws into the scheduler's fire handler, and+ * carries only local ids plus the bounded classification — never the prompt,+ * the directive or any feedback.+ *+ * @param {object} commission sanitized commission record, or `{ id }` when the+ * record itself could not be read (a pre-fire storage failure)+ * @param {object} warning the `historyWarning` persistRun produced+ */+export async function surfaceCommissionHistoryLoss(commission, warning) {+ if (!commission?.id || !warning) return;+ const name = commission.name || 'A commission';+ const link = warning.projectId+ ? `/creative-director/${encodeURIComponent(warning.projectId)}`+ : `/creative-commission/${encodeURIComponent(commission.id)}`;+ const body = warning.projectId+ ? 'The project is running, but this run was not saved to the commission’s history — it will not appear there or be ratable. Open the project to find the work.'+ : 'The outcome of this fire was not saved to the commission’s history.';++ try {+ const { addNotification, NOTIFICATION_TYPES, PRIORITY_LEVELS } = await import('../notifications.js');+ await addNotification({+ type: NOTIFICATION_TYPES.CREATIVE_COMMISSION,+ title: `“${name}” could not save its run history`,+ description: body,+ priority: PRIORITY_LEVELS.MEDIUM,+ link,+ metadata: {+ commissionId: commission.id,+ projectId: warning.projectId || null,+ historyWarning: warning.code,+ outcome: warning.outcome,+ trigger: warning.trigger,+ detail: warning.detail,+ },+ });+ } catch (err) {+ console.error(`❌ Commission history-loss surface failed (${commission.id}): ${err?.message || err}`);+ }+}