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: address /simplify — event-driven scheduler re-sync + dedup
[._.]/ Adam Eivy598c1734c04d
diff --git a/client/src/pages/CreativeCommissions.jsx b/client/src/pages/CreativeCommissions.jsxindex 7493c3dbdb..6508d0a5e0 100644--- a/client/src/pages/CreativeCommissions.jsx+++ b/client/src/pages/CreativeCommissions.jsx@@ -36,14 +36,8 @@ function describeSchedule(schedule) {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 },-});+// A blank form is just the editable projection of an empty record.+const blankForm = () => toForm({});// Map a stored record → editable form state (fills gaps so inputs stay controlled).function toForm(c) {@@ -113,7 +107,12 @@ export default function CreativeCommissions() {const drawerOpen = id != null; // '/new' or an idconst creating = id === 'new';- const editing = drawerOpen && !creating ? commissions.find((c) => c.id === id) : null;+ // Memoized so the O(n) lookup (and the sync effect that depends on it) only+ // recomputes when the list or target id changes — not on every keystroke.+ const editing = useMemo(+ () => (drawerOpen && !creating ? commissions.find((c) => c.id === id) || null : null),+ [drawerOpen, creating, commissions, id],+ );useEffect(() => {let cancelled = false;@@ -293,7 +292,7 @@ export default function CreativeCommissions() {)}<Drawer- open={drawerOpen && (creating || !!editing)}+ open={creating || !!editing}onClose={closeDrawer}title={creating ? 'New Commission' : 'Edit Commission'}subtitle={!creating && editing ? editing.name : undefined}@@ -315,6 +314,8 @@ export default function CreativeCommissions() {}function CommissionForm({ form, patchForm, runs, saving, onSave, onCancel }) {+ // Newest-first, memoized so the copy+reverse doesn't run on every keystroke.+ const orderedRuns = useMemo(() => [...runs].reverse(), [runs]);return (<div className="space-y-5">{/* Identity */}@@ -499,7 +500,7 @@ function CommissionForm({ form, patchForm, runs, saving, onSave, onCancel }) {<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) => (+ {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={diff --git a/server/routes/creativeCommissions.js b/server/routes/creativeCommissions.jsindex 96ff7ff0a6..6ee24d67e7 100644--- a/server/routes/creativeCommissions.js+++ b/server/routes/creativeCommissions.js@@ -1,8 +1,10 @@/*** 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.+ * scheduler fires on a cadence. The scheduler re-arms crons off the store's+ * `commission:changed` event (emitted by every create/update/delete), so the+ * route stays decoupled from the scheduler graph and non-REST writers re-sync+ * too — the same seam seriesAutopilotScheduler uses for `settings:updated`.** No try/catch — errors bubble to the centralized error middleware. Service* errors carry a `code` mapped to an HTTP status via createServiceErrorMapper.@@ -18,7 +20,6 @@ import {paginateArray,} from '../lib/validation.js';import * as svc from '../services/creativeCommissions/store.js';-import { syncCommissionSchedules } from '../services/creativeCommissions/scheduler.js';const router = Router();@@ -28,13 +29,6 @@ const SERVICE_ERROR_STATUS = {};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);@@ -44,7 +38,6 @@ router.get('/', asyncHandler(async (req, res) => {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);}));@@ -56,13 +49,11 @@ router.get('/:id', asyncHandler(async (req, res) => {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);}));diff --git a/server/routes/creativeCommissions.test.js b/server/routes/creativeCommissions.test.jsindex 6f3723c768..e09395b008 100644--- a/server/routes/creativeCommissions.test.js+++ b/server/routes/creativeCommissions.test.js@@ -3,8 +3,9 @@ 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.+// The store service is mocked so the route test asserts exact call args without+// touching the collectionStore. Scheduler re-sync is now event-driven off the+// store (not called by the route), so the route no longer imports the scheduler.const svc = {ERR_NOT_FOUND: 'NOT_FOUND',ERR_VALIDATION: 'VALIDATION_ERROR',@@ -15,8 +16,6 @@ const svc = {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;@@ -46,7 +45,7 @@ describe('GET /api/creative-commission', () => {});describe('POST /api/creative-commission', () => {- it('validates + creates + re-syncs the scheduler', async () => {+ it('validates and creates', 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);@@ -56,7 +55,6 @@ describe('POST /api/creative-commission', () => {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 () => {@@ -93,12 +91,11 @@ describe('GET /api/creative-commission/:id', () => {});describe('PATCH /api/creative-commission/:id', () => {- it('updates + re-syncs', async () => {+ it('updates the commission', 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 () => {@@ -109,11 +106,10 @@ describe('PATCH /api/creative-commission/:id', () => {});describe('DELETE /api/creative-commission/:id', () => {- it('deletes + re-syncs', async () => {+ it('deletes the commission', 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/scheduler.js b/server/services/creativeCommissions/scheduler.jsindex 77ad7f5e84..1c560617bd 100644--- a/server/services/creativeCommissions/scheduler.js+++ b/server/services/creativeCommissions/scheduler.js@@ -24,13 +24,22 @@import { schedule, cancel, isValidCron } from '../eventScheduler.js';import { getUserTimezone } from '../../lib/timezone.js';-import { listCommissions, recordCommissionRun } from './store.js';+import { listCommissions, getCommission, recordCommissionRun, commissionEvents } from './store.js';import { commissionToCron, buildCommissionDirective } from './directive.js';const eventId = (commissionId) => `creative-commission-${commissionId}`;const registered = new Set();let lastSignature = null;+// Re-arm crons whenever a commission is created/updated/deleted through ANY+// writer, not just the REST route — mirrors seriesAutopilotScheduler's+// `settings:updated` subscription. The signature guard makes an unrelated+// change a cheap no-op.+commissionEvents.on('commission:changed', () => {+ syncCommissionSchedules().catch((err) =>+ console.error(`❌ Creative commission schedule re-sync failed: ${err.message}`));+});+/*** Enabled commissions whose schedule composes into a cron the scheduler honors.* Pure over the passed-in list.@@ -49,7 +58,7 @@ export function activeCommissions(commissions) {function signatureOf(active, fallbackTz) {return JSON.stringify({tz: fallbackTz || null,- s: active.map((e) => [e.id, e.cron, e.timezone ?? null]),+ s: active.map((e) => [e.id, e.cron, e.timezone]),});}@@ -107,7 +116,6 @@ export function stopCommissionScheduler() {*/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;diff --git a/server/services/creativeCommissions/scheduler.test.js b/server/services/creativeCommissions/scheduler.test.jsindex b4adc30828..098db250eb 100644--- a/server/services/creativeCommissions/scheduler.test.js+++ b/server/services/creativeCommissions/scheduler.test.js@@ -1,4 +1,5 @@import { describe, it, expect, vi, beforeEach } from 'vitest';+import { EventEmitter } from 'events';// eventScheduler is mocked so no real timers arm and isValidCron is deterministic.const scheduleMock = vi.fn();@@ -14,10 +15,12 @@ vi.mock('../../lib/timezone.js', () => ({ getUserTimezone: async () => 'UTC' }))const listCommissionsMock = vi.fn();const getCommissionMock = vi.fn();const recordRunMock = vi.fn(async () => ({}));+const commissionEvents = new EventEmitter();vi.mock('./store.js', () => ({listCommissions: (...a) => listCommissionsMock(...a),getCommission: (...a) => getCommissionMock(...a),recordCommissionRun: (...a) => recordRunMock(...a),+ commissionEvents,}));// CD graph + autonomy/budget mocks (dynamic-imported inside the fire handler).@@ -100,6 +103,15 @@ describe('startCommissionScheduler (no cold-boot generation)', () => {await syncCommissionSchedules();expect(cancelMock).toHaveBeenCalledWith('creative-commission-commission-1');});++ it('re-arms crons when the store emits commission:changed (any writer path)', async () => {+ listCommissionsMock.mockResolvedValue([videoCommission()]);+ // Emitting the store event should trigger a re-sync without the route calling in.+ commissionEvents.emit('commission:changed', { id: 'commission-1', action: 'create' });+ await vi.waitFor(() => expect(scheduleMock).toHaveBeenCalledWith(expect.objectContaining({+ id: 'creative-commission-commission-1',+ })));+ });});describe('runScheduledCommission gates', () => {diff --git a/server/services/creativeCommissions/store.js b/server/services/creativeCommissions/store.jsindex ebaa38c8e8..4b9882a88f 100644--- a/server/services/creativeCommissions/store.js+++ b/server/services/creativeCommissions/store.js@@ -8,20 +8,35 @@* 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.+ * every machine. Federation is Phase 2 work, and it must split this record: the+ * brief/feedback CAN federate, but the `schedule` field (+ a future "home peer"+ * pointer) MUST stay machine-local, or the whole double-run avoidance breaks.+ * seriesAutopilot already proved this shape out (local schedule → federated+ * series); Phase 2 will decompose the monolithic local record accordingly.** 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.+ *+ * Mutations emit `commission:changed` on `commissionEvents` so the scheduler+ * re-arms crons off the DATA changing (any writer), not off the three REST+ * handlers that happen to change it today — mirroring seriesAutopilot's+ * `settings:updated` seam and keeping the HTTP route decoupled from the+ * scheduler graph.*/import { join } from 'path';import { randomUUID } from 'crypto';+import { EventEmitter } from 'events';import { PATHS } from '../../lib/fileUtils.js';import { createCollectionStore } from '../../lib/collectionStore.js';import { isValidCron } from '../eventScheduler.js';import { commissionToCron } from './directive.js';+// Emits `commission:changed` on any create/update/delete (not on run-record+// appends, which don't affect scheduling). The scheduler subscribes to re-sync.+export const commissionEvents = new EventEmitter();+export const TYPE = 'creative-commissions';export const COMMISSIONS_SCHEMA_VERSION = 1;export const MAX_PERSISTED_RUNS = 50;@@ -134,9 +149,12 @@ export async function createCommission(input) {const store = commissionStore();const now = new Date().toISOString();const id = `commission-${randomUUID()}`;- const record = sanitizeCommission({ ...input, id, createdAt: now, updatedAt: now, runs: [], feedback: [] });+ // sanitizeCommission defaults runs/feedback to [] and the create schema carries+ // neither key, so no explicit empties are needed here.+ const record = sanitizeCommission({ ...input, id, createdAt: now, updatedAt: now });await ensureTypeIndex(store);await store.saveOne(id, record);+ commissionEvents.emit('commission:changed', { id, action: 'create' });return record;}@@ -144,8 +162,7 @@ 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);+ if (patch.schedule) assertValidSchedule(patch.schedule);const merged = sanitizeCommission({...current,...patch,@@ -159,6 +176,7 @@ export async function updateCommission(id, patch) {updatedAt: new Date().toISOString(),});await store.saveOne(id, merged);+ commissionEvents.emit('commission:changed', { id, action: 'update' });return merged;}@@ -167,6 +185,7 @@ export async function deleteCommission(id) {const current = await store.loadOne(id);if (!current) throw makeErr(`Commission not found: ${id}`, ERR_NOT_FOUND);await store.deleteOne(id);+ commissionEvents.emit('commission:changed', { id, action: 'delete' });return { id, deleted: true };}