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: add replayable persistent mind context (#5065)
[._.]/ Adam Eivy239d89646f25
diff --git a/scripts/migrations/298-persistent-mind-runtime-state.test.js b/scripts/migrations/298-persistent-mind-runtime-state.test.jsindex 4e63176e21..7afac729c9 100644--- a/scripts/migrations/298-persistent-mind-runtime-state.test.js+++ b/scripts/migrations/298-persistent-mind-runtime-state.test.js@@ -29,7 +29,7 @@ describe('migration 298 — persistent mind runtime state', () => {running: true,config: { alwaysOn: true },agents: { a1: { status: 'completed' } },- persistentMind: { schemaVersion: 1, enabled: false, started: false, status: 'disabled' },+ persistentMind: { schemaVersion: 2, mindId: 'cos-persistent-mind', enabled: false, started: false, status: 'disabled' },});});diff --git a/scripts/migrations/299-persistent-mind-identity.js b/scripts/migrations/299-persistent-mind-identity.jsnew file mode 100644index 0000000000..c6a64404fa--- /dev/null+++ b/scripts/migrations/299-persistent-mind-identity.js@@ -0,0 +1,44 @@+/** Give every existing persistent-mind runtime slice its stable trajectory id. */++import { readFile } from 'fs/promises';+import { join } from 'path';+import { PERSISTENT_MIND_SCHEMA_VERSION } from '../../server/lib/persistentMind.js';+import { PERSISTENT_MIND_ID } from '../../server/lib/persistentMindTrajectory.js';+import { atomicWrite } from '../../server/lib/fileUtils.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' };+ }+ const existing = state?.persistentMind;+ if (!existing || typeof existing !== 'object' || Array.isArray(existing)) {+ return { updated: 0, reason: 'no-persistent-mind' };+ }+ if (existing.mindId === PERSISTENT_MIND_ID+ && existing.schemaVersion === PERSISTENT_MIND_SCHEMA_VERSION) {+ return { updated: 0, reason: 'already-applied' };+ }++ state.persistentMind = {+ ...existing,+ schemaVersion: PERSISTENT_MIND_SCHEMA_VERSION,+ mindId: typeof existing.mindId === 'string' && existing.mindId.trim()+ ? existing.mindId.trim().slice(0, 128)+ : PERSISTENT_MIND_ID,+ };+ await atomicWrite(statePath, state);+ console.log('🧠 migration 299: added stable persistent mind trajectory identity');+ return { updated: 1 };+ },+};diff --git a/scripts/migrations/299-persistent-mind-identity.test.js b/scripts/migrations/299-persistent-mind-identity.test.jsnew file mode 100644index 0000000000..484b2358f9--- /dev/null+++ b/scripts/migrations/299-persistent-mind-identity.test.js@@ -0,0 +1,51 @@+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 './299-persistent-mind-identity.js';++const readJson = (path) => JSON.parse(readFileSync(path, 'utf8'));++describe('migration 299 — persistent mind identity', () => {+ let rootDir;+ let statePath;++ beforeEach(() => {+ rootDir = mkdtempSync(join(tmpdir(), 'migration-299-persistent-mind-'));+ mkdirSync(join(rootDir, 'data', 'cos'), { recursive: true });+ statePath = join(rootDir, 'data', 'cos', 'state.json');+ });++ afterEach(() => rmSync(rootDir, { recursive: true, force: true }));++ it('upgrades an existing slice without losing future fields', async () => {+ writeFileSync(statePath, JSON.stringify({+ running: true,+ persistentMind: { schemaVersion: 1, enabled: true, customFutureField: 'preserve' },+ }));++ await expect(migration.up({ rootDir })).resolves.toEqual({ updated: 1 });+ expect(readJson(statePath)).toMatchObject({+ running: true,+ persistentMind: {+ schemaVersion: 2,+ mindId: 'cos-persistent-mind',+ enabled: true,+ customFutureField: 'preserve',+ },+ });+ });++ it('is idempotent', async () => {+ writeFileSync(statePath, JSON.stringify({+ persistentMind: { schemaVersion: 2, mindId: 'cos-persistent-mind' },+ }));+ await expect(migration.up({ rootDir })).resolves.toEqual({ updated: 0, reason: 'already-applied' });+ });++ it('leaves corrupt state untouched', async () => {+ 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.mdindex 18c38f8ea5..cfd72b6c0a 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -40,6 +40,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `agentRunReconcile.js` | CoS run reconciliation (#4540) — pure diff between a ledger projection (`projectRunStates`) and the durable run record. Closed finding vocabulary `RUN_RECONCILE_FINDINGS` (`record-open`, `record-missing`, `verdict-mismatch`, `ledger-open`), `diffRunRecord()`, `reconcileRunRecords()` with a zero-filled per-kind summary, and `planRunRecordRepair()` — the metadata patch that closes a record the ledger proves is finished. Repairs are one-directional (ledger → record) by design: a record closed while the ledger missed the close is reported, never back-filled, so the stream stays an audit of the record rather than a copy of it. I/O half: `services/agentRunReconciler.js`. || `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. || `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/agentRunEvents.js b/server/lib/agentRunEvents.jsindex c3e9fc861e..a5d2663e94 100644--- a/server/lib/agentRunEvents.js+++ b/server/lib/agentRunEvents.js@@ -33,11 +33,16 @@ import { homedir } from 'os';import { sha256Text } from './fileUtils.js';import { canonicalStringify, POLLUTING_KEYS } from './objects.js';import { redactOutput } from './commandSecurity.js';+import {+ PERSISTENT_MIND_EVENT_KINDS,+ isPersistentMindEventKind,+} from './persistentMindTrajectory.js';/*** Envelope schema version. Bump when the envelope SHAPE changes in a way a- * reader must notice; adding a new value to `AGENT_RUN_EVENT_KINDS` is not- * such a change (unknown kinds fold into the projection as no-ops).+ * reader must notice. The mind fields below are confined to a new kind+ * namespace, so ordinary v1 run envelopes remain byte-for-byte compatible;+ * adding a kind is not a shape change (unknown kinds fold as no-ops).** This is deliberately NOT a `PORTOS_SCHEMA_VERSIONS` entry: the ledger never* crosses the wire, so no peer ever has to agree with this number.@@ -93,7 +98,14 @@ export const AGENT_RUN_EVENT_KINDS = Object.freeze(['run.reconciled']);-const KIND_SET = new Set(AGENT_RUN_EVENT_KINDS);+/** All writeable kinds in the shared machine-local ledger. */+export const RUN_EVENT_KINDS = Object.freeze([+ ...AGENT_RUN_EVENT_KINDS,+ ...PERSISTENT_MIND_EVENT_KINDS,+]);++const KIND_SET = new Set(RUN_EVENT_KINDS);+const AGENT_KIND_SET = new Set(AGENT_RUN_EVENT_KINDS);// ---------------------------------------------------------------------------// Redaction@@ -126,6 +138,9 @@ const DROPPED_KEY_PATTERNS = [/** Bounds. A ledger line must stay a diagnostic, not become a record copy. */export const RUN_EVENT_LIMITS = Object.freeze({maxStringChars: 200,+ // Explicitly display-safe mind text is allowed to be useful context while+ // still bounded. Prompt/result/body keys never take this path.+ maxDisplayChars: 4_000,maxArrayItems: 20,maxObjectKeys: 40,maxDepth: 3@@ -167,10 +182,10 @@ export function scrubHomePath(value) {* Scrub + bound one free-form string: home path, then the shared secret filter,* then a hard length cap.*/-function scrubString(value) {+function scrubString(value, maxChars = RUN_EVENT_LIMITS.maxStringChars) {const scrubbed = redactOutput(scrubHomePath(value)) ?? '';- return scrubbed.length > RUN_EVENT_LIMITS.maxStringChars- ? `${scrubbed.slice(0, RUN_EVENT_LIMITS.maxStringChars)}…`+ return scrubbed.length > maxChars+ ? `${scrubbed.slice(0, maxChars)}…`: scrubbed;}@@ -232,6 +247,8 @@ function redactValue(value, depth) {// payload that was already safe.if (isDroppedKey(key) && (typeof raw === 'string' || (raw !== null && typeof raw === 'object'))) {out[key] = { redacted: 'content', chars: typeof raw === 'string' ? raw.length : null };+ } else if ((key === 'displayText' || key === 'summaryText') && typeof raw === 'string') {+ out[key] = scrubString(raw, RUN_EVENT_LIMITS.maxDisplayChars);} else {out[key] = redactValue(raw, depth + 1);}@@ -248,17 +265,40 @@ function redactValue(value, depth) {* Zod schema for one ledger line. `.strict()` so a call site cannot smuggle an* extra top-level field past redaction (redaction only walks `data`).*/-export const agentRunEventSchema = z.object({+const runEventEnvelopeSchema = z.object({schemaVersion: z.literal(AGENT_RUN_EVENT_SCHEMA_VERSION),eventId: z.string().min(1).max(128),- kind: z.enum(AGENT_RUN_EVENT_KINDS),+ kind: z.string().min(1).max(64),runId: z.string().min(1).max(128).nullable(),agentId: z.string().min(1).max(128).nullable(),taskId: z.string().min(1).max(128).nullable(),+ // Present only on persistent-mind events. Ordinary lifecycle envelopes keep+ // their exact pre-mind shape, so existing consumers do not grow fake ids.+ mindId: z.string().min(1).max(128).optional(),+ turnId: z.string().min(1).max(128).nullable().optional(),+ sequence: z.number().int().nonnegative().optional(),at: z.string().datetime(),data: z.record(z.unknown())}).strict();+const refineKnownEventIdentity = (event, ctx) => {+ const mindEvent = isPersistentMindEventKind(event.kind);+ if (mindEvent && !event.mindId) {+ ctx.addIssue({ code: z.ZodIssueCode.custom, path: ['mindId'], message: 'persistent-mind events require mindId' });+ }+ if (mindEvent && !Number.isSafeInteger(event.sequence)) {+ ctx.addIssue({ code: z.ZodIssueCode.custom, path: ['sequence'], message: 'persistent-mind events require sequence' });+ }+ if (AGENT_KIND_SET.has(event.kind)+ && (event.mindId !== undefined || event.turnId !== undefined || event.sequence !== undefined)) {+ ctx.addIssue({ code: z.ZodIssueCode.custom, path: ['mindId'], message: 'ordinary run events cannot carry persistent-mind identity' });+ }+};++export const agentRunEventSchema = runEventEnvelopeSchema.extend({+ kind: z.enum(RUN_EVENT_KINDS),+}).superRefine(refineKnownEventIdentity);+/*** Structural envelope check for the READ path.*@@ -271,9 +311,7 @@ export const agentRunEventSchema = z.object({* folds unknown kinds as no-ops). Writes stay strict — a typo at a call site is* still a bug, and `buildRunEvent` is where it gets caught.*/-export const storedRunEventSchema = agentRunEventSchema.extend({- kind: z.string().min(1).max(64)-});+export const storedRunEventSchema = runEventEnvelopeSchema.superRefine(refineKnownEventIdentity);/** Is this parsed line a structurally sound ledger line? Used by the read path. */export function isStoredRunEvent(value) {@@ -303,17 +341,21 @@ const nullableId = (value) => (typeof value === 'string' && value.trim() ? value* is where that throw gets absorbed.** @param {object} input- * @param {string} input.kind - one of AGENT_RUN_EVENT_KINDS+ * @param {string} input.kind - one of RUN_EVENT_KINDS* @param {string} [input.runId]* @param {string} [input.agentId]* @param {string} [input.taskId]+ * @param {string} [input.mindId] - required for persistent-mind kinds+ * @param {string} [input.turnId] - persistent-mind turn identity+ * @param {number} [input.sequence] - ledger-assigned mind ordering cursor* @param {string|Date} [input.at] - defaults to now* @param {object} [input.data] - redacted before it is hashed or stored* @param {string} [input.eventId] - explicit idempotency key* @returns {object} validated envelope*/-export function buildRunEvent({ kind, runId, agentId, taskId, at, data, eventId } = {}) {+export function buildRunEvent({ kind, runId, agentId, taskId, mindId, turnId, sequence, at, data, eventId } = {}) {const timestamp = at instanceof Date ? at.toISOString() : (typeof at === 'string' && at ? at : new Date().toISOString());+ const mindEvent = isPersistentMindEventKind(kind);const core = {schemaVersion: AGENT_RUN_EVENT_SCHEMA_VERSION,kind,@@ -323,6 +365,11 @@ export function buildRunEvent({ kind, runId, agentId, taskId, at, data, eventIdat: timestamp,data: redactRunEventData(data)};+ if (mindEvent) {+ core.mindId = nullableId(mindId);+ core.turnId = nullableId(turnId);+ core.sequence = sequence;+ }const envelope = {...core,eventId: typeof eventId === 'string' && eventId ? eventId.slice(0, 128) : deriveEventId(core)diff --git a/server/lib/agentRunEvents.test.js b/server/lib/agentRunEvents.test.jsindex 80b463661e..cd452f0200 100644--- a/server/lib/agentRunEvents.test.js+++ b/server/lib/agentRunEvents.test.js@@ -37,6 +37,29 @@ describe('buildRunEvent — envelope schema', () => {expect(event.taskId).toBeNull();});+ it('adds mind identity only to typed persistent-mind envelopes', () => {+ const event = buildRunEvent({+ kind: 'mind.message.accepted',+ mindId: 'cos-persistent-mind',+ turnId: 'turn-1',+ sequence: 42,+ at: AT,+ data: { displayText: 'Hello' },+ });+ expect(event).toMatchObject({+ kind: 'mind.message.accepted',+ mindId: 'cos-persistent-mind',+ turnId: 'turn-1',+ sequence: 42,+ });+ expect(() => buildRunEvent({ kind: 'mind.wake', mindId: 'cos-persistent-mind', at: AT })).toThrow();++ const ordinary = buildRunEvent({ kind: 'run.spawned', runId: 'r1', at: AT });+ expect(ordinary).not.toHaveProperty('mindId');+ expect(ordinary).not.toHaveProperty('turnId');+ expect(ordinary).not.toHaveProperty('sequence');+ });+it('accepts a Date for `at` and normalizes it to ISO', () => {const event = buildRunEvent({ kind: 'run.spawned', runId: 'r1', at: new Date(AT) });expect(event.at).toBe(AT);@@ -61,6 +84,15 @@ describe('buildRunEvent — envelope schema', () => {expect(isStoredRunEvent({ kind: 'run.spawned' })).toBe(false);expect(isStoredRunEvent({ ...buildRunEvent({ kind: 'run.spawned', runId: 'r1', at: AT }), at: 'not-a-date' })).toBe(false);expect(isStoredRunEvent({ ...buildRunEvent({ kind: 'run.spawned', runId: 'r1', at: AT }), extra: 1 })).toBe(false);+ const mind = buildRunEvent({+ kind: 'mind.wake',+ mindId: 'cos-persistent-mind',+ turnId: 'turn-1',+ sequence: 1,+ at: AT,+ });+ const { sequence: _sequence, ...missingSequence } = mind;+ expect(isStoredRunEvent(missingSequence)).toBe(false);});it('isKnownRunEventKind tracks the exported vocabulary', () => {@@ -193,6 +225,30 @@ describe('redactRunEventData — privacy', () => {const event = buildRunEvent({ kind: 'run.spawned', runId: 'r1', at: AT, data: { prompt: 'private words' } });expect(event.data.prompt).toEqual({ redacted: 'content', chars: 13 });});++ it('bounds display-safe mind text while still dropping prompt-like fields and secrets', () => {+ const event = buildRunEvent({+ kind: 'mind.model.result',+ mindId: 'cos-persistent-mind',+ turnId: 'turn-1',+ sequence: 1,+ at: AT,+ data: {+ displayText: `${'x'.repeat(RUN_EVENT_LIMITS.maxDisplayChars + 200)} {"API_KEY":"sk-live-example-secret"}`,+ prompt: 'private prompt words',+ body: { privateRecord: 'must not persist' },+ output: 'private model output',+ },+ });+ const persisted = JSON.stringify(event);+ expect(event.data.displayText.length).toBeLessThanOrEqual(RUN_EVENT_LIMITS.maxDisplayChars + 1);+ expect(persisted).not.toContain('sk-live-example-secret');+ expect(persisted).not.toContain('private prompt words');+ expect(persisted).not.toContain('must not persist');+ expect(persisted).not.toContain('private model output');+ expect(event.data.prompt).toEqual({ redacted: 'content', chars: 20 });+ expect(event.data.body).toEqual({ redacted: 'content', chars: null });+ });});describe('projectRunStates — replayable status', () => {diff --git a/server/lib/index.js b/server/lib/index.jsindex 8c4800c784..7e01e6a736 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -215,6 +215,7 @@ export * from './agentOutputMarkers.js';export * from './agentRunEvents.js';export * from './agentRunReconcile.js';export * from './persistentMind.js';+export * from './persistentMindTrajectory.js';export * from './agentSentinel.js';export * from './bareUrl.js';export * from './bashResolver.js';diff --git a/server/lib/persistentMind.js b/server/lib/persistentMind.jsindex 592217224c..ac75c0d4c9 100644--- a/server/lib/persistentMind.js+++ b/server/lib/persistentMind.js@@ -6,7 +6,9 @@* rules without depending on module-level process state.*/-export const PERSISTENT_MIND_SCHEMA_VERSION = 1;+import { PERSISTENT_MIND_ID } from './persistentMindTrajectory.js';++export const PERSISTENT_MIND_SCHEMA_VERSION = 2;export const PERSISTENT_MIND_STATUSES = ['disabled',@@ -42,6 +44,7 @@ const asBoundedString = (value, max) => ();const asId = (value) => asBoundedString(value, 200);+const asMindId = (value) => asBoundedString(value, 128);const asCount = (value) => (Number.isSafeInteger(value) && value >= 0 ? value : 0@@ -99,6 +102,7 @@ const sanitizeActiveTurn = (value) => {export function createDefaultPersistentMindState() {return {schemaVersion: PERSISTENT_MIND_SCHEMA_VERSION,+ mindId: PERSISTENT_MIND_ID,enabled: false,started: false,status: 'disabled',@@ -161,6 +165,7 @@ export function normalizePersistentMindState(raw) {return {...defaults,schemaVersion: PERSISTENT_MIND_SCHEMA_VERSION,+ mindId: asMindId(source.mindId) || PERSISTENT_MIND_ID,enabled,started,status,diff --git a/server/lib/persistentMindTrajectory.js b/server/lib/persistentMindTrajectory.jsnew file mode 100644index 0000000000..11dc176390--- /dev/null+++ b/server/lib/persistentMindTrajectory.js@@ -0,0 +1,391 @@+/**+ * Pure persistent-mind trajectory helpers.+ *+ * The machine-local run-event ledger owns persistence and ordering. This module+ * owns the mind-specific vocabulary, cursor shape, replay projection, rollup+ * record validation, and bounded context rendering so restart replay and live+ * reads use the same deterministic rules.+ */++import { z } from 'zod';++export const PERSISTENT_MIND_ID = 'cos-persistent-mind';+export const PERSISTENT_MIND_ROLLUP_PROMPT_VERSION = 1;++export const PERSISTENT_MIND_EVENT_KINDS = Object.freeze([+ 'mind.message.accepted',+ 'mind.annotation.accepted',+ 'mind.wake',+ 'mind.model.request',+ 'mind.model.result',+ 'mind.capability.request',+ 'mind.capability.result',+ 'mind.summary',+ 'mind.paused',+ 'mind.failed',+ 'mind.turn.completed',+ 'mind.memory.promoted',+]);++const MIND_KIND_SET = new Set(PERSISTENT_MIND_EVENT_KINDS);++export const PERSISTENT_MIND_TRAJECTORY_LIMITS = Object.freeze({+ defaultPageSize: 100,+ maxPageSize: 500,+ recentContextEvents: 60,+ maxContextChars: 16_000,+ maxIdentityChars: 2_000,+ maxSummaryChars: 6_000,+ maxStoredRollups: 100,+ maxProjectedTurns: 100,+ maxProjectedInputs: 200,+});++export const persistentMindRollupSchema = z.object({+ schemaVersion: z.literal(1),+ id: z.string().min(1).max(160),+ mindId: z.string().min(1).max(128),+ status: z.enum(['ready', 'failed']),+ summary: z.string().max(PERSISTENT_MIND_TRAJECTORY_LIMITS.maxSummaryChars).nullable(),+ error: z.string().max(500).nullable(),+ source: z.object({+ fromSequence: z.number().int().nonnegative(),+ toSequence: z.number().int().nonnegative(),+ fromEventId: z.string().min(1).max(128),+ toEventId: z.string().min(1).max(128),+ }).strict(),+ provenance: z.object({+ providerId: z.string().max(128).nullable(),+ model: z.string().max(500).nullable(),+ promptVersion: z.number().int().positive(),+ createdAt: z.string().datetime(),+ }).strict(),+}).strict().superRefine((value, ctx) => {+ if (value.source.toSequence < value.source.fromSequence) {+ ctx.addIssue({ code: z.ZodIssueCode.custom, path: ['source', 'toSequence'], message: 'must not precede fromSequence' });+ }+ if (value.status === 'ready' && value.summary === null) {+ ctx.addIssue({ code: z.ZodIssueCode.custom, path: ['summary'], message: 'ready rollups require a summary string' });+ }+ if (value.status === 'failed' && !value.error) {+ ctx.addIssue({ code: z.ZodIssueCode.custom, path: ['error'], message: 'failed rollups require an error' });+ }+});++export function isPersistentMindEventKind(kind) {+ return MIND_KIND_SET.has(kind);+}++const orderedMindEvents = (events, mindId = PERSISTENT_MIND_ID) => {+ const seen = new Set();+ return (Array.isArray(events) ? events : [])+ .filter((event) => event?.mindId === mindId && isPersistentMindEventKind(event.kind))+ .filter((event) => {+ if (!event.eventId || seen.has(event.eventId)) return false;+ seen.add(event.eventId);+ return true;+ })+ .sort((a, b) => {+ const sequenceDelta = (Number.isSafeInteger(a.sequence) ? a.sequence : Number.MAX_SAFE_INTEGER)+ - (Number.isSafeInteger(b.sequence) ? b.sequence : Number.MAX_SAFE_INTEGER);+ if (sequenceDelta !== 0) return sequenceDelta;+ const timeDelta = String(a.at).localeCompare(String(b.at));+ return timeDelta || String(a.eventId).localeCompare(String(b.eventId));+ });+};++export function persistentMindEventCursor(event) {+ if (!Number.isSafeInteger(event?.sequence) || event.sequence < 0 || typeof event?.eventId !== 'string') return null;+ return `${event.sequence}:${event.eventId}`;+}++export function parsePersistentMindCursor(cursor) {+ if (typeof cursor !== 'string') return null;+ // Event ids commonly contain namespace colons (`mind-message:<id>`). The+ // first colon separates the numeric sequence; the remainder is opaque.+ const match = /^(\d+):(.{1,128})$/.exec(cursor);+ if (!match) return null;+ const sequence = Number(match[1]);+ return Number.isSafeInteger(sequence) ? { sequence, eventId: match[2] } : null;+}++const displayText = (event) => (+ typeof event?.data?.displayText === 'string' ? event.data.displayText+ : typeof event?.data?.summaryText === 'string' ? event.data.summaryText+ : null+);++const emptyMindProjection = (mindId) => ({+ mindId,+ status: 'idle',+ activeTurnId: null,+ lastCompletedTurnId: null,+ lastEventAt: null,+ lastSequence: null,+ eventCount: 0,+ messages: [],+ annotations: [],+ turns: [],+});++/** Replay retained mind events into a stable, bounded visible projection. */+export function projectPersistentMind(events, mindId = PERSISTENT_MIND_ID) {+ const ordered = orderedMindEvents(events, mindId);+ const projection = emptyMindProjection(mindId);+ const turns = new Map();++ for (const event of ordered) {+ projection.eventCount += 1;+ projection.lastEventAt = event.at;+ projection.lastSequence = event.sequence;+ if (event.turnId && !turns.has(event.turnId)) {+ turns.set(event.turnId, {+ id: event.turnId,+ status: 'queued',+ startedAt: null,+ completedAt: null,+ providerId: null,+ model: null,+ effort: null,+ eventCount: 0,+ });+ }+ const turn = event.turnId ? turns.get(event.turnId) : null;+ if (turn) turn.eventCount += 1;++ switch (event.kind) {+ case 'mind.message.accepted':+ projection.messages.push({+ eventId: event.eventId,+ messageId: event.data?.messageId || null,+ turnId: event.turnId,+ at: event.at,+ text: displayText(event),+ });+ break;+ case 'mind.annotation.accepted':+ projection.annotations.push({+ eventId: event.eventId,+ annotationId: event.data?.annotationId || null,+ turnId: event.turnId,+ targetEventId: event.data?.targetEventId || null,+ at: event.at,+ text: displayText(event),+ });+ break;+ case 'mind.wake':+ projection.status = event.data?.status || 'thinking';+ projection.activeTurnId = event.turnId;+ if (turn) {+ turn.status = projection.status;+ turn.startedAt = turn.startedAt || event.at;+ }+ break;+ case 'mind.model.request':+ projection.status = 'thinking';+ projection.activeTurnId = event.turnId;+ if (turn) {+ turn.status = 'thinking';+ turn.startedAt = turn.startedAt || event.at;+ turn.providerId = event.data?.providerId || turn.providerId;+ turn.model = event.data?.model || turn.model;+ turn.effort = event.data?.effort || turn.effort;+ }+ break;+ case 'mind.paused':+ projection.status = event.data?.status || 'paused';+ projection.activeTurnId = null;+ if (turn) turn.status = projection.status;+ break;+ case 'mind.failed':+ projection.status = event.data?.status || 'failed';+ projection.activeTurnId = null;+ if (turn) {+ turn.status = projection.status;+ turn.completedAt = event.at;+ }+ break;+ case 'mind.turn.completed':+ projection.status = event.data?.status || 'idle';+ projection.activeTurnId = null;+ projection.lastCompletedTurnId = event.turnId;+ if (turn) {+ turn.status = 'completed';+ turn.completedAt = event.at;+ }+ break;+ default:+ break;+ }+ }++ projection.messages = projection.messages.slice(-PERSISTENT_MIND_TRAJECTORY_LIMITS.maxProjectedInputs);+ projection.annotations = projection.annotations.slice(-PERSISTENT_MIND_TRAJECTORY_LIMITS.maxProjectedInputs);+ projection.turns = [...turns.values()].slice(-PERSISTENT_MIND_TRAJECTORY_LIMITS.maxProjectedTurns);+ return projection;+}++export function isStoredPersistentMindRollup(value) {+ return persistentMindRollupSchema.safeParse(value).success;+}++const bounded = (value, max) => (typeof value === 'string' ? value.slice(0, max) : '');++export function buildPersistentMindRollup({+ id,+ mindId = PERSISTENT_MIND_ID,+ status,+ summary = null,+ error = null,+ source,+ providerId = null,+ model = null,+ promptVersion = PERSISTENT_MIND_ROLLUP_PROMPT_VERSION,+ createdAt = new Date().toISOString(),+}) {+ return persistentMindRollupSchema.parse({+ schemaVersion: 1,+ id,+ mindId,+ status,+ summary: summary === null ? null : bounded(summary, PERSISTENT_MIND_TRAJECTORY_LIMITS.maxSummaryChars),+ error: error === null ? null : bounded(error, 500),+ source,+ provenance: {+ providerId: providerId ? bounded(providerId, 128) : null,+ model: model ? bounded(model, 500) : null,+ promptVersion,+ createdAt,+ },+ });+}++const renderEventLine = (event) => {+ const parts = [`[${event.at}]`, event.kind];+ if (event.turnId) parts.push(`turn=${event.turnId}`);+ const text = displayText(event);+ if (text !== null) parts.push(JSON.stringify(text));+ for (const key of ['providerId', 'model', 'effort', 'capability', 'status']) {+ const value = event.data?.[key];+ if (typeof value === 'string' && value) parts.push(`${key}=${value}`);+ }+ return parts.join(' ');+};++/**+ * Render stable identity + older rollups + recent verbatim events into a hard+ * character budget. Unavailable/failed/stale summary state is explicit;+ * a real empty history is `summaryState: "empty"`, never conflated with one.+ */+export function assemblePersistentMindContext({+ mindId = PERSISTENT_MIND_ID,+ identity = '',+ events = [],+ rollups = [],+ maxChars = PERSISTENT_MIND_TRAJECTORY_LIMITS.maxContextChars,+ recentEventLimit = PERSISTENT_MIND_TRAJECTORY_LIMITS.recentContextEvents,+ promptVersion = PERSISTENT_MIND_ROLLUP_PROMPT_VERSION,+} = {}) {+ const cap = Math.max(1_000, Math.min(Number(maxChars) || PERSISTENT_MIND_TRAJECTORY_LIMITS.maxContextChars, 100_000));+ const ordered = orderedMindEvents(events, mindId);+ const recent = ordered.slice(-Math.max(1, recentEventLimit));+ const older = ordered.slice(0, Math.max(0, ordered.length - recent.length));+ const validRollups = (Array.isArray(rollups) ? rollups : [])+ .filter(isStoredPersistentMindRollup)+ .filter((rollup) => rollup.mindId === mindId)+ .sort((a, b) => a.source.fromSequence - b.source.fromSequence);++ // A rollup can outlive every raw event it summarizes. Select every sealed+ // range before the recent window, not only ranges that overlap retained raw+ // history, or a quiet mind would appear to forget its life after retention.+ const recentStart = recent[0]?.sequence ?? Number.POSITIVE_INFINITY;+ const selectedRollups = validRollups.filter((rollup) => rollup.source.toSequence < recentStart);+ const currentReadyRollups = selectedRollups+ .filter((rollup) => rollup.status === 'ready' && rollup.provenance.promptVersion === promptVersion);+ // Incremental summaries are cumulative. Keep only ranges that are not fully+ // superseded by another ready range so context never repeats every prior+ // version of the same life summary.+ const effectiveReadyRollups = currentReadyRollups.filter((candidate) => !currentReadyRollups.some((other) => (+ other.id !== candidate.id+ && other.source.fromSequence <= candidate.source.fromSequence+ && other.source.toSequence >= candidate.source.toSequence+ )));+ const hasOmittedHistory = older.length > 0 || selectedRollups.length > 0;+ let summaryState = !hasOmittedHistory+ ? (ordered.length === 0 ? 'empty' : 'not-needed')+ : 'unavailable';+ if (hasOmittedHistory) {+ const stale = selectedRollups.some((rollup) => rollup.provenance.promptVersion !== promptVersion);+ const failed = selectedRollups.some((rollup) => rollup.status === 'failed');+ const everyOlderEventCovered = older.every((event) => effectiveReadyRollups.some((rollup) => (+ event.sequence >= rollup.source.fromSequence && event.sequence <= rollup.source.toSequence+ )));+ const everySelectedRangeCovered = selectedRollups.every((selected) => effectiveReadyRollups.some((rollup) => (+ selected.source.fromSequence >= rollup.source.fromSequence+ && selected.source.toSequence <= rollup.source.toSequence+ )));+ if (effectiveReadyRollups.length > 0 && everyOlderEventCovered && everySelectedRangeCovered) summaryState = 'ready';+ else if (failed) summaryState = 'failed';+ else if (stale) summaryState = 'stale';+ }++ const identityText = bounded(+ typeof identity === 'string' ? identity : JSON.stringify(identity),+ PERSISTENT_MIND_TRAJECTORY_LIMITS.maxIdentityChars+ );+ const prefix = `# Persistent mind identity\nmindId=${mindId}${identityText ? `\n${identityText}` : ''}`;+ const summaryLines = effectiveReadyRollups+ .map((rollup) => `[events ${rollup.source.fromSequence}-${rollup.source.toSequence}; ${rollup.provenance.providerId || 'unknown'}/${rollup.provenance.model || 'default'}; prompt v${rollup.provenance.promptVersion}]\n${rollup.summary}`);+ const omittedStarts = [selectedRollups[0]?.source.fromSequence, older[0]?.sequence].filter(Number.isSafeInteger);+ const omittedEnds = [older.at(-1)?.sequence, selectedRollups.at(-1)?.source.toSequence].filter(Number.isSafeInteger);+ const omittedStart = omittedStarts.length ? Math.min(...omittedStarts) : null;+ const omittedEnd = omittedEnds.length ? Math.max(...omittedEnds) : null;+ const statusLine = hasOmittedHistory+ ? `summary-cache=${summaryState}; omitted-events=${omittedStart}-${omittedEnd}`+ : `summary-cache=${summaryState}`;++ // Keep recent raw events available even if many large rollups exist. Older+ // summaries receive at most 45% of the post-header budget; newest summaries+ // win inside that bound, while recent events consume the remainder.+ const sectionOverhead = `\n\n# Older context\n${statusLine}\n\n# Recent trajectory\n`;+ const contentBudget = Math.max(0, cap - prefix.length - sectionOverhead.length);+ const summaryBudget = summaryLines.length ? Math.floor(contentBudget * 0.45) : 0;+ const keptSummaryLines = [];+ let summaryChars = 0;+ for (const line of [...summaryLines].reverse()) {+ const separator = keptSummaryLines.length ? 1 : 0;+ if (summaryChars + separator + line.length > summaryBudget) continue;+ keptSummaryLines.unshift(line);+ summaryChars += separator + line.length;+ }+ const recentBudget = contentBudget - summaryChars;+ const recentLines = [];+ let recentChars = 0;+ for (const event of [...recent].reverse()) {+ const line = renderEventLine(event);+ const separator = recentLines.length ? 1 : 0;+ if (recentChars + separator + line.length > recentBudget) continue;+ recentLines.unshift(line);+ recentChars += separator + line.length;+ }+ const sections = [+ prefix,+ `# Older context\n${statusLine}${keptSummaryLines.length ? `\n${keptSummaryLines.join('\n')}` : ''}`,+ `# Recent trajectory\n${recentLines.join('\n')}`,+ ];+ const text = sections.join('\n\n').slice(0, cap);+ return {+ mindId,+ text,+ chars: text.length,+ approximateTokens: Math.ceil(text.length / 4),+ summaryState,+ omittedRange: hasOmittedHistory ? {+ fromSequence: omittedStart,+ toSequence: omittedEnd,+ fromEventId: selectedRollups[0]?.source.fromEventId ?? older[0]?.eventId ?? null,+ toEventId: older.at(-1)?.eventId ?? selectedRollups.at(-1)?.source.toEventId ?? null,+ } : null,+ recentEventCount: recentLines.length,+ };+}diff --git a/server/lib/persistentMindTrajectory.test.js b/server/lib/persistentMindTrajectory.test.jsnew file mode 100644index 0000000000..e3234ea0ee--- /dev/null+++ b/server/lib/persistentMindTrajectory.test.js@@ -0,0 +1,139 @@+import { describe, expect, it } from 'vitest';+import {+ PERSISTENT_MIND_ID,+ assemblePersistentMindContext,+ buildPersistentMindRollup,+ parsePersistentMindCursor,+ persistentMindEventCursor,+ projectPersistentMind,+} from './persistentMindTrajectory.js';++const event = ({+ eventId,+ sequence,+ kind,+ turnId = null,+ text = null,+ at = `2026-08-25T12:00:${String(sequence).padStart(2, '0')}.000Z`,+ data = {},+}) => ({+ schemaVersion: 1,+ eventId,+ kind,+ runId: null,+ agentId: null,+ taskId: null,+ mindId: PERSISTENT_MIND_ID,+ turnId,+ sequence,+ at,+ data: text === null ? data : { ...data, displayText: text },+});++const source = (events) => ({+ fromSequence: events[0].sequence,+ toSequence: events.at(-1).sequence,+ fromEventId: events[0].eventId,+ toEventId: events.at(-1).eventId,+});++describe('persistent mind cursors', () => {+ it('round-trips a durable sequence and event id', () => {+ const cursor = persistentMindEventCursor({ sequence: 42, eventId: 'event-42' });+ expect(cursor).toBe('42:event-42');+ expect(parsePersistentMindCursor(cursor)).toEqual({ sequence: 42, eventId: 'event-42' });+ });++ it('rejects malformed or unsafe cursors instead of treating them as empty history', () => {+ expect(parsePersistentMindCursor('not-a-cursor')).toBeNull();+ expect(parsePersistentMindCursor('-1:event')).toBeNull();+ expect(parsePersistentMindCursor(`${Number.MAX_SAFE_INTEGER}0:event`)).toBeNull();+ });+});++describe('projectPersistentMind', () => {+ const stream = [+ event({ eventId: 'message-1', sequence: 1, kind: 'mind.message.accepted', text: 'Please inspect this.' }),+ event({ eventId: 'wake-1', sequence: 2, kind: 'mind.wake', turnId: 'turn-1' }),+ event({ eventId: 'request-1', sequence: 3, kind: 'mind.model.request', turnId: 'turn-1', data: { providerId: 'example', model: 'model-a' } }),+ event({ eventId: 'annotation-1', sequence: 4, kind: 'mind.annotation.accepted', turnId: 'turn-1', text: 'Prefer the smaller change.', data: { targetEventId: 'request-1' } }),+ event({ eventId: 'complete-1', sequence: 5, kind: 'mind.turn.completed', turnId: 'turn-1' }),+ ];++ it('replays the same visible state after restart and ignores duplicate deliveries', () => {+ const replayed = projectPersistentMind([...stream].reverse().concat(stream[0]));+ expect(replayed).toEqual(projectPersistentMind(stream));+ expect(replayed).toMatchObject({+ status: 'idle',+ activeTurnId: null,+ lastCompletedTurnId: 'turn-1',+ eventCount: 5,+ messages: [{ eventId: 'message-1', text: 'Please inspect this.' }],+ annotations: [{ eventId: 'annotation-1', turnId: 'turn-1', targetEventId: 'request-1', text: 'Prefer the smaller change.' }],+ turns: [{ id: 'turn-1', status: 'completed', providerId: 'example', model: 'model-a', eventCount: 4 }],+ });+ });+});++describe('assemblePersistentMindContext', () => {+ const history = [+ event({ eventId: 'e1', sequence: 1, kind: 'mind.message.accepted', text: 'First message' }),+ event({ eventId: 'e2', sequence: 2, kind: 'mind.wake', turnId: 'turn-1' }),+ event({ eventId: 'e3', sequence: 3, kind: 'mind.turn.completed', turnId: 'turn-1' }),+ event({ eventId: 'e4', sequence: 4, kind: 'mind.message.accepted', text: 'Recent message' }),+ event({ eventId: 'e5', sequence: 5, kind: 'mind.wake', turnId: 'turn-2' }),+ ];++ const readyRollup = buildPersistentMindRollup({+ id: 'rollup-1',+ status: 'ready',+ summary: 'The first turn established the task boundary.',+ source: source(history.slice(0, 3)),+ providerId: 'example-provider',+ model: 'example-model',+ promptVersion: 1,+ createdAt: '2026-08-25T12:30:00.000Z',+ });++ it('stays within budget while including identity, provenance, summary, and recent raw events', () => {+ const context = assemblePersistentMindContext({+ identity: 'A stable resident Chief of Staff.',+ events: history,+ rollups: [readyRollup],+ recentEventLimit: 2,+ maxChars: 2_000,+ });++ expect(context.chars).toBeLessThanOrEqual(2_000);+ expect(context.summaryState).toBe('ready');+ expect(context.text).toContain('A stable resident Chief of Staff.');+ expect(context.text).toContain('example-provider/example-model; prompt v1');+ expect(context.text).toContain('The first turn established the task boundary.');+ expect(context.text).toContain('Recent message');+ expect(context.omittedRange).toMatchObject({ fromSequence: 1, toSequence: 3 });+ });++ it('keeps a ready rollup after its raw source events have expired', () => {+ const context = assemblePersistentMindContext({ events: [], rollups: [readyRollup] });+ expect(context.summaryState).toBe('ready');+ expect(context.text).toContain('The first turn established the task boundary.');+ expect(context.omittedRange).toMatchObject({ fromSequence: 1, toSequence: 3 });+ });++ it('distinguishes empty, unavailable, failed, stale, and not-needed context', () => {+ expect(assemblePersistentMindContext().summaryState).toBe('empty');+ expect(assemblePersistentMindContext({ events: history.slice(-1) }).summaryState).toBe('not-needed');+ expect(assemblePersistentMindContext({ events: history, recentEventLimit: 2 }).summaryState).toBe('unavailable');++ const failed = buildPersistentMindRollup({+ id: 'failed-1',+ status: 'failed',+ error: 'provider unavailable',+ source: source(history.slice(0, 3)),+ });+ expect(assemblePersistentMindContext({ events: history, rollups: [failed], recentEventLimit: 2 }).summaryState)+ .toBe('failed');+ expect(assemblePersistentMindContext({ events: history, rollups: [readyRollup], recentEventLimit: 2, promptVersion: 2 }).summaryState)+ .toBe('stale');+ });+});diff --git a/server/services/agentRunEventLog.js b/server/services/agentRunEventLog.jsindex c1828cdfa3..db5f741817 100644--- a/server/services/agentRunEventLog.js+++ b/server/services/agentRunEventLog.js@@ -20,12 +20,11 @@* MAX_ACTIVE_EVENTS it becomes the archive and the previous archive is dropped,* so the ledger holds between MAX_ACTIVE_EVENTS and 2×MAX_ACTIVE_EVENTS events.*- * On top of that sits an AGE bound (MAX_EVENT_AGE_DAYS). The count alone is- * only half a retention policy: it bounds a busy install but lets a quiet one- * keep a trace of a run from last spring, describing a workspace, a provider,- * and a code path that no longer exist. Expired events are filtered out on- * every read (so the bound holds continuously) and swept off disk on a- * throttled prune (so the files actually shrink) — see `pruneExpired`.+ * On top of that sits an AGE bound (MAX_EVENT_AGE_DAYS) for ordinary run+ * diagnostics. Persistent-mind events are count-bounded only: a quiet mind's+ * last unsummarized recent window must survive long enough to be rolled up on+ * its next explicit restart. Expired ordinary events are filtered on every+ * read and swept on a throttled prune — see `pruneExpired`.** Two invariants the callers depend on:*@@ -42,7 +41,9 @@ import { join } from 'path';import { rename, unlink } from 'fs/promises';import {PATHS,+ atomicWrite,appendJSONLine,+ readJSONFileStrict,readJSONLFile,writeJSONLines,pathExists@@ -51,12 +52,22 @@ import {buildRunEvent,isStoredRunEvent,projectRunStates,- AGENT_RUN_EVENT_KINDS,+ RUN_EVENT_KINDS,RUN_EVENT_READ_LIMITS} from '../lib/agentRunEvents.js';+import {+ PERSISTENT_MIND_ID,+ PERSISTENT_MIND_TRAJECTORY_LIMITS,+ isPersistentMindEventKind,+ parsePersistentMindCursor,+ persistentMindEventCursor,+ projectPersistentMind,+} from '../lib/persistentMindTrajectory.js';const ACTIVE_PATH = join(PATHS.cos, 'run-events.jsonl');const ARCHIVE_PATH = join(PATHS.cos, 'run-events.1.jsonl');+const MIND_SEQUENCE_PATH = join(PATHS.cos, 'persistent-mind-sequences.json');+const MIND_SEQUENCE_SCHEMA_VERSION = 1;/*** Events per generation. 5000 covers weeks of a busy install's lifecycle@@ -74,9 +85,9 @@ export const MAX_ACTIVE_EVENTS = 5000;* solves. So: keep at most 2×MAX_ACTIVE_EVENTS events, AND nothing older than* this, whichever bites first.*- * 30 days is well past the window in which a run failure is still worth a- * post-mortem, and comfortably past the longest restart/recovery cycle a run- * can survive.+ * 30 days is well past the window in which an ordinary run failure is still+ * worth a post-mortem. Persistent-mind events instead use the count bound so+ * their recent unsummarized window survives a long user-initiated stop.*/export const MAX_EVENT_AGE_DAYS = 30;const MAX_EVENT_AGE_MS = MAX_EVENT_AGE_DAYS * 24 * 60 * 60 * 1000;@@ -96,7 +107,7 @@ const PRUNE_INTERVAL_MS = 60 * 60 * 1000;export const DEFAULT_READ_LIMIT = RUN_EVENT_READ_LIMITS.default;export const MAX_READ_LIMIT = RUN_EVENT_READ_LIMITS.max;-// Lazily hydrated on first append/read: Maps of eventId → the event's `at`.+// Lazily hydrated on first append/read: Maps of eventId → retention metadata.// `null` (not an empty Map) is the "never loaded" sentinel, so a genuinely// empty ledger caches as empty instead of re-reading both files on every single// append. The timestamp is carried so the duplicate check can apply the SAME age@@ -105,6 +116,11 @@ export const MAX_READ_LIMIT = RUN_EVENT_READ_LIMITS.max;let activeIds = null;let archiveIds = null;let activeCount = 0;+// Highest sequence observed per mind. The timestamp-based floor keeps a new+// event above a fully-retained-away generation after restart; the retained max+// keeps strict monotonic order when the wall clock moves backwards.+let mindSequenceHighWater = null;+let mindSequenceCheckpointError = null;// `null` = never pruned in this process, so the first append/read always// prunes; a timestamp means "pruned then, skip until the interval elapses".let lastPrunedAt = null;@@ -112,9 +128,12 @@ let lastPrunedAt = null;// Serializes appends; also the handle callers await.let appendQueue = Promise.resolve();-/** eventId → `at`, for the duplicate check. Lines with no id are unindexable. */+/** eventId → retention metadata, for the duplicate check. */function indexById(events) {- return new Map(events.filter((e) => e?.eventId).map((e) => [e.eventId, e.at ?? null]));+ return new Map(events.filter((e) => e?.eventId).map((e) => [e.eventId, {+ at: e.at ?? null,+ persistentMind: isPersistentMindEventKind(e.kind),+ }]));}/**@@ -127,23 +146,55 @@ function indexById(events) {* duplicate — applied continuously rather than only at the moment of a prune.*/function isStoredDuplicate(eventId, cutoff) {- const at = activeIds.has(eventId) ? activeIds.get(eventId)+ const metadata = activeIds.has(eventId) ? activeIds.get(eventId): archiveIds.has(eventId) ? archiveIds.get(eventId): undefined;- return at !== undefined && typeof at === 'string' && at > cutoff;+ return metadata !== undefined+ && (metadata.persistentMind || (typeof metadata.at === 'string' && metadata.at > cutoff));}async function hydrate() {if (activeIds) return;- const [active, archive] = await Promise.all([+ const [active, archive, sequenceStore] = await Promise.all([readJSONLFile(ACTIVE_PATH),- readJSONLFile(ARCHIVE_PATH)+ readJSONLFile(ARCHIVE_PATH),+ readJSONFileStrict(MIND_SEQUENCE_PATH, { schemaVersion: MIND_SEQUENCE_SCHEMA_VERSION, minds: {} }),]);+ const invalidSequenceStore = !sequenceStore.ok || !sequenceStore.value+ || typeof sequenceStore.value !== 'object' || Array.isArray(sequenceStore.value)+ || sequenceStore.value.schemaVersion !== MIND_SEQUENCE_SCHEMA_VERSION+ || !sequenceStore.value.minds || typeof sequenceStore.value.minds !== 'object'+ || Array.isArray(sequenceStore.value.minds)+ || Object.entries(sequenceStore.value.minds).some(([mindId, sequence]) => (+ !mindId || mindId.length > 128 || !Number.isSafeInteger(sequence) || sequence < 0+ ));+ const validSequenceStore = !invalidSequenceStore;activeIds = indexById(active);archiveIds = indexById(archive);activeCount = active.length;+ mindSequenceCheckpointError = validSequenceStore+ ? null+ : 'Persistent mind sequence checkpoint is unreadable or invalid';+ mindSequenceHighWater = new Map(validSequenceStore ? Object.entries(sequenceStore.value.minds) : []);+ for (const event of [...archive, ...active]) {+ if (!event?.mindId || !Number.isSafeInteger(event.sequence)) continue;+ mindSequenceHighWater.set(+ event.mindId,+ Math.max(mindSequenceHighWater.get(event.mindId) ?? -1, event.sequence)+ );+ }}+function nextMindSequence(mindId) {+ const previous = mindSequenceHighWater.get(mindId) ?? -1;+ return Math.max(previous + 1, Date.now() * 1000);+}++const saveMindSequenceHighWater = () => atomicWrite(MIND_SEQUENCE_PATH, {+ schemaVersion: MIND_SEQUENCE_SCHEMA_VERSION,+ minds: Object.fromEntries(mindSequenceHighWater),+});+/*** Rotate when the active generation is full: active becomes the archive, the* previous archive is dropped. The seen-id sets move with the files, so an@@ -170,8 +221,8 @@ function expiryCutoff(now = Date.now()) {}/**- * Would a reader see this line — i.e. is it structurally sound AND still inside- * the age window?+ * Would a reader see this line — structurally sound and either a mind event or+ * still inside the ordinary-run age window?** One predicate, used by the read path, the stats, and the prune, so all three* agree by construction. A structurally invalid or undatable line counts as@@ -180,7 +231,8 @@ function expiryCutoff(now = Date.now()) {* would let unreadable bytes accumulate forever under a retention policy that* can never date them. The prune is the only thing that ever cleans them up.*/-const isRetained = (event, cutoff) => isStoredRunEvent(event) && event.at > cutoff;+const isRetained = (event, cutoff) => isStoredRunEvent(event)+ && (isPersistentMindEventKind(event.kind) || event.at > cutoff);/*** Rewrite both generations without their expired events, and drop the expired@@ -223,8 +275,17 @@ async function pruneExpired({ now = Date.now(), force = false } = {}) {}async function appendNow(input) {- const event = buildRunEvent(input);await hydrate();+ const mindEvent = isPersistentMindEventKind(input?.kind);+ if (mindEvent && mindSequenceCheckpointError) throw new Error(mindSequenceCheckpointError);+ // A stable explicit id lets a retry short-circuit before consuming a new+ // sequence. Every supervisor boundary supplies one; derived ids remain+ // available for one-off callers and ordinary lifecycle events.+ if (mindEvent && input?.eventId && isStoredDuplicate(input.eventId, expiryCutoff())) {+ return { appended: false, duplicate: true, event: null };+ }+ const sequence = mindEvent ? nextMindSequence(input.mindId) : undefined;+ const event = buildRunEvent(mindEvent ? { ...input, sequence } : input);// Age out BEFORE the duplicate check: an event whose only copy just expired// must be appendable again, exactly as after a rotation.await pruneExpired();@@ -233,8 +294,16 @@ async function appendNow(input) {}await rotateIfFull();await appendJSONLine(ACTIVE_PATH, event);- activeIds.set(event.eventId, event.at);+ activeIds.set(event.eventId, { at: event.at, persistentMind: mindEvent });activeCount += 1;+ if (mindEvent) {+ mindSequenceHighWater.set(event.mindId, event.sequence);+ // The ledger generations are intentionally retained only for 30 days, but+ // rollups can live indefinitely. Persist the high-water separately so a+ // clock rollback after raw retention expires cannot reuse an old sequence+ // range and hide an older rollup.+ await saveMindSequenceHighWater();+ }return { appended: true, duplicate: false, event };}@@ -258,6 +327,11 @@ export function appendRunEvent(input) {return appendQueue;}+/** Append one persistent-mind trajectory event through the shared queue. */+export function appendMindEvent(input) {+ return appendRunEvent({ ...input, mindId: input?.mindId || PERSISTENT_MIND_ID });+}+/** Resolve once every queued append has landed. Used by the read path + tests. */export function flushRunEvents() {return appendQueue.then(() => undefined, () => undefined);@@ -296,7 +370,7 @@ function schedulePrune() {* @param {number} [options.limit] - newest-N cap (default DEFAULT_READ_LIMIT)* @returns {Promise<object[]>} validated events in append order*/-export async function readRunEvents({ runId, agentId, taskId, kind, since, limit } = {}) {+async function readRetainedEvents() {await schedulePrune();const [archive, active] = await Promise.all([readJSONLFile(ARCHIVE_PATH),@@ -311,7 +385,11 @@ export async function readRunEvents({ runId, agentId, taskId, kind, since, limit// The check deliberately admits kinds this build does not know (see// `isStoredRunEvent`): a newer install's ledger must still read here. The// same predicate bounds the age, so a reader never sees an expired event.- let events = [...archive, ...active].filter((e) => isRetained(e, cutoff));+ return [...archive, ...active].filter((e) => isRetained(e, cutoff));+}++export async function readRunEvents({ runId, agentId, taskId, kind, since, limit } = {}) {+ let events = await readRetainedEvents();if (runId) events = events.filter((e) => e.runId === runId);if (agentId) events = events.filter((e) => e.agentId === agentId);@@ -323,6 +401,46 @@ export async function readRunEvents({ runId, agentId, taskId, kind, since, limitreturn events.length > cap ? events.slice(events.length - cap) : events;}+/** All retained events for one mind, ordered by durable sequence. */+export async function readPersistentMindHistory(mindId = PERSISTENT_MIND_ID) {+ return (await readRetainedEvents())+ .filter((event) => event.mindId === mindId && isPersistentMindEventKind(event.kind))+ .sort((a, b) => a.sequence - b.sequence || String(a.eventId).localeCompare(String(b.eventId)));+}++/**+ * Cursor-aware mind tail read. A missing predecessor is explicit `gap: true`;+ * the same response carries a fresh projection and retained tail so a client+ * can recover without treating the gap as an empty conversation.+ */+export async function readPersistentMindEvents({+ mindId = PERSISTENT_MIND_ID,+ cursor,+ limit = PERSISTENT_MIND_TRAJECTORY_LIMITS.defaultPageSize,+} = {}) {+ const retained = await readPersistentMindHistory(mindId);+ const cap = Math.min(+ Number.isFinite(limit) && limit > 0 ? Math.floor(limit) : PERSISTENT_MIND_TRAJECTORY_LIMITS.defaultPageSize,+ PERSISTENT_MIND_TRAJECTORY_LIMITS.maxPageSize+ );+ const parsed = cursor ? parsePersistentMindCursor(cursor) : null;+ const cursorIndex = parsed+ ? retained.findIndex((event) => event.sequence === parsed.sequence && event.eventId === parsed.eventId)+ : -1;+ const gap = Boolean(cursor) && cursorIndex < 0;+ const available = cursorIndex >= 0 ? retained.slice(cursorIndex + 1) : retained;+ const events = cursorIndex >= 0 ? available.slice(0, cap) : available.slice(-cap);+ const last = events.at(-1) || retained.at(-1) || null;+ return {+ mindId,+ events,+ cursor: persistentMindEventCursor(last),+ gap,+ hasMore: cursorIndex >= 0 && available.length > events.length,+ snapshot: projectPersistentMind(retained, mindId),+ };+}+/*** Replay the ledger into per-run current state.*@@ -383,8 +501,9 @@ export async function getRunEventLedgerStats() {maxActiveEvents: MAX_ACTIVE_EVENTS,maxRetainedEvents: MAX_ACTIVE_EVENTS * 2,maxEventAgeDays: MAX_EVENT_AGE_DAYS,+ persistentMindAgeBounded: false,oldestEventAt: oldest,- kinds: AGENT_RUN_EVENT_KINDS+ kinds: RUN_EVENT_KINDS};}@@ -398,6 +517,8 @@ export function __resetRunEventLogCache() {activeIds = null;archiveIds = null;activeCount = 0;+ mindSequenceHighWater = null;+ mindSequenceCheckpointError = null;lastPrunedAt = null;appendQueue = Promise.resolve();}diff --git a/server/services/agentRunEventLog.test.js b/server/services/agentRunEventLog.test.jsindex 626e82ed4f..b5045d76cb 100644--- a/server/services/agentRunEventLog.test.js+++ b/server/services/agentRunEventLog.test.js@@ -21,7 +21,10 @@ vi.mock('../lib/fileUtils.js', async (importOriginal) => {const {appendRunEvent,+ appendMindEvent,readRunEvents,+ readPersistentMindEvents,+ readPersistentMindHistory,getRunProjections,getRunDiagnostic,getRunEventLedgerStats,@@ -31,13 +34,15 @@ const {MAX_EVENT_AGE_DAYS} = await import('./agentRunEventLog.js');const { buildRunEvent } = await import('../lib/agentRunEvents.js');+const { persistentMindEventCursor } = await import('../lib/persistentMindTrajectory.js');const ACTIVE = join(LEDGER_DIR, 'run-events.jsonl');const ARCHIVE = join(LEDGER_DIR, 'run-events.1.jsonl');+const MIND_SEQUENCES = join(LEDGER_DIR, 'persistent-mind-sequences.json');/** Wipe the on-disk ledger AND the in-process caches — i.e. a fresh install. */function resetLedger() {- for (const path of [ACTIVE, ARCHIVE]) if (existsSync(path)) rmSync(path);+ for (const path of [ACTIVE, ARCHIVE, MIND_SEQUENCES]) if (existsSync(path)) rmSync(path);__resetRunEventLogCache();}@@ -146,6 +151,102 @@ describe('duplicate-event idempotency', () => {});});+describe('persistent-mind ordering, replay, and cursors', () => {+ const appendMessage = (id) => appendMindEvent({+ kind: 'mind.message.accepted',+ eventId: `mind-message:${id}`,+ data: { messageId: id, displayText: `Message ${id}` },+ });++ it('serializes concurrent appends into strict per-mind sequence order', async () => {+ const results = await Promise.all(Array.from({ length: 20 }, (_, index) => appendMessage(index)));+ const events = await readPersistentMindHistory();++ expect(results.every((result) => result.appended)).toBe(true);+ expect(events.map((event) => event.data.messageId)).toEqual(Array.from({ length: 20 }, (_, index) => index));+ expect(events.every((event, index) => index === 0 || event.sequence > events[index - 1].sequence)).toBe(true);+ });++ it('deduplicates an explicit event id without consuming another sequence', async () => {+ const first = await appendMessage('one');+ const duplicate = await appendMessage('one');+ const second = await appendMessage('two');++ expect(duplicate).toMatchObject({ appended: false, duplicate: true });+ expect(await readPersistentMindHistory()).toHaveLength(2);+ expect(second.event.sequence).toBe(first.event.sequence + 1);+ });++ it('continues sequence order and reconstructs the same snapshot after restart', async () => {+ await appendMessage('one');+ await appendMindEvent({+ kind: 'mind.wake',+ turnId: 'turn-1',+ eventId: 'mind-wake:turn-1',+ });+ const before = await readPersistentMindEvents();++ restartServer();+ const after = await readPersistentMindEvents();+ const completed = await appendMindEvent({+ kind: 'mind.turn.completed',+ turnId: 'turn-1',+ eventId: 'mind-complete:turn-1',+ });++ expect(after.snapshot).toEqual(before.snapshot);+ expect(completed.event.sequence).toBeGreaterThan(after.snapshot.lastSequence);+ });++ it('keeps sequence order after all raw events expire and the wall clock moves backwards', async () => {+ const first = await appendMessage('one');+ writeFileSync(ACTIVE, '');+ restartServer();+ vi.setSystemTime(new Date('2026-08-17T13:00:00.000Z'));++ const later = await appendMessage('two');+ expect(later.event.sequence).toBe(first.event.sequence + 1);+ });++ it('fails mind appends closed on a corrupt sequence checkpoint without blocking ordinary run events', async () => {+ writeFileSync(MIND_SEQUENCES, '{broken');+ restartServer();+ const spy = vi.spyOn(console, 'error').mockImplementation(() => {});++ await expect(appendMessage('one')).resolves.toMatchObject({+ appended: false,+ error: 'Persistent mind sequence checkpoint is unreadable or invalid',+ });+ await expect(appendRunEvent({+ kind: 'run.spawned',+ runId: 'ordinary-run',+ at: '2026-08-18T12:00:00.000Z',+ })).resolves.toMatchObject({ appended: true });+ expect((await readRunEvents()).map((item) => item.runId)).toEqual(['ordinary-run']);+ spy.mockRestore();+ });++ it('pages strictly after a cursor and reports a missing retained predecessor as a gap', async () => {+ await appendMessage('one');+ await appendMessage('two');+ await appendMessage('three');+ const history = await readPersistentMindHistory();+ const cursor = persistentMindEventCursor(history[0]);++ const page = await readPersistentMindEvents({ cursor, limit: 1 });+ expect(page).toMatchObject({ gap: false, hasMore: true });+ expect(page.events.map((item) => item.data.messageId)).toEqual(['two']);+ expect(page.cursor).toBe(persistentMindEventCursor(history[1]));++ writeFileSync(ACTIVE, history.slice(1).map((item) => `${JSON.stringify(item)}\n`).join(''));+ restartServer();+ const recovered = await readPersistentMindEvents({ cursor, limit: 2 });+ expect(recovered.gap).toBe(true);+ expect(recovered.events.map((item) => item.data.messageId)).toEqual(['two', 'three']);+ expect(recovered.snapshot.messages.map((item) => item.messageId)).toEqual(['two', 'three']);+ });+});+describe('retention / rotation bound', () => {it('rotates at MAX_ACTIVE_EVENTS and keeps exactly one archive generation', async () => {const seed = (n, offset = 0) => Array.from({ length: n }, (_, i) =>@@ -314,6 +415,28 @@ describe('retention — age bound (#4540)', () => {expect(countLines(ACTIVE)).toBe(1);});+ it('keeps the mind recent window count-bounded across a long explicit stop', async () => {+ const mindEvent = buildRunEvent({+ kind: 'mind.message.accepted',+ mindId: 'cos-persistent-mind',+ sequence: 1,+ eventId: 'mind-message:ancient',+ at: stale(),+ data: { messageId: 'ancient', displayText: 'Retain until it can be summarized.' },+ });+ writeFileSync(ACTIVE, `${JSON.stringify(mindEvent)}\n`);+ restartServer();++ expect((await readPersistentMindHistory()).map((item) => item.eventId)).toEqual(['mind-message:ancient']);+ expect(countLines(ACTIVE)).toBe(1);+ expect(await appendMindEvent({+ kind: 'mind.message.accepted',+ eventId: 'mind-message:ancient',+ at: stale(),+ data: { messageId: 'ancient', displayText: 'Retain until it can be summarized.' },+ })).toMatchObject({ appended: false, duplicate: true });+ });+it('drops an archive generation that has aged out entirely', async () => {writeFileSync(ARCHIVE, seedLines([{ kind: 'run.spawned', runId: 'ancient', at: stale() }]));writeFileSync(ACTIVE, seedLines([{ kind: 'run.spawned', runId: 'current', at: recent() }]));diff --git a/server/services/cos.test.js b/server/services/cos.test.jsindex 310100df8a..c516010433 100644--- a/server/services/cos.test.js+++ b/server/services/cos.test.js@@ -2404,7 +2404,8 @@ describe('canQueueImprovementTasks — autonomous queuing gate', () => {describe('persistent mind — default-off CoS state integration (#5064)', () => {it('adds no cold-bootstrap provider work to a fresh CoS state', () => {expect(DEFAULT_STATE.persistentMind).toMatchObject({- schemaVersion: 1,+ schemaVersion: 2,+ mindId: 'cos-persistent-mind',enabled: false,started: false,status: 'disabled',diff --git a/server/services/persistentMindContext.js b/server/services/persistentMindContext.jsnew file mode 100644index 0000000000..d55b304a28--- /dev/null+++ b/server/services/persistentMindContext.js@@ -0,0 +1,248 @@+/**+ * Persistent-mind context rollups and explicit Brain promotion.+ *+ * Raw events remain in the bounded machine-local run-event ledger. Older+ * sealed ranges are represented by provenance-tagged rollups in a separate+ * machine-local cache, so assembling one turn never requires an unbounded JSONL+ * read. A corrupt/unreadable cache fails closed rather than becoming `[]` and+ * overwriting the only summaries of history that has left raw retention.+ */++import { join } from 'path';+import {+ PATHS,+ atomicWrite,+ readJSONFileStrict,+ sha256Text,+} from '../lib/fileUtils.js';+import { createFileWriteQueue } from '../lib/fileWriteQueue.js';+import {+ PERSISTENT_MIND_ID,+ PERSISTENT_MIND_ROLLUP_PROMPT_VERSION,+ PERSISTENT_MIND_TRAJECTORY_LIMITS,+ assemblePersistentMindContext,+ buildPersistentMindRollup,+ isStoredPersistentMindRollup,+} from '../lib/persistentMindTrajectory.js';+import {+ appendMindEvent,+ readPersistentMindHistory,+} from './agentRunEventLog.js';+import * as memoryBackend from './memoryBackend.js';++const ROLLUP_PATH = join(PATHS.cos, 'persistent-mind-rollups.json');+const ROLLUP_STORE_SCHEMA_VERSION = 1;+const queueRollupWrite = createFileWriteQueue();++const emptyStore = () => ({ schemaVersion: ROLLUP_STORE_SCHEMA_VERSION, rollups: [] });++async function loadRollupStore() {+ const { ok, value } = await readJSONFileStrict(ROLLUP_PATH, emptyStore());+ if (!ok) throw new Error('Persistent mind rollup cache is unreadable');+ if (!value || typeof value !== 'object' || Array.isArray(value)+ || value.schemaVersion !== ROLLUP_STORE_SCHEMA_VERSION || !Array.isArray(value.rollups)+ || value.rollups.some((rollup) => !isStoredPersistentMindRollup(rollup))) {+ throw new Error('Persistent mind rollup cache has an invalid shape');+ }+ return value;+}++export async function readPersistentMindRollups(mindId = PERSISTENT_MIND_ID) {+ const store = await loadRollupStore();+ return store.rollups+ .filter((rollup) => rollup.mindId === mindId)+ .sort((a, b) => a.source.fromSequence - b.source.fromSequence);+}++export function recordPersistentMindRollup(input) {+ const rollup = buildPersistentMindRollup(input);+ return queueRollupWrite(async () => {+ const store = await loadRollupStore();+ const ordered = [...store.rollups.filter((item) => item.id !== rollup.id), rollup]+ .sort((a, b) => a.source.fromSequence - b.source.fromSequence || a.source.toSequence - b.source.toSequence);+ const latestReadyByMind = new Map();+ for (const item of ordered.filter((candidate) => candidate.status === 'ready')) {+ const previous = latestReadyByMind.get(item.mindId);+ if (!previous || item.source.toSequence > previous.source.toSequence) {+ latestReadyByMind.set(item.mindId, item);+ }+ }+ const latestReadyIds = new Set([...latestReadyByMind.values()].map((item) => item.id));+ const tail = ordered+ .filter((item) => !latestReadyIds.has(item.id))+ .slice(-Math.max(0, PERSISTENT_MIND_TRAJECTORY_LIMITS.maxStoredRollups - latestReadyIds.size));+ const keptIds = new Set([...latestReadyIds, ...tail.map((item) => item.id)]);+ const rollups = ordered.filter((item) => keptIds.has(item.id));+ await atomicWrite(ROLLUP_PATH, { schemaVersion: ROLLUP_STORE_SCHEMA_VERSION, rollups });+ return rollup;+ });+}++const latestReadyRollup = (rollups, promptVersion) => rollups+ .filter((rollup) => rollup.status === 'ready' && rollup.provenance.promptVersion === promptVersion)+ .sort((a, b) => a.source.toSequence - b.source.toSequence)+ .at(-1) || null;++const summaryOutcome = (summarize, input) => Promise.resolve()+ .then(() => summarize(input))+ .then(+ (summary) => typeof summary === 'string'+ ? { ok: true, summary }+ : { ok: false, error: 'Persistent mind summarizer returned no summary string' },+ (error) => ({ ok: false, error: String(error?.message || error || 'Persistent mind summary failed').slice(0, 500) })+ );++/**+ * Assemble context and, when a summarizer is available, incrementally seal the+ * older range that just fell outside the recent verbatim window.+ */+export async function preparePersistentMindContext({+ mindId = PERSISTENT_MIND_ID,+ identity = '',+ maxChars,+ recentEventLimit = PERSISTENT_MIND_TRAJECTORY_LIMITS.recentContextEvents,+ promptVersion = PERSISTENT_MIND_ROLLUP_PROMPT_VERSION,+ providerId = null,+ model = null,+ summarize = null,+ forceSummary = false,+} = {}) {+ const history = await readPersistentMindHistory(mindId);+ let rollups = await readPersistentMindRollups(mindId);+ const older = history.slice(0, Math.max(0, history.length - Math.max(1, recentEventLimit)));++ if (older.length > 0 && typeof summarize === 'function') {+ const previous = latestReadyRollup(rollups, promptVersion);+ const coveredThrough = previous?.source.toSequence ?? -1;+ const rangeEvents = older.filter((event) => event.sequence > coveredThrough);+ if (rangeEvents.length > 0) {+ const source = {+ fromSequence: previous?.source.fromSequence ?? rangeEvents[0].sequence,+ toSequence: rangeEvents.at(-1).sequence,+ fromEventId: previous?.source.fromEventId ?? rangeEvents[0].eventId,+ toEventId: rangeEvents.at(-1).eventId,+ };+ const rollupId = `${mindId}:${source.fromSequence}-${source.toSequence}:v${promptVersion}`;+ const alreadyAttempted = rollups.some((rollup) => rollup.id === rollupId);+ if (forceSummary || !alreadyAttempted) {+ const outcome = await summaryOutcome(summarize, {+ mindId,+ source,+ events: rangeEvents,+ previousSummary: previous?.summary ?? null,+ previousProvenance: previous?.provenance ?? null,+ promptVersion,+ });+ const rollup = await recordPersistentMindRollup({+ id: rollupId,+ mindId,+ status: outcome.ok ? 'ready' : 'failed',+ summary: outcome.ok ? outcome.summary : null,+ error: outcome.ok ? null : outcome.error,+ source,+ providerId,+ model,+ promptVersion,+ });+ await appendMindEvent({+ kind: 'mind.summary',+ mindId,+ eventId: `mind-summary-${sha256Text(rollup.id).slice(0, 32)}`,+ data: {+ rollupId: rollup.id,+ status: rollup.status,+ fromSequence: source.fromSequence,+ toSequence: source.toSequence,+ providerId,+ model,+ promptVersion,+ summaryText: rollup.summary,+ error: rollup.error,+ },+ });+ rollups = await readPersistentMindRollups(mindId);+ }+ }+ }++ return assemblePersistentMindContext({+ mindId,+ identity,+ events: history,+ rollups,+ maxChars,+ recentEventLimit,+ promptVersion,+ });+}++/** Add an attributable comment/idea to the trajectory. */+export function appendPersistentMindAnnotation({+ id,+ mindId = PERSISTENT_MIND_ID,+ turnId = null,+ targetEventId = null,+ text,+ at,+} = {}) {+ if (typeof id !== 'string' || !id.trim() || typeof text !== 'string' || !text.trim()) {+ return Promise.resolve({ appended: false, error: 'Annotation id and text are required' });+ }+ return appendMindEvent({+ kind: 'mind.annotation.accepted',+ mindId,+ turnId,+ at,+ eventId: `mind-annotation:${id.trim()}`,+ data: {+ annotationId: id.trim(),+ targetEventId: typeof targetEventId === 'string' ? targetEventId : null,+ displayText: text.trim(),+ textChars: text.trim().length,+ },+ });+}++/**+ * Promote one user-approved fact into the existing Brain backend. Absence of an+ * explicit `approved: true` is a refusal, not a pending or empty memory.+ */+export async function promotePersistentMindMemory({+ approved,+ mindId = PERSISTENT_MIND_ID,+ turnId = null,+ sourceEventId = null,+ content,+ summary,+ type = 'fact',+ category = 'other',+ tags = [],+ memoryApi = memoryBackend,+} = {}) {+ if (approved !== true) return { success: false, error: 'Explicit user approval is required' };+ if (typeof content !== 'string' || !content.trim()) return { success: false, error: 'Memory content is required' };+ const memory = await memoryApi.createMemory({+ type,+ content: content.trim().slice(0, 10_240),+ 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',+ });+ await appendMindEvent({+ kind: 'mind.memory.promoted',+ mindId,+ turnId,+ eventId: `mind-memory:${memory.id}`,+ data: {+ memoryId: memory.id,+ sourceEventId,+ type,+ category,+ approved: true,+ },+ });+ return { success: true, memory };+}diff --git a/server/services/persistentMindContext.test.js b/server/services/persistentMindContext.test.jsnew file mode 100644index 0000000000..7ef142d060--- /dev/null+++ b/server/services/persistentMindContext.test.js@@ -0,0 +1,204 @@+import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';++const mock = vi.hoisted(() => ({+ history: [],+ appendMindEvent: vi.fn(async (event) => ({ appended: true, event })),+}));++const { CONTEXT_DIR } = await vi.hoisted(async () => {+ const { mkdtempSync: mk } = await import('fs');+ const { tmpdir: tmp } = await import('os');+ const { join: pathJoin } = await import('path');+ return { CONTEXT_DIR: mk(pathJoin(tmp(), 'portos-mind-context-')) };+});++vi.mock('../lib/fileUtils.js', async (importOriginal) => {+ const actual = await importOriginal();+ return { ...actual, PATHS: { ...actual.PATHS, cos: CONTEXT_DIR } };+});++vi.mock('./agentRunEventLog.js', () => ({+ appendMindEvent: (...args) => mock.appendMindEvent(...args),+ readPersistentMindHistory: vi.fn(async () => mock.history),+}));++const {+ appendPersistentMindAnnotation,+ preparePersistentMindContext,+ promotePersistentMindMemory,+ readPersistentMindRollups,+} = await import('./persistentMindContext.js');++const ROLLUPS = join(CONTEXT_DIR, 'persistent-mind-rollups.json');++const event = (sequence, kind = 'mind.message.accepted') => ({+ schemaVersion: 1,+ eventId: `event-${sequence}`,+ kind,+ runId: null,+ agentId: null,+ taskId: null,+ mindId: 'cos-persistent-mind',+ turnId: kind === 'mind.message.accepted' ? null : 'turn-1',+ sequence,+ at: `2026-08-25T12:00:0${sequence}.000Z`,+ data: { displayText: `Visible event ${sequence}` },+});++beforeEach(() => {+ if (existsSync(ROLLUPS)) rmSync(ROLLUPS);+ mkdirSync(CONTEXT_DIR, { recursive: true });+ mock.history = [];+ mock.appendMindEvent.mockClear();+});++afterAll(() => rmSync(CONTEXT_DIR, { recursive: true, force: true }));++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')];+ const summarize = vi.fn(async () => 'The older events established a useful decision.');++ const context = await preparePersistentMindContext({+ identity: 'Stable example identity.',+ recentEventLimit: 1,+ maxChars: 1_500,+ providerId: 'example-provider',+ model: 'example-model',+ summarize,+ });+ const [rollup] = await readPersistentMindRollups();++ expect(summarize).toHaveBeenCalledWith(expect.objectContaining({+ mindId: 'cos-persistent-mind',+ source: expect.objectContaining({ fromSequence: 1, toSequence: 2 }),+ events: mock.history.slice(0, 2),+ promptVersion: 1,+ }));+ expect(rollup).toMatchObject({+ status: 'ready',+ summary: 'The older events established a useful decision.',+ source: { fromSequence: 1, toSequence: 2, fromEventId: 'event-1', toEventId: 'event-2' },+ provenance: { providerId: 'example-provider', model: 'example-model', promptVersion: 1 },+ });+ expect(context.summaryState).toBe('ready');+ expect(context.chars).toBeLessThanOrEqual(1_500);+ expect(context.text).toContain('The older events established a useful decision.');+ expect(mock.appendMindEvent).toHaveBeenCalledWith(expect.objectContaining({+ kind: 'mind.summary',+ data: expect.objectContaining({ status: 'ready', fromSequence: 1, toSequence: 2 }),+ }));+ });++ it('keeps a failed summary explicit without erasing raw history or retrying silently', async () => {+ mock.history = [event(1), event(2), event(3)];+ const summarize = vi.fn(async () => { throw new Error('summary provider unavailable'); });++ const first = await preparePersistentMindContext({ recentEventLimit: 1, summarize });+ const second = await preparePersistentMindContext({ recentEventLimit: 1, summarize });+ const [rollup] = await readPersistentMindRollups();++ expect(first.summaryState).toBe('failed');+ expect(second.summaryState).toBe('failed');+ expect(summarize).toHaveBeenCalledTimes(1);+ expect(mock.history).toHaveLength(3);+ expect(rollup).toMatchObject({ status: 'failed', summary: null, error: 'summary provider unavailable' });+ });++ it('builds cumulative rollups so a bounded cache retains the full summarized life', async () => {+ mock.history = [event(1), event(2), event(3)];+ const summarize = vi.fn()+ .mockResolvedValueOnce('First cumulative summary.')+ .mockResolvedValueOnce('Updated cumulative summary.');++ await preparePersistentMindContext({ recentEventLimit: 1, summarize });+ mock.history = [...mock.history, event(4)];+ const context = await preparePersistentMindContext({ recentEventLimit: 1, summarize });+ const rollups = await readPersistentMindRollups();++ expect(summarize).toHaveBeenLastCalledWith(expect.objectContaining({+ source: expect.objectContaining({ fromSequence: 1, toSequence: 3 }),+ events: [mock.history[2]],+ previousSummary: 'First cumulative summary.',+ previousProvenance: expect.objectContaining({ promptVersion: 1 }),+ }));+ expect(rollups.at(-1)).toMatchObject({+ status: 'ready',+ summary: 'Updated cumulative summary.',+ source: { fromSequence: 1, toSequence: 3, fromEventId: 'event-1', toEventId: 'event-3' },+ });+ expect(context.summaryState).toBe('ready');+ expect(context.text).toContain('Updated cumulative summary.');+ expect(context.text).not.toContain('First cumulative summary.');+ });++ it('fails closed on a corrupt cache instead of replacing it with empty state', async () => {+ writeFileSync(ROLLUPS, '{broken');++ await expect(readPersistentMindRollups()).rejects.toThrow('rollup cache is unreadable');+ await expect(preparePersistentMindContext()).rejects.toThrow('rollup cache is unreadable');+ expect(readFileSync(ROLLUPS, 'utf8')).toBe('{broken');+ });+});++describe('trajectory annotations and Brain promotion', () => {+ it('keeps comments attributable to their turn and target event', async () => {+ await expect(appendPersistentMindAnnotation({+ id: 'annotation-1',+ turnId: 'turn-1',+ targetEventId: 'event-2',+ text: 'Use the bounded variant.',+ at: '2026-08-25T12:30:00.000Z',+ })).resolves.toMatchObject({ appended: true });++ expect(mock.appendMindEvent).toHaveBeenCalledWith(expect.objectContaining({+ kind: 'mind.annotation.accepted',+ turnId: 'turn-1',+ data: expect.objectContaining({+ annotationId: 'annotation-1',+ targetEventId: 'event-2',+ displayText: 'Use the bounded variant.',+ }),+ }));+ });++ it('requires explicit approval before creating a Brain memory', async () => {+ const memoryApi = { createMemory: vi.fn(async (input) => ({ id: 'memory-1', ...input })) };++ await expect(promotePersistentMindMemory({+ approved: false,+ content: 'Remember this.',+ memoryApi,+ })).resolves.toEqual({ success: false, error: 'Explicit user approval is required' });+ expect(memoryApi.createMemory).not.toHaveBeenCalled();+ expect(mock.appendMindEvent).not.toHaveBeenCalled();++ const promoted = await promotePersistentMindMemory({+ approved: true,+ turnId: 'turn-1',+ sourceEventId: 'event-2',+ content: 'Remember this user-approved fact.',+ summary: 'Approved fact',+ tags: ['approved', 'approved'],+ memoryApi,+ });++ expect(promoted).toMatchObject({ success: true, memory: { id: 'memory-1', status: 'active' } });+ expect(memoryApi.createMemory).toHaveBeenCalledWith(expect.objectContaining({+ content: 'Remember this user-approved fact.',+ summary: 'Approved fact',+ tags: ['approved'],+ sourceTaskId: 'turn-1',+ sourceAgentId: 'cos-persistent-mind',+ status: 'active',+ }));+ expect(mock.appendMindEvent).toHaveBeenCalledWith(expect.objectContaining({+ kind: 'mind.memory.promoted',+ turnId: 'turn-1',+ data: expect.objectContaining({ memoryId: 'memory-1', sourceEventId: 'event-2', approved: true }),+ }));+ });+});diff --git a/server/services/persistentMindSupervisor.js b/server/services/persistentMindSupervisor.jsindex cb09b6e04c..9be29c3ead 100644--- a/server/services/persistentMindSupervisor.js+++ b/server/services/persistentMindSupervisor.js@@ -27,6 +27,8 @@ import { schedule, cancel } from './eventScheduler.js';import { getDomainBudgetStatus, recordDomainUsage } from './domainUsage.js';import { acquireLocalEndpointProviderSlot } from './cosLocalEndpointSlots.js';import { acquireCosActionReservation, acquireCosGlobalSlot } from './cosAdmissionReservations.js';+import { appendMindEvent } from './agentRunEventLog.js';+import { preparePersistentMindContext } from './persistentMindContext.js';export const PERSISTENT_MIND_WAKE_EVENT_ID = 'cos-persistent-mind-wake';export const PERSISTENT_MIND_WATCHDOG_EVENT_ID = 'cos-persistent-mind-watchdog';@@ -148,15 +150,22 @@ async function interruptActiveTurn(reason, status, { retry = false, expectedTurn? new Date(Date.now() + persistentMindBackoffMs(failureCount)).toISOString(): null,},- value: interrupted,+ value: { interrupted, turnId: mind.activeTurn?.id || null, mindId: mind.mindId },};});- if (result.value) {+ if (result.value?.interrupted) {runtimeGeneration += 1;activeAbortController?.abort(reason);+ await appendMindEvent({+ kind: status === 'paused' ? 'mind.paused' : 'mind.failed',+ mindId: result.value.mindId,+ turnId: result.value.turnId,+ eventId: `mind-${status}:${result.value.turnId}`,+ data: { status, error: reason },+ });}emitMindStatus(result.state);- return { state: result.state, interrupted: result.value === true };+ return { state: result.state, interrupted: result.value?.interrupted === true };}async function parkActiveTurn(turnId, reason, status = 'waiting', retryAt = null) {@@ -176,6 +185,13 @@ async function parkActiveTurn(turnId, reason, status = 'waiting', retryAt = null},};});+ await appendMindEvent({+ kind: 'mind.failed',+ mindId: result.state.mindId,+ turnId,+ eventId: `mind-failed:${turnId}:${status}`,+ data: { status, error: reason, retryAt },+ });emitMindStatus(result.state);return result.state;}@@ -209,7 +225,23 @@ async function claimNextTurn() {value: activeTurn,};});- if (result.value) emitMindStatus(result.state);+ if (result.value) {+ await appendMindEvent({+ kind: 'mind.wake',+ mindId: result.state.mindId,+ turnId: result.value.id,+ eventId: `mind-wake:${result.value.id}`,+ at: result.value.startedAt,+ data: {+ status: result.state.status,+ wakeKind: result.value.wake.kind,+ wakeId: result.value.wake.id || null,+ messageId: result.value.wake.message?.id || null,+ reason: result.value.wake.reason || null,+ },+ });+ emitMindStatus(result.state);+ }return result.value;}@@ -297,6 +329,20 @@ async function completeTurn(turnId, result, generation) {};});if (!updated.value) return;+ await appendMindEvent({+ kind: 'mind.turn.completed',+ mindId: updated.state.mindId,+ turnId,+ eventId: `mind-turn-completed:${turnId}`,+ at: completedAt,+ data: {+ status: updated.state.status,+ providerId: result?.providerId || null,+ model: result?.model || null,+ effort: result?.effort || null,+ summaryText: typeof result?.summary === 'string' ? result.summary : null,+ },+ });emitMindStatus(updated.state);cosEvents.emit('persistent-mind:turn-completed', {turnId,@@ -424,6 +470,35 @@ async function runOnePersistentMindTurn() {await recordTurnProfile(turn.id, prepared);if (!await turnCanContinue(turn.id, generation, controller.signal)) return;+ const context = await preparePersistentMindContext({+ mindId: mind.mindId,+ identity: turnAdapter.identity || 'One supervised persistent Chief of Staff mind.',+ providerId: prepared.provider.id,+ model: prepared.model || null,+ summarize: typeof turnAdapter.summarize === 'function'+ ? (input) => turnAdapter.summarize({+ ...input,+ provider: prepared.provider,+ model: prepared.model || null,+ effort: prepared.effort || null,+ signal: controller.signal,+ })+ : null,+ });+ await appendMindEvent({+ kind: 'mind.model.request',+ mindId: mind.mindId,+ turnId: turn.id,+ eventId: `mind-model-request:${turn.id}`,+ data: {+ providerId: prepared.provider.id,+ model: prepared.model || null,+ effort: prepared.effort || null,+ contextChars: context.chars,+ contextSummaryState: context.summaryState,+ },+ });+const latestRoot = await loadState();const slot = await acquireLocalEndpointProviderSlot(prepared.provider, latestRoot.agents, turn.id);if (!slot.ok) {@@ -441,8 +516,39 @@ async function runOnePersistentMindTurn() {effort: prepared.effort || null,signal: controller.signal,heartbeat: () => heartbeat(turn.id, generation),+ context,+ recordCapabilityEvent: ({ kind, id, data } = {}) => {+ const eventKind = kind === 'result' ? 'mind.capability.result' : 'mind.capability.request';+ const capabilityId = typeof id === 'string' && id ? id : randomUUID();+ return appendMindEvent({+ kind: eventKind,+ mindId: mind.mindId,+ turnId: turn.id,+ eventId: `mind-capability:${turn.id}:${capabilityId}:${kind === 'result' ? 'result' : 'request'}`,+ data: { capabilityId, ...(data && typeof data === 'object' ? data : {}) },+ });+ },});- await completeTurn(turn.id, { ...result, providerId: prepared.provider.id }, generation);+ await appendMindEvent({+ kind: 'mind.model.result',+ mindId: mind.mindId,+ turnId: turn.id,+ eventId: `mind-model-result:${turn.id}`,+ data: {+ providerId: prepared.provider.id,+ model: prepared.model || null,+ effort: prepared.effort || null,+ summaryText: typeof result?.summary === 'string' ? result.summary : null,+ responseChars: typeof result?.output === 'string' ? result.output.length : null,+ success: true,+ },+ });+ await completeTurn(turn.id, {+ ...result,+ providerId: prepared.provider.id,+ model: prepared.model || null,+ effort: prepared.effort || null,+ }, generation);} catch (error) {if (generation === runtimeGeneration) {const message = controller.signal.aborted@@ -495,6 +601,8 @@ export async function setPersistentMindEnabled(enabled) {cancel(PERSISTENT_MIND_WATCHDOG_EVENT_ID);}const result = await mutateMindState((mind) => {+ const changedToDisabled = !enabled && (mind.enabled || Boolean(mind.activeTurn));+ const interruptedTurnId = !enabled ? mind.activeTurn?.id || null : null;let next = mind;if (!enabled && mind.activeTurn) next = requeuePersistentMindWake(next, mind.activeTurn.wake);return {@@ -507,8 +615,18 @@ export async function setPersistentMindEnabled(enabled) {pauseReason: null,nextEligibleWakeAt: enabled ? next.nextEligibleWakeAt : null,},+ value: { changedToDisabled, interruptedTurnId, mindId: mind.mindId },};});+ if (result.value.changedToDisabled) {+ await appendMindEvent({+ kind: 'mind.paused',+ mindId: result.value.mindId,+ turnId: result.value.interruptedTurnId,+ eventId: `mind-disabled:${result.value.interruptedTurnId || randomUUID()}`,+ data: { status: 'disabled', error: 'Persistent mind disabled' },+ });+ }emitMindStatus(result.state);return result.state;}@@ -538,7 +656,15 @@ export async function startPersistentMind() {}export async function pausePersistentMind(reason = 'Paused by user') {- const { state } = await interruptActiveTurn(reason, 'paused');+ const { state, interrupted } = await interruptActiveTurn(reason, 'paused');+ if (!interrupted) {+ await appendMindEvent({+ kind: 'mind.paused',+ mindId: state.mindId,+ eventId: `mind-paused:${randomUUID()}`,+ data: { status: 'paused', error: reason },+ });+ }cancel(PERSISTENT_MIND_WAKE_EVENT_ID);return { success: true, state };}@@ -573,6 +699,8 @@ export async function stopPersistentMind() {cancel(PERSISTENT_MIND_WAKE_EVENT_ID);cancel(PERSISTENT_MIND_WATCHDOG_EVENT_ID);const result = await mutateMindState((mind) => {+ const wasStarted = mind.started;+ const interruptedTurnId = mind.activeTurn?.id || null;let next = mind;if (mind.activeTurn) next = requeuePersistentMindWake(next, mind.activeTurn.wake);return {@@ -584,8 +712,18 @@ export async function stopPersistentMind() {pauseReason: null,nextEligibleWakeAt: null,},+ value: { wasStarted, interruptedTurnId, mindId: mind.mindId },};});+ if (result.value.wasStarted || result.value.interruptedTurnId) {+ await appendMindEvent({+ kind: 'mind.paused',+ mindId: result.value.mindId,+ turnId: result.value.interruptedTurnId,+ eventId: `mind-stopped:${result.value.interruptedTurnId || randomUUID()}`,+ data: { status: result.state.status, error: 'Persistent mind stopped' },+ });+ }emitMindStatus(result.state);return { success: true };}@@ -612,6 +750,22 @@ export async function enqueuePersistentMindMessage({ id = randomUUID(), text, crvalue: { success: true, duplicate: false, messageId: message.id },};});+ if (result.value.success) {+ // Retry the stable event id even when the mutable queue already saw this+ // message. The ledger deduplicates a healthy first append; if the first+ // append was dropped, the caller's idempotent retry repairs the trajectory.+ await appendMindEvent({+ kind: 'mind.message.accepted',+ mindId: result.state.mindId,+ eventId: `mind-message:${message.id}`,+ at: message.createdAt,+ data: {+ messageId: message.id,+ displayText: message.text,+ textChars: message.text.length,+ },+ });+ }if (result.value.success && result.state.started) await scheduleNextWake();emitMindStatus(result.state);return result.value;@@ -667,6 +821,7 @@ export async function initializePersistentMindSupervisor() {const recovered = await mutateMindState((mind) => {if (!mind.enabled || !mind.started) return { mind };let next = mind;+ const orphanedTurnId = mind.activeTurn?.id || null;if (mind.activeTurn) {next = requeuePersistentMindWake(next, mind.activeTurn.wake);const failureCount = next.failureCount + 1;@@ -683,8 +838,20 @@ export async function initializePersistentMindSupervisor() {const base = next.lastCompletedAt ? Date.parse(next.lastCompletedAt) : Date.now();next = { ...next, selfWake: quietSelfWake(next.lastCompletedTurnId || 'restart', base + PERSISTENT_MIND_LIMITS.MAX_QUIET_MS) };}- return { mind: next };+ return { mind: next, value: { orphanedTurnId, mindId: mind.mindId } };});+ if (recovered.value?.orphanedTurnId) {+ await appendMindEvent({+ kind: 'mind.failed',+ mindId: recovered.value.mindId,+ turnId: recovered.value.orphanedTurnId,+ eventId: `mind-restart-recovered:${recovered.value.orphanedTurnId}`,+ data: {+ status: 'interrupted',+ error: 'Recovered an orphaned persistent mind turn after restart',+ },+ });+ }if (recovered.state.enabled && recovered.state.started) {armWatchdog();await scheduleNextWake();diff --git a/server/services/persistentMindSupervisor.test.js b/server/services/persistentMindSupervisor.test.jsindex 9bd7096c53..af153df91b 100644--- a/server/services/persistentMindSupervisor.test.js+++ b/server/services/persistentMindSupervisor.test.js@@ -13,6 +13,8 @@ const mock = vi.hoisted(() => ({budget: { withinBudget: true, exceeded: null },recordUsage: vi.fn(async () => {}),acquireSlot: vi.fn(async () => ({ ok: true, release: vi.fn() })),+ appendMindEvent: vi.fn(async (event) => ({ appended: true, event })),+ prepareContext: vi.fn(async () => ({ text: 'bounded context', chars: 15, summaryState: 'not-needed' })),daemonRunning: true,}));@@ -45,6 +47,14 @@ vi.mock('./cosLocalEndpointSlots.js', () => ({acquireLocalEndpointProviderSlot: (...args) => mock.acquireSlot(...args),}));+vi.mock('./agentRunEventLog.js', () => ({+ appendMindEvent: (...args) => mock.appendMindEvent(...args),+}));++vi.mock('./persistentMindContext.js', () => ({+ preparePersistentMindContext: (...args) => mock.prepareContext(...args),+}));+const supervisor = await import('./persistentMindSupervisor.js');const makeRoot = () => ({@@ -71,6 +81,8 @@ describe('persistent mind supervisor', () => {mock.recordUsage.mockClear();mock.acquireSlot.mockReset();mock.acquireSlot.mockResolvedValue({ ok: true, release: vi.fn() });+ mock.appendMindEvent.mockClear();+ mock.prepareContext.mockClear();__resetCosAdmissionReservations();supervisor.__resetPersistentMindSupervisorForTests();});@@ -118,6 +130,20 @@ describe('persistent mind supervisor', () => {pending.resolve({});await Promise.all([firstDrain, secondDrain]);+ expect(mock.prepareContext).toHaveBeenCalledWith(expect.objectContaining({+ mindId: 'cos-persistent-mind',+ providerId: 'example-cloud',+ model: 'example-model',+ }));+ expect(run.mock.calls[0][0].context).toMatchObject({ text: 'bounded context', summaryState: 'not-needed' });+ expect(mock.appendMindEvent.mock.calls.map(([event]) => event.kind)).toEqual(expect.arrayContaining([+ 'mind.message.accepted',+ 'mind.wake',+ 'mind.model.request',+ 'mind.model.result',+ 'mind.turn.completed',+ ]));+expect(prepare).toHaveBeenCalledTimes(1);expect(mock.acquireSlot).toHaveBeenCalledTimes(1);expect(mock.root.persistentMind.activeTurn).toBeNull();@@ -149,6 +175,34 @@ describe('persistent mind supervisor', () => {expect(recovered.queuedMessages).toEqual([message]);expect(recovered.nextEligibleWakeAt).not.toBeNull();expect(mock.scheduled.has(supervisor.PERSISTENT_MIND_WATCHDOG_EVENT_ID)).toBe(true);+ expect(mock.appendMindEvent).toHaveBeenCalledWith(expect.objectContaining({+ kind: 'mind.failed',+ turnId: 'turn-orphan',+ data: expect.objectContaining({ status: 'interrupted' }),+ }));+ });++ it('records pause, stop, and disable boundaries even without an active provider turn', async () => {+ await supervisor.setPersistentMindEnabled(true);+ await supervisor.startPersistentMind();+ await supervisor.pausePersistentMind('Pause for inspection');+ expect(mock.appendMindEvent).toHaveBeenLastCalledWith(expect.objectContaining({+ kind: 'mind.paused',+ data: expect.objectContaining({ status: 'paused', error: 'Pause for inspection' }),+ }));++ await supervisor.resumePersistentMind();+ await supervisor.stopPersistentMind();+ expect(mock.appendMindEvent).toHaveBeenLastCalledWith(expect.objectContaining({+ kind: 'mind.paused',+ data: expect.objectContaining({ status: 'idle', error: 'Persistent mind stopped' }),+ }));++ await supervisor.setPersistentMindEnabled(false);+ expect(mock.appendMindEvent).toHaveBeenLastCalledWith(expect.objectContaining({+ kind: 'mind.paused',+ data: expect.objectContaining({ status: 'disabled', error: 'Persistent mind disabled' }),+ }));});it('requeues a message and degrades visibly when the pinned provider is unavailable', async () => {