Skip to content

Commit 29af4ad

Browse files
committed
feat: trigger compaction for oversized transcripts
1 parent d5063d5 commit 29af4ad

17 files changed

Lines changed: 230 additions & 15 deletions

‎CHANGELOG.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,10 @@ Docs: https://docs.openclaw.ai
44

55
## Unreleased
66

7+
### Changes
8+
9+
- Agents/compaction: add an opt-in `agents.defaults.compaction.maxActiveTranscriptBytes` preflight trigger that runs normal local compaction when the active JSONL grows too large, requiring transcript rotation so successful compaction moves future turns onto a smaller successor file instead of raw byte-splitting history. Thanks @vincentkoc.
10+
711
### Fixes
812

913
- Cron: classify isolated runs as errors when final output narrates known execution-denial markers such as `SYSTEM_RUN_DENIED`, `INVALID_REQUEST`, or approval-binding refusal phrases, so blocked commands no longer appear green in cron history. Fixes #67172; carries forward #67186. Thanks @oc-gh-dr, @hclsys, and @1yihui.
Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
29181dbaa26242ced515ba4c2b363853a24b5b2623b33ecfede252c2a984b7c6 config-baseline.json
2-
2edac1da06bbb3709375bf82ae68890c67634f5ad3200a98a1d008b22c335e79 config-baseline.core.json
1+
0c3eaaee031f0adec2fcfc8a3a6a0d80dfc19d4d1c10b0ff4249b30e04b3c47d config-baseline.json
2+
420269ce22f17382cb253c80a232329e943296be101cda313506341ae39cc674 config-baseline.core.json
33
07963db49502132f26db396c56b36e018b110e6c55a68b3cb012d3ec96f43901 config-baseline.channel.json
44
74b74cb18ac37c0acaa765f398f1f9edbcee4c43567f02d45c89598a1e13afb4 config-baseline.plugin.json

‎docs/concepts/compaction.md‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -124,6 +124,16 @@ active successor transcript from the compaction summary, preserved state, and
124124
unsummarized tail, then keeps the previous JSONL as the archived checkpoint
125125
source.
126126

127+
When `agents.defaults.compaction.maxActiveTranscriptBytes` is set, OpenClaw can
128+
trigger normal local compaction before a run if the active JSONL reaches that
129+
size. This is useful for long-running sessions where provider-side context
130+
management may keep model context healthy while the local transcript keeps
131+
growing. It does not split raw JSONL bytes; it only asks the normal compaction
132+
pipeline to create a semantic summary. Combine it with
133+
`truncateAfterCompaction: true` to move future turns onto the smaller successor
134+
transcript; without transcript rotation, the byte guard remains inactive because
135+
the active file would not shrink.
136+
127137
## Using a different model
128138

129139
By default, compaction uses your agent's primary model. You can use a more

‎docs/gateway/config-agents.md‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -554,6 +554,8 @@ Periodic heartbeat runs.
554554
qualityGuard: { enabled: true, maxRetries: 1 },
555555
postCompactionSections: ["Session Startup", "Red Lines"], // [] disables reinjection
556556
model: "openrouter/anthropic/claude-sonnet-4-6", // optional compaction-only model override
557+
truncateAfterCompaction: true, // rotate to a smaller successor JSONL after compaction
558+
maxActiveTranscriptBytes: "20mb", // optional preflight local compaction trigger
557559
notifyUser: true, // send brief notices when compaction starts and completes (default: false)
558560
memoryFlush: {
559561
enabled: true,
@@ -576,6 +578,7 @@ Periodic heartbeat runs.
576578
- `qualityGuard`: retry-on-malformed-output checks for safeguard summaries. Enabled by default in safeguard mode; set `enabled: false` to skip the audit.
577579
- `postCompactionSections`: optional AGENTS.md H2/H3 section names to re-inject after compaction. Defaults to `["Session Startup", "Red Lines"]`; set `[]` to disable reinjection. When unset or explicitly set to that default pair, older `Every Session`/`Safety` headings are also accepted as a legacy fallback.
578580
- `model`: optional `provider/model-id` override for compaction summarization only. Use this when the main session should keep one model but compaction summaries should run on another; when unset, compaction uses the session's primary model.
581+
- `maxActiveTranscriptBytes`: optional byte threshold (`number` or strings like `"20mb"`) that triggers normal local compaction before a run when the active JSONL grows past the threshold. Requires `truncateAfterCompaction` so successful compaction can rotate to a smaller successor transcript. Disabled when unset or `0`.
579582
- `notifyUser`: when `true`, sends brief notices to the user when compaction starts and when it completes (for example, "Compacting context..." and "Compaction complete"). Disabled by default to keep compaction silent.
580583
- `memoryFlush`: silent agentic turn before auto-compaction to store durable memories. Skipped when workspace is read-only.
581584

‎docs/reference/session-management-compaction.md‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -259,6 +259,13 @@ Where:
259259

260260
These are Pi runtime semantics (OpenClaw consumes the events, but Pi decides when to compact).
261261

262+
OpenClaw can also trigger a preflight local compaction before opening the next
263+
run when `agents.defaults.compaction.maxActiveTranscriptBytes` is set and the
264+
active transcript file reaches that size. This is a file-size guard for local
265+
reopen cost, not raw archival: OpenClaw still runs normal semantic compaction,
266+
and it requires `truncateAfterCompaction` so the compacted summary can become a
267+
new successor transcript.
268+
262269
---
263270

264271
## Compaction settings (`reserveTokens`, `keepRecentTokens`)
@@ -285,6 +292,11 @@ OpenClaw also enforces a safety floor for embedded runs:
285292
and keeps Pi's recent-tail cut point. Without an explicit keep budget,
286293
manual compaction remains a hard checkpoint and rebuilt context starts from
287294
the new summary.
295+
- Set `agents.defaults.compaction.maxActiveTranscriptBytes` to a byte value or
296+
string such as `"20mb"` to run local compaction before a turn when the active
297+
transcript gets large. This guard is active only when
298+
`truncateAfterCompaction` is also enabled. Leave it unset or set `0` to
299+
disable.
288300
- When `agents.defaults.compaction.truncateAfterCompaction` is enabled,
289301
OpenClaw rotates the active transcript to a compacted successor JSONL after
290302
compaction. The old full transcript remains archived and linked from the

‎src/auto-reply/reply/agent-runner-memory.test.ts‎

Lines changed: 110 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -364,6 +364,116 @@ describe("runMemoryFlushIfNeeded", () => {
364364
});
365365
});
366366

367+
it("triggers preflight compaction when the active transcript exceeds the configured byte threshold", async () => {
368+
const sessionFile = path.join(rootDir, "large-session.jsonl");
369+
await fs.writeFile(
370+
sessionFile,
371+
`${JSON.stringify({ message: { role: "user", content: "x".repeat(256) } })}\n`,
372+
"utf8",
373+
);
374+
const sessionEntry: SessionEntry = {
375+
sessionId: "session",
376+
sessionFile,
377+
updatedAt: Date.now(),
378+
totalTokens: 10,
379+
totalTokensFresh: true,
380+
compactionCount: 0,
381+
};
382+
const sessionStore = { main: sessionEntry };
383+
const replyOperation = {
384+
abortSignal: new AbortController().signal,
385+
setPhase: vi.fn(),
386+
updateSessionId: vi.fn(),
387+
};
388+
389+
const entry = await runPreflightCompactionIfNeeded({
390+
cfg: {
391+
agents: {
392+
defaults: {
393+
compaction: {
394+
truncateAfterCompaction: true,
395+
maxActiveTranscriptBytes: "10b",
396+
},
397+
},
398+
},
399+
},
400+
followupRun: createTestFollowupRun({
401+
sessionId: "session",
402+
sessionFile,
403+
sessionKey: "main",
404+
}),
405+
defaultModel: "anthropic/claude-opus-4-6",
406+
agentCfgContextTokens: 100_000,
407+
sessionEntry,
408+
sessionStore,
409+
sessionKey: "main",
410+
storePath: path.join(rootDir, "sessions.json"),
411+
isHeartbeat: false,
412+
replyOperation: replyOperation as never,
413+
});
414+
415+
expect(entry?.compactionCount).toBe(1);
416+
expect(replyOperation.setPhase).toHaveBeenCalledWith("preflight_compacting");
417+
const compactCall = compactEmbeddedPiSessionMock.mock.calls[0]?.[0] as {
418+
currentTokenCount?: number;
419+
sessionFile?: string;
420+
sessionId?: string;
421+
trigger?: string;
422+
};
423+
expect(compactCall).toEqual(
424+
expect.objectContaining({
425+
sessionId: "session",
426+
trigger: "budget",
427+
currentTokenCount: 10,
428+
}),
429+
);
430+
expect(compactCall.sessionFile).toContain("large-session.jsonl");
431+
});
432+
433+
it("keeps the active transcript byte threshold inactive unless transcript rotation is enabled", async () => {
434+
const sessionFile = path.join(rootDir, "large-session-no-rotation.jsonl");
435+
await fs.writeFile(
436+
sessionFile,
437+
`${JSON.stringify({ message: { role: "user", content: "x".repeat(256) } })}\n`,
438+
"utf8",
439+
);
440+
const sessionEntry: SessionEntry = {
441+
sessionId: "session",
442+
sessionFile,
443+
updatedAt: Date.now(),
444+
totalTokens: 10,
445+
totalTokensFresh: true,
446+
compactionCount: 0,
447+
};
448+
449+
const entry = await runPreflightCompactionIfNeeded({
450+
cfg: {
451+
agents: {
452+
defaults: {
453+
compaction: {
454+
maxActiveTranscriptBytes: "10b",
455+
},
456+
},
457+
},
458+
},
459+
followupRun: createTestFollowupRun({
460+
sessionId: "session",
461+
sessionFile,
462+
sessionKey: "main",
463+
}),
464+
defaultModel: "anthropic/claude-opus-4-6",
465+
agentCfgContextTokens: 100_000,
466+
sessionEntry,
467+
sessionStore: { main: sessionEntry },
468+
sessionKey: "main",
469+
isHeartbeat: false,
470+
replyOperation: createReplyOperation(),
471+
});
472+
473+
expect(entry).toBe(sessionEntry);
474+
expect(compactEmbeddedPiSessionMock).not.toHaveBeenCalled();
475+
});
476+
367477
it("uses configured prompts and stored bootstrap warning signatures", async () => {
368478
const sessionEntry: SessionEntry = {
369479
sessionId: "session",

‎src/auto-reply/reply/agent-runner-memory.ts‎

Lines changed: 30 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ import {
3535
} from "./agent-runner-utils.js";
3636
import {
3737
hasAlreadyFlushedForCurrentCompaction,
38+
resolveMaxActiveTranscriptBytes,
3839
resolveMemoryFlushContextWindowTokens,
3940
shouldRunMemoryFlush,
4041
shouldRunPreflightCompaction,
@@ -400,8 +401,25 @@ export async function runPreflightCompactionIfNeeded(params: {
400401
typeof persistedTotalTokens === "number" &&
401402
Number.isFinite(persistedTotalTokens) &&
402403
persistedTotalTokens > 0;
404+
const maxActiveTranscriptBytes = resolveMaxActiveTranscriptBytes(params.cfg);
405+
const shouldCheckActiveTranscriptBytes = typeof maxActiveTranscriptBytes === "number";
406+
const transcriptSizeSnapshot = shouldCheckActiveTranscriptBytes
407+
? await readSessionLogSnapshot({
408+
sessionId: entry.sessionId,
409+
sessionEntry: entry,
410+
sessionKey: params.sessionKey ?? params.followupRun.run.sessionKey,
411+
opts: { storePath: params.storePath },
412+
includeByteSize: true,
413+
includeUsage: false,
414+
})
415+
: undefined;
416+
const activeTranscriptBytes = transcriptSizeSnapshot?.byteSize;
417+
const shouldCompactByTranscriptBytes =
418+
typeof activeTranscriptBytes === "number" &&
419+
typeof maxActiveTranscriptBytes === "number" &&
420+
activeTranscriptBytes >= maxActiveTranscriptBytes;
403421
const shouldUseTranscriptFallback = entry.totalTokensFresh === false || !hasPersistedTotalTokens;
404-
if (!shouldUseTranscriptFallback) {
422+
if (!shouldUseTranscriptFallback && !shouldCompactByTranscriptBytes) {
405423
return entry ?? params.sessionEntry;
406424
}
407425
const promptTokenEstimate = estimatePromptTokensForMemoryFlush(
@@ -434,24 +452,31 @@ export async function runPreflightCompactionIfNeeded(params: {
434452
`isHeartbeat=${params.isHeartbeat} isCli=${isCli} ` +
435453
`persistedFresh=${entry?.totalTokensFresh === true} ` +
436454
`transcriptPromptTokens=${transcriptPromptTokens ?? "undefined"} ` +
437-
`promptTokensEst=${promptTokenEstimate ?? "undefined"}`,
455+
`promptTokensEst=${promptTokenEstimate ?? "undefined"} ` +
456+
`activeTranscriptBytes=${activeTranscriptBytes ?? "undefined"} ` +
457+
`maxActiveTranscriptBytes=${maxActiveTranscriptBytes ?? "undefined"} ` +
458+
`sizeTrigger=${shouldCompactByTranscriptBytes}`,
438459
);
439460

440-
const shouldCompact = shouldRunPreflightCompaction({
461+
const shouldCompactByTokens = shouldRunPreflightCompaction({
441462
entry,
442463
tokenCount: tokenCountForCompaction,
443464
contextWindowTokens,
444465
reserveTokensFloor,
445466
softThresholdTokens,
446467
});
468+
const shouldCompact = shouldCompactByTokens || shouldCompactByTranscriptBytes;
447469
if (!shouldCompact) {
448470
return entry ?? params.sessionEntry;
449471
}
450472

473+
const compactionTrigger = shouldCompactByTranscriptBytes ? "transcript_bytes" : "tokens";
451474
logVerbose(
452475
`preflightCompaction triggered: sessionKey=${params.sessionKey} ` +
453476
`tokenCount=${tokenCountForCompaction ?? freshPersistedTokens ?? "undefined"} ` +
454-
`threshold=${threshold}`,
477+
`threshold=${threshold} trigger=${compactionTrigger} ` +
478+
`activeTranscriptBytes=${activeTranscriptBytes ?? "undefined"} ` +
479+
`maxActiveTranscriptBytes=${maxActiveTranscriptBytes ?? "undefined"}`,
455480
);
456481

457482
params.replyOperation.setPhase("preflight_compacting");
@@ -486,7 +511,7 @@ export async function runPreflightCompactionIfNeeded(params: {
486511
thinkLevel: params.followupRun.run.thinkLevel,
487512
bashElevated: params.followupRun.run.bashElevated,
488513
trigger: "budget",
489-
currentTokenCount: tokenCountForCompaction,
514+
currentTokenCount: tokenCountForCompaction ?? freshPersistedTokens,
490515
senderIsOwner: params.followupRun.run.senderIsOwner,
491516
ownerNumbers: params.followupRun.run.ownerNumbers,
492517
abortSignal: params.replyOperation.abortSignal,

‎src/auto-reply/reply/memory-flush.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import crypto from "node:crypto";
22
import { resolveContextTokensForModel } from "../../agents/context.js";
33
import { DEFAULT_CONTEXT_TOKENS } from "../../agents/defaults.js";
4+
import { parseNonNegativeByteSize } from "../../config/byte-size.js";
45
import { resolveFreshSessionTotalTokens, type SessionEntry } from "../../config/sessions.js";
56
import type { OpenClawConfig } from "../../config/types.openclaw.js";
67

@@ -21,6 +22,15 @@ export function resolveMemoryFlushContextWindowTokens(params: {
2122
);
2223
}
2324

25+
export function resolveMaxActiveTranscriptBytes(cfg?: OpenClawConfig): number | undefined {
26+
const compaction = cfg?.agents?.defaults?.compaction;
27+
if (compaction?.truncateAfterCompaction !== true) {
28+
return undefined;
29+
}
30+
const parsed = parseNonNegativeByteSize(compaction.maxActiveTranscriptBytes);
31+
return typeof parsed === "number" && parsed > 0 ? parsed : undefined;
32+
}
33+
2434
function resolvePositiveTokenCount(value: number | undefined): number | undefined {
2535
return typeof value === "number" && Number.isFinite(value) && value > 0
2636
? Math.floor(value)

‎src/config/config.compaction-settings.test.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ describe("config compaction settings", () => {
3232
prompt: "Write notes.",
3333
systemPrompt: "Flush memory now.",
3434
},
35+
maxActiveTranscriptBytes: "20mb",
3536
});
3637

3738
expect(compaction?.reserveTokensFloor).toBe(12_345);
@@ -46,6 +47,7 @@ describe("config compaction settings", () => {
4647
expect(compaction?.memoryFlush?.softThresholdTokens).toBe(1234);
4748
expect(compaction?.memoryFlush?.prompt).toBe("Write notes.");
4849
expect(compaction?.memoryFlush?.systemPrompt).toBe("Flush memory now.");
50+
expect(compaction?.maxActiveTranscriptBytes).toBe("20mb");
4951
});
5052

5153
it("preserves pi compaction override values", () => {

‎src/config/config.schema-regressions.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -151,6 +151,7 @@ describe("config schema regressions", () => {
151151
defaults: {
152152
compaction: {
153153
truncateAfterCompaction: true,
154+
maxActiveTranscriptBytes: "20mb",
154155
},
155156
},
156157
},

0 commit comments

Comments
 (0)