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
fix: preserve completed CLI agents on shutdown (#3246)
[._.]/ Adam Eivy9fdce37c0b90
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex fe8c7aa432..1712263977 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -21,6 +21,10 @@- **[issue-3247] Forked sprites now validate their pinned render model before saving.** Invalid model IDs are rejected immediately instead of leaving a sprite pinned to a model that later renders cannot use or replace.+## Agents++- **[issue-3246] Completed direct-CLI agents now survive a PortOS restart without repeating their work.** When an agent has already written its completion sentinel, shutdown finalizes that result and dispatches its output instead of requeuing the task and potentially opening a duplicate pull request.+## POST- **[issue-3253] Powers practice now teaches a fast mental path before raising the difficulty.** New sessions begin with recall-friendly powers of two, unlock named techniques through speed-and-accuracy mastery, never generate a pair without a documented method, and show the worked steps after a miss and in session review. Manual base and exponent controls remain available when Progressive is switched off.diff --git a/server/lib/README.md b/server/lib/README.mdindex e463136f13..f0f53cfca5 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -161,7 +161,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `spawnCwd.js` | `resolveSpawnCwd(workspacePath, fallbackRoot, label)` — resolves and **logs** the working directory a run/agent spawns into (expanding `~`), and throws when a workspace was requested but is missing / not a directory. Behind `services/runner.js#resolveRunCwd`, which turns that throw into a normal failed-run record for the two spawning runners. Stops a bad app `repoPath` from silently spawning in the PortOS checkout (#3180). `withSpawnCwdEnv(env, cwd)` — returns a copy of `env` with `PWD` pinned to `cwd` (dropping stale case-variant keys), because `spawn({ cwd })` doesn't rewrite the inherited `PWD` and OpenCode resolves its project root as `process.env.PWD ?? process.cwd()` (#3193). Apply it at every spawn that names its own cwd — the shared wrappers (`bufferedSpawn`, `spawnDetached`) already do, so their callers inherit it. `spawnCwd.test.js` discovers cwd-passing spawns across `server/` and fails on any that neither pins nor is listed exempt.| `commandSecurity.js` | Allowlist of safe shell commands + `validatePm2Command(args)` (rejects daemon-wide `pm2 kill`/`startup`/`unstartup` and `<verb> all`). `validateCommand` runs the pm2 check for `pm2` base commands. Mirrored by the `agentGuard/` PATH shim for agentic paths. || `detachedSpawn.js` | `spawnDetached(bin, args, {controlDir,env,cwd})` → ChildProcess-like handle for a long media job that SURVIVES `pm2 restart portos-server`. A pure-`sh` double-fork reparents the job to init (escaping pm2's PPID-based TreeKill — `detached:true` alone doesn't, since it only changes the process group); the server tails on-disk log files for `stdout`/`stderr`/`close`. Used by loraTraining + videoGen. Also exports `reattachDetached(controlDir)` / `isReattachable(controlDir)` to RE-ATTACH a survivor after a restart (boot re-attach, #1332) and `reapDetached` to checkpoint-kill one when re-attach isn't possible. |-| `hostShutdown.js` | Tells "PortOS was restarted out from under a running agent" apart from "the agent failed" (#3202). `markHostShuttingDown()` / `isHostShuttingDown()` are the in-process latch the SIGTERM/SIGINT handler sets first thing, read by the TUI spawner so a PTY that dies under pm2's TreeKill is abandoned (worktree preserved) instead of finalized as a completed run. `writeHostShutdownMarker({agentIds,signal})` / `readHostShutdownMarker()` / `clearHostShutdownMarker()` persist that verdict to `data/cos/host-shutdown.json` so the NEXT boot's orphan sweep can requeue those agents as *interrupted* — no orphan-retry charge, no 30-minute cooldown. All non-throwing: a missing marker degrades to the ordinary orphan path. |+| `hostShutdown.js` | Tells "PortOS was restarted out from under a running agent" apart from "the agent failed" (#3202). `markHostShuttingDown()` / `isHostShuttingDown()` are the in-process latch the SIGTERM/SIGINT handler sets first thing; `shouldAbandonForHostShutdown({sentinelPresent,terminatedByUser,paused})` keeps every spawn path on the same preserve-vs-finalize policy. `writeHostShutdownMarker({agentIds,signal})` / `readHostShutdownMarker()` / `clearHostShutdownMarker()` persist that verdict to `data/cos/host-shutdown.json` so the NEXT boot's orphan sweep can requeue those agents as *interrupted* — no orphan-retry charge, no 30-minute cooldown. All non-throwing: a missing marker degrades to the ordinary orphan path. || `execGit.js` | `execGit` utility imported by `git.js` + worktree manager. || `ffmpeg.js` | Shared ffmpeg helpers (videoGen + videoTimeline). || `ffmpegRenderGuard.js` | `attachFfmpegRenderGuard(proc, {label, onSpawnError, onProcessError, onClose})` — shared spawn-state tracking + exactly-once `terminal` guard + pre-vs-post-spawn dispatch for the SSE ffmpeg render runners (musicVideo/render + videoTimeline/local). Owns the 'spawn'/'error'/'close' wiring (only the pre-spawn 'error' or 'close' finalizes; a post-spawn 'error' records only) and takes the service-specific finalize bodies as callbacks so each renderer keeps its own project-status/history behavior. |diff --git a/server/lib/hostShutdown.js b/server/lib/hostShutdown.jsindex 821c652c9e..11a8c626dc 100644--- a/server/lib/hostShutdown.js+++ b/server/lib/hostShutdown.js@@ -65,6 +65,22 @@ export function isHostShuttingDown() {return shuttingDown;}+/**+ * Should an agent exit be preserved for restart recovery instead of finalized?+ *+ * Completion, user termination, and pause are all authoritative outcomes that+ * retain their normal handling even when the host shutdown latch is set. Keep+ * this policy shared by every spawn path so their recovery behavior cannot+ * drift independently.+ */+export function shouldAbandonForHostShutdown({+ sentinelPresent = false,+ terminatedByUser = false,+ paused = false,+} = {}) {+ return shuttingDown && !sentinelPresent && !terminatedByUser && !paused;+}+/*** Reset the flag. Test-only — production never un-shuts-down.*/diff --git a/server/lib/hostShutdown.test.js b/server/lib/hostShutdown.test.jsindex 3054d3fff3..1916b4f1d3 100644--- a/server/lib/hostShutdown.test.js+++ b/server/lib/hostShutdown.test.js@@ -31,6 +31,7 @@ const { createTempDataRoot } = await import('./mockPathsDataRoot.js');const {markHostShuttingDown,isHostShuttingDown,+ shouldAbandonForHostShutdown,resetHostShutdownFlagForTests,writeHostShutdownMarker,readHostShutdownMarker,@@ -61,6 +62,19 @@ describe('in-process shutdown flag', () => {it('names a stable completion reason', () => {expect(HOST_SHUTDOWN_REASON).toBe('host-shutdown');});++ it('abandons only unfinished, unpaused runs that were not user-terminated', () => {+ markHostShuttingDown();++ expect(shouldAbandonForHostShutdown()).toBe(true);+ expect(shouldAbandonForHostShutdown({ sentinelPresent: true })).toBe(false);+ expect(shouldAbandonForHostShutdown({ terminatedByUser: true })).toBe(false);+ expect(shouldAbandonForHostShutdown({ paused: true })).toBe(false);+ });++ it('never abandons while the host is still running', () => {+ expect(shouldAbandonForHostShutdown()).toBe(false);+ });});describe('marker round-trip', () => {diff --git a/server/services/agentCliSpawning.js b/server/services/agentCliSpawning.jsindex 69a3a08b55..329c059d80 100644--- a/server/services/agentCliSpawning.js+++ b/server/services/agentCliSpawning.js@@ -34,7 +34,8 @@ import { resolveForgeTokenEnv } from './git.js';import { prepareCliSpawn, killProcessTree } from '../lib/bufferedSpawn.js';import { buildCliChildEnv } from '../lib/cliChildEnv.js';import { resolvePrCompletion } from '../lib/prDisposition.js';-import { isHostShuttingDown, HOST_SHUTDOWN_REASON } from '../lib/hostShutdown.js';+import { DONE_SENTINEL_NAME } from '../lib/agentSentinel.js';+import { isHostShuttingDown, shouldAbandonForHostShutdown, HOST_SHUTDOWN_REASON } from '../lib/hostShutdown.js';const AGENTS_DIR = PATHS.cosAgents;@@ -748,6 +749,8 @@ export async function spawnDirectly({const terminatedByUser = userTerminatedAgents.has(agentId);if (terminatedByUser) userTerminatedAgents.delete(agentId);+ const completionSentinelPresent = !!workspacePath && existsSync(join(workspacePath, DONE_SENTINEL_NAME));+ const completedBeforeHostShutdown = isHostShuttingDown() && completionSentinelPresent;// If the user terminated the agent, force success=false even if the// process happened to exit 0 in the race window — otherwise the run is@@ -755,8 +758,12 @@ export async function spawnDirectly({// `finish` path's `finalSuccess = terminatedByUser ? false : success`.// A mid-stream fallback signal (e.g. usage-limit hit) kills the CLI; if it// races to exit 0, don't record success or the fallback/retry never fires.+ // A completion sentinel written before host shutdown is also authoritative:+ // TreeKill may surface its otherwise-completed child with a null exit code.// Mirrors the runner path (`runner.js`) and the TUI finish() handling.- const finalSuccess = terminatedByUser ? false : (success && !immediateFallbackAnalysis);+ const finalSuccess = terminatedByUser+ ? false+ : ((success || completedBeforeHostShutdown) && !immediateFallbackAnalysis);const finalError = terminatedByUser ? 'Agent terminated by user' : null;// Drain any queued transcript writes before reading/appending outputBuffer@@ -816,7 +823,11 @@ export async function spawnDirectly({// The transcript is already flushed and output.txt written above.// A user-terminated run still finalizes, so it's recorded as such rather// than resurrected by the requeue.- if (isHostShuttingDown() && !terminatedByUser) {+ if (shouldAbandonForHostShutdown({+ sentinelPresent: completionSentinelPresent,+ terminatedByUser,+ paused: pausedAgents.has(agentId),+ })) {outputBatcher.push('🛑 PortOS restarted while this agent was running — the run was interrupted, not completed. Its worktree is preserved and the task will resume.');emitLog('warn', `Agent ${agentId} interrupted by a PortOS host restart — preserved for resume`, { agentId, phase: 'interrupted' });await Promise.all([diff --git a/server/services/agentCliSpawning.test.js b/server/services/agentCliSpawning.test.jsindex d381d7f63d..9e10d44b9a 100644--- a/server/services/agentCliSpawning.test.js+++ b/server/services/agentCliSpawning.test.js@@ -93,6 +93,7 @@ import { buildCliSpawnConfig, createStreamJsonParser, spawnDirectly } from './ag// Real module — the flag is a plain process-local boolean, so driving it// directly exercises the same code path production does.import { markHostShuttingDown, resetHostShutdownFlagForTests } from '../lib/hostShutdown.js';+import { existsSync } from 'fs';import { spawn } from 'child_process';import { prepareCliSpawn, killProcessTree } from '../lib/bufferedSpawn.js';@@ -481,6 +482,7 @@ describe('stream error containment', () => {(await import('./agentRunTracking.js')).completeAgentRun.mockResolvedValue(undefined);(await import('./agentFinalization.js')).finalizeAgent.mockResolvedValue(undefined);minimalArgs.cleanupWorktreeFn.mockResolvedValue(undefined);+ vi.mocked(existsSync).mockReturnValue(false);// Reset the resolve+wrap helper to its POSIX passthrough before each test// (afterEach's restoreAllMocks can clear the factory implementation).vi.mocked(prepareCliSpawn).mockImplementation((command, args) => ({ command, args }));@@ -819,11 +821,11 @@ describe('stream error containment', () => {afterEach(() => resetHostShutdownFlagForTests());- const runToClose = async (args) => {+ const runToClose = async (args, code = 0) => {spawnDirectly(args);await new Promise((r) => setTimeout(r, 10));markHostShuttingDown();- fakeProcess.emit('close', 0);+ fakeProcess.emit('close', code);await new Promise((r) => setTimeout(r, 80));};@@ -854,5 +856,20 @@ describe('stream error containment', () => {);userTerminatedAgents.delete(minimalArgs.agentId);});++ it('still finalizes when the agent already wrote its completion sentinel', async () => {+ const { finalizeAgent } = await import('./agentFinalization.js');+ vi.mocked(existsSync).mockImplementation((path) => path === '/tmp/.agent-done');++ await runToClose({ ...minimalArgs }, null);++ expect(finalizeAgent).toHaveBeenCalledWith(+ expect.objectContaining({+ agentId: minimalArgs.agentId,+ success: true,+ workspacePath: minimalArgs.workspacePath,+ }),+ );+ });});});diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.jsindex ace5cc47e9..fdc6c97bc9 100644--- a/server/services/agentTuiSpawning.js+++ b/server/services/agentTuiSpawning.js@@ -19,7 +19,7 @@ import { finalizeAgent, releaseAgentLane } from './agentFinalization.js';import { activeAgents, userTerminatedAgents, pausedAgents, isFalsyMeta } from './agentState.js';import { PATHS } from '../lib/fileUtils.js';import { DONE_SENTINEL_NAME, parseSentinelPayload } from '../lib/agentSentinel.js';-import { isHostShuttingDown, HOST_SHUTDOWN_REASON } from '../lib/hostShutdown.js';+import { shouldAbandonForHostShutdown, HOST_SHUTDOWN_REASON } from '../lib/hostShutdown.js';import { SENTINEL_COMPLETION_MARKER } from '../lib/agentOutputMarkers.js';import { resolvePrCompletion } from '../lib/prDisposition.js';import { canTypeSlashCommands } from '../lib/slashdoInvocation.js';@@ -545,10 +545,11 @@ export async function spawnTuiAgent({// recovery's user-terminated skip would miss it and resurrect the run. And a// run the user paused already has its own don't-finalize branch below, which// owns the paused bookkeeping (pid unregister, activeAgents delete).- if (isHostShuttingDown()- && !sentinelPresent()- && !userTerminatedAgents.has(agentId)- && !pausedAgents.has(agentId)) {+ if (shouldAbandonForHostShutdown({+ sentinelPresent: sentinelPresent(),+ terminatedByUser: userTerminatedAgents.has(agentId),+ paused: pausedAgents.has(agentId),+ })) {await abandonForHostShutdown();return;}