Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -971,6 +971,17 @@ so merge ranges from all mounted editors before replacing a registry entry.
process answers nothing after it releases the lease, and refuses nothing it was routed.
Before SIGTERM's cut it keeps serving and starts no new Planner turn. Do not move a step
across the release or the listener stop, and do not make readiness depend on a query.
A running remote turn whose client offered `turn-handover` is handed over at the turn-wait's
end instead of cut (`Chat.handTurnOver`, `RemoteSession.handOver`): its frames are dropped
unanswered from then on, every write it called finishes first (never stopped half way), and the
checkpoint goes into its `planner_link_holds` session (`turn`), written before the release; a
failed write makes the process end the turn itself and abort the client. The next process takes
it out of the row before showing the hold, holds it open in Chat (`busy`, from `Chat.restore`),
answers the client's `resume` only then, and applies frames after its cursor once
(`docs/agent-connection.md`). Any other turn is cut; a person's message it cut waits in line
again (`requeueCut`) for one automatic pick-up: a retry if it called only reads (`READ_TOOLS`),
a continuation from the saved Atomic session if it called a write, else nothing but Retry.
`Chat.restore` says a restart interrupted any reply it ends mid-way.
`Chat.close` waits for every send already admitted before it marks the Chat closed, so a
message being saved at the cut is saved and answered; a `chat:send` that reaches a closed Chat
of a stopping process (`holdStarts`) is answered with nothing, never "chat is closed", because
Expand Down
23 changes: 23 additions & 0 deletions apps/server/src/agent/job-scope.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,29 @@ export const CHILD_TOOLS: ReadonlySet<string> = new Set([
"anchor_child",
]);

/**
* The host tools that change nothing: running one again, or having run one, has no effect anyone
* can see. Every other tool, one this list does not name included, counts as a write.
*/
export const READ_TOOLS: ReadonlySet<string> = new Set([
"read_plan",
"read_reference",
"list_background_jobs",
"read_background_job",
"read_implementation_graph",
"list_children",
"read_child",
"list_investigations",
"read_investigation",
"read_decision_scope",
"read_repository_file",
"list_repository_tree",
"search_repository",
"repository_history",
"list_pull_requests",
"pull_request_read",
]);

export const INVESTIGATION_READS: ReadonlySet<string> = new Set([
"list_investigations",
"read_investigation",
Expand Down
58 changes: 58 additions & 0 deletions apps/server/src/chat/handover.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
/**
* What Chat keeps of a Planner turn its process handed to the next one (`turn-handover`), for the
* next process to go on with it in the same entries, or to end it saying what its writes came to.
* Ids and small values only: the words of its reply are read back from the transcript, which the
* guard says is the one this was written beside.
*/

import { createHash } from "node:crypto";

import type { Chat as Wire } from "@chopin/protocol";
import type { Focus } from "./address";

export type HandedChat = {
turn: Wire.Turn;
writing?: string;
tooling?: string;
/** The harness's text part ids and the entries they write into. */
messageIds: [string, string][];
/** The calls and the entries their rows are filed in. */
toolEntries: [string, string][];
/** The person's message the turn answers, when one began it. */
request?: { entryId: string; userId: string; claimantSessionId?: string; focus?: Focus };
answering?: string;
captured: string[];
/** The entries the turn wrote, by id. */
entries: string[];
/** What those entries held when the process that handed the turn over committed them (`guard`). */
guard: string;
};

/**
* What a turn's entries hold, as a digest: their words, and each call's state and report count.
* A transcript that did not commit what the process handing over had shows a different one, so the
* next process never goes on from a reply with a hole in it.
*/
export function guard(entries: readonly Wire.Entry[], ids: readonly string[]): string {
let wanted = new Set(ids);
let shown = entries.filter(entry => wanted.has(entry.id)).map(entry => [
entry.id,
entry.text,
(entry.tools ?? []).map(
tool => [tool.id, tool.name, tool.status, tool.rev ?? 0, tool.result ?? ""],
),
]);
return createHash("sha256").update(JSON.stringify([ids.length, shown])).digest("hex");
}

/** Whether a value read back from a hold is Chat's part of a handed-over turn. */
export function handedChat(value: unknown): HandedChat | undefined {
if (typeof value !== "object" || value === null) return undefined;
let chat = value as Partial<HandedChat>;
if (
typeof chat.guard !== "string" || !Array.isArray(chat.entries) || !chat.turn
|| typeof chat.turn.id !== "string" || !Array.isArray(chat.messageIds)
|| !Array.isArray(chat.toolEntries) || !Array.isArray(chat.captured)
) return undefined;
return chat as HandedChat;
}
164 changes: 164 additions & 0 deletions apps/server/src/chat/restart-recovery.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,164 @@
/**
* A turn a restart cuts off that cannot be handed to the next process (one run in this process, or
* on a client that takes no hand-over): Chat says so, and a person's message whose reply it cut off
* waits in line again, at the place it was sent, for the next process to pick up once. That process
* runs it again as at first when the cut attempt called nothing but reads, goes on from the agent's
* saved session when it called a write and its harness keeps one, and otherwise leaves the notice
* and its Retry.
*/
import { afterEach, expect, test } from "bun:test";

import * as Chat from "./service";
import {
harness,
installJobCleanup,
JOB,
member,
reopened,
savedLine,
socket,
until,
} from "./job.test-fixtures";

import type { Socket } from "../wire";

installJobCleanup();
afterEach(() => Chat.holdStarts(false));

const WAITS = "A restart interrupted this reply, so @ana's message waits to be answered again.";

function speaking(handle: string): Socket {
return { data: { handle, principalId: `U_${handle}` }, send() {} } as unknown as Socket;
}

/**
* A turn on @ana's message that has made the calls `made` (read_plan reads, refine_decision
* writes), each reported unless `reported` is false: a call made whose result has not come back.
*/
async function running(made: Array<"read_plan" | "refine_decision">, reported = true) {
let h = harness();
await Chat.send(h.context, socket(), member("@chopin write the plan"));
await until(() => h.prompts.length === 1);
h.emit("assistant.message_delta", { messageId: "m1", deltaContent: "Writing" });
made.forEach((toolName, at) => {
h.emit("tool.execution_start", { toolCallId: `call-${at}`, toolName });
if (!reported) return;
h.emit("tool.execution_complete", {
toolCallId: `call-${at}`,
success: true,
result: { content: "{}" },
});
});
await until(() => h.chat.entries.flatMap(entry => entry.tools ?? []).length === made.length);
return h;
}

/** What a restart does once its turn-wait runs out: starts held, the turn cut off. */
async function restart(h: ReturnType<typeof harness>): Promise<void> {
Chat.holdStarts();
Chat.interrupt(h.chat, Chat.RESTART_INTERRUPTED);
await Chat.settled(h.chat);
await until(() => !h.chat.busy);
}

/** The next process: it opens what was saved and starts the line, as `resumeLine` does. */
async function nextProcess(h: ReturnType<typeof harness>) {
Chat.holdStarts(false);
let next = await reopened(h);
Chat.resume(next.context);
return next;
}

test("a reply that only read is run again by the next process, once, as at first, its cut attempt taken out", async () => {
let h = await running(["read_plan"]);
await restart(h);
expect(h.chat.entries.at(-1)?.text).toBe(WAITS);
// Nobody is offered a Retry of a message that waits to be answered.
expect(h.chat.entries.at(-1)?.turnFailure?.request).toBeUndefined();
expect(await savedLine(h)).toEqual(["write the plan"]);

let next = await nextProcess(h);
await until(() => next.prompts.length === 1);
expect(next.prompts[0]).toContain("write the plan");
expect(next.chat.entries.map(entry => entry.text)).toEqual(["write the plan"]);
expect(next.frames).toContainEqual(expect.objectContaining({ kind: "chat:removed" }));
next.emit("assistant.message_delta", { messageId: "m2", deltaContent: "Done." });
next.emit("session.idle");
await until(() => !next.chat.busy);
expect(next.chat.entries.map(entry => entry.text)).toEqual(["write the plan", "Done."]);
});

for (let reported of [true, false]) {
test(`a reply that called a write ${reported ? "that reported" : "that had not reported"} is not run again: it is gone on with from the saved session, told what each call truly came to`, async () => {
let h = await running(["read_plan", "refine_decision"], reported);
h.context.config.harness = "atomic";
h.context.sessionForks = { prepareTurn: () => ({}), finishTurn: () => {} };
await restart(h);
expect(h.chat.entries.at(-1)?.text).toBe(WAITS);

let next = await nextProcess(h);
next.context.config.harness = "atomic";
next.context.sessionForks = { prepareTurn: () => ({}), finishTurn: () => {} };
Chat.resume(next.context);
await until(() => next.prompts.length === 1);
let prompt = next.prompts[0]!;
expect(prompt).toContain("Chopin restarted while you were answering @ana's message");
expect(prompt).toContain(reported ? "- read_plan: it completed" : "- read_plan: No result");
expect(prompt).toContain(
reported
? "- refine_decision: it completed"
: "- refine_decision: No result: a restart interrupted the turn before this call reported one. It may have been applied.",
);
expect(prompt).toContain("Do not repeat a call that took effect");
expect(prompt).not.toContain("write the plan");
// What the cut attempt wrote stays: the reply goes on after it.
expect(next.chat.entries.map(entry => entry.text)).toContain("Writing");
});
}

test("a reply that called a write on a harness that keeps no session is left with the notice and its Retry", async () => {
let h = await running(["refine_decision"]);
await restart(h);
expect(h.chat.entries.at(-1)?.text).toBe(Chat.RESTART_INTERRUPTED);
expect(h.chat.entries.at(-1)?.turnFailure).toMatchObject({ kind: "error" });
expect(h.chat.entries.at(-1)?.turnFailure?.request).toBeDefined();
expect(await savedLine(h)).toEqual([]);
});

test("a message is picked up once: cut again after it was, it is left with the notice and its Retry", async () => {
let h = await running(["read_plan"]);
await restart(h);
let next = await nextProcess(h);
await until(() => next.prompts.length === 1);
await restart(next);
expect(next.chat.entries.at(-1)?.text).toBe(Chat.RESTART_INTERRUPTED);
expect(await savedLine(next)).toEqual([]);
});

test("a message sent back to the line waits where it was sent, ahead of one sent after it", async () => {
let h = await running(["read_plan"]);
h.context.steers = undefined;
h.context.config.harness = "copilot-sdk";
await Chat.send(h.context, speaking("bo"), member("@chopin and then this"));
await until(() => h.chat.queue.length === 1);
await restart(h);
expect(await savedLine(h)).toEqual(["write the plan", "and then this"]);
});

test("a reply whose write was called but has not reported is not run again, though nothing says it was applied", async () => {
let h = await running(["refine_decision"], false);
await restart(h);
expect(h.chat.entries.flatMap(entry => entry.tools ?? []).map(tool => tool.status)).toEqual([
"failed",
]);
expect(h.chat.entries.at(-1)?.text).toBe(Chat.RESTART_INTERRUPTED);
expect(await savedLine(h)).toEqual([]);
});

test("a background job a restart cuts off goes back to wait, its attempts unspent", async () => {
let h = harness();
let job = Chat.job(h.context, JOB, "job prompt", "session");
await until(() => h.prompts.length === 1);
await restart(h);
expect(await job).toMatchObject({ status: "preempted" });
});
Loading
Loading