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: pin persistent mind provider profile (#5067)

[._.]/ Adam Eivyd09e55aaae30
diff --git a/client/src/components/cos/tabs/ConfigTab.jsx b/client/src/components/cos/tabs/ConfigTab.jsx
index 5c8896e483..43f177c6d0 100644
--- a/client/src/components/cos/tabs/ConfigTab.jsx
+++ b/client/src/components/cos/tabs/ConfigTab.jsx
@@ -263,10 +263,34 @@ const getDefaultFormData = (config, avatarStyle) => ({
avatarStyle: config?.avatarStyle || avatarStyle || 'svg'
});
+const DEFAULT_PERSISTENT_MIND_PROFILE = {
+ schemaVersion: 1,
+ enabled: false,
+ providerId: '',
+ model: '',
+ effort: '',
+ thinkingInterface: 'text',
+};
+
+const mindProfileFromConfig = (config) => ({
+ ...DEFAULT_PERSISTENT_MIND_PROFILE,
+ ...(config?.persistentMindProfile || {}),
+});
+
export default function ConfigTab({ config, onUpdate, onEvaluate, avatarStyle }) {
const { providers, availableModels, setSelectedProviderId: setProviderHook, setSelectedModel: setModelHook, selectedProviderId: hookProviderId, selectedModel: hookModel } = useProviderModels();
+ const {
+ providers: mindProviders,
+ availableModels: mindModels,
+ setSelectedProviderId: setMindProviderHook,
+ setSelectedModel: setMindModelHook,
+ selectedProviderId: mindHookProviderId,
+ selectedModel: mindHookModel,
+ } = useProviderModels({ allowDefault: true, withEffort: true, silent: true });
const [embeddingProviderId, setEmbeddingProviderId] = useState(config?.embeddingProviderId || 'lmstudio');
const [embeddingModel, setEmbeddingModel] = useState(config?.embeddingModel || '');
+ const [mindProfile, setMindProfile] = useState(() => mindProfileFromConfig(config));
+ const [mindProfileSaving, setMindProfileSaving] = useState(false);
// Sync local state when config prop updates
useEffect(() => {
@@ -280,6 +304,13 @@ export default function ConfigTab({ config, onUpdate, onEvaluate, avatarStyle })
}
}, [config?.embeddingProviderId, config?.embeddingModel, setProviderHook, setModelHook]);
+ useEffect(() => {
+ const next = mindProfileFromConfig(config);
+ setMindProfile(next);
+ setMindProviderHook(next.providerId);
+ setMindModelHook(next.model);
+ }, [config?.persistentMindProfile, setMindProviderHook, setMindModelHook]);
+
const [editing, setEditing] = useState(false);
const [formData, setFormData] = useState(() => getDefaultFormData(config, avatarStyle));
@@ -357,6 +388,31 @@ export default function ConfigTab({ config, onUpdate, onEvaluate, avatarStyle })
}
};
+ const saveMindProfile = async (patch) => {
+ const providerChanged = patch.providerId !== undefined && patch.providerId !== mindProfile.providerId;
+ const next = {
+ ...mindProfile,
+ ...patch,
+ ...(providerChanged && patch.model === undefined ? { model: '' } : {}),
+ ...(providerChanged && patch.effort === undefined ? { effort: '' } : {}),
+ };
+ const previous = mindProfile;
+ setMindProfile(next);
+ setMindProfileSaving(true);
+ try {
+ await api.updateCosConfig({ persistentMindProfile: next }, { silent: true });
+ toast.success('Persistent mind profile updated');
+ onUpdate();
+ } catch (err) {
+ setMindProfile(previous);
+ setMindProviderHook(previous.providerId);
+ setMindModelHook(previous.model);
+ toast.error(err.message);
+ } finally {
+ setMindProfileSaving(false);
+ }
+ };
+
const handleSave = async () => {
// Keep the user in edit mode on failure — only close the editor and toast
// success once the config PUT actually resolves.
@@ -420,6 +476,54 @@ export default function ConfigTab({ config, onUpdate, onEvaluate, avatarStyle })
<DomainBudgetControl config={config} usage={budgetUsage} onBudgetChange={handleBudgetChange} />
+ <div>
+ <h4 className="text-sm font-medium text-gray-400 mb-2">Persistent Mind</h4>
+ <div className="bg-port-card border border-port-border rounded-lg p-4 space-y-3">
+ <div className="flex items-start justify-between gap-4">
+ <div>
+ <label htmlFor="persistent-mind-enabled" className="text-sm text-gray-300">Enable persistent mind profile</label>
+ <p className="text-xs text-gray-600 mt-0.5">
+ Pins text reasoning to one provider and model. Saving this profile never starts a turn or downloads a model.
+ </p>
+ </div>
+ <input
+ id="persistent-mind-enabled"
+ type="checkbox"
+ checked={mindProfile.enabled}
+ disabled={mindProfileSaving}
+ onChange={(event) => saveMindProfile({ enabled: event.target.checked })}
+ className="mt-1 h-4 w-4 accent-port-accent disabled:opacity-50"
+ />
+ </div>
+ <ProviderModelSelector
+ providers={mindProviders}
+ selectedProviderId={mindProfile.providerId || mindHookProviderId}
+ selectedModel={mindProfile.model || mindHookModel}
+ availableModels={mindModels}
+ effort={mindProfile.effort}
+ disabled={mindProfileSaving || !mindProfile.enabled}
+ emptyProviderOption="Select a provider"
+ emptyModelOption="Select a model"
+ alwaysShowModel
+ layout="stacked"
+ label="Persistent mind provider"
+ onProviderChange={(providerId) => {
+ setMindProviderHook(providerId);
+ setMindModelHook('');
+ saveMindProfile({ providerId });
+ }}
+ onModelChange={(model) => {
+ setMindModelHook(model);
+ saveMindProfile({ model });
+ }}
+ onEffortChange={(effort) => saveMindProfile({ effort })}
+ />
+ <p className="text-xs text-gray-600">
+ Interface: text reasoning only. File-changing work remains an explicit typed CoS task with its own coding harness; an unavailable or invalid pin pauses the mind instead of falling back.
+ </p>
+ </div>
+ </div>
+
<div className="bg-port-card border border-port-border rounded-lg divide-y divide-port-border">
<ConfigRow
label="Health Check Interval"
diff --git a/client/src/components/cos/tabs/ConfigTab.test.jsx b/client/src/components/cos/tabs/ConfigTab.test.jsx
index 507d7f75c7..04be6ec903 100644
--- a/client/src/components/cos/tabs/ConfigTab.test.jsx
+++ b/client/src/components/cos/tabs/ConfigTab.test.jsx
@@ -9,6 +9,10 @@ const api = vi.hoisted(() => ({
getCosBudgetUsage: vi.fn(),
}));
const toast = vi.hoisted(() => ({ success: vi.fn(), error: vi.fn() }));
+const providerHook = vi.hoisted(() => ({
+ setSelectedProviderId: vi.fn(),
+ setSelectedModel: vi.fn(),
+}));
vi.mock('../../../services/api', () => api);
vi.mock('../../ui/Toast', () => ({ default: toast }));
@@ -16,10 +20,10 @@ vi.mock('../../ui/Toast', () => ({ default: toast }));
// so the test exercises only the config-save / level-change handlers.
vi.mock('../../../hooks/useProviderModels', () => ({
default: () => ({
- providers: [],
- availableModels: [],
- setSelectedProviderId: vi.fn(),
- setSelectedModel: vi.fn(),
+ providers: [{ id: 'codex', name: 'Codex', models: ['gpt-5'], defaultModel: 'gpt-5' }],
+ availableModels: ['gpt-5'],
+ setSelectedProviderId: providerHook.setSelectedProviderId,
+ setSelectedModel: providerHook.setSelectedModel,
selectedProviderId: '',
selectedModel: '',
}),
@@ -77,6 +81,25 @@ describe('ConfigTab handleSave', () => {
});
});
+describe('persistent mind profile', () => {
+ it('starts disabled and saving its toggle sends a default-safe profile without starting a mind', async () => {
+ api.updateCosConfig.mockResolvedValue({ success: true });
+ render(<ConfigTab config={config} onUpdate={vi.fn()} onEvaluate={vi.fn()} avatarStyle="svg" setAvatarStyle={vi.fn()} />);
+
+ const toggle = screen.getByRole('checkbox', { name: 'Enable persistent mind profile' });
+ expect(toggle).not.toBeChecked();
+ fireEvent.click(toggle);
+
+ await waitFor(() => expect(api.updateCosConfig).toHaveBeenCalledWith(
+ expect.objectContaining({
+ persistentMindProfile: expect.objectContaining({ enabled: true, thinkingInterface: 'text' }),
+ }),
+ { silent: true },
+ ));
+ expect(screen.getByText(/never starts a turn or downloads a model/i)).toBeInTheDocument();
+ });
+});
+
describe('Default Avatar Style dropdown', () => {
it('disables default avatar style dropdown when not editing', async () => {
render(<ConfigTab config={{ ...config, avatarStyle: 'svg' }} onUpdate={vi.fn()} onEvaluate={vi.fn()} avatarStyle="svg" setAvatarStyle={vi.fn()} />);
diff --git a/scripts/migrations/300-persistent-mind-profile.js b/scripts/migrations/300-persistent-mind-profile.js
new file mode 100644
index 0000000000..b848251f1a
--- /dev/null
+++ b/scripts/migrations/300-persistent-mind-profile.js
@@ -0,0 +1,45 @@
+/**
+ * Add the default-off persistent-mind provider profile to existing CoS state.
+ *
+ * The runtime slice arrived in migration 298. Keeping the profile in config
+ * makes its schema independently evolvable and, crucially, never turns an
+ * existing install's persistent mind on during upgrade.
+ */
+
+import { readFile } from 'fs/promises';
+import { join } from 'path';
+import { atomicWrite } from '../../server/lib/fileUtils.js';
+import { createDefaultPersistentMindProfile } from '../../server/lib/persistentMindProfile.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' };
+ }
+
+ state.config = state.config && typeof state.config === 'object' && !Array.isArray(state.config)
+ ? state.config
+ : {};
+ if (Object.hasOwn(state.config, 'persistentMindProfile')) {
+ return { updated: 0, reason: 'already-applied' };
+ }
+
+ state.config.persistentMindProfile = createDefaultPersistentMindProfile();
+ await atomicWrite(statePath, state);
+ console.log('🧠 migration 300: added disabled persistent mind provider profile');
+ return { updated: 1 };
+ },
+};
diff --git a/scripts/migrations/300-persistent-mind-profile.test.js b/scripts/migrations/300-persistent-mind-profile.test.js
new file mode 100644
index 0000000000..7bfb6446a4
--- /dev/null
+++ b/scripts/migrations/300-persistent-mind-profile.test.js
@@ -0,0 +1,37 @@
+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 './300-persistent-mind-profile.js';
+
+const readJson = (path) => JSON.parse(readFileSync(path, 'utf8'));
+
+describe('migration 300 — persistent mind profile', () => {
+ let rootDir;
+ let statePath;
+
+ beforeEach(() => {
+ rootDir = mkdtempSync(join(tmpdir(), 'migration-300-persistent-mind-profile-'));
+ mkdirSync(join(rootDir, 'data', 'cos'), { recursive: true });
+ statePath = join(rootDir, 'data', 'cos', 'state.json');
+ });
+
+ afterEach(() => rmSync(rootDir, { recursive: true, force: true }));
+
+ it('adds a disabled profile without changing existing config or runtime state', async () => {
+ writeFileSync(statePath, JSON.stringify({ config: { alwaysOn: true }, persistentMind: { enabled: true } }));
+ await expect(migration.up({ rootDir })).resolves.toEqual({ updated: 1 });
+ expect(readJson(statePath)).toMatchObject({
+ config: { alwaysOn: true, persistentMindProfile: { enabled: false, thinkingInterface: 'text' } },
+ persistentMind: { enabled: true },
+ });
+ });
+
+ it('is idempotent and leaves malformed input for normal CoS recovery', async () => {
+ writeFileSync(statePath, JSON.stringify({ config: { persistentMindProfile: { enabled: true } } }));
+ await expect(migration.up({ rootDir })).resolves.toEqual({ updated: 0, reason: 'already-applied' });
+ 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.md
index cfd72b6c0a..a8f2005a9f 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -41,6 +41,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `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. |
| `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. |
| `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.js
index 7e01e6a736..29c1a86ca9 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -216,6 +216,7 @@ export * from './agentRunEvents.js';
export * from './agentRunReconcile.js';
export * from './persistentMind.js';
export * from './persistentMindTrajectory.js';
+export * from './persistentMindProfile.js';
export * from './agentSentinel.js';
export * from './bareUrl.js';
export * from './bashResolver.js';
diff --git a/server/lib/persistentMindProfile.js b/server/lib/persistentMindProfile.js
new file mode 100644
index 0000000000..43341d2fdc
--- /dev/null
+++ b/server/lib/persistentMindProfile.js
@@ -0,0 +1,77 @@
+/**
+ * Durable provider profile for the persistent CoS mind.
+ *
+ * This is deliberately separate from persistentMind.js: that module owns
+ * runtime wake state, while this one owns the user's stable, default-off
+ * provider choice. A profile never implies that a mind is running.
+ */
+
+import { z } from 'zod';
+import { EFFORT_LEVELS } from './providerModels.js';
+
+export const PERSISTENT_MIND_PROFILE_SCHEMA_VERSION = 1;
+
+export const PERSISTENT_MIND_THINKING_INTERFACE = 'text';
+
+export const PERSISTENT_MIND_PROFILE_LIMITS = Object.freeze({
+ PROVIDER_ID_MAX: 100,
+ MODEL_MAX: 200,
+});
+
+export const persistentMindProfileSchema = z.object({
+ schemaVersion: z.literal(PERSISTENT_MIND_PROFILE_SCHEMA_VERSION).optional(),
+ enabled: z.boolean().optional(),
+ providerId: z.string().max(PERSISTENT_MIND_PROFILE_LIMITS.PROVIDER_ID_MAX).optional(),
+ model: z.string().max(PERSISTENT_MIND_PROFILE_LIMITS.MODEL_MAX).optional(),
+ // Empty is the UI's explicit "provider default" sentinel. It is stored as
+ // 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(),
+}).strict();
+
+export function createDefaultPersistentMindProfile() {
+ return {
+ schemaVersion: PERSISTENT_MIND_PROFILE_SCHEMA_VERSION,
+ enabled: false,
+ providerId: '',
+ model: '',
+ effort: '',
+ thinkingInterface: PERSISTENT_MIND_THINKING_INTERFACE,
+ };
+}
+
+const text = (value, max) => (typeof value === 'string' ? value.trim().slice(0, max) : '');
+
+/** Normalize legacy or hand-edited config without turning an invalid effort into a pin. */
+export function normalizePersistentMindProfile(raw) {
+ const defaults = createDefaultPersistentMindProfile();
+ const source = raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : {};
+ const effort = text(source.effort, 20);
+ return {
+ ...defaults,
+ enabled: source.enabled === true,
+ providerId: text(source.providerId, PERSISTENT_MIND_PROFILE_LIMITS.PROVIDER_ID_MAX),
+ model: text(source.model, PERSISTENT_MIND_PROFILE_LIMITS.MODEL_MAX),
+ effort: EFFORT_LEVELS.includes(effort) ? effort : '',
+ thinkingInterface: source.thinkingInterface === PERSISTENT_MIND_THINKING_INTERFACE
+ ? source.thinkingInterface
+ : PERSISTENT_MIND_THINKING_INTERFACE,
+ };
+}
+
+/**
+ * Merge a partial update without carrying a model/effort chosen for another
+ * provider. Changing providers always clears dependent selections unless the
+ * caller supplies replacements in the same request.
+ */
+export function mergePersistentMindProfile(previous, update) {
+ const prior = normalizePersistentMindProfile(previous);
+ const patch = update && typeof update === 'object' && !Array.isArray(update) ? update : {};
+ const providerChanged = patch.providerId !== undefined && patch.providerId !== prior.providerId;
+ return normalizePersistentMindProfile({
+ ...prior,
+ ...patch,
+ ...(providerChanged && patch.model === undefined ? { model: '' } : {}),
+ ...(providerChanged && patch.effort === undefined ? { effort: '' } : {}),
+ });
+}
diff --git a/server/lib/persistentMindProfile.test.js b/server/lib/persistentMindProfile.test.js
new file mode 100644
index 0000000000..f76f3002e5
--- /dev/null
+++ b/server/lib/persistentMindProfile.test.js
@@ -0,0 +1,39 @@
+import { describe, expect, it } from 'vitest';
+import {
+ createDefaultPersistentMindProfile,
+ mergePersistentMindProfile,
+ normalizePersistentMindProfile,
+ persistentMindProfileSchema,
+} from './persistentMindProfile.js';
+
+describe('persistent mind profile', () => {
+ it('defaults to disabled text reasoning with no provider pin', () => {
+ expect(createDefaultPersistentMindProfile()).toEqual({
+ schemaVersion: 1,
+ enabled: false,
+ providerId: '',
+ model: '',
+ effort: '',
+ thinkingInterface: 'text',
+ });
+ });
+
+ 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' });
+ });
+
+ it('clears model and effort when a provider changes without replacements', () => {
+ const prior = { enabled: true, providerId: 'codex', model: 'gpt-5', effort: 'high', thinkingInterface: 'text' };
+ expect(mergePersistentMindProfile(prior, { providerId: 'claude' }))
+ .toMatchObject({ providerId: 'claude', model: '', effort: '' });
+ expect(mergePersistentMindProfile(prior, { providerId: 'claude', model: 'sonnet', effort: 'medium' }))
+ .toMatchObject({ providerId: 'claude', model: 'sonnet', effort: 'medium' });
+ });
+
+ it('uses the shared effort vocabulary and an explicit text interface at the API boundary', () => {
+ 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);
+ });
+});
diff --git a/server/routes/cosStatusRoutes.js b/server/routes/cosStatusRoutes.js
index eedcf28752..b9a1bec0fa 100644
--- a/server/routes/cosStatusRoutes.js
+++ b/server/routes/cosStatusRoutes.js
@@ -12,6 +12,7 @@ import { validateRequest } from '../lib/validation.js';
import { z } from 'zod';
import { DOMAIN_IDS, DOMAIN_MODES } from '../lib/domainAutonomy.js';
import { BUDGET_LIMIT_FIELDS } from '../lib/domainBudgets.js';
+import { persistentMindProfileSchema } from '../lib/persistentMindProfile.js';
const router = Router();
@@ -49,6 +50,9 @@ export const cosConfigSchema = z.object({
autonomousJobsEnabled: z.boolean().optional(),
autonomyLevel: z.enum(['standby', 'assistant', 'manager', 'yolo']).optional(),
autoApproveInvestigations: z.boolean().optional(),
+ // A durable reasoning route for the persistent mind. It is separate from
+ // `alwaysOn`: saving or enabling this profile never starts background work.
+ persistentMindProfile: persistentMindProfileSchema.optional(),
// Per-domain autonomy guardrails (#711): partial map of domainId → mode.
// Partial is fine — updateConfig() merges it over the stored map.
domainAutonomy: z.object(
diff --git a/server/services/cos.js b/server/services/cos.js
index 8271c91b55..9c35f47881 100644
--- a/server/services/cos.js
+++ b/server/services/cos.js
@@ -35,6 +35,7 @@ import { todayInTimezone } from '../lib/timezone.js';
import { getUserTimezone } from './userTimezone.js';
import { normalizeDomainAutonomy, getDomainMode } from '../lib/domainAutonomy.js';
import { normalizeDomainBudgets, remainingActionBudget } from '../lib/domainBudgets.js';
+import { mergePersistentMindProfile } from '../lib/persistentMindProfile.js';
import { getDomainBudgetStatus } from './domainUsage.js';
import { pendingCosActionReservations } from './cosAdmissionReservations.js';
// Dependency-free leaf holding the shared agent maps + the runner-mode flag,
@@ -220,6 +221,7 @@ export async function updateConfig(updates) {
// Same for domainBudgets — a PATCH naming one domain (or one cap on one
// domain) must merge field-by-field over the rest, not replace the map.
const priorDomainBudgets = state.config.domainBudgets;
+ const priorPersistentMindProfile = state.config.persistentMindProfile;
state.config = { ...state.config, ...updates };
if (updates.domainAutonomy !== undefined) {
state.config.domainAutonomy = normalizeDomainAutonomy({
@@ -234,6 +236,12 @@ export async function updateConfig(updates) {
}
state.config.domainBudgets = normalizeDomainBudgets(mergedBudgets);
}
+ if (updates.persistentMindProfile !== undefined) {
+ state.config.persistentMindProfile = mergePersistentMindProfile(
+ priorPersistentMindProfile,
+ updates.persistentMindProfile,
+ );
+ }
await saveState(state);
return state.config;
});
diff --git a/server/services/cosState.js b/server/services/cosState.js
index ac0396b915..c0b90721c8 100644
--- a/server/services/cosState.js
+++ b/server/services/cosState.js
@@ -12,6 +12,7 @@ import { ensureDirs, safeJSONParse, PATHS, atomicWrite } from '../lib/fileUtils.
import { normalizeDomainAutonomy, getDomainMode } from '../lib/domainAutonomy.js';
import { normalizeDomainBudgets } from '../lib/domainBudgets.js';
import { createDefaultPersistentMindState, normalizePersistentMindState } from '../lib/persistentMind.js';
+import { createDefaultPersistentMindProfile, normalizePersistentMindProfile } from '../lib/persistentMindProfile.js';
import { DEFAULT_ALWAYS_APPROVE_KINDS } from './taskLearning/safetyKind.js';
export const STATE_FILE = join(PATHS.cos, 'state.json');
@@ -62,6 +63,9 @@ export const DEFAULT_CONFIG = {
// Investigation tasks normally hold only failure loops for a human. This
// opt-in also admits those loop/storm investigations unattended.
autoApproveInvestigations: false,
+ // Persisting a profile is not consent to wake the mind. Fresh and upgraded
+ // installs stay disabled until the user explicitly enables and starts it.
+ persistentMindProfile: createDefaultPersistentMindProfile(),
// Per-domain autonomy guardrails (#711). Each domain is off | dry-run | execute.
// Default is `execute` for every domain, reproducing pre-#711 behavior so no
// migration is needed — an install with no stored value reads `execute`.
@@ -219,7 +223,11 @@ export async function loadState() {
stateCache = {
...DEFAULT_STATE,
...state,
- config: { ...DEFAULT_CONFIG, ...persistedConfig },
+ config: {
+ ...DEFAULT_CONFIG,
+ ...persistedConfig,
+ persistentMindProfile: normalizePersistentMindProfile(persistedConfig.persistentMindProfile),
+ },
stats: { ...DEFAULT_STATE.stats, ...state.stats },
persistentMind: normalizePersistentMindState(state.persistentMind),
agents: state.agents ?? {}
diff --git a/server/services/persistentMindProfile.js b/server/services/persistentMindProfile.js
new file mode 100644
index 0000000000..b8b570af11
--- /dev/null
+++ b/server/services/persistentMindProfile.js
@@ -0,0 +1,55 @@
+/**
+ * Resolve the persistent mind's pinned text-reasoning profile.
+ *
+ * This deliberately has no fallback path. A mind waking on a different
+ * provider/model than the one the user selected is a different identity, not
+ * a recovery. It also does not start a model, fetch a catalog, or generate
+ * text: it only reads the already-configured provider and status services.
+ */
+
+import { effortLevelsForProvider } from '../lib/providerModels.js';
+import { normalizePersistentMindProfile } from '../lib/persistentMindProfile.js';
+import { getProviderById } from './providers.js';
+import { getProviderStatus, isProviderAvailable } from './providerStatus.js';
+
+const providerModelIds = (provider) => (provider?.models || [])
+ .map((model) => typeof model === 'string' ? model : model?.id)
+ .filter(Boolean);
+
+/**
+ * Resolve a configured profile to one exact provider route, or a visible
+ * failure suitable for the supervisor's degraded state.
+ */
+export async function resolvePersistentMindProfile(rawProfile) {
+ const profile = normalizePersistentMindProfile(rawProfile);
+ if (!profile.enabled) return { ok: false, error: 'Persistent mind profile is disabled' };
+ if (!profile.providerId || !profile.model) {
+ return { ok: false, error: 'Persistent mind profile requires a provider and model' };
+ }
+
+ const provider = await getProviderById(profile.providerId);
+ if (!provider || provider.enabled === false) {
+ return { ok: false, error: `Pinned provider "${profile.providerId}" is unavailable` };
+ }
+ if (!isProviderAvailable(provider.id)) {
+ const status = getProviderStatus(provider.id);
+ return { ok: false, error: status?.message || `Pinned provider "${provider.id}" is unavailable` };
+ }
+
+ const models = providerModelIds(provider);
+ if (models.length > 0 && !models.includes(profile.model)) {
+ return { ok: false, error: `Pinned model "${profile.model}" is not available from provider "${provider.id}"` };
+ }
+ const supportedEfforts = effortLevelsForProvider(provider, profile.model);
+ if (profile.effort && (!supportedEfforts || !supportedEfforts.includes(profile.effort))) {
+ return { ok: false, error: `Pinned effort "${profile.effort}" is not supported by provider "${provider.id}"` };
+ }
+
+ return {
+ ok: true,
+ provider,
+ model: profile.model,
+ effort: profile.effort || null,
+ thinkingInterface: profile.thinkingInterface,
+ };
+}
diff --git a/server/services/persistentMindProfile.test.js b/server/services/persistentMindProfile.test.js
new file mode 100644
index 0000000000..64c7001a12
--- /dev/null
+++ b/server/services/persistentMindProfile.test.js
@@ -0,0 +1,56 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({
+ provider: null,
+ available: true,
+ status: { message: 'offline' },
+}));
+
+vi.mock('./providers.js', () => ({
+ getProviderById: vi.fn(async () => mocks.provider),
+}));
+vi.mock('./providerStatus.js', () => ({
+ isProviderAvailable: vi.fn(() => mocks.available),
+ getProviderStatus: vi.fn(() => mocks.status),
+}));
+
+const { resolvePersistentMindProfile } = await import('./persistentMindProfile.js');
+
+const profile = { enabled: true, providerId: 'local', model: 'reasoner', effort: '', thinkingInterface: 'text' };
+
+describe('resolvePersistentMindProfile', () => {
+ beforeEach(() => {
+ mocks.provider = { id: 'local', type: 'api', models: ['reasoner'] };
+ mocks.available = true;
+ mocks.status = { message: 'offline' };
+ });
+
+ it('resolves an API provider for text reasoning without treating it as a file-writing harness', async () => {
+ await expect(resolvePersistentMindProfile(profile)).resolves.toMatchObject({
+ ok: true,
+ provider: { id: 'local', type: 'api' },
+ model: 'reasoner',
+ thinkingInterface: 'text',
+ });
+ });
+
+ it('fails closed for a missing, unhealthy, or catalog-drifted pin', async () => {
+ mocks.provider = null;
+ await expect(resolvePersistentMindProfile(profile)).resolves.toMatchObject({ ok: false, error: /unavailable/ });
+
+ mocks.provider = { id: 'local', models: ['reasoner'] };
+ mocks.available = false;
+ await expect(resolvePersistentMindProfile(profile)).resolves.toEqual({ ok: false, error: 'offline' });
+
+ mocks.available = true;
+ await expect(resolvePersistentMindProfile({ ...profile, model: 'removed-model' })).resolves
+ .toMatchObject({ ok: false, error: /not available/ });
+ });
+
+ it('requires a complete enabled pin and rejects effort a provider cannot accept', async () => {
+ await expect(resolvePersistentMindProfile({ ...profile, model: '' })).resolves
+ .toEqual({ ok: false, error: 'Persistent mind profile requires a provider and model' });
+ await expect(resolvePersistentMindProfile({ ...profile, effort: 'high' })).resolves
+ .toMatchObject({ ok: false, error: /not supported/ });
+ });
+});
diff --git a/server/services/persistentMindSupervisor.js b/server/services/persistentMindSupervisor.js
index 9be29c3ead..55100cd4a8 100644
--- a/server/services/persistentMindSupervisor.js
+++ b/server/services/persistentMindSupervisor.js
@@ -29,6 +29,7 @@ import { acquireLocalEndpointProviderSlot } from './cosLocalEndpointSlots.js';
import { acquireCosActionReservation, acquireCosGlobalSlot } from './cosAdmissionReservations.js';
import { appendMindEvent } from './agentRunEventLog.js';
import { preparePersistentMindContext } from './persistentMindContext.js';
+import { resolvePersistentMindProfile } from './persistentMindProfile.js';
export const PERSISTENT_MIND_WAKE_EVENT_ID = 'cos-persistent-mind-wake';
export const PERSISTENT_MIND_WATCHDOG_EVENT_ID = 'cos-persistent-mind-watchdog';
@@ -459,12 +460,34 @@ async function runOnePersistentMindTurn() {
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 });
+ // The profile is resolved before an adapter can run. This is a read-only
+ // catalog/status check: no alternate provider, model pull, or generation
+ // is allowed while deciding whether the pinned mind can wake.
+ const profile = await resolvePersistentMindProfile(root.config?.persistentMindProfile);
+ if (!profile.ok) {
+ await parkActiveTurn(turn.id, profile.error, 'degraded');
+ return;
+ }
+ // Adapters receive the exact profile. They may prepare their text
+ // transport, but cannot substitute a fallback provider/model/effort.
+ const adapterPrepared = await turnAdapter.prepare({ wake: turn.wake, signal: controller.signal, profile });
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);
+ if (!adapterPrepared?.ok || !adapterPrepared.provider) {
+ await parkActiveTurn(turn.id, adapterPrepared?.error || 'Persistent mind provider is unavailable', 'degraded', adapterPrepared?.retryAt || null);
+ return;
+ }
+ // Existing adapters only named their transport provider; missing model or
+ // effort now means "use the supplied profile", while an explicit value
+ // still must match exactly and cannot become a fallback route.
+ const prepared = {
+ ...adapterPrepared,
+ model: adapterPrepared.model ?? profile.model,
+ effort: adapterPrepared.effort ?? profile.effort,
+ };
+ if (prepared.provider.id !== profile.provider.id
+ || prepared.model !== profile.model
+ || prepared.effort !== profile.effort) {
+ await parkActiveTurn(turn.id, 'Persistent mind adapter did not honor the pinned provider profile', 'degraded');
return;
}
await recordTurnProfile(turn.id, prepared);
diff --git a/server/services/persistentMindSupervisor.test.js b/server/services/persistentMindSupervisor.test.js
index af153df91b..f28cafd781 100644
--- a/server/services/persistentMindSupervisor.test.js
+++ b/server/services/persistentMindSupervisor.test.js
@@ -16,6 +16,13 @@ const mock = vi.hoisted(() => ({
appendMindEvent: vi.fn(async (event) => ({ appended: true, event })),
prepareContext: vi.fn(async () => ({ text: 'bounded context', chars: 15, summaryState: 'not-needed' })),
daemonRunning: true,
+ profile: {
+ ok: true,
+ provider: { id: 'example-cloud' },
+ model: 'example-model',
+ effort: 'high',
+ thinkingInterface: 'text',
+ },
}));
vi.mock('./cosState.js', () => ({
@@ -55,11 +62,19 @@ vi.mock('./persistentMindContext.js', () => ({
preparePersistentMindContext: (...args) => mock.prepareContext(...args),
}));
+vi.mock('./persistentMindProfile.js', () => ({
+ resolvePersistentMindProfile: vi.fn(async () => mock.profile),
+}));
+
const supervisor = await import('./persistentMindSupervisor.js');
const makeRoot = () => ({
paused: false,
- config: { domainAutonomy: { cos: 'execute' }, maxConcurrentAgents: 3 },
+ config: {
+ domainAutonomy: { cos: 'execute' },
+ maxConcurrentAgents: 3,
+ persistentMindProfile: { enabled: true, providerId: 'example-cloud', model: 'example-model', effort: 'high', thinkingInterface: 'text' },
+ },
agents: {},
persistentMind: createDefaultPersistentMindState(),
});
@@ -79,6 +94,13 @@ describe('persistent mind supervisor', () => {
mock.budget = { withinBudget: true, exceeded: null };
mock.daemonRunning = true;
mock.recordUsage.mockClear();
+ mock.profile = {
+ ok: true,
+ provider: { id: 'example-cloud' },
+ model: 'example-model',
+ effort: 'high',
+ thinkingInterface: 'text',
+ };
mock.acquireSlot.mockReset();
mock.acquireSlot.mockResolvedValue({ ok: true, release: vi.fn() });
mock.appendMindEvent.mockClear();
@@ -145,12 +167,27 @@ describe('persistent mind supervisor', () => {
]));
expect(prepare).toHaveBeenCalledTimes(1);
+ expect(prepare).toHaveBeenCalledWith(expect.objectContaining({
+ profile: expect.objectContaining({ provider: { id: 'example-cloud' }, model: 'example-model', effort: 'high' }),
+ }));
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('pauses before adapter preparation when the pinned profile cannot resolve', async () => {
+ const prepare = vi.fn();
+ await supervisor.registerPersistentMindTurnAdapter({ prepare, run: vi.fn() });
+ mock.profile = { ok: false, error: 'Pinned provider unavailable' };
+ await supervisor.setPersistentMindEnabled(true);
+ await supervisor.startPersistentMind();
+ await supervisor.drainPersistentMind();
+
+ expect(prepare).not.toHaveBeenCalled();
+ expect(mock.root.persistentMind).toMatchObject({ status: 'degraded', pauseReason: 'Pinned provider unavailable' });
+ });
+
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 = {
@@ -310,6 +347,13 @@ describe('persistent mind supervisor', () => {
it('requeues a claimed message when the shared local endpoint has no slot', async () => {
const run = vi.fn();
+ mock.profile = {
+ ok: true,
+ provider: { id: 'example-local', endpoint: 'http://127.0.0.1:1234' },
+ model: 'example-model',
+ effort: 'high',
+ thinkingInterface: 'text',
+ };
await supervisor.registerPersistentMindTurnAdapter({
prepare: vi.fn(async () => ({ ok: true, provider: { id: 'example-local', endpoint: 'http://127.0.0.1:1234' } })),
run,