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: add persistent CoS mind conversation (#5066)
[._.]/ Adam Eivyf739fbdbc389
diff --git a/client/src/components/Layout.jsx b/client/src/components/Layout.jsxindex a6243a8daa..ff7ec98640 100644--- a/client/src/components/Layout.jsx+++ b/client/src/components/Layout.jsx@@ -196,6 +196,7 @@ export const NAV_PRESENTATION = {'/cos/health': { icon: Activity },'/cos/learning': { icon: GraduationCap },'/cos/memory': { icon: Brain },+ '/cos/mind': { icon: MessageSquare },'/cos/run-events': { icon: ScrollText },'/cos/runs': { icon: Play },'/cos/schedule': { icon: Clock },diff --git a/client/src/components/cos/constants.js b/client/src/components/cos/constants.jsindex 5f13dd122f..370c6e4b20 100644--- a/client/src/components/cos/constants.js+++ b/client/src/components/cos/constants.js@@ -13,7 +13,8 @@ import {Newspaper,ChartGantt,Play,- ScrollText+ ScrollText,+ MessageCircle} from 'lucide-react';import { normalizeReviewerSlug } from '../../lib/reviewerPins';import { inPlaceClipName } from '../../utils/animationClips';@@ -32,6 +33,7 @@ export const TABS = [{ id: 'productivity', label: 'Streaks', icon: Flame },{ id: 'learning', label: 'Learning', icon: GraduationCap },{ id: 'memory', label: 'Memory', icon: Brain },+ { id: 'mind', label: 'Mind', icon: MessageCircle },{ id: 'health', label: 'Health', icon: Activity },{ id: 'config', label: 'Config', icon: Settings }];diff --git a/client/src/components/cos/tabs/MindTab.jsx b/client/src/components/cos/tabs/MindTab.jsxnew file mode 100644index 0000000000..8acfc3f39c--- /dev/null+++ b/client/src/components/cos/tabs/MindTab.jsx@@ -0,0 +1,323 @@+import { useCallback, useEffect, useRef, useState } from 'react';+import { useSearchParams } from 'react-router';+import { Check, CirclePause, CirclePlay, MessageCircle, RefreshCw, Square, Upload } from 'lucide-react';+import { useSocket } from '../../../hooks/useSocket';+import { uuidv4 } from '../../../lib/uuid.js';+import * as api from '../../../services/api';+import { formatDateTime } from '../../../utils/formatters';+import BrailleSpinner from '../../BrailleSpinner';+import Banner from '../../ui/Banner';++const PAGE_LIMIT = 200;+const MAX_BACKFILL_PAGES = 5;++const EVENT_LABELS = {+ 'mind.message.accepted': 'User input',+ 'mind.annotation.accepted': 'Annotation',+ 'mind.summary': 'Mind summary',+ 'mind.model.result': 'Mind summary',+ 'mind.capability.request': 'Action request',+ 'mind.capability.result': 'Action outcome',+ 'mind.memory.promoted': 'Memory promoted',+};++const eventLabel = (kind) => EVENT_LABELS[kind] || 'System state';+const eventText = (event) => {+ const data = event?.data || {};+ if (typeof data.displayText === 'string') return data.displayText;+ if (typeof data.summaryText === 'string') return data.summaryText;+ if (typeof data.error === 'string') return data.error;+ if (typeof data.status === 'string') return data.status;+ if (typeof data.capability === 'string') return data.capability;+ return null;+};++const mergeEvents = (previous, incoming) => {+ const byId = new Map(previous.map((event) => [event.eventId, event]));+ for (const event of incoming) byId.set(event.eventId, event);+ return [...byId.values()].sort((a, b) => a.sequence - b.sequence);+};++const mintId = (prefix) => `${prefix}-${uuidv4()}`;++export default function MindTab() {+ const [searchParams, setSearchParams] = useSearchParams();+ const selectedEventId = searchParams.get('event');+ const socket = useSocket();+ const [events, setEvents] = useState(null);+ const [mind, setMind] = useState(null);+ const [loadError, setLoadError] = useState(null);+ const [gap, setGap] = useState(false);+ const [loading, setLoading] = useState(true);+ const [kind, setKind] = useState('message');+ const [text, setText] = useState('');+ const [submitting, setSubmitting] = useState(false);+ const [submitError, setSubmitError] = useState(null);+ const [lifecyclePending, setLifecyclePending] = useState(null);+ const [lifecycleError, setLifecycleError] = useState(null);+ const cursorRef = useRef(null);+ const loadPendingRef = useRef(false);+ const deferredLoadRef = useRef(false);+ const draftIdRef = useRef(null);++ const loadHistory = useCallback(async ({ reset = false } = {}) => {+ if (loadPendingRef.current) {+ deferredLoadRef.current = true;+ return;+ }+ loadPendingRef.current = true;+ if (reset) setLoading(true);+ let cursor = reset ? null : cursorRef.current;+ let page = 0;+ let accumulated = [];+ let sawGap = false;+ let needsMore = false;+ try {+ do {+ const response = await api.getPersistentMind({ cursor, limit: PAGE_LIMIT }, { silent: true });+ accumulated = mergeEvents(accumulated, response.events || []);+ sawGap ||= response.gap === true;+ cursor = response.cursor || cursor;+ setMind({ state: response.state, profile: response.profile, autonomyMode: response.autonomyMode });+ page += 1;+ needsMore = response.hasMore === true && !sawGap;+ if (!needsMore) break;+ } while (page < MAX_BACKFILL_PAGES);+ cursorRef.current = cursor;+ setEvents((previous) => reset || sawGap || previous === null ? accumulated : mergeEvents(previous, accumulated));+ setGap(sawGap);+ setLoadError(null);+ if (needsMore) deferredLoadRef.current = true;+ } catch (error) {+ setLoadError(error?.message || 'Could not load the persistent mind');+ } finally {+ setLoading(false);+ loadPendingRef.current = false;+ if (deferredLoadRef.current) {+ deferredLoadRef.current = false;+ void loadHistory();+ }+ }+ }, []);++ useEffect(() => { void loadHistory({ reset: true }); }, [loadHistory]);++ useEffect(() => {+ const refresh = () => { void loadHistory(); };+ socket.on('connect', refresh);+ socket.on('cos:mind:event', refresh);+ socket.on('cos:mind:status', refresh);+ return () => {+ socket.off('connect', refresh);+ socket.off('cos:mind:event', refresh);+ socket.off('cos:mind:status', refresh);+ };+ }, [loadHistory, socket]);++ const submit = async (event) => {+ event.preventDefault();+ const trimmed = text.trim();+ if (!trimmed || submitting) return;+ const id = draftIdRef.current || mintId(kind);+ draftIdRef.current = id;+ setSubmitting(true);+ setSubmitError(null);+ try {+ if (kind === 'message') {+ await api.sendPersistentMindMessage({ id, text: trimmed }, { silent: true });+ } else {+ await api.addPersistentMindAnnotation({+ id,+ text: trimmed,+ targetEventId: selectedEventId || null,+ }, { silent: true });+ }+ const sequence = Math.max(-1, ...(events || []).map((item) => item.sequence || -1)) + 1;+ setEvents((previous) => mergeEvents(previous || [], [{+ eventId: `mind-${kind === 'message' ? 'message' : 'annotation'}:${id}`,+ kind: kind === 'message' ? 'mind.message.accepted' : 'mind.annotation.accepted',+ mindId: 'cos-persistent-mind',+ turnId: null,+ sequence,+ at: new Date().toISOString(),+ data: {+ displayText: trimmed,+ ...(kind === 'annotation' ? { annotationId: id, targetEventId: selectedEventId || null } : { messageId: id }),+ },+ }]));+ setText('');+ draftIdRef.current = null;+ await loadHistory();+ } catch (error) {+ setSubmitError(error?.message || 'The input was not accepted');+ } finally {+ setSubmitting(false);+ }+ };++ const changeKind = (next) => {+ setKind(next);+ draftIdRef.current = null;+ setSubmitError(null);+ };++ const runLifecycle = async (action) => {+ setLifecyclePending(action);+ setLifecycleError(null);+ try {+ if (action === 'start') await api.startPersistentMind({ silent: true });+ if (action === 'pause') await api.pausePersistentMind('Paused from Mind page', { silent: true });+ if (action === 'resume') await api.resumePersistentMind({ silent: true });+ if (action === 'stop') await api.stopPersistentMind({ silent: true });+ await loadHistory();+ } catch (error) {+ setLifecycleError(error?.message || `Could not ${action} the persistent mind`);+ } finally {+ setLifecyclePending(null);+ }+ };++ const acknowledge = async (event) => {+ setLifecycleError(null);+ try {+ await api.acknowledgePersistentMindEvent(event.eventId, mintId('ack'), { silent: true });+ await loadHistory();+ } catch (error) {+ setLifecycleError(error?.message || 'Could not acknowledge the action');+ }+ };++ const promote = async (event) => {+ const content = eventText(event);+ if (!content) return;+ setLifecycleError(null);+ try {+ await api.promotePersistentMindEvent(event.eventId, {+ id: mintId('promotion'), approved: true, content, summary: content.slice(0, 500), type: 'insight', category: 'other',+ }, { silent: true });+ await loadHistory();+ } catch (error) {+ setLifecycleError(error?.message || 'Could not promote the action');+ }+ };++ const state = mind?.state;+ const selectedEvent = events?.find((event) => event.eventId === selectedEventId) || null;+ const isPaused = state?.status === 'paused';++ return (+ <section aria-labelledby="mind-heading" className="space-y-4">+ <header className="flex flex-col gap-3 rounded border border-port-border bg-port-card p-4 sm:flex-row sm:items-start sm:justify-between">+ <div>+ <h2 id="mind-heading" className="flex items-center gap-2 text-lg font-semibold text-port-text">+ <MessageCircle size={20} aria-hidden="true" /> Persistent Mind+ </h2>+ <p className="mt-1 text-sm text-port-text-muted">One durable, machine-local conversation with the resident Chief of Staff mind.</p>+ <p className="mt-2 text-xs text-port-text-muted">+ {mind ? `${mind.profile?.providerId || 'No provider'} · ${mind.profile?.model || 'No model'} · ${mind.profile?.effort || 'provider default'} · autonomy ${mind.autonomyMode}` : 'Profile unavailable'}+ </p>+ </div>+ <div className="flex flex-wrap gap-2" aria-label="Persistent mind lifecycle">+ {!state?.started && <ActionButton label="Start" icon={CirclePlay} pending={lifecyclePending === 'start'} onClick={() => runLifecycle('start')} />}+ {state?.started && !isPaused && <ActionButton label="Pause" icon={CirclePause} pending={lifecyclePending === 'pause'} onClick={() => runLifecycle('pause')} />}+ {state?.started && isPaused && <ActionButton label="Resume" icon={CirclePlay} pending={lifecyclePending === 'resume'} onClick={() => runLifecycle('resume')} />}+ {state?.started && <ActionButton label="Stop" icon={Square} pending={lifecyclePending === 'stop'} onClick={() => runLifecycle('stop')} />}+ <ActionButton label="Reload" icon={RefreshCw} pending={loading} onClick={() => loadHistory({ reset: true })} />+ </div>+ </header>++ {gap && <Banner tone="warning" title="History gap detected">The saved cursor is no longer retained. The visible trace was reloaded from the newest bounded snapshot.</Banner>}+ {loadError && <Banner tone="error" title="Conversation unavailable">{loadError}. Existing messages are preserved; retry when the connection recovers.</Banner>}+ {lifecycleError && <Banner tone="error" title="Action failed">{lifecycleError}</Banner>}++ <div data-testid="mind-layout" className="grid gap-4 lg:grid-cols-[minmax(0,1fr)_minmax(18rem,0.42fr)]">+ <div className="min-w-0 rounded border border-port-border bg-port-card">+ <div className="border-b border-port-border px-4 py-3 text-sm text-port-text-muted">+ Status: <span className="font-medium text-port-text">{state?.status || 'unknown'}</span>+ {state?.pauseReason ? ` · ${state.pauseReason}` : ''}+ </div>+ {loading && events === null ? (+ <div className="flex justify-center p-10"><BrailleSpinner text="Loading mind history" /></div>+ ) : events?.length === 0 && !loadError ? (+ <p className="p-8 text-center text-sm text-port-text-muted">No conversation yet. Add a message or idea below.</p>+ ) : (+ <ol className="max-h-[52vh] space-y-2 overflow-y-auto p-3" aria-label="Persistent mind conversation">+ {(events || []).map((event) => {+ const selected = event.eventId === selectedEventId;+ const textValue = eventText(event);+ return (+ <li key={event.eventId}>+ <button+ type="button"+ onClick={() => setSearchParams((current) => {+ const next = new URLSearchParams(current);+ next.set('event', event.eventId);+ return next;+ })}+ aria-current={selected ? 'true' : undefined}+ className={`w-full rounded border p-3 text-left ${selected ? 'border-port-accent bg-port-accent/10' : 'border-port-border hover:bg-port-border/20'}`}+ >+ <span className="flex flex-wrap items-center justify-between gap-2">+ <span className="text-xs font-semibold uppercase tracking-wide text-port-accent">{eventLabel(event.kind)}</span>+ <time className="text-xs text-port-text-muted" dateTime={event.at}>{formatDateTime(event.at)}</time>+ </span>+ <span className="mt-1 block whitespace-pre-wrap break-words text-sm text-port-text">{textValue || event.kind}</span>+ {event.turnId && <span className="mt-1 block truncate font-mono text-[11px] text-port-text-muted">turn {event.turnId}</span>}+ </button>+ </li>+ );+ })}+ </ol>+ )}+ </div>++ <aside className="space-y-3 rounded border border-port-border bg-port-card p-4" aria-label="Selected mind event">+ <h3 className="text-sm font-semibold text-port-text">Selected event</h3>+ {selectedEvent ? (+ <>+ <p className="break-all font-mono text-xs text-port-text-muted">{selectedEvent.eventId}</p>+ <p className="text-sm text-port-text">{eventLabel(selectedEvent.kind)}</p>+ {selectedEvent.kind === 'mind.capability.request' && (+ <div className="flex flex-wrap gap-2">+ <ActionButton label="Acknowledge" icon={Check} onClick={() => acknowledge(selectedEvent)} />+ <ActionButton label="Promote" icon={Upload} disabled={!eventText(selectedEvent)} onClick={() => promote(selectedEvent)} />+ </div>+ )}+ </>+ ) : <p className="text-sm text-port-text-muted">Choose an event to keep the selection in the URL and attach an annotation.</p>}+ </aside>+ </div>++ <form onSubmit={submit} className="rounded border border-port-border bg-port-card p-4">+ <div className="grid gap-3 sm:grid-cols-[12rem_minmax(0,1fr)]">+ <div>+ <label htmlFor="mind-input-kind" className="mb-1 block text-sm font-medium text-port-text">Input type</label>+ <select id="mind-input-kind" value={kind} onChange={(event) => changeKind(event.target.value)} className="w-full rounded border border-port-border bg-port-bg px-3 py-2 text-sm text-port-text">+ <option value="message">Instruction / message</option>+ <option value="annotation">Comment / idea</option>+ </select>+ </div>+ <div>+ <label htmlFor="mind-input-text" className="mb-1 block text-sm font-medium text-port-text">{kind === 'message' ? 'Message' : 'Comment or idea'}</label>+ <textarea id="mind-input-text" value={text} onChange={(event) => setText(event.target.value)} maxLength={8000} rows={3} className="w-full resize-y rounded border border-port-border bg-port-bg px-3 py-2 text-sm text-port-text" placeholder={kind === 'message' ? 'What should the mind consider on its next eligible wake?' : 'Add context without turning it into an immediate task.'} />+ </div>+ </div>+ {kind === 'annotation' && selectedEventId && <p className="mt-2 text-xs text-port-text-muted">Attached to selected event {selectedEventId}</p>}+ {submitError && <p role="alert" className="mt-2 text-sm text-port-error">{submitError} — Retry uses the same id, so it will not duplicate the input.</p>}+ <div className="mt-3 flex justify-end">+ <button type="submit" disabled={!text.trim() || submitting} className="rounded bg-port-accent px-4 py-2 text-sm font-medium text-white disabled:cursor-not-allowed disabled:opacity-50">+ {submitting ? 'Submitting…' : submitError ? 'Retry' : 'Submit'}+ </button>+ </div>+ </form>+ </section>+ );+}++function ActionButton({ label, icon: Icon, pending = false, disabled = false, onClick }) {+ return (+ <button type="button" disabled={pending || disabled} onClick={onClick} className="flex min-h-[36px] items-center gap-2 rounded border border-port-border px-3 py-1.5 text-sm text-port-text hover:bg-port-border/30 disabled:cursor-not-allowed disabled:opacity-50">+ <Icon size={16} className={pending ? 'animate-spin' : ''} aria-hidden="true" /> {pending ? `${label}…` : label}+ </button>+ );+}diff --git a/client/src/components/cos/tabs/MindTab.test.jsx b/client/src/components/cos/tabs/MindTab.test.jsxnew file mode 100644index 0000000000..a5bf86fb2a--- /dev/null+++ b/client/src/components/cos/tabs/MindTab.test.jsx@@ -0,0 +1,142 @@+import { act } from 'react';+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { render, screen, waitFor } from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import { MemoryRouter } from 'react-router';++const api = vi.hoisted(() => ({+ getPersistentMind: vi.fn(),+ sendPersistentMindMessage: vi.fn(),+ addPersistentMindAnnotation: vi.fn(),+ startPersistentMind: vi.fn(),+ pausePersistentMind: vi.fn(),+ resumePersistentMind: vi.fn(),+ stopPersistentMind: vi.fn(),+ acknowledgePersistentMindEvent: vi.fn(),+ promotePersistentMindEvent: vi.fn(),+}));++const socket = vi.hoisted(() => {+ const handlers = new Map();+ return {+ on: vi.fn((event, handler) => handlers.set(event, handler)),+ off: vi.fn((event) => handlers.delete(event)),+ emitServer: (event, data) => handlers.get(event)?.(data),+ reset: () => handlers.clear(),+ };+});++vi.mock('../../../services/api', () => api);+vi.mock('../../../hooks/useSocket', () => ({ useSocket: () => socket }));++import MindTab from './MindTab';++const event = (overrides = {}) => ({+ eventId: 'mind-message:message-1',+ kind: 'mind.message.accepted',+ mindId: 'cos-persistent-mind',+ turnId: null,+ sequence: 1,+ at: '2026-08-26T12:00:00.000Z',+ data: { displayText: 'Review the next bounded slice.' },+ ...overrides,+});++const response = (overrides = {}) => ({+ events: [event()],+ cursor: '1:mind-message:message-1',+ gap: false,+ hasMore: false,+ snapshot: {},+ state: { enabled: true, started: true, status: 'waiting', pauseReason: null },+ profile: { enabled: true, providerId: 'demo', model: 'demo-model', effort: 'high', thinkingInterface: 'text' },+ autonomyMode: 'execute',+ ...overrides,+});++const renderTab = (path = '/cos/mind') => render(+ <MemoryRouter initialEntries={[path]}>+ <MindTab />+ </MemoryRouter>+);++describe('MindTab', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ socket.reset();+ api.getPersistentMind.mockResolvedValue(response());+ api.sendPersistentMindMessage.mockResolvedValue({ success: true, duplicate: false });+ api.addPersistentMindAnnotation.mockResolvedValue({ success: true, duplicate: false });+ api.startPersistentMind.mockResolvedValue({ success: true });+ api.pausePersistentMind.mockResolvedValue({ success: true });+ api.resumePersistentMind.mockResolvedValue({ success: true });+ api.stopPersistentMind.mockResolvedValue({ success: true });+ api.acknowledgePersistentMindEvent.mockResolvedValue({ success: true });+ api.promotePersistentMindEvent.mockResolvedValue({ success: true });+ });++ it('restores the selected event from the URL and uses a responsive single DOM tree', async () => {+ renderTab('/cos/mind?event=mind-message%3Amessage-1');++ expect(await screen.findByRole('button', { name: /user input/i })).toHaveAttribute('aria-current', 'true');+ expect(screen.getByTestId('mind-layout')).toHaveClass('grid');+ expect(screen.getByTestId('mind-layout').className).toContain('lg:grid-cols-');+ expect(screen.getByLabelText('Input type')).toBeInTheDocument();+ expect(screen.getByLabelText('Message')).toBeInTheDocument();+ });++ it('never renders a fetch failure as an empty conversation', async () => {+ api.getPersistentMind.mockRejectedValue(new Error('Server unreachable'));+ renderTab();++ expect(await screen.findByText('Conversation unavailable')).toBeInTheDocument();+ expect(screen.queryByText(/No conversation yet/)).not.toBeInTheDocument();+ });++ it('deduplicates a socket-triggered cursor backfill', async () => {+ renderTab();+ expect(await screen.findByText('Review the next bounded slice.')).toBeInTheDocument();++ api.getPersistentMind.mockResolvedValue(response({ events: [event()], hasMore: false }));+ await act(async () => { socket.emitServer('cos:mind:event', event()); });++ await waitFor(() => expect(api.getPersistentMind).toHaveBeenCalledTimes(2));+ expect(screen.getAllByText('Review the next bounded slice.')).toHaveLength(1);+ });++ it('shows an explicit reload state when reconnect backfill reports a gap', async () => {+ api.getPersistentMind.mockResolvedValue(response({ gap: true }));+ renderTab();++ expect(await screen.findByText('History gap detected')).toBeInTheDocument();+ expect(screen.getByText(/reloaded from the newest bounded snapshot/i)).toBeInTheDocument();+ });++ it('keeps a failed message for a visible idempotent retry', async () => {+ const user = userEvent.setup();+ api.sendPersistentMindMessage.mockRejectedValueOnce(new Error('Provider unavailable'));+ renderTab();+ await screen.findByText('Review the next bounded slice.');++ await user.type(screen.getByLabelText('Message'), 'Keep this queued.');+ await user.click(screen.getByRole('button', { name: 'Submit' }));+ expect(await screen.findByRole('alert')).toHaveTextContent(/Retry uses the same id/);+ expect(screen.getByLabelText('Message')).toHaveValue('Keep this queued.');++ await user.click(screen.getByRole('button', { name: 'Retry' }));+ await waitFor(() => expect(api.sendPersistentMindMessage).toHaveBeenCalledTimes(2));+ const firstId = api.sendPersistentMindMessage.mock.calls[0][0].id;+ expect(api.sendPersistentMindMessage.mock.calls[1][0].id).toBe(firstId);+ });++ it('renders only redacted display fields, never hidden prompt payloads', async () => {+ api.getPersistentMind.mockResolvedValue(response({ events: [event({+ kind: 'mind.model.result',+ data: { summaryText: 'A synthesized summary.', prompt: { redacted: 'content', chars: 5000 }, apiKey: 'not-rendered' },+ })] }));+ renderTab();++ expect(await screen.findByText('A synthesized summary.')).toBeInTheDocument();+ expect(screen.queryByText(/not-rendered|5000|prompt/i)).not.toBeInTheDocument();+ });+});diff --git a/client/src/pages/ChiefOfStaff.jsx b/client/src/pages/ChiefOfStaff.jsxindex 3b3612da28..da48ce427e 100644--- a/client/src/pages/ChiefOfStaff.jsx+++ b/client/src/pages/ChiefOfStaff.jsx@@ -41,6 +41,7 @@ const RunsTab = lazy(() => import('../components/cos/tabs/RunsTab'));// post-mortem surface nobody opens on a normal day, and it pulls the whole// ledger read path with it.const RunEventsTab = lazy(() => import('../components/cos/tabs/RunEventsTab'));+const MindTab = lazy(() => import('../components/cos/tabs/MindTab'));// The task and agent tabs are the default CoS landing surfaces and stay eager.// Every other tab is loaded only when selected so the common queue view does// not pay for charts, memory graphs, briefing readers, or configuration forms.@@ -1107,6 +1108,13 @@ export default function ChiefOfStaff() {</Suspense></div>)}+ {activeTab === 'mind' && (+ <div role="tabpanel" id="tabpanel-mind" aria-labelledby="tab-mind">+ <Suspense fallback={<TabLoadFallback label="mind" />}>+ <MindTab />+ </Suspense>+ </div>+ )}{activeTab === 'schedule' && (<div role="tabpanel" id="tabpanel-schedule" aria-labelledby="tab-schedule"><Suspense fallback={<TabLoadFallback label="schedule" />}>diff --git a/client/src/services/README.md b/client/src/services/README.mdindex bac40d645f..fb438e032f 100644--- a/client/src/services/README.md+++ b/client/src/services/README.md@@ -41,7 +41,7 @@ toasts on throw). **Custom catch ⇒ `silent: true`** — otherwise toasts fire| `apiApps.js` | App CRUD + PM2 ops (start/stop/restart/logs) + local open actions (editor, Claude Code, folder, Xcode) + `getAppIssues` (open GitHub/GitLab issues for the Issues tab). || `apiWorkspaceContexts.js` | Per-project working-context save/restore (branch, shells, tasks). || `apiAccounts.js` | Platform accounts. |-| `apiAgents.js` | Running-agent process management. |+| `apiAgents.js` | Running-agent process management, CoS run-event diagnostics, and persistent-mind conversation/lifecycle calls. || `apiCommands.js` | CLI command dispatch. || `apiDashboard.js` | Dashboard state. || `apiDatabase.js` | Database introspection. |diff --git a/client/src/services/apiAgents.js b/client/src/services/apiAgents.jsindex b4a9b1f8a5..a5cce9f115 100644--- a/client/src/services/apiAgents.js+++ b/client/src/services/apiAgents.js@@ -60,6 +60,30 @@ export const getRunReconciliation = (filters = {}, options = {}) =>export const repairRunRecords = (body = {}, options = {}) =>request('/agents/activity/run-events/reconcile', { method: 'POST', body: JSON.stringify(body), ...options });+// Persistent CoS mind — the cursor read is both the initial bounded snapshot+// and the reconnect backfill path. Writes carry caller-minted ids so retrying a+// timed-out request cannot duplicate a message or annotation.+export const getPersistentMind = (filters = {}, options = {}) =>+ request(`/cos/mind${runEventQuery(filters)}`, options);+export const sendPersistentMindMessage = (body, options = {}) =>+ request('/cos/mind/messages', { method: 'POST', body: JSON.stringify(body), ...options });+export const addPersistentMindAnnotation = (body, options = {}) =>+ request('/cos/mind/annotations', { method: 'POST', body: JSON.stringify(body), ...options });+export const startPersistentMind = (options = {}) => request('/cos/mind/start', { method: 'POST', ...options });+export const pausePersistentMind = (reason, options = {}) => request('/cos/mind/pause', {+ method: 'POST', body: JSON.stringify({ reason }), ...options,+});+export const resumePersistentMind = (options = {}) => request('/cos/mind/resume', { method: 'POST', ...options });+export const stopPersistentMind = (options = {}) => request('/cos/mind/stop', { method: 'POST', ...options });+export const acknowledgePersistentMindEvent = (eventId, id, options = {}) =>+ request(`/cos/mind/events/${encodeURIComponent(eventId)}/acknowledge`, {+ method: 'POST', body: JSON.stringify({ id }), ...options,+ });+export const promotePersistentMindEvent = (eventId, body, options = {}) =>+ request(`/cos/mind/events/${encodeURIComponent(eventId)}/promote`, {+ method: 'POST', body: JSON.stringify(body), ...options,+ });+// Chief of Staffexport const getCosStatus = () => request('/cos');export const startCos = (options = {}) => request('/cos/start', { method: 'POST', ...options });diff --git a/server/lib/README.md b/server/lib/README.mdindex 72f503d95b..a99e18e003 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -43,6 +43,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `persistentMind.js` | Pure persistent-CoS-mind runtime state: default-off durable shape, normalization, FIFO-message/self-wake selection, interrupted-wake requeue, bounded exponential backoff, watchdog staleness, and next-wake projection. || `persistentMindTrajectory.js` | Pure persistent-mind trajectory vocabulary, sequence cursor parsing, replay projection, provenance-tagged rollup validation, and hard-budget context assembly with explicit empty/missing/failed/stale summary states. || `persistentMindProfile.js` | Versioned, default-off persistent-mind provider profile (`enabled`, provider/model/effort, text interface), its strict API schema, and safe partial-update merge that clears model/effort on a provider switch. |+| `persistentMindPublic.js` | `publicPersistentMindState(state)` — the sole client/socket projection of durable mind state: exposes lifecycle fields and queue count, drops queued message bodies/active wake payloads, and replaces free-form provider errors with coarse safe reasons. || `heavyJobClaim.js` | Cross-process, machine-wide accelerator claim: `claimHeavyLocalJob({ kind, id, timeoutMs? })` either acquires an ephemeral `data/` lock or reports its active holder; dead-PID claims are reclaimed, and a spawned child can take over the recorded PID across a server restart. || `agentValidation.js` | Social-bot agent schemas (personality, Moltbook/Moltworld accounts, automation schedules, agent tools + Moltworld payloads) and CoS Feature Agent definitions. || `quotaBurnConfig.js` | Quota-burn plan shape: the provider families, the burn-job type alphabet + catalog the config page renders its form from, `QUOTA_BURN_BOUNDS` (the one bounds table the normalizer clamps to, the Zod schemas reject against, and the catalog descriptors publish as min/max), and total normalization (`normalizeQuotaBurnConfig`). Owns the dispatch-cap sentinel too (`QUOTA_BURN_UNLIMITED_DISPATCHES` / `isUnlimitedDispatchCap`) — -1 means the window is not counted, and is the default. Also owns the queued burn task's description shape (`burnTaskDescription` / `quotaBurnFamilyOfDescription`), shared with migration 225, and the `run once` vocabulary (`quotaBurnJobKey` / `jobIsSpent`, plus the two family predicates `familyIsConfigured` and `familyHasRunnableJobs`). Pure — no storage, no provider I/O. |diff --git a/server/lib/index.js b/server/lib/index.jsindex b1dad1f43a..77126fae07 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -48,6 +48,7 @@ export * as spriteValidation from './spriteValidation.js';export * as storyBuilderValidation from './storyBuilderValidation.js';export * as telegramValidation from './telegramValidation.js';export * from './validation.js';+export * from './persistentMindPublic.js';// Cross-domain Zod fragments both `validation.js` and the per-domain files// import (leaf module, no cycle). Flat because `validation.js` re-exports the// same objects — same identity, so the collision detector is satisfied.diff --git a/server/lib/navManifest.js b/server/lib/navManifest.jsindex 5528f22166..51a001a852 100644--- a/server/lib/navManifest.js+++ b/server/lib/navManifest.js@@ -157,6 +157,7 @@ const RAW_NAV_COMMANDS = [{ id: 'nav.cos.health', path: '/cos/health', label: 'Health', section: 'Chief of Staff', aliases: ['cos-health', 'health'] },{ id: 'nav.cos.learning', path: '/cos/learning', label: 'Learning', section: 'Chief of Staff', aliases: ['cos-learning'] },{ id: 'nav.cos.memory', path: '/cos/memory', label: 'Memory', section: 'Chief of Staff', aliases: ['cos-memory'] },+ { id: 'nav.cos.mind', path: '/cos/mind', label: 'Mind', section: 'Chief of Staff', aliases: ['cos-mind', 'persistent-mind', 'mind-chat'], keywords: ['persistent mind', 'chat', 'annotation', 'resident mind', 'conversation'] },{ id: 'nav.cos.runs', path: '/cos/runs', label: 'Runs', section: 'Chief of Staff', previousPaths: ['/devtools/runs'], aliases: ['runs', 'ai-runs', 'cos-runs', 'recent-runs', 'run-history'], keywords: ['runs', 'run history', 'recent runs', 'ai runs', 'agent runs', 'failed runs'] },{ id: 'nav.cos.run-events', path: '/cos/run-events', label: 'Run Events', section: 'Chief of Staff', aliases: ['run-events', 'cos-run-events', 'run-event-ledger', 'lifecycle-events'], keywords: ['run events', 'lifecycle', 'ledger', 'replay', 'diagnostics', 'orphaned', 'handoff', 'reconnect', 'interrupted', 'why did this run fail'] },{ id: 'nav.cos.schedule', path: '/cos/schedule', label: 'Schedule', section: 'Chief of Staff', aliases: ['schedule', 'cos-schedule'] },diff --git a/server/lib/persistentMindPublic.js b/server/lib/persistentMindPublic.jsnew file mode 100644index 0000000000..26a7397548--- /dev/null+++ b/server/lib/persistentMindPublic.js@@ -0,0 +1,24 @@+/** Safe client projection for the machine-local persistent-mind state. */++const publicReason = (state) => {+ if (!state.pauseReason) return null;+ if (state.status === 'paused') return 'Paused by user';+ if (state.status === 'degraded' || state.status === 'failed') return 'Provider unavailable or wake failed';+ return 'Waiting for the next eligible wake';+};++export function publicPersistentMindState(state = {}) {+ return {+ enabled: state.enabled === true,+ started: state.started === true,+ status: typeof state.status === 'string' ? state.status : 'unknown',+ pauseReason: publicReason(state),+ queuedMessageCount: Array.isArray(state.queuedMessages) ? state.queuedMessages.length : 0,+ activeTurnId: typeof state.activeTurn?.id === 'string' ? state.activeTurn.id : null,+ lastCompletedTurnId: typeof state.lastCompletedTurnId === 'string' ? state.lastCompletedTurnId : null,+ lastCompletedAt: typeof state.lastCompletedAt === 'string' ? state.lastCompletedAt : null,+ nextEligibleWakeAt: typeof state.nextEligibleWakeAt === 'string' ? state.nextEligibleWakeAt : null,+ failureCount: Number.isInteger(state.failureCount) ? state.failureCount : 0,+ lastError: state.lastError ? 'The last wake did not complete; local diagnostics have details' : null,+ };+}diff --git a/server/routes/cos.js b/server/routes/cos.jsindex e8eb1c833c..3a3cffe53b 100644--- a/server/routes/cos.js+++ b/server/routes/cos.js@@ -13,6 +13,7 @@ import jobRoutes from './cosJobRoutes.js';import templateRoutes from './cosTemplateRoutes.js';import insightRoutes from './cosInsightRoutes.js';import workflowRoutes from './cosWorkflowRoutes.js';+import mindRoutes from './cosMindRoutes.js';const router = Router();@@ -26,5 +27,6 @@ router.use(jobRoutes);router.use(templateRoutes);router.use(insightRoutes);router.use(workflowRoutes);+router.use(mindRoutes);export default router;diff --git a/server/routes/cosMindRoutes.js b/server/routes/cosMindRoutes.jsnew file mode 100644index 0000000000..cf8e2a9d70--- /dev/null+++ b/server/routes/cosMindRoutes.js@@ -0,0 +1,139 @@+/** Persistent Chief-of-Staff mind conversation and lifecycle routes. */++import { Router } from 'express';+import { z } from 'zod';+import { asyncHandler, ServerError } from '../lib/errorHandler.js';+import { getDomainMode } from '../lib/domainAutonomy.js';+import { PERSISTENT_MIND_LIMITS } from '../lib/persistentMind.js';+import {+ PERSISTENT_MIND_ID,+ PERSISTENT_MIND_TRAJECTORY_LIMITS,+ parsePersistentMindCursor,+} from '../lib/persistentMindTrajectory.js';+import { normalizePersistentMindProfile } from '../lib/persistentMindProfile.js';+import { publicPersistentMindState } from '../lib/persistentMindPublic.js';+import { validateRequest } from '../lib/validation.js';+import { readPersistentMindEvents } from '../services/agentRunEventLog.js';+import { loadState } from '../services/cosState.js';+import {+ appendPersistentMindAnnotation,+ promotePersistentMindMemory,+} from '../services/persistentMindContext.js';+import {+ enqueuePersistentMindMessage,+ getPersistentMindState,+ pausePersistentMind,+ resumePersistentMind,+ startPersistentMind,+ stopPersistentMind,+} from '../services/persistentMindSupervisor.js';++const router = Router();++const idempotencyId = z.string().trim().min(1).max(200);+const eventId = z.string().trim().min(1).max(128);+const text = z.string().trim().min(1).max(PERSISTENT_MIND_LIMITS.MAX_MESSAGE_CHARS);+const mindReadSchema = z.object({+ cursor: z.string().max(260).refine((value) => parsePersistentMindCursor(value) !== null, 'Invalid cursor').optional(),+ limit: z.coerce.number().int().positive().max(PERSISTENT_MIND_TRAJECTORY_LIMITS.maxPageSize).optional(),+}).strict();+const messageSchema = z.object({ id: idempotencyId, text }).strict();+const annotationSchema = z.object({+ id: idempotencyId,+ text,+ turnId: z.string().trim().min(1).max(128).nullable().optional(),+ targetEventId: eventId.nullable().optional(),+}).strict();+const pauseSchema = z.object({ reason: z.string().trim().min(1).max(PERSISTENT_MIND_LIMITS.MAX_REASON_CHARS).optional() }).strict();+const acknowledgementSchema = z.object({ id: idempotencyId }).strict();+const eventParamsSchema = z.object({ eventId }).strict();+const promotionSchema = z.object({+ id: idempotencyId,+ approved: z.literal(true),+ content: z.string().trim().min(1).max(10_240),+ summary: z.string().trim().max(500).optional(),+ turnId: z.string().trim().min(1).max(128).nullable().optional(),+ type: z.enum(['fact', 'preference', 'pattern', 'insight', 'context']).optional(),+ category: z.string().trim().min(1).max(100).optional(),+ tags: z.array(z.string().trim().min(1).max(100)).max(20).optional(),+}).strict();++const requireSuccess = (result) => {+ if (result?.success === false) {+ throw new ServerError(result.error || 'Persistent mind request was refused', { status: 409, code: 'INVALID_STATE' });+ }+ return result;+};++router.get('/mind', asyncHandler(async (req, res) => {+ const query = validateRequest(mindReadSchema, req.query);+ const [history, state, root] = await Promise.all([+ readPersistentMindEvents({ mindId: PERSISTENT_MIND_ID, ...query }),+ getPersistentMindState(),+ loadState(),+ ]);+ const profile = normalizePersistentMindProfile(root.config?.persistentMindProfile);+ res.json({+ ...history,+ state: publicPersistentMindState(state),+ profile: {+ enabled: profile.enabled,+ providerId: profile.providerId || null,+ model: profile.model || null,+ effort: profile.effort || null,+ thinkingInterface: profile.thinkingInterface,+ },+ autonomyMode: getDomainMode(root.config, 'cos'),+ });+}));++router.post('/mind/messages', asyncHandler(async (req, res) => {+ const input = validateRequest(messageSchema, req.body);+ res.status(202).json(requireSuccess(await enqueuePersistentMindMessage(input)));+}));++router.post('/mind/annotations', asyncHandler(async (req, res) => {+ const input = validateRequest(annotationSchema, req.body);+ const result = await appendPersistentMindAnnotation(input);+ if (result.error) throw new ServerError(result.error, { status: 409, code: 'INVALID_STATE' });+ res.status(202).json({ success: true, duplicate: result.duplicate === true, annotationId: input.id });+}));++router.post('/mind/start', asyncHandler(async (_req, res) => {+ res.json(requireSuccess(await startPersistentMind()));+}));++router.post('/mind/pause', asyncHandler(async (req, res) => {+ const { reason } = validateRequest(pauseSchema, req.body ?? {});+ const result = requireSuccess(await pausePersistentMind(reason));+ res.json({ success: true, state: publicPersistentMindState(result.state) });+}));++router.post('/mind/resume', asyncHandler(async (_req, res) => {+ res.json(requireSuccess(await resumePersistentMind()));+}));++router.post('/mind/stop', asyncHandler(async (_req, res) => {+ res.json(requireSuccess(await stopPersistentMind()));+}));++router.post('/mind/events/:eventId/acknowledge', asyncHandler(async (req, res) => {+ const { eventId: targetEventId } = validateRequest(eventParamsSchema, req.params);+ const { id } = validateRequest(acknowledgementSchema, req.body);+ const result = await appendPersistentMindAnnotation({+ id,+ targetEventId,+ text: 'Acknowledged by user',+ });+ if (result.error) throw new ServerError(result.error, { status: 409, code: 'INVALID_STATE' });+ res.status(202).json({ success: true, duplicate: result.duplicate === true, acknowledgementId: id });+}));++router.post('/mind/events/:eventId/promote', asyncHandler(async (req, res) => {+ const { eventId: sourceEventId } = validateRequest(eventParamsSchema, req.params);+ const { id: _id, ...input } = validateRequest(promotionSchema, req.body);+ const result = requireSuccess(await promotePersistentMindMemory({ ...input, sourceEventId }));+ res.status(201).json({ success: true, memoryId: result.memory?.id || null });+}));++export default router;diff --git a/server/routes/cosMindRoutes.test.js b/server/routes/cosMindRoutes.test.jsnew file mode 100644index 0000000000..54a49b7586--- /dev/null+++ b/server/routes/cosMindRoutes.test.js@@ -0,0 +1,144 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import express from 'express';+import { request } from '../lib/testHelper.js';+import { errorMiddleware } from '../lib/errorHandler.js';++const mocks = vi.hoisted(() => ({+ readPersistentMindEvents: vi.fn(),+ loadState: vi.fn(),+ getPersistentMindState: vi.fn(),+ enqueuePersistentMindMessage: vi.fn(),+ appendPersistentMindAnnotation: vi.fn(),+ promotePersistentMindMemory: vi.fn(),+ startPersistentMind: vi.fn(),+ pausePersistentMind: vi.fn(),+ resumePersistentMind: vi.fn(),+ stopPersistentMind: vi.fn(),+}));++vi.mock('../services/agentRunEventLog.js', () => ({ readPersistentMindEvents: mocks.readPersistentMindEvents }));+vi.mock('../services/cosState.js', () => ({ loadState: mocks.loadState }));+vi.mock('../services/persistentMindContext.js', () => ({+ appendPersistentMindAnnotation: mocks.appendPersistentMindAnnotation,+ promotePersistentMindMemory: mocks.promotePersistentMindMemory,+}));+vi.mock('../services/persistentMindSupervisor.js', () => ({+ getPersistentMindState: mocks.getPersistentMindState,+ enqueuePersistentMindMessage: mocks.enqueuePersistentMindMessage,+ startPersistentMind: mocks.startPersistentMind,+ pausePersistentMind: mocks.pausePersistentMind,+ resumePersistentMind: mocks.resumePersistentMind,+ stopPersistentMind: mocks.stopPersistentMind,+}));++import cosMindRoutes from './cosMindRoutes.js';++const app = () => {+ const instance = express();+ instance.use(express.json());+ instance.use('/api/cos', cosMindRoutes);+ instance.use(errorMiddleware);+ return instance;+};++const get = (path) => request(app()).get(`/api/cos${path}`);+const post = (path, body) => request(app()).post(`/api/cos${path}`).send(body);++describe('persistent mind routes', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mocks.readPersistentMindEvents.mockResolvedValue({ events: [], cursor: null, gap: false, hasMore: false, snapshot: {} });+ mocks.getPersistentMindState.mockResolvedValue({+ enabled: true, status: 'idle', started: false, queuedMessages: [{ id: 'private', text: 'must not leak' }],+ activeTurn: null, lastCompletedTurnId: null, lastCompletedAt: null, nextEligibleWakeAt: null,+ failureCount: 0, pauseReason: null, lastError: 'provider failed with \"apiKey\": \"secret-value\"',+ });+ mocks.loadState.mockResolvedValue({ config: { domainAutonomy: { cos: 'execute' }, persistentMindProfile: { enabled: true, providerId: 'demo', model: 'demo-model', effort: 'high' } } });+ mocks.enqueuePersistentMindMessage.mockResolvedValue({ success: true, duplicate: false, messageId: 'message-1' });+ mocks.appendPersistentMindAnnotation.mockResolvedValue({ appended: true, duplicate: false });+ mocks.promotePersistentMindMemory.mockResolvedValue({ success: true, memory: { id: 'memory-1' } });+ mocks.startPersistentMind.mockResolvedValue({ success: true });+ mocks.pausePersistentMind.mockResolvedValue({ success: true });+ mocks.resumePersistentMind.mockResolvedValue({ success: true });+ mocks.stopPersistentMind.mockResolvedValue({ success: true });+ });++ it('serves a bounded cursor snapshot with only the safe profile fields', async () => {+ const res = await get('/mind?cursor=12%3Amind-message%3Aone&limit=25');+ expect(res.status).toBe(200);+ expect(mocks.readPersistentMindEvents).toHaveBeenCalledWith({ mindId: 'cos-persistent-mind', cursor: '12:mind-message:one', limit: 25 });+ expect(res.body).toMatchObject({+ events: [], gap: false, state: { status: 'idle' },+ profile: { enabled: true, providerId: 'demo', model: 'demo-model', effort: 'high', thinkingInterface: 'text' },+ autonomyMode: 'execute',+ });+ expect(res.body.profile).not.toHaveProperty('credential');+ expect(res.body.state).not.toHaveProperty('queuedMessages');+ expect(res.body.state.queuedMessageCount).toBe(1);+ expect(JSON.stringify(res.body)).not.toContain('secret-value');+ });++ it('rejects malformed cursors, oversized pages, and unknown query fields', async () => {+ expect((await get('/mind?cursor=broken')).status).toBe(400);+ expect((await get('/mind?limit=501')).status).toBe(400);+ expect((await get('/mind?secret=1')).status).toBe(400);+ expect(mocks.readPersistentMindEvents).not.toHaveBeenCalled();+ });++ it('passes the caller id through so a retried message is idempotent', async () => {+ const first = await post('/mind/messages', { id: 'message-1', text: 'Consider the next bounded slice.' });+ mocks.enqueuePersistentMindMessage.mockResolvedValue({ success: true, duplicate: true, messageId: 'message-1' });+ const retry = await post('/mind/messages', { id: 'message-1', text: 'Consider the next bounded slice.' });++ expect(first.status).toBe(202);+ expect(retry.status).toBe(202);+ expect(retry.body.duplicate).toBe(true);+ expect(mocks.enqueuePersistentMindMessage).toHaveBeenNthCalledWith(2, { id: 'message-1', text: 'Consider the next bounded slice.' });+ });++ it('validates annotation targets and lifecycle inputs', async () => {+ expect((await post('/mind/annotations', { id: '', text: 'Idea' })).status).toBe(400);+ expect((await post('/mind/annotations', { id: 'annotation-1', text: 'Idea', extra: true })).status).toBe(400);+ expect((await post('/mind/pause', { reason: '' })).status).toBe(400);++ const accepted = await post('/mind/annotations', {+ id: 'annotation-1', text: 'Keep this as context.', turnId: 'turn-1', targetEventId: 'event-1',+ });+ expect(accepted.status).toBe(202);+ expect(mocks.appendPersistentMindAnnotation).toHaveBeenCalledWith({+ id: 'annotation-1', text: 'Keep this as context.', turnId: 'turn-1', targetEventId: 'event-1',+ });+ });++ it('projects lifecycle state instead of returning queued message bodies', async () => {+ mocks.pausePersistentMind.mockResolvedValue({+ success: true,+ state: {+ enabled: true, started: true, status: 'paused', queuedMessages: [{ id: 'private', text: 'must not leak' }],+ pauseReason: 'Paused from Mind page', activeTurn: null, failureCount: 0,+ },+ });+ const res = await post('/mind/pause', { reason: 'Paused from Mind page' });+ expect(res.status).toBe(200);+ expect(res.body.state).toMatchObject({ status: 'paused', queuedMessageCount: 1 });+ expect(JSON.stringify(res.body)).not.toContain('must not leak');+ });++ it('fails visibly when the supervisor refuses a lifecycle transition', async () => {+ mocks.startPersistentMind.mockResolvedValue({ success: false, error: 'Persistent mind is disabled' });+ const res = await post('/mind/start');+ expect(res.status).toBe(409);+ expect(res.body.error).toBe('Persistent mind is disabled');+ });++ it('requires explicit approval before promoting a redacted event summary', async () => {+ expect((await post('/mind/events/event-1/promote', { id: 'promotion-1', approved: false, content: 'Safe summary' })).status).toBe(400);+ const res = await post('/mind/events/event-1/promote', {+ id: 'promotion-1', approved: true, content: 'Safe summary', type: 'insight', category: 'other',+ });+ expect(res.status).toBe(201);+ expect(mocks.promotePersistentMindMemory).toHaveBeenCalledWith(expect.objectContaining({+ approved: true, content: 'Safe summary', sourceEventId: 'event-1',+ }));+ });+});diff --git a/server/services/agentRunEventLog.js b/server/services/agentRunEventLog.jsindex db5f741817..77448b3553 100644--- a/server/services/agentRunEventLog.js+++ b/server/services/agentRunEventLog.js@@ -39,6 +39,7 @@import { join } from 'path';import { rename, unlink } from 'fs/promises';+import { EventEmitter } from 'events';import {PATHS,atomicWrite,@@ -69,6 +70,10 @@ const ARCHIVE_PATH = join(PATHS.cos, 'run-events.1.jsonl');const MIND_SEQUENCE_PATH = join(PATHS.cos, 'persistent-mind-sequences.json');const MIND_SEQUENCE_SCHEMA_VERSION = 1;+// Live delivery is only a hint that a cursor-aware client should backfill from+// the durable ledger. The event itself is already redacted at construction.+export const runEventLogEvents = new EventEmitter();+/*** Events per generation. 5000 covers weeks of a busy install's lifecycle* boundaries at a few hundred bytes per line — a couple of MB per generation.@@ -328,8 +333,10 @@ export function appendRunEvent(input) {}/** Append one persistent-mind trajectory event through the shared queue. */-export function appendMindEvent(input) {- return appendRunEvent({ ...input, mindId: input?.mindId || PERSISTENT_MIND_ID });+export async function appendMindEvent(input) {+ const result = await appendRunEvent({ ...input, mindId: input?.mindId || PERSISTENT_MIND_ID });+ if (result.appended && result.event) runEventLogEvents.emit('mind:event', result.event);+ return result;}/** Resolve once every queued append has landed. Used by the read path + tests. */diff --git a/server/services/socket.js b/server/services/socket.jsindex 6551a91515..7813807bab 100644--- a/server/services/socket.js+++ b/server/services/socket.js@@ -35,6 +35,8 @@ import { cleanupSocketStreams, registerLogHandlers } from '../sockets/logs.js';import { detachShellSocket, registerShellHandlers } from '../sockets/shell.js';import { getBuildId } from '../lib/buildId.js';import { authEvents, extractToken, isAuthEnabled, verifySession } from './auth.js';+import { runEventLogEvents } from './agentRunEventLog.js';+import { publicPersistentMindState } from '../lib/persistentMindPublic.js';// Store CoS subscribersconst cosSubscribers = new Set();@@ -204,6 +206,14 @@ function setupEventForwarding() {setupWritersRoomEventForwarding();setupMusicVideoEventForwarding();setupProactiveSpeechForwarding();+ setupPersistentMindEventForwarding();+}++let persistentMindEventForwardingSetup = false;+function setupPersistentMindEventForwarding() {+ if (persistentMindEventForwardingSetup) return;+ persistentMindEventForwardingSetup = true;+ runEventLogEvents.on('mind:event', (event) => broadcastToCos('cos:mind:event', event));}export function initSocket(io) {@@ -322,6 +332,9 @@ function setupCosEventForwarding() {cosEvents.on('agent:completed', (data) => broadcastToCos('cos:agent:completed', data));cosEvents.on('agent:output', (data) => broadcastToCos('cos:agent:output', data));cosEvents.on('agent:btw', (data) => broadcastToCos('cos:agent:btw', data));+ cosEvents.on('persistent-mind:status', (data) => {+ broadcastToCos('cos:mind:status', publicPersistentMindState(data));+ });// Memory eventscosEvents.on('memory:created', (data) => broadcastToCos('cos:memory:created', data));