Files
PaperClipAI/server/src/services/acknowledged-native-stop.ts
T
DottaandClaude Opus 5.5 b05d3db2b3 fix(recovery): continue a pre-turn interrupt after recovery, not after the destroy (#19292)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - A board user can interrupt a native run with a comment. The next
turn should start soon after the run stops
> - When the stop leaves sandbox files unsaved, recovery saves them,
re-stops the sandbox, and then queues the destroy for an ephemeral lease
> - #19224 kept the verified stop on that lease as
`workspaceRecoveryCleanup.stopReceipt`, and taught the continuation
gates to accept it
> - One gate was missed: `acknowledgedNativeStopExecutionHasStopped`. An
interrupt that lands before the provider turn opens leaves no gating
hold, so the saved comment goes through this gate, not through the
explicit continuation gate
> - That gate still wanted the raw `remoteExecutionTermination` receipt,
so the comment waited about 5 minutes for the destroy retry
> - This pull request lets that gate accept the carried-forward stop
receipt too
> - The benefit is that an interrupt during startup continues right
after recovery, as #19224 intended for every lease policy

## Linked Issues or Issue Description

Refs #19224
Refs #19206

**What happened?**
On hosted staging, an `interrupt: true` comment reached a native run of
an ephemeral-lease agent while the run was still in startup (the
provider pack upload). The run stopped before any provider turn.
Recovery saved its files at once. The follow-up turn started about 6
minutes after the interrupt. The stopped run's lease was released by
`pending_cleanup_retry`, and the follow-up started 2 seconds later.
Agents whose interrupt landed after the provider turn opened continued
in 30 to 50 seconds on the same build.

**Expected behavior**
The saved comment starts a new turn right after recovery saves the files
and the sandbox is stopped. The destroy of a stopped sandbox is cleanup
and must not hold the next turn.

**Steps to reproduce**
1. Use an agent whose sandbox lease is ephemeral (destroy after each
turn).
2. Post an `interrupt: true` comment while its native run is still
starting, before the provider turn opens.
3. Let recovery save the files. See the follow-up start only after the
destroy retry releases the lease.

**Paperclip version or commit**
Hosted staging at `e37ab23d` (includes #19206 and #19224).

## What Changed

- `server/src/services/acknowledged-native-stop.ts`:
`acknowledgedNativeStopExecutionHasStopped` accepts a remote lease that
has `hasRemoteTerminationReceipt` or `hasRecoveredCleanupStopReceipt`.
Before, it accepted only the first one.
- `server/src/services/workspace-recovery.test.ts`: new regression for a
pre-turn interrupt on an ephemeral lease. Recovery completes, the
destroy is queued, and the saved comment is handed to
`resumeRemoteStopComments` twice. With a verified carried stop, exactly
one turn starts while the lease is still `pending_cleanup`. Without the
stop receipt, the comment stays deferred and no turn starts.
- `doc/execution-semantics.md`: one sentence that extends the #19224
paragraph to the pre-turn Stop case.

## Verification

- Red before the fix: `cd server && npx vitest run
src/services/workspace-recovery.test.ts -t "starts the interrupt
redirect once after recovery"` failed the `verified-stop` case with
`expected [] to have a length of 1 but got +0`. The `no-stop-receipt`
case passed.
- Green after the fix: the same command passes both cases.
- `npx vitest run src/services/workspace-recovery.test.ts`: 382 passed.
- Related suites pass: `acknowledged-native-stop`,
`explicit-native-continuation`, `heartbeat/run-control`,
`heartbeat/recovery`, `heartbeat/native-stop-evidence-read`,
`native-session-executor`, `heartbeat-observed-workspace-preservation`,
`native-startup-cleanup-recovery`, `execution-control-work`. Two
`run-control` cases timed out at 30 s under parallel load and passed
when run alone.
- `pnpm --filter @paperclipai/server typecheck` passes.
- Not done: a live re-run on staging. This change is not deployed.

## Risks

- Low risk. `hasRecoveredCleanupStopReceipt` is the same check #19224
added to the other gates. It is true only for a lease whose recovery
cleanup belongs to its own run, which was released, and whose carried
stop receipt matches the company, run, lease, provider, and provider
lease id. A lease without that receipt still blocks.
- The no-replay hold is unchanged. The successor still goes through
ordinary admission with all task gates. The test calls the resume twice
and sees one turn only.

> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.

## Model Used

- Claude Opus 5.5 (Anthropic), model ID `claude-opus-5-5`, used through
Claude Code with tool use (shell, file edits, browser reads of staging).
Extended reasoning was used.

## 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)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 11:46:57 -06:00

111 lines
7.7 KiB
TypeScript

import { and, desc, eq, inArray, isNotNull } from "drizzle-orm";
import { environmentLeases, heartbeatRunEvents, heartbeatRuns, type Db } from "@paperclipai/db";
import { parseObject } from "../adapters/utils.js";
import { resolveProviderApiPlacement } from "./native-runtime/provider-api-placement.js";
import { hasNativeLocalProcessStop } from "./native-local-process-stop.js";
import { hasRecoveredCleanupStopReceipt, hasRemoteTerminationReceipt } from "./remote-execution-termination.js";
import { validatePrpEvent } from "../vendor/paperclip-runner/index.js";
import { nativeSha256 } from "./native-runtime/canonical.js";
import { isConfirmedCursorCloudTerminalObservation } from "./native-runtime/cursor-cloud-runtime.js";
export function hasAcknowledgedNativeRunStopRequest(run: {
id: string; companyId: string; status: string; nativeIssueId: string | null;
resultJson: Record<string, unknown> | null;
}): boolean {
const result = run.resultJson;
const intent = result?.nativeCancellation as Record<string, unknown> | undefined;
return intent?.schema === "paperclip.native-cancellation.v1" && intent.runId === run.id &&
intent.companyId === run.companyId && intent.issueId === run.nativeIssueId &&
intent.scope === "run" && intent.reasonCode === "cancellation_run_only" &&
intent.dispatchState === "acknowledged" && typeof intent.dispatched === "boolean" &&
typeof intent.intentAuditId === "string" && Boolean(intent.intentAuditId) &&
typeof intent.acknowledgementAuditId === "string" && Boolean(intent.acknowledgementAuditId);
}
export function hasAcknowledgedNativeRunStopReceipt(run: Parameters<typeof hasAcknowledgedNativeRunStopRequest>[0]): boolean {
return hasAcknowledgedNativeRunStopRequest(run) &&
(run.resultJson?.nativeCancellation as Record<string, unknown>).dispatched === true;
}
export function hasAcknowledgedNativeStopIntent(run: Parameters<typeof hasAcknowledgedNativeRunStopReceipt>[0]): boolean {
return run.resultJson?.cancelledByActorType === "user" &&
typeof run.resultJson.cancelledByUserId === "string" && Boolean(run.resultJson.cancelledByUserId) &&
hasAcknowledgedNativeRunStopReceipt(run);
}
/** An intentional handoff retains task state and deferred work for its successor. */
export function hasAcknowledgedNativeReassignmentStopIntent(run: Parameters<typeof hasAcknowledgedNativeRunStopReceipt>[0]): boolean {
return run.resultJson?.reassignmentStopRequested === true && hasAcknowledgedNativeRunStopReceipt(run);
}
export function isAcknowledgedNativeReassignmentStop(run: Parameters<typeof hasAcknowledgedNativeRunStopReceipt>[0]): boolean {
return run.status === "cancelled" && hasAcknowledgedNativeReassignmentStopIntent(run);
}
export function isAcknowledgedNativeStop(run: Parameters<typeof hasAcknowledgedNativeStopIntent>[0]): boolean {
return run.status === "cancelled" && hasAcknowledgedNativeStopIntent(run);
}
/** API-owned execution has no Computer lease. Its provider terminal and retired
* local controller must both be recorded before publishing shared Stop proof. */
export async function acknowledgedNativeApiStopExecutionHasStopped(db: Db, run: Pick<typeof heartbeatRuns.$inferSelect,
"id" | "companyId" | "agentId" | "nativeIssueId" | "status" | "resultJson" | "processPid" | "processGroupId" |
"runtimeMode" | "driverKind" | "runnerProfileJson" | "nativeSessionId" | "runnerInstanceId">): Promise<boolean> {
if (run.runtimeMode !== "native" || run.driverKind !== "cursor_cloud_api" || !isAcknowledgedNativeStop(run) ||
run.processPid !== null || run.processGroupId !== null || !run.nativeIssueId || !run.nativeSessionId || !run.runnerInstanceId) return false;
const intent = parseObject(run.resultJson?.nativeCancellation);
const requestedAt = typeof intent.recordedAt === "string" ? Date.parse(intent.recordedAt) : NaN;
if (!Number.isFinite(requestedAt) || !Array.isArray(intent.effects) || intent.effects.length !== 1 ||
intent.effects[0] !== "release_run_resources" ||
!String(intent.intentAuditId ?? "").trim() || !String(intent.acknowledgementAuditId ?? "").trim()) return false;
const profile = parseObject(run.runnerProfileJson);
const execution = parseObject(profile.nativeExecutionInput);
const binding = parseObject(execution.binding), session = parseObject(execution.session);
if (profile.executionPlacement === undefined || profile.backend !== "cursor_cloud_api" ||
binding.companyId !== run.companyId || binding.runId !== run.id || binding.issueId !== run.nativeIssueId ||
binding.agentId !== run.agentId || session.normalizedSessionId !== run.nativeSessionId || session.driverKind !== "cursor_cloud_api") return false;
try {
if (!resolveProviderApiPlacement({ run, agent: { adapterType: "process", adapterConfig: {} } })) return false;
} catch { return false; }
const [lease] = await db.select({ id: environmentLeases.id }).from(environmentLeases).where(and(
eq(environmentLeases.companyId, run.companyId), eq(environmentLeases.heartbeatRunId, run.id),
)).limit(1);
if (lease || !await hasNativeLocalProcessStop(db, run.companyId, run.id)) return false;
const [terminal] = await db.select().from(heartbeatRunEvents).where(and(
eq(heartbeatRunEvents.companyId, run.companyId), eq(heartbeatRunEvents.runId, run.id),
isNotNull(heartbeatRunEvents.sourceEventId),
inArray(heartbeatRunEvents.eventType, ["turn.started", "turn.completed", "turn.failed", "turn.cancelled", "turn.interrupted"]),
)).orderBy(desc(heartbeatRunEvents.seq)).limit(1);
const validated = validatePrpEvent(parseObject(terminal?.payload).prpEvent);
if (!terminal || !validated.ok || terminal.sourcePayloadSha256 !== nativeSha256(validated.event)) return false;
const event = validated.event;
return isConfirmedCursorCloudTerminalObservation({ eventType: terminal.eventType, payload: event.payload }) && terminal.agentId === run.agentId &&
event.schema === "paperclip.prp.event.v1" && [1, 2].includes(Number(event.schemaVersion)) &&
terminal.protocolSchemaVersion === event.schemaVersion && event.eventType === terminal.eventType &&
event.sourceKind === "runner" && event.runId === run.id && event.normalizedSessionId === run.nativeSessionId &&
event.sourceInstanceId === run.runnerInstanceId && terminal.sourceInstanceId === event.sourceInstanceId &&
terminal.sourceEventId === event.sourceEventId && terminal.sourceSeq === event.sourceSeq &&
Number.isSafeInteger(event.sourceSeq) && Number(event.sourceSeq) > 0 &&
typeof event.turnId === "string" && Boolean(event.turnId);
}
/** A Stop acknowledgement alone does not prove provider cleanup completed. */
export async function acknowledgedNativeStopExecutionHasStopped(db: Db, run: Pick<typeof heartbeatRuns.$inferSelect,
"id" | "companyId" | "nativeIssueId" | "status" | "resultJson" | "processPid" | "processGroupId">) {
if (!isAcknowledgedNativeStop(run)) return false;
const leases = await db.select().from(environmentLeases).where(and(
eq(environmentLeases.companyId, run.companyId), eq(environmentLeases.heartbeatRunId, run.id),
));
// Provider PIDs are meaningful only on their own host. A recovered sandbox
// queued for destroy keeps its verified stop; the destroy is only cleanup.
if (leases.some(lease => lease.provider !== "local"))
return leases.every(lease => hasRemoteTerminationReceipt(lease) || hasRecoveredCleanupStopReceipt(lease));
if (leases.some(lease => !lease.releasedAt || lease.cleanupStatus === "failed")) return false;
if (!run.processPid && !run.processGroupId) return hasNativeLocalProcessStop(db, run.companyId, run.id);
const absent = (pid: number) => {
try { process.kill(pid, 0); return false; }
catch (error) { return (error as NodeJS.ErrnoException).code === "ESRCH"; }
};
return (!run.processPid || absent(run.processPid)) && (!run.processGroupId || absent(-run.processGroupId));
}