Skip to content

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

fix: reserve persistent mind admission capacity (#5064)

[._.]/ Adam Eivyde185ead1b78
diff --git a/server/lib/persistentMind.js b/server/lib/persistentMind.js
index 317f698794..592217224c 100644
--- a/server/lib/persistentMind.js
+++ b/server/lib/persistentMind.js
@@ -143,6 +143,21 @@ export function normalizePersistentMindState(raw) {
if (!enabled) status = 'disabled';
else if (!started || status === 'disabled') status = 'idle';
+ let selfWake = sanitizeSelfWake(source.selfWake);
+ let activeTurn = sanitizeActiveTurn(source.activeTurn);
+ if (!started && activeTurn) {
+ if (activeTurn.wake.kind === 'message') {
+ const message = activeTurn.wake.message;
+ if (!seenQueued.has(message.id) && !recentMessageIds.includes(message.id)) {
+ queuedMessages.unshift(message);
+ if (queuedMessages.length > PERSISTENT_MIND_LIMITS.MAX_QUEUED_MESSAGES) queuedMessages.pop();
+ }
+ } else if (!selfWake) {
+ selfWake = activeTurn.wake;
+ }
+ activeTurn = null;
+ }
+
return {
...defaults,
schemaVersion: PERSISTENT_MIND_SCHEMA_VERSION,
@@ -151,8 +166,8 @@ export function normalizePersistentMindState(raw) {
status,
pauseReason: asBoundedString(source.pauseReason, PERSISTENT_MIND_LIMITS.MAX_REASON_CHARS) || null,
queuedMessages,
- selfWake: sanitizeSelfWake(source.selfWake),
- activeTurn: sanitizeActiveTurn(source.activeTurn),
+ selfWake,
+ activeTurn,
recentMessageIds: recentMessageIds.slice(-PERSISTENT_MIND_LIMITS.MAX_RECENT_MESSAGE_IDS),
lastCompletedTurnId: asId(source.lastCompletedTurnId) || null,
lastCompletedAt: asIso(source.lastCompletedAt),
diff --git a/server/lib/persistentMind.test.js b/server/lib/persistentMind.test.js
index c4b9d52cd9..eaf1daa22f 100644
--- a/server/lib/persistentMind.test.js
+++ b/server/lib/persistentMind.test.js
@@ -33,7 +33,15 @@ describe('persistent mind state', () => {
});
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');
+ const activeTurn = {
+ id: 't1',
+ wake: { kind: 'message', message: { id: 'm1', text: 'keep me', createdAt: iso(1) } },
+ startedAt: iso(1), heartbeatAt: iso(1), providerId: null, model: null, effort: null,
+ };
+ const stopped = normalizePersistentMindState({ enabled: true, started: false, status: 'thinking', activeTurn });
+ expect(stopped.status).toBe('idle');
+ expect(stopped.activeTurn).toBeNull();
+ expect(stopped.queuedMessages.map((message) => message.id)).toEqual(['m1']);
expect(normalizePersistentMindState({ enabled: true, started: true, status: 'disabled' }).status).toBe('idle');
});
diff --git a/server/services/cos.js b/server/services/cos.js
index f1f65b7e37..8271c91b55 100644
--- a/server/services/cos.js
+++ b/server/services/cos.js
@@ -36,6 +36,7 @@ import { getUserTimezone } from './userTimezone.js';
import { normalizeDomainAutonomy, getDomainMode } from '../lib/domainAutonomy.js';
import { normalizeDomainBudgets, remainingActionBudget } from '../lib/domainBudgets.js';
import { getDomainBudgetStatus } from './domainUsage.js';
+import { pendingCosActionReservations } from './cosAdmissionReservations.js';
// Dependency-free leaf holding the shared agent maps + the runner-mode flag,
// read by `isRunnerHolding` below.
import { useRunner } from './agentState.js';
@@ -1085,7 +1086,11 @@ async function spawnDequeuePriority2AutoApproved(ctx) {
const runningAutonomous = Object.values(state.agents).filter(
(a) => a.status === 'running' && a.metadata?.taskType && a.metadata.taskType !== 'user'
).length;
- autonomousActionsRemaining = remainingActionBudget(cosBudget.budget, cosBudget.usage, runningAutonomous);
+ autonomousActionsRemaining = remainingActionBudget(
+ cosBudget.budget,
+ cosBudget.usage,
+ runningAutonomous + pendingCosActionReservations()
+ );
if (autonomousActionsRemaining === 0) {
emitLog('info', `CoS auto-run paused — daily actions budget reached`, { domainBudget: 'cos', exceeded: 'actions' });
cosAutonomyMode = 'off';
diff --git a/server/services/cosAdmissionReservations.js b/server/services/cosAdmissionReservations.js
new file mode 100644
index 0000000000..b6dc2f386a
--- /dev/null
+++ b/server/services/cosAdmissionReservations.js
@@ -0,0 +1,64 @@
+/**
+ * In-process admission reservations shared by CoS agents and direct autonomous
+ * provider turns. They bridge the await window before a durable agent/usage
+ * record exists, so every admission path observes the same pending work.
+ */
+
+import { remainingActionBudget } from '../lib/domainBudgets.js';
+
+const globalReservations = new Map();
+const actionReservations = new Map();
+let reservationSequence = 0;
+
+const noopRelease = () => {};
+
+function reserve(map, reservationId) {
+ const token = ++reservationSequence;
+ map.set(token, reservationId || null);
+ let released = false;
+ return () => {
+ if (released) return;
+ released = true;
+ map.delete(token);
+ };
+}
+
+function runningAgentEntries(agents) {
+ return Object.values(agents || {}).filter((agent) => agent.status === 'running');
+}
+
+export function pendingCosGlobalReservations(agents = {}) {
+ const runningTaskIds = new Set(runningAgentEntries(agents).map((agent) => agent.taskId).filter(Boolean));
+ let count = 0;
+ for (const reservationId of globalReservations.values()) {
+ if (!reservationId || !runningTaskIds.has(reservationId)) count += 1;
+ }
+ return count;
+}
+
+export function acquireCosGlobalSlot({ agents = {}, limit, reservationId = null } = {}) {
+ const max = Number(limit);
+ const running = runningAgentEntries(agents).length;
+ const pending = pendingCosGlobalReservations(agents);
+ if (Number.isSafeInteger(max) && max > 0 && running + pending >= max) {
+ return { ok: false, reason: `CoS agent capacity exhausted (${running + pending}/${max})` };
+ }
+ return { ok: true, release: reserve(globalReservations, reservationId) };
+}
+
+export function pendingCosActionReservations() {
+ return actionReservations.size;
+}
+
+export function acquireCosActionReservation({ budget, usage, inFlight = 0, reservationId = null } = {}) {
+ const pending = pendingCosActionReservations();
+ if (remainingActionBudget(budget, usage, inFlight + pending) < 1) {
+ return { ok: false, reason: 'CoS actions budget exhausted' };
+ }
+ return { ok: true, release: reserve(actionReservations, reservationId) };
+}
+
+export function __resetCosAdmissionReservations() {
+ globalReservations.clear();
+ actionReservations.clear();
+}
diff --git a/server/services/cosAdmissionReservations.test.js b/server/services/cosAdmissionReservations.test.js
new file mode 100644
index 0000000000..661853e01c
--- /dev/null
+++ b/server/services/cosAdmissionReservations.test.js
@@ -0,0 +1,38 @@
+import { beforeEach, describe, expect, it } from 'vitest';
+import {
+ __resetCosAdmissionReservations,
+ acquireCosActionReservation,
+ acquireCosGlobalSlot,
+ pendingCosActionReservations,
+ pendingCosGlobalReservations,
+} from './cosAdmissionReservations.js';
+
+describe('shared CoS admission reservations', () => {
+ beforeEach(() => __resetCosAdmissionReservations());
+
+ it('prevents a second admission while a global slot is reserved', () => {
+ const first = acquireCosGlobalSlot({ agents: {}, limit: 1, reservationId: 'mind-turn' });
+ expect(first.ok).toBe(true);
+ expect(acquireCosGlobalSlot({ agents: {}, limit: 1, reservationId: 'task-1' })).toMatchObject({ ok: false });
+ first.release();
+ expect(pendingCosGlobalReservations()).toBe(0);
+ });
+
+ it('does not double-count a spawn reservation after its agent is running', () => {
+ const first = acquireCosGlobalSlot({ agents: {}, limit: 2, reservationId: 'task-1' });
+ const agents = { a1: { status: 'running', taskId: 'task-1' } };
+ expect(pendingCosGlobalReservations(agents)).toBe(0);
+ expect(acquireCosGlobalSlot({ agents, limit: 2, reservationId: 'task-2' }).ok).toBe(true);
+ first.release();
+ });
+
+ it('atomically reserves the final daily action', () => {
+ const budget = { maxActionsPerDay: 1, maxMinutesPerDay: null };
+ const usage = { actions: 0, ms: 0 };
+ const first = acquireCosActionReservation({ budget, usage, reservationId: 'mind-turn' });
+ expect(first.ok).toBe(true);
+ expect(acquireCosActionReservation({ budget, usage, reservationId: 'job-1' })).toMatchObject({ ok: false });
+ first.release();
+ expect(pendingCosActionReservations()).toBe(0);
+ });
+});
diff --git a/server/services/cosJobScheduler.js b/server/services/cosJobScheduler.js
index d8c71ebcb0..a334f8f0f4 100644
--- a/server/services/cosJobScheduler.js
+++ b/server/services/cosJobScheduler.js
@@ -34,6 +34,10 @@ import { getCosTasks } from './cosTaskStore.js';
import { queueEligibleImprovementTasks } from './cosTaskGenerator.js';
import { generateTaskFromJob, recordJobGateSkip, isScriptJob, executeScriptJob, isShellJob, executeShellJob } from './autonomousJobs.js';
import { checkJobGate, hasGate } from './jobGates.js';
+import {
+ acquireCosActionReservation,
+ pendingCosActionReservations,
+} from './cosAdmissionReservations.js';
/**
* Compute the next fire time for an autonomous job.
@@ -137,7 +141,7 @@ export async function registerSingleJobSchedule(jobId) {
const spawningJobIds = new Set();
const spawningJobTimeouts = new Map();
-// Synchronous daily-action reservation counter (#984). The budget gate in
+// Shared synchronous daily-action reservations (#984). The budget gate in
// executeScheduledJob reads recorded usage + spawningJobIds + running autonomous
// agents — but there are awaits between a job passing that gate and being
// counted by spawningJobIds (agent jobs) or recordDomainUsage (script/shell
@@ -149,12 +153,10 @@ const spawningJobTimeouts = new Map();
// It's released the moment the job is handed off to spawningJobIds /
// recordDomainUsage or hits any exit path (a `finally` plus the agent handoff
// cover every path, so the two counters never double-count the same job).
-let scheduledActionReservations = 0;
-
// Test-only observability: lets the concurrency test assert the reservation
// counter settles back to zero after a tick (no leak across any exit path).
export function getScheduledActionReservations() {
- return scheduledActionReservations;
+ return pendingCosActionReservations();
}
function addSpawningJob(jobId) {
@@ -230,7 +232,7 @@ export async function executeScheduledJob(jobId) {
// In-flight = autonomous agents already running PLUS jobs admitted this
// tick whose agent hasn't registered yet (`spawningJobIds`) PLUS jobs
// admitted-to-fire this tick but not yet handed off to `spawningJobIds`
- // or recorded usage (`scheduledActionReservations`, #984). The reservation
+ // or recorded usage (the shared action reservations, #984). The reservation
// term closes the same-tick window: two jobs coming due in one event-loop
// tick used to each clear this gate before either was counted, because an
// agent job reserves `spawningJobIds` only after later awaits and an inline
@@ -240,7 +242,7 @@ export async function executeScheduledJob(jobId) {
const runningAutonomous = Object.values(state.agents).filter(
(a) => a.status === 'running' && a.metadata?.taskType && a.metadata.taskType !== 'user'
).length;
- const inFlight = runningAutonomous + spawningJobIds.size + scheduledActionReservations;
+ const inFlight = runningAutonomous + spawningJobIds.size + pendingCosActionReservations();
if (remainingActionBudget(cosBudget.budget, cosBudget.usage, inFlight) < 1) overBudget = true;
}
if (overBudget) {
@@ -261,7 +263,7 @@ export async function executeScheduledJob(jobId) {
}
// Admitted to fire: reserve one daily action SYNCHRONOUSLY, before any further
- // await (#984). The budget gate above read `scheduledActionReservations`, and
+ // await (#984). The budget gate above read the shared reservation count, and
// there is no `await` between that read and this increment — so "read gate →
// reserve" is an atomic critical section. Two jobs coming due in the same tick
// serialize on it: the first reads remaining≥1 and reserves; the second reads
@@ -271,13 +273,22 @@ export async function executeScheduledJob(jobId) {
// releases it on every non-firing exit path (already-spawning, already-running,
// capacity-defer, gate-skip, spawn failure). `releaseReservation` is idempotent
// so the explicit handoff release and the `finally` can both fire harmlessly.
- let reserved = true;
- scheduledActionReservations += 1;
- const releaseReservation = () => {
- if (!reserved) return;
- reserved = false;
- scheduledActionReservations = Math.max(0, scheduledActionReservations - 1);
- };
+ const actionReservation = acquireCosActionReservation({
+ budget: cosBudget.budget,
+ usage: cosBudget.usage,
+ inFlight: Object.values(state.agents).filter(
+ (agent) => agent.status === 'running' && agent.metadata?.taskType && agent.metadata.taskType !== 'user'
+ ).length + spawningJobIds.size,
+ reservationId: `scheduled-job:${jobId}`,
+ });
+ if (!actionReservation.ok) {
+ await recordJobGateSkip(jobId).catch((err) =>
+ console.error(`❌ Failed to record budget-skip for ${jobId}: ${err.message}`)
+ );
+ await registerSingleJobSchedule(jobId);
+ return;
+ }
+ const releaseReservation = actionReservation.release;
try {
// Script jobs and shell jobs execute directly without spawning an AI agent —
diff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.js
index 2130d76a2b..d88fc3e963 100644
--- a/server/services/cosTaskGenerator.js
+++ b/server/services/cosTaskGenerator.js
@@ -29,6 +29,7 @@ import { loadState, saveState, withStateLock, isImprovementEnabled, isDaemonRunn
import { getDomainMode } from '../lib/domainAutonomy.js';
import { remainingActionBudget } from '../lib/domainBudgets.js';
import { getDomainBudgetStatus } from './domainUsage.js';
+import { pendingCosActionReservations } from './cosAdmissionReservations.js';
import { cosEvents, emitLog } from './cosEvents.js';
import { addTask, updateTask, reviveBlockedTask, getAllTasks, getCosTasks, firstLine, PRIORITY_VALUES } from './cosTaskStore.js';
import { recordDecision, DECISION_TYPES } from './decisionLog.js';
@@ -822,7 +823,11 @@ async function resolveAutonomyBudget(state, runningAgentEntries) {
const runningAutonomous = runningAgentEntries.filter(
(a) => a.metadata?.taskType && a.metadata.taskType !== 'user'
).length;
- autonomousActionsRemaining = remainingActionBudget(cosBudget.budget, cosBudget.usage, runningAutonomous);
+ autonomousActionsRemaining = remainingActionBudget(
+ cosBudget.budget,
+ cosBudget.usage,
+ runningAutonomous + pendingCosActionReservations()
+ );
if (autonomousActionsRemaining === 0) {
emitLog('info', `CoS auto-run paused — daily actions budget reached`, { domainBudget: 'cos', exceeded: 'actions' });
cosAutonomyMode = 'off';
diff --git a/server/services/domainUsage.js b/server/services/domainUsage.js
index 5c8bbc950b..6808b43b48 100644
--- a/server/services/domainUsage.js
+++ b/server/services/domainUsage.js
@@ -20,6 +20,7 @@ import { createFileWriteQueue } from '../lib/fileWriteQueue.js';
import { DOMAIN_IDS } from '../lib/domainAutonomy.js';
import { getDomainBudget, hasBudget, evaluateBudget } from '../lib/domainBudgets.js';
import { loadState } from './cosState.js';
+import { pendingCosActionReservations } from './cosAdmissionReservations.js';
export const USAGE_FILE = join(PATHS.cos, 'domain-usage.json');
@@ -113,6 +114,9 @@ export async function getDomainBudgetStatus(domainId) {
return { withinBudget: true, exceeded: null, budget, usage: { actions: 0, ms: 0 } };
}
const usage = await getDomainUsageToday(domainId);
- const { withinBudget, exceeded } = evaluateBudget(budget, usage);
+ const effectiveUsage = domainId === 'cos'
+ ? { ...usage, actions: usage.actions + pendingCosActionReservations() }
+ : usage;
+ const { withinBudget, exceeded } = evaluateBudget(budget, effectiveUsage);
return { withinBudget, exceeded, budget, usage };
}
diff --git a/server/services/domainUsage.test.js b/server/services/domainUsage.test.js
index a072eabf9b..e66f9c0233 100644
--- a/server/services/domainUsage.test.js
+++ b/server/services/domainUsage.test.js
@@ -22,10 +22,15 @@ const {
getAllDomainUsageToday,
getDomainBudgetStatus
} = await import('./domainUsage.js');
+const {
+ __resetCosAdmissionReservations,
+ acquireCosActionReservation,
+} = await import('./cosAdmissionReservations.js');
beforeEach(() => {
store = new Map();
mockConfig = {};
+ __resetCosAdmissionReservations();
});
describe('recordDomainUsage + getDomainUsageToday', () => {
@@ -95,6 +100,17 @@ describe('getDomainBudgetStatus', () => {
expect(status.exceeded).toBe('actions');
});
+ it('counts a pending CoS action reservation before usage is recorded', async () => {
+ mockConfig = { domainBudgets: { cos: { maxActionsPerDay: 1 } } };
+ const reservation = acquireCosActionReservation({
+ budget: { maxActionsPerDay: 1 },
+ usage: { actions: 0, ms: 0 },
+ reservationId: 'persistent-mind-turn',
+ });
+ expect((await getDomainBudgetStatus('cos')).withinBudget).toBe(false);
+ reservation.release();
+ });
+
it('reports exceeded once the minutes cap is reached', async () => {
mockConfig = { domainBudgets: { cos: { maxMinutesPerDay: 5 } } };
await recordDomainUsage('cos', { ms: 5 * 60_000 });
diff --git a/server/services/persistentMindSupervisor.js b/server/services/persistentMindSupervisor.js
index ac7db459ce..cb09b6e04c 100644
--- a/server/services/persistentMindSupervisor.js
+++ b/server/services/persistentMindSupervisor.js
@@ -26,6 +26,7 @@ import { cosEvents, emitLog } from './cosEvents.js';
import { schedule, cancel } from './eventScheduler.js';
import { getDomainBudgetStatus, recordDomainUsage } from './domainUsage.js';
import { acquireLocalEndpointProviderSlot } from './cosLocalEndpointSlots.js';
+import { acquireCosActionReservation, acquireCosGlobalSlot } from './cosAdmissionReservations.js';
export const PERSISTENT_MIND_WAKE_EVENT_ID = 'cos-persistent-mind-wake';
export const PERSISTENT_MIND_WATCHDOG_EVENT_ID = 'cos-persistent-mind-watchdog';
@@ -327,14 +328,20 @@ async function runOnePersistentMindTurn() {
if (!mind.enabled || !mind.started || mind.status === 'paused') return;
if (root.paused || getDomainMode(root.config, 'cos') !== 'execute') return;
- const runningAgents = Object.values(root.agents || {}).filter((agent) => agent.status === 'running').length;
+ const runningAgentEntries = Object.values(root.agents || {}).filter((agent) => agent.status === 'running');
const maxConcurrentAgents = Number(root.config?.maxConcurrentAgents);
- if (Number.isSafeInteger(maxConcurrentAgents) && runningAgents >= maxConcurrentAgents) {
+ const admissionId = `persistent-mind:${randomUUID()}`;
+ const globalSlot = acquireCosGlobalSlot({
+ agents: root.agents,
+ limit: maxConcurrentAgents,
+ reservationId: admissionId,
+ });
+ if (!globalSlot.ok) {
const updated = await mutateMindState((current) => ({
mind: {
...current,
status: 'waiting',
- pauseReason: `CoS agent capacity exhausted (${runningAgents}/${maxConcurrentAgents})`,
+ pauseReason: globalSlot.reason,
nextEligibleWakeAt: new Date(Date.now() + PERSISTENT_MIND_LIMITS.BACKOFF_BASE_MS).toISOString(),
},
}));
@@ -342,91 +349,119 @@ async function runOnePersistentMindTurn() {
return;
}
- let budget;
+ let actionReservation = null;
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 (!await turnCanContinue(turn.id, generation, controller.signal)) return;
- if (!prepared?.ok || !prepared.provider) {
- await parkActiveTurn(turn.id, prepared?.error || 'Persistent mind provider is unavailable', 'degraded', prepared?.retryAt || null);
+ 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;
}
- await recordTurnProfile(turn.id, prepared);
- if (!await turnCanContinue(turn.id, generation, controller.signal)) return;
-
- const latestRoot = await loadState();
- const slot = await acquireLocalEndpointProviderSlot(prepared.provider, latestRoot.agents, turn.id);
- if (!slot.ok) {
- await parkActiveTurn(turn.id, slot.reason, 'waiting');
+ 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;
}
- release = slot.release;
- if (!await turnCanContinue(turn.id, generation, controller.signal)) return;
- 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),
+
+ const runningAutonomous = runningAgentEntries.filter(
+ (agent) => agent.metadata?.taskType && agent.metadata.taskType !== 'user'
+ ).length;
+ actionReservation = acquireCosActionReservation({
+ budget: budget.budget,
+ usage: budget.usage,
+ inFlight: runningAutonomous,
+ reservationId: admissionId,
});
- 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 });
+ if (!actionReservation.ok) {
+ const updated = await mutateMindState((current) => ({
+ mind: {
+ ...current,
+ status: 'waiting',
+ pauseReason: actionReservation.reason,
+ nextEligibleWakeAt: new Date(Date.now() + PERSISTENT_MIND_LIMITS.BACKOFF_MAX_MS).toISOString(),
+ },
+ }));
+ emitMindStatus(updated.state);
+ return;
}
- } 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}`);
+
+ 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 (!await turnCanContinue(turn.id, generation, controller.signal)) return;
+ 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);
+ if (!await turnCanContinue(turn.id, generation, controller.signal)) return;
+
+ 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;
+ if (!await turnCanContinue(turn.id, generation, controller.signal)) return;
+ 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}`);
+ });
+ }
}
+ } finally {
+ actionReservation?.release?.();
+ globalSlot.release();
}
}
diff --git a/server/services/persistentMindSupervisor.test.js b/server/services/persistentMindSupervisor.test.js
index cf87731135..9bd7096c53 100644
--- a/server/services/persistentMindSupervisor.test.js
+++ b/server/services/persistentMindSupervisor.test.js
@@ -1,5 +1,10 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { createDefaultPersistentMindState, PERSISTENT_MIND_LIMITS } from '../lib/persistentMind.js';
+import {
+ __resetCosAdmissionReservations,
+ acquireCosActionReservation,
+ acquireCosGlobalSlot,
+} from './cosAdmissionReservations.js';
const mock = vi.hoisted(() => ({
root: null,
@@ -66,6 +71,7 @@ describe('persistent mind supervisor', () => {
mock.recordUsage.mockClear();
mock.acquireSlot.mockReset();
mock.acquireSlot.mockResolvedValue({ ok: true, release: vi.fn() });
+ __resetCosAdmissionReservations();
supervisor.__resetPersistentMindSupervisorForTests();
});
@@ -199,6 +205,55 @@ describe('persistent mind supervisor', () => {
expect(mock.root.persistentMind.nextEligibleWakeAt).not.toBeNull();
});
+ it('holds a shared global slot throughout provider preparation', async () => {
+ const prepared = deferred();
+ await supervisor.registerPersistentMindTurnAdapter({
+ prepare: vi.fn(() => prepared.promise),
+ run: vi.fn(async () => ({})),
+ });
+ mock.root.config.maxConcurrentAgents = 1;
+ await supervisor.setPersistentMindEnabled(true);
+ await supervisor.startPersistentMind();
+ const drain = supervisor.drainPersistentMind();
+ await vi.waitFor(() => expect(mock.root.persistentMind.activeTurn).not.toBeNull());
+
+ expect(acquireCosGlobalSlot({ agents: {}, limit: 1, reservationId: 'ordinary-task' })).toMatchObject({ ok: false });
+ await supervisor.pausePersistentMind();
+ prepared.resolve({ ok: true, provider: { id: 'example-cloud' } });
+ await drain;
+ const released = acquireCosGlobalSlot({ agents: {}, limit: 1, reservationId: 'ordinary-task' });
+ expect(released.ok).toBe(true);
+ released.release();
+ });
+
+ it('does not claim a turn when another admission reserved the final daily action', async () => {
+ mock.budget = {
+ withinBudget: true,
+ exceeded: null,
+ budget: { maxActionsPerDay: 1, maxMinutesPerDay: null },
+ usage: { actions: 0, ms: 0 },
+ };
+ const existing = acquireCosActionReservation({
+ budget: mock.budget.budget,
+ usage: mock.budget.usage,
+ reservationId: 'ordinary-agent',
+ });
+ const run = vi.fn();
+ await supervisor.registerPersistentMindTurnAdapter({
+ prepare: vi.fn(async () => ({ ok: true, provider: { id: 'example-cloud' } })),
+ run,
+ });
+ await supervisor.setPersistentMindEnabled(true);
+ await supervisor.startPersistentMind();
+
+ await supervisor.drainPersistentMind();
+
+ expect(run).not.toHaveBeenCalled();
+ expect(mock.root.persistentMind.activeTurn).toBeNull();
+ expect(mock.root.persistentMind.pauseReason).toBe('CoS actions budget exhausted');
+ existing.release();
+ });
+
it('requeues a claimed message when the shared local endpoint has no slot', async () => {
const run = vi.fn();
await supervisor.registerPersistentMindTurnAdapter({
diff --git a/server/services/subAgentSpawner.js b/server/services/subAgentSpawner.js
index c300989524..3d4e133446 100644
--- a/server/services/subAgentSpawner.js
+++ b/server/services/subAgentSpawner.js
@@ -49,6 +49,7 @@ import { isUpdateInProgress } from './updateChecker.js';
import { releaseMissionSubTask } from './missions.js';
import { loadState } from './cosState.js';
import { acquireLocalEndpointSpawnSlot } from './cosLocalEndpointSlots.js';
+import { acquireCosGlobalSlot } from './cosAdmissionReservations.js';
// This module's own event wiring drives three LIFECYCLE TRANSITIONS, so it takes
// them from the facade rather than from the three separate leaves that happen to
// implement them (#3450). It can: nothing the facade imports imports this module
@@ -371,7 +372,18 @@ async function runInitSpawner() {
if (useRunner && !(await isRunnerReachable())) {
return holdTask(task, 'CoS Runner is down');
}
- // 3. Local inference endpoint at capacity (issue #4834). A CoS agent runs a
+ // 3. Global capacity. Reserve across the spawn window so direct persistent
+ // turns and ordinary agents cannot both pass a stale pre-registration
+ // snapshot.
+ const capacityState = await loadState();
+ const globalSlot = acquireCosGlobalSlot({
+ agents: capacityState.agents,
+ limit: capacityState.config.maxConcurrentAgents,
+ reservationId: task.id,
+ });
+ if (!globalSlot.ok) return holdTask(task, globalSlot.reason);
+
+ // 4. Local inference endpoint at capacity (issue #4834). A CoS agent runs a
// vendor CLI that opens its own connection to the local model server, so
// promptRunner's in-flight gate never sees it — without this, two agents
// can be dispatched at one GPU and the runtime kills a turn with an
@@ -380,20 +392,22 @@ async function runInitSpawner() {
// Creative Director bridge all reach this listener directly. The slot is
// reserved across the spawn window and released below, since the agent
// record isn't countable until it reaches `running`.
- const localSlot = await acquireLocalEndpointSpawnSlot(task, (await loadState()).agents);
- if (!localSlot.ok) {
- return holdTask(task, localSlot.reason);
- }
try {
- await spawnAgentForTask(task);
- } catch (err) {
- emitLog('error', `Failed to spawn agent for task ${task.id}: ${err?.message || err}`, { taskId: task.id });
- const jobId = task.metadata?.jobId;
- if (jobId) {
- cosEvents.emit('job:spawn-failed', { jobId });
+ const localSlot = await acquireLocalEndpointSpawnSlot(task, capacityState.agents);
+ if (!localSlot.ok) return holdTask(task, localSlot.reason);
+ try {
+ await spawnAgentForTask(task);
+ } catch (err) {
+ emitLog('error', `Failed to spawn agent for task ${task.id}: ${err?.message || err}`, { taskId: task.id });
+ const jobId = task.metadata?.jobId;
+ if (jobId) {
+ cosEvents.emit('job:spawn-failed', { jobId });
+ }
+ } finally {
+ localSlot.release();
}
} finally {
- localSlot.release();
+ globalSlot.release();
}
});