Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: let persistent mind save its own memories
[._.]/ Adam Eivy82f3d0ac3597
diff --git a/client/src/components/cos/PersistentMindContextPanel.jsx b/client/src/components/cos/PersistentMindContextPanel.jsxindex 5c89d2ad8b..49d7228f09 100644--- a/client/src/components/cos/PersistentMindContextPanel.jsx+++ b/client/src/components/cos/PersistentMindContextPanel.jsx@@ -71,7 +71,7 @@ export default function PersistentMindContextPanel() {{[['1 · Observe', 'Messages, annotations, and scheduled self-wakes enter one FIFO stream.'],['2 · Assemble', 'Identity, instructions, curated memories, rollups, and recent events fill a bounded context.'],- ['3 · Think', 'The exact pinned provider returns a visible working note, reply, memory proposals, and optional follow-up.'],+ ['3 · Think', 'The exact pinned provider returns a visible working note, reply, durable memories, and optional follow-up.'],['4 · Persist', 'The append-only trajectory becomes the source for chat, inspection, replay, and later context.'],].map(([title, body]) => (<div key={title} className="rounded border border-port-border bg-port-bg/40 p-3">@@ -113,7 +113,7 @@ export default function PersistentMindContextPanel() {<section className="rounded border border-port-border bg-port-card p-4" aria-labelledby="mind-memory-heading"><div><h3 id="mind-memory-heading" className="flex items-center gap-2 text-sm font-semibold text-port-text"><Database size={16} aria-hidden="true" /> Curated memories</h3>- <p className="mt-1 text-xs text-port-text-muted">Only memories explicitly promoted or added here enter the mind context. Model proposals stay in the conversation until you promote them.</p>+ <p className="mt-1 text-xs text-port-text-muted">Memories created by the persistent mind and memories added here enter its bounded context automatically. You can edit them here at any time.</p></div><MemoryCreator onCreated={load} /><div className="mt-3 space-y-2">diff --git a/client/src/components/cos/tabs/MindTab.jsx b/client/src/components/cos/tabs/MindTab.jsxindex 5da31be37d..76436e3bfa 100644--- a/client/src/components/cos/tabs/MindTab.jsx+++ b/client/src/components/cos/tabs/MindTab.jsx@@ -38,6 +38,8 @@ const EVENT_LABELS = {'mind.thought': 'Working note','mind.reply': 'Chief of Staff','mind.memory.candidate': 'Memory proposal',+ 'mind.memory.created': 'Memory created',+ 'mind.memory.failed': 'Memory save failed','mind.capability.request': 'Action request','mind.capability.result': 'Action outcome','mind.memory.promoted': 'Memory promoted',diff --git a/server/lib/persistentMindTrajectory.js b/server/lib/persistentMindTrajectory.jsindex e681d31513..3e43f04cc9 100644--- a/server/lib/persistentMindTrajectory.js+++ b/server/lib/persistentMindTrajectory.js@@ -22,6 +22,8 @@ export const PERSISTENT_MIND_EVENT_KINDS = Object.freeze(['mind.thought','mind.reply','mind.memory.candidate',+ 'mind.memory.created',+ 'mind.memory.failed','mind.capability.request','mind.capability.result','mind.summary',diff --git a/server/services/persistentMindAdapter.js b/server/services/persistentMindAdapter.jsindex 782c767aea..30052b95aa 100644--- a/server/services/persistentMindAdapter.js+++ b/server/services/persistentMindAdapter.js@@ -17,7 +17,10 @@ import {import { PERSISTENT_MIND_ID } from '../lib/persistentMindTrajectory.js';import { parseLLMJSON } from '../lib/llmText.js';import { loadState } from './cosState.js';-import { readPersistentMindMemories } from './persistentMindContext.js';+import {+ createPersistentMindMemoryFromCandidate,+ readPersistentMindMemories,+} from './persistentMindContext.js';import { normalizePersistentMindPrompt } from '../lib/persistentMindPrompt.js';import { runPromptThroughProvider } from './promptRunner.js';import { stopRun } from './runner.js';@@ -105,11 +108,11 @@ Return ONLY one JSON object with this shape:{"thinkingSummary": "A concise, user-visible working note explaining what you considered and why. Do not reveal hidden chain-of-thought.","message": "The conversational reply. Required for a human message; optional for a self-directed wake.",- "memoryCandidates": [{ "content": "A durable fact worth proposing", "summary": "Short label", "type": "fact", "category": "other", "tags": ["optional"] }],+ "memoryCandidates": [{ "content": "A durable fact worth remembering", "summary": "Short label", "type": "fact", "category": "other", "tags": ["optional"] }],"taskRequests": [{ "description": "Concise queue label", "prompt": "Complete instructions for the agent", "priority": "MEDIUM", "appId": "configured-app-id", "providerId": "configured-provider-id", "model": "configured-model-id-or-empty-for-default", "effort": "high", "prCompletion": "review-then-merge" }],"selfWake": { "reason": "Why another wake would be useful", "delayMinutes": 60 }}-Use empty arrays when there is no durable memory candidate or task request, and null when no earlier follow-up is needed. Memory candidates are proposals only; a human decides whether to promote them. Typed CoS task creation is the only action capability in this lane and is available only when the capability section says ON. This lane still cannot mutate files directly, call arbitrary tools, contact people, or perform other external actions.`;+Use empty arrays when there is no durable memory candidate or task request, and null when no earlier follow-up is needed. Memory candidates are durable memories to save automatically; only include information that is worth retaining. Typed CoS task creation is the only action capability in this lane and is available only when the capability section says ON. This lane still cannot mutate files directly, call arbitrary tools, contact people, or perform other external actions.`;}const summaryEventLines = (events) => (Array.isArray(events) ? events : []).map((event) => {@@ -220,6 +223,13 @@ export function createPersistentMindTurnAdapter() {signal,recordCapabilityEvent,});+ const memoryWrites = await Promise.allSettled(parsed.memoryCandidates.map((candidate, index) => (+ createPersistentMindMemoryFromCandidate({+ ...candidate,+ candidateId: `${turnId}:${index}`,+ turnId,+ })+ )));const events = [];if (parsed.thinkingSummary) {events.push({@@ -235,11 +245,28 @@ export function createPersistentMindTurnAdapter() {data: { displayText: message, replyToMessageId: wake?.message?.id || null },});}- parsed.memoryCandidates.forEach((candidate, index) => events.push({- kind: 'mind.memory.candidate',- id: `memory-candidate:${turnId}:${index}`,- data: { ...candidate, displayText: candidate.content },- }));+ memoryWrites.forEach((result, index) => {+ const candidate = parsed.memoryCandidates[index];+ if (result.status === 'fulfilled') {+ events.push({+ kind: 'mind.memory.created',+ id: `memory-created:${turnId}:${index}`,+ data: {+ ...candidate,+ memoryId: result.value.memory.id,+ duplicate: result.value.duplicate,+ displayText: candidate.content,+ },+ });+ } else {+ console.error(`❌ Persistent mind memory write failed for turn ${turnId}: ${result.reason?.message || 'unknown error'}`);+ events.push({+ kind: 'mind.memory.failed',+ id: `memory-failed:${turnId}:${index}`,+ data: { displayText: 'The persistent mind could not save this memory automatically.' },+ });+ }+ });return {output: result.text,events,diff --git a/server/services/persistentMindAdapter.test.js b/server/services/persistentMindAdapter.test.jsindex 83a7620757..57eebecfb7 100644--- a/server/services/persistentMindAdapter.test.js+++ b/server/services/persistentMindAdapter.test.js@@ -7,10 +7,18 @@ const mock = vi.hoisted(() => ({stopRun: vi.fn(),readTaskCatalog: vi.fn(),executeTaskRequests: vi.fn(),+ createPersistentMindMemoryFromCandidate: vi.fn(async ({ candidateId, ...candidate }) => ({+ success: true,+ duplicate: false,+ memory: { id: `memory-${candidateId}`, ...candidate },+ })),}));vi.mock('./cosState.js', () => ({ loadState: vi.fn(async () => mock.root) }));-vi.mock('./persistentMindContext.js', () => ({ readPersistentMindMemories: vi.fn(async () => mock.memories) }));+vi.mock('./persistentMindContext.js', () => ({+ createPersistentMindMemoryFromCandidate: (...args) => mock.createPersistentMindMemoryFromCandidate(...args),+ readPersistentMindMemories: vi.fn(async () => mock.memories),+}));vi.mock('./promptRunner.js', () => ({ runPromptThroughProvider: (...args) => mock.runPrompt(...args) }));vi.mock('./runner.js', () => ({ stopRun: (...args) => mock.stopRun(...args) }));vi.mock('./persistentMindTaskCapability.js', () => ({@@ -68,8 +76,12 @@ describe('persistent mind adapter', () => {}));expect(heartbeat).toHaveBeenCalled();expect(result.events.map((event) => event.kind)).toEqual([- 'mind.thought', 'mind.reply', 'mind.memory.candidate',+ 'mind.thought', 'mind.reply', 'mind.memory.created',]);+ expect(mock.createPersistentMindMemoryFromCandidate).toHaveBeenCalledWith({+ content: 'Remember this.', type: 'fact', category: 'other', tags: [], summary: '',+ candidateId: 'turn-1:0', turnId: 'turn-1',+ });expect(mock.runPrompt.mock.calls[0][0].prompt).toContain('Task access: ON');});diff --git a/server/services/persistentMindContext.js b/server/services/persistentMindContext.jsindex 06930aa113..9a266a074e 100644--- a/server/services/persistentMindContext.js+++ b/server/services/persistentMindContext.js@@ -34,6 +34,7 @@ const ROLLUP_PATH = join(PATHS.cos, 'persistent-mind-rollups.json');const ROLLUP_STORE_SCHEMA_VERSION = 1;const queueRollupWrite = createFileWriteQueue();const promotionRuns = new Map();+const memoryCreationRuns = new Map();const emptyStore = () => ({ schemaVersion: ROLLUP_STORE_SCHEMA_VERSION, rollups: [] });@@ -230,6 +231,70 @@ export function createPersistentMindMemory({ mindId = PERSISTENT_MIND_ID, ...inp});}+async function findExistingAutomaticMemory({ memoryApi, mindId, turnId, content }) {+ const result = await memoryApi.getMemories({+ status: 'active',+ sourceAgentId: mindId,+ limit: 1000,+ });+ const candidates = result.memories || [];+ for (const candidate of candidates) {+ const memory = await memoryApi.peekMemory(candidate.id);+ if (memory?.sourceTaskId === turnId && memory.content === content) return memory;+ }+ return null;+}++async function performAutomaticMemoryCreation({+ candidateId,+ mindId = PERSISTENT_MIND_ID,+ turnId = null,+ content,+ summary,+ type = 'observation',+ category = 'other',+ tags = [],+ memoryApi = memoryBackend,+} = {}) {+ if (typeof candidateId !== 'string' || !candidateId.trim()) {+ throw new Error('Persistent mind memory candidate id is required');+ }+ if (typeof content !== 'string' || !content.trim()) {+ throw new Error('Persistent mind memory content is required');+ }+ const id = candidateId.trim();+ const normalizedContent = content.trim().slice(0, 10_240);+ const history = await readPersistentMindHistory(mindId);+ const previous = history.find((event) => (+ event.kind === 'mind.memory.created' && event.data?.candidateId === id+ ));+ if (previous?.data?.memoryId) {+ return { success: true, duplicate: true, memory: { id: previous.data.memoryId } };+ }++ const existing = await findExistingAutomaticMemory({ memoryApi, mindId, turnId, content: normalizedContent });+ const memory = existing || await memoryApi.createMemory({+ type,+ content: normalizedContent,+ summary: typeof summary === 'string' ? summary.trim().slice(0, 500) : undefined,+ category,+ tags: [...new Set(Array.isArray(tags) ? tags.filter((tag) => typeof tag === 'string' && tag) : [])].slice(0, 20),+ sourceTaskId: turnId,+ sourceAgentId: mindId,+ status: 'active',+ });+ return { success: true, duplicate: Boolean(existing), memory };+}++/** Persist a structured memory emitted by the mind without a human approval step. */+export function createPersistentMindMemoryFromCandidate(input = {}) {+ const key = `${input.mindId || PERSISTENT_MIND_ID}:${input.candidateId || ''}`;+ if (memoryCreationRuns.has(key)) return memoryCreationRuns.get(key);+ const run = performAutomaticMemoryCreation(input).finally(() => memoryCreationRuns.delete(key));+ memoryCreationRuns.set(key, run);+ return run;+}+export async function updatePersistentMindMemory(memoryId, updates, mindId = PERSISTENT_MIND_ID) {const existing = await memoryBackend.peekMemory(memoryId);if (!existing || existing.sourceAgentId !== mindId) return null;diff --git a/server/services/persistentMindContext.test.js b/server/services/persistentMindContext.test.jsindex 6b36d79a0e..b84f5fb1e7 100644--- a/server/services/persistentMindContext.test.js+++ b/server/services/persistentMindContext.test.js@@ -6,6 +6,11 @@ import { join } from 'path';const mock = vi.hoisted(() => ({history: [],appendMindEvent: vi.fn(async (event) => ({ appended: true, event })),+ memoryApi: {+ getMemories: vi.fn(async () => ({ memories: [] })),+ peekMemory: vi.fn(),+ createMemory: vi.fn(async (input) => ({ id: 'memory-automatic-1', ...input })),+ },}));const { CONTEXT_DIR } = await vi.hoisted(async () => {@@ -24,9 +29,11 @@ vi.mock('./agentRunEventLog.js', () => ({appendMindEvent: (...args) => mock.appendMindEvent(...args),readPersistentMindHistory: vi.fn(async () => mock.history),}));+vi.mock('./memoryBackend.js', () => mock.memoryApi);const {appendPersistentMindAnnotation,+ createPersistentMindMemoryFromCandidate,preparePersistentMindContext,promotePersistentMindMemory,readPersistentMindRollups,@@ -53,6 +60,9 @@ beforeEach(() => {mkdirSync(CONTEXT_DIR, { recursive: true });mock.history = [];mock.appendMindEvent.mockClear();+ mock.memoryApi.getMemories.mockClear();+ mock.memoryApi.peekMemory.mockClear();+ mock.memoryApi.createMemory.mockClear();});afterAll(() => rmSync(CONTEXT_DIR, { recursive: true, force: true }));@@ -222,6 +232,31 @@ describe('persistent mind rollups', () => {});describe('trajectory annotations and Brain promotion', () => {+ it('automatically creates a mind-owned memory without approval', async () => {+ const created = await createPersistentMindMemoryFromCandidate({+ candidateId: 'turn-automatic:0',+ turnId: 'turn-automatic',+ content: 'Remember this automatically created fact.',+ summary: 'Automatic fact',+ type: 'fact',+ category: 'other',+ tags: ['durable', 'durable'],+ memoryApi: mock.memoryApi,+ });++ expect(created).toMatchObject({ success: true, duplicate: false, memory: { id: 'memory-automatic-1', status: 'active' } });+ expect(mock.memoryApi.createMemory).toHaveBeenCalledWith({+ content: 'Remember this automatically created fact.',+ summary: 'Automatic fact',+ type: 'fact',+ category: 'other',+ tags: ['durable'],+ sourceTaskId: 'turn-automatic',+ sourceAgentId: 'cos-persistent-mind',+ status: 'active',+ });+ });+it('keeps comments attributable to their turn and target event', async () => {await expect(appendPersistentMindAnnotation({id: 'annotation-1',