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([issue-3202]): make the interruption verdict survive a lost marker, and refund the spawn a restart destroyed
[._.]/ Adam Eivyc05e822a5464
diff --git a/server/lib/hostShutdown.js b/server/lib/hostShutdown.jsindex b16122391e..821c652c9e 100644--- a/server/lib/hostShutdown.js+++ b/server/lib/hostShutdown.js@@ -81,7 +81,14 @@ export function resetHostShutdownFlagForTests() {* @returns {Promise<boolean>} true when the marker landed on disk*/export async function writeHostShutdownMarker({ agentIds = [], signal = null } = {}) {- const ids = [...new Set(agentIds.filter(isNonEmptyString))];+ // UNION with any marker the previous shutdown left unconsumed, rather than+ // replacing it. A boot that is killed before its orphan sweep runs (the sweep+ // is a couple of seconds in) leaves the prior marker in place; a plain+ // overwrite would drop those agents and silently demote them to ordinary+ // orphans — the exact penalty this marker exists to prevent. Consuming the+ // marker is the sweep's job, so anything still here has not been recovered yet.+ const prior = await readHostShutdownMarker();+ const ids = [...new Set([...(prior?.agentIds || []), ...agentIds.filter(isNonEmptyString)])];// Nothing was running — don't leave a marker the next boot has to reason// about (and don't overwrite a prior one; a marker with no agents is noise).if (ids.length === 0) return false;diff --git a/server/lib/hostShutdown.test.js b/server/lib/hostShutdown.test.jsindex 592029e261..3054d3fff3 100644--- a/server/lib/hostShutdown.test.js+++ b/server/lib/hostShutdown.test.js@@ -84,6 +84,31 @@ describe('marker round-trip', () => {expect(await readHostShutdownMarker()).toBeNull();});+ // A boot killed before its orphan sweep runs leaves the prior marker unconsumed.+ // Overwriting it would drop those agents and demote them to ordinary orphans —+ // the exact penalty the marker exists to prevent.+ it('unions with an unconsumed marker instead of replacing it', async () => {+ await writeHostShutdownMarker({ agentIds: ['a1'], signal: 'SIGTERM' });+ await writeHostShutdownMarker({ agentIds: ['a2'], signal: 'SIGTERM' });++ expect((await readHostShutdownMarker()).agentIds).toEqual(['a1', 'a2']);+ });++ it('does not resurrect a consumed marker', async () => {+ await writeHostShutdownMarker({ agentIds: ['a1'], signal: 'SIGTERM' });+ await clearHostShutdownMarker();+ await writeHostShutdownMarker({ agentIds: ['a2'], signal: 'SIGTERM' });++ expect((await readHostShutdownMarker()).agentIds).toEqual(['a2']);+ });++ it('leaves an unconsumed marker intact when the next shutdown had no live agents', async () => {+ await writeHostShutdownMarker({ agentIds: ['a1'], signal: 'SIGTERM' });++ expect(await writeHostShutdownMarker({ agentIds: [], signal: 'SIGTERM' })).toBe(true);+ expect((await readHostShutdownMarker()).agentIds).toEqual(['a1']);+ });+it('clears the marker', async () => {await writeHostShutdownMarker({ agentIds: ['a1'], signal: 'SIGTERM' });await clearHostShutdownMarker();diff --git a/server/services/agentManagement.js b/server/services/agentManagement.jsindex 50a2bca7e6..2b429600e5 100644--- a/server/services/agentManagement.js+++ b/server/services/agentManagement.js@@ -673,7 +673,14 @@ export async function cleanupOrphanedAgents() {for (const { taskId, agentId, agentMetadata } of orphanedTaskIds) {await handleOrphanedTask(taskId, agentId, getTask, {agentMetadata,- interrupted: interruptedByRestart.has(agentId),+ // `|| null`, not a bare boolean: a plain `false` would hard-override the+ // per-agent breadcrumb fallback, leaving this — the path that handles+ // essentially all boot recovery — with the marker as its ONLY signal. The+ // marker is best-effort (a stalled disk can blow the 1.5s shutdown grace,+ // or the write can simply fail), and when it's the only signal its loss+ // silently reinstates the original bug. `null` means "no verdict from me,+ // check the breadcrumb"; `true` still short-circuits it.+ interrupted: interruptedByRestart.has(agentId) || null,});}@@ -681,7 +688,12 @@ export async function cleanupOrphanedAgents() {// mid-sweep leaves it in place and the next boot still classifies these agents// correctly; re-reading a stale marker is harmless because the sweep only ever// looks at agents still marked `running`.- if (interruptedByRestart.size > 0) await clearHostShutdownMarker();+ //+ // Gated on the marker EXISTING, not on it naming anyone: a truncated or+ // malformed marker parses to zero agent ids, and gating on the id count would+ // leave that file on disk to be re-read and re-parsed on every boot and every+ // 15-minute sweep, forever.+ if (shutdownMarker) await clearHostShutdownMarker();// Trigger evaluation to spawn new agents for retried tasksif (cleanedCount > 0) {@@ -724,6 +736,17 @@ export async function handleOrphanedTask(taskId, agentId, getTaskByIdFn, { agent// Without this, correctness depended on `cleanupOrphanedAgents` happening to// run before `resetOrphanedTasks` in cos.js's boot sequence.const wasInterrupted = interrupted ?? (agentMetadata?.interruptedBy === HOST_SHUTDOWN_REASON);+ // Consume the breadcrumb the moment it's honored, exactly as the marker is+ // consumed after the sweep. It is written once and would otherwise stay on the+ // agent record forever: `resetOrphanedTasks` keys on the most recent agent per+ // task, so a respawn that dies before creating its own agent record would keep+ // re-deriving `wasInterrupted` from this same stale breadcrumb — and, because+ // an interrupted run bypasses the cooldown, respawn on EVERY 15-minute sweep+ // instead of once per 30 minutes.+ if (wasInterrupted && agentMetadata?.interruptedBy === HOST_SHUTDOWN_REASON) {+ await updateAgent(agentId, { metadata: { interruptedBy: null } })+ .catch(err => emitLog('warn', `Could not clear interrupted breadcrumb on ${agentId}: ${err.message}`, { agentId }));+ }const task = await getTaskByIdFn(taskId).catch(() => null);if (!task) {emitLog('warn', `Could not find task ${taskId} for orphaned agent ${agentId}`, { taskId, agentId });@@ -775,9 +798,19 @@ export async function handleOrphanedTask(taskId, agentId, getTaskByIdFn, { agent// unboundedly even under a restart loop.const priorOrphanRetries = Number(task.metadata?.orphanRetryCount) || 0;const retryCount = wasInterrupted ? priorOrphanRetries : priorOrphanRetries + 1;- const totalSpawns = Number(task.metadata?.totalSpawnCount) || 0;const taskType = task.taskType || 'user';+ // `totalSpawnCount` is incremented when a task goes `in_progress`, so the run a+ // restart destroyed already consumed a spawn. REFUND it: that spawn produced no+ // work and was ended by PortOS, not by the task. Without the refund the fix is+ // only half-done — the ceiling moves from 3 restarts to MAX_TOTAL_SPAWNS, after+ // which the task is still blocked `max-retries` AND an "[Auto-Fix] Investigate+ // repeated agent orphaning" task is filed blaming an agent that never failed.+ // The refund keeps a real ceiling on genuine failures (each still costs a+ // spawn) while making a restart cost nothing.+ const priorTotalSpawns = Number(task.metadata?.totalSpawnCount) || 0;+ const totalSpawns = wasInterrupted ? Math.max(0, priorTotalSpawns - 1) : priorTotalSpawns;+// Block if total spawn count across all retry types is exhaustedconst totalExceeded = totalSpawns >= MAX_TOTAL_SPAWNS;@@ -824,6 +857,9 @@ export async function handleOrphanedTask(taskId, agentId, getTaskByIdFn, { agentconst now = new Date().toISOString();const recoveryMetadata = wasInterrupted? {+ // Persist the refunded count (see the totalSpawns note above) so the+ // restart's spawn is genuinely given back rather than just ignored once.+ totalSpawnCount: totalSpawns,lastInterruptedAt: now,lastInterruptedAgentId: agentId,interruptedByRestart: true,@@ -856,6 +892,10 @@ export async function handleOrphanedTask(taskId, agentId, getTaskByIdFn, { agentorphanRetryCount: retryCount,lastOrphanedAt: new Date().toISOString(),lastOrphanedAgentId: agentId,+ // Cleared for the same reason the requeue branch clears it: the metadata+ // spread carries every prior key forward, so a task interrupted once+ // would read as restart-interrupted through every later outcome.+ interruptedByRestart: false,blockedReason: `Orphan retry cooldown (${cooldownMinutes}m remaining)`,blockedCategory: 'orphan-cooldown',blockedAt: new Date().toISOString(),@@ -877,6 +917,8 @@ export async function handleOrphanedTask(taskId, agentId, getTaskByIdFn, { agentmetadata: {...task.metadata,orphanRetryCount: retryCount,+ // See the requeue branch: the metadata spread carries prior keys forward.+ interruptedByRestart: false,blockedReason: reason,blockedCategory: 'max-retries',blockedAt: new Date().toISOString()diff --git a/server/services/agentManagement.test.js b/server/services/agentManagement.test.jsindex 278be90f88..09645f1480 100644--- a/server/services/agentManagement.test.js+++ b/server/services/agentManagement.test.js@@ -977,6 +977,83 @@ describe('host-restart interruptions are not charged orphan-retry budget (#3202)expect(metadata.interruptedByRestart).toBe(true);});+ // The marker is best-effort — a stalled disk can blow the 1.5s shutdown grace.+ // The sweep must therefore pass a null verdict (not a bare `false`, which would+ // hard-override the `??` fallback) so the breadcrumb can still be honored. This+ // is the SWEEP path, not a direct handleOrphanedTask call: without it the+ // fallback is dead exactly where nearly all boot recovery happens.+ it('falls back to the breadcrumb through the sweep when the marker did not survive', async () => {+ getAgents.mockResolvedValue([+ { ...deadAgent, metadata: { ...deadMetadata, interruptedBy: 'host-shutdown' } },+ ]);+ getTaskById.mockResolvedValue({+ id: 'task-1', taskType: 'user', status: 'in_progress',+ metadata: { orphanRetryCount: 1, totalSpawnCount: 2 },+ });+ readHostShutdownMarker.mockResolvedValue(null); // marker lost++ await cleanupOrphanedAgents();++ const metadata = requeuedMetadata();+ expect(metadata.orphanRetryCount).toBe(1);+ expect(metadata.interruptedByRestart).toBe(true);+ });++ // The breadcrumb is consumed on use, like the marker. Left in place, a respawn+ // that dies before creating its own agent record would keep re-deriving+ // "interrupted" from it — and, because an interrupted run bypasses the+ // cooldown, respawn on every 15-minute sweep instead of once per 30 minutes.+ it('clears the breadcrumb once it has been honored', async () => {+ getTaskById.mockResolvedValue({ id: 'task-1', taskType: 'user', status: 'in_progress', metadata: {} });++ await handleOrphanedTask('task-1', 'agent-dead', getTaskById, {+ agentMetadata: { ...deadMetadata, interruptedBy: 'host-shutdown' },+ });++ expect(updateAgent).toHaveBeenCalledWith('agent-dead', { metadata: { interruptedBy: null } });+ });++ // totalSpawnCount is charged when the task goes in_progress, so the destroyed+ // run already consumed a spawn. Without the refund the fix only moves the+ // ceiling: the task still ends up blocked `max-retries` with a bogus+ // "investigate repeated agent orphaning" task filed against a healthy agent.+ it('refunds the spawn a restart destroyed so MAX_TOTAL_SPAWNS is not charged', async () => {+ getTaskById.mockResolvedValue({+ id: 'task-1', taskType: 'user', status: 'in_progress',+ metadata: { totalSpawnCount: 3 },+ });+ readHostShutdownMarker.mockResolvedValue({ at: null, signal: 'SIGTERM', agentIds: ['agent-dead'] });++ await cleanupOrphanedAgents();++ expect(requeuedMetadata().totalSpawnCount).toBe(2);+ });++ it('does not refund a spawn for a genuine orphan', async () => {+ getTaskById.mockResolvedValue({+ id: 'task-1', taskType: 'user', status: 'in_progress',+ metadata: { totalSpawnCount: 3 },+ });++ await cleanupOrphanedAgents();++ // Carried through the metadata spread unchanged — a genuine failure keeps+ // costing a spawn; only a restart is refunded.+ expect(requeuedMetadata().totalSpawnCount).toBe(3);+ });++ // A truncated/malformed marker parses to zero ids. Gating the clear on the id+ // count would leave that file on disk to be re-read on every boot and every+ // 15-minute sweep, forever.+ it('clears a marker that parsed to no agents at all', async () => {+ getTaskById.mockResolvedValue({ id: 'task-1', taskType: 'user', status: 'in_progress', metadata: {} });+ readHostShutdownMarker.mockResolvedValue({ at: null, signal: null, agentIds: [] });++ await cleanupOrphanedAgents();++ expect(clearHostShutdownMarker).toHaveBeenCalled();+ });+it('flags the interruption on the agent record and consumes the marker', async () => {getTaskById.mockResolvedValue({ id: 'task-1', taskType: 'user', status: 'in_progress', metadata: {} });readHostShutdownMarker.mockResolvedValue({ at: null, signal: 'SIGTERM', agentIds: ['agent-dead'] });