fix(runner): keep the session of a stopped run (#23543)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The conversation an agent has on a task is called a session. Each
task saves a pointer to its session (the session link), and the next run
uses it to continue the conversation
> - A run's own record keeps its session id. The task gets its pointer
to that session only when the run's result is accepted
> - A stopped run has no accepted result, so it saves no pointer. If a
task's first run is stopped, the task has no pointer. The next run
starts a new session and the agent has forgotten the first run
> - A later run can also start a new session, for example after an
assignment, a retry or a configuration change. If that run is stopped,
the pointer still names the older session. The next message goes back to
the older session or starts another one
> - Saving the pointer on every stop would be unsafe. The agent's turn
might still be open, a request might still be waiting, or the provider
might not have kept the session
> - This pull request copies the session id from a stopped run to the
task only when the records show that the stop was acknowledged, the turn
started and then ended with nothing waiting, the provider kept the
session, and no newer run has taken over the task. Otherwise, the
pointer does not change
> - The benefit is that someone can stop a run, send a correction, and
continue the same conversation

## Linked Issues or Issue Description

No issue exists.

**What happened?**

A user stopped the first run of a task. The user then sent a message.
The agent started a new session and did not remember the first run. The
same loss happens when a user stops a later run that started a new
session.

**Expected behavior**

The agent continues the session of the stopped run.

**Steps to reproduce**

1. Use an agent whose environment provider runs Runner tasks and keeps
their session state.
2. Create a task and wait for the first run to start a turn.
3. Stop the run during the turn.
4. Send a message on the task.
5. See that the new run has a new session.

**Paperclip version or commit**

`4db307d53c`

**Deployment mode**

Self-hosted server with a sandbox environment plugin.

## What Changed

- A stopped run now links its session after its environment lease is
released.
- The link needs all of this evidence:
  - The Stop was delivered and acknowledged.
- The provider accepted a turn. The next prompt leaves out messages that
the linked run received, so a run whose turn did not start cannot be
linked.
  - The turn ended. No request, background work or goal is waiting.
  - The controller journal is settled.
- The provider reports that the task stopped and that it kept the
session state.
  - No newer run, reset or conversation owns the task.
- An existing link is replaced only if its run belongs to the same task
and agent and finished before the stopped run started. Accepted results
already use this rule. Both paths now share one function.
- If any evidence is missing, the link does not change, as before.
- If the provider later confirms that the kept state is gone, the next
run starts a new session. The acknowledged Stop replaces the committed
result in that proof. All other checks in that proof still apply.

## Verification

- `npx vitest run` on the publication tests for stopped runs, the
publication tests for accepted results, the runtime execution tests and
the terminal state reader test: 121 passed. The executor tests ran on an
earlier commit, and the executor code has not changed since.
- The publication tests use embedded Postgres. They test six saves and
37 refusals. Each refusal checks that the task session row did not
change.
- The executor tests check that a stopped run retires after a confirmed
state loss. They also check that an unacknowledged Stop and a different
failure stay refused.
- `npx tsc --noEmit` in `server` has no errors.
- Saved evidence from two real first-run stops during a turn shows ended
turns with no request waiting. The first has a released lease with kept
session state. The second failed its lease cleanup, so this change still
refuses it.
- Saved evidence from two real later-run stops: one kept its session,
and the next run resumed it. The other kept no session and had no
settled turn, and the next run failed. This change refuses to link the
second.
- Two of 104 real stops with a cancelled terminal had no accepted turn.
The turn check refuses them.
- Not done: a live test of this change. CI runs the Runner integration
suites.

## Risks

- A wrong link could resume an unsafe session. The link uses the same
evidence that the resume path checks again, so the resume path still
refuses an unsettled session.
- A link that turns out to be unusable now replaces an older link
instead of no link. The next run then usually fails, and the run after
it usually starts a new session, as it does for an unusable link from a
finished run.
- The change applies only to providers that run Runner tasks and report
kept session state. Local Runners and other sandboxes have no equal
evidence, so they keep the previous behavior.
- A stop while the agent waits for background work is not covered. The
Runner holds its terminal event in that state, so the evidence is
missing.
- The saved link keeps that run's Runner checkpoint, as any other link
does.
- No migration.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, in Claude Code, with
extended thinking, 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)
- [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>
This commit is contained in:
Nicky LeachandClaude Opus 5.5 authored and GitHub committed 2026-12-03 08:17:44 -08:00
1 parent dc16c47362
commit 63d3354be7
10 files changed
+379 -15

No files matched your search

+13
View File
@@ -603,6 +603,19 @@ or cancelled result must retire that session and collect its managed files befor
heartbeat stops the reusable sandbox. A later retry can resume the same sandbox
without inheriting the stopped provider transport.
A stopped run has no accepted result, so `publishStoppedNativeSession` moves the
task's session link to it after its environment lease is released. It does so
only for an acknowledged Stop whose turn the provider accepted and then ended
with no request or background work waiting, whose controller journal is settled,
and whose provider reports that the task stopped and kept its session state. An
existing link is replaced only when its run belongs to the same task and agent
and finished before the stopped run started, which is the rule for accepted
results. A newer run, a reset, a conversation or any missing evidence leaves the
link unchanged. A task without a link then starts a new session on its next run.
The outcome is logged as `stopped run's task session`. If the provider later
confirms that the retained state is gone, the next run retires the stopped run's
controller state and starts a new session.
A rejected warm-session close retains its owner, even when no managed instruction
copy exists. Idle expiry, failed-turn release, and restart must not report that
owner as quiet or launch a replacement over it. The next retirement attempt uses
@@ -20,6 +20,7 @@ const ALLOWED: ReadonlyArray<readonly [file: string, line: string, reason: strin
["services/recovery/service.ts", "terminal.runTerminalState !== \"succeeded\" ||", "only yielded/blocked results reach here; an accepted outcome only exists for done"],
["services/recovery/service.ts", "terminal.turnTerminalState !== \"completed\" ||", "only yielded/blocked results reach here; an accepted outcome only exists for done"],
["services/native-runtime/native-task-session-publication.ts", "return snapshot.goal == null && snapshot.semanticResult != null && snapshot.terminal?.runTerminalState === \"succeeded\"", "runner session snapshot; a turn that failed is not published for resume, so the next turn starts from saved context"],
["services/native-runtime/native-stopped-session-publication.ts", "|| record(snapshot.terminal).runTerminalState !== \"cancelled\" || snapshot.activeTurnId !== null", "runner session checkpoint, not a stored result; a stopped run has none"],
["services/native-runtime/status-decision-committer.ts", "terminal.schema !== \"paperclip.prp.terminal.v1\" || terminal.runTerminalState !== \"succeeded\" || terminal.turnTerminalState !== \"completed\" || terminal.reportedWorkDisposition !== \"yielded\") throw new NativeStatusRaceError();", "only yielded/blocked results reach here; an accepted outcome only exists for done"],
["services/native-runtime/status-decision-committer.ts", "terminal.runTerminalState !== \"succeeded\" || terminal.turnTerminalState !== \"completed\" ||", "reads the effective outcome (accepted outcome applied)"],
["services/native-runtime/native-board-response-wait.ts", "terminal.runTerminalState !== \"succeeded\" ||", "only yielded/blocked results reach here; an accepted outcome only exists for done"],
+9
View File
@@ -26,6 +26,8 @@ import { nativeRecoveryNoticeWork } from "./native-runtime/native-recovery-notic
import { nativeRunProjectionWork } from "./native-runtime/native-run-projection-work.js";
import { nativeResultCommitWork } from "./native-runtime/native-result-commit-work.js";
import { nativeStatusReassessmentWork } from "./native-runtime/native-status-reassessment-work.js";
import { publishStoppedNativeSession } from "./native-runtime/native-stopped-session-publication.js";
import type { NativeTaskSessionPublicationContext } from "./native-runtime/native-task-session-publication.js";
import { registerNativeReviewResponseWork } from "./native-runtime/native-review-response-work.js";
import { registerNativeResponsePresentationWork } from "./native-runtime/native-response-presentation-work.js";
import { registerNativePendingEffectWork } from "./native-runtime/native-pending-effect-work.js";
@@ -2192,6 +2194,7 @@ export function heartbeatService(
return true;
};
let nativeWorkspaceFinalizeScheduled = false;
let taskSessionPublication: NativeTaskSessionPublicationContext | undefined;
let nativeWorkspaceSync: Awaited<
ReturnType<typeof prepareNativeWorkspaceSync>
> = null;
@@ -3840,6 +3843,7 @@ export function heartbeatService(
effects: {
onUsageCaptureReady: (value) => { persistUsageCaptureFailure = value; },
onNativeDispatchStarted: () => { nativeDispatchStarted = true; },
onTaskSessionPublicationReady: (value) => { taskSessionPublication = value; },
onLegacyAdapterEntered: () => {
legacyAdapterEntered = true;
// A direct adapter reports its own progress from here on.
@@ -4272,6 +4276,11 @@ export function heartbeatService(
providerResourceDisposition: providerResourceDispositionForRun,
nativeLifecycleTelemetry: nativeLifecycleTelemetryForRun,
}));
if (taskSessionPublication && latestRun?.status === "cancelled" && latestRun.runtimeMode === "native") {
await publishStoppedNativeSession(db, run.id, taskSessionPublication)
.then(outcome => logger.info({ runId: run.id, outcome }, "stopped run's task session"))
.catch(err => logger.warn({ err, runId: run.id }, "could not keep a stopped run's task session"));
}
crashPoint("environment.lease.after_release_before_runtime_services");
await releaseRuntimeServicesForRun(run.id).catch(() => undefined);
caseHandoffCleanupSettled = true;
@@ -129,7 +129,7 @@ describe.skipIf(!support.supported)("heartbeat runtime execution boundary", () =
envOrchestrator: { releaseForRun: vi.fn() }, cancelRunInternal: vi.fn(), enqueueWakeup: vi.fn(),
persistRunProcessMetadata: vi.fn(), recordCurrentHeartbeatRunRuntimeProgress: vi.fn(), dispatchPendingNativeStatusWakeups: vi.fn(),
},
effects: { onUsageCaptureReady: vi.fn(), onNativeDispatchStarted: vi.fn(), onLegacyAdapterEntered: vi.fn(), onWorkspaceRestoreFailure: vi.fn(), onProviderResourceDisposition: vi.fn(), onNativeWorkspaceFinalizeScheduled: vi.fn(), onNativeSessionResumeScheduled: vi.fn(), onNativeOwnershipHeld: vi.fn() },
effects: { onUsageCaptureReady: vi.fn(), onNativeDispatchStarted: vi.fn(), onTaskSessionPublicationReady: vi.fn(), onLegacyAdapterEntered: vi.fn(), onWorkspaceRestoreFailure: vi.fn(), onProviderResourceDisposition: vi.fn(), onNativeWorkspaceFinalizeScheduled: vi.fn(), onNativeSessionResumeScheduled: vi.fn(), onNativeOwnershipHeld: vi.fn() },
};
return { input, adapter, run };
}
@@ -579,6 +579,8 @@ describe.skipIf(!support.supported)("heartbeat runtime execution boundary", () =
expect(await executeHeartbeatRuntime(db, input)).toMatchObject({ dispatched: true, adapterResult: { usage: { inputTokens: 7, outputTokens: 3 }, usageComplete: true } });
expect(adapter.execute).not.toHaveBeenCalled();
expect(input.effects.onNativeDispatchStarted).toHaveBeenCalledOnce();
expect(input.effects.onTaskSessionPublicationReady).toHaveBeenCalledExactlyOnceWith(
vi.mocked(executePaperclipNativeSession).mock.lastCall![0].taskSessionPublication);
expect(await read(run.id)).toMatchObject({ status: "running", usageJson: { inputTokens: 7, outputTokens: 3, accountingReceiptReady: true } });
expect(await finalizations()).toMatchObject([{ status: "succeeded" }]);
expectCleanup(input);
@@ -1,3 +1,4 @@
import type { NativeTaskSessionPublicationContext } from "../native-runtime/native-task-session-publication.js";
import { readClaimedNativeStopRecovery } from "../native-runtime/native-cancellation-request.js";
import { readContextCompactionRequest } from "../context-compaction.js";
import { remoteWorkspaceFailureCause } from "../remote-workspace-transport.js";
@@ -209,6 +210,7 @@ export interface HeartbeatRuntimeExecutionInput {
effects: {
onUsageCaptureReady: (persistFailure: () => Promise<void>) => void;
onNativeDispatchStarted: () => void;
onTaskSessionPublicationReady: (context: NativeTaskSessionPublicationContext | undefined) => void;
onLegacyAdapterEntered: () => void;
onWorkspaceRestoreFailure: (evidence: Record<string, unknown>) => void;
onProviderResourceDisposition: (disposition: ProviderResourceDisposition) => void;
@@ -618,6 +620,7 @@ export async function executeHeartbeatRuntime(db: Db, input: HeartbeatRuntimeExe
),
}
: undefined;
input.effects.onTaskSessionPublicationReady(taskSessionPublication);
const nativeDispatchAtMs = Date.now();
const runCreatedAtMs = run.createdAt.getTime();
const runStartedAtMs = (run.startedAt ?? run.createdAt).getTime();
@@ -20083,6 +20083,9 @@ describe("runnerd provider runtime wiring", () => {
"stopped-availability-omitted",
"stop-unconfirmed",
"stopped-lease-unreleased",
"run-stopped-state-unavailable",
"run-stopped-unacknowledged",
"run-stopped-other-failure",
] as const)(
"handles unconfirmed plugin checkpoint status on replacement lease: %s",
async mode => {
@@ -20112,16 +20115,27 @@ describe("runnerd provider runtime wiring", () => {
const ordinarySelect = db.select.bind(db);
const { currentNativeControllerIdentity } = await import("./native-restart-recovery.js");
const controller = await currentNativeControllerIdentity();
const runStopped = mode.startsWith("run-stopped");
const committedPrior = {
run: {
id: first.binding.runId, companyId: first.binding.companyId, agentId: first.binding.agentId,
nativeIssueId: first.binding.issueId, runtimeMode: "native", status: "succeeded",
nativeIssueId: first.binding.issueId, runtimeMode: "native", status: runStopped ? "cancelled" : "succeeded",
resultJson: runStopped ? { nativeCancellation: {
schema: "paperclip.native-cancellation.v1", runId: first.binding.runId, companyId: first.binding.companyId,
issueId: first.binding.issueId, scope: "run", reasonCode: "cancellation_run_only", dispatched: true,
dispatchState: mode === "run-stopped-unacknowledged" ? "requested" : "acknowledged",
intentAuditId: "intent", acknowledgementAuditId: "acknowledgement",
} } : null,
runnerProfileJson: { nativeExecutionInput: first },
processPid: null, processGroupId: null, processStartedAt: null,
},
owner: {
runId: first.binding.runId, companyId: first.binding.companyId, issueId: first.binding.issueId,
phase: "committed", resultId: "result-1", leaseOwner: null, recoveryState: null,
...(runStopped
? { phase: "terminal_failure", resultId: null,
failureCode: mode === "run-stopped-other-failure" ? "provider_failed" : "native_retry_cancelled" }
: { phase: "committed", resultId: "result-1", failureCode: null }),
leaseOwner: null, recoveryState: null,
controllerPid: controller.pid, controllerProcessStartedAt: controller.processStartedAt,
controllerBootId: controller.bootId,
},
@@ -20150,7 +20164,7 @@ describe("runnerd provider runtime wiring", () => {
};
db.select = ((fields?: Record<string, unknown>) => {
if (fields?.status === heartbeatRuns.status && fields?.runnerProfileJson === heartbeatRuns.runnerProfileJson) {
return priorNativeRunDb(first, "succeeded").select(fields as never);
return priorNativeRunDb(first, committedPrior.run.status).select(fields as never);
}
if (fields && "run" in fields && "owner" in fields) {
return {
@@ -20202,10 +20216,14 @@ describe("runnerd provider runtime wiring", () => {
sandboxLeaseAcquisition: { outcome: "replacement", providerLeaseId: "replacement-task" },
} as never,
};
if (mode === "stopped-state-unavailable") {
if (mode === "stopped-state-unavailable" || mode === "run-stopped-state-unavailable") {
await expect(createRunnerdBackend(launch)).resolves.toBeDefined();
expect(state.createBackend).toHaveBeenCalledOnce();
expect(existsSync(join(scoped, "continuity-breaks"))).toBe(true);
} else if (runStopped) {
await expect(createRunnerdBackend(launch)).rejects.toThrow("retirement_refused=owner_terminal_failure");
expect(state.createBackend).not.toHaveBeenCalled();
expect(existsSync(join(scoped, "continuity-breaks"))).toBe(false);
} else if (mode === "stopped-lease-unreleased") {
await expect(createRunnerdBackend(launch)).rejects.toThrow("retirement_refused=prior_lease_active");
expect(state.createBackend).not.toHaveBeenCalled();
@@ -6319,8 +6319,11 @@ async function inspectFinishedPerTurnRunnerdOwner(input: {
}
if (!prior || prior.run.runtimeMode !== "native") return refuse("owner_missing");
if (!TERMINAL_HEARTBEAT_RUN_STATUSES.has(prior.run.status)) return refuse("owner_run_not_terminal");
if (prior.owner.phase !== "committed") return refuse(`owner_${retirementReasonName("ownerPhase", prior.owner.phase)}`);
if (!prior.owner.resultId) return refuse("owner_result_missing");
const stoppedOwner = confirmedGonePluginTask && prior.run.status === "cancelled"
&& prior.owner.phase === "terminal_failure" && prior.owner.failureCode === "native_retry_cancelled"
&& !prior.owner.resultId && hasAcknowledgedNativeRunStopReceipt(prior.run);
if (!stoppedOwner && prior.owner.phase !== "committed") return refuse(`owner_${retirementReasonName("ownerPhase", prior.owner.phase)}`);
if (!stoppedOwner && !prior.owner.resultId) return refuse("owner_result_missing");
if (prior.owner.leaseOwner) return refuse("owner_lease_held");
if (prior.owner.recoveryState) return refuse(`owner_recovery_${retirementReasonName("recoveryState", prior.owner.recoveryState)}`);
// A durable controller is fenced by its released database lease; a legacy
@@ -0,0 +1,213 @@
import { randomUUID } from "node:crypto";
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import { eq } from "drizzle-orm";
import { agents, agentTaskSessions, companies, createDb, environmentLeases, environments, heartbeatRunEvents,
heartbeatRuns, issues, nativeRunFinalizations } from "@paperclipai/db";
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../../__tests__/helpers/embedded-postgres.js";
import { uniqueIssuePrefix } from "../../__tests__/helpers/issue-prefix.js";
const journal = vi.hoisted(() => ({ load: vi.fn() }));
vi.mock("./native-runner-checkpoint.js", async original => ({
...await original<typeof import("./native-runner-checkpoint.js")>(), loadNativeRunnerCheckpoint: journal.load,
}));
const { publishStoppedNativeSession } = await import("./native-stopped-session-publication.js");
const support = await getEmbeddedPostgresTestSupport();
(support.supported ? describe : describe.skip)("stopped run's task session", () => {
let temporary: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
let db: ReturnType<typeof createDb>;
beforeAll(async () => {
temporary = await startEmbeddedPostgresTestDatabase("paperclip-stopped-session-");
db = createDb(temporary.connectionString);
}, 60_000);
afterAll(async () => {
await db?.$client.end({ timeout: 1 });
await temporary?.cleanup();
});
beforeEach(() => { journal.load.mockReset(); });
async function fixture() {
const companyId = randomUUID(), agentId = randomUUID(), issueId = randomUUID(), runId = randomUUID();
const sessionId = randomUUID(), runner = randomUUID(), environmentId = randomUUID();
await db.insert(companies).values({ id: companyId, name: "Stopped session", issuePrefix: uniqueIssuePrefix("SS") });
await db.insert(agents).values({ id: agentId, companyId, name: "Agent", adapterType: "paperclip_runner" });
await db.insert(issues).values({ id: issueId, companyId, title: "Task", status: "in_progress", assigneeAgentId: agentId });
const nativeCancellation = { schema: "paperclip.native-cancellation.v1", intentId: "intent", intentAuditId: "intent-audit",
acknowledgementAuditId: "acknowledgement-audit", companyId, runId, issueId, scope: "run",
reasonCode: "cancellation_run_only", dispatchState: "acknowledged", dispatched: true };
const sessionCheckpoint = { backendKind: "test", sessionId, providerSessionId: "provider-thread", activeTurnId: null,
identity: { companyId, agentId, issueId, runId, sessionId }, pendingRuntimeRequests: [], goal: null, semanticResult: null,
terminal: { schema: "paperclip.prp.terminal.v1", turnTerminalState: "cancelled", runTerminalState: "cancelled",
reportedWorkDisposition: "yielded" } };
await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, status: "cancelled", runtimeMode: "native",
nativeIssueId: issueId, issueId, nativeSessionId: sessionId, runnerInstanceId: runner,
startedAt: new Date("2026-01-01T00:10:00Z"), finishedAt: new Date("2026-01-01T00:20:00Z"), resultJson: { nativeCancellation }, runnerProfileJson: { sessionCheckpoint } });
await db.insert(heartbeatRunEvents).values({ companyId, agentId, runId, seq: 1, eventType: "turn.accepted" });
await db.insert(nativeRunFinalizations).values({ runId, companyId, issueId, phase: "terminal_failure",
failureCode: "native_retry_cancelled", attempt: 1 });
await db.insert(environments).values({ id: environmentId, name: `Environment ${environmentId}`, driver: "plugin" });
const metadata = { runnerTaskLease: true, runnerTaskExecutionStopped: true, runnerTaskSessionRetained: true,
runnerTaskIdentity: { runnerId: runner, leaseId: "lease", runId, sessionId } };
const [lease] = await db.insert(environmentLeases).values({ companyId, environmentId, issueId, heartbeatRunId: runId,
status: "released", cleanupStatus: "success", provider: "plugin", providerLeaseId: "task", metadata }).returning();
await db.insert(agentTaskSessions).values({ companyId, agentId, adapterType: "paperclip_runner", taskKey: issueId,
goalSourceId: `${runner}:${runId}`, goalSourceCursor: 4 });
const envelope = { runId, normalizedSessionId: sessionId };
const control: Record<string, unknown> = { identity: { runId, normalizedSessionId: sessionId, runnerInstanceId: runner },
commands: [{ type: "turn.start", status: "completed", controllerSeq: 1 }, { type: "runner.suspend", status: "completed", controllerSeq: 2 }],
committedEvents: [{ eventType: "turn.cancelled", envelope }, { eventType: "run.terminal", envelope }] };
journal.load.mockImplementation(async () => ({ records: new Map([
["header", JSON.stringify({ state: { identity: control.identity } })],
["cursor", "{}"],
...(control.commands as unknown[]).map((command, index) => [`command:${index + 1}`, JSON.stringify(command)] as const),
...(control.committedEvents as unknown[]).map((event, index) => [`event:${index + 1}`, JSON.stringify(event)] as const),
]) }));
const context = { taskKey: issueId, adapterType: "paperclip_runner",
sessionParamsJson: { cwd: "/workspace", paperclipSessionConfigFingerprint: "prepared" } };
const read = async () => (await db.select().from(agentTaskSessions).where(eq(agentTaskSessions.taskKey, issueId)))[0];
const setRun = (values: Partial<typeof heartbeatRuns.$inferInsert>) =>
db.update(heartbeatRuns).set(values).where(eq(heartbeatRuns.id, runId));
const setLease = (values: Partial<typeof environmentLeases.$inferInsert>) =>
db.update(environmentLeases).set(values).where(eq(environmentLeases.id, lease!.id));
return { companyId, agentId, issueId, runId, sessionId, runner, environmentId, nativeCancellation, sessionCheckpoint,
metadata, control, context, read, setRun, setLease, publish: () => publishStoppedNativeSession(db, runId, context) };
}
type Fixture = Awaited<ReturnType<typeof fixture>>;
const linkEarlierRun = async (f: Fixture, sessionId: string, run: Partial<typeof heartbeatRuns.$inferInsert> = {}) => {
const id = randomUUID();
await db.insert(heartbeatRuns).values({ id, companyId: f.companyId, agentId: f.agentId, status: "succeeded", issueId: f.issueId,
startedAt: new Date("2026-01-01T00:00:00Z"), finishedAt: new Date("2026-01-01T00:05:00Z"), ...run });
await db.update(agentTaskSessions).set({ lastRunId: id, sessionDisplayId: "earlier-thread",
sessionParamsJson: { sessionId, paperclipSessionConfigFingerprint: "earlier" } }).where(eq(agentTaskSessions.taskKey, f.issueId));
};
const newerRun = async (f: Fixture) => {
const id = randomUUID();
await db.insert(heartbeatRuns).values({ id, companyId: f.companyId, agentId: f.agentId, status: "queued", issueId: f.issueId });
return id;
};
it("links the session with the prepared metadata, so the next run can resume it", async () => {
const f = await fixture();
expect(await f.publish()).toBe("published");
expect(await f.read()).toMatchObject({ lastRunId: f.runId, sessionDisplayId: "provider-thread", lastError: null,
sessionParamsJson: { ...f.context.sessionParamsJson, sessionId: f.sessionId } });
expect(await f.publish()).toBe("published");
});
it.each([
["the same session", (f: Fixture) => f.sessionId],
["another session", () => randomUUID()],
])("replaces an earlier run's link to %s", async (_name, linkedSession) => {
const f = await fixture();
await linkEarlierRun(f, linkedSession(f));
expect(await f.publish()).toBe("published");
expect(await f.read()).toMatchObject({ lastRunId: f.runId, sessionDisplayId: "provider-thread",
sessionParamsJson: { ...f.context.sessionParamsJson, sessionId: f.sessionId } });
});
it("replaces an earlier run that finished when this run started", async () => {
const f = await fixture();
await linkEarlierRun(f, randomUUID(), { finishedAt: new Date("2026-01-01T00:10:00Z") });
expect(await f.publish()).toBe("published");
});
it("accepts the provider's own turn start", async () => {
const f = await fixture();
await db.update(heartbeatRunEvents).set({ eventType: "turn.started" }).where(eq(heartbeatRunEvents.runId, f.runId));
expect(await f.publish()).toBe("published");
});
it("accepts the issue's execution lock when this run still holds it", async () => {
const f = await fixture();
await db.update(issues).set({ executionRunId: f.runId }).where(eq(issues.id, f.issueId));
expect(await f.publish()).toBe("published");
});
const refusals: Array<[string, string, (f: Fixture) => Promise<unknown> | void]> = [
["the Stop was never acknowledged", "stop_unproven", f =>
f.setRun({ resultJson: { nativeCancellation: { ...f.nativeCancellation, dispatchState: "pending" } } })],
["the Stop did not reach the provider", "stop_unproven", f =>
f.setRun({ resultJson: { nativeCancellation: { ...f.nativeCancellation, dispatched: false } } })],
["the run failed instead of stopping", "stop_unproven", f => f.setRun({ status: "failed" })],
["the coordinator did not settle as a Stop", "stop_unproven", f => db.update(nativeRunFinalizations)
.set({ phase: "retryable_failure", failureCode: "native_session_interrupted" }).where(eq(nativeRunFinalizations.runId, f.runId))],
["recovery still owns the run", "stop_unproven", f => db.update(nativeRunFinalizations)
.set({ leaseOwner: "owner", leaseExpiresAt: new Date(Date.now() + 60_000) }).where(eq(nativeRunFinalizations.runId, f.runId))],
["no checkpoint was saved", "turn_unsettled", f => f.setRun({ runnerProfileJson: {} })],
["the checkpoint belongs to another session", "turn_unsettled", f => f.setRun({ nativeSessionId: randomUUID() })],
["the turn never ended", "turn_unsettled", f => f.setRun({ runnerProfileJson: { sessionCheckpoint:
{ ...f.sessionCheckpoint, activeTurnId: "turn", terminal: null } } })],
["the turn waits for background work", "turn_unsettled", f => f.setRun({ runnerProfileJson: { sessionCheckpoint:
{ ...f.sessionCheckpoint, awaitingProviderTurn: true, terminal: null } } })],
["the turn failed", "turn_unsettled", f => f.setRun({ runnerProfileJson: { sessionCheckpoint:
{ ...f.sessionCheckpoint, terminal: { ...f.sessionCheckpoint.terminal, runTerminalState: "failed" } } } })],
["a request is still waiting for an answer", "turn_unsettled", f => f.setRun({ runnerProfileJson: { sessionCheckpoint:
{ ...f.sessionCheckpoint, pendingRuntimeRequests: [{ requestId: "request" }] } } })],
["a goal is recorded", "turn_unsettled", f => f.setRun({ runnerProfileJson: { sessionCheckpoint:
{ ...f.sessionCheckpoint, goal: { status: "active" } } } })],
["the provider never accepted a turn", "turn_not_started", f => db.update(heartbeatRunEvents)
.set({ eventType: "turn.submitted" }).where(eq(heartbeatRunEvents.runId, f.runId))],
["only another run's turn was accepted", "turn_not_started", async f => {
const runId = await newerRun(f);
await db.update(heartbeatRunEvents).set({ runId }).where(eq(heartbeatRunEvents.runId, f.runId));
}],
["the journal is missing", "journal_unsettled", () => { journal.load.mockResolvedValue(null); }],
["the journal cannot be read", "journal_unsettled", () => { journal.load.mockRejectedValue(new Error("retired")); }],
["the journal names another run", "journal_unsettled", f => { (f.control.identity as Record<string, unknown>).runId = randomUUID(); }],
["the journal has no terminal", "journal_unsettled", f => { (f.control.committedEvents as unknown[]).pop(); }],
["a command is still pending", "journal_unsettled", f => { (f.control.commands as Array<Record<string, unknown>>)[1]!.status = "pending"; }],
["a command's outcome is unknown", "journal_unsettled", f => {
(f.control.commands as Array<Record<string, unknown>>)[0]!.status = "indeterminate"; }],
["a tool call started after the terminal", "journal_unsettled", f => {
(f.control.committedEvents as unknown[]).push({ eventType: "tool.execution.started",
envelope: { runId: f.runId, normalizedSessionId: f.sessionId } }); }],
["the provider kept no session state", "session_not_retained", f =>
f.setLease({ metadata: { ...f.metadata, runnerTaskSessionRetained: false } })],
["the task is not known to have stopped", "session_not_retained", f =>
f.setLease({ metadata: { ...f.metadata, runnerTaskExecutionStopped: false } })],
["the retained state names another session", "session_not_retained", f =>
f.setLease({ metadata: { ...f.metadata, runnerTaskIdentity: { ...f.metadata.runnerTaskIdentity, sessionId: randomUUID() } } })],
["the lease is not a Runner task", "session_not_retained", f =>
f.setLease({ metadata: { ...f.metadata, runnerTaskLease: false } })],
["lease cleanup is still pending", "session_not_retained", f =>
f.setLease({ status: "pending_cleanup", cleanupStatus: "failed" })],
["the run used a second lease", "session_not_retained", f => db.insert(environmentLeases).values({ companyId: f.companyId,
environmentId: f.environmentId, issueId: f.issueId, heartbeatRunId: f.runId, status: "released", cleanupStatus: "success",
provider: "plugin", providerLeaseId: "other-task", metadata: f.metadata })],
["a newer run holds the task", "superseded", async f => db.update(issues).set({ executionRunId: await newerRun(f) })
.where(eq(issues.id, f.issueId))],
["a newer run wrote the session row", "superseded", async f => db.update(agentTaskSessions)
.set({ goalSourceId: `${f.runner}:${await newerRun(f)}` }).where(eq(agentTaskSessions.taskKey, f.issueId))],
["the session was reset", "session_row_missing", f => db.delete(agentTaskSessions).where(eq(agentTaskSessions.taskKey, f.issueId))],
["a later run wrote the link", "superseded", f => linkEarlierRun(f, randomUUID(), {
startedAt: new Date("2026-01-01T00:21:00Z"), finishedAt: new Date("2026-01-01T00:22:00Z") })],
["the linked run has not finished", "superseded", f => linkEarlierRun(f, randomUUID(), { status: "running", finishedAt: null })],
["the linked run belongs to another task", "superseded", async f => {
const issueId = randomUUID();
await db.insert(issues).values({ id: issueId, companyId: f.companyId, title: "Other task", status: "todo" });
await linkEarlierRun(f, randomUUID(), { issueId });
}],
["the linked run belongs to another agent", "superseded", async f => {
const agentId = randomUUID();
await db.insert(agents).values({ id: agentId, companyId: f.companyId, name: "Other agent", adapterType: "paperclip_runner" });
await linkEarlierRun(f, randomUUID(), { agentId });
}],
["this run has no start time", "superseded", async f => {
await linkEarlierRun(f, randomUUID());
await f.setRun({ startedAt: null });
}],
["the task is a conversation", "unsupported_task", f => db.update(issues).set({ conversationAgentId: f.agentId,
conversationUserId: "stopped-session-user", conversationState: "active" }).where(eq(issues.id, f.issueId))],
["the run's content was deleted", "unsupported_task", f => f.setRun({
resultJson: { nativeCancellation: f.nativeCancellation, contentDeletedAt: new Date(0).toISOString() } })],
];
it.each(refusals)("leaves the task session unchanged when %s", async (_name, outcome, change) => {
const f = await fixture();
await change(f);
const before = await f.read();
expect(await f.publish()).toBe(outcome);
expect(await f.read()).toEqual(before);
});
});
@@ -0,0 +1,96 @@
import { and, eq } from "drizzle-orm";
import { agentTaskSessions, environmentLeases, heartbeatRuns, issues, nativeRunFinalizations, type Db } from "@paperclipai/db";
import { hasAcknowledgedNativeRunStopReceipt } from "../acknowledged-native-stop.js";
import { RUN_CONTENT_DELETED_MARKER } from "../tool-access/connections/run-session-reset.js";
import { loadNativeRunnerCheckpoint } from "./native-runner-checkpoint.js";
import { taskSessionLinkReplaceable, type NativeTaskSessionPublicationContext } from "./native-task-session-publication.js";
import { readProviderAttemptOutcome } from "./provider-attempt-outcome.js";
import { isSettledRemoteWarmControlState } from "./remote-warm-session-recovery.js";
export type StoppedSessionOutcome = "published" | "stop_unproven" | "turn_unsettled" | "turn_not_started"
| "session_not_retained" | "journal_unsettled" | "unsupported_task" | "superseded" | "session_row_missing";
type Run = typeof heartbeatRuns.$inferSelect;
type Lease = typeof environmentLeases.$inferSelect;
function record(value: unknown): Record<string, unknown> {
return value !== null && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : {};
}
function settledSnapshot(run: Run): { sessionId: string; displayId: string } | null {
const snapshot = record(run.runnerProfileJson?.sessionCheckpoint), identity = record(snapshot.identity);
const displayId = snapshot.providerSessionId ?? snapshot.sessionId;
if (identity.companyId !== run.companyId || identity.agentId !== run.agentId || identity.issueId !== run.nativeIssueId
|| identity.runId !== run.id || typeof identity.sessionId !== "string" || identity.sessionId !== run.nativeSessionId
|| typeof displayId !== "string" || !displayId
|| record(snapshot.terminal).runTerminalState !== "cancelled" || snapshot.activeTurnId !== null
|| snapshot.awaitingProviderTurn === true || snapshot.goal != null
|| (Array.isArray(snapshot.pendingRuntimeRequests) && snapshot.pendingRuntimeRequests.length > 0)) return null;
return { sessionId: identity.sessionId, displayId };
}
function sessionRetained(run: Run, leases: Lease[]): boolean {
if (leases.length !== 1) return false;
const [lease] = leases, metadata = record(lease!.metadata), identity = record(metadata.runnerTaskIdentity);
return lease!.status === "released" && lease!.cleanupStatus === "success" && metadata.runnerTaskLease === true
&& metadata.runnerTaskExecutionStopped === true && metadata.runnerTaskSessionRetained === true
&& identity.runId === run.id && identity.sessionId === run.nativeSessionId && identity.runnerId === run.runnerInstanceId;
}
async function journalSettled(db: Db, run: Run): Promise<boolean> {
const checkpoint = await loadNativeRunnerCheckpoint(db, { companyId: run.companyId, issueId: run.nativeIssueId!, runId: run.id })
.catch(() => null);
if (!checkpoint) return false;
const { records } = checkpoint, read = (key: string) => record(JSON.parse(records.get(key)!));
const keys = [...records.keys()], committedEvents: Record<string, unknown>[] = [];
for (const key of keys.filter(key => key.startsWith("event:")).reverse()) {
const event = read(key);
committedEvents.unshift(event);
if (event.eventType === "run.terminal") break;
}
const identity = record(record(read("header").state).identity);
const control = { identity, commands: keys.filter(key => key.startsWith("command:")).map(read), committedEvents };
return identity.runId === run.id && identity.normalizedSessionId === run.nativeSessionId
&& identity.runnerInstanceId === run.runnerInstanceId && isSettledRemoteWarmControlState(control, identity);
}
export async function publishStoppedNativeSession(db: Db, runId: string,
context: NativeTaskSessionPublicationContext): Promise<StoppedSessionOutcome> {
const [observed] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId)).limit(1);
if (!observed?.nativeIssueId || !hasAcknowledgedNativeRunStopReceipt(observed)) return "stop_unproven";
if (!settledSnapshot(observed)) return "turn_unsettled";
if (await readProviderAttemptOutcome(db, { runId, sinceSeq: 0 }) === "provider_not_started") return "turn_not_started";
if (!await journalSettled(db, observed)) return "journal_unsettled";
const companyId = observed.companyId, issueId = observed.nativeIssueId;
return db.transaction(async tx => {
const [coordinator] = await tx.select().from(nativeRunFinalizations).where(and(
eq(nativeRunFinalizations.runId, runId), eq(nativeRunFinalizations.companyId, companyId),
eq(nativeRunFinalizations.issueId, issueId))).for("update").limit(1);
const [issue] = await tx.select().from(issues).where(and(eq(issues.id, issueId), eq(issues.companyId, companyId)))
.for("no key update").limit(1);
const [run] = await tx.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.id, runId),
eq(heartbeatRuns.companyId, companyId))).for("update").limit(1);
if (!run || run.status !== "cancelled" || run.runtimeMode !== "native" || !hasAcknowledgedNativeRunStopReceipt(run)
|| coordinator?.phase !== "terminal_failure" || coordinator.failureCode !== "native_retry_cancelled"
|| coordinator.resultId || coordinator.leaseOwner || coordinator.recoveryState) return "stop_unproven";
const session = settledSnapshot(run);
if (!session) return "turn_unsettled";
if (!issue || issue.conversationAgentId || context.taskKey !== issueId
|| record(run.resultJson)[RUN_CONTENT_DELETED_MARKER]) return "unsupported_task";
if (issue.executionRunId && issue.executionRunId !== runId) return "superseded";
const leases = await tx.select().from(environmentLeases).where(and(
eq(environmentLeases.companyId, companyId), eq(environmentLeases.heartbeatRunId, runId)));
if (!sessionRetained(run, leases)) return "session_not_retained";
const [row] = await tx.select().from(agentTaskSessions).where(and(eq(agentTaskSessions.companyId, companyId),
eq(agentTaskSessions.agentId, run.agentId), eq(agentTaskSessions.adapterType, context.adapterType),
eq(agentTaskSessions.taskKey, context.taskKey))).for("update").limit(1);
if (!row) return "session_row_missing";
if (!row.goalSourceId?.endsWith(`:${runId}`) || !await taskSessionLinkReplaceable(tx, row.lastRunId, {
companyId, agentId: run.agentId, issueId, runId, startedAt: run.startedAt })) return "superseded";
await tx.update(agentTaskSessions).set({
sessionParamsJson: { ...context.sessionParamsJson, sessionId: session.sessionId },
sessionDisplayId: session.displayId, lastRunId: runId, lastError: null, updatedAt: new Date(),
}).where(eq(agentTaskSessions.id, row.id));
return "published";
});
}
@@ -67,6 +67,18 @@ export type NativeTaskSessionPublicationRun = Pick<typeof heartbeatRuns.$inferSe
export type NativeTaskSessionPublicationIssue = Pick<typeof issues.$inferSelect,
"id" | "companyId" | "executionRunId" | "conversationAgentId" | "conversationSessionGeneration">;
export async function taskSessionLinkReplaceable(tx: Transaction, lastRunId: string | null, owner: {
companyId: string; agentId: string; issueId: string; runId: string; startedAt: Date | null;
}): Promise<boolean> {
if (!lastRunId || lastRunId === owner.runId) return true;
const [prior] = await tx.select({ companyId: heartbeatRuns.companyId, agentId: heartbeatRuns.agentId,
issueId: heartbeatRuns.issueId, nativeIssueId: heartbeatRuns.nativeIssueId, finishedAt: heartbeatRuns.finishedAt,
}).from(heartbeatRuns).where(eq(heartbeatRuns.id, lastRunId)).limit(1);
return Boolean(prior && prior.companyId === owner.companyId && prior.agentId === owner.agentId
&& (prior.nativeIssueId ?? prior.issueId) === owner.issueId && prior.finishedAt && owner.startedAt
&& prior.finishedAt <= owner.startedAt);
}
/** Caller holds coordinator → issue NO KEY UPDATE → run. This helper owns only
* the task-row lock and UPDATE; never starts a transaction or creates a stub. */
export async function publishNativeTaskSessionInTransaction(tx: Transaction, input: {
@@ -128,14 +140,8 @@ export async function publishNativeTaskSessionInTransaction(tx: Transaction, inp
.filter((value): value is string => typeof value === "string" && value.length > 0)
.map(source => `${source}:${binding.runId}`);
if (!session.goalSourceId || !boundSources.includes(session.goalSourceId)) return receipt("suppressed_newer");
if (session.lastRunId && session.lastRunId !== binding.runId) {
const [prior] = await tx.select({ companyId: heartbeatRuns.companyId, agentId: heartbeatRuns.agentId,
issueId: heartbeatRuns.issueId, nativeIssueId: heartbeatRuns.nativeIssueId, finishedAt: heartbeatRuns.finishedAt,
}).from(heartbeatRuns).where(eq(heartbeatRuns.id, session.lastRunId)).limit(1);
if (!prior || prior.companyId !== binding.companyId || prior.agentId !== binding.agentId
|| (prior.nativeIssueId ?? prior.issueId) !== binding.issueId || !prior.finishedAt || !run.startedAt
|| prior.finishedAt > run.startedAt) return receipt("suppressed_newer");
}
if (!await taskSessionLinkReplaceable(tx, session.lastRunId, { companyId: binding.companyId, agentId: binding.agentId,
issueId: binding.issueId, runId: binding.runId, startedAt: run.startedAt })) return receipt("suppressed_newer");
await tx.update(agentTaskSessions).set({
sessionParamsJson: { ...context.sessionParamsJson, sessionId: snapshot.identity.sessionId },
sessionDisplayId: snapshot.providerSessionId ?? snapshot.sessionId, lastRunId: binding.runId,