Skip to content

The open-source app everyone uses to manage agents at work

fix(heartbeat): reconcile stranded running agent status (#16791)

Devin Foley2f6ad2226aec
diff --git a/doc/DEVELOPING.md b/doc/DEVELOPING.md
index c56e8dfb67..12d8fadfbd 100644
--- a/doc/DEVELOPING.md
+++ b/doc/DEVELOPING.md
@@ -563,6 +563,32 @@ Allow additional private hostnames (for example custom Tailscale hostnames):
npx paperclipai allowed-hostname dotta-macbook-pro
```
+## Agent status recovery
+
+Heartbeat completion locks the agent row before it reads remaining running work
+and writes the agent status. A concurrent execution start cannot be overwritten
+by a completion that read older run state. Run terminalization and agent status
+finalization remain separate steps. If the process exits between them, the
+existing startup and periodic orphan-run recovery pass repairs stranded agent
+statuses after a five-minute grace period, at most 25 agents per pass.
+
+The repair requires finished runs and wake requests, expired controller ownership,
+settled accounting and retries, and no pending resource or instruction cleanup.
+It also checks the shared local execution sets. It rechecks under an agent row
+lock, preserves pause and retirement, and records the correction in the same
+transaction. It preserves run history and does not invent a heartbeat timestamp.
+The latest failed or timed-out run produces an error status. This adds no timer,
+provider call, or automatic workspace wake. Idle sleep checks remain independent.
+Failed lease history uses the same exact cleanup proof as idle sleep. Cleanup
+queues are checked separately from retained run metadata. Recovery queries have
+a two-second statement timeout, and the repair stops starting new candidates
+after five seconds. A repair failure is logged without rejecting the rest of
+orphan recovery.
+
+```sh
+pnpm exec vitest run server/src/services/heartbeat/agent-status.test.ts server/src/__tests__/heartbeat-agent-status-recovery.test.ts
+```
+
## Test Commands
The [feature map](../maps/feature-map/README.md) is an optional reference for user
diff --git a/server/src/__tests__/heartbeat-agent-status-recovery.test.ts b/server/src/__tests__/heartbeat-agent-status-recovery.test.ts
new file mode 100644
index 0000000000..cec0412de6
--- /dev/null
+++ b/server/src/__tests__/heartbeat-agent-status-recovery.test.ts
@@ -0,0 +1,71 @@
+import { randomUUID } from "node:crypto";
+import { agents, companies, createDb, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS, heartbeatRuns, type Db } from "@paperclipai/db";
+import { eq, sql } from "drizzle-orm";
+import { afterAll, beforeAll, describe, expect, it } from "vitest";
+import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
+import { heartbeatService } from "../services/heartbeat.js";
+import { readIdleSleepSafety } from "../services/idle-sleep-safety.js";
+
+const support = await getEmbeddedPostgresTestSupport();
+const describePostgres = support.supported ? describe : describe.skip;
+if (!support.supported) console.warn(`Skipping assembled agent status recovery: ${support.reason}`);
+
+describePostgres("heartbeat recovery of a stranded agent", () => {
+ let db: Db;
+ let database: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
+ beforeAll(async () => {
+ database = await startEmbeddedPostgresTestDatabase("paperclip-heartbeat-agent-status-");
+ db = createDb(database.connectionString);
+ }, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS);
+ afterAll(async () => { await database?.cleanup(); });
+
+ it("repairs shutdown state through the existing reaper and permits a quiet idle proof", async () => {
+ const companyId = randomUUID(), agentId = randomUUID(), runId = randomUUID();
+ const old = new Date(Date.now() - 60 * 60_000);
+ await db.insert(companies).values({ id: companyId, name: "Recovery fixture", issuePrefix: "RCVR" });
+ await db.insert(agents).values({ id: agentId, companyId, name: "Worker", role: "engineer",
+ status: "running", adapterType: "process", runtimeConfig: { heartbeat: { enabled: false } },
+ updatedAt: old, lastHeartbeatAt: null });
+ await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId,
+ status: "interrupted", runtimeMode: "legacy", invocationSource: "automation",
+ errorCode: "server_shutdown_interrupted", startedAt: old, finishedAt: old, updatedAt: old });
+ const now = Date.now();
+ const ownerId = randomUUID();
+ const drain = () => ({ ownerId, draining: true, startedAt: new Date(now - 1_000),
+ expiresAt: new Date(now + 60_000), activeRuns: 0, pendingWakes: 0 });
+ const inspect = () => readIdleSleepSafety(db, drain, () => now, ownerId, async () => "none");
+ expect(await inspect()).toEqual({ version: 1, backgroundWork: "present" });
+
+ const service = heartbeatService(db);
+ expect(await service.reapOrphanedRuns()).toEqual({ reaped: 0, runIds: [] });
+ expect(await db.select().from(agents).where(eq(agents.id, agentId)))
+ .toEqual([expect.objectContaining({ status: "idle", lastHeartbeatAt: null })]);
+ expect(await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId)))
+ .toEqual([expect.objectContaining({ status: "interrupted", errorCode: "server_shutdown_interrupted" })]);
+ expect(await inspect()).toEqual({ version: 1, backgroundWork: "none" });
+
+ const replacement = heartbeatService(db);
+ expect(await replacement.reapOrphanedRuns()).toEqual({ reaped: 0, runIds: [] });
+ expect(await inspect()).toEqual({ version: 1, backgroundWork: "none" });
+ });
+
+ it("keeps unrelated recovery available when the correction audit fails", async () => {
+ const companyId = randomUUID(), agentId = randomUUID();
+ const old = new Date(Date.now() - 60 * 60_000);
+ await db.insert(companies).values({ id: companyId, name: "Audit failure", issuePrefix: "ADTF" });
+ await db.insert(agents).values({ id: agentId, companyId, name: "Worker", role: "engineer",
+ status: "running", adapterType: "process", updatedAt: old });
+ await db.execute(sql`ALTER TABLE activity_log ADD CONSTRAINT reject_status_repair CHECK (action <> 'agent.status_reconciled') NOT VALID`);
+ const service = heartbeatService(db);
+ try {
+ expect(await service.reapOrphanedRuns()).toEqual({ reaped: 0, runIds: [] });
+ expect(await db.select().from(agents).where(eq(agents.id, agentId)))
+ .toEqual([expect.objectContaining({ status: "running" })]);
+ } finally {
+ await db.execute(sql`ALTER TABLE activity_log DROP CONSTRAINT reject_status_repair`);
+ }
+ expect(await service.reapOrphanedRuns()).toEqual({ reaped: 0, runIds: [] });
+ expect(await db.select().from(agents).where(eq(agents.id, agentId)))
+ .toEqual([expect.objectContaining({ status: "idle" })]);
+ });
+});
diff --git a/server/src/services/heartbeat.ts b/server/src/services/heartbeat.ts
index 31c26160a2..55d6d15d59 100644
--- a/server/src/services/heartbeat.ts
+++ b/server/src/services/heartbeat.ts
@@ -1,3 +1,4 @@
+import { createHeartbeatAgentStatus } from "./heartbeat/agent-status.js";
import { heartbeatExternalProvider, nativeRuntimeHasInstructionFilesystem } from "./heartbeat/external-provider.js";
import { dotRunnerBroker } from "./dot-runner-broker.js";
import { withRunExecutionTiming, measureRunPhase, measureWorkspaceSyncPhase, isWorkspaceSyncDetailPhase } from "./execution-preparation-timing.js";
@@ -368,8 +369,6 @@ import {
isNativeRunnerOwnershipHeld,
NATIVE_OWNERSHIP_UNVERIFIED_ERROR_CODE,
} from "./native-runtime/native-runner-ownership.js";
-import { trackAgentFirstHeartbeat } from "@paperclipai/shared/telemetry";
-import { getTelemetryClient } from "../telemetry.js";
import {
emitAgentTaskRun,
emitAgentTaskRunById,
@@ -798,6 +797,7 @@ export function heartbeatService(
db: Db,
options: HeartbeatServiceOptions = {},
) {
+ const { finalizeAgentStatus } = createHeartbeatAgentStatus(db);
const {
getAgent,
resolveSessionBeforeForWakeup,
@@ -1261,7 +1261,6 @@ export function heartbeatService(
});
const {
- countRunningRunsForAgent,
releaseRunClaimedJustBeforeSuppression,
claimQueuedRun,
withChatControlRecoveryGate,
@@ -1543,85 +1542,6 @@ export function heartbeatService(
void reportRunFailure(db, updated, failureReport);
}
- function truncateAgentErrorReason(
- reason: string | null | undefined,
- ): string | null {
- if (!reason) return null;
- const trimmed = reason.trim();
- if (!trimmed) return null;
- return trimmed.length > 500 ? `${trimmed.slice(0, 499)}…` : trimmed;
- }
-
- async function finalizeAgentStatus(
- agentId: string,
- outcome: "succeeded" | "interrupted" | "failed" | "cancelled" | "timed_out",
- failureReason?: string | null,
- options?: { keepIdleOnFailure?: boolean; wasFirstHeartbeat?: boolean },
- ) {
- const existing = await getAgent(agentId);
- if (!existing) return;
-
- if (existing.status === "paused" || existing.status === "terminated") {
- return;
- }
-
- const isFirstHeartbeat =
- options?.wasFirstHeartbeat ?? !existing.lastHeartbeatAt;
-
- const runningCount = await countRunningRunsForAgent(agentId);
- const nextStatus =
- runningCount > 0
- ? "running"
- : outcome === "succeeded" ||
- outcome === "interrupted" ||
- outcome === "cancelled" ||
- (outcome === "failed" && options?.keepIdleOnFailure)
- ? "idle"
- : "error";
-
- const updated = await db
- .update(agents)
- .set({
- status: nextStatus,
- // Persist a human-readable reason on the agent record when it enters
- // error so operators see it on the agent page without digging into run
- // events; clear it whenever the agent leaves error.
- errorReason:
- nextStatus === "error"
- ? truncateAgentErrorReason(failureReason)
- : null,
- lastHeartbeatAt: new Date(),
- updatedAt: new Date(),
- })
- .where(and(eq(agents.id, agentId), eq(agents.lifecycleState, "ready")))
- .returning()
- .then((rows) => rows[0] ?? null);
-
- if (isFirstHeartbeat && updated) {
- const tc = getTelemetryClient();
- if (tc)
- trackAgentFirstHeartbeat(tc, {
- agentRole: updated.role,
- agentId: updated.id,
- });
- }
-
- if (updated) {
- publishLiveEvent({
- companyId: updated.companyId,
- type: "agent.status",
- payload: {
- agentId: updated.id,
- status: updated.status,
- lastHeartbeatAt: updated.lastHeartbeatAt
- ? new Date(updated.lastHeartbeatAt).toISOString()
- : null,
- outcome,
- },
- });
- }
- }
-
async function reconcileStrandedAssignedIssues() {
return recovery.reconcileStrandedAssignedIssues({
issueCreatedAtGte: await getWorktreeExecutionCutoff(),
diff --git a/server/src/services/heartbeat/agent-status.test.ts b/server/src/services/heartbeat/agent-status.test.ts
new file mode 100644
index 0000000000..648fbded0f
--- /dev/null
+++ b/server/src/services/heartbeat/agent-status.test.ts
@@ -0,0 +1,320 @@
+import { randomUUID } from "node:crypto";
+import {
+ activityLog, agentInstructionWorkingCopies, agents, agentWakeupRequests, companies,
+ createDb, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS, environmentLeases, environments, heartbeatRuns,
+ issues, nativeRunFinalizations, type Db,
+} from "@paperclipai/db";
+import { and, eq, sql } from "drizzle-orm";
+import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
+import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../../__tests__/helpers/embedded-postgres.js";
+import { createHeartbeatAgentStatus, settledAgentWorkCondition } from "./agent-status.js";
+
+const support = await getEmbeddedPostgresTestSupport();
+const describePostgres = support.supported ? describe : describe.skip;
+if (!support.supported) console.warn(`Skipping agent status database tests: ${support.reason}`);
+
+describePostgres("heartbeat agent status", () => {
+ let db: Db;
+ let database: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
+ let service: ReturnType<typeof createHeartbeatAgentStatus>;
+ const live = new Set<string>();
+ const old = () => new Date(Date.now() - 60 * 60_000);
+
+ beforeAll(async () => {
+ database = await startEmbeddedPostgresTestDatabase("paperclip-agent-status-");
+ db = createDb(database.connectionString);
+ service = createHeartbeatAgentStatus(db);
+ }, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS);
+ beforeEach(async () => {
+ live.clear();
+ await db.delete(nativeRunFinalizations);
+ await db.delete(environmentLeases);
+ await db.delete(environments);
+ await db.delete(activityLog);
+ await db.delete(agentInstructionWorkingCopies);
+ await db.delete(heartbeatRuns);
+ await db.delete(agentWakeupRequests);
+ await db.delete(issues);
+ await db.delete(agents);
+ await db.delete(companies);
+ });
+ afterAll(async () => { await database?.cleanup(); });
+
+ async function seed(status = "interrupted") {
+ const companyId = randomUUID(), agentId = randomUUID(), runId = randomUUID(), issueId = randomUUID();
+ await db.insert(companies).values({ id: companyId, name: "Status recovery", issuePrefix: `T${companyId.slice(0, 6)}` });
+ await db.insert(agents).values({ id: agentId, companyId, name: "Worker", role: "engineer",
+ status: "running", adapterType: "process", runtimeConfig: { heartbeat: { enabled: false } },
+ lastHeartbeatAt: null, updatedAt: old(), createdAt: old() });
+ await db.insert(issues).values({ id: issueId, companyId, title: "Finished work", status: "done" });
+ await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId,
+ invocationSource: "automation", status, runtimeMode: "legacy", startedAt: old(),
+ finishedAt: ["running", "queued"].includes(status) ? null : old(),
+ updatedAt: old(), createdAt: old(),
+ errorCode: status === "interrupted" ? "server_shutdown_interrupted" : null });
+ return { companyId, agentId, runId, issueId };
+ }
+
+ const reconcile = () => service.reconcileStrandedAgentStatuses(() => live);
+ const agent = (id: string) => db.select().from(agents).where(eq(agents.id, id)).then(rows => rows[0]!);
+
+ it("repairs a shutdown flag without inventing a heartbeat, and records the repair once", async () => {
+ const { agentId, runId } = await seed();
+ expect(await reconcile()).toEqual([agentId]);
+ expect(await agent(agentId)).toMatchObject({ status: "idle", lastHeartbeatAt: null, errorReason: null });
+ expect(await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId)))
+ .toEqual([expect.objectContaining({ status: "interrupted", errorCode: "server_shutdown_interrupted" })]);
+ expect(await reconcile()).toEqual([]);
+ expect(await db.select().from(activityLog)).toEqual([expect.objectContaining({
+ entityId: agentId, action: "agent.status_reconciled",
+ details: { previousStatus: "running", nextStatus: "idle", reason: "no_unsettled_execution" },
+ })]);
+ });
+
+ it("repairs a pre-run flag when no run was ever recorded", async () => {
+ const { agentId, runId } = await seed();
+ await db.delete(heartbeatRuns).where(eq(heartbeatRuns.id, runId));
+ expect(await reconcile()).toEqual([agentId]);
+ });
+
+ it.each(["failed", "timed_out"])("preserves a %s outcome and its error", async status => {
+ const { agentId, runId } = await seed(status);
+ await db.update(heartbeatRuns).set({ error: " Execution failed " }).where(eq(heartbeatRuns.id, runId));
+ expect(await reconcile()).toEqual([agentId]);
+ expect(await agent(agentId)).toMatchObject({ status: "error", errorReason: "Execution failed" });
+ });
+
+ it.each(["running", "queued", "unrecognized"])("keeps a %s run as work", async status => {
+ const { agentId } = await seed(status);
+ expect(await reconcile()).toEqual([]);
+ expect((await agent(agentId)).status).toBe("running");
+ });
+
+ it.each(["paused", "terminated", "error", "pending_approval"])("preserves an agent's %s state", async status => {
+ const { agentId } = await seed();
+ await db.update(agents).set({ status }).where(eq(agents.id, agentId));
+ expect(await reconcile()).toEqual([]);
+ if (["paused", "terminated", "pending_approval"].includes(status)) {
+ await db.update(agents).set({ lifecycleState: "paused" }).where(eq(agents.id, agentId));
+ await service.finalizeAgentStatus(agentId, "succeeded");
+ }
+ expect((await agent(agentId)).status).toBe(status);
+ });
+
+ it("retains the startup grace window", async () => {
+ const { agentId } = await seed();
+ await db.update(agents).set({ updatedAt: new Date() }).where(eq(agents.id, agentId));
+ expect(await reconcile()).toEqual([]);
+ });
+
+ it.each(["missing_finish", "accounting", "retry", "controller", "local_execution"])("retains unfinished %s work", async hold => {
+ const { runId } = await seed();
+ const patch = hold === "missing_finish" ? { finishedAt: null }
+ : hold === "accounting" ? { costAccountingPending: true }
+ : hold === "retry" ? { scheduledRetryAt: new Date() }
+ : hold === "controller" ? { controllerLeaseExpiresAt: new Date(Date.now() + 60_000) } : {};
+ await db.update(heartbeatRuns).set({ ...patch, updatedAt: old() }).where(eq(heartbeatRuns.id, runId));
+ if (hold === "local_execution") live.add(runId);
+ expect(await reconcile()).toEqual([]);
+ });
+
+ it("retains an admitted wake even without a run", async () => {
+ const { companyId, agentId } = await seed();
+ await db.insert(agentWakeupRequests).values({ companyId, agentId, source: "on_demand", status: "queued" });
+ expect(await reconcile()).toEqual([]);
+ });
+
+ it("retains resource cleanup and succeeds after cleanup is recorded", async () => {
+ const { companyId, agentId, runId } = await seed();
+ const [lease] = await db.insert(environmentLeases).values({ companyId, heartbeatRunId: runId,
+ status: "pending_cleanup", provider: "daytona", providerLeaseId: "synthetic-allocation" }).returning();
+ expect(await reconcile()).toEqual([]);
+ await db.update(environmentLeases).set({ status: "released", releasedAt: old() }).where(eq(environmentLeases.id, lease!.id));
+ expect(await reconcile()).toEqual([agentId]);
+ });
+
+ it.each(["pendingCleanupInFlight", "nativeWorkspaceExportResume", "sandboxStopAndRetain"])("keeps a released lease's %s obligation", async key => {
+ const { companyId, runId } = await seed();
+ await db.insert(environmentLeases).values({ companyId, heartbeatRunId: runId,
+ status: "released", releasedAt: old(), metadata: { [key]: true } });
+ expect(await reconcile()).toEqual([]);
+ });
+
+ it("accepts proved-settled failed local lease history before a later shutdown", async () => {
+ const { companyId, agentId, runId } = await seed("failed");
+ const [environment] = await db.insert(environments).values({ name: "Local", driver: "local" }).returning();
+ await db.insert(environmentLeases).values({ companyId, heartbeatRunId: runId, environmentId: environment!.id,
+ status: "failed", leasePolicy: "ephemeral", provider: "local", releasedAt: old(), metadata: { driver: "local" } });
+ await db.insert(heartbeatRuns).values({ companyId, agentId, invocationSource: "automation", status: "interrupted",
+ runtimeMode: "legacy", startedAt: old(), finishedAt: new Date(Date.now() - 30 * 60_000) });
+ expect(await reconcile()).toEqual([agentId]);
+ expect((await agent(agentId)).status).toBe("idle");
+ });
+
+ it.each(["valid", "wrong_run", "missing_receipt", "pending_cleanup"])("requires exact failed remote cleanup proof: %s", async kind => {
+ const { companyId, agentId, runId } = await seed();
+ const leaseId = randomUUID();
+ const receipt = { schema: "paperclip.remote-termination.v1", companyId, runId: kind === "wrong_run" ? randomUUID() : runId,
+ leaseId, provider: "daytona", providerLeaseId: "synthetic-allocation", state: "destroyed" };
+ await db.insert(environmentLeases).values({ id: leaseId, companyId, heartbeatRunId: runId,
+ status: "failed", leasePolicy: "ephemeral", provider: "daytona", providerLeaseId: "synthetic-allocation",
+ releasedAt: old(), cleanupStatus: "success", metadata: {
+ ...(kind === "missing_receipt" ? {} : { remoteExecutionTermination: receipt }),
+ ...(kind === "pending_cleanup" ? { pendingCleanupInFlight: true } : {}),
+ } });
+ expect(await reconcile()).toEqual(kind === "valid" ? [agentId] : []);
+ });
+
+ it("does not probe cleanup once per retained finished run", async () => {
+ const { companyId, agentId } = await seed();
+ await db.execute(sql`INSERT INTO heartbeat_runs (company_id, agent_id, invocation_source, status,
+ started_at, finished_at, created_at, updated_at)
+ SELECT ${companyId}::uuid, ${agentId}::uuid, 'automation', 'succeeded',
+ ${old().toISOString()}::timestamptz, ${old().toISOString()}::timestamptz,
+ ${old().toISOString()}::timestamptz, ${old().toISOString()}::timestamptz
+ FROM generate_series(1, 10000)`);
+ await db.execute(sql`ANALYZE heartbeat_runs`);
+ const predicate = and(eq(agents.id, agentId), settledAgentWorkCondition(live, new Date()));
+ const result = await db.execute(sql`EXPLAIN (ANALYZE, FORMAT JSON)
+ SELECT ${agents.id} FROM ${agents} WHERE ${predicate}`);
+ const plan = result[0]!["QUERY PLAN"] as Array<{ Plan: Record<string, unknown> }>;
+ const scans: Record<string, number[]> = {};
+ function visit(node: Record<string, unknown>) {
+ const relation = node["Relation Name"] as string | undefined;
+ if (relation) (scans[relation] ??= []).push(Number(node["Actual Loops"]));
+ for (const child of (node.Plans ?? []) as Record<string, unknown>[]) visit(child);
+ }
+ visit(plan[0]!.Plan);
+ for (const table of ["native_run_finalizations", "environment_leases"]) {
+ expect(scans[table]?.length).toBeGreaterThan(0);
+ expect(Math.max(...scans[table]!)).toBeLessThanOrEqual(1);
+ }
+ expect(await reconcile()).toEqual([agentId]);
+ });
+
+ it("retains unfinished instruction copyback", async () => {
+ const { companyId, agentId, runId } = await seed();
+ await db.insert(agentInstructionWorkingCopies).values({ companyId, agentId, runId,
+ responsibleUserId: "test-user", entryFile: "AGENTS.md", baseHash: "test-hash",
+ localRoot: "/tmp/test-root", executionRoot: "/tmp/test-root", location: "local",
+ state: "captured", receipt: {}, processStoppedAt: old() });
+ expect(await reconcile()).toEqual([]);
+ await db.update(agentInstructionWorkingCopies).set({ state: "saved" })
+ .where(eq(agentInstructionWorkingCopies.runId, runId));
+ expect(await reconcile()).toEqual([agentId]);
+ });
+
+ it("retains native finalization ownership", async () => {
+ const { companyId, runId, issueId } = await seed();
+ await db.update(heartbeatRuns).set({ runtimeMode: "native", nativeIssueId: issueId }).where(eq(heartbeatRuns.id, runId));
+ await db.insert(nativeRunFinalizations).values({ companyId, runId, issueId, phase: "workspace_finalizing" });
+ expect(await reconcile()).toEqual([]);
+ });
+
+ it("does not read another company's run as the agent's outcome", async () => {
+ const own = await seed();
+ const other = await seed("failed");
+ await db.update(heartbeatRuns).set({ agentId: own.agentId }).where(eq(heartbeatRuns.id, other.runId));
+ expect(await reconcile()).toContain(own.agentId);
+ expect((await agent(own.agentId)).status).toBe("idle");
+ });
+
+ it("bounds each recovery pass and leaves the next batch eligible", async () => {
+ for (let i = 0; i < 27; i++) await seed();
+ expect(await reconcile()).toHaveLength(25);
+ expect(await reconcile()).toHaveLength(2);
+ });
+
+ it("rolls the correction back when the audit write fails", async () => {
+ const { agentId } = await seed();
+ await db.execute(sql`ALTER TABLE activity_log ADD CONSTRAINT reject_status_repair CHECK (action <> 'agent.status_reconciled')`);
+ try {
+ await expect(reconcile()).rejects.toThrow();
+ expect((await agent(agentId)).status).toBe("running");
+ } finally {
+ await db.execute(sql`ALTER TABLE activity_log DROP CONSTRAINT reject_status_repair`);
+ }
+ expect(await reconcile()).toEqual([agentId]);
+ });
+
+ it("rechecks admission that commits after candidate selection", async () => {
+ const { companyId, agentId } = await seed();
+ let transactions = 0;
+ const raced = new Proxy(db, {
+ get(target, property, receiver) {
+ if (property !== "transaction") return Reflect.get(target, property, receiver);
+ return async (callback: Parameters<Db["transaction"]>[0]) => {
+ if (++transactions === 2) await db.insert(heartbeatRuns).values({ companyId, agentId, invocationSource: "on_demand", status: "queued" });
+ return db.transaction(callback);
+ };
+ },
+ });
+ expect(await createHeartbeatAgentStatus(raced).reconcileStrandedAgentStatuses(() => live)).toEqual([]);
+ expect((await agent(agentId)).status).toBe("running");
+ });
+
+ it("skips a concurrent status writer and preserves its pause", async () => {
+ const { agentId } = await seed();
+ let locked!: () => void, release!: () => void;
+ const acquired = new Promise<void>(resolve => { locked = resolve; });
+ const gate = new Promise<void>(resolve => { release = resolve; });
+ const pause = db.transaction(async tx => {
+ await tx.update(agents).set({ status: "paused" }).where(eq(agents.id, agentId));
+ locked();
+ await gate;
+ });
+ await acquired;
+ try { expect(await reconcile()).toEqual([]); }
+ finally { release(); await pause; }
+ expect((await agent(agentId)).status).toBe("paused");
+ });
+
+ it("does not overwrite a new run while finalization waits for the agent row", async () => {
+ const { companyId, agentId } = await seed();
+ let locked!: () => void, release!: () => void;
+ const acquired = new Promise<void>(resolve => { locked = resolve; });
+ const gate = new Promise<void>(resolve => { release = resolve; });
+ const dispatch = db.transaction(async tx => {
+ await tx.update(agents).set({ status: "running" }).where(eq(agents.id, agentId));
+ locked();
+ await gate;
+ await tx.insert(heartbeatRuns).values({ companyId, agentId,
+ invocationSource: "on_demand", status: "running" });
+ });
+ await acquired;
+ const completion = service.finalizeAgentStatus(agentId, "succeeded");
+ try {
+ const deadline = Date.now() + 5_000;
+ while (true) {
+ const result = await db.execute<{ blocked: boolean }>(sql`SELECT EXISTS (
+ SELECT 1 FROM pg_stat_activity WHERE datname = current_database()
+ AND wait_event_type = 'Lock' AND query LIKE '%agents%'
+ ) AS blocked`);
+ if (result[0]?.blocked) break;
+ if (Date.now() > deadline) throw new Error("Finalization did not wait on the dispatch lock");
+ await new Promise(resolve => setTimeout(resolve, 10));
+ }
+ } finally {
+ release();
+ await dispatch;
+ await completion;
+ }
+ expect((await agent(agentId)).status).toBe("running");
+ });
+
+ it.each(["succeeded", "interrupted", "cancelled", "failed", "timed_out"] as const)("keeps completion semantics for %s", async outcome => {
+ const { agentId } = await seed(outcome);
+ await service.finalizeAgentStatus(agentId, outcome, "Failure detail");
+ expect(await agent(agentId)).toMatchObject({
+ status: ["failed", "timed_out"].includes(outcome) ? "error" : "idle",
+ errorReason: ["failed", "timed_out"].includes(outcome) ? "Failure detail" : null,
+ lastHeartbeatAt: expect.any(Date),
+ });
+ });
+
+ it("keeps failures idle when the caller owns a continuation", async () => {
+ const { agentId } = await seed("failed");
+ await service.finalizeAgentStatus(agentId, "failed", "Retrying", { keepIdleOnFailure: true });
+ expect(await agent(agentId)).toMatchObject({ status: "idle", errorReason: null });
+ });
+});
diff --git a/server/src/services/heartbeat/agent-status.ts b/server/src/services/heartbeat/agent-status.ts
new file mode 100644
index 0000000000..427e02121a
--- /dev/null
+++ b/server/src/services/heartbeat/agent-status.ts
@@ -0,0 +1,161 @@
+import { agents, heartbeatRuns, type Db } from "@paperclipai/db";
+import { and, asc, desc, eq, lte, sql } from "drizzle-orm";
+import { trackAgentFirstHeartbeat } from "@paperclipai/shared/telemetry";
+import { getTelemetryClient } from "../../telemetry.js";
+import { logActivity, publishActivity, type ActivityPublication } from "../activity-log.js";
+import { publishLiveEvent } from "../live-events.js";
+import { finishedIdleRun, finishedIdleWake, finishedFailedIdleLease } from "../idle-work-proof.js";
+
+type Outcome = "succeeded" | "interrupted" | "failed" | "cancelled" | "timed_out";
+
+const RECONCILIATION_GRACE_MS = 5 * 60_000;
+const RECONCILIATION_BATCH_SIZE = 25;
+
+function errorReason(reason: string | null | undefined) {
+ const trimmed = reason?.trim();
+ if (!trimmed) return null;
+ return trimmed.length > 500 ? `${trimmed.slice(0, 499)}…` : trimmed;
+}
+
+function settledStatus(outcome: string | undefined, keepIdleOnFailure = false) {
+ return outcome === "failed" || outcome === "timed_out"
+ ? keepIdleOnFailure && outcome === "failed" ? "idle" : "error"
+ : "idle";
+}
+
+function publishStatus(agent: typeof agents.$inferSelect, outcome: string) {
+ publishLiveEvent({
+ companyId: agent.companyId,
+ type: "agent.status",
+ payload: {
+ agentId: agent.id,
+ status: agent.status,
+ lastHeartbeatAt: agent.lastHeartbeatAt?.toISOString() ?? null,
+ outcome,
+ },
+ });
+}
+
+export function settledAgentWorkCondition(liveRunIds: ReadonlySet<string>, now: Date) {
+ const localRuns = liveRunIds.size > 0
+ ? sql`AND NOT EXISTS (SELECT 1 FROM heartbeat_runs r
+ WHERE r.id IN (${sql.join([...liveRunIds].map(id => sql`${id}::uuid`), sql`, `)})
+ AND r.company_id = ${agents.companyId} AND r.agent_id = ${agents.id})`
+ : sql``;
+ return sql`NOT EXISTS (SELECT 1 FROM heartbeat_runs r
+ WHERE r.company_id = ${agents.companyId} AND r.agent_id = ${agents.id}
+ AND r.status IN ('running', 'queued'))
+ AND NOT EXISTS (SELECT 1 FROM heartbeat_runs r
+ WHERE r.company_id = ${agents.companyId} AND r.agent_id = ${agents.id}
+ AND ((${sql.raw(finishedIdleRun("r"))}) IS NOT TRUE
+ OR r.controller_lease_expires_at > ${now.toISOString()}::timestamptz))
+ ${localRuns}
+ AND NOT EXISTS (SELECT 1 FROM native_run_finalizations f
+ JOIN heartbeat_runs r ON r.id = f.run_id AND r.company_id = f.company_id
+ WHERE f.company_id = ${agents.companyId} AND r.agent_id = ${agents.id}
+ AND (f.phase NOT IN ('committed', 'terminal_failure')
+ OR f.lease_expires_at > ${now.toISOString()}::timestamptz OR f.next_attempt_at IS NOT NULL))
+ AND NOT EXISTS (SELECT 1 FROM environment_leases l
+ JOIN heartbeat_runs r ON r.id = l.heartbeat_run_id AND r.company_id = l.company_id
+ WHERE l.company_id = ${agents.companyId} AND r.agent_id = ${agents.id}
+ AND ((l.status NOT IN ('released', 'expired')
+ AND (${sql.raw(finishedFailedIdleLease("l"))}) IS NOT TRUE)
+ OR COALESCE(l.metadata->>'pendingCleanupInFlight', 'false') <> 'false'
+ OR COALESCE(l.metadata, '{}'::jsonb) ?| ARRAY['nativeWorkspaceExportResume', 'sandboxStopAndRetain']))
+ AND NOT EXISTS (SELECT 1 FROM agent_wakeup_requests w
+ WHERE w.company_id = ${agents.companyId} AND w.agent_id = ${agents.id}
+ AND (${sql.raw(finishedIdleWake("w"))}) IS NOT TRUE)
+ AND NOT EXISTS (SELECT 1 FROM agent_instruction_working_copies c
+ WHERE c.company_id = ${agents.companyId} AND c.agent_id = ${agents.id}
+ AND (c.state NOT IN ('saved', 'unchanged', 'resolved', 'unavailable', 'conflict')
+ OR c.process_stopped_at IS NULL OR c.next_attempt_at IS NOT NULL
+ OR c.receipt ? 'baseline' OR c.receipt->>'cleanupPending' = 'true'))`;
+}
+
+export function createHeartbeatAgentStatus(db: Db) {
+ async function finalizeAgentStatus(
+ agentId: string,
+ outcome: Outcome,
+ failureReason?: string | null,
+ options?: { keepIdleOnFailure?: boolean; wasFirstHeartbeat?: boolean },
+ ) {
+ const result = await db.transaction(async (tx) => {
+ const [existing] = await tx.select().from(agents)
+ .where(eq(agents.id, agentId)).for("no key update");
+ if (!existing || existing.lifecycleState !== "ready" ||
+ existing.status === "paused" || existing.status === "terminated") return null;
+ const [running] = await tx.select({ id: heartbeatRuns.id }).from(heartbeatRuns).where(and(
+ eq(heartbeatRuns.companyId, existing.companyId),
+ eq(heartbeatRuns.agentId, agentId), eq(heartbeatRuns.status, "running"),
+ )).limit(1);
+ const nextStatus = running ? "running" : settledStatus(outcome, options?.keepIdleOnFailure);
+ const now = new Date();
+ const [updated] = await tx.update(agents).set({
+ status: nextStatus,
+ errorReason: nextStatus === "error" ? errorReason(failureReason) : null,
+ lastHeartbeatAt: now,
+ updatedAt: now,
+ }).where(and(eq(agents.id, agentId), eq(agents.companyId, existing.companyId),
+ eq(agents.lifecycleState, "ready"))).returning();
+ return { updated, isFirstHeartbeat: options?.wasFirstHeartbeat ?? !existing.lastHeartbeatAt };
+ });
+ if (!result?.updated) return;
+ if (result.isFirstHeartbeat) {
+ const client = getTelemetryClient();
+ if (client) trackAgentFirstHeartbeat(client, { agentRole: result.updated.role, agentId: result.updated.id });
+ }
+ publishStatus(result.updated, outcome);
+ }
+
+ async function reconcileStrandedAgentStatuses(liveRunIds: () => ReadonlySet<string>) {
+ const now = new Date();
+ const cutoff = new Date(now.getTime() - RECONCILIATION_GRACE_MS);
+ const candidates = await db.transaction(async tx => {
+ await tx.execute(sql`SET LOCAL statement_timeout = '2s'`);
+ return tx.select({ id: agents.id, companyId: agents.companyId }).from(agents)
+ .where(and(eq(agents.status, "running"), eq(agents.lifecycleState, "ready"),
+ lte(agents.updatedAt, cutoff), settledAgentWorkCondition(liveRunIds(), now)))
+ .orderBy(asc(agents.updatedAt), asc(agents.id)).limit(RECONCILIATION_BATCH_SIZE);
+ });
+ const reconciled: string[] = [];
+ for (const candidate of candidates) {
+ if (Date.now() - now.getTime() > 5_000) break;
+ const publications: ActivityPublication[] = [];
+ const updated = await db.transaction(async (tx) => {
+ await tx.execute(sql`SET LOCAL statement_timeout = '2s'`);
+ const [locked] = await tx.select({ id: agents.id }).from(agents).where(and(
+ eq(agents.id, candidate.id), eq(agents.companyId, candidate.companyId),
+ )).for("update", { skipLocked: true });
+ if (!locked) return null;
+ const [current] = await tx.select().from(agents).where(and(
+ eq(agents.id, candidate.id), eq(agents.companyId, candidate.companyId),
+ eq(agents.status, "running"), eq(agents.lifecycleState, "ready"),
+ lte(agents.updatedAt, cutoff), settledAgentWorkCondition(liveRunIds(), now),
+ ));
+ if (!current) return null;
+ const [lastRun] = await tx.select({ status: heartbeatRuns.status, error: heartbeatRuns.error })
+ .from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, candidate.companyId),
+ eq(heartbeatRuns.agentId, candidate.id)))
+ .orderBy(desc(heartbeatRuns.finishedAt), desc(heartbeatRuns.createdAt), desc(heartbeatRuns.id)).limit(1);
+ const nextStatus = settledStatus(lastRun?.status);
+ const [agent] = await tx.update(agents).set({ status: nextStatus,
+ errorReason: nextStatus === "error" ? errorReason(lastRun?.error) : null, updatedAt: now,
+ }).where(and(eq(agents.id, candidate.id), eq(agents.companyId, candidate.companyId),
+ eq(agents.status, "running"), eq(agents.lifecycleState, "ready"))).returning();
+ await logActivity(tx as unknown as Db, {
+ companyId: candidate.companyId, actorType: "system", actorId: "system",
+ action: "agent.status_reconciled", entityType: "agent", entityId: candidate.id,
+ details: { previousStatus: "running", nextStatus, reason: "no_unsettled_execution" },
+ }, publications);
+ return agent;
+ });
+ if (!updated) continue;
+ reconciled.push(updated.id);
+ for (const publication of publications) publishActivity(publication);
+ publishStatus(updated, "reconciled");
+ }
+ return reconciled;
+ }
+
+ return { finalizeAgentStatus, reconcileStrandedAgentStatuses };
+}
diff --git a/server/src/services/heartbeat/recovery.ts b/server/src/services/heartbeat/recovery.ts
index 1b79b61b0d..4623b7bae3 100644
--- a/server/src/services/heartbeat/recovery.ts
+++ b/server/src/services/heartbeat/recovery.ts
@@ -1,3 +1,4 @@
+import { createHeartbeatAgentStatus } from "./agent-status.js";
import { preserveWorkspaceRestoreRecoveryMetadataSql } from "../legacy-workspace-restore-recovery.js";
import { preserveCancelledNativeWorkspaces } from "../native-runtime/native-failed-workspace-recovery.js";
import { nativeWorkspaceExportPendingForLease, pendingNativeWorkspaceFinalizationCondition } from "../native-runtime/native-workspace-finalization-state.js";
@@ -2510,6 +2511,12 @@ export function createHeartbeatRecovery(db: Db, dependencies: HeartbeatRecoveryD
);
}
+ await createHeartbeatAgentStatus(db).reconcileStrandedAgentStatuses(() => new Set([
+ ...activeRunExecutions, ...runningProcesses.keys(), ...adapterExecutionControls.keys(),
+ ])).catch(() => {
+ logger.error({ errorKind: "agent_status_reconciliation_failed" }, "stranded agent status repair failed");
+ });
+
return { reaped: reaped.length, runIds: reaped };
}
diff --git a/server/src/services/idle-sleep-safety.ts b/server/src/services/idle-sleep-safety.ts
index 11c228f1ef..bd7900b360 100644
--- a/server/src/services/idle-sleep-safety.ts
+++ b/server/src/services/idle-sleep-safety.ts
@@ -2,7 +2,7 @@ import { idleWorkSnapshot } from "./task-admission.js";
import { readIdleLocalWork, type IdleLocalWork } from "./idle-local-work.js";
import { readIdleRoutineSchedule, type ScheduledWake } from "./idle-scheduled-work.js";
import { combineIdleSchedules, readIdleIssueSchedule } from "./idle-issue-schedule.js";
-import { connectionDeliveryWaitingForResponse, finishedIdleRun as finishedRun, finishedIdleWake, passiveBoardRecovery } from "./idle-work-proof.js";
+import { connectionDeliveryWaitingForResponse, finishedIdleRun as finishedRun, finishedIdleWake, finishedFailedIdleLease as finishedFailedLease, passiveBoardRecovery } from "./idle-work-proof.js";
import type { Db } from "@paperclipai/db";
import { sql } from "drizzle-orm";
import { verifiedResourceCleanup } from "./cleanup-verification-proof.js";
@@ -31,32 +31,6 @@ export type InspectIdlePlugins = (hold: { ownerId: string; expiresAt: number })
// cleanup label alone is not provider termination proof. Require the exact
// host-owned receipt and finished run, and retain all cleanup/export intents.
// Aliases are fixed at the call sites, never supplied by a client.
-function finishedFailedLease(alias: string): string {
- const receipt = `${alias}.metadata->'remoteExecutionTermination'`;
- return `${alias}.status = 'failed' AND ${alias}.lease_policy = 'ephemeral'
- AND ${alias}.released_at IS NOT NULL
- AND COALESCE(${alias}.metadata->>'pendingCleanupInFlight', 'false') = 'false'
- AND NOT (COALESCE(${alias}.metadata, '{}'::jsonb) ?| ARRAY['nativeWorkspaceExportResume', 'sandboxStopAndRetain'])
- AND (( ${alias}.provider = 'local' AND ${alias}.provider_lease_id IS NULL
- AND ${alias}.metadata->>'driver' = 'local'
- AND ${receipt} IS NULL
- AND EXISTS (SELECT 1 FROM environments local_environment
- WHERE local_environment.id = ${alias}.environment_id AND local_environment.driver = 'local'))
- OR (${alias}.cleanup_status = 'success' AND ${alias}.provider IS NOT NULL AND ${alias}.provider <> 'local'
- AND ${alias}.provider_lease_id IS NOT NULL AND ${alias}.provider_lease_id <> ''
- AND ((${receipt}->>'schema' = 'paperclip.remote-termination.v1'
- AND ${receipt}->>'companyId' = ${alias}.company_id::text
- AND ${receipt}->>'runId' = ${alias}.heartbeat_run_id::text
- AND ${receipt}->>'leaseId' = ${alias}.id::text
- AND ${receipt}->>'provider' = ${alias}.provider
- AND ${receipt}->>'providerLeaseId' = ${alias}.provider_lease_id
- AND ${receipt}->>'state' IN ('stopped', 'destroyed'))
- OR (${verifiedResourceCleanup(alias, 'lease')}))))
- AND ((${alias}.heartbeat_run_id IS NULL AND ${alias}.provider <> 'local'
- AND (${verifiedResourceCleanup(alias, 'lease')})) OR EXISTS (SELECT 1 FROM heartbeat_runs r WHERE r.id = ${alias}.heartbeat_run_id
- AND r.company_id = ${alias}.company_id
- AND ${finishedRun("r")}))`;
-}
// These are deliberately conservative. Completed agent runs and workspace
// operations are history, not reasons to keep an otherwise idle instance up.
diff --git a/server/src/services/idle-work-proof.ts b/server/src/services/idle-work-proof.ts
index cff70af709..cd6442a581 100644
--- a/server/src/services/idle-work-proof.ts
+++ b/server/src/services/idle-work-proof.ts
@@ -1,3 +1,5 @@
+import { verifiedResourceCleanup } from "./cleanup-verification-proof.js";
+
/** Fixed SQL aliases only. These predicates do not accept request input. */
export function finishedIdleRun(alias: string): string {
return `${alias}.status IN ('succeeded', 'failed', 'cancelled', 'timed_out', 'interrupted')
@@ -125,3 +127,30 @@ export function passiveBoardRecovery(alias: string): string {
AND (recovery_source.execution_state IS NULL OR recovery_source.execution_state->>'status' = 'idle')
AND COALESCE(recovery_source.execution_policy->'monitor', 'null'::jsonb) = 'null'::jsonb)`;
}
+
+export function finishedFailedIdleLease(alias: string): string {
+ const receipt = `${alias}.metadata->'remoteExecutionTermination'`;
+ return `${alias}.status = 'failed' AND ${alias}.lease_policy = 'ephemeral'
+ AND ${alias}.released_at IS NOT NULL
+ AND COALESCE(${alias}.metadata->>'pendingCleanupInFlight', 'false') = 'false'
+ AND NOT (COALESCE(${alias}.metadata, '{}'::jsonb) ?| ARRAY['nativeWorkspaceExportResume', 'sandboxStopAndRetain'])
+ AND (( ${alias}.provider = 'local' AND ${alias}.provider_lease_id IS NULL
+ AND ${alias}.metadata->>'driver' = 'local'
+ AND ${receipt} IS NULL
+ AND EXISTS (SELECT 1 FROM environments local_environment
+ WHERE local_environment.id = ${alias}.environment_id AND local_environment.driver = 'local'))
+ OR (${alias}.cleanup_status = 'success' AND ${alias}.provider IS NOT NULL AND ${alias}.provider <> 'local'
+ AND ${alias}.provider_lease_id IS NOT NULL AND ${alias}.provider_lease_id <> ''
+ AND ((${receipt}->>'schema' = 'paperclip.remote-termination.v1'
+ AND ${receipt}->>'companyId' = ${alias}.company_id::text
+ AND ${receipt}->>'runId' = ${alias}.heartbeat_run_id::text
+ AND ${receipt}->>'leaseId' = ${alias}.id::text
+ AND ${receipt}->>'provider' = ${alias}.provider
+ AND ${receipt}->>'providerLeaseId' = ${alias}.provider_lease_id
+ AND ${receipt}->>'state' IN ('stopped', 'destroyed'))
+ OR (${verifiedResourceCleanup(alias, 'lease')}))))
+ AND ((${alias}.heartbeat_run_id IS NULL AND ${alias}.provider <> 'local'
+ AND (${verifiedResourceCleanup(alias, 'lease')})) OR EXISTS (SELECT 1 FROM heartbeat_runs r WHERE r.id = ${alias}.heartbeat_run_id
+ AND r.company_id = ${alias}.company_id
+ AND ${finishedIdleRun("r")}))`;
+}