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

address review (codex): post-lock re-check, sum agent count, poll while updatable

[._.]/ Adam Eivy6efee508e00b
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index f4121ef0ce..e30565ac4a 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -61,7 +61,7 @@
## Fixed
-- **Updating/reconciling no longer severs a live CoS agent.** The update page's "Update Now", "Reconcile Now", and every fork *update* variant run `update.sh`, which pm2-restarts PortOS — killing any CoS agent mid-task (each agent's PTY/child process is a child of the server process). The Update tab now suppresses the "Install out of sync" reconcile prompt and the restart-triggering update buttons while agents are running, showing a "Update paused — CoS agents running" notice that clears automatically once the last agent finishes (the tab polls status every 4s while agents are live). Safe, non-restarting actions stay available — "Sync Fork Only" (just `gh repo sync`) and "Ignore v…" are not hidden. Defense-in-depth on the server: `POST /api/update/execute` hard-rejects with `409 AGENTS_ACTIVE` when agents exist, so a race, a stale client, or a direct API call can't restart out from under a running agent. The active-agent signal counts the in-memory live-process maps (direct + runner spawns) **plus in-flight spawns** (`spawningTasks`) — a just-launched agent whose child process exists but isn't yet registered in a process map would otherwise be invisible to a plain live-process check and still get severed. A stale persisted `status: 'running'` can't spuriously block, and a paused agent (process already stopped) correctly doesn't. `GET /api/update/status` now reports `activeCosAgents`. Covered by `update.test.js` and `UpdateTab.test.jsx`.
+- **Updating/reconciling no longer severs a live CoS agent.** The update page's "Update Now", "Reconcile Now", and every fork *update* variant run `update.sh`, which pm2-restarts PortOS — killing any CoS agent mid-task (each agent's PTY/child process is a child of the server process). The Update tab now suppresses the "Install out of sync" reconcile prompt and the restart-triggering update buttons while agents are running, showing a "Update paused — CoS agents running" notice that clears automatically once the last agent finishes (the tab polls status every 4s while agents are live). Safe, non-restarting actions stay available — "Sync Fork Only" (just `gh repo sync`) and "Ignore v…" are not hidden. Defense-in-depth on the server: `POST /api/update/execute` hard-rejects with `409 AGENTS_ACTIVE` when agents exist, so a race, a stale client, or a direct API call can't restart out from under a running agent — and it re-checks once more *after* acquiring the update lock (releasing it on abort) so an agent that goes live during the git/fork work still blocks the restart. The active-agent signal counts the in-memory live-process maps (direct + runner spawns) **plus in-flight spawns** (`spawningTasks`) — a just-launched agent whose child process exists but isn't yet registered in a process map would otherwise be invisible to a plain live-process check and still get severed. A stale persisted `status: 'running'` can't spuriously block, and a paused agent (process already stopped) correctly doesn't. `GET /api/update/status` reports `activeCosAgents`, and the tab keeps a light status poll running whenever an update/reconcile surface is on screen, so an agent that starts (from a schedule or another tab) suppresses the buttons promptly rather than leaving one that 409s on click. Covered by `update.test.js` and `UpdateTab.test.jsx`.
- **[issue-2681] POST daily status now uses your timezone, not the server's UTC day.** `completedToday`, `todayScore`, and the POST streaks in the MeatSpace POST service derived the day boundary from the server's UTC day (the process runs `TZ=UTC`), so for anyone outside UTC a POST completed the previous local evening could read as "done today," or a just-completed local-day POST could read as incomplete — and the Daily Post widget and the Daily Driver card (#2666), which both render `completedToday` from `getPostStats()`, inherited the drift. The day boundary now threads your configured timezone (`getUserTimezone`/`todayInTimezone`, via a shared `userLocalToday()` helper) through both sides: every writer that stamps a day (`submitPostSession`, `submitTrainingEntry`, memory-practice `submitPractice`, and Morse `appendMorseRound`) records a new record's `date` in your local day — derived from the same instant it stamps into `timestamp`/`startedAt` so a midnight boundary can't split the two — and every reader (`getPostStats`/`getPostProgress`/`getUnifiedActivityStreak`/`getTrainingStats`/`getMorseProgress`, plus the mastery-window cutoffs) derives "today" in your local day, mirroring the Daily Driver's tz-correct first-visit/handled markers so every surface agrees. All window cutoffs use DST-safe day math off the local today. The POST launcher's "completed today"/today's-minutes and the history range floor also derive their day key in your configured timezone (new `useUserTimezone` hook + `dayKeyInTimezone` util) so the client agrees with the server instead of computing "today" in UTC. A one-time migration (`192-post-dates-to-local-timezone`) re-derives existing session, training-log, and Morse-round day-strings from each record's stored UTC timestamp in your timezone (preferring the retry-stable `startedAt`, and preserving a legacy practice entry's only instant into `timestamp` before rewriting `date`), so historical streaks stay correct and don't collide with newly-written local-day records; it falls back to UTC (matching the server's `TZ=UTC` runtime), making it a no-op for UTC/unconfigured installs.
diff --git a/PLAN.md b/PLAN.md
index 7f514965bd..f6344a7cdd 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -79,3 +79,7 @@ by `/do:replan --issues`:
### POST timezone follow-ups (#2681)
- [ ] **Re-derive POST day keys from timestamps at read time (or re-normalize on timezone change).** #2681 made POST records store their `date` in the user's configured timezone (writers) and read "today" in that zone (readers: `getPostStats`/`getPostProgress`/`getUnifiedActivityStreak`/`getTrainingStats`/`getMorseProgress`, plus the client). Migration 192 re-keys existing records once. The residual gap: a stored `date` is frozen in the zone that was active when it was written, so if the user *changes* `settings.timezone` after accumulating history, the old day keys disagree with the new-zone readers (a session saved as `2026-07-15` in LA reads as incomplete-today after switching to UTC). The reminder path (`meatspacePostReminder.js` `firePostReminderIfIncomplete`) is already immune because it derives the day from each record's `startedAt`/`timestamp` at read time via `isOnLocalDay(instant, tz)` — NOT the stored `date`. Two fix options: (a) apply that same read-time derivation in the streak/stats/history readers — map each record to `{ ...r, date: localDay(r.startedAt||r.completedAt||r.timestamp, tz) }` before it reaches `computePostStreaks`/aggregation, making the stored `date` a cache the readers ignore (comprehensive, no re-normalization ever needed, but touches every reader + the pure-helper integration and needs careful test updates); or (b) subscribe to the `settings:updated` timezone-change event (there's already `timezoneUpdatedAt` infra) and re-run migration-192-style normalization through the services' load/save paths (must NOT raw-write the files — that bypasses service caches, see the "sync direct-write bypasses cache" precedent). Deferred from #2681 review (codex r6, P2) — an uncommon tz-change-after-history scenario whose correct fix is a sizable, separately-reviewable refactor against real POST data; the steady-state configured-tz behavior shipped in #2681 is fully covered. Note: codex's r6 claim that the reminder recomputes `startedAt` in UTC is factually wrong — it already uses `getUserTimezone()`.
+
+### PortOS-update / CoS-agent mutual-exclusion follow-up
+
+- [ ] **Gate every CoS spawn engine on `updateInProgress` so a scheduled/autopilot spawn can't start during a PortOS self-update.** The update flow now blocks `POST /api/update/execute` when a CoS agent is live or mid-spawn (`server/routes/update.js` `countActiveCosAgents`, fast-fail + post-lock re-check via `getActiveAgentIds()` + `spawningTasks`), and the Update tab suppresses restart buttons while agents run. Residual: an agent that begins spawning *after* the route's post-lock re-check but before `update.sh` reaches its `pm2 delete` (a multi-second window covering git pull / submodules / npm install) is still severed. Fully closing it means having the spawn side consult the update lock: add a synchronous in-memory `isUpdateInProgress()` mirror to `server/services/updateChecker.js` (kept in lockstep with the persisted flag in `setUpdateInProgress`) and have the CoS spawn engines skip-and-requeue (return the existing `SPAWN_DEDUP_SKIP`-style no-op, leaving the task queued for after the restart) when it's set. **This must cover ALL spawn engines, not just `spawnAgentForTask`** — per the CoS autonomous-spawn precedent, gating one chokepoint gives false confidence; audit `dequeueNextTask` / `evaluateTasks` / `executeScheduledJob` and the Creative Director / on-demand bridges (grep the spawn call sites in `server/services/agentLifecycle.js` + `subAgentSpawner.js` + `cos*.js`). Deferred from the codex review of this PR (r2 P1) because it's a CoS-subsystem change spanning multiple spawn paths that deserves its own focused PR + tests; the 409 guard, post-lock re-check, and the orphan reaper bound the residual exposure in the meantime.
diff --git a/client/src/components/apps/tabs/UpdateTab.jsx b/client/src/components/apps/tabs/UpdateTab.jsx
index 2a11342346..4647f27786 100644
--- a/client/src/components/apps/tabs/UpdateTab.jsx
+++ b/client/src/components/apps/tabs/UpdateTab.jsx
@@ -234,12 +234,16 @@ export default function UpdateTab() {
useAutoRefetch(pollHealth, 2000, { enabled: polling, pollOnly: true });
- // While CoS agents are live, updates/reconcile are blocked server-side (a
- // restart would sever them). Poll the status so the block clears promptly once
- // the last agent finishes, without the user manually re-checking. No-op when
- // no agents are running or an update is already underway.
+ // Keep the status fresh while there's an update/reconcile surface on screen,
+ // so the agent block appears AND clears without a manual re-check: if an agent
+ // starts (from a schedule or another tab) while the buttons are showing, the
+ // next poll suppresses them; when the last agent finishes, it restores them.
+ // Gated to only run when there's something actionable (agents live, or an
+ // update/reconcile is available) and no update is already underway.
useAutoRefetch(fetchStatus, 4000, {
- enabled: (status?.activeCosAgents || 0) > 0 && !updating && !polling,
+ enabled: ((status?.activeCosAgents || 0) > 0 ||
+ !!status?.installState?.outOfSync ||
+ !!status?.updateAvailable) && !updating && !polling,
pollOnly: true
});
diff --git a/client/src/components/apps/tabs/UpdateTab.test.jsx b/client/src/components/apps/tabs/UpdateTab.test.jsx
index 46903fb3de..217220b213 100644
--- a/client/src/components/apps/tabs/UpdateTab.test.jsx
+++ b/client/src/components/apps/tabs/UpdateTab.test.jsx
@@ -252,6 +252,36 @@ describe('UpdateTab — active CoS agent suppression', () => {
expect(screen.getByRole('button', { name: 'Sync Fork Only' })).toBeTruthy();
});
+ it('suppresses restart buttons when an agent starts while the update surface is showing (4s poll)', async () => {
+ // Codex P2: tab loads with 0 agents and an available update, then a scheduled
+ // task (or another browser tab) starts an agent. The poll — enabled whenever
+ // there's an actionable update surface — picks it up and suppresses "Update
+ // Now" instead of leaving a button that 409s on click.
+ let agentCount = 0;
+ mockGetUpdateStatus.mockReset().mockImplementation(async () => ({
+ currentVersion: '2.24.0',
+ updateAvailable: true,
+ latestRelease: { version: '2.25.0' },
+ remoteInfo: { isFork: false, hasOrigin: true, fullName: 'atomantic/PortOS' },
+ activeCosAgents: agentCount,
+ }));
+ vi.useFakeTimers();
+ render(<UpdateTab />);
+
+ // Initially updatable — button present, no notice.
+ await act(async () => { await vi.advanceTimersByTimeAsync(0); });
+ expect(screen.getByRole('button', { name: 'Update Now' })).toBeTruthy();
+ expect(screen.queryByText(/Update paused/i)).toBeNull();
+
+ // An agent starts; the next poll observes it.
+ agentCount = 1;
+ await act(async () => { await vi.advanceTimersByTimeAsync(4000); });
+ vi.useRealTimers();
+
+ expect(screen.queryByRole('button', { name: 'Update Now' })).toBeNull();
+ expect(screen.getByText(/Update paused — CoS agents running/i)).toBeTruthy();
+ });
+
it('auto-clears the paused notice when the last agent finishes (4s status poll)', async () => {
// Pins the notice's "this notice clears automatically" claim: while agents
// are live the tab polls status every 4s (useAutoRefetch), so when the last
diff --git a/server/routes/update.js b/server/routes/update.js
index 2f3d89468b..06f18270f9 100644
--- a/server/routes/update.js
+++ b/server/routes/update.js
@@ -14,17 +14,30 @@ const router = Router();
// spawn the task sits in `spawningTasks` while its child process is created and
// only THEN registered in the process maps (`withSpawnDedupGuard` holds the set
// across the whole launch) — so an agent that has already spawned a process but
-// not yet registered it is invisible to getActiveAgentIds() alone. Counting
-// spawningTasks closes that launch window. Use `live || spawning` (not a sum):
-// during the brief overlap where a launching agent is in BOTH a process map and
-// spawningTasks, a sum would double-count it. This still can't close the
-// sub-millisecond window where a NEW spawn begins after this read but before
-// update.sh execs — full spawn/update mutual-exclusion is disproportionate for a
-// single-user install where updating is a deliberate, rare action, and the
-// orphan reaper handles any agent the restart does catch.
+// not yet registered it is invisible to getActiveAgentIds() alone. Summing both
+// includes every distinct in-flight task in the count (a live agent plus two
+// spawning tasks reads as 3, not 1). It can transiently over-report by 1 during
+// the sub-second overlap where a single launching agent sits in BOTH sets, but
+// the guard only needs `> 0` and the count is a near-exact upper bound shown in
+// an advisory notice — an occasional +1 mid-launch is preferable to dropping
+// the spawning tasks entirely.
+//
+// This still can't close the window where a NEW spawn begins AFTER a caller
+// reads this but before update.sh's pm2 restart. The route's post-lock re-check
+// below narrows it; fully closing it needs every CoS spawn engine to consult
+// updateInProgress (tracked in PLAN.md) — the orphan reaper bounds the residual.
function countActiveCosAgents() {
- const live = getActiveAgentIds().length;
- return live || spawningTasks.size;
+ return getActiveAgentIds().length + spawningTasks.size;
+}
+
+// The 409 the update flow raises when a restart would sever a live/spawning
+// agent — shared by the fast-fail pre-check and the post-lock re-check.
+function agentsActiveError(n) {
+ return new ServerError(
+ `${n} CoS agent${n === 1 ? ' is' : 's are'} running — updating would restart PortOS and ` +
+ `sever ${n === 1 ? 'it' : 'them'}. Pause or wait for the agent${n === 1 ? '' : 's'} to finish, then update.`,
+ { status: 409, code: 'AGENTS_ACTIVE' }
+ );
}
const ignoreSchema = z.object({
@@ -139,16 +152,12 @@ router.post('/execute', asyncHandler(async (req, res) => {
// countActiveCosAgents() reflects exactly what a restart would kill — live
// processes plus in-flight spawns — so a stale persisted `status: 'running'`
// on disk can't spuriously block, and a paused agent (its process already
- // stopped) correctly doesn't. Gate here so it covers reconcile, normal update,
- // and both fork variants, which all funnel through /execute.
- const n = countActiveCosAgents();
- if (n > 0) {
- throw new ServerError(
- `${n} CoS agent${n === 1 ? ' is' : 's are'} running — updating would restart PortOS and ` +
- `sever ${n === 1 ? 'it' : 'them'}. Pause or wait for the agent${n === 1 ? '' : 's'} to finish, then update.`,
- { status: 409, code: 'AGENTS_ACTIVE' }
- );
- }
+ // stopped) correctly doesn't. Fast-fail here so it covers reconcile, normal
+ // update, and both fork variants (all funnel through /execute) before doing
+ // the git/fork work below; a second re-check after the lock closes the window
+ // an agent could start in during that work.
+ const preCheck = countActiveCosAgents();
+ if (preCheck > 0) throw agentsActiveError(preCheck);
const status = await updateChecker.getUpdateStatus();
@@ -206,6 +215,17 @@ router.post('/execute', asyncHandler(async (req, res) => {
throw new ServerError('Update already in progress', { status: 409, code: 'UPDATE_IN_PROGRESS' });
}
+ // Re-check after acquiring the lock: an agent (e.g. a scheduled/autopilot
+ // 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 PLAN.md spawn-engine gate will close.
+ const postLock = countActiveCosAgents();
+ if (postLock > 0) {
+ await updateChecker.setUpdateInProgress(false);
+ throw agentsActiveError(postLock);
+ }
+
const io = req.app.get('io');
// Start update in background, stream progress via socket
diff --git a/server/routes/update.test.js b/server/routes/update.test.js
index 5c27c33f36..ceaa27785b 100644
--- a/server/routes/update.test.js
+++ b/server/routes/update.test.js
@@ -171,6 +171,20 @@ describe('POST /api/update/execute — active CoS agent gating', () => {
expect(executeUpdate).not.toHaveBeenCalled();
});
+ it('re-checks after acquiring the lock and releases it if an agent started during the git/fork awaits', async () => {
+ // Pre-check sees no agents (call 1), but one goes live during getUpdateStatus/
+ // fork-gate (call 2 at the post-lock re-check) — the update must abort and
+ // release the in-progress lock instead of restarting out from under it.
+ getActiveAgentIds.mockReturnValueOnce([]).mockReturnValueOnce(['agent-late']);
+ const res = await request(makeApp()).post('/api/update/execute').send({});
+ expect(res.status).toBe(409);
+ expect(res.body.code).toBe('AGENTS_ACTIVE');
+ expect(executeUpdate).not.toHaveBeenCalled();
+ // Lock was acquired then released (true, then false), leaving no stuck lock.
+ expect(updateChecker.setUpdateInProgress).toHaveBeenNthCalledWith(1, true);
+ expect(updateChecker.setUpdateInProgress).toHaveBeenCalledWith(false);
+ });
+
it('rejects a reconcile with 409 AGENTS_ACTIVE while agents are live', async () => {
updateChecker.getUpdateStatus.mockResolvedValue(baseStatus({ installState: { outOfSync: true } }));
getActiveAgentIds.mockReturnValue(['agent-1', 'agent-2']);
@@ -214,6 +228,15 @@ describe('GET /api/update/status — activeCosAgents', () => {
expect(res.body.activeCosAgents).toBe(1);
});
+ it('sums distinct live and spawning agents (a live agent plus two spawns → 3)', async () => {
+ getActiveAgentIds.mockReturnValue(['agent-1']);
+ mockSpawningTasks.add('task-1');
+ mockSpawningTasks.add('task-2');
+ const res = await request(makeApp()).get('/api/update/status');
+ expect(res.status).toBe(200);
+ expect(res.body.activeCosAgents).toBe(3);
+ });
+
it('reports 0 when no agents are running', async () => {
const res = await request(makeApp()).get('/api/update/status');
expect(res.status).toBe(200);