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: skip CoS agent spawns while a self-update is in progress (#4124)

[._.]/ Adam Eivy3129e7895f1c
diff --git a/.changelog/next/fixed-issue-4124.md b/.changelog/next/fixed-issue-4124.md
new file mode 100644
index 0000000000..aac0928ae6
--- /dev/null
+++ b/.changelog/next/fixed-issue-4124.md
@@ -0,0 +1 @@
+- CoS agents no longer spawn into a server that a self-update is about to restart — a task dispatched during update.sh now stays queued and runs after the restart instead of being severed mid-run
diff --git a/server/routes/update.js b/server/routes/update.js
index 781a6db559..58e1c09d71 100644
--- a/server/routes/update.js
+++ b/server/routes/update.js
@@ -219,7 +219,10 @@ router.post('/execute', asyncHandler(async (req, res) => {
// spawn) may have started live during the git/fork awaits between the
// fast-fail pre-check and here. If so, release the lock and reject rather than
// restart out from under it. A spawn that begins AFTER this, during update.sh
- // itself, is the residual the #4124 spawn-engine gate will close.
+ // itself, is closed from the spawn side: the lock we just acquired flips
+ // `updateChecker.isUpdateInProgress()`, which subAgentSpawner's `task:ready`
+ // listener and `spawnAgentForTask` both check, holding the task as `pending`
+ // until after the restart (issue #4124).
const postLock = countActiveCosAgents();
if (postLock > 0) {
await updateChecker.setUpdateInProgress(false);
diff --git a/server/services/agentGuards.js b/server/services/agentGuards.js
index 7398ee2cee..44c1e6c295 100644
--- a/server/services/agentGuards.js
+++ b/server/services/agentGuards.js
@@ -5,8 +5,9 @@
* ~470-LOC `spawnAgentForTask` and `handleAgentCompletion` orchestrators
* (agentLifecycle.js) so the concurrency contracts they enforce are unit-
* testable against the REAL code path instead of a hand-copied replica
- * (issue #2548). Both operate purely on a Set/Map passed in — no module
- * state, no I/O — so a test can drive them with a throwaway collection.
+ * (issue #2548). All of them operate purely on the collection/predicate passed
+ * in — no module state, no I/O — so a test can drive them with a throwaway
+ * collection or a stub predicate.
*/
/**
@@ -48,6 +49,39 @@ export async function withSpawnDedupGuard(spawningTasks, taskId, fn) {
}
}
+/**
+ * Sentinel returned by `withUpdateInProgressGuard` when a PortOS self-update is
+ * running. A distinct Symbol from `SPAWN_DEDUP_SKIP` so the caller can log the
+ * right reason — "held for an update" is a temporary, self-clearing hold, not a
+ * duplicate dispatch — while both share the same "no-op, leave the task queued"
+ * contract.
+ */
+export const SPAWN_UPDATE_SKIP = Symbol('spawn-update-skip');
+
+/**
+ * Run `fn` only when no self-update is in progress.
+ *
+ * Contract (the race closed by issue #4124): `/api/update/execute` blocks on
+ * live CoS agents both before and after acquiring the update lock, but
+ * `update.sh` then spends multiple seconds in `git pull` / submodule update /
+ * `npm install` before it reaches `pm2 delete`. An agent that starts inside
+ * THAT window is severed by the restart — its PTY/child process is a child of
+ * this server. This guard closes it from the spawn side: while the update flag
+ * is set, a spawn is a no-op and the task stays queued for after the restart,
+ * rather than burning a spawn (and its retry budget) on a doomed run.
+ *
+ * The predicate is injected rather than imported so this module stays free of
+ * module state and I/O, and so a test can drive the real guard with a stub.
+ *
+ * @param {() => boolean} isUpdateInProgress - synchronous flag reader
+ * @param {() => Promise<any>} fn - the guarded spawn work
+ * @returns {Promise<any|typeof SPAWN_UPDATE_SKIP>}
+ */
+export async function withUpdateInProgressGuard(isUpdateInProgress, fn) {
+ if (isUpdateInProgress()) return SPAWN_UPDATE_SKIP;
+ return fn();
+}
+
/**
* Run `fn`, then unconditionally delete `key` from `map` in a `finally`.
*
diff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.js
index 1493d60b67..5f7c4e5657 100644
--- a/server/services/agentLifecycle.js
+++ b/server/services/agentLifecycle.js
@@ -65,7 +65,8 @@ import { ensureInstanceId } from './instances.js';
import { isClaimableBy, buildClaim, buildRelease, getClaimOwner } from './cosTaskClaim.js';
import { resolveForgeTokenEnv } from './git.js';
import { runnerAgents, pausedAgents, spawningTasks, useRunner, isTruthyMeta } from './agentState.js';
-import { withSpawnDedupGuard, withMapEntryCleanup, SPAWN_DEDUP_SKIP } from './agentGuards.js';
+import { withSpawnDedupGuard, withMapEntryCleanup, withUpdateInProgressGuard, SPAWN_DEDUP_SKIP, SPAWN_UPDATE_SKIP } from './agentGuards.js';
+import { isUpdateInProgress } from './updateChecker.js';
import { v4 as uuidv4 } from '../lib/uuid.js';
// Extracted helpers — these carve the two giant orchestrators
@@ -99,9 +100,24 @@ const AGENTS_DIR = PATHS.cosAgents;
* it in a `finally` so no early `return null` or throw can strand the task id
* in the set. Extracting the guard makes the late-delete race it closes
* unit-testable against the real helper (issue #2548) instead of a replica.
+ *
+ * Outside that, `withUpdateInProgressGuard` holds every spawn while a PortOS
+ * self-update is running (issue #4124) — `update.sh` pm2-restarts this server,
+ * which severs any agent it started, so the task stays queued for after the
+ * restart instead. This is the LAST-LINE gate: the primary hold sits at
+ * subAgentSpawner's `task:ready` listener, where the app-review marker and the
+ * job spawn-failed signal can also be released (an unconditional bail from here
+ * would strand both — the #989 failure mode). Both exist because this is the
+ * one function every spawn path ends at, so a future direct caller that
+ * bypasses the listener is still gated.
*/
export async function spawnAgentForTask(task) {
- const outcome = await withSpawnDedupGuard(spawningTasks, task.id, () => runAgentSpawn(task));
+ const outcome = await withUpdateInProgressGuard(isUpdateInProgress, () =>
+ withSpawnDedupGuard(spawningTasks, task.id, () => runAgentSpawn(task)));
+ if (outcome === SPAWN_UPDATE_SKIP) {
+ console.log(`⏸️ Holding task ${task.id} — a PortOS self-update is in progress`);
+ return null;
+ }
if (outcome === SPAWN_DEDUP_SKIP) {
console.log(`⚠️ Task ${task.id} already being spawned, skipping duplicate`);
return null;
diff --git a/server/services/agentLifecycle.test.js b/server/services/agentLifecycle.test.js
index afe094c2ff..54eb1e2e92 100644
--- a/server/services/agentLifecycle.test.js
+++ b/server/services/agentLifecycle.test.js
@@ -26,11 +26,11 @@
*/
import { describe, it, expect, beforeEach } from 'vitest';
-import { readFileSync } from 'fs';
+import { readFileSync, readdirSync } from 'fs';
import { fileURLToPath } from 'url';
import { dirname, join } from 'path';
import { spawningTasks, runnerAgents } from './agentState.js';
-import { withSpawnDedupGuard, withMapEntryCleanup, SPAWN_DEDUP_SKIP } from './agentGuards.js';
+import { withSpawnDedupGuard, withMapEntryCleanup, withUpdateInProgressGuard, SPAWN_DEDUP_SKIP, SPAWN_UPDATE_SKIP } from './agentGuards.js';
import { isInternalTaskId } from '../lib/taskParser.js';
const __dirname = dirname(fileURLToPath(import.meta.url));
@@ -117,6 +117,56 @@ describe('withSpawnDedupGuard — spawn dedup guard', () => {
});
});
+// ─── withUpdateInProgressGuard — the self-update spawn hold (issue #4124) ───
+
+describe('withUpdateInProgressGuard — self-update spawn hold', () => {
+ it('runs the spawn body when no update is in progress', async () => {
+ let ran = false;
+ const result = await withUpdateInProgressGuard(() => false, async () => {
+ ran = true;
+ return 'agent-1';
+ });
+ expect(ran).toBe(true);
+ expect(result).toBe('agent-1');
+ });
+
+ it('returns SPAWN_UPDATE_SKIP without running the body while an update is in progress', async () => {
+ let ran = false;
+ const result = await withUpdateInProgressGuard(() => true, async () => {
+ ran = true;
+ return 'agent-2';
+ });
+ // The whole point: no agent process is created inside the window where
+ // update.sh is about to pm2-delete this server. The task record is never
+ // touched, so it stays `pending` and runs after the restart.
+ expect(ran).toBe(false);
+ expect(result).toBe(SPAWN_UPDATE_SKIP);
+ });
+
+ it('reads the flag on EVERY call, so the hold releases when the update settles', async () => {
+ let updating = true;
+ const isUpdating = () => updating;
+ expect(await withUpdateInProgressGuard(isUpdating, async () => 'spawned')).toBe(SPAWN_UPDATE_SKIP);
+ updating = false;
+ expect(await withUpdateInProgressGuard(isUpdating, async () => 'spawned')).toBe('spawned');
+ });
+
+ it('uses a sentinel distinct from the dedup skip, so the two holds stay distinguishable', () => {
+ expect(SPAWN_UPDATE_SKIP).not.toBe(SPAWN_DEDUP_SKIP);
+ });
+
+ it('checks the flag OUTSIDE the dedup guard, so a held task leaves no stranded guard entry', async () => {
+ // Mirrors how spawnAgentForTask composes them. If the update check sat
+ // inside withSpawnDedupGuard the task id would be added and removed for a
+ // spawn that never happened — harmless today, but it would also mean the
+ // dedup set churned once per held dispatch during the whole update window.
+ const outcome = await withUpdateInProgressGuard(() => true, () =>
+ withSpawnDedupGuard(spawningTasks, 'task-held', async () => 'agent-3'));
+ expect(outcome).toBe(SPAWN_UPDATE_SKIP);
+ expect(spawningTasks.has('task-held')).toBe(false);
+ });
+});
+
// ─── The reported late-delete race, driven by the real guard ────────────────
describe('spawnAgentForTask dedup — late-delete race (issue #2548 / #1563)', () => {
@@ -240,6 +290,91 @@ describe('agentLifecycle — guard wiring', () => {
expect(body).toMatch(/SPAWN_DEDUP_SKIP/);
});
+ // Issue #4124: `/api/update/execute` refuses to start while an agent is live,
+ // but `update.sh` then runs git pull / submodule update / npm install for
+ // seconds before `pm2 delete`. This is the last-line gate for a spawn landing
+ // in THAT window.
+ it('spawnAgentForTask wraps the spawn in withUpdateInProgressGuard(isUpdateInProgress)', () => {
+ const idx = AGENT_LIFECYCLE_SRC.indexOf('export async function spawnAgentForTask');
+ expect(idx, 'spawnAgentForTask must exist').toBeGreaterThan(-1);
+ const body = AGENT_LIFECYCLE_SRC.slice(idx, idx + 1200);
+ expect(body).toMatch(/withUpdateInProgressGuard\(\s*isUpdateInProgress\s*,/);
+ expect(body).toMatch(/SPAWN_UPDATE_SKIP/);
+ // The synchronous mirror, not a re-implemented disk read.
+ expect(AGENT_LIFECYCLE_SRC).toMatch(/import \{ isUpdateInProgress \} from '\.\/updateChecker\.js'/);
+ });
+});
+
+// ─── Coverage guard for the self-update spawn gate (issue #4124) ────────────
+//
+// The gate is argued to cover EVERY path that can start an agent because those
+// paths funnel through exactly two chokepoints: `task:ready` → subAgentSpawner's
+// listener → `spawnAgentForTask` → one of the three low-level spawn helpers.
+// Gating fewer files than "every spawn engine" is only sound while that funnel
+// holds, so pin it: a new direct caller of `spawnAgentForTask` or of a spawn
+// helper would bypass the gate and must fail here rather than in production.
+
+describe('self-update spawn gate — funnel coverage (#4124)', () => {
+ const SERVICES_DIR = __dirname;
+
+ /** Every non-test .js under server/services (recursively), with its source. */
+ const serviceSources = () => {
+ const out = [];
+ const walk = (dir) => {
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
+ const full = join(dir, entry.name);
+ if (entry.isDirectory()) { walk(full); continue; }
+ if (!entry.name.endsWith('.js') || entry.name.includes('.test.')) continue;
+ out.push({ path: full, src: readFileSync(full, 'utf-8') });
+ }
+ };
+ walk(SERVICES_DIR);
+ return out;
+ };
+
+ /**
+ * Files whose source invokes `name(` somewhere other than its own
+ * declaration, relative to server/services and sorted. Listing the DEFINING
+ * file too keeps the assertions non-vacuous: a regex that silently stopped
+ * matching would drop that file and fail, instead of passing as an empty set.
+ */
+ const invokersOf = (name) => serviceSources()
+ .filter(({ src }) => new RegExp(`(?<!function )\\b${name}\\(`).test(src))
+ .map(({ path }) => path.slice(SERVICES_DIR.length + 1))
+ .sort();
+
+ it('spawnAgentForTask is invoked from exactly one place — the gated task:ready listener', () => {
+ expect(
+ invokersOf('spawnAgentForTask'),
+ 'a new caller of spawnAgentForTask must also carry the self-update hold (see subAgentSpawner.js)'
+ ).toEqual(['agentLifecycle.js', 'subAgentSpawner.js']);
+ });
+
+ it('the three low-level spawn helpers are invoked only from the gated dispatch', () => {
+ // If any other module called these directly it would create an agent
+ // process without passing spawnAgentForTask's update guard at all.
+ for (const helper of ['spawnTuiAgent', 'spawnViaRunner', 'spawnDirectly']) {
+ expect(
+ invokersOf(helper),
+ `${helper} must stay reachable only through spawnAgentForTask`
+ ).toEqual(['agentLifecycle.js']);
+ }
+ });
+
+ it('subAgentSpawner holds the dispatch on the synchronous update flag', () => {
+ const src = readFileSync(join(SERVICES_DIR, 'subAgentSpawner.js'), 'utf-8');
+ expect(src).toMatch(/import \{ isUpdateInProgress \} from '\.\/updateChecker\.js'/);
+ const idx = src.indexOf("cosEvents.on('task:ready'");
+ expect(idx, 'the task:ready listener must exist').toBeGreaterThan(-1);
+ const spawnIdx = src.indexOf('await spawnAgentForTask(task)', idx);
+ expect(spawnIdx).toBeGreaterThan(idx);
+ // The hold is BEFORE the spawn, and before the (awaited) runner probe — a
+ // synchronous check can't be raced by anything in between.
+ const preamble = src.slice(idx, spawnIdx);
+ expect(preamble).toMatch(/if \(isUpdateInProgress\(\)\) \{\s*return holdTask\(task,/);
+ expect(preamble.indexOf('isUpdateInProgress()')).toBeLessThan(preamble.indexOf('isRunnerReachable()'));
+ });
+
it('handleAgentCompletion delegates runnerAgents cleanup to withMapEntryCleanup', () => {
const idx = AGENT_LIFECYCLE_SRC.indexOf('export async function handleAgentCompletion');
expect(idx, 'handleAgentCompletion must exist').toBeGreaterThan(-1);
diff --git a/server/services/subAgentSpawner.runnerHold.test.js b/server/services/subAgentSpawner.dispatchHolds.test.js
similarity index 65%
rename from server/services/subAgentSpawner.runnerHold.test.js
rename to server/services/subAgentSpawner.dispatchHolds.test.js
index 7f6e0e4c8b..4bbfd7aa1d 100644
--- a/server/services/subAgentSpawner.runnerHold.test.js
+++ b/server/services/subAgentSpawner.dispatchHolds.test.js
@@ -1,12 +1,20 @@
/**
- * Runner-down HOLD at the dispatch chokepoint, and the reconnect that releases it.
+ * The two dispatch HOLDS at the `task:ready` chokepoint, and what releases them.
*
- * `portos-cos` is a separate PM2 app the user can stop from the Apps page, and
- * in runner mode it owns every agent process. Dispatching into a stopped runner
- * is not a task failure, but both spawn arms recorded it as one — see the
- * `task:ready` listener in subAgentSpawner.js for the two failure modes.
+ * Both leave the task queued for a condition that clears on its own, rather than
+ * failing it:
*
- * The hold lives in that listener, not inside `runAgentSpawn`, because a hold
+ * - Runner down. `portos-cos` is a separate PM2 app the user can stop from the
+ * Apps page, and in runner mode it owns every agent process. Dispatching into
+ * a stopped runner is not a task failure, but both spawn arms recorded it as
+ * one — see the `task:ready` listener in subAgentSpawner.js for the two
+ * failure modes.
+ * - Self-update in progress (issue #4124). `/api/update/execute` refuses to
+ * start while an agent is live, but `update.sh` then spends seconds in git
+ * pull / submodule update / npm install before `pm2 delete`. An agent spawned
+ * in that window is severed by the restart.
+ *
+ * The holds live in that listener, not inside `runAgentSpawn`, because a hold
* below the spawn body's entry returns past `releaseAppReviewMarker` and strands
* the synthetic "in review" marker for the whole outage (issue #989). The two
* side effects the dequeue tiers already committed — that marker and the
@@ -40,6 +48,7 @@ vi.mock('./agentLifecycle.js', () => ({ handleAgentCompletion: vi.fn() }));
vi.mock('./agentManagement.js', () => ({ cleanupOrphanedAgents: vi.fn().mockResolvedValue(undefined) }));
vi.mock('./agentRunTracking.js', () => ({ completeAgentRun: vi.fn() }));
vi.mock('./appActivity.js', () => ({ releaseAppReviewMarker: vi.fn().mockResolvedValue(undefined) }));
+vi.mock('./updateChecker.js', () => ({ isUpdateInProgress: vi.fn().mockReturnValue(false) }));
vi.mock('./agentOrchestrator.js', () => ({
completeAgent: vi.fn(),
spawnAgentForTask: vi.fn().mockResolvedValue('agent-1'),
@@ -54,6 +63,7 @@ import { cosEvents, emitLog } from './cosEvents.js';
import { isRunnerReachable } from './cosRunnerClient.js';
import { spawnAgentForTask } from './agentOrchestrator.js';
import { releaseAppReviewMarker } from './appActivity.js';
+import { isUpdateInProgress } from './updateChecker.js';
import { setUseRunner } from './agentState.js';
const dispatch = (task) => taskHandlers.get('task:ready')(task);
@@ -65,6 +75,7 @@ describe('subAgentSpawner — runner-down hold', () => {
vi.useRealTimers();
setUseRunner(true);
isRunnerReachable.mockResolvedValue(true);
+ isUpdateInProgress.mockReturnValue(false);
});
it('spawns normally while the runner is up', async () => {
@@ -116,6 +127,64 @@ describe('subAgentSpawner — runner-down hold', () => {
});
});
+describe('subAgentSpawner — self-update hold (#4124)', () => {
+ beforeEach(async () => {
+ await initSpawner();
+ vi.clearAllMocks();
+ vi.useRealTimers();
+ setUseRunner(true);
+ isRunnerReachable.mockResolvedValue(true);
+ isUpdateInProgress.mockReturnValue(false);
+ });
+
+ it('holds the task instead of spawning into a process update.sh is about to restart', async () => {
+ isUpdateInProgress.mockReturnValue(true);
+
+ await dispatch({ id: 'cos-u1', metadata: {} });
+
+ // No agent is created, and the task record is untouched — it stays
+ // `pending` and is picked up by the first dequeue after the restart.
+ expect(spawnAgentForTask).not.toHaveBeenCalled();
+ });
+
+ it('holds BEFORE the awaited runner probe, so nothing can race between check and spawn', async () => {
+ isUpdateInProgress.mockReturnValue(true);
+
+ await dispatch({ id: 'cos-u2', metadata: {} });
+
+ expect(isRunnerReachable).not.toHaveBeenCalled();
+ });
+
+ it('releases the app-review marker and the job spawn reservation, same as the runner hold', async () => {
+ isUpdateInProgress.mockReturnValue(true);
+
+ await dispatch({ id: 'cos-u3', metadata: { app: 'some-app', jobId: 'job-9' } });
+
+ expect(releaseAppReviewMarker).toHaveBeenCalledWith('some-app');
+ expect(cosEvents.emit).toHaveBeenCalledWith('job:spawn-failed', { jobId: 'job-9' });
+ });
+
+ it('resumes spawning once the update settles — the hold is not sticky', async () => {
+ isUpdateInProgress.mockReturnValue(true);
+ await dispatch({ id: 'cos-u4', metadata: {} });
+ expect(spawnAgentForTask).not.toHaveBeenCalled();
+
+ isUpdateInProgress.mockReturnValue(false);
+ await dispatch({ id: 'cos-u4', metadata: {} });
+
+ expect(spawnAgentForTask).toHaveBeenCalledTimes(1);
+ });
+
+ it('holds in direct mode too, where there is no runner probe to hide behind', async () => {
+ setUseRunner(false);
+ isUpdateInProgress.mockReturnValue(true);
+
+ await dispatch({ id: 'cos-u5', metadata: {} });
+
+ expect(spawnAgentForTask).not.toHaveBeenCalled();
+ });
+});
+
describe('subAgentSpawner — runner connection events', () => {
beforeEach(async () => {
await initSpawner();
diff --git a/server/services/subAgentSpawner.js b/server/services/subAgentSpawner.js
index 0e81cf4394..0646af4165 100644
--- a/server/services/subAgentSpawner.js
+++ b/server/services/subAgentSpawner.js
@@ -44,6 +44,7 @@ import { cleanupOrphanedAgents } from './agentManagement.js';
import { completeAgentRun } from './agentRunTracking.js';
import { runnerAgents, setUseRunner, useRunner } from './agentState.js';
import { releaseAppReviewMarker } from './appActivity.js';
+import { isUpdateInProgress } from './updateChecker.js';
// This module's own event wiring drives three LIFECYCLE TRANSITIONS, so it takes
// them from the facade rather than from the three separate leaves that happen to
// implement them (#3450). It can: nothing the facade imports imports this module
@@ -56,6 +57,34 @@ const RUNS_DIR = PATHS.runs;
const RECONNECT_DEQUEUE_DEBOUNCE_MS = 1000;
let reconnectDequeueTimer = null;
+/**
+ * Decline a `task:ready` dispatch WITHOUT failing the task.
+ *
+ * The task record is left untouched (still `pending`), so the next dequeue tick
+ * picks it up once `reason` clears — no status write, no retry charged, no
+ * `blocked` walk. What must still be undone is the state the emitter bound in
+ * anticipation of a spawn:
+ *
+ * - the synthetic app-review marker, or the app reads "in review" for the
+ * whole outage (issue #989);
+ * - `spawningJobIds` for a scheduled job, cleared by `job:spawn-failed`,
+ * which also re-registers the cron schedule. Without it an autonomous job
+ * sits wedged until the scheduler's 5-minute spawn timeout — per job, per
+ * outage.
+ *
+ * Shared by both hold conditions (self-update in progress, runner down) so a
+ * third one can't ship with only half the releases.
+ */
+async function holdTask(task, reason) {
+ emitLog('debug', `⏸️ Holding task ${task.id} — ${reason}`, { taskId: task.id });
+ await releaseAppReviewMarker(task.metadata?.app).catch(err =>
+ emitLog('warn', `Failed to release app review marker for ${task.metadata?.app}: ${err.message}`, { taskId: task.id })
+ );
+ if (task.metadata?.jobId) {
+ cosEvents.emit('job:spawn-failed', { jobId: task.metadata.jobId });
+ }
+}
+
/**
* Load a slashdo command from the bundled submodule, resolving !`cat` lib includes inline.
*/
@@ -225,30 +254,33 @@ async function runInitSpawner() {
}
cosEvents.on('task:ready', async (task) => {
- // Runner-down HOLD, at the one chokepoint all seven `task:ready` emitters
- // funnel through. Dispatching into a stopped runner is not a task failure,
- // but both spawn arms recorded it as one: the CLI arm finalized
- // `spawn-rejected` (a retry each time, so a runner left off overnight walked
- // every queued task through its retry budget into `blocked`), and the TUI arm
- // threw into the actionable `spawn-error`, parking the task for a human over
- // an app the user simply turned off.
+ // ── HOLDS, at the one chokepoint all seven `task:ready` emitters funnel
+ // through. Both leave the task queued (no status write, no retry charged)
+ // for a condition that clears on its own.
//
// Held HERE rather than inside `runAgentSpawn`: a hold below this line would
// return past `releaseAppReviewMarker`, stranding the synthetic "in review"
- // marker for the whole outage — issue #989's exact failure mode. The two
- // releases below are the same ones the spawn body owns.
+ // marker for the whole outage — issue #989's exact failure mode. The
+ // releases in `holdTask` are the same ones the spawn body owns.
+ //
+ // 1. Self-update in progress (issue #4124). `/api/update/execute` refuses to
+ // start while an agent is live, but `update.sh` then spends multiple
+ // seconds in `git pull` / submodule update / `npm install` before it
+ // reaches `pm2 delete` — an agent spawned inside that window is severed
+ // by the restart (its PTY/child process is a child of this server). The
+ // flag reads synchronously, so nothing can slip between the check and the
+ // spawn; the task runs on the other side of the restart.
+ if (isUpdateInProgress()) {
+ return holdTask(task, 'a PortOS self-update is in progress');
+ }
+ // 2. Runner down. Dispatching into a stopped runner is not a task failure,
+ // but both spawn arms recorded it as one: the CLI arm finalized
+ // `spawn-rejected` (a retry each time, so a runner left off overnight
+ // walked every queued task through its retry budget into `blocked`), and
+ // the TUI arm threw into the actionable `spawn-error`, parking the task
+ // for a human over an app the user simply turned off.
if (useRunner && !(await isRunnerReachable())) {
- emitLog('debug', `⏸️ Holding task ${task.id} — CoS Runner is down`, { taskId: task.id });
- await releaseAppReviewMarker(task.metadata?.app).catch(err =>
- emitLog('warn', `Failed to release app review marker for ${task.metadata?.app}: ${err.message}`, { taskId: task.id })
- );
- // Clears `spawningJobIds` immediately and re-registers the cron schedule.
- // Without it an autonomous job sits wedged until the scheduler's 5-minute
- // spawn timeout — per job, per outage.
- if (task.metadata?.jobId) {
- cosEvents.emit('job:spawn-failed', { jobId: task.metadata.jobId });
- }
- return;
+ return holdTask(task, 'CoS Runner is down');
}
try {
await spawnAgentForTask(task);
diff --git a/server/services/updateChecker.js b/server/services/updateChecker.js
index 65b2780737..2b2bd45f13 100644
--- a/server/services/updateChecker.js
+++ b/server/services/updateChecker.js
@@ -30,6 +30,42 @@ export const updateEvents = new EventEmitter();
const withLock = createMutex();
+// ─── Synchronous in-memory mirror of the persisted `updateInProgress` flag ───
+//
+// The flag itself lives in `data/update.json` and is only readable through an
+// `await` (loadState). The CoS spawn engines need the answer SYNCHRONOUSLY, at
+// the top of a spawn, to hold a task rather than launch an agent into a process
+// `update.sh` is about to `pm2 delete` (issue #4124). Awaiting a disk read there
+// would both slow the hot dispatch path and re-open the very window the gate
+// exists to close, so this module keeps a boolean in lockstep with every write
+// it makes to the persisted flag.
+//
+// Semantics — deliberately PROCESS-LOCAL, and NOT hydrated from disk on boot:
+// - It flips only where this module actually WRITES `state.updateInProgress`
+// (setUpdateInProgress, recordUpdateResult, clearStaleUpdateInProgress's
+// clear branch). A `setUpdateInProgress(true)` that loses the atomic
+// check-and-set writes nothing, so it leaves the mirror alone.
+// - It starts `false` on every boot because a *running* server process is by
+// definition post-restart: `update.sh` pm2-deletes the old process before it
+// starts a new one, so nothing this process spawns can be severed by an
+// update that was already underway. Hydrating a persisted `true` (which
+// survives a killed-mid-update cycle until `clearStaleUpdateInProgress`
+// ages it out at 30 minutes) would instead wedge CoS for half an hour.
+let updateInProgressMirror = false;
+
+/**
+ * Is a self-update running in THIS process right now?
+ *
+ * Synchronous, allocation-free, and safe to call on every spawn attempt.
+ * `true` from the moment `/api/update/execute` acquires the update lock until
+ * the update settles (`recordUpdateResult`) or is released — i.e. exactly the
+ * window in which `update.sh` may pm2-restart the server out from under a
+ * freshly spawned agent.
+ */
+export function isUpdateInProgress() {
+ return updateInProgressMirror;
+}
+
let schedulerInterval = null;
let startupTimeout = null;
@@ -297,6 +333,9 @@ export async function setUpdateInProgress(inProgress) {
state.updateInProgress = inProgress;
state.updateStartedAt = inProgress ? new Date().toISOString() : null;
await saveState(state);
+ // Mirror BEFORE returning so the caller's next synchronous statement — and
+ // any spawn engine that runs before the next tick — already sees the gate.
+ updateInProgressMirror = inProgress;
return true;
});
}
@@ -311,6 +350,7 @@ export async function recordUpdateResult(result) {
state.updateStartedAt = null;
state.lastUpdateResult = result;
await saveState(state);
+ updateInProgressMirror = false;
});
}
@@ -396,6 +436,7 @@ export async function clearStaleUpdateInProgress() {
log: 'Cleared stale update lock on boot — server was likely killed mid-update'
};
await saveState(state);
+ updateInProgressMirror = false;
return true;
}
diff --git a/server/services/updateChecker.test.js b/server/services/updateChecker.test.js
index 048a746e0c..075353f066 100644
--- a/server/services/updateChecker.test.js
+++ b/server/services/updateChecker.test.js
@@ -54,7 +54,10 @@ import {
getRemoteInfo,
syncFork,
processUpdateMarker,
- updateEvents
+ updateEvents,
+ isUpdateInProgress,
+ setUpdateInProgress,
+ recordUpdateResult
} from './updateChecker.js';
describe('compareSemver', () => {
@@ -439,6 +442,102 @@ describe('clearStaleUpdateInProgress', () => {
});
});
+// ─── isUpdateInProgress — the synchronous mirror (issue #4124) ──────────────
+//
+// The CoS spawn engines gate on this to avoid launching an agent into a process
+// `update.sh` is about to `pm2 delete`. It must track every write this module
+// makes to the persisted flag — a mirror that drifts either wedges CoS (stuck
+// true) or silently re-opens the race (stuck false).
+
+describe('isUpdateInProgress mirror', () => {
+ const persisted = (overrides = {}) => ({
+ lastCheck: null,
+ latestRelease: null,
+ ignoredVersions: [],
+ updateInProgress: false,
+ updateStartedAt: null,
+ lastUpdateResult: null,
+ ...overrides
+ });
+
+ beforeEach(async () => {
+ vi.clearAllMocks();
+ atomicWrite.mockResolvedValue(undefined);
+ ensureDir.mockResolvedValue(undefined);
+ // Module state is shared across tests in this file — return to the boot
+ // value so each case starts from a known mirror.
+ readJSONFile.mockResolvedValue(persisted({ updateInProgress: true }));
+ await recordUpdateResult({ version: '0.0.0', success: true, completedAt: null, log: '' });
+ // …and forget the reset's own write, so a test can assert on writes.
+ atomicWrite.mockClear();
+ });
+
+ it('starts false — a live process is by definition post-restart', () => {
+ expect(isUpdateInProgress()).toBe(false);
+ });
+
+ it('flips true the moment setUpdateInProgress(true) acquires the lock', async () => {
+ readJSONFile.mockResolvedValue(persisted());
+
+ const acquired = await setUpdateInProgress(true);
+
+ expect(acquired).toBe(true);
+ expect(isUpdateInProgress()).toBe(true);
+ // Lockstep: what the mirror reports is what was persisted.
+ const saved = JSON.parse(atomicWrite.mock.calls.at(-1)[1]);
+ expect(saved.updateInProgress).toBe(true);
+ });
+
+ it('flips back to false when the lock is released', async () => {
+ readJSONFile.mockResolvedValue(persisted());
+ await setUpdateInProgress(true);
+
+ readJSONFile.mockResolvedValue(persisted({ updateInProgress: true }));
+ await setUpdateInProgress(false);
+
+ expect(isUpdateInProgress()).toBe(false);
+ });
+
+ it('flips back to false when the update settles via recordUpdateResult', async () => {
+ readJSONFile.mockResolvedValue(persisted());
+ await setUpdateInProgress(true);
+ expect(isUpdateInProgress()).toBe(true);
+
+ readJSONFile.mockResolvedValue(persisted({ updateInProgress: true }));
+ await recordUpdateResult({ version: '1.28.0', success: true, completedAt: new Date().toISOString(), log: '' });
+
+ expect(isUpdateInProgress()).toBe(false);
+ });
+
+ it('is not raised by a setUpdateInProgress(true) that LOSES the check-and-set', async () => {
+ // The persisted flag is already true — set from a process that has since
+ // died, since this one's mirror is false. Nothing is written, so nothing is
+ // mirrored: the 409 already stops /execute, and raising the flag here would
+ // hold every CoS spawn until the 30-minute stale sweep with no update
+ // actually running.
+ readJSONFile.mockResolvedValue(persisted({ updateInProgress: true, updateStartedAt: new Date().toISOString() }));
+
+ const acquired = await setUpdateInProgress(true);
+
+ expect(acquired).toBe(false);
+ expect(isUpdateInProgress()).toBe(false);
+ expect(atomicWrite).not.toHaveBeenCalled();
+ });
+
+ it('is cleared by the boot-time stale sweep', async () => {
+ readJSONFile.mockResolvedValue(persisted());
+ await setUpdateInProgress(true);
+
+ readJSONFile.mockResolvedValue(persisted({
+ updateInProgress: true,
+ updateStartedAt: new Date(Date.now() - 60 * 60 * 1000).toISOString()
+ }));
+ expect(await clearStaleUpdateInProgress()).toBe(true);
+
+ expect(isUpdateInProgress()).toBe(false);
+ });
+});
+
describe('getRemoteInfo', () => {
beforeEach(() => {
vi.clearAllMocks();