Skip to content

Commit 805c66e

Browse files
clark-wqForge
andcommitted
fix(compaction): recover reset Codex sessions
Co-Authored-By: Forge <[email protected]>
1 parent f5add81 commit 805c66e

12 files changed

Lines changed: 459 additions & 107 deletions

‎src/agents/command/cli-compaction.ts‎

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ import {
2525
} from "../agent-settings.js";
2626
import { resolveCliBackendConfig as resolveCliBackendConfigImpl } from "../cli-backends.js";
2727
import {
28+
AUTOMATIC_COMPACTION_OWNED_REASON,
2829
isBenignCompactionSkipReason,
2930
isBenignCompactionSkipResult,
3031
} from "../embedded-agent-runner/compact-reasons.js";
@@ -50,8 +51,6 @@ import {
5051
recordCliCompactionInStore as recordCliCompactionInStoreImpl,
5152
} from "./session-store.js";
5253

53-
const CODEX_APP_SERVER_OWNS_AUTO_COMPACTION_REASON = "codex app-server owns automatic compaction";
54-
5554
type SessionManagerLike = ReturnType<typeof SessionManager.open>;
5655
type SettingsManagerLike = {
5756
getCompactionReserveTokens: () => number;
@@ -219,9 +218,7 @@ function isIntentionalNativeAutoCompactionSkip(
219218
result: EmbeddedAgentCompactResult | undefined,
220219
): boolean {
221220
return (
222-
result?.ok === true &&
223-
!result.compacted &&
224-
result.reason === CODEX_APP_SERVER_OWNS_AUTO_COMPACTION_REASON
221+
result?.ok === true && !result.compacted && result.reason === AUTOMATIC_COMPACTION_OWNED_REASON
225222
);
226223
}
227224

@@ -545,7 +542,7 @@ async function compactNativeHarnessCliTranscript(params: {
545542
// turns); falling back to context-engine compaction here fought that
546543
// ownership and failed OAuth-only sessions with "No API key found".
547544
log.info(
548-
`CLI native harness compaction skipped for ${params.provider}/${params.model}: ${CODEX_APP_SERVER_OWNS_AUTO_COMPACTION_REASON}`,
545+
`CLI native harness compaction skipped for ${params.provider}/${params.model}: ${AUTOMATIC_COMPACTION_OWNED_REASON}`,
549546
);
550547
return { compacted: false };
551548
}

‎src/agents/embedded-agent-runner/compact-reasons.test.ts‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
11
// Classification coverage for compaction failure and skip reason telemetry.
22
import { describe, expect, it } from "vitest";
33
import {
4+
AUTOMATIC_COMPACTION_OWNED_REASON,
45
classifyCompactionReason,
56
formatUnknownCompactionReasonDetail,
7+
isAutomaticCompactionOwnershipResult,
68
isBenignCompactionSkipResult,
79
isBenignCompactionSkipReason,
810
resolveCompactionFailureReason,
@@ -47,6 +49,12 @@ describe("classifyCompactionReason", () => {
4749
expect(classifyCompactionReason("already compacted")).toBe("already_compacted");
4850
});
4951

52+
it("classifies native automatic-compaction ownership", () => {
53+
expect(classifyCompactionReason(AUTOMATIC_COMPACTION_OWNED_REASON)).toBe(
54+
"automatic_compaction_owned",
55+
);
56+
});
57+
5058
it("classifies deferred background maintenance as a skip-like reason", () => {
5159
expect(classifyCompactionReason("deferred to background context-engine maintenance")).toBe(
5260
"deferred_background",
@@ -90,6 +98,25 @@ describe("isBenignCompactionSkipReason", () => {
9098
);
9199
});
92100

101+
describe("isAutomaticCompactionOwnershipResult", () => {
102+
it("requires the successful native ownership handoff result", () => {
103+
expect(
104+
isAutomaticCompactionOwnershipResult({
105+
ok: true,
106+
compacted: false,
107+
reason: AUTOMATIC_COMPACTION_OWNED_REASON,
108+
}),
109+
).toBe(true);
110+
expect(
111+
isAutomaticCompactionOwnershipResult({
112+
ok: false,
113+
compacted: false,
114+
reason: AUTOMATIC_COMPACTION_OWNED_REASON,
115+
}),
116+
).toBe(false);
117+
});
118+
});
119+
93120
describe("formatUnknownCompactionReasonDetail", () => {
94121
it("formats unknown reasons as single-token diagnostic detail", () => {
95122
expect(formatUnknownCompactionReasonDetail("No API provider registered for api: ollama")).toBe(

‎src/agents/embedded-agent-runner/compact-reasons.ts‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@ import { sanitizeForLog } from "../../../packages/terminal-core/src/ansi.js";
66

77
const MAX_COMPACTION_REASON_DETAIL_CHARS = 100;
88

9+
export const AUTOMATIC_COMPACTION_OWNED_REASON = "codex app-server owns automatic compaction";
10+
911
export const DEFERRED_CONTEXT_ENGINE_COMPACTION_REASON =
1012
"deferred to background context-engine maintenance";
1113

@@ -42,6 +44,9 @@ export function classifyCompactionReason(reason?: string): string {
4244
if (text.includes("already compacted") || text.includes("already_compacted")) {
4345
return "already_compacted";
4446
}
47+
if (text === AUTOMATIC_COMPACTION_OWNED_REASON) {
48+
return "automatic_compaction_owned";
49+
}
4550
if (text.includes("deferred to background")) {
4651
return "deferred_background";
4752
}
@@ -97,6 +102,17 @@ export function isBenignCompactionSkipResult(result: {
97102
);
98103
}
99104

105+
/** Return whether a native runtime handed automatic compaction back to its owner. */
106+
export function isAutomaticCompactionOwnershipResult(
107+
result: { ok: boolean; compacted: boolean; reason?: string } | undefined,
108+
): boolean {
109+
return (
110+
result?.ok === true &&
111+
!result.compacted &&
112+
classifyCompactionReason(result.reason) === "automatic_compaction_owned"
113+
);
114+
}
115+
100116
/** Sanitize an unknown reason into a short log/metric-safe detail suffix. */
101117
export function formatUnknownCompactionReasonDetail(reason?: string): string | undefined {
102118
const sanitized = sanitizeForLog((reason ?? "").replace(/\s+/g, " "))

‎src/agents/embedded-agent-runner/compact.hooks.test.ts‎

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3709,6 +3709,52 @@ describe("compactEmbeddedAgentSession hooks (ownsCompaction engine)", () => {
37093709
});
37103710
});
37113711

3712+
it("routes required model-locked Codex byte preflight through semantic and native compaction", async () => {
3713+
resolveAgentHarnessPolicyMock.mockReturnValue({ runtime: "openclaw" });
3714+
maybeCompactAgentHarnessSessionMock
3715+
.mockResolvedValueOnce({
3716+
ok: true,
3717+
compacted: false,
3718+
reason: "codex app-server owns automatic compaction",
3719+
})
3720+
.mockResolvedValueOnce({
3721+
ok: true,
3722+
compacted: true,
3723+
result: {
3724+
summary: "",
3725+
firstKeptEntryId: "",
3726+
tokensBefore: 333,
3727+
},
3728+
});
3729+
3730+
const result = await compactEmbeddedAgentSession(
3731+
wrappedCompactionArgs({
3732+
provider: "openai",
3733+
model: "gpt-5.5",
3734+
agentHarnessId: "codex",
3735+
modelSelectionLocked: true,
3736+
currentTokenCount: 333,
3737+
trigger: "budget",
3738+
forcePreflight: true,
3739+
preflightRequired: true,
3740+
preflightCompactionTrigger: "transcript_bytes",
3741+
}),
3742+
);
3743+
3744+
expect(result).toMatchObject({ ok: true, compacted: true });
3745+
expect(contextEngineCompactMock).toHaveBeenCalledTimes(1);
3746+
expect(maybeCompactAgentHarnessSessionMock).toHaveBeenCalledTimes(2);
3747+
expect(maybeCompactAgentHarnessSessionMock).toHaveBeenNthCalledWith(
3748+
2,
3749+
expect.objectContaining({
3750+
provider: "openai",
3751+
model: "gpt-5.5",
3752+
agentHarnessId: "codex",
3753+
}),
3754+
{ nativeCompactionRequest: "after_context_engine" },
3755+
);
3756+
});
3757+
37123758
it.each([
37133759
["missing_thread_binding", "no codex app-server thread binding"],
37143760
["stale_thread_binding", "thread not found"],

‎src/agents/embedded-agent-runner/compact.queued.ts‎

Lines changed: 20 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,10 @@ import {
3535
import { resolveAgentRunSessionTarget } from "../run-session-target.js";
3636
import { materializePreparedRuntimeModel } from "../runtime-plan/materialize-model.js";
3737
import { SessionManager } from "../sessions/index.js";
38-
import { DEFERRED_CONTEXT_ENGINE_COMPACTION_REASON } from "./compact-reasons.js";
38+
import {
39+
DEFERRED_CONTEXT_ENGINE_COMPACTION_REASON,
40+
isAutomaticCompactionOwnershipResult,
41+
} from "./compact-reasons.js";
3942
import type { CompactEmbeddedAgentSessionParams } from "./compact.types.js";
4043
import { compactionCheckpointStore, persistCompactionCheckpoint } from "./compaction-checkpoint.js";
4144
import { asCompactionHookRunner, runPostCompactionSideEffects } from "./compaction-hooks.js";
@@ -69,8 +72,12 @@ import type { EmbeddedAgentCompactResult } from "./types.js";
6972

7073
function shouldFallbackAfterHarnessCompaction(
7174
result: EmbeddedAgentCompactResult | undefined,
75+
allowAutomaticOwnershipHandoff: boolean,
7276
): boolean {
73-
return isRecoverableNativeHarnessBindingFailure(result);
77+
return (
78+
isRecoverableNativeHarnessBindingFailure(result) ||
79+
(allowAutomaticOwnershipHandoff && isAutomaticCompactionOwnershipResult(result))
80+
);
7481
}
7582

7683
function lockedCompactionRuntimeFailure(runtime?: string): EmbeddedAgentCompactResult {
@@ -558,15 +565,23 @@ async function compactResolvedContextEngine(
558565
contextEngineRuntimeContext,
559566
})
560567
: undefined;
561-
if (lockedNativeHarness) {
568+
const allowAutomaticOwnershipHandoff =
569+
params.preflightRequired === true && params.preflightCompactionTrigger === "transcript_bytes";
570+
const shouldFallbackFromHarness = shouldFallbackAfterHarnessCompaction(
571+
harnessResult,
572+
allowAutomaticOwnershipHandoff,
573+
);
574+
const allowLockedHarnessFallback =
575+
allowAutomaticOwnershipHandoff && isAutomaticCompactionOwnershipResult(harnessResult);
576+
if (lockedNativeHarness && !allowLockedHarnessFallback) {
562577
return harnessResult ?? lockedCompactionRuntimeFailure(selectedHarnessRuntime);
563578
}
564579
if (harnessResult) {
565-
if (!shouldFallbackAfterHarnessCompaction(harnessResult)) {
580+
if (!shouldFallbackFromHarness) {
566581
return harnessResult;
567582
}
568583
log.warn(
569-
`native harness compaction could not use its session binding; falling back to context engine: ${harnessResult.reason ?? "unknown"}`,
584+
`native harness compaction could not complete; falling back to context engine: ${harnessResult.reason ?? "unknown"}`,
570585
);
571586
}
572587
if (

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

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2851,6 +2851,83 @@ describe("runMemoryFlushIfNeeded", () => {
28512851
});
28522852
});
28532853

2854+
it("dispatches past preflight after reset of an oversized physical Codex transcript", async () => {
2855+
const storePath = path.join(rootDir, "sqlite-codex-reset-byte-guard.json");
2856+
const sessionKey = "agent:main:discord:direct:test-user";
2857+
const scope = { agentId: "main", sessionId: "session", sessionKey, storePath };
2858+
await upsertSessionEntry(scope, { sessionId: "session", updatedAt: 10 });
2859+
await replaceSqliteTranscriptEvents(scope, [
2860+
{
2861+
id: "oversized-history",
2862+
parentId: null,
2863+
message: { role: "user", content: "x".repeat(4_300_000) },
2864+
type: "message",
2865+
},
2866+
{
2867+
id: "kept-user",
2868+
parentId: "oversized-history",
2869+
message: { role: "user", content: "kept question" },
2870+
type: "message",
2871+
},
2872+
{
2873+
id: "kept-assistant",
2874+
parentId: "kept-user",
2875+
message: { role: "assistant", content: "kept answer" },
2876+
type: "message",
2877+
},
2878+
{
2879+
type: "reset",
2880+
id: "reset-boundary",
2881+
parentId: "kept-assistant",
2882+
timestamp: "2026-08-06T14:20:01.969Z",
2883+
reason: "new",
2884+
firstKeptEntryId: "kept-user",
2885+
},
2886+
]);
2887+
expect(readTranscriptStatsSync(scope).sizeBytes).toBeGreaterThan(4 * 1024 * 1024);
2888+
2889+
const sessionEntry: SessionEntry = {
2890+
sessionId: "session",
2891+
updatedAt: Date.now(),
2892+
totalTokens: 0,
2893+
totalTokensFresh: true,
2894+
compactionCount: 0,
2895+
agentRuntimeOverride: "codex",
2896+
agentHarnessId: "codex",
2897+
modelSelectionLocked: true,
2898+
};
2899+
const replyOperation = createReplyOperation();
2900+
2901+
const entry = await runPreflightCompactionIfNeeded({
2902+
cfg: {
2903+
agents: {
2904+
defaults: {
2905+
compaction: { maxActiveTranscriptBytes: "4mb" },
2906+
},
2907+
},
2908+
},
2909+
followupRun: createTestFollowupRun({
2910+
provider: "openai",
2911+
model: "gpt-5.5",
2912+
sessionId: "session",
2913+
sessionKey,
2914+
}),
2915+
defaultModel: "gpt-5.5",
2916+
agentCfgContextTokens: 1_000_000,
2917+
sessionEntry,
2918+
sessionStore: { [sessionKey]: sessionEntry },
2919+
sessionKey,
2920+
storePath,
2921+
isHeartbeat: false,
2922+
replyOperation,
2923+
});
2924+
2925+
expect(entry).toBe(sessionEntry);
2926+
expect(replyOperation.setPhase).not.toHaveBeenCalled();
2927+
expect(compactEmbeddedAgentSessionMock).not.toHaveBeenCalled();
2928+
expect(incrementCompactionCountMock).not.toHaveBeenCalled();
2929+
});
2930+
28542931
it("leaves an under-limit SQLite Codex session to native token compaction", async () => {
28552932
const storePath = path.join(rootDir, "sqlite-codex-under-byte-guard.json");
28562933
const sessionKey = "agent:main:main";

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

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ import {
4040
} from "../../config/sessions.js";
4141
import {
4242
readRecentSessionTranscriptActiveEvents,
43-
readSessionTranscriptActiveStats,
43+
readSessionTranscriptContextByteSize,
4444
updateSessionEntry,
4545
} from "../../config/sessions/session-accessor.js";
4646
import { resolveSessionStorePathForScope } from "../../config/sessions/session-store-path.js";
@@ -465,7 +465,7 @@ function readSqliteSessionLogSnapshot(
465465
const snapshot: SessionLogSnapshot = {};
466466
try {
467467
if (options.includeByteSize) {
468-
snapshot.byteSize = readSessionTranscriptActiveStats(scope).sizeBytes;
468+
snapshot.byteSize = readSessionTranscriptContextByteSize(scope);
469469
}
470470
if (options.includeUsage || options.includeTurnTaint) {
471471
const events = readRecentSessionTranscriptActiveEvents(scope, SQLITE_USAGE_TAIL_MAX_EVENTS);

‎src/config/sessions/session-accessor.sqlite-active-events.test.ts‎

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import {
1414
readSessionTranscriptActiveLeafEvents,
1515
readSessionTranscriptActiveStats,
1616
readSessionTranscriptBoundedMessageTailPage,
17+
readSessionTranscriptContextByteSize,
1718
readSessionTranscriptMessageAnchorPage,
1819
readSessionTranscriptMessageEventById,
1920
readSessionTranscriptMessageEventCount,
@@ -226,6 +227,59 @@ describe("SQLite active transcript event projection", () => {
226227
expect(page.events.map(({ event }) => (event as { id?: unknown }).id)).toEqual(["small"]);
227228
});
228229

230+
it("sizes only the reset-bounded replay window while retaining oversized history", async () => {
231+
await persistSessionTranscriptTurn(scope, {
232+
messages: [
233+
{
234+
eventId: "oversized-history",
235+
parentId: null,
236+
message: { role: "user", content: "x".repeat(4_300_000) },
237+
},
238+
{
239+
eventId: "kept-user",
240+
parentId: "oversized-history",
241+
message: { role: "user", content: "kept question" },
242+
},
243+
{
244+
eventId: "kept-assistant",
245+
parentId: "kept-user",
246+
message: { role: "assistant", content: "kept answer" },
247+
},
248+
],
249+
touchSessionEntry: false,
250+
});
251+
await appendTranscriptEvent(scope, {
252+
type: "reset",
253+
id: "reset-boundary",
254+
parentId: "kept-assistant",
255+
timestamp: "2026-08-06T14:20:01.969Z",
256+
reason: "new",
257+
firstKeptEntryId: "kept-user",
258+
});
259+
await persistSessionTranscriptTurn(scope, {
260+
messages: [
261+
{
262+
eventId: "post-reset",
263+
parentId: "reset-boundary",
264+
message: { role: "user", content: "ordinary next turn" },
265+
},
266+
],
267+
touchSessionEntry: false,
268+
});
269+
270+
expect(readSessionTranscriptActiveStats(scope).sizeBytes).toBeGreaterThan(4 * 1024 * 1024);
271+
expect(readSessionTranscriptContextByteSize(scope)).toBeLessThan(4 * 1024);
272+
expect(readSessionTranscriptMessageEventCount(scope)).toBe(3);
273+
expect(readSessionTranscriptMessageEventById(scope, "oversized-history")).toBeUndefined();
274+
275+
const database = openOpenClawAgentDatabase({ agentId: scope.agentId, env: scope.env });
276+
expect(
277+
database.db
278+
.prepare("SELECT COUNT(*) AS count FROM transcript_events WHERE session_id = ?")
279+
.get(scope.sessionId),
280+
).toEqual({ count: 6 });
281+
});
282+
229283
it("fails fast and schedules maintenance when out-of-band state is dirty", async () => {
230284
await persistSessionTranscriptTurn(scope, {
231285
messages: [

0 commit comments

Comments
 (0)