The open-source app everyone uses to manage agents at work
TypeScript acpxagent-orchestrationagent-skillsagentic-aiai-agentsai-engineeringai-governanceai-toolsautonomous-agentsclaudeclaude-codeclaude-skillscodexhermesllmmcpmulti-agentopenclawproject-managementworkflow-automation
refactor(server): move scheduled-retry and queued-run dispatch into a run-dispatch module (#12920)
Nicky Leachf65991a5f114
diff --git a/scripts/check-module-boundaries.mjs b/scripts/check-module-boundaries.mjsindex 4be852f8c1..483a7086f0 100644--- a/scripts/check-module-boundaries.mjs+++ b/scripts/check-module-boundaries.mjs@@ -104,8 +104,18 @@ export function scanModuleBoundaries({addViolation(violations, sourceLabel, "domain", specifier, "domain cannot import database packages");} else if (specifier.startsWith("node:")) {addViolation(violations, sourceLabel, "domain", specifier, "domain cannot import Node.js runtime modules");- } else if (targetSegments.includes("services") || targetSegments.includes("routes")) {- addViolation(violations, sourceLabel, "domain", specifier, "domain cannot import server services or routes");+ } else if (+ targetSegments.includes("services") ||+ targetSegments.includes("routes") ||+ targetSegments.includes("adapters")+ ) {+ addViolation(+ violations,+ sourceLabel,+ "domain",+ specifier,+ "domain cannot import server services, routes, or adapters",+ );} else if (targetLocation?.layer === "application" || targetLocation?.layer === "adapters") {addViolation(violations, sourceLabel, "domain", specifier, "domain cannot depend on outer module layers");}@@ -114,7 +124,7 @@ export function scanModuleBoundaries({if (sourceLocation?.layer === "application") {if (isDatabasePackage(specifier)) {addViolation(violations, sourceLabel, "application", specifier, "application cannot import database packages");- } else if (targetLocation?.layer === "adapters") {+ } else if (targetLocation?.layer === "adapters" || targetSegments.includes("adapters")) {addViolation(violations, sourceLabel, "application", specifier, "application cannot import concrete adapters");} else if (targetSegments.join("/") === "errors.js" || targetSegments.join("/") === "errors.ts") {addViolation(violations, sourceLabel, "application", specifier, "application cannot import HTTP error helpers");diff --git a/scripts/check-module-boundaries.test.mjs b/scripts/check-module-boundaries.test.mjsindex 9d270df848..a73f87e855 100644--- a/scripts/check-module-boundaries.test.mjs+++ b/scripts/check-module-boundaries.test.mjs@@ -32,12 +32,14 @@ test("scanModuleBoundaries rejects outward dependencies and module-internal impowrite("modules/watchdog/domain/policy.ts", ['import { eq } from "drizzle-orm";','import { service } from "../../../services/example.js";',+ 'import { parse } from "../../../adapters/utils.js";','import { run } from "../application/run.js";',].join("\n"));write("modules/watchdog/application/run.ts",['import { adapter } from "../adapters/postgres.js";',+ 'import { parse } from "../../../adapters/application-utils.js";','import { forbidden } from "../../../errors.js";','import db = require("@paperclipai/db");',].join("\n"),@@ -51,10 +53,21 @@ test("scanModuleBoundaries rejects outward dependencies and module-internal impoviolations.map(({ specifier, reason }) => ({ specifier, reason })),[{ specifier: "../adapters/postgres.js", reason: "application cannot import concrete adapters" },+ {+ specifier: "../../../adapters/application-utils.js",+ reason: "application cannot import concrete adapters",+ },{ specifier: "../../../errors.js", reason: "application cannot import HTTP error helpers" },{ specifier: "@paperclipai/db", reason: "application cannot import database packages" },{ specifier: "drizzle-orm", reason: "domain cannot import database packages" },- { specifier: "../../../services/example.js", reason: "domain cannot import server services or routes" },+ {+ specifier: "../../../services/example.js",+ reason: "domain cannot import server services, routes, or adapters",+ },+ {+ specifier: "../../../adapters/utils.js",+ reason: "domain cannot import server services, routes, or adapters",+ },{ specifier: "../application/run.js", reason: "domain cannot depend on outer module layers" },{specifier: "../modules/watchdog/application/run.js",diff --git a/server/src/__tests__/heartbeat-retry-scheduling.test.ts b/server/src/__tests__/heartbeat-retry-scheduling.test.tsindex 28683fa801..7ee3e6168c 100644--- a/server/src/__tests__/heartbeat-retry-scheduling.test.ts+++ b/server/src/__tests__/heartbeat-retry-scheduling.test.ts@@ -24,6 +24,7 @@ import {} from "./helpers/embedded-postgres.js";import { drainHeartbeatRunsToQuiescence } from "./helpers/drain-heartbeat-runs.js";import { registerServerAdapter, unregisterServerAdapter } from "../adapters/index.ts";+import { createPostgresRunDispatchAdapter } from "../modules/run-dispatch/adapters/postgres.js";const mockTelemetryClient = vi.hoisted(() => ({ track: vi.fn() }));const mockTrackAgentTaskRun = vi.hoisted(() => vi.fn());@@ -42,6 +43,15 @@ vi.mock("@paperclipai/shared/telemetry", async () => {};});+// Wraps the real implementation so most tests exercise genuine transactional+// writes; a test that needs to prove a rollback overrides one call with+// `mockRejectedValueOnce` and lets every other call fall through untouched.+vi.mock("../services/heartbeat-run-events.js", async (importOriginal) => {+ const actual = await importOriginal<typeof import("../services/heartbeat-run-events.js")>();+ return { ...actual, appendHeartbeatRunEvent: vi.fn(actual.appendHeartbeatRunEvent) };+});++import { appendHeartbeatRunEvent } from "../services/heartbeat-run-events.js";import {BOUNDED_TRANSIENT_HEARTBEAT_RETRY_DELAYS_MS,INTERACTION_CONTINUATION_INFRA_RETRY_REASON,@@ -51,6 +61,8 @@ import {heartbeatService,} from "../services/heartbeat.ts";+const mockedAppendHeartbeatRunEvent = vi.mocked(appendHeartbeatRunEvent);+const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport();const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip;const PROVIDER_QUOTA_TEST_ADAPTER = "provider_quota_test";@@ -1323,34 +1335,6 @@ describeEmbeddedPostgres("heartbeat bounded retry scheduling", () => {expect(duplicateWakeup?.status).toBe("cancelled");});- it.each(["blocked", "todo", "backlog"] as const)(- "does not schedule a max-turn continuation when the issue is already %s",- async (issueStatus) => {- const { issueId, runId, now } = await seedMaxTurnFixture({ issueStatus });-- const scheduled = await heartbeat.scheduleBoundedRetry(runId, {- now,- retryReason: MAX_TURN_CONTINUATION_RETRY_REASON,- wakeReason: MAX_TURN_CONTINUATION_WAKE_REASON,- maxAttempts: 2,- delayMs: 1_000,- });-- expect(scheduled).toMatchObject({- outcome: "not_scheduled",- errorCode: "issue_not_in_progress",- issueId,- });-- const retryRuns = await db- .select({ count: sql<number>`count(*)::int` })- .from(heartbeatRuns)- .where(eq(heartbeatRuns.retryOfRunId, runId))- .then((rows) => rows[0]?.count ?? 0);- expect(retryRuns).toBe(0);- },- );-it.each(["blocked", "todo", "backlog"] as const)("cancels a due max-turn continuation when the issue moves to %s before retry promotion",async (issueStatus) => {@@ -1428,114 +1412,6 @@ describeEmbeddedPostgres("heartbeat bounded retry scheduling", () => {},);- it("does not queue max-turn continuations after the configured cap", async () => {- const { runId, now } = await seedMaxTurnFixture({ scheduledRetryAttempt: 2 });-- const exhausted = await heartbeat.scheduleBoundedRetry(runId, {- now,- retryReason: MAX_TURN_CONTINUATION_RETRY_REASON,- wakeReason: MAX_TURN_CONTINUATION_WAKE_REASON,- maxAttempts: 2,- delayMs: 1_000,- });-- expect(exhausted).toEqual({- outcome: "retry_exhausted",- attempt: 3,- maxAttempts: 2,- });-- const runCount = await db- .select({ count: sql<number>`count(*)::int` })- .from(heartbeatRuns)- .then((rows) => rows[0]?.count ?? 0);- expect(runCount).toBe(1);-- const exhaustionEvent = await db- .select({ message: heartbeatRunEvents.message, payload: heartbeatRunEvents.payload })- .from(heartbeatRunEvents)- .where(eq(heartbeatRunEvents.runId, runId))- .orderBy(sql`${heartbeatRunEvents.id} desc`)- .then((rows) => rows[0] ?? null);- expect(exhaustionEvent?.message).toContain("Bounded retry exhausted");- expect(exhaustionEvent?.payload).toMatchObject({- retryReason: MAX_TURN_CONTINUATION_RETRY_REASON,- maxAttempts: 2,- });- });-- it("suppresses max-turn continuation scheduling when budget or dependencies block the issue", async () => {- const budgetBlocked = await seedMaxTurnFixture({ now: new Date("2026-04-20T16:00:00.000Z") });- await db.insert(budgetPolicies).values({- companyId: budgetBlocked.companyId,- scopeType: "agent",- scopeId: budgetBlocked.agentId,- windowKind: "monthly",- metric: "billed_cents",- amount: 0,- hardStopEnabled: true,- isActive: true,- });- await db- .update(agents)- .set({ status: "paused", pauseReason: "budget" })- .where(eq(agents.id, budgetBlocked.agentId));-- const budgetResult = await heartbeat.scheduleBoundedRetry(budgetBlocked.runId, {- now: budgetBlocked.now,- retryReason: MAX_TURN_CONTINUATION_RETRY_REASON,- wakeReason: MAX_TURN_CONTINUATION_WAKE_REASON,- maxAttempts: 2,- delayMs: 1_000,- });- expect(budgetResult).toMatchObject({- outcome: "not_scheduled",- errorCode: "budget_blocked",- issueId: budgetBlocked.issueId,- });-- await cleanupRetryFixture();-- const dependencyBlocked = await seedMaxTurnFixture({ now: new Date("2026-04-20T17:00:00.000Z") });- const blockerId = randomUUID();- await db.insert(issues).values({- id: blockerId,- companyId: dependencyBlocked.companyId,- title: "Blocker",- status: "todo",- priority: "medium",- responsibleUserId: "responsible-user",- issueNumber: 2,- identifier: `T${dependencyBlocked.companyId.replace(/-/g, "").slice(0, 6).toUpperCase()}-2`,- });- await db.insert(issueRelations).values({- companyId: dependencyBlocked.companyId,- issueId: blockerId,- relatedIssueId: dependencyBlocked.issueId,- type: "blocks",- });-- const dependencyResult = await heartbeat.scheduleBoundedRetry(dependencyBlocked.runId, {- now: dependencyBlocked.now,- retryReason: MAX_TURN_CONTINUATION_RETRY_REASON,- wakeReason: MAX_TURN_CONTINUATION_WAKE_REASON,- maxAttempts: 2,- delayMs: 1_000,- });- expect(dependencyResult).toMatchObject({- outcome: "not_scheduled",- errorCode: "issue_dependencies_blocked",- issueId: dependencyBlocked.issueId,- });-- const retryRuns = await db- .select({ count: sql<number>`count(*)::int` })- .from(heartbeatRuns)- .where(eq(heartbeatRuns.retryOfRunId, dependencyBlocked.runId))- .then((rows) => rows[0]?.count ?? 0);- expect(retryRuns).toBe(0);- });-it("does not defer a new assignee behind the previous assignee's scheduled retry", async () => {const companyId = randomUUID();const oldAgentId = randomUUID();@@ -1705,132 +1581,11 @@ describeEmbeddedPostgres("heartbeat bounded retry scheduling", () => {});});- it("does not promote a scheduled retry after issue ownership changes", async () => {- const companyId = randomUUID();- const oldAgentId = randomUUID();- const newAgentId = randomUUID();- const issueId = randomUUID();- const sourceRunId = randomUUID();- const now = new Date("2026-04-20T14:00:00.000Z");-- await db.insert(companies).values({- id: companyId,- name: "Paperclip",- issuePrefix: `T${companyId.replace(/-/g, "").slice(0, 6).toUpperCase()}`,- requireBoardApprovalForNewAgents: false,- defaultResponsibleUserId: "responsible-user",- });-- await db.insert(agents).values([- {- id: oldAgentId,- companyId,- name: "ClaudeCoder",- role: "engineer",- status: "active",- adapterType: "claude_local",- adapterConfig: {},- runtimeConfig: {- heartbeat: {- wakeOnDemand: true,- maxConcurrentRuns: 1,- },- },- permissions: {},- },- {- id: newAgentId,- companyId,- name: "CodexCoder",- role: "engineer",- status: "active",- adapterType: "codex_local",- adapterConfig: {},- runtimeConfig: {- heartbeat: {- wakeOnDemand: true,- maxConcurrentRuns: 1,- },- },- permissions: {},- },- ]);-- await db.insert(heartbeatRuns).values({- id: sourceRunId,- companyId,- agentId: oldAgentId,- invocationSource: "assignment",- triggerDetail: "system",- status: "failed",- error: "upstream overload",- errorCode: "adapter_failed",- finishedAt: now,- contextSnapshot: {- issueId,- wakeReason: "issue_assigned",- },- updatedAt: now,- createdAt: now,- });-- await db.insert(issues).values({- id: issueId,- companyId,- title: "Retry promotion reassignment",- status: "todo",- priority: "medium",- responsibleUserId: "responsible-user",- assigneeAgentId: oldAgentId,- executionRunId: sourceRunId,- executionAgentNameKey: "claudecoder",- executionLockedAt: now,- issueNumber: 1,- identifier: `T${companyId.replace(/-/g, "").slice(0, 6).toUpperCase()}-2`,- });-- const scheduled = await heartbeat.scheduleBoundedRetry(sourceRunId, {- now,- random: () => 0.5,- });- expect(scheduled.outcome).toBe("scheduled");- if (scheduled.outcome !== "scheduled") return;-- await db.update(issues).set({- assigneeAgentId: newAgentId,- updatedAt: now,- }).where(eq(issues.id, issueId));-- const promotion = await heartbeat.promoteDueScheduledRetries(scheduled.dueAt);- expect(promotion).toEqual({ promoted: 0, runIds: [] });-- const oldRetry = await db- .select({- status: heartbeatRuns.status,- errorCode: heartbeatRuns.errorCode,- })- .from(heartbeatRuns)- .where(eq(heartbeatRuns.id, scheduled.run.id))- .then((rows) => rows[0] ?? null);- expect(oldRetry).toEqual({- status: "cancelled",- errorCode: "issue_reassigned",- });-- const issue = await db- .select({ executionRunId: issues.executionRunId })- .from(issues)- .where(eq(issues.id, issueId))- .then((rows) => rows[0] ?? null);- expect(issue?.executionRunId).toBeNull();- });-- it("does not promote a scheduled retry after the issue is handed to a human owner", async () => {+ it("exhausts bounded retries after the hard cap", async () => {const companyId = randomUUID();- const oldAgentId = randomUUID();- const issueId = randomUUID();- const sourceRunId = randomUUID();- const now = new Date("2026-04-20T14:30:00.000Z");+ const agentId = randomUUID();+ const cappedRunId = randomUUID();+ const now = new Date("2026-04-20T18:00:00.000Z");await db.insert(companies).values({id: companyId,@@ -1841,12 +1596,12 @@ describeEmbeddedPostgres("heartbeat bounded retry scheduling", () => {});await db.insert(agents).values({- id: oldAgentId,+ id: agentId,companyId,- name: "ClaudeCoder",+ name: "CodexCoder",role: "engineer",status: "active",- adapterType: "claude_local",+ adapterType: "codex_local",adapterConfig: {},runtimeConfig: {heartbeat: {@@ -1858,243 +1613,33 @@ describeEmbeddedPostgres("heartbeat bounded retry scheduling", () => {});await db.insert(heartbeatRuns).values({- id: sourceRunId,+ id: cappedRunId,companyId,- agentId: oldAgentId,- invocationSource: "assignment",- triggerDetail: "system",+ agentId,+ invocationSource: "automation",status: "failed",- error: "upstream overload",+ error: "still transient",errorCode: "adapter_failed",finishedAt: now,+ scheduledRetryAttempt: BOUNDED_TRANSIENT_HEARTBEAT_RETRY_DELAYS_MS.length,+ scheduledRetryReason: "transient_failure",contextSnapshot: {- issueId,- wakeReason: "issue_assigned",+ wakeReason: "transient_failure_retry",},updatedAt: now,createdAt: now,});- await db.insert(issues).values({- id: issueId,- companyId,- title: "Retry human handoff",- status: "in_progress",- priority: "medium",- responsibleUserId: "responsible-user",- assigneeAgentId: oldAgentId,- executionRunId: sourceRunId,- executionAgentNameKey: "claudecoder",- executionLockedAt: now,- issueNumber: 1,- identifier: `T${companyId.replace(/-/g, "").slice(0, 6).toUpperCase()}-3`,- });-- const scheduled = await heartbeat.scheduleBoundedRetry(sourceRunId, {+ const exhausted = await heartbeat.scheduleBoundedRetry(cappedRunId, {now,random: () => 0.5,});- expect(scheduled.outcome).toBe("scheduled");- if (scheduled.outcome !== "scheduled") return;-- await db.update(issues).set({- assigneeAgentId: null,- assigneeUserId: "local-board",- updatedAt: now,- }).where(eq(issues.id, issueId));- const promotion = await heartbeat.promoteDueScheduledRetries(scheduled.dueAt);- expect(promotion).toEqual({ promoted: 0, runIds: [] });-- const oldRetry = await db- .select({- status: heartbeatRuns.status,- errorCode: heartbeatRuns.errorCode,- })- .from(heartbeatRuns)- .where(eq(heartbeatRuns.id, scheduled.run.id))- .then((rows) => rows[0] ?? null);- expect(oldRetry).toEqual({- status: "cancelled",- errorCode: "issue_reassigned",- });-- const issue = await db- .select({- assigneeAgentId: issues.assigneeAgentId,- assigneeUserId: issues.assigneeUserId,- executionRunId: issues.executionRunId,- })- .from(issues)- .where(eq(issues.id, issueId))- .then((rows) => rows[0] ?? null);- expect(issue).toMatchObject({- assigneeAgentId: null,- assigneeUserId: "local-board",- executionRunId: null,- });- });-- it("does not promote a scheduled retry after the issue is cancelled", async () => {- const companyId = randomUUID();- const agentId = randomUUID();- const issueId = randomUUID();- const sourceRunId = randomUUID();- const now = new Date("2026-04-20T15:00:00.000Z");-- await db.insert(companies).values({- id: companyId,- name: "Paperclip",- issuePrefix: `T${companyId.replace(/-/g, "").slice(0, 6).toUpperCase()}`,- requireBoardApprovalForNewAgents: false,- defaultResponsibleUserId: "responsible-user",- });-- await db.insert(agents).values({- id: agentId,- companyId,- name: "CodexCoder",- role: "engineer",- status: "active",- adapterType: "codex_local",- adapterConfig: {},- runtimeConfig: {- heartbeat: {- wakeOnDemand: true,- maxConcurrentRuns: 1,- },- },- permissions: {},- });-- await db.insert(heartbeatRuns).values({- id: sourceRunId,- companyId,- agentId,- invocationSource: "assignment",- triggerDetail: "system",- status: "failed",- error: "upstream overload",- errorCode: "adapter_failed",- finishedAt: now,- contextSnapshot: {- issueId,- wakeReason: "issue_assigned",- },- updatedAt: now,- createdAt: now,- });-- await db.insert(issues).values({- id: issueId,- companyId,- title: "Retry promotion cancellation",- status: "todo",- priority: "medium",- responsibleUserId: "responsible-user",- assigneeAgentId: agentId,- executionRunId: sourceRunId,- executionAgentNameKey: "codexcoder",- executionLockedAt: now,- issueNumber: 1,- identifier: `T${companyId.replace(/-/g, "").slice(0, 6).toUpperCase()}-3`,- });-- const scheduled = await heartbeat.scheduleBoundedRetry(sourceRunId, {- now,- random: () => 0.5,- });- expect(scheduled.outcome).toBe("scheduled");- if (scheduled.outcome !== "scheduled") return;-- await db.update(issues).set({- status: "cancelled",- updatedAt: now,- }).where(eq(issues.id, issueId));-- const promotion = await heartbeat.promoteDueScheduledRetries(scheduled.dueAt);- expect(promotion).toEqual({ promoted: 0, runIds: [] });-- const oldRetry = await db- .select({- status: heartbeatRuns.status,- errorCode: heartbeatRuns.errorCode,- })- .from(heartbeatRuns)- .where(eq(heartbeatRuns.id, scheduled.run.id))- .then((rows) => rows[0] ?? null);- expect(oldRetry).toEqual({- status: "cancelled",- errorCode: "issue_cancelled",- });-- const issue = await db- .select({ executionRunId: issues.executionRunId })- .from(issues)- .where(eq(issues.id, issueId))- .then((rows) => rows[0] ?? null);- expect(issue?.executionRunId).toBeNull();- });-- it("exhausts bounded retries after the hard cap", async () => {- const companyId = randomUUID();- const agentId = randomUUID();- const cappedRunId = randomUUID();- const now = new Date("2026-04-20T18:00:00.000Z");-- await db.insert(companies).values({- id: companyId,- name: "Paperclip",- issuePrefix: `T${companyId.replace(/-/g, "").slice(0, 6).toUpperCase()}`,- requireBoardApprovalForNewAgents: false,- defaultResponsibleUserId: "responsible-user",- });-- await db.insert(agents).values({- id: agentId,- companyId,- name: "CodexCoder",- role: "engineer",- status: "active",- adapterType: "codex_local",- adapterConfig: {},- runtimeConfig: {- heartbeat: {- wakeOnDemand: true,- maxConcurrentRuns: 1,- },- },- permissions: {},- });-- await db.insert(heartbeatRuns).values({- id: cappedRunId,- companyId,- agentId,- invocationSource: "automation",- status: "failed",- error: "still transient",- errorCode: "adapter_failed",- finishedAt: now,- scheduledRetryAttempt: BOUNDED_TRANSIENT_HEARTBEAT_RETRY_DELAYS_MS.length,- scheduledRetryReason: "transient_failure",- contextSnapshot: {- wakeReason: "transient_failure_retry",- },- updatedAt: now,- createdAt: now,- });-- const exhausted = await heartbeat.scheduleBoundedRetry(cappedRunId, {- now,- random: () => 0.5,- });-- expect(exhausted).toEqual({- outcome: "retry_exhausted",- attempt: BOUNDED_TRANSIENT_HEARTBEAT_RETRY_DELAYS_MS.length + 1,- maxAttempts: BOUNDED_TRANSIENT_HEARTBEAT_RETRY_DELAYS_MS.length,- });+ expect(exhausted).toEqual({+ outcome: "retry_exhausted",+ attempt: BOUNDED_TRANSIENT_HEARTBEAT_RETRY_DELAYS_MS.length + 1,+ maxAttempts: BOUNDED_TRANSIENT_HEARTBEAT_RETRY_DELAYS_MS.length,+ });const runCount = await db.select({ count: sql<number>`count(*)::int` })@@ -2339,4 +1884,383 @@ describeEmbeddedPostgres("heartbeat bounded retry scheduling", () => {retryNotBefore.toISOString(),);});++ describe("run-dispatch module transactions", () => {+ it("promotes a due scheduled retry exactly once under concurrent promotion attempts", async () => {+ const companyId = randomUUID();+ const agentId = randomUUID();+ const sourceRunId = randomUUID();+ const now = new Date("2026-05-01T00:00:00.000Z");++ await seedRetryFixture({ runId: sourceRunId, companyId, agentId, now, errorCode: "adapter_failed" });+ const scheduled = await heartbeat.scheduleBoundedRetry(sourceRunId, { now, random: () => 0.5 });+ expect(scheduled.outcome).toBe("scheduled");+ if (scheduled.outcome !== "scheduled") return;++ const [first, second] = await Promise.all([+ heartbeat.promoteDueScheduledRetries(scheduled.dueAt),+ heartbeat.promoteDueScheduledRetries(scheduled.dueAt),+ ]);++ expect(first.promoted + second.promoted).toBe(1);+ const [row] = await db+ .select({ status: heartbeatRuns.status })+ .from(heartbeatRuns)+ .where(eq(heartbeatRuns.id, scheduled.run.id));+ expect(row?.status).toBe("queued");+ });++ it("rolls back the run-status update when the run-event write fails during promotion", async () => {+ const companyId = randomUUID();+ const agentId = randomUUID();+ const sourceRunId = randomUUID();+ const now = new Date("2026-05-02T00:00:00.000Z");++ await seedRetryFixture({ runId: sourceRunId, companyId, agentId, now, errorCode: "adapter_failed" });+ const scheduled = await heartbeat.scheduleBoundedRetry(sourceRunId, { now, random: () => 0.5 });+ expect(scheduled.outcome).toBe("scheduled");+ if (scheduled.outcome !== "scheduled") return;++ mockedAppendHeartbeatRunEvent.mockRejectedValueOnce(new Error("injected promotion event fault"));++ await expect(heartbeat.promoteDueScheduledRetries(scheduled.dueAt)).rejects.toThrow(+ "injected promotion event fault",+ );++ const [row] = await db+ .select({ status: heartbeatRuns.status })+ .from(heartbeatRuns)+ .where(eq(heartbeatRuns.id, scheduled.run.id));+ expect(row?.status).toBe("scheduled_retry");+ });++ it("rolls back the wakeup-request update when the run-event write fails during a gate-suppressed cancellation", async () => {+ const companyId = randomUUID();+ const agentId = randomUUID();+ const sourceRunId = randomUUID();+ const missingIssueId = randomUUID();+ const now = new Date("2026-05-03T00:00:00.000Z");++ await seedRetryFixture({ runId: sourceRunId, companyId, agentId, now, errorCode: "adapter_failed" });++ const wakeupRequestId = randomUUID();+ await db.insert(agentWakeupRequests).values({+ id: wakeupRequestId,+ companyId,+ agentId,+ source: "retry",+ status: "queued",+ });++ // A max-turn continuation whose issue no longer exists trips the gate's+ // "issue_not_found" rejection without the legacy transient-retry+ // exception, so promotion routes it to the cancel-suppressed-retry write.+ const retryRunId = randomUUID();+ await db.insert(heartbeatRuns).values({+ id: retryRunId,+ companyId,+ agentId,+ invocationSource: "retry",+ status: "scheduled_retry",+ scheduledRetryAt: now,+ scheduledRetryAttempt: 1,+ scheduledRetryReason: MAX_TURN_CONTINUATION_RETRY_REASON,+ wakeupRequestId,+ contextSnapshot: { issueId: missingIssueId, wakeReason: "issue_continuation_needed" },+ updatedAt: now,+ createdAt: now,+ });++ mockedAppendHeartbeatRunEvent.mockRejectedValueOnce(new Error("injected cancellation event fault"));++ await expect(heartbeat.promoteDueScheduledRetries(now)).rejects.toThrow(+ "injected cancellation event fault",+ );++ const [run] = await db+ .select({ status: heartbeatRuns.status })+ .from(heartbeatRuns)+ .where(eq(heartbeatRuns.id, retryRunId));+ expect(run?.status).toBe("scheduled_retry");++ const [wake] = await db+ .select({ status: agentWakeupRequests.status })+ .from(agentWakeupRequests)+ .where(eq(agentWakeupRequests.id, wakeupRequestId));+ expect(wake?.status).toBe("queued");+ });++ it("keeps promotion and stale-queued-run cancellation company-scoped", async () => {+ const adapter = createPostgresRunDispatchAdapter(db);+ const companyId = randomUUID();+ const otherCompanyId = randomUUID();+ const agentId = randomUUID();+ const runId = randomUUID();+ const now = new Date("2026-05-04T00:00:00.000Z");++ await seedRetryFixture({ runId, companyId, agentId, now, errorCode: "adapter_failed" });+ await db+ .update(heartbeatRuns)+ .set({ status: "scheduled_retry", scheduledRetryAt: now })+ .where(eq(heartbeatRuns.id, runId));++ const wrongCompanyPromotion = await adapter.promoteOrCancelDueRetry({+ runId,+ companyId: otherCompanyId,+ now,+ });+ expect(wrongCompanyPromotion).toEqual({ outcome: "not_promoted" });+ const [afterWrongCompanyPromotion] = await db+ .select({ status: heartbeatRuns.status })+ .from(heartbeatRuns)+ .where(eq(heartbeatRuns.id, runId));+ expect(afterWrongCompanyPromotion?.status).toBe("scheduled_retry");++ const rightCompanyPromotion = await adapter.promoteOrCancelDueRetry({ runId, companyId, now });+ expect(rightCompanyPromotion.outcome).toBe("promoted");++ const issueId = randomUUID();+ const issuePrefix = `T${companyId.replace(/-/g, "").slice(0, 6).toUpperCase()}`;+ await db.insert(issues).values({+ id: issueId,+ companyId,+ title: "Stale queued run target",+ status: "cancelled",+ priority: "medium",+ responsibleUserId: "responsible-user",+ issueNumber: 2,+ identifier: `${issuePrefix}-2`,+ });+ const queuedRunId = randomUUID();+ await db.insert(heartbeatRuns).values({+ id: queuedRunId,+ companyId,+ agentId,+ invocationSource: "assignment",+ status: "queued",+ contextSnapshot: { issueId },+ updatedAt: now,+ createdAt: now,+ });++ await expect(+ adapter.cancelStaleQueuedRun({+ runId: queuedRunId,+ companyId: otherCompanyId,+ expectedStatus: "queued",+ now,+ }),+ ).rejects.toThrow();+ const [afterWrongCompanyCancel] = await db+ .select({ status: heartbeatRuns.status })+ .from(heartbeatRuns)+ .where(eq(heartbeatRuns.id, queuedRunId));+ expect(afterWrongCompanyCancel?.status).toBe("queued");++ const lostRaceCancel = await adapter.cancelStaleQueuedRun({+ runId: queuedRunId,+ companyId,+ expectedStatus: "running",+ now,+ });+ expect(lostRaceCancel).toEqual({ outcome: "lost_race" });+ const [afterLostRaceCancel] = await db+ .select({ status: heartbeatRuns.status })+ .from(heartbeatRuns)+ .where(eq(heartbeatRuns.id, queuedRunId));+ expect(afterLostRaceCancel?.status).toBe("queued");++ const rightCompanyCancel = await adapter.cancelStaleQueuedRun({+ runId: queuedRunId,+ companyId,+ expectedStatus: "queued",+ now,+ });+ expect(rightCompanyCancel.outcome).toBe("cancelled");+ });++ it("never writes another company's wakeup request during suppressed-retry or stale-queued-run cancellation", async () => {+ const adapter = createPostgresRunDispatchAdapter(db);+ const companyId = randomUUID();+ const otherCompanyId = randomUUID();+ const agentId = randomUUID();+ const otherAgentId = randomUUID();+ const now = new Date("2026-05-05T00:00:00.000Z");++ await seedRetryFixture({ runId: randomUUID(), companyId, agentId, now, errorCode: "adapter_failed" });+ await db.insert(companies).values({+ id: otherCompanyId,+ name: "Other Co",+ issuePrefix: `T${otherCompanyId.replace(/-/g, "").slice(0, 6).toUpperCase()}`,+ requireBoardApprovalForNewAgents: false,+ defaultResponsibleUserId: "responsible-user",+ });+ await db.insert(agents).values({+ id: otherAgentId,+ companyId: otherCompanyId,+ name: "OtherCoder",+ role: "engineer",+ status: "active",+ adapterType: "codex_local",+ adapterConfig: {},+ runtimeConfig: { heartbeat: { wakeOnDemand: true, maxConcurrentRuns: 1 } },+ permissions: {},+ });++ // Each wakeup request belongs to `otherCompanyId`, standing in for a+ // mismatched cross-company reference on the run — the scenario the+ // company predicate on the wakeup write must guard against.+ const suppressedWakeupId = randomUUID();+ await db.insert(agentWakeupRequests).values({+ id: suppressedWakeupId,+ companyId: otherCompanyId,+ agentId: otherAgentId,+ source: "retry",+ status: "queued",+ });+ const suppressedRunId = randomUUID();+ await db.insert(heartbeatRuns).values({+ id: suppressedRunId,+ companyId,+ agentId,+ invocationSource: "retry",+ status: "scheduled_retry",+ scheduledRetryAt: now,+ wakeupRequestId: suppressedWakeupId,+ scheduledRetryReason: MAX_TURN_CONTINUATION_RETRY_REASON,+ contextSnapshot: { issueId: randomUUID() },+ updatedAt: now,+ createdAt: now,+ });++ const suppressedCancel = await adapter.promoteOrCancelDueRetry({+ runId: suppressedRunId,+ companyId,+ now,+ });+ expect(suppressedCancel.outcome).toBe("gate_suppressed");++ const [suppressedWakeup] = await db+ .select({ status: agentWakeupRequests.status })+ .from(agentWakeupRequests)+ .where(eq(agentWakeupRequests.id, suppressedWakeupId));+ expect(suppressedWakeup?.status).toBe("queued");++ const staleWakeupId = randomUUID();+ await db.insert(agentWakeupRequests).values({+ id: staleWakeupId,+ companyId: otherCompanyId,+ agentId: otherAgentId,+ source: "assignment",+ status: "queued",+ });+ const staleIssueId = randomUUID();+ const staleIssuePrefix = `T${companyId.replace(/-/g, "").slice(0, 6).toUpperCase()}`;+ await db.insert(issues).values({+ id: staleIssueId,+ companyId,+ title: "Stale queued run target",+ status: "cancelled",+ priority: "medium",+ responsibleUserId: "responsible-user",+ issueNumber: 3,+ identifier: `${staleIssuePrefix}-3`,+ });+ const staleRunId = randomUUID();+ await db.insert(heartbeatRuns).values({+ id: staleRunId,+ companyId,+ agentId,+ invocationSource: "assignment",+ status: "queued",+ wakeupRequestId: staleWakeupId,+ contextSnapshot: { issueId: staleIssueId },+ updatedAt: now,+ createdAt: now,+ });++ const staleCancel = await adapter.cancelStaleQueuedRun({+ runId: staleRunId,+ companyId,+ expectedStatus: "queued",+ now,+ });+ expect(staleCancel.outcome).toBe("cancelled");++ const [staleWakeup] = await db+ .select({ status: agentWakeupRequests.status })+ .from(agentWakeupRequests)+ .where(eq(agentWakeupRequests.id, staleWakeupId));+ expect(staleWakeup?.status).toBe("queued");+ });++ it("orders due retries by due time, honors the cutoff, and caps a sweep at 50 runs", async () => {+ const adapter = createPostgresRunDispatchAdapter(db);+ const companyId = randomUUID();+ const agentId = randomUUID();+ const now = new Date("2026-05-05T00:00:00.000Z");+ const issuePrefix = `T${companyId.replace(/-/g, "").slice(0, 6).toUpperCase()}`;++ await db.insert(companies).values({+ id: companyId,+ name: "Paperclip",+ issuePrefix,+ requireBoardApprovalForNewAgents: false,+ defaultResponsibleUserId: "responsible-user",+ });+ await db.insert(agents).values({+ id: agentId,+ companyId,+ name: "CodexCoder",+ role: "engineer",+ status: "active",+ adapterType: "codex_local",+ adapterConfig: {},+ runtimeConfig: { heartbeat: { wakeOnDemand: true, maxConcurrentRuns: 1 } },+ permissions: {},+ });++ // Due, but created well before the cutoff: the cutoff must exclude it+ // even though it is the single most-overdue run in the table.+ const beforeCutoffRunId = randomUUID();+ await db.insert(heartbeatRuns).values({+ id: beforeCutoffRunId,+ companyId,+ agentId,+ invocationSource: "retry",+ status: "scheduled_retry",+ scheduledRetryAt: new Date(now.getTime() - 1_000),+ contextSnapshot: {},+ createdAt: new Date(now.getTime() - 1_000_000),+ updatedAt: now,+ });++ // 52 due, in-cutoff runs, strictly ordered by scheduledRetryAt/createdAt.+ const dueRunIds = Array.from({ length: 52 }, () => randomUUID());+ for (let i = 0; i < dueRunIds.length; i += 1) {+ const dueAt = new Date(now.getTime() - (dueRunIds.length - i) * 1_000);+ await db.insert(heartbeatRuns).values({+ id: dueRunIds[i],+ companyId,+ agentId,+ invocationSource: "retry",+ status: "scheduled_retry",+ scheduledRetryAt: dueAt,+ contextSnapshot: {},+ createdAt: dueAt,+ updatedAt: now,+ });+ }++ const cutoff = new Date(now.getTime() - 500_000);+ const result = await adapter.listDueRetries({ now, cutoff, limit: 50 });++ expect(result).toHaveLength(50);+ expect(result.map((r) => r.runId)).toEqual(dueRunIds.slice(0, 50));+ const resultIds = new Set(result.map((r) => r.runId));+ expect(resultIds.has(beforeCutoffRunId)).toBe(false);+ expect(resultIds.has(dueRunIds[50])).toBe(false);+ expect(resultIds.has(dueRunIds[51])).toBe(false);+ });+ });});diff --git a/server/src/__tests__/heartbeat-stale-queue-invalidation.test.ts b/server/src/__tests__/heartbeat-stale-queue-invalidation.test.tsindex 7896cd4fd3..dc42bf9373 100644--- a/server/src/__tests__/heartbeat-stale-queue-invalidation.test.ts+++ b/server/src/__tests__/heartbeat-stale-queue-invalidation.test.ts@@ -621,7 +621,7 @@ describeEmbeddedPostgres("heartbeat stale queued-run invalidation", () => {},);- it("releases the final continuation gate at non-process adapter dispatch", async () => {+ it("releases the final continuation gate at adapter handoff before adapter DB callbacks", async () => {const { companyId, agentId } = await seedCompanyAndAgent();const issueId = randomUUID();await db.insert(issues).values({@@ -677,14 +677,20 @@ describeEmbeddedPostgres("heartbeat stale queued-run invalidation", () => {expect(ordering).toEqual(["validated"]);};mockAdapterExecute.mockImplementation(async (context) => {+ ordering.push("handed-off");+ // Real adapters record invocation metadata before process/remote+ // dispatch. Event sequencing updates the run row, so adapter-owned DB+ // callbacks must execute after the atomic gate releases its locks.+ await context.onMeta?.({ adapterType: "test", command: "test" });+ ordering.push("metadata-recorded");ordering.push("preparing");// Model asynchronous adapter setup before the child process exists.await new Promise((resolve) => setTimeout(resolve, 25));- expect(ordering).toEqual(["validated", "preparing"]);+ await waitForCondition(async () => ordering.includes("parked"));+ expect(ordering.slice(0, 2)).toEqual(["validated", "handed-off"]);+ expect(ordering).toEqual(expect.arrayContaining(["metadata-recorded", "preparing", "parked"]));ordering.push("dispatched");context.onDispatch?.();- await waitForCondition(async () => ordering.includes("parked"));- expect(ordering).toEqual(["validated", "preparing", "dispatched", "parked"]);ordering.push("settled");return {exitCode: 0,@@ -714,7 +720,9 @@ describeEmbeddedPostgres("heartbeat stale queued-run invalidation", () => {.where(eq(issues.id, issueId)).then((rows) => rows[0] ?? null);expect(issue?.status).toBe("backlog");- expect(ordering).toEqual(["validated", "preparing", "dispatched", "parked", "settled"]);+ expect(ordering.slice(0, 2)).toEqual(["validated", "handed-off"]);+ expect(ordering.slice(-2)).toEqual(["dispatched", "settled"]);+ expect(ordering).toEqual(expect.arrayContaining(["metadata-recorded", "preparing", "parked"]));expect(countExecuteCallsForRun(runId)).toBe(1);});@@ -1434,188 +1442,6 @@ describeEmbeddedPostgres("heartbeat stale queued-run invalidation", () => {expect(promotedRun?.agentId).toBe(peerAgentId);});- it("cancels queued runs when the issue assignee changes before the run starts", async () => {- const { companyId, agentId } = await seedCompanyAndAgent({ agentName: "OriginalCoder" });- const replacementAgentId = randomUUID();- await db.insert(agents).values({- id: replacementAgentId,- companyId,- name: "ReplacementCoder",- role: "engineer",- status: "active",- adapterType: "codex_local",- adapterConfig: {},- runtimeConfig: {- heartbeat: {- wakeOnDemand: true,- maxConcurrentRuns: 1,- },- },- permissions: {},- });-- const issueId = randomUUID();- await db.insert(issues).values({- id: issueId,- companyId,- title: "Reassigned task",- status: "in_progress",- priority: "high",- assigneeAgentId: replacementAgentId,- });-- const { runId, wakeupRequestId } = await seedQueuedRun({- companyId,- agentId,- issueId,- wakeReason: "issue_assigned",- });-- await heartbeat.resumeQueuedRuns();-- await waitForCondition(async () => {- const run = await db- .select({ status: heartbeatRuns.status })- .from(heartbeatRuns)- .where(eq(heartbeatRuns.id, runId))- .then((rows) => rows[0] ?? null);- return run?.status === "cancelled";- });-- const [run, wakeup] = await Promise.all([- db- .select({- status: heartbeatRuns.status,- errorCode: heartbeatRuns.errorCode,- resultJson: heartbeatRuns.resultJson,- })- .from(heartbeatRuns)- .where(eq(heartbeatRuns.id, runId))- .then((rows) => rows[0] ?? null),- db- .select({ status: agentWakeupRequests.status, error: agentWakeupRequests.error })- .from(agentWakeupRequests)- .where(eq(agentWakeupRequests.id, wakeupRequestId))- .then((rows) => rows[0] ?? null),- ]);-- expect(run?.status).toBe("cancelled");- expect(run?.errorCode).toBe("issue_assignee_changed");- expect(run?.resultJson).toMatchObject({ stopReason: "issue_assignee_changed" });- expect(wakeup?.status).toBe("skipped");- expect(wakeup?.error).toContain("assignee changed");- expect(countExecuteCallsForRun(runId)).toBe(0);- });-- it("cancels queued runs when the issue reaches a terminal status before the run starts", async () => {- const { companyId, agentId } = await seedCompanyAndAgent();- const issueId = randomUUID();- await db.insert(issues).values({- id: issueId,- companyId,- title: "Already-completed task",- status: "done",- priority: "medium",- assigneeAgentId: agentId,- });-- const { runId, wakeupRequestId } = await seedQueuedRun({- companyId,- agentId,- issueId,- wakeReason: "issue_assigned",- });-- await heartbeat.resumeQueuedRuns();-- await waitForCondition(async () => {- const run = await db- .select({ status: heartbeatRuns.status })- .from(heartbeatRuns)- .where(eq(heartbeatRuns.id, runId))- .then((rows) => rows[0] ?? null);- return run?.status === "cancelled";- });-- const [run, wakeup] = await Promise.all([- db- .select({ status: heartbeatRuns.status, errorCode: heartbeatRuns.errorCode })- .from(heartbeatRuns)- .where(eq(heartbeatRuns.id, runId))- .then((rows) => rows[0] ?? null),- db- .select({ status: agentWakeupRequests.status })- .from(agentWakeupRequests)- .where(eq(agentWakeupRequests.id, wakeupRequestId))- .then((rows) => rows[0] ?? null),- ]);-- expect(run?.status).toBe("cancelled");- expect(run?.errorCode).toBe("issue_terminal_status");- expect(wakeup?.status).toBe("skipped");- expect(countExecuteCallsForRun(runId)).toBe(0);- });-- it("cancels queued max-turn continuations when the issue is no longer in_progress before the run starts", async () => {- const { companyId, agentId } = await seedCompanyAndAgent();- const issueId = randomUUID();- await db.insert(issues).values({- id: issueId,- companyId,- title: "Parked max-turn continuation",- status: "blocked",- priority: "medium",- assigneeAgentId: agentId,- });-- const { runId, wakeupRequestId } = await seedQueuedRun({- companyId,- agentId,- issueId,- wakeReason: MAX_TURN_CONTINUATION_WAKE_REASON,- invocationSource: "automation",- scheduledRetryReason: MAX_TURN_CONTINUATION_RETRY_REASON,- contextExtras: {- retryReason: MAX_TURN_CONTINUATION_RETRY_REASON,- },- });-- await heartbeat.resumeQueuedRuns();-- await waitForCondition(async () => {- const run = await db- .select({ status: heartbeatRuns.status })- .from(heartbeatRuns)- .where(eq(heartbeatRuns.id, runId))- .then((rows) => rows[0] ?? null);- return run?.status === "cancelled";- });-- const [run, wakeup] = await Promise.all([- db- .select({- status: heartbeatRuns.status,- errorCode: heartbeatRuns.errorCode,- resultJson: heartbeatRuns.resultJson,- })- .from(heartbeatRuns)- .where(eq(heartbeatRuns.id, runId))- .then((rows) => rows[0] ?? null),- db- .select({ status: agentWakeupRequests.status, error: agentWakeupRequests.error })- .from(agentWakeupRequests)- .where(eq(agentWakeupRequests.id, wakeupRequestId))- .then((rows) => rows[0] ?? null),- ]);-- expect(run?.status).toBe("cancelled");- expect(run?.errorCode).toBe("issue_not_in_progress");- expect(run?.resultJson).toMatchObject({ stopReason: "issue_not_in_progress" });- expect(wakeup?.status).toBe("skipped");- expect(wakeup?.error).toContain("no longer in_progress");- expect(countExecuteCallsForRun(runId)).toBe(0);- });-it("cancels queued max-turn continuations when another continuation owns the issue lock", async () => {const { companyId, agentId } = await seedCompanyAndAgent();const issueId = randomUUID();@@ -1704,331 +1530,4 @@ describeEmbeddedPostgres("heartbeat stale queued-run invalidation", () => {expect(countExecuteCallsForRun(runId)).toBe(0);});- it("cancels queued in_review runs when the current participant changes before the run starts", async () => {- const { companyId, agentId } = await seedCompanyAndAgent();- const otherAgentId = randomUUID();- await db.insert(agents).values({- id: otherAgentId,- companyId,- name: "ReviewerAgent",- role: "qa",- status: "active",- adapterType: "codex_local",- adapterConfig: {},- runtimeConfig: { heartbeat: { wakeOnDemand: true, maxConcurrentRuns: 1 } },- permissions: {},- });-- const issueId = randomUUID();- await db.insert(issues).values({- id: issueId,- companyId,- title: "In-review task now owned by reviewer",- status: "in_review",- priority: "medium",- assigneeAgentId: agentId,- executionState: {- status: "pending",- currentStageId: randomUUID(),- currentStageIndex: 0,- currentStageType: "review",- currentParticipant: { type: "agent", agentId: otherAgentId, userId: null },- returnAssignee: { type: "agent", agentId, userId: null },- reviewRequest: null,- completedStageIds: [],- lastDecisionId: null,- lastDecisionOutcome: null,- },- });-- const { runId, wakeupRequestId } = await seedQueuedRun({- companyId,- agentId,- issueId,- wakeReason: "issue_assigned",- });-- await heartbeat.resumeQueuedRuns();-- await waitForCondition(async () => {- const run = await db- .select({ status: heartbeatRuns.status })- .from(heartbeatRuns)- .where(eq(heartbeatRuns.id, runId))- .then((rows) => rows[0] ?? null);- return run?.status === "cancelled";- });-- const [run, wakeup] = await Promise.all([- db- .select({- status: heartbeatRuns.status,- errorCode: heartbeatRuns.errorCode,- resultJson: heartbeatRuns.resultJson,- })- .from(heartbeatRuns)- .where(eq(heartbeatRuns.id, runId))- .then((rows) => rows[0] ?? null),- db- .select({ status: agentWakeupRequests.status, error: agentWakeupRequests.error })- .from(agentWakeupRequests)- .where(eq(agentWakeupRequests.id, wakeupRequestId))- .then((rows) => rows[0] ?? null),- ]);-- expect(run?.status).toBe("cancelled");- expect(run?.errorCode).toBe("issue_review_participant_changed");- expect(run?.resultJson).toMatchObject({ stopReason: "issue_review_participant_changed" });- expect(wakeup?.status).toBe("skipped");- expect(wakeup?.error).toContain("in-review participant changed");- expect(countExecuteCallsForRun(runId)).toBe(0);- });-- it("still runs comment-driven wakes on in_review issues even when the agent is no longer the current participant", async () => {- const { companyId, agentId } = await seedCompanyAndAgent();- const otherAgentId = randomUUID();- await db.insert(agents).values({- id: otherAgentId,- companyId,- name: "ReviewerAgent",- role: "qa",- status: "active",- adapterType: "codex_local",- adapterConfig: {},- runtimeConfig: { heartbeat: { wakeOnDemand: true, maxConcurrentRuns: 1 } },- permissions: {},- });-- const issueId = randomUUID();- const commentId = randomUUID();- await db.insert(issues).values({- id: issueId,- companyId,- title: "In-review task with comment feedback",- status: "in_review",- priority: "medium",- assigneeAgentId: agentId,- executionState: {- status: "pending",- currentStageId: randomUUID(),- currentStageIndex: 0,- currentStageType: "review",- currentParticipant: { type: "agent", agentId: otherAgentId, userId: null },- returnAssignee: { type: "agent", agentId, userId: null },- reviewRequest: null,- completedStageIds: [],- lastDecisionId: null,- lastDecisionOutcome: null,- },- });- await db.insert(issueComments).values({- id: commentId,- companyId,- issueId,- authorAgentId: otherAgentId,- body: "Review feedback comment",- });-- const { runId } = await seedQueuedRun({- companyId,- agentId,- issueId,- wakeReason: "issue_commented",- invocationSource: "automation",- contextExtras: {- commentId,- wakeCommentId: commentId,- source: "issue.comment",- },- });-- await heartbeat.resumeQueuedRuns();-- await waitForCondition(async () => {- const run = await db- .select({ status: heartbeatRuns.status })- .from(heartbeatRuns)- .where(eq(heartbeatRuns.id, runId))- .then((rows) => rows[0] ?? null);- return run?.status === "succeeded";- });-- const run = await db- .select({ status: heartbeatRuns.status, errorCode: heartbeatRuns.errorCode })- .from(heartbeatRuns)- .where(eq(heartbeatRuns.id, runId))- .then((rows) => rows[0] ?? null);- expect(run?.status).toBe("succeeded");- expect(run?.errorCode).toBeNull();- });-- it("baseline: runs queued runs when the issue is in_progress with the same assignee", async () => {- const { companyId, agentId } = await seedCompanyAndAgent();- const issueId = randomUUID();- await db.insert(issues).values({- id: issueId,- companyId,- title: "Still actionable",- status: "in_progress",- priority: "medium",- assigneeAgentId: agentId,- });-- const { runId } = await seedQueuedRun({- companyId,- agentId,- issueId,- wakeReason: "issue_assigned",- });-- await heartbeat.resumeQueuedRuns();-- await waitForCondition(async () => {- const run = await db- .select({ status: heartbeatRuns.status })- .from(heartbeatRuns)- .where(eq(heartbeatRuns.id, runId))- .then((rows) => rows[0] ?? null);- return run?.status === "succeeded";- });-- const run = await db- .select({ status: heartbeatRuns.status, errorCode: heartbeatRuns.errorCode })- .from(heartbeatRuns)- .where(eq(heartbeatRuns.id, runId))- .then((rows) => rows[0] ?? null);- expect(run?.status).toBe("succeeded");- expect(run?.errorCode).toBeNull();- expect(countExecuteCallsForRun(runId)).toBe(1);- });-- it("cancels queued continuation recovery when the continuation summary parks executor work for review", async () => {- const { companyId, agentId } = await seedCompanyAndAgent();- const issueId = randomUUID();- await db.insert(issues).values({- id: issueId,- companyId,- title: "Implementation parked for review",- status: "in_progress",- priority: "medium",- assigneeAgentId: agentId,- });- await seedContinuationSummary({- companyId,- issueId,- agentId,- body: [- "# Continuation Summary",- "",- "## Next Action",- "",- "- Wait for reviewer feedback or approval before continuing executor work.",- ].join("\n"),- });-- const { runId, wakeupRequestId } = await seedQueuedRun({- companyId,- agentId,- issueId,- wakeReason: "issue_continuation_needed",- invocationSource: "automation",- contextExtras: {- retryReason: "issue_continuation_needed",- },- });-- await heartbeat.resumeQueuedRuns();-- await waitForCondition(async () => {- const run = await db- .select({ status: heartbeatRuns.status })- .from(heartbeatRuns)- .where(eq(heartbeatRuns.id, runId))- .then((rows) => rows[0] ?? null);- return run?.status === "cancelled";- });-- const [run, wakeup] = await Promise.all([- db- .select({- status: heartbeatRuns.status,- errorCode: heartbeatRuns.errorCode,- resultJson: heartbeatRuns.resultJson,- })- .from(heartbeatRuns)- .where(eq(heartbeatRuns.id, runId))- .then((rows) => rows[0] ?? null),- db- .select({ status: agentWakeupRequests.status, error: agentWakeupRequests.error })- .from(agentWakeupRequests)- .where(eq(agentWakeupRequests.id, wakeupRequestId))- .then((rows) => rows[0] ?? null),- ]);-- expect(run?.status).toBe("cancelled");- expect(run?.errorCode).toBe("issue_continuation_waiting_on_review");- expect(run?.resultJson).toMatchObject({ stopReason: "issue_continuation_waiting_on_review" });- expect(wakeup?.status).toBe("skipped");- expect(wakeup?.error).toContain("continuation summary says the executor should wait");- expect(countExecuteCallsForRun(runId)).toBe(0);- });-- it("runs accepted-interaction continuation recovery despite a pre-acceptance review park", async () => {- const { companyId, agentId } = await seedCompanyAndAgent();- const issueId = randomUUID();- await db.insert(issues).values({- id: issueId,- companyId,- title: "Approved implementation resumes",- status: "in_progress",- priority: "medium",- assigneeAgentId: agentId,- });- await seedContinuationSummary({- companyId,- issueId,- agentId,- body: [- "# Continuation Summary",- "",- "## Next Action",- "",- "- Wait for reviewer feedback or approval before continuing executor work.",- ].join("\n"),- });-- const { runId } = await seedQueuedRun({- companyId,- agentId,- issueId,- wakeReason: "issue_continuation_needed",- invocationSource: "automation",- contextExtras: {- retryReason: "issue_continuation_needed",- mutation: "interaction",- interactionId: randomUUID(),- interactionResolvedAt: "2026-03-19T00:05:00.000Z",- },- });-- await heartbeat.resumeQueuedRuns();-- await waitForCondition(async () => {- const run = await db- .select({ status: heartbeatRuns.status })- .from(heartbeatRuns)- .where(eq(heartbeatRuns.id, runId))- .then((rows) => rows[0] ?? null);- return run?.status === "succeeded";- });-- const run = await db- .select({ status: heartbeatRuns.status, errorCode: heartbeatRuns.errorCode })- .from(heartbeatRuns)- .where(eq(heartbeatRuns.id, runId))- .then((rows) => rows[0] ?? null);- expect(run?.status).toBe("succeeded");- expect(run?.errorCode).toBeNull();- expect(countExecuteCallsForRun(runId)).toBe(1);- });});diff --git a/server/src/__tests__/heartbeat-task-drain-admission-release.test.ts b/server/src/__tests__/heartbeat-task-drain-admission-release.test.tsindex cefe6cff38..4abed5f5dc 100644--- a/server/src/__tests__/heartbeat-task-drain-admission-release.test.ts+++ b/server/src/__tests__/heartbeat-task-drain-admission-release.test.ts@@ -225,9 +225,9 @@ describeEmbeddedPostgres("heartbeat task-drain admission release", () => {// partway through, without touching any other table's update path.// tablesByCall maps a 0-based db.transaction() call index (in call order)// to the table that call should fail on; a call index with no entry runs- // every update for real. For example { 0: issues } fails only the- // issue-lock write inside releaseRunClaimedJustBeforeSuppression's- // transaction.+ // every update for real. For example { 1: issues } lets the atomic stale-run+ // validation transaction complete, then fails only the issue-lock write+ // inside releaseRunClaimedJustBeforeSuppression's transaction.function withFailingTransactionalUpdate(realDb: typeof db, tablesByCall: Record<number, unknown>) {let callIndex = 0;return new Proxy(realDb, {@@ -262,7 +262,7 @@ describeEmbeddedPostgres("heartbeat task-drain admission release", () => {// Fault the release transaction on the issue-lock write, so executeRun's// suppression branch catches the failure, logs it, and returns instead// of throwing. There is no in-process fallback or retry for this path.- const failingDb = withFailingTransactionalUpdate(db, { 0: issues });+ const failingDb = withFailingTransactionalUpdate(db, { 1: issues });const heartbeat = heartbeatService(failingDb);const unsubscribe = subscribeCompanyLiveEvents(companyId, (event) => {diff --git a/server/src/__tests__/heartbeat-workspace-session.test.ts b/server/src/__tests__/heartbeat-workspace-session.test.tsindex 1da2071e2c..73a9c1f1af 100644--- a/server/src/__tests__/heartbeat-workspace-session.test.ts+++ b/server/src/__tests__/heartbeat-workspace-session.test.ts@@ -17,7 +17,6 @@ import {buildEffectiveRunWorkspaceConfigMetadata,buildWorkspaceConfigFreshnessOperation,deriveTaskKeyWithHeartbeatFallback,- extractWakeCommentIds,formatRuntimeWorkspaceWarningLog,mergeExecutionWorkspaceMetadataForPersistence,mergeCoalescedContextSnapshot,@@ -2638,7 +2637,7 @@ describe("deriveTaskKeyWithHeartbeatFallback", () => {});describe("comment wake batching", () => {- it("preserves ordered wake comment ids when coalescing queued follow-up wakes", () => {+ it("updates the latest comment when coalescing queued follow-up wakes", () => {const merged = mergeCoalescedContextSnapshot({issueId: "issue-1",@@ -2656,7 +2655,7 @@ describe("comment wake batching", () => {},);- expect(extractWakeCommentIds(merged)).toEqual(["comment-1", "comment-2"]);+ expect(merged.wakeCommentIds).toEqual(["comment-1", "comment-2"]);expect(merged.commentId).toBe("comment-2");expect(merged.wakeCommentId).toBe("comment-2");expect(merged.paperclipWake).toBeUndefined();diff --git a/server/src/__tests__/issue-scheduled-retry-routes.test.ts b/server/src/__tests__/issue-scheduled-retry-routes.test.tsindex d863fc6351..c5d477d659 100644--- a/server/src/__tests__/issue-scheduled-retry-routes.test.ts+++ b/server/src/__tests__/issue-scheduled-retry-routes.test.ts@@ -385,28 +385,6 @@ describeEmbeddedPostgres("issue scheduled retry routes", () => {});});- it("does not promote a scheduled retry after on-demand wakes are disabled", async () => {- const { companyId, agentId, issueId, retryRunId } = await seedIssueWithRetry();- await db- .update(agents)- .set({ runtimeConfig: { heartbeat: { wakeOnDemand: false } } })- .where(eq(agents.id, agentId));-- const res = await request(createApp(boardActor(companyId)))- .post(`/api/issues/${issueId}/scheduled-retry/retry-now`)- .send({});-- expect(res.status, JSON.stringify(res.body)).toBe(200);- expect(res.body).toMatchObject({- outcome: "gate_suppressed",- scheduledRetry: {- runId: retryRunId,- status: "cancelled",- errorCode: "heartbeat_wake_on_demand_disabled",- },- });- });-it("requires board access for retry-now", async () => {const { companyId, agentId, issueId } = await seedIssueWithRetry();@@ -427,161 +405,4 @@ describeEmbeddedPostgres("issue scheduled retry routes", () => {expect(res.status).toBe(404);});- it("suppresses retry-now when the issue is under a budget hard-stop", async () => {- const { companyId, agentId, issueId, retryRunId } = await seedIssueWithRetry();- await db- .update(agents)- .set({ status: "paused", pauseReason: "budget" })- .where(eq(agents.id, agentId));-- const res = await request(createApp(boardActor(companyId)))- .post(`/api/issues/${issueId}/scheduled-retry/retry-now`)- .send({});-- expect(res.status, JSON.stringify(res.body)).toBe(200);- expect(res.body).toMatchObject({- outcome: "gate_suppressed",- scheduledRetry: {- runId: retryRunId,- status: "cancelled",- errorCode: "budget_blocked",- },- });- });-- it("suppresses retry-now when the issue is waiting on another review participant", async () => {- const { companyId, agentId, issueId, retryRunId } = await seedIssueWithRetry({ issueStatus: "in_progress" });- const reviewerAgentId = randomUUID();- await db.insert(agents).values({- id: reviewerAgentId,- companyId,- name: "ReviewerAgent",- role: "qa",- status: "active",- adapterType: "codex_local",- adapterConfig: {},- runtimeConfig: {- heartbeat: {- wakeOnDemand: true,- maxConcurrentRuns: 1,- },- },- permissions: {},- });- await db- .update(issues)- .set({- status: "in_review",- executionState: {- status: "pending",- currentStageId: randomUUID(),- currentStageIndex: 0,- currentStageType: "review",- currentParticipant: { type: "agent", agentId: reviewerAgentId, userId: null },- returnAssignee: { type: "agent", agentId, userId: null },- reviewRequest: null,- completedStageIds: [],- lastDecisionId: null,- lastDecisionOutcome: null,- },- })- .where(eq(issues.id, issueId));-- const res = await request(createApp(boardActor(companyId)))- .post(`/api/issues/${issueId}/scheduled-retry/retry-now`)- .send({});-- expect(res.status, JSON.stringify(res.body)).toBe(200);- expect(res.body).toMatchObject({- outcome: "gate_suppressed",- scheduledRetry: {- runId: retryRunId,- status: "cancelled",- errorCode: "issue_review_participant_changed",- },- });- });-- it("suppresses retry-now when the issue is under an active subtree pause hold", async () => {- const { companyId, issueId, retryRunId } = await seedIssueWithRetry();- await db.insert(issueTreeHolds).values({- companyId,- rootIssueId: issueId,- mode: "pause",- status: "active",- reason: "manual pause for review",- releasePolicy: { strategy: "manual" },- });-- const res = await request(createApp(boardActor(companyId)))- .post(`/api/issues/${issueId}/scheduled-retry/retry-now`)- .send({});-- expect(res.status, JSON.stringify(res.body)).toBe(200);- expect(res.body).toMatchObject({- outcome: "gate_suppressed",- scheduledRetry: {- runId: retryRunId,- status: "cancelled",- errorCode: "issue_paused",- },- });- });-- it("suppresses retry-now when unresolved blockers remain", async () => {- const { companyId, issueId, retryRunId } = await seedIssueWithRetry();- const blockerId = randomUUID();- await db.insert(issues).values({- id: blockerId,- companyId,- title: "Blocking task",- status: "todo",- priority: "medium",- issueNumber: 2,- identifier: "BLOCK-2",- });- await db.insert(issueRelations).values({- id: randomUUID(),- companyId,- issueId: blockerId,- relatedIssueId: issueId,- type: "blocks",- });- await db- .update(issues)- .set({ status: "blocked" })- .where(eq(issues.id, issueId));-- const res = await request(createApp(boardActor(companyId)))- .post(`/api/issues/${issueId}/scheduled-retry/retry-now`)- .send({});-- expect(res.status, JSON.stringify(res.body)).toBe(200);- expect(res.body).toMatchObject({- outcome: "gate_suppressed",- scheduledRetry: {- runId: retryRunId,- status: "cancelled",- errorCode: "issue_dependencies_blocked",- },- });- });-- it("suppresses retry-now when the issue already reached a terminal status", async () => {- const { companyId, issueId, retryRunId } = await seedIssueWithRetry({ issueStatus: "done" });-- const res = await request(createApp(boardActor(companyId)))- .post(`/api/issues/${issueId}/scheduled-retry/retry-now`)- .send({});-- expect(res.status, JSON.stringify(res.body)).toBe(200);- expect(res.body).toMatchObject({- outcome: "gate_suppressed",- scheduledRetry: {- runId: retryRunId,- status: "cancelled",- errorCode: "issue_terminal_status",- },- });- });});diff --git a/server/src/modules/run-dispatch/adapters/postgres.test.ts b/server/src/modules/run-dispatch/adapters/postgres.test.tsnew file mode 100644index 0000000000..a0a62f8a77--- /dev/null+++ b/server/src/modules/run-dispatch/adapters/postgres.test.ts@@ -0,0 +1,615 @@+import { randomUUID } from "node:crypto";+import { eq, sql } from "drizzle-orm";+import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";+import {+ agents,+ companies,+ createDb,+ documentRevisions,+ documents,+ heartbeatRunEvents,+ heartbeatRuns,+ issueDocuments,+ issueRelations,+ issueTreeHolds,+ issues,+} from "@paperclipai/db";+import { ISSUE_CONTINUATION_SUMMARY_DOCUMENT_KEY } from "@paperclipai/shared";+import {+ getEmbeddedPostgresTestSupport,+ startEmbeddedPostgresTestDatabase,+} from "../../../__tests__/helpers/embedded-postgres.js";+import { createPostgresRunDispatchAdapter } from "./postgres.js";++// Proves the DB-to-facts mapping this adapter owns for each state the two+// run-dispatch gates decide on. `application/use-cases.test.ts` and+// `domain/policy.test.ts` cover the gates' branching with hand-built facts;+// this file proves the adapter reads the right rows into those facts, then+// feeds the mapped facts back through the real gate to prove the wiring+// produces the same suppression a caller would have seen before this module+// existed.+const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport();+const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip;++if (!embeddedPostgresSupport.supported) {+ console.warn(+ `Skipping embedded Postgres run-dispatch adapter tests on this host: ${embeddedPostgresSupport.reason ?? "unsupported environment"}`,+ );+}++describeEmbeddedPostgres("run-dispatch postgres adapter", () => {+ let db!: ReturnType<typeof createDb>;+ let tempDb: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | null = null;++ beforeAll(async () => {+ tempDb = await startEmbeddedPostgresTestDatabase("paperclip-run-dispatch-postgres-adapter-");+ db = createDb(tempDb.connectionString);+ }, 20_000);++ afterEach(async () => {+ await db.delete(issueDocuments);+ await db.delete(documentRevisions);+ await db.delete(documents);+ await db.delete(issueTreeHolds);+ await db.delete(issueRelations);+ await db.delete(issues);+ await db.delete(heartbeatRunEvents);+ await db.delete(heartbeatRuns);+ await db.delete(agents);+ await db.delete(companies);+ });++ afterAll(async () => {+ await tempDb?.cleanup();+ });++ async function seedCompanyAndAgent(): Promise<{ companyId: string; agentId: string }> {+ const companyId = randomUUID();+ const agentId = randomUUID();+ await db.insert(companies).values({+ id: companyId,+ name: "Paperclip",+ issuePrefix: `T${companyId.replace(/-/g, "").slice(0, 6).toUpperCase()}`,+ requireBoardApprovalForNewAgents: false,+ defaultResponsibleUserId: "responsible-user",+ });+ await db.insert(agents).values({+ id: agentId,+ companyId,+ name: "CodexCoder",+ role: "engineer",+ status: "active",+ adapterType: "codex_local",+ adapterConfig: {},+ runtimeConfig: { heartbeat: { wakeOnDemand: true, maxConcurrentRuns: 1 } },+ permissions: {},+ });+ return { companyId, agentId };+ }++ async function seedAgent(input: {+ id: string;+ companyId: string;+ name: string;+ role?: string;+ }) {+ await db.insert(agents).values({+ id: input.id,+ companyId: input.companyId,+ name: input.name,+ role: input.role ?? "engineer",+ status: "active",+ adapterType: "codex_local",+ adapterConfig: {},+ runtimeConfig: { heartbeat: { wakeOnDemand: true, maxConcurrentRuns: 1 } },+ permissions: {},+ });+ }++ async function seedIssue(input: {+ companyId: string;+ issueId: string;+ status: string;+ assigneeAgentId?: string | null;+ executionState?: Record<string, unknown> | null;+ }) {+ await db.insert(issues).values({+ id: input.issueId,+ companyId: input.companyId,+ title: "Run-dispatch adapter fixture issue",+ status: input.status,+ priority: "medium",+ assigneeAgentId: input.assigneeAgentId ?? null,+ executionState: input.executionState ?? null,+ });+ }++ async function seedRun(input: {+ companyId: string;+ agentId: string;+ contextSnapshot?: Record<string, unknown>;+ status?: "queued" | "running" | "scheduled_retry";+ scheduledRetryReason?: string | null;+ now?: Date;+ }) {+ const runId = randomUUID();+ const now = input.now ?? new Date();+ await db.insert(heartbeatRuns).values({+ id: runId,+ companyId: input.companyId,+ agentId: input.agentId,+ invocationSource: "retry",+ status: input.status ?? "queued",+ contextSnapshot: input.contextSnapshot ?? {},+ scheduledRetryReason: input.scheduledRetryReason ?? null,+ scheduledRetryAt: input.status === "scheduled_retry" ? now : null,+ createdAt: now,+ updatedAt: now,+ });+ return runId;+ }++ async function seedContinuationSummary(input: {+ companyId: string;+ issueId: string;+ agentId: string;+ body: string;+ }) {+ const documentId = randomUUID();+ const revisionId = randomUUID();+ await db.insert(documents).values({+ id: documentId,+ companyId: input.companyId,+ title: "Continuation Summary",+ format: "markdown",+ latestBody: input.body,+ latestRevisionId: revisionId,+ latestRevisionNumber: 1,+ createdByAgentId: input.agentId,+ updatedByAgentId: input.agentId,+ });+ await db.insert(documentRevisions).values({+ id: revisionId,+ companyId: input.companyId,+ documentId,+ revisionNumber: 1,+ title: "Continuation Summary",+ format: "markdown",+ body: input.body,+ createdByAgentId: input.agentId,+ });+ await db.insert(issueDocuments).values({+ companyId: input.companyId,+ issueId: input.issueId,+ documentId,+ key: ISSUE_CONTINUATION_SUMMARY_DOCUMENT_KEY,+ });+ }++ async function waitForBlockedForUpdate(tableName: string) {+ for (let attempt = 0; attempt < 80; attempt += 1) {+ const [waiting] = await db.execute<{ waiting: boolean }>(sql`+ SELECT EXISTS (+ SELECT 1+ FROM pg_stat_activity+ WHERE state = 'active'+ AND wait_event_type = 'Lock'+ AND query ILIKE ${`%${tableName}%`}+ AND query ILIKE '%for update%'+ ) AS waiting+ `);+ if (waiting?.waiting) return true;+ await new Promise((resolve) => setTimeout(resolve, 25));+ }+ return false;+ }++ async function reassignIssueAndLockRunOnceAConcurrentWaiterBlocks(+ issueId: string,+ runId: string,+ newAssigneeAgentId: string,+ ) {+ let signalLocked!: () => void;+ const locked = new Promise<void>((resolve) => {+ signalLocked = resolve;+ });+ const transaction = db.transaction(async (tx) => {+ await tx.select({ id: issues.id }).from(issues).where(eq(issues.id, issueId)).for("update");+ signalLocked();+ if (!(await waitForBlockedForUpdate("issues"))) {+ throw new Error("expected a concurrent `for update` waiter on issues");+ }+ // The production claim path locks issue -> wake -> run. Taking the run+ // lock here proves the semantic adapter follows the same ordering: if it+ // held run while waiting for issue, these two transactions would deadlock.+ await tx+ .select({ id: heartbeatRuns.id })+ .from(heartbeatRuns)+ .where(eq(heartbeatRuns.id, runId))+ .for("update");+ await tx+ .update(issues)+ .set({ assigneeAgentId: newAssigneeAgentId })+ .where(eq(issues.id, issueId));+ });+ await locked;+ return transaction;+ }++ describe("evaluateScheduledRetryGate", () => {+ it("maps a disabled on-demand wake into a blocked scheduled-retry gate decision", async () => {+ const { companyId, agentId } = await seedCompanyAndAgent();+ await db+ .update(agents)+ .set({ runtimeConfig: { heartbeat: { wakeOnDemand: false } } })+ .where(eq(agents.id, agentId));++ const adapter = createPostgresRunDispatchAdapter(db);+ const now = new Date();+ const runId = await seedRun({ companyId, agentId });+ const result = await adapter.evaluateScheduledRetryGate({+ runId,+ companyId,+ retryReasonOverride: "other",+ now,+ });++ expect(result).toMatchObject({+ allowed: false,+ errorCode: "heartbeat_wake_on_demand_disabled",+ });+ });++ it("maps an active subtree pause hold into a blocked scheduled-retry gate decision", async () => {+ const { companyId, agentId } = await seedCompanyAndAgent();+ const issueId = randomUUID();+ await seedIssue({ companyId, issueId, status: "in_progress", assigneeAgentId: agentId });+ await db.insert(issueTreeHolds).values({+ companyId,+ rootIssueId: issueId,+ mode: "pause",+ status: "active",+ reason: "manual pause for review",+ releasePolicy: { strategy: "manual" },+ });++ const adapter = createPostgresRunDispatchAdapter(db);+ const now = new Date();+ const runId = await seedRun({ companyId, agentId, contextSnapshot: { issueId } });+ const result = await adapter.evaluateScheduledRetryGate({+ runId,+ companyId,+ retryReasonOverride: "other",+ now,+ });++ expect(result).toMatchObject({+ allowed: false,+ errorCode: "issue_paused",+ });+ });++ it("maps an unresolved dependency blocker into a blocked scheduled-retry gate decision", async () => {+ const { companyId, agentId } = await seedCompanyAndAgent();+ const issueId = randomUUID();+ const blockerId = randomUUID();+ await seedIssue({ companyId, issueId, status: "blocked", assigneeAgentId: agentId });+ await seedIssue({ companyId, issueId: blockerId, status: "todo" });+ await db.insert(issueRelations).values({+ companyId,+ issueId: blockerId,+ relatedIssueId: issueId,+ type: "blocks",+ });++ const adapter = createPostgresRunDispatchAdapter(db);+ const now = new Date();+ const runId = await seedRun({ companyId, agentId, contextSnapshot: { issueId } });+ const result = await adapter.evaluateScheduledRetryGate({+ runId,+ companyId,+ retryReasonOverride: "other",+ now,+ });++ expect(result).toMatchObject({+ allowed: false,+ errorCode: "issue_dependencies_blocked",+ details: { unresolvedBlockerIssueIds: [blockerId] },+ });+ });++ it("maps a changed review participant into a blocked scheduled-retry gate decision", async () => {+ const { companyId, agentId } = await seedCompanyAndAgent();+ const reviewerAgentId = randomUUID();+ await seedAgent({ id: reviewerAgentId, companyId, name: "ReviewerAgent", role: "qa" });+ const issueId = randomUUID();+ await seedIssue({+ companyId,+ issueId,+ status: "in_review",+ assigneeAgentId: agentId,+ executionState: {+ status: "pending",+ currentStageId: randomUUID(),+ currentStageIndex: 0,+ currentStageType: "review",+ currentParticipant: { type: "agent", agentId: reviewerAgentId, userId: null },+ returnAssignee: { type: "agent", agentId, userId: null },+ reviewRequest: null,+ completedStageIds: [],+ lastDecisionId: null,+ lastDecisionOutcome: null,+ },+ });++ const adapter = createPostgresRunDispatchAdapter(db);+ const now = new Date();+ const runId = await seedRun({ companyId, agentId, contextSnapshot: { issueId } });+ const result = await adapter.evaluateScheduledRetryGate({+ runId,+ companyId,+ retryReasonOverride: "other",+ now,+ });++ expect(result).toMatchObject({+ allowed: false,+ errorCode: "issue_review_participant_changed",+ });+ });++ it("maps a terminal issue status into a blocked scheduled-retry gate decision", async () => {+ const { companyId, agentId } = await seedCompanyAndAgent();+ const issueId = randomUUID();+ await seedIssue({ companyId, issueId, status: "done", assigneeAgentId: agentId });++ const adapter = createPostgresRunDispatchAdapter(db);+ const now = new Date();+ const runId = await seedRun({ companyId, agentId, contextSnapshot: { issueId } });+ const result = await adapter.evaluateScheduledRetryGate({+ runId,+ companyId,+ retryReasonOverride: "other",+ now,+ });++ expect(result).toMatchObject({+ allowed: false,+ errorCode: "issue_terminal_status",+ });+ });+ });++ describe("cancelStaleQueuedRun", () => {+ it("maps a reassigned issue into a stale queued-run decision", async () => {+ const { companyId, agentId } = await seedCompanyAndAgent();+ const replacementAgentId = randomUUID();+ await seedAgent({ id: replacementAgentId, companyId, name: "ReplacementCoder" });+ const issueId = randomUUID();+ await seedIssue({ companyId, issueId, status: "in_progress", assigneeAgentId: replacementAgentId });++ const adapter = createPostgresRunDispatchAdapter(db);+ const now = new Date();+ const runId = await seedRun({+ companyId,+ agentId,+ contextSnapshot: { issueId, wakeReason: "issue_assigned" },+ });+ const result = await adapter.cancelStaleQueuedRun({+ runId,+ companyId,+ expectedStatus: "queued",+ now,+ });++ expect(result).toMatchObject({+ outcome: "cancelled",+ errorCode: "issue_assignee_changed",+ });+ });++ it(+ "reads the locked issue state and cancels in the same semantic transaction",+ async () => {+ const { companyId, agentId } = await seedCompanyAndAgent();+ const replacementAgentId = randomUUID();+ await seedAgent({ id: replacementAgentId, companyId, name: "ReplacementCoder" });+ const issueId = randomUUID();+ await seedIssue({ companyId, issueId, status: "in_progress", assigneeAgentId: agentId });+ const runId = await seedRun({+ companyId,+ agentId,+ contextSnapshot: { issueId, wakeReason: "issue_assigned" },+ });++ const holderDone = reassignIssueAndLockRunOnceAConcurrentWaiterBlocks(+ issueId,+ runId,+ replacementAgentId,+ );+ const outcome = await createPostgresRunDispatchAdapter(db).cancelStaleQueuedRun({+ runId,+ companyId,+ expectedStatus: "queued",+ now: new Date(),+ });+ await holderDone;++ expect(outcome).toMatchObject({+ outcome: "cancelled",+ errorCode: "issue_assignee_changed",+ });+ const persisted = await db+ .select({ status: heartbeatRuns.status })+ .from(heartbeatRuns)+ .where(eq(heartbeatRuns.id, runId))+ .then((rows) => rows[0]);+ expect(persisted?.status).toBe("cancelled");+ },+ 15_000,+ );++ it("maps a review-parking continuation summary into a stale queued-run decision", async () => {+ const { companyId, agentId } = await seedCompanyAndAgent();+ const issueId = randomUUID();+ await seedIssue({ companyId, issueId, status: "in_progress", assigneeAgentId: agentId });+ await seedContinuationSummary({+ companyId,+ issueId,+ agentId,+ body: [+ "# Continuation Summary",+ "",+ "## Next Action",+ "",+ "- Wait for reviewer feedback or approval before continuing executor work.",+ ].join("\n"),+ });++ const adapter = createPostgresRunDispatchAdapter(db);+ const now = new Date();+ const runId = await seedRun({+ companyId,+ agentId,+ contextSnapshot: {+ issueId,+ wakeReason: "issue_continuation_needed",+ retryReason: "issue_continuation_needed",+ },+ });+ const result = await adapter.cancelStaleQueuedRun({+ runId,+ companyId,+ expectedStatus: "queued",+ now,+ });++ expect(result).toMatchObject({+ outcome: "cancelled",+ errorCode: "issue_continuation_waiting_on_review",+ });+ });+ });++ describe("promoteOrCancelDueRetry", () => {+ async function seedScheduledRetryRun(input: {+ runId: string;+ companyId: string;+ agentId: string;+ issueId: string;+ now: Date;+ }) {+ await db.insert(heartbeatRuns).values({+ id: input.runId,+ companyId: input.companyId,+ agentId: input.agentId,+ invocationSource: "retry",+ status: "scheduled_retry",+ scheduledRetryAttempt: 1,+ scheduledRetryAt: input.now,+ scheduledRetryReason: "max_turns_continuation",+ contextSnapshot: { issueId: input.issueId },+ updatedAt: input.now,+ createdAt: input.now,+ });+ }++ it("promotes an allowed due retry", async () => {+ const { companyId, agentId } = await seedCompanyAndAgent();+ const issueId = randomUUID();+ const runId = randomUUID();+ const now = new Date();+ await seedIssue({ companyId, issueId, status: "in_progress", assigneeAgentId: agentId });+ await seedScheduledRetryRun({ runId, companyId, agentId, issueId, now });+ await db.update(issues).set({ executionRunId: runId }).where(eq(issues.id, issueId));++ const adapter = createPostgresRunDispatchAdapter(db);+ const outcome = await adapter.promoteOrCancelDueRetry({+ runId,+ companyId,+ now,+ });++ expect(outcome.outcome).toBe("promoted");+ const [row] = await db.select({ status: heartbeatRuns.status }).from(heartbeatRuns).where(eq(heartbeatRuns.id, runId));+ expect(row?.status).toBe("queued");+ });++ it("cancels a due retry a pause hold blocks", async () => {+ const { companyId, agentId } = await seedCompanyAndAgent();+ const issueId = randomUUID();+ const runId = randomUUID();+ const now = new Date();+ await seedIssue({ companyId, issueId, status: "in_progress", assigneeAgentId: agentId });+ await db.insert(issueTreeHolds).values({+ companyId,+ rootIssueId: issueId,+ mode: "pause",+ status: "active",+ reason: "manual pause for review",+ releasePolicy: { strategy: "manual" },+ });+ await seedScheduledRetryRun({ runId, companyId, agentId, issueId, now });+ await db.update(issues).set({ executionRunId: runId }).where(eq(issues.id, issueId));++ const adapter = createPostgresRunDispatchAdapter(db);+ const outcome = await adapter.promoteOrCancelDueRetry({+ runId,+ companyId,+ now,+ });++ expect(outcome.outcome).toBe("gate_suppressed");+ if (outcome.outcome === "gate_suppressed") {+ expect(outcome.errorCode).toBe("issue_paused");+ }+ const [row] = await db.select({ status: heartbeatRuns.status }).from(heartbeatRuns).where(eq(heartbeatRuns.id, runId));+ expect(row?.status).toBe("cancelled");+ });++ it(+ "locks the issue row for the whole decision, so a reassignment committed while it waits is not missed",+ async () => {+ const { companyId, agentId: originalAgentId } = await seedCompanyAndAgent();+ const newAgentId = randomUUID();+ await seedAgent({ id: newAgentId, companyId, name: "ReplacementCoder" });+ const issueId = randomUUID();+ const runId = randomUUID();+ const now = new Date();+ await seedIssue({ companyId, issueId, status: "in_progress", assigneeAgentId: originalAgentId });+ await seedScheduledRetryRun({ runId, companyId, agentId: originalAgentId, issueId, now });+ await db.update(issues).set({ executionRunId: runId }).where(eq(issues.id, issueId));++ // Acquire the issue row lock first and hold it until it observes a+ // concurrent `for update` waiter — the promote call below — proving+ // this is a real block, not a race the assertion got lucky on.+ const holderDone = reassignIssueAndLockRunOnceAConcurrentWaiterBlocks(+ issueId,+ runId,+ newAgentId,+ );++ const adapter = createPostgresRunDispatchAdapter(db);+ const outcome = await adapter.promoteOrCancelDueRetry({+ runId,+ companyId,+ now,+ });+ await holderDone;++ // Without the lock, this call would have read the ORIGINAL assignee+ // (captured before the concurrent reassignment committed) and+ // promoted the run. With the lock, it waits for the reassignment to+ // commit, then reads the NEW assignee and cancels instead.+ expect(outcome.outcome).toBe("gate_suppressed");+ if (outcome.outcome === "gate_suppressed") {+ expect(outcome.errorCode).toBe("issue_reassigned");+ }+ const [row] = await db.select({ status: heartbeatRuns.status }).from(heartbeatRuns).where(eq(heartbeatRuns.id, runId));+ expect(row?.status).toBe("cancelled");+ },+ 15_000,+ );+ });+});diff --git a/server/src/modules/run-dispatch/adapters/postgres.ts b/server/src/modules/run-dispatch/adapters/postgres.tsnew file mode 100644index 0000000000..df6fd05d5e--- /dev/null+++ b/server/src/modules/run-dispatch/adapters/postgres.ts@@ -0,0 +1,984 @@+import { and, asc, eq, gte, inArray, lte } from "drizzle-orm";+import type { Db } from "@paperclipai/db";+import {+ agentWakeupRequests,+ agents,+ heartbeatRuns,+ issueRecoveryActions,+ issues,+} from "@paperclipai/db";+import { ISSUE_DISPOSITION_REPAIR_RETRY_REASON } from "@paperclipai/shared";+import { parseObject } from "../../../adapters/utils.js";+import { evaluateAgentInvokabilityFromDb } from "../../../services/agent-invokability.js";+import { budgetService } from "../../../services/budgets.js";+import { isHeartbeatWakeOnDemandEnabled } from "../../../services/heartbeat-policy.js";+import { collectDispositionRepairSourceState } from "../../../services/recovery/disposition-repair.js";+import { appendHeartbeatRunEvent } from "../../../services/heartbeat-run-events.js";+import { emitAgentTaskRun } from "../../../services/agent-task-run-telemetry.js";+import { issueService } from "../../../services/issues.js";+import {+ issueTreeControlService,+ isVerifiedIssueTreeControlInteractionWake,+ ISSUE_TREE_CONTROL_INTERACTION_WAKE_REASONS,+} from "../../../services/issue-tree-control.js";+import {+ continuationSummaryParksExecutor,+ getIssueContinuationSummaryDocument,+} from "../../../services/issue-continuation-summary.js";+import { parseIssueExecutionState } from "../../../services/issue-execution-policy.js";+import { decideQueuedRunStaleness, decideScheduledRetryGate } from "../domain/policy.js";+import type {+ QueuedRunFacts,+ ReviewParticipantFacts,+ RetryReasonKind,+ ScheduledRetryFacts,+} from "../domain/policy.js";+import {+ MAX_TURN_CONTINUATION_RETRY_REASON,+ allowsIssueInteractionWake,+ deriveCommentId,+ isNonAssigneeWorkspaceBusyRetry,+ isResolvedInteractionContinuationWakeContext,+} from "../domain/wake-context.js";+import type {+ CancelStaleQueuedRunInput,+ DispatchResolvedInteractionInput,+ DispatchResolvedInteractionOutcome,+ DueRetryRun,+ EvaluateScheduledRetryGateInput,+ ListDueRetriesInput,+ PromoteOrCancelDueRetryInput,+ RunDispatchWriter,+ ScheduledRetryReader,+} from "../application/ports.js";+import type {+ CancelStaleQueuedRunOutcome,+ PostCommitEffect,+ PromoteScheduledRetryOutcome,+} from "../application/types.js";+import { RunDispatchApplicationError } from "../application/types.js";++type HeartbeatRun = typeof heartbeatRuns.$inferSelect;+type LoadGateFactsInput = {+ runId: string;+ companyId: string;+ agentId: string;+ contextSnapshot: Record<string, unknown>;+ scheduledRetryReason: string | null;+ retryReasonOverride?: string | null;+ wakeupRequestId: string | null;+};+type LoadGateFactsResult =+ | { agentFound: true; facts: ScheduledRetryFacts }+ | { agentFound: false; issueId: string | null };+type LoadStalenessFactsInput = {+ runId: string;+ companyId: string;+ agentId: string;+ issueId: string;+ contextSnapshot: Record<string, unknown>;+ scheduledRetryReason: string | null;+};+type CancelSuppressedRetryInput = {+ runId: string;+ companyId: string;+ now: Date;+ reason: string;+ errorCode: string;+ issueId: string | null;+ details: Record<string, unknown>;+};+type CancelSuppressedRetryResult = { applied: true; run: HeartbeatRun } | { applied: false };++const NO_REVIEW_PARTICIPANT: ReviewParticipantFacts = {+ isInReview: false,+ hasParticipant: false,+ participantIsAgent: false,+ participantAgentId: null,+ currentStageType: null,+ currentParticipant: null,+};++function readNonEmptyString(value: unknown): string | null {+ return typeof value === "string" && value.trim().length > 0 ? value : null;+}++function classifyRetryReasonKind(retryReason: string | null): RetryReasonKind {+ if (retryReason === MAX_TURN_CONTINUATION_RETRY_REASON) return "max_turn_continuation";+ if (retryReason === ISSUE_DISPOSITION_REPAIR_RETRY_REASON) return "disposition_repair";+ return "other";+}++function buildReviewParticipantFacts(input: {+ isInReview: boolean;+ executionState: ReturnType<typeof parseIssueExecutionState>;+}): ReviewParticipantFacts {+ const currentParticipant = input.executionState?.currentParticipant ?? null;+ return {+ isInReview: input.isInReview,+ hasParticipant: currentParticipant !== null,+ participantIsAgent: currentParticipant?.type === "agent",+ participantAgentId:+ currentParticipant?.type === "agent" ? (currentParticipant.agentId ?? null) : null,+ currentStageType: input.executionState?.currentStageType ?? null,+ currentParticipant: currentParticipant as Record<string, unknown> | null,+ };+}++function queuedEffect(run: HeartbeatRun): PostCommitEffect {+ return {+ kind: "run_queued",+ companyId: run.companyId,+ runId: run.id,+ agentId: run.agentId,+ invocationSource: run.invocationSource,+ triggerDetail: run.triggerDetail,+ wakeupRequestId: run.wakeupRequestId,+ };+}++function statusEffect(run: HeartbeatRun, previousStatus: string | null): PostCommitEffect {+ return {+ kind: "run_status_published",+ companyId: run.companyId,+ runId: run.id,+ agentId: run.agentId,+ status: run.status,+ invocationSource: run.invocationSource,+ triggerDetail: run.triggerDetail,+ error: run.error,+ errorCode: run.errorCode,+ startedAt: run.startedAt,+ finishedAt: run.finishedAt,+ result: parseObject(run.resultJson),+ issueId: readNonEmptyString(parseObject(run.contextSnapshot).issueId),+ previousStatus,+ };+}++export function createPostgresRunDispatchAdapter(+ db: Db,+): ScheduledRetryReader & RunDispatchWriter {+ const budgets = budgetService(db);+ const treeControlSvc = issueTreeControlService(db);+ const issuesSvc = issueService(db);++ async function withIssueThenRunLocks<T>(+ input: { runId: string; companyId: string },+ onMissing: () => T,+ operation: (tx: Db, run: HeartbeatRun) => Promise<T>,+ ): Promise<T> {+ // Queue editing and claiming already use issue -> wake -> run. Read the+ // immutable issue reference without a lock first, then acquire issue ->+ // run here as well. Locking the run first can deadlock with a claimant+ // that owns the issue lock and is waiting for the run.+ for (let attempt = 0; attempt < 3; attempt += 1) {+ const hint = await db+ .select({ contextSnapshot: heartbeatRuns.contextSnapshot })+ .from(heartbeatRuns)+ .where(and(eq(heartbeatRuns.id, input.runId), eq(heartbeatRuns.companyId, input.companyId)))+ .then((rows) => rows[0] ?? null);+ if (!hint) return onMissing();+ const hintedIssueId = readNonEmptyString(parseObject(hint.contextSnapshot).issueId);++ const result: { kind: "missing" | "retry" } | { kind: "value"; value: T } =+ await db.transaction(async (tx) => {+ const typedTx = tx as unknown as Db;+ if (hintedIssueId) {+ await typedTx+ .select({ id: issues.id })+ .from(issues)+ .where(and(eq(issues.id, hintedIssueId), eq(issues.companyId, input.companyId)))+ .for("update");+ }++ const run = await typedTx+ .select()+ .from(heartbeatRuns)+ .where(+ and(eq(heartbeatRuns.id, input.runId), eq(heartbeatRuns.companyId, input.companyId)),+ )+ // Keep the run status stable through the semantic decision and any+ // resulting mutation. Adapter-owned work starts only after this+ // transaction releases the lock at the handoff boundary.+ .for("update")+ .then((rows) => rows[0] ?? null);+ if (!run) return { kind: "missing" as const };++ const lockedIssueId = readNonEmptyString(parseObject(run.contextSnapshot).issueId);+ if (lockedIssueId !== hintedIssueId) return { kind: "retry" as const };+ return { kind: "value" as const, value: await operation(typedTx, run) };+ });++ if (result.kind === "missing") return onMissing();+ if (result.kind === "value") return result.value;+ }++ throw new Error(+ `run-dispatch: run ${input.runId} changed issue context repeatedly while acquiring locks`,+ );+ }++ async function loadGateFacts(+ input: LoadGateFactsInput,+ now: Date,+ tx?: unknown,+ ): Promise<LoadGateFactsResult> {+ // Semantic adapter operations pass their transaction here so the fact+ // read and the state transition share one unit of work. This helper is+ // deliberately not exposed through the module's public API.+ const dbOrTx = (tx as Db | undefined) ?? db;+ const budgetsForRead = tx ? budgetService(dbOrTx) : budgets;+ const treeControlForRead = tx ? issueTreeControlService(dbOrTx) : treeControlSvc;+ const issuesSvcForRead = tx ? issueService(dbOrTx) : issuesSvc;++ const agent = await dbOrTx+ .select()+ .from(agents)+ .where(and(eq(agents.id, input.agentId), eq(agents.companyId, input.companyId)))+ .then((rows) => rows[0] ?? null);+ if (!agent) {+ return { agentFound: false, issueId: readNonEmptyString(input.contextSnapshot.issueId) };+ }++ const retryReason =+ input.retryReasonOverride ??+ readNonEmptyString(input.contextSnapshot.retryReason) ??+ input.scheduledRetryReason ??+ null;+ const issueId = readNonEmptyString(input.contextSnapshot.issueId);+ const retryReasonKind = classifyRetryReasonKind(retryReason);++ // Facts fill in through the same rule order `decideScheduledRetryGate`+ // evaluates. A field still awaiting its own read keeps a value that+ // rule never blocks on, EXCEPT `issueFound`, which starts unresolved+ // and gets an explicit early check once the issue read lands — a+ // false default there would look exactly like "the issue is gone" the+ // moment `issueId` is set, before the read that would prove it. Once a+ // group of fields is real, this calls the gate on the facts gathered+ // so far, so a rule an earlier read already decided stops the run+ // before it pays for a later, unrelated read — a sweep of many due+ // retries must not query pause holds or dependencies for a retry a+ // budget block or a stale assignment already suppresses.+ const facts: ScheduledRetryFacts = {+ runId: input.runId,+ runAgentId: input.agentId,+ issueId,+ retryReasonKind,+ enforceIssueExecutionLock: retryReasonKind === "max_turn_continuation",+ isNonAssigneeWorkspaceBusyRetry: isNonAssigneeWorkspaceBusyRetry(retryReason, input.contextSnapshot),+ budgetBlock: null,+ agentInvokable: true,+ agentInvokabilityDetails: {},+ agentInvokabilityInvalidOrgChain: false,+ heartbeatWakeOnDemandEnabled: true,+ issueFound: false,+ issueStatus: null,+ issueAssigneeAgentId: null,+ issueExecutionRunId: null,+ reviewParticipant: NO_REVIEW_PARTICIPANT,+ activePauseHold: null,+ dependenciesBlocked: null,+ dispositionRepair: null,+ };+ const isBlocked = () => !decideScheduledRetryGate(facts, now).allowed;++ const budgetBlock = await budgetsForRead.getInvocationBlock(input.companyId, input.agentId, {+ issueId,+ projectId: readNonEmptyString(input.contextSnapshot.projectId),+ });+ facts.budgetBlock = budgetBlock+ ? { reason: budgetBlock.reason, scopeType: budgetBlock.scopeType, scopeId: budgetBlock.scopeId }+ : null;+ if (facts.budgetBlock) return { agentFound: true, facts };++ const agentInvokability = await evaluateAgentInvokabilityFromDb(dbOrTx, agent);+ facts.agentInvokable = agentInvokability.invokable;+ facts.agentInvokabilityDetails = agentInvokability.invokable ? {} : agentInvokability.details;+ facts.agentInvokabilityInvalidOrgChain = agentInvokability.invokable+ ? false+ : agentInvokability.invalidOrgChain;+ if (!facts.agentInvokable) return { agentFound: true, facts };++ facts.heartbeatWakeOnDemandEnabled = isHeartbeatWakeOnDemandEnabled(agent);+ if (!facts.heartbeatWakeOnDemandEnabled) return { agentFound: true, facts };++ if (!issueId) return { agentFound: true, facts };++ const issueQuery = dbOrTx+ .select({+ id: issues.id,+ companyId: issues.companyId,+ status: issues.status,+ assigneeAgentId: issues.assigneeAgentId,+ assigneeUserId: issues.assigneeUserId,+ executionRunId: issues.executionRunId,+ executionPolicy: issues.executionPolicy,+ executionState: issues.executionState,+ monitorNextCheckAt: issues.monitorNextCheckAt,+ })+ .from(issues)+ .where(and(eq(issues.id, issueId), eq(issues.companyId, input.companyId)));+ // Locking the row here, only when a caller opened a transaction for the+ // promote-or-cancel write, is what makes that write's decision hold: a+ // concurrent reassignment, pause, or status change blocks on this lock+ // instead of landing between this read and that write.+ const issue = await (tx ? issueQuery.for("update") : issueQuery).then(+ (rows) => rows[0] ?? null,+ );++ facts.issueFound = issue !== null;+ if (!facts.issueFound) return { agentFound: true, facts };++ facts.issueStatus = issue.status;+ facts.issueAssigneeAgentId = issue.assigneeAgentId;+ facts.issueExecutionRunId = issue.executionRunId;+ facts.reviewParticipant = buildReviewParticipantFacts({+ isInReview: issue.status === "in_review",+ executionState: parseIssueExecutionState(issue.executionState),+ });++ // The gate checks a disposition repair's own supersession before it+ // checks ownership or status, so this read must land before the next+ // isBlocked() call — checking isBlocked() first would report the wrong+ // suppression reason for a superseded repair.+ if (retryReasonKind === "disposition_repair") {+ const expectedFingerprint = readNonEmptyString(input.contextSnapshot.dispositionRepairFingerprint);+ const sourceState = await collectDispositionRepairSourceState(dbOrTx, {+ issue,+ excludeRunId: input.runId,+ excludeWakeupRequestId: input.wakeupRequestId,+ });+ facts.dispositionRepair = {+ expectedFingerprintPresent: expectedFingerprint !== null,+ fingerprintMatches: sourceState.fingerprint === expectedFingerprint,+ hasActiveExecutionPath: sourceState.hasActiveExecutionPath,+ hasDurableWaitingPath: sourceState.hasDurableWaitingPath,+ expectedFingerprint,+ currentFingerprint: sourceState.fingerprint,+ durablePathReason: sourceState.durablePathReason,+ };+ }+ if (isBlocked()) return { agentFound: true, facts };++ const activePauseHold = await treeControlForRead.getActivePauseHoldGate(input.companyId, issueId);+ facts.activePauseHold = activePauseHold+ ? { holdId: activePauseHold.holdId, rootIssueId: activePauseHold.rootIssueId }+ : null;+ if (isBlocked()) return { agentFound: true, facts };++ const dependencyReadiness = await issuesSvcForRead.listDependencyReadiness(input.companyId, [issueId]);+ const readiness = dependencyReadiness.get(issueId);+ facts.dependenciesBlocked =+ readiness && !readiness.isDependencyReady+ ? {+ unresolvedBlockerIssueIds: readiness.unresolvedBlockerIssueIds,+ unresolvedBlockerCount: readiness.unresolvedBlockerCount,+ }+ : null;++ return { agentFound: true, facts };+ }++ async function evaluateScheduledRetryGate(input: EvaluateScheduledRetryGateInput) {+ const run = await db+ .select()+ .from(heartbeatRuns)+ .where(and(eq(heartbeatRuns.id, input.runId), eq(heartbeatRuns.companyId, input.companyId)))+ .then((rows) => rows[0] ?? null);+ if (!run) {+ throw new RunDispatchApplicationError(+ "run_not_found",+ `run-dispatch: run ${input.runId} was not found while evaluating retry eligibility`,+ );+ }+ const factsResult = await loadGateFacts(+ {+ runId: run.id,+ companyId: run.companyId,+ agentId: run.agentId,+ contextSnapshot: parseObject(run.contextSnapshot),+ scheduledRetryReason: run.scheduledRetryReason,+ retryReasonOverride: input.retryReasonOverride,+ wakeupRequestId: run.wakeupRequestId,+ },+ input.now,+ );+ if (!factsResult.agentFound) {+ return {+ allowed: false as const,+ reason: "Scheduled retry suppressed because the agent no longer exists",+ errorCode: "agent_not_invokable" as const,+ issueId: factsResult.issueId,+ details: { agentId: run.agentId },+ };+ }+ return decideScheduledRetryGate(factsResult.facts, input.now);+ }++ async function listDueRetries(input: ListDueRetriesInput): Promise<DueRetryRun[]> {+ const rows = await db+ .select()+ .from(heartbeatRuns)+ .where(+ and(+ eq(heartbeatRuns.status, "scheduled_retry"),+ lte(heartbeatRuns.scheduledRetryAt, input.now),+ input.cutoff ? gte(heartbeatRuns.createdAt, input.cutoff) : undefined,+ ),+ )+ .orderBy(+ asc(heartbeatRuns.scheduledRetryAt),+ asc(heartbeatRuns.createdAt),+ asc(heartbeatRuns.id),+ )+ .limit(input.limit);++ return rows.map((row) => ({+ runId: row.id,+ companyId: row.companyId,+ }));+ }++ async function loadStalenessFacts(+ input: LoadStalenessFactsInput,+ _now: Date,+ tx?: unknown,+ ): Promise<QueuedRunFacts> {+ const dbOrTx = (tx as Db | undefined) ?? db;+ const issueId = input.issueId;+ const context = input.contextSnapshot;++ const issueQuery = dbOrTx+ .select({+ id: issues.id,+ status: issues.status,+ assigneeAgentId: issues.assigneeAgentId,+ executionRunId: issues.executionRunId,+ executionState: issues.executionState,+ })+ .from(issues)+ .where(and(eq(issues.id, issueId), eq(issues.companyId, input.companyId)));+ const issue = await (tx ? issueQuery.for("update") : issueQuery).then(+ (rows) => rows[0] ?? null,+ );++ const wakeCommentId = deriveCommentId(context);+ const isInteractionWake = allowsIssueInteractionWake(+ context,+ ISSUE_TREE_CONTROL_INTERACTION_WAKE_REASONS,+ );+ const resumeIntent = context.resumeIntent === true || context.followUpRequested === true;+ const wakeReason = readNonEmptyString(context.wakeReason);+ const retryReason =+ readNonEmptyString(context.retryReason) ?? input.scheduledRetryReason ?? null;+ const interactionResolvedAt = readNonEmptyString(context.interactionResolvedAt);+ const hasResolvedInteractionEvidence =+ interactionResolvedAt !== null && !Number.isNaN(Date.parse(interactionResolvedAt));+ const isResolvedInteractionContinuation = isResolvedInteractionContinuationWakeContext(context);++ const continuationParkApplies = Boolean(+ issue &&+ issue.status === "in_progress" &&+ !wakeCommentId &&+ !hasResolvedInteractionEvidence &&+ (wakeReason === "issue_continuation_needed" || retryReason === "issue_continuation_needed"),+ );+ let continuationSummaryBody: string | null = null;+ let continuationParksExecutor = false;+ if (continuationParkApplies) {+ const queuedWake = parseObject(context.paperclipWake);+ const queuedContinuationSummary =+ readNonEmptyString(parseObject(context.paperclipContinuationSummary).body) ??+ readNonEmptyString(parseObject(queuedWake.continuationSummary).body);+ const currentContinuationSummary = queuedContinuationSummary+ ? null+ : await getIssueContinuationSummaryDocument(dbOrTx, issueId);+ continuationSummaryBody = queuedContinuationSummary ?? currentContinuationSummary?.body ?? null;+ continuationParksExecutor = continuationSummaryParksExecutor(continuationSummaryBody);+ }++ const recoveryActionId = readNonEmptyString(context.recoveryActionId);+ const isAuthorizedSourceScopedRecovery =+ issue && wakeReason === "source_scoped_recovery_action" && recoveryActionId+ ? await dbOrTx+ .select({ id: issueRecoveryActions.id })+ .from(issueRecoveryActions)+ .where(+ and(+ eq(issueRecoveryActions.id, recoveryActionId),+ eq(issueRecoveryActions.companyId, input.companyId),+ eq(issueRecoveryActions.sourceIssueId, issue.id),+ eq(issueRecoveryActions.ownerAgentId, input.agentId),+ inArray(issueRecoveryActions.status, ["active", "escalated"]),+ ),+ )+ .limit(1)+ .then((rows) => Boolean(rows[0]))+ : false;++ return {+ runId: input.runId,+ runAgentId: input.agentId,+ issueId,+ retryReasonKind: classifyRetryReasonKind(retryReason),+ issueFound: issue !== null,+ issueStatus: issue?.status ?? null,+ issueAssigneeAgentId: issue?.assigneeAgentId ?? null,+ issueExecutionRunId: issue?.executionRunId ?? null,+ isResolvedInteractionContinuation,+ isInteractionWake,+ isAuthorizedSourceScopedRecovery,+ isNonAssigneeWorkspaceBusyRetry: isNonAssigneeWorkspaceBusyRetry(retryReason, context),+ resumeIntent,+ wakeCommentIdPresent: Boolean(wakeCommentId),+ continuationParkApplies,+ continuationParksExecutor,+ continuationSummaryBody,+ wakeReason,+ retryReason,+ reviewParticipant: issue+ ? buildReviewParticipantFacts({+ isInReview: issue.status === "in_review",+ executionState: issue.status === "in_review" ? parseIssueExecutionState(issue.executionState) : null,+ })+ : NO_REVIEW_PARTICIPANT,+ };+ }++ async function promoteDueRetryInTx(+ tx: Db,+ input: PromoteOrCancelDueRetryInput,+ ): Promise<+ | { applied: true; run: HeartbeatRun; postCommitEffects: PostCommitEffect[] }+ | { applied: false }+ > {+ const [row] = await tx+ .update(heartbeatRuns)+ .set({ status: "queued", updatedAt: input.now })+ .where(+ and(+ eq(heartbeatRuns.id, input.runId),+ eq(heartbeatRuns.companyId, input.companyId),+ eq(heartbeatRuns.status, "scheduled_retry"),+ lte(heartbeatRuns.scheduledRetryAt, input.now),+ ),+ )+ .returning();+ if (!row) return { applied: false };++ await appendHeartbeatRunEvent(tx as unknown as Db, {+ companyId: row.companyId,+ runId: row.id,+ agentId: row.agentId,+ eventType: "lifecycle",+ stream: "system",+ level: "info",+ message: "Scheduled retry became due and was promoted to the queued run pool",+ payload: {+ scheduledRetryAttempt: row.scheduledRetryAttempt,+ scheduledRetryAt: row.scheduledRetryAt ? new Date(row.scheduledRetryAt).toISOString() : null,+ scheduledRetryReason: row.scheduledRetryReason,+ },+ });++ return { applied: true as const, run: row, postCommitEffects: [queuedEffect(row)] };+ }++ async function cancelSuppressedRetryInTx(+ tx: Db,+ input: CancelSuppressedRetryInput,+ ): Promise<CancelSuppressedRetryResult> {+ const [row] = await tx+ .update(heartbeatRuns)+ .set({+ status: "cancelled",+ finishedAt: input.now,+ error: input.reason,+ errorCode: input.errorCode,+ updatedAt: input.now,+ })+ .where(+ and(+ eq(heartbeatRuns.id, input.runId),+ eq(heartbeatRuns.companyId, input.companyId),+ eq(heartbeatRuns.status, "scheduled_retry"),+ lte(heartbeatRuns.scheduledRetryAt, input.now),+ ),+ )+ .returning();+ if (!row) return { applied: false };++ if (row.wakeupRequestId) {+ await tx+ .update(agentWakeupRequests)+ .set({ status: "cancelled", finishedAt: input.now, error: input.reason, updatedAt: input.now })+ .where(+ and(+ eq(agentWakeupRequests.id, row.wakeupRequestId),+ eq(agentWakeupRequests.companyId, row.companyId),+ ),+ );+ }++ if (input.issueId) {+ await tx+ .update(issues)+ .set({+ executionRunId: null,+ executionAgentNameKey: null,+ executionLockedAt: null,+ updatedAt: input.now,+ })+ .where(+ and(+ eq(issues.companyId, row.companyId),+ eq(issues.id, input.issueId),+ eq(issues.executionRunId, row.id),+ ),+ );+ }++ await appendHeartbeatRunEvent(tx as unknown as Db, {+ companyId: row.companyId,+ runId: row.id,+ agentId: row.agentId,+ eventType: "lifecycle",+ stream: "system",+ level: "warn",+ message: input.reason,+ payload: {+ ...input.details,+ scheduledRetryAttempt: row.scheduledRetryAttempt,+ scheduledRetryAt: row.scheduledRetryAt ? new Date(row.scheduledRetryAt).toISOString() : null,+ scheduledRetryReason: row.scheduledRetryReason,+ },+ });++ return { applied: true, run: row };+ }++ async function promoteOrCancelDueRetry(+ input: PromoteOrCancelDueRetryInput,+ ): Promise<PromoteScheduledRetryOutcome> {+ const now = input.now;++ const promoteLockedRun = async (tx: Db, run: HeartbeatRun) => {+ if (+ run.status !== "scheduled_retry" ||+ !run.scheduledRetryAt ||+ new Date(run.scheduledRetryAt).getTime() > now.getTime()+ ) {+ return { outcome: { outcome: "not_promoted" as const }, telemetryRun: null };+ }+ const factsResult = await loadGateFacts(+ {+ runId: run.id,+ companyId: run.companyId,+ agentId: run.agentId,+ contextSnapshot: parseObject(run.contextSnapshot),+ scheduledRetryReason: run.scheduledRetryReason,+ retryReasonOverride: run.scheduledRetryReason,+ wakeupRequestId: run.wakeupRequestId,+ },+ now,+ tx,+ );++ if (!factsResult.agentFound) {+ const cancelled = await cancelSuppressedRetryInTx(tx as unknown as Db, {+ runId: input.runId,+ companyId: input.companyId,+ now,+ reason: "Scheduled retry suppressed because the agent no longer exists",+ errorCode: "agent_not_invokable",+ issueId: factsResult.issueId,+ details: { agentId: run.agentId },+ });+ return cancelled.applied+ ? {+ outcome: {+ outcome: "gate_suppressed" as const,+ reason: "Scheduled retry suppressed because the agent no longer exists",+ errorCode: "agent_not_invokable" as const,+ },+ telemetryRun: cancelled.run,+ }+ : { outcome: { outcome: "not_promoted" as const }, telemetryRun: null };+ }++ const gate = decideScheduledRetryGate(factsResult.facts, now);++ // Preserve legacy transient retry behavior for runs that only carry a+ // loose task context rather than a persisted issue row: a missing+ // issue suppresses a max-turn continuation, but every other retry+ // reason proceeds to promotion anyway.+ const isLegacyMissingIssueException =+ !gate.allowed &&+ gate.errorCode === "issue_not_found" &&+ factsResult.facts.retryReasonKind !== "max_turn_continuation";++ if (!gate.allowed && !isLegacyMissingIssueException) {+ const cancelled = await cancelSuppressedRetryInTx(tx as unknown as Db, {+ runId: input.runId,+ companyId: input.companyId,+ now,+ reason: gate.reason,+ errorCode: gate.errorCode,+ issueId: gate.issueId,+ details: gate.details,+ });+ return cancelled.applied+ ? {+ outcome: {+ outcome: "gate_suppressed" as const,+ reason: gate.reason,+ errorCode: gate.errorCode,+ },+ telemetryRun: cancelled.run,+ }+ : { outcome: { outcome: "not_promoted" as const }, telemetryRun: null };+ }++ const promoted = await promoteDueRetryInTx(tx as unknown as Db, {+ runId: input.runId,+ companyId: input.companyId,+ now,+ });+ return promoted.applied+ ? {+ outcome: {+ outcome: "promoted" as const,+ postCommitEffects: promoted.postCommitEffects,+ },+ telemetryRun: null,+ }+ : { outcome: { outcome: "not_promoted" as const }, telemetryRun: null };+ };+ const transactionResult = await withIssueThenRunLocks(+ input,+ () => ({ outcome: { outcome: "not_promoted" as const }, telemetryRun: null }),+ promoteLockedRun,+ );++ // Telemetry is best-effort background work; fire it only after the+ // transaction above has committed, so a suppressed retry is never+ // published before its cancellation is durable, and never published at+ // all if the transaction rolled back.+ if (transactionResult.telemetryRun) {+ void emitAgentTaskRun(db, transactionResult.telemetryRun);+ }++ return transactionResult.outcome;+ }++ async function cancelStaleRunInTx(+ tx: Db,+ run: HeartbeatRun,+ issueId: string,+ decision: Extract<ReturnType<typeof decideQueuedRunStaleness>, { stale: true }>,+ expectedStatus: "queued" | "running",+ now: Date,+ ): Promise<CancelStaleQueuedRunOutcome> {+ const [row] = await tx+ .update(heartbeatRuns)+ .set({+ status: "cancelled",+ finishedAt: now,+ error: decision.reason,+ errorCode: decision.errorCode,+ resultJson: {+ ...parseObject(run.resultJson),+ stopReason: decision.errorCode,+ effectiveTimeoutSec: 0,+ timeoutConfigured: false,+ timeoutSource: "stale_queued_run_gate",+ timeoutFired: false,+ },+ updatedAt: now,+ })+ .where(+ and(+ eq(heartbeatRuns.id, run.id),+ eq(heartbeatRuns.companyId, run.companyId),+ eq(heartbeatRuns.status, expectedStatus),+ ),+ )+ .returning();+ // A concurrent claimant or canceller already moved the run off+ // `expectedStatus`: the caller's staleness decision lost the race, so+ // this write must not overwrite whatever status won it.+ if (!row) return { outcome: "lost_race" };++ if (row.wakeupRequestId) {+ await tx+ .update(agentWakeupRequests)+ .set({ status: "skipped", finishedAt: now, error: decision.reason, updatedAt: now })+ .where(+ and(+ eq(agentWakeupRequests.id, row.wakeupRequestId),+ eq(agentWakeupRequests.companyId, row.companyId),+ ),+ );+ }++ await tx+ .update(issues)+ .set({+ executionRunId: null,+ executionAgentNameKey: null,+ executionLockedAt: null,+ updatedAt: now,+ })+ .where(+ and(+ eq(issues.companyId, row.companyId),+ eq(issues.id, issueId),+ eq(issues.executionRunId, row.id),+ ),+ );++ await appendHeartbeatRunEvent(tx as unknown as Db, {+ companyId: row.companyId,+ runId: row.id,+ agentId: row.agentId,+ eventType: "lifecycle",+ stream: "system",+ level: "warn",+ message: decision.reason,+ payload: decision.details,+ });++ return {+ outcome: "cancelled",+ reason: decision.reason,+ errorCode: decision.errorCode,+ postCommitEffects: [statusEffect(row, expectedStatus)],+ };+ }++ async function decideCurrentRunStaleness(tx: Db, run: HeartbeatRun, now: Date) {+ const contextSnapshot = parseObject(run.contextSnapshot);+ const issueId = readNonEmptyString(contextSnapshot.issueId);+ if (!issueId) return { issueId: null, decision: { stale: false as const } };+ const facts = await loadStalenessFacts(+ {+ runId: run.id,+ companyId: run.companyId,+ agentId: run.agentId,+ issueId,+ contextSnapshot,+ scheduledRetryReason: run.scheduledRetryReason,+ },+ now,+ tx,+ );+ return { issueId, decision: decideQueuedRunStaleness(facts, now) };+ }++ async function cancelStaleQueuedRun(+ input: CancelStaleQueuedRunInput,+ ): Promise<CancelStaleQueuedRunOutcome> {+ const cancelLockedRun = async (tx: Db, run: HeartbeatRun) => {+ if (run.status !== input.expectedStatus) return { outcome: "lost_race" as const };+ const { issueId, decision } = await decideCurrentRunStaleness(tx, run, input.now);+ if (!decision.stale || !issueId) return { outcome: "not_stale" as const };+ return cancelStaleRunInTx(tx, run, issueId, decision, input.expectedStatus, input.now);+ };++ return withIssueThenRunLocks(+ input,+ () => {+ throw new RunDispatchApplicationError(+ "run_not_found",+ `run-dispatch: run ${input.runId} disappeared during stale-run validation`,+ );+ },+ cancelLockedRun,+ );+ }++ async function dispatchResolvedInteractionIfCurrent<T>(+ input: DispatchResolvedInteractionInput<T>,+ ): Promise<DispatchResolvedInteractionOutcome<T>> {+ const dispatchLockedRun = async (tx: Db, run: HeartbeatRun) => {+ if (run.status !== input.expectedStatus) {+ return { dispatched: false as const, cancellation: { outcome: "lost_race" as const } };+ }+ const { issueId, decision: initialDecision } = await decideCurrentRunStaleness(+ tx,+ run,+ input.now,+ );+ const decision =+ !initialDecision.stale && issueId+ ? await tx+ .select({ executionRunId: issues.executionRunId })+ .from(issues)+ .where(and(eq(issues.id, issueId), eq(issues.companyId, run.companyId)))+ .then((rows) => rows[0] ?? null)+ .then((issue) =>+ issue?.executionRunId === run.id+ ? initialDecision+ : {+ stale: true as const,+ errorCode: "issue_execution_lock_changed" as const,+ reason:+ "Cancelled because resolved-interaction continuation no longer owns the issue execution lock before adapter dispatch",+ details: {+ issueId,+ expectedExecutionRunId: run.id,+ currentExecutionRunId: issue?.executionRunId ?? null,+ },+ },+ )+ : initialDecision;++ if (decision.stale && issueId) {+ const cancellation = await cancelStaleRunInTx(+ tx,+ run,+ issueId,+ decision,+ input.expectedStatus,+ input.now,+ );+ return { dispatched: false as const, cancellation };+ }++ let dispatchStarted = false;+ let resolveDispatchStarted!: () => void;+ const dispatchStartedPromise = new Promise<void>((resolve) => {+ resolveDispatchStarted = resolve;+ });+ const markDispatchStarted = () => {+ if (dispatchStarted) return;+ dispatchStarted = true;+ resolveDispatchStarted();+ };+ const resultPromise = input.dispatch(markDispatchStarted);+ void resultPromise.then(markDispatchStarted, markDispatchStarted);+ await dispatchStartedPromise;+ return { dispatched: true as const, resultPromise };+ };++ return withIssueThenRunLocks(+ input,+ () => {+ throw new RunDispatchApplicationError(+ "run_not_found",+ `run-dispatch: run ${input.runId} disappeared before resolved-interaction dispatch`,+ );+ },+ dispatchLockedRun,+ );+ }++ return {+ evaluateScheduledRetryGate,+ listDueRetries,+ cancelStaleQueuedRun,+ dispatchResolvedInteractionIfCurrent,+ promoteOrCancelDueRetry,+ };+}diff --git a/server/src/modules/run-dispatch/application/ports.ts b/server/src/modules/run-dispatch/application/ports.tsnew file mode 100644index 0000000000..799eba5686--- /dev/null+++ b/server/src/modules/run-dispatch/application/ports.ts@@ -0,0 +1,59 @@+import type { GateDecision } from "../domain/policy.js";+import type {+ CancelStaleQueuedRunOutcome,+ PromoteScheduledRetryOutcome,+} from "./types.js";++export type DueRetryRun = {+ runId: string;+ companyId: string;+};++export type ListDueRetriesInput = {+ now: Date;+ cutoff: Date | null;+ limit: number;+};++export type EvaluateScheduledRetryGateInput = {+ runId: string;+ companyId: string;+ retryReasonOverride: string;+ now: Date;+};++/** Read-only scheduled-retry operations exposed to application use cases. */+export interface ScheduledRetryReader {+ evaluateScheduledRetryGate(input: EvaluateScheduledRetryGateInput): Promise<GateDecision>;+ listDueRetries(input: ListDueRetriesInput): Promise<DueRetryRun[]>;+}++export type PromoteOrCancelDueRetryInput = {+ runId: string;+ companyId: string;+ now: Date;+};++export type CancelStaleQueuedRunInput = {+ runId: string;+ companyId: string;+ now: Date;+ expectedStatus: "queued" | "running";+};++export type DispatchResolvedInteractionInput<T> = CancelStaleQueuedRunInput & {+ dispatch: (markDispatchStarted: () => void) => Promise<T>;+};++export type DispatchResolvedInteractionOutcome<T> =+ | { dispatched: true; resultPromise: Promise<T> }+ | { dispatched: false; cancellation: CancelStaleQueuedRunOutcome };++/** Semantic database operations; persistence rows and transaction handles stay inside the adapter. */+export interface RunDispatchWriter {+ promoteOrCancelDueRetry(input: PromoteOrCancelDueRetryInput): Promise<PromoteScheduledRetryOutcome>;+ cancelStaleQueuedRun(input: CancelStaleQueuedRunInput): Promise<CancelStaleQueuedRunOutcome>;+ dispatchResolvedInteractionIfCurrent<T>(+ input: DispatchResolvedInteractionInput<T>,+ ): Promise<DispatchResolvedInteractionOutcome<T>>;+}diff --git a/server/src/modules/run-dispatch/application/types.ts b/server/src/modules/run-dispatch/application/types.tsnew file mode 100644index 0000000000..c91d333533--- /dev/null+++ b/server/src/modules/run-dispatch/application/types.ts@@ -0,0 +1,66 @@+import type {+ QueuedRunStalenessErrorCode,+ ScheduledRetryGateErrorCode,+} from "../domain/policy.js";++export type QueuedRunEvent = {+ kind: "run_queued";+ companyId: string;+ runId: string;+ agentId: string;+ invocationSource: string;+ triggerDetail: string | null;+ wakeupRequestId: string | null;+};++export type RunStatusEvent = {+ kind: "run_status_published";+ companyId: string;+ runId: string;+ agentId: string;+ status: string;+ invocationSource: string;+ triggerDetail: string | null;+ error: string | null;+ errorCode: string | null;+ startedAt: Date | null;+ finishedAt: Date | null;+ result: Record<string, unknown>;+ issueId: string | null;+ previousStatus: string | null;+};++/** Explicit event payloads a caller publishes after the semantic transaction commits. */+export type PostCommitEffect = QueuedRunEvent | RunStatusEvent;++export type PromoteScheduledRetryOutcome =+ | { outcome: "promoted"; postCommitEffects: PostCommitEffect[] }+ | {+ outcome: "gate_suppressed";+ reason: string;+ errorCode: ScheduledRetryGateErrorCode;+ }+ | { outcome: "not_promoted" };++export type CancelStaleQueuedRunOutcome =+ | { outcome: "not_stale" }+ /** The run's status no longer matched the phase the caller expected; a concurrent writer already won. */+ | { outcome: "lost_race" }+ | {+ outcome: "cancelled";+ reason: string;+ errorCode: QueuedRunStalenessErrorCode;+ postCommitEffects: PostCommitEffect[];+ };++export type RunDispatchApplicationErrorCode = "run_not_found";++export class RunDispatchApplicationError extends Error {+ constructor(+ readonly code: RunDispatchApplicationErrorCode,+ message: string,+ ) {+ super(message);+ this.name = "RunDispatchApplicationError";+ }+}diff --git a/server/src/modules/run-dispatch/application/use-cases.test.ts b/server/src/modules/run-dispatch/application/use-cases.test.tsnew file mode 100644index 0000000000..0992a63969--- /dev/null+++ b/server/src/modules/run-dispatch/application/use-cases.test.ts@@ -0,0 +1,170 @@+import { describe, expect, it, vi } from "vitest";+import {+ createCancelStaleQueuedRun,+ createDispatchResolvedInteractionIfCurrent,+ createEvaluateScheduledRetryGate,+ createPromoteDueScheduledRetries,+ createPromoteScheduledRetry,+} from "./use-cases.js";+import type { DueRetryRun, RunDispatchWriter, ScheduledRetryReader } from "./ports.js";++function fakeReader(dueRuns: DueRetryRun[] = []): ScheduledRetryReader & { evaluateCalls: unknown[] } {+ const evaluateCalls: unknown[] = [];+ return {+ evaluateCalls,+ async evaluateScheduledRetryGate(input) {+ evaluateCalls.push(input);+ return { allowed: true };+ },+ async listDueRetries() {+ return dueRuns;+ },+ };+}++function fakeWriter(overrides: Partial<RunDispatchWriter> = {}): RunDispatchWriter & {+ promoteCalls: unknown[];+ cancelCalls: unknown[];+ dispatchCalls: unknown[];+} {+ const promoteCalls: unknown[] = [];+ const cancelCalls: unknown[] = [];+ const dispatchCalls: unknown[] = [];+ return {+ promoteCalls,+ cancelCalls,+ dispatchCalls,+ async promoteOrCancelDueRetry(input) {+ promoteCalls.push(input);+ return { outcome: "promoted", postCommitEffects: [] };+ },+ async cancelStaleQueuedRun(input) {+ cancelCalls.push(input);+ return { outcome: "not_stale" };+ },+ async dispatchResolvedInteractionIfCurrent(input) {+ dispatchCalls.push(input);+ return { dispatched: true, resultPromise: input.dispatch(() => {}) };+ },+ ...overrides,+ };+}++describe("createEvaluateScheduledRetryGate", () => {+ it("maps identifiers and a default clock onto the semantic reader operation", async () => {+ const reader = fakeReader();+ const before = Date.now();+ const result = await createEvaluateScheduledRetryGate({ reader })({+ runId: "run-1",+ companyId: "company-1",+ retryReasonOverride: "max_turns_continuation",+ });++ expect(result).toEqual({ allowed: true });+ expect(reader.evaluateCalls).toHaveLength(1);+ const call = reader.evaluateCalls[0] as { now: Date };+ expect(call).toMatchObject({+ runId: "run-1",+ companyId: "company-1",+ retryReasonOverride: "max_turns_continuation",+ });+ expect(call.now.getTime()).toBeGreaterThanOrEqual(before);+ });+});++describe("createPromoteScheduledRetry", () => {+ it("passes only semantic identifiers and the clock to the atomic operation", async () => {+ const writer = fakeWriter();+ const now = new Date("2026-01-01T00:00:00.000Z");+ const result = await createPromoteScheduledRetry({ writer })({+ runId: "run-1",+ companyId: "company-1",+ now,+ });++ expect(result).toEqual({ outcome: "promoted", postCommitEffects: [] });+ expect(writer.promoteCalls).toEqual([{ runId: "run-1", companyId: "company-1", now }]);+ });++ it("passes a gate-suppressed outcome through without a persistence row", async () => {+ const writer = fakeWriter({+ promoteOrCancelDueRetry: vi.fn(async () => ({+ outcome: "gate_suppressed" as const,+ reason: "agent paused",+ errorCode: "agent_not_invokable" as const,+ })),+ });+ const result = await createPromoteScheduledRetry({ writer })({+ runId: "run-1",+ companyId: "company-1",+ });+ expect(result).toEqual({+ outcome: "gate_suppressed",+ reason: "agent paused",+ errorCode: "agent_not_invokable",+ });+ });+});++describe("createPromoteDueScheduledRetries", () => {+ it("keeps due order and caps a sweep at 50 runs", async () => {+ const dueRuns = Array.from({ length: 75 }, (_, i) => ({+ runId: `run-${i}`,+ companyId: "company-1",+ }));+ const reader = fakeReader(dueRuns);+ const writer = fakeWriter();+ const result = await createPromoteDueScheduledRetries({+ reader,+ promoteScheduledRetry: createPromoteScheduledRetry({ writer }),+ })({ cutoff: null });++ expect(result.promoted).toBe(50);+ expect(result.runIds).toEqual(dueRuns.slice(0, 50).map(({ runId }) => runId));+ });+});++describe("createCancelStaleQueuedRun", () => {+ it("delegates the complete read-decide-cancel operation to the writer", async () => {+ const cancelStaleQueuedRun = vi.fn(async () => ({+ outcome: "cancelled" as const,+ reason: "issue reassigned",+ errorCode: "issue_assignee_changed" as const,+ postCommitEffects: [],+ }));+ const writer = fakeWriter({+ cancelStaleQueuedRun,+ });+ const now = new Date("2026-01-01T00:00:00.000Z");+ const result = await createCancelStaleQueuedRun({ writer })({+ runId: "run-1",+ companyId: "company-1",+ expectedStatus: "queued",+ now,+ });++ expect(result.outcome).toBe("cancelled");+ expect(cancelStaleQueuedRun).toHaveBeenCalledWith({+ runId: "run-1",+ companyId: "company-1",+ expectedStatus: "queued",+ now,+ });+ });+});++describe("createDispatchResolvedInteractionIfCurrent", () => {+ it("delegates the lock, validation, cancellation, and dispatch boundary", async () => {+ const writer = fakeWriter();+ const dispatch = vi.fn(async () => "started");+ const result = await createDispatchResolvedInteractionIfCurrent({ writer })({+ runId: "run-1",+ companyId: "company-1",+ expectedStatus: "running",+ dispatch,+ });++ expect(result.dispatched).toBe(true);+ expect(writer.dispatchCalls).toHaveLength(1);+ });+});diff --git a/server/src/modules/run-dispatch/application/use-cases.ts b/server/src/modules/run-dispatch/application/use-cases.tsnew file mode 100644index 0000000000..fda09062e5--- /dev/null+++ b/server/src/modules/run-dispatch/application/use-cases.ts@@ -0,0 +1,71 @@+import type { RunDispatchWriter, ScheduledRetryReader } from "./ports.js";+import type { PostCommitEffect, PromoteScheduledRetryOutcome } from "./types.js";++export function createEvaluateScheduledRetryGate(deps: { reader: ScheduledRetryReader }) {+ return (input: {+ runId: string;+ companyId: string;+ retryReasonOverride: string;+ now?: Date;+ }) => deps.reader.evaluateScheduledRetryGate({ ...input, now: input.now ?? new Date() });+}++export function createPromoteScheduledRetry(deps: { writer: RunDispatchWriter }) {+ return (input: {+ runId: string;+ companyId: string;+ now?: Date;+ }): Promise<PromoteScheduledRetryOutcome> =>+ deps.writer.promoteOrCancelDueRetry({+ runId: input.runId,+ companyId: input.companyId,+ now: input.now ?? new Date(),+ });+}++const MAX_DUE_RETRIES_PER_SWEEP = 50;++export function createPromoteDueScheduledRetries(deps: {+ reader: ScheduledRetryReader;+ promoteScheduledRetry: ReturnType<typeof createPromoteScheduledRetry>;+}) {+ return async function promoteDueScheduledRetries(input: { now?: Date; cutoff: Date | null }) {+ const now = input.now ?? new Date();+ const dueRuns = (+ await deps.reader.listDueRetries({ now, cutoff: input.cutoff, limit: MAX_DUE_RETRIES_PER_SWEEP })+ ).slice(0, MAX_DUE_RETRIES_PER_SWEEP);+ const runIds: string[] = [];+ const postCommitEffects: PostCommitEffect[] = [];++ for (const dueRun of dueRuns) {+ const result = await deps.promoteScheduledRetry({ ...dueRun, now });+ if (result.outcome !== "promoted") continue;+ runIds.push(dueRun.runId);+ postCommitEffects.push(...result.postCommitEffects);+ }++ return { promoted: runIds.length, runIds, postCommitEffects };+ };+}++export function createCancelStaleQueuedRun(deps: { writer: RunDispatchWriter }) {+ return (input: {+ runId: string;+ companyId: string;+ expectedStatus: "queued" | "running";+ now?: Date;+ }) => deps.writer.cancelStaleQueuedRun({ ...input, now: input.now ?? new Date() });+}++export function createDispatchResolvedInteractionIfCurrent(deps: { writer: RunDispatchWriter }) {+ return <T>(input: {+ runId: string;+ companyId: string;+ expectedStatus: "queued" | "running";+ dispatch: (markDispatchStarted: () => void) => Promise<T>;+ now?: Date;+ }) => deps.writer.dispatchResolvedInteractionIfCurrent({+ ...input,+ now: input.now ?? new Date(),+ });+}diff --git a/server/src/modules/run-dispatch/domain/policy.test.ts b/server/src/modules/run-dispatch/domain/policy.test.tsnew file mode 100644index 0000000000..3b20934de0--- /dev/null+++ b/server/src/modules/run-dispatch/domain/policy.test.ts@@ -0,0 +1,399 @@+import { describe, expect, it } from "vitest";+import {+ decideQueuedRunStaleness,+ decideScheduledRetryGate,+ type QueuedRunFacts,+ type ReviewParticipantFacts,+ type ScheduledRetryFacts,+} from "./policy.js";++const NOW = new Date("2026-01-01T00:00:00.000Z");++const NO_PARTICIPANT: ReviewParticipantFacts = {+ isInReview: false,+ hasParticipant: false,+ participantIsAgent: false,+ participantAgentId: null,+ currentStageType: null,+ currentParticipant: null,+};++function baseGateFacts(): ScheduledRetryFacts {+ return {+ runId: "run-1",+ runAgentId: "agent-1",+ issueId: "issue-1",+ retryReasonKind: "other",+ enforceIssueExecutionLock: false,+ budgetBlock: null,+ agentInvokable: true,+ agentInvokabilityDetails: {},+ agentInvokabilityInvalidOrgChain: false,+ heartbeatWakeOnDemandEnabled: true,+ issueFound: true,+ issueStatus: "in_progress",+ issueAssigneeAgentId: "agent-1",+ issueExecutionRunId: "run-1",+ isNonAssigneeWorkspaceBusyRetry: false,+ reviewParticipant: NO_PARTICIPANT,+ activePauseHold: null,+ dependenciesBlocked: null,+ dispositionRepair: null,+ };+}++function baseStalenessFacts(): QueuedRunFacts {+ return {+ runId: "run-1",+ runAgentId: "agent-1",+ issueId: "issue-1",+ retryReasonKind: "other",+ issueFound: true,+ issueStatus: "in_progress",+ issueAssigneeAgentId: "agent-1",+ issueExecutionRunId: "run-1",+ isResolvedInteractionContinuation: false,+ isInteractionWake: false,+ isAuthorizedSourceScopedRecovery: false,+ isNonAssigneeWorkspaceBusyRetry: false,+ resumeIntent: false,+ wakeCommentIdPresent: false,+ continuationParkApplies: false,+ continuationParksExecutor: false,+ continuationSummaryBody: null,+ wakeReason: null,+ retryReason: null,+ reviewParticipant: NO_PARTICIPANT,+ };+}++describe("decideScheduledRetryGate", () => {+ it("allows a run with no issueId before any issue check runs", () => {+ const facts = { ...baseGateFacts(), issueId: null, issueFound: false };+ expect(decideScheduledRetryGate(facts, NOW)).toEqual({ allowed: true });+ });++ it("allows a run when every rule passes", () => {+ expect(decideScheduledRetryGate(baseGateFacts(), NOW)).toEqual({+ allowed: true,+ });+ });++ it.each([+ {+ name: "budget_blocked",+ overrides: {+ budgetBlock: { reason: "over budget", scopeType: "company", scopeId: "co-1" },+ } satisfies Partial<ScheduledRetryFacts>,+ errorCode: "budget_blocked",+ },+ {+ name: "agent_not_invokable",+ overrides: { agentInvokable: false } satisfies Partial<ScheduledRetryFacts>,+ errorCode: "agent_not_invokable",+ },+ {+ name: "heartbeat_wake_on_demand_disabled",+ overrides: {+ heartbeatWakeOnDemandEnabled: false,+ } satisfies Partial<ScheduledRetryFacts>,+ errorCode: "heartbeat_wake_on_demand_disabled",+ },+ {+ name: "issue_not_found",+ overrides: { issueFound: false } satisfies Partial<ScheduledRetryFacts>,+ errorCode: "issue_not_found",+ },+ {+ name: "issue_reassigned",+ overrides: {+ issueAssigneeAgentId: "agent-2",+ } satisfies Partial<ScheduledRetryFacts>,+ errorCode: "issue_reassigned",+ },+ {+ name: "issue_cancelled",+ overrides: { issueStatus: "cancelled" } satisfies Partial<ScheduledRetryFacts>,+ errorCode: "issue_cancelled",+ },+ {+ name: "issue_terminal_status (done)",+ overrides: { issueStatus: "done" } satisfies Partial<ScheduledRetryFacts>,+ errorCode: "issue_terminal_status",+ },+ {+ name: "issue_not_in_progress",+ overrides: {+ retryReasonKind: "max_turn_continuation",+ issueStatus: "todo",+ } satisfies Partial<ScheduledRetryFacts>,+ errorCode: "issue_not_in_progress",+ },+ {+ name: "issue_execution_lock_changed",+ overrides: {+ retryReasonKind: "max_turn_continuation",+ enforceIssueExecutionLock: true,+ issueExecutionRunId: "run-2",+ } satisfies Partial<ScheduledRetryFacts>,+ errorCode: "issue_execution_lock_changed",+ },+ {+ name: "issue_review_participant_changed",+ overrides: {+ issueStatus: "in_review",+ reviewParticipant: {+ isInReview: true,+ hasParticipant: true,+ participantIsAgent: true,+ participantAgentId: "agent-2",+ currentStageType: "review",+ currentParticipant: { type: "agent", agentId: "agent-2" },+ },+ } satisfies Partial<ScheduledRetryFacts>,+ errorCode: "issue_review_participant_changed",+ },+ {+ name: "issue_paused",+ overrides: {+ activePauseHold: { holdId: "hold-1", rootIssueId: "issue-root" },+ } satisfies Partial<ScheduledRetryFacts>,+ errorCode: "issue_paused",+ },+ {+ name: "issue_dependencies_blocked",+ overrides: {+ dependenciesBlocked: {+ unresolvedBlockerIssueIds: ["issue-2"],+ unresolvedBlockerCount: 1,+ },+ } satisfies Partial<ScheduledRetryFacts>,+ errorCode: "issue_dependencies_blocked",+ },+ {+ name: "issue_disposition_repair_superseded (fingerprint mismatch)",+ overrides: {+ retryReasonKind: "disposition_repair",+ dispositionRepair: {+ expectedFingerprintPresent: true,+ fingerprintMatches: false,+ hasActiveExecutionPath: false,+ hasDurableWaitingPath: false,+ expectedFingerprint: "fp-old",+ currentFingerprint: "fp-new",+ durablePathReason: null,+ },+ } satisfies Partial<ScheduledRetryFacts>,+ errorCode: "issue_disposition_repair_superseded",+ },+ {+ name: "issue_disposition_repair_superseded (active execution path)",+ overrides: {+ retryReasonKind: "disposition_repair",+ dispositionRepair: {+ expectedFingerprintPresent: true,+ fingerprintMatches: true,+ hasActiveExecutionPath: true,+ hasDurableWaitingPath: false,+ expectedFingerprint: "fp-1",+ currentFingerprint: "fp-1",+ durablePathReason: null,+ },+ } satisfies Partial<ScheduledRetryFacts>,+ errorCode: "issue_disposition_repair_superseded",+ },+ ])("blocks with $errorCode", ({ overrides, errorCode }) => {+ const facts = { ...baseGateFacts(), ...overrides };+ const decision = decideScheduledRetryGate(facts, NOW);+ expect(decision.allowed).toBe(false);+ expect(decision).toMatchObject({ errorCode });+ });++ it("allows a disposition repair retry when the fingerprint matches and no other path is active", () => {+ const facts: ScheduledRetryFacts = {+ ...baseGateFacts(),+ retryReasonKind: "disposition_repair",+ dispositionRepair: {+ expectedFingerprintPresent: true,+ fingerprintMatches: true,+ hasActiveExecutionPath: false,+ hasDurableWaitingPath: false,+ expectedFingerprint: "fp-1",+ currentFingerprint: "fp-1",+ durablePathReason: null,+ },+ };+ expect(decideScheduledRetryGate(facts, NOW)).toEqual({ allowed: true });+ });++ it("allows a reassigned issue when the retry is a non-assignee workspace-busy retry", () => {+ const facts: ScheduledRetryFacts = {+ ...baseGateFacts(),+ issueAssigneeAgentId: "agent-2",+ isNonAssigneeWorkspaceBusyRetry: true,+ };+ expect(decideScheduledRetryGate(facts, NOW)).toEqual({ allowed: true });+ });++ it("keeps the legacy missing-issue exception's precondition: issue_not_found is reported the same way for a non-max-turn retry as for a max-turn retry", () => {+ const nonMaxTurn = decideScheduledRetryGate(+ { ...baseGateFacts(), retryReasonKind: "other", issueFound: false },+ NOW,+ );+ const maxTurn = decideScheduledRetryGate(+ {+ ...baseGateFacts(),+ retryReasonKind: "max_turn_continuation",+ issueFound: false,+ },+ NOW,+ );+ expect(nonMaxTurn).toMatchObject({ allowed: false, errorCode: "issue_not_found" });+ expect(maxTurn).toMatchObject({ allowed: false, errorCode: "issue_not_found" });+ });+});++describe("decideQueuedRunStaleness", () => {+ it("is not stale when every rule passes", () => {+ expect(decideQueuedRunStaleness(baseStalenessFacts(), NOW)).toEqual({+ stale: false,+ });+ });++ it.each([+ {+ name: "issue_not_found",+ overrides: { issueFound: false } satisfies Partial<QueuedRunFacts>,+ errorCode: "issue_not_found",+ },+ {+ name: "issue_assignee_changed (general ownership)",+ overrides: {+ issueAssigneeAgentId: "agent-2",+ } satisfies Partial<QueuedRunFacts>,+ errorCode: "issue_assignee_changed",+ },+ {+ name: "issue_assignee_changed (resolved-interaction continuation)",+ overrides: {+ isResolvedInteractionContinuation: true,+ issueAssigneeAgentId: "agent-2",+ } satisfies Partial<QueuedRunFacts>,+ errorCode: "issue_assignee_changed",+ },+ {+ name: "issue_not_in_progress (resolved-interaction continuation)",+ overrides: {+ isResolvedInteractionContinuation: true,+ issueStatus: "todo",+ } satisfies Partial<QueuedRunFacts>,+ errorCode: "issue_not_in_progress",+ },+ {+ name: "issue_not_in_progress (max-turn continuation)",+ overrides: {+ retryReasonKind: "max_turn_continuation",+ issueStatus: "todo",+ } satisfies Partial<QueuedRunFacts>,+ errorCode: "issue_not_in_progress",+ },+ {+ name: "issue_terminal_status",+ overrides: { issueStatus: "done" } satisfies Partial<QueuedRunFacts>,+ errorCode: "issue_terminal_status",+ },+ {+ name: "issue_execution_lock_changed",+ overrides: {+ retryReasonKind: "max_turn_continuation",+ issueExecutionRunId: "run-2",+ } satisfies Partial<QueuedRunFacts>,+ errorCode: "issue_execution_lock_changed",+ },+ {+ name: "issue_review_participant_changed",+ overrides: {+ issueStatus: "in_review",+ reviewParticipant: {+ isInReview: true,+ hasParticipant: true,+ participantIsAgent: true,+ participantAgentId: "agent-2",+ currentStageType: "review",+ currentParticipant: { type: "agent", agentId: "agent-2" },+ },+ } satisfies Partial<QueuedRunFacts>,+ errorCode: "issue_review_participant_changed",+ },+ {+ name: "issue_continuation_waiting_on_review (parked-summary case)",+ overrides: {+ continuationParkApplies: true,+ continuationParksExecutor: true,+ continuationSummaryBody: "Waiting for reviewer approval before continuing.",+ wakeReason: "issue_continuation_needed",+ } satisfies Partial<QueuedRunFacts>,+ errorCode: "issue_continuation_waiting_on_review",+ },+ ])("cancels with $errorCode", ({ overrides, errorCode }) => {+ const facts = { ...baseStalenessFacts(), ...overrides };+ const decision = decideQueuedRunStaleness(facts, NOW);+ expect(decision.stale).toBe(true);+ expect(decision).toMatchObject({ errorCode });+ });++ it("does not cancel a parked continuation summary when the classifier says it does not park the executor", () => {+ const facts: QueuedRunFacts = {+ ...baseStalenessFacts(),+ continuationParkApplies: true,+ continuationParksExecutor: false,+ };+ expect(decideQueuedRunStaleness(facts, NOW)).toEqual({ stale: false });+ });++ it("allows a comment wake to bypass the ownership, terminal-status, and review-participant checks", () => {+ const facts: QueuedRunFacts = {+ ...baseStalenessFacts(),+ issueAssigneeAgentId: "agent-1",+ isInteractionWake: true,+ wakeCommentIdPresent: true,+ issueStatus: "in_review",+ reviewParticipant: {+ isInReview: true,+ hasParticipant: true,+ participantIsAgent: true,+ participantAgentId: "agent-2",+ currentStageType: "review",+ currentParticipant: { type: "agent", agentId: "agent-2" },+ },+ };+ expect(decideQueuedRunStaleness(facts, NOW)).toEqual({ stale: false });+ });++ it("allows resume intent to bypass a terminal status", () => {+ const facts: QueuedRunFacts = {+ ...baseStalenessFacts(),+ issueStatus: "done",+ resumeIntent: true,+ };+ expect(decideQueuedRunStaleness(facts, NOW)).toEqual({ stale: false });+ });++ it("allows a non-assignee workspace-busy retry to bypass the ownership check", () => {+ const facts: QueuedRunFacts = {+ ...baseStalenessFacts(),+ issueAssigneeAgentId: "agent-2",+ isNonAssigneeWorkspaceBusyRetry: true,+ };+ expect(decideQueuedRunStaleness(facts, NOW)).toEqual({ stale: false });+ });++ it("allows an authorized source-scoped recovery to bypass the ownership check", () => {+ const facts: QueuedRunFacts = {+ ...baseStalenessFacts(),+ issueAssigneeAgentId: "agent-2",+ isAuthorizedSourceScopedRecovery: true,+ };+ expect(decideQueuedRunStaleness(facts, NOW)).toEqual({ stale: false });+ });+});diff --git a/server/src/modules/run-dispatch/domain/policy.ts b/server/src/modules/run-dispatch/domain/policy.tsnew file mode 100644index 0000000000..70c5940e16--- /dev/null+++ b/server/src/modules/run-dispatch/domain/policy.ts@@ -0,0 +1,606 @@+// Pure decision rules for two heartbeat run-dispatch gates:+// - the scheduled-retry promotion gate (decideScheduledRetryGate)+// - the queued-run staleness check (decideQueuedRunStaleness)+// The caller reads the database, the clock, and the agent's invokability,+// then packs the result into a facts object. This file only branches on+// that facts object; it never queries a database or reads the clock.++/** The retry reason a run carries, reduced to the three kinds a gate cares about. */+export type RetryReasonKind =+ | "max_turn_continuation"+ | "disposition_repair"+ | "other";++export type BudgetBlockFacts = {+ reason: string;+ scopeType: string;+ scopeId: string;+};++export type PauseHoldFacts = {+ holdId: string;+ rootIssueId: string;+};++export type DependencyBlockFacts = {+ unresolvedBlockerIssueIds: string[];+ unresolvedBlockerCount: number;+};++export type DispositionRepairFacts = {+ expectedFingerprintPresent: boolean;+ fingerprintMatches: boolean;+ hasActiveExecutionPath: boolean;+ hasDurableWaitingPath: boolean;+ expectedFingerprint: string | null;+ currentFingerprint: string | null;+ durablePathReason: string | null;+};++export type ReviewParticipantFacts = {+ isInReview: boolean;+ hasParticipant: boolean;+ participantIsAgent: boolean;+ participantAgentId: string | null;+ currentStageType: string | null;+ currentParticipant: Record<string, unknown> | null;+};++export type ScheduledRetryGateErrorCode =+ | "agent_not_invokable"+ | "heartbeat_wake_on_demand_disabled"+ | "budget_blocked"+ | "issue_not_found"+ | "issue_reassigned"+ | "issue_cancelled"+ | "issue_terminal_status"+ | "issue_not_in_progress"+ | "issue_execution_lock_changed"+ | "issue_review_participant_changed"+ | "issue_paused"+ | "issue_dependencies_blocked"+ | "issue_disposition_repair_superseded";++export type GateDecision =+ | { allowed: true }+ | {+ allowed: false;+ reason: string;+ errorCode: ScheduledRetryGateErrorCode;+ issueId: string | null;+ details: Record<string, unknown>;+ };++export type ScheduledRetryFacts = {+ runId: string;+ runAgentId: string;+ issueId: string | null;+ retryReasonKind: RetryReasonKind;+ enforceIssueExecutionLock: boolean;++ budgetBlock: BudgetBlockFacts | null;++ agentInvokable: boolean;+ agentInvokabilityDetails: Record<string, unknown>;+ agentInvokabilityInvalidOrgChain: boolean;++ heartbeatWakeOnDemandEnabled: boolean;++ issueFound: boolean;+ issueStatus: string | null;+ issueAssigneeAgentId: string | null;+ issueExecutionRunId: string | null;++ isNonAssigneeWorkspaceBusyRetry: boolean;+ reviewParticipant: ReviewParticipantFacts;+ activePauseHold: PauseHoldFacts | null;+ dependenciesBlocked: DependencyBlockFacts | null;++ /** Present only when retryReasonKind is "disposition_repair". */+ dispositionRepair: DispositionRepairFacts | null;+};++export type QueuedRunStalenessErrorCode =+ | "issue_not_found"+ | "issue_assignee_changed"+ | "issue_terminal_status"+ | "issue_not_in_progress"+ | "issue_execution_lock_changed"+ | "issue_review_participant_changed"+ | "issue_continuation_waiting_on_review";++export type StalenessDecision =+ | { stale: false }+ | {+ stale: true;+ reason: string;+ errorCode: QueuedRunStalenessErrorCode;+ details: Record<string, unknown>;+ };++export type QueuedRunFacts = {+ runId: string;+ runAgentId: string;+ issueId: string;+ retryReasonKind: RetryReasonKind;++ issueFound: boolean;+ issueStatus: string | null;+ issueAssigneeAgentId: string | null;+ issueExecutionRunId: string | null;++ isResolvedInteractionContinuation: boolean;+ isInteractionWake: boolean;+ isAuthorizedSourceScopedRecovery: boolean;+ isNonAssigneeWorkspaceBusyRetry: boolean;++ resumeIntent: boolean;+ wakeCommentIdPresent: boolean;++ /** True when the run's wake or retry reason asks for a continuation the parked-summary check must inspect. */+ continuationParkApplies: boolean;+ /** The pre-classified verdict on whatever continuation summary body applies; only meaningful when continuationParkApplies is true. */+ continuationParksExecutor: boolean;+ continuationSummaryBody: string | null;+ wakeReason: string | null;+ retryReason: string | null;++ reviewParticipant: ReviewParticipantFacts;+};++type OwnershipFacts = {+ runAgentId: string;+ issueAssigneeAgentId: string | null;+ isNonAssigneeWorkspaceBusyRetry: boolean;+ isInteractionWake?: boolean;+ isCurrentReviewParticipant?: boolean;+ isAuthorizedSourceScopedRecovery?: boolean;+};++type OwnershipOutcome = "current_owner" | "reassigned";++/**+ * Decides whether the run's agent still owns the issue. A caller passes+ * only the bypass signals it has; an omitted bypass is treated as absent,+ * not as granted.+ */+function decideIssueOwnership(facts: OwnershipFacts): OwnershipOutcome {+ if (facts.issueAssigneeAgentId === facts.runAgentId) return "current_owner";+ if (facts.isNonAssigneeWorkspaceBusyRetry) return "current_owner";+ if (facts.isInteractionWake) return "current_owner";+ if (facts.isCurrentReviewParticipant) return "current_owner";+ if (facts.isAuthorizedSourceScopedRecovery) return "current_owner";+ return "reassigned";+}++type IssueStatusFacts = {+ status: string | null;+ requiresInProgress: boolean;+ /** When true, a terminal status does not block the run (staleness only). */+ terminalBypass?: boolean;+};++type IssueStatusOutcome = "ok" | "terminal" | "not_in_progress";++/**+ * Decides whether the issue's current status still supports the run. A+ * terminal status is checked before the in-progress requirement, matching+ * the order the gates have always evaluated them in.+ */+function decideIssueStatus(facts: IssueStatusFacts): IssueStatusOutcome {+ const isTerminal = facts.status === "cancelled" || facts.status === "done";+ if (isTerminal && !facts.terminalBypass) return "terminal";+ if (facts.requiresInProgress && facts.status !== "in_progress") {+ return "not_in_progress";+ }+ return "ok";+}++type ExecutionLockFacts = {+ requiresExecutionLock: boolean;+ runId: string;+ issueExecutionRunId: string | null;+};++type ExecutionLockOutcome = "ok" | "lock_changed";++/** Decides whether the issue's execution lock still belongs to this run. */+function decideExecutionLock(facts: ExecutionLockFacts): ExecutionLockOutcome {+ if (facts.requiresExecutionLock && facts.issueExecutionRunId !== facts.runId) {+ return "lock_changed";+ }+ return "ok";+}++type ReviewParticipantCheckFacts = ReviewParticipantFacts & {+ runAgentId: string;+ /** True when a comment wake excuses a participant mismatch (staleness only). */+ bypass?: boolean;+};++type ReviewParticipantOutcome = "ok" | "participant_changed";++/**+ * Decides whether the current review participant still matches the run's+ * agent. An issue with no assigned participant, or one not in review, never+ * blocks here.+ */+function decideReviewParticipant(+ facts: ReviewParticipantCheckFacts,+): ReviewParticipantOutcome {+ if (!facts.isInReview || !facts.hasParticipant) return "ok";+ const participantMatches =+ facts.participantIsAgent && facts.participantAgentId === facts.runAgentId;+ if (participantMatches || facts.bypass) return "ok";+ return "participant_changed";+}++/**+ * Decides whether a due scheduled retry may promote to a queued run. The+ * caller passes now for signature symmetry with future clock-dependent+ * rules; today's rules need no clock read.+ */+export function decideScheduledRetryGate(+ facts: ScheduledRetryFacts,+ _now: Date,+): GateDecision {+ if (facts.budgetBlock) {+ return {+ allowed: false,+ reason: facts.budgetBlock.reason,+ errorCode: "budget_blocked",+ issueId: facts.issueId,+ details: {+ scopeType: facts.budgetBlock.scopeType,+ scopeId: facts.budgetBlock.scopeId,+ },+ };+ }++ if (!facts.agentInvokable) {+ return {+ allowed: false,+ reason: "Scheduled retry suppressed because the agent is not invokable",+ errorCode: "agent_not_invokable",+ issueId: facts.issueId,+ details: {+ ...facts.agentInvokabilityDetails,+ invalidOrgChain: facts.agentInvokabilityInvalidOrgChain,+ },+ };+ }++ if (!facts.heartbeatWakeOnDemandEnabled) {+ return {+ allowed: false,+ reason:+ "Scheduled retry suppressed because on-demand agent wakes are disabled",+ errorCode: "heartbeat_wake_on_demand_disabled",+ issueId: facts.issueId,+ details: { agentId: facts.runAgentId },+ };+ }++ if (!facts.issueId) return { allowed: true };++ if (!facts.issueFound) {+ return {+ allowed: false,+ reason:+ "Scheduled retry suppressed because the target issue no longer exists",+ errorCode: "issue_not_found",+ issueId: facts.issueId,+ details: { issueId: facts.issueId },+ };+ }++ if (facts.retryReasonKind === "disposition_repair" && facts.dispositionRepair) {+ const repair = facts.dispositionRepair;+ const superseded =+ !repair.expectedFingerprintPresent ||+ !repair.fingerprintMatches ||+ repair.hasActiveExecutionPath ||+ repair.hasDurableWaitingPath;+ if (superseded) {+ return {+ allowed: false,+ reason:+ "Scheduled disposition repair suppressed because the source state changed or gained a durable path",+ errorCode: "issue_disposition_repair_superseded",+ issueId: facts.issueId,+ details: {+ issueId: facts.issueId,+ expectedFingerprint: repair.expectedFingerprint,+ currentFingerprint: repair.currentFingerprint,+ hasActiveExecutionPath: repair.hasActiveExecutionPath,+ durablePathReason: repair.durablePathReason,+ },+ };+ }+ }++ const ownership = decideIssueOwnership({+ runAgentId: facts.runAgentId,+ issueAssigneeAgentId: facts.issueAssigneeAgentId,+ isNonAssigneeWorkspaceBusyRetry: facts.isNonAssigneeWorkspaceBusyRetry,+ });+ if (ownership === "reassigned") {+ return {+ allowed: false,+ reason: "Scheduled retry suppressed because issue ownership changed",+ errorCode: "issue_reassigned",+ issueId: facts.issueId,+ details: {+ issueId: facts.issueId,+ previousAssigneeAgentId: facts.runAgentId,+ currentAssigneeAgentId: facts.issueAssigneeAgentId,+ },+ };+ }++ const requiresInProgress = facts.retryReasonKind === "max_turn_continuation";+ const statusOutcome = decideIssueStatus({+ status: facts.issueStatus,+ requiresInProgress,+ });+ if (statusOutcome === "terminal") {+ return {+ allowed: false,+ reason: `Scheduled retry suppressed because issue reached terminal status (${facts.issueStatus})`,+ errorCode:+ facts.issueStatus === "cancelled"+ ? "issue_cancelled"+ : "issue_terminal_status",+ issueId: facts.issueId,+ details: { issueId: facts.issueId, currentStatus: facts.issueStatus },+ };+ }+ if (statusOutcome === "not_in_progress") {+ return {+ allowed: false,+ reason: `Scheduled max-turn continuation suppressed because issue is no longer in_progress (current status: ${facts.issueStatus})`,+ errorCode: "issue_not_in_progress",+ issueId: facts.issueId,+ details: {+ issueId: facts.issueId,+ currentStatus: facts.issueStatus,+ requiredStatus: "in_progress",+ },+ };+ }++ const lockOutcome = decideExecutionLock({+ requiresExecutionLock: requiresInProgress && facts.enforceIssueExecutionLock,+ runId: facts.runId,+ issueExecutionRunId: facts.issueExecutionRunId,+ });+ if (lockOutcome === "lock_changed") {+ return {+ allowed: false,+ reason:+ "Scheduled max-turn continuation suppressed because the issue execution lock belongs to a different run",+ errorCode: "issue_execution_lock_changed",+ issueId: facts.issueId,+ details: {+ issueId: facts.issueId,+ expectedExecutionRunId: facts.runId,+ currentExecutionRunId: facts.issueExecutionRunId,+ },+ };+ }++ const participantOutcome = decideReviewParticipant({+ ...facts.reviewParticipant,+ runAgentId: facts.runAgentId,+ });+ if (participantOutcome === "participant_changed") {+ return {+ allowed: false,+ reason:+ "Scheduled retry suppressed because the issue is waiting on another review participant",+ errorCode: "issue_review_participant_changed",+ issueId: facts.issueId,+ details: {+ issueId: facts.issueId,+ currentStageType: facts.reviewParticipant.currentStageType,+ currentParticipant: facts.reviewParticipant.currentParticipant,+ },+ };+ }++ if (facts.activePauseHold) {+ return {+ allowed: false,+ reason:+ "Scheduled retry suppressed because the issue is held by an active subtree pause hold",+ errorCode: "issue_paused",+ issueId: facts.issueId,+ details: {+ issueId: facts.issueId,+ holdId: facts.activePauseHold.holdId,+ rootIssueId: facts.activePauseHold.rootIssueId,+ },+ };+ }++ if (facts.dependenciesBlocked) {+ return {+ allowed: false,+ reason: "Scheduled retry suppressed because issue dependencies are still blocked",+ errorCode: "issue_dependencies_blocked",+ issueId: facts.issueId,+ details: {+ issueId: facts.issueId,+ unresolvedBlockerIssueIds: facts.dependenciesBlocked.unresolvedBlockerIssueIds,+ unresolvedBlockerCount: facts.dependenciesBlocked.unresolvedBlockerCount,+ },+ };+ }++ return { allowed: true };+}++/**+ * Decides whether a queued run has gone stale before it could start. The+ * caller passes now for signature symmetry with future clock-dependent+ * rules; today's rules need no clock read.+ */+export function decideQueuedRunStaleness(+ facts: QueuedRunFacts,+ _now: Date,+): StalenessDecision {+ if (!facts.issueFound) {+ return {+ stale: true,+ errorCode: "issue_not_found",+ reason: "Cancelled because the target issue no longer exists",+ details: { issueId: facts.issueId },+ };+ }++ if (facts.isResolvedInteractionContinuation) {+ const earlyStatus = decideIssueStatus({+ status: facts.issueStatus,+ requiresInProgress: true,+ terminalBypass: true,+ });+ if (earlyStatus === "not_in_progress") {+ return {+ stale: true,+ errorCode: "issue_not_in_progress",+ reason: `Cancelled because resolved-interaction continuation issue is no longer in_progress (current status: ${facts.issueStatus}) before the queued run could start`,+ details: {+ issueId: facts.issueId,+ currentStatus: facts.issueStatus,+ requiredStatus: "in_progress",+ },+ };+ }++ const earlyOwnership = decideIssueOwnership({+ runAgentId: facts.runAgentId,+ issueAssigneeAgentId: facts.issueAssigneeAgentId,+ isNonAssigneeWorkspaceBusyRetry: false,+ });+ if (earlyOwnership === "reassigned") {+ return {+ stale: true,+ errorCode: "issue_assignee_changed",+ reason:+ "Cancelled because resolved-interaction continuation issue changed assignee before the queued run could start",+ details: {+ issueId: facts.issueId,+ previousAssigneeAgentId: facts.runAgentId,+ currentAssigneeAgentId: facts.issueAssigneeAgentId,+ },+ };+ }+ }++ if (facts.continuationParkApplies && facts.continuationParksExecutor) {+ return {+ stale: true,+ errorCode: "issue_continuation_waiting_on_review",+ reason:+ "Cancelled because the continuation summary says the executor should wait for reviewer feedback or approval before more work starts",+ details: {+ issueId: facts.issueId,+ wakeReason: facts.wakeReason,+ retryReason: facts.retryReason,+ nextAction: facts.continuationSummaryBody,+ },+ };+ }++ const ownership = decideIssueOwnership({+ runAgentId: facts.runAgentId,+ issueAssigneeAgentId: facts.issueAssigneeAgentId,+ isNonAssigneeWorkspaceBusyRetry: facts.isNonAssigneeWorkspaceBusyRetry,+ isInteractionWake: facts.isInteractionWake,+ isCurrentReviewParticipant:+ facts.reviewParticipant.isInReview &&+ facts.reviewParticipant.participantIsAgent &&+ facts.reviewParticipant.participantAgentId === facts.runAgentId,+ isAuthorizedSourceScopedRecovery: facts.isAuthorizedSourceScopedRecovery,+ });+ if (ownership === "reassigned") {+ return {+ stale: true,+ errorCode: "issue_assignee_changed",+ reason:+ "Cancelled because issue assignee changed before the queued run could start; the new owner will be woken instead",+ details: {+ issueId: facts.issueId,+ previousAssigneeAgentId: facts.runAgentId,+ currentAssigneeAgentId: facts.issueAssigneeAgentId,+ },+ };+ }++ const requiresInProgress = facts.retryReasonKind === "max_turn_continuation";+ const statusOutcome = decideIssueStatus({+ status: facts.issueStatus,+ requiresInProgress,+ terminalBypass: facts.resumeIntent || facts.wakeCommentIdPresent,+ });+ if (statusOutcome === "terminal") {+ return {+ stale: true,+ errorCode: "issue_terminal_status",+ reason: `Cancelled because issue reached terminal status (${facts.issueStatus}) before the queued run could start`,+ details: { issueId: facts.issueId, currentStatus: facts.issueStatus },+ };+ }+ if (statusOutcome === "not_in_progress") {+ return {+ stale: true,+ errorCode: "issue_not_in_progress",+ reason: `Cancelled because max-turn continuation issue is no longer in_progress (current status: ${facts.issueStatus}) before the queued run could start`,+ details: {+ issueId: facts.issueId,+ currentStatus: facts.issueStatus,+ requiredStatus: "in_progress",+ },+ };+ }++ const lockOutcome = decideExecutionLock({+ requiresExecutionLock: requiresInProgress,+ runId: facts.runId,+ issueExecutionRunId: facts.issueExecutionRunId,+ });+ if (lockOutcome === "lock_changed") {+ return {+ stale: true,+ errorCode: "issue_execution_lock_changed",+ reason:+ "Cancelled because max-turn continuation no longer owns the issue execution lock before the queued run could start",+ details: {+ issueId: facts.issueId,+ expectedExecutionRunId: facts.runId,+ currentExecutionRunId: facts.issueExecutionRunId,+ },+ };+ }++ const participantOutcome = decideReviewParticipant({+ ...facts.reviewParticipant,+ runAgentId: facts.runAgentId,+ bypass: facts.wakeCommentIdPresent,+ });+ if (participantOutcome === "participant_changed") {+ return {+ stale: true,+ errorCode: "issue_review_participant_changed",+ reason:+ "Cancelled because the in-review participant changed before the queued run could start; the current participant will be woken instead",+ details: {+ issueId: facts.issueId,+ currentStageType: facts.reviewParticipant.currentStageType,+ currentParticipant: facts.reviewParticipant.currentParticipant,+ },+ };+ }++ return { stale: false };+}diff --git a/server/src/modules/run-dispatch/domain/wake-context.test.ts b/server/src/modules/run-dispatch/domain/wake-context.test.tsnew file mode 100644index 0000000000..846a190ca4--- /dev/null+++ b/server/src/modules/run-dispatch/domain/wake-context.test.ts@@ -0,0 +1,81 @@+import { describe, expect, it } from "vitest";+import {+ allowsIssueInteractionWake,+ deriveCommentId,+ extractWakeCommentIds,+ isNonAssigneeWorkspaceBusyRetry,+ isResolvedInteractionContinuationWakeContext,+ WORKSPACE_BUSY_RETRY_REASON,+} from "./wake-context.js";++describe("wake context", () => {+ it("recognizes only workspace-busy retries deferred outside assignee-ship", () => {+ expect(isNonAssigneeWorkspaceBusyRetry(WORKSPACE_BUSY_RETRY_REASON, {+ workspaceBusyDeferredWhileAssignee: false,+ })).toBe(true);+ expect(isNonAssigneeWorkspaceBusyRetry(WORKSPACE_BUSY_RETRY_REASON, {+ workspaceBusyDeferredWhileAssignee: true,+ })).toBe(false);+ expect(isNonAssigneeWorkspaceBusyRetry("another_reason", {+ workspaceBusyDeferredWhileAssignee: false,+ })).toBe(false);+ });++ it("keeps ordered, unique, non-empty wake comment ids", () => {+ expect(extractWakeCommentIds({+ wakeCommentIds: ["comment-1", "", null, "comment-2", "comment-1"],+ })).toEqual(["comment-1", "comment-2"]);+ expect(extractWakeCommentIds({ wakeCommentIds: "comment-1" })).toEqual([]);+ expect(extractWakeCommentIds(undefined)).toEqual([]);+ });++ it.each([+ [{ wakeCommentIds: ["batch-1", "batch-2"], wakeCommentId: "wake" }, {}, "batch-2"],+ [{ wakeCommentId: "wake", commentId: "context" }, {}, "wake"],+ [{ commentId: "context" }, { commentId: "payload" }, "context"],+ [{}, { commentId: "payload" }, "payload"],+ [{ wakeCommentId: " " }, { commentId: " " }, null],+ ])("derives comment ids by canonical precedence", (context, payload, expected) => {+ expect(deriveCommentId(context, payload)).toBe(expected);+ });++ it("allows interaction wakes only for an allowed reason with a comment id", () => {+ const allowed = new Set(["issue_commented"]);+ expect(allowsIssueInteractionWake({+ wakeReason: "issue_commented",+ wakeCommentId: "comment-1",+ }, allowed)).toBe(true);+ expect(allowsIssueInteractionWake({+ wakeReason: "timer",+ wakeCommentId: "comment-1",+ }, allowed)).toBe(false);+ expect(allowsIssueInteractionWake({ wakeReason: "issue_commented" }, allowed)).toBe(false);+ });++ it.each(["accepted", "answered", "rejected"])(+ "recognizes %s issue-comment interaction continuations",+ (interactionStatus) => {+ expect(isResolvedInteractionContinuationWakeContext({+ interactionId: "interaction-1",+ interactionStatus,+ mutation: "interaction",+ wakeReason: "issue_commented",+ })).toBe(true);+ },+ );++ it("recognizes infrastructure continuations and rejects incomplete contexts", () => {+ const base = { interactionId: "interaction-1", interactionStatus: "accepted" };+ expect(isResolvedInteractionContinuationWakeContext({+ ...base,+ wakeReason: "interaction_continuation_infra_retry",+ })).toBe(true);+ expect(isResolvedInteractionContinuationWakeContext({+ ...base,+ retryReason: "interaction_continuation_infra_retry",+ })).toBe(true);+ expect(isResolvedInteractionContinuationWakeContext({ ...base, interactionStatus: "pending" })).toBe(false);+ expect(isResolvedInteractionContinuationWakeContext({ interactionStatus: "accepted" })).toBe(false);+ expect(isResolvedInteractionContinuationWakeContext(null)).toBe(false);+ });+});diff --git a/server/src/modules/run-dispatch/domain/wake-context.ts b/server/src/modules/run-dispatch/domain/wake-context.tsnew file mode 100644index 0000000000..c7fc2de88e--- /dev/null+++ b/server/src/modules/run-dispatch/domain/wake-context.ts@@ -0,0 +1,103 @@+// Shared wake-reason and retry-reason constants, and the pure classifiers+// that read them off a run's context snapshot. `heartbeat.ts` and this+// module's own Postgres adapter both decide on the same context snapshot+// shape, so this file is their one shared source for it: a second,+// independently maintained copy in either file could silently drift out of+// sync with the other and change only one of the two gates that read it.++function parseObject(value: unknown): Record<string, unknown> {+ return typeof value === "object" && value !== null && !Array.isArray(value)+ ? (value as Record<string, unknown>)+ : {};+}++function readNonEmptyString(value: unknown): string | null {+ return typeof value === "string" && value.trim().length > 0 ? value : null;+}++export const MAX_TURN_CONTINUATION_RETRY_REASON = "max_turns_continuation";+export const WORKSPACE_BUSY_RETRY_REASON = "workspace_busy";+export const INTERACTION_CONTINUATION_INFRA_RETRY_REASON = "interaction_continuation_infra_retry";+export const INTERACTION_CONTINUATION_INFRA_WAKE_REASON = "interaction_continuation_infra_retry";+export const WAKE_COMMENT_IDS_KEY = "wakeCommentIds";+export const RESOLVED_INTERACTION_CONTINUATION_STATUSES = new Set([+ "accepted",+ "answered",+ "rejected",+]);++/**+ * True for the retry of a workspace-busy deferral whose original run did not+ * execute under assignee-ship (a comment or review-participant wake). Such a+ * retry has an expected assignee mismatch, so the scheduled-retry gate and+ * the queued-run staleness check must not treat it as a reassignment.+ */+export function isNonAssigneeWorkspaceBusyRetry(+ retryReason: string | null | undefined,+ contextSnapshot: Record<string, unknown>,+): boolean {+ return (+ retryReason === WORKSPACE_BUSY_RETRY_REASON &&+ contextSnapshot.workspaceBusyDeferredWhileAssignee === false+ );+}++export function extractWakeCommentIds(+ contextSnapshot: Record<string, unknown> | null | undefined,+): string[] {+ const raw = contextSnapshot?.[WAKE_COMMENT_IDS_KEY];+ if (!Array.isArray(raw)) return [];+ const out: string[] = [];+ for (const entry of raw) {+ const value = readNonEmptyString(entry);+ if (!value || out.includes(value)) continue;+ out.push(value);+ }+ return out;+}++export function deriveCommentId(+ contextSnapshot: Record<string, unknown> | null | undefined,+ payload?: Record<string, unknown> | null,+): string | null {+ const batchedCommentId = extractWakeCommentIds(contextSnapshot).at(-1);+ return (+ batchedCommentId ??+ readNonEmptyString(contextSnapshot?.wakeCommentId) ??+ readNonEmptyString(contextSnapshot?.commentId) ??+ readNonEmptyString(payload?.commentId) ??+ null+ );+}++/**+ * `allowedWakeReasons` is the issue-tree-control module's own set of wake+ * reasons that excuse an interaction wake. This file stays free of service+ * imports, so the caller passes the set in rather than this function reading+ * it from the service directly.+ */+export function allowsIssueInteractionWake(+ contextSnapshot: Record<string, unknown> | null | undefined,+ allowedWakeReasons: ReadonlySet<string>,+): boolean {+ const wakeReason = readNonEmptyString(contextSnapshot?.wakeReason);+ if (!wakeReason || !allowedWakeReasons.has(wakeReason)) return false;+ return Boolean(deriveCommentId(contextSnapshot));+}++export function isResolvedInteractionContinuationWakeContext(contextSnapshot: unknown): boolean {+ const context = parseObject(contextSnapshot);+ const interactionId = readNonEmptyString(context.interactionId);+ const interactionStatus = readNonEmptyString(context.interactionStatus);+ if (!interactionId || !interactionStatus) return false;+ if (!RESOLVED_INTERACTION_CONTINUATION_STATUSES.has(interactionStatus)) return false;++ const mutation = readNonEmptyString(context.mutation);+ const wakeReason = readNonEmptyString(context.wakeReason);+ const retryReason = readNonEmptyString(context.retryReason);+ return (+ (mutation === "interaction" && wakeReason === "issue_commented") ||+ wakeReason === INTERACTION_CONTINUATION_INFRA_WAKE_REASON ||+ retryReason === INTERACTION_CONTINUATION_INFRA_RETRY_REASON+ );+}diff --git a/server/src/modules/run-dispatch/index.ts b/server/src/modules/run-dispatch/index.tsnew file mode 100644index 0000000000..20f3473bda--- /dev/null+++ b/server/src/modules/run-dispatch/index.ts@@ -0,0 +1,80 @@+import type { Db } from "@paperclipai/db";+import { createPostgresRunDispatchAdapter } from "./adapters/postgres.js";+import {+ createCancelStaleQueuedRun,+ createDispatchResolvedInteractionIfCurrent,+ createEvaluateScheduledRetryGate,+ createPromoteDueScheduledRetries,+ createPromoteScheduledRetry,+} from "./application/use-cases.js";+import type { RunDispatchWriter, ScheduledRetryReader } from "./application/ports.js";++export {+ MAX_TURN_CONTINUATION_RETRY_REASON,+ WORKSPACE_BUSY_RETRY_REASON,+ INTERACTION_CONTINUATION_INFRA_RETRY_REASON,+ INTERACTION_CONTINUATION_INFRA_WAKE_REASON,+ WAKE_COMMENT_IDS_KEY,+ RESOLVED_INTERACTION_CONTINUATION_STATUSES,+ isNonAssigneeWorkspaceBusyRetry,+ extractWakeCommentIds,+ deriveCommentId,+ allowsIssueInteractionWake,+ isResolvedInteractionContinuationWakeContext,+} from "./domain/wake-context.js";+export type {+ RetryReasonKind,+ BudgetBlockFacts,+ PauseHoldFacts,+ DependencyBlockFacts,+ DispositionRepairFacts,+ ReviewParticipantFacts,+ ScheduledRetryGateErrorCode,+ GateDecision,+ ScheduledRetryFacts,+ QueuedRunStalenessErrorCode,+ StalenessDecision,+ QueuedRunFacts,+} from "./domain/policy.js";+export type {+ PostCommitEffect,+ PromoteScheduledRetryOutcome,+ CancelStaleQueuedRunOutcome,+} from "./application/types.js";+export { RunDispatchApplicationError } from "./application/types.js";++export type RunDispatchDeps = {+ /** Overrides the Postgres adapter; a test builds its module against a fake instead. */+ adapter?: ScheduledRetryReader & RunDispatchWriter;+};++/**+ * Composes the run-dispatch module: the Postgres adapter and its semantic+ * use cases. `heartbeat.ts` holds the only caller: it builds one+ * instance per process and delegates the scheduled-retry promotion gate and+ * the queued-run staleness gate to it.+ */+export function createRunDispatch(db: Db, deps: RunDispatchDeps = {}) {+ const adapter = deps.adapter ?? createPostgresRunDispatchAdapter(db);++ const promoteScheduledRetry = createPromoteScheduledRetry({+ writer: adapter,+ });++ return {+ evaluateScheduledRetryGate: createEvaluateScheduledRetryGate({ reader: adapter }),+ promoteScheduledRetry,+ promoteDueScheduledRetries: createPromoteDueScheduledRetries({+ reader: adapter,+ promoteScheduledRetry,+ }),+ cancelStaleQueuedRun: createCancelStaleQueuedRun({+ writer: adapter,+ }),+ dispatchResolvedInteractionIfCurrent: createDispatchResolvedInteractionIfCurrent({+ writer: adapter,+ }),+ };+}++export type RunDispatch = ReturnType<typeof createRunDispatch>;diff --git a/server/src/services/agent-task-run-telemetry.ts b/server/src/services/agent-task-run-telemetry.tsindex 6a1941d68f..c7fb031276 100644--- a/server/src/services/agent-task-run-telemetry.ts+++ b/server/src/services/agent-task-run-telemetry.ts@@ -1,4 +1,4 @@-import { eq } from "drizzle-orm";+import { and, eq } from "drizzle-orm";import { agents, heartbeatRuns, type Db } from "@paperclipai/db";import { trackAgentTaskRun } from "@paperclipai/shared/telemetry";import { parseObject } from "../adapters/utils.js";@@ -122,3 +122,20 @@ export async function emitAgentTaskRun(db: Db, run: HeartbeatRun): Promise<void>);}}++/** Loads a committed run before emitting telemetry, keeping database rows out of application contracts. */+export async function emitAgentTaskRunById(+ db: Db,+ input: { runId: string; companyId: string },+): Promise<void> {+ try {+ const run = await db+ .select()+ .from(heartbeatRuns)+ .where(and(eq(heartbeatRuns.id, input.runId), eq(heartbeatRuns.companyId, input.companyId)))+ .then((rows) => rows[0] ?? null);+ if (run) await emitAgentTaskRun(db, run);+ } catch (err) {+ logger.warn({ err, runId: input.runId }, "failed to load run for agent.task_run telemetry");+ }+}diff --git a/server/src/services/heartbeat.ts b/server/src/services/heartbeat.tsindex 3d80e7af99..ca370ddda5 100644--- a/server/src/services/heartbeat.ts+++ b/server/src/services/heartbeat.ts@@ -193,7 +193,7 @@ import {import { costService } from "./costs.js";import { trackAgentFirstHeartbeat } from "@paperclipai/shared/telemetry";import { getTelemetryClient } from "../telemetry.js";-import { emitAgentTaskRun } from "./agent-task-run-telemetry.js";+import { emitAgentTaskRun, emitAgentTaskRunById } from "./agent-task-run-telemetry.js";import { companySkillService } from "./company-skills.js";import { budgetService, type BudgetEnforcementScope } from "./budgets.js";import { secretService, type MissingRuntimeBinding } from "./secrets.js";@@ -367,7 +367,20 @@ import {ACTIVE_RUN_OUTPUT_SUSPICION_THRESHOLD_MS as RECOVERY_ACTIVE_RUN_OUTPUT_SUSPICION_THRESHOLD_MS,recoveryService,} from "./recovery/service.js";-import { collectDispositionRepairSourceState } from "./recovery/disposition-repair.js";+import {+ createRunDispatch,+ type PostCommitEffect,+ MAX_TURN_CONTINUATION_RETRY_REASON,+ WORKSPACE_BUSY_RETRY_REASON,+ INTERACTION_CONTINUATION_INFRA_RETRY_REASON,+ INTERACTION_CONTINUATION_INFRA_WAKE_REASON,+ WAKE_COMMENT_IDS_KEY,+ isNonAssigneeWorkspaceBusyRetry,+ extractWakeCommentIds,+ deriveCommentId,+ allowsIssueInteractionWake,+ isResolvedInteractionContinuationWakeContext,+} from "../modules/run-dispatch/index.js";import {buildIssueReviewPathLostIdempotencyKey,decideIssueReviewPathRecovery,@@ -497,7 +510,6 @@ const LIVENESS_BOOKKEEPING_ACTIVITY_ACTIONS = ["environment.lease_released",];const DEFERRED_WAKE_CONTEXT_KEY = "_paperclipWakeContext";-const WAKE_COMMENT_IDS_KEY = "wakeCommentIds";const PAPERCLIP_WAKE_PAYLOAD_KEY = "paperclipWake";const ACCEPTED_PLAN_CONVERSION_SKILL_KEY ="paperclipai/paperclip/paperclip-converting-plans-to-tasks";@@ -619,16 +631,8 @@ const BOUNDED_TRANSIENT_HEARTBEAT_RETRY_REASON = "transient_failure";const BOUNDED_TRANSIENT_HEARTBEAT_RETRY_WAKE_REASON = "transient_failure_retry";const BOUNDED_TRANSIENT_HEARTBEAT_RETRY_MAX_ATTEMPTS =BOUNDED_TRANSIENT_HEARTBEAT_RETRY_DELAYS_MS.length;-export const INTERACTION_CONTINUATION_INFRA_RETRY_REASON =- "interaction_continuation_infra_retry";-export const INTERACTION_CONTINUATION_INFRA_WAKE_REASON =- "interaction_continuation_infra_retry";+export { INTERACTION_CONTINUATION_INFRA_RETRY_REASON, INTERACTION_CONTINUATION_INFRA_WAKE_REASON };const INTERACTION_CONTINUATION_INFRA_MAX_ATTEMPTS = 3;-const RESOLVED_INTERACTION_CONTINUATION_STATUSES = new Set([- "accepted",- "answered",- "rejected",-]);const WORKSPACE_VALIDATION_FAILURE_CODE = "workspace_validation_failed";const WORKSPACE_VALIDATION_RECOVERY_CAUSE = "workspace_validation_failed";const CONFIGURATION_INCOMPLETE_FAILURE_CODE = "configuration_incomplete";@@ -663,7 +667,7 @@ const GIT_SENSITIVE_LOCAL_ADAPTER_TYPES = new Set(["opencode_local","pi_local",]);-export const MAX_TURN_CONTINUATION_RETRY_REASON = "max_turns_continuation";+export { MAX_TURN_CONTINUATION_RETRY_REASON };export const MAX_TURN_CONTINUATION_WAKE_REASON = "max_turns_continuation_retry";const MAX_TURN_CONTINUATION_DEFAULT_MAX_ATTEMPTS = 2;const MAX_TURN_CONTINUATION_MAX_ATTEMPTS_CAP = 10;@@ -674,7 +678,7 @@ const MAX_TURN_CONTINUATION_LIVE_RUN_STATUSES = ["queued","running",] as const;-export const WORKSPACE_BUSY_RETRY_REASON = "workspace_busy";+export { WORKSPACE_BUSY_RETRY_REASON };export const WORKSPACE_BUSY_RETRY_WAKE_REASON = "workspace_busy_retry";export const WORKSPACE_BUSY_ERROR_CODE = "workspace_busy";export const WORKSPACE_BUSY_RETRY_BASE_DELAY_MS = 60 * 1000;@@ -852,21 +856,7 @@ export function computeWorkspaceBusyRetryDelayMs();}-// True for the retry of a workspace-busy deferral whose original run did NOT-// execute under assignee-ship (a comment or review-participant wake). For such-// a retry an assignee mismatch is the expected state, so the reassignment-// protections in the promotion gate and the claim-time staleness check must-// not cancel it — cancelling would silently drop the wake the deferral-// promised to replay.-export function isNonAssigneeWorkspaceBusyRetry(- retryReason: string | null | undefined,- contextSnapshot: Record<string, unknown>,-) {- return (- retryReason === WORKSPACE_BUSY_RETRY_REASON &&- contextSnapshot.workspaceBusyDeferredWhileAssignee === false- );-}+export { isNonAssigneeWorkspaceBusyRetry };function resolveCodexTransientFallbackMode(attempt: number,@@ -936,25 +926,6 @@ function readTransientRecoveryContractFromRun(: null;}-function isResolvedInteractionContinuationWakeContext(- contextSnapshot: unknown,-) {- const context = parseObject(contextSnapshot);- const interactionId = readNonEmptyString(context.interactionId);- const interactionStatus = readNonEmptyString(context.interactionStatus);- if (!interactionId || !interactionStatus) return false;- if (!RESOLVED_INTERACTION_CONTINUATION_STATUSES.has(interactionStatus))- return false;-- const mutation = readNonEmptyString(context.mutation);- const wakeReason = readNonEmptyString(context.wakeReason);- const retryReason = readNonEmptyString(context.retryReason);- return (- (mutation === "interaction" && wakeReason === "issue_commented") ||- wakeReason === INTERACTION_CONTINUATION_INFRA_WAKE_REASON ||- retryReason === INTERACTION_CONTINUATION_INFRA_RETRY_REASON- );-}function isSpawnLikeFailureMessage(value: unknown) {if (typeof value !== "string") return false;@@ -5315,18 +5286,6 @@ function shouldRequireIssueCommentForWake();}-function allowsIssueInteractionWake(- contextSnapshot: Record<string, unknown> | null | undefined,-) {- const wakeReason = readNonEmptyString(contextSnapshot?.wakeReason);- if (- !wakeReason ||- !ISSUE_TREE_CONTROL_INTERACTION_WAKE_REASONS.has(wakeReason)- )- return false;- return Boolean(deriveCommentId(contextSnapshot, null));-}-async function listUnresolvedBlockerSummaries(dbOrTx: Pick<Db, "select">,companyId: string,@@ -6648,33 +6607,7 @@ function isCheckoutConflictError(error: unknown): boolean {);}-function deriveCommentId(- contextSnapshot: Record<string, unknown> | null | undefined,- payload: Record<string, unknown> | null | undefined,-) {- const batchedCommentId = extractWakeCommentIds(contextSnapshot).at(-1);- return (- batchedCommentId ??- readNonEmptyString(contextSnapshot?.wakeCommentId) ??- readNonEmptyString(contextSnapshot?.commentId) ??- readNonEmptyString(payload?.commentId) ??- null- );-}--export function extractWakeCommentIds(- contextSnapshot: Record<string, unknown> | null | undefined,-): string[] {- const raw = contextSnapshot?.[WAKE_COMMENT_IDS_KEY];- if (!Array.isArray(raw)) return [];- const out: string[] = [];- for (const entry of raw) {- const value = readNonEmptyString(entry);- if (!value || out.includes(value)) continue;- out.push(value);- }- return out;-}+export { extractWakeCommentIds };function mergeWakeCommentIds(...values: Array<unknown>): string[] {const merged: string[] = [];@@ -8470,6 +8403,57 @@ export function heartbeatService(};const budgets = budgetService(db, budgetHooks);const recovery = recoveryService(db, { enqueueWakeup, liveRunExecutions });+ const runDispatch = createRunDispatch(db);++ // Applies the post-commit effects a run-dispatch operation returns, on a+ // best-effort basis, exactly as this service publishes them for every+ // other run write. A publish failure never rolls back the write that+ // already committed.+ function applyRunDispatchPostCommitEffects(effects: PostCommitEffect[]) {+ for (const effect of effects) {+ if (effect.kind === "run_queued") {+ publishLiveEvent({+ companyId: effect.companyId,+ type: "heartbeat.run.queued",+ payload: {+ runId: effect.runId,+ agentId: effect.agentId,+ invocationSource: effect.invocationSource,+ triggerDetail: effect.triggerDetail,+ wakeupRequestId: effect.wakeupRequestId,+ },+ });+ } else {+ publishLiveEvent({+ companyId: effect.companyId,+ type: "heartbeat.run.status",+ payload: buildHeartbeatRunStatusLiveEventPayload({+ id: effect.runId,+ agentId: effect.agentId,+ status: effect.status,+ invocationSource: effect.invocationSource,+ triggerDetail: effect.triggerDetail,+ error: effect.error,+ errorCode: effect.errorCode,+ startedAt: effect.startedAt,+ finishedAt: effect.finishedAt,+ resultJson: effect.result,+ }),+ });+ publishRunLifecyclePluginEventData(effect);+ if (+ isHeartbeatRunTerminalStatus(effect.status) &&+ effect.previousStatus !== effect.status+ ) {+ clearHeartbeatRunRuntimeStatus(effect.runId);+ void emitAgentTaskRunById(db, {+ runId: effect.runId,+ companyId: effect.companyId,+ });+ }+ }+ }+ }function isPlanApprovalConfirmationPayload(payload: unknown) {const target = parseObject(parseObject(payload).target);@@ -11173,6 +11157,34 @@ export function heartbeatService(function publishRunLifecyclePluginEvent(run: typeof heartbeatRuns.$inferSelect,) {+ publishRunLifecyclePluginEventData({+ companyId: run.companyId,+ runId: run.id,+ agentId: run.agentId,+ status: run.status,+ invocationSource: run.invocationSource,+ triggerDetail: run.triggerDetail,+ error: run.error,+ errorCode: run.errorCode,+ issueId: readNonEmptyString(parseObject(run.contextSnapshot).issueId),+ startedAt: run.startedAt,+ finishedAt: run.finishedAt,+ });+ }++ function publishRunLifecyclePluginEventData(run: {+ companyId: string;+ runId: string;+ agentId: string;+ status: string;+ invocationSource: string;+ triggerDetail: string | null;+ error: string | null;+ errorCode: string | null;+ issueId: string | null;+ startedAt: Date | null;+ finishedAt: Date | null;+ }) {const eventType =run.status === "running"? "agent.run.started"@@ -11190,22 +11202,18 @@ export function heartbeatService(occurredAt: new Date().toISOString(),actorId: run.agentId,actorType: "agent",- entityId: run.id,+ entityId: run.runId,entityType: "heartbeat_run",companyId: run.companyId,payload: {- runId: run.id,+ runId: run.runId,agentId: run.agentId,status: run.status,invocationSource: run.invocationSource,triggerDetail: run.triggerDetail,error: run.error ?? null,errorCode: run.errorCode ?? null,- issueId:- typeof run.contextSnapshot === "object" &&- run.contextSnapshot !== null- ? ((run.contextSnapshot as Record<string, unknown>).issueId ?? null)- : null,+ issueId: run.issueId,startedAt: run.startedAt ? new Date(run.startedAt).toISOString() : null,finishedAt: run.finishedAt? new Date(run.finishedAt).toISOString()@@ -13504,624 +13512,151 @@ export function heartbeatService(};}- type ScheduledRetryGate =- | { allowed: true }- | {- allowed: false;- reason: string;- errorCode:- | "agent_not_invokable"- | "heartbeat_wake_on_demand_disabled"- | "budget_blocked"- | "issue_not_found"- | "issue_reassigned"- | "issue_cancelled"- | "issue_terminal_status"- | "issue_not_in_progress"- | "issue_execution_lock_changed"- | "issue_review_participant_changed"- | "issue_paused"- | "issue_dependencies_blocked"- | "issue_disposition_repair_superseded";- issueId: string | null;- details: Record<string, unknown>;- };- type BlockedScheduledRetryGate = Extract<- ScheduledRetryGate,- { allowed: false }- >;-- async function evaluateScheduledRetryGate(input: {- run: typeof heartbeatRuns.$inferSelect;- agent: typeof agents.$inferSelect;- contextSnapshot: Record<string, unknown>;- retryReason?: string | null;- enforceIssueExecutionLock?: boolean;- }): Promise<ScheduledRetryGate> {- const { run, agent, contextSnapshot } = input;+ async function scheduleBoundedRetryForRun(+ run: typeof heartbeatRuns.$inferSelect,+ agent: typeof agents.$inferSelect,+ opts?: {+ now?: Date;+ random?: () => number;+ retryReason?: string;+ wakeReason?: string;+ maxAttempts?: number;+ delayMs?: number;+ },+ ) {+ const now = opts?.now ?? new Date();const retryReason =- input.retryReason ??- readNonEmptyString(contextSnapshot.retryReason) ??- run.scheduledRetryReason ??- null;- const issueId = readNonEmptyString(contextSnapshot.issueId);- const projectId = readNonEmptyString(contextSnapshot.projectId);-- const budgetBlock = await budgets.getInvocationBlock(- run.companyId,- run.agentId,- {- issueId,- projectId,- },+ opts?.retryReason ?? BOUNDED_TRANSIENT_HEARTBEAT_RETRY_REASON;+ const wakeReason =+ opts?.wakeReason ?? BOUNDED_TRANSIENT_HEARTBEAT_RETRY_WAKE_REASON;+ const maxAttempts = Math.max(+ 0,+ Math.floor(+ opts?.maxAttempts ?? BOUNDED_TRANSIENT_HEARTBEAT_RETRY_MAX_ATTEMPTS,+ ),);- if (budgetBlock) {- return {- allowed: false,- reason: budgetBlock.reason,- errorCode: "budget_blocked",- issueId,- details: {- scopeType: budgetBlock.scopeType,- scopeId: budgetBlock.scopeId,- },- };- }+ const nextAttempt = (run.scheduledRetryAttempt ?? 0) + 1;+ const computedBaseSchedule =+ opts?.delayMs != null+ ? nextAttempt <= maxAttempts+ ? {+ attempt: nextAttempt,+ baseDelayMs: Math.max(0, Math.floor(opts.delayMs)),+ delayMs: Math.max(0, Math.floor(opts.delayMs)),+ dueAt: new Date(+ now.getTime() + Math.max(0, Math.floor(opts.delayMs)),+ ),+ maxAttempts,+ }+ : null+ : nextAttempt <= maxAttempts+ ? computeBoundedTransientHeartbeatRetrySchedule(+ nextAttempt,+ now,+ opts?.random,+ )+ : null;+ const baseSchedule = computedBaseSchedule+ ? { ...computedBaseSchedule, maxAttempts }+ : null;+ const transientRecovery =+ retryReason === BOUNDED_TRANSIENT_HEARTBEAT_RETRY_REASON+ ? readTransientRecoveryContractFromRun(run)+ : null;+ const codexTransientFallbackMode =+ agent.adapterType === "codex_local" &&+ transientRecovery?.errorFamily === "transient_upstream"+ ? resolveCodexTransientFallbackMode(nextAttempt)+ : null;+ const transientRetryNotBefore = transientRecovery?.retryNotBefore ?? null;+ const contextSnapshot = parseObject(run.contextSnapshot);+ const issueId = readNonEmptyString(contextSnapshot.issueId);- const agentInvokability = await getAgentInvokability(agent);- if (!agentInvokability.invokable) {- return {- allowed: false,- reason: "Scheduled retry suppressed because the agent is not invokable",- errorCode: "agent_not_invokable",- issueId,- details: {- ...agentInvokability.details,- invalidOrgChain: agentInvokability.invalidOrgChain,+ if (!baseSchedule) {+ await appendRunEvent(run, {+ eventType: "lifecycle",+ stream: "system",+ level: "warn",+ message: `Bounded retry exhausted after ${run.scheduledRetryAttempt ?? 0} scheduled attempts; no further automatic retry will be queued`,+ payload: {+ retryReason,+ scheduledRetryAttempt: run.scheduledRetryAttempt ?? 0,+ maxAttempts,},- };- }-- if (!isHeartbeatWakeOnDemandEnabled(agent)) {- return {- allowed: false,- reason:- "Scheduled retry suppressed because on-demand agent wakes are disabled",- errorCode: "heartbeat_wake_on_demand_disabled",- issueId,- details: { agentId: agent.id },- };- }-- if (!issueId) return { allowed: true };-- const issue = await db- .select({- id: issues.id,- companyId: issues.companyId,- status: issues.status,- assigneeAgentId: issues.assigneeAgentId,- assigneeUserId: issues.assigneeUserId,- executionRunId: issues.executionRunId,- executionPolicy: issues.executionPolicy,- executionState: issues.executionState,- monitorNextCheckAt: issues.monitorNextCheckAt,- })- .from(issues)- .where(and(eq(issues.id, issueId), eq(issues.companyId, run.companyId)))- .then((rows) => rows[0] ?? null);-- if (!issue) {+ });+ if (retryReason === INTERACTION_CONTINUATION_INFRA_RETRY_REASON) {+ await escalatePlanApprovalResumeFailureNeedsAttention({+ run,+ issueId,+ attempt: Math.min(+ run.scheduledRetryAttempt ?? maxAttempts,+ maxAttempts,+ ),+ maxAttempts,+ }).catch((error) => {+ logger.warn(+ { err: error, runId: run.id, issueId },+ "failed to escalate exhausted plan-approval resume failure",+ );+ });+ }return {- allowed: false,- reason:- "Scheduled retry suppressed because the target issue no longer exists",- errorCode: "issue_not_found",- issueId,- details: { issueId },+ outcome: "retry_exhausted" as const,+ attempt: nextAttempt,+ maxAttempts,};}- if (retryReason === ISSUE_DISPOSITION_REPAIR_RETRY_REASON) {- const expectedFingerprint = readNonEmptyString(- contextSnapshot.dispositionRepairFingerprint,- );- const sourceState = await collectDispositionRepairSourceState(db, {- issue,- excludeRunId: run.id,- excludeWakeupRequestId: run.wakeupRequestId,- });- if (- !expectedFingerprint ||- sourceState.fingerprint !== expectedFingerprint ||- sourceState.hasActiveExecutionPath ||- sourceState.hasDurableWaitingPath- ) {+ if (retryReason !== MAX_TURN_CONTINUATION_RETRY_REASON) {+ const invokability = await getAgentInvokability(agent);+ if (!invokability.invokable) {+ await appendRunEvent(run, {+ eventType: "lifecycle",+ stream: "system",+ level: "warn",+ message:+ "Scheduled retry suppressed because the agent is not invokable",+ payload: {+ retryReason,+ scheduledRetryAttempt: nextAttempt,+ maxAttempts,+ reason: invokability.reason,+ invalidOrgChain: invokability.invalidOrgChain,+ ...invokability.details,+ },+ });return {- allowed: false,+ outcome: "not_scheduled" as const,reason:- "Scheduled disposition repair suppressed because the source state changed or gained a durable path",- errorCode: "issue_disposition_repair_superseded",+ "Scheduled retry suppressed because the agent is not invokable",+ errorCode: "agent_not_invokable" as const,issueId,- details: {- issueId,- expectedFingerprint,- currentFingerprint: sourceState.fingerprint,- hasActiveExecutionPath: sourceState.hasActiveExecutionPath,- durablePathReason: sourceState.durablePathReason,- },};}}- if (issue.assigneeAgentId !== run.agentId) {- if (!isNonAssigneeWorkspaceBusyRetry(retryReason, contextSnapshot)) {- return {- allowed: false,- reason: "Scheduled retry suppressed because issue ownership changed",- errorCode: "issue_reassigned",- issueId,- details: {- issueId,- previousAssigneeAgentId: run.agentId,- currentAssigneeAgentId: issue.assigneeAgentId,- },- };- }- }-- if (issue.status === "cancelled" || issue.status === "done") {- return {- allowed: false,- reason: `Scheduled retry suppressed because issue reached terminal status (${issue.status})`,- errorCode:- issue.status === "cancelled"- ? "issue_cancelled"- : "issue_terminal_status",- issueId,- details: { issueId, currentStatus: issue.status },- };- }-- if (- retryReason === MAX_TURN_CONTINUATION_RETRY_REASON &&- issue.status !== "in_progress"- ) {- return {- allowed: false,- reason: `Scheduled max-turn continuation suppressed because issue is no longer in_progress (current status: ${issue.status})`,- errorCode: "issue_not_in_progress",- issueId,- details: {- issueId,- currentStatus: issue.status,- requiredStatus: "in_progress",- },- };- }-- if (- retryReason === MAX_TURN_CONTINUATION_RETRY_REASON &&- input.enforceIssueExecutionLock &&- issue.executionRunId !== run.id- ) {- return {- allowed: false,- reason:- "Scheduled max-turn continuation suppressed because the issue execution lock belongs to a different run",- errorCode: "issue_execution_lock_changed",- issueId,- details: {- issueId,- expectedExecutionRunId: run.id,- currentExecutionRunId: issue.executionRunId,- },- };- }-- if (issue.status === "in_review") {- const executionState = parseIssueExecutionState(issue.executionState);- const currentParticipant = executionState?.currentParticipant ?? null;- if (currentParticipant) {- const participantMatches =- currentParticipant.type === "agent" &&- currentParticipant.agentId === run.agentId;- if (!participantMatches) {- return {- allowed: false,- reason:- "Scheduled retry suppressed because the issue is waiting on another review participant",- errorCode: "issue_review_participant_changed",- issueId,- details: {- issueId,- currentStageType: executionState?.currentStageType ?? null,- currentParticipant,- },- };- }- }- }-- const activePauseHold = await treeControlSvc.getActivePauseHoldGate(- run.companyId,- issueId,- );- if (activePauseHold) {- return {- allowed: false,- reason:- "Scheduled retry suppressed because the issue is held by an active subtree pause hold",- errorCode: "issue_paused",- issueId,- details: {- issueId,- holdId: activePauseHold.holdId,- rootIssueId: activePauseHold.rootIssueId,- },- };- }-- const dependencyReadiness = await issuesSvc.listDependencyReadiness(- run.companyId,- [issueId],- );- const readiness = dependencyReadiness.get(issueId);- if (readiness && !readiness.isDependencyReady) {- return {- allowed: false,- reason:- "Scheduled retry suppressed because issue dependencies are still blocked",- errorCode: "issue_dependencies_blocked",- issueId,- details: {- issueId,- unresolvedBlockerIssueIds: readiness.unresolvedBlockerIssueIds,- unresolvedBlockerCount: readiness.unresolvedBlockerCount,- },- };- }-- return { allowed: true };- }-- async function cancelScheduledRetryForGate(- run: typeof heartbeatRuns.$inferSelect,- gate: Extract<ScheduledRetryGate, { allowed: false }>,- now: Date,- ) {- const cancelled = await db- .update(heartbeatRuns)- .set({- status: "cancelled",- finishedAt: now,- error: gate.reason,- errorCode: gate.errorCode,- updatedAt: now,- })- .where(- and(- eq(heartbeatRuns.id, run.id),- eq(heartbeatRuns.status, "scheduled_retry"),- lte(heartbeatRuns.scheduledRetryAt, now),- ),- )- .returning()- .then((rows) => rows[0] ?? null);-- if (!cancelled) return null;-- // Telemetry is best-effort background work. Fire it in the background- // instead of awaiting it, so a slow telemetry lookup never delays the- // wake cancel, the issue lock clear, or this function's return.- void emitAgentTaskRun(db, cancelled);-- if (cancelled.wakeupRequestId) {- await db- .update(agentWakeupRequests)- .set({- status: "cancelled",- finishedAt: now,- error: gate.reason,- updatedAt: now,- })- .where(eq(agentWakeupRequests.id, cancelled.wakeupRequestId));- }-- if (gate.issueId) {- await db- .update(issues)- .set({- executionRunId: null,- executionAgentNameKey: null,- executionLockedAt: null,- updatedAt: now,- })- .where(- and(- eq(issues.companyId, cancelled.companyId),- eq(issues.id, gate.issueId),- eq(issues.executionRunId, cancelled.id),- ),- );- }-- await appendRunEvent(cancelled, {- eventType: "lifecycle",- stream: "system",- level: "warn",- message: gate.reason,- payload: {- ...gate.details,- scheduledRetryAttempt: cancelled.scheduledRetryAttempt,- scheduledRetryAt: cancelled.scheduledRetryAt- ? new Date(cancelled.scheduledRetryAt).toISOString()- : null,- scheduledRetryReason: cancelled.scheduledRetryReason,- },- });-- return cancelled;- }-- async function promoteScheduledRetryRun(- dueRun: typeof heartbeatRuns.$inferSelect,- now: Date,- ): Promise<- | { outcome: "promoted"; run: typeof heartbeatRuns.$inferSelect }- | {- outcome: "gate_suppressed";- run: typeof heartbeatRuns.$inferSelect;- reason: string;- errorCode: BlockedScheduledRetryGate["errorCode"];- }- | { outcome: "not_promoted"; run: typeof heartbeatRuns.$inferSelect | null }- > {- const agent = await getAgent(dueRun.agentId);- if (!agent) {- const gate = {- allowed: false as const,- reason: "Scheduled retry suppressed because the agent no longer exists",- errorCode: "agent_not_invokable" as const,- issueId: readNonEmptyString(- parseObject(dueRun.contextSnapshot).issueId,- ),- details: { agentId: dueRun.agentId },- };- const cancelled = await cancelScheduledRetryForGate(dueRun, gate, now);- return cancelled- ? {- outcome: "gate_suppressed",- run: cancelled,- reason: gate.reason,- errorCode: gate.errorCode,- }- : { outcome: "not_promoted", run: null };- }-- const contextSnapshot = parseObject(dueRun.contextSnapshot);- const gate = await evaluateScheduledRetryGate({- run: dueRun,- agent,- contextSnapshot,- retryReason: dueRun.scheduledRetryReason,- enforceIssueExecutionLock:- dueRun.scheduledRetryReason === MAX_TURN_CONTINUATION_RETRY_REASON,- });- if (!gate.allowed) {- if (- gate.errorCode === "issue_not_found" &&- dueRun.scheduledRetryReason !== MAX_TURN_CONTINUATION_RETRY_REASON- ) {- // Preserve legacy transient retry behavior for runs that only carry a- // loose task context rather than a persisted issue row.- } else {- const cancelled = await cancelScheduledRetryForGate(dueRun, gate, now);- return cancelled- ? {- outcome: "gate_suppressed",- run: cancelled,- reason: gate.reason,- errorCode: gate.errorCode,- }- : { outcome: "not_promoted", run: null };- }- }-- const promoted = await db- .update(heartbeatRuns)- .set({- status: "queued",- updatedAt: now,- })- .where(- and(- eq(heartbeatRuns.id, dueRun.id),- eq(heartbeatRuns.status, "scheduled_retry"),- lte(heartbeatRuns.scheduledRetryAt, now),- ),- )- .returning()- .then((rows) => rows[0] ?? null);- if (!promoted) return { outcome: "not_promoted", run: null };-- await appendRunEvent(promoted, {- eventType: "lifecycle",- stream: "system",- level: "info",- message:- "Scheduled retry became due and was promoted to the queued run pool",- payload: {- scheduledRetryAttempt: promoted.scheduledRetryAttempt,- scheduledRetryAt: promoted.scheduledRetryAt- ? new Date(promoted.scheduledRetryAt).toISOString()- : null,- scheduledRetryReason: promoted.scheduledRetryReason,- },- });-- publishLiveEvent({- companyId: promoted.companyId,- type: "heartbeat.run.queued",- payload: {- runId: promoted.id,- agentId: promoted.agentId,- invocationSource: promoted.invocationSource,- triggerDetail: promoted.triggerDetail,- wakeupRequestId: promoted.wakeupRequestId,- },- });-- return { outcome: "promoted", run: promoted };- }-- async function scheduleBoundedRetryForRun(- run: typeof heartbeatRuns.$inferSelect,- agent: typeof agents.$inferSelect,- opts?: {- now?: Date;- random?: () => number;- retryReason?: string;- wakeReason?: string;- maxAttempts?: number;- delayMs?: number;- },- ) {- const now = opts?.now ?? new Date();- const retryReason =- opts?.retryReason ?? BOUNDED_TRANSIENT_HEARTBEAT_RETRY_REASON;- const wakeReason =- opts?.wakeReason ?? BOUNDED_TRANSIENT_HEARTBEAT_RETRY_WAKE_REASON;- const maxAttempts = Math.max(- 0,- Math.floor(- opts?.maxAttempts ?? BOUNDED_TRANSIENT_HEARTBEAT_RETRY_MAX_ATTEMPTS,- ),- );- const nextAttempt = (run.scheduledRetryAttempt ?? 0) + 1;- const computedBaseSchedule =- opts?.delayMs != null- ? nextAttempt <= maxAttempts- ? {- attempt: nextAttempt,- baseDelayMs: Math.max(0, Math.floor(opts.delayMs)),- delayMs: Math.max(0, Math.floor(opts.delayMs)),- dueAt: new Date(- now.getTime() + Math.max(0, Math.floor(opts.delayMs)),- ),- maxAttempts,- }- : null- : nextAttempt <= maxAttempts- ? computeBoundedTransientHeartbeatRetrySchedule(- nextAttempt,- now,- opts?.random,- )- : null;- const baseSchedule = computedBaseSchedule- ? { ...computedBaseSchedule, maxAttempts }- : null;- const transientRecovery =- retryReason === BOUNDED_TRANSIENT_HEARTBEAT_RETRY_REASON- ? readTransientRecoveryContractFromRun(run)- : null;- const codexTransientFallbackMode =- agent.adapterType === "codex_local" &&- transientRecovery?.errorFamily === "transient_upstream"- ? resolveCodexTransientFallbackMode(nextAttempt)- : null;- const transientRetryNotBefore = transientRecovery?.retryNotBefore ?? null;- const contextSnapshot = parseObject(run.contextSnapshot);- const issueId = readNonEmptyString(contextSnapshot.issueId);-- if (!baseSchedule) {- await appendRunEvent(run, {- eventType: "lifecycle",- stream: "system",- level: "warn",- message: `Bounded retry exhausted after ${run.scheduledRetryAttempt ?? 0} scheduled attempts; no further automatic retry will be queued`,- payload: {- retryReason,- scheduledRetryAttempt: run.scheduledRetryAttempt ?? 0,- maxAttempts,- },- });- if (retryReason === INTERACTION_CONTINUATION_INFRA_RETRY_REASON) {- await escalatePlanApprovalResumeFailureNeedsAttention({- run,- issueId,- attempt: Math.min(- run.scheduledRetryAttempt ?? maxAttempts,- maxAttempts,- ),- maxAttempts,- }).catch((error) => {- logger.warn(- { err: error, runId: run.id, issueId },- "failed to escalate exhausted plan-approval resume failure",- );- });- }- return {- outcome: "retry_exhausted" as const,- attempt: nextAttempt,- maxAttempts,- };- }-- if (retryReason !== MAX_TURN_CONTINUATION_RETRY_REASON) {- const invokability = await getAgentInvokability(agent);- if (!invokability.invokable) {- await appendRunEvent(run, {- eventType: "lifecycle",- stream: "system",- level: "warn",- message:- "Scheduled retry suppressed because the agent is not invokable",- payload: {- retryReason,- scheduledRetryAttempt: nextAttempt,- maxAttempts,- reason: invokability.reason,- invalidOrgChain: invokability.invalidOrgChain,- ...invokability.details,- },- });- return {- outcome: "not_scheduled" as const,- reason:- "Scheduled retry suppressed because the agent is not invokable",- errorCode: "agent_not_invokable" as const,- issueId,- };- }- }-- const schedule =- transientRetryNotBefore &&- transientRetryNotBefore.getTime() > baseSchedule.dueAt.getTime()- ? {- ...baseSchedule,- dueAt: transientRetryNotBefore,- delayMs: Math.max(- 0,- transientRetryNotBefore.getTime() - now.getTime(),- ),- }- : baseSchedule;+ const schedule =+ transientRetryNotBefore &&+ transientRetryNotBefore.getTime() > baseSchedule.dueAt.getTime()+ ? {+ ...baseSchedule,+ dueAt: transientRetryNotBefore,+ delayMs: Math.max(+ 0,+ transientRetryNotBefore.getTime() - now.getTime(),+ ),+ }+ : baseSchedule;const requiresIssueGate =retryReason === MAX_TURN_CONTINUATION_RETRY_REASON ||retryReason === INTERACTION_CONTINUATION_INFRA_RETRY_REASON;if (requiresIssueGate) {- const gate = await evaluateScheduledRetryGate({- run,- agent,- contextSnapshot,- retryReason,- enforceIssueExecutionLock:- retryReason === MAX_TURN_CONTINUATION_RETRY_REASON,+ const gate = await runDispatch.evaluateScheduledRetryGate({+ runId: run.id,+ companyId: run.companyId,+ retryReasonOverride: retryReason,+ now,});if (!gate.allowed) {await appendRunEvent(run, {@@ -14993,36 +14528,9 @@ export function heartbeatService(async function promoteDueScheduledRetries(now = new Date()) {const cutoff = await getWorktreeExecutionCutoff();- const dueRuns = await db- .select()- .from(heartbeatRuns)- .where(- and(- eq(heartbeatRuns.status, "scheduled_retry"),- lte(heartbeatRuns.scheduledRetryAt, now),- cutoff ? gte(heartbeatRuns.createdAt, cutoff) : undefined,- ),- )- .orderBy(- asc(heartbeatRuns.scheduledRetryAt),- asc(heartbeatRuns.createdAt),- asc(heartbeatRuns.id),- )- .limit(50);-- const promotedRunIds: string[] = [];-- for (const dueRun of dueRuns) {- const result = await promoteScheduledRetryRun(dueRun, now);- if (result.outcome === "promoted") {- promotedRunIds.push(result.run.id);- }- }-- return {- promoted: promotedRunIds.length,- runIds: promotedRunIds,- };+ const result = await runDispatch.promoteDueScheduledRetries({ now, cutoff });+ applyRunDispatchPostCommitEffects(result.postCommitEffects);+ return { promoted: result.promoted, runIds: result.runIds };}async function getIssueRetryRun(@@ -15200,7 +14708,14 @@ export function heartbeatService(},});- const promotion = await promoteScheduledRetryRun(updated, now);+ const promotion = await runDispatch.promoteScheduledRetry({+ runId: updated.id,+ companyId: updated.companyId,+ now,+ });+ if (promotion.outcome === "promoted") {+ applyRunDispatchPostCommitEffects(promotion.postCommitEffects);+ }const promotedRow = await getIssueRetryRun(issue.companyId, issue.id, ["queued","running",@@ -15209,7 +14724,7 @@ export function heartbeatService(const scheduledRetry = promotedRow? summarizeIssueScheduledRetryRun(promotedRow): summarizeIssueScheduledRetryRun({- run: promotion.run ?? updated,+ run: updated,agentName: scheduled.agentName,});@@ -15667,7 +15182,10 @@ export function heartbeatService();const readiness = dependencyReadiness.get(issueId);const unresolvedBlockerCount = readiness?.unresolvedBlockerCount ?? 0;- if (unresolvedBlockerCount > 0 && !allowsIssueInteractionWake(context)) {+ if (+ unresolvedBlockerCount > 0 &&+ !allowsIssueInteractionWake(context, ISSUE_TREE_CONTROL_INTERACTION_WAKE_REASONS)+ ) {await cancelQueuedRunForBlockedDependencies(run,issueId,@@ -15680,9 +15198,13 @@ export function heartbeatService(return null;}- const staleness = await evaluateQueuedRunStaleness(run, issueId, context);- if (staleness.stale) {- await cancelRunForStaleIssue(run, issueId, staleness);+ const staleness = await runDispatch.cancelStaleQueuedRun({+ runId: run.id,+ companyId: run.companyId,+ expectedStatus: "queued",+ });+ if (staleness.outcome === "cancelled") {+ applyRunDispatchPostCommitEffects(staleness.postCommitEffects);logger.info({ runId: run.id, issueId, errorCode: staleness.errorCode },"claimQueuedRun: cancelled stale queued run",@@ -16124,302 +15646,6 @@ export function heartbeatService(return cancelled;}- type QueuedRunStaleness =- | { stale: false }- | {- stale: true;- reason: string;- errorCode:- | "issue_not_found"- | "issue_assignee_changed"- | "issue_terminal_status"- | "issue_not_in_progress"- | "issue_execution_lock_changed"- | "issue_review_participant_changed"- | "issue_continuation_waiting_on_review";- details: Record<string, unknown>;- };-- async function evaluateQueuedRunStaleness(- run: typeof heartbeatRuns.$inferSelect,- issueId: string,- context: Record<string, unknown>,- dbOrTx: Db = db,- ): Promise<QueuedRunStaleness> {- const issue = await dbOrTx- .select({- id: issues.id,- status: issues.status,- assigneeAgentId: issues.assigneeAgentId,- executionRunId: issues.executionRunId,- executionState: issues.executionState,- })- .from(issues)- .where(and(eq(issues.id, issueId), eq(issues.companyId, run.companyId)))- .then((rows) => rows[0] ?? null);-- if (!issue) {- return {- stale: true,- errorCode: "issue_not_found",- reason: "Cancelled because the target issue no longer exists",- details: { issueId },- };- }-- const wakeCommentId = deriveCommentId(context, null);- const isInteractionWake = allowsIssueInteractionWake(context);- const resumeIntent =- context.resumeIntent === true || context.followUpRequested === true;- const wakeReason = readNonEmptyString(context.wakeReason);- const retryReason =- readNonEmptyString(context.retryReason) ??- run.scheduledRetryReason ??- null;- const interactionResolvedAt = readNonEmptyString(- context.interactionResolvedAt,- );- const hasResolvedInteractionEvidence =- interactionResolvedAt !== null &&- !Number.isNaN(Date.parse(interactionResolvedAt));- const isResolvedInteractionContinuation =- isResolvedInteractionContinuationWakeContext(context);-- if (isResolvedInteractionContinuation && issue.status !== "in_progress") {- return {- stale: true,- errorCode: "issue_not_in_progress",- reason: `Cancelled because resolved-interaction continuation issue is no longer in_progress (current status: ${issue.status}) before the queued run could start`,- details: {- issueId,- currentStatus: issue.status,- requiredStatus: "in_progress",- },- };- }-- if (- isResolvedInteractionContinuation &&- issue.assigneeAgentId !== run.agentId- ) {- return {- stale: true,- errorCode: "issue_assignee_changed",- reason:- "Cancelled because resolved-interaction continuation issue changed assignee before the queued run could start",- details: {- issueId,- previousAssigneeAgentId: run.agentId,- currentAssigneeAgentId: issue.assigneeAgentId,- },- };- }-- if (- issue.status === "in_progress" &&- !wakeCommentId &&- !hasResolvedInteractionEvidence &&- (wakeReason === "issue_continuation_needed" ||- retryReason === "issue_continuation_needed")- ) {- const queuedWake = parseObject(context.paperclipWake);- const queuedContinuationSummary =- readNonEmptyString(- parseObject(context.paperclipContinuationSummary).body,- ) ??- readNonEmptyString(parseObject(queuedWake.continuationSummary).body);- const currentContinuationSummary = queuedContinuationSummary- ? null- : await getIssueContinuationSummaryDocument(dbOrTx, issueId);- const continuationSummaryBody =- queuedContinuationSummary ?? currentContinuationSummary?.body ?? null;- if (continuationSummaryParksExecutor(continuationSummaryBody)) {- return {- stale: true,- errorCode: "issue_continuation_waiting_on_review",- reason:- "Cancelled because the continuation summary says the executor should wait for reviewer feedback or approval before more work starts",- details: {- issueId,- wakeReason,- retryReason,- nextAction: continuationSummaryBody,- },- };- }- }-- const reviewExecutionState =- issue.status === "in_review"- ? parseIssueExecutionState(issue.executionState)- : null;- const reviewParticipant = reviewExecutionState?.currentParticipant ?? null;- const isCurrentReviewParticipant =- reviewParticipant?.type === "agent" &&- reviewParticipant.agentId === run.agentId;-- const recoveryActionId = readNonEmptyString(context.recoveryActionId);- const authorizedSourceScopedRecovery =- wakeReason === "source_scoped_recovery_action" && recoveryActionId- ? await dbOrTx- .select({ id: issueRecoveryActions.id })- .from(issueRecoveryActions)- .where(- and(- eq(issueRecoveryActions.id, recoveryActionId),- eq(issueRecoveryActions.companyId, run.companyId),- eq(issueRecoveryActions.sourceIssueId, issue.id),- eq(issueRecoveryActions.ownerAgentId, run.agentId),- inArray(issueRecoveryActions.status, ["active", "escalated"]),- ),- )- .limit(1)- .then((rows) => Boolean(rows[0]))- : false;-- if (- issue.assigneeAgentId !== run.agentId &&- !isInteractionWake &&- !isCurrentReviewParticipant &&- !authorizedSourceScopedRecovery &&- !isNonAssigneeWorkspaceBusyRetry(retryReason, context)- ) {- return {- stale: true,- errorCode: "issue_assignee_changed",- reason:- "Cancelled because issue assignee changed before the queued run could start; the new owner will be woken instead",- details: {- issueId,- previousAssigneeAgentId: run.agentId,- currentAssigneeAgentId: issue.assigneeAgentId,- },- };- }-- if (issue.status === "done" || issue.status === "cancelled") {- if (!resumeIntent && !wakeCommentId) {- return {- stale: true,- errorCode: "issue_terminal_status",- reason: `Cancelled because issue reached terminal status (${issue.status}) before the queued run could start`,- details: { issueId, currentStatus: issue.status },- };- }- }-- if (- retryReason === MAX_TURN_CONTINUATION_RETRY_REASON &&- issue.status !== "in_progress"- ) {- return {- stale: true,- errorCode: "issue_not_in_progress",- reason: `Cancelled because max-turn continuation issue is no longer in_progress (current status: ${issue.status}) before the queued run could start`,- details: {- issueId,- currentStatus: issue.status,- requiredStatus: "in_progress",- },- };- }-- if (- retryReason === MAX_TURN_CONTINUATION_RETRY_REASON &&- issue.executionRunId !== run.id- ) {- return {- stale: true,- errorCode: "issue_execution_lock_changed",- reason:- "Cancelled because max-turn continuation no longer owns the issue execution lock before the queued run could start",- details: {- issueId,- expectedExecutionRunId: run.id,- currentExecutionRunId: issue.executionRunId,- },- };- }-- if (issue.status === "in_review") {- const currentParticipant =- reviewExecutionState?.currentParticipant ?? null;- if (currentParticipant) {- const participantMatches =- currentParticipant.type === "agent" &&- currentParticipant.agentId === run.agentId;- if (!participantMatches && !wakeCommentId) {- return {- stale: true,- errorCode: "issue_review_participant_changed",- reason:- "Cancelled because the in-review participant changed before the queued run could start; the current participant will be woken instead",- details: {- issueId,- currentStageType: reviewExecutionState?.currentStageType ?? null,- currentParticipant,- },- };- }- }- }-- return { stale: false };- }-- async function cancelRunForStaleIssue(- run: typeof heartbeatRuns.$inferSelect,- issueId: string,- staleness: Extract<QueuedRunStaleness, { stale: true }>,- ) {- const now = new Date();- const cancelled = await setRunStatus(run.id, "cancelled", {- finishedAt: now,- error: staleness.reason,- errorCode: staleness.errorCode,- resultJson: {- ...parseObject(run.resultJson),- stopReason: staleness.errorCode,- effectiveTimeoutSec: 0,- timeoutConfigured: false,- timeoutSource: "stale_queued_run_gate",- timeoutFired: false,- },- });- if (!cancelled) return null;-- await setWakeupStatus(run.wakeupRequestId, "skipped", {- finishedAt: now,- error: staleness.reason,- });-- await db- .update(issues)- .set({- executionRunId: null,- executionAgentNameKey: null,- executionLockedAt: null,- updatedAt: now,- })- .where(- and(- eq(issues.companyId, run.companyId),- eq(issues.id, issueId),- eq(issues.executionRunId, run.id),- ),- );-- await appendRunEvent(cancelled, {- eventType: "lifecycle",- stream: "system",- level: "warn",- message: staleness.reason,- payload: staleness.details,- });-- return cancelled;- }-function truncateAgentErrorReason(reason: string | null | undefined,): string | null {@@ -18245,13 +17471,13 @@ export function heartbeatService(context[PAPERCLIP_HARNESS_CHECKOUT_KEY] = true;} catch (error) {if (!isCheckoutConflictError(error)) throw error;- const staleness = await evaluateQueuedRunStaleness(- run,- issueId,- context,- );- if (staleness.stale) {- await cancelRunForStaleIssue(run, issueId, staleness);+ const staleness = await runDispatch.cancelStaleQueuedRun({+ runId: run.id,+ companyId: run.companyId,+ expectedStatus: "running",+ });+ if (staleness.outcome === "cancelled") {+ applyRunDispatchPostCommitEffects(staleness.postCommitEffects);return;}throw error;@@ -19844,68 +19070,28 @@ export function heartbeatService(issueId,});- const gate = await db.transaction(async (tx) => {- const lockedIssue = await tx- .select({ executionRunId: issues.executionRunId })- .from(issues)- .where(- and(eq(issues.id, issueId), eq(issues.companyId, run.companyId)),- )- .for("update")- .then((rows) => rows[0] ?? null);- const staleness = await evaluateQueuedRunStaleness(- run,- issueId,- context,- tx as unknown as Db,- );- if (staleness.stale) {- return { dispatched: false as const, staleness };- }- if (lockedIssue?.executionRunId !== run.id) {- return {- dispatched: false as const,- staleness: {- stale: true as const,- errorCode: "issue_execution_lock_changed" as const,- reason:- "Cancelled because resolved-interaction continuation no longer owns the issue execution lock before adapter dispatch",- details: {- issueId,- expectedExecutionRunId: run.id,- currentExecutionRunId: lockedIssue?.executionRunId ?? null,- },- },- };- }-- await options.afterResolvedInteractionContinuationDispatchCheck?.({- runId: run.id,- issueId,- });- let dispatchStarted = false;- let resolveDispatchStarted!: () => void;- const dispatchStartedPromise = new Promise<void>((resolve) => {- resolveDispatchStarted = resolve;- });- const markDispatchStarted = () => {- if (dispatchStarted) return;- dispatchStarted = true;- resolveDispatchStarted();- };-- // Keep the issue row locked through the adapter's asynchronous- // preparation and release it only once the adapter reports an- // actual process spawn. If preparation fails or returns without a- // spawn, settling the adapter promise also releases the gate.- const resultPromise = dispatch(markDispatchStarted);- void resultPromise.then(markDispatchStarted, markDispatchStarted);- await dispatchStartedPromise;- return { dispatched: true as const, resultPromise };+ const gate = await runDispatch.dispatchResolvedInteractionIfCurrent({+ runId: run.id,+ companyId: run.companyId,+ expectedStatus: "running",+ dispatch: async (markDispatchStarted) => {+ await options.afterResolvedInteractionContinuationDispatchCheck?.({+ runId: run.id,+ issueId,+ });+ // The adapter owns everything after this handoff, including run-log+ // writes which allocate an event sequence by updating the run row.+ // Release the validation locks before invoking adapter code so those+ // callbacks cannot self-deadlock against this transaction.+ markDispatchStarted();+ return dispatch(markDispatchStarted);+ },});if (gate.dispatched) return gate;- await cancelRunForStaleIssue(run, issueId, gate.staleness);+ if (gate.cancellation.outcome === "cancelled") {+ applyRunDispatchPostCommitEffects(gate.cancellation.postCommitEffects);+ }return { dispatched: false };};if (!executionTarget || executionTarget.kind === "local") {@@ -24776,7 +23962,10 @@ export function heartbeatService(const blockedInteractionWake =dependencyReadiness &&!dependencyReadiness.isDependencyReady &&- allowsIssueInteractionWake(enrichedContextSnapshot);+ allowsIssueInteractionWake(+ enrichedContextSnapshot,+ ISSUE_TREE_CONTROL_INTERACTION_WAKE_REASONS,+ );if (blockedInteractionWake) {enrichedContextSnapshot.dependencyBlockedInteraction = true;