Skip to content

Commit 0ee6dff

Browse files
fix(server): preserve summary recovery within handoff budgets
1 parent 5420bd7 commit 0ee6dff

2 files changed

Lines changed: 88 additions & 27 deletions

File tree

‎apps/server/src/orchestration-v2/ContextHandoffBudget.test.ts‎

Lines changed: 45 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1342,33 +1342,62 @@ describe("handoff delivery", () => {
13421342
it.effect.each([
13431343
{
13441344
budget: 6_000,
1345+
tailCount: 0,
1346+
grows: false,
13451347
shown: ["item:many-19", "item:many-18", "item:many-17"],
13461348
line: `17 more summaries hold omitted items; list them with ${listCall}.`,
13471349
},
13481350
{
13491351
budget: 1_400,
1352+
tailCount: 0,
1353+
grows: false,
13501354
shown: [],
13511355
line: `Not shown here: 20 conversation summaries hold omitted items; list them with ${listCall}.`,
13521356
},
1357+
{
1358+
budget: 16_000,
1359+
tailCount: 50,
1360+
grows: false,
1361+
shown: [],
1362+
line: `Not shown here: 20 conversation summaries hold omitted items; list them with ${listCall}.`,
1363+
},
1364+
{
1365+
budget: 3_448,
1366+
tailCount: 50,
1367+
grows: true,
1368+
shown: [],
1369+
line: `Not shown here: 10 conversation summaries hold omitted items; list them with ${listCall}.`,
1370+
},
13531371
])(
13541372
"still points at unsent summaries when their lines do not all fit: $budget",
1355-
({ budget, shown, line }) =>
1373+
({ budget, tailCount, grows, shown, line }) =>
13561374
Effect.gen(function* () {
1357-
const tools = Array.from({ length: 20 }, (_, index) => ({
1375+
const indexText = (index: number) => (grows ? String(index).padStart(2, "0") : index);
1376+
const tools = Array.from({ length: grows ? 30 : 20 }, (_, index) => ({
13581377
...message(
1359-
`item:many-${index}`,
1378+
`item:many-${indexText(index)}`,
13601379
"assistant",
13611380
`Command: step ${index}\n${"o".repeat(8_000)}`,
13621381
),
13631382
kind: "command_execution" as const,
13641383
}));
1384+
const tail =
1385+
tailCount === 0
1386+
? [message("item:many-kept", "user", "kept")]
1387+
: Array.from({ length: tailCount }, (_, index) =>
1388+
message(
1389+
`item:tail-${indexText(index)}`,
1390+
index % 2 === 0 ? "user" : "assistant",
1391+
"k".repeat(grows ? 1 : 64),
1392+
),
1393+
);
13651394
const idFor = (index: number) => `summary:${index.toString(16).padStart(64, "0")}`;
13661395
const source: OrchestrationV2ContextHandoff = {
13671396
...handoff,
13681397
id: ContextHandoffId.make("handoff:many-unsent"),
13691398
summaryText: "Coverage.",
13701399
history: {
1371-
messages: [...tools, message("item:many-kept", "user", "kept")],
1400+
messages: [...tools, ...tail],
13721401
coverage: "Coverage.",
13731402
omittedItems: 0,
13741403
},
@@ -1384,12 +1413,14 @@ describe("handoff delivery", () => {
13841413
alreadyDeliveredItemIds: new Set(),
13851414
summaries: () =>
13861415
Effect.succeed(
1387-
tools.toReversed().map((tool, index) => ({
1388-
id: idFor(19 - index),
1389-
...summaryScope,
1390-
coveredItemIds: [tool.itemId],
1391-
text: "S".repeat(40_000),
1392-
})),
1416+
(grows ? [...tools.slice(0, 9), tail[41]!] : tools.toReversed()).map(
1417+
(tool, index) => ({
1418+
id: idFor(grows ? index : 19 - index),
1419+
...summaryScope,
1420+
coveredItemIds: [tool.itemId],
1421+
text: "S".repeat(40_000),
1422+
}),
1423+
),
13931424
),
13941425
inject: (input) => {
13951426
injected = input;
@@ -1399,6 +1430,10 @@ describe("handoff delivery", () => {
13991430
});
14001431
yield* delivery.delivered;
14011432
assert.include(injected.context, line);
1433+
assert.includeMembers(
1434+
injected.messages.map((entry) => entry.itemId),
1435+
tail.slice(-6).map((entry) => entry.itemId),
1436+
);
14021437
for (const index of [19, 18, 17, 16]) {
14031438
const named = `${idFor(index)} holds`;
14041439
if (shown.includes(`item:many-${index}`)) assert.include(injected.context, named);

‎apps/server/src/orchestration-v2/ContextHandoffDelivery.ts‎

Lines changed: 43 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -70,9 +70,10 @@ function notShownBlock(input: {
7070
readonly omitted: ReadonlySet<string>;
7171
readonly messages: ReadonlyArray<OrchestrationV2HistoricalMessage>;
7272
readonly fits: (block: string) => boolean;
73-
}): string {
73+
}) {
7474
const lines = notShownLines(input);
75-
if (lines.length === 0) return "";
75+
if (lines.length === 0) return { text: "", fallback: "" };
76+
const fallback = `Not shown here: ${summaryCount(lines.length, "conversation")}; list them with ${listCall(lines[0]!.offer)}.`;
7677
for (let shown = Math.min(lines.length, NOT_SHOWN_LINES); shown > 0; shown--) {
7778
const rest = lines.slice(shown);
7879
const block = [
@@ -81,10 +82,9 @@ function notShownBlock(input: {
8182
? []
8283
: [`${summaryCount(rest.length, "more")}; list them with ${listCall(rest[0]!.offer)}.`]),
8384
].join("\n");
84-
if (input.fits(block)) return block;
85+
if (input.fits(block)) return { text: block, fallback };
8586
}
86-
const fallback = `Not shown here: ${summaryCount(lines.length, "conversation")}; list them with ${listCall(lines[0]!.offer)}.`;
87-
return input.fits(fallback) ? fallback : "";
87+
return { text: input.fits(fallback) ? fallback : "", fallback };
8888
}
8989

9090
function notShownLines(input: {
@@ -230,18 +230,19 @@ export const deliverContextHandoffs = Effect.fn("orchestrationV2.deliverContextH
230230
0,
231231
);
232232
const freshTail = new Set<string>(freshTailMessages(messages).map((message) => message.itemId));
233-
let selected = selectHistory({
233+
let selection: Parameters<typeof selectHistory>[0] = {
234234
messages,
235235
coverage: fullCoverage,
236236
omittedItems: priorOmittedCount,
237237
omittedItemIds: pending.flatMap((handoff) => handoff.history?.omittedItemIds ?? []),
238238
budget,
239239
first: freshTail,
240-
});
240+
};
241+
let selected = selectHistory(selection);
241242
const summarized = new Set<TurnItemId>();
242243
const chosen: Array<HandoffSummary> = [];
243244
let offered: ReadonlyArray<HandoffSummary> = [];
244-
const priorOmitted = new Set<string>(
245+
const priorOmitted = new Set<TurnItemId>(
245246
pending.flatMap((handoff) => handoff.history?.omittedItemIds ?? []),
246247
);
247248
if (
@@ -274,7 +275,7 @@ export const deliverContextHandoffs = Effect.fn("orchestrationV2.deliverContextH
274275
const proposed = new Set([...summarized, ...candidate.coveredItemIds]);
275276
const summaryBlock = [...chosen, candidate].map((summary) => summary.text).join("\n\n");
276277
const proposedIds = new Set<string>(proposed);
277-
const reduced = selectHistory({
278+
const proposedSelection = {
278279
messages: messages.filter((message) => !proposed.has(message.itemId)),
279280
coverage: `${fullCoverage}\n${proposed.size} older items are represented by the generated conversation summaries below instead of verbatim.\n${summaryBlock}`,
280281
omittedItems:
@@ -284,7 +285,8 @@ export const deliverContextHandoffs = Effect.fn("orchestrationV2.deliverContextH
284285
// Otherwise a newer tool result takes the room an older pinned message needs, and
285286
// the summary is refused for a loss it did not have to cause.
286287
first: pinned,
287-
});
288+
};
289+
const reduced = selectHistory(proposedSelection);
288290
// A summary earns its space only when more history arrives with it than without it.
289291
const kept = new Set<string>(reduced.messages.map((message) => message.itemId));
290292
if (
@@ -295,9 +297,39 @@ export const deliverContextHandoffs = Effect.fn("orchestrationV2.deliverContextH
295297
continue;
296298
chosen.push(candidate);
297299
for (const id of candidate.coveredItemIds) summarized.add(id);
300+
selection = proposedSelection;
298301
selected = reduced;
299302
}
300303
}
304+
const notShown = () =>
305+
notShownBlock({
306+
offers: offered.filter((offer) => !chosen.includes(offer)),
307+
omitted: new Set(
308+
[...priorOmitted, ...selected.omittedItemIds].filter((id) => !summarized.has(id)),
309+
),
310+
messages,
311+
fits: (block) => historyCost(selected.messages, `${selected.context}\n${block}`) <= budget,
312+
});
313+
let pointer = notShown();
314+
let reserved = 0;
315+
while (pointer.text === "" && pointer.fallback !== "") {
316+
const reserve =
317+
historyCost(selected.messages, `${selected.context}\n${pointer.fallback}`) -
318+
historyCost(selected.messages, selected.context);
319+
if (reserve <= reserved) break;
320+
const reduced = selectHistory({ ...selection, budget: budget - reserve });
321+
const kept = new Set<string>(reduced.messages.map((message) => message.itemId));
322+
// Older optional history yields to recovery instructions; the fresh tail stays pinned.
323+
if (
324+
selected.messages.some(
325+
(message) => freshTail.has(message.itemId) && !kept.has(message.itemId),
326+
)
327+
)
328+
break;
329+
reserved = reserve;
330+
selected = reduced;
331+
pointer = notShown();
332+
}
301333
const summaryFactIds = [
302334
...new Set(chosen.flatMap((summary) => summary.knowledgeFactIds ?? [])),
303335
];
@@ -349,13 +381,7 @@ export const deliverContextHandoffs = Effect.fn("orchestrationV2.deliverContextH
349381
omittedHaveSummaries: omittedHaveSummaries(stillOmitted(handoff)),
350382
}),
351383
);
352-
const notShown = notShownBlock({
353-
offers: offered.filter((offer) => !chosen.includes(offer)),
354-
omitted: new Set(pending.flatMap((handoff) => [...stillOmitted(handoff)])),
355-
messages,
356-
fits: (block) => historyCost(selected.messages, `${selected.context}\n${block}`) <= budget,
357-
});
358-
const context = notShown === "" ? selected.context : `${selected.context}\n${notShown}`;
384+
const context = pointer.text === "" ? selected.context : `${selected.context}\n${pointer.text}`;
359385
const estimatedTokens = historyCost(selected.messages, context);
360386
if (estimatedTokens > budget) {
361387
if (input.deferInline) return empty;

0 commit comments

Comments
 (0)