Skip to content

Commit 61bc612

Browse files
authored
test(agents): trim compaction duplicate coverage (#123903)
1 parent 27bf9c2 commit 61bc612

4 files changed

Lines changed: 2 additions & 156 deletions

File tree

‎src/agents/agent-hooks/compaction-safeguard.test-support.ts‎

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@ type CompactionSafeguardTestApi = {
77
formatToolFailuresSection: CallableFunction;
88
splitPreservedRecentTurns: CallableFunction;
99
formatPreservedTurnsSection: CallableFunction;
10-
formatSplitTurnContextSection: CallableFunction;
1110
buildCompactionStructureInstructions: CallableFunction;
1211
buildStructuredFallbackSummary: CallableFunction;
1312
prependPreviousSummaryForRedistill: CallableFunction;
@@ -33,7 +32,6 @@ type CompactionSafeguardTestApi = {
3332
SUMMARY_TRUNCATED_MARKER: string;
3433
CONTEXT_TRUNCATED_MARKER: string;
3534
MAX_SPLIT_TURN_CONTEXT_CHARS: number;
36-
SPLIT_TURN_TRUNCATED_MARKER: string;
3735
};
3836

3937
function getTestApi(): CompactionSafeguardTestApi {

‎src/agents/agent-hooks/compaction-safeguard.test.ts‎

Lines changed: 1 addition & 73 deletions
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,6 @@ const {
8282
formatToolFailuresSection,
8383
splitPreservedRecentTurns,
8484
formatPreservedTurnsSection,
85-
formatSplitTurnContextSection,
8685
buildCompactionStructureInstructions,
8786
buildStructuredFallbackSummary,
8887
prependPreviousSummaryForRedistill,
@@ -105,7 +104,6 @@ const {
105104
SUMMARY_TRUNCATED_MARKER,
106105
CONTEXT_TRUNCATED_MARKER,
107106
MAX_SPLIT_TURN_CONTEXT_CHARS,
108-
SPLIT_TURN_TRUNCATED_MARKER,
109107
} = testing;
110108

111109
function auditSummaryQuality(
@@ -498,43 +496,6 @@ describe("compaction-safeguard tool failures", () => {
498496
});
499497

500498
describe("compaction-safeguard summary budgets", () => {
501-
it.each([
502-
{ bodyLength: 60, suffixLength: 0, maxChars: 100, overflows: false },
503-
{ bodyLength: 60, suffixLength: 40, maxChars: 100, overflows: false },
504-
{ bodyLength: 80, suffixLength: 10, maxChars: 100, overflows: false },
505-
{ bodyLength: 80, suffixLength: 21, maxChars: 100, overflows: true },
506-
{ bodyLength: 20, suffixLength: 100, maxChars: 100, overflows: true },
507-
])(
508-
"uses the slack-aware body allocation at body=$bodyLength suffix=$suffixLength cap=$maxChars",
509-
({ bodyLength, suffixLength, maxChars, overflows }) => {
510-
const body = "b".repeat(bodyLength);
511-
const suffix = "s".repeat(suffixLength);
512-
513-
const capped = capCompactionSummaryPreservingSuffix(body, suffix, maxChars);
514-
515-
expect(capped.length).toBeLessThanOrEqual(maxChars);
516-
if (!overflows) {
517-
expect(capped).toBe(`${body}${suffix}`);
518-
return;
519-
}
520-
const bodyFloor = Math.min(bodyLength, Math.max(1, Math.ceil(maxChars / 2)));
521-
const bodySlot = Math.min(
522-
bodyLength,
523-
Math.max(bodyFloor, maxChars - Math.min(suffixLength, maxChars)),
524-
);
525-
if (bodyLength > bodySlot && bodySlot >= SUMMARY_TRUNCATED_MARKER.length) {
526-
expect(capped).toContain(SUMMARY_TRUNCATED_MARKER);
527-
}
528-
if (suffixLength > maxChars - Math.min(bodyLength, bodySlot)) {
529-
expect(capped).toContain(
530-
maxChars - Math.min(bodyLength, bodySlot) > CONTEXT_TRUNCATED_MARKER.length
531-
? CONTEXT_TRUNCATED_MARKER
532-
: "s",
533-
);
534-
}
535-
},
536-
);
537-
538499
it("caps file operations summary and reports omitted entries", () => {
539500
const readFiles = Array.from(
540501
{ length: 200 },
@@ -655,40 +616,6 @@ describe("compaction-safeguard summary budgets", () => {
655616
expect(capped).toContain("<read-files>");
656617
expect(capped).toContain("## Session Startup");
657618
});
658-
659-
it("keeps generated summary content when an oversized suffix exhausts the artifact budget", () => {
660-
const body = "BODY-START\nBODY-MIDDLE\nBODY-END";
661-
const oversizedSuffix = `${"old context\n".repeat(MAX_COMPACTION_SUMMARY_CHARS)}CRITICAL-TAIL`;
662-
663-
const capped = capCompactionSummaryPreservingSuffix(body, oversizedSuffix);
664-
665-
expect(capped.length).toBeLessThanOrEqual(MAX_COMPACTION_SUMMARY_CHARS);
666-
expect(capped).toContain("BODY-START");
667-
expect(capped).toContain("BODY-MIDDLE");
668-
expect(capped).toContain("BODY-END");
669-
expect(capped).toContain("CRITICAL-TAIL");
670-
expect(capped).toContain("truncated");
671-
});
672-
673-
it("keeps an oversized preserved suffix UTF-16 safe at its leading edge", () => {
674-
expect(capCompactionSummaryPreservingSuffix("body", "A🚀tail", 5)).toBe("bodil");
675-
});
676-
677-
it("bounds raw split-turn context on whole-message boundaries and retains the newest end", () => {
678-
const messages = Array.from({ length: 20 }, (_, index) => ({
679-
role: "user" as const,
680-
content: `message-${String(index).padStart(2, "0")}-${"x".repeat(700)}`,
681-
timestamp: index,
682-
}));
683-
684-
const section = formatSplitTurnContextSection(messages) as string;
685-
686-
expect(section.length).toBeLessThanOrEqual(MAX_SPLIT_TURN_CONTEXT_CHARS);
687-
expect(section).toContain(SPLIT_TURN_TRUNCATED_MARKER.trim());
688-
expect(section).not.toContain("message-00-");
689-
expect(section).toContain("message-19-");
690-
expect(section.split("\n").some((line) => line.startsWith("x"))).toBe(false);
691-
});
692619
});
693620

694621
describe("computeAdaptiveChunkRatio", () => {
@@ -3123,6 +3050,7 @@ describe("compaction-safeguard recent-turn preservation", () => {
31233050
const retainedSuffix = summary.split(CONTEXT_TRUNCATED_MARKER)[1] ?? "";
31243051
const firstRetainedLine = retainedSuffix.split("\n").find((line) => line.length > 0);
31253052
expect(firstRetainedLine).toMatch(/^- User: raw-prefix-\d{2}-/);
3053+
expect(summary).toContain("raw-prefix-19-");
31263054
expect(summary.length).toBeLessThanOrEqual(MAX_COMPACTION_SUMMARY_CHARS);
31273055
expect(summary).toContain("## Recent turns preserved verbatim");
31283056
});

‎src/agents/agent-hooks/compaction-safeguard.ts‎

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -965,10 +965,6 @@ function buildSplitTurnContextSection(
965965
});
966966
}
967967

968-
function formatSplitTurnContextSection(messages: AgentMessage[], onTruncated?: () => void): string {
969-
return buildSplitTurnContextSection(messages, onTruncated).text;
970-
}
971-
972968
function formatGeneratedSplitTurnSection(summary: string, onTruncated?: () => void): string {
973969
const heading = "**Turn Context (split turn):**\n\n";
974970
const summaryBudget = MAX_SPLIT_TURN_CONTEXT_CHARS - heading.length;
@@ -1512,7 +1508,6 @@ const testing = {
15121508
formatToolFailuresSection,
15131509
splitPreservedRecentTurns,
15141510
formatPreservedTurnsSection,
1515-
formatSplitTurnContextSection,
15161511
buildCompactionStructureInstructions,
15171512
buildStructuredFallbackSummary,
15181513
prependPreviousSummaryForRedistill,
@@ -1538,7 +1533,6 @@ const testing = {
15381533
SUMMARY_TRUNCATED_MARKER,
15391534
CONTEXT_TRUNCATED_MARKER,
15401535
MAX_SPLIT_TURN_CONTEXT_CHARS,
1541-
SPLIT_TURN_TRUNCATED_MARKER,
15421536
} as const;
15431537

15441538
if (process.env.VITEST || process.env.NODE_ENV === "test") {

‎src/agents/sessions/agent-session-compaction.test.ts‎

Lines changed: 1 addition & 75 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,6 @@
1-
import path from "node:path";
21
import type { AssistantMessage, Context, Model } from "openclaw/plugin-sdk/llm";
3-
import { afterEach, describe, expect, it } from "vitest";
4-
import { useAutoCleanupTempDirTracker } from "../../../test/helpers/temp-dir.js";
5-
import {
6-
appendTranscriptMessage,
7-
upsertSessionEntryCore,
8-
} from "../../config/sessions/session-accessor.js";
9-
import { resolveSqliteTargetFromSessionStorePath } from "../../config/sessions/session-sqlite-target.js";
10-
import { closeOpenClawAgentDatabaseByPath } from "../../state/openclaw-agent-db.js";
2+
import { describe, expect, it } from "vitest";
113
import { MAX_OVERFLOW_COMPACTION_ATTEMPTS } from "../agent-compaction-constants.js";
12-
import { testing as compactionSafeguardTesting } from "../agent-hooks/compaction-safeguard.test-support.js";
134
import {
145
createAssistant,
156
createAssistantResultStream,
@@ -29,7 +20,6 @@ import { SessionManager } from "./session-manager.js";
2920
import { SettingsManager } from "./settings-manager.js";
3021

3122
registerAgentSessionLoopTestLifecycle();
32-
const tempDirs = useAutoCleanupTempDirTracker(afterEach);
3323

3424
function createStaleThinkingContent(): AssistantMessage["content"] {
3525
return [
@@ -42,70 +32,6 @@ function createStaleThinkingContent(): AssistantMessage["content"] {
4232
}
4333

4434
describe("AgentSession compaction", () => {
45-
it("persists and replays a body-preserving oversized-suffix artifact after reopen", async () => {
46-
const dir = tempDirs.make("openclaw-body-preserving-compaction-");
47-
const target = {
48-
agentId: "main",
49-
sessionId: "body-preserving-compaction",
50-
sessionKey: "agent:main:body-preserving-compaction",
51-
storePath: path.join(dir, "sessions.json"),
52-
};
53-
await upsertSessionEntryCore(target, { sessionId: target.sessionId, updatedAt: 1 });
54-
await appendTranscriptMessage(target, {
55-
cwd: dir,
56-
message: { role: "user", content: "authoritative question", timestamp: 1 },
57-
});
58-
const sessionManager = SessionManager.open(target, dir);
59-
const retainedAssistantId = sessionManager.appendMessage(
60-
createAssistant(testModel, [{ type: "text", text: "authoritative answer" }]),
61-
);
62-
const body = "BODY-MARKER\n## Decisions\nKeep the generated summary.";
63-
const suffix = `${"older split-turn context\n".repeat(2_000)}SELECTED-SUFFIX-CONTEXT`;
64-
const finalized = compactionSafeguardTesting.capCompactionSummaryPreservingSuffix(
65-
body,
66-
suffix,
67-
) as string;
68-
expect(finalized).toContain("BODY-MARKER");
69-
expect(finalized).toContain("Earlier compaction context truncated");
70-
expect(finalized).toContain("SELECTED-SUFFIX-CONTEXT");
71-
const handlers = createCompactionHandlers();
72-
handlers.set("session_before_compact", [
73-
async (event: unknown) => ({
74-
compaction: {
75-
summary: finalized,
76-
firstKeptEntryId: retainedAssistantId,
77-
tokensBefore: (event as { preparation: { tokensBefore: number } }).preparation
78-
.tokensBefore,
79-
},
80-
}),
81-
]);
82-
const { session } = await createTestSession({
83-
sessionManager,
84-
resourceLoader: createResourceLoader(handlers),
85-
});
86-
87-
const result = await session.compact();
88-
89-
expect(result.summary).toBe(finalized);
90-
expect(sessionManager.getBranch().filter((entry) => entry.type === "compaction")).toHaveLength(
91-
1,
92-
);
93-
expect(JSON.stringify(sessionManager.buildSessionContext())).toContain("BODY-MARKER");
94-
sessionManager.flushPendingPersistence();
95-
const databasePath = resolveSqliteTargetFromSessionStorePath(target.storePath).path;
96-
expect(closeOpenClawAgentDatabaseByPath(databasePath)).toBe(true);
97-
const reopened = SessionManager.open(target, dir);
98-
try {
99-
expect(reopened.getBranch().findLast((entry) => entry.type === "compaction")).toMatchObject({
100-
summary: finalized,
101-
});
102-
expect(JSON.stringify(reopened.buildSessionContext())).toContain("BODY-MARKER");
103-
expect(JSON.stringify(reopened.buildSessionContext())).toContain("SELECTED-SUFFIX-CONTEXT");
104-
} finally {
105-
closeOpenClawAgentDatabaseByPath(databasePath);
106-
}
107-
});
108-
10935
it.each(Array.from({ length: MAX_OVERFLOW_COMPACTION_ATTEMPTS }, (_, index) => index + 1))(
11036
"recovers when the provider accepts overflow compaction attempt %i",
11137
async (overflowCount) => {

0 commit comments

Comments
 (0)