Files
PaperClipAI/server/src/services/conversation-continuation.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

192 lines
10 KiB
TypeScript

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";
import { canonicalExecutionUuid } from "./execution-identity.js";
import { readProcessStartedAt } from "./hot-restart.js";
import { hasRemoteTerminationReceipt } from "./remote-execution-termination.js";
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<string, unknown> | 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<string, unknown> | null | undefined): boolean {
return result?.workspaceRestoreFailure !== "restore_unsafe_archive" && !hasRequiredWorkspaceRecovery(result) && result?.conversationContinuation === CONVERSATION_CONTINUATION_POLICY;
}
/** Persisted by the server when it claims the run, before remote provisioning. */
export function claimedAdapterType(run: Pick<typeof heartbeatRuns.$inferSelect, "runnerProfileJson">): string | null {
const dispatch = run.runnerProfileJson?.adapterDispatch as Record<string, unknown> | undefined;
return typeof dispatch?.adapterType === "string" ? dispatch.adapterType : null;
}
function conversationRunPredicate() {
return or(
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'`, [...LOCAL_CONVERSATION_ADAPTER_TYPES])}
)`,
);
}
/** Recovery must not infer the old adapter from the agent's mutable settings. */
export async function historicalAdapterType(db: Db, run: Pick<typeof heartbeatRuns.$inferSelect,
"id" | "companyId" | "runnerProfileJson">): Promise<string | null> {
const selected = claimedAdapterType(run);
if (selected) return selected;
const [invocation] = await db.select({ payload: heartbeatRunEvents.payload }).from(heartbeatRunEvents)
.where(and(eq(heartbeatRunEvents.companyId, run.companyId), eq(heartbeatRunEvents.runId, run.id),
eq(heartbeatRunEvents.eventType, "adapter.invoke")))
.orderBy(desc(heartbeatRunEvents.seq)).limit(1);
const adapterType = invocation?.payload?.adapterType;
return typeof adapterType === "string" ? adapterType : null;
}
export async function runUsedConversationAdapter(db: Db, run: typeof heartbeatRuns.$inferSelect): Promise<boolean> {
if (run.resultJson?.workspaceRestoreFailure === "restore_unsafe_archive" || hasRequiredWorkspaceRecovery(run.resultJson)) return false;
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);
}
/** Only immutable run evidence can retire a historical conversation hold.
* An agent's current adapter can differ from the one that executed this run.
* Missing evidence retains the hold; the current agent is never a fallback.
*/
export function conversationRecoveryActionPredicate() {
return and(
eq(issueRecoveryActions.cause, "legacy_execution_requires_reconciliation"),
sql`exists (
select 1 from ${heartbeatRuns}
where ${heartbeatRuns.companyId} = ${issueRecoveryActions.companyId}
and ${heartbeatRuns.id} = ${canonicalExecutionUuid(sql`${issueRecoveryActions.evidence}->>'runId'`)}
and ${or(
eq(heartbeatRuns.nativeIssueId, issueRecoveryActions.sourceIssueId),
and(isNull(heartbeatRuns.nativeIssueId), sql`${heartbeatRuns.contextSnapshot}->>'issueId' = ${issueRecoveryActions.sourceIssueId}::text`),
)}
and ${heartbeatRuns.runtimeMode} = 'legacy'
and coalesce(${heartbeatRuns.resultJson}->>'workspaceRestoreFailure', '') <> 'restore_unsafe_archive'
and coalesce(${heartbeatRuns.resultJson}->'workspaceRestoreRecovery'->>'schema', '') <> 'paperclip.workspace-restore-recovery.v1'
and ${inArray(heartbeatRuns.status, ['failed', 'timed_out', 'interrupted', 'cancelled'])}
and ${conversationRunPredicate()}
and ${or(
sql`${heartbeatRuns.resultJson}->>'conversationContinuation' = ${CONVERSATION_CONTINUATION_POLICY}`,
eq(heartbeatRuns.status, "interrupted"),
inArray(heartbeatRuns.errorCode, ["process_lost", "server_shutdown_interrupted", "execution_reconciliation_required"]),
and(eq(heartbeatRuns.status, "cancelled"), sql`${heartbeatRuns.resultJson}->'executionCancellation'->>'state' = 'acknowledged'`),
)}
)`,
);
}
/** OS liveness probes do not signal or stop the process. Unknown ownership holds. */
function processMayBeAlive(pid: number): boolean {
try {
process.kill(pid, 0);
return true;
} catch (error) {
return (error as NodeJS.ErrnoException).code !== "ESRCH";
}
}
/** A terminal conversation row does not prove that its execution authority ended.
* Other adapters keep their existing bootstrap and ownership protocols.
*/
export async function getConversationOwnershipBlocker(db: Db, companyId: string, issueId: string) {
const activeLease = sql`exists (select 1 from ${environmentLeases}
where ${environmentLeases.companyId} = "heartbeat_runs"."company_id"
and ${environmentLeases.heartbeatRunId} = "heartbeat_runs"."id"
and (${environmentLeases.releasedAt} is null
or ${environmentLeases.status} = 'pending_cleanup'
or ${environmentLeases.cleanupStatus} = 'failed'))`;
const candidates = await db.select({ run: {
id: heartbeatRuns.id,
agentId: heartbeatRuns.agentId,
processPid: heartbeatRuns.processPid,
processGroupId: heartbeatRuns.processGroupId,
processStartedAt: heartbeatRuns.processStartedAt,
resultJson: heartbeatRuns.resultJson,
}, activeLease }).from(heartbeatRuns)
.where(and(
eq(heartbeatRuns.companyId, companyId), eq(heartbeatRuns.runtimeMode, "legacy"),
conversationRunPredicate(),
or(
eq(heartbeatRuns.nativeIssueId, canonicalExecutionUuid(sql`${issueId}::text`)),
and(isNull(heartbeatRuns.nativeIssueId), sql`${heartbeatRuns.contextSnapshot}->>'issueId' = ${issueId}`),
),
inArray(heartbeatRuns.status, ["failed", "timed_out", "interrupted", "cancelled"]),
or(isNotNull(heartbeatRuns.processPid), isNotNull(heartbeatRuns.processGroupId), activeLease,
sql`${heartbeatRuns.resultJson}->'workspaceRestoreRecovery'->>'schema' = 'paperclip.workspace-restore-recovery.v1'`),
)).orderBy(desc(heartbeatRuns.createdAt), desc(heartbeatRuns.id));
for (const { run, activeLease: leaseHeld } of candidates) {
if (hasRequiredWorkspaceRecovery(run.resultJson)) {
const leases = await db.select().from(environmentLeases).where(and(
eq(environmentLeases.companyId, companyId), eq(environmentLeases.heartbeatRunId, run.id),
));
const retainedIds = (run.resultJson!.workspaceRestoreRecovery as { leaseIds?: unknown }).leaseIds;
const remoteLeases = leases.filter(lease => lease.provider !== "local");
const remoteStopped = Array.isArray(retainedIds) && retainedIds.length > 0
&& retainedIds.every(id => typeof id === "string" && remoteLeases.some(lease =>
lease.id === id && hasRemoteTerminationReceipt(lease)))
&& remoteLeases.every(hasRemoteTerminationReceipt);
if (!remoteStopped) return {
runId: run.id, agentId: run.agentId, cause: "execution_owner_active",
nextAction: "The retained workspace environment has not confirmed that it stopped. Wait for cleanup before continuing this task.",
};
// These PIDs came from the sandbox. A matching process on this host is
// unrelated and must not hide the repair action or block a repaired task.
// A separate local lease keeps the existing host process checks below.
if (leases.every(lease => lease.provider !== "local")) continue;
}
let pidAlive = run.processPid !== null && processMayBeAlive(run.processPid);
if (pidAlive && run.processStartedAt) {
// A recycled PID cannot keep an old task blocked. An unreadable identity
// stays conservative; the original process may still own execution.
const observed = await readProcessStartedAt(run.processPid!).catch(() => null);
if (observed && new Date(observed).getTime() !== run.processStartedAt.getTime()) pidAlive = false;
}
const groupAlive = run.processGroupId !== null && processMayBeAlive(-run.processGroupId);
if (pidAlive || groupAlive || leaseHeld) {
return {
runId: run.id,
agentId: run.agentId,
cause: "execution_owner_active",
nextAction: pidAlive || groupAlive
? "The previous provider process is still running. Stop it before continuing this task."
: "The previous execution has not released its environment lease. Wait for cleanup before continuing this task.",
};
}
}
return null;
}