Skip to content

Commit 16cde04

Browse files
fix(agents): allow required-preflight native Codex compaction (#120197)
* fix(agents): allow required-preflight native Codex compaction Required reply-preflight compaction on a Codex app-server-backed session returns the intentional `ok: true, compacted: false` "codex app-server owns automatic compaction" no-op because the preflight caller never passes `allowNonManualNativeRequest`. The reply/preflight path then misclassifies that successful skip as a failure and throws, dropping the user's turn with "Context is too large and auto-compaction could not recover this turn." The equivalent CLI path was fixed by #88207; this is the second, unpatched caller. Route required-preflight through the existing private `compactAfterContextEngine` harness capability (which already passes `allowNonManualNativeRequest: true`) by adding a typed `nativeCompactionRequest: "required_preflight" | "after_context_engine"` origin on `maybeCompactAgentHarnessSession` and the Codex compact bridge. The non-manual skip guard is bypassed for preflight, so Codex actually compacts the thread. A binding change between the initial read and the native request is a stale-binding race, not a benign skip. For `required_preflight` (and the non-manual CLI path) it now surfaces as the canonical recoverable `stale_thread_binding` failure so the queued harness falls back to the context engine instead of treating an uncompacted `ok: true` result as a completed turn. A genuine post-context-engine request may still skip, because the context engine has already compacted. Required-preflight is also the one scoped exception to the model-locked terminal rule: missing or stale Codex thread bindings recover via the shared context-engine fallback while the persisted harness lock stays intact; other locked failures remain terminal. Rebased onto main after #120740 restructured the guarded native compaction block; the recoverable-binding semantics are reintroduced on the new structure and scoped by `nativeCompactionRequest` so #120740's post-context-engine skip behavior is preserved. Closes #119971. * test(evidence): commit inspectable required-preflight live proof scripts for #119971 Adds the two live codex app-server proof scripts (binding-race + locked-preflight) so the redacted terminal traces in the PR body are inspectable on the exact head. Both drive the real codex binary and real maybeCompactCodexAppServerSession with nativeCompactionRequest: "required_preflight"; neither runs in CI (no codex binary). * fix(agents): scope locked-preflight compaction fallback to Codex Restrict the required-preflight model-lock exception to the Codex harness so missing/stale thread bindings in other locked native harnesses (e.g. Copilot) stay terminal instead of escaping the persisted model-lock boundary via context-engine fallback. Add a model-locked Copilot required-preflight regression covering both missing and stale thread bindings. * fix(codex): require native preflight compaction * chore(plugin-sdk): account for native compaction exports * test(codex): use complete cron authority fixtures * chore(lint): shrink compaction assertion baseline * fix(lint): honor root boundary timeout * fix(lint): extend package boundary timeout * fix(plugins): verify native compaction owner --------- Co-authored-by: fuller-stack-dev <[email protected]>
1 parent 7f842da commit 16cde04

26 files changed

Lines changed: 990 additions & 181 deletions

‎config/assertion-safety-baseline.txt‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1940,7 +1940,6 @@ src/agents/failover/signal-details.ts 1
19401940
src/agents/fallback-skip-cache.ts 1
19411941
src/agents/fast-mode.ts 1
19421942
src/agents/harness/builtin-openclaw.ts 2
1943-
src/agents/harness/compaction.ts 2
19441943
src/agents/harness/context-engine-lifecycle.ts 3
19451944
src/agents/harness/context-engine-turn-outbox.ts 3
19461945
src/agents/harness/gateway-question.ts 6

‎extensions/codex/harness.ts‎

Lines changed: 34 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,7 @@
33
*/
44
import type {
55
AgentHarnessV2,
6-
AgentHarnessCompactParams,
7-
AgentHarnessCompactResult,
6+
AgentHarnessNativeCompaction,
87
ContextEngineHostCapability,
98
} from "openclaw/plugin-sdk/agent-harness-runtime";
109
import type { OpenClawConfig } from "openclaw/plugin-sdk/config-contracts";
@@ -49,9 +48,18 @@ const CODEX_APP_SERVER_CONTEXT_ENGINE_HOST_CAPABILITIES = [
4948

5049
type CodexAppServerAgentHarness = AgentHarnessV2 & {
5150
cloudPlacement?: { mode: "remote-exec" };
52-
compactAfterContextEngine?(
53-
params: AgentHarnessCompactParams,
54-
): Promise<AgentHarnessCompactResult | undefined>;
51+
};
52+
53+
type CodexAppServerAgentHarnessOptions = {
54+
id?: string;
55+
label?: string;
56+
providerIds?: Iterable<string>;
57+
pluginConfig?: unknown;
58+
resolvePluginConfig?: () => unknown;
59+
resolveConfig?: () => OpenClawConfig | undefined;
60+
runtime?: PluginRuntime;
61+
bindingStore: CodexAppServerBindingStore;
62+
sessionCatalogControlFactory?: CodexSessionCatalogControlFactory;
5563
};
5664

5765
type CodexHostPreparedIsolatedCompletionParams = Parameters<
@@ -97,17 +105,9 @@ async function disposeSharedCodexAppServerClients(): Promise<void> {
97105
* Creates the Codex app-server harness used for attempts, side questions,
98106
* compaction, reset, and disposal.
99107
*/
100-
export function createCodexAppServerAgentHarness(options: {
101-
id?: string;
102-
label?: string;
103-
providerIds?: Iterable<string>;
104-
pluginConfig?: unknown;
105-
resolvePluginConfig?: () => unknown;
106-
resolveConfig?: () => OpenClawConfig | undefined;
107-
runtime?: PluginRuntime;
108-
bindingStore: CodexAppServerBindingStore;
109-
sessionCatalogControlFactory?: CodexSessionCatalogControlFactory;
110-
}): AgentHarnessV2 {
108+
export function createCodexAppServerAgentHarness(
109+
options: CodexAppServerAgentHarnessOptions,
110+
): AgentHarnessV2 {
111111
const harnessRuntimeId = options?.id ?? "codex";
112112
const normalizedHarnessRuntimeId = harnessRuntimeId.trim().toLowerCase();
113113
const providerIds = new Set(
@@ -285,14 +285,6 @@ export function createCodexAppServerAgentHarness(options: {
285285
pluginConfig: options?.resolvePluginConfig?.() ?? options?.pluginConfig,
286286
});
287287
},
288-
compactAfterContextEngine: async (params) => {
289-
const { maybeCompactCodexAppServerSession } = await import("./src/app-server/compact.js");
290-
return maybeCompactCodexAppServerSession(params, {
291-
bindingStore: options.bindingStore,
292-
pluginConfig: options?.resolvePluginConfig?.() ?? options?.pluginConfig,
293-
allowNonManualNativeRequest: true,
294-
});
295-
},
296288
reset: async (params) => {
297289
if (params.sessionId) {
298290
const [
@@ -335,3 +327,21 @@ export function createCodexAppServerAgentHarness(options: {
335327
};
336328
return harness;
337329
}
330+
331+
/** Creates the private native-compaction bridge registered in host-owned capability state. */
332+
export function createCodexAppServerNativeCompaction(
333+
options: Pick<
334+
CodexAppServerAgentHarnessOptions,
335+
"bindingStore" | "pluginConfig" | "resolvePluginConfig"
336+
>,
337+
): AgentHarnessNativeCompaction {
338+
return async (params) => {
339+
const { maybeCompactCodexAppServerSession } = await import("./src/app-server/compact.js");
340+
return maybeCompactCodexAppServerSession(params, {
341+
bindingStore: options.bindingStore,
342+
pluginConfig: options.resolvePluginConfig?.() ?? options.pluginConfig,
343+
allowNonManualNativeRequest: true,
344+
nativeCompactionRequest: params.nativeCompactionRequest,
345+
});
346+
};
347+
}

‎extensions/codex/index.test.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -196,6 +196,9 @@ describe("codex plugin", () => {
196196
);
197197

198198
const agentHarnessRegistration = mockCallArg(registerAgentHarness) as Record<string, unknown>;
199+
const agentHarnessOptions = mockCallArg(registerAgentHarness, 0, 1) as
200+
| Record<string, unknown>
201+
| undefined;
199202
const mediaProviderRegistration = mockCallArg(registerMediaUnderstandingProvider) as
200203
| Record<string, unknown>
201204
| undefined;
@@ -210,6 +213,8 @@ describe("codex plugin", () => {
210213
expect(agentHarnessRegistration.deliveryDefaults).toEqual({
211214
visibleReplies: "message_tool",
212215
});
216+
expect(agentHarnessRegistration.compactNative).toBeUndefined();
217+
expect(typeof agentHarnessOptions?.nativeCompaction).toBe("function");
213218
expect(typeof agentHarnessRegistration.dispose).toBe("function");
214219
expect(typeof agentHarnessRegistration.fetchUsageSnapshot).toBe("function");
215220
expect(typeof agentHarnessRegistration.loadMcpToolCatalog).toBe("function");

‎extensions/codex/index.ts‎

Lines changed: 14 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,10 @@ import {
1212
import { definePluginEntry } from "openclaw/plugin-sdk/plugin-entry";
1313
import type { PluginStateSyncKeyedStore } from "openclaw/plugin-sdk/plugin-state-runtime";
1414
import { registerCodexCliMetadata } from "./cli-metadata.js";
15-
import { createCodexAppServerAgentHarness } from "./harness.js";
15+
import {
16+
createCodexAppServerAgentHarness,
17+
createCodexAppServerNativeCompaction,
18+
} from "./harness.js";
1619
import { buildCodexMediaUnderstandingProvider } from "./media-understanding-provider.js";
1720
import { readCodexPluginConfig } from "./src/app-server/config.js";
1821
import { createCodexAppServerConnectionHealthService } from "./src/app-server/connection-health.js";
@@ -175,15 +178,16 @@ export default definePluginEntry({
175178
{ names: [...CODEX_SUPERVISION_COMPAT_TOOL_NAMES] },
176179
);
177180
}
178-
api.registerAgentHarness(
179-
createCodexAppServerAgentHarness({
180-
bindingStore,
181-
sessionCatalogControlFactory,
182-
resolveConfig: resolveCurrentConfig,
183-
resolvePluginConfig: resolveCurrentPluginConfig,
184-
runtime: api.runtime,
185-
}),
186-
);
181+
const agentHarnessOptions = {
182+
bindingStore,
183+
sessionCatalogControlFactory,
184+
resolveConfig: resolveCurrentConfig,
185+
resolvePluginConfig: resolveCurrentPluginConfig,
186+
runtime: api.runtime,
187+
};
188+
api.registerAgentHarness(createCodexAppServerAgentHarness(agentHarnessOptions), {
189+
nativeCompaction: createCodexAppServerNativeCompaction(agentHarnessOptions),
190+
});
187191
api.registerMediaUnderstandingProvider(
188192
buildCodexMediaUnderstandingProvider({ pluginConfig: api.pluginConfig }),
189193
);

‎extensions/codex/src/app-server/compact.test.ts‎

Lines changed: 152 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -695,6 +695,59 @@ describe("maybeCompactCodexAppServerSession", () => {
695695
);
696696
});
697697

698+
it("records the required-preflight origin on native app-server compaction requests", async () => {
699+
const fake = createFakeCodexClient({ retainedThreadId: null });
700+
setCodexAppServerClientFactoryForTest(async () => fake.client);
701+
const sessionFile = await writeTestBinding({
702+
contextEngine: {
703+
schemaVersion: 1,
704+
engineId: "lossless-claw",
705+
policyFingerprint: "policy-1",
706+
projection: {
707+
schemaVersion: 1,
708+
mode: "thread_bootstrap",
709+
epoch: "epoch-1",
710+
fingerprint: "fingerprint-1",
711+
},
712+
},
713+
});
714+
715+
const result = requireCompactResult(
716+
await maybeCompactCodexAppServerSession(
717+
{
718+
sessionId: "session-1",
719+
sessionKey: "agent:main:session-1",
720+
sessionFile,
721+
workspaceDir: tempDir,
722+
trigger: "budget",
723+
preflightRequired: true,
724+
currentTokenCount: 456,
725+
},
726+
{
727+
allowNonManualNativeRequest: true,
728+
nativeCompactionRequest: "required_preflight",
729+
},
730+
),
731+
);
732+
733+
expect(fake.request).toHaveBeenCalledWith(
734+
"thread/compact/start",
735+
{ threadId: "thread-1" },
736+
{ timeoutMs: 60_000 },
737+
);
738+
expect(result.ok).toBe(true);
739+
expect(result.compacted).toBe(true);
740+
expect(compactDetails(result)).toMatchObject({
741+
backend: "codex-app-server",
742+
threadId: "thread-1",
743+
signal: "thread/compact/start",
744+
pending: false,
745+
completed: true,
746+
request: "required_preflight",
747+
trigger: "budget",
748+
});
749+
});
750+
698751
it("preserves projection when aborted before guarded native compaction", async () => {
699752
const fake = createFakeCodexClient();
700753
setCodexAppServerClientFactoryForTest(async () => fake.client);
@@ -832,6 +885,76 @@ describe("maybeCompactCodexAppServerSession", () => {
832885
});
833886
});
834887

888+
it("reports a recoverable stale-binding failure when a required-preflight native request sees the binding change", async () => {
889+
const fake = createFakeCodexClient();
890+
setCodexAppServerClientFactoryForTest(async () => fake.client);
891+
const originalContextEngine = {
892+
schemaVersion: 1 as const,
893+
engineId: "lossless-claw",
894+
policyFingerprint: "policy-1",
895+
projection: {
896+
schemaVersion: 1 as const,
897+
mode: "thread_bootstrap" as const,
898+
epoch: "epoch-1",
899+
fingerprint: "fingerprint-1",
900+
},
901+
};
902+
const sessionFile = await writeTestBinding({
903+
contextEngine: originalContextEngine,
904+
});
905+
let bindingReads = 0;
906+
const bindingStore = {
907+
...testCodexAppServerBindingStore,
908+
read: vi.fn(async (...args: Parameters<typeof testCodexAppServerBindingStore.read>) => {
909+
const result = await testCodexAppServerBindingStore.read(...args);
910+
if (bindingReads++ === 0) {
911+
seedCodexTestBinding(sessionFile, {
912+
threadId: "thread-2",
913+
cwd: tempDir,
914+
contextEngine: {
915+
...originalContextEngine,
916+
projection: {
917+
schemaVersion: 1,
918+
mode: "thread_bootstrap",
919+
epoch: "epoch-2",
920+
fingerprint: "fingerprint-2",
921+
},
922+
},
923+
});
924+
}
925+
return result;
926+
}),
927+
};
928+
929+
const result = requireCompactResult(
930+
await maybeCompactCodexAppServerSession(
931+
{
932+
sessionId: "session-1",
933+
sessionKey: "agent:main:session-1",
934+
sessionFile,
935+
workspaceDir: tempDir,
936+
trigger: "budget",
937+
preflightRequired: true,
938+
currentTokenCount: 456,
939+
},
940+
{
941+
allowNonManualNativeRequest: true,
942+
nativeCompactionRequest: "required_preflight",
943+
bindingStore,
944+
},
945+
),
946+
);
947+
948+
// A required-preflight request has not compacted yet, so a binding change
949+
// must surface as the recoverable failure rather than a benign ok:true skip,
950+
// letting the queued harness fall back to the context engine.
951+
expect(fake.request).not.toHaveBeenCalled();
952+
expect(result.ok).toBe(false);
953+
expect(result.compacted).toBe(false);
954+
expect(result.reason).toBe("codex app-server binding changed before native compaction");
955+
expect(result.failure?.reason).toBe("stale_thread_binding");
956+
});
957+
835958
it("blocks same-process binding writes until guarded native compaction starts", async () => {
836959
let releaseExternalWrite!: () => void;
837960
const externalWriteGate = new Promise<void>((resolve) => {
@@ -1709,6 +1832,35 @@ describe("maybeCompactCodexAppServerSession", () => {
17091832
expect(result.result).toBeUndefined();
17101833
});
17111834

1835+
it("reports required-preflight missing binding as a recoverable native failure", async () => {
1836+
const sessionFile = path.join(tempDir, "required-preflight-missing-binding.jsonl");
1837+
1838+
const result = requireCompactResult(
1839+
await maybeCompactCodexAppServerSession(
1840+
{
1841+
sessionId: "session-1",
1842+
sessionKey: "agent:main:session-1",
1843+
sessionFile,
1844+
workspaceDir: tempDir,
1845+
trigger: "budget",
1846+
preflightRequired: true,
1847+
},
1848+
{
1849+
allowNonManualNativeRequest: true,
1850+
nativeCompactionRequest: "required_preflight",
1851+
},
1852+
),
1853+
);
1854+
1855+
expect(result).toMatchObject({
1856+
ok: false,
1857+
compacted: false,
1858+
failure: {
1859+
reason: "missing_thread_binding",
1860+
},
1861+
});
1862+
});
1863+
17121864
it("preserves stale thread binding metadata for recovery and reports failed native compaction", async () => {
17131865
const fake = createFakeCodexClient();
17141866
fake.request.mockRejectedValueOnce(

0 commit comments

Comments
 (0)