Skip to content

Commit 13c224c

Browse files
steipeteATKasem
andcommitted
fix(agents): resolve effective runtime before preflight byte-guard compaction (#108984)
Co-authored-by: ATKasem <[email protected]>
1 parent 5434550 commit 13c224c

2 files changed

Lines changed: 135 additions & 65 deletions

File tree

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

Lines changed: 97 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,20 @@ function registerMemoryFlushPlanResolverForTest(resolver: MemoryFlushPlanResolve
4444
registerMemoryCapability("memory-core", { flushPlanResolver: resolver });
4545
}
4646

47+
function registerClaudeCliBackend(ownsNativeCompaction = false): void {
48+
cliBackendsTesting.setDepsForTest({
49+
resolveRuntimeCliBackends: () => [
50+
{
51+
id: "claude-cli",
52+
modelProvider: "anthropic",
53+
pluginId: "anthropic",
54+
config: { command: "claude" },
55+
ownsNativeCompaction,
56+
},
57+
],
58+
});
59+
}
60+
4761
type TestReplyOperation = ReplyOperation & {
4862
setPhase: ReturnType<typeof vi.fn<ReplyOperation["setPhase"]>>;
4963
updateSessionId: ReturnType<typeof vi.fn<ReplyOperation["updateSessionId"]>>;
@@ -1311,16 +1325,7 @@ describe("runMemoryFlushIfNeeded", () => {
13111325
});
13121326

13131327
it("skips memory flush for compatible CLI session runtime pins", async () => {
1314-
cliBackendsTesting.setDepsForTest({
1315-
resolveRuntimeCliBackends: () => [
1316-
{
1317-
id: "claude-cli",
1318-
modelProvider: "anthropic",
1319-
pluginId: "anthropic",
1320-
config: { command: "claude" },
1321-
},
1322-
],
1323-
});
1328+
registerClaudeCliBackend();
13241329
const sessionEntry: SessionEntry = {
13251330
sessionId: "session",
13261331
updatedAt: Date.now(),
@@ -2177,16 +2182,7 @@ describe("runMemoryFlushIfNeeded", () => {
21772182
});
21782183

21792184
it("skips preflight compaction for compatible CLI session runtime pins", async () => {
2180-
cliBackendsTesting.setDepsForTest({
2181-
resolveRuntimeCliBackends: () => [
2182-
{
2183-
id: "claude-cli",
2184-
modelProvider: "anthropic",
2185-
pluginId: "anthropic",
2186-
config: { command: "claude" },
2187-
},
2188-
],
2189-
});
2185+
registerClaudeCliBackend();
21902186
registerMemoryFlushPlanResolverForTest(() => ({
21912187
softThresholdTokens: 4_000,
21922188
forceFlushTranscriptBytes: 1_000_000_000,
@@ -2680,7 +2676,87 @@ describe("runMemoryFlushIfNeeded", () => {
26802676
expect(compactCall.sessionFile).toContain("large-session.jsonl");
26812677
});
26822678

2683-
it("triggers preflight compaction when a SQLite-backed transcript exceeds the configured byte threshold", async () => {
2679+
it("skips OpenClaw maintenance when model policy routes a SQLite session to native-compacting claude-cli", async () => {
2680+
registerClaudeCliBackend(true);
2681+
registerMemoryFlushPlanResolverForTest(() => ({
2682+
softThresholdTokens: 4_000,
2683+
forceFlushTranscriptBytes: 10,
2684+
reserveTokensFloor: 20_000,
2685+
prompt: "Pre-compaction memory flush.\nNO_REPLY",
2686+
systemPrompt: "Write memory to memory/YYYY-MM-DD.md.",
2687+
relativePath: "memory/2023-11-14.md",
2688+
}));
2689+
const storePath = path.join(rootDir, "sqlite-cli-owned-session.json");
2690+
const sessionKey = "agent:main:main";
2691+
const scope = { agentId: "main", sessionId: "session", sessionKey, storePath };
2692+
await upsertSessionEntry(scope, { sessionId: "session", updatedAt: 10 });
2693+
await replaceSqliteTranscriptEvents(scope, [
2694+
{ message: { role: "user", content: "x".repeat(256) }, type: "message" },
2695+
]);
2696+
expect(readTranscriptStatsSync(scope).sizeBytes).toBeGreaterThan(10);
2697+
2698+
const sessionEntry: SessionEntry = {
2699+
sessionId: "session",
2700+
updatedAt: Date.now(),
2701+
totalTokens: 10,
2702+
totalTokensFresh: true,
2703+
compactionCount: 0,
2704+
};
2705+
const cfg = {
2706+
agents: {
2707+
defaults: {
2708+
models: {
2709+
"anthropic/claude-opus-4-6": { agentRuntime: { id: "claude-cli" } },
2710+
},
2711+
compaction: {
2712+
memoryFlush: {},
2713+
maxActiveTranscriptBytes: "10b",
2714+
},
2715+
},
2716+
},
2717+
} as const;
2718+
const followupRun = createTestFollowupRun({
2719+
provider: "anthropic",
2720+
model: "claude-opus-4-6",
2721+
sessionId: "session",
2722+
sessionKey,
2723+
});
2724+
2725+
const flushResult = await runMemoryFlushIfNeeded({
2726+
cfg,
2727+
followupRun,
2728+
sessionCtx: { Provider: "whatsapp" } as unknown as TemplateContext,
2729+
defaultModel: "anthropic/claude-opus-4-6",
2730+
agentCfgContextTokens: 100_000,
2731+
resolvedVerboseLevel: "off",
2732+
sessionEntry,
2733+
sessionStore: { [sessionKey]: sessionEntry },
2734+
sessionKey,
2735+
storePath,
2736+
isHeartbeat: false,
2737+
replyOperation: createReplyOperation(),
2738+
});
2739+
const preflightEntry = await runPreflightCompactionIfNeeded({
2740+
cfg,
2741+
followupRun,
2742+
defaultModel: "anthropic/claude-opus-4-6",
2743+
agentCfgContextTokens: 100_000,
2744+
sessionEntry,
2745+
sessionStore: { [sessionKey]: sessionEntry },
2746+
sessionKey,
2747+
storePath,
2748+
isHeartbeat: false,
2749+
replyOperation: createReplyOperation(),
2750+
});
2751+
2752+
expect(flushResult).toEqual({ sessionEntry, outcome: "skipped" });
2753+
expect(preflightEntry).toBe(sessionEntry);
2754+
expect(preflightEntry?.compactionCount).toBe(0);
2755+
expect(runEmbeddedAgentMock).not.toHaveBeenCalled();
2756+
expect(compactEmbeddedAgentSessionMock).not.toHaveBeenCalled();
2757+
});
2758+
2759+
it("still byte-guards a genuine embedded SQLite-backed session", async () => {
26842760
const storePath = path.join(rootDir, "sqlite-large-session.json");
26852761
const sessionKey = "agent:main:main";
26862762
const scope = { agentId: "main", sessionId: "session", sessionKey, storePath };

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

Lines changed: 38 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import {
88
} from "@openclaw/normalization-core/string-coerce";
99
import { truncateUtf16Safe } from "@openclaw/normalization-core/utf16-slice";
1010
import { resolveBootstrapWarningSignaturesSeen } from "../../agents/bootstrap-budget.js";
11+
import { resolveCliBackendConfig } from "../../agents/cli-backends.js";
1112
import { estimateMessagesTokens } from "../../agents/compaction.js";
1213
import { isBenignCompactionSkipResult } from "../../agents/embedded-agent-runner/compact-reasons.js";
1314
import { runEmbeddedAgentEntry } from "../../agents/embedded-agent-runner/run-entry.js";
@@ -255,32 +256,28 @@ function resolveMemoryFlushModelFallbackOptions(
255256
};
256257
}
257258

258-
function followupUsesCliRuntime(params: {
259+
type FollowupRuntimeParams = {
259260
cfg: OpenClawConfig;
260261
followupRun: FollowupRun;
261262
sessionEntry?: Pick<
262263
SessionEntry,
263-
"agentHarnessId" | "agentRuntimeOverride" | "modelSelectionLocked"
264+
"agentHarnessId" | "agentRuntimeOverride" | "modelSelectionLocked" | "sessionId"
264265
>;
265-
}): boolean {
266+
sessionKey?: string;
267+
runtimePolicySessionKey?: string;
268+
};
269+
270+
function followupUsesCliRuntime(params: FollowupRuntimeParams, runtimeId: string): boolean {
266271
const provider = params.followupRun.run.provider;
267272
if (isCliProvider(provider, params.cfg)) {
268273
return true;
269274
}
270-
return isCliRuntimeAliasForProvider({
271-
provider,
272-
runtime: resolvePersistedSessionRuntimeId(params.sessionEntry),
273-
cfg: params.cfg,
274-
});
275+
return [resolvePersistedSessionRuntimeId(params.sessionEntry), runtimeId].some((runtime) =>
276+
isCliRuntimeAliasForProvider({ provider, runtime, cfg: params.cfg }),
277+
);
275278
}
276279

277-
function resolveFollowupContextConfigProvider(params: {
278-
cfg: OpenClawConfig;
279-
followupRun: FollowupRun;
280-
sessionEntry?: SessionEntry;
281-
sessionKey?: string;
282-
runtimePolicySessionKey?: string;
283-
}): string {
280+
function resolveFollowupContextConfigProvider(params: FollowupRuntimeParams): string {
284281
const provider = params.followupRun.run.provider;
285282
return resolveContextConfigProviderForRuntime({
286283
provider,
@@ -289,13 +286,7 @@ function resolveFollowupContextConfigProvider(params: {
289286
});
290287
}
291288

292-
function resolveFollowupAgentRuntimeId(params: {
293-
cfg: OpenClawConfig;
294-
followupRun: FollowupRun;
295-
sessionEntry?: SessionEntry;
296-
sessionKey?: string;
297-
runtimePolicySessionKey?: string;
298-
}): string {
289+
function resolveFollowupAgentRuntimeId(params: FollowupRuntimeParams): string {
299290
const matchingSessionEntry =
300291
params.sessionEntry?.sessionId === params.followupRun.run.sessionId
301292
? params.sessionEntry
@@ -314,14 +305,14 @@ function resolveFollowupAgentRuntimeId(params: {
314305
});
315306
}
316307

317-
function followupUsesCodexRuntime(params: {
318-
cfg: OpenClawConfig;
319-
followupRun: FollowupRun;
320-
sessionEntry?: SessionEntry;
321-
sessionKey?: string;
322-
runtimePolicySessionKey?: string;
323-
}): boolean {
324-
return normalizeLowercaseStringOrEmpty(resolveFollowupAgentRuntimeId(params)) === "codex";
308+
function followupOwnsNativeCompaction(params: FollowupRuntimeParams, runtimeId: string): boolean {
309+
// Backends that persist resumable native transcripts must remain the sole
310+
// compaction owner; OpenClaw maintenance would corrupt that runtime state.
311+
return (
312+
resolveCliBackendConfig(runtimeId, params.cfg, {
313+
agentId: params.followupRun.run.agentId,
314+
})?.ownsNativeCompaction === true
315+
);
325316
}
326317

327318
function resolveVisibleMemoryFlushErrorPayloads(payloads?: ReplyPayload[]): ReplyPayload[] {
@@ -792,23 +783,20 @@ export async function runPreflightCompactionIfNeeded(params: {
792783
return entry ?? params.sessionEntry;
793784
}
794785

795-
const isCli = followupUsesCliRuntime({
786+
const runtimeParams = {
796787
cfg: params.cfg,
797788
followupRun: params.followupRun,
798789
sessionEntry: entry,
799-
});
800-
if (params.isHeartbeat || isCli) {
790+
sessionKey: params.sessionKey,
791+
runtimePolicySessionKey: params.runtimePolicySessionKey,
792+
};
793+
const runtimeId = resolveFollowupAgentRuntimeId(runtimeParams);
794+
const isCli = followupUsesCliRuntime(runtimeParams, runtimeId);
795+
const ownsNativeCompaction = followupOwnsNativeCompaction(runtimeParams, runtimeId);
796+
if (params.isHeartbeat || isCli || ownsNativeCompaction) {
801797
return entry ?? params.sessionEntry;
802798
}
803-
if (
804-
followupUsesCodexRuntime({
805-
cfg: params.cfg,
806-
followupRun: params.followupRun,
807-
sessionEntry: entry,
808-
sessionKey: params.sessionKey,
809-
runtimePolicySessionKey: params.runtimePolicySessionKey,
810-
})
811-
) {
799+
if (normalizeLowercaseStringOrEmpty(runtimeId) === "codex") {
812800
// Codex runtime sessions should reach Codex with their real thread state.
813801
// Its harness owns automatic compaction; OpenClaw preflight compaction is
814802
// only for non-Codex embedded runtimes.
@@ -1170,11 +1158,17 @@ export async function runMemoryFlushIfNeeded(params: {
11701158
if (entry?.incognito === true || isIncognitoSessionKey(params.sessionKey)) {
11711159
return { sessionEntry: entry, outcome: "skipped" };
11721160
}
1173-
const isCli = followupUsesCliRuntime({
1161+
const runtimeParams = {
11741162
cfg: params.cfg,
11751163
followupRun: params.followupRun,
11761164
sessionEntry: entry,
1177-
});
1165+
sessionKey: params.sessionKey,
1166+
runtimePolicySessionKey: params.runtimePolicySessionKey,
1167+
};
1168+
const runtimeId = resolveFollowupAgentRuntimeId(runtimeParams);
1169+
const isCli =
1170+
followupUsesCliRuntime(runtimeParams, runtimeId) ||
1171+
followupOwnsNativeCompaction(runtimeParams, runtimeId);
11781172
const canAttemptFlush = memoryFlushWritable && !params.isHeartbeat && !isCli;
11791173
const contextWindowTokens = resolveMemoryFlushContextWindowTokens({
11801174
cfg: params.cfg,

0 commit comments

Comments
 (0)