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 supervisor (#5064)
[._.]/ Adam Eivy755dfb9053eb
diff --git a/scripts/migrations/298-persistent-mind-runtime-state.js b/scripts/migrations/298-persistent-mind-runtime-state.jsnew file mode 100644index 0000000000..30f2d9b1e9--- /dev/null+++ b/scripts/migrations/298-persistent-mind-runtime-state.js@@ -0,0 +1,41 @@+/**+ * Add the default-off persistent-mind runtime slice to existing CoS state.+ *+ * Fresh installs receive the same shape from cosState.DEFAULT_STATE. Existing+ * installs get an explicit durable slice so later child issues can evolve it+ * through schemaVersion without mistaking absence for user consent.+ */++import { readFile } from 'fs/promises';+import { join } from 'path';+import { createDefaultPersistentMindState } from '../../server/lib/persistentMind.js';+import { atomicWrite } from '../../server/lib/fileUtils.js';++export default {+ async up({ rootDir }) {+ const statePath = join(rootDir, 'data', 'cos', 'state.json');+ const raw = await readFile(statePath, 'utf8').catch((error) => {+ if (error.code === 'ENOENT') return null;+ throw error;+ });+ if (raw == null) return { updated: 0, reason: 'no-state' };++ let state;+ try {+ state = JSON.parse(raw);+ } catch {+ return { updated: 0, reason: 'invalid-state' };+ }+ if (!state || typeof state !== 'object' || Array.isArray(state)) {+ return { updated: 0, reason: 'invalid-state' };+ }+ if (Object.hasOwn(state, 'persistentMind')) {+ return { updated: 0, reason: 'already-applied' };+ }++ state.persistentMind = createDefaultPersistentMindState();+ await atomicWrite(statePath, state);+ console.log('🧠 migration 298: added disabled persistent CoS mind runtime state');+ return { updated: 1 };+ },+};diff --git a/scripts/migrations/298-persistent-mind-runtime-state.test.js b/scripts/migrations/298-persistent-mind-runtime-state.test.jsnew file mode 100644index 0000000000..4e63176e21--- /dev/null+++ b/scripts/migrations/298-persistent-mind-runtime-state.test.js@@ -0,0 +1,48 @@+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';+import migration from './298-persistent-mind-runtime-state.js';++const readJson = (path) => JSON.parse(readFileSync(path, 'utf8'));++describe('migration 298 — persistent mind runtime state', () => {+ let rootDir;+ let statePath;++ beforeEach(() => {+ rootDir = mkdtempSync(join(tmpdir(), 'migration-298-persistent-mind-'));+ mkdirSync(join(rootDir, 'data', 'cos'), { recursive: true });+ statePath = join(rootDir, 'data', 'cos', 'state.json');+ });++ afterEach(() => rmSync(rootDir, { recursive: true, force: true }));++ it('does nothing when a fresh install has no CoS state yet', async () => {+ await expect(migration.up({ rootDir })).resolves.toEqual({ updated: 0, reason: 'no-state' });+ });++ it('adds a disabled, stopped runtime slice while preserving existing state', async () => {+ writeFileSync(statePath, JSON.stringify({ running: true, config: { alwaysOn: true }, agents: { a1: { status: 'completed' } } }));+ await expect(migration.up({ rootDir })).resolves.toEqual({ updated: 1 });+ expect(readJson(statePath)).toMatchObject({+ running: true,+ config: { alwaysOn: true },+ agents: { a1: { status: 'completed' } },+ persistentMind: { schemaVersion: 1, enabled: false, started: false, status: 'disabled' },+ });+ });++ it('is idempotent and never overwrites an existing runtime slice', async () => {+ const existing = { enabled: true, started: true, status: 'waiting', customFutureField: 'preserve' };+ writeFileSync(statePath, JSON.stringify({ persistentMind: existing }));+ await expect(migration.up({ rootDir })).resolves.toEqual({ updated: 0, reason: 'already-applied' });+ expect(readJson(statePath).persistentMind).toEqual(existing);+ });++ it('leaves a corrupted state file for cosState recovery instead of replacing it', async () => {+ writeFileSync(statePath, '{broken');+ await expect(migration.up({ rootDir })).resolves.toEqual({ updated: 0, reason: 'invalid-state' });+ expect(readFileSync(statePath, 'utf8')).toBe('{broken');+ });+});diff --git a/server/lib/README.md b/server/lib/README.mdindex df0d2a4606..18c38f8ea5 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -39,6 +39,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `agentRunEvents.js` | CoS run lifecycle-event envelope (#4540) — pure half of the append-only ledger in `services/agentRunEventLog.js`. `AGENT_RUN_EVENT_KINDS` (closed vocabulary: spawned, handoff, output, reconnected, paused, resumed, interrupted, pr-verified, orphan-recovered, runner-recovered, finalized), `agentRunEventSchema` (Zod, `.strict()`), `buildRunEvent()` which redacts then mints a CONTENT-derived `eventId` (sha256 of the canonicalized envelope) so a redelivered lifecycle transition dedupes instead of double-counting, `redactRunEventData()` (drops prompt/description/output/result-class keys to a `{ redacted, chars }` stub, scrubs the home-dir prefix out of every remaining string via `scrubHomePath`, runs `redactOutput`, and caps string/array/key/depth per `RUN_EVENT_LIMITS`), and `projectRunStates()` — the clock-free fold that derives current run status from the ordered stream, so replay-after-restart and read-current-status are one code path. Unknown kinds fold as no-ops so a newer install's ledger replays on an older one. || `agentRunReconcile.js` | CoS run reconciliation (#4540) — pure diff between a ledger projection (`projectRunStates`) and the durable run record. Closed finding vocabulary `RUN_RECONCILE_FINDINGS` (`record-open`, `record-missing`, `verdict-mismatch`, `ledger-open`), `diffRunRecord()`, `reconcileRunRecords()` with a zero-filled per-kind summary, and `planRunRecordRepair()` — the metadata patch that closes a record the ledger proves is finished. Repairs are one-directional (ledger → record) by design: a record closed while the ledger missed the close is reported, never back-filled, so the stream stays an audit of the record rather than a copy of it. I/O half: `services/agentRunReconciler.js`. || `agentSentinel.js` | The `.agent-done` completion sentinel: `DONE_SENTINEL_NAME`, `doneSentinelName(agentId)` → the per-instance filename `.agent-done-<agentId>` (worktree-less agents share one workspace, so a shared name lets concurrent runs clobber — and finalize on — each other's signal), `doneSentinelPath(workspacePath, agentId)` → the single path every producer and consumer resolves, + pure `parseSentinelPayload(contents)` → `{ summary, payload }`. Back-compat — a plain-markdown sentinel yields `payload: null`; a JSON object yields its structured `payload` for a programmatic-I/O task type's `processTaskOutput` hook. `salvageSentinelPayload(contents)` (async) is the lenient second tier — runs `jsonExtract` over a fenced/prose-trailed/control-char-corrupted envelope so a less-capable model's near-valid output still surfaces its `payload` instead of being dropped. `extractSentinelPayloadFromTranscript(transcript, isPayload)` (async) is the third tier for programmatic-I/O types ONLY — scans the ANSI-stripped PTY transcript, newest balanced JSON block first, for a payload the model PRINTED instead of writing, and adopts it only if the owning hook's shape predicate accepts it (#3640). `PROGRAMMATIC_OUTPUT_COMPLETION_HEADING` names the briefing section that prints this run's absolute sentinel path — a task-type hook renders its prompt before spawn, so it points the agent at that section by name rather than at a filename it cannot know. |+| `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. || `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 db7a5d1091..8c4800c784 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -214,6 +214,7 @@ export * from './agentGuard/index.js';export * from './agentOutputMarkers.js';export * from './agentRunEvents.js';export * from './agentRunReconcile.js';+export * from './persistentMind.js';export * from './agentSentinel.js';export * from './bareUrl.js';export * from './bashResolver.js';diff --git a/server/lib/persistentMind.js b/server/lib/persistentMind.jsnew file mode 100644index 0000000000..317f698794--- /dev/null+++ b/server/lib/persistentMind.js@@ -0,0 +1,219 @@+/**+ * Pure persistent-CoS-mind state helpers.+ *+ * The supervisor service owns I/O and timers. This module owns the durable+ * shape and clock-driven decisions so restart recovery can replay the same+ * rules without depending on module-level process state.+ */++export const PERSISTENT_MIND_SCHEMA_VERSION = 1;++export const PERSISTENT_MIND_STATUSES = [+ 'disabled',+ 'idle',+ 'thinking',+ 'waiting',+ 'paused',+ 'degraded',+ 'interrupted',+ 'stopping',+];++export const PERSISTENT_MIND_WAKE_KINDS = ['message', 'self'];++export const PERSISTENT_MIND_LIMITS = Object.freeze({+ MAX_QUEUED_MESSAGES: 100,+ MAX_RECENT_MESSAGE_IDS: 200,+ MAX_MESSAGE_CHARS: 8_000,+ MAX_REASON_CHARS: 500,+ BACKOFF_BASE_MS: 5_000,+ BACKOFF_MAX_MS: 15 * 60_000,+ WATCHDOG_STALE_MS: 5 * 60_000,+ MAX_QUIET_MS: 30 * 60_000,+});++const asIso = (value) => {+ if (typeof value !== 'string' || !Number.isFinite(Date.parse(value))) return null;+ return new Date(value).toISOString();+};++const asBoundedString = (value, max) => (+ typeof value === 'string' ? value.trim().slice(0, max) : ''+);++const asId = (value) => asBoundedString(value, 200);++const asCount = (value) => (+ Number.isSafeInteger(value) && value >= 0 ? value : 0+);++const sanitizeMessage = (value) => {+ const id = asId(value?.id);+ const text = asBoundedString(value?.text, PERSISTENT_MIND_LIMITS.MAX_MESSAGE_CHARS);+ if (!id || !text) return null;+ return {+ id,+ text,+ createdAt: asIso(value?.createdAt) || new Date(0).toISOString(),+ };+};++const sanitizeSelfWake = (value) => {+ const id = asId(value?.id);+ const reason = asBoundedString(value?.reason, PERSISTENT_MIND_LIMITS.MAX_REASON_CHARS);+ const sourceTurnId = asId(value?.sourceTurnId);+ if (!id || !reason || !sourceTurnId) return null;+ return {+ id,+ kind: 'self',+ reason,+ sourceTurnId,+ createdAt: asIso(value?.createdAt) || new Date(0).toISOString(),+ notBefore: asIso(value?.notBefore),+ };+};++const sanitizeWake = (value) => {+ if (value?.kind === 'message') {+ const message = sanitizeMessage(value.message);+ return message ? { kind: 'message', message } : null;+ }+ return sanitizeSelfWake(value);+};++const sanitizeActiveTurn = (value) => {+ const id = asId(value?.id);+ const wake = sanitizeWake(value?.wake);+ if (!id || !wake) return null;+ return {+ id,+ wake,+ startedAt: asIso(value?.startedAt) || new Date(0).toISOString(),+ heartbeatAt: asIso(value?.heartbeatAt) || asIso(value?.startedAt) || new Date(0).toISOString(),+ providerId: asId(value?.providerId) || null,+ model: asBoundedString(value?.model, 500) || null,+ effort: asBoundedString(value?.effort, 100) || null,+ };+};++export function createDefaultPersistentMindState() {+ return {+ schemaVersion: PERSISTENT_MIND_SCHEMA_VERSION,+ enabled: false,+ started: false,+ status: 'disabled',+ pauseReason: null,+ queuedMessages: [],+ selfWake: null,+ activeTurn: null,+ recentMessageIds: [],+ lastCompletedTurnId: null,+ lastCompletedAt: null,+ nextEligibleWakeAt: null,+ failureCount: 0,+ lastError: null,+ };+}++/** Normalize hand-edited, legacy, or partially migrated state. */+export function normalizePersistentMindState(raw) {+ const defaults = createDefaultPersistentMindState();+ const source = raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : {};+ const queuedMessages = [];+ const seenQueued = new Set();+ for (const candidate of Array.isArray(source.queuedMessages) ? source.queuedMessages : []) {+ const message = sanitizeMessage(candidate);+ if (!message || seenQueued.has(message.id)) continue;+ seenQueued.add(message.id);+ queuedMessages.push(message);+ if (queuedMessages.length >= PERSISTENT_MIND_LIMITS.MAX_QUEUED_MESSAGES) break;+ }+ const recentMessageIds = [];+ for (const candidate of Array.isArray(source.recentMessageIds) ? source.recentMessageIds : []) {+ const id = asId(candidate);+ if (!id || recentMessageIds.includes(id)) continue;+ recentMessageIds.push(id);+ }++ const enabled = source.enabled === true;+ const started = enabled && source.started === true;+ let status = PERSISTENT_MIND_STATUSES.includes(source.status)+ ? source.status+ : started ? 'idle' : enabled ? 'idle' : 'disabled';+ if (!enabled) status = 'disabled';+ else if (!started || status === 'disabled') status = 'idle';++ return {+ ...defaults,+ schemaVersion: PERSISTENT_MIND_SCHEMA_VERSION,+ enabled,+ started,+ status,+ pauseReason: asBoundedString(source.pauseReason, PERSISTENT_MIND_LIMITS.MAX_REASON_CHARS) || null,+ queuedMessages,+ selfWake: sanitizeSelfWake(source.selfWake),+ activeTurn: sanitizeActiveTurn(source.activeTurn),+ recentMessageIds: recentMessageIds.slice(-PERSISTENT_MIND_LIMITS.MAX_RECENT_MESSAGE_IDS),+ lastCompletedTurnId: asId(source.lastCompletedTurnId) || null,+ lastCompletedAt: asIso(source.lastCompletedAt),+ nextEligibleWakeAt: asIso(source.nextEligibleWakeAt),+ failureCount: asCount(source.failureCount),+ lastError: asBoundedString(source.lastError, PERSISTENT_MIND_LIMITS.MAX_REASON_CHARS) || null,+ };+}++export function persistentMindBackoffMs(failureCount) {+ const exponent = Math.max(0, Math.min(20, asCount(failureCount) - 1));+ return Math.min(+ PERSISTENT_MIND_LIMITS.BACKOFF_MAX_MS,+ PERSISTENT_MIND_LIMITS.BACKOFF_BASE_MS * (2 ** exponent)+ );+}++/** User messages always outrank a due self-wake. */+export function takeNextPersistentMindWake(raw, now = Date.now()) {+ const state = normalizePersistentMindState(raw);+ const gateAt = state.nextEligibleWakeAt ? Date.parse(state.nextEligibleWakeAt) : 0;+ if (Number.isFinite(gateAt) && gateAt > now) return { state, wake: null, dueAt: gateAt };++ if (state.queuedMessages.length > 0) {+ const [message, ...queuedMessages] = state.queuedMessages;+ return { state: { ...state, queuedMessages }, wake: { kind: 'message', message }, dueAt: now };+ }++ if (!state.selfWake) return { state, wake: null, dueAt: null };+ const dueAt = state.selfWake.notBefore ? Date.parse(state.selfWake.notBefore) : now;+ if (Number.isFinite(dueAt) && dueAt > now) return { state, wake: null, dueAt };+ return { state: { ...state, selfWake: null }, wake: state.selfWake, dueAt: now };+}++export function requeuePersistentMindWake(raw, wake) {+ const state = normalizePersistentMindState(raw);+ const sanitized = sanitizeWake(wake);+ if (!sanitized) return state;+ if (sanitized.kind === 'message') {+ const alreadyQueued = state.queuedMessages.some((message) => message.id === sanitized.message.id);+ const alreadyCompleted = state.recentMessageIds.includes(sanitized.message.id);+ return alreadyQueued || alreadyCompleted+ ? state+ : { ...state, queuedMessages: [sanitized.message, ...state.queuedMessages] };+ }+ return { ...state, selfWake: sanitized };+}++export function persistentMindTurnIsStale(raw, now = Date.now(), staleMs = PERSISTENT_MIND_LIMITS.WATCHDOG_STALE_MS) {+ const active = normalizePersistentMindState(raw).activeTurn;+ if (!active) return false;+ const heartbeatAt = Date.parse(active.heartbeatAt);+ return Number.isFinite(heartbeatAt) && now - heartbeatAt >= staleMs;+}++export function nextPersistentMindWakeAt(raw, now = Date.now()) {+ const state = normalizePersistentMindState(raw);+ if (!state.enabled || !state.started || state.activeTurn || state.status === 'paused') return null;+ const gateAt = state.nextEligibleWakeAt ? Date.parse(state.nextEligibleWakeAt) : now;+ if (state.queuedMessages.length > 0) return Math.max(now, gateAt || now);+ if (!state.selfWake) return null;+ const selfAt = state.selfWake.notBefore ? Date.parse(state.selfWake.notBefore) : now;+ return Math.max(now, gateAt || now, selfAt || now);+}diff --git a/server/lib/persistentMind.test.js b/server/lib/persistentMind.test.jsnew file mode 100644index 0000000000..c4b9d52cd9--- /dev/null+++ b/server/lib/persistentMind.test.js@@ -0,0 +1,90 @@+import { describe, expect, it } from 'vitest';+import {+ PERSISTENT_MIND_LIMITS,+ createDefaultPersistentMindState,+ nextPersistentMindWakeAt,+ normalizePersistentMindState,+ persistentMindBackoffMs,+ persistentMindTurnIsStale,+ requeuePersistentMindWake,+ takeNextPersistentMindWake,+} from './persistentMind.js';++const iso = (ms) => new Date(ms).toISOString();++describe('persistent mind state', () => {+ it('defaults to opt-in, stopped, and silent', () => {+ expect(createDefaultPersistentMindState()).toMatchObject({+ enabled: false,+ started: false,+ status: 'disabled',+ queuedMessages: [],+ selfWake: null,+ activeTurn: null,+ });+ });++ it('normalizes a partial legacy shape without treating missing state as enabled', () => {+ const state = normalizePersistentMindState({ started: true, queuedMessages: [{ id: 'm1', text: 'hello' }] });+ expect(state.enabled).toBe(false);+ expect(state.started).toBe(false);+ expect(state.status).toBe('disabled');+ expect(state.queuedMessages).toEqual([{ id: 'm1', text: 'hello', createdAt: iso(0) }]);+ });++ it('does not preserve a running status when the durable started flag is false', () => {+ expect(normalizePersistentMindState({ enabled: true, started: false, status: 'thinking' }).status).toBe('idle');+ expect(normalizePersistentMindState({ enabled: true, started: true, status: 'disabled' }).status).toBe('idle');+ });++ it('keeps FIFO user messages ahead of a due self-wake', () => {+ const base = {+ ...createDefaultPersistentMindState(), enabled: true, started: true, status: 'waiting',+ queuedMessages: [+ { id: 'm1', text: 'first', createdAt: iso(1) },+ { id: 'm2', text: 'second', createdAt: iso(2) },+ ],+ selfWake: { id: 'w1', kind: 'self', reason: 'idle', sourceTurnId: 't0', createdAt: iso(1), notBefore: iso(2) },+ };+ const first = takeNextPersistentMindWake(base, 10);+ const second = takeNextPersistentMindWake(first.state, 10);+ const third = takeNextPersistentMindWake(second.state, 10);+ expect(first.wake.message.id).toBe('m1');+ expect(second.wake.message.id).toBe('m2');+ expect(third.wake.id).toBe('w1');+ });++ it('does not consume work before the retry or self-wake deadline', () => {+ const state = {+ ...createDefaultPersistentMindState(), enabled: true, started: true,+ queuedMessages: [{ id: 'm1', text: 'wait', createdAt: iso(1) }],+ nextEligibleWakeAt: iso(1_000),+ };+ expect(takeNextPersistentMindWake(state, 500)).toMatchObject({ wake: null, dueAt: 1_000 });+ expect(nextPersistentMindWakeAt(state, 500)).toBe(1_000);+ });++ it('requeues an interrupted message once and never resurrects a completed id', () => {+ const wake = { kind: 'message', message: { id: 'm1', text: 'keep me', createdAt: iso(1) } };+ const once = requeuePersistentMindWake(createDefaultPersistentMindState(), wake);+ const twice = requeuePersistentMindWake(once, wake);+ const completed = requeuePersistentMindWake({ ...once, queuedMessages: [], recentMessageIds: ['m1'] }, wake);+ expect(twice.queuedMessages).toHaveLength(1);+ expect(completed.queuedMessages).toHaveLength(0);+ });++ it('caps exponential backoff and detects stale heartbeats at the boundary', () => {+ expect(persistentMindBackoffMs(1)).toBe(PERSISTENT_MIND_LIMITS.BACKOFF_BASE_MS);+ expect(persistentMindBackoffMs(99)).toBe(PERSISTENT_MIND_LIMITS.BACKOFF_MAX_MS);+ const state = {+ ...createDefaultPersistentMindState(), enabled: true, started: true, status: 'thinking',+ activeTurn: {+ id: 't1',+ wake: { kind: 'message', message: { id: 'm1', text: 'hello', createdAt: iso(1) } },+ startedAt: iso(1), heartbeatAt: iso(1), providerId: null, model: null, effort: null,+ },+ };+ expect(persistentMindTurnIsStale(state, 1 + PERSISTENT_MIND_LIMITS.WATCHDOG_STALE_MS - 1)).toBe(false);+ expect(persistentMindTurnIsStale(state, 1 + PERSISTENT_MIND_LIMITS.WATCHDOG_STALE_MS)).toBe(true);+ });+});diff --git a/server/services/cos.js b/server/services/cos.jsindex a86fd42e7e..865df4f6a1 100644--- a/server/services/cos.js+++ b/server/services/cos.js@@ -150,6 +150,25 @@ import {// `spawnDequeuePriorityN(ctx)` helpers.import { createDequeueCapacity, countRunningAgentsByLocalEndpoint, isMissionTierEligible, isIdleTierEligible } from './cosDequeue.js';import { buildLocalEndpointSlotContext, localEndpointCapacityError } from './cosLocalEndpointSlots.js';+import {+ initializePersistentMindSupervisor,+ shutdownPersistentMindSupervisor,+ handlePersistentMindGlobalPause,+ handlePersistentMindGlobalResume,+} from './persistentMindSupervisor.js';++export {+ getPersistentMindState,+ setPersistentMindEnabled,+ startPersistentMind,+ pausePersistentMind,+ resumePersistentMind,+ stopPersistentMind,+ enqueuePersistentMindMessage,+ requestPersistentMindWake,+ registerPersistentMindTurnAdapter,+ unregisterPersistentMindTurnAdapter,+} from './persistentMindSupervisor.js';/*** Get current CoS status@@ -425,6 +444,7 @@ export async function start() {emitLog('info', 'Running initial task evaluation...');await evaluateTasks({ initialStartup: true });await runHealthCheck();+ await initializePersistentMindSupervisor();cosEvents.emit('status', { running: true });emitLog('success', 'CoS daemon started');@@ -454,6 +474,8 @@ export async function stop() {return { success: false, error: 'Not running' };}+ await shutdownPersistentMindSupervisor();+// Cancel all scheduled eventscancelEvent('cos-health-check');cancelEvent('cos-performance-summary');@@ -479,7 +501,7 @@ export async function stop() {* Daemon stays running but skips evaluations*/export async function pause(reason = null) {- return withStateLock(async () => {+ const result = await withStateLock(async () => {const state = await loadState();if (state.paused) {@@ -495,6 +517,8 @@ export async function pause(reason = null) {cosEvents.emit('status:paused', { paused: true, pausedAt: state.pausedAt, reason });return { success: true, pausedAt: state.pausedAt };});+ if (result.success) await handlePersistentMindGlobalPause(reason || 'Chief of Staff paused');+ return result;}/**@@ -520,6 +544,7 @@ export async function resume() {// Trigger immediate task dequeue on resume (outside lock to avoid holding it)if (result.success && isDaemonRunning()) {+ await handlePersistentMindGlobalResume();setTimeout(() => dequeueNextTask(), RESUME_DEQUEUE_DELAY_MS);}diff --git a/server/services/cos.test.js b/server/services/cos.test.jsindex b3970cb6f8..f9be7b97c4 100644--- a/server/services/cos.test.js+++ b/server/services/cos.test.js@@ -35,7 +35,7 @@ import { readFileSync } from 'fs';import { fileURLToPath } from 'url';import { dirname, join } from 'path';import { firstLine, isPerpetualRefillCandidate, perpetualRefillPlan } from './cos.js';-import { canQueueImprovementTasks } from './cosState.js';+import { canQueueImprovementTasks, DEFAULT_STATE } from './cosState.js';import { createDequeueCapacity, countRunningAgentsByLocalEndpoint, isMissionTierEligible, isIdleTierEligible } from './cosDequeue.js';import {createLocalEndpointSlotContext,@@ -43,6 +43,7 @@ import {localEndpointOfProvider,providerBaseUrl,reserveLocalEndpointSpawn,+ acquireLocalEndpointProviderSlot,pendingLocalEndpointSpawns,__resetLocalEndpointSpawnReservations,readEndpointCapacity,@@ -913,6 +914,17 @@ describe('local-endpoint spawn reservations (#4834)', () => {expect(() => release()).not.toThrow();});+ it('gives a direct cloud provider call a no-op shared-capacity release', async () => {+ const claim = await acquireLocalEndpointProviderSlot(+ { id: 'cloud-api', endpoint: 'https://api.example.com/v1' },+ {},+ 'persistent-mind-turn'+ );+ expect(claim.ok).toBe(true);+ expect(() => claim.release()).not.toThrow();+ expect(pendingLocalEndpointSpawns(LOCAL_ENDPOINT)).toBe(0);+ });+it('keeps reservations per endpoint', () => {reserveLocalEndpointSpawn(LOCAL_ENDPOINT);reserveLocalEndpointSpawn(OTHER_LOCAL_ENDPOINT);@@ -2389,6 +2401,19 @@ describe('canQueueImprovementTasks — autonomous queuing gate', () => {});});+describe('persistent mind — default-off CoS state integration (#5064)', () => {+ it('adds no cold-bootstrap provider work to a fresh CoS state', () => {+ expect(DEFAULT_STATE.persistentMind).toMatchObject({+ schemaVersion: 1,+ enabled: false,+ started: false,+ status: 'disabled',+ queuedMessages: [],+ activeTurn: null,+ });+ });+});+describe('pending-merge sweep — own timer, not the evaluation cadence (#3630)', () => {// Evaluation is event-driven (cosState.js records that the periodic// evaluateTasks timer was removed), so the drain inside evaluateTasks firesdiff --git a/server/services/cosLocalEndpointSlots.js b/server/services/cosLocalEndpointSlots.jsindex 69e585a746..6da4a0ee64 100644--- a/server/services/cosLocalEndpointSlots.js+++ b/server/services/cosLocalEndpointSlots.js@@ -303,6 +303,25 @@ export async function acquireLocalEndpointSpawnSlot(task, agents) {return { ok: true, release: reserveLocalEndpointSpawn(endpoint, task?.id ?? null) };}+/**+ * Reserve the same local inference capacity for a non-agent provider call.+ *+ * Persistent-mind turns use PortOS's text-provider interface directly rather+ * than spawning a file-writing task agent. They still occupy the same model+ * server and must therefore share this accounting instead of inventing a+ * parallel GPU counter. Cloud providers return a no-op release.+ */+export async function acquireLocalEndpointProviderSlot(provider, agents, reservationId = null) {+ const endpoint = localEndpointOfProvider(provider);+ if (!endpoint) return { ok: true, release: NOOP_RELEASE };+ const slots = await buildLocalEndpointSlotContext();+ const { atCapacity, inFlight, limit } = readEndpointCapacity(endpoint, agents, slots);+ if (atCapacity) {+ return { ok: false, reason: `local endpoint ${endpoint} is at capacity (${inFlight}/${limit})` };+ }+ return { ok: true, release: reserveLocalEndpointSpawn(endpoint, reservationId) };+}+/*** Running agents plus in-flight reservations on `endpoint`, against the cap.*diff --git a/server/services/cosState.js b/server/services/cosState.jsindex cefbc0424f..ac0396b915 100644--- a/server/services/cosState.js+++ b/server/services/cosState.js@@ -11,6 +11,7 @@ import { createFileWriteQueue } from '../lib/fileWriteQueue.js';import { ensureDirs, safeJSONParse, PATHS, atomicWrite } from '../lib/fileUtils.js';import { normalizeDomainAutonomy, getDomainMode } from '../lib/domainAutonomy.js';import { normalizeDomainBudgets } from '../lib/domainBudgets.js';+import { createDefaultPersistentMindState, normalizePersistentMindState } from '../lib/persistentMind.js';import { DEFAULT_ALWAYS_APPROVE_KINDS } from './taskLearning/safetyKind.js';export const STATE_FILE = join(PATHS.cos, 'state.json');@@ -113,6 +114,7 @@ export const DEFAULT_STATE = {lastEvaluation: null,lastIdleReview: null},+ persistentMind: createDefaultPersistentMindState(),agents: {}};@@ -219,6 +221,7 @@ export async function loadState() {...state,config: { ...DEFAULT_CONFIG, ...persistedConfig },stats: { ...DEFAULT_STATE.stats, ...state.stats },+ persistentMind: normalizePersistentMindState(state.persistentMind),agents: state.agents ?? {}};return stateCache;diff --git a/server/services/persistentMindSupervisor.js b/server/services/persistentMindSupervisor.jsnew file mode 100644index 0000000000..9ea9bc92a3--- /dev/null+++ b/server/services/persistentMindSupervisor.js@@ -0,0 +1,633 @@+/**+ * Persistent CoS mind supervisor.+ *+ * This service owns liveness, durable wake admission, restart recovery, and+ * one-turn-at-a-time execution. It deliberately does not own provider/model+ * selection or the mind prompt: the model-profile slice registers an exact+ * provider adapter, and the trajectory slice supplies bounded context. Until+ * that adapter is registered, an explicitly started mind degrades visibly and+ * makes zero provider calls.+ */++import { randomUUID } from 'crypto';+import { getDomainMode } from '../lib/domainAutonomy.js';+import {+ PERSISTENT_MIND_LIMITS,+ createDefaultPersistentMindState,+ nextPersistentMindWakeAt,+ normalizePersistentMindState,+ persistentMindBackoffMs,+ persistentMindTurnIsStale,+ requeuePersistentMindWake,+ takeNextPersistentMindWake,+} from '../lib/persistentMind.js';+import { loadState, saveState, withStateLock } from './cosState.js';+import { cosEvents, emitLog } from './cosEvents.js';+import { schedule, cancel } from './eventScheduler.js';+import { getDomainBudgetStatus, recordDomainUsage } from './domainUsage.js';+import { acquireLocalEndpointProviderSlot } from './cosLocalEndpointSlots.js';++export const PERSISTENT_MIND_WAKE_EVENT_ID = 'cos-persistent-mind-wake';+export const PERSISTENT_MIND_WATCHDOG_EVENT_ID = 'cos-persistent-mind-watchdog';+export const PERSISTENT_MIND_WATCHDOG_INTERVAL_MS = 30_000;++let turnAdapter = null;+let activeRun = null;+let activeAbortController = null;+let runtimeGeneration = 0;++const nowIso = () => new Date().toISOString();+const errorMessage = (error) => String(error?.message || error || 'Persistent mind turn failed')+ .slice(0, PERSISTENT_MIND_LIMITS.MAX_REASON_CHARS);++async function mutateMindState(mutator) {+ return withStateLock(async () => {+ const root = await loadState();+ const mind = normalizePersistentMindState(root.persistentMind);+ const result = await mutator(mind, root);+ root.persistentMind = normalizePersistentMindState(result?.mind || mind);+ await saveState(root);+ return { state: root.persistentMind, value: result?.value };+ });+}++function emitMindStatus(state) {+ cosEvents.emit('persistent-mind:status', {+ enabled: state.enabled,+ started: state.started,+ status: state.status,+ pauseReason: state.pauseReason,+ queuedMessages: state.queuedMessages.length,+ activeTurnId: state.activeTurn?.id || null,+ lastCompletedTurnId: state.lastCompletedTurnId,+ nextEligibleWakeAt: state.nextEligibleWakeAt,+ });+}++function armWatchdog() {+ schedule({+ id: PERSISTENT_MIND_WATCHDOG_EVENT_ID,+ type: 'interval',+ intervalMs: PERSISTENT_MIND_WATCHDOG_INTERVAL_MS,+ handler: () => checkPersistentMindWatchdog(),+ metadata: { description: 'Persistent CoS mind stale-turn watchdog' },+ });+}++async function scheduleNextWake() {+ const root = await loadState();+ const state = normalizePersistentMindState(root.persistentMind);+ const dueAt = nextPersistentMindWakeAt(state);+ cancel(PERSISTENT_MIND_WAKE_EVENT_ID);+ if (dueAt == null || activeRun) return;+ schedule({+ id: PERSISTENT_MIND_WAKE_EVENT_ID,+ type: 'once',+ delayMs: Math.max(1, dueAt - Date.now()),+ handler: () => drainPersistentMind(),+ metadata: { description: 'Persistent CoS mind next eligible wake' },+ });+}++function initialSelfWake(reason) {+ const createdAt = nowIso();+ return {+ id: `wake-${randomUUID()}`,+ kind: 'self',+ reason,+ sourceTurnId: reason,+ createdAt,+ notBefore: createdAt,+ };+}++function quietSelfWake(turnId, notBefore = Date.now() + PERSISTENT_MIND_LIMITS.MAX_QUIET_MS) {+ return {+ id: `wake-${randomUUID()}`,+ kind: 'self',+ reason: 'maximum quiet period elapsed',+ sourceTurnId: turnId,+ createdAt: nowIso(),+ notBefore: new Date(notBefore).toISOString(),+ };+}++async function interruptActiveTurn(reason, status, { retry = false } = {}) {+ runtimeGeneration += 1;+ activeAbortController?.abort(reason);+ const result = await mutateMindState((mind) => {+ let next = mind;+ if (mind.activeTurn) next = requeuePersistentMindWake(next, mind.activeTurn.wake);+ const failureCount = retry ? next.failureCount + 1 : next.failureCount;+ return {+ mind: {+ ...next,+ activeTurn: null,+ status,+ pauseReason: reason,+ failureCount,+ lastError: reason,+ nextEligibleWakeAt: retry+ ? new Date(Date.now() + persistentMindBackoffMs(failureCount)).toISOString()+ : null,+ },+ };+ });+ emitMindStatus(result.state);+ return result.state;+}++async function parkActiveTurn(turnId, reason, status = 'waiting', retryAt = null) {+ const result = await mutateMindState((mind) => {+ if (mind.activeTurn?.id !== turnId) return { mind };+ const next = requeuePersistentMindWake(mind, mind.activeTurn.wake);+ const failureCount = next.failureCount + 1;+ return {+ mind: {+ ...next,+ activeTurn: null,+ status,+ pauseReason: reason,+ failureCount,+ lastError: reason,+ nextEligibleWakeAt: retryAt || new Date(Date.now() + persistentMindBackoffMs(failureCount)).toISOString(),+ },+ };+ });+ emitMindStatus(result.state);+ return result.state;+}++async function claimNextTurn() {+ const result = await mutateMindState((mind, root) => {+ if (!mind.enabled || !mind.started || mind.activeTurn || mind.status === 'paused') return { mind, value: null };+ if (root.paused || getDomainMode(root.config, 'cos') !== 'execute') return { mind, value: null };+ const selected = takeNextPersistentMindWake(mind);+ if (!selected.wake) return { mind: selected.state, value: null };+ const id = `mind-turn-${randomUUID()}`;+ const startedAt = nowIso();+ const activeTurn = {+ id,+ wake: selected.wake,+ startedAt,+ heartbeatAt: startedAt,+ providerId: null,+ model: null,+ effort: null,+ };+ return {+ mind: {+ ...selected.state,+ status: 'thinking',+ pauseReason: null,+ activeTurn,+ nextEligibleWakeAt: null,+ },+ value: activeTurn,+ };+ });+ if (result.value) emitMindStatus(result.state);+ return result.value;+}++async function recordTurnProfile(turnId, prepared) {+ await mutateMindState((mind) => {+ if (mind.activeTurn?.id !== turnId) return { mind };+ return {+ mind: {+ ...mind,+ activeTurn: {+ ...mind.activeTurn,+ providerId: prepared.provider?.id || null,+ model: prepared.model || null,+ effort: prepared.effort || null,+ },+ },+ };+ });+}++async function heartbeat(turnId, generation) {+ if (generation !== runtimeGeneration) return false;+ const result = await mutateMindState((mind) => {+ if (mind.activeTurn?.id !== turnId) return { mind, value: false };+ return {+ mind: {+ ...mind,+ activeTurn: { ...mind.activeTurn, heartbeatAt: nowIso() },+ },+ value: true,+ };+ });+ return result.value === true;+}++async function completeTurn(turnId, result, generation) {+ if (generation !== runtimeGeneration) return;+ const completedAt = nowIso();+ const updated = await mutateMindState((mind) => {+ if (mind.activeTurn?.id !== turnId) return { mind };+ const messageId = mind.activeTurn.wake.kind === 'message'+ ? mind.activeTurn.wake.message.id+ : null;+ const recentMessageIds = messageId+ ? [...mind.recentMessageIds.filter((id) => id !== messageId), messageId]+ .slice(-PERSISTENT_MIND_LIMITS.MAX_RECENT_MESSAGE_IDS)+ : mind.recentMessageIds;+ const requestedWake = result?.selfWake && typeof result.selfWake === 'object'+ ? {+ id: `wake-${randomUUID()}`,+ kind: 'self',+ reason: String(result.selfWake.reason || 'turn requested follow-up')+ .slice(0, PERSISTENT_MIND_LIMITS.MAX_REASON_CHARS),+ sourceTurnId: turnId,+ createdAt: completedAt,+ notBefore: result.selfWake.notBefore || completedAt,+ }+ : quietSelfWake(turnId);+ const hasQueuedMessages = mind.queuedMessages.length > 0;+ return {+ mind: {+ ...mind,+ activeTurn: null,+ recentMessageIds,+ selfWake: requestedWake,+ lastCompletedTurnId: turnId,+ lastCompletedAt: completedAt,+ nextEligibleWakeAt: null,+ failureCount: 0,+ lastError: null,+ status: hasQueuedMessages ? 'waiting' : 'idle',+ pauseReason: null,+ },+ };+ });+ emitMindStatus(updated.state);+ cosEvents.emit('persistent-mind:turn-completed', {+ turnId,+ providerId: updated.state.lastCompletedTurnId === turnId ? result?.providerId || null : null,+ });+}++async function runOnePersistentMindTurn() {+ if (!turnAdapter) {+ const updated = await mutateMindState((mind) => ({+ mind: mind.enabled && mind.started+ ? {+ ...mind,+ status: 'degraded',+ pauseReason: 'Persistent mind provider is not configured',+ lastError: 'Persistent mind provider is not configured',+ nextEligibleWakeAt: new Date(Date.now() + PERSISTENT_MIND_LIMITS.BACKOFF_MAX_MS).toISOString(),+ }+ : mind,+ }));+ emitMindStatus(updated.state);+ return;+ }++ const root = await loadState();+ const mind = normalizePersistentMindState(root.persistentMind);+ if (!mind.enabled || !mind.started || mind.status === 'paused') return;+ if (root.paused || getDomainMode(root.config, 'cos') !== 'execute') return;++ let budget;+ try {+ budget = await getDomainBudgetStatus('cos');+ } catch (error) {+ const message = `Persistent mind budget check failed: ${errorMessage(error)}`;+ const updated = await mutateMindState((current) => ({+ mind: {+ ...current,+ status: 'degraded',+ pauseReason: message,+ lastError: message,+ nextEligibleWakeAt: new Date(Date.now() + persistentMindBackoffMs(current.failureCount + 1)).toISOString(),+ failureCount: current.failureCount + 1,+ },+ }));+ emitMindStatus(updated.state);+ return;+ }+ if (!budget.withinBudget) {+ const updated = await mutateMindState((current) => ({+ mind: {+ ...current,+ status: 'waiting',+ pauseReason: `CoS ${budget.exceeded || 'daily'} budget exhausted`,+ nextEligibleWakeAt: new Date(Date.now() + PERSISTENT_MIND_LIMITS.BACKOFF_MAX_MS).toISOString(),+ },+ }));+ emitMindStatus(updated.state);+ return;+ }++ const turn = await claimNextTurn();+ if (!turn) return;++ const generation = runtimeGeneration;+ const controller = new AbortController();+ activeAbortController = controller;+ let release = () => {};+ let runStartedAt = null;+ try {+ // `prepare` must resolve the exact configured provider. The supervisor never+ // follows a fallback chain: an unavailable pin is a visible degraded state.+ const prepared = await turnAdapter.prepare({ wake: turn.wake, signal: controller.signal });+ if (!prepared?.ok || !prepared.provider) {+ await parkActiveTurn(turn.id, prepared?.error || 'Persistent mind provider is unavailable', 'degraded', prepared?.retryAt || null);+ return;+ }+ await recordTurnProfile(turn.id, prepared);++ const latestRoot = await loadState();+ const slot = await acquireLocalEndpointProviderSlot(prepared.provider, latestRoot.agents, turn.id);+ if (!slot.ok) {+ await parkActiveTurn(turn.id, slot.reason, 'waiting');+ return;+ }+ release = slot.release;+ runStartedAt = Date.now();+ const result = await turnAdapter.run({+ turnId: turn.id,+ wake: turn.wake,+ provider: prepared.provider,+ model: prepared.model || null,+ effort: prepared.effort || null,+ signal: controller.signal,+ heartbeat: () => heartbeat(turn.id, generation),+ });+ await completeTurn(turn.id, { ...result, providerId: prepared.provider.id }, generation);+ } catch (error) {+ if (generation === runtimeGeneration) {+ const message = controller.signal.aborted+ ? String(controller.signal.reason || 'Persistent mind turn interrupted')+ : errorMessage(error);+ await parkActiveTurn(turn.id, message, 'interrupted');+ emitLog('warn', `Persistent mind turn interrupted: ${message}`, { turnId: turn.id });+ }+ } finally {+ release();+ if (runStartedAt != null) {+ await recordDomainUsage('cos', { actions: 1, ms: Date.now() - runStartedAt }).catch((error) => {+ console.error(`❌ Failed to record persistent mind usage: ${error.message}`);+ });+ }+ }+}++export async function registerPersistentMindTurnAdapter(adapter) {+ if (!adapter || typeof adapter.prepare !== 'function' || typeof adapter.run !== 'function') {+ throw new Error('Persistent mind adapter requires prepare() and run()');+ }+ turnAdapter = adapter;+ await mutateMindState((mind) => ({+ mind: mind.lastError === 'Persistent mind provider is not configured'+ ? { ...mind, status: mind.started ? 'waiting' : mind.status, pauseReason: null, lastError: null, nextEligibleWakeAt: null }+ : mind,+ }));+ await scheduleNextWake();+}++export function unregisterPersistentMindTurnAdapter() {+ turnAdapter = null;+}++export async function getPersistentMindState() {+ const state = await loadState();+ return normalizePersistentMindState(state.persistentMind);+}++export async function setPersistentMindEnabled(enabled) {+ if (!enabled) {+ runtimeGeneration += 1;+ activeAbortController?.abort('Persistent mind disabled');+ cancel(PERSISTENT_MIND_WAKE_EVENT_ID);+ cancel(PERSISTENT_MIND_WATCHDOG_EVENT_ID);+ }+ const result = await mutateMindState((mind) => {+ let next = mind;+ if (!enabled && mind.activeTurn) next = requeuePersistentMindWake(next, mind.activeTurn.wake);+ return {+ mind: {+ ...next,+ enabled: Boolean(enabled),+ started: enabled ? next.started : false,+ status: enabled ? (next.started ? 'waiting' : 'idle') : 'disabled',+ activeTurn: enabled ? next.activeTurn : null,+ pauseReason: null,+ nextEligibleWakeAt: enabled ? next.nextEligibleWakeAt : null,+ },+ };+ });+ emitMindStatus(result.state);+ return result.state;+}++export async function startPersistentMind() {+ const result = await mutateMindState((mind) => {+ if (!mind.enabled) return { mind, value: { success: false, error: 'Persistent mind is disabled' } };+ if (mind.started) return { mind, value: { success: true, alreadyStarted: true } };+ return {+ mind: {+ ...mind,+ started: true,+ status: 'waiting',+ pauseReason: null,+ selfWake: mind.queuedMessages.length > 0 ? mind.selfWake : initialSelfWake('explicit-start'),+ nextEligibleWakeAt: null,+ },+ value: { success: true, alreadyStarted: false },+ };+ });+ if (result.value.success) {+ armWatchdog();+ await scheduleNextWake();+ }+ emitMindStatus(result.state);+ return result.value;+}++export async function pausePersistentMind(reason = 'Paused by user') {+ const state = await interruptActiveTurn(reason, 'paused');+ cancel(PERSISTENT_MIND_WAKE_EVENT_ID);+ return { success: true, state };+}++export async function resumePersistentMind() {+ const result = await mutateMindState((mind) => {+ if (!mind.enabled || !mind.started) return { mind, value: { success: false, error: 'Persistent mind is not started' } };+ if (mind.status !== 'paused') return { mind, value: { success: true, alreadyRunning: true } };+ return {+ mind: {+ ...mind,+ status: 'waiting',+ pauseReason: null,+ selfWake: mind.queuedMessages.length > 0 || mind.selfWake+ ? mind.selfWake+ : initialSelfWake('explicit-resume'),+ },+ value: { success: true, alreadyRunning: false },+ };+ });+ if (result.value.success) {+ armWatchdog();+ await scheduleNextWake();+ }+ emitMindStatus(result.state);+ return result.value;+}++export async function stopPersistentMind() {+ runtimeGeneration += 1;+ activeAbortController?.abort('Persistent mind stopped');+ cancel(PERSISTENT_MIND_WAKE_EVENT_ID);+ cancel(PERSISTENT_MIND_WATCHDOG_EVENT_ID);+ const result = await mutateMindState((mind) => {+ let next = mind;+ if (mind.activeTurn) next = requeuePersistentMindWake(next, mind.activeTurn.wake);+ return {+ mind: {+ ...next,+ started: false,+ status: mind.enabled ? 'idle' : 'disabled',+ activeTurn: null,+ pauseReason: null,+ nextEligibleWakeAt: null,+ },+ };+ });+ emitMindStatus(result.state);+ return { success: true };+}++export async function enqueuePersistentMindMessage({ id = randomUUID(), text, createdAt = nowIso() } = {}) {+ const message = normalizePersistentMindState({ queuedMessages: [{ id, text, createdAt }] }).queuedMessages[0];+ if (!message) return { success: false, error: 'Message id and text are required' };+ const result = await mutateMindState((mind) => {+ const duplicate = mind.recentMessageIds.includes(message.id)+ || mind.queuedMessages.some((queued) => queued.id === message.id)+ || (mind.activeTurn?.wake.kind === 'message' && mind.activeTurn.wake.message.id === message.id);+ if (duplicate) return { mind, value: { success: true, duplicate: true, messageId: message.id } };+ const acceptedMessageCount = mind.queuedMessages.length+ + (mind.activeTurn?.wake.kind === 'message' ? 1 : 0);+ if (acceptedMessageCount >= PERSISTENT_MIND_LIMITS.MAX_QUEUED_MESSAGES) {+ return { mind, value: { success: false, error: 'Persistent mind message queue is full' } };+ }+ return {+ mind: {+ ...mind,+ queuedMessages: [...mind.queuedMessages, message],+ status: mind.started && mind.status !== 'paused' ? 'waiting' : mind.status,+ },+ value: { success: true, duplicate: false, messageId: message.id },+ };+ });+ if (result.value.success && result.state.started) await scheduleNextWake();+ emitMindStatus(result.state);+ return result.value;+}++export async function requestPersistentMindWake({ sourceTurnId, reason, notBefore = nowIso() } = {}) {+ const result = await mutateMindState((mind) => {+ if (!sourceTurnId || sourceTurnId !== mind.lastCompletedTurnId) {+ return { mind, value: { success: false, error: 'Self-wake must reference the last completed turn' } };+ }+ const selfWake = {+ id: `wake-${randomUUID()}`,+ kind: 'self',+ reason: String(reason || 'self-wake').slice(0, PERSISTENT_MIND_LIMITS.MAX_REASON_CHARS),+ sourceTurnId,+ createdAt: nowIso(),+ notBefore,+ };+ return {+ mind: { ...mind, selfWake, status: mind.started && mind.status !== 'paused' ? 'waiting' : mind.status },+ value: { success: true, wakeId: selfWake.id },+ };+ });+ if (result.value.success && result.state.started) await scheduleNextWake();+ emitMindStatus(result.state);+ return result.value;+}++export async function drainPersistentMind() {+ if (activeRun) return activeRun;+ const run = runOnePersistentMindTurn();+ activeRun = run.finally(async () => {+ activeRun = null;+ activeAbortController = null;+ await scheduleNextWake();+ });+ return activeRun;+}++export async function checkPersistentMindWatchdog() {+ const state = await getPersistentMindState();+ if (!persistentMindTurnIsStale(state)) return { interrupted: false };+ await interruptActiveTurn('Persistent mind turn heartbeat expired', 'interrupted', { retry: true });+ await scheduleNextWake();+ return { interrupted: true };+}++export async function initializePersistentMindSupervisor() {+ const recovered = await mutateMindState((mind) => {+ if (!mind.enabled || !mind.started) return { mind };+ let next = mind;+ if (mind.activeTurn) {+ next = requeuePersistentMindWake(next, mind.activeTurn.wake);+ const failureCount = next.failureCount + 1;+ next = {+ ...next,+ activeTurn: null,+ status: 'interrupted',+ pauseReason: 'Recovered an orphaned persistent mind turn after restart',+ failureCount,+ lastError: 'Recovered an orphaned persistent mind turn after restart',+ nextEligibleWakeAt: new Date(Date.now() + persistentMindBackoffMs(failureCount)).toISOString(),+ };+ } else if (next.queuedMessages.length === 0 && !next.selfWake) {+ const base = next.lastCompletedAt ? Date.parse(next.lastCompletedAt) : Date.now();+ next = { ...next, selfWake: quietSelfWake(next.lastCompletedTurnId || 'restart', base + PERSISTENT_MIND_LIMITS.MAX_QUIET_MS) };+ }+ return { mind: next };+ });+ if (recovered.state.enabled && recovered.state.started) {+ armWatchdog();+ await scheduleNextWake();+ }+ emitMindStatus(recovered.state);+ return recovered.state;+}++export async function handlePersistentMindGlobalPause(reason = 'Chief of Staff paused') {+ const state = await getPersistentMindState();+ if (!state.activeTurn) {+ cancel(PERSISTENT_MIND_WAKE_EVENT_ID);+ return state;+ }+ return interruptActiveTurn(reason, 'waiting');+}++export async function handlePersistentMindGlobalResume() {+ await scheduleNextWake();+}++export async function shutdownPersistentMindSupervisor() {+ runtimeGeneration += 1;+ activeAbortController?.abort('Chief of Staff daemon stopped');+ cancel(PERSISTENT_MIND_WAKE_EVENT_ID);+ cancel(PERSISTENT_MIND_WATCHDOG_EVENT_ID);+ const state = await getPersistentMindState();+ if (!state.activeTurn) return state;+ return interruptActiveTurn('Chief of Staff daemon stopped', 'interrupted', { retry: true });+}++export function __resetPersistentMindSupervisorForTests() {+ turnAdapter = null;+ activeRun = null;+ activeAbortController = null;+ runtimeGeneration = 0;+ cancel(PERSISTENT_MIND_WAKE_EVENT_ID);+ cancel(PERSISTENT_MIND_WATCHDOG_EVENT_ID);+}diff --git a/server/services/persistentMindSupervisor.test.js b/server/services/persistentMindSupervisor.test.jsnew file mode 100644index 0000000000..75d6407980--- /dev/null+++ b/server/services/persistentMindSupervisor.test.js@@ -0,0 +1,241 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { createDefaultPersistentMindState, PERSISTENT_MIND_LIMITS } from '../lib/persistentMind.js';++const mock = vi.hoisted(() => ({+ root: null,+ scheduled: new Map(),+ emitted: [],+ budget: { withinBudget: true, exceeded: null },+ recordUsage: vi.fn(async () => {}),+ acquireSlot: vi.fn(async () => ({ ok: true, release: vi.fn() })),+}));++vi.mock('./cosState.js', () => ({+ loadState: vi.fn(async () => mock.root),+ saveState: vi.fn(async (state) => { mock.root = state; }),+ withStateLock: vi.fn(async (fn) => fn()),+}));++vi.mock('./cosEvents.js', () => ({+ cosEvents: { emit: vi.fn((...args) => mock.emitted.push(args)) },+ emitLog: vi.fn(),+}));++vi.mock('./eventScheduler.js', () => ({+ schedule: vi.fn((config) => {+ mock.scheduled.set(config.id, config);+ return config;+ }),+ cancel: vi.fn((id) => mock.scheduled.delete(id)),+}));++vi.mock('./domainUsage.js', () => ({+ getDomainBudgetStatus: vi.fn(async () => mock.budget),+ recordDomainUsage: (...args) => mock.recordUsage(...args),+}));++vi.mock('./cosLocalEndpointSlots.js', () => ({+ acquireLocalEndpointProviderSlot: (...args) => mock.acquireSlot(...args),+}));++const supervisor = await import('./persistentMindSupervisor.js');++const makeRoot = () => ({+ paused: false,+ config: { domainAutonomy: { cos: 'execute' } },+ agents: {},+ persistentMind: createDefaultPersistentMindState(),+});++const deferred = () => {+ let resolve;+ let reject;+ const promise = new Promise((res, rej) => { resolve = res; reject = rej; });+ return { promise, resolve, reject };+};++describe('persistent mind supervisor', () => {+ beforeEach(() => {+ mock.root = makeRoot();+ mock.scheduled.clear();+ mock.emitted.length = 0;+ mock.budget = { withinBudget: true, exceeded: null };+ mock.recordUsage.mockClear();+ mock.acquireSlot.mockReset();+ mock.acquireSlot.mockResolvedValue({ ok: true, release: vi.fn() });+ supervisor.__resetPersistentMindSupervisorForTests();+ });++ it('is silent on boot and refuses start until explicitly enabled', async () => {+ const prepare = vi.fn();+ const run = vi.fn();+ await supervisor.registerPersistentMindTurnAdapter({ prepare, run });++ await supervisor.initializePersistentMindSupervisor();+ expect(mock.scheduled.size).toBe(0);+ expect(await supervisor.startPersistentMind()).toEqual({ success: false, error: 'Persistent mind is disabled' });+ expect(prepare).not.toHaveBeenCalled();+ expect(run).not.toHaveBeenCalled();+ });++ it('parks an explicitly started mind instead of spinning when no provider adapter is registered', async () => {+ await supervisor.setPersistentMindEnabled(true);+ await supervisor.startPersistentMind();+ await supervisor.drainPersistentMind();++ expect(mock.root.persistentMind.status).toBe('degraded');+ expect(mock.root.persistentMind.pauseReason).toBe('Persistent mind provider is not configured');+ expect(Date.parse(mock.root.persistentMind.nextEligibleWakeAt)).toBeGreaterThan(Date.now());+ expect(mock.scheduled.get(supervisor.PERSISTENT_MIND_WAKE_EVENT_ID).delayMs).toBeGreaterThan(1_000);+ });++ it('accepts a message durably, deduplicates retries, and runs only one turn', async () => {+ const pending = deferred();+ const prepare = vi.fn(async () => ({ ok: true, provider: { id: 'example-cloud' }, model: 'example-model', effort: 'high' }));+ const run = vi.fn(() => pending.promise);+ await supervisor.registerPersistentMindTurnAdapter({ prepare, run });+ await supervisor.setPersistentMindEnabled(true);+ await supervisor.startPersistentMind();++ expect(await supervisor.enqueuePersistentMindMessage({ id: 'message-1', text: 'Please review this.' }))+ .toEqual({ success: true, duplicate: false, messageId: 'message-1' });+ expect(await supervisor.enqueuePersistentMindMessage({ id: 'message-1', text: 'Please review this.' }))+ .toEqual({ success: true, duplicate: true, messageId: 'message-1' });++ const firstDrain = supervisor.drainPersistentMind();+ const secondDrain = supervisor.drainPersistentMind();+ await vi.waitFor(() => expect(run).toHaveBeenCalledTimes(1));+ expect(run.mock.calls[0][0].wake).toMatchObject({ kind: 'message', message: { id: 'message-1' } });+ pending.resolve({});+ await Promise.all([firstDrain, secondDrain]);++ expect(prepare).toHaveBeenCalledTimes(1);+ expect(mock.acquireSlot).toHaveBeenCalledTimes(1);+ expect(mock.root.persistentMind.activeTurn).toBeNull();+ expect(mock.root.persistentMind.recentMessageIds).toContain('message-1');+ expect(mock.recordUsage).toHaveBeenCalledWith('cos', expect.objectContaining({ actions: 1 }));+ });++ it('recovers an orphaned turn without losing or duplicating its accepted message', async () => {+ const message = { id: 'message-1', text: 'Do not lose me.', createdAt: new Date(1).toISOString() };+ mock.root.persistentMind = {+ ...createDefaultPersistentMindState(),+ enabled: true,+ started: true,+ status: 'thinking',+ activeTurn: {+ id: 'turn-orphan',+ wake: { kind: 'message', message },+ startedAt: new Date(1).toISOString(),+ heartbeatAt: new Date(1).toISOString(),+ providerId: 'example-cloud',+ model: 'example-model',+ effort: 'high',+ },+ };++ const recovered = await supervisor.initializePersistentMindSupervisor();+ expect(recovered.activeTurn).toBeNull();+ expect(recovered.status).toBe('interrupted');+ expect(recovered.queuedMessages).toEqual([message]);+ expect(recovered.nextEligibleWakeAt).not.toBeNull();+ expect(mock.scheduled.has(supervisor.PERSISTENT_MIND_WATCHDOG_EVENT_ID)).toBe(true);+ });++ it('requeues a message and degrades visibly when the pinned provider is unavailable', async () => {+ await supervisor.registerPersistentMindTurnAdapter({+ prepare: vi.fn(async () => ({ ok: false, error: 'Pinned provider unavailable' })),+ run: vi.fn(),+ });+ await supervisor.setPersistentMindEnabled(true);+ await supervisor.startPersistentMind();+ await supervisor.enqueuePersistentMindMessage({ id: 'message-1', text: 'Wait for the configured provider.' });+ await supervisor.drainPersistentMind();++ expect(mock.root.persistentMind.status).toBe('degraded');+ expect(mock.root.persistentMind.pauseReason).toBe('Pinned provider unavailable');+ expect(mock.root.persistentMind.queuedMessages.map((item) => item.id)).toEqual(['message-1']);+ expect(mock.root.persistentMind.nextEligibleWakeAt).not.toBeNull();+ expect(mock.acquireSlot).not.toHaveBeenCalled();+ });++ it('holds queued work durably when the CoS budget is exhausted', async () => {+ const prepare = vi.fn();+ const run = vi.fn();+ await supervisor.registerPersistentMindTurnAdapter({ prepare, run });+ await supervisor.setPersistentMindEnabled(true);+ await supervisor.startPersistentMind();+ await supervisor.enqueuePersistentMindMessage({ id: 'message-1', text: 'Wait for tomorrow.' });+ mock.budget = { withinBudget: false, exceeded: 'actions' };++ await supervisor.drainPersistentMind();++ expect(prepare).not.toHaveBeenCalled();+ expect(run).not.toHaveBeenCalled();+ expect(mock.root.persistentMind.queuedMessages.map((item) => item.id)).toEqual(['message-1']);+ expect(mock.root.persistentMind.pauseReason).toBe('CoS actions budget exhausted');+ expect(mock.root.persistentMind.nextEligibleWakeAt).not.toBeNull();+ });++ it('requeues a claimed message when the shared local endpoint has no slot', async () => {+ const run = vi.fn();+ await supervisor.registerPersistentMindTurnAdapter({+ prepare: vi.fn(async () => ({ ok: true, provider: { id: 'example-local', endpoint: 'http://127.0.0.1:1234' } })),+ run,+ });+ mock.acquireSlot.mockResolvedValueOnce({ ok: false, reason: 'local endpoint localhost:1234 is at capacity (1/1)' });+ await supervisor.setPersistentMindEnabled(true);+ await supervisor.startPersistentMind();+ await supervisor.enqueuePersistentMindMessage({ id: 'message-1', text: 'Wait for capacity.' });++ await supervisor.drainPersistentMind();++ expect(run).not.toHaveBeenCalled();+ expect(mock.root.persistentMind.status).toBe('waiting');+ expect(mock.root.persistentMind.queuedMessages.map((item) => item.id)).toEqual(['message-1']);+ expect(mock.root.persistentMind.pauseReason).toContain('at capacity');+ });++ it('watchdog interruption aborts and requeues a stale turn without starting a second copy', async () => {+ const run = vi.fn(({ signal }) => new Promise((resolve, reject) => {+ signal.addEventListener('abort', () => reject(new Error('aborted')), { once: true });+ }));+ await supervisor.registerPersistentMindTurnAdapter({+ prepare: vi.fn(async () => ({ ok: true, provider: { id: 'example-cloud' } })),+ run,+ });+ await supervisor.setPersistentMindEnabled(true);+ await supervisor.startPersistentMind();+ await supervisor.enqueuePersistentMindMessage({ id: 'message-1', text: 'Watch this turn.' });+ const drain = supervisor.drainPersistentMind();+ await vi.waitFor(() => expect(run).toHaveBeenCalledTimes(1));++ mock.root.persistentMind.activeTurn.heartbeatAt = new Date(+ Date.now() - PERSISTENT_MIND_LIMITS.WATCHDOG_STALE_MS+ ).toISOString();+ await expect(supervisor.checkPersistentMindWatchdog()).resolves.toEqual({ interrupted: true });+ await drain;++ expect(run).toHaveBeenCalledTimes(1);+ expect(mock.root.persistentMind.activeTurn).toBeNull();+ expect(mock.root.persistentMind.queuedMessages.map((item) => item.id)).toEqual(['message-1']);+ expect(mock.root.persistentMind.status).toBe('interrupted');+ });++ it('coalesces self-wakes and rejects a recursive wake without a completed source turn', async () => {+ mock.root.persistentMind = {+ ...createDefaultPersistentMindState(),+ enabled: true,+ started: true,+ status: 'idle',+ lastCompletedTurnId: 'turn-1',+ };+ expect(await supervisor.requestPersistentMindWake({ sourceTurnId: 'turn-0', reason: 'stale' }))+ .toEqual({ success: false, error: 'Self-wake must reference the last completed turn' });+ const first = await supervisor.requestPersistentMindWake({ sourceTurnId: 'turn-1', reason: 'first' });+ const second = await supervisor.requestPersistentMindWake({ sourceTurnId: 'turn-1', reason: 'newest' });+ expect(first.success).toBe(true);+ expect(second.success).toBe(true);+ expect(mock.root.persistentMind.selfWake.reason).toBe('newest');+ });+});