The Open Framework for Building Agents
feat(eve): hand off sessions to a fresh run after compaction (#4239)
Andrew Barba1062c92ada6f
diff --git a/.changeset/compaction-handoff.md b/.changeset/compaction-handoff.mdnew file mode 100644index 000000000..2d0ccba4c--- /dev/null+++ b/.changeset/compaction-handoff.md@@ -0,0 +1,5 @@+---+"eve": patch+---++After compaction, eve now moves an idle session to a fresh workflow run on the same deployment, so long-running sessions no longer accumulate an ever-growing workflow event log. The session keeps its ID, event stream, continuation addresses, and deadline.diff --git a/.changeset/eval-session-compact.md b/.changeset/eval-session-compact.mdnew file mode 100644index 000000000..05b03007f--- /dev/null+++ b/.changeset/eval-session-compact.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Eval sessions now have `session.compact()`, which compacts the session between turns and resolves to the compaction events through `session.waiting`, so evals no longer need raw `fetch` calls to cover compaction.diff --git a/docs/agent-config.md b/docs/agent-config.mdindex 26ecae764..5161f764f 100644--- a/docs/agent-config.md+++ b/docs/agent-config.md@@ -180,8 +180,8 @@ export default defineAgent({`sessionTimeoutMs` sets the lifetime for every session, including delegatedsessions. It defaults to 30 days and starts at creation. Each successfuldeployment handoff or legacy-session import restarts the original configured-duration. Process restarts, ordinary messages, and failed or skipped handoffs-keep the existing deadline. At the deadline, eve lets an active turn settle,+duration. Process restarts, ordinary messages, compaction handoffs, and failed+or skipped handoffs keep the existing deadline. At the deadline, eve lets an active turn settle,then emits `session.completed` and releases every continuation address; the nextqualifying channel message starts fresh. Set it to `false` to disable thetimeout. Expiration does not delete stored session data.diff --git a/docs/concepts/default-harness.md b/docs/concepts/default-harness.mdindex c08ed9931..d814bb0c1 100644--- a/docs/concepts/default-harness.md+++ b/docs/concepts/default-harness.md@@ -36,6 +36,10 @@ if a turn is running, eve queues it until that turn settles. A successful manualcompaction emits the same `compaction.requested` and `compaction.completed`events as automatic compaction, followed by `session.waiting`.+After either kind of compaction, eve moves the idle session to a fresh workflow+run on the same deployment, so a long session's run history does not keep+growing. See [Execution model and durability](./execution-model-and-durability#compaction-handoff).+To discard model-message history instead of summarizing it, call the corresponding`clear()` method on any of those handles. Clearing preserves the session identity,system prompt, configured tools and skills, durable state, limits, and sandbox.diff --git a/docs/concepts/execution-model-and-durability.mdx b/docs/concepts/execution-model-and-durability.mdxindex ecb26ba81..95f9b90e8 100644--- a/docs/concepts/execution-model-and-durability.mdx+++ b/docs/concepts/execution-model-and-durability.mdx@@ -31,6 +31,12 @@ If the target deployment rejects the session, the previous owner keeps it and preve does not move live work between deployments. A session with a running turn, pending human input or authorization, queued messages, or active tasks and subagents stays on its current deployment. After that work settles, a later delivery can move the idle session; the earlier deployment signal is not remembered.+### Compaction handoff++Every workflow run records each step it executes, so a session that ran on one run for weeks would carry its whole history in that run. To bound this, eve moves a session to a fresh run on its current deployment after [compaction](./default-harness#compaction) rewrites the conversation history. This applies to automatic compaction during a turn and to a client or channel compaction request.++The move happens once the turn settles and nothing else is waiting: no queued messages, running tasks or subagents, or pending human input. The new run receives the compacted history and settled state, then waits for the next message. If a single message reaches an otherwise idle session before the move completes, eve moves the session with that message, and the message's turn runs on the new run. If work is still pending, eve tries again after a later turn settles. The session keeps its ID, event stream, continuation addresses, and deadline; compaction never extends [`sessionTimeoutMs`](../agent-config#runtime-limits). If the new run cannot take ownership, the current run keeps the session, writes a `session handoff failed` warning to its runtime logs, and tries again later.+### Upgrading sessions from the former execution modelYou can upgrade directly from a release that used a session driver and separatediff --git a/docs/concepts/sessions-runs-and-streaming.md b/docs/concepts/sessions-runs-and-streaming.mdindex 3edc1a67e..e71f94714 100644--- a/docs/concepts/sessions-runs-and-streaming.md+++ b/docs/concepts/sessions-runs-and-streaming.md@@ -12,8 +12,8 @@ controls, and streams. Every operation targets that exact session; none followsor creates a replacement implicitly.The session ID currently identifies the original Workflow run that owns the-event stream. A deployment handoff changes the executing run, not the session-ID or stream. Stream namespaces belong to a run; eve does not support+event stream. A deployment or compaction handoff changes the executing run, not+the session ID or stream. Stream namespaces belong to a run; eve does not supportcaller-assigned session IDs or globally addressed streams.Authored channels also have channel-local continuation tokens. A token addresses@@ -24,7 +24,7 @@ by the eve HTTP session API. See [Custom channels](../channels/custom#channel-opSessions last 30 days by default; configure `limits.sessionTimeoutMs` in`agent.ts`, or set it to `false` to disable the deadline. A successful deploymenthandoff or legacy-session import restarts the original configured duration.-Ordinary messages and process restarts keep the existing deadline. At expiration, eve+Ordinary messages, compaction handoffs, and process restarts keep the existing deadline. At expiration, evelets an active turn settle, emits `session.completed`, and releases thesession's continuation addresses so the next qualifying channel message starts fresh. Storedsession data is not deleted. See [Agent config](../agent-config#runtime-limits).diff --git a/docs/evals/cases.mdx b/docs/evals/cases.mdxindex 1ce04e4ca..60b13ba77 100644--- a/docs/evals/cases.mdx+++ b/docs/evals/cases.mdx@@ -110,6 +110,7 @@ Every `t.session()` or `t.send()` creates a new independent conversation. Contin- `session.send(message, options?)` sends a follow-up on that session and waits for it to settle.- `session.start(message, options?)` starts a text turn and returns as soon as the server accepts it. The live turn exposes `.session`, `.sessionId`, `.waitForEvent(...)`, `.cancel()`, and `.result()`.- `session.cancel()` requests cooperative cancellation of that session's active turn. Both `accepted` and `no_active_turn` are successful outcomes.+- `session.compact()` compacts that session's history between turns and waits for it to finish. It resolves to the captured events from `compaction.requested` through `session.waiting`, so assertions such as `.event("compaction.completed")` work on the result. It throws when the session is no longer active.- `session.sendFile(text, path, mediaType?)` attaches a local file as a data URL.- `session.agent(started).stream(options?)` follows a delegated child's stream through the parent with the eval client's credentials. Pass an `agent.started` event from that session. It also reaches children on another deployment, which `t.target.watchTurn(...)` cannot address.- `session.requireInputRequest(filter?)` records a gate, requires exactly one pending request, and returns it. Filters match tool name, action input, prompt, display, and option ids.diff --git a/e2e/fixtures/agent-cancellation/agent/agent.ts b/e2e/fixtures/agent-cancellation/agent/agent.tsindex 347546dff..803e42caf 100644--- a/e2e/fixtures/agent-cancellation/agent/agent.ts+++ b/e2e/fixtures/agent-cancellation/agent/agent.ts@@ -8,6 +8,9 @@ const SLEEPER_FOLLOW_UP = "SLEEPER-FOLLOW-UP";const CANCELLED_TURN_FOLLOW_UP = "CANCELLATION-SUBAGENT-FOLLOW-UP-OK";/** How a call the cancelled turn stopped reads in history. */const CANCELLED_CALL_TEXT = "cancelled before this call finished";+/** Shared with `evals/cancellation/compact-session-handoff.eval.ts`. */+const CODE_WORD = "ORCHID-42";+const CODE_WORD_QUESTION = "What is Alice's project code word?";async function respond(request: MockModelRequest): Promise<MockModelResponse | string> {const message = request.lastUserMessage ?? "";@@ -76,9 +79,18 @@ async function respond(request: MockModelRequest): Promise<MockModelResponse | s};}if (message.includes(CANCELLED_TURN_FOLLOW_UP)) return replyAfterCancelledTurn(request);+ if (message.includes(CODE_WORD_QUESTION)) return recallCodeWord(request);return `Mock reply: ${message}`;}+/** Answers only from history, so a session that lost it across compaction cannot answer. */+function recallCodeWord(request: MockModelRequest): string {+ const remembered = request.messages.some(+ (entry) => !entry.text.includes(CODE_WORD_QUESTION) && entry.text.includes(CODE_WORD),+ );+ return remembered ? CODE_WORD : "Alice's code word is not in this conversation.";+}+/*** Answers the follow-up to a cancelled sleeper turn only when history keeps* what that turn did: the sleeper call, and the calls the cancel stoppeddiff --git a/e2e/fixtures/agent-cancellation/evals/cancellation/compact-session-handoff.eval.ts b/e2e/fixtures/agent-cancellation/evals/cancellation/compact-session-handoff.eval.tsnew file mode 100644index 000000000..215bb2b10--- /dev/null+++ b/e2e/fixtures/agent-cancellation/evals/cancellation/compact-session-handoff.eval.ts@@ -0,0 +1,55 @@+import { defineEval, type EveEvalTurn } from "eve/evals";++function expectCompaction(compacted: EveEvalTurn): void {+ compacted.event("compaction.requested", { count: 1 });+ compacted.event("compaction.completed", { count: 1 });+ compacted.eventOrder([+ { type: "compaction.requested" },+ { type: "compaction.completed" },+ { type: "session.waiting" },+ ]);+ compacted.notEvent("turn.started");+ compacted.notEvent("session.failed");+}++/**+ * Keep a conversation going across repeated compactions.+ *+ * Each compaction moves the idle session to a fresh workflow run on the same+ * deployment. The session keeps its ID, event stream, and conversation, so+ * later messages still stream normally and a fact from before both+ * compactions is still known.+ */+export default defineEval({+ description: "Continue a session and its conversation across repeated compactions.",+ timeoutMs: 240_000,++ async test(t) {+ const session = await t.session();++ const opening = await session.send(+ "Alice is starting a project with the code word ORCHID-42. Acknowledge it in one short sentence.",+ );+ opening.expectOk();++ expectCompaction(await session.compact());++ const update = await session.send(+ "Bob joins Alice's project and asks for a status check. Reply with exactly STATUS-AFTER-COMPACTION-OK.",+ );+ update.expectOk();+ update.notEvent("session.failed");+ update.messageIncludes(/STATUS-AFTER-COMPACTION-OK/);++ expectCompaction(await session.compact());++ const recall = await session.send(+ "What is Alice's project code word? Reply with only the code word.",+ );+ recall.expectOk();+ recall.notEvent("session.failed");+ recall.messageIncludes(/ORCHID-42/);++ t.succeeded();+ },+});diff --git a/packages/eve/src/evals/session.test.ts b/packages/eve/src/evals/session.test.tsindex d6198dac6..0b5642096 100644--- a/packages/eve/src/evals/session.test.ts+++ b/packages/eve/src/evals/session.test.ts@@ -88,6 +88,36 @@ describe("eval judge input", () => {});});+describe("eval session compact", () => {+ it("returns the compaction events through session.waiting", async () => {+ const { session } = await setup();+ await session.send("Plan Alice's trip.");+ const compact = vi+ .spyOn(ClientSession.prototype, "compact")+ .mockResolvedValue({ sessionId: "session_1", status: "accepted" });+ vi.mocked(ClientSession.prototype.stream).mockImplementation(compactionEvents);++ const compacted = await session.compact();++ expect(compact).toHaveBeenCalledOnce();+ expect(compacted.events.map((event) => event.type)).toEqual([+ "compaction.requested",+ "compaction.completed",+ "session.waiting",+ ]);+ });++ it("throws instead of waiting when the session is no longer active", async () => {+ const { session } = await setup();+ vi.spyOn(ClientSession.prototype, "compact").mockResolvedValue({+ status: "no_active_session",+ });++ await expect(session.compact()).rejects.toThrow(/no active session/);+ expect(ClientSession.prototype.stream).not.toHaveBeenCalled();+ });+});+async function setup() {mocks.evaluate.mockResolvedValue({answers: { judgment: { type: "boolean", probability: 1 } },@@ -126,6 +156,24 @@ function response() {});}+async function* compactionEvents() {+ const compaction = {+ modelId: "test",+ sequence: 2,+ sessionId: "session_1",+ stepIndex: 0,+ turnId: "turn_1",+ };+ yield* stampTestEvents([+ { type: "compaction.requested", data: { ...compaction, usageInputTokens: 100 } },+ { type: "compaction.completed", data: compaction },+ {+ type: "session.waiting",+ data: { continuationToken: "session_1", wait: "next-user-message" },+ },+ ]);+}+async function* events() {yield* stampTestEvents([{diff --git a/packages/eve/src/evals/session.ts b/packages/eve/src/evals/session.tsindex f33e7d59e..cb055f02a 100644--- a/packages/eve/src/evals/session.ts+++ b/packages/eve/src/evals/session.ts@@ -147,6 +147,14 @@ export class EvalSessionDriver implements EveEvalSession {return await this.#session.cancel();}+ async compact(): Promise<EveEvalTurn> {+ const result = await this.#session.compact();+ if (result.status !== "accepted") {+ throw new Error(`compact() found no active session for "${this.sessionId}".`);+ }+ return await this.readTurn();+ }+agent(started: AgentStartedStreamEvent): EveEvalAgentSession {const child = this.#session.agent(started);const signal = this.#signal;diff --git a/packages/eve/src/evals/types.ts b/packages/eve/src/evals/types.tsindex 80a0a4a5c..764bc6e09 100644--- a/packages/eve/src/evals/types.ts+++ b/packages/eve/src/evals/types.ts@@ -326,6 +326,12 @@ interface EveEvalSessionDriver {readonly sessionId: string;/** Request cooperative cancellation of this session's active turn. */cancel(): Promise<CancelSessionResult>;+ /**+ * Compact this session's history between turns and wait for it to finish.+ * Returns the compaction events through `session.waiting`; throws when the+ * session is no longer active.+ */+ compact(): Promise<EveEvalTurn>;/** Require exactly one pending input request matching `filter`, or abort dependent control flow. */requireInputRequest(filter?: EveEvalInputRequestMatchOptions): InputRequest;/** Resolve specific pending requests and run the resumed turn. */diff --git a/packages/eve/src/execution/legacy-session/turn-workflow.ts b/packages/eve/src/execution/legacy-session/turn-workflow.tsindex 65a51b708..39fd57443 100644--- a/packages/eve/src/execution/legacy-session/turn-workflow.ts+++ b/packages/eve/src/execution/legacy-session/turn-workflow.ts@@ -60,11 +60,13 @@ export async function turnWorkflow(rawInput: unknown): Promise<void> {capabilities: prepared.input.capabilities,deploymentId: prepared.deploymentId,history: interrupted.history,- initialInput:- prepared.input.delivery === undefined- ? undefined- : { ...prepared.input.delivery, caller: undefined },- awaitFirstMessage: false,+ start: {+ input:+ prepared.input.delivery === undefined+ ? undefined+ : { ...prepared.input.delivery, caller: undefined },+ kind: "turn",+ },retention: prepared.input.retention,serializedContext: interrupted.serializedContext,sessionId,diff --git a/packages/eve/src/execution/session/active-turn.ts b/packages/eve/src/execution/session/active-turn.tsindex eff8cb144..ab6317677 100644--- a/packages/eve/src/execution/session/active-turn.ts+++ b/packages/eve/src/execution/session/active-turn.ts@@ -53,6 +53,8 @@ export class ActiveTurn {private steeringController = new AbortController();/** The delegated caller of the latest message the turn read. */caller: TurnCaller | undefined;+ /** A step of this turn compacted the history. */+ compacted = false;constructor(input: SessionExecutionInput,diff --git a/packages/eve/src/execution/session/entry-handoff-lifetime.integration.test.ts b/packages/eve/src/execution/session/entry-handoff-lifetime.integration.test.tsindex 9617eb24b..e0b7abd13 100644--- a/packages/eve/src/execution/session/entry-handoff-lifetime.integration.test.ts+++ b/packages/eve/src/execution/session/entry-handoff-lifetime.integration.test.ts@@ -1,5 +1,5 @@import { DEFAULT_SESSION_TIMEOUT_MS } from "#execution/session/timeout.js";-import { describe, expect, it, vi } from "vitest";+import { assert, describe, expect, it, vi } from "vitest";import { getWorld, resumeHook, start } from "#internal/workflow/runtime.js";import { hydrateStepReturnValue, hydrateWorkflowArguments } from "@workflow/core/serialization";import { captureTurnEvents } from "#internal/testing/events.js";@@ -214,6 +214,133 @@ describe("workflowEntry integration", () => {},);});++ describe("compaction handoff", () => {+ it("moves each compacted session to a fresh run on its deployment and keeps its deadline", async () => {+ const output = captureConsoleOutput();+ const runtime = await createTestRuntime({ agent: { name: "workflow-entry-compaction" } });++ await runtime.run(async () => {+ const anchor = await start(workflowEntry, [+ {+ kind: "initial",+ sessionTimeoutMs: 60_000,+ ownerDeploymentId: "dpl_a",+ input: { message: "Alice starts a long planning session." },+ serializedContext: buildSerializedContext({+ acceptedDeploymentId: "dpl_a",+ channelKind: "http",+ }),+ },+ ]);+ const stream = captureTurnEvents(anchor);+ const world = await getWorld();+ const workflowRuntime = createWorkflowRuntime({+ compiledArtifactsSource: createBundledRuntimeCompiledArtifactsSource(),+ });+ const inboxToken = sessionInboxHookToken(sessionCommandHookToken(anchor.runId));+ const compactTo = async (previousOwnerRunId: string) => {+ await workflowRuntime.dispatchSession({+ command: { kind: "compact" },+ sessionId: anchor.runId,+ });+ const events = await stream.nextTurn();+ expect(events.map((event) => event.type)).toContain("compaction.completed");+ let owner: Awaited<ReturnType<typeof waitForCommandHookOwner>> | undefined;+ await vi.waitFor(async () => {+ owner = await waitForCommandHookOwner(inboxToken);+ expect(owner.runId).not.toBe(previousOwnerRunId);+ });+ return owner!;+ };+ let completed = false;+ try {+ expect((await stream.nextTurn()).at(-1)?.type).toBe("session.waiting");+ await waitForParkedTurnStep(anchor.runId);+ const originalTimer = await readSessionTimer(anchor.runId);++ const successor = await compactTo(anchor.runId);+ expect((await readSessionTimer(successor.runId)).deadline).toEqual(+ originalTimer.deadline,+ );+ await vi.waitFor(async () =>+ expect((await world.runs.get(originalTimer.runId)).status).toBe("cancelled"),+ );+ await vi.waitFor(async () => {+ const anchorHooks = await world.hooks.list({ runId: anchor.runId });+ expect(+ anchorHooks.data+ .map((hook) => hook.token)+ .filter((token) => !token.startsWith("abrt_")),+ ).toEqual([`${anchor.runId}:anchor`]);+ });++ // The next message on the same deployment runs on the successor and+ // streams on the original run.+ await workflowRuntime.dispatchSession({+ command: handoffFollowUp("dpl_a", "Bob asks for the next milestone.", "delivery-b"),+ sessionId: anchor.runId,+ });+ const followUp = await stream.nextTurn();+ expect(+ followUp.some(+ (event) =>+ event.type === "message.completed" &&+ event.data.message?.includes("Bob asks for the next milestone.") === true,+ ),+ ).toBe(true);+ await waitForParkedTurnStep(successor.runId);++ // A message sent right behind the compaction is answered, and+ // the session still moves. An intermediate owner exits after its own+ // compaction handoff.+ await workflowRuntime.dispatchSession({+ command: { kind: "compact" },+ sessionId: anchor.runId,+ });+ await workflowRuntime.dispatchSession({+ command: handoffFollowUp("dpl_a", "Alice confirms the milestone.", "delivery-c"),+ sessionId: anchor.runId,+ });+ expect((await stream.nextTurn()).map((event) => event.type)).toContain(+ "compaction.completed",+ );+ expect(+ (await stream.nextTurn()).some(+ (event) =>+ event.type === "message.completed" &&+ event.data.message?.includes("Alice confirms the milestone.") === true,+ ),+ ).toBe(true);+ let nextOwner: Awaited<ReturnType<typeof waitForCommandHookOwner>> | undefined;+ await vi.waitFor(async () => {+ nextOwner = await waitForCommandHookOwner(inboxToken);+ expect(nextOwner.runId).not.toBe(successor.runId);+ });+ assert(nextOwner !== undefined);+ await vi.waitFor(async () =>+ expect((await world.runs.get(successor.runId)).status).toBe("completed"),+ );+ expect((await world.runs.get(anchor.runId)).status).toBe("running");+ expect((await readSessionTimer(nextOwner.runId)).deadline).toEqual(+ originalTimer.deadline,+ );++ await workflowRuntime.dispatchSession({+ command: { kind: "reset", reason: "compaction handoff test" },+ sessionId: anchor.runId,+ });+ await expect(anchor.returnValue).resolves.toEqual({ output: "" });+ completed = true;+ } finally {+ stream.dispose();+ if (!completed) await anchor.cancel();+ }+ });+ // Successors start on the test's synthetic deployment, not the local world's.+ expect(output.unexpected(workflowSdkNotice.unpinnedDelivery)).toEqual([]);+ });+ });});async function readSessionTimer(ownerRunId: string): Promise<{ runId: string; deadline: Date }> {diff --git a/packages/eve/src/execution/session/entry-input.ts b/packages/eve/src/execution/session/entry-input.tsindex 3a897eb14..bf3939dec 100644--- a/packages/eve/src/execution/session/entry-input.ts+++ b/packages/eve/src/execution/session/entry-input.ts@@ -22,12 +22,33 @@ export interface InitialWorkflowEntryInput {readonly serializedContext: Record<string, unknown>;}-/** A successor owner started by a previous owner during a deployment handoff. */-export interface HandoffWorkflowEntryInput {+/** Why a previous owner started a successor, and what the successor does first. */+export type SessionHandoffStart =+ | {+ /** The one delivery that triggered a deployment handoff; processed before any later arrival. */+ readonly delivery: DeliverHookPayload;+ readonly reason?: undefined;+ }+ | {+ /**+ * The previous owner compacted the session and moved it to a fresh run on+ * its own deployment, so no single run's event log grows with the+ * session.+ */+ readonly reason: "compaction";+ /**+ * The lone delivery that arrived before the owner could move, processed+ * first. Without one, the successor parks until the next input arrives.+ */+ readonly delivery?: DeliverHookPayload;+ /** Compaction does not extend the session's lifetime. */+ readonly sessionTimeoutDeadline?: Date;+ };++/** A successor owner started by a previous owner during a handoff. */+export type HandoffWorkflowEntryInput = SessionHandoffStart & {readonly activationToken: string;readonly checkpoint: SessionCheckpoint;- /** The one delivery that triggered the handoff; processed before any later arrival. */- readonly delivery: DeliverHookPayload;/** Omitted by version 1 sources, whose hooks cannot safely be force-claimed. */readonly handoffVersion?: number;readonly kind: "handoff";@@ -35,7 +56,7 @@ export interface HandoffWorkflowEntryInput {readonly sessionWritable: WritableStream<Uint8Array>;/** Stable public identity; also the original run that anchors the stream. */readonly sessionId: string;-}+};export type WorkflowEntryInput = InitialWorkflowEntryInput | HandoffWorkflowEntryInput;diff --git a/packages/eve/src/execution/session/entry.ts b/packages/eve/src/execution/session/entry.tsindex 91227f2e0..17667d374 100644--- a/packages/eve/src/execution/session/entry.ts+++ b/packages/eve/src/execution/session/entry.ts@@ -133,8 +133,10 @@ async function bootInitialOwner(capabilities: serializedContext["eve.capabilities"] as SessionCapabilities | undefined,deploymentId: input.ownerDeploymentId,history: sessionCreation.value.history,- initialInput: createInitialDelivery(input, serializedContext),- awaitFirstMessage: input.input.message === undefined,+ start:+ input.input.message === undefined+ ? { kind: "first-message" }+ : { input: createInitialDelivery(input, serializedContext), kind: "turn" },retention: input.retention,serializedContext,sessionId,@@ -200,22 +202,26 @@ async function bootHandoffOwner(if (childRunIdsToStop.length > 0) {await stopUntrackedChildSessionsStep({ runIds: childRunIdsToStop, sessionId });}+ const compaction = input.reason === "compaction";return {inbox,session: {anchor: { kind: "successor" },- caller: input.delivery.caller,+ caller: input.delivery?.caller,capabilities: checkpoint.capabilities,deploymentId: input.ownerDeploymentId,history: checkpoint.history,- initialInput: input.delivery,- awaitFirstMessage: false,+ start:+ input.delivery === undefined ? { kind: "parked" } : { input: input.delivery, kind: "turn" },retention: checkpoint.retention,serializedContext,sessionId,sessionState: checkpoint.sessionState,sessionTimeoutMs: checkpoint.sessionTimeoutMs,- sessionTimeoutDeadline: sessionTimeoutDeadline(checkpoint.sessionTimeoutMs, Date.now()),+ // A deployment handoff renews the configured lifetime; compaction keeps the deadline.+ sessionTimeoutDeadline: compaction+ ? input.sessionTimeoutDeadline+ : sessionTimeoutDeadline(checkpoint.sessionTimeoutMs, Date.now()),sessionWritable: input.sessionWritable,},};diff --git a/packages/eve/src/execution/session/handoff.test.ts b/packages/eve/src/execution/session/handoff.test.tsindex 93544686c..bf23f8d8f 100644--- a/packages/eve/src/execution/session/handoff.test.ts+++ b/packages/eve/src/execution/session/handoff.test.ts@@ -71,6 +71,41 @@ describe("SessionHandoff", () => {expect(startSessionOwnerStepMock).not.toHaveBeenCalled();});+ it("moves a compacted session to this deployment with the delivery that arrived first", async () => {+ installActivation({ kind: "active" });+ startSessionOwnerStepMock.mockResolvedValue(undefined);+ const sessionTimeoutDeadline = new Date("2026-11-01T00:00:00.000Z");+ const trigger = selection("deployment-a");++ await expect(+ createHandoff(createInbox()).tryTransfer(trigger, state(), {+ compaction: { sessionTimeoutDeadline },+ }),+ ).resolves.toEqual({ kind: "transferred" });+ expect(startSessionOwnerStepMock).toHaveBeenCalledWith(+ expect.objectContaining({+ delivery: trigger.delivery,+ reason: "compaction",+ sessionTimeoutDeadline,+ targetDeploymentId: "deployment-a",+ }),+ );+ });++ it("moves a compacted session to a newer deployment as a deployment handoff", async () => {+ installActivation({ kind: "active" });+ startSessionOwnerStepMock.mockResolvedValue(undefined);++ await expect(+ createHandoff(createInbox()).tryTransfer(selection("deployment-b"), state(), {+ compaction: { sessionTimeoutDeadline: new Date("2026-11-01T00:00:00.000Z") },+ }),+ ).resolves.toEqual({ kind: "transferred" });+ const [start] = startSessionOwnerStepMock.mock.calls[0] as [Record<string, unknown>];+ expect(start).toMatchObject({ targetDeploymentId: "deployment-b" });+ expect(start).not.toHaveProperty("reason");+ });+it("retains ownership when the selection was not a lone fresh conversational delivery", async () => {installActivation({ kind: "active" });const inbox = createInbox();diff --git a/packages/eve/src/execution/session/handoff.ts b/packages/eve/src/execution/session/handoff.tsindex 2a8a0759f..7b2f0ca28 100644--- a/packages/eve/src/execution/session/handoff.ts+++ b/packages/eve/src/execution/session/handoff.ts@@ -8,7 +8,7 @@ import { claimHookOwnership, disposeHook } from "#execution/hook-ownership.js";import { sessionHookTokens } from "#execution/session/hook-tokens.js";import type { SessionInboxHandle, SessionInboxPayload } from "#execution/session-inbox/inbox.js";import type { TurnSelection } from "#execution/session/input-queue.js";-import type { WorkflowEntryResult } from "#execution/session/entry-input.js";+import type { SessionHandoffStart, WorkflowEntryResult } from "#execution/session/entry-input.js";import { startSessionOwnerStep } from "#execution/workflow-runtime.js";import { sessionHandoffMarkerToken } from "#execution/session-inbox/address.js";import {@@ -56,21 +56,6 @@ export type SessionOwnerActivation =readonly payloads: readonly SessionInboxPayload[];};-type SessionTransferOutcome =- | { readonly kind: "transferred" }- | {- readonly kind: "retained";- readonly reason:- | "same-deployment"- | "missing-deployment"- | "not-idle"- | "busy"- | "accepted-during-release"- | "activation-failed"- | "checkpoint-incompatible"- | "known-incompatible";- };-interface SessionHandoffInput {readonly checkpoint: Omit<SessionCheckpoint,@@ -86,9 +71,35 @@ export function sessionAnchorToken(sessionId: string): string {return `${sessionId}:anchor`;}+type SessionTransferOutcome =+ | { readonly kind: "transferred" }+ | { readonly kind: "retained"; readonly reason: SessionRetainedReason };++type SessionRetainedReason =+ | "same-deployment"+ | "missing-deployment"+ | "not-idle"+ | "busy"+ | "accepted-during-release"+ | "activation-failed"+ | "checkpoint-incompatible"+ | "known-incompatible";++/** A compaction handoff the owner owes; the successor keeps this deadline. */+export interface CompactionHandoff {+ readonly sessionTimeoutDeadline: Date | undefined;+}++type SessionTransferState = Pick<+ SessionCheckpoint,+ "history" | "serializedContext" | "sessionState"+>;+/**- * The sole boundary for moving an idle session to another exact deployment.- * Constructed once per owner; `tryTransfer()` is attempted per eligible selection.+ * The sole boundary for moving an idle session to a successor run: on another+ * exact deployment when newer code accepts a delivery, or on this deployment+ * after compaction so no single run's event log grows with the session.+ * Constructed once per owner; each `try*` method attempts one transfer.* When the upstream atomic hook-handoff primitive lands, only this class changes.** Skipping known-incompatible targets requires this owner run to execute the@@ -108,21 +119,56 @@ export class SessionHandoff {}/**- * Attempts to move the session to the selected delivery's deployment. The- * outcome states whether the successor activated or this owner retained the- * session. Candidate failures recover locally rather than escaping.+ * Attempts to move the session to the selected delivery's deployment. When a+ * compaction handoff is due and that deployment is this one or unknown, the+ * session moves to a fresh run here instead. The outcome states whether the+ * successor activated or this owner retained the session. Candidate failures+ * recover locally rather than escaping.*/async tryTransfer(selection: TurnSelection,- state: Pick<SessionCheckpoint, "history" | "serializedContext" | "sessionState">,+ state: SessionTransferState,+ options: { readonly compaction?: CompactionHandoff } = {},): Promise<SessionTransferOutcome> {- const { deploymentId, inbox } = this.input;- const targetDeploymentId = readAcceptedDeploymentId(selection.delivery);+ const { delivery } = selection;+ const targetDeploymentId = readAcceptedDeploymentId(delivery);+ const sameDeployment =+ targetDeploymentId === undefined || targetDeploymentId === this.input.deploymentId;+ if (sameDeployment && options.compaction !== undefined) {+ if (!selection.handoffEligible) return { kind: "retained", reason: "busy" };+ return await this.tryCompactionTransfer(state, { ...options.compaction, delivery });+ }if (targetDeploymentId === undefined) return { kind: "retained", reason: "missing-deployment" };- if (targetDeploymentId === deploymentId) return { kind: "retained", reason: "same-deployment" };+ if (targetDeploymentId === this.input.deploymentId)+ return { kind: "retained", reason: "same-deployment" };if (this.incompatibleTargetDeploymentIds.has(targetDeploymentId))return { kind: "retained", reason: "known-incompatible" };if (!selection.handoffEligible) return { kind: "retained", reason: "busy" };+ return await this.transfer(state, targetDeploymentId, { delivery });+ }++ /**+ * Attempts to move a session that compacted to a fresh run on this+ * deployment. Without a delivery the caller guarantees no input is waiting,+ * and the successor parks until the next one arrives. The successor keeps+ * the session's deadline.+ */+ async tryCompactionTransfer(+ state: SessionTransferState,+ compaction: CompactionHandoff & { readonly delivery?: DeliverHookPayload },+ ): Promise<SessionTransferOutcome> {+ const { deploymentId } = this.input;+ if (this.incompatibleTargetDeploymentIds.has(deploymentId))+ return { kind: "retained", reason: "known-incompatible" };+ return await this.transfer(state, deploymentId, { ...compaction, reason: "compaction" });+ }++ private async transfer(+ state: SessionTransferState,+ targetDeploymentId: string,+ start: SessionHandoffStart,+ ): Promise<SessionTransferOutcome> {+ const { inbox } = this.input;if (!(await isSessionIdleForHandoffStep({ sessionState: state.sessionState })))return { kind: "retained", reason: "not-idle" };@@ -153,11 +199,7 @@ export class SessionHandoff {}let acceptedByFailedCandidate: readonly SessionInboxPayload[] = [];try {- const activation = await this.startAndActivate(- checkpoint,- selection.delivery,- targetDeploymentId,- );+ const activation = await this.startAndActivate(checkpoint, start, targetDeploymentId);if (activation.kind === "active") return { kind: "transferred" };acceptedByFailedCandidate = activation.payloads;if (activation.kind === "incompatible") {@@ -198,7 +240,7 @@ export class SessionHandoff {/** Starts the candidate and waits for it to activate or fail. */private async startAndActivate(checkpoint: SessionCheckpoint,- delivery: DeliverHookPayload,+ start: SessionHandoffStart,targetDeploymentId: string,): Promise<SessionOwnerActivation> {const activation = createHook<SessionOwnerActivation>({@@ -207,10 +249,10 @@ export class SessionHandoff {await claimHookOwnership(activation);try {await startSessionOwnerStep({+ ...start,activationToken: activation.token,anchorRunId: this.input.sessionId,checkpoint,- delivery,targetDeploymentId,});return await activation;diff --git a/packages/eve/src/execution/session/program.ts b/packages/eve/src/execution/session/program.tsindex 69f061d2e..0e57a091f 100644--- a/packages/eve/src/execution/session/program.ts+++ b/packages/eve/src/execution/session/program.ts@@ -18,7 +18,11 @@ import { settleCancelledTurnStep } from "#execution/settle-cancelled-turn-step.jimport { finalizeSession, type SessionTerminalOutcome } from "#execution/session/finalization.js";import { type SessionInboxHandle } from "#execution/session-inbox/inbox.js";import { createSessionTimeoutControl } from "#execution/session/timeout-control.js";-import { SessionHandoff, sessionAnchorToken } from "#execution/session/handoff.js";+import {+ type CompactionHandoff,+ SessionHandoff,+ sessionAnchorToken,+} from "#execution/session/handoff.js";import { signalSessionAnchorStep } from "#execution/session/handoff-steps.js";import type { WorkflowEntryResult } from "#execution/session/entry-input.js";@@ -42,15 +46,22 @@ export type SessionAnchor =}| { readonly kind: "successor" };+/** What an owner does before it first waits on its inbox. */+export type SessionStart =+ /** Runs a turn first; `input` is absent for a session started without a message. */+ | { readonly kind: "turn"; readonly input: DeliverHookPayload | undefined }+ /** A prewarmed session parks on the inbox before any session-scoped lifecycle work. */+ | { readonly kind: "first-message" }+ /** A successor that received a settled session waits for its next input. */+ | { readonly kind: "parked" };+export interface SessionBoot {readonly anchor: SessionAnchor;readonly caller: TurnCaller | undefined;readonly capabilities?: SessionCapabilities;readonly deploymentId: string;readonly history: HarnessModelMessage[];- readonly initialInput: DeliverHookPayload | undefined;- /** Parks on the inbox before any session-scoped lifecycle work. */- readonly awaitFirstMessage: boolean;+ readonly start: SessionStart;readonly retention?: AgentWorkflowRetentionDefinition;readonly serializedContext: Record<string, unknown>;readonly sessionId: string;@@ -232,20 +243,44 @@ async function runSessionLoop(};let turnIndex = 0;+ // Set when a turn compacts and kept until the session moves to a fresh run,+ // so this run's event log does not keep growing.+ let compactionHandoffDue = false;const runTurn = async (payload: TurnStepPayload | undefined): Promise<TurnOutcome> => {const caller = progress.caller;progress.turnId = `turn_${String(turnIndex++)}`;const outcome = await execution.runTurn(payload, { caller });if (outcome.caller !== undefined) progress.caller = outcome.caller;+ if (outcome.compacted === true) compactionHandoffDue = true;return outcome;};+ const transferState = () => ({+ history: cursor.history,+ serializedContext: cursor.serializedContext,+ sessionState: cursor.sessionState,+ });+ const dueCompactionHandoff = (): CompactionHandoff | undefined =>+ compactionHandoffDue &&+ progress.caller === undefined &&+ workingTasks(sessionTaskTable(cursor)).length === 0+ ? { sessionTimeoutDeadline: boot.sessionTimeoutDeadline }+ : undefined;+ /**+ * Hands a session that compacted to a fresh run on this deployment while+ * nothing is waiting. When input arrives first, the next lone delivery+ * carries the handoff instead; see `runDeliveredTurn`.+ */+ const tryCompactionHandoff = async (): Promise<SessionLoopOutcome | undefined> => {+ const compaction = dueCompactionHandoff();+ if (compaction === undefined || queue.pendingCount > 0 || inbox.hasPending()) return undefined;+ const transfer = await handoff.tryCompactionTransfer(transferState(), compaction);+ return transfer.kind === "transferred" ? transfer : undefined;+ };const runDeliveredTurn = async (next: Extract<NextTurnInstruction, { kind: "turn" }>,): Promise<SessionActionResult> => {- const transfer = await handoff.tryTransfer(next, {- history: cursor.history,- serializedContext: cursor.serializedContext,- sessionState: cursor.sessionState,+ const transfer = await handoff.tryTransfer(next, transferState(), {+ compaction: dueCompactionHandoff(),});if (transfer.kind === "transferred") return transfer;if (next.delivery.caller !== undefined) progress.caller = next.delivery.caller;@@ -277,11 +312,17 @@ async function runSessionLoop(}};const runInitialAction = async (): Promise<SessionActionResult> => {- if (boot.awaitFirstMessage) return await awaitPrewarmedAction();- const action = await runTurn(- boot.initialInput === undefined ? undefined : { delivery: boot.initialInput },- );- return { action, kind: "action" };+ switch (boot.start.kind) {+ case "first-message":+ return await awaitPrewarmedAction();+ case "parked":+ return { action: { kind: "park" }, kind: "action" };+ case "turn": {+ const { input } = boot.start;+ const action = await runTurn(input === undefined ? undefined : { delivery: input });+ return { action, kind: "action" };+ }+ }};try {@@ -321,6 +362,9 @@ async function runSessionLoop(progress.caller = undefined;}+ const transferred = await tryCompactionHandoff();+ if (transferred !== undefined) return transferred;+const next = await nextParkedActivity();switch (next.kind) {diff --git a/packages/eve/src/execution/session/turn-step-types.ts b/packages/eve/src/execution/session/turn-step-types.tsindex d1d2dac55..076259824 100644--- a/packages/eve/src/execution/session/turn-step-types.ts+++ b/packages/eve/src/execution/session/turn-step-types.ts@@ -78,7 +78,10 @@ export type DurableStepResult = (readonly settled?: SettledTurn;}) &- DurableStepResultFields;+ DurableStepResultFields & {+ /** The step compacted the history. */+ readonly compacted?: true;+ };/** What `turnStep` returns: its result, with the session state as a delta. */export type TurnStepResult = WithSessionStateDelta<DurableStepResult>;@@ -90,6 +93,8 @@ export type TurnOutcome = {* later message awaits its reply at its own address, so the turn reports there.*/readonly caller?: TurnCaller;+ /** A step of the turn compacted the history. */+ readonly compacted?: true;} & (| {readonly kind: "done";diff --git a/packages/eve/src/execution/session/turn-step.ts b/packages/eve/src/execution/session/turn-step.tsindex 02b833488..402bd9b8f 100644--- a/packages/eve/src/execution/session/turn-step.ts+++ b/packages/eve/src/execution/session/turn-step.ts@@ -49,7 +49,7 @@ import {type UserModelMessage,} from "#harness/messages.js";import { consumeDeferredStepInput } from "#harness/pending-input-batches.js";-import type { HarnessSession, StepInput, StepResult } from "#harness/types.js";+import type { HandleEventFn, HarnessSession, StepInput, StepResult } from "#harness/types.js";import type {DurableStepResult,TurnStepInput,@@ -262,7 +262,8 @@ async function runSessionStep(input: TurnStepInput): Promise<DurableStepResult>try {const dynamicConnections = bindDynamicConnections(ctx, bundle.resolvedAgent);const effectiveNode = { ...bundle.graph.root, turnAgent: effectiveAgent.turnAgent };- const handleEvent = createTurnEventHandler({+ let compacted = false;+ const emitTurnEvent = createTurnEventHandler({abortSignal,bundle,canCancelTurn: input.input?.control === undefined,@@ -274,6 +275,10 @@ async function runSessionStep(input: TurnStepInput): Promise<DurableStepResult>instrumentation,publisher,});+ const handleEvent: HandleEventFn = async (event, messages) => {+ if (event.type === "compaction.completed") compacted = true;+ await emitTurnEvent(event, messages);+ };const previousAdapterState =delivery !== undefined && !isHarnessBetweenTurns(initialSession)? structuredClone(adapterCtx.state)@@ -571,7 +576,7 @@ async function runSessionStep(input: TurnStepInput): Promise<DurableStepResult>const durableResult = resolveSessionStepResult(stepResult, nextSerializedContext);if (durableResult.action === "done") await publisher.writer.close();- return durableResult;+ return compacted ? { ...durableResult, compacted: true } : durableResult;} finally {publisher.writer.release();}diff --git a/packages/eve/src/execution/session/turn.test.ts b/packages/eve/src/execution/session/turn.test.tsindex 5ed262294..f9adba77a 100644--- a/packages/eve/src/execution/session/turn.test.ts+++ b/packages/eve/src/execution/session/turn.test.ts@@ -100,18 +100,7 @@ const routeWork = stepWork<Parameters<typeof routeDeliverToChildren>[0], RoutedDdescribe("SessionExecution checkpoints", () => {it("retains the durable steering signal across steps until a correction uses it", async () => {- const inbox: SessionInbox = {- claimedTokens: [],- claimSessionHook: vi.fn(),- claimSessionHooks: vi.fn(),- drain: () => [],- hasPending: () => false,- whenPending: () => new Promise<void>(() => {}),- next: vi.fn(),- restore: vi.fn(),- onDelivery: () => () => {},- onInterrupt: () => () => {},- };+ const inbox = idleInbox();let signal: AbortSignal | undefined;vi.mocked(turnStep).mockReset()@@ -138,6 +127,32 @@ describe("SessionExecution checkpoints", () => {await createExecution({ inbox, sessionState: state("") }).runTurn(undefined);expect(turnStep).toHaveBeenCalledTimes(2);});++ it("reports a compaction from an earlier step when the turn settles", async () => {+ vi.mocked(turnStep)+ .mockReset()+ .mockImplementationOnce(+ turnStepWork(async (input) => ({+ action: "continue",+ compacted: true,+ serializedContext: input.serializedContext,+ sessionState: input.sessionState,+ })),+ )+ .mockImplementationOnce(+ turnStepWork(async (input) => ({+ action: "park",+ serializedContext: input.serializedContext,+ sessionState: input.sessionState,+ settled: { output: "Alice's plan is ready." },+ })),+ );+ const outcome = await createExecution({+ inbox: idleInbox(),+ sessionState: state(""),+ }).runTurn(undefined);+ expect(outcome).toMatchObject({ compacted: true, kind: "park" });+ });it("binds the delegated caller on the turn's first step only", async () => {const inbox: SessionInbox = {claimedTokens: [],@@ -1424,6 +1439,21 @@ function createCursor(input: {});}+function idleInbox(): SessionInbox {+ return {+ claimedTokens: [],+ claimSessionHook: vi.fn(),+ claimSessionHooks: vi.fn(),+ drain: () => [],+ hasPending: () => false,+ whenPending: () => new Promise<void>(() => {}),+ next: vi.fn(),+ restore: vi.fn(),+ onDelivery: () => () => {},+ onInterrupt: () => () => {},+ };+}+function createExecution(input: {readonly capabilities?: SessionCapabilities;readonly cursor?: SessionStateCursor;diff --git a/packages/eve/src/execution/session/turn.ts b/packages/eve/src/execution/session/turn.tsindex 91e1c42ba..b15861022 100644--- a/packages/eve/src/execution/session/turn.ts+++ b/packages/eve/src/execution/session/turn.ts@@ -108,7 +108,11 @@ export class SessionExecution {if (outcome.kind === "park" && outcome.settled !== undefined) {await cancelWorkingTasks(this.input.cursor, "turn_ended");}- return turn.caller === undefined ? outcome : { ...outcome, caller: turn.caller };+ return {+ ...outcome,+ ...(turn.caller !== undefined && { caller: turn.caller }),+ ...(turn.compacted && { compacted: true }),+ };} finally {turn.dispose();}@@ -158,6 +162,7 @@ export class SessionExecution {steeringSignal: turn.steeringSignal,}),);+ if (result.compacted === true) turn.compacted = true;const pendingCallIds =result.action === "park" ? result.pendingCoordinationCallIds : undefined;const turnCompleted = result.action === "park" && result.settled !== undefined;diff --git a/packages/eve/src/execution/workflow-runtime.ts b/packages/eve/src/execution/workflow-runtime.tsindex be530c46f..c0681f950 100644--- a/packages/eve/src/execution/workflow-runtime.ts+++ b/packages/eve/src/execution/workflow-runtime.ts@@ -9,7 +9,6 @@ import {import type {CancelTurnInput,CancelTurnResult,- DeliverHookPayload,DispatchContinuationInput,DispatchSessionInput,GetEventStreamOptions,@@ -52,6 +51,7 @@ import {SESSION_HANDOFF_VERSION,type HandoffWorkflowEntryInput,type InitialWorkflowEntryInput,+ type SessionHandoffStart,} from "#execution/session/entry-input.js";import type { SessionCheckpoint } from "#execution/session/handoff.js";import { walkCauseChain } from "#shared/errors.js";@@ -253,35 +253,35 @@ export function createWorkflowRuntime(config: {};}-export interface SessionOwnerStartInput {+export type SessionOwnerStartInput = SessionHandoffStart & {readonly activationToken: string;/** Original run whose stream stays the public session stream. */readonly anchorRunId: string;readonly checkpoint: SessionCheckpoint;- readonly delivery: DeliverHookPayload;readonly targetDeploymentId: string;-}+};/** Starts a successor owner and binds its output to the original session stream. */export async function startSessionOwnerStep(input: SessionOwnerStartInput): Promise<void> {"use step";+ const { activationToken, anchorRunId, checkpoint, targetDeploymentId, ...start } = input;const workflowInput: HandoffWorkflowEntryInput = {- activationToken: input.activationToken,- checkpoint: input.checkpoint,- delivery: input.delivery,+ ...start,+ activationToken,+ checkpoint,handoffVersion: SESSION_HANDOFF_VERSION,kind: "handoff",- ownerDeploymentId: input.targetDeploymentId,- sessionWritable: getRun(input.anchorRunId).getWritable<Uint8Array>(),- sessionId: input.anchorRunId,+ ownerDeploymentId: targetDeploymentId,+ sessionWritable: getRun(anchorRunId).getWritable<Uint8Array>(),+ sessionId: anchorRunId,};await startWorkflowOnDeployment(workflowEntryReference,[workflowInput],- input.targetDeploymentId,- input.checkpoint.retention === undefined+ targetDeploymentId,+ checkpoint.retention === undefined? undefined- : { experimental_retention: input.checkpoint.retention },+ : { experimental_retention: checkpoint.retention },);}diff --git a/research/single-workflow-session-upgrades.md b/research/single-workflow-session-upgrades.mdindex 61263c616..cab98fb99 100644--- a/research/single-workflow-session-upgrades.md+++ b/research/single-workflow-session-upgrades.md@@ -1,7 +1,7 @@---issue: https://github.com/vercel/eve/issues/876status: implemented-last_updated: "2026-09-15"+last_updated: "2026-10-02"---# Single-workflow sessions with ingress-driven upgrades@@ -151,7 +151,8 @@ Deferring to the next idle delivery costs nothing in protocol and only delays cobusy sessions.HITL responses, tool and subagent results, cancellation, reset, clear, and compact never trigger-upgrades. eve never cancels or restarts work to make a session eligible.+upgrades. eve never cancels or restarts work to make a session eligible. Compaction does trigger a+same-deployment handoff; see [Compaction handoff](#compaction-handoff).### Exact deployment selection@@ -235,6 +236,33 @@ available and delete the anchor. Keep the anchor mechanics behind the session rupublic identity, streaming, and cursors are unaffected either way. Global streams are follow-upwork, not a prerequisite.+## Compaction handoff++Workflow replay reads every step output of a run, so one owner that serves a session for its whole+life accumulates an unbounded event log. Compaction is the natural reset point: it rewrites history+to a summary plus a recent window, and it is already a slow, infrequent operation.++When any step of a turn (automatic or an explicit `compact` control) reports `compacted`, the owner+latches a handoff. At the next idle boundary after the turn settles, it moves the session to a+successor on its own deployment through the same `SessionHandoff` transaction:++- Eligibility adds to the shared idle check: no queued or buffered input, no unsettled delegated+ caller, and no working tasks. The latch holds until a transfer succeeds; like deployment+ handoffs, a failed successor is retried at the next opportunity, and an incompatible one is+ remembered.+- The successor input carries `reason: "compaction"`. From the eager path it carries no delivery,+ so the successor claims the hook set, activates, and parks instead of running a turn.+- A client that replies the moment `session.waiting` arrives races that eager attempt, which+ then abandons the transfer and restores the message. While the latch holds, a lone+ handoff-eligible delivery therefore carries the transfer itself, exactly like a deployment+ signal: the successor runs that delivery first. A delivery accepted by another deployment+ takes the ordinary deployment handoff instead.+- The successor keeps the existing deadline. Compaction is a storage concern and never extends the+ session lifetime, unlike a deployment handoff.++The anchor's log stops growing at the first handoff, and each later owner's log spans at most the+turns between two compactions.+## Open questions and upstream request### The no-owner interval