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: dispatch output hooks from recovery paths (#3182)
[._.]/ Adam Eivy8be1e74eed88
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex d1403d4d4e..eef15872f7 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -20,6 +20,7 @@## Quota burn- **[issue-3179] Quota-burn no longer spends window budget on runs that never happened** — a scheduled quota-burn run counted against the family's per-window dispatch cap as soon as it was considered, even when it was subsequently skipped and no agent was ever started. Those phantom dispatches ate the budget, so a family configured for e.g. 5 burns per reset window could fire far fewer — and a family capped at 1 could never fire at all, because the skipped run consumed the only slot before the next gate re-read it. A burn is now counted once its agent has actually run, and a burn that is queued or in progress holds its slot in the meantime, so the cap stays accurate without letting a second app or a repeated "Run" overshoot it.+- **[issue-3182] Quota-burn dispatch caps survive agent recovery and server restarts** — when PortOS reaped an orphaned burn or received its completion after restarting, the recovery path skipped the output hook that records the consumed slot. The next tick could then launch another burn beyond the configured window cap. Recovery now runs the same bounded output hook as normal completion, with an exactly-once marker that prevents normal and recovery paths from double-counting the same agent.## Fixeddiff --git a/server/services/agentFinalization.js b/server/services/agentFinalization.jsindex 542a7babaa..ed46d89f2d 100644--- a/server/services/agentFinalization.js+++ b/server/services/agentFinalization.js@@ -19,7 +19,7 @@import { join } from 'path';import { emitLog } from './cosEvents.js';-import { updateAgent, completeAgent } from './cosAgents.js';+import { getAgent, updateAgent, completeAgent } from './cosAgents.js';import { updateTask } from './cos.js';import { getActiveProvider } from './providers.js';import { markProviderUsageLimit, markProviderRateLimited } from './providerStatus.js';@@ -192,6 +192,7 @@ const HOOK_ABORTED_BEFORE_EVALUATION = new Set(['no-app', 'app-not-found']);* subscribes to both), so it can't surface as an unhandled rejection.*/const OUTPUT_HOOK_TIMEOUT_MS = 5 * 60_000;+const outputHookDispatches = new Map();export function withOutputHookTimeout(promise, { agentId, timeoutMs = OUTPUT_HOOK_TIMEOUT_MS }) {let timer;@@ -215,6 +216,78 @@ export function withOutputHookTimeout(promise, { agentId, timeoutMs = OUTPUT_HOOreturn Promise.race([promise, timeout]).finally(() => clearTimeout(timer));}+/**+ * Run an agent's task-type output hook at most once, including completion paths+ * that bypass finalizeAgent after a restart or orphan reap.+ *+ * The persisted marker closes the sequential normal/recovery gap; the per-agent+ * promise closes the smaller same-process race where two completion paths both+ * observe a running, unmarked agent before either hook finishes.+ */+export function dispatchTaskOutputHookOnce({+ agentId,+ task,+ success,+ workspacePath = null,+ readPayload = true,+}) {+ const existing = outputHookDispatches.get(agentId);+ if (existing) return existing;++ const dispatch = (async () => {+ const agent = await getAgent(agentId).catch(() => null);+ if (agent?.metadata?.outputHookDispatchedAt) {+ return { ran: false, alreadyDispatched: true };+ }++ const result = await withOutputHookTimeout(+ dispatchTaskOutputHook({ agentId, task, success, workspacePath, readPayload }),+ { agentId }+ ).catch(err => {+ emitLog('error', `❌ processTaskOutput hook threw for ${agentId} (${task?.taskType}): ${err.message}`, { agentId, error: err.message });+ return { ran: true, threw: true };+ });++ // A missing task/type/hook is not a dispatch and must remain retryable if a+ // later completion path has fuller context. A timeout does count: the hook+ // keeps running after Promise.race releases the completion path.+ if (result.ran || result.timedOut) {+ // Best-effort durability: completion must continue if the marker write+ // fails, while the in-flight promise still protects concurrent callers+ // this cycle.+ await updateAgent(agentId, {+ metadata: { outputHookDispatchedAt: new Date().toISOString() }+ }).catch(err => {+ emitLog('warn', `⚠️ Failed to persist output-hook dispatch marker for ${agentId}: ${err.message}`, { agentId });+ });+ }+ return result;+ })();++ outputHookDispatches.set(agentId, dispatch);+ dispatch.finally(() => {+ if (outputHookDispatches.get(agentId) === dispatch) {+ outputHookDispatches.delete(agentId);+ }+ });+ return dispatch;+}++/**+ * Recovery paths have no trustworthy worktree after a restart/orphan reap, so+ * they deliberately dispatch with a null payload rather than reading a stale+ * `.agent-done` from the task's repository root.+ */+export function dispatchRecoveredTaskOutputHook({ agentId, task, success }) {+ return dispatchTaskOutputHookOnce({+ agentId,+ task,+ success,+ workspacePath: null,+ readPayload: false,+ });+}+/*** Stamp an LI hand-off's per-proposal execution verdict into a completion `taskUpdate`'s* federated metadata (#2779), mutating `taskUpdate.metadata` in place. Shared by every@@ -318,15 +391,7 @@ export async function finalizeAgent({// of awaiting here is that the agent still counts against the CoS concurrency// gate for the hook's duration, so the dispatch is hard-bounded — see// withOutputHookTimeout.- const hookResult = await withOutputHookTimeout(- dispatchTaskOutputHook({ agentId, task, success, workspacePath }),- { agentId }- ).catch(err => {- emitLog('error', `❌ processTaskOutput hook threw for ${agentId} (${task?.taskType}): ${err.message}`, { agentId, error: err.message });- // A thrown hook is a non-success signal for the type ledger (#2616) and a- // rejected success criterion for task-learning (#2727).- return { ran: true, threw: true };- });+ const hookResult = await dispatchTaskOutputHookOnce({ agentId, task, success, workspacePath });// Success-criteria validation (issue #2344): stamp an explicit pass/fail (or// null-when-undeclared) verdict onto the completion result, distinct from the@@ -431,7 +496,7 @@ export async function finalizeAgent({* task types (no hook). The hook receives `{ appId, success, payload, ... }` and* loads its own app/config — finalizeAgent stays domain-agnostic.*/-async function dispatchTaskOutputHook({ agentId, task, success, workspacePath }) {+async function dispatchTaskOutputHook({ agentId, task, success, workspacePath, readPayload = true }) {// Shared resolver with evaluateSuccessCriteria's gate — "runs a hook" and "gets// the programmatic-I/O criterion" must stay the same question (#2727).const taskType = resolveTaskHookType(task);@@ -440,7 +505,7 @@ async function dispatchTaskOutputHook({ agentId, task, success, workspacePath })const hook = await getTaskOutputHook(taskType);if (!hook) return { ran: false };- const cwd = workspacePath || task?.metadata?.repoPath || null;+ const cwd = readPayload ? (workspacePath || task?.metadata?.repoPath || null) : null;let payload = null;if (cwd) {const { DONE_SENTINEL_NAME, parseSentinelPayload, salvageSentinelPayload } = await import('../lib/agentSentinel.js');diff --git a/server/services/agentFinalization.outputHooks.test.js b/server/services/agentFinalization.outputHooks.test.jsnew file mode 100644index 0000000000..ae2e4f380e--- /dev/null+++ b/server/services/agentFinalization.outputHooks.test.js@@ -0,0 +1,165 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { readFileSync } from 'fs';+import { dirname, join } from 'path';+import { fileURLToPath } from 'url';++vi.mock('./cosAgents.js', () => ({+ getAgent: vi.fn(),+ updateAgent: vi.fn(),+ completeAgent: vi.fn(),+}));++vi.mock('./taskTypeHooks.js', () => ({+ getTaskOutputHook: vi.fn(),+ isNonCommittingCoordinatorTask: vi.fn(() => false),+ isProgrammaticIoTaskType: vi.fn(() => true),+ resolveTaskHookType: vi.fn(task => task?.metadata?.analysisType || null),+}));++import { getAgent, updateAgent } from './cosAgents.js';+import { getTaskOutputHook } from './taskTypeHooks.js';+import {+ dispatchRecoveredTaskOutputHook,+ dispatchTaskOutputHookOnce,+} from './agentFinalization.js';++const __dirname = dirname(fileURLToPath(import.meta.url));+const MANAGEMENT_SOURCE = readFileSync(join(__dirname, 'agentManagement.js'), 'utf8');+const LIFECYCLE_SOURCE = readFileSync(join(__dirname, 'agentLifecycle.js'), 'utf8');+const TASK = {+ id: 'sys-example',+ taskType: 'internal',+ metadata: {+ analysisType: 'example-output-hook',+ app: 'app-example',+ repoPath: '/example/repo',+ },+};++describe('recovery output-hook dispatch (#3182)', () => {+ let persistedAgent;+ let hook;++ beforeEach(() => {+ vi.clearAllMocks();+ persistedAgent = {+ id: 'agent-example',+ status: 'running',+ metadata: {},+ };+ getAgent.mockImplementation(async () => persistedAgent);+ updateAgent.mockImplementation(async (_agentId, updates) => {+ persistedAgent = {+ ...persistedAgent,+ metadata: { ...persistedAgent.metadata, ...updates.metadata },+ };+ return persistedAgent;+ });+ hook = vi.fn().mockResolvedValue({ recorded: true });+ getTaskOutputHook.mockResolvedValue(hook);+ });++ it.each([+ ['orphan cleanup', false],+ ['post-restart completion', true],+ ])('runs a registered processTaskOutput hook for %s with no stale sentinel payload', async (_path, success) => {+ const result = await dispatchRecoveredTaskOutputHook({+ agentId: persistedAgent.id,+ task: TASK,+ success,+ });++ expect(result).toEqual({ ran: true, outcome: { recorded: true } });+ expect(hook).toHaveBeenCalledOnce();+ expect(hook).toHaveBeenCalledWith(expect.objectContaining({+ agentId: persistedAgent.id,+ task: TASK,+ appId: 'app-example',+ success,+ payload: null,+ workspacePath: null,+ }));+ expect(updateAgent).toHaveBeenCalledWith(+ persistedAgent.id,+ { metadata: { outputHookDispatchedAt: expect.any(String) } },+ );+ });++ it('deduplicates concurrent normal/recovery completion and persists the gate', async () => {+ let finishHook;+ hook.mockReturnValueOnce(new Promise(resolve => { finishHook = resolve; }));++ const normal = dispatchTaskOutputHookOnce({+ agentId: persistedAgent.id,+ task: TASK,+ success: true,+ workspacePath: '/example/worktree',+ });+ const recovery = dispatchRecoveredTaskOutputHook({+ agentId: persistedAgent.id,+ task: TASK,+ success: false,+ });++ expect(recovery).toBe(normal);+ await vi.waitFor(() => expect(hook).toHaveBeenCalledOnce());+ finishHook({ recorded: true });+ await expect(normal).resolves.toEqual({ ran: true, outcome: { recorded: true } });++ await expect(dispatchRecoveredTaskOutputHook({+ agentId: persistedAgent.id,+ task: TASK,+ success: false,+ })).resolves.toEqual({ ran: false, alreadyDispatched: true });+ expect(hook).toHaveBeenCalledOnce();+ });++ it('does not dispatch after finalizeAgent persisted the explicit hook marker', async () => {+ persistedAgent.metadata.outputHookDispatchedAt = new Date().toISOString();++ await expect(dispatchRecoveredTaskOutputHook({+ agentId: persistedAgent.id,+ task: TASK,+ success: false,+ })).resolves.toEqual({ ran: false, alreadyDispatched: true });+ expect(hook).not.toHaveBeenCalled();+ });++ it('still dispatches for an agent completed early by terminate/kill before finalizeAgent', async () => {+ persistedAgent.status = 'completed';++ await expect(dispatchTaskOutputHookOnce({+ agentId: persistedAgent.id,+ task: TASK,+ success: false,+ })).resolves.toEqual({ ran: true, outcome: { recorded: true } });+ expect(hook).toHaveBeenCalledOnce();+ });++ it('does not persist a dispatch marker when recovery has no registered hook', async () => {+ getTaskOutputHook.mockResolvedValueOnce(null);++ await expect(dispatchRecoveredTaskOutputHook({+ agentId: persistedAgent.id,+ task: TASK,+ success: false,+ })).resolves.toEqual({ ran: false });+ expect(updateAgent).not.toHaveBeenCalled();+ });+});++describe('recovery path wiring (#3182)', () => {+ it('dispatches before orphan cleanup marks the agent complete', () => {+ const start = MANAGEMENT_SOURCE.indexOf('export async function cleanupOrphanedAgents');+ const body = MANAGEMENT_SOURCE.slice(start, start + 7_000);+ expect(body.indexOf('dispatchRecoveredTaskOutputHook({')).toBeGreaterThan(-1);+ expect(body.indexOf('dispatchRecoveredTaskOutputHook({')).toBeLessThan(body.indexOf('await markComplete(agent.id'));+ });++ it('dispatches before post-restart recovery marks the agent complete', () => {+ const start = LIFECYCLE_SOURCE.indexOf('Completing untracked agent');+ const body = LIFECYCLE_SOURCE.slice(start, start + 2_000);+ expect(body.indexOf('dispatchRecoveredTaskOutputHook({')).toBeGreaterThan(-1);+ expect(body.indexOf('dispatchRecoveredTaskOutputHook({')).toBeLessThan(body.indexOf('await completeAgent(agentId'));+ });+});diff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.jsindex bf50d3fe45..a2f43ff07f 100644--- a/server/services/agentLifecycle.js+++ b/server/services/agentLifecycle.js@@ -59,7 +59,7 @@ import { resolveAgentProviderAndModel } from './agentProviderResolution.js';import { prepareAgentWorkspace } from './agentWorkspacePrep.js';import { cleanupAgentWorktree } from './agentWorktreeCleanup.js';import { runAgentCompletionCleanup } from './agentCompletionCleanup.js';-import { finalizeAgent, stampLiExecutionVerdict } from './agentFinalization.js';+import { dispatchRecoveredTaskOutputHook, finalizeAgent, stampLiExecutionVerdict } from './agentFinalization.js';import { extractFinalSummary } from './agentSummaryExtraction.js';import { handleOrphanedTask } from './agentManagement.js';@@ -74,7 +74,7 @@ export { handlePipelineProgression } from './agentCompletionCleanup.js';// break the static import cycle with the two spawners (issue #2837). Re-exported// here so long-standing consumers (subAgentSpawner's barrel, agentManagement,// existing tests) keep resolving them from agentLifecycle.js.-export { finalizeAgent, releaseAgentLane, evaluateSuccessCriteria, resolveProgrammaticIoVerdict, withOutputHookTimeout, persistSimplifySummaries } from './agentFinalization.js';+export { dispatchRecoveredTaskOutputHook, dispatchTaskOutputHookOnce, finalizeAgent, releaseAgentLane, evaluateSuccessCriteria, resolveProgrammaticIoVerdict, withOutputHookTimeout, persistSimplifySummaries } from './agentFinalization.js';export { extractFinalSummary, extractSimplifySummaries } from './agentSummaryExtraction.js';export { syncRunnerAgents } from './agentRunnerSync.js';@@ -774,6 +774,8 @@ export async function handleAgentCompletion(agentId, exitCode, success, durationreturn;}console.log(`🔄 Completing untracked agent ${agentId} from cos state (post-restart)`);+ const task = cosAgent.taskId ? await getTaskById(cosAgent.taskId).catch(() => null) : null;+ await dispatchRecoveredTaskOutputHook({ agentId, task, success });await completeAgent(agentId, {success,exitCode,@@ -782,7 +784,6 @@ export async function handleAgentCompletion(agentId, exitCode, success, durationerror: success ? undefined : 'Agent completed after server restart'});if (cosAgent.taskId) {- const task = await getTaskById(cosAgent.taskId).catch(() => null);if (task && task.status !== 'completed') {if (success) {// Stamp the LI hand-off verdict here too (#2779, codex P2) — this post-restartdiff --git a/server/services/agentManagement.js b/server/services/agentManagement.jsindex c0915cb7b3..8b1e287cde 100644--- a/server/services/agentManagement.js+++ b/server/services/agentManagement.js@@ -22,6 +22,7 @@ import { cleanupAgentWorktree } from './agentWorktreeCleanup.js';import { syncRunnerAgents } from './agentRunnerSync.js';import { flushRunnerOutputBatcher } from './agentRunnerOutputBatchers.js';import { checkForTaskCommit } from './agentRunTracking.js';+import { dispatchRecoveredTaskOutputHook } from './agentFinalization.js';import { PATHS } from '../lib/fileUtils.js';import { killProcessTree } from '../lib/bufferedSpawn.js';import { release } from './executionLanes.js';@@ -596,6 +597,12 @@ export async function cleanupOrphanedAgents() {}console.log(`🧹 Cleaning up orphaned agent ${agent.id} (PID ${agent.pid || 'unknown'} not running)`);+ const task = agent.taskId ? await getTask(agent.taskId).catch(() => null) : null;+ await dispatchRecoveredTaskOutputHook({+ agentId: agent.id,+ task,+ success: false,+ });await markComplete(agent.id, {success: false,error: 'Agent process terminated unexpectedly',