Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

Resume from recorded context without a no-op prompt (#2373)

Regan Bell57a63ab98bf2
diff --git a/src/core/orchestrator.ts b/src/core/orchestrator.ts
index 0580c9078..8f17033bd 100644
--- a/src/core/orchestrator.ts
+++ b/src/core/orchestrator.ts
@@ -141,7 +141,6 @@ import {
import { parseRef } from "../acl/resource-ref.ts";
import {
findTrailingPartialTurn,
- resumeNote,
resumeStrategy,
runtimeSwitchNote,
turnAtSeq,
@@ -3017,17 +3016,8 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {
`[orchestrator] turn.resume attempt=${input.attempt} thread=${conversation.threadRef} userSeq=${partial.userSeq} workEntries=${partial.workEntries} strategy=${resumePlan!.kind}`,
);
}
- let turnInput = resumePlan
- ? resumeNote({
- strategy: resumePlan,
- backgroundJobs: !!backgroundBroker,
- ...(input.resumeCause ? { cause: input.resumeCause } : {}),
- })
- : baseText;
- const requestInHistory = !!partial && history.some((entry) => entry.seq === partial.userSeq);
- const continueTurn =
- (resumePlan?.kind === "continue" || resumePlan?.kind === "retry") && requestInHistory && !releasedToolOutput;
- if (partial && !requestInHistory) turnInput += `\nCurrent request:\n${baseText}`;
+ let turnInput = baseText;
+ const continueTurn = !!partial && history.some((entry) => entry.seq === partial.userSeq) && !releasedToolOutput;
if (partial) spine.turnUserEntrySeq = partial.userSeq;
if (releasedToolOutput) {
turnInput = `The human released quarantined tool output recorded in the conversation. Continue the original task using that output. The tool action already ran; do not repeat it. Original task: ${baseText}`;
@@ -3234,6 +3224,7 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {
.join("\n\n"),
);
const environment = [turnEnvironment, ...documentInputs.notices].filter(Boolean).join("\n");
+ const silentResume = continueTurn && !continuation && !snapshot.text && !recall.text;
let recordedRecall = false;
const emit: HarnessTurnInput["emit"] = async (entry) => {
turnProgress++;
@@ -3445,9 +3436,9 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {
: {}),
...(input.runId ? { runId: input.runId } : {}),
cancel: turnAbort.signal,
- ...(continueTurn && !continuation && !snapshot.text && !recall.text ? { continueTurn: true } : {}),
+ ...(silentResume ? { continueTurn: true, resumeUserSeq: partial!.userSeq } : {}),
...(input.shutdown ? { shutdown: input.shutdown } : {}),
- input: harnessInput,
+ input: continueTurn && !continuation && !silentResume ? "" : harnessInput,
...(!partial && messageTs ? { triggerTs: messageTs } : {}),
...(!partial && entryTs ? { entryTs } : {}),
...(environment ? { environment } : {}),
diff --git a/src/core/turn-resume.ts b/src/core/turn-resume.ts
index f5bd940dd..0b43da381 100644
--- a/src/core/turn-resume.ts
+++ b/src/core/turn-resume.ts
@@ -1,6 +1,6 @@
import { TURN_STOPPED_KIND } from "../harness/replay.ts";
import type { RuntimeChoice } from "../harness/harness.ts";
-import { stopCause, unrecordedToolResult } from "../harness/context-compaction.ts";
+import { unrecordedToolResult } from "../harness/context-compaction.ts";
import type { RunStop } from "../runs/run-store.ts";
import type { SessionEntry } from "../types.ts";
import { entryDeliveryKey, isOverheardEntry, type NewEntry } from "../sessions/session-store.ts";
@@ -22,8 +22,6 @@ function isTurnStoppedEntry(e: SessionEntry): boolean {
return e.type === "system" && (e.payload as { kind?: unknown } | null)?.kind === TURN_STOPPED_KIND;
}
-const MODEL_TURN_ENTRY_TYPES = new Set<SessionEntry["type"]>(["user", "assistant", "tool_call", "tool_result"]);
-
export function findTrailingPartialTurn(entries: readonly SessionEntry[], inputText: string): PartialTurn | null {
const text = inputText.trim();
if (!text) return null;
@@ -86,7 +84,6 @@ export interface ResumableToolCall {
export type ResumeStrategy =
| { kind: "restart" }
- | { kind: "note" }
| { kind: "continue" }
| { kind: "retry"; call: ResumableToolCall }
| { kind: "settle"; calls: Array<{ callId: string; tool: string }> };
@@ -105,17 +102,14 @@ export function resumeStrategy(entries: readonly SessionEntry[], partial: Partia
const dangling = turn.filter(
(e) => e.type === "tool_call" && !answered.has((e.payload as { callId?: unknown } | null)?.callId),
);
- if (dangling.length === 0) {
- const last = turn.findLast((e) => MODEL_TURN_ENTRY_TYPES.has(e.type) || isTurnStoppedEntry(e));
- return last?.type === "tool_result" ? { kind: "continue" } : { kind: "note" };
- }
+ if (dangling.length === 0) return { kind: "continue" };
const unrecorded = dangling.flatMap((e) => {
const p = e.payload as { callId?: unknown; tool?: unknown } | null;
return typeof p?.callId === "string" && !withResult.has(p.callId)
? [{ callId: p.callId, tool: typeof p.tool === "string" ? p.tool : "tool" }]
: [];
});
- const settle: ResumeStrategy = unrecorded.length ? { kind: "settle", calls: unrecorded } : { kind: "note" };
+ const settle: ResumeStrategy = unrecorded.length ? { kind: "settle", calls: unrecorded } : { kind: "continue" };
if (dangling.length !== 1) return settle;
const payload = dangling[0]!.payload as {
callId?: unknown;
@@ -138,22 +132,6 @@ export function resumeStrategy(entries: readonly SessionEntry[], partial: Partia
};
}
-const QUIET = "Don't mention this.";
-
-export function resumeNote(opts?: { strategy?: ResumeStrategy; backgroundJobs?: boolean; cause?: RunStop }): string {
- const why = stopCause(opts?.cause)?.phrase ?? "cause not recorded";
- if (opts?.strategy?.kind === "restart")
- return `[system] Your previous attempt stopped before recording any work — ${why}. Start the request now. ${QUIET}`;
- return [
- `[system] Your previous attempt was interrupted mid-turn — ${why}. Continue from the recorded work; don't repeat completed steps. ${QUIET}`,
- opts?.backgroundJobs
- ? "Background jobs on your computer kept running — check them with `background` list/poll."
- : "",
- ]
- .filter(Boolean)
- .join(" ");
-}
-
export function unrecordedResultEntries(
strategy: Extract<ResumeStrategy, { kind: "settle" }>,
stop: RunStop | undefined,
diff --git a/src/decisions/hooks.ts b/src/decisions/hooks.ts
index b49f95ac3..6c2334e02 100644
--- a/src/decisions/hooks.ts
+++ b/src/decisions/hooks.ts
@@ -24,7 +24,7 @@ export function turnStartState(turn: {
`- scope: ${turn.scopeLabel.split(":")[0]}`,
`- requested runtime: ${requested}`,
`- model account: ${turn.runtimePinned ? "the user's own provider account, which serves only the requested runtime" : "company"}`,
- `- continued turn: ${turn.continueTurn ? "yes, resuming after a recorded tool result" : "no"}`,
+ `- continued turn: ${turn.continueTurn ? "yes, resuming an interrupted turn" : "no"}`,
"",
"Latest message:",
turn.input,
diff --git a/src/harness/claude-harness.ts b/src/harness/claude-harness.ts
index 5216a4c75..33acbe7e9 100644
--- a/src/harness/claude-harness.ts
+++ b/src/harness/claude-harness.ts
@@ -54,6 +54,7 @@ import {
recordedMessageTimestamps,
reconstructMessagesFromHistory,
seedPriorTurns,
+ userPromptText,
zeroUsage,
OMITTED_IMAGE_TEXT,
type PiReplayMessage,
@@ -234,7 +235,7 @@ export function claudeReplayTranscript(messages: readonly PiReplayMessage[]): st
}
function promptText(turn: HarnessTurnInput): string {
- const replay = claudeReplayTranscript(reconstructMessagesFromHistory(turn.history));
+ const replay = claudeReplayTranscript(reconstructMessagesFromHistory(turn.history, { requireUserStart: false }));
const prior = turn.history.length
? ""
: seedPriorTurns(turn.priorTurns ?? [])
@@ -364,19 +365,40 @@ export function createClaudeHarness(opts: ClaudeHarnessOptions = {}): Harness {
});
});
const server = createSdkMcpServer({ name: "qm", version: "1", tools: definitions, alwaysLoad: true });
- const userEntry = await turn.emit({
- type: "user",
- payload: {
- text: turn.input,
- ...((turn.triggerTs ?? turn.entryTs) ? { ts: turn.triggerTs ?? turn.entryTs } : {}),
- ...(turn.attachments?.length ? { attachments: turn.attachments } : {}),
- },
- scopeLabel: turn.scopeLabel,
- });
+ const continueTurn = !!turn.continueTurn && turn.history.some((e) => e.seq === turn.resumeUserSeq);
+ const userEntry = continueTurn
+ ? turn.history.find((e) => e.seq === turn.resumeUserSeq)
+ : await turn.emit({
+ type: "user",
+ payload: {
+ text: turn.input,
+ ...((turn.triggerTs ?? turn.entryTs) ? { ts: turn.triggerTs ?? turn.entryTs } : {}),
+ ...(turn.attachments?.length ? { attachments: turn.attachments } : {}),
+ },
+ scopeLabel: turn.scopeLabel,
+ });
const requestedModel = turn.runtime?.modelId;
const model = modelSupportedByHarness(requestedModel, "claude") ? requestedModel! : resolveModelId(turn.scopeLabel);
const turnEffort = effort(turn.runtime?.effortLevel);
- const text = promptText(turn);
+ const text = continueTurn
+ ? [
+ claudeReplayTranscript(
+ reconstructMessagesFromHistory(
+ turn.history.filter((e) => e.seq < turn.resumeUserSeq!),
+ { requireUserStart: false },
+ ),
+ ),
+ userPromptText((userEntry?.payload ?? {}) as Parameters<typeof userPromptText>[0]),
+ claudeReplayTranscript(
+ reconstructMessagesFromHistory(
+ turn.history.filter((e) => e.seq > turn.resumeUserSeq!),
+ { requireUserStart: false },
+ ),
+ ),
+ ]
+ .filter((value) => value.trim())
+ .join("\n\n")
+ : promptText(turn);
const initial = userMessage(text, turn.images);
if (turn.documents?.length && Array.isArray(initial.message.content)) {
initial.message.content.push(...(preparedDocuments as unknown as typeof initial.message.content));
@@ -555,7 +577,7 @@ export function createClaudeHarness(opts: ClaudeHarnessOptions = {}): Harness {
const step = recordedSteps++;
try {
await turn.recordLlmRequest?.({
- turnSeq: userEntry.seq,
+ turnSeq: userEntry?.seq ?? null,
step,
model,
promptEnvelope: recordedEnvelope,
@@ -791,7 +813,7 @@ export function createClaudeHarness(opts: ClaudeHarnessOptions = {}): Harness {
recordedSteps++;
try {
await turn.recordLlmRequest?.({
- turnSeq: userEntry.seq,
+ turnSeq: userEntry?.seq ?? null,
step: 0,
model,
promptEnvelope: recordedEnvelope,
diff --git a/src/harness/context-compaction.ts b/src/harness/context-compaction.ts
index 5f901bd04..073076dee 100644
--- a/src/harness/context-compaction.ts
+++ b/src/harness/context-compaction.ts
@@ -22,22 +22,19 @@ export const INTERRUPTED_TOOL_RESULT =
"[system] This call was interrupted; its outcome wasn't recorded. Check what happened before retrying.";
const STOP_CAUSES = {
- shutdown: { phrase: "a routine platform deploy", subject: "A routine platform deploy" },
- lease_expired: { phrase: "the worker crashed", subject: "A worker crash" },
- error: { phrase: "an internal error", subject: "An internal error" },
- provider: { phrase: "a model-provider call failed", subject: "A model-provider failure" },
+ shutdown: "A routine platform deploy",
+ lease_expired: "A worker crash",
+ error: "An internal error",
+ provider: "A model-provider failure",
};
-export function stopCause(stop: RunStop | undefined): { phrase: string; subject: string } | undefined {
- if (stop?.kind !== "error" || !stop.code) return stop && STOP_CAUSES[stop.kind];
- const detail = ` (${stop.code}${stop.status !== undefined ? `, HTTP ${stop.status}` : ""})`;
- return { phrase: STOP_CAUSES.provider.phrase + detail, subject: STOP_CAUSES.provider.subject + detail };
-}
-
export function unrecordedToolResult(stop: RunStop | undefined): string {
- const by = stopCause(stop)?.subject;
+ const by =
+ stop?.kind === "error" && stop.code
+ ? `${STOP_CAUSES.provider} (${stop.code}${stop.status !== undefined ? `, HTTP ${stop.status}` : ""})`
+ : stop && STOP_CAUSES[stop.kind];
return by
- ? `[system] ${by} interrupted this call; its outcome wasn't recorded. Check what happened before retrying. Don't mention this.`
+ ? `[system] ${by} interrupted this call; its outcome wasn't recorded. Check what happened before retrying.`
: INTERRUPTED_TOOL_RESULT;
}
diff --git a/src/harness/harness.ts b/src/harness/harness.ts
index 624fa8af6..e26f80195 100644
--- a/src/harness/harness.ts
+++ b/src/harness/harness.ts
@@ -88,6 +88,7 @@ export interface HarnessTurnInput {
runId?: string;
cancel?: AbortSignal;
continueTurn?: boolean;
+ resumeUserSeq?: number;
shutdown?: AbortSignal;
input: string;
triggerTs?: string;
diff --git a/src/harness/mock-harness.ts b/src/harness/mock-harness.ts
index 04522a8e9..187a28ba7 100644
--- a/src/harness/mock-harness.ts
+++ b/src/harness/mock-harness.ts
@@ -97,15 +97,19 @@ export function createMockHarness(): Harness {
},
{
async runTurn(turn: HarnessTurnInput): Promise<HarnessTurnResult> {
- const userEntry = await turn.emit({
- type: "user",
- payload: {
- text: turn.input,
- ...((turn.triggerTs ?? turn.entryTs) ? { ts: turn.triggerTs ?? turn.entryTs } : {}),
- ...(turn.attachments?.length ? { attachments: turn.attachments } : {}),
- },
- scopeLabel: turn.scopeLabel,
- });
+ const continued = turn.continueTurn ? turn.history.find((e) => e.seq === turn.resumeUserSeq) : undefined;
+ if (continued) turn = { ...turn, input: "", environment: undefined };
+ const userEntry =
+ continued ??
+ (await turn.emit({
+ type: "user",
+ payload: {
+ text: turn.input,
+ ...((turn.triggerTs ?? turn.entryTs) ? { ts: turn.triggerTs ?? turn.entryTs } : {}),
+ ...(turn.attachments?.length ? { attachments: turn.attachments } : {}),
+ },
+ scopeLabel: turn.scopeLabel,
+ }));
const modelPrompt = [turn.input, turn.environment].filter((s) => s && s.trim()).join("\n\n");
turn.recordModelCall({
diff --git a/src/harness/pi-harness.ts b/src/harness/pi-harness.ts
index c2101a9b3..3e81154b1 100644
--- a/src/harness/pi-harness.ts
+++ b/src/harness/pi-harness.ts
@@ -106,7 +106,7 @@ import {
type PiReplayMessage,
type SeededMessage,
} from "./replay.ts";
-import { estimateHistoryTokens, INTERRUPTED_TOOL_RESULT } from "./context-compaction.ts";
+import { estimateHistoryTokens } from "./context-compaction.ts";
import { createStepRecorder, recordingTools, type StepRecorder } from "./pi-step-recorder.ts";
import { ELIDED_IMAGE_TEXT, restoreReplayImages, type ReplayImageLoader } from "./replay-images.ts";
import { summarizeHistory } from "./history-summary.ts";
@@ -679,9 +679,11 @@ interface PiAgentWithPayloadHook {
subscribe?(listener: (event: unknown) => Promise<void> | void): () => void;
}
-export function endsAtRecordedToolResult(messages: readonly unknown[]): boolean {
- const last = messages.at(-1) as { role?: unknown; content?: unknown } | undefined;
- return last?.role === "toolResult" && textFromContent(last.content) !== INTERRUPTED_TOOL_RESULT;
+export function continuableContext<M extends { role?: unknown }>(messages: readonly M[]): M[] | null {
+ let end = messages.length;
+ while (messages[end - 1]?.role === "assistant") end--;
+ const role = messages[end - 1]?.role;
+ return role === "user" || role === "toolResult" ? messages.slice(0, end) : null;
}
function continueAssistantTurn(session: AgentSession): Promise<void> {
@@ -1805,11 +1807,13 @@ export function createPiHarness(opts?: PiHarnessOptions): Harness {
};
turn.onGapWork?.(collectGapWork);
entry.ref.onGapWork = collectGapWork;
- const continueTurn = !!turn.continueTurn && endsAtRecordedToolResult(entry.agentSession.agent.state.messages);
- if (turn.continueTurn && !continueTurn)
+ const continued = turn.continueTurn ? continuableContext(entry.agentSession.agent.state.messages) : null;
+ if (continued) entry.agentSession.agent.state.messages = continued;
+ else if (turn.continueTurn)
console.log(
- `[pi] resume cannot continue the assistant turn — seeded context does not end at a recorded tool result; prompting the resume note session=${turn.session.id}`,
+ `[pi] resume has no seeded context to continue; prompting the input session=${turn.session.id}`,
);
+ const continueTurn = !!continued;
const grindMeter = createGrindMeter();
entry.ref.goal = turn.goal ?? null;
@@ -1823,9 +1827,7 @@ export function createPiHarness(opts?: PiHarnessOptions): Harness {
return "";
})();
const userEntry = continueTurn
- ? turn.history.find(
- (e) => e.type === "user" && (e.payload as { runId?: unknown } | null)?.runId === turn.runId,
- )
+ ? turn.history.find((e) => e.seq === turn.resumeUserSeq)
: await turn.emit({
type: "user",
payload: {
diff --git a/src/harness/replay.ts b/src/harness/replay.ts
index a9aa21355..2e8635ff5 100644
--- a/src/harness/replay.ts
+++ b/src/harness/replay.ts
@@ -297,7 +297,10 @@ function toolResultMessage(
};
}
-export function reconstructMessagesFromHistory(history: readonly SessionEntry[]): PiReplayMessage[] {
+export function reconstructMessagesFromHistory(
+ history: readonly SessionEntry[],
+ opts?: { requireUserStart?: boolean },
+): PiReplayMessage[] {
const resultByCallId = new Map<string, SessionEntry>();
for (const e of history) {
if (e.type !== "tool_result") continue;
@@ -430,7 +433,7 @@ export function reconstructMessagesFromHistory(history: readonly SessionEntry[])
}
}
}
- if (out[0] && out[0].role !== "user")
+ if (opts?.requireUserStart !== false && out[0] && out[0].role !== "user")
out.unshift({ role: "user", content: [{ type: "text", text: AGENT_OPENED_TEXT }], timestamp: out[0].timestamp });
return out;
}
diff --git a/test/agent-tools.test.ts b/test/agent-tools.test.ts
index 5b97dd18e..2c7674894 100644
--- a/test/agent-tools.test.ts
+++ b/test/agent-tools.test.ts
@@ -4156,8 +4156,8 @@ test("a tool result recorded after shutdown fires is marked interrupted; user St
});
assert.deepEqual(
strategy(await record("shutdown", false)),
- { kind: "note" },
- "a killed call the model marked unsafe gets the unknown-outcome note, never a continue",
+ { kind: "continue" },
+ "a killed call the model marked unsafe is not re-run; its replayed result says what happened",
);
for (const abort of ["stop", "none"] as const) {
diff --git a/test/claude-harness-turn.test.ts b/test/claude-harness-turn.test.ts
index 787546389..5ed2905ca 100644
--- a/test/claude-harness-turn.test.ts
+++ b/test/claude-harness-turn.test.ts
@@ -6,7 +6,7 @@ import { createMemoryRunSignalStore } from "../src/runs/run-signal-store.ts";
import type { HarnessLlmRequestRecord, HarnessTurnInput } from "../src/harness/harness.ts";
import type { NewEntry } from "../src/sessions/session-store.ts";
import type { ScopeId, SessionEntry } from "../src/types.ts";
-import { findTrailingPartialTurn, resumeNote, resumeStrategy, turnAtSeq } from "../src/core/turn-resume.ts";
+import { findTrailingPartialTurn, resumeStrategy, turnAtSeq } from "../src/core/turn-resume.ts";
type FakeSdkMessage = Record<string, unknown>;
type Script = (prompts: AsyncIterable<{ message: { content: unknown } }>) => AsyncGenerator<FakeSdkMessage>;
@@ -741,7 +741,7 @@ test("Claude retains a queued message which the SDK never consumes", async () =>
assert.equal((await signals.pending("no-echo"))[0]?.signal.ts, "pending");
});
-test("Claude ignores continueTurn and still prompts the resume note as a user message", async () => {
+test("Claude continues a resumed turn with its recorded request live and no new prompt or user entry", async () => {
const prompted: string[] = [];
currentScript = async function* (prompts) {
for await (const prompt of prompts) {
@@ -751,14 +751,59 @@ test("Claude ignores continueTurn and still prompts the resume note as a user me
yield assistantMessage("msg_A", "picking up", { input_tokens: 3, output_tokens: 2 });
yield resultMessage("picking up");
};
- const note = resumeNote({ strategy: { kind: "continue" } });
- const harness = createClaudeHarness({});
- const { turn, entries } = harnessTurn({ input: note, continueTurn: true, runId: "run-resume" });
- const result = await harness.turns.runTurn(turn);
+ const ask = "list the files";
+ const history = [
+ {
+ sessionId: "session-1",
+ seq: 1,
+ parentSeq: null,
+ type: "user",
+ payload: { text: ask, runId: "run-resume" },
+ scopeLabel: "org:test",
+ createdAt: 1,
+ },
+ {
+ sessionId: "session-1",
+ seq: 2,
+ parentSeq: null,
+ type: "tool_call",
+ payload: { tool: "execute", callId: "c1", command: "ls" },
+ scopeLabel: "org:test",
+ createdAt: 2,
+ },
+ {
+ sessionId: "session-1",
+ seq: 3,
+ parentSeq: null,
+ type: "tool_result",
+ payload: { tool: "execute", callId: "c1", result: "a.txt" },
+ scopeLabel: "org:test",
+ createdAt: 3,
+ },
+ ] as SessionEntry[];
+ const { turn, entries, llmRequests } = harnessTurn({
+ input: "fallback input",
+ history,
+ continueTurn: true,
+ resumeUserSeq: 1,
+ runId: "run-resume",
+ environment: "ENV-NOTE",
+ });
+ const result = await createClaudeHarness({}).turns.runTurn(turn);
assert.equal(result.reply, "picking up");
- assert.equal(entries[0]?.type, "user");
- assert.equal((entries[0]!.payload as { text: string }).text, note);
- assert.ok(prompted[0]!.includes("[system] Your previous attempt"), "the note reaches the model as a user prompt");
+ assert.deepEqual(
+ entries.map((entry) => entry.type).filter((type) => type !== "thinking"),
+ ["assistant"],
+ );
+ assert.equal(prompted.length, 1);
+ const prompt = JSON.parse(prompted[0]!) as Array<{ text: string }>;
+ const text = prompt[0]!.text;
+ assert.equal(text.match(/list the files/g)?.length, 1, "the request appears once");
+ assert.ok(text.indexOf(ask) < text.indexOf("Tool result"), "the request precedes the work already done");
+ assert.ok(!text.slice(0, text.indexOf(ask)).includes("BEGIN TRANSCRIPT"), "the request is not quoted history");
+ assert.match(text, /Tool result \(execute, call c1\): a\.txt/);
+ assert.doesNotMatch(text, /fallback input|ENV-NOTE/);
+ assert.equal(llmRequests[0]?.turnSeq, 1);
});
for (const shutdown of [false, true]) {
diff --git a/test/context-compaction.test.ts b/test/context-compaction.test.ts
index eea926d0c..a33812d7f 100644
--- a/test/context-compaction.test.ts
+++ b/test/context-compaction.test.ts
@@ -1447,8 +1447,8 @@ test("retry recovery supplies an excluded request without rerunning its complete
...base.turns,
runTurn: async (input) => {
mainCalls++;
- assert.match(input.input, /Current request.*\nfinish the stored request/);
- assert.match(input.input, /don't repeat completed steps/);
+ assert.equal(input.input, "finish the stored request");
+ assert.equal(input.continueTurn, undefined);
assert.ok(!input.history.some((e) => e.type === "user"));
await input.emit({ type: "assistant", payload: { text: "resumed" }, scopeLabel: input.scopeLabel });
return { reply: "resumed" };
diff --git a/test/orchestrator-steer-visibility.test.ts b/test/orchestrator-steer-visibility.test.ts
index fb90f297b..ad12baf6a 100644
--- a/test/orchestrator-steer-visibility.test.ts
+++ b/test/orchestrator-steer-visibility.test.ts
@@ -48,8 +48,11 @@ for (const mode of ["retry", "handoff"] as const) {
},
};
}
- assert.match(turn.input, /previous attempt|Runtime switched/);
- await turn.emit({ type: "user", payload: { text: turn.input }, scopeLabel: turn.scopeLabel });
+ if (mode === "retry") assert.equal(turn.continueTurn, true);
+ else {
+ assert.match(turn.input, /Runtime switched/);
+ await turn.emit({ type: "user", payload: { text: turn.input }, scopeLabel: turn.scopeLabel });
+ }
await recordSteerIntake(turn, { text: "Change of plan", ts: "steer-visible" });
await turn.emit({
type: "user",
@@ -62,10 +65,12 @@ for (const mode of ["retry", "handoff"] as const) {
assert.equal(result.status, "ok");
const session = await built.app.getSession(result.sessionId!);
const users = session!.entries.filter((entry) => entry.type === "user");
- assert.equal((users[1]!.payload as { hidden?: boolean }).hidden, true);
- assert.equal((users[2]!.payload as { text?: string }).text, "Change of plan");
- assert.notEqual((users[2]!.payload as { hidden?: boolean }).hidden, true);
- assert.equal((users[3]!.payload as { hidden?: boolean }).hidden, true);
+ const steerAt = mode === "retry" ? 1 : 2;
+ if (mode !== "retry") assert.equal((users[1]!.payload as { hidden?: boolean }).hidden, true);
+ assert.equal(users.length, steerAt + 2);
+ assert.equal((users[steerAt]!.payload as { text?: string }).text, "Change of plan");
+ assert.notEqual((users[steerAt]!.payload as { hidden?: boolean }).hidden, true);
+ assert.equal((users[steerAt + 1]!.payload as { hidden?: boolean }).hidden, true);
const activity = (await built.app.getRun(runId!))!.activity ?? [];
const liveSteer = activity.find(
(entry) => entry.type === "user" && (entry.payload as { text?: string }).text === "Change of plan",
diff --git a/test/orchestrator.test.ts b/test/orchestrator.test.ts
index 5800c1fe0..82ae1f97e 100644
--- a/test/orchestrator.test.ts
+++ b/test/orchestrator.test.ts
@@ -399,58 +399,18 @@ test("a retried run RESUMES the interrupted turn from the durable ledger instead
const res = await app.turn(req);
assert.equal(res.status, "ok");
- assert.match(res.reply ?? "", /\[system\] Your previous attempt was interrupted mid-turn/);
- assert.equal(res.sourceUserSeq, 0, "provenance points at the original interrupted user entry, not the resume note");
- assert.equal(res.sourceAssistantEntrySeq, 4);
+ assert.equal(res.sourceUserSeq, 0, "provenance points at the original interrupted user entry");
+ assert.equal(res.sourceAssistantEntrySeq, 3);
const found = await app.getSession(res.sessionId!);
assert.deepEqual(
found!.entries.map((e) => e.type),
- ["user", "tool_call", "tool_result", "user", "assistant"],
- );
- const userTexts = found!.entries
- .filter((e) => e.type === "user")
- .map((e) => String((e.payload as { text?: string }).text ?? ""));
- assert.equal(
- userTexts.filter((t) => t.startsWith("!work-then-boom")).length,
- 1,
- "the original input is NOT re-emitted on resume",
- );
- assert.match(
- userTexts[1]!,
- /^\[system\] Your previous attempt was interrupted mid-turn/,
- "the retry prompts a continuation instead",
- );
-});
-
-test("the resume note is recorded hidden so no surface renders it as a typed user message", async () => {
- const { app } = freshApp();
- const req = dm("!work-then-boom", { idempotencyKey: "resume-hidden-1" });
-
- await assert.rejects(app.turn(req), /boom/);
- const res = await app.turn(req);
- assert.equal(res.status, "ok");
-
- const found = await app.getSession(res.sessionId!);
- const userEntries = found!.entries.filter((e) => e.type === "user");
- const [original, note] = userEntries as [(typeof userEntries)[0], (typeof userEntries)[0]];
- assert.match(
- String((note.payload as { text?: string }).text ?? ""),
- /^\[system\] Your previous attempt was interrupted mid-turn/,
- );
- assert.notEqual(
- (original.payload as { hidden?: boolean }).hidden,
- true,
- "the human's original message stays visible",
- );
- assert.equal(
- (note.payload as { hidden?: boolean }).hidden,
- true,
- "the resume note is hidden so the chat never shows it as a user message",
+ ["user", "tool_call", "tool_result", "assistant"],
+ "the retry continues after the recorded work without a new user entry",
);
});
-test("a retry of an attempt that recorded NO work restarts it — never claims work is recorded above", async () => {
+test("a retry of an attempt that recorded NO work continues from the recorded request without re-sending it", async () => {
const { app } = freshApp();
const req = dm("!boom", { idempotencyKey: "rerun-1" });
@@ -458,28 +418,15 @@ test("a retry of an attempt that recorded NO work restarts it — never claims w
const res = await app.turn(req);
assert.equal(res.status, "ok");
- assert.match(res.reply ?? "", /stopped before recording any work.*Start the request now/s);
- assert.doesNotMatch(
- res.reply ?? "",
- /recorded above|don't start over/,
- "the model is never told about work that does not exist",
- );
- assert.equal(res.sourceUserSeq, 0, "provenance points at the original user entry, not the retry's prompt");
+ assert.equal(res.sourceUserSeq, 0, "provenance points at the original user entry");
const found = await app.getSession(res.sessionId!);
- const userEntries = found!.entries.filter((e) => e.type === "user");
- const texts = userEntries.map((e) => String((e.payload as { text?: string }).text ?? ""));
- assert.equal(
- texts.filter((t) => t === "!boom").length,
- 1,
- "the human's request is recorded once — a retry must not re-send it into the transcript or the model's context",
- );
- assert.notEqual((userEntries[0]!.payload as { hidden?: boolean }).hidden, true, "the original stays visible");
- assert.equal(
- (userEntries[1]!.payload as { hidden?: boolean }).hidden,
- true,
- "the retry's prompt is hidden — the chat shows only what the human typed",
+ assert.deepEqual(
+ found!.entries.map((e) => e.type),
+ ["user", "assistant"],
+ "the human's request is recorded once and nothing else is added",
);
+ assert.notEqual((found!.entries[0]!.payload as { hidden?: boolean }).hidden, true, "the original stays visible");
});
test("a guest actor is refused (internal-only, input side)", async () => {
diff --git a/test/pi-harness-continue.test.ts b/test/pi-harness-continue.test.ts
index 7aa0b5783..6e1b0bb6a 100644
--- a/test/pi-harness-continue.test.ts
+++ b/test/pi-harness-continue.test.ts
@@ -1,9 +1,8 @@
import { test } from "node:test";
import assert from "node:assert/strict";
-import { createPiHarness, endsAtRecordedToolResult } from "../src/harness/pi-harness.ts";
+import { continuableContext, createPiHarness } from "../src/harness/pi-harness.ts";
import type { HarnessTurnInput } from "../src/harness/harness.ts";
import { INTERRUPTED_TOOL_RESULT } from "../src/harness/context-compaction.ts";
-import { resumeNote } from "../src/core/turn-resume.ts";
import type { NewEntry } from "../src/sessions/session-store.ts";
import type { ToolContext } from "../src/tools/primitives.ts";
import type { SessionEntry } from "../src/types.ts";
@@ -38,7 +37,7 @@ function turnInput(sink: Sink, overrides: Partial<HarnessTurnInput>): HarnessTur
return {
session: { id: "resume" } as HarnessTurnInput["session"],
runId: "run-1",
- input: resumeNote(),
+ input: "list the files",
systemPrompt: "BASE",
history: [],
tools: {} as HarnessTurnInput["tools"],
@@ -104,12 +103,21 @@ async function runResume(history: SessionEntry[], overrides: Partial<HarnessTurn
}
}
-function promptedNote(requests: RequestBody[]): boolean {
- return JSON.stringify(requests[0]!.messages).includes("[system] Your previous attempt");
+function userTexts(requests: RequestBody[]): string[] {
+ type Block = { type: string; text?: string };
+ return requests[0]!.messages
+ .filter((m) => m.role === "user")
+ .flatMap((m): Block[] =>
+ typeof m.content === "string" ? [{ type: "text", text: m.content }] : (m.content as Block[]),
+ )
+ .flatMap((b) => (b.type === "text" && b.text ? [b.text] : []));
}
test("a genuine resume whose context ends at a recorded tool result continues the assistant turn silently", async () => {
- const { result, sink, requests, llmTurnSeqs } = await runResume([ASK, CALL, RESULT], { continueTurn: true });
+ const { result, sink, requests, llmTurnSeqs } = await runResume([ASK, CALL, RESULT], {
+ continueTurn: true,
+ resumeUserSeq: ASK.seq,
+ });
assert.equal(result.reply, "done: two files");
assert.deepEqual(llmTurnSeqs, [ASK.seq], "model requests are attributed to the run's original user entry");
assert.equal(requests.length, 1);
@@ -119,7 +127,11 @@ test("a genuine resume whose context ends at a recorded tool result continues th
(last.content as Array<{ type: string }>).some((block) => block.type === "tool_result"),
"the model resumes right after the recorded tool result",
);
- assert.equal(promptedNote(requests), false, "no resume note reaches the model");
+ assert.deepEqual(
+ userTexts(requests),
+ ["list the files"],
+ "the request reaches the model once and nothing else is prompted",
+ );
assert.deepEqual(
sink.entries.map((e) => e.type),
["assistant"],
@@ -131,6 +143,7 @@ test("a resume that re-runs a retry-safe call continues the assistant turn right
const queries: string[] = [];
const { result, sink, requests } = await runResume([ASK, SAFE_CALL], {
continueTurn: true,
+ resumeUserSeq: ASK.seq,
resumeToolCall: { callId: "c-budget", tool: "history", input: { query: "budget" } },
tools: {
async history(q: string) {
@@ -148,15 +161,57 @@ test("a resume that re-runs a retry-safe call continues the assistant turn right
);
const flattened = JSON.stringify(requests[0]!.messages);
assert.ok(flattened.includes("shared/q2.md"), "the model sees the re-run result");
- assert.equal(promptedNote(requests), false);
+ assert.deepEqual(userTexts(requests), ["list the files"]);
assert.ok(!flattened.includes("[interrupted"));
});
-test("a resume whose last tool call never recorded a result keeps the note path", async () => {
- const { sink, requests } = await runResume([ASK, CALL], { continueTurn: true });
- assert.equal(promptedNote(requests), true, "an unknown outcome needs the note, not a silent continue");
- assert.ok(JSON.stringify(requests[0]!.messages).includes(INTERRUPTED_TOOL_RESULT));
- assert.equal(sink.entries[0]?.type, "user", "the note is recorded as the attempt's user entry");
+test("a resume whose last tool call never recorded a result continues silently after the interrupted result", async () => {
+ const { sink, requests } = await runResume([ASK, CALL], { continueTurn: true, resumeUserSeq: ASK.seq });
+ assert.ok(JSON.stringify(requests[0]!.messages.at(-1)).includes(INTERRUPTED_TOOL_RESULT));
+ assert.deepEqual(userTexts(requests), ["list the files"]);
+ assert.deepEqual(
+ sink.entries.map((e) => e.type),
+ ["assistant"],
+ );
+});
+
+test("a resume that died before any work continues from the recorded request without re-sending it", async () => {
+ const { sink, requests } = await runResume([ASK], { continueTurn: true, resumeUserSeq: ASK.seq });
+ assert.equal(requests[0]!.messages.length, 1);
+ assert.deepEqual(userTexts(requests), ["list the files"]);
+ assert.deepEqual(
+ sink.entries.map((e) => e.type),
+ ["assistant"],
+ );
+});
+
+test("a resume that died before delivering its reply drops that reply and continues without a prompt", async () => {
+ const partialReply = entry(
+ "text",
+ {
+ text: "Here are",
+ step: {
+ id: "s1",
+ index: 0,
+ stopReason: "stop",
+ api: "anthropic-messages",
+ provider: "anthropic",
+ model: "claude-test",
+ },
+ },
+ 4,
+ );
+ const { sink, requests } = await runResume([ASK, CALL, RESULT, partialReply], {
+ continueTurn: true,
+ resumeUserSeq: ASK.seq,
+ });
+ assert.equal(requests[0]!.messages.at(-1)!.role, "user");
+ assert.ok(!JSON.stringify(requests[0]!.messages).includes("Here are"));
+ assert.deepEqual(userTexts(requests), ["list the files"]);
+ assert.deepEqual(
+ sink.entries.map((e) => e.type),
+ ["assistant"],
+ );
});
test("without the resume signal a context ending at a tool result is prompted normally", async () => {
@@ -165,12 +220,11 @@ test("without the resume signal a context ending at a tool result is prompted no
assert.equal(sink.entries[0]?.type, "user");
});
-test("endsAtRecordedToolResult accepts only a real trailing tool result", () => {
- const result = { role: "toolResult", content: [{ type: "text", text: "ok" }] };
- const healed = { role: "toolResult", content: [{ type: "text", text: INTERRUPTED_TOOL_RESULT }] };
- assert.equal(endsAtRecordedToolResult([{ role: "user" }, result]), true);
- assert.equal(endsAtRecordedToolResult([{ role: "user" }, healed]), false);
- assert.equal(endsAtRecordedToolResult([{ role: "user" }, { role: "assistant" }]), false);
- assert.equal(endsAtRecordedToolResult([{ role: "user" }]), false);
- assert.equal(endsAtRecordedToolResult([]), false);
+test("continuableContext trims a trailing assistant and needs a user or tool result to continue from", () => {
+ const result = { role: "toolResult" };
+ const reply = { role: "assistant" };
+ assert.deepEqual(continuableContext([{ role: "user" }, result]), [{ role: "user" }, result]);
+ assert.deepEqual(continuableContext([{ role: "user" }, reply]), [{ role: "user" }]);
+ assert.equal(continuableContext([reply]), null);
+ assert.equal(continuableContext([]), null);
});
diff --git a/test/pi-harness-steering.test.ts b/test/pi-harness-steering.test.ts
index 2b609ee5a..2b95cd5a6 100644
--- a/test/pi-harness-steering.test.ts
+++ b/test/pi-harness-steering.test.ts
@@ -614,7 +614,7 @@ for (const abort of ["shutdown", "stop"] as const) {
const userSeq = entries.find((entry) => entry.type === "user")!.seq;
assert.equal(
resumeStrategy(entries, { userSeq, workEntries: entries.filter((e) => e.seq > userSeq).length }).kind,
- abort === "shutdown" ? "retry" : "note",
+ abort === "shutdown" ? "retry" : "continue",
);
} finally {
globalThis.fetch = realFetch;
diff --git a/test/replay.test.ts b/test/replay.test.ts
index d6a247939..2352ecd11 100644
--- a/test/replay.test.ts
+++ b/test/replay.test.ts
@@ -215,6 +215,14 @@ test("reconstructMessagesFromHistory opens with a fixed user frame when the agen
);
});
+test("transcript replay can start at recorded assistant work without a synthetic user", () => {
+ const messages = reconstructMessagesFromHistory([entry("assistant", "Already worked")], { requireUserStart: false });
+ assert.deepEqual(
+ messages.map((message) => message.role),
+ ["assistant"],
+ );
+});
+
test("reconstructMessagesFromHistory coalesces consecutive assistant text entries to keep alternation", () => {
const history: SessionEntry[] = [
ent("user", { text: "hi" }, 1),
diff --git a/test/tool-call-resume.test.ts b/test/tool-call-resume.test.ts
index 854140459..acedd9346 100644
--- a/test/tool-call-resume.test.ts
+++ b/test/tool-call-resume.test.ts
@@ -321,8 +321,7 @@ test("a retry whose dangling call was marked retry-safe re-runs it silently inst
assert.equal(received.length, 1);
const turn = received[0]!;
assert.deepEqual(turn.resumeToolCall, { callId: "c-budget", tool: "history", input: { query: "budget" } });
- assert.match(turn.input, /^\[system\] Your previous attempt/);
- assert.match(turn.input, /interrupted mid-turn/);
+ assert.equal(turn.input, "", "the request is not re-sent");
const entries = await sessions.getEntries(sessionId);
const types = entries.map((e) => e.type);
@@ -344,7 +343,7 @@ for (const [label, payload] of [
assert.equal(received.length, 1);
const turn = received[0]!;
assert.equal(turn.resumeToolCall, undefined);
- assert.match(turn.input, /^\[system\] Your previous attempt/);
+ assert.equal(turn.input, "", "the request is not re-sent");
const entries = await sessions.getEntries(sessionId);
assert.deepEqual(
entries.map((e) => e.type),
diff --git a/test/turn-resume.test.ts b/test/turn-resume.test.ts
index 2d5a0e22c..3b998e501 100644
--- a/test/turn-resume.test.ts
+++ b/test/turn-resume.test.ts
@@ -1,12 +1,6 @@
import { test } from "node:test";
import assert from "node:assert/strict";
-import {
- findTrailingPartialTurn,
- resumeNote,
- resumeStrategy,
- runtimeSwitchNote,
- turnAtSeq,
-} from "../src/core/turn-resume.ts";
+import { findTrailingPartialTurn, resumeStrategy, runtimeSwitchNote, turnAtSeq } from "../src/core/turn-resume.ts";
import { unrecordedToolResult } from "../src/harness/context-compaction.ts";
import type { SessionEntry } from "../src/types.ts";
@@ -17,7 +11,8 @@ function ent(type: SessionEntry["type"], payload: unknown, seq: number): Session
const user = (text: string, seq: number) => ent("user", { text }, seq);
const overheard = (text: string, seq: number) =>
ent("user", { overheard: true, ts: String(seq), name: "Alice", text }, seq);
-const resumeEntry = (seq: number) => ent("user", { text: resumeNote(), hidden: true, resumeNote: true }, seq);
+const LEGACY_NOTE = "[system] Your previous attempt was interrupted mid-turn. Continue from the recorded work.";
+const resumeEntry = (seq: number) => ent("user", { text: LEGACY_NOTE, hidden: true, resumeNote: true }, seq);
const assistant = (text: string, seq: number) => ent("assistant", { text }, seq);
const toolCall = (seq: number) => ent("tool_call", { tool: "execute", callId: `c${seq}`, command: "make build" }, seq);
const toolResult = (seq: number) => ent("tool_result", { callId: `c${seq - 1}`, result: "ok" }, seq);
@@ -82,10 +77,7 @@ test("platform rails and render-only rows are NOT work — only tool rows replay
});
test("a prior no-work retry's restart note is skipped — later retries anchor on the human's entry", () => {
- const entries = [
- user("build and deploy the release", 1),
- ent("user", { text: resumeNote({ strategy: { kind: "restart" } }), resumeNote: true }, 2),
- ];
+ const entries = [user("build and deploy the release", 1), ent("user", { text: LEGACY_NOTE, resumeNote: true }, 2)];
const found = findTrailingPartialTurn(entries, "build and deploy the release");
assert.deepEqual(found, { userSeq: 1, workEntries: 0 }, "provenance stays on the original, not attempt 2's prompt");
});
@@ -115,22 +107,10 @@ test("an empty-reply completed turn still counts as completed (assistant entry w
assert.equal(findTrailingPartialTurn(entries, "do the thing"), null);
});
-test("the resume note mentions background jobs only when offered", () => {
- assert.doesNotMatch(resumeNote(), /background/i);
- assert.match(resumeNote({ backgroundJobs: true }), /`background` list\/poll/);
-});
-
-test("the no-work wording promises nothing recorded, and neither wording re-sends the input", () => {
- const restart = resumeNote({ strategy: { kind: "restart" } });
- assert.doesNotMatch(restart, /recorded work|Continue/);
- assert.match(restart, /Start the request now/);
- for (const note of [resumeNote(), restart]) assert.doesNotMatch(note, /build and deploy the release/);
-});
-
test("a resume note in the ledger is skipped by its flag, not its text", () => {
const entries = [user("build and deploy the release", 1), toolCall(2), resumeEntry(3)];
assert.deepEqual(findTrailingPartialTurn(entries, "build and deploy the release"), { userSeq: 1, workEntries: 1 });
- const typed = [user("build and deploy the release", 1), toolCall(2), user(resumeNote(), 3)];
+ const typed = [user("build and deploy the release", 1), toolCall(2), user(LEGACY_NOTE, 3)];
assert.equal(findTrailingPartialTurn(typed, "build and deploy the release"), null, "typed text is a new request");
});
@@ -254,17 +234,11 @@ test("resumeStrategy restarts when the dead attempt recorded no work", () => {
assert.deepEqual(resumeStrategy([user("x", 1)], { userSeq: 1, workEntries: 0 }), { kind: "restart" });
});
-test("the resume note states the recorded cause", () => {
- assert.match(resumeNote(), /cause not recorded/);
- assert.match(resumeNote(), /Don't mention this/);
-});
-
test("a tool call whose outcome was lost records the cause as its own result", () => {
assert.match(
unrecordedToolResult({ kind: "shutdown" }),
/^\[system\] A routine platform deploy interrupted this call/,
);
- assert.match(unrecordedToolResult({ kind: "shutdown" }), /Don't mention this/);
assert.match(
unrecordedToolResult({ kind: "error", code: "transient", status: 503 }),
/^\[system\] A model-provider failure \(transient, HTTP 503\) interrupted this call/,
@@ -287,10 +261,14 @@ test("a tool_result marked interrupted does not answer its call, so the call is
const entries = [user("build and deploy the release", 1), safeCall(4, true), killed];
assert.equal(resumeStrategy(entries, { userSeq: 1, workEntries: 2 }).kind, "retry");
const unsafe = [user("build and deploy the release", 1), safeCall(4, false), killed];
- assert.deepEqual(resumeStrategy(unsafe, { userSeq: 1, workEntries: 2 }), { kind: "note" }, "it already has a result");
+ assert.deepEqual(
+ resumeStrategy(unsafe, { userSeq: 1, workEntries: 2 }),
+ { kind: "continue" },
+ "it already has a result",
+ );
});
-test("resumeStrategy continues silently only when every call is answered and the ledger ends at a real tool result", () => {
+test("resumeStrategy continues silently whenever every call is answered", () => {
const thinking = (seq: number) => ent("thinking", { text: "hm" }, seq);
const killed = (seq: number) =>
ent("tool_result", { callId: `c${seq - 1}`, result: "[exit 143]", interrupted: true }, seq);
@@ -301,12 +279,12 @@ test("resumeStrategy continues silently only when every call is answered and the
kind: "continue",
});
assert.deepEqual(resumeStrategy([user("go", 1), toolCall(2), toolResult(3), steer("also", 4)], partial), {
- kind: "note",
+ kind: "continue",
});
assert.deepEqual(resumeStrategy([user("go", 1), toolCall(2), toolResult(3), resumeEntry(4)], partial), {
- kind: "note",
+ kind: "continue",
});
- assert.deepEqual(resumeStrategy([user("go", 1), toolCall(2), killed(3)], partial), { kind: "note" });
+ assert.deepEqual(resumeStrategy([user("go", 1), toolCall(2), killed(3)], partial), { kind: "continue" });
assert.deepEqual(resumeStrategy([safeCall(0, true), user("go", 1), toolCall(2)], { userSeq: 1, workEntries: 1 }), {
kind: "settle",
calls: [{ callId: "c2", tool: "execute" }],
@@ -319,16 +297,3 @@ test("resumeStrategy continues silently only when every call is answered and the
"retry",
);
});
-
-test("resume notes name exactly the cause the run store recorded", () => {
- assert.match(resumeNote({ cause: { kind: "shutdown" } }), /mid-turn — a routine platform deploy\./);
- assert.match(
- resumeNote({ cause: { kind: "error", code: "transient", status: 503 } }),
- /a model-provider call failed \(transient, HTTP 503\)/,
- );
- assert.match(
- resumeNote({ strategy: { kind: "restart" }, cause: { kind: "lease_expired" } }),
- /stopped before recording any work — the worker crashed\. Start the request now/,
- );
- assert.match(resumeNote({ cause: { kind: "error" } }), /— an internal error\./);
-});
diff --git a/test/turn-retry-replay.test.ts b/test/turn-retry-replay.test.ts
index 72d953f97..15f324ba8 100644
--- a/test/turn-retry-replay.test.ts
+++ b/test/turn-retry-replay.test.ts
@@ -68,11 +68,12 @@ function buildScenario(interruptAfterToolResult = false) {
turns.push(turn.input);
continued.push(turn.continueTurn);
environments.push(turn.environment);
- await turn.emit({
- type: "user",
- payload: { text: turn.input },
- scopeLabel: turn.scopeLabel,
- });
+ if (!turn.continueTurn)
+ await turn.emit({
+ type: "user",
+ payload: { text: turn.input },
+ scopeLabel: turn.scopeLabel,
+ });
if (interruptAfterToolResult && turns.length === 1) {
await turn.emit({
type: "tool_call",
@@ -297,12 +298,12 @@ test("a resume whose recorded work ends at a tool result asks the harness to con
assert.equal(retry.status, "ok");
assert.deepEqual(continued, [undefined, true], "unchanged inventories preserve assistant continuation");
assert.doesNotMatch(environments[1]!, /## Where you are|Environment changes/);
- assert.match(turns[1]!, /^\[system\] Your previous attempt/, "the note still travels as the fallback input");
+ assert.equal(turns[1], ASK, "only the original request travels, as the harness's fallback");
assert.equal((await asks()).length, 1);
});
test("a changed inventory on retry reaches the model instead of continuing past the update", async () => {
- const { orchestrator, runs, continued, environments, sandbox, input, asks } = buildScenario(true);
+ const { orchestrator, runs, turns, continued, environments, sandbox, input, asks } = buildScenario(true);
sandbox.profile.spec = { os: "Old Linux" };
const run = (await runs.enqueue({ sessionId: conversation.threadRef, request: input(ASK) })).run;
await assert.rejects(
@@ -315,14 +316,15 @@ test("a changed inventory on retry reaches the model instead of continuing past
const retry = await orchestrator.handleTurn(input(ASK, { runId: run.id, attempt: 2 }));
assert.equal(retry.status, "ok");
assert.deepEqual(continued, [undefined, undefined], "the new user message carries changed inventory");
+ assert.equal(turns[1], "", "the request is not re-sent with the changed inventory");
assert.match(environments[1]!, /Environment changes/);
assert.match(environments[1]!, /New Linux/);
assert.doesNotMatch(environments[1]!, /Old Linux|## Where you are/);
assert.equal((await asks()).length, 1);
});
-test("a resume whose last tool call has no recorded result is not asked to continue", async () => {
- const { orchestrator, sessions, runs, continued, input } = buildScenario();
+test("a resume whose last tool call has no recorded result settles it and does not re-send the request", async () => {
+ const { orchestrator, sessions, runs, turns, continued, input } = buildScenario();
const run = (await runs.enqueue({ sessionId: conversation.threadRef, request: input(ASK) })).run;
const marker = await seedTurn(sessions, [
{ type: "user", payload: { text: ASK } },
@@ -332,7 +334,13 @@ test("a resume whose last tool call has no recorded result is not asked to conti
const retry = await orchestrator.handleTurn(input(ASK, { runId: run.id, attempt: 2 }));
assert.equal(retry.status, "ok");
- assert.deepEqual(continued, [undefined]);
+ assert.deepEqual(continued, [undefined], "the seeded turn has no recorded environment, so its context is sent");
+ assert.equal(turns[0], "");
+ const settled = (await sessions.getEntries((await sessions.getByThread(conversation.threadRef))!.id)).find(
+ (e) => e.type === "tool_result",
+ );
+ assert.ok(settled);
+ assert.match(String((settled.payload as { result?: unknown }).result), /^\[system\] This call was interrupted/);
});
test("a first attempt and a no-work retry are never asked to continue", async () => {