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: requeue a task whose runner spawn was rejected instead of stranding it for the orphan sweep (#3632)
[._.]/ Adam Eivya97827f99b80
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 5ef164ddb3..0899d08e47 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -15,4 +15,7 @@- CoS agents whose deliverable is a **commit** are no longer scored as failures. The idle reaper's "did this agent do anything?" gate read only *uncommitted* changes, so a `/do:release` or `/do:pr` run that committed, pushed, and opened its PR — leaving a clean tree *because it succeeded* — was recorded as `idle-no-changes` and retried. Two consecutive release runs on 2026-08-08 each did their whole job (cut the release commit, opened the release PR, then repaired it against review findings) and were both reported failed, holding the release for two days. The gate now counts commits made inside the run window as evidence of work, alongside a dirty tree. The report-shaped half of the same problem (`/do:review`, `/do:scan`, `/do:plan-task`, `/do:replan`, whose deliverable lands outside the repo) is tracked in #3636, and the unsatisfiable `[task-<id>]` success criterion one layer up in #3637.- Green merge-only PRs are drained on a real 30-minute cadence again. The pending-merge sweep had moved onto the CoS evaluation pass, but evaluation is event-driven — there is no evaluation timer — so on a quiet install it ran roughly once per PortOS restart, and the `MAX_PENDING_MERGE_TICKS` escape hatch counted restarts instead of the six hours it documents. The sweep now owns a `cos-pending-merge-sweep` interval job registered and cancelled with the other CoS timers, gated on the same "CoS auto-run is `execute` and not paused" switch. It stays decoupled from the `pr-watcher` task type, so leaving that task disabled still can't strand a queued merge, and `POST /api/cos/evaluate` still drains opportunistically.+- An agent that merely *prints* a provider banner no longer benches a healthy provider. The immediate-fallback detector stamped every match as provider chrome, so a CoS agent that quoted Antigravity's account-eligibility banner — investigating that failure mode, `cat`-ing a prior run's transcript, grepping for it — sidelined the provider for the full cooldown across every subsequently dequeued task, not just its own run. The banner is now promoted to provider provenance only when it opens its own line behind nothing but TUI gutter chrome, the shape the CLI actually renders; a quoted mention still fails that one run and routes it to a fallback, but is no longer treated as evidence about the provider's health. Real banners arriving as the run's own terminal output bench exactly as before.++- A CoS task whose agent spawn is **rejected by the runner** is now requeued immediately instead of being penalized for it. The runner-rejection path finalized the agent but never transitioned the task, so it sat `in_progress` holding its federation claim until the 15-minute orphan sweep — a path meant for genuine orphans, which charged one of the task's finite `orphanRetryCount` retries and armed a 30-minute cooldown for a failure the task did not cause (the agent never started; a momentarily unreachable runner was enough). It now runs the same `finalizeAgent` → `releaseRetryHold` chain the TUI path does, under its own `spawn-rejected` reason, so the task returns to `pending` with its claim released the moment the rejection lands and the runner's actual error is on the agent record.diff --git a/server/services/agentErrorAnalysis.js b/server/services/agentErrorAnalysis.jsindex cfcee7597b..34d2e77f82 100644--- a/server/services/agentErrorAnalysis.js+++ b/server/services/agentErrorAnalysis.js@@ -657,6 +657,22 @@ export const COMPLETION_REASON_ANALYSES = {escalation: 'Confirm the required CLI/tool is installed and on PATH for the agent user (or fix the command), then approve the retry.',message: 'Failed to start the agent session',suggestedFix: 'The shell/PTY session could not be created. Check system resources and the provider command configuration.'+ },+ // The runner refused the spawn outright — a command missing from its+ // allowlist, malformed cliArgs, or the runner simply unreachable. No child+ // ever existed, so there is no transcript to classify and the rejection prose+ // (carried in as `completionError`) is the whole diagnosis.+ //+ // Deliberately NOT actionable, unlike its `spawn-error` sibling above: a+ // rejection is frequently just a briefly-unreachable runner, and blocking the+ // task for a human would park work that a plain retry fixes. A genuinely+ // misconfigured command still surfaces — it fails identically every attempt+ // and blocks on MAX_TASK_RETRIES, with the runner's own message attached.+ 'spawn-rejected': {+ category: 'spawn-error',+ actionable: false,+ message: 'The runner rejected the spawn',+ suggestedFix: 'No agent process was ever created — the cos-runner refused the spawn or was unreachable. Check that the runner is up and that the provider command is on its allowlist; the task is requeued for a retry either way.'}};diff --git a/server/services/agentErrorAnalysis.test.js b/server/services/agentErrorAnalysis.test.jsindex 37f52a0a11..b4a4eed75b 100644--- a/server/services/agentErrorAnalysis.test.js+++ b/server/services/agentErrorAnalysis.test.js@@ -877,6 +877,37 @@ describe('analyzeAgentFailure — runner completion reason (COMPLETION_REASON_ANexpect(endsAwaitingUserInput(answeredEarly)).toBe(false);});+ // #3632: the runner refused the spawn, so there is no transcript at all — the+ // rejection prose is the entire diagnosis, and it must reach the analysis.+ it('classifies a runner-rejected spawn from its reason alone, carrying the rejection prose', () => {+ const rejection = 'Command not allowed: grok. Permitted commands: claude, codex';+ const analysis = analyzeAgentFailure('', { id: 't' }, 'x', {+ completionReason: 'spawn-rejected',+ completionError: rejection,+ });+ expect(analysis.category).toBe('spawn-error');+ expect(analysis.origin).toBe('runner');+ expect(analysis.completionReason).toBe('spawn-rejected');+ expect(analysis.snippet).toContain('Command not allowed: grok');+ });++ // The distinction from its `spawn-error` sibling is the whole point: an+ // actionable verdict BLOCKS the task for a human, and a runner that was briefly+ // unreachable does not warrant that. Non-actionable ⇒ resolveFailedTaskDecision+ // budgets an ordinary retry (held for its resume pointer, then released).+ it('leaves a runner-rejected spawn retryable rather than blocking the task', () => {+ expect(COMPLETION_REASON_ANALYSES['spawn-rejected'].actionable).toBe(false);+ expect(COMPLETION_REASON_ANALYSES['spawn-error'].actionable).toBe(true);++ const analysis = analyzeAgentFailure('', { id: 't' }, 'x', {+ completionReason: 'spawn-rejected',+ completionError: 'runner unreachable',+ });+ const decision = resolveFailedTaskDecision({ id: 't', metadata: {} }, analysis, { agentId: 'agent-1' });+ expect(decision.status).toBe('in_progress');+ expect(decision.metadataUpdates.blockedReason).toBeUndefined();+ });+it('maps every reason to a category ERROR_PATTERNS already produces (no orphan taxonomy tokens)', () => {const known = new Set([...ERROR_PATTERNS.map(p => p.category), 'startup-failure']);for (const [reason, def] of Object.entries(COMPLETION_REASON_ANALYSES)) {diff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.jsindex 3caaf1d12b..25e374467f 100644--- a/server/services/agentLifecycle.js+++ b/server/services/agentLifecycle.js@@ -49,7 +49,7 @@ import { ensureDir, PATHS, sleep, tryReadFile } from '../lib/fileUtils.js';import { createToolExecution, startExecution, completeExecution, errorExecution } from './toolStateMachine.js';import { determineLane, acquire, release } from './executionLanes.js';import { analyzeAgentFailure } from './agentErrorAnalysis.js';-import { createAgentRun, checkForTaskCommit, completeAgentRun } from './agentRunTracking.js';+import { createAgentRun, checkForTaskCommit } from './agentRunTracking.js';import { buildAgentPrompt, getAppWorkspace } from './agentPromptBuilder.js';import { isOllamaClaudeProvider, isClaudeCommand, providerSuppliesGithubToken } from '../lib/providerModels.js';import { canTypeSlashCommands } from '../lib/slashdoInvocation.js';@@ -71,7 +71,11 @@ import { v4 as uuidv4 } from '../lib/uuid.js';// below them were retired with the `subAgentSpawner.js` barrel (#3450).import { resolveAgentProviderAndModel } from './agentProviderResolution.js';import { prepareAgentWorkspace } from './agentWorkspacePrep.js';-import { cleanupAgentWorktree } from './agentWorktreeCleanup.js';+// `releaseRetryHold` is imported STATICALLY here (the TUI/direct-CLI spawners+// reach for it via `await import()` only because they sit BELOW this module and+// a top-level import there would race the cycle) — this module already imports+// `cleanupAgentWorktree` from the same file, so there is no new edge.+import { cleanupAgentWorktree, releaseRetryHold } from './agentWorktreeCleanup.js';import { runAgentCompletionCleanup } from './agentCompletionCleanup.js';import { dispatchRecoveredTaskOutputHook, finalizeAgent, releaseAgentLane, stampLiExecutionVerdict } from './agentFinalization.js';import { extractFinalSummary } from './agentSummaryExtraction.js';@@ -740,9 +744,10 @@ export async function spawnViaRunner(agentId, task, opts) {// because `runnerAgents` still holds the entry, `isAgentOwnedLocally` makes// the orphan sweep skip the record too, so the 3s timer above flips it to// `working` and it sits there for the life of the process. Finalize with the- // real error instead — same shape as the runner's own `agent:error` handling- // in subAgentSpawner.js. (The TUI arm of this dispatch owns the equivalent- // handling inside spawnTuiAgent, where `finish()` is the idempotent finalizer.)+ // real error instead, through the ordinary finalizeAgent → releaseRetryHold+ // chain so the TASK is transitioned too — see the catch below. (The TUI arm of+ // this dispatch owns the equivalent handling inside spawnTuiAgent, where+ // `finish()` is the idempotent finalizer that runs the same chain.)let result;try {result = await spawnAgentViaRunner({@@ -770,11 +775,51 @@ export async function spawnViaRunner(agentId, task, opts) {clearTimeout(agentInfo.initializationTimeout);runnerAgents.delete(agentId);releaseAgentLane({ agentId, success: false, exitCode: 1, executionId, laneName, errorExecutionMessage: message });- // validationPassed is the null sentinel (#2344): no success criterion was- // ever evaluated, so this records "not declared" rather than a false- // "declared and failed".- await completeAgent(agentId, { success: false, validationPassed: null, error: message });- await completeAgentRun(runId, '', 1, 0, { message, category: 'runner-error' });+ // Finalize through the SAME chokepoint every other ending uses (#3632).+ // Finalizing the agent alone — which is all this used to do — left the TASK+ // sitting `in_progress` holding its federation claim until the 15-minute+ // orphan sweep, and that sweep is for orphans: it charges+ // `orphanRetryCount` against MAX_ORPHAN_RETRIES and arms a 30-minute+ // cooldown for a failure the task did not cause. finalizeAgent owns the+ // task transition, execution tracking, and the per-type failure ledger;+ // releaseRetryHold then flips the held retry to `pending` immediately (and+ // `updateTask` strips the claim keys on the way out of `in_progress`), so+ // the task is re-dequeuable the moment the rejection lands.+ //+ // `spawn-rejected` is its own reason, deliberately NOT the TUI's+ // `spawn-error`: that one is `actionable` (→ the task is BLOCKED for a+ // human), which is right when a PTY genuinely can't start but wrong for a+ // runner that was merely unreachable for a moment. See its entry in+ // COMPLETION_REASON_ANALYSES.+ const errorAnalysis = analyzeAgentFailure('', task, model, {+ completionReason: 'spawn-rejected',+ completionError: message,+ });+ // validationPassed is the null sentinel (#2344), applied inside+ // finalizeAgent: no success criterion was ever evaluated, so this records+ // "not declared" rather than a false "declared and failed".+ await finalizeAgent({+ agentId,+ task,+ runId,+ providerId: provider.id,+ success: false,+ exitCode: 1,+ duration: 0,+ outputBuffer: '',+ errorAnalysis,+ isTruthyMetaFn: isTruthyMeta,+ error: message,+ completionReason: 'spawn-rejected',+ workspacePath,+ // The agent never ran, so it cannot have opened a PR — skip the+ // PR-claim verification entirely (it only applies to claimed successes).+ prExpected: false,+ }).catch(err => {+ emitLog('error', `finalizeAgent threw for rejected spawn ${agentId}: ${err.message}`, { agentId, taskId: task.id, error: err.message });+ });+ await releaseRetryHold({ agentId, task, success: false })+ .catch(err => emitLog('warn', `Retry-hold release failed for rejected spawn ${agentId}: ${err.message}`, { agentId, taskId: task.id }));emitLog('error', `Agent ${agentId} failed to spawn via runner: ${message}`, { agentId, taskId: task.id });cosEvents.emit('agent:error', { agentId, taskId: task.id, error: message });return null;diff --git a/server/services/agentLifecycle.spawnViaRunner.test.js b/server/services/agentLifecycle.spawnViaRunner.test.jsindex 76f7e6496f..7bd878de3c 100644--- a/server/services/agentLifecycle.spawnViaRunner.test.js+++ b/server/services/agentLifecycle.spawnViaRunner.test.js@@ -11,6 +11,14 @@* dispatch had the same hole with a shorter tail: the zombie reaper eventually* finalized it with a generic message that named no cause.)*+ * The follow-on hole (#3632): that recovery finalized the AGENT with a bare+ * `completeAgent` and never transitioned the TASK, so it sat `in_progress`+ * holding its federation claim until the 15-minute orphan sweep — which treats+ * it as an orphan, charging `orphanRetryCount` and arming a 30-minute cooldown+ * for a failure the task did not cause. It now runs the same+ * finalizeAgent → releaseRetryHold chain the TUI `finish()` does, which is+ * pinned at the same seam in agentTuiSpawning.test.js.+ ** Lives in its own file because agentLifecycle.test.js deliberately imports no* part of the orchestrator graph — it reads the source as a string. Driving the* real function needs the leaves mocked, which would change that file's whole@@ -74,12 +82,20 @@ vi.mock('./agentTuiSpawning.js', () => ({vi.mock('./agentProviderResolution.js', () => ({ resolveAgentProviderAndModel: vi.fn() }));vi.mock('./agentWorkspacePrep.js', () => ({ prepareAgentWorkspace: vi.fn() }));-vi.mock('./agentWorktreeCleanup.js', () => ({ cleanupAgentWorktree: vi.fn() }));+vi.mock('./agentWorktreeCleanup.js', () => ({+ cleanupAgentWorktree: vi.fn(),+ releaseRetryHold: vi.fn().mockResolvedValue({}),+}));vi.mock('./agentCompletionCleanup.js', () => ({ runAgentCompletionCleanup: vi.fn() }));vi.mock('./agentSummaryExtraction.js', () => ({ extractFinalSummary: vi.fn() }));vi.mock('./agentManagement.js', () => ({ handleOrphanedTask: vi.fn() }));vi.mock('./agentPromptBuilder.js', () => ({ buildAgentPrompt: vi.fn(), getAppWorkspace: vi.fn() }));-vi.mock('./agentErrorAnalysis.js', () => ({ analyzeAgentFailure: vi.fn().mockReturnValue(null) }));+// The real classification of a `spawn-rejected` reason (non-actionable, so the+// task is budgeted a retry rather than blocked) is pinned in+// agentErrorAnalysis.test.js; here we only need a stand-in object to follow.+vi.mock('./agentErrorAnalysis.js', () => ({+ analyzeAgentFailure: vi.fn().mockReturnValue({ category: 'startup-failure', actionable: false }),+}));vi.mock('./appActivity.js', () => ({ releaseAppReviewMarker: vi.fn().mockResolvedValue(undefined) }));vi.mock('./instances.js', () => ({ ensureInstanceId: vi.fn().mockResolvedValue('instance-1') }));vi.mock('./toolStateMachine.js', () => ({@@ -98,7 +114,10 @@ import { spawnViaRunner } from './agentLifecycle.js';import { spawnAgentViaRunner } from './cosRunnerClient.js';import { completeAgent, updateAgent } from './cosAgentLifecycle.js';import { completeAgentRun } from './agentRunTracking.js';-import { releaseAgentLane } from './agentFinalization.js';+import { finalizeAgent, releaseAgentLane } from './agentFinalization.js';+import { releaseRetryHold } from './agentWorktreeCleanup.js';+import { analyzeAgentFailure } from './agentErrorAnalysis.js';+import { handleOrphanedTask } from './agentManagement.js';import { runnerAgents } from './agentState.js';const REJECTION = 'Command not allowed: grok. Permitted commands: claude, codex';@@ -127,21 +146,64 @@ describe('spawnViaRunner — the runner rejects the spawn', () => {await expect(spawnViaRunner('agent-1', { id: 'task-1' }, runnerOpts())).resolves.toBeNull();});- it('finalizes the agent record with the runner\'s actual error', async () => {+ it('finalizes through finalizeAgent with the runner\'s actual error, not a bare completeAgent', async () => {vi.mocked(spawnAgentViaRunner).mockRejectedValueOnce(new Error(REJECTION));await spawnViaRunner('agent-1', { id: 'task-1' }, runnerOpts());- expect(completeAgent).toHaveBeenCalledWith('agent-1', expect.objectContaining({+ expect(finalizeAgent).toHaveBeenCalledWith(expect.objectContaining({+ agentId: 'agent-1',+ runId: 'run-1',+ providerId: 'grok-cli',success: false,- // No success criterion was ever evaluated — the null sentinel (#2344)- // keeps "never ran" out of the declared-and-failed bucket.- validationPassed: null,+ exitCode: 1,+ // Attributable: a rejected spawn is not an ordinary run failure, and the+ // agent never ran so it cannot owe a PR.+ completionReason: 'spawn-rejected',+ prExpected: false,error: expect.stringContaining('Command not allowed: grok'),}));- expect(completeAgentRun).toHaveBeenCalledWith(- 'run-1', '', 1, 0, expect.objectContaining({ category: 'runner-error' })- );+ // finalizeAgent owns the completeAgent + completeAgentRun writes (with the+ // #2344 null validation sentinel) — doing them here as well would double-write.+ expect(completeAgent).not.toHaveBeenCalled();+ expect(completeAgentRun).not.toHaveBeenCalled();+ });++ it('classifies the rejection under the spawn-rejected reason, carrying the runner message', async () => {+ vi.mocked(spawnAgentViaRunner).mockRejectedValueOnce(new Error(REJECTION));++ await spawnViaRunner('agent-1', { id: 'task-1' }, runnerOpts());++ expect(analyzeAgentFailure).toHaveBeenCalledWith('', expect.objectContaining({ id: 'task-1' }), 'some-model', {+ completionReason: 'spawn-rejected',+ completionError: REJECTION,+ });+ });++ it('releases the retry hold so the task returns to pending instead of waiting on the orphan sweep', async () => {+ const task = { id: 'task-1' };+ vi.mocked(spawnAgentViaRunner).mockRejectedValueOnce(new Error(REJECTION));++ await spawnViaRunner('agent-1', task, runnerOpts());++ // The seam the TUI path is pinned at (agentTuiSpawning.test.js). releaseRetryHold+ // flips the held retry to `pending` in one write, and leaving `in_progress`+ // is what strips the federation claim keys (cosTaskClaim.CLAIM_METADATA_KEYS).+ expect(releaseRetryHold).toHaveBeenCalledWith({ agentId: 'agent-1', task, success: false });+ // Ordering matters: finalizeAgent arms the hold, releaseRetryHold clears it.+ expect(vi.mocked(finalizeAgent).mock.invocationCallOrder[0])+ .toBeLessThan(vi.mocked(releaseRetryHold).mock.invocationCallOrder[0]);+ // The whole point: the orphan path — which charges `orphanRetryCount` and+ // arms a 30-minute cooldown — is never reached for a spawn the task didn't cause.+ expect(handleOrphanedTask).not.toHaveBeenCalled();+ });++ it('still finalizes when releaseRetryHold rejects — the orphan sweep is the fallback, not a crash', async () => {+ vi.mocked(spawnAgentViaRunner).mockRejectedValueOnce(new Error(REJECTION));+ vi.mocked(releaseRetryHold).mockRejectedValueOnce(new Error('task store unreadable'));++ await expect(spawnViaRunner('agent-1', { id: 'task-1' }, runnerOpts())).resolves.toBeNull();+ expect(finalizeAgent).toHaveBeenCalled();});it('drops the runnerAgents entry so the orphan sweep can see the record', async () => {@@ -188,7 +250,8 @@ describe('spawnViaRunner — the runner rejects the spawn', () => {await expect(spawnViaRunner('agent-1', { id: 'task-1' }, runnerOpts())).resolves.toBe('agent-1');expect(updateAgent).toHaveBeenCalledWith('agent-1', { pid: 4242 });- expect(completeAgent).not.toHaveBeenCalled();+ expect(finalizeAgent).not.toHaveBeenCalled();+ expect(releaseRetryHold).not.toHaveBeenCalled();expect(runnerAgents.has('agent-1')).toBe(true);});});