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(cos): recover orphaned mind turns after server restart

atomanticagent9d1007d55f50
diff --git a/server/services/auth.js b/server/services/auth.js
index ac92525e72..33ac89b2d0 100644
--- a/server/services/auth.js
+++ b/server/services/auth.js
@@ -1,6 +1,7 @@
import { join } from 'path';
import { EventEmitter } from 'events';
import { randomBytes } from 'crypto';
+import { stat } from 'fs/promises';
import { atomicWrite, PATHS, safeJSONParse, tryReadFile } from '../lib/fileUtils.js';
import {
COOKIE_NAME,
@@ -69,6 +70,9 @@ const sessions = new Map();
// burst of concurrent verifySession calls after a restart can't observe an
// empty Map while the first call is still reading auth-sessions.json.
let loadPromise = null;
+// mtime of auth-sessions.json at last read/write — used to pick up tokens
+// minted out-of-process (see mergeSessionsFromDisk).
+let sessionsFileMtimeMs = 0;
const now = () => Date.now();
@@ -92,6 +96,11 @@ const readSessions = async () => {
const id = typeof entry.id === 'string' ? entry.id : randomBytes(SESSION_ID_BYTES).toString('hex');
sessions.set(entry.tokenHash, { expiresAt: entry.expiresAt, label, id });
}
+ try {
+ sessionsFileMtimeMs = (await stat(SESSIONS_FILE)).mtimeMs;
+ } catch {
+ // leave prior stamp; miss path will retry
+ }
};
const writeSessions = async () => {
@@ -100,6 +109,11 @@ const writeSessions = async () => {
tokens.push({ tokenHash, expiresAt, label, id });
}
await atomicWrite(SESSIONS_FILE, JSON.stringify({ tokens }, null, 2) + '\n');
+ try {
+ sessionsFileMtimeMs = (await stat(SESSIONS_FILE)).mtimeMs;
+ } catch {
+ // next miss will refresh
+ }
};
const ensureLoaded = async () => {
@@ -111,6 +125,24 @@ const ensureLoaded = async () => {
return loadPromise;
};
+// Out-of-process callers (box keepalive, a shell one-liner) mint sessions by
+// importing this module against the same auth-sessions.json the running server
+// owns. The server's Map is loaded once at first verify, so a token written
+// after that load is invisible until restart — which made keepalive's
+// POST /api/cos/start keep answering AUTH_REQUIRED after the instance password
+// was enabled. On a miss, merge any newer disk records into the live Map;
+// never drop in-memory entries a racing disk write might have omitted.
+const mergeSessionsFromDisk = async () => {
+ let mtimeMs = 0;
+ try {
+ mtimeMs = (await stat(SESSIONS_FILE)).mtimeMs;
+ } catch {
+ return;
+ }
+ if (mtimeMs <= sessionsFileMtimeMs) return;
+ await readSessions();
+};
+
const readAuthConfig = async () => {
const settings = await getSettings();
return settings?.secrets?.auth ?? null;
@@ -289,7 +321,11 @@ export const verifySession = async (token) => {
if (typeof token !== 'string' || token.length === 0) return false;
await ensureLoaded();
const key = hashToken(token);
- const entry = sessions.get(key);
+ let entry = sessions.get(key);
+ if (!entry) {
+ await mergeSessionsFromDisk();
+ entry = sessions.get(key);
+ }
if (!entry) return false;
if (entry.expiresAt <= now()) {
sessions.delete(key);
diff --git a/server/services/auth.test.js b/server/services/auth.test.js
index 0f2f4b3b89..26e29ac822 100644
--- a/server/services/auth.test.js
+++ b/server/services/auth.test.js
@@ -225,6 +225,26 @@ describe('auth service', () => {
expect(await fresh.verifySession(token)).toBe(true);
});
+ it('picks up a session another process wrote to disk after this process loaded', async () => {
+ // Keepalive mints via createSession in a separate Node process against the
+ // same auth-sessions.json. The already-running server must accept that
+ // token without a restart (mergeSessionsFromDisk on verify miss).
+ const server = await import('./auth.js');
+ await server.setPassword({ newPassword: 'correct-horse' });
+ // Prime the server Map + mtime stamp.
+ expect(await server.verifySession('not-a-real-token')).toBe(false);
+
+ // Separate module namespace = separate Map, writing the shared session file
+ // the way an out-of-process mint does.
+ vi.resetModules();
+ const mint = await import('./auth.js');
+ const { token } = await mint.createSession({ label: 'keepalive' });
+
+ // The original server namespace is still alive (resetModules only affects
+ // subsequent imports). Its Map lacks `token` until the miss-path merge.
+ expect(await server.verifySession(token)).toBe(true);
+ });
+
it('stores sessions hashed at rest (plaintext token never lands in the file)', async () => {
const { readFileSync } = await import('fs');
const { join } = await import('path');
diff --git a/server/services/cos.js b/server/services/cos.js
index a292043bd0..c6752e4c5e 100644
--- a/server/services/cos.js
+++ b/server/services/cos.js
@@ -1663,9 +1663,17 @@ export async function init() {
const state = await loadState();
- // Auto-start if alwaysOn mode is enabled (or legacy autoStart)
- if (state.config.alwaysOn || state.config.autoStart) {
- console.log('🚀 CoS auto-starting (alwaysOn mode)');
+ // Auto-start when alwaysOn/autoStart is set, OR when the previous process left
+ // `running: true` on disk. The in-memory daemon flag dies with the process, but
+ // initializePersistentMindSupervisor (orphan-turn recovery + watchdog) only
+ // runs inside start(). Without this, a portos-server restart with the mind mid-
+ // turn leaves activeTurn stuck on disk forever — especially once the instance
+ // password is on and keepalive's unauthenticated POST /api/cos/start 401s.
+ if (state.config.alwaysOn || state.config.autoStart || state.running) {
+ const reason = (state.config.alwaysOn || state.config.autoStart)
+ ? 'alwaysOn mode'
+ : 'persisted running=true after restart';
+ console.log(`🚀 CoS auto-starting (${reason})`);
await start();
}
}
diff --git a/server/services/cos.test.js b/server/services/cos.test.js
index c7ad91d432..35be10f441 100644
--- a/server/services/cos.test.js
+++ b/server/services/cos.test.js
@@ -2525,6 +2525,21 @@ describe('pending-merge sweep — own timer, not the evaluation cadence (#3630)'
});
});
+describe('CoS startup — resume persisted running + mind recovery', () => {
+ // After a portos-server restart the in-memory daemon flag is false, but
+ // state.running may still be true on disk. initializePersistentMindSupervisor
+ // (orphan activeTurn recovery + watchdog) only runs inside start(), so boot
+ // must re-enter start() when the previous process left running=true — not
+ // only when alwaysOn/autoStart is set.
+ it('auto-starts on boot when state.running was persisted true', () => {
+ const initStart = COS_SRC.indexOf('export async function init(');
+ expect(initStart).toBeGreaterThan(-1);
+ const initFn = extractFnBody(COS_SRC, initStart);
+ expect(initFn).toMatch(/state\.config\.alwaysOn\s*\|\|\s*state\.config\.autoStart\s*\|\|\s*state\.running/);
+ expect(initFn).toMatch(/await start\(\)/);
+ });
+});
+
describe('CoS startup — single-flight recovery', () => {
it('shares the full boot promise across concurrent start callers', () => {
expect(COS_SRC).toMatch(/let daemonStartPromise = null/);
diff --git a/server/services/cosState.test.js b/server/services/cosState.test.js
index f11ba90e5d..d97fca16d2 100644
--- a/server/services/cosState.test.js
+++ b/server/services/cosState.test.js
@@ -164,11 +164,12 @@ describe('CoS config lives in its own file', () => {
});
// The shipped default is the ONLY thing stopping a never-configured install
- // from auto-starting CoS (server/services/cos.js reads `alwaysOn || autoStart`
- // at boot) and with it every work-generation flag that defaults on. That used
- // to be enforced by a data.reference/cos/config.json seed, which was deleted
- // in #6182's repair (migration 340) — so nothing but this literal enforces
- // AGENTS.md's "No cold-bootstrap LLM calls" for a fresh install now.
+ // from auto-starting CoS (server/services/cos.js reads
+ // `alwaysOn || autoStart || state.running` at boot — and a fresh install's
+ // state.running is false) and with it every work-generation flag that defaults
+ // on. That used to be enforced by a data.reference/cos/config.json seed, which
+ // was deleted in #6182's repair (migration 340) — so nothing but this literal
+ // enforces AGENTS.md's "No cold-bootstrap LLM calls" for a fresh install now.
it('defaults alwaysOn off so a fresh install never auto-starts CoS', async () => {
const { DEFAULT_CONFIG } = await freshModule();
expect(DEFAULT_CONFIG.alwaysOn).toBe(false);