Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: isolate persistent mind retention and accounting (#5082)

[._.]/ Adam Eivy50b98b096edb
diff --git a/docs/STORAGE.md b/docs/STORAGE.md
index 89acbc81c1..3238edf617 100644
--- a/docs/STORAGE.md
+++ b/docs/STORAGE.md
@@ -101,7 +101,7 @@ PostgreSQL is a **required** install/runtime dependency (see [Backup & Restore](
- Media job queue — runtime queue state can stay file-backed short term, but **job history and artifact lineage are `db-primary`** and should move to the DB.
- Browser CDP profile / downloads — `data/browser-profile/`, `data/browser-downloads/` — cache, non-overridable backup excludes.
- Brain parity audit results — `data/brain_parity_reports.json` (`server/services/brainParity.js`, #4519). The last record-level brain-parity report per peer, keyed by peer `instanceId` (the same key `data/instances_sync_cursors.json` uses). `ephemeral-file` because it is a point-in-time *observation* about two installs, fully regenerable by re-running the audit, and stale the moment either side syncs — the durable state it describes lives in the brain stores. **Intentionally machine-local — never federated**: it is this install's view of a peer, and each peer computes its own. No sync cursor, no tombstone, no migration (an absent file reads as "nothing audited yet"). Per-type record lists are capped at 25 ids with a `truncated` flag so a badly diverged install can't grow the file without bound.
-- CoS run event ledger — `data/cos/run-events.jsonl` + one retained archive generation `run-events.1.jsonl` (`server/services/agentRunEventLog.js`, #4540). The ordered, append-only trace of how a CoS agent run reached its current state: spawn, handoff to/from the CoS Runner, first output, PTY reconnect, pause/resume, interruption, PR-claim verification, orphan reap, runner re-adoption, finalization, and the ledger-driven close of a run record left open (`run.reconciled`, `server/services/agentRunReconciler.js`). `ephemeral-file` because the DURABLE record of a run is still `data/runs/{id}/metadata.json` — this is a regenerable-by-observation diagnostic over it, with no cross-record queries, no relationships, and no sync cursor; the projection that derives current status is a pure fold (`server/lib/agentRunEvents.js`), so losing the ledger costs post-mortem detail and nothing else. **Intentionally machine-local — never federated**: every line describes a process on THIS box, so a peer would inherit a trace of runs that never existed there. No sync cursor, no tombstone, no `PORTOS_SCHEMA_VERSIONS` entry. Bounded on TWO axes, because neither alone is a retention policy. A COUNT: the active generation rotates at 5000 events and exactly one archive is kept, so the ledger is capped at ~2×5000 events forever with no cleanup job. And an AGE (30 days), because the count alone 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 of every read (so the bound holds continuously) and swept off disk on a throttled prune (so the files actually shrink). No migration and no `data.reference/` seed: an absent file reads as an empty ledger. Payloads are redacted at APPEND time (prompt/description/output/result keys dropped to a `{ redacted, chars }` stub, home-dir prefix scrubbed, string/array/key/depth capped), so no reader has to re-redact. Backed up with the rest of `data/cos/` — it is small, bounded, and the thing you most want after the crash you are debugging.
+- CoS event ledgers — ordinary diagnostics use `data/cos/run-events.jsonl` + `run-events.1.jsonl`; persistent-mind trajectory uses the separate `mind-events.jsonl` + `mind-events.1.jsonl` pair (`server/services/agentRunEventLog.js`, #4540, #5082). Both are append-only, machine-local `ephemeral-file` replay aids with no federation cursor, tombstone, or `PORTOS_SCHEMA_VERSIONS` entry. The durable ordinary run record remains `data/runs/{id}/metadata.json`; mind rollups remain in their own bounded cache. Ordinary generations rotate at 5000 events and additionally expire after 30 days. Mind generations rotate at 10000 events without an age cutoff so a stopped mind keeps its unsummarized window, while high-volume mind chatter cannot evict ordinary run diagnostics. Migration 301 moves existing `mind.*` lines out of the shared files and stamps predecessor sequence provenance used to distinguish a legitimate timestamp jump from lost retained events. Payloads are redacted at append time, and both bounded pairs are backed up with the rest of `data/cos/`.
- Remote-API metadata cache — `data/cache/huggingface-repos.json` (`server/services/huggingFaceRepoCache.js`). Hugging Face per-repo records (file sizes, native context window) backing the local-LLM catalog's quant pickers. `ephemeral-file` rather than `db-primary` because it is a pure projection of someone else's API with no queries, no relationships, and no sync cursor — and because it is *machine-local by construction*: it exists to spare THIS install's cold-start requests, so federating it would be pure noise. Long TTL (7 days) since published GGUF file sizes are immutable, but bounded because a repo can gain a new quant. Non-overridable backup exclude — regenerable on demand, and stale by restore time anyway. Purgeable from Data Manager (`cache` category).
- Rapid Reader's Accelerando source cache — `data/cache/accelerando.html` (`server/services/rapidReader.js`). The official author-hosted HTML edition is fetched only when the user asks to load it, then retained locally for repeat and offline reads. `ephemeral-file` rather than `db-primary`: it is a machine-local copy of a separately licensed remote work, has no PortOS records or queries, and can be re-downloaded or purged without data loss. It is not bundled, federated, or backed up; Data Manager purges it with the `cache` category.
diff --git a/scripts/migrations/301-split-persistent-mind-ledger.js b/scripts/migrations/301-split-persistent-mind-ledger.js
new file mode 100644
index 0000000000..e1c73c4eab
--- /dev/null
+++ b/scripts/migrations/301-split-persistent-mind-ledger.js
@@ -0,0 +1,83 @@
+/**
+ * Move persistent-mind trajectory events out of the ordinary CoS diagnostic
+ * ledger. The two streams have different retention contracts and must not
+ * consume each other's count budget.
+ */
+
+import { readFile } from 'fs/promises';
+import { join } from 'path';
+import { atomicWrite } from '../../server/lib/fileUtils.js';
+import { isPersistentMindEventKind } from '../../server/lib/persistentMindTrajectory.js';
+
+const readOptional = (path) => readFile(path, 'utf8').catch((error) => {
+ if (error.code === 'ENOENT') return '';
+ throw error;
+});
+
+const parseLines = (raw) => raw.split('\n').filter(Boolean).map((line) => {
+ try { return { line, event: JSON.parse(line) }; } catch { return { line, event: null }; }
+});
+
+const serialize = (entries) => entries.length
+ ? `${entries.map(({ event, line }) => event ? JSON.stringify(event) : line).join('\n')}\n`
+ : '';
+
+export function splitPersistentMindLedger({ runArchive = '', runActive = '', mindArchive = '', mindActive = '' } = {}) {
+ const splitSource = (raw) => parseLines(raw).reduce((result, entry) => {
+ const bucket = entry.event && isPersistentMindEventKind(entry.event.kind) ? result.mind : result.ordinary;
+ bucket.push(entry);
+ return result;
+ }, { ordinary: [], mind: [] });
+ const archive = splitSource(runArchive);
+ const active = splitSource(runActive);
+ const existingArchive = parseLines(mindArchive).filter(({ event }) => event && isPersistentMindEventKind(event.kind));
+ const existingActive = parseLines(mindActive).filter(({ event }) => event && isPersistentMindEventKind(event.kind));
+ const seen = new Set();
+ const lastSequence = new Map();
+ const prepareMind = (entries) => entries.filter(({ event }) => {
+ if (!event?.eventId || seen.has(event.eventId)) return false;
+ seen.add(event.eventId);
+ return true;
+ }).map(({ event }) => {
+ const previous = lastSequence.get(event.mindId) ?? null;
+ const data = event.data && typeof event.data === 'object' && !Array.isArray(event.data) ? event.data : {};
+ const annotated = Object.hasOwn(data, 'previousSequence')
+ ? event
+ : { ...event, data: { ...data, previousSequence: previous } };
+ if (event.mindId && Number.isSafeInteger(event.sequence)) lastSequence.set(event.mindId, event.sequence);
+ return { event: annotated };
+ });
+ const preparedArchive = prepareMind([...existingArchive, ...archive.mind]);
+ const preparedActive = prepareMind([...existingActive, ...active.mind]);
+ return {
+ runArchive: serialize(archive.ordinary),
+ runActive: serialize(active.ordinary),
+ mindArchive: serialize(preparedArchive),
+ mindActive: serialize(preparedActive),
+ moved: archive.mind.length + active.mind.length,
+ };
+}
+
+export default {
+ async up({ rootDir }) {
+ const cosDir = join(rootDir, 'data', 'cos');
+ const paths = {
+ runArchive: join(cosDir, 'run-events.1.jsonl'),
+ runActive: join(cosDir, 'run-events.jsonl'),
+ mindArchive: join(cosDir, 'mind-events.1.jsonl'),
+ mindActive: join(cosDir, 'mind-events.jsonl'),
+ };
+ const values = Object.fromEntries(await Promise.all(Object.entries(paths).map(async ([key, path]) => [key, await readOptional(path)])));
+ const result = splitPersistentMindLedger(values);
+ if (result.moved === 0) return { updated: 0, reason: 'no-mind-events' };
+ // Destination-first is the crash-recovery contract. If a later source
+ // rewrite fails, the old line remains and a retry dedupes it against the
+ // already-written destination. Source-first could remove the only copy.
+ await atomicWrite(paths.mindArchive, result.mindArchive);
+ await atomicWrite(paths.mindActive, result.mindActive);
+ await atomicWrite(paths.runArchive, result.runArchive);
+ await atomicWrite(paths.runActive, result.runActive);
+ console.log(`🧠 migration 301: moved ${result.moved} persistent mind event(s) into their own ledger`);
+ return { updated: result.moved };
+ },
+};
diff --git a/scripts/migrations/301-split-persistent-mind-ledger.test.js b/scripts/migrations/301-split-persistent-mind-ledger.test.js
new file mode 100644
index 0000000000..9dc133c26f
--- /dev/null
+++ b/scripts/migrations/301-split-persistent-mind-ledger.test.js
@@ -0,0 +1,37 @@
+import { beforeEach, afterEach, describe, expect, it } from 'vitest';
+import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import migration, { splitPersistentMindLedger } from './301-split-persistent-mind-ledger.js';
+
+const line = (value) => `${JSON.stringify(value)}\n`;
+
+describe('migration 301 — split persistent mind ledger', () => {
+ let rootDir;
+ beforeEach(() => {
+ rootDir = mkdtempSync(join(tmpdir(), 'migration-301-'));
+ mkdirSync(join(rootDir, 'data', 'cos'), { recursive: true });
+ });
+ afterEach(() => rmSync(rootDir, { recursive: true, force: true }));
+
+ it('moves mind events, preserves ordinary and corrupt lines, and records predecessor provenance', () => {
+ const result = splitPersistentMindLedger({
+ runArchive: `${line({ eventId: 'run-1', kind: 'run.spawned' })}${line({ eventId: 'mind-1', kind: 'mind.wake', mindId: 'mind', sequence: 100, data: {} })}`,
+ runActive: `not-json\n${line({ eventId: 'mind-2', kind: 'mind.turn.completed', mindId: 'mind', sequence: 9000, data: {} })}`,
+ });
+ expect(result.runArchive).toContain('run.spawned');
+ expect(result.runActive).toBe('not-json\n');
+ expect(result.mindArchive).toContain('"previousSequence":null');
+ expect(result.mindActive).toContain('"previousSequence":100');
+ expect(result.moved).toBe(2);
+ });
+
+ it('writes the split idempotently through the migration entrypoint', async () => {
+ const cosDir = join(rootDir, 'data', 'cos');
+ writeFileSync(join(cosDir, 'run-events.jsonl'), `${line({ eventId: 'run-1', kind: 'run.spawned' })}${line({ eventId: 'mind-1', kind: 'mind.wake', mindId: 'mind', sequence: 1, data: {} })}`);
+ await expect(migration.up({ rootDir })).resolves.toEqual({ updated: 1 });
+ expect(readFileSync(join(cosDir, 'run-events.jsonl'), 'utf8')).not.toContain('mind.wake');
+ expect(readFileSync(join(cosDir, 'mind-events.jsonl'), 'utf8')).toContain('mind.wake');
+ await expect(migration.up({ rootDir })).resolves.toMatchObject({ updated: 0 });
+ });
+});
diff --git a/server/lib/agentRunEvents.js b/server/lib/agentRunEvents.js
index 168d6d1ca3..4e7db7d867 100644
--- a/server/lib/agentRunEvents.js
+++ b/server/lib/agentRunEvents.js
@@ -46,6 +46,10 @@ import {
*
* 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.
+ * A rollback to a build predating persistent-mind fields can drop `mind.*`
+ * lines because that older strict envelope cannot validate them. That accepted
+ * machine-local diagnostic loss is preferable to weakening today's typed
+ * identity or pretending this non-authoritative replay aid is sync-versioned.
*/
export const AGENT_RUN_EVENT_SCHEMA_VERSION = 1;
diff --git a/server/lib/persistentMindTrajectory.js b/server/lib/persistentMindTrajectory.js
index 11dc176390..e82ab5cb73 100644
--- a/server/lib/persistentMindTrajectory.js
+++ b/server/lib/persistentMindTrajectory.js
@@ -285,6 +285,7 @@ export function assemblePersistentMindContext({
maxChars = PERSISTENT_MIND_TRAJECTORY_LIMITS.maxContextChars,
recentEventLimit = PERSISTENT_MIND_TRAJECTORY_LIMITS.recentContextEvents,
promptVersion = PERSISTENT_MIND_ROLLUP_PROMPT_VERSION,
+ coverageGap = null,
} = {}) {
const cap = Math.max(1_000, Math.min(Number(maxChars) || PERSISTENT_MIND_TRAJECTORY_LIMITS.maxContextChars, 100_000));
const ordered = orderedMindEvents(events, mindId);
@@ -314,7 +315,9 @@ export function assemblePersistentMindContext({
let summaryState = !hasOmittedHistory
? (ordered.length === 0 ? 'empty' : 'not-needed')
: 'unavailable';
- if (hasOmittedHistory) {
+ if (coverageGap) {
+ summaryState = 'gap';
+ } else 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) => (
@@ -380,6 +383,7 @@ export function assemblePersistentMindContext({
chars: text.length,
approximateTokens: Math.ceil(text.length / 4),
summaryState,
+ coverageGap,
omittedRange: hasOmittedHistory ? {
fromSequence: omittedStart,
toSequence: omittedEnd,
diff --git a/server/services/agentRunEventLog.js b/server/services/agentRunEventLog.js
index 5d43c13de7..c1c23d0b09 100644
--- a/server/services/agentRunEventLog.js
+++ b/server/services/agentRunEventLog.js
@@ -11,6 +11,8 @@
* On disk:
* data/cos/run-events.jsonl — active generation
* data/cos/run-events.1.jsonl — the one retained archive generation
+ * data/cos/mind-events.jsonl — persistent-mind active generation
+ * data/cos/mind-events.1.jsonl — persistent-mind archive generation
*
* Retention is TWO bounds, and both are load-bearing.
*
@@ -20,11 +22,9 @@
* 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) 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`.
+ * Ordinary diagnostics additionally carry an AGE bound (MAX_EVENT_AGE_DAYS).
+ * Persistent-mind events live in their own larger count-bounded pool: mind
+ * chatter can neither evict ordinary diagnostics nor age out while stopped.
*
* Two invariants the callers depend on:
*
@@ -67,6 +67,8 @@ import {
const ACTIVE_PATH = join(PATHS.cos, 'run-events.jsonl');
const ARCHIVE_PATH = join(PATHS.cos, 'run-events.1.jsonl');
+const MIND_ACTIVE_PATH = join(PATHS.cos, 'mind-events.jsonl');
+const MIND_ARCHIVE_PATH = join(PATHS.cos, 'mind-events.1.jsonl');
const MIND_SEQUENCE_PATH = join(PATHS.cos, 'persistent-mind-sequences.json');
const MIND_SEQUENCE_SCHEMA_VERSION = 1;
@@ -79,6 +81,7 @@ export const runEventLogEvents = new EventEmitter();
* boundaries at a few hundred bytes per line — a couple of MB per generation.
*/
export const MAX_ACTIVE_EVENTS = 5000;
+export const MAX_ACTIVE_MIND_EVENTS = 10_000;
/**
* Age bound, on TOP of the count bound.
@@ -121,6 +124,9 @@ export const MAX_READ_LIMIT = RUN_EVENT_READ_LIMITS.max;
let activeIds = null;
let archiveIds = null;
let activeCount = 0;
+let mindActiveIds = null;
+let mindArchiveIds = null;
+let mindActiveCount = 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.
@@ -134,13 +140,39 @@ let lastPrunedAt = null;
let appendQueue = Promise.resolve();
/** eventId → retention metadata, for the duplicate check. */
-function indexById(events) {
+function indexById(events, { persistentMind = false } = {}) {
return new Map(events.filter((e) => e?.eventId).map((e) => [e.eventId, {
at: e.at ?? null,
- persistentMind: isPersistentMindEventKind(e.kind),
+ persistentMind: persistentMind || isPersistentMindEventKind(e.kind),
}]));
}
+const isMindShapedEvent = (event) => isStoredRunEvent(event)
+ && typeof event.mindId === 'string'
+ && Number.isSafeInteger(event.sequence);
+
+function normalizeMindGenerations(events) {
+ const seen = new Set();
+ const previousByMind = new Map();
+ const ordered = events
+ .filter(isMindShapedEvent)
+ .filter((event) => !seen.has(event.eventId) && seen.add(event.eventId))
+ .sort((a, b) => a.sequence - b.sequence || String(a.eventId).localeCompare(String(b.eventId)))
+ .map((event) => {
+ const previousSequence = previousByMind.get(event.mindId) ?? null;
+ previousByMind.set(event.mindId, event.sequence);
+ return Object.hasOwn(event.data, 'previousSequence')
+ ? event
+ : { ...event, data: { ...event.data, previousSequence } };
+ });
+ const active = ordered.slice(-MAX_ACTIVE_MIND_EVENTS);
+ const archive = ordered.slice(
+ Math.max(0, ordered.length - (MAX_ACTIVE_MIND_EVENTS * 2)),
+ Math.max(0, ordered.length - MAX_ACTIVE_MIND_EVENTS)
+ );
+ return { archive, active };
+}
+
/**
* Have we already stored this event, in a copy a reader can still see?
*
@@ -153,6 +185,8 @@ function indexById(events) {
function isStoredDuplicate(eventId, cutoff) {
const metadata = activeIds.has(eventId) ? activeIds.get(eventId)
: archiveIds.has(eventId) ? archiveIds.get(eventId)
+ : mindActiveIds.has(eventId) ? mindActiveIds.get(eventId)
+ : mindArchiveIds.has(eventId) ? mindArchiveIds.get(eventId)
: undefined;
return metadata !== undefined
&& (metadata.persistentMind || (typeof metadata.at === 'string' && metadata.at > cutoff));
@@ -160,11 +194,35 @@ function isStoredDuplicate(eventId, cutoff) {
async function hydrate() {
if (activeIds) return;
- const [active, archive, sequenceStore] = await Promise.all([
+ let [active, archive, mindActive, mindArchive, sequenceStore] = await Promise.all([
readJSONLFile(ACTIVE_PATH),
readJSONLFile(ARCHIVE_PATH),
+ readJSONLFile(MIND_ACTIVE_PATH),
+ readJSONLFile(MIND_ARCHIVE_PATH),
readJSONFileStrict(MIND_SEQUENCE_PATH, { schemaVersion: MIND_SEQUENCE_SCHEMA_VERSION, minds: {} }),
]);
+ const legacyArchive = archive.filter((event) => isPersistentMindEventKind(event?.kind));
+ const legacyActive = active.filter((event) => isPersistentMindEventKind(event?.kind));
+ if (legacyArchive.length > 0 || legacyActive.length > 0) {
+ const recovered = normalizeMindGenerations([
+ ...mindArchive,
+ ...mindActive,
+ ...legacyArchive,
+ ...legacyActive,
+ ]);
+ // Destination-first makes recovery retry-safe if a later source rewrite
+ // fails. This path handles upgrade -> rollback -> upgrade installs after
+ // migration 301 is already marked applied.
+ await writeJSONLines(MIND_ARCHIVE_PATH, recovered.archive);
+ await writeJSONLines(MIND_ACTIVE_PATH, recovered.active);
+ archive = archive.filter((event) => !isPersistentMindEventKind(event?.kind));
+ active = active.filter((event) => !isPersistentMindEventKind(event?.kind));
+ await writeJSONLines(ARCHIVE_PATH, archive);
+ await writeJSONLines(ACTIVE_PATH, active);
+ mindArchive = recovered.archive;
+ mindActive = recovered.active;
+ console.log(`🧠 Re-homed ${legacyArchive.length + legacyActive.length} rollback-era persistent mind event(s)`);
+ }
const invalidSequenceStore = !sequenceStore.ok || !sequenceStore.value
|| typeof sequenceStore.value !== 'object' || Array.isArray(sequenceStore.value)
|| sequenceStore.value.schemaVersion !== MIND_SEQUENCE_SCHEMA_VERSION
@@ -176,12 +234,15 @@ async function hydrate() {
const validSequenceStore = !invalidSequenceStore;
activeIds = indexById(active);
archiveIds = indexById(archive);
+ mindActiveIds = indexById(mindActive, { persistentMind: true });
+ mindArchiveIds = indexById(mindArchive, { persistentMind: true });
activeCount = active.length;
+ mindActiveCount = mindActive.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]) {
+ for (const event of [...mindArchive, ...mindActive]) {
if (!event?.mindId || !Number.isSafeInteger(event.sequence)) continue;
mindSequenceHighWater.set(
event.mindId,
@@ -206,14 +267,24 @@ const saveMindSequenceHighWater = () => atomicWrite(MIND_SEQUENCE_PATH, {
* event whose only copy just aged out of the ledger is appendable again — which
* is correct: a duplicate we can no longer see is no longer a duplicate.
*/
-async function rotateIfFull() {
- if (activeCount < MAX_ACTIVE_EVENTS) return;
- if (await pathExists(ARCHIVE_PATH)) await unlink(ARCHIVE_PATH);
- await rename(ACTIVE_PATH, ARCHIVE_PATH);
- archiveIds = activeIds;
- activeIds = new Map();
- activeCount = 0;
- console.log(`🔁 Rotated CoS run event ledger at ${MAX_ACTIVE_EVENTS} events`);
+async function rotateIfFull(mindEvent) {
+ const count = mindEvent ? mindActiveCount : activeCount;
+ const limit = mindEvent ? MAX_ACTIVE_MIND_EVENTS : MAX_ACTIVE_EVENTS;
+ if (count < limit) return;
+ const activePath = mindEvent ? MIND_ACTIVE_PATH : ACTIVE_PATH;
+ const archivePath = mindEvent ? MIND_ARCHIVE_PATH : ARCHIVE_PATH;
+ if (await pathExists(archivePath)) await unlink(archivePath);
+ await rename(activePath, archivePath);
+ if (mindEvent) {
+ mindArchiveIds = mindActiveIds;
+ mindActiveIds = new Map();
+ mindActiveCount = 0;
+ } else {
+ archiveIds = activeIds;
+ activeIds = new Map();
+ activeCount = 0;
+ }
+ console.log(`🔁 Rotated ${mindEvent ? 'persistent mind' : 'CoS run'} event ledger at ${limit} events`);
}
/**
@@ -289,24 +360,31 @@ async function appendNow(input) {
if (mindEvent && input?.eventId && isStoredDuplicate(input.eventId, expiryCutoff())) {
return { appended: false, duplicate: true, event: null };
}
+ const previousSequence = mindEvent ? (mindSequenceHighWater.get(input.mindId) ?? null) : null;
const sequence = mindEvent ? nextMindSequence(input.mindId) : undefined;
- const event = buildRunEvent(mindEvent ? { ...input, sequence } : input);
+ const event = buildRunEvent(mindEvent ? {
+ ...input,
+ sequence,
+ data: { ...(input.data && typeof input.data === 'object' ? input.data : {}), previousSequence },
+ } : 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();
if (isStoredDuplicate(event.eventId, expiryCutoff())) {
return { appended: false, duplicate: true, event };
}
- await rotateIfFull();
- await appendJSONLine(ACTIVE_PATH, event);
- activeIds.set(event.eventId, { at: event.at, persistentMind: mindEvent });
- activeCount += 1;
+ await rotateIfFull(mindEvent);
+ const activePath = mindEvent ? MIND_ACTIVE_PATH : ACTIVE_PATH;
+ await appendJSONLine(activePath, event);
+ const ids = mindEvent ? mindActiveIds : activeIds;
+ ids.set(event.eventId, { at: event.at, persistentMind: mindEvent });
+ if (mindEvent) mindActiveCount += 1;
+ else 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.
+ // Mind generations are bounded by rotation, while rollups can live
+ // indefinitely. Persist the high-water separately so a clock rollback
+ // after raw retention rotates cannot reuse an old sequence range.
await saveMindSequenceHighWater();
}
return { appended: true, duplicate: false, event };
@@ -378,10 +456,11 @@ function schedulePrune() {
* @returns {Promise<object[]>} validated events in append order
*/
async function readRetainedEvents() {
+ await hydrate();
await schedulePrune();
const [archive, active] = await Promise.all([
readJSONLFile(ARCHIVE_PATH),
- readJSONLFile(ACTIVE_PATH)
+ readJSONLFile(ACTIVE_PATH),
]);
// The age bound is enforced on read as well as on disk, so it holds in the
// window between prunes — a reader must never see an event the retention
@@ -392,7 +471,7 @@ async function readRetainedEvents() {
// 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.
- return [...archive, ...active].filter((e) => isRetained(e, cutoff));
+ return [...archive, ...active].filter((event) => isRetained(event, cutoff) && !isMindShapedEvent(event));
}
export async function readRunEvents({ runId, agentId, taskId, kind, since, limit } = {}) {
@@ -410,8 +489,15 @@ export async function readRunEvents({ runId, agentId, taskId, kind, since, limit
/** 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))
+ await hydrate();
+ const [archive, active] = await Promise.all([
+ readJSONLFile(MIND_ARCHIVE_PATH),
+ readJSONLFile(MIND_ACTIVE_PATH),
+ ]);
+ return [...archive, ...active]
+ // Preserve structurally valid future kinds in the physical mind stream.
+ // Current projections can ignore an unknown kind without deleting history.
+ .filter((event) => isMindShapedEvent(event) && event.mindId === mindId)
.sort((a, b) => a.sequence - b.sequence || String(a.eventId).localeCompare(String(b.eventId)));
}
@@ -493,9 +579,11 @@ export async function getRunDiagnostic(id) {
*/
export async function getRunEventLedgerStats() {
await schedulePrune();
- const [archive, active] = await Promise.all([
+ const [archive, active, mindArchive, mindActive] = await Promise.all([
readJSONLFile(ARCHIVE_PATH),
- readJSONLFile(ACTIVE_PATH)
+ readJSONLFile(ACTIVE_PATH),
+ readJSONLFile(MIND_ARCHIVE_PATH),
+ readJSONLFile(MIND_ACTIVE_PATH),
]);
// Counted through the SAME predicate the read path uses, so "stats say 40
// events" and "the events endpoint returns 40" can never disagree.
@@ -509,6 +597,10 @@ export async function getRunEventLedgerStats() {
maxActiveEvents: MAX_ACTIVE_EVENTS,
maxRetainedEvents: MAX_ACTIVE_EVENTS * 2,
maxEventAgeDays: MAX_EVENT_AGE_DAYS,
+ mindActiveEvents: mindActive.filter((event) => isStoredRunEvent(event) && isPersistentMindEventKind(event.kind)).length,
+ mindArchivedEvents: mindArchive.filter((event) => isStoredRunEvent(event) && isPersistentMindEventKind(event.kind)).length,
+ maxActiveMindEvents: MAX_ACTIVE_MIND_EVENTS,
+ maxRetainedMindEvents: MAX_ACTIVE_MIND_EVENTS * 2,
persistentMindAgeBounded: false,
oldestEventAt: oldest,
kinds: RUN_EVENT_KINDS
@@ -525,6 +617,9 @@ export function __resetRunEventLogCache() {
activeIds = null;
archiveIds = null;
activeCount = 0;
+ mindActiveIds = null;
+ mindArchiveIds = null;
+ mindActiveCount = 0;
mindSequenceHighWater = null;
mindSequenceCheckpointError = null;
lastPrunedAt = null;
diff --git a/server/services/agentRunEventLog.test.js b/server/services/agentRunEventLog.test.js
index 4d4a70f412..cdd21fec38 100644
--- a/server/services/agentRunEventLog.test.js
+++ b/server/services/agentRunEventLog.test.js
@@ -31,6 +31,7 @@ const {
flushRunEvents,
__resetRunEventLogCache,
MAX_ACTIVE_EVENTS,
+ MAX_ACTIVE_MIND_EVENTS,
MAX_EVENT_AGE_DAYS
} = await import('./agentRunEventLog.js');
const { buildRunEvent } = await import('../lib/agentRunEvents.js');
@@ -38,11 +39,13 @@ const { persistentMindEventCursor } = await import('../lib/persistentMindTraject
const ACTIVE = join(LEDGER_DIR, 'run-events.jsonl');
const ARCHIVE = join(LEDGER_DIR, 'run-events.1.jsonl');
+const MIND_ACTIVE = join(LEDGER_DIR, 'mind-events.jsonl');
+const MIND_ARCHIVE = join(LEDGER_DIR, 'mind-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, MIND_SEQUENCES]) if (existsSync(path)) rmSync(path);
+ for (const path of [ACTIVE, ARCHIVE, MIND_ACTIVE, MIND_ARCHIVE, MIND_SEQUENCES]) if (existsSync(path)) rmSync(path);
__resetRunEventLogCache();
}
@@ -200,7 +203,7 @@ describe('persistent-mind ordering, replay, and cursors', () => {
it('keeps sequence order after all raw events expire and the wall clock moves backwards', async () => {
const first = await appendMessage('one');
- writeFileSync(ACTIVE, '');
+ writeFileSync(MIND_ACTIVE, '');
restartServer();
vi.setSystemTime(new Date('2026-08-17T13:00:00.000Z'));
@@ -238,7 +241,7 @@ describe('persistent-mind ordering, replay, and cursors', () => {
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(''));
+ writeFileSync(MIND_ACTIVE, history.slice(1).map((item) => `${JSON.stringify(item)}\n`).join(''));
restartServer();
const recovered = await readPersistentMindEvents({ cursor, limit: 2 });
expect(recovered.gap).toBe(true);
@@ -288,6 +291,81 @@ describe('retention / rotation bound', () => {
expect(countLines(ARCHIVE)).toBe(MAX_ACTIVE_EVENTS);
expect(countLines(ACTIVE)).toBe(1);
});
+
+ it('keeps persistent-mind chatter in its own larger rotation pool', async () => {
+ const mindSeed = Array.from({ length: MAX_ACTIVE_MIND_EVENTS }, (_, index) => `${JSON.stringify(buildRunEvent({
+ kind: 'mind.wake',
+ mindId: 'cos-persistent-mind',
+ sequence: index + 1,
+ eventId: `mind-${index}`,
+ at: '2026-08-18T10:00:00.000Z',
+ data: { previousSequence: index || null },
+ }))}\n`).join('');
+ writeFileSync(MIND_ACTIVE, mindSeed);
+ await appendRunEvent({ kind: 'run.spawned', runId: 'ordinary', at: '2026-08-18T12:00:00.000Z' });
+ restartServer();
+ await appendMindEvent({ kind: 'mind.wake', eventId: 'mind-fresh' });
+
+ expect(countLines(ACTIVE)).toBe(1);
+ expect(countLines(ARCHIVE)).toBe(0);
+ expect(countLines(MIND_ACTIVE)).toBe(1);
+ expect(countLines(MIND_ARCHIVE)).toBe(MAX_ACTIVE_MIND_EVENTS);
+ const stats = await getRunEventLedgerStats();
+ expect(stats.maxRetainedMindEvents).toBe(MAX_ACTIVE_MIND_EVENTS * 2);
+ });
+
+ it('does not let a full mind page crowd ordinary run diagnostics out of their read cap', async () => {
+ const ordinary = buildRunEvent({ kind: 'run.spawned', runId: 'ordinary', at: '2026-08-18T10:00:00.000Z' });
+ const minds = Array.from({ length: 1001 }, (_, index) => buildRunEvent({
+ kind: 'mind.wake',
+ mindId: 'cos-persistent-mind',
+ sequence: index + 1,
+ eventId: `mind-page-${index}`,
+ at: '2026-08-18T10:00:00.000Z',
+ data: { previousSequence: index || null },
+ }));
+ writeFileSync(ACTIVE, `${JSON.stringify(ordinary)}\n`);
+ writeFileSync(MIND_ACTIVE, minds.map((event) => `${JSON.stringify(event)}\n`).join(''));
+ restartServer();
+
+ expect((await readRunEvents()).map((event) => event.runId)).toEqual(['ordinary']);
+ expect((await getRunProjections()).map((state) => state.id)).toEqual(['ordinary']);
+ });
+
+ it('re-homes rollback-era mind events without counting them as ordinary diagnostics', async () => {
+ const ordinary = buildRunEvent({ kind: 'run.spawned', runId: 'ordinary', at: '2026-08-18T10:00:00.000Z' });
+ const legacyMind = buildRunEvent({
+ kind: 'mind.wake',
+ mindId: 'cos-persistent-mind',
+ sequence: 10,
+ eventId: 'legacy-mind',
+ at: '2026-08-18T10:00:01.000Z',
+ });
+ writeFileSync(ACTIVE, `${JSON.stringify(ordinary)}\n${JSON.stringify(legacyMind)}\n`);
+ restartServer();
+
+ expect((await readRunEvents()).map((event) => event.runId)).toEqual(['ordinary']);
+ expect((await readPersistentMindHistory()).map((event) => event.eventId)).toEqual(['legacy-mind']);
+ expect(countLines(ACTIVE)).toBe(1);
+ expect(countLines(MIND_ACTIVE)).toBe(1);
+ });
+
+ it('preserves structurally valid future kinds from the physical mind ledger', async () => {
+ const future = {
+ ...buildRunEvent({
+ kind: 'mind.wake',
+ mindId: 'cos-persistent-mind',
+ sequence: 1,
+ eventId: 'future-mind-kind',
+ at: '2026-08-18T10:00:00.000Z',
+ }),
+ kind: 'mind.future-boundary',
+ };
+ writeFileSync(MIND_ACTIVE, `${JSON.stringify(future)}\n`);
+ restartServer();
+
+ expect((await readPersistentMindHistory()).map((event) => event.kind)).toEqual(['mind.future-boundary']);
+ });
});
describe('readRunEvents', () => {
@@ -434,11 +512,11 @@ describe('retention — age bound (#4540)', () => {
at: stale(),
data: { messageId: 'ancient', displayText: 'Retain until it can be summarized.' },
});
- writeFileSync(ACTIVE, `${JSON.stringify(mindEvent)}\n`);
+ writeFileSync(MIND_ACTIVE, `${JSON.stringify(mindEvent)}\n`);
restartServer();
expect((await readPersistentMindHistory()).map((item) => item.eventId)).toEqual(['mind-message:ancient']);
- expect(countLines(ACTIVE)).toBe(1);
+ expect(countLines(MIND_ACTIVE)).toBe(1);
expect(await appendMindEvent({
kind: 'mind.message.accepted',
eventId: 'mind-message:ancient',
diff --git a/server/services/persistentMindContext.js b/server/services/persistentMindContext.js
index 3d21c8833e..5d8cd380d5 100644
--- a/server/services/persistentMindContext.js
+++ b/server/services/persistentMindContext.js
@@ -111,12 +111,30 @@ export async function preparePersistentMindContext({
const history = await readPersistentMindHistory(mindId);
let rollups = await readPersistentMindRollups(mindId);
const older = history.slice(0, Math.max(0, history.length - Math.max(1, recentEventLimit)));
+ let coverageGap = null;
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 expectedPredecessor = previous?.source.toSequence ?? null;
+ const brokenLinkIndex = rangeEvents.findIndex((event, index) => {
+ const expected = index === 0 ? expectedPredecessor : rangeEvents[index - 1].sequence;
+ return event.data?.previousSequence !== expected;
+ });
+ if (brokenLinkIndex >= 0) {
+ const brokenEvent = rangeEvents[brokenLinkIndex];
+ const expected = brokenLinkIndex === 0
+ ? expectedPredecessor
+ : rangeEvents[brokenLinkIndex - 1].sequence;
+ const actualPredecessor = brokenEvent.data?.previousSequence;
+ coverageGap = {
+ expectedAfterSequence: expected,
+ retainedFromSequence: brokenEvent.sequence,
+ recordedPredecessorSequence: Number.isSafeInteger(actualPredecessor) ? actualPredecessor : null,
+ };
+ }
const source = {
fromSequence: previous?.source.fromSequence ?? rangeEvents[0].sequence,
toSequence: rangeEvents.at(-1).sequence,
@@ -125,7 +143,7 @@ export async function preparePersistentMindContext({
};
const rollupId = `${mindId}:${source.fromSequence}-${source.toSequence}:v${promptVersion}`;
const alreadyAttempted = rollups.some((rollup) => rollup.id === rollupId);
- if (forceSummary || !alreadyAttempted) {
+ if (!coverageGap && (forceSummary || !alreadyAttempted)) {
const outcome = await summaryOutcome(summarize, {
mindId,
source,
@@ -180,6 +198,7 @@ export async function preparePersistentMindContext({
maxChars,
recentEventLimit,
promptVersion,
+ coverageGap,
});
}
diff --git a/server/services/persistentMindContext.test.js b/server/services/persistentMindContext.test.js
index 743e03c8ad..bd9cef9aac 100644
--- a/server/services/persistentMindContext.test.js
+++ b/server/services/persistentMindContext.test.js
@@ -45,7 +45,7 @@ const event = (sequence, kind = 'mind.message.accepted') => ({
turnId: kind === 'mind.message.accepted' ? null : 'turn-1',
sequence,
at: `2026-08-25T12:00:0${sequence}.000Z`,
- data: { displayText: `Visible event ${sequence}` },
+ data: { displayText: `Visible event ${sequence}`, previousSequence: sequence > 1 ? sequence - 1 : null },
});
beforeEach(() => {
@@ -178,6 +178,42 @@ describe('persistent mind rollups', () => {
expect(context.text).not.toContain('First cumulative summary.');
});
+ it('reports a retained-history gap instead of claiming complete rollup coverage', async () => {
+ mock.history = [event(2), event(3), event(4)];
+ const summarize = vi.fn(async () => 'This must not be recorded as complete.');
+
+ const context = await preparePersistentMindContext({ recentEventLimit: 1, summarize });
+
+ expect(summarize).not.toHaveBeenCalled();
+ expect(await readPersistentMindRollups()).toEqual([]);
+ expect(context).toMatchObject({
+ summaryState: 'gap',
+ coverageGap: {
+ expectedAfterSequence: null,
+ retainedFromSequence: 2,
+ recordedPredecessorSequence: 1,
+ },
+ });
+ expect(context.text).toContain('summary-cache=gap');
+ });
+
+ it('detects a missing event inside the retained summary range', async () => {
+ mock.history = [event(1), event(2), event(4), event(5)];
+ const summarize = vi.fn(async () => 'This must not bridge the missing sequence.');
+
+ const context = await preparePersistentMindContext({ recentEventLimit: 1, summarize });
+
+ expect(summarize).not.toHaveBeenCalled();
+ expect(context).toMatchObject({
+ summaryState: 'gap',
+ coverageGap: {
+ expectedAfterSequence: 2,
+ retainedFromSequence: 4,
+ recordedPredecessorSequence: 3,
+ },
+ });
+ });
+
it('fails closed on a corrupt cache instead of replacing it with empty state', async () => {
writeFileSync(ROLLUPS, '{broken');
diff --git a/server/services/persistentMindSupervisor.js b/server/services/persistentMindSupervisor.js
index ea84046e9e..8ee5d0a040 100644
--- a/server/services/persistentMindSupervisor.js
+++ b/server/services/persistentMindSupervisor.js
@@ -485,6 +485,18 @@ async function runOnePersistentMindTurn() {
await recordTurnProfile(turn.id, prepared);
if (!await turnCanContinue(turn.id, generation, controller.signal)) return;
+ const latestRoot = await loadState();
+ const slot = await acquireLocalEndpointProviderSlot(prepared.provider, latestRoot.agents, turn.id);
+ if (!slot.ok) {
+ await parkActiveTurn(turn.id, slot.reason, 'waiting');
+ return;
+ }
+ release = slot.release;
+ if (!await turnCanContinue(turn.id, generation, controller.signal)) return;
+ // One accounted provider span covers both optional context summarization
+ // and the turn itself. A local adapter must not bypass endpoint capacity
+ // merely because its first inference happens while context is prepared.
+ runStartedAt = Date.now();
const context = await preparePersistentMindContext({
mindId: mind.mindId,
identity: turnAdapter.identity || 'One supervised persistent Chief of Staff mind.',
@@ -500,6 +512,7 @@ async function runOnePersistentMindTurn() {
})
: null,
});
+ if (!await turnCanContinue(turn.id, generation, controller.signal)) return;
await appendMindEvent({
kind: 'mind.model.request',
mindId: mind.mindId,
@@ -513,16 +526,8 @@ async function runOnePersistentMindTurn() {
contextSummaryState: context.summaryState,
},
});
-
- const latestRoot = await loadState();
- const slot = await acquireLocalEndpointProviderSlot(prepared.provider, latestRoot.agents, turn.id);
- if (!slot.ok) {
- await parkActiveTurn(turn.id, slot.reason, 'waiting');
- return;
- }
- release = slot.release;
if (!await turnCanContinue(turn.id, generation, controller.signal)) return;
- runStartedAt = Date.now();
+
const result = await turnAdapter.run({
turnId: turn.id,
wake: turn.wake,
diff --git a/server/services/persistentMindSupervisor.test.js b/server/services/persistentMindSupervisor.test.js
index f28cafd781..84808eaecb 100644
--- a/server/services/persistentMindSupervisor.test.js
+++ b/server/services/persistentMindSupervisor.test.js
@@ -366,11 +366,60 @@ describe('persistent mind supervisor', () => {
await supervisor.drainPersistentMind();
expect(run).not.toHaveBeenCalled();
+ expect(mock.prepareContext).not.toHaveBeenCalled();
expect(mock.root.persistentMind.status).toBe('waiting');
expect(mock.root.persistentMind.queuedMessages.map((item) => item.id)).toEqual(['message-1']);
expect(mock.root.persistentMind.pauseReason).toContain('at capacity');
});
+ it('holds one local endpoint slot and one usage span across context summarization and the turn', async () => {
+ const contextReady = deferred();
+ const release = vi.fn();
+ mock.acquireSlot.mockResolvedValue({ ok: true, release });
+ mock.prepareContext.mockImplementationOnce(() => contextReady.promise);
+ const run = vi.fn(async () => ({}));
+ await supervisor.registerPersistentMindTurnAdapter({
+ prepare: vi.fn(async () => ({ ok: true, provider: { id: 'example-cloud' } })),
+ summarize: vi.fn(async () => 'summary'),
+ run,
+ });
+ await supervisor.setPersistentMindEnabled(true);
+ await supervisor.startPersistentMind();
+ const drain = supervisor.drainPersistentMind();
+ await vi.waitFor(() => expect(mock.prepareContext).toHaveBeenCalled());
+
+ expect(mock.acquireSlot).toHaveBeenCalledTimes(1);
+ expect(release).not.toHaveBeenCalled();
+ expect(run).not.toHaveBeenCalled();
+
+ contextReady.resolve({ text: 'bounded context', chars: 15, summaryState: 'ready' });
+ await drain;
+ expect(run).toHaveBeenCalledTimes(1);
+ expect(release).toHaveBeenCalledTimes(1);
+ expect(mock.recordUsage).toHaveBeenCalledWith('cos', expect.objectContaining({ actions: 1 }));
+ });
+
+ it('does not run a turn canceled while context preparation is pending', async () => {
+ const contextReady = deferred();
+ mock.prepareContext.mockImplementationOnce(() => contextReady.promise);
+ const run = vi.fn(async () => ({}));
+ await supervisor.registerPersistentMindTurnAdapter({
+ prepare: vi.fn(async () => ({ ok: true, provider: { id: 'example-cloud' } })),
+ run,
+ });
+ await supervisor.setPersistentMindEnabled(true);
+ await supervisor.startPersistentMind();
+ const drain = supervisor.drainPersistentMind();
+ await vi.waitFor(() => expect(mock.prepareContext).toHaveBeenCalled());
+
+ await supervisor.pausePersistentMind();
+ contextReady.resolve({ text: 'bounded context', chars: 15, summaryState: 'ready' });
+ await drain;
+
+ expect(run).not.toHaveBeenCalled();
+ expect(mock.root.persistentMind.status).toBe('paused');
+ });
+
it('does not schedule or run a wake while the CoS lifecycle gate is closed', async () => {
const run = vi.fn();
await supervisor.registerPersistentMindTurnAdapter({