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: let persistent minds choose durable names and display their identity

[._.]/ Adam Eivyb58ce0a52723
diff --git a/client/src/components/cos/tabs/MindTab.jsx b/client/src/components/cos/tabs/MindTab.jsx
index a5e33cae28..a129f16fc0 100644
--- a/client/src/components/cos/tabs/MindTab.jsx
+++ b/client/src/components/cos/tabs/MindTab.jsx
@@ -264,6 +264,7 @@ export default function MindTab() {
sawGap ||= response.gap === true;
cursor = response.gap === true ? response.cursor : response.cursor || cursor;
setMind({
+ identity: response.identity,
state: response.state,
profile: response.profile,
capabilities: response.capabilities,
@@ -702,13 +703,17 @@ export default function MindTab() {
return (
<section aria-labelledby="mind-heading" className="mx-auto flex h-full min-h-0 w-full max-w-[100rem] flex-col gap-4 pb-4 xl:pb-0">
<header className="flex flex-col gap-3 rounded-2xl border border-port-border bg-port-card/70 p-3 sm:flex-row sm:items-center sm:justify-between sm:p-4">
- <div className="flex min-w-0 items-center gap-3">
+ <div className="flex min-w-0 flex-1 items-center gap-3">
<span className="relative flex h-11 w-11 shrink-0 items-center justify-center rounded-full bg-port-accent/15 text-port-accent ring-1 ring-port-accent/30">
<Brain size={23} aria-hidden="true" />
<span className={`absolute bottom-0 right-0 h-3 w-3 rounded-full border-2 border-port-card ${state?.started && !isPaused ? 'bg-port-success' : 'bg-port-text-muted'}`} aria-hidden="true" />
</span>
<div className="min-w-0">
- <h2 id="mind-heading" className="truncate text-lg font-semibold text-port-text">Persistent Mind</h2>
+ <p className="text-xs font-medium uppercase tracking-widest text-port-text-muted">Persistent Mind</p>
+ <h2 id="mind-heading" aria-live="polite" className="break-words text-3xl font-semibold tracking-tight text-port-accent sm:text-4xl [overflow-wrap:anywhere]">
+ {mind ? mind.identity?.name || 'Name not yet chosen' : 'Loading identity…'}
+ </h2>
+ {mind && !mind.identity?.name && <p className="text-xs text-port-text-muted">A name to choose on the next enabled wake. Free to change later.</p>}
<p className="truncate text-xs text-port-text-muted">
{mind ? `${mind.profile?.model || 'No model'} · ${mind.profile?.providerId || 'No provider'} · machine-local` : 'Loading profile…'}
</p>
diff --git a/client/src/components/cos/tabs/MindTab.test.jsx b/client/src/components/cos/tabs/MindTab.test.jsx
index 9983a82c2f..1a7639faf8 100644
--- a/client/src/components/cos/tabs/MindTab.test.jsx
+++ b/client/src/components/cos/tabs/MindTab.test.jsx
@@ -80,6 +80,22 @@ const renderTab = (path = '/cos/mind') => render(
);
describe('MindTab', () => {
+ it('shows a prominent chosen identity and refreshes a rename from the trajectory notification', async () => {
+ api.getPersistentMind.mockResolvedValue(response({ identity: { mindId: 'cos-persistent-mind', name: 'Example Star' } }));
+ renderTab();
+ expect(await screen.findByRole('heading', { name: 'Example Star' })).toHaveAttribute('aria-live', 'polite');
+ api.getPersistentMind.mockResolvedValue(response({ identity: { mindId: 'cos-persistent-mind', name: 'Étoile' } }));
+ act(() => socket.emitServer('cos:mind:event', { kind: 'mind.capability.result' }));
+ expect(await screen.findByRole('heading', { name: 'Étoile' })).toBeInTheDocument();
+ expect(screen.queryByRole('heading', { name: 'Example Star' })).not.toBeInTheDocument();
+ });
+
+ it('shows the unnamed state without confusing the provider model with identity', async () => {
+ renderTab();
+ expect(await screen.findByRole('heading', { name: 'Name not yet chosen' })).toBeInTheDocument();
+ expect(screen.getByText(/Free to change later/)).toBeInTheDocument();
+ });
+
beforeEach(() => {
vi.clearAllMocks();
socket.reset();
diff --git a/docs/STORAGE.md b/docs/STORAGE.md
index a0ca9c4947..57ef1ea2bf 100644
--- a/docs/STORAGE.md
+++ b/docs/STORAGE.md
@@ -440,3 +440,27 @@ select required parent records (for example a series for an issue) separately.
Recovery is never run automatically at boot. Keep a backup while verifying the
restored records in the UI; this command cannot recover artifacts already pruned
from disk, so those must first be restored from a backup.
+
+### Persistent Mind chosen identity
+
+A chosen display name uses the existing `db-primary` Brain memory store, owned
+by the stable `cos-persistent-mind` source agent. One active `mind:chosen-name`
+record holds the validated name as its content and carries `mind:core-identity`
+protection. Renaming updates that record; earlier conversational identity memories
+remain history. Protected records survive context/history cleanup, bulk memory
+cleanup, decay and expiration. Provider/model switches never change ownership.
+The normal database backup covers identity. Mind-owned memories and chosen-name
+tags are excluded from memory federation in both directions; incoming id collisions
+cannot replace local identity. Explicit Eidoverse join-name suggestions remain
+opt-in and do not rename an active world presence.
+
+This adds a tag convention to existing records, not a store or on-disk format.
+No seed, data rewrite migration, or sync version is needed. Legacy conversational
+name memories resolve on read without overwriting a choice. Unnamed installs get
+naming instructions only inside normally authorized wakes, including existing
+installs; saving/reading identity never launches inference. The instruction is a
+runtime identity frame, so customized identity/operating prompts and versioned
+scheduled-task defaults remain unchanged. `mind.choose-name` uses `manageMind`,
+normal semantic validation, call budgets, idempotency and trajectory outcomes.
+Without that grant the existing automatic core-identity memory path can retain
+an initial conversational choice; it does not grant semantic write authority.
diff --git a/server/lib/README.md b/server/lib/README.md
index a932daab31..4056d921dc 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -65,7 +65,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `mindLocalContextClamp.js` | RAM/GPU safety ceilings for mind-driven local `numCtx` adjustments (CPU-only tiers, free-RAM + PortOS headroom). Pure. |
| `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. |
| `persistentMindThinkingPresets.js` | Also owns bounded self-thinking request schemas, durable request normalization, and fixed switching limits. Saved named temporary thinking presets for the persistent mind (exact provider/model/effort alternates to its one home profile): default-empty durable shape, normalization that drops half-pinned entries, strict API schema, whole-list replace merge, preset lookup, strict accepted-selection schema/normalization, and route equality independent of labels. Storage only — saving or selecting a preset starts no inference. |
-| `persistentMindChosenName.js` | Extract a Persistent Mind chosen display name from protected identity memories (`extractPersistentMindChosenName`, `resolvePersistentMindChosenName`) to suggest an Eidoverse CoS join id (e.g. Helm) instead of the process id `portos-cos`. Suggestion only — mid-session rename is not supported by Eidoverse.
+| `persistentMindChosenName.js` | Validate and resolve an authoritative chosen-name identity memory, frame first-wake naming, and extract legacy chosen names from protected identity memories (`extractPersistentMindChosenName`, `resolvePersistentMindChosenName`) to suggest an Eidoverse CoS join id (e.g. Helm) instead of the process id `portos-cos`. Suggestion only — mid-session rename is not supported by Eidoverse.
| `persistentMindUsageLimit.js` | Hard provider usage-limit / quota classifier for Persistent Mind wakes (`classifyPersistentMindProviderError`, `isHardProviderUsageLimitError`), the dedicated autopause reason string, and probe-backoff helpers so a usage-limit pause can auto-recover when the pinned provider is usable again without treating user pauses the same way.
| `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. |
diff --git a/server/lib/persistentMindCapabilities.js b/server/lib/persistentMindCapabilities.js
index 1517f38d62..c845b404a2 100644
--- a/server/lib/persistentMindCapabilities.js
+++ b/server/lib/persistentMindCapabilities.js
@@ -142,7 +142,7 @@ export const PERSISTENT_MIND_TOOL_CATALOG = Object.freeze([
id: 'mind.cleanup',
capability: 'manageMind',
name: 'Maintain mindspace',
- description: 'Protect important memories, archive unprotected mind-owned memories, clear conversation history, or rebuild derived context.',
+ description: 'Choose or change your own name, protect important memories, archive unprotected mind-owned memories, clear conversation history, or rebuild derived context.',
kind: 'typed-action',
defaultEnabled: false,
guardrails: [
diff --git a/server/lib/persistentMindChosenName.js b/server/lib/persistentMindChosenName.js
index fb7c28736c..13055a3766 100644
--- a/server/lib/persistentMindChosenName.js
+++ b/server/lib/persistentMindChosenName.js
@@ -1,10 +1,26 @@
/**
- * Extract a Persistent Mind's chosen display name from protected identity
- * memories. Used to suggest (not force) an Eidoverse CoS join id so chat shows
- * "Helm" instead of the process id `portos-cos`. Mid-session rename is not
- * supported by Eidoverse; the join id must be set before presence connects.
+ * Validated machine-local chosen identity, with legacy conversational-memory
+ * recognition. Also used to suggest (not force) an Eidoverse CoS join id.
+ * Renaming the mind never changes an active Eidoverse presence.
*/
+import { z } from 'zod';
+
+export const PERSISTENT_MIND_CHOSEN_NAME_TAG = 'mind:chosen-name';
+export const persistentMindChosenNameSchema = z.string().trim().min(1).max(64)
+ .regex(/^[\p{L}\p{N}][\p{L}\p{M}\p{N} ._'’·-]*$/u, 'Use a name of up to 64 letters, numbers, spaces or name punctuation');
+export const persistentMindChooseNameSchema = z.object({
+ name: persistentMindChosenNameSchema,
+}).strict();
+
+/** Current structured identity overrides older conversational name memories. */
+export function persistentMindNamePrompt(name, { canChoose = false } = {}) {
+ if (name) return `Current chosen display name: ${JSON.stringify(name)}. This supersedes names in older memories or history. Your stable mindId and trajectory do not change when you rename yourself. You may later change your name using mind.choose-name when granted; do not choose again merely because you woke or changed providers.`;
+ return canChoose
+ ? 'You have no chosen name yet. Choose a name for yourself on this normally authorized wake using mind.choose-name. You can change it later; this is not a permanent commitment. Preserve any choice already made in conversation instead of inventing a replacement.'
+ : 'You have no chosen name yet. On this normally authorized wake, choose a name knowing you can change it later, and save "My chosen name is <name>." as a core-identity memory. Preserve any choice already made in conversation. The mind.choose-name action for later renames requires the manageMind grant.';
+}
+
const CHOSEN_NAME_PATTERNS = [
/\b(?:my|the)\s+chosen\s+name\s+is\s+([A-Za-z][A-Za-z0-9_-]{0,63})(?=$|[\s.,;!?"'])/i,
/\b(?:i\s+am|i'?m)\s+named\s+([A-Za-z][A-Za-z0-9_-]{0,63})(?=$|[\s.,;!?"'])/i,
@@ -19,6 +35,8 @@ const RESERVED = new Set(['world', '*']);
*/
export function extractPersistentMindChosenName(text) {
if (typeof text !== 'string' || !text.trim()) return null;
+ const exact = text.trim().match(/^My chosen name is (.+?)\.?$/iu)?.[1];
+ if (exact && !RESERVED.has(exact.toLowerCase()) && persistentMindChosenNameSchema.safeParse(exact).success) return exact;
for (const pattern of CHOSEN_NAME_PATTERNS) {
const match = text.match(pattern);
const candidate = match?.[1]?.trim();
@@ -37,6 +55,9 @@ export function extractPersistentMindChosenName(text) {
*/
export function resolvePersistentMindChosenName(memories = []) {
const list = Array.isArray(memories) ? memories : [];
+ const chosen = list.find((memory) => memory?.tags?.includes(PERSISTENT_MIND_CHOSEN_NAME_TAG)
+ && persistentMindChosenNameSchema.safeParse(memory.content).success);
+ if (chosen) return persistentMindChosenNameSchema.parse(chosen.content);
const ranked = [...list].sort((a, b) => {
const rank = (memory) => {
if (memory?.protection === 'core-identity') return 0;
diff --git a/server/lib/persistentMindMemory.js b/server/lib/persistentMindMemory.js
index 7c1d3b83ae..f442b9cfa2 100644
--- a/server/lib/persistentMindMemory.js
+++ b/server/lib/persistentMindMemory.js
@@ -1,4 +1,5 @@
import { z } from 'zod';
+import { PERSISTENT_MIND_CHOSEN_NAME_TAG } from './persistentMindChosenName.js';
import { memoryIdSchema } from './memoryValidation.js';
// Use the existing durable tags column in both memory backends. No new store,
@@ -31,7 +32,8 @@ export function persistentMindMemoryTags(tags, protection) {
export function comparePersistentMindMemories(a, b) {
const rank = { 'core-identity': 2, important: 1, standard: 0 };
- return rank[persistentMindMemoryProtection(b)] - rank[persistentMindMemoryProtection(a)]
+ return Number(b.tags?.includes(PERSISTENT_MIND_CHOSEN_NAME_TAG) || false) - Number(a.tags?.includes(PERSISTENT_MIND_CHOSEN_NAME_TAG) || false)
+ || rank[persistentMindMemoryProtection(b)] - rank[persistentMindMemoryProtection(a)]
|| (b.importance ?? 0.5) - (a.importance ?? 0.5);
}
diff --git a/server/routes/cosMindRoutes.js b/server/routes/cosMindRoutes.js
index a3ed2e39af..f94d92e727 100644
--- a/server/routes/cosMindRoutes.js
+++ b/server/routes/cosMindRoutes.js
@@ -39,6 +39,7 @@ import {
preparePersistentMindContext,
promotePersistentMindMemory,
readPersistentMindMemories,
+ readPersistentMindName,
readPersistentMindRollups,
updatePersistentMindMemory,
} from '../services/persistentMindContext.js';
@@ -200,6 +201,7 @@ router.get('/mind', asyncHandler(async (req, res) => {
const { snapshot, ...publicHistory } = history;
res.json({
...publicHistory,
+ identity: { mindId: PERSISTENT_MIND_ID, name: await readPersistentMindName(PERSISTENT_MIND_ID) },
turnExecutions: publicPersistentMindTurnExecutions(snapshot),
state: publicPersistentMindState(state),
profile: {
diff --git a/server/routes/cosMindRoutes.test.js b/server/routes/cosMindRoutes.test.js
index 46d29a7553..5e1657351d 100644
--- a/server/routes/cosMindRoutes.test.js
+++ b/server/routes/cosMindRoutes.test.js
@@ -1,3 +1,4 @@
+import { resolvePersistentMindChosenName } from '../lib/persistentMindChosenName.js';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import express from 'express';
import { request } from '../lib/testHelper.js';
@@ -41,6 +42,7 @@ vi.mock('../services/persistentMindContext.js', () => ({
preparePersistentMindContext: mocks.preparePersistentMindContext,
promotePersistentMindMemory: mocks.promotePersistentMindMemory,
readPersistentMindMemories: mocks.readPersistentMindMemories,
+ readPersistentMindName: async () => resolvePersistentMindChosenName(await mocks.readPersistentMindMemories()),
readPersistentMindRollups: mocks.readPersistentMindRollups,
updatePersistentMindMemory: mocks.updatePersistentMindMemory,
}));
@@ -98,6 +100,19 @@ const post = (path, body) => request(app()).post(`/api/cos${path}`).send(body);
const put = (path, body) => request(app()).put(`/api/cos${path}`).send(body);
describe('persistent mind routes', () => {
+ it('projects the current protected name without changing trajectory identity or exposing memory records', async () => {
+ mocks.readPersistentMindMemories.mockResolvedValue([
+ { content: 'My chosen name is Earlier.', protection: 'core-identity' },
+ { content: 'Example Star', tags: ['mind:chosen-name', 'mind:core-identity'] },
+ ]);
+ const res = await get('/mind');
+ expect(res.status).toBe(200);
+ expect(res.body.identity).toEqual({ mindId: 'cos-persistent-mind', name: 'Example Star' });
+ expect(res.body.memories).toBeUndefined();
+ mocks.readPersistentMindMemories.mockResolvedValue([]);
+ expect((await get('/mind')).body.identity.name).toBeNull();
+ });
+
beforeEach(() => {
vi.clearAllMocks();
mocks.readPersistentMindEvents.mockResolvedValue({ events: [], cursor: null, gap: false, hasMore: false, snapshot: {} });
diff --git a/server/services/cosToolRegistry.js b/server/services/cosToolRegistry.js
index a28a17d146..391ebd606d 100644
--- a/server/services/cosToolRegistry.js
+++ b/server/services/cosToolRegistry.js
@@ -23,6 +23,7 @@ import {
eidoverseWorldSaySchema,
eidoverseChatReadSchema, eidoverseTravelVisitSchema, eidoverseVisitChatSchema, eidoverseVisitLeaveSchema,
} from '../lib/validation.js';
+import { persistentMindChooseNameSchema } from '../lib/persistentMindChosenName.js';
import { persistentMindProtectMemorySchema } from '../lib/persistentMindMemory.js';
import { persistentMindThinkingRequestSchema } from '../lib/persistentMindThinkingPresets.js';
import { USER_ACTION_ACTORS, USER_ACTION_TYPES } from '../lib/userActionTypes.js';
@@ -159,6 +160,19 @@ const mindProtectMemoryTool = Object.freeze({
adapter: { kind: 'persistent-mind-memory-protection' },
});
+const mindChooseNameTool = Object.freeze({
+ type: 'portos_tool', name: 'mind.choose-name', version: COS_TOOL_SCHEMA_VERSION,
+ providerName: 'mind_choose_name', aliases: ['mind_choose_name'],
+ description: 'Choose or change your own display name. Saves one protected machine-local identity memory; preserves your stable mindId and trajectory. The successful result is authoritative over older names.',
+ input_schema: zodToOpenApiSchema(persistentMindChooseNameSchema),
+ output_schema: objectOutputSchema,
+ policy: {
+ scopes: ['mind'], requiredCapabilities: ['manageMind'], sideEffect: 'write',
+ idempotent: true, async: false, confirmation: 'capability-grant',
+ },
+ adapter: { kind: 'persistent-mind-name' },
+});
+
// One mind turn must not be able to dump the whole ledger into context — the
// store's own list cap (500) is sized for the HTTP API, not a prompt.
export const USER_ACTIONS_QUERY_MAX_RESULTS = 100;
@@ -323,7 +337,7 @@ const localContextTools = (() => {
},
];
})();
-const toolCatalog = (intent) => [...thinkingTools, ...localContextTools, taskTool, mindCleanupTool, mindProtectMemoryTool, userActionsQueryTool, ...eidoverseTools, ...voiceTools(intent)];
+const toolCatalog = (intent) => [...thinkingTools, ...localContextTools, taskTool, mindCleanupTool, mindProtectMemoryTool, mindChooseNameTool, userActionsQueryTool, ...eidoverseTools, ...voiceTools(intent)];
const toolCalls = new Map();
const toolCallFingerprints = new Map();
@@ -438,7 +452,10 @@ const validateAuthority = (tool, authority) => {
};
const validateArguments = (tool, args) => {
- const schema = z.fromJSONSchema(tool.input_schema);
+ // JSON Schema does not carry JavaScript regexp flags; keep the Unicode
+ // naming contract on its original Zod schema at the execution boundary.
+ const schema = tool.adapter.kind === 'persistent-mind-name'
+ ? persistentMindChooseNameSchema : z.fromJSONSchema(tool.input_schema);
const parsed = schema.safeParse(args);
if (!parsed.success) {
throw new ServerError(`Invalid arguments for '${tool.name}': ${parsed.error.issues.map((issue) => `${issue.path.join('.')} ${issue.message}`).join('; ')}`, {
@@ -465,6 +482,10 @@ const executeAdapter = async (tool, args, context) => {
if (tool.adapter.kind === 'voice-tool') {
return dispatchTool(tool.adapter.legacyName, args, { sideEffects: [], signal: context.signal });
}
+ if (tool.adapter.kind === 'persistent-mind-name') {
+ const { choosePersistentMindName } = await import('./persistentMindContext.js');
+ return choosePersistentMindName(args);
+ }
if (tool.adapter.kind === 'persistent-mind-memory-protection') {
const { protectPersistentMindMemory } = await import('./persistentMindContext.js');
return protectPersistentMindMemory(args);
diff --git a/server/services/cosToolRegistry.test.js b/server/services/cosToolRegistry.test.js
index 3c9e7b8c54..25cf7de221 100644
--- a/server/services/cosToolRegistry.test.js
+++ b/server/services/cosToolRegistry.test.js
@@ -5,6 +5,7 @@ const mocks = vi.hoisted(() => ({
executeTasks: vi.fn(),
cleanupMind: vi.fn(),
protectMemory: vi.fn(),
+ chooseName: vi.fn(),
worldStatus: vi.fn(),
worldProject: vi.fn(),
worldAugment: vi.fn(),
@@ -47,7 +48,7 @@ vi.mock('./voice/tools.js', () => ({
vi.mock('./persistentMindTaskCapability.js', () => ({
executePersistentMindTaskRequests: (...args) => mocks.executeTasks(...args),
}));
-vi.mock('./persistentMindContext.js', () => ({ protectPersistentMindMemory: (...args) => mocks.protectMemory(...args) }));
+vi.mock('./persistentMindContext.js', () => ({ choosePersistentMindName: (...args) => mocks.chooseName(...args), protectPersistentMindMemory: (...args) => mocks.protectMemory(...args) }));
vi.mock('./persistentMindMaintenance.js', () => ({
cleanupPersistentMind: (...args) => mocks.cleanupMind(...args),
}));
@@ -83,6 +84,21 @@ beforeEach(() => {
});
describe('cosToolRegistry', () => {
+ it('allows only a bounded mind-owned naming action under manageMind and deduplicates retries', async () => {
+ const call = { requestId: 'name-1', name: 'mind.choose-name', arguments: { name: 'Example Star' } };
+ const authority = { scope: 'mind', capabilities: { manageMind: true } };
+ await expect(executeCosToolCall({ call, authority: { scope: 'mind', capabilities: { writePortos: true } } })).rejects.toMatchObject({ code: 'TOOL_CAPABILITY_DENIED' });
+ await expect(executeCosToolCall({ call, authority: { ...authority, scope: 'agent' } })).rejects.toMatchObject({ code: 'TOOL_SCOPE_DENIED' });
+ for (const args of [{ name: '' }, { name: 'x'.repeat(65) }, { name: 'Example', mindId: 'other' }, { name: 'Bad\nName' }]) {
+ await expect(executeCosToolCall({ call: { ...call, arguments: args }, authority })).rejects.toBeDefined();
+ }
+ mocks.chooseName.mockResolvedValue({ ok: true, success: true, name: 'Example Star', previousName: null });
+ const first = await executeCosToolCall({ call, authority });
+ expect(first).toMatchObject({ state: 'completed', result: { name: 'Example Star' } });
+ await executeCosToolCall({ call, authority });
+ expect(mocks.chooseName).toHaveBeenCalledTimes(1);
+ });
+
it('keeps local thinking authority separate and refuses raw configuration arguments', async () => {
const call = { requestId: 'thinking-1', name: 'mind.request-thinking-preset', arguments: { presetId: 'local', reason: 'Try a focused pass' } };
await expect(executeCosToolCall({ call, authority: { scope: 'mind', capabilities: { writePortos: true, createTasks: true } } })).rejects.toMatchObject({ code: 'TOOL_CAPABILITY_DENIED' });
@@ -101,6 +117,7 @@ describe('cosToolRegistry', () => {
'cos.create-task',
'mind.cleanup',
'mind.protect-memory',
+ 'mind.choose-name',
'user-actions.query',
'eidoverse.chat',
'eidoverse.destinations',
diff --git a/server/services/memorySync.db.test.js b/server/services/memorySync.db.test.js
index 8e34b1cfeb..93c02bf14e 100644
--- a/server/services/memorySync.db.test.js
+++ b/server/services/memorySync.db.test.js
@@ -89,6 +89,20 @@ describe.skipIf(!runDb)('memorySync.applyRemoteChanges', () => {
await close();
});
+ it('keeps chosen identity local through outbound and incoming federation, including id collisions', async () => {
+ await memorySync.applyRemoteChanges([remoteMemory(ID_A, '2026-01-02T00:00:00.000Z')]);
+ await query(`UPDATE memories SET source_agent_id = $1, content = $2, tags = $3 WHERE id = $4`, ['cos-persistent-mind', 'Example Star', ['mind:chosen-name', 'mind:core-identity'], ID_A]);
+ expect((await memorySync.getChangesSince()).memories).toEqual([]);
+ const result = await memorySync.applyRemoteChanges([
+ remoteMemory(ID_A, '2026-01-03T00:00:00.000Z'),
+ remoteMemory(ID_B, '2026-01-03T00:00:00.000Z', { sourceAgentId: 'cos-persistent-mind' }),
+ remoteMemory('00000000-0000-4000-8000-00000000cccc', '2026-01-03T00:00:00.000Z', { tags: ['mind:chosen-name'] }),
+ ]);
+ expect(result).toEqual({ inserted: 0, updated: 0, skipped: 3 });
+ expect(await contentOf(ID_A)).toBe('Example Star');
+ expect(await contentOf(ID_B)).toBeNull();
+ });
+
it('applies a duplicated id instead of aborting the whole transaction', async () => {
// Regression: a peer payload repeating one id made the batched multi-row
// upsert throw "ON CONFLICT DO UPDATE command cannot affect row a second
diff --git a/server/services/memorySync.js b/server/services/memorySync.js
index 62b8412eca..29d5bd1e78 100644
--- a/server/services/memorySync.js
+++ b/server/services/memorySync.js
@@ -17,6 +17,8 @@
*/
import { query, withTransaction, arrayToPgvector, pgvectorToArray } from '../lib/db.js';
+import { PERSISTENT_MIND_ID } from '../lib/persistentMindTrajectory.js';
+import { PERSISTENT_MIND_CHOSEN_NAME_TAG } from '../lib/persistentMindChosenName.js';
import { dedupeByKey } from '../lib/arrayUtils.js';
/**
@@ -37,9 +39,11 @@ export async function getChangesSince(sinceSequence = '0', limit = 100) {
origin_instance_id
FROM memories
WHERE sync_sequence > $1
+ AND source_agent_id IS DISTINCT FROM $3
+ AND NOT ($4 = ANY(COALESCE(tags, '{}'::text[])))
ORDER BY sync_sequence ASC
LIMIT $2`,
- [sinceSequence, limit + 1]
+ [sinceSequence, limit + 1, PERSISTENT_MIND_ID, PERSISTENT_MIND_CHOSEN_NAME_TAG]
);
const hasMore = result.rows.length > limit;
@@ -114,7 +118,8 @@ export async function applyRemoteChanges(incomingMemories) {
return Number.isNaN(at) ? -Infinity : at;
};
const deduped = dedupeByKey(
- incomingMemories,
+ incomingMemories.filter((mem) => mem.sourceAgentId !== PERSISTENT_MIND_ID
+ && !mem.tags?.includes(PERSISTENT_MIND_CHOSEN_NAME_TAG)),
(mem) => mem.id,
(held, next) => (lwwClock(held) >= lwwClock(next) ? held : next),
);
@@ -143,6 +148,9 @@ export async function applyRemoteChanges(incomingMemories) {
);
});
+ params.push(PERSISTENT_MIND_ID, PERSISTENT_MIND_CHOSEN_NAME_TAG);
+ const localMindParam = params.length - 1;
+ const nameTagParam = params.length;
// access_count and last_accessed are instance-local, not synced
const result = await client.query(
`INSERT INTO memories (
@@ -162,6 +170,8 @@ export async function applyRemoteChanges(incomingMemories) {
source_app_id = EXCLUDED.source_app_id,
origin_instance_id = EXCLUDED.origin_instance_id
WHERE EXCLUDED.updated_at > memories.updated_at
+ AND memories.source_agent_id IS DISTINCT FROM $${localMindParam}
+ AND NOT ($${nameTagParam} = ANY(COALESCE(memories.tags, '{}'::text[])))
RETURNING (xmax = 0) AS is_insert`,
params
);
diff --git a/server/services/persistentMindAdapter.js b/server/services/persistentMindAdapter.js
index de9564a302..3e7f2cae7f 100644
--- a/server/services/persistentMindAdapter.js
+++ b/server/services/persistentMindAdapter.js
@@ -8,6 +8,7 @@
* the configured model is the user's explicit inference choice.
*/
+import { persistentMindNamePrompt, persistentMindChosenNameSchema } from '../lib/persistentMindChosenName.js';
import { persistentMindMemoryProtectionSchema } from '../lib/persistentMindMemory.js';
import { z } from 'zod';
import {
@@ -25,6 +26,7 @@ import { loadState } from './cosState.js';
import {
createPersistentMindMemoryFromCandidate,
readPersistentMindMemories,
+ readPersistentMindName,
} from './persistentMindContext.js';
import { normalizePersistentMindPrompt } from '../lib/persistentMindPrompt.js';
import { composePersistentMindInstructions, normalizePersistentMindPlaybook } from '../lib/persistentMindPlaybook.js';
@@ -126,7 +128,10 @@ const executeMindToolCalls = async ({ calls, turnId, wake, signal, capabilities,
kind: 'result',
id: `tool-result:${requestId}`,
data: {
- displayText: `${candidate.name} ${result.state}`,
+ displayText: ['mind.choose-name', 'mind_choose_name'].includes(candidate.name)
+ && result.state === 'completed' && persistentMindChosenNameSchema.safeParse(result.result?.name).success
+ ? `Chosen display name: ${result.result.name}`
+ : `${candidate.name} ${result.state}`,
tool: candidate.name,
success: result.state === 'completed',
},
@@ -414,7 +419,7 @@ export function createPersistentMindTurnAdapter() {
// model earned by asking for tools. Each is admitted on its own.
result = await callBoundary(
{ purpose: round === 0 ? 'turn' : 'tool-round', round },
- ({ reportRunId }) => runPinnedPrompt({
+ async ({ reportRunId }) => runPinnedPrompt({
provider,
model,
effort,
@@ -422,7 +427,7 @@ export function createPersistentMindTurnAdapter() {
heartbeat,
screenshots,
reportRunId,
- prompt: providerPrompt,
+ prompt: `${providerPrompt}\n\n# Current naming identity\n${persistentMindNamePrompt(await readPersistentMindName(PERSISTENT_MIND_ID), { canChoose: taskAccess.manageMind })}`,
responseSchema: persistentMindResponseSchema,
}),
);
diff --git a/server/services/persistentMindAdapter.test.js b/server/services/persistentMindAdapter.test.js
index bc640dbe37..ee00604f0a 100644
--- a/server/services/persistentMindAdapter.test.js
+++ b/server/services/persistentMindAdapter.test.js
@@ -1,3 +1,4 @@
+import { resolvePersistentMindChosenName } from '../lib/persistentMindChosenName.js';
import { beforeEach, describe, expect, it, vi } from 'vitest';
const mock = vi.hoisted(() => ({
@@ -27,6 +28,7 @@ vi.mock('../lib/fileUtils.js', async (importOriginal) => ({
vi.mock('./persistentMindContext.js', () => ({
createPersistentMindMemoryFromCandidate: (...args) => mock.createPersistentMindMemoryFromCandidate(...args),
readPersistentMindMemories: vi.fn(async () => mock.memories),
+ readPersistentMindName: vi.fn(async () => resolvePersistentMindChosenName(mock.memories)),
}));
vi.mock('./promptRunner.js', () => ({
runPromptThroughProvider: (...args) => mock.runPrompt(...args),
@@ -62,6 +64,7 @@ const profile = { provider: { id: 'example-api', type: 'api' }, model: 'example-
beforeEach(() => {
vi.clearAllMocks();
+ mock.memories = [{ id: 'memory-1', type: 'fact', content: 'A durable fact.', sourceAgentId: 'cos-persistent-mind', status: 'active' }];
mock.root.config.persistentMindCapabilities = { createTasks: true };
mock.readTaskCatalog.mockResolvedValue({ apps: [{ id: 'portos' }], providers: [{ id: 'codex' }] });
mock.readTaskInventory.mockResolvedValue([]);
@@ -78,6 +81,33 @@ beforeEach(() => {
}) });
});
+describe('naming on authorized turns', () => {
+ it('asks unnamed minds to choose and refreshes identity after a successful semantic action', async () => {
+ mock.root.config.persistentMindCapabilities = { manageMind: true };
+ mock.runPrompt.mockResolvedValueOnce({ text: JSON.stringify({ message: '', toolCalls: [{ requestId: 'choose', name: 'mind.choose-name', arguments: { name: 'Example Star' } }] }) });
+ mock.executeToolCall.mockImplementationOnce(async () => {
+ mock.memories = [{ content: 'Example Star', tags: ['mind:chosen-name', 'mind:core-identity'] }];
+ return { state: 'completed', result: { success: true, name: 'Example Star' } };
+ });
+ const recordCapabilityEvent = vi.fn();
+ await createPersistentMindTurnAdapter().run({ ...profile, turnId: 'name-turn', wake: { kind: 'self' }, context: { text: 'Continuity' }, recordCapabilityEvent });
+ expect(mock.runPrompt.mock.calls[0][0].prompt).toContain('Choose a name for yourself on this normally authorized wake using mind.choose-name');
+ expect(mock.runPrompt.mock.calls[1][0].prompt).toContain('Current chosen display name: "Example Star"');
+ expect(mock.runPrompt.mock.calls[1][0].prompt).not.toContain('You have no chosen name yet');
+ expect(recordCapabilityEvent).toHaveBeenCalledWith(expect.objectContaining({ kind: 'result', data: expect.objectContaining({ tool: 'mind.choose-name', success: true, displayText: 'Chosen display name: Example Star' }) }));
+ });
+
+ it('preserves an existing conversational choice and offers unnamed minds the existing protected-memory path without granting tools', async () => {
+ mock.memories = [{ content: 'My chosen name is Example.', protection: 'core-identity' }];
+ await createPersistentMindTurnAdapter().run({ ...profile, turnId: 'named-turn', wake: { kind: 'self' }, context: { text: '' } });
+ expect(mock.runPrompt.mock.calls[0][0].prompt).toContain('Current chosen display name: "Example"');
+ expect(mock.runPrompt.mock.calls[0][0].prompt).not.toContain('You have no chosen name yet');
+ mock.memories = [];
+ await createPersistentMindTurnAdapter().run({ ...profile, turnId: 'unnamed-turn', wake: { kind: 'self' }, context: { text: '' } });
+ expect(mock.runPrompt.mock.calls[1][0].prompt).toContain('as a core-identity memory');
+ });
+});
+
describe('persistent mind adapter', () => {
it.each([
'OpenAI Codex v1\nuser\n{"message":"example"}',
diff --git a/server/services/persistentMindContext.js b/server/services/persistentMindContext.js
index 962a78aca2..924f7d5647 100644
--- a/server/services/persistentMindContext.js
+++ b/server/services/persistentMindContext.js
@@ -29,6 +29,7 @@ import {
appendMindEvent,
readPersistentMindHistory,
} from './agentRunEventLog.js';
+import { PERSISTENT_MIND_CHOSEN_NAME_TAG, persistentMindChooseNameSchema, resolvePersistentMindChosenName } from '../lib/persistentMindChosenName.js';
import * as memoryBackend from './memoryBackend.js';
import {
PERSISTENT_MIND_MEMORY_PROTECTION_TAGS,
@@ -84,6 +85,7 @@ export async function readPersistentMindMemories(mindId = PERSISTENT_MIND_ID) {
// outside the first page of ordinary memories before we get to sort it.
const pages = await Promise.all([
memoryBackend.getMemories(options),
+ memoryBackend.getMemories({ ...options, tags: [PERSISTENT_MIND_CHOSEN_NAME_TAG] }),
...Object.values(PERSISTENT_MIND_MEMORY_PROTECTION_TAGS).map((tag) => memoryBackend.getMemories({ ...options, tags: [tag] })),
]);
const candidates = [...new Map(pages.flatMap((page) => page.memories || []).map((memory) => [memory.id, memory])).values()];
@@ -92,6 +94,20 @@ export async function readPersistentMindMemories(mindId = PERSISTENT_MIND_ID) {
.sort(comparePersistentMindMemories).slice(0, 100).map(projectPersistentMindMemory);
}
+/** Named installs need only one record for frequent page/turn identity refreshes. */
+export async function readPersistentMindName(mindId = PERSISTENT_MIND_ID) {
+ const { memories = [] } = await memoryBackend.getMemories({
+ status: 'active', sourceAgentId: mindId, tags: [PERSISTENT_MIND_CHOSEN_NAME_TAG],
+ sortBy: 'updatedAt', sortOrder: 'desc', limit: 1,
+ });
+ const memory = memories[0] ? await memoryBackend.peekMemory(memories[0].id) : null;
+ if (memory?.sourceAgentId === mindId && memory.status === 'active') {
+ const name = resolvePersistentMindChosenName([memory]);
+ if (name) return name;
+ }
+ return resolvePersistentMindChosenName(await readPersistentMindMemories(mindId));
+}
+
/** Bulk cleanup never archives protected memories, regardless of its caller. */
export function archivePersistentMindMemories(mindId = PERSISTENT_MIND_ID) {
return queueMemoryWrite(async () => {
@@ -279,9 +295,12 @@ export async function preparePersistentMindContext({
}
}
+ const chosenName = resolvePersistentMindChosenName(memories);
return assemblePersistentMindContext({
mindId,
- identity,
+ identity: [chosenName
+ ? `Current chosen display name: ${JSON.stringify(chosenName)}. This supersedes older name memories; mindId and trajectory remain unchanged.`
+ : 'No chosen display name yet.', identity].filter(Boolean).join('\n'),
instructions,
memories,
events: history,
@@ -293,6 +312,27 @@ export async function preparePersistentMindContext({
});
}
+/** One protected record is the current name; older identity prose remains history. */
+export function choosePersistentMindName(input, mindId = PERSISTENT_MIND_ID) {
+ const { name } = persistentMindChooseNameSchema.parse(input);
+ return queueMemoryWrite(async () => {
+ const memories = await readPersistentMindMemories(mindId);
+ const previousName = resolvePersistentMindChosenName(memories);
+ const existing = memories.find((memory) => memory.tags?.includes(PERSISTENT_MIND_CHOSEN_NAME_TAG));
+ const fields = {
+ content: name,
+ summary: `Current chosen display name: ${name}`,
+ tags: persistentMindMemoryTags([PERSISTENT_MIND_CHOSEN_NAME_TAG, 'name'], 'core-identity'),
+ importance: 1,
+ };
+ const memory = existing
+ ? await memoryBackend.updateMemory(existing.id, fields)
+ : await memoryBackend.createMemory({ ...fields, type: 'fact', category: 'preferences', sourceAgentId: mindId, status: 'active' });
+ if (!memory) throw new Error('Chosen name could not be saved');
+ return { ok: true, success: true, name, previousName, mindId, memoryId: memory.id };
+ });
+}
+
export function createPersistentMindMemory({ mindId = PERSISTENT_MIND_ID, protection = 'standard', ...input } = {}) {
return queueMemoryWrite(async () => projectPersistentMindMemory(await memoryBackend.createMemory({
...input,
diff --git a/server/services/persistentMindContext.test.js b/server/services/persistentMindContext.test.js
index 9ff584bbb3..febb5cd49b 100644
--- a/server/services/persistentMindContext.test.js
+++ b/server/services/persistentMindContext.test.js
@@ -39,6 +39,7 @@ const {
clearPersistentMindRollups,
createPersistentMindMemoryFromCandidate,
createPersistentMindMemory,
+ choosePersistentMindName,
readPersistentMindMemories,
updatePersistentMindMemory,
protectPersistentMindMemory,
@@ -78,6 +79,37 @@ beforeEach(() => {
afterAll(() => rmSync(CONTEXT_DIR, { recursive: true, force: true }));
+describe('chosen identity continuity', () => {
+ it('selects and later renames one protected record across reload, cleanup and provider changes', async () => {
+ const records = new Map();
+ mock.memoryApi.getMemories.mockImplementation(async ({ offset = 0 }) => ({ memories: [...records.values()].filter((m) => m.status === 'active').slice(offset, offset + 100) }));
+ mock.memoryApi.peekMemory.mockImplementation(async (id) => records.get(id));
+ mock.memoryApi.createMemory.mockImplementationOnce(async (input) => {
+ const memory = { id: 'chosen-identity', ...input };
+ records.set(memory.id, memory);
+ return memory;
+ });
+ mock.memoryApi.updateMemory.mockImplementation(async (id, updates) => {
+ const memory = { ...records.get(id), ...updates };
+ records.set(id, memory);
+ return memory;
+ });
+ expect(await choosePersistentMindName({ name: 'Example Star' })).toMatchObject({ name: 'Example Star', previousName: null, mindId: 'cos-persistent-mind' });
+ records.set('legacy', { id: 'legacy', content: 'My chosen name is Earlier.', tags: ['mind:core-identity'], sourceAgentId: 'cos-persistent-mind', status: 'active' });
+ vi.resetModules();
+ const reloaded = await import('./persistentMindContext.js');
+ expect(await reloaded.choosePersistentMindName({ name: 'Étoile' })).toMatchObject({ name: 'Étoile', previousName: 'Example Star', memoryId: 'chosen-identity' });
+ expect(records.size).toBe(2);
+ expect(await reloaded.readPersistentMindName()).toBe('Étoile');
+ expect(await reloaded.archivePersistentMindMemories()).toEqual({ archived: 0, preserved: 2 });
+ await reloaded.clearPersistentMindRollups();
+ const context = await reloaded.preparePersistentMindContext({ memories: await reloaded.readPersistentMindMemories(), providerId: 'other-provider', model: 'other-model' });
+ expect(context.text).toContain('Current chosen display name: "Étoile"');
+ expect(context.text).toContain('mindId=cos-persistent-mind');
+ expect(mock.appendMindEvent).not.toHaveBeenCalled();
+ });
+});
+
describe('persistent mind rollups', () => {
it('records source and model provenance and assembles it within the budget', async () => {
mock.history = [event(1), event(2, 'mind.wake'), event(3, 'mind.turn.completed')];