Files
PaperClipAI/packages/paperclip-runner/src/backends/harness-driver-backend.test.ts
T
Nicky LeachandClaude Fable 5.2 ddfbbfff20 fix(runner): recover provider-started turns after a controller restart (#21612)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Core runs Claude Code through Paperclip Runner. Claude can start a
shell command in the background and end its turn. When the command
finishes, Claude Code starts a cycle of its own to continue.
> - The Runner can keep Claude while a background shell is running and
give the cycle of Claude to the controller as a turn that the provider
started. Core can wait for that turn. #21607 lets a caller ask the
transport for it.
> - A controller can restart at any time, for example at a deploy. A
wait can last 10 minutes and a provider-started turn can last longer, so
a restart during one of them is a normal event.
> - Tests with the real `paperclip-runnerd` showed that such a restart
failed the session. The checkpoint that Core had was the checkpoint of
the turn before, and the recovery of the driver refused or mislabelled
the turns that it did not know.
> - This pull request makes that restart safe. It changes no production
run, because no caller asks for provider-started turns before part 3.
> - The benefit is that part 3 can turn the behavior on without a failed
run at each deploy.

## Linked Issues or Issue Description

No public issue exists. The issue is described here.

#21456 turned the behavior on and had grown too large to review. It is
now three stacked pull requests:

1. #21607 (merged): the transport can ask the Runner for
provider-started turns. No caller asks.
2. **This pull request:** the recovery after a controller restart during
a wait or during a provider-started turn.
3. #21456: Core sets the option for native ACPX Claude runs. Only that
part changes what a production run does.

This is part 2. Its base branch is `master`. Refs #19912 (design),
#21456.

**What existing behavior does this improve?**

None in production. It makes a controller restart safe for a run that
asked for provider-started turns.

**Subsystem affected**

Paperclip Runner package: the consumer
(`src/native-session-runtime.ts`), the session backend
(`src/backends/harness-driver-backend.ts`), the driver
(`src/drivers/codex/`) and the transport (`src/live/`). Only for a run
that asked for provider-started turns.

**Current behavior**

- The consumer saves no checkpoint when a wait starts or when a
provider-started turn starts. During a wait and during a
provider-started turn, the checkpoint that Core has is the checkpoint
from the start of the turn before. It names that turn as active.
- A restart from that checkpoint fails: the driver has the old turn as
active, gets the events of a provider-started turn, and stops the
session with `turn_binding_mismatch`.
- The recovery of the driver adopts one turn that it does not know as a
disposition recovery turn, and refuses two or more. With two or more, it
closes the transport, and that stops the Runner and Claude.
- The Runner does not send again an event that the controller
acknowledged. If the start of a provider-started turn was acknowledged
before the restart, the new driver gets the other events of that turn
with no start.
- A turn that ends waiting for a provider-started turn sets the terminal
of the session, as a turn that ends the run does. After a restart, if
the provider-started turn already has its result when recovery
completes, the consumer finds a result and a terminal, settles the run,
and does not read the events of that turn. The start, the items, the
usage event and the terminal of that turn do not reach Core.
- The recovered driver reads notifications from its construction, and
`reconcile()` maps the terminal of the saved turn only after its reads.
If the saved checkpoint is still the checkpoint of the controller turn
and the start of the provider-started turn is already queued, the driver
judges that start too early and stops the session with
`turn_binding_mismatch`.
- A checkpoint that waits can also have a consumed disposition marker (a
recovery turn after an earlier restart ended waiting). The driver
restores that session as closed and reads no notifications, and the
consumer settles the run on the earlier terminal with no result.

**Proposed behavior**

- **Checkpoints.** The consumer saves a checkpoint when a wait starts
and when a provider-started turn starts, with the function that it
already uses for a governed wait. A checkpoint that fails stops the
turn, as for a governed wait.
- **A checkpoint as of the event that Core stored.** The driver gives
each event its sequence when it reads it from the provider, before the
consumer stores it. A snapshot that is taken later can be ahead of Core.
For these two checkpoints, the driver captures its snapshot when it has
handled the notification that made the event (the `turn.completed` that
waits, or the `turn.started` of the provider), with the sequence of that
event. The consumer asks for the snapshot as of the event that it has
just appended. The saved state and cursor are then those of an event
that Core has.
- **Session terminal.** A turn that ends waiting for a provider-started
turn does not set the terminal of the session (`HarnessNativeSession`).
The terminal of the session is the end of the run, and that turn does
not end the run. A checkpoint that is saved during a wait or during a
provider-started turn has no terminal, so a recovered session settles
only from the events that it reads, in order, to the terminal of the
turn that has the result.
- **Driver, a checkpoint that waits.** Recovery keeps the wait. It does
not adopt and does not refuse the turns after the last terminal that it
knows. The Runner sends again, in order, each event that was not
acknowledged, and the driver admits each provider-started turn from that
stream, as it does with no restart.
- **Driver, a checkpoint with an active turn.** `reconcile()` accepts
one turn in progress that comes after the saved active turn, when the
saved turn ended with the wait marker. It refuses each other unexpected
active turn as before, and it refuses this one too when the reconciled
turn settled a result.
- **Driver, a start that is queued before recovery reconciled the saved
turn.** A `turn/started` of the provider that arrives while the session
does not wait for one first waits until `reconcile()` has settled, and
is then judged as before. `reconcile()` judges the live state after its
reads; if the stream already settled the saved turn into a wait, it
accepts exactly one turn in progress after the last terminal turn and
does not adopt it. The driver admits that turn at its start.
- **A wait with a consumed disposition marker.** The driver keeps
reading notifications for a restored session that waits, as it does for
a wait with no restart. It still refuses a second controller-started
turn. The consumer does not take the consumed-marker shortcut for a
recovered snapshot that waits, so the wait is resumed.
- **Transport, the start comes first.** For each driver, the transport
gives the `turn/started` of a provider-started turn before each other
notification and before a tool call of that turn. If it did not give
that start to this driver, it builds it from the `turn.started` event in
its stored events. It does not do this for the turn that the recovered
driver already has as active (`resumeActiveTurnId`). It binds the events
and the tool call of a provider-started turn to that turn, not to the
turn that the Runner reports as active at the time of the recovery read.
- **Transport, which start owns an event.** The stored events can have
gaps: the window removes old events but keeps the latest of each anchor
type, and the controller checkpoint drops streamed deltas. The owner of
an event is the last stored `turn.started` before it, if it is a
provider start, and if the first turn terminal that is stored after that
start is not before the event and is the terminal of the same provider
turn (`providerTurnId`). If the first stored terminal after the start is
the terminal of a different turn, the end of the provider turn is not
known, and the transport builds no start.

**Reason and benefit**

- The checkpoint is the cause. With a true checkpoint, the two states of
a restart are states that recovery can handle: a wait, or an active
turn.
- The Runner already sends again each event that was not acknowledged.
Recovery uses that stream and does not build the turns again from a
read.
- The window removes a terminal only while a later terminal of the same
type is stored. Thus the first stored terminal after a start shows if a
terminal of that turn was removed. A rule that only ignores the gaps is
not safe: the Runner can make a `turn.failed` for a turn that did not
emit its start (`provider_turn_lost_on_restore`).

## What Changed

Production code: 113 lines added, 19 removed.

- `src/native-session-runtime.ts` (15 added, 4 removed): the two
checkpoints in `consumeTurn`, with the sequence of the appended event,
and the resumed wait with a consumed disposition marker.
- `src/drivers/codex/codex-session-state.ts` (24 added, 1 removed),
`codex-session-terminal.ts` (2 added), `codex-session-notifications.ts`
(2 added), `codex-harness-session.ts` (24 added, 7 removed),
`codex-app-server-driver-impl.ts` (4 added, 1 removed): the snapshot at
the event, and the recovery of the driver.
- `src/contracts/harness-driver.ts` and
`src/contracts/native-session-backend.ts` (1 added each): an optional
`boundarySnapshot` on a driver session, and an optional sequence in the
snapshot options. Other drivers do not implement it and are not changed.
- `src/backends/harness-driver-backend.ts` (7 added, 5 removed): the
session terminal, and the snapshot as of a sequence.
- `src/live/runnerd-codex-transport.ts` (15 added, 1 removed) and
`src/live/provider-turn-tool-order.ts` (18 added): the start-first rule
and the owner of an event.
- Tests: `src/live/runnerd-acpx-provider-turn.test.ts` (572 added, 5
removed),
`src/drivers/codex/codex-app-server-driver.provider-turn.test.ts` (348
added), `src/live/runnerd-codex-transport.test.ts` (137 added),
`src/control-plane/durable-prp-control-plane.test.ts` (84 added),
`src/live/provider-turn-tool-order.test.ts` (new, 61),
`src/native-session-runtime.provider-turn.test.ts` (92 added, 6
removed), `src/backends/harness-driver-backend.test.ts` (56 added).
- `runner/crates/runner-core/src/bin/fake-acpx-sidecar.rs` (test binary
only, 123 added, 14 removed): a delay before a provider-started turn, a
goal state at its terminal, a list of provider-started turns for one
session, a gap between them, a turn that stays open until the new
controller reads the snapshot, and a turn that starts after that read.
The modes that existed are not changed, and the fake reads its input on
one thread as before.

## State saved by the previous release

- No new persisted field. The driver session already has
`awaitingProviderTurn` (#21453).
- **More checkpoints:** one when a wait starts and one when a
provider-started turn starts. An ordinary turn saves the same number of
checkpoints as before (4 in the unit test, measured before and after).
- **No terminal in a checkpoint of a wait.** A checkpoint that is saved
during a wait or during a provider-started turn has `terminal: null`.
When a wait ends with no provider-started turn (the limit, a comment of
a person, or the Runner ends the run), the last checkpoint of the run
also has `terminal: null`; before, it had the terminal of the turn that
waited. One reader uses that field with no result: the text of a cleanup
failure (`nativeCheckpointRecordsCompletedTurn`), which then does not
say that the turn completed. In the tests with the real daemon (the
limit, the provider process lost, the sidecar exits), the run still ends
on the path of today (`native_finalization_missing`).
- **A checkpoint of the previous release** has no waiting state.
Recovery takes the path of today.
- **Rollback of the Runner package during a wait:** the previous code
reads the checkpoint, ignores `awaitingProviderTurn`, and takes its
recovery path of today.

## Verification

With nothing from part 3. The Rust checks and the build checks in the
first item were run before the last seven commits; these commits change
no Rust. The other items were run at the head of this branch
(`36d5e5e587`), or at an earlier commit of this branch for a suite whose
files the later commits do not change.

- Before the last seven commits: `pnpm run typecheck:typescript`, `pnpm
run build:typescript` and `node --test
test/acpx-sidecar-contract.test.mjs` (18 passed) in
`packages/paperclip-runner`; `node
scripts/verify-runner-vendor-dependencies.mjs` in `server`; `node --test
scripts/__tests__/runner-release-crate-cache.test.mjs`; `cargo fmt
--check`, `cargo build`, the 17 `acpx_*` suites (241 passed) and the
`acpx` unit tests (102 passed): all passed.
- `npx tsc --noEmit -p tsconfig.json` and `npx tsc --noEmit -p
tsconfig.test.json` in `packages/paperclip-runner`; `pnpm typecheck` in
`server`: all passed.
- `src/live/runnerd-acpx-provider-turn.test.ts`, 4 runs with the
production code of this head, 26 of 26 passed in each. The Core of these
tests follows the production append (`appendNativeSourceEvent`): it
stores an event that is out of order, keeps its contiguous cursor below
a gap, and reports a duplicate or a conflict for an event that it has.
It does not reject a gap in the sequence; production does not. The
restart cases, all with the real `paperclip-runnerd`:
- **From the checkpoint that the real consumer saved.** The first
`executeNativeSession` is fenced and detached as the server does for a
restart, and a second one recovers from the last checkpoint that the
first one saved. (a) Restart during the wait; the provider-started turn
starts after the new controller is attached. (b) Restart while a
provider-started turn is in progress. In each: the test asserts the
shape of that checkpoint, the run settles with the result of the
provider-started turn, each event is appended one time and in order, the
turn has one `turn.started` with `origin: "provider"`, and the session
closes with no error.
- **Without the two checkpoints, each of these cases fails:** the saved
checkpoint is the checkpoint of the turn before, and the second
controller fails with `turn_binding_mismatch` or with a replay conflict.
- **A slow `appendEvent`, with events that arrive behind the stored
event** (3 cases, each run 3 times with the fix and 3 times without it,
with the same result in each run). R7: the append of the
`turn.completed` that waits is slow, and the provider-started turn
starts behind it. With the snapshot at the event, the checkpoint is the
waiting state at the sequence that Core has, and Core gets the
`turn.started` of the turn one time. Without it, the checkpoint names
the provider-started turn as active, the transport builds no start, and
Core never gets that `turn.started`. R8: the first controller answers
the `paperclip_finish` call while the append of the provider
`turn.started` is slow. With the snapshot at the event, the checkpoint
has no result and the run ends with `native_finalization_missing` (see
Risks). Without it, the checkpoint has a result that Core does not have,
and recovery stops with "session cannot start another turn". R6: the
append of the provider `turn.started` is slow and a delta is queued
behind it. With the snapshot at the event, the new controller continues
the sequence that Core has. Without it, the only difference is one
sequence number that Core never gets.
- **The start was acknowledged before the restart** (3 cases: one turn
open across the restart; two turns; a turn that waits for the answer to
its `paperclip_finish` call). The new driver gets the start of each turn
one time before its other events, the finish call is answered exactly
one time, and the session closes with no error.
- **The turn ran with no controller attached** (2 cases, with and with
no result) and **two turns in one outage** (2 cases): the turns arrive
in order after the recovery.
- **A provider-started turn that is active in the checkpoint** gets no
second start, and the next provider-started turn arrives after it.
- **The turn already has its result when recovery completes** (3 cases:
the turn made its `paperclip_finish` call with no controller attached;
the turn waited for the answer to that call at the restart; two turns
across the restart). The test asserts the exact list of events that Core
gets: each provider-started turn has one start, its usage item, its
message item and its terminal, and then `run.result.accepted` and
`run.terminal`. `completeRun` is called one time with the turn that has
the result. Before the change to the session terminal, the second
controller appended only `run.result.accepted` and `run.terminal` in
each of these cases.
- **The wait checkpoint is not saved, then a restart** (R10). The last
checkpoint is the checkpoint of the controller turn, Core has the
terminal of that turn, and the start of the provider-started turn is
queued. The run settles with the result of the provider-started turn,
Core has one `turn.started` for it, and the finish call is answered one
time. Without the wait in the driver, recovery stops with
`turn_binding_mismatch`.
- **An ordinary turn**, with no option. One that waits for the answer to
its finish call at a restart: Core gets its result, its terminal and the
run terminal one time. One whose checkpoint after `startTurn` is ahead
of Core at a restart (R9): the run settles, and Core does not have only
the one event that the first controller did not store. These cases pass
with and without this pull request.
- **No checkpoint with a terminal and no result** is saved by the two
controllers in the cases above.
- `src/live/provider-turn-tool-order.test.ts` and
`src/live/runnerd-codex-transport.test.ts`: 345 passed. The helper tests
cover a stored start with removed events after it, a dropped delta, the
terminal of the turn before and after the event, a terminal of a
different turn after a removed terminal, and a controller start. With no
option, with a different agent or provider, and for a turn that the
controller started, the notifications of the transport are the same as
before this pull request.
- `src/control-plane/durable-prp-control-plane.test.ts`: 230 passed.
Three new tests use the real commit path: a full window of 4,096 events
removes the events after a provider start and the start is found; the
window removes the `turn.failed` of a provider turn after a later
`turn.failed` with no start, and no start is found; a restored
checkpoint that dropped the deltas of the turn, and the start is found.
- `src/drivers/codex` and `src/backends/harness-driver-backend.test.ts`:
491 passed. The driver tests cover a provider start that is queued
before `recoverSession()` is called, the wait state with one turn in
progress at `reconcile()` (and the two cases that it must still refuse),
a restored wait with a consumed disposition marker (the provider turn is
admitted and `startTurn` is refused), the snapshot at the two events
(also after the driver moved on, and for a restart continuation that
ends waiting), one later turn in progress, one completed and a second in
progress, two completed with a result, and the cases that `reconcile()`
must still refuse. The backend tests cover the session terminal and the
snapshot as of a sequence.
- `src/native-session-runtime.provider-turn.test.ts` and
`src/native-session-runtime.test.ts`: 333 passed. Two new cases resume a
restored wait with a consumed disposition marker: the provider-started
turn arrives and settles the run, or the wait ends at its limit and the
run takes the path of today with no new turn.
- `server`: `native-session-executor.test.ts`,
`native-provider-turn-wait.test.ts` and
`native-runner-restart-recovery.integration.test.ts`: 1,743 passed, 21
skipped.
- Mutation checks, each made named tests fail: no checkpoint at the
start of a wait; no checkpoint at the start of a provider-started turn;
the consumer does not pass the sequence (R6, R7 and R8 fail: a hole in
the sequence, no `turn.started` in Core, a different failure); the
backend ignores the sequence; the driver has no snapshot at the event;
no start-first rule; no exclusion of the active turn of the recovered
driver; the turn binding only at the first delivery; the contiguous
sequence required again; no check of the first terminal after the start;
the adoption of later turns put back; no exception in `reconcile()`; no
check after the settlement in `reconcile()`; the terminal of the session
set again by a turn that ends waiting; no wait of the provider start for
`reconcile()`; no exception in `reconcile()` for a session that waits;
the pump deferred for a restored wait; the consumed-marker shortcut
taken for a snapshot that waits.

Not run: the full suite. CI supplies that coverage.

## Risks

- **No production effect.** Each change is behind the waiting state, a
provider `turn.started`, or the option of the transport. No caller sets
the option before part 3.
- **An event that the first controller received but Core did not store
is not sent again after a restart.** This is the same on `master` and is
not changed here. Only the terminal of a turn is built again. If the
lost event is the result of a provider-started turn (the first
controller answered the `paperclip_finish` call and stopped before Core
stored the proposal), the run ends on the path of today for a turn with
no result. R8 shows this. R9 shows the same loss for one event of an
ordinary turn.
- **A second `turn.started` for one provider-started turn can reach
Core.** This occurs if the restart comes after Core stored the start and
before the checkpoint of that start is saved (the time of one checkpoint
write). The last checkpoint then waits, and the transport builds the
start again for the new driver. Seen with the real daemon when the
checkpoint write is held; not in a committed test. The usage accounting
of the server uses the turn id as its key, so there is no second count,
but the second start resets the "restored" mark of that turn. The
transcript does not read `turn.started`.
- **The older checkpoints can also save a cursor that is ahead of Core**
(measured for the checkpoint after `startTurn` of an ordinary turn).
Production accepts the gap in the sequence that follows, so this is not
a failure there. It is on `master` and is not changed here.
- **When the terminal of a provider-started turn was removed from the
stored events,** the transport builds no start for an event of that
turn, and the session stops on that event, as before. This needs a later
terminal of the same type with no start of its own (a turn that was lost
while it started) and a full window.
- **The last checkpoint of a wait that ends with no provider-started
turn has no terminal,** as the section above says. The change is only in
a run that waits, and no run waits before part 3.
- **A wait with a consumed disposition marker has no test with the real
daemon.** The state needs two restarts in one run, and the test helper
does one. Unit tests of the driver and of the consumer cover it.
- **A provider start that waits for `reconcile()`** waits as long as the
reads of `reconcile()` take. Each read ends at the command deadline of
the Runner (30 seconds by default) or when the transport closes.
- **`item.delta` events across a restart are not asserted.** A streamed
delta that the first controller received is not sent again. The
completed items are asserted.
- **The driver keeps a maximum of 8 snapshots at events** and drops each
one when the consumer asks for it or for a later one. If the consumer is
more than 8 such events behind, the checkpoint uses the current
snapshot, as before this change.
- **A second provider-started turn that also ends during the same
outage** is not tested with the real daemon: the fake gives each
terminal the same goal revision, and the Runner then holds the second
terminal until a controller is attached. The end of the reconnect time
of the Runner is not tested here.

## Model Used

- Claude Fable 5.2 (`claude-fable-5-2`) in Claude Code planned the
change and the split, decided the designs, reviewed the diffs, and ran a
part of the verification again.
- Claude Opus 5.5 (`claude-opus-5-5`), as Claude Code subagents with
tool use (shell, file edits, local test runs), wrote the change and the
tests, reproduced the review findings with the real daemon, and verified
this slice alone.

## 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 Fable 5.2 <noreply@anthropic.com>
2026-11-14 12:51:52 -08:00

1313 lines
55 KiB
TypeScript

import { describe, expect, it, vi } from "vitest";
import type { HarnessDriver, HarnessSession, PersistedHarnessSession } from "../contracts/harness-driver.js";
import {
NativeRunnerSourceReconciliationRequiredError,
PROVIDER_ATTACH_REFUSED,
PROVIDER_SIDE_EFFECT_PENDING,
PROVIDER_STATE_INCOMPATIBLE,
runnerRecoveryFailureClass,
} from "../contracts/harness-driver.js";
import type { PrpEvent, PrpStructuredRunResult, PrpTerminalState } from "../protocol/replay-contract.js";
import { NativeSessionProtocolIntegrityError, type NativeSession } from "../contracts/native-session-backend.js";
import { HarnessDriverBackend } from "./harness-driver-backend.js";
const result: PrpStructuredRunResult = {
schema: "paperclip.run_result.v1",
reportedWorkDisposition: "done",
summary: "Backend adapter completed.",
completionClaim: {
contractRevision: "1",
objectiveSatisfied: true,
criteria: [{ criterionId: "objective", status: "satisfied", evidenceRefs: [] }],
remainingWork: [],
},
evidence: [],
verification: [{ commandOrCheck: "fake", status: "passed" }],
attentionRequests: [],
artifacts: [],
};
const providerIdentity = {
kind: "acpx" as const,
normalizedSessionId: "session-1",
acpxRecordId: "driver-1",
backendSessionId: "backend-1",
agentSessionId: "provider-1",
profileDigest: "sha256:profile",
workspaceDigest: "sha256:workspace",
requestedModel: "claude-sonnet-4-20250514",
effectiveModel: "claude-sonnet-4-20250514",
providerLifetimeFenceCandidates: [60_001, 60_002, 60_003] as const,
};
function prpEvent(sourceSeq: number, eventType: PrpEvent["eventType"], payload: Record<string, unknown>): PrpEvent {
return {
schema: "paperclip.prp.event.v1",
sourceEventId: `fake:${sourceSeq}`,
sourceSeq,
sourceInstanceId: "fake",
sourceKind: "runner",
runId: "run-1",
normalizedSessionId: "session-1",
turnId: "turn-1",
eventType,
schemaVersion: 1,
priority: 0,
emittedAt: `2026-08-09T00:00:0${sourceSeq}.000Z`,
payload,
};
}
const runtimeResolutions: unknown[] = [];
function cancelSession(session: NativeSession, input: Parameters<NonNullable<NativeSession["cancel"]>>[0]) {
if (!session.cancel) throw new Error("backend session does not support cancellation");
return session.cancel(input);
}
class FakeHarnessSession implements HarnessSession {
ids(): ReturnType<HarnessSession["ids"]> { return { driverSessionId: "driver-1", providerSessionId: "provider-1" }; }
async *events() {
yield prpEvent(1, "run.result.proposed", result);
yield prpEvent(2, "turn.completed", { status: "completed" });
}
async startTurn() { return { turnId: "turn-1" }; }
async resolveRuntimeRequest(input: unknown) {
runtimeResolutions.push(structuredClone(input));
}
async snapshot(): Promise<PersistedHarnessSession> {
return {
driverKind: "fake",
driverSessionId: "driver-1",
providerSessionId: "provider-1",
providerIdentity,
providerRecoveryPolicy: "allow_replacement_after_governed_wait",
semanticResult: { result, fingerprint: "fingerprint", turnId: "turn-1" },
lastSourceSequence: 2,
};
}
async close() {}
}
const driver: HarnessDriver = {
async descriptor() {
return {
kind: "fake",
displayName: "Fake harness",
version: "1",
capabilities: {
resume: false,
typedEvents: true,
steering: false,
interruption: false,
structuredResult: true,
},
};
},
async openSession() { return new FakeHarnessSession(); },
};
describe("HarnessDriverBackend", () => {
it.each(["default", "disabled"] as const)("rejects unsupported reasoning %s before starting provider work", async reasoningMode => {
const startTurn = vi.fn(async () => ({ turnId: "turn-1" }));
const session = Object.assign(new FakeHarnessSession(), { startTurn });
const backend = new HarnessDriverBackend({ ...driver, openSession: async () => session });
const opened = await backend.openSession({ identity: {
runId: "run-1", sessionId: "session-1", companyId: "company-1", issueId: "issue-1", agentId: "agent-1",
} });
expect((await opened.capabilities()).perTurnReasoning).toBe(false);
const message = { role: "user" as const, text: "Hi" };
await expect(opened.startTurn({ message, reasoningMode })).rejects.toThrow("Per-turn reasoning is not supported");
expect(startTurn).not.toHaveBeenCalled();
await expect(opened.startTurn({ message })).resolves.toEqual({ turnId: "turn-1" });
expect(startTurn).toHaveBeenCalledExactlyOnceWith({ message });
});
it.each([
{ cancelled: false, failureCleanup: false, retainUnsettledRemoteRunner: true },
{ cancelled: true, failureCleanup: false, retainUnsettledRemoteRunner: false },
{ cancelled: true, failureCleanup: true, retainUnsettledRemoteRunner: true },
])("asks to retain an unsettled remote Runner on close only when the run was not stopped (cancelled=$cancelled, failureCleanup=$failureCleanup)",
async ({ cancelled, failureCleanup, retainUnsettledRemoteRunner }) => {
const close = vi.fn(async () => {});
const session = Object.assign(new FakeHarnessSession(), { close });
const backend = new HarnessDriverBackend({ ...driver, openSession: async () => session });
const opened = await backend.openSession({ identity: {
runId: "run-1", sessionId: "session-1", companyId: "company-1", issueId: "issue-1", agentId: "agent-1",
} });
if (cancelled) await cancelSession(opened, { reason: failureCleanup ? "Native session event consumption failed." : "Stop requested",
signal: new AbortController().signal, ...(failureCleanup ? { failureCleanup } : {}) }).cleanup;
if (failureCleanup) expect(await opened.result()).toBeNull();
await opened.close({ reason: "native session execution complete" });
expect(close).toHaveBeenCalledExactlyOnceWith({ reason: "native session execution complete", retainUnsettledRemoteRunner });
});
it("forwards reasoning when the provider explicitly supports it", async () => {
const startTurn = vi.fn(async () => ({ turnId: "turn-1" }));
const session = Object.assign(new FakeHarnessSession(), { startTurn, supportsTurnReasoning: () => true });
const backend = new HarnessDriverBackend({ ...driver, openSession: async () => session });
const opened = await backend.openSession({ identity: {
runId: "run-1", sessionId: "session-1", companyId: "company-1", issueId: "issue-1", agentId: "agent-1",
} });
expect((await opened.capabilities()).perTurnReasoning).toBe(true);
const input = { message: { role: "user" as const, text: "Hi" }, reasoningMode: "disabled" as const };
await opened.startTurn(input);
expect(startTurn).toHaveBeenCalledExactlyOnceWith(input);
});
it("refreshes negotiated controls after a warm handshake and separates follow-ups", async () => {
let controls = { steering: false, queuedFollowUp: false };
const steer = vi.fn(async () => {});
const session = Object.assign(new FakeHarnessSession(), { steer, turnControlCapabilities: () => ({ ...controls }) });
const backend = new HarnessDriverBackend({ ...driver, openSession: async () => session });
const opened = await backend.openSession({ identity: {
runId: "run-1", sessionId: "session-1", companyId: "company-1", issueId: "issue-1", agentId: "agent-1",
} });
expect(await opened.capabilities()).toMatchObject({ steering: false, queuedFollowUp: false });
controls = { steering: false, queuedFollowUp: true };
expect(await opened.capabilities()).toMatchObject(controls);
expect(() => opened.steer!({ turnId: "turn-1", message: { role: "user", text: "steer" }, correlationId: "c-1" })).toThrow();
await opened.steer!({ turnId: "turn-1", message: { role: "user", text: "follow" }, correlationId: "c-2", mode: "follow_up" });
expect(steer).toHaveBeenCalledWith(expect.objectContaining({ mode: "follow_up" }));
controls = { steering: true, queuedFollowUp: false };
expect(await opened.capabilities()).toMatchObject(controls);
expect(() => opened.steer!({ turnId: "turn-1", message: { role: "user", text: "follow" }, correlationId: "c-3", mode: "follow_up" })).toThrow();
});
it.each([false, true])("honors driver steering support even when the transport exposes a steer method (%s)", async supported => {
const steer = vi.fn(async () => { throw new Error("provider does not support steering"); });
const session = Object.assign(new FakeHarnessSession(), { steer });
const backend = new HarnessDriverBackend({ ...driver,
descriptor: async () => ({ ...(await driver.descriptor()), capabilities: {
...(await driver.descriptor()).capabilities, steering: supported,
} }),
openSession: async () => session,
recoverSession: async () => ({ recovered: true, session }),
});
const opened = await backend.openSession({ identity: {
runId: "run-1", sessionId: "session-1", companyId: "company-1", issueId: "issue-1", agentId: "agent-1",
} });
expect((await opened.capabilities()).steering).toBe(supported);
const recovered = await backend.recoverSession(await opened.snapshot(), { signal: new AbortController().signal });
expect(recovered.recovered).toBe(true);
expect((await recovered.session!.capabilities()).steering).toBe(supported);
expect(steer).not.toHaveBeenCalled();
});
it("retains Codex accounting and startup state through a serialized native checkpoint", async () => {
const fields = { workingDirectory: "/workspace/selected", codexUsageBaseline: {
baseline: { inputTokens: 100, outputTokens: 20 },
latest: { inputTokens: 150, outputTokens: 35 },
} };
class RecoveryFieldsSession extends FakeHarnessSession {
override async snapshot(): Promise<PersistedHarnessSession> {
return { ...(await super.snapshot()), ...fields, semanticResult: undefined, activeTurnId: null };
}
}
const original = new HarnessDriverBackend({ ...driver, openSession: async () => new RecoveryFieldsSession() });
const session = await original.openSession({ identity: {
runId: "run-1", sessionId: "session-1", companyId: "company-1", issueId: "issue-1", agentId: "agent-1",
}, workingDirectory: fields.workingDirectory });
const checkpoint = JSON.parse(JSON.stringify(await session.snapshot()));
expect(checkpoint).toMatchObject(fields);
const recover = vi.fn(async (_snapshot: PersistedHarnessSession) => ({ recovered: true, session: new RecoveryFieldsSession() }));
const restarted = new HarnessDriverBackend({ ...driver, recoverSession: recover });
const restored = await restarted.recoverSession(checkpoint, { signal: new AbortController().signal });
expect(restored.recovered).toBe(true);
expect(recover.mock.calls[0]![0]).toMatchObject(fields);
expect(await restored.session!.snapshot()).toMatchObject(fields);
checkpoint.codexUsageBaseline.latest.inputTokens = 999;
expect(recover.mock.calls[0]![0].codexUsageBaseline!.latest.inputTokens).toBe(150);
});
it.each([true, false])("carries the provider-turn wait marker through a serialized native checkpoint only while waiting (%s)", async (awaiting) => {
class WaitSession extends FakeHarnessSession {
override async snapshot(): Promise<PersistedHarnessSession> {
return { ...(await super.snapshot()), semanticResult: undefined, activeTurnId: null,
...(awaiting ? { awaitingProviderTurn: true } : {}) };
}
}
const original = new HarnessDriverBackend({ ...driver, openSession: async () => new WaitSession() });
const session = await original.openSession({ identity: {
runId: "run-1", sessionId: "session-1", companyId: "company-1", issueId: "issue-1", agentId: "agent-1",
} });
const checkpoint = JSON.parse(JSON.stringify(await session.snapshot()));
const recover = vi.fn(async (_snapshot: PersistedHarnessSession) => ({ recovered: true, session: new WaitSession() }));
await new HarnessDriverBackend({ ...driver, recoverSession: recover })
.recoverSession(checkpoint, { signal: new AbortController().signal });
if (awaiting) {
expect(checkpoint.awaitingProviderTurn).toBe(true);
expect(recover.mock.calls[0]![0].awaitingProviderTurn).toBe(true);
} else {
expect(checkpoint).not.toHaveProperty("awaitingProviderTurn");
expect(recover.mock.calls[0]![0]).not.toHaveProperty("awaitingProviderTurn");
}
});
it("rejects and closes a provider session without a durable provider identity", async () => {
let closed = false;
class MissingProviderIdentitySession extends FakeHarnessSession {
override ids() {
return {
driverSessionId: "driver-missing-provider",
providerSessionId: null,
};
}
override async close() {
closed = true;
}
}
const incompleteDriver: HarnessDriver = {
...driver,
async openSession() {
return new MissingProviderIdentitySession();
},
};
const backend = new HarnessDriverBackend(incompleteDriver);
await expect(backend.openSession({
identity: {
runId: "run-incomplete",
sessionId: "session-incomplete",
companyId: "company-1",
issueId: "issue-1",
agentId: "agent-1",
},
workingDirectory: "/workspace",
})).rejects.toThrow(
"provider_initialize_protocol_error: provider=fake stage=session.open missing durable provider session identity",
);
expect(closed).toBe(true);
});
it("rejects and closes a recovered session without a durable provider identity", async () => {
let closed = false;
class MissingRecoveredIdentitySession extends FakeHarnessSession {
override ids() {
return {
driverSessionId: "driver-missing-recovered-provider",
providerSessionId: null,
};
}
override async close() {
closed = true;
}
}
const incompleteDriver: HarnessDriver = {
...driver,
async recoverSession() {
return {
recovered: true,
session: new MissingRecoveredIdentitySession(),
};
},
};
const backend = new HarnessDriverBackend(incompleteDriver);
await expect(backend.recoverSession({
backendKind: "runner",
driverKind: "fake",
sessionId: "driver-1",
providerSessionId: "provider-1",
identity: {
runId: "run-recover-incomplete",
sessionId: "session-recover-incomplete",
companyId: "company-1",
issueId: "issue-1",
agentId: "agent-1",
},
cursor: "0",
}, {
signal: new AbortController().signal,
})).rejects.toThrow(
"provider_initialize_protocol_error: provider=fake stage=session.recover missing durable provider session identity",
);
expect(closed).toBe(true);
});
it("normalizes harness events, result, terminal, and snapshot", async () => {
const backend = new HarnessDriverBackend(driver);
const session = await backend.openSession({
identity: { runId: "run-1", sessionId: "session-1", companyId: "company-1", issueId: "issue-1", agentId: "agent-1" },
workingDirectory: "/workspace",
});
const events: PrpEvent[] = [];
for await (const event of session.events()) events.push(event);
expect(events).toHaveLength(2);
await expect(session.result()).resolves.toMatchObject({ result, turnId: "turn-1", terminal: { runTerminalState: "succeeded" } });
await expect(session.snapshot()).resolves.toMatchObject({
driverKind: "fake",
sessionId: "driver-1",
providerSessionId: "provider-1",
providerIdentity,
providerRecoveryPolicy: "allow_replacement_after_governed_wait",
});
});
it("passes the persisted harness driver kind through recovery", async () => {
let recoveredDriverKind: string | null = null;
let recoveredProviderIdentity: PersistedHarnessSession["providerIdentity"];
let recoveredDispositionAllowance: boolean | undefined;
const recoveryDriver: HarnessDriver = {
...driver,
async recoverSession(snapshot) {
recoveredDriverKind = snapshot.driverKind;
recoveredProviderIdentity = snapshot.providerIdentity;
recoveredDispositionAllowance =
snapshot.dispositionOnlyRecoveryConsumed;
return { recovered: true, session: new FakeHarnessSession() };
},
};
const backend = new HarnessDriverBackend(recoveryDriver);
const recovery = await backend.recoverSession({
backendKind: "runner",
driverKind: "fake",
sessionId: "driver-1",
providerSessionId: "provider-1",
providerIdentity,
providerRecoveryPolicy: "allow_replacement_after_governed_wait",
dispositionOnlyRecoveryConsumed: true,
identity: { runId: "run-2", sessionId: "session-1", companyId: "company-1", issueId: "issue-1", agentId: "agent-1" },
}, {
signal: new AbortController().signal,
});
expect(recovery.recovered).toBe(true);
expect(recoveredDriverKind).toBe("fake");
expect(recoveredProviderIdentity).toEqual(providerIdentity);
expect(recoveredDispositionAllowance).toBe(true);
});
it("keeps the runner's closed class of a failed recovery", async () => {
const commandFailure = Object.defineProperty(new Error("PRP command run.attach failed"), "runnerCommandResult", {
value: { status: "failed", commandType: "run.attach",
result: { code: "command_execution_failed", message: "saved launch profile changed",
classification: PROVIDER_STATE_INCOMPATIBLE } },
enumerable: false,
});
expect(runnerRecoveryFailureClass(commandFailure)).toBe(PROVIDER_STATE_INCOMPATIBLE);
expect(runnerRecoveryFailureClass(new Error("wrapped", { cause: commandFailure }))).toBe(PROVIDER_STATE_INCOMPATIBLE);
expect(runnerRecoveryFailureClass(new Error(`text only: ${PROVIDER_STATE_INCOMPATIBLE}`))).toBeUndefined();
const unclassified = Object.defineProperty(new Error("PRP command run.attach failed"), "runnerCommandResult", {
value: { status: "failed", result: { code: "command_execution_failed", classification: "other" } },
enumerable: false,
});
expect(runnerRecoveryFailureClass(unclassified)).toBeUndefined();
for (const classification of [PROVIDER_ATTACH_REFUSED, PROVIDER_SIDE_EFFECT_PENDING]) {
const refused = Object.defineProperty(new Error("PRP command run.attach failed"), "runnerCommandResult", {
value: { status: "failed", result: { code: "command_execution_failed", classification } },
enumerable: false,
});
expect(runnerRecoveryFailureClass(new Error("wrapped", { cause: refused }))).toBe(classification);
}
const pendingSource = new NativeRunnerSourceReconciliationRequiredError("semantic");
expect(pendingSource.message).toBe("native_runner_source_semantic_reconciliation_required");
expect(runnerRecoveryFailureClass(pendingSource)).toBe(PROVIDER_SIDE_EFFECT_PENDING);
expect(runnerRecoveryFailureClass(new Error("wrapped", { cause: new NativeRunnerSourceReconciliationRequiredError("runtime") })))
.toBe(PROVIDER_SIDE_EFFECT_PENDING);
expect(runnerRecoveryFailureClass(new Error("native_runner_source_semantic_reconciliation_required"))).toBeUndefined();
const backend = new HarnessDriverBackend({
...driver,
recoverSession: async () => ({ recovered: false, reason: String(commandFailure),
failureClass: runnerRecoveryFailureClass(commandFailure) }),
});
await expect(backend.recoverSession({
backendKind: "runner", driverKind: "fake", sessionId: "driver-1", providerSessionId: "provider-1",
providerIdentity,
identity: { runId: "run-2", sessionId: "session-1", companyId: "company-1", issueId: "issue-1", agentId: "agent-1" },
}, { signal: new AbortController().signal })).resolves.toEqual({
recovered: false, reason: "Error: PRP command run.attach failed", failureClass: PROVIDER_STATE_INCOMPATIBLE,
});
});
it("builds a native snapshot from the driver's boundary snapshot only when asked for that sequence", async () => {
const boundarySnapshot = vi.fn((sourceSeq: number): PersistedHarnessSession | null => sourceSeq !== 7 ? null : {
driverKind: "fake", driverSessionId: "driver-1", providerSessionId: "provider-1", providerIdentity,
activeTurnId: null, semanticResult: null, awaitingProviderTurn: true, lastSourceSequence: 7 });
class BoundarySession extends FakeHarnessSession {
boundarySnapshot = boundarySnapshot;
override async snapshot(): Promise<PersistedHarnessSession> {
return { ...(await super.snapshot()), activeTurnId: "provider-1", lastSourceSequence: 9 };
}
}
const backend = new HarnessDriverBackend({ ...driver, async openSession() { return new BoundarySession(); } });
const session = await backend.openSession({ identity: {
runId: "run-boundary", sessionId: "session-1", companyId: "company-1", issueId: "issue-1", agentId: "agent-1",
} });
const signal = new AbortController().signal;
await expect(session.snapshot({ signal, sourceSeq: 7 })).resolves.toMatchObject({
cursor: "7", activeTurnId: null, semanticResult: null, awaitingProviderTurn: true });
expect(boundarySnapshot).toHaveBeenCalledExactlyOnceWith(7);
const current = await session.snapshot();
expect(current).toMatchObject({ cursor: "9", activeTurnId: "provider-1" });
expect(current).not.toHaveProperty("awaitingProviderTurn");
expect(boundarySnapshot).toHaveBeenCalledOnce();
await expect(session.snapshot({ signal, sourceSeq: 8 })).resolves.toMatchObject({ cursor: "9", activeTurnId: "provider-1" });
expect(boundarySnapshot).toHaveBeenLastCalledWith(8);
});
it("preserves a consumed disposition allowance in native snapshots", async () => {
class ConsumedRecoverySession extends FakeHarnessSession {
override async snapshot(): Promise<PersistedHarnessSession> {
return {
...(await super.snapshot()),
dispositionOnlyRecoveryConsumed: true,
};
}
}
const backend = new HarnessDriverBackend({
...driver,
async openSession() {
return new ConsumedRecoverySession();
},
});
const session = await backend.openSession({
identity: {
runId: "run-consumed-recovery",
sessionId: "session-1",
companyId: "company-1",
issueId: "issue-1",
agentId: "agent-1",
},
});
await expect(session.snapshot()).resolves.toMatchObject({
dispositionOnlyRecoveryConsumed: true,
});
});
it("forwards the native bootstrap signal to the harness driver", async () => {
const controller = new AbortController();
let receivedSignal: AbortSignal | undefined;
const backend = new HarnessDriverBackend({
...driver,
async openSession(input) {
receivedSignal = input.signal;
return new FakeHarnessSession();
},
});
await backend.openSession({
identity: { runId: "run-signal", sessionId: "session-signal", companyId: "company-1", issueId: "issue-1", agentId: "agent-1" },
workingDirectory: "/workspace",
signal: controller.signal,
});
expect(receivedSignal).toBe(controller.signal);
});
it("forwards the native recovery signal to the harness driver", async () => {
const controller = new AbortController();
let receivedSignal: AbortSignal | undefined;
const backend = new HarnessDriverBackend({
...driver,
async recoverSession(_snapshot, options) {
receivedSignal = options.signal;
return { recovered: true, session: new FakeHarnessSession() };
},
});
const recovery = await backend.recoverSession({
backendKind: "runner",
driverKind: "fake",
sessionId: "driver-1",
providerSessionId: "provider-1",
providerIdentity,
identity: { runId: "run-recover-signal", sessionId: "session-1", companyId: "company-1", issueId: "issue-1", agentId: "agent-1" },
}, {
signal: controller.signal,
});
expect(recovery.recovered).toBe(true);
expect(receivedSignal).toBe(controller.signal);
});
it("does not resurrect a settled turn across repeated backend recovery", async () => {
const terminal: PrpTerminalState = {
schema: "paperclip.prp.terminal.v1",
turnTerminalState: "completed",
runTerminalState: "succeeded",
reportedWorkDisposition: "done",
};
const recoveredSnapshots: PersistedHarnessSession[] = [];
class SettledRecoveredSession extends FakeHarnessSession {
readonly #snapshot: PersistedHarnessSession;
constructor(snapshot: PersistedHarnessSession) {
super();
this.#snapshot = structuredClone(snapshot);
}
override async *events() {
// Model the deterministic driver's recovery rule: only an active turn
// produces a reconstructed result/terminal sequence.
if (this.#snapshot.activeTurnId === null || this.#snapshot.activeTurnId === undefined) return;
yield prpEvent(3, "run.result.proposed", result);
yield prpEvent(4, "turn.completed", { status: "completed" });
yield prpEvent(5, "run.terminal", terminal);
}
override async snapshot(): Promise<PersistedHarnessSession> {
return structuredClone(this.#snapshot);
}
}
const recoveryDriver: HarnessDriver = {
...driver,
async recoverSession(snapshot) {
recoveredSnapshots.push(structuredClone(snapshot));
return { recovered: true, session: new SettledRecoveredSession(snapshot) };
},
};
const backend = new HarnessDriverBackend(recoveryDriver);
const settledSnapshot = {
backendKind: "runner" as const,
driverKind: "fake",
sessionId: "driver-1",
providerSessionId: "provider-1",
identity: {
runId: "run-1",
sessionId: "session-1",
companyId: "company-1",
issueId: "issue-1",
agentId: "agent-1",
},
cursor: "2",
semanticResult: result,
terminal,
activeTurnId: null,
terminalTurns: [{ turnId: "turn-1", fingerprint: "terminal-1" }],
};
const firstRecovery = await backend.recoverSession(settledSnapshot, {
signal: new AbortController().signal,
});
expect(firstRecovery.recovered).toBe(true);
const firstSession = firstRecovery.session!;
const firstRecoveredSnapshot = await firstSession.snapshot();
expect(firstRecoveredSnapshot).toMatchObject({
activeTurnId: null,
semanticResult: result,
terminal,
});
await expect(firstSession.result()).resolves.toEqual({
result,
terminal,
turnId: "turn-1",
});
const secondRecovery = await backend.recoverSession(firstRecoveredSnapshot, {
signal: new AbortController().signal,
});
expect(secondRecovery.recovered).toBe(true);
const secondSession = secondRecovery.session!;
await expect(secondSession.snapshot()).resolves.toMatchObject({
activeTurnId: null,
semanticResult: result,
terminal,
});
const replayedEvents: PrpEvent[] = [];
for await (const event of secondSession.events()) replayedEvents.push(event);
expect(replayedEvents.filter((event) =>
event.eventType === "run.result.proposed" || event.eventType === "run.terminal"
)).toEqual([]);
expect(recoveredSnapshots.map((snapshot) => snapshot.activeTurnId)).toEqual([null, null]);
await secondSession.close({ reason: "double recovery complete" });
await firstSession.close({ reason: "first recovery complete" });
});
it("allows only the run id to change when a harness session is attached", async () => {
const attachedRunIds: string[] = [];
const grants: unknown[] = [];
class AttachableHarnessSession extends FakeHarnessSession {
async attachRun(input: { runId: string; currentRunGrant?: { runtimeContext: null; instructions: string } }) {
attachedRunIds.push(input.runId);
grants.push(input.currentRunGrant);
}
}
const backend = new HarnessDriverBackend({
...driver,
async openSession() { return new AttachableHarnessSession(); },
});
const originalIdentity = {
runId: "run-1",
sessionId: "session-1",
companyId: "company-1",
issueId: "issue-1",
agentId: "agent-1",
};
const session = await backend.openSession({
identity: originalIdentity,
workingDirectory: "/workspace",
});
for (const identity of [
{ ...originalIdentity, runId: "run-forged-company", companyId: "company-2" },
{ ...originalIdentity, runId: "run-forged-issue", issueId: "issue-2" },
{ ...originalIdentity, runId: "run-forged-agent", agentId: "agent-2" },
{ ...originalIdentity, runId: "run-forged-session", sessionId: "session-2" },
]) {
await expect(session.attachRun?.({ identity })).rejects.toThrow(
"native_session_attach_binding_mismatch",
);
expect(session.identity()).toEqual(originalIdentity);
}
expect(attachedRunIds).toEqual([]);
await expect(session.attachRun?.({
identity: { ...originalIdentity, runId: "run-2" },
currentRunGrant: { runtimeContext: null, instructions: "Current registered instructions." },
})).resolves.toBeUndefined();
expect(attachedRunIds).toEqual(["run-2"]);
expect(grants).toEqual([{ runtimeContext: null, instructions: "Current registered instructions." }]);
expect(session.identity()).toEqual({ ...originalIdentity, runId: "run-2" });
});
it.each([undefined, 30_000])("preserves the cancellation terminal bound through open and recovery (%s)", async bound => {
const harness = new FakeHarnessSession();
const backend = new HarnessDriverBackend({ ...driver, async openSession() { return harness; }, async recoverSession() { return { recovered: true, session: harness }; } }, undefined, bound);
const identity = { companyId: "company-1", agentId: "agent-1", issueId: "issue-1", runId: "run-1", sessionId: "session-1" };
const opened = await backend.openSession({ identity });
const snapshot = await opened.snapshot({ signal: new AbortController().signal });
const recovered = await backend.recoverSession(snapshot, { signal: new AbortController().signal });
expect(recovered.recovered).toBe(true);
for (const session of [opened, recovered.session!]) {
const cancellation = session.cancel!({ reason: "durable wait", signal: new AbortController().signal });
expect(cancellation.terminalDrainTimeoutMs).toBe(bound);
await cancellation.cleanup;
}
});
it("restores a persisted terminal before the recovered stream is consumed", async () => {
const recoveryDriver: HarnessDriver = {
...driver,
async recoverSession() {
return { recovered: true, session: new FakeHarnessSession() };
},
};
const backend = new HarnessDriverBackend(recoveryDriver);
const terminal = {
schema: "paperclip.prp.terminal.v1" as const,
turnTerminalState: "completed" as const,
runTerminalState: "succeeded" as const,
reportedWorkDisposition: "done" as const,
};
const recovery = await backend.recoverSession({
backendKind: "runner",
driverKind: "fake",
sessionId: "driver-1",
providerSessionId: "provider-1",
identity: {
runId: "run-terminal-recovery",
sessionId: "session-1",
companyId: "company-1",
issueId: "issue-1",
agentId: "agent-1",
},
semanticResult: result,
terminal,
activeTurnId: "turn-1",
terminalTurns: [
{ turnId: "turn-1", fingerprint: "terminal-fingerprint" },
],
}, {
signal: new AbortController().signal,
});
expect(recovery).toMatchObject({ recovered: true });
await expect(recovery.session!.snapshot()).resolves.toMatchObject({
semanticResult: result,
terminal,
});
await expect(recovery.session!.result()).resolves.toEqual({
result,
terminal,
turnId: "turn-1",
});
});
async function terminalsAfterEachTurnEnd(turnEnds: Array<Record<string, unknown>>) {
class TurnEndsSession extends FakeHarnessSession {
override async *events() {
for (const [index, payload] of turnEnds.entries()) yield prpEvent(index + 1, "turn.completed", payload);
}
}
const backend = new HarnessDriverBackend({ ...driver, async openSession() { return new TurnEndsSession(); } });
const session = await backend.openSession({
identity: { runId: "run-1", sessionId: "session-1", companyId: "company-1", issueId: "issue-1", agentId: "agent-1" },
});
const terminals: Array<PrpTerminalState | null> = [];
for await (const _event of session.events()) terminals.push((await session.snapshot()).terminal ?? null);
return terminals;
}
it("leaves the run terminal open when a turn ends waiting for the provider's own next turn", async () => {
await expect(terminalsAfterEachTurnEnd([{ status: "completed", awaitingProviderTurn: true }])).resolves.toEqual([null]);
});
it("sets the run terminal when a turn ends without waiting for the provider", async () => {
const [terminal] = await terminalsAfterEachTurnEnd([{ status: "completed" }]);
expect(terminal).toMatchObject({ turnTerminalState: "completed", runTerminalState: "succeeded" });
});
it("sets the run terminal at the first turn end that does not wait for the provider", async () => {
const [waiting, settled] = await terminalsAfterEachTurnEnd([{ status: "completed", awaitingProviderTurn: true }, { status: "completed" }]);
expect(waiting).toBeNull();
expect(settled).toMatchObject({ turnTerminalState: "completed", runTerminalState: "succeeded" });
});
it("reconstructs a missing top-level terminal from a completed semantic turn", async () => {
const recoveryDriver: HarnessDriver = {
...driver,
async recoverSession() {
return { recovered: true, session: new FakeHarnessSession() };
},
};
const backend = new HarnessDriverBackend(recoveryDriver);
const semanticFingerprint = canonicalTestJson(result);
const recovery = await backend.recoverSession({
backendKind: "runner",
driverKind: "fake",
sessionId: "driver-1",
providerSessionId: "provider-1",
identity: {
runId: "run-terminal-inference",
sessionId: "session-1",
companyId: "company-1",
issueId: "issue-1",
agentId: "agent-1",
},
semanticResult: result,
terminal: null,
activeTurnId: null,
terminalTurns: [
{
turnId: "turn-1",
fingerprint: JSON.stringify({
status: "completed",
semanticResult: semanticFingerprint,
}),
},
],
}, {
signal: new AbortController().signal,
});
expect(recovery).toMatchObject({ recovered: true });
await expect(recovery.session!.result()).resolves.toEqual({
result,
terminal: {
schema: "paperclip.prp.terminal.v1",
turnTerminalState: "completed",
runTerminalState: "succeeded",
reportedWorkDisposition: "done",
},
turnId: "turn-1",
});
});
it("does not pair a recovered semantic result with another turn's terminal", async () => {
let recoveredPersisted: PersistedHarnessSession | null = null;
class RecoveredHarnessSession extends FakeHarnessSession {
override async snapshot(): Promise<PersistedHarnessSession> {
if (recoveredPersisted === null) throw new Error("missing recovered snapshot");
return structuredClone(recoveredPersisted);
}
}
const recoveryDriver: HarnessDriver = {
...driver,
async recoverSession(snapshot) {
recoveredPersisted = snapshot;
return { recovered: true, session: new RecoveredHarnessSession() };
},
};
const backend = new HarnessDriverBackend(recoveryDriver);
const semanticFingerprint = canonicalTestJson(result);
const recovery = await backend.recoverSession({
backendKind: "runner",
driverKind: "fake",
sessionId: "driver-1",
providerSessionId: "provider-1",
identity: {
runId: "run-cross-turn-terminal",
sessionId: "session-1",
companyId: "company-1",
issueId: "issue-1",
agentId: "agent-1",
},
semanticResult: result,
terminal: {
schema: "paperclip.prp.terminal.v1",
turnTerminalState: "cancelled",
runTerminalState: "cancelled",
reportedWorkDisposition: "yielded",
},
activeTurnId: null,
terminalTurns: [
{
turnId: "turn-with-result",
fingerprint: JSON.stringify({
status: "completed",
semanticResult: semanticFingerprint,
}),
},
{
turnId: "later-cancelled-turn",
fingerprint: JSON.stringify({ status: "cancelled" }),
},
],
}, {
signal: new AbortController().signal,
});
expect(recovery).toMatchObject({ recovered: true });
await expect(recovery.session!.result()).resolves.toEqual({
result,
terminal: {
schema: "paperclip.prp.terminal.v1",
turnTerminalState: "completed",
runTerminalState: "succeeded",
reportedWorkDisposition: "done",
},
turnId: "turn-with-result",
});
});
it("rejects oversized terminal history before inspecting the semantic result", async () => {
const recoverSession = vi.fn(async () => ({
recovered: true,
session: new FakeHarnessSession(),
}));
const backend = new HarnessDriverBackend({ ...driver, recoverSession });
const inaccessibleResult = new Proxy(result, {
ownKeys() {
throw new Error("semantic result must not be inspected");
},
});
await expect(backend.recoverSession({
backendKind: "runner",
driverKind: "fake",
sessionId: "driver-1",
providerSessionId: "provider-1",
identity: {
runId: "run-oversized-terminals",
sessionId: "session-1",
companyId: "company-1",
issueId: "issue-1",
agentId: "agent-1",
},
semanticResult: inaccessibleResult,
terminalTurns: Array.from({ length: 4_097 }, (_, index) => ({
turnId: `turn-${index}`,
fingerprint: "terminal",
})),
}, {
signal: new AbortController().signal,
})).resolves.toEqual({
recovered: false,
reason: "persisted harness terminal history exceeds its recovery limit",
});
expect(recoverSession).not.toHaveBeenCalled();
});
it("rejects an oversized semantic result before canonicalization", async () => {
const recoverSession = vi.fn(async () => ({
recovered: true,
session: new FakeHarnessSession(),
}));
const backend = new HarnessDriverBackend({ ...driver, recoverSession });
await expect(backend.recoverSession({
backendKind: "runner",
driverKind: "fake",
sessionId: "driver-1",
providerSessionId: "provider-1",
identity: {
runId: "run-oversized-semantic-result",
sessionId: "session-1",
companyId: "company-1",
issueId: "issue-1",
agentId: "agent-1",
},
semanticResult: {
...result,
summary: "x".repeat(8 * 1024 * 1024),
},
terminalTurns: [],
}, {
signal: new AbortController().signal,
})).resolves.toEqual({
recovered: false,
reason: "persisted harness semantic result exceeds its recovery limit",
});
expect(recoverSession).not.toHaveBeenCalled();
});
it("delegates native runtime-request resolutions to the harness session", async () => {
runtimeResolutions.length = 0;
const backend = new HarnessDriverBackend(driver);
const session = await backend.openSession({
identity: {
runId: "run-1",
sessionId: "session-1",
companyId: "company-1",
issueId: "issue-1",
agentId: "agent-1",
},
workingDirectory: "/workspace",
});
await session.resolveRuntimeRequest?.({
requestId: "permission-1",
turnId: "turn-1",
resolution: { action: "accept_for_session" },
});
expect(runtimeResolutions).toEqual([
{
requestId: "permission-1",
turnId: "turn-1",
resolution: { action: "accept_for_session" },
},
]);
});
it.each(["typed", "typed-snapshot", "lookalike", "generic"] as const)(
"only a typed integrity fault forbids pending-input fallback: %s",
async (kind) => {
const typed = kind === "typed" || kind === "typed-snapshot";
const fault = typed
? new NativeSessionProtocolIntegrityError(
"semantic_input_digest_mismatch",
)
: kind === "lookalike"
? Object.assign(new Error("native_event_replay_conflict"), {
code: "native_event_replay_conflict",
reason: "semantic_input_digest_mismatch",
})
: new Error("provider transport lost");
class PendingInputSession extends FakeHarnessSession {
override async *events() {
yield prpEvent(1, "runtime_request.created", {
request: {
schema: "paperclip.runtime_request.v2",
requestKind: "runtime",
requestId: "input-1",
type: "input",
status: "pending",
turnId: "turn-1",
itemId: "input-1",
input: {
schema: "paperclip.question_set.v1",
questions: [
{
id: "color",
prompt: "Which color?",
required: true,
answerMode: "text",
},
],
},
},
});
throw kind === "typed-snapshot"
? new Error("ordinary stream failure")
: fault;
}
override async snapshot(): Promise<PersistedHarnessSession> {
if (kind === "typed-snapshot") throw fault;
return super.snapshot();
}
}
const session = await new HarnessDriverBackend({
...driver,
openSession: async () => new PendingInputSession(),
}).openSession({
identity: {
runId: "run-1",
sessionId: "session-1",
companyId: "company-1",
issueId: "issue-1",
agentId: "agent-1",
},
workingDirectory: "/workspace",
});
const events: PrpEvent[] = [];
const consumed = (async () => {
for await (const event of session.events()) events.push(event);
})();
if (typed) {
await expect(consumed).rejects.toBe(fault);
expect(events.map((event) => event.eventType)).toEqual([
"runtime_request.created",
]);
await expect(session.result()).rejects.toBe(fault);
await expect(session.snapshot()).rejects.toBe(fault);
} else {
await consumed;
expect(events.map((event) => event.eventType)).toEqual([
"runtime_request.created",
"runtime_request.expired",
"turn.failed",
]);
}
await session.close({ reason: "fixture complete" });
},
);
it("never exposes an earlier terminal result after a later typed integrity fault", async () => {
const fault = new NativeSessionProtocolIntegrityError(
"semantic_input_digest_mismatch",
);
class TerminalThenIntegrityFailure extends FakeHarnessSession {
goal = vi.fn(async () => null);
steer = vi.fn(async () => {});
override async *events() {
yield* super.events();
throw fault;
}
}
const harness = new TerminalThenIntegrityFailure();
const session = await new HarnessDriverBackend({
...driver,
openSession: async () => harness,
}).openSession({
identity: {
runId: "run-1",
sessionId: "session-1",
companyId: "company-1",
issueId: "issue-1",
agentId: "agent-1",
},
workingDirectory: "/workspace",
});
const iterator = session.events()[Symbol.asyncIterator]();
await iterator.next();
await iterator.next();
await expect(iterator.next()).rejects.toBe(fault);
await expect(session.result()).rejects.toBe(fault);
await expect(session.snapshot()).rejects.toBe(fault);
await expect(Promise.resolve().then(() => session.goal!({ action: "get" }))).rejects.toBe(fault);
await expect(Promise.resolve().then(() => session.steer!({ turnId: "turn-1", message: { role: "user", text: "must not send" } }))).rejects.toBe(fault);
await expect(Promise.resolve().then(() => session.resolveRuntimeRequest!({ requestId: "request-1", turnId: "turn-1", resolution: { type: "input", answers: [] } as never }))).rejects.toBe(fault);
expect(harness.goal).not.toHaveBeenCalled();
expect(harness.steer).not.toHaveBeenCalled();
await session.close({ reason: "fixture complete" });
});
it("expires pending input without converting provider loss into a successful wait", async () => {
const questionSet = {
schema: "paperclip.question_set.v1" as const,
questions: [{ id: "target", prompt: "Which target?", required: true, answerMode: "text" as const }],
};
class LostProviderSession extends FakeHarnessSession {
override async *events() {
yield prpEvent(1, "runtime_request.created", { request: {
schema: "paperclip.runtime_request.v2",
requestKind: "runtime",
requestId: "input-1",
type: "input",
status: "pending",
prompt: "Which target?",
input: questionSet,
turnId: "turn-1",
itemId: "input-1",
} });
throw new Error("provider transport lost");
}
override async snapshot(): Promise<PersistedHarnessSession> {
return { driverKind: "fake", driverSessionId: "driver-1", lastSourceSequence: 1 };
}
}
const backend = new HarnessDriverBackend({ ...driver, async openSession() { return new LostProviderSession(); } });
const session = await backend.openSession({
identity: { runId: "run-1", sessionId: "session-1", companyId: "company-1", issueId: "issue-1", agentId: "agent-1" },
workingDirectory: "/workspace",
});
const iterator = session.events()[Symbol.asyncIterator]();
await expect(iterator.next()).resolves.toMatchObject({ value: { eventType: "runtime_request.created" } });
await expect(iterator.next()).resolves.toMatchObject({ value: {
eventType: "runtime_request.expired",
sourceSeq: 2,
payload: {
requestId: "input-1",
reason: "provider_process_lost",
replayAllowed: false,
request: { input: questionSet },
},
} });
await expect(iterator.next()).resolves.toMatchObject({ value: {
eventType: "turn.failed",
sourceSeq: 3,
payload: { reason: "provider_process_lost" },
} });
await expect(iterator.next()).resolves.toMatchObject({ done: true });
await expect(session.snapshot()).resolves.toMatchObject({ terminal: {
turnTerminalState: "failed", runTerminalState: "failed",
} });
});
it("does not synthesize a fallback after the input was already resolved", async () => {
class ResolvedThenLostSession extends FakeHarnessSession {
override async *events() {
yield prpEvent(1, "runtime_request.created", { request: {
schema: "paperclip.runtime_request.v2",
requestKind: "runtime",
requestId: "input-1",
type: "input",
status: "pending",
prompt: "Which target?",
input: { schema: "paperclip.question_set.v1", questions: [{ id: "target", prompt: "Which target?", required: true, answerMode: "text" }] },
} });
yield prpEvent(2, "runtime_request.resolved", { requestId: "input-1", action: "submit" });
throw new Error("provider transport lost after resolution");
}
}
const backend = new HarnessDriverBackend({ ...driver, async openSession() { return new ResolvedThenLostSession(); } });
const session = await backend.openSession({
identity: { runId: "run-1", sessionId: "session-1", companyId: "company-1", issueId: "issue-1", agentId: "agent-1" },
workingDirectory: "/workspace",
});
const iterator = session.events()[Symbol.asyncIterator]();
await iterator.next();
await iterator.next();
await expect(iterator.next()).rejects.toThrow("provider transport lost after resolution");
});
it.each([false, true])("retains final usage without accepting late output (journal boundary only: %s)", async journalOnly => {
class AccountingAfterCancelSession extends FakeHarnessSession {
async interrupt() {}
override async *events() {
yield prpEvent(1, "item.completed", { kind: "agentMessage", text: "late answer" });
yield prpEvent(2, "item.completed", { kind: "usage", usage: { runDelta: { inputTokens: 7, outputTokens: 3 }, runDeltaComplete: true } });
yield prpEvent(3, "turn.completed", { status: "completed" });
}
}
const backend = new HarnessDriverBackend({ ...driver, async openSession() { return new AccountingAfterCancelSession(); } });
const session = await backend.openSession({
identity: { runId: "run-1", sessionId: "session-1", companyId: "company-1", issueId: "issue-1", agentId: "agent-1" }, workingDirectory: "/workspace",
});
if (journalOnly) session.revokeTurnPublication!();
else await cancelSession(session, { reason: "durable governed wait", signal: new AbortController().signal }).cleanup;
const events = [];
for await (const event of session.events()) events.push(event);
expect(events.filter(event => event.payload.kind === "agentMessage")).toHaveLength(0);
expect(events.find(event => event.payload.kind === "usage")?.payload.usage).toMatchObject({ runDelta: { inputTokens: 7, outputTokens: 3 } });
expect(events.some(event => event.eventType === "turn.cancelled")).toBe(true);
});
it("does not start provider work when Stop arrives before the first turn", async () => {
const provider = new FakeHarnessSession();
const start = vi.spyOn(provider, "startTurn");
const backend = new HarnessDriverBackend({ ...driver, async openSession() { return provider; } });
const session = await backend.openSession({
identity: { runId: "run-1", sessionId: "session-1", companyId: "company-1", issueId: "issue-1", agentId: "agent-1" },
workingDirectory: "/workspace",
});
await cancelSession(session, { reason: "user stop during startup", signal: new AbortController().signal }).cleanup;
await expect(session.startTurn({ message: { role: "user", text: "cancelled work" } }))
.rejects.toThrow("native_session_cancelled");
expect(start).not.toHaveBeenCalled();
});
it("preserves a failed provider terminal after Stop instead of waiting for timeout", async () => {
class FailedAfterStop extends FakeHarnessSession {
override async *events() {
yield prpEvent(1, "item.delta", { text: "before stop" });
yield prpEvent(2, "item.delta", { text: "suppressed after stop" });
yield prpEvent(3, "runtime_request.cancelled", { requestId: "permission-1", turnId: "turn-1" });
yield prpEvent(4, "turn.failed", { status: "failed" });
}
async interrupt() {}
}
const backend = new HarnessDriverBackend({ ...driver, async openSession() { return new FailedAfterStop(); } });
const session = await backend.openSession({
identity: { runId: "run-1", sessionId: "session-1", companyId: "company-1", issueId: "issue-1", agentId: "agent-1" },
workingDirectory: "/workspace",
});
const iterator = session.events()[Symbol.asyncIterator]();
await iterator.next();
await cancelSession(session, { reason: "operator stop", signal: new AbortController().signal }).cleanup;
await expect(iterator.next()).resolves.toMatchObject({ value: { eventType: "runtime_request.cancelled", sourceSeq: 3 } });
await expect(iterator.next()).resolves.toMatchObject({ value: { eventType: "turn.failed", sourceSeq: 4 } });
await expect(iterator.next()).resolves.toMatchObject({ done: true });
});
it("settles Stop after provider completion but before its queued terminal is consumed", async () => {
class CompletedBeforeStop extends FakeHarnessSession {
override async *events() {
yield prpEvent(1, "item.delta", { text: "before stop" });
yield prpEvent(2, "turn.completed", { status: "completed" });
yield prpEvent(3, "run.terminal", {
schema: "paperclip.prp.terminal.v1", turnTerminalState: "completed",
runTerminalState: "succeeded", reportedWorkDisposition: "done",
});
}
async interrupt() { throw new Error("no active provider turn"); }
}
const backend = new HarnessDriverBackend({ ...driver, async openSession() { return new CompletedBeforeStop(); } });
const session = await backend.openSession({
identity: { runId: "run-1", sessionId: "session-1", companyId: "company-1", issueId: "issue-1", agentId: "agent-1" },
workingDirectory: "/workspace",
});
const iterator = session.events()[Symbol.asyncIterator]();
await iterator.next();
await expect(cancelSession(session, { reason: "operator stop", signal: new AbortController().signal }).cleanup).rejects.toThrow("no active provider turn");
await expect(iterator.next()).resolves.toMatchObject({ value: { eventType: "turn.cancelled", sourceSeq: 2,
payload: { status: "cancelled", providerTerminalState: "completed", reason: "cancelled_after_provider_completed" } } });
await expect(iterator.next()).resolves.toMatchObject({ value: { eventType: "run.terminal", sourceSeq: 3,
payload: { turnTerminalState: "cancelled", runTerminalState: "cancelled", reportedWorkDisposition: "yielded" } } });
await expect(iterator.next()).resolves.toMatchObject({ done: true });
await expect(session.result()).resolves.toBeNull();
await expect(session.snapshot()).resolves.toMatchObject({ terminal: { runTerminalState: "cancelled" } });
});
it("does not synthesize a fallback after explicit run cancellation", async () => {
class CancelledProviderSession extends FakeHarnessSession {
override async *events() {
yield prpEvent(1, "runtime_request.created", { request: {
schema: "paperclip.runtime_request.v2",
requestKind: "runtime",
requestId: "input-1",
type: "input",
status: "pending",
prompt: "Which target?",
input: { schema: "paperclip.question_set.v1", questions: [{ id: "target", prompt: "Which target?", required: true, answerMode: "text" }] },
} });
throw new Error("provider stopped after cancellation");
}
async interrupt() {}
}
const backend = new HarnessDriverBackend({ ...driver, async openSession() { return new CancelledProviderSession(); } });
const session = await backend.openSession({
identity: { runId: "run-1", sessionId: "session-1", companyId: "company-1", issueId: "issue-1", agentId: "agent-1" },
workingDirectory: "/workspace",
});
const iterator = session.events()[Symbol.asyncIterator]();
await expect(iterator.next()).resolves.toMatchObject({ value: { eventType: "runtime_request.created" } });
await cancelSession(session, {
reason: "operator cancelled the run",
signal: new AbortController().signal,
}).cleanup;
await expect(iterator.next()).rejects.toThrow("provider stopped after cancellation");
});
});
function canonicalTestJson(value: unknown): string {
if (Array.isArray(value)) {
return `[${value.map(canonicalTestJson).join(",")}]`;
}
if (typeof value === "object" && value !== null) {
const record = value as Record<string, unknown>;
return `{${Object.keys(record)
.sort()
.map((key) => `${JSON.stringify(key)}:${canonicalTestJson(record[key])}`)
.join(",")}}`;
}
return JSON.stringify(value) ?? "undefined";
}