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

feat: configure persistent mind wake cadence

Adam Eivy182ffb7dee0c
diff --git a/client/src/components/cos/PersistentMindProfileControls.jsx b/client/src/components/cos/PersistentMindProfileControls.jsx
index ec5fd333ed..1787982f5c 100644
--- a/client/src/components/cos/PersistentMindProfileControls.jsx
+++ b/client/src/components/cos/PersistentMindProfileControls.jsx
@@ -14,8 +14,21 @@ const DEFAULT_PROFILE = {
model: '',
effort: '',
thinkingInterface: 'text',
+ wakeIntervalMinutes: 30,
};
+const WAKE_INTERVAL_OPTIONS = [
+ [5, 'Every 5 minutes'],
+ [15, 'Every 15 minutes'],
+ [30, 'Every 30 minutes'],
+ [60, 'Every hour'],
+ [120, 'Every 2 hours'],
+ [240, 'Every 4 hours'],
+ [480, 'Every 8 hours'],
+ [1_440, 'Every day'],
+ [10_080, 'Every week'],
+];
+
const normalizeProfile = (profile) => ({
...DEFAULT_PROFILE,
...(profile || {}),
@@ -31,6 +44,7 @@ export default function PersistentMindProfileControls({
onSavingChange,
}) {
const enabledId = useId();
+ const wakeIntervalId = useId();
const {
providers,
availableModels,
@@ -89,6 +103,7 @@ export default function PersistentMindProfileControls({
profile?.model,
profile?.effort,
profile?.thinkingInterface,
+ profile?.wakeIntervalMinutes,
]);
const save = async (patch) => {
@@ -181,6 +196,24 @@ export default function PersistentMindProfileControls({
}}
onEffortChange={(effort) => save({ effort })}
/>
+ <div>
+ <label htmlFor={wakeIntervalId} className="block text-sm font-medium text-port-text">Wake cadence</label>
+ <select
+ id={wakeIntervalId}
+ value={draft.wakeIntervalMinutes}
+ disabled={disabled || saving || !draft.enabled}
+ onChange={(event) => save({ wakeIntervalMinutes: Number(event.target.value) })}
+ className="mt-1 w-full rounded border border-port-border bg-port-bg px-3 py-2 text-sm text-port-text disabled:cursor-not-allowed disabled:opacity-50"
+ >
+ {!WAKE_INTERVAL_OPTIONS.some(([minutes]) => minutes === draft.wakeIntervalMinutes) && (
+ <option value={draft.wakeIntervalMinutes}>Every {draft.wakeIntervalMinutes} minutes</option>
+ )}
+ {WAKE_INTERVAL_OPTIONS.map(([minutes, label]) => <option key={minutes} value={minutes}>{label}</option>)}
+ </select>
+ <p className="mt-1 text-xs text-port-text-muted">
+ Messages wake the mind immediately. This is the maximum quiet time between self-directed thoughts; the mind can ask to wake sooner, and shorter intervals use the selected provider more often.
+ </p>
+ </div>
<ModelCapabilitySummary
provider={selectedProvider}
model={capabilityModel}
diff --git a/client/src/components/cos/PersistentMindRuntimePanel.jsx b/client/src/components/cos/PersistentMindRuntimePanel.jsx
index 23cdb56202..37e0285d1f 100644
--- a/client/src/components/cos/PersistentMindRuntimePanel.jsx
+++ b/client/src/components/cos/PersistentMindRuntimePanel.jsx
@@ -1,5 +1,5 @@
import { Brain, Cpu, Gauge } from 'lucide-react';
-import { formatBytes } from '../../utils/formatters.js';
+import { formatBytes, timeUntil } from '../../utils/formatters.js';
const number = (value) => Number.isFinite(value) ? value.toLocaleString() : '—';
@@ -15,9 +15,11 @@ const residencyLabel = (runtime) => {
export function PersistentMindThoughtStatus({ state, model }) {
const thinking = state?.status === 'thinking' && Boolean(state.activeTurnId);
+ const scheduled = state?.started && state?.nextWakeAt && ['idle', 'waiting'].includes(state.status);
const label = thinking
? `Thinking${model ? ` with ${model}` : ''}`
- : state?.status === 'waiting' ? 'Waiting for the next wake'
+ : scheduled ? `Waiting · next wake ${timeUntil(state.nextWakeAt)}`
+ : state?.status === 'waiting' ? 'Waiting for the next wake'
: state?.status === 'paused' ? 'Mind paused'
: state?.status === 'idle' ? 'Mind idle'
: state?.status === 'disabled' ? 'Mind disabled'
diff --git a/client/src/components/cos/tabs/MindTab.jsx b/client/src/components/cos/tabs/MindTab.jsx
index 9fa3fe7a0e..00537ae36d 100644
--- a/client/src/components/cos/tabs/MindTab.jsx
+++ b/client/src/components/cos/tabs/MindTab.jsx
@@ -6,7 +6,7 @@ import useMounted from '../../../hooks/useMounted';
import { useSocket } from '../../../hooks/useSocket';
import { uuidv4 } from '../../../lib/uuid.js';
import * as api from '../../../services/api';
-import { formatDateTime } from '../../../utils/formatters';
+import { formatDateTime, timeUntil } from '../../../utils/formatters';
import BrailleSpinner from '../../BrailleSpinner';
import Drawer from '../../Drawer';
import Banner from '../../ui/Banner';
@@ -700,6 +700,16 @@ export default function MindTab() {
{state?.status === 'thinking' ? 'Working through the current turn.' : state?.pauseReason || (state?.started ? 'Listening for messages and scheduled wakes.' : 'Configure the AI profile to begin.')}
</p>
{state?.queuedMessageCount > 0 && <p className="mt-2 text-xs font-medium text-port-accent">{state.queuedMessageCount} queued message{state.queuedMessageCount === 1 ? '' : 's'}</p>}
+ {state?.started && state?.nextWakeAt && (
+ <button
+ type="button"
+ onClick={() => openPanel('settings')}
+ aria-label="Configure wake cadence"
+ className="mt-2 block rounded text-left text-xs text-port-text-muted hover:text-port-accent focus:outline-none focus:ring-2 focus:ring-port-accent/50"
+ >
+ Next wake <time dateTime={state.nextWakeAt} className="font-medium text-port-text">{formatDateTime(state.nextWakeAt)}</time> · {timeUntil(state.nextWakeAt)}
+ </button>
+ )}
</section>
<div className="grid grid-cols-2 gap-2 xl:grid-cols-1">
@@ -740,7 +750,7 @@ export default function MindTab() {
{(visitedPanels.has('settings') || activePanel === 'settings') && <section hidden={activePanel !== 'settings'} aria-labelledby="mind-profile-heading" className="rounded border border-port-border bg-port-card p-4">
<div className="mb-3">
<h3 id="mind-profile-heading" className="text-sm font-semibold text-port-text">AI profile</h3>
- <p className="mt-1 text-xs text-port-text-muted">Pin the provider, model, and effort used on every wake. Changes apply to the next wake and never silently fall back to another model.</p>
+ <p className="mt-1 text-xs text-port-text-muted">Pin the provider, model, effort, and wake cadence. Changes apply to the next wake and never silently fall back to another model.</p>
</div>
<PersistentMindProfileControls
profile={mind?.profile}
diff --git a/client/src/components/cos/tabs/MindTab.test.jsx b/client/src/components/cos/tabs/MindTab.test.jsx
index 5c9a401bd8..41b7d60e96 100644
--- a/client/src/components/cos/tabs/MindTab.test.jsx
+++ b/client/src/components/cos/tabs/MindTab.test.jsx
@@ -65,7 +65,7 @@ const response = (overrides = {}) => ({
truncated: false,
snapshot: {},
state: { enabled: true, started: true, status: 'waiting', pauseReason: null },
- profile: { enabled: true, providerId: 'demo', model: 'demo-model', effort: 'high', thinkingInterface: 'text' },
+ profile: { enabled: true, providerId: 'demo', model: 'demo-model', effort: 'high', thinkingInterface: 'text', wakeIntervalMinutes: 30 },
capabilities: { schemaVersion: 1, createTasks: false },
autonomyMode: 'execute',
...overrides,
@@ -271,6 +271,35 @@ describe('MindTab', () => {
await waitFor(() => expect(api.startPersistentMind).toHaveBeenCalledTimes(1));
});
+ it('shows the next wake and persists a discoverable wake cadence', async () => {
+ const user = userEvent.setup();
+ const nextWakeAt = new Date(Date.now() + 30 * 60_000).toISOString();
+ api.getPersistentMind.mockResolvedValue(response({
+ state: {
+ enabled: true,
+ started: true,
+ status: 'waiting',
+ pauseReason: null,
+ nextWakeAt,
+ },
+ }));
+ renderTab('/cos/mind?panel=settings');
+
+ expect(await screen.findByText(/Waiting · next wake in/i)).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: 'Configure wake cadence' })).toBeInTheDocument();
+ expect(document.querySelector(`time[datetime="${nextWakeAt}"]`)).toBeInTheDocument();
+ const cadence = screen.getByLabelText('Wake cadence');
+ expect(cadence).toHaveValue('30');
+ expect(cadence).toBeEnabled();
+
+ fireEvent.change(cadence, { target: { value: '60' } });
+
+ await waitFor(() => expect(api.updateCosConfig).toHaveBeenCalledWith(
+ { persistentMindProfile: expect.objectContaining({ wakeIntervalMinutes: 60 }) },
+ { silent: true },
+ ));
+ });
+
it('starts a ready persistent mind directly from the dashboard header', async () => {
const user = userEvent.setup();
api.getPersistentMind.mockResolvedValue(response({
diff --git a/server/lib/README.md b/server/lib/README.md
index 3cd2c7e72c..2f844ee862 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -46,9 +46,9 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `persistentMindCapabilities.js` | Default-off persistent-mind action grants plus the bounded typed CoS-task request contract (app/provider/model/effort and PR completion policy). |
| `cosToolContracts.js` | Provider-neutral `portos_tool` catalog/call schema version, request-id and per-turn bounds, catalog query formats, and Persistent Mind tool-call shape. |
| `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. |
+| `persistentMindProfile.js` | Versioned, default-off persistent-mind provider profile (`enabled`, provider/model/effort, text interface, maximum quiet interval), its strict API schema, duration resolver, and safe partial-update merge that clears model/effort on a provider switch. |
| `persistentMindPrompt.js` | Editable persistent-mind identity and operating-instructions schema/defaults; saving it never starts inference. |
-| `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. |
+| `persistentMindPublic.js` | `publicPersistentMindState(state)` — the sole client/socket projection of durable mind state: exposes lifecycle fields, queue count, and the derived next wake time; 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/persistentMindProfile.js b/server/lib/persistentMindProfile.js
index 43341d2fdc..1ea9b7d68a 100644
--- a/server/lib/persistentMindProfile.js
+++ b/server/lib/persistentMindProfile.js
@@ -16,8 +16,12 @@ export const PERSISTENT_MIND_THINKING_INTERFACE = 'text';
export const PERSISTENT_MIND_PROFILE_LIMITS = Object.freeze({
PROVIDER_ID_MAX: 100,
MODEL_MAX: 200,
+ WAKE_INTERVAL_MINUTES_MIN: 5,
+ WAKE_INTERVAL_MINUTES_MAX: 10_080,
});
+export const DEFAULT_PERSISTENT_MIND_WAKE_INTERVAL_MINUTES = 30;
+
export const persistentMindProfileSchema = z.object({
schemaVersion: z.literal(PERSISTENT_MIND_PROFILE_SCHEMA_VERSION).optional(),
enabled: z.boolean().optional(),
@@ -27,6 +31,11 @@ export const persistentMindProfileSchema = z.object({
// empty rather than null because config is a mergeable settings object.
effort: z.union([z.literal(''), z.enum(EFFORT_LEVELS)]).optional(),
thinkingInterface: z.literal(PERSISTENT_MIND_THINKING_INTERFACE).optional(),
+ wakeIntervalMinutes: z.number()
+ .int()
+ .min(PERSISTENT_MIND_PROFILE_LIMITS.WAKE_INTERVAL_MINUTES_MIN)
+ .max(PERSISTENT_MIND_PROFILE_LIMITS.WAKE_INTERVAL_MINUTES_MAX)
+ .optional(),
}).strict();
export function createDefaultPersistentMindProfile() {
@@ -37,11 +46,20 @@ export function createDefaultPersistentMindProfile() {
model: '',
effort: '',
thinkingInterface: PERSISTENT_MIND_THINKING_INTERFACE,
+ wakeIntervalMinutes: DEFAULT_PERSISTENT_MIND_WAKE_INTERVAL_MINUTES,
};
}
const text = (value, max) => (typeof value === 'string' ? value.trim().slice(0, max) : '');
+const wakeIntervalMinutes = (value) => (
+ Number.isInteger(value)
+ && value >= PERSISTENT_MIND_PROFILE_LIMITS.WAKE_INTERVAL_MINUTES_MIN
+ && value <= PERSISTENT_MIND_PROFILE_LIMITS.WAKE_INTERVAL_MINUTES_MAX
+ ? value
+ : DEFAULT_PERSISTENT_MIND_WAKE_INTERVAL_MINUTES
+);
+
/** Normalize legacy or hand-edited config without turning an invalid effort into a pin. */
export function normalizePersistentMindProfile(raw) {
const defaults = createDefaultPersistentMindProfile();
@@ -56,9 +74,15 @@ export function normalizePersistentMindProfile(raw) {
thinkingInterface: source.thinkingInterface === PERSISTENT_MIND_THINKING_INTERFACE
? source.thinkingInterface
: PERSISTENT_MIND_THINKING_INTERFACE,
+ wakeIntervalMinutes: wakeIntervalMinutes(source.wakeIntervalMinutes),
};
}
+/** Resolve the user's maximum quiet period to scheduler milliseconds. */
+export function persistentMindWakeIntervalMs(raw) {
+ return normalizePersistentMindProfile(raw).wakeIntervalMinutes * 60_000;
+}
+
/**
* Merge a partial update without carrying a model/effort chosen for another
* provider. Changing providers always clears dependent selections unless the
diff --git a/server/lib/persistentMindProfile.test.js b/server/lib/persistentMindProfile.test.js
index f76f3002e5..410005a5c4 100644
--- a/server/lib/persistentMindProfile.test.js
+++ b/server/lib/persistentMindProfile.test.js
@@ -3,6 +3,7 @@ import {
createDefaultPersistentMindProfile,
mergePersistentMindProfile,
normalizePersistentMindProfile,
+ persistentMindWakeIntervalMs,
persistentMindProfileSchema,
} from './persistentMindProfile.js';
@@ -15,12 +16,15 @@ describe('persistent mind profile', () => {
model: '',
effort: '',
thinkingInterface: 'text',
+ wakeIntervalMinutes: 30,
});
});
it('keeps an older config safe while normalizing invalid hand-edited fields', () => {
expect(normalizePersistentMindProfile({ enabled: true, providerId: ' local ', model: 42, effort: 'turbo' }))
- .toMatchObject({ enabled: true, providerId: 'local', model: '', effort: '', thinkingInterface: 'text' });
+ .toMatchObject({ enabled: true, providerId: 'local', model: '', effort: '', thinkingInterface: 'text', wakeIntervalMinutes: 30 });
+ expect(normalizePersistentMindProfile({ wakeIntervalMinutes: 0 }).wakeIntervalMinutes).toBe(30);
+ expect(persistentMindWakeIntervalMs({ wakeIntervalMinutes: 90 })).toBe(90 * 60_000);
});
it('clears model and effort when a provider changes without replacements', () => {
@@ -35,5 +39,8 @@ describe('persistent mind profile', () => {
expect(persistentMindProfileSchema.safeParse({ providerId: 'codex', model: 'gpt-5', effort: 'max', thinkingInterface: 'text' }).success).toBe(true);
expect(persistentMindProfileSchema.safeParse({ effort: 'turbo' }).success).toBe(false);
expect(persistentMindProfileSchema.safeParse({ thinkingInterface: 'tools' }).success).toBe(false);
+ expect(persistentMindProfileSchema.safeParse({ wakeIntervalMinutes: 5 }).success).toBe(true);
+ expect(persistentMindProfileSchema.safeParse({ wakeIntervalMinutes: 4 }).success).toBe(false);
+ expect(persistentMindProfileSchema.safeParse({ wakeIntervalMinutes: 10_081 }).success).toBe(false);
});
});
diff --git a/server/lib/persistentMindPublic.js b/server/lib/persistentMindPublic.js
index 20880fce89..d054785ba7 100644
--- a/server/lib/persistentMindPublic.js
+++ b/server/lib/persistentMindPublic.js
@@ -1,5 +1,7 @@
/** Safe client projection for the machine-local persistent-mind state. */
+import { nextPersistentMindWakeAt } from './persistentMind.js';
+
const publicReason = (state) => {
if (!state.pauseReason) return null;
if (state.status === 'paused') return 'Paused by user';
@@ -8,6 +10,7 @@ const publicReason = (state) => {
};
export function publicPersistentMindState(state = {}) {
+ const nextWakeAt = nextPersistentMindWakeAt(state);
return {
enabled: state.enabled === true,
started: state.started === true,
@@ -18,6 +21,7 @@ export function publicPersistentMindState(state = {}) {
lastCompletedTurnId: typeof state.lastCompletedTurnId === 'string' ? state.lastCompletedTurnId : null,
lastCompletedAt: typeof state.lastCompletedAt === 'string' ? state.lastCompletedAt : null,
nextEligibleWakeAt: typeof state.nextEligibleWakeAt === 'string' ? state.nextEligibleWakeAt : null,
+ nextWakeAt: nextWakeAt == null ? null : new Date(nextWakeAt).toISOString(),
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/lib/persistentMindPublic.test.js b/server/lib/persistentMindPublic.test.js
new file mode 100644
index 0000000000..42c9d35b20
--- /dev/null
+++ b/server/lib/persistentMindPublic.test.js
@@ -0,0 +1,28 @@
+import { describe, expect, it } from 'vitest';
+import { createDefaultPersistentMindState } from './persistentMind.js';
+import { publicPersistentMindState } from './persistentMindPublic.js';
+
+describe('public persistent mind state', () => {
+ it('projects the scheduled wake without exposing queued message content', () => {
+ const nextWakeAt = new Date(Date.now() + 15 * 60_000).toISOString();
+ const projected = publicPersistentMindState({
+ ...createDefaultPersistentMindState(),
+ enabled: true,
+ started: true,
+ status: 'waiting',
+ queuedMessages: [],
+ selfWake: {
+ id: 'wake-1',
+ kind: 'self',
+ reason: 'scheduled reflection',
+ sourceTurnId: 'turn-1',
+ createdAt: new Date().toISOString(),
+ notBefore: nextWakeAt,
+ },
+ });
+
+ expect(projected.nextWakeAt).toBe(nextWakeAt);
+ expect(projected).not.toHaveProperty('selfWake');
+ expect(projected).not.toHaveProperty('queuedMessages');
+ });
+});
diff --git a/server/routes/cos.test.js b/server/routes/cos.test.js
index 3b0f226591..335352e777 100644
--- a/server/routes/cos.test.js
+++ b/server/routes/cos.test.js
@@ -250,6 +250,20 @@ describe('CoS Routes', () => {
expect(cos.updateConfig).toHaveBeenCalledWith(updates);
});
+ it('validates the persistent mind wake cadence', async () => {
+ const updates = { persistentMindProfile: { wakeIntervalMinutes: 60 } };
+ cos.updateConfig.mockResolvedValue(updates);
+
+ const accepted = await request(app).put('/api/cos/config').send(updates);
+ const rejected = await request(app).put('/api/cos/config').send({
+ persistentMindProfile: { wakeIntervalMinutes: 4 },
+ });
+
+ expect(accepted.status).toBe(200);
+ expect(cos.updateConfig).toHaveBeenCalledWith(updates);
+ expect(rejected.status).toBe(400);
+ });
+
it.each([
['autonomyLevel', 'manager'],
['comprehensiveAppImprovement', true],
diff --git a/server/routes/cosMindRoutes.js b/server/routes/cosMindRoutes.js
index 8f7976d545..b4f01d355a 100644
--- a/server/routes/cosMindRoutes.js
+++ b/server/routes/cosMindRoutes.js
@@ -169,6 +169,7 @@ router.get('/mind', asyncHandler(async (req, res) => {
model: profile.model || null,
effort: profile.effort || null,
thinkingInterface: profile.thinkingInterface,
+ wakeIntervalMinutes: profile.wakeIntervalMinutes,
},
capabilities,
harness: persistentMindHarnessInfo(provider),
diff --git a/server/routes/cosMindRoutes.test.js b/server/routes/cosMindRoutes.test.js
index 36a73841af..9beba1c852 100644
--- a/server/routes/cosMindRoutes.test.js
+++ b/server/routes/cosMindRoutes.test.js
@@ -163,7 +163,14 @@ describe('persistent mind routes', () => {
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' },
+ profile: {
+ enabled: true,
+ providerId: 'demo',
+ model: 'demo-model',
+ effort: 'high',
+ thinkingInterface: 'text',
+ wakeIntervalMinutes: 30,
+ },
capabilities: { schemaVersion: 2, createTasks: true, readPortos: false, writePortos: false },
harness: { type: 'api', recommendation: 'recommended' },
imageCapability: { status: 'unknown' },
diff --git a/server/services/cos.js b/server/services/cos.js
index 04964fb777..5e70cefd44 100644
--- a/server/services/cos.js
+++ b/server/services/cos.js
@@ -36,7 +36,7 @@ import { getUserTimezone } from './userTimezone.js';
import { normalizeDomainAutonomy, getDomainMode } from '../lib/domainAutonomy.js';
import { normalizeDomainBudgets, remainingActionBudget } from '../lib/domainBudgets.js';
import { mergePersistentMindCapabilities } from '../lib/persistentMindCapabilities.js';
-import { mergePersistentMindProfile } from '../lib/persistentMindProfile.js';
+import { mergePersistentMindProfile, normalizePersistentMindProfile } from '../lib/persistentMindProfile.js';
import { mergePersistentMindPrompt } from '../lib/persistentMindPrompt.js';
import { getDomainBudgetStatus } from './domainUsage.js';
import { pendingCosActionReservations } from './cosAdmissionReservations.js';
@@ -167,6 +167,7 @@ import {
shutdownPersistentMindSupervisor,
handlePersistentMindGlobalPause,
handlePersistentMindGlobalResume,
+ refreshPersistentMindWakeCadence,
registerPersistentMindTurnAdapter,
unregisterPersistentMindTurnAdapter,
} from './persistentMindSupervisor.js';
@@ -224,6 +225,7 @@ export { getConfig } from './cosState.js';
* Update configuration
*/
export async function updateConfig(updates) {
+ let persistentMindWakeCadenceChanged = false;
const config = await withStateLock(async () => {
const state = await loadState();
// domainAutonomy is a partial-friendly map: a PATCH that names only one
@@ -252,10 +254,13 @@ export async function updateConfig(updates) {
state.config.domainBudgets = normalizeDomainBudgets(mergedBudgets);
}
if (updates.persistentMindProfile !== undefined) {
- state.config.persistentMindProfile = mergePersistentMindProfile(
+ const nextPersistentMindProfile = mergePersistentMindProfile(
priorPersistentMindProfile,
updates.persistentMindProfile,
);
+ persistentMindWakeCadenceChanged = nextPersistentMindProfile.wakeIntervalMinutes
+ !== normalizePersistentMindProfile(priorPersistentMindProfile).wakeIntervalMinutes;
+ state.config.persistentMindProfile = nextPersistentMindProfile;
}
if (updates.persistentMindCapabilities !== undefined) {
state.config.persistentMindCapabilities = mergePersistentMindCapabilities(
@@ -273,6 +278,9 @@ export async function updateConfig(updates) {
return state.config;
});
cosEvents.emit('config:changed', config);
+ if (persistentMindWakeCadenceChanged) {
+ await refreshPersistentMindWakeCadence();
+ }
if (isDaemonRunning() && updates.domainAutonomy !== undefined) {
const mode = getDomainMode(config, 'cos');
if (mode === 'execute') await handlePersistentMindGlobalResume();
diff --git a/server/services/persistentMindSupervisor.js b/server/services/persistentMindSupervisor.js
index fa93b21c6a..103afbc3af 100644
--- a/server/services/persistentMindSupervisor.js
+++ b/server/services/persistentMindSupervisor.js
@@ -47,7 +47,7 @@ import { preparePersistentMindContext } from './persistentMindContext.js';
import { resolvePersistentMindProfile } from './persistentMindProfile.js';
import { isUpdateInProgress } from './updateChecker.js';
import { publicPersistentMindState } from '../lib/persistentMindPublic.js';
-import { normalizePersistentMindProfile } from '../lib/persistentMindProfile.js';
+import { normalizePersistentMindProfile, persistentMindWakeIntervalMs } from '../lib/persistentMindProfile.js';
import { getProviderById } from './providers.js';
import {
imageCapabilityAllowsAttempt,
@@ -498,14 +498,16 @@ function initialSelfWake(reason) {
};
}
-function quietSelfWake(turnId, notBefore = Date.now() + PERSISTENT_MIND_LIMITS.MAX_QUIET_MS) {
+const QUIET_SELF_WAKE_REASON = 'maximum quiet period elapsed';
+
+function quietSelfWake(turnId, quietPeriodMs = PERSISTENT_MIND_LIMITS.MAX_QUIET_MS, baseAt = Date.now()) {
return {
id: `wake-${randomUUID()}`,
kind: 'self',
- reason: 'maximum quiet period elapsed',
+ reason: QUIET_SELF_WAKE_REASON,
sourceTurnId: turnId,
createdAt: nowIso(),
- notBefore: new Date(notBefore).toISOString(),
+ notBefore: new Date(baseAt + quietPeriodMs).toISOString(),
};
}
@@ -670,7 +672,7 @@ async function heartbeat(turnId, generation) {
async function completeTurn(turnId, result, generation) {
if (generation !== runtimeGeneration) return;
const completedAt = nowIso();
- const updated = await mutateMindState((mind) => {
+ const updated = await mutateMindState((mind, root) => {
if (mind.activeTurn?.id !== turnId) return { mind, value: false };
const messageId = mind.activeTurn.wake.kind === 'message'
? mind.activeTurn.wake.message.id
@@ -688,6 +690,9 @@ async function completeTurn(turnId, result, generation) {
fingerprint: messageFingerprint,
}].slice(-PERSISTENT_MIND_LIMITS.MAX_RECENT_MESSAGE_IDS)
: mind.recentMessageFingerprints;
+ const quietPeriodMs = persistentMindWakeIntervalMs(root.config?.persistentMindProfile);
+ const quietDeadline = Date.parse(completedAt) + quietPeriodMs;
+ const requestedAt = Date.parse(result?.selfWake?.notBefore);
const requestedWake = result?.selfWake && typeof result.selfWake === 'object'
? {
id: `wake-${randomUUID()}`,
@@ -696,9 +701,14 @@ async function completeTurn(turnId, result, generation) {
.slice(0, PERSISTENT_MIND_LIMITS.MAX_REASON_CHARS),
sourceTurnId: turnId,
createdAt: completedAt,
- notBefore: result.selfWake.notBefore || completedAt,
+ // A turn may request an earlier follow-up, but the saved cadence is
+ // the operator's maximum quiet period and therefore caps later asks.
+ notBefore: new Date(Math.min(
+ quietDeadline,
+ Number.isFinite(requestedAt) ? Math.max(Date.parse(completedAt), requestedAt) : Date.parse(completedAt),
+ )).toISOString(),
}
- : quietSelfWake(turnId);
+ : quietSelfWake(turnId, quietPeriodMs, Date.parse(completedAt));
const hasQueuedMessages = mind.queuedMessages.length > 0;
return {
mind: {
@@ -1032,6 +1042,30 @@ export async function getPersistentMindState() {
return normalizePersistentMindState(state.persistentMind);
}
+/** Apply a saved cadence to the currently scheduled self-wake and timer. */
+export async function refreshPersistentMindWakeCadence() {
+ const result = await mutateMindState((mind, root) => {
+ if (!mind.started || mind.activeTurn) return { mind };
+ const quietPeriodMs = persistentMindWakeIntervalMs(root.config?.persistentMindProfile);
+ const baseAt = Number.isFinite(Date.parse(mind.lastCompletedAt))
+ ? Date.parse(mind.lastCompletedAt)
+ : Date.now();
+ const quietDeadline = baseAt + quietPeriodMs;
+ let selfWake = mind.selfWake;
+ if (!selfWake && mind.queuedMessages.length === 0) {
+ selfWake = quietSelfWake(mind.lastCompletedTurnId || 'cadence-change', quietPeriodMs, baseAt);
+ } else if (selfWake?.reason === QUIET_SELF_WAKE_REASON) {
+ selfWake = quietSelfWake(selfWake.sourceTurnId || mind.lastCompletedTurnId || 'cadence-change', quietPeriodMs, baseAt);
+ } else if (selfWake && (!Number.isFinite(Date.parse(selfWake.notBefore)) || Date.parse(selfWake.notBefore) > quietDeadline)) {
+ selfWake = { ...selfWake, notBefore: new Date(quietDeadline).toISOString() };
+ }
+ return { mind: { ...mind, selfWake } };
+ });
+ if (result.state.started) await scheduleNextWake();
+ emitMindStatus(result.state);
+ return result.state;
+}
+
export async function setPersistentMindEnabled(enabled) {
if (!enabled) {
runtimeGeneration += 1;
@@ -1392,7 +1426,7 @@ export async function checkPersistentMindWatchdog() {
export async function initializePersistentMindSupervisor() {
supervisorStopping = false;
await cleanupPersistentMindAttachments();
- const recovered = await mutateMindState((mind) => {
+ const recovered = await mutateMindState((mind, root) => {
if (!mind.enabled || !mind.started) return { mind };
let next = mind;
const orphanedTurnId = mind.activeTurn?.id || null;
@@ -1410,7 +1444,14 @@ export async function initializePersistentMindSupervisor() {
};
} 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) };
+ next = {
+ ...next,
+ selfWake: quietSelfWake(
+ next.lastCompletedTurnId || 'restart',
+ persistentMindWakeIntervalMs(root.config?.persistentMindProfile),
+ base,
+ ),
+ };
}
return { mind: next, value: { orphanedTurnId, mindId: mind.mindId } };
});
diff --git a/server/services/persistentMindSupervisor.test.js b/server/services/persistentMindSupervisor.test.js
index 4ba70e0110..cde973c0ee 100644
--- a/server/services/persistentMindSupervisor.test.js
+++ b/server/services/persistentMindSupervisor.test.js
@@ -196,6 +196,52 @@ describe('persistent mind supervisor', () => {
expect(mock.recordUsage).toHaveBeenCalledWith('cos', expect.objectContaining({ actions: 1 }));
});
+ it('caps model-requested follow-ups at the saved maximum quiet period', async () => {
+ mock.root.config.persistentMindProfile.wakeIntervalMinutes = 15;
+ await supervisor.registerPersistentMindTurnAdapter({
+ prepare: vi.fn(async () => ({ ok: true, provider: { id: 'example-cloud' } })),
+ run: vi.fn(async () => ({
+ selfWake: {
+ reason: 'Check again later',
+ notBefore: new Date(Date.now() + 2 * 60 * 60_000).toISOString(),
+ },
+ })),
+ });
+ await supervisor.setPersistentMindEnabled(true);
+ await supervisor.startPersistentMind();
+ await supervisor.drainPersistentMind();
+
+ const { lastCompletedAt, selfWake } = mock.root.persistentMind;
+ expect(selfWake.reason).toBe('Check again later');
+ expect(Date.parse(selfWake.notBefore) - Date.parse(lastCompletedAt)).toBe(15 * 60_000);
+ });
+
+ it('re-arms an idle automatic wake when its saved cadence changes', async () => {
+ const lastCompletedAt = new Date(Date.now() - 10 * 60_000).toISOString();
+ mock.root.persistentMind = {
+ ...createDefaultPersistentMindState(),
+ enabled: true,
+ started: true,
+ status: 'idle',
+ lastCompletedTurnId: 'turn-1',
+ lastCompletedAt,
+ selfWake: {
+ id: 'wake-old',
+ kind: 'self',
+ reason: 'maximum quiet period elapsed',
+ sourceTurnId: 'turn-1',
+ createdAt: lastCompletedAt,
+ notBefore: new Date(Date.parse(lastCompletedAt) + 30 * 60_000).toISOString(),
+ },
+ };
+ mock.root.config.persistentMindProfile.wakeIntervalMinutes = 60;
+
+ await supervisor.refreshPersistentMindWakeCadence();
+
+ expect(Date.parse(mock.root.persistentMind.selfWake.notBefore) - Date.parse(lastCompletedAt)).toBe(60 * 60_000);
+ expect(mock.scheduled.get(supervisor.PERSISTENT_MIND_WAKE_EVENT_ID).delayMs).toBeGreaterThan(40 * 60_000);
+ });
+
it('fails closed when a legacy completed message has no retry fingerprint', async () => {
mock.root.persistentMind.recentMessageIds = ['legacy-message'];