From 560765988d836d3b05a1e5d20e1bd068d3e93ee6 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:32:05 -0600 Subject: [PATCH] fix(recovery): unblock hermes_gateway holds, classify 429/529 transient, and isolate binding_mismatch (#22969) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Task execution recovery prevents failed, timed-out, or interrupted runs from leaving tasks permanently blocked. > - Three concrete recovery gaps still leave tasks stuck: `hermes_gateway` is omitted from `CONVERSATION_ADAPTER_TYPES` (so timed-out/cancelled runs stick in `legacy_execution_requires_reconciliation`), terminal `hermes_gateway` 429/529 failures omit `errorFamily` (so bounded transient retry never fires), and automatic continuation after a non-retryable workspace `binding_mismatch` chooses `writer_ended` (reusing the broken workspace in a loop) while stranded notices omit the saved failure reason. > - Users cannot unblock `hermes_gateway` tasks via Retry or board comments, transient provider rate limits park tasks indefinitely, and `binding_mismatch` tasks exhaust the hourly retry cap with only a generic chat notice. > - This pull request adds `hermes_gateway` to conversation continuation and explicit continuation admission (delegating terminal stop proof to the Hermes adapter), classifies terminal `hermes_gateway` 429/529/5xx/quota/gateway-shutdown failures with `errorFamily` and `retryNotBefore`, switches automatic continuation to `fresh_isolated_workspace` on non-retryable `binding_mismatch`, and surfaces the Core-owned failure reason in stranded no-running-execution notices. > - The benefit is that stuck `hermes_gateway` holds clear cleanly when stopped, transient upstream errors retry automatically, and `binding_mismatch` continuations start in a fresh isolated workspace with clear user-facing diagnostics. ## Linked Issues or Issue Description - Fixes: #17196 - Fixes: #17526 - Refs #21289 (extends non-retryable `binding_mismatch` fresh-workspace handling from manual board Retry to automatic continuation fallback and stranded recovery notices) - Related open PRs checked during dedup search (no overlap): #22756, #22810, #22738 ## What Changed - **`hermes_gateway` conversation continuation and hold clearing (#17196)**: - Add `"hermes_gateway"` to `CONVERSATION_ADAPTER_TYPES` in `server/src/services/conversation-continuation.ts` so failed, interrupted, and acknowledged-cancelled `hermes_gateway` runs receive `conversationContinuation` policy and matching holds retire cleanly. - Export `hasHermesGatewayTerminalStopProof` from `@paperclipai/hermes-paperclip-adapter/gateway/server` (`packages/adapters/hermes/src/gateway/server/terminal-failure.ts`) and consume its boolean result in `server/src/services/explicit-native-continuation.ts` so pre-existing `legacy_execution_requires_reconciliation` holds for remote `hermes_gateway` runs clear `process_identity_missing` only when the Hermes adapter confirms a terminal gateway response or pre-fetch configuration error, while unconfirmed `hermes_gateway` timeouts fail closed. - **`hermes_gateway` terminal transient/quota classification (#17526)**: - Extract terminal error classification into `packages/adapters/hermes/src/gateway/server/terminal-failure.ts` and wire it in `packages/adapters/hermes/src/gateway/server/execute.ts` (`extractErrorMessage`, `classifyTerminalFailure`, `mapFinalResultForTest`) to classify terminal provider 429/529/5xx/rate-limit/overload errors (including camelCase `statusCode`/`httpStatus`, `HTTP/x.y` status lines, and `Bad Gateway`/`Gateway Timeout` phrases) as `errorFamily: "transient_upstream"`, structured/message quota errors (including `insufficient_quota`) as `errorFamily: "provider_quota"`, and forward range-checked `retryNotBefore` from `retry_not_before` / `retry_after`. - Map unexpected `hermes_gateway` shutdown/restart interruptions (`status: "cancelled"` with shutdown/restart wording) to retryable failed outcomes (`errorCode: "hermes_gateway_run_failed"`, `signal: null`, `errorFamily: "transient_upstream"`, `resultJson: { status: "interrupted", gateway_status: "cancelled" }`) while keeping deliberate cancels as `cancelled`, keeping HTTP 400/403 errors (even with rate-limit/overloaded text) non-transient, and never forging `connectionFailure` from remote text. - **Automatic continuation `binding_mismatch` isolation and saved failure cause**: - Export `readWorkspaceProviderFailure` and `workspaceProviderFailureMessage` in `server/src/services/workspace-provider-failure.ts` using only Core-owned closed messages (no raw provider text). - Update `server/src/services/fresh-continuation-fallback.ts` to choose `isolation: "fresh_isolated_workspace"` instead of `"writer_ended"` strictly when `run.resultJson.workspaceProviderFailure?.retryable === false && workspaceProviderFailure.reason === "binding_mismatch"`, clearing `issues.executionWorkspaceId` and tagging `freshContinuationIsolation` while preserving `"writer_ended"` for retryable and non-binding errors (e.g. `storage_pending`, `credential_unavailable`). - Update `buildNoRunningExecutionNoticeSeed` and `buildImmediateExecutionPathRecoveryNoticeSeed` in `server/src/services/recovery/stranded-notice.ts` to accept typed `WorkspaceProviderFailureSummary | PluginWorkspaceOperationFailureReason | null` (resolving once and dropping unknown strings) and pass `readWorkspaceProviderFailure(latestRun?.resultJson)` from `server/src/services/recovery/service.ts` (minimal argument additions at existing escalation call sites). - **Regression and embedded-Postgres E2E tests**: - Added tests to existing test suites (`packages/adapters/hermes/src/gateway/server/execute.test.ts`, `server/src/services/conversation-continuation.test.ts`, `server/src/services/fresh-continuation-fallback.test.ts`, `server/src/__tests__/workspace-provider-failure.test.ts`, `server/src/__tests__/heartbeat-retry-scheduling.test.ts`, `server/src/services/heartbeat/run-completion.test.ts`) without adding new test files. ## Verification - **Hermes adapter unit tests**: `pnpm --filter @paperclipai/hermes-paperclip-adapter exec vitest run src/gateway/server/execute.test.ts` — 122/122 passed. - **Hermes adapter typecheck**: `pnpm --filter @paperclipai/hermes-paperclip-adapter typecheck` — passed. - **Server typecheck**: `pnpm --filter @paperclipai/server typecheck` — passed (all 7 project layers). - **Module boundaries**: `node scripts/check-module-boundaries.mjs` — passed. - **Server recovery, retry scheduling, `completeRun`, and embedded-Postgres E2E suites**: - `pnpm --filter @paperclipai/server exec vitest run --hookTimeout=60000 src/services/conversation-continuation.test.ts src/__tests__/workspace-provider-failure.test.ts` — 11/11 passed. - `pnpm --filter @paperclipai/server exec vitest run --hookTimeout=60000 src/services/fresh-continuation-fallback.test.ts -t "binding_mismatch|workspaceProviderFailure"` — 3/3 passed. - `pnpm --filter @paperclipai/server exec vitest run --hookTimeout=60000 src/services/heartbeat/run-completion.test.ts -t "hermes_gateway shutdown"` — 1/1 passed. - `pnpm --filter @paperclipai/server exec vitest run --hookTimeout=60000 src/__tests__/heartbeat-retry-scheduling.test.ts -t "hermes_gateway 429"` — 1/1 passed. - **Test budget check**: `node scripts/check-test-budget.mjs --files server/src/services/conversation-continuation.test.ts server/src/services/fresh-continuation-fallback.test.ts server/src/__tests__/workspace-provider-failure.test.ts server/src/__tests__/heartbeat-retry-scheduling.test.ts server/src/services/heartbeat/run-completion.test.ts` — passed. ## Risks - Low risk; no database schema migrations or breaking API changes. - `hermes_gateway` holds without a confirmed terminal gateway response (such as unconfirmed client-side timeouts) intentionally fail closed with `process_identity_missing` to prevent overlapping remote execution. - Only `binding_mismatch` workspace provider failures trigger `fresh_isolated_workspace` on automatic continuation; retryable and non-binding non-retryable failures keep `writer_ended` so usable task workspaces are not discarded. - Stranded recovery notices render only Core-owned closed failure messages and drop unrecognized values, preventing raw provider error strings from reaching issue threads. ## Model Used - Google Gemini (Antigravity agent with tool use and code execution) ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) --- .../hermes/src/gateway/server/execute.test.ts | 174 +++++++++++++ .../hermes/src/gateway/server/execute.ts | 29 ++- .../hermes/src/gateway/server/index.ts | 1 + .../src/gateway/server/terminal-failure.ts | 164 ++++++++++++ .../heartbeat-retry-scheduling.test.ts | 65 +++++ .../workspace-provider-failure.test.ts | 58 ++++- .../conversation-continuation.test.ts | 239 +++++++++++++++++- .../src/services/conversation-continuation.ts | 29 ++- .../services/explicit-native-continuation.ts | 11 +- .../fresh-continuation-fallback.test.ts | 43 ++++ .../services/fresh-continuation-fallback.ts | 15 +- .../services/heartbeat/run-completion.test.ts | 144 +++++++++++ .../src/services/heartbeat/run-lifecycle.ts | 4 +- server/src/services/recovery/service.ts | 23 +- .../src/services/recovery/stranded-notice.ts | 19 +- .../services/workspace-provider-failure.ts | 56 ++++ 16 files changed, 1048 insertions(+), 26 deletions(-) create mode 100644 packages/adapters/hermes/src/gateway/server/terminal-failure.ts diff --git a/packages/adapters/hermes/src/gateway/server/execute.test.ts b/packages/adapters/hermes/src/gateway/server/execute.test.ts index d7e4366c8e2..01701300c48 100644 --- a/packages/adapters/hermes/src/gateway/server/execute.test.ts +++ b/packages/adapters/hermes/src/gateway/server/execute.test.ts @@ -2,6 +2,7 @@ import { describe, expect, it, vi, afterEach } from "vitest"; import type { AdapterExecutionContext } from "@paperclipai/adapter-utils"; import { createPromptContextFixture } from "@paperclipai/adapter-utils/test-fixtures/prompt-context"; import { execute, mapFinalResultForTest, parseSseFramesForTest, resolveSessionKey } from "./execute.js"; +import { hasHermesGatewayTerminalStopProof } from "./index.js"; import { testEnvironment } from "./test.js"; import { parseHermesGatewayStdoutLine } from "../ui/parse-stdout.js"; @@ -1139,5 +1140,178 @@ describe("mapFinalResultForTest", () => { expect(result.exitCode).toBe(1); expect(result.errorCode).toBe("hermes_gateway_run_failed"); expect(result.errorMessage).toBe("boom"); + expect(result.errorFamily ?? null).toBeNull(); + }); + + it.each([ + ["HTTP 429: This request would exceed your account's rate limit. Please try again later.", "transient_upstream"], + ["HTTP 429: Rate limit exceeded: new-account-rpm/requests", "transient_upstream"], + ["API Error: 529 overloaded_error", "transient_upstream"], + ["HTTP 503 Service Unavailable", "transient_upstream"], + ["HTTP/1.1 502", "transient_upstream"], + ["502 Bad Gateway", "transient_upstream"], + ["504 Gateway Timeout", "transient_upstream"], + ])("classifies terminal provider failure %j as %s", (error, expectedFamily) => { + const result = mapFinalResultForTest({ + terminal: { + runId: "run-429", + status: "failed", + payload: { status: "failed", error, retry_not_before: "2099-01-01T00:05:00.000Z" }, + }, + outputChunks: [], + sessionKey: "session-key", + strategy: "issue", + }); + expect(result.exitCode).toBe(1); + expect(result.errorCode).toBe("hermes_gateway_run_failed"); + expect(result.errorFamily).toBe(expectedFamily); + expect(result.retryNotBefore).toBe("2099-01-01T00:05:00.000Z"); + }); + + it("classifies structured quota errors as provider_quota over rate_limit_error and 401", () => { + const result = mapFinalResultForTest({ + terminal: { + runId: "run-quota", + status: "failed", + payload: { + status: "failed", + error: { + type: "rate_limit_error", + code: "insufficient_quota", + status_code: 401, + message: "You exceeded your current quota.", + }, + retry_after: 120, + }, + }, + outputChunks: [], + sessionKey: "session-key", + strategy: "issue", + }); + expect(result.errorCode).toBe("hermes_gateway_run_failed"); + expect(result.errorFamily).toBe("provider_quota"); + expect(result.errorMessage).toBe("You exceeded your current quota."); + expect(typeof result.retryNotBefore).toBe("string"); + expect(Number.isFinite(Date.parse(result.retryNotBefore!))).toBe(true); + }); + + it("maps gateway shutdown interruptions to retryable failed outcomes while keeping deliberate cancels unchanged", () => { + const shutdown = mapFinalResultForTest({ + terminal: { + runId: "run-shutdown", + status: "cancelled", + payload: { status: "cancelled", error: "Gateway shutdown interrupted the run." }, + }, + outputChunks: [], + sessionKey: "session-key", + strategy: "issue", + }); + expect(shutdown.exitCode).toBe(1); + expect(shutdown.signal).toBeNull(); + expect(shutdown.errorCode).toBe("hermes_gateway_run_failed"); + expect(shutdown.errorFamily).toBe("transient_upstream"); + expect(shutdown.resultJson).toMatchObject({ status: "interrupted", gateway_status: "cancelled" }); + + const deliberate = mapFinalResultForTest({ + terminal: { + runId: "run-stop", + status: "cancelled", + payload: { status: "cancelled", error: "Stopped by operator." }, + }, + outputChunks: [], + sessionKey: "session-key", + strategy: "issue", + }); + expect(deliberate.errorCode).toBe("hermes_gateway_cancelled"); + expect(deliberate.signal).toBe("SIGTERM"); + expect(deliberate.resultJson?.status).toBe("cancelled"); + expect(deliberate.errorFamily ?? null).toBeNull(); + }); + + it.each([1e20, "1e20", "99999999999999999999"])("ignores out-of-range retry_after %j without discarding terminal result", (retryAfter) => { + const result = mapFinalResultForTest({ + terminal: { + runId: "run-huge-retry", + status: "failed", + payload: { + status: "failed", + error: "HTTP 429: Rate limit exceeded", + retry_after: retryAfter, + usage: { input_tokens: 12, output_tokens: 4 }, + }, + }, + outputChunks: [], + sessionKey: "session-key", + strategy: "issue", + }); + expect(result.errorCode).toBe("hermes_gateway_run_failed"); + expect(result.errorFamily).toBe("transient_upstream"); + expect(result.retryNotBefore).toBeUndefined(); + expect(result.usage).toEqual({ inputTokens: 12, outputTokens: 4 }); + }); + + it("classifies camelCase statusCode 429 in nested error payloads as transient_upstream", () => { + const result = mapFinalResultForTest({ + terminal: { + runId: "run-camel-429", + status: "failed", + payload: { status: "failed", error: { statusCode: 429, message: "slow down" } }, + }, + outputChunks: [], + sessionKey: "session-key", + strategy: "issue", + }); + expect(result.errorCode).toBe("hermes_gateway_run_failed"); + expect(result.errorFamily).toBe("transient_upstream"); + expect(result.errorMessage).toBe("slow down"); + }); + + it.each([ + { status: "failed", error: "HTTP 400: invalid request body" }, + { status: "failed", error: "HTTP 400: rate_limit_error header invalid" }, + { status: "failed", error: "HTTP 403: API key limit denied" }, + { status: "failed", error: "HTTP 403: overloaded project key" }, + { status: "failed", error: "HTTP/1.1 403: overloaded project key" }, + { status: "failed", error: "Validation error: maximum 500 tokens exceeded" }, + { status: "failed", error: { status_code: 403, message: "Forbidden" } }, + ])("keeps non-transient terminal error %j unclassified", (payload) => { + const result = mapFinalResultForTest({ + terminal: { runId: "run-perm", status: "failed", payload }, + outputChunks: [], + sessionKey: "session-key", + strategy: "issue", + }); + expect(result.errorCode).toBe("hermes_gateway_run_failed"); + expect(result.errorFamily ?? null).toBeNull(); + }); + + it("recognizes confirmed terminal stop proofs and fails closed on unconfirmed timeout or missing status", () => { + expect(hasHermesGatewayTerminalStopProof({ status: "completed" })).toBe(true); + expect(hasHermesGatewayTerminalStopProof({ status: "failed" })).toBe(true); + expect(hasHermesGatewayTerminalStopProof({ status: "cancelled" })).toBe(true); + expect(hasHermesGatewayTerminalStopProof({ status: "interrupted", gateway_status: "cancelled" })).toBe(true); + expect(hasHermesGatewayTerminalStopProof({ + connectionFailure: { provider: "hermes_gateway", operation: "configuration" }, + })).toBe(true); + expect(hasHermesGatewayTerminalStopProof({ + connectionFailure: { provider: "hermes_gateway", operation: "create_run", reason: "rate_limited" }, + })).toBe(false); + expect(hasHermesGatewayTerminalStopProof({ + connectionFailure: { provider: "hermes_gateway", operation: "create_run", reason: "remote_unavailable" }, + })).toBe(false); + expect(hasHermesGatewayTerminalStopProof({ + connectionFailure: { provider: "hermes_gateway", operation: "create_run", reason: "connection_refused" }, + })).toBe(false); + expect(hasHermesGatewayTerminalStopProof({ + connectionFailure: { provider: "hermes_gateway", operation: "create_run", reason: "connection_timeout" }, + })).toBe(false); + expect(hasHermesGatewayTerminalStopProof({ + connectionFailure: { provider: "hermes_gateway", operation: "create_run", reason: "connection_reset" }, + })).toBe(false); + expect(hasHermesGatewayTerminalStopProof({ status: "timeout" })).toBe(false); + expect(hasHermesGatewayTerminalStopProof({ + connectionFailure: { provider: "hermes_gateway", operation: "stream" }, + })).toBe(false); + expect(hasHermesGatewayTerminalStopProof(null)).toBe(false); }); }); diff --git a/packages/adapters/hermes/src/gateway/server/execute.ts b/packages/adapters/hermes/src/gateway/server/execute.ts index d3200af788c..f803050c9fc 100644 --- a/packages/adapters/hermes/src/gateway/server/execute.ts +++ b/packages/adapters/hermes/src/gateway/server/execute.ts @@ -27,6 +27,7 @@ import { isRemotePlainHttp, remotePlainHttpDeniedMessage, } from "./transport-security.js"; +import { classifyTerminalFailure } from "./terminal-failure.js"; type SessionKeyStrategy = "issue" | "agent" | "run" | "none"; @@ -733,7 +734,13 @@ function extractModel(value: unknown): string | null { function extractErrorMessage(value: unknown): string | null { const record = asRecord(value); - return nonEmpty(record?.error) ?? nonEmpty(record?.message) ?? nonEmpty(record?.detail) ?? extractOutput(value); + const nestedError = asRecord(record?.error); + return nonEmpty(record?.error) + ?? nonEmpty(nestedError?.message) + ?? nonEmpty(nestedError?.detail) + ?? nonEmpty(record?.message) + ?? nonEmpty(record?.detail) + ?? extractOutput(value); } function terminalResultCode(status: string): { exitCode: number; signal: string | null; errorCode: string | null } { @@ -760,16 +767,25 @@ export function mapFinalResultForTest(input: { const mapped = terminalResultCode(input.terminal.status); const usage = parseUsage(payload); const costUsd = parseCostUsd(payload); - const errorMessage = mapped.errorCode - ? redactText(extractErrorMessage(payload) ?? `Hermes run ${input.terminal.status}`) + const rawErrorMessage = mapped.errorCode + ? (extractErrorMessage(payload) ?? `Hermes run ${input.terminal.status}`) : null; + const errorMessage = rawErrorMessage ? redactText(rawErrorMessage) : null; + const terminalClassification = mapped.errorCode + ? classifyTerminalFailure(input.terminal.status, payload, rawErrorMessage) + : { errorFamily: null, retryNotBefore: null, gatewayShutdown: false }; + const effectiveSignal = terminalClassification.gatewayShutdown ? null : mapped.signal; + const effectiveErrorCode = terminalClassification.gatewayShutdown ? "hermes_gateway_run_failed" : mapped.errorCode; + const resultStatus = terminalClassification.gatewayShutdown ? "interrupted" : input.terminal.status; return { exitCode: mapped.exitCode, - signal: mapped.signal, + signal: effectiveSignal, timedOut: false, provider: "hermes_gateway", model: extractModel(payload), - ...(mapped.errorCode ? { errorCode: mapped.errorCode } : {}), + ...(effectiveErrorCode ? { errorCode: effectiveErrorCode } : {}), + ...(terminalClassification.errorFamily ? { errorFamily: terminalClassification.errorFamily } : {}), + ...(terminalClassification.retryNotBefore ? { retryNotBefore: terminalClassification.retryNotBefore } : {}), ...(errorMessage ? { errorMessage } : {}), ...(usage ? { usage } : {}), ...(costUsd !== null ? { costUsd } : {}), @@ -783,7 +799,8 @@ export function mapFinalResultForTest(input: { sessionDisplayId, resultJson: { run_id: input.terminal.runId, - status: input.terminal.status, + status: resultStatus, + ...(terminalClassification.gatewayShutdown ? { gateway_status: input.terminal.status } : {}), session_id: sessionDisplayId, last_event: input.terminal.eventName ?? null, output: output ?? "", diff --git a/packages/adapters/hermes/src/gateway/server/index.ts b/packages/adapters/hermes/src/gateway/server/index.ts index b29873d6ec0..0dc8023ef1c 100644 --- a/packages/adapters/hermes/src/gateway/server/index.ts +++ b/packages/adapters/hermes/src/gateway/server/index.ts @@ -1,6 +1,7 @@ import type { AdapterSessionCodec } from "@paperclipai/adapter-utils"; export { execute, resolveSessionKey, parseSseFramesForTest, mapFinalResultForTest } from "./execute.js"; +export { hasHermesGatewayTerminalStopProof } from "./terminal-failure.js"; export { testEnvironment } from "./test.js"; export { getConfigSchema } from "./config-schema.js"; diff --git a/packages/adapters/hermes/src/gateway/server/terminal-failure.ts b/packages/adapters/hermes/src/gateway/server/terminal-failure.ts new file mode 100644 index 00000000000..00b192d4065 --- /dev/null +++ b/packages/adapters/hermes/src/gateway/server/terminal-failure.ts @@ -0,0 +1,164 @@ +import type { AdapterExecutionResult } from "@paperclipai/adapter-utils"; + +const FAILURE_STATUSES = new Set(["failed", "error"]); +const CANCELLED_STATUSES = new Set(["cancelled", "canceled", "stopped", "interrupted"]); +const TERMINAL_STOP_STATUSES = new Set(["completed", ...FAILURE_STATUSES, ...CANCELLED_STATUSES]); + +const TERMINAL_PROVIDER_QUOTA_CODES = new Set([ + "insufficient_quota", + "usage_limit_reached", + "quota_exceeded", + "billing_hard_limit_reached", +]); + +const TERMINAL_TRANSIENT_ERROR_CODES = new Set([ + "rate_limit_error", + "overloaded_error", + "service_unavailable", + "api_connection_error", + "server_error", + "internal_server_error", + "bad_gateway", + "gateway_timeout", + "too_many_requests", +]); + +const TERMINAL_PROVIDER_QUOTA_RE = + /(?:insufficient_quota|usage\s+limit\s+reached|usage\s+cap\s+reached|quota\s+exceeded|exceeded\s+your\s+(?:current\s+)?quota|you(?:'|’)ve\s+hit\s+your\s+(?:\w+\s+)?limit|session\s+limit\s+(?:reached|exceeded)|out\s+of\s+extra\s+usage|5[-\s]?hour\s+limit\s+reached|weekly\s+limit\s+reached|servicequotaexceededexception)/i; + +const MESSAGE_HTTP_STATUS_RE = + /(?:^|[^\w])(?:http(?:\/\d+(?:\.\d+)?)?|status(?:[_\s-]?code)?|api\s+error)\s*[:=]?\s*(\d{3})\b/i; + +const TERMINAL_TRANSIENT_UPSTREAM_RE = + /(?:\b(?:http(?:\/\d+(?:\.\d+)?)?|status(?:[_\s-]?code)?|api\s+error)\s*[:=]?\s*(?:429|500|502|503|504|529)\b|rate[-\s_]?limit(?:ed|_error)?|too\s+many\s+requests|overloaded(?:_error)?|server\s+overloaded|service\s+unavailable|bad\s+gateway|gateway\s+timeout|temporarily\s+unavailable|high\s+demand|try\s+again\s+later|throttl(?:ed|ing)|throttlingexception)/i; + +const TERMINAL_GATEWAY_SHUTDOWN_RE = + /(?:gateway\s+(?:shutdown|restart)|(?:shutdown|restart)\s+interrupted\s+the\s+run)/i; + +const MAX_EPOCH_MS = 8_640_000_000_000_000; + +function asRecord(value: unknown): Record | null { + if (typeof value !== "object" || value === null || Array.isArray(value)) return null; + return value as Record; +} + +function nonEmpty(value: unknown): string | null { + return typeof value === "string" && value.trim().length > 0 ? value.trim() : null; +} + +function parseTerminalStatusCode(value: unknown): number | null { + if (typeof value === "number" && Number.isInteger(value) && value >= 100 && value <= 599) return value; + if (typeof value === "string" && /^\d{3}$/.test(value.trim())) return Number.parseInt(value.trim(), 10); + return null; +} + +function parseMessageHttpStatusCode(message: string | null): number | null { + if (!message) return null; + const match = MESSAGE_HTTP_STATUS_RE.exec(message); + if (!match?.[1]) return null; + const parsed = Number.parseInt(match[1], 10); + return parsed >= 100 && parsed <= 599 ? parsed : null; +} + +function formatValidIsoDate(ms: number): string | null { + if (!Number.isFinite(ms) || Math.abs(ms) > MAX_EPOCH_MS) return null; + const date = new Date(ms); + return Number.isNaN(date.getTime()) ? null : date.toISOString(); +} + +export function parseTerminalRetryNotBefore(payload: Record, nowMs = Date.now()): string | null { + const nestedError = asRecord(payload.error); + const direct = nonEmpty(payload.retry_not_before) + ?? nonEmpty(payload.retryNotBefore) + ?? nonEmpty(nestedError?.retry_not_before) + ?? nonEmpty(nestedError?.retryNotBefore); + if (direct) { + const formatted = formatValidIsoDate(Date.parse(direct)); + if (formatted) return formatted; + } + const retryAfter = payload.retry_after + ?? payload.retryAfter + ?? payload.retry_after_seconds + ?? payload.retryAfterSeconds + ?? nestedError?.retry_after + ?? nestedError?.retryAfter + ?? nestedError?.retry_after_seconds + ?? nestedError?.retryAfterSeconds; + if (typeof retryAfter === "number" && Number.isFinite(retryAfter) && retryAfter > 0) { + return formatValidIsoDate(nowMs + Math.ceil(retryAfter * 1000)); + } + if (typeof retryAfter === "string" && retryAfter.trim().length > 0) { + const trimmed = retryAfter.trim(); + if (/^\d+(?:\.\d+)?$/.test(trimmed)) { + const seconds = Number.parseFloat(trimmed); + if (Number.isFinite(seconds) && seconds > 0) { + return formatValidIsoDate(nowMs + Math.ceil(seconds * 1000)); + } + } + return formatValidIsoDate(Date.parse(trimmed)); + } + return null; +} + +export function classifyTerminalFailure( + status: string, + payload: Record, + errorMessage: string | null, +): { errorFamily: AdapterExecutionResult["errorFamily"]; retryNotBefore: string | null; gatewayShutdown: boolean } { + let errorFamily: AdapterExecutionResult["errorFamily"] = null; + let gatewayShutdown = false; + if (FAILURE_STATUSES.has(status)) { + const nestedError = asRecord(payload.error); + const codeField = (nonEmpty(nestedError?.code) ?? nonEmpty(payload.error_code) ?? nonEmpty(payload.errorCode))?.toLowerCase() ?? null; + const typeField = (nonEmpty(nestedError?.type) ?? nonEmpty(payload.error_type) ?? nonEmpty(payload.errorType))?.toLowerCase() ?? null; + const statusCode = parseTerminalStatusCode( + nestedError?.status_code + ?? nestedError?.statusCode + ?? nestedError?.status + ?? payload.status_code + ?? payload.statusCode + ?? payload.http_status + ?? payload.httpStatus, + ) ?? parseMessageHttpStatusCode(errorMessage); + const isQuota = (codeField !== null && TERMINAL_PROVIDER_QUOTA_CODES.has(codeField)) + || (typeField !== null && TERMINAL_PROVIDER_QUOTA_CODES.has(typeField)) + || (errorMessage !== null && TERMINAL_PROVIDER_QUOTA_RE.test(errorMessage)); + if (isQuota) { + errorFamily = "provider_quota"; + } else { + const isNonTransientClientStatus = statusCode !== null && statusCode >= 400 && statusCode < 500 && statusCode !== 429; + if (!isNonTransientClientStatus) { + const isTransientStatus = statusCode === 429 || statusCode === 529 || (statusCode !== null && statusCode >= 500); + const isTransientField = (typeField !== null && TERMINAL_TRANSIENT_ERROR_CODES.has(typeField)) + || (codeField !== null && TERMINAL_TRANSIENT_ERROR_CODES.has(codeField)); + if (isTransientStatus || isTransientField || (errorMessage !== null && TERMINAL_TRANSIENT_UPSTREAM_RE.test(errorMessage))) { + errorFamily = "transient_upstream"; + } + } + } + } else if (CANCELLED_STATUSES.has(status) && errorMessage !== null && TERMINAL_GATEWAY_SHUTDOWN_RE.test(errorMessage)) { + errorFamily = "transient_upstream"; + gatewayShutdown = true; + } + const retryNotBefore = errorFamily ? parseTerminalRetryNotBefore(payload) : null; + return { errorFamily, retryNotBefore, gatewayShutdown }; +} + +/** + * Remote hermes_gateway runs have no local host PID; require either a saved + * terminal gateway status or a pre-request configuration failure (returned + * before any outbound fetch). Outbound create_run HTTP 429/5xx and transport + * failures intentionally fail closed because redirect-following fetch or an + * intermediary may have already created the remote run and retries mint a new + * Idempotency-Key. + */ +export function hasHermesGatewayTerminalStopProof( + resultJson: Record | null | undefined, +): boolean { + const result = asRecord(resultJson); + if (!result) return false; + const status = nonEmpty(result.status)?.toLowerCase() ?? ""; + if (TERMINAL_STOP_STATUSES.has(status)) return true; + const connectionFailure = asRecord(result.connectionFailure); + return connectionFailure?.provider === "hermes_gateway" && connectionFailure?.operation === "configuration"; +} diff --git a/server/src/__tests__/heartbeat-retry-scheduling.test.ts b/server/src/__tests__/heartbeat-retry-scheduling.test.ts index 15ae4940933..82f75a83acf 100644 --- a/server/src/__tests__/heartbeat-retry-scheduling.test.ts +++ b/server/src/__tests__/heartbeat-retry-scheduling.test.ts @@ -2309,6 +2309,71 @@ describeEmbeddedPostgres("heartbeat bounded retry scheduling", () => { ); }); + it("schedules bounded retries for hermes_gateway 429 transient failures instead of parking in reconciliation hold", async () => { + const { mapFinalResultForTest } = await import("@paperclipai/hermes-paperclip-adapter/gateway/server"); + const adapterResult = mapFinalResultForTest({ + terminal: { + runId: "hermes-429-run", + status: "failed", + payload: { + status: "failed", + error: "HTTP 429: This request would exceed your account's rate limit. Please try again later.", + retry_not_before: "2026-04-22T16:00:00.000Z", + }, + }, + outputChunks: [], + sessionKey: "session-429", + strategy: "issue", + }); + + expect(adapterResult.errorCode).toBe("hermes_gateway_run_failed"); + expect(adapterResult.errorFamily).toBe("transient_upstream"); + + const companyId = randomUUID(); + const agentId = randomUUID(); + const issueId = randomUUID(); + const runId = randomUUID(); + const now = new Date("2026-04-22T10:00:00.000Z"); + + await seedRetryFixture({ + runId, + companyId, + agentId, + now, + errorCode: adapterResult.errorCode!, + adapterType: "hermes_gateway", + agentName: "HermesGateway", + resultJson: { + ...(adapterResult.resultJson ?? {}), + errorFamily: adapterResult.errorFamily, + retryNotBefore: adapterResult.retryNotBefore, + transientRetryNotBefore: adapterResult.retryNotBefore, + conversationContinuation: "continue_conversation_v1", + }, + }); + await db.insert(issues).values({ + id: issueId, + companyId, + title: "Hermes 429 retry issue", + status: "in_progress", + assigneeAgentId: agentId, + }); + await db.update(heartbeatRuns).set({ + issueId, + contextSnapshot: { issueId, wakeReason: "issue_assigned" }, + runnerProfileJson: { adapterDispatch: { adapterType: "hermes_gateway" } }, + }).where(eq(heartbeatRuns.id, runId)); + + const scheduled = await heartbeat.scheduleBoundedRetry(runId, { + now, + random: () => 0.5, + }); + + expect(scheduled).toMatchObject({ outcome: "scheduled" }); + if (scheduled.outcome !== "scheduled") return; + expect(scheduled.dueAt.toISOString()).toBe("2026-04-22T16:00:00.000Z"); + }); + describe("run-dispatch module transactions", () => { it("promotes a due scheduled retry exactly once under concurrent promotion attempts", async () => { const companyId = randomUUID(); diff --git a/server/src/__tests__/workspace-provider-failure.test.ts b/server/src/__tests__/workspace-provider-failure.test.ts index ab2c6d3a867..945741fa2af 100644 --- a/server/src/__tests__/workspace-provider-failure.test.ts +++ b/server/src/__tests__/workspace-provider-failure.test.ts @@ -16,7 +16,16 @@ import { } from "@paperclipai/plugin-sdk"; import { HttpError } from "../errors.js"; import { findPluginWorkerUnavailableError, PluginWorkerUnavailableError } from "../services/plugin-worker-unavailable-error.js"; -import { findWorkspaceProviderFailure, workspaceProviderCallFailure } from "../services/workspace-provider-failure.js"; +import { + findWorkspaceProviderFailure, + readWorkspaceProviderFailure, + workspaceProviderCallFailure, + workspaceProviderFailureMessage, +} from "../services/workspace-provider-failure.js"; +import { + buildNoRunningExecutionNoticeSeed, + buildStrandedRecoveryEscalationNotice, +} from "../services/recovery/stranded-notice.js"; const id = (n: number) => `10000000-0000-4000-8000-${String(n).padStart(12, "0")}`; const params = { @@ -108,4 +117,51 @@ describe("workspace provider call failures", () => { expect(findWorkspaceProviderFailure(new Error("setup failed", { cause: failure }))).toBe(failure); expect(findWorkspaceProviderFailure(new Error("other"))).toBeNull(); }); + + it("surfaces a saved binding_mismatch failure reason in the no-running-execution stranded notice and drops unknown text", () => { + const inProgress = buildNoRunningExecutionNoticeSeed({ + status: "in_progress", + attempts: 3, + workspaceProviderFailure: "binding_mismatch", + }); + expect(inProgress.body).toContain("after 3 tries"); + expect(inProgress.body).toContain("Saved workspace storage no longer matches this workspace"); + expect(inProgress.body).toContain("Press Retry"); + + const todo = buildNoRunningExecutionNoticeSeed({ + status: "todo", + workspaceProviderFailure: "binding_mismatch", + }); + expect(todo.body).toContain("Saved workspace storage no longer matches this workspace"); + expect(todo.body).toContain("Press Retry to start it again."); + + const generic = buildNoRunningExecutionNoticeSeed({ status: "todo" }); + expect(generic.body).toBe( + "Paperclip tried to start this task again, but it still could not start. Press Retry to start it again.", + ); + + // Arbitrary/raw provider strings are never echoed into user-facing notices. + const unknownText = buildNoRunningExecutionNoticeSeed({ + status: "todo", + workspaceProviderFailure: "raw provider stack trace" as never, + }); + expect(unknownText.body).toBe(generic.body); + + const savedSummary = readWorkspaceProviderFailure({ + workspaceProviderFailure: { kind: "provider", reason: "binding_mismatch", retryable: false }, + }); + const escalated = buildStrandedRecoveryEscalationNotice({ + seed: buildNoRunningExecutionNoticeSeed({ status: "in_progress", attempts: 2, workspaceProviderFailure: savedSummary }), + recoveryActionId: id(10), + recoveryOwner: null, + sourceRun: { + id: id(11), + status: "failed", + errorCode: "setup_failed", + errorSummary: workspaceProviderFailureMessage(savedSummary), + }, + }); + expect(escalated.body).toContain("Saved workspace storage no longer matches this workspace"); + expect(escalated.body).toContain("after 2 tries"); + }); }); diff --git a/server/src/services/conversation-continuation.test.ts b/server/src/services/conversation-continuation.test.ts index 31166bfa59f..52dd75065c6 100644 --- a/server/src/services/conversation-continuation.test.ts +++ b/server/src/services/conversation-continuation.test.ts @@ -1,10 +1,13 @@ import { randomUUID } from "node:crypto"; import { afterAll, beforeAll, describe, expect, it } from "vitest"; import { and, eq } from "drizzle-orm"; -import { agents, companies, createDb, heartbeatRuns, issues, issueRecoveryActions, type Db } from "@paperclipai/db"; +import { agents, companies, createDb, heartbeatRuns, issueComments, issues, issueRecoveryActions, type Db } from "@paperclipai/db"; import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../__tests__/helpers/embedded-postgres.js"; -import { conversationRecoveryActionPredicate, getConversationOwnershipBlocker } from "./conversation-continuation.js"; +import { CONVERSATION_CONTINUATION_POLICY, conversationRecoveryActionPredicate, getConversationOwnershipBlocker, isConversationAdapter, runUsedConversationAdapter } from "./conversation-continuation.js"; import { deliverExecutionStatuses } from "./execution-status-delivery.js"; +import { admitExplicitNativeContinuation } from "./explicit-native-continuation.js"; +import { getExecutionBlocker } from "./execution-blocker.js"; +import { legacyExecutionNeedsReconciliation } from "./legacy-execution-recovery.js"; const support = await getEmbeddedPostgresTestSupport(); const describePostgres = support.supported ? describe : describe.skip; @@ -78,4 +81,236 @@ describePostgres("execution identity query contracts", () => { expect(seen).toEqual(expected); expect(await deliverExecutionStatuses(db, { publish: () => { throw new Error("duplicate delivery"); } })).toEqual({ scanned: 0, delivered: 0 }); }); + + it("treats hermes_gateway as a conversation adapter and lets Retry and board comments clear timed-out or cancelled holds", async () => { + expect(isConversationAdapter("hermes_gateway")).toBe(true); + + const f = await fixture(); + await db.update(agents).set({ adapterType: "hermes_gateway" }).where(eq(agents.id, f.agentId)); + await db.update(issues).set({ status: "blocked", assigneeAgentId: f.agentId }).where(eq(issues.id, f.issueId)); + + const timedOutRunId = randomUUID(); + const finishedAt = new Date("2026-09-11T10:00:00Z"); + await db.insert(heartbeatRuns).values({ + id: timedOutRunId, + companyId: f.companyId, + agentId: f.agentId, + issueId: f.issueId, + status: "timed_out", + errorCode: "hermes_gateway_timeout", + runtimeMode: "legacy", + processPid: null, + processGroupId: null, + finishedAt, + contextSnapshot: { issueId: f.issueId }, + runnerProfileJson: { adapterDispatch: { adapterType: "hermes_gateway" } }, + resultJson: { run_id: "hermes-remote-1", status: "cancelled" }, + }); + const [hold] = await db.insert(issueRecoveryActions).values({ + companyId: f.companyId, + sourceIssueId: f.issueId, + kind: "active_run_watchdog", + status: "resolved", + outcome: "blocked", + ownerType: "board", + cause: "legacy_execution_requires_reconciliation", + fingerprint: `legacy-execution:${timedOutRunId}`, + evidence: { runId: timedOutRunId, automaticRecovery: { replay: "blocked", actionOutcome: "unknown" } }, + nextAction: "Inspect the stopped run before continuing.", + }).returning(); + + // Hold is currently blocking until user Retry or board comment arrives. + expect(await getExecutionBlocker(db, f.companyId, f.issueId)).toMatchObject({ recoveryActionId: hold!.id }); + + // (a) Board Retry clears the timed-out hermes_gateway hold (no local PID exists for gateway runs). + const retryBlocked: string[] = []; + const retryAdmitted = await admitExplicitNativeContinuation({ + db, + companyId: f.companyId, + issueId: f.issueId, + agentId: f.agentId, + actorType: "user", + actorId: "board", + reason: "retry_failed_run", + commentId: null, + failedRunId: timedOutRunId, + successorRunId: randomUUID(), + dryRun: true, + onBlocked: reason => retryBlocked.push(reason), + }); + expect(retryBlocked).toEqual([]); + expect(retryAdmitted).toMatchObject({ previousRunId: timedOutRunId, failedRunId: timedOutRunId }); + + // (b) Board comment also clears the timed-out hermes_gateway hold. + const commentId = randomUUID(); + await db.insert(issueComments).values({ + id: commentId, + companyId: f.companyId, + issueId: f.issueId, + authorType: "user", + authorUserId: "board", + body: "Please continue with the remaining steps.", + createdAt: new Date("2026-09-11T10:05:00Z"), + }); + const commentBlocked: string[] = []; + const commentAdmitted = await admitExplicitNativeContinuation({ + db, + companyId: f.companyId, + issueId: f.issueId, + agentId: f.agentId, + actorType: "user", + actorId: "board", + reason: "issue_commented", + commentId, + successorRunId: randomUUID(), + onBlocked: reason => commentBlocked.push(reason), + }); + expect(commentBlocked).toEqual([]); + expect(commentAdmitted).toMatchObject({ previousRunId: timedOutRunId, commentId }); + expect(await getExecutionBlocker(db, f.companyId, f.issueId)).toBeNull(); + + // (c) New hermes_gateway runs with conversationContinuation policy are retired by conversationRecoveryActionPredicate. + const policyRunId = randomUUID(); + await db.insert(heartbeatRuns).values({ + id: policyRunId, + companyId: f.companyId, + agentId: f.agentId, + issueId: f.otherIssueId, + status: "timed_out", + errorCode: "hermes_gateway_timeout", + runtimeMode: "legacy", + finishedAt, + contextSnapshot: { issueId: f.otherIssueId }, + runnerProfileJson: { adapterDispatch: { adapterType: "hermes_gateway" } }, + resultJson: { status: "cancelled", conversationContinuation: CONVERSATION_CONTINUATION_POLICY }, + }); + const [policyHold] = await db.insert(issueRecoveryActions).values({ + companyId: f.companyId, + sourceIssueId: f.otherIssueId, + kind: "active_run_watchdog", + status: "resolved", + ownerType: "board", + cause: "legacy_execution_requires_reconciliation", + fingerprint: `legacy-execution:${policyRunId}`, + evidence: { runId: policyRunId }, + nextAction: "Fixture", + }).returning(); + const matched = await db.select({ id: issueRecoveryActions.id }).from(issueRecoveryActions) + .where(and(eq(issueRecoveryActions.id, policyHold!.id), conversationRecoveryActionPredicate())); + expect(matched).toEqual([{ id: policyHold!.id }]); + + // (d) A cancelled hermes_gateway run (e.g. issue_reassigned) also unblocks on a new board comment. + const cancelledIssueId = randomUUID(); + const cancelledRunId = randomUUID(); + await db.insert(issues).values({ id: cancelledIssueId, companyId: f.companyId, title: "Cancelled Hermes", status: "blocked", assigneeAgentId: f.agentId }); + await db.insert(heartbeatRuns).values({ + id: cancelledRunId, + companyId: f.companyId, + agentId: f.agentId, + issueId: cancelledIssueId, + status: "cancelled", + errorCode: "issue_reassigned", + runtimeMode: "legacy", + processPid: null, + processGroupId: null, + finishedAt, + contextSnapshot: { issueId: cancelledIssueId }, + runnerProfileJson: { adapterDispatch: { adapterType: "hermes_gateway" } }, + resultJson: { run_id: "hermes-remote-2", status: "cancelled" }, + }); + await db.insert(issueRecoveryActions).values({ + companyId: f.companyId, + sourceIssueId: cancelledIssueId, + kind: "active_run_watchdog", + status: "resolved", + outcome: "blocked", + ownerType: "board", + cause: "legacy_execution_requires_reconciliation", + fingerprint: `legacy-execution:${cancelledRunId}`, + evidence: { runId: cancelledRunId, automaticRecovery: { replay: "blocked", actionOutcome: "unknown" } }, + nextAction: "Inspect the stopped run before continuing.", + }); + const followUpCommentId = randomUUID(); + await db.insert(issueComments).values({ + id: followUpCommentId, + companyId: f.companyId, + issueId: cancelledIssueId, + authorType: "user", + authorUserId: "board", + body: "Reassigned back to you, please continue.", + createdAt: new Date("2026-09-11T10:10:00Z"), + }); + const cancelledBlocked: string[] = []; + const cancelledAdmitted = await admitExplicitNativeContinuation({ + db, + companyId: f.companyId, + issueId: cancelledIssueId, + agentId: f.agentId, + actorType: "user", + actorId: "board", + reason: "issue_commented", + commentId: followUpCommentId, + successorRunId: randomUUID(), + onBlocked: reason => cancelledBlocked.push(reason), + }); + expect(cancelledBlocked).toEqual([]); + expect(cancelledAdmitted).toMatchObject({ previousRunId: cancelledRunId, commentId: followUpCommentId }); + expect(await getExecutionBlocker(db, f.companyId, cancelledIssueId)).toBeNull(); + + // (e) A timed-out hermes_gateway run whose remote stop was never confirmed (status: "timeout") fails closed + // across reconciliation classification, conversation hold retirement, execution blocking, and explicit Retry. + const unconfirmedIssueId = randomUUID(); + const unconfirmedRunId = randomUUID(); + await db.insert(issues).values({ id: unconfirmedIssueId, companyId: f.companyId, title: "Unconfirmed Hermes timeout", status: "blocked", assigneeAgentId: f.agentId }); + const [unconfirmedRun] = await db.insert(heartbeatRuns).values({ + id: unconfirmedRunId, + companyId: f.companyId, + agentId: f.agentId, + issueId: unconfirmedIssueId, + status: "timed_out", + errorCode: "execution_reconciliation_required", + runtimeMode: "legacy", + processPid: null, + processGroupId: null, + finishedAt, + contextSnapshot: { issueId: unconfirmedIssueId }, + runnerProfileJson: { adapterDispatch: { adapterType: "hermes_gateway" } }, + resultJson: { run_id: "hermes-remote-3", status: "timeout" }, + }).returning(); + expect(legacyExecutionNeedsReconciliation(unconfirmedRun!)).toBe(true); + expect(await runUsedConversationAdapter(db, unconfirmedRun!)).toBe(false); + const [unconfirmedHold] = await db.insert(issueRecoveryActions).values({ + companyId: f.companyId, + sourceIssueId: unconfirmedIssueId, + kind: "active_run_watchdog", + status: "resolved", + outcome: "blocked", + ownerType: "board", + cause: "legacy_execution_requires_reconciliation", + fingerprint: `legacy-execution:${unconfirmedRunId}`, + evidence: { runId: unconfirmedRunId, automaticRecovery: { replay: "blocked", actionOutcome: "unknown" } }, + nextAction: "Inspect the stopped run before continuing.", + }).returning(); + const unconfirmedRetired = await db.select({ id: issueRecoveryActions.id }).from(issueRecoveryActions) + .where(and(eq(issueRecoveryActions.id, unconfirmedHold!.id), conversationRecoveryActionPredicate())); + expect(unconfirmedRetired).toEqual([]); + const unconfirmedBlocked: string[] = []; + const unconfirmedAdmitted = await admitExplicitNativeContinuation({ + db, + companyId: f.companyId, + issueId: unconfirmedIssueId, + agentId: f.agentId, + actorType: "user", + actorId: "board", + reason: "retry_failed_run", + commentId: null, + failedRunId: unconfirmedRunId, + successorRunId: randomUUID(), + dryRun: true, + onBlocked: reason => unconfirmedBlocked.push(reason), + }); + expect(unconfirmedAdmitted).toBeNull(); + expect(unconfirmedBlocked).toEqual(["process_identity_missing"]); + expect(await getExecutionBlocker(db, f.companyId, unconfirmedIssueId)).toMatchObject({ recoveryActionId: unconfirmedHold!.id }); + }); }); diff --git a/server/src/services/conversation-continuation.ts b/server/src/services/conversation-continuation.ts index 75ff2463f94..761127de092 100644 --- a/server/src/services/conversation-continuation.ts +++ b/server/src/services/conversation-continuation.ts @@ -1,3 +1,4 @@ +import { hasHermesGatewayTerminalStopProof } from "@paperclipai/hermes-paperclip-adapter/gateway/server"; import { hasRequiredWorkspaceRecovery } from "./workspace-restore-recovery-state.js"; import { and, desc, eq, inArray, isNotNull, isNull, or, sql } from "drizzle-orm"; import { environmentLeases, heartbeatRunEvents, heartbeatRuns, issueRecoveryActions, type Db } from "@paperclipai/db"; @@ -5,17 +6,32 @@ import { canonicalExecutionUuid } from "./execution-identity.js"; import { readProcessStartedAt } from "./hot-restart.js"; import { hasRemoteTerminationReceipt } from "./remote-execution-termination.js"; -// These adapters accept a conversation turn. Retrying a process or webhook can -// replay the action itself, so those adapters retain their recovery contract. -export const CONVERSATION_ADAPTER_TYPES = [ +const LOCAL_CONVERSATION_ADAPTER_TYPES = [ "claude_local", "codex_local", "cursor", "gemini_local", "opencode_local", "pi_local", "grok_local", "kimi_local", "hermes_local", ] as const; +// These adapters accept a conversation turn. Retrying a process or webhook can +// replay the action itself, so those adapters retain their recovery contract. +export const CONVERSATION_ADAPTER_TYPES = [ + ...LOCAL_CONVERSATION_ADAPTER_TYPES, + "hermes_gateway", +] as const; + export function isConversationAdapter(adapterType: string): boolean { return (CONVERSATION_ADAPTER_TYPES as readonly string[]).includes(adapterType); } +/** Remote hermes_gateway runs have no local host PID; require adapter-confirmed stop proof. */ +export function isConversationContinuationEligible( + adapterType: string, + resultJson: Record | null | undefined, +): boolean { + if (!isConversationAdapter(adapterType)) return false; + if (adapterType === "hermes_gateway") return hasHermesGatewayTerminalStopProof(resultJson); + return true; +} + export const CONVERSATION_CONTINUATION_POLICY = "continue_conversation_v1"; export function hasConversationContinuationPolicy(result: Record | null | undefined): boolean { @@ -30,14 +46,14 @@ export function claimedAdapterType(run: Pick'adapterDispatch'->>'adapterType'`, [...CONVERSATION_ADAPTER_TYPES]), + inArray(sql`${heartbeatRuns.runnerProfileJson}->'adapterDispatch'->>'adapterType'`, [...LOCAL_CONVERSATION_ADAPTER_TYPES]), sql`${heartbeatRuns.resultJson}->>'conversationContinuation' = ${CONVERSATION_CONTINUATION_POLICY}`, sql`exists ( select 1 from ${heartbeatRunEvents} where ${heartbeatRunEvents.companyId} = ${heartbeatRuns.companyId} and ${heartbeatRunEvents.runId} = ${heartbeatRuns.id} and ${heartbeatRunEvents.eventType} = 'adapter.invoke' - and ${inArray(sql`${heartbeatRunEvents.payload}->>'adapterType'`, [...CONVERSATION_ADAPTER_TYPES])} + and ${inArray(sql`${heartbeatRunEvents.payload}->>'adapterType'`, [...LOCAL_CONVERSATION_ADAPTER_TYPES])} )`, ); } @@ -57,8 +73,9 @@ export async function historicalAdapterType(db: Db, run: Pick { if (run.resultJson?.workspaceRestoreFailure === "restore_unsafe_archive" || hasRequiredWorkspaceRecovery(run.resultJson)) return false; - if (hasConversationContinuationPolicy(run.resultJson)) return true; const adapterType = await historicalAdapterType(db, run); + if (adapterType === "hermes_gateway") return hasHermesGatewayTerminalStopProof(run.resultJson); + if (hasConversationContinuationPolicy(run.resultJson)) return true; return adapterType !== null && isConversationAdapter(adapterType); } diff --git a/server/src/services/explicit-native-continuation.ts b/server/src/services/explicit-native-continuation.ts index 8032d09f863..18adaee78d2 100644 --- a/server/src/services/explicit-native-continuation.ts +++ b/server/src/services/explicit-native-continuation.ts @@ -34,6 +34,7 @@ import { adapterExecutionControls } from "./adapter-execution-control.js"; import { persistActivity } from "./activity-log.js"; import { activeIssueInteractionCondition } from "./issue-question-context.js"; +import { hasHermesGatewayTerminalStopProof } from "@paperclipai/hermes-paperclip-adapter/gateway/server"; import { historicalAdapterType, isConversationAdapter } from "./conversation-continuation.js"; import { queuedCommentIdsFromWakePayload } from "./issue-queued-comment-queue.js"; import { firstTurnDeliveredCommentIds, historyReadDeliveredCommentIds } from "./queued-comment-delivery.js"; @@ -424,8 +425,9 @@ export async function admitExplicitNativeContinuation(input: { // operator Stop or redeliver a message already consumed by this run. if (queuedRequest && !queuedInterrupt && (run.contextSnapshot?.wakeCommentId === commentId || (Array.isArray(run.contextSnapshot?.wakeCommentIds) && run.contextSnapshot.wakeCommentIds.includes(commentId)))) return null; + let historicalAdapter: string | null = null; if (legacyUserTurn && !failedPreparation) { - const historicalAdapter = await historicalAdapterType(db, run); + historicalAdapter = await historicalAdapterType(db, run); // A settings change never converts a known process/webhook execution into // a conversation. Those adapters retain their reconciliation contract. if (historicalAdapter && !isConversationAdapter(historicalAdapter)) { @@ -581,7 +583,14 @@ export async function admitExplicitNativeContinuation(input: { if (freshIntent && (run.processPid || run.processGroupId) && !await recordedLocalExecutionStopped(db, run)) return blocked("process_identity_missing", "Paperclip is verifying that the previous session stopped."); // A missing process identity is not evidence that a provider exited. + // Remote HTTP gateway adapters (hermes_gateway) never spawn a local OS child process; + // require a saved terminal response from the gateway before clearing the hold so an + // unconfirmed timeout cannot overlap with a still-running remote run. + const remoteGatewayStopped = legacyUserTurn + && historicalAdapter === "hermes_gateway" + && hasHermesGatewayTerminalStopProof(run.resultJson); if (!run.processPid && !run.processGroupId && + !remoteGatewayStopped && !await hasNativeLocalProcessStop(db, companyId, run.id) && !await hasHistoricalSuspendedNativeSession(db, run) && !await nativeRunNeverLaunched(db, run) && diff --git a/server/src/services/fresh-continuation-fallback.test.ts b/server/src/services/fresh-continuation-fallback.test.ts index d130aea9cbd..b019619dca0 100644 --- a/server/src/services/fresh-continuation-fallback.test.ts +++ b/server/src/services/fresh-continuation-fallback.test.ts @@ -1562,4 +1562,47 @@ suite("fresh-continuation fallback", () => { expect(await ensureFreshContinuation(db, { companyId, runId: f.runId, trigger: "held_recovery" })) .toEqual({ kind: "person_owned", reason: "retry_needed" }); }, 60_000); + + it("starts a fresh isolated workspace on auto-continuation after a non-retryable workspace binding_mismatch instead of reusing the broken workspace", async () => { + const f = await unfinishedRun({ runtime: "legacy", errorCode: "setup_failed", + error: "Saved workspace storage no longer matches this workspace; retrying the same workspace will not help" }); + const [workspace] = await db.insert(executionWorkspaces).values({ companyId, sourceIssueId: f.issueId, mode: "isolated", + strategyType: "git_worktree", name: "Broken task workspace", providerType: "local_fs", cwd: "/tmp/broken-binding-workspace" }).returning(); + await db.update(issues).set({ executionWorkspaceId: workspace!.id, workspaceBindingRevision: 1 }).where(eq(issues.id, f.issueId)); + await db.update(heartbeatRuns).set({ + resultJson: { workspaceProviderFailure: { kind: "provider", reason: "binding_mismatch", retryable: false } }, + }).where(eq(heartbeatRuns.id, f.runId)); + + const decided = await ensureFreshContinuation(db, { companyId, runId: f.runId, trigger: "recovery_refused" }); + expect(decided).toMatchObject({ kind: "continued", isolation: "fresh_isolated_workspace", delivery: "recorded" }); + expect(await issue(f.issueId)).toMatchObject({ executionWorkspaceId: null, workspaceBindingRevision: 2, status: "todo" }); + + await occupySlot(); + await deliver(); + const [next] = await successors(f.runId); + expect(next).toBeDefined(); + expect(next!.contextSnapshot).toMatchObject({ freshContinuationIsolation: f.actionId, forceFreshSession: true }); + expect(await readFreshWorkspaceReadiness(db, next!)).toMatchObject({ + mode: "fresh_isolated_workspace", + retryIntentId: f.actionId, + sourceRunId: f.runId, + }); + }, 60_000); + + it.each([ + { reason: "storage_pending", retryable: true, error: "Project storage is still being prepared; retry the same workspace shortly" }, + { reason: "credential_unavailable", retryable: false, error: "Workspace storage provider cannot use the project's Git credential; reconnect it before retrying" }, + ])("keeps writer_ended isolation for non-binding workspaceProviderFailure ($reason)", async ({ reason, retryable, error }) => { + const f = await unfinishedRun({ runtime: "legacy", errorCode: "setup_failed", error }); + const [workspace] = await db.insert(executionWorkspaces).values({ companyId, sourceIssueId: f.issueId, mode: "isolated", + strategyType: "git_worktree", name: "Reusable task workspace", providerType: "local_fs", cwd: "/tmp/reusable-workspace" }).returning(); + await db.update(issues).set({ executionWorkspaceId: workspace!.id, workspaceBindingRevision: 1 }).where(eq(issues.id, f.issueId)); + await db.update(heartbeatRuns).set({ + resultJson: { workspaceProviderFailure: { kind: "provider", reason, retryable } }, + }).where(eq(heartbeatRuns.id, f.runId)); + + const decided = await ensureFreshContinuation(db, { companyId, runId: f.runId, trigger: "recovery_refused" }); + expect(decided).toMatchObject({ kind: "continued", isolation: "writer_ended", delivery: "recorded" }); + expect(await issue(f.issueId)).toMatchObject({ executionWorkspaceId: workspace!.id, workspaceBindingRevision: 1 }); + }, 60_000); }); diff --git a/server/src/services/fresh-continuation-fallback.ts b/server/src/services/fresh-continuation-fallback.ts index bfc28ef8d31..e0cfc89c177 100644 --- a/server/src/services/fresh-continuation-fallback.ts +++ b/server/src/services/fresh-continuation-fallback.ts @@ -29,6 +29,7 @@ import { notifyStatusCardIssueChange } from "./status-card-notifications.js"; import { readRunCancellation } from "./run-cancellation.js"; import { activeIssueInteractionCondition } from "./issue-question-context.js"; import { readSystemRecovery } from "./system-recovery-state.js"; +import { readWorkspaceProviderFailure } from "./workspace-provider-failure.js"; import { RESTART_CLASS_FAILURE_CODES, continuationCauseIsSystemOwned, isPersonOwnedFailureCode } from "./continuation-cause.js"; import { sharedContinuationAttempts } from "./recovery/continuation-ledger.js"; import { BACKLOG_CONTINUATION_MAX_AGE_MS, failureOwnsBlock, heldExecutionWhere, heldRunIdSql, interruptionEligibility, @@ -587,9 +588,17 @@ export async function continueFreshInTransaction(tx: Db, input: Input): Promise< const aliveWait = writer === "alive" ? pending("previous_process_running", new Date(now.getTime() + step)) : null; if (aliveWait) return aliveWait; const fenced = await fenceSourceWorkspace(tx, run); + const workspaceProviderFailure = readWorkspaceProviderFailure(run.resultJson); + const workspaceBindingInvalidated = workspaceProviderFailure?.retryable === false + && workspaceProviderFailure.reason === "binding_mismatch"; // Never claim a stop that was not proven: record what isolates the successor. + // Only a workspace binding mismatch forces a fresh isolated workspace; other + // non-retryable operator/provider errors (e.g. credential_unavailable, + // unsupported_operation) preserve the usable task workspace. const isolation: FreshContinuationIsolation = fenced || remoteSource ? "remote_epoch" - : writer === "ended" && !pastBound() && !refused ? "writer_ended" : "fresh_isolated_workspace"; + : writer === "ended" && !pastBound() && !refused && !workspaceBindingInvalidated + ? "writer_ended" + : "fresh_isolated_workspace"; if (isolation === "fresh_isolated_workspace" && delivery === "saved_input") delivery = "recorded"; const unconfirmed = object(coordinator?.failureDetail).unconfirmedActions; const unverified = [...new Set([...await unverifiedActions(tx, run), @@ -607,7 +616,9 @@ export async function continueFreshInTransaction(tx: Db, input: Input): Promise< ? `Paperclip abandoned unverified workspace epoch ${fenced.abandonedEpoch} of run ${run.id}; the continuation restores ` + `${fenced.snapshotId ? `committed snapshot ${fenced.snapshotId}` : "the workspace source"} into a new root.` : isolation === "fresh_isolated_workspace" - ? `The previous writer of run ${run.id} is not proven stopped, so the continuation starts in a new isolated workspace; no unverified files are applied.` + ? workspaceBindingInvalidated + ? `The previous workspace of run ${run.id} could not be reused (${workspaceProviderFailure.reason}), so the continuation starts in a new isolated workspace.` + : `The previous writer of run ${run.id} is not proven stopped, so the continuation starts in a new isolated workspace; no unverified files are applied.` : `The continuation of run ${run.id} starts from the task's last saved workspace; no unverified files are applied.` }; const freshContinuation = { schema: FRESH_CONTINUATION_SCHEMA, sourceRunId: run.id, trigger: input.trigger, failureCode: run.errorCode ?? null, delivery, recordedAt: now.toISOString(), isolation, diff --git a/server/src/services/heartbeat/run-completion.test.ts b/server/src/services/heartbeat/run-completion.test.ts index eb500f25b0a..b673b32c923 100644 --- a/server/src/services/heartbeat/run-completion.test.ts +++ b/server/src/services/heartbeat/run-completion.test.ts @@ -1967,4 +1967,148 @@ describe.skipIf(!support.supported && !process.env.PAPERCLIP_TEST_DATABASE_URL)( expect(f.deps.releaseIssueExecutionAndPromote).not.toHaveBeenCalled(); expect(f.deps.finalizeAgentStatus).not.toHaveBeenCalled(); }); + + it("routes hermes_gateway shutdown interruptions through failed transient retry while keeping deliberate cancels cancelled", async () => { + const { mapFinalResultForTest } = await import("@paperclipai/hermes-paperclip-adapter/gateway/server"); + + const fShutdown = await fixture({}, `HG${randomUUID().slice(0, 6)}`); + const [hermesAgent] = await db.update(agents).set({ adapterType: "hermes_gateway" }) + .where(eq(agents.id, fShutdown.agent.id)).returning(); + const shutdownResult = mapFinalResultForTest({ + terminal: { + runId: "hermes-shutdown-1", + status: "cancelled", + payload: { status: "cancelled", error: "Gateway shutdown interrupted the run." }, + }, + outputChunks: [], + sessionKey: "session-shutdown", + strategy: "issue", + }); + await fShutdown.completion.completeRun({ + ...fShutdown.input, + agent: hermesAgent!, + adapterResult: shutdownResult, + }); + expect(await read(fShutdown.run.id)).toMatchObject({ + status: "failed", + errorCode: "hermes_gateway_run_failed", + resultJson: { + status: "interrupted", + gateway_status: "cancelled", + errorFamily: "transient_upstream", + conversationContinuation: "continue_conversation_v1", + }, + }); + expect(fShutdown.deps.scheduleBoundedRetryForRun).toHaveBeenCalledWith( + expect.objectContaining({ id: fShutdown.run.id, status: "failed" }), + hermesAgent, + ); + + const fCancel = await fixture({}, `HC${randomUUID().slice(0, 6)}`); + const [hermesCancelAgent] = await db.update(agents).set({ adapterType: "hermes_gateway" }) + .where(eq(agents.id, fCancel.agent.id)).returning(); + const cancelResult = mapFinalResultForTest({ + terminal: { + runId: "hermes-cancel-1", + status: "cancelled", + payload: { status: "cancelled", error: "Stopped by operator." }, + }, + outputChunks: [], + sessionKey: "session-cancel", + strategy: "issue", + }); + await fCancel.completion.completeRun({ + ...fCancel.input, + agent: hermesCancelAgent!, + adapterResult: cancelResult, + }); + expect(await read(fCancel.run.id)).toMatchObject({ + status: "cancelled", + resultJson: { status: "cancelled" }, + }); + expect(fCancel.deps.scheduleBoundedRetryForRun).not.toHaveBeenCalled(); + + const { hasConversationContinuationPolicy } = await import("../conversation-continuation.js"); + const { legacyExecutionNeedsReconciliation } = await import("../legacy-execution-recovery.js"); + + const fUnconfirmedTimeout = await fixture({}, `HU${randomUUID().slice(0, 6)}`); + const [hermesUnconfirmedAgent] = await db.update(agents).set({ adapterType: "hermes_gateway" }) + .where(eq(agents.id, fUnconfirmedTimeout.agent.id)).returning(); + await fUnconfirmedTimeout.completion.completeRun({ + ...fUnconfirmedTimeout.input, + agent: hermesUnconfirmedAgent!, + adapterResult: { + exitCode: 1, + signal: null, + timedOut: true, + errorCode: "hermes_gateway_timeout", + errorMessage: "Hermes gateway run timed out after 300s.", + provider: "hermes_gateway", + resultJson: { run_id: "hermes-timeout-unconfirmed", status: "timeout" }, + }, + }); + const unconfirmedPersisted = await read(fUnconfirmedTimeout.run.id); + expect(unconfirmedPersisted?.status).toBe("timed_out"); + expect(hasConversationContinuationPolicy(unconfirmedPersisted?.resultJson)).toBe(false); + expect(legacyExecutionNeedsReconciliation(unconfirmedPersisted!)).toBe(true); + + const fConfirmedTimeout = await fixture({}, `HT${randomUUID().slice(0, 6)}`); + const [hermesConfirmedAgent] = await db.update(agents).set({ adapterType: "hermes_gateway" }) + .where(eq(agents.id, fConfirmedTimeout.agent.id)).returning(); + await fConfirmedTimeout.completion.completeRun({ + ...fConfirmedTimeout.input, + agent: hermesConfirmedAgent!, + adapterResult: { + exitCode: 1, + signal: null, + timedOut: true, + errorCode: "hermes_gateway_timeout", + errorMessage: "Hermes gateway run timed out after 300s.", + provider: "hermes_gateway", + resultJson: { run_id: "hermes-timeout-confirmed", status: "cancelled" }, + }, + }); + const confirmedPersisted = await read(fConfirmedTimeout.run.id); + expect(confirmedPersisted?.status).toBe("timed_out"); + expect(hasConversationContinuationPolicy(confirmedPersisted?.resultJson)).toBe(true); + expect(legacyExecutionNeedsReconciliation(confirmedPersisted!)).toBe(false); + + // Ambiguous outbound POST /v1/runs HTTP 429/5xx responses do not prove non-dispatch + // (a proxy or redirect may have created the remote run), so they fail closed without + // stamping conversationContinuation and keep legacyExecutionNeedsReconciliation true. + for (const [tag, errorCode, reason] of [ + ["H4", "hermes_gateway_rate_limited", "rate_limited"], + ["H5", "hermes_gateway_upstream_error", "remote_unavailable"], + ] as const) { + const fCreateErr = await fixture({}, `${tag}${randomUUID().slice(0, 6)}`); + const [hermesCreateAgent] = await db.update(agents).set({ adapterType: "hermes_gateway" }) + .where(eq(agents.id, fCreateErr.agent.id)).returning(); + await fCreateErr.completion.completeRun({ + ...fCreateErr.input, + agent: hermesCreateAgent!, + adapterResult: { + exitCode: 1, + signal: null, + timedOut: false, + errorCode, + errorFamily: "transient_upstream", + errorMessage: `Hermes gateway ${reason}`, + provider: "hermes_gateway", + resultJson: { + connectionFailure: { + schemaVersion: 1, + provider: "hermes_gateway", + operation: "create_run", + reason, + }, + }, + }, + }); + const createErrPersisted = await read(fCreateErr.run.id); + expect(createErrPersisted?.status).toBe("failed"); + expect(hasConversationContinuationPolicy(createErrPersisted?.resultJson)).toBe(false); + expect(legacyExecutionNeedsReconciliation(createErrPersisted!)).toBe(true); + expect(fCreateErr.deps.scheduleBoundedRetryForRun).not.toHaveBeenCalled(); + } + }); }); diff --git a/server/src/services/heartbeat/run-lifecycle.ts b/server/src/services/heartbeat/run-lifecycle.ts index 7c6e8bf397f..d41ab0b41f4 100644 --- a/server/src/services/heartbeat/run-lifecycle.ts +++ b/server/src/services/heartbeat/run-lifecycle.ts @@ -60,7 +60,7 @@ import { import { connectionIntentService } from "../connection-intents.js"; import { CONVERSATION_CONTINUATION_POLICY, - isConversationAdapter, + isConversationContinuationEligible, } from "../conversation-continuation.js"; import { terminalizeLegacyExecution } from "../legacy-execution-recovery.js"; import { retryTransientLockContention } from "../transient-lock-contention.js"; @@ -2957,7 +2957,7 @@ export function createHeartbeatLifecycle(db: Db, dependencies: HeartbeatLifecycl parseObject(result?.executionCancellation).state === "acknowledged"; return options?.conversationContinuationEligible !== false && outcome !== "succeeded" && (outcome !== "cancelled" || cancellationAcknowledged) && - isConversationAdapter(agent.adapterType) + isConversationContinuationEligible(agent.adapterType, result) ? { ...result, conversationContinuation: CONVERSATION_CONTINUATION_POLICY } : result; } diff --git a/server/src/services/recovery/service.ts b/server/src/services/recovery/service.ts index ffb7302cf87..e8a1326c4f4 100644 --- a/server/src/services/recovery/service.ts +++ b/server/src/services/recovery/service.ts @@ -194,6 +194,7 @@ import { } from "./origins.js"; import { withRecoveryContext } from "./status-only-context.js"; import { getExecutionBlocker } from "../execution-blocker.js"; +import { readWorkspaceProviderFailure } from "../workspace-provider-failure.js"; import { currentRunFailureText } from "../native-runtime/native-exact-resume-failure.js"; import { isAutomaticRecoverySuppressedByPauseHold } from "./pause-hold-guard.js"; import { rehomeStrandedLegacyWorkspaceTasks } from "./legacy-workspace-rehome.js"; @@ -5792,7 +5793,10 @@ export function recoveryService( issue, previousStatus: "todo", latestRun, - notice: buildNoRunningExecutionNoticeSeed({ status: "todo" }), + notice: buildNoRunningExecutionNoticeSeed({ + status: "todo", + workspaceProviderFailure: readWorkspaceProviderFailure(latestRun?.resultJson), + }), }); if (updated) { result.escalated += 1; @@ -5835,7 +5839,10 @@ export function recoveryService( issue, previousStatus: "todo", latestRun, - notice: buildNoRunningExecutionNoticeSeed({ status: "todo" }), + notice: buildNoRunningExecutionNoticeSeed({ + status: "todo", + workspaceProviderFailure: readWorkspaceProviderFailure(latestRun?.resultJson), + }), }); if (updated) { result.escalated += 1; @@ -6072,7 +6079,11 @@ export function recoveryService( issue, previousStatus: "in_progress", latestRun, - notice: buildNoRunningExecutionNoticeSeed({ status: "in_progress", attempts: consecutive }), + notice: buildNoRunningExecutionNoticeSeed({ + status: "in_progress", + attempts: consecutive, + workspaceProviderFailure: readWorkspaceProviderFailure(latestRun?.resultJson), + }), }); if (updated) { result.escalated += 1; @@ -6130,7 +6141,11 @@ export function recoveryService( issue, previousStatus: "in_progress", latestRun, - notice: recoveryOutcome.retryExhausted ? buildNoRunningExecutionNoticeSeed({ status: "in_progress" }) + notice: recoveryOutcome.retryExhausted + ? buildNoRunningExecutionNoticeSeed({ + status: "in_progress", + workspaceProviderFailure: readWorkspaceProviderFailure(latestRun?.resultJson), + }) : recoveryOutcome.continuationRefused ? CONTINUATION_REFUSED_NOTICE : nonRetryableContinuationNotice(), }); diff --git a/server/src/services/recovery/stranded-notice.ts b/server/src/services/recovery/stranded-notice.ts index 2fd167dbc5a..c8c4b3d5102 100644 --- a/server/src/services/recovery/stranded-notice.ts +++ b/server/src/services/recovery/stranded-notice.ts @@ -1,6 +1,11 @@ import type { IssueCommentMetadata, IssueCommentPresentation } from "@paperclipai/shared"; +import type { PluginWorkspaceOperationFailureReason } from "@paperclipai/plugin-sdk"; import { ENVIRONMENT_PROVIDER_UNAVAILABLE_CODE } from "../environment-provider-unavailable-error.js"; import { PROJECT_STORAGE_ENVIRONMENT_INCOMPATIBLE } from "../project-storage-environment-reason.js"; +import { + workspaceProviderFailureMessage, + type WorkspaceProviderFailureSummary, +} from "../workspace-provider-failure.js"; import { agentLinkRow, keyValueRow, @@ -97,15 +102,24 @@ const SETUP_FAILURE_NOTICES: Record = { export const NO_RUNNING_EXECUTION_NOTICE_TITLE = "Task could not continue"; +export type StrandedWorkspaceProviderFailureInput = + | WorkspaceProviderFailureSummary + | PluginWorkspaceOperationFailureReason + | null + | undefined; + export function buildNoRunningExecutionNoticeSeed(input: { status: "todo" | "in_progress"; attempts?: number; + workspaceProviderFailure?: StrandedWorkspaceProviderFailureInput; }): StrandedRecoveryNoticeSeed { const tries = input.attempts && input.attempts > 1 ? ` after ${input.attempts} tries` : ""; + const resolvedReason = workspaceProviderFailureMessage(input.workspaceProviderFailure); + const detail = resolvedReason ? ` ${resolvedReason.replace(/[.!?]+$/, "")}.` : ""; return { body: input.status === "todo" - ? `Paperclip tried to start this task again, but it still could not start${tries}. Press Retry to start it again.` - : `Paperclip tried to continue this task again, but it still could not continue${tries}. ` + ? `Paperclip tried to start this task again, but it still could not start${tries}.${detail} Press Retry to start it again.` + : `Paperclip tried to continue this task again, but it still could not continue${tries}.${detail} ` + "Press Retry to start it again from the saved work.", title: NO_RUNNING_EXECUTION_NOTICE_TITLE, tone: "danger", @@ -114,6 +128,7 @@ export function buildNoRunningExecutionNoticeSeed(input: { export function buildImmediateExecutionPathRecoveryNoticeSeed(input: { status: "todo" | "in_progress"; + workspaceProviderFailure?: StrandedWorkspaceProviderFailureInput; }): StrandedRecoveryNoticeSeed { return buildNoRunningExecutionNoticeSeed(input); } diff --git a/server/src/services/workspace-provider-failure.ts b/server/src/services/workspace-provider-failure.ts index 8db7319a0f1..5b4cd0deaf5 100644 --- a/server/src/services/workspace-provider-failure.ts +++ b/server/src/services/workspace-provider-failure.ts @@ -106,3 +106,59 @@ export function findWorkspaceProviderFailure(error: unknown): WorkspaceProviderF } return null; } + +export type WorkspaceProviderFailureSummary = { + kind: WorkspaceProviderFailureKind; + reason: PluginWorkspaceOperationFailureReason | null; + retryable: boolean; +}; + +const KINDS: ReadonlySet = new Set([ + "worker_unavailable", "timeout", "worker_exited", "transport", "provider", +]); + +const KIND_MESSAGES: Record, string> = { + worker_unavailable: "Workspace storage provider is not running", + timeout: "Workspace storage operation timed out", + worker_exited: "Workspace storage provider stopped during the operation", + transport: "Workspace storage operation is incomplete", +}; + +/** Read the bounded workspace provider failure recorded on a failed run's `resultJson`. */ +export function readWorkspaceProviderFailure( + resultJson: unknown, +): WorkspaceProviderFailureSummary | null { + if (!resultJson || typeof resultJson !== "object" || Array.isArray(resultJson)) return null; + const raw = (resultJson as Record).workspaceProviderFailure; + if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null; + const record = raw as Record; + if (typeof record.kind !== "string" || !KINDS.has(record.kind as WorkspaceProviderFailureKind)) return null; + if (typeof record.retryable !== "boolean") return null; + const reason = typeof record.reason === "string" && Object.hasOwn(REASONS, record.reason) + ? (record.reason as PluginWorkspaceOperationFailureReason) + : null; + return { + kind: record.kind as WorkspaceProviderFailureKind, + reason, + retryable: record.retryable, + }; +} + +/** Resolve a closed, Core-owned human-readable message for a saved workspace provider failure or reason key. */ +export function workspaceProviderFailureMessage( + failureOrReason: WorkspaceProviderFailureSummary | string | null | undefined, +): string | null { + if (!failureOrReason) return null; + if (typeof failureOrReason === "string") { + return Object.hasOwn(REASONS, failureOrReason) + ? REASONS[failureOrReason as PluginWorkspaceOperationFailureReason].message + : null; + } + if (failureOrReason.reason && Object.hasOwn(REASONS, failureOrReason.reason)) { + return REASONS[failureOrReason.reason].message; + } + if (failureOrReason.kind !== "provider") { + return KIND_MESSAGES[failureOrReason.kind]; + } + return null; +}