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
address review (codex): preserve requested wake timing
Adam Eivy9fd727dcf883
diff --git a/scripts/migrations/298-persistent-mind-runtime-state.test.js b/scripts/migrations/298-persistent-mind-runtime-state.test.jsindex f88917e955..a0366fa121 100644--- a/scripts/migrations/298-persistent-mind-runtime-state.test.js+++ b/scripts/migrations/298-persistent-mind-runtime-state.test.js@@ -3,6 +3,7 @@ import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs'import { tmpdir } from 'os';import { join } from 'path';import migration from './298-persistent-mind-runtime-state.js';+import { PERSISTENT_MIND_SCHEMA_VERSION } from '../../server/lib/persistentMind.js';const readJson = (path) => JSON.parse(readFileSync(path, 'utf8'));@@ -29,7 +30,7 @@ describe('migration 298 — persistent mind runtime state', () => {running: true,config: { alwaysOn: true },agents: { a1: { status: 'completed' } },- persistentMind: { schemaVersion: 3, mindId: 'cos-persistent-mind', enabled: false, started: false, status: 'disabled', pendingAttachments: [] },+ persistentMind: { schemaVersion: PERSISTENT_MIND_SCHEMA_VERSION, mindId: 'cos-persistent-mind', enabled: false, started: false, status: 'disabled', pendingAttachments: [] },});});diff --git a/scripts/migrations/299-persistent-mind-identity.test.js b/scripts/migrations/299-persistent-mind-identity.test.jsindex 9ead3cb3e0..a5e62b0500 100644--- a/scripts/migrations/299-persistent-mind-identity.test.js+++ b/scripts/migrations/299-persistent-mind-identity.test.js@@ -3,6 +3,7 @@ import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs'import { tmpdir } from 'os';import { join } from 'path';import migration from './299-persistent-mind-identity.js';+import { PERSISTENT_MIND_SCHEMA_VERSION } from '../../server/lib/persistentMind.js';const readJson = (path) => JSON.parse(readFileSync(path, 'utf8'));@@ -28,7 +29,7 @@ describe('migration 299 — persistent mind identity', () => {expect(readJson(statePath)).toMatchObject({running: true,persistentMind: {- schemaVersion: 3,+ schemaVersion: PERSISTENT_MIND_SCHEMA_VERSION,mindId: 'cos-persistent-mind',enabled: true,customFutureField: 'preserve',@@ -38,7 +39,7 @@ describe('migration 299 — persistent mind identity', () => {it('is idempotent', async () => {writeFileSync(statePath, JSON.stringify({- persistentMind: { schemaVersion: 3, mindId: 'cos-persistent-mind' },+ persistentMind: { schemaVersion: PERSISTENT_MIND_SCHEMA_VERSION, mindId: 'cos-persistent-mind' },}));await expect(migration.up({ rootDir })).resolves.toEqual({ updated: 0, reason: 'already-applied' });});diff --git a/scripts/migrations/307-persistent-mind-self-wake-schedule-kind.js b/scripts/migrations/307-persistent-mind-self-wake-schedule-kind.jsnew file mode 100644index 0000000000..9976b40fd3--- /dev/null+++ b/scripts/migrations/307-persistent-mind-self-wake-schedule-kind.js@@ -0,0 +1,58 @@+/** Classify durable Persistent Mind self-wakes without inferring from display text. */++import { readFile } from 'fs/promises';+import { join } from 'path';+import {+ PERSISTENT_MIND_SCHEMA_VERSION,+ PERSISTENT_MIND_SELF_WAKE_SCHEDULE_KINDS,+} from '../../server/lib/persistentMind.js';+import { atomicWrite, safeJSONParse } from '../../server/lib/fileUtils.js';++const classifySelfWake = (wake) => {+ if (!wake || typeof wake !== 'object' || Array.isArray(wake) || wake.kind !== 'self') return wake;+ if (PERSISTENT_MIND_SELF_WAKE_SCHEDULE_KINDS.includes(wake.scheduleKind)) return wake;+ // Legacy wake reasons are model-authored text. Treat them as requested so a+ // cadence increase never postpones a possibly intentional follow-up.+ return { ...wake, scheduleKind: 'requested' };+};++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' };++ const state = safeJSONParse(raw, null, { logError: false });+ if (!state || typeof state !== 'object' || Array.isArray(state)) {+ 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' };+ }++ const selfWake = classifySelfWake(existing.selfWake);+ const activeWake = classifySelfWake(existing.activeTurn?.wake);+ const activeTurn = activeWake === existing.activeTurn?.wake+ ? existing.activeTurn+ : { ...existing.activeTurn, wake: activeWake };+ if (existing.schemaVersion === PERSISTENT_MIND_SCHEMA_VERSION+ && selfWake === existing.selfWake+ && activeTurn === existing.activeTurn) {+ return { updated: 0, reason: 'already-applied' };+ }++ state.persistentMind = {+ ...existing,+ schemaVersion: PERSISTENT_MIND_SCHEMA_VERSION,+ selfWake,+ activeTurn,+ };+ await atomicWrite(statePath, state);+ console.log('🧠 migration 307: classified Persistent Mind self-wake schedules');+ return { updated: 1 };+ },+};diff --git a/scripts/migrations/307-persistent-mind-self-wake-schedule-kind.test.js b/scripts/migrations/307-persistent-mind-self-wake-schedule-kind.test.jsnew file mode 100644index 0000000000..271854c6e8--- /dev/null+++ b/scripts/migrations/307-persistent-mind-self-wake-schedule-kind.test.js@@ -0,0 +1,77 @@+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { mkdtemp, mkdir, readFile, rm, writeFile } from 'fs/promises';+import { tmpdir } from 'os';+import { join } from 'path';+import migration from './307-persistent-mind-self-wake-schedule-kind.js';+import { PERSISTENT_MIND_SCHEMA_VERSION } from '../../server/lib/persistentMind.js';++let rootDir;++afterEach(async () => {+ if (rootDir) await rm(rootDir, { recursive: true, force: true });+ rootDir = null;+});++const statePath = () => join(rootDir, 'data', 'cos', 'state.json');++describe('migration 307 — persistent mind self-wake schedule kind', () => {+ beforeEach(async () => {+ rootDir = await mkdtemp(join(tmpdir(), 'portos-mind-wake-kind-'));+ await mkdir(join(rootDir, 'data', 'cos'), { recursive: true });+ });++ it('conservatively classifies unmarked queued and active self-wakes as requested', async () => {+ const selfWake = {+ id: 'wake-queued',+ kind: 'self',+ reason: 'maximum quiet period elapsed',+ sourceTurnId: 'turn-1',+ };+ const activeWake = { ...selfWake, id: 'wake-active' };+ await writeFile(statePath(), JSON.stringify({+ persistentMind: {+ schemaVersion: 3,+ selfWake,+ activeTurn: { id: 'active-turn', wake: activeWake },+ futureField: 'preserve',+ },+ }));++ await expect(migration.up({ rootDir })).resolves.toEqual({ updated: 1 });+ const migrated = JSON.parse(await readFile(statePath(), 'utf8')).persistentMind;+ expect(migrated).toMatchObject({+ schemaVersion: PERSISTENT_MIND_SCHEMA_VERSION,+ selfWake: { scheduleKind: 'requested' },+ activeTurn: { wake: { scheduleKind: 'requested' } },+ futureField: 'preserve',+ });+ });++ it('preserves an explicitly classified quiet wake', async () => {+ const selfWake = { id: 'wake-quiet', kind: 'self', scheduleKind: 'quiet' };+ await writeFile(statePath(), JSON.stringify({ persistentMind: { schemaVersion: 3, selfWake } }));++ await expect(migration.up({ rootDir })).resolves.toEqual({ updated: 1 });+ expect(JSON.parse(await readFile(statePath(), 'utf8')).persistentMind.selfWake).toEqual(selfWake);+ });++ it('is idempotent once the schema and wake classifications are current', async () => {+ const current = {+ schemaVersion: PERSISTENT_MIND_SCHEMA_VERSION,+ selfWake: { id: 'wake-requested', kind: 'self', scheduleKind: 'requested' },+ activeTurn: null,+ };+ await writeFile(statePath(), JSON.stringify({ persistentMind: current }));++ await expect(migration.up({ rootDir })).resolves.toEqual({ updated: 0, reason: 'already-applied' });+ expect(JSON.parse(await readFile(statePath(), 'utf8')).persistentMind).toEqual(current);+ });++ it('leaves missing and invalid Persistent Mind state untouched', async () => {+ await expect(migration.up({ rootDir })).resolves.toEqual({ updated: 0, reason: 'no-state' });+ await writeFile(statePath(), JSON.stringify({ config: {} }));+ await expect(migration.up({ rootDir })).resolves.toEqual({ updated: 0, reason: 'no-persistent-mind' });+ await writeFile(statePath(), '{broken');+ await expect(migration.up({ rootDir })).resolves.toEqual({ updated: 0, reason: 'invalid-state' });+ });+});diff --git a/server/lib/persistentMind.js b/server/lib/persistentMind.jsindex 4814d61d0a..a85002637c 100644--- a/server/lib/persistentMind.js+++ b/server/lib/persistentMind.js@@ -12,7 +12,7 @@ import { MAX_SCREENSHOT_BYTES } from './uploadLimits.js';import { sanitizeFilename } from './mimeTypes.js';import { isSafeFilename } from './pathSafety.js';-export const PERSISTENT_MIND_SCHEMA_VERSION = 3;+export const PERSISTENT_MIND_SCHEMA_VERSION = 4;export const PERSISTENT_MIND_IMAGE_EXTENSIONS = Object.freeze(['.png', '.jpg', '.jpeg', '.gif', '.webp']);export const PERSISTENT_MIND_IMAGE_MIME_TYPES = Object.freeze({@@ -35,6 +35,7 @@ export const PERSISTENT_MIND_STATUSES = [];export const PERSISTENT_MIND_WAKE_KINDS = ['message', 'self'];+export const PERSISTENT_MIND_SELF_WAKE_SCHEDULE_KINDS = ['quiet', 'requested'];export const PERSISTENT_MIND_LIMITS = Object.freeze({MAX_QUEUED_MESSAGES: 100,@@ -229,6 +230,9 @@ const sanitizeSelfWake = (value) => {return {id,kind: 'self',+ scheduleKind: PERSISTENT_MIND_SELF_WAKE_SCHEDULE_KINDS.includes(value?.scheduleKind)+ ? value.scheduleKind+ : 'requested',reason,sourceTurnId,createdAt: asIso(value?.createdAt) || new Date(0).toISOString(),diff --git a/server/lib/persistentMind.test.js b/server/lib/persistentMind.test.jsindex c71e2e8b2f..2745393ade 100644--- a/server/lib/persistentMind.test.js+++ b/server/lib/persistentMind.test.js@@ -35,6 +35,28 @@ describe('persistent mind state', () => {expect(state.queuedMessages).toEqual([{ id: 'm1', text: 'hello', createdAt: iso(0) }]);});+ it('classifies unmarked legacy self-wakes as requested without trusting their reason text', () => {+ const state = normalizePersistentMindState({+ enabled: true,+ started: true,+ selfWake: {+ id: 'w1',+ kind: 'self',+ reason: 'maximum quiet period elapsed',+ sourceTurnId: 't1',+ createdAt: iso(1),+ notBefore: iso(2),+ },+ });++ expect(state.selfWake).toMatchObject({ scheduleKind: 'requested' });+ expect(normalizePersistentMindState({+ enabled: true,+ started: true,+ selfWake: { ...state.selfWake, scheduleKind: 'quiet' },+ }).selfWake).toMatchObject({ scheduleKind: 'quiet' });+ });+it('does not preserve a running status when the durable started flag is false', () => {const activeTurn = {id: 't1',diff --git a/server/services/cos.test.js b/server/services/cos.test.jsindex 59fa2187d8..3da4d1b6c5 100644--- a/server/services/cos.test.js+++ b/server/services/cos.test.js@@ -49,6 +49,7 @@ import {readEndpointCapacity,} from './cosLocalEndpointSlots.js';import { PENDING_MERGE_SWEEP_INTERVAL_MS, MAX_PENDING_MERGE_TICKS } from './prWatcher.js';+import { PERSISTENT_MIND_SCHEMA_VERSION } from '../lib/persistentMind.js';const __dirname = dirname(fileURLToPath(import.meta.url));const COS_SRC = readFileSync(join(__dirname, 'cos.js'), 'utf-8');@@ -2411,7 +2412,7 @@ 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: 3,+ schemaVersion: PERSISTENT_MIND_SCHEMA_VERSION,mindId: 'cos-persistent-mind',enabled: false,started: false,diff --git a/server/services/persistentMindSupervisor.js b/server/services/persistentMindSupervisor.jsindex 103afbc3af..be775d4229 100644--- a/server/services/persistentMindSupervisor.js+++ b/server/services/persistentMindSupervisor.js@@ -491,6 +491,7 @@ function initialSelfWake(reason) {return {id: `wake-${randomUUID()}`,kind: 'self',+ scheduleKind: 'requested',reason,sourceTurnId: reason,createdAt,@@ -504,6 +505,7 @@ function quietSelfWake(turnId, quietPeriodMs = PERSISTENT_MIND_LIMITS.MAX_QUIET_return {id: `wake-${randomUUID()}`,kind: 'self',+ scheduleKind: 'quiet',reason: QUIET_SELF_WAKE_REASON,sourceTurnId: turnId,createdAt: nowIso(),@@ -697,6 +699,7 @@ async function completeTurn(turnId, result, generation) {? {id: `wake-${randomUUID()}`,kind: 'self',+ scheduleKind: 'requested',reason: String(result.selfWake.reason || 'turn requested follow-up').slice(0, PERSISTENT_MIND_LIMITS.MAX_REASON_CHARS),sourceTurnId: turnId,@@ -1054,7 +1057,7 @@ export async function refreshPersistentMindWakeCadence() {let selfWake = mind.selfWake;if (!selfWake && mind.queuedMessages.length === 0) {selfWake = quietSelfWake(mind.lastCompletedTurnId || 'cadence-change', quietPeriodMs, baseAt);- } else if (selfWake?.reason === QUIET_SELF_WAKE_REASON) {+ } else if (selfWake?.scheduleKind === 'quiet') {selfWake = quietSelfWake(selfWake.sourceTurnId || mind.lastCompletedTurnId || 'cadence-change', quietPeriodMs, baseAt);} else if (selfWake && (!Number.isFinite(Date.parse(selfWake.notBefore)) || Date.parse(selfWake.notBefore) > quietDeadline)) {selfWake = { ...selfWake, notBefore: new Date(quietDeadline).toISOString() };@@ -1386,6 +1389,7 @@ export async function requestPersistentMindWake({ sourceTurnId, reason, notBeforconst selfWake = {id: `wake-${randomUUID()}`,kind: 'self',+ scheduleKind: 'requested',reason: String(reason || 'self-wake').slice(0, PERSISTENT_MIND_LIMITS.MAX_REASON_CHARS),sourceTurnId,createdAt: nowIso(),diff --git a/server/services/persistentMindSupervisor.test.js b/server/services/persistentMindSupervisor.test.jsindex cde973c0ee..5e53c7afab 100644--- a/server/services/persistentMindSupervisor.test.js+++ b/server/services/persistentMindSupervisor.test.js@@ -213,6 +213,7 @@ describe('persistent mind supervisor', () => {const { lastCompletedAt, selfWake } = mock.root.persistentMind;expect(selfWake.reason).toBe('Check again later');+ expect(selfWake.scheduleKind).toBe('requested');expect(Date.parse(selfWake.notBefore) - Date.parse(lastCompletedAt)).toBe(15 * 60_000);});@@ -228,6 +229,7 @@ describe('persistent mind supervisor', () => {selfWake: {id: 'wake-old',kind: 'self',+ scheduleKind: 'quiet',reason: 'maximum quiet period elapsed',sourceTurnId: 'turn-1',createdAt: lastCompletedAt,@@ -242,6 +244,34 @@ describe('persistent mind supervisor', () => {expect(mock.scheduled.get(supervisor.PERSISTENT_MIND_WAKE_EVENT_ID).delayMs).toBeGreaterThan(40 * 60_000);});+ it('does not postpone a requested wake whose reason matches the automatic wake text', async () => {+ const lastCompletedAt = new Date(Date.now() - 10 * 60_000).toISOString();+ const requestedAt = new Date(Date.now() + 5 * 60_000).toISOString();+ mock.root.persistentMind = {+ ...createDefaultPersistentMindState(),+ enabled: true,+ started: true,+ status: 'waiting',+ lastCompletedTurnId: 'turn-1',+ lastCompletedAt,+ selfWake: {+ id: 'wake-requested',+ kind: 'self',+ scheduleKind: 'requested',+ reason: 'maximum quiet period elapsed',+ sourceTurnId: 'turn-1',+ createdAt: lastCompletedAt,+ notBefore: requestedAt,+ },+ };+ mock.root.config.persistentMindProfile.wakeIntervalMinutes = 60;++ await supervisor.refreshPersistentMindWakeCadence();++ expect(mock.root.persistentMind.selfWake.notBefore).toBe(requestedAt);+ expect(mock.scheduled.get(supervisor.PERSISTENT_MIND_WAKE_EVENT_ID).delayMs).toBeLessThanOrEqual(5 * 60_000);+ });+it('fails closed when a legacy completed message has no retry fingerprint', async () => {mock.root.persistentMind.recentMessageIds = ['legacy-message'];