Files
PaperClipAI/server/src/services/workspace-provider-failure.ts
T
Dotta 560765988d fix(recovery): unblock hermes_gateway holds, classify 429/529 transient, and isolate binding_mismatch (#22969)
## 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)
2026-11-25 15:32:05 -06:00

165 lines
8.7 KiB
TypeScript

import {
JsonRpcCallError,
PLUGIN_RPC_ERROR_CODES,
readWorkspaceOperationFailureReason,
type PluginWorkspaceOperationFailureReason,
} from "@paperclipai/plugin-sdk";
import { HttpError } from "../errors.js";
import { findPluginWorkerUnavailableError, PluginWorkerUnavailableError } from "./plugin-worker-unavailable-error.js";
/**
* How a `workspaceOperation` call failed.
* - `worker_unavailable`: the worker was not running, so no request was sent.
* - `timeout`: no reply arrived in time; the operation may still have run.
* - `worker_exited`: the worker stopped with the call pending; the operation may have run.
* - `transport`: any other failure before a reply; the outcome is unknown.
* - `provider`: the provider replied with an error.
*/
export type WorkspaceProviderFailureKind = "worker_unavailable" | "timeout" | "worker_exited" | "transport" | "provider";
const INCOMPLETE = "Workspace storage operation is incomplete; retry the same workspace";
/** Core owns every message. Provider text and values never reach the run, the log or the API. */
const REASONS: Record<PluginWorkspaceOperationFailureReason, { message: string; retryable: boolean }> = {
unsupported_operation: { retryable: false,
message: "Workspace storage provider does not support this workspace operation" },
configuration_unavailable: { retryable: false,
message: "Workspace storage provider configuration is unavailable; an operator must fix it before retrying" },
credential_unavailable: { retryable: false,
message: "Workspace storage provider cannot use the project's Git credential; reconnect it before retrying" },
storage_grant_unavailable: { retryable: false,
message: "Project storage access is unavailable or out of date; reconcile the project's storage before retrying" },
binding_mismatch: { retryable: false,
message: "Saved workspace storage no longer matches this workspace; retrying the same workspace will not help" },
storage_pending: { retryable: true,
message: "Project storage is still being prepared; retry the same workspace shortly" },
runtime_unavailable: { retryable: true,
message: "The selected runtime is not ready; retry the same workspace once it is ready" },
runtime_connection_invalid: { retryable: false,
message: "The selected runtime's saved connection is invalid; reprovision the runtime before retrying" },
remote_incomplete: { retryable: true, message: INCOMPLETE },
context_changed: { retryable: true,
message: "Workspace storage changed during the operation; retry the same workspace" },
deadline_exceeded: { retryable: true,
message: "Workspace storage operation expired; retry the same workspace" },
};
/** A failed `workspaceOperation` call, with a bounded kind and reason. */
export class WorkspaceProviderFailureError extends HttpError {
readonly kind: WorkspaceProviderFailureKind;
readonly reason: PluginWorkspaceOperationFailureReason | null;
readonly retryable: boolean;
constructor(input: { kind: WorkspaceProviderFailureKind; reason?: PluginWorkspaceOperationFailureReason | null;
retryable: boolean; message: string; cause?: unknown }) {
const reason = input.reason ?? null;
super(409, input.message, { code: "workspace_provider_failed", kind: input.kind, reason, retryable: input.retryable });
this.name = "WorkspaceProviderFailureError";
this.kind = input.kind;
this.reason = reason;
this.retryable = input.retryable;
if (input.cause !== undefined) this.cause = input.cause;
}
/** Bounded fields for run results and logs. */
summary() {
return { kind: this.kind, reason: this.reason, retryable: this.retryable };
}
}
/**
* Classify a rejected `workspaceOperation` call. A provider error never passes
* its message or data through; only a reason from the SDK's closed set does.
*/
export function workspaceProviderCallFailure(error: unknown): WorkspaceProviderFailureError {
const unavailable = findPluginWorkerUnavailableError(error);
// Keep the refusal as the cause so setup can retry it: no request reached the provider.
if (unavailable) return new WorkspaceProviderFailureError({ kind: "worker_unavailable", retryable: true,
message: "Workspace storage provider is not running; retry the same workspace", cause: unavailable });
if (!(error instanceof JsonRpcCallError)) return new WorkspaceProviderFailureError({ kind: "transport", retryable: true, message: INCOMPLETE });
if (error.code === PLUGIN_RPC_ERROR_CODES.TIMEOUT) return new WorkspaceProviderFailureError({ kind: "timeout", retryable: true,
message: "Workspace storage operation timed out; retry the same workspace" });
if (error.code === PLUGIN_RPC_ERROR_CODES.WORKER_UNAVAILABLE) return new WorkspaceProviderFailureError({ kind: "worker_exited", retryable: true,
message: "Workspace storage provider stopped during the operation; retry the same workspace" });
const reason = readWorkspaceOperationFailureReason(error);
if (!reason) return new WorkspaceProviderFailureError({ kind: "provider", retryable: true,
message: "Workspace storage provider reported a failure; retry the same workspace" });
return new WorkspaceProviderFailureError({ kind: "provider", reason, ...REASONS[reason] });
}
/**
* Before a call to a ready provider: a worker that is missing, or not running and without
* `workspaceOperation`, refuses the call retryably. A restart removes or replaces the worker
* while the plugin stays ready, and its methods are unknown until it runs. A running worker
* without the method is an unsupported provider, so this returns null for it.
*/
export function workspaceWorkerRefusal(pluginId: string, worker: { status?: string; supportedMethods?: readonly string[] } | undefined) {
if (worker?.supportedMethods?.includes("workspaceOperation") || worker?.status === "running") return null;
return workspaceProviderCallFailure(new PluginWorkerUnavailableError({ pluginId, workerStatus: worker?.status ?? null,
message: `Cannot call "workspaceOperation" — worker for "${pluginId}" is ${worker?.status ?? "not registered"}` }));
}
/** Find a provider call failure through setup's error wrappers. */
export function findWorkspaceProviderFailure(error: unknown): WorkspaceProviderFailureError | null {
for (let cause = error, depth = 0; cause && depth < 4; cause = (cause as { cause?: unknown }).cause, depth++) {
if (cause instanceof WorkspaceProviderFailureError) return cause;
}
return null;
}
export type WorkspaceProviderFailureSummary = {
kind: WorkspaceProviderFailureKind;
reason: PluginWorkspaceOperationFailureReason | null;
retryable: boolean;
};
const KINDS: ReadonlySet<WorkspaceProviderFailureKind> = new Set([
"worker_unavailable", "timeout", "worker_exited", "transport", "provider",
]);
const KIND_MESSAGES: Record<Exclude<WorkspaceProviderFailureKind, "provider">, 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<string, unknown>).workspaceProviderFailure;
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;
const record = raw as Record<string, unknown>;
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;
}