Skip to content

Commit 0924fd9

Browse files
authored
fix(codex): reclaim binding capacity after session deletion (#128366)
* fix(codex): reclaim binding ownership when sessions are deleted Prepare harness deletion outside the SQLite writer and compare-delete exact companion ownership at the session removal edge, with compensation before commit and native subscription release afterward. Preserve live siblings and upstream native history. Repair proven orphan bindings through the existing Doctor planner under maintenance ownership. * fix(codex): reuse prepared auth for resumed thread ownership * docs(plugins): clarify shared migration and auth contracts * test(codex): use the canonical config type facade * fix(codex): preserve native threads during manual resume Record pending attachment intent and validate the immutable native tool catalog before applying configuration to the selected thread. Require uninterrupted physical-client ownership through native unsubscribe, resume, and binding commit. Keep the thread intact on unsupported policy, competing work, or failed proof. Reuse canonical retained-owner cleanup and preserve unsafe-client retirement. Cover the real command producer, cold and loaded resumes, competing leases, lazy-store commit fencing, and the Gateway competing-owner path. * test: isolate Codex auth and session completion fixtures
1 parent 7334f8d commit 0924fd9

81 files changed

Lines changed: 6478 additions & 1506 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎docs/plugins/codex-harness.md‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -996,6 +996,22 @@ disable <name>` update its persisted policy. Mutations require an owner or
996996
- `/codex computer-use [status|install]` manages Codex Computer Use.
997997
- `/codex help` lists the full command tree.
998998

999+
When `/codex resume` attaches a thread without an existing verified harness
1000+
binding, its next turn checks the native thread's stored tool catalog and
1001+
applies the current harness configuration before continuing. This first
1002+
attachment requires the local stdio app-server and its per-agent Codex home.
1003+
It also needs exclusive use of that app-server while applying configuration;
1004+
if another turn or native child is active, wait for it to finish and retry.
1005+
Use [Codex supervision](/plugins/codex-supervision) or native Codex to continue
1006+
threads in a shared user home or on another app-server.
1007+
1008+
Codex cannot replace a thread's dynamic tool catalog during resume. If that
1009+
catalog differs from the current harness tools, its metadata cannot be read,
1010+
or Codex cannot confirm that it applied the configuration, OpenClaw reports
1011+
the problem and keeps the selected native thread intact. It does not silently
1012+
start another thread. Use `/new` to start with the current harness tools, or
1013+
continue the preserved thread in native Codex.
1014+
9991015
### Shared Fast mode and Codex fast mode
10001016

10011017
`/fast` controls the shared OpenClaw policy. A directive-only `/fast off`
@@ -1585,6 +1601,14 @@ allocation. An OS hard limit can terminate Codex rather than backpressure it.
15851601
`plugins.entries.codex.config.discovery.timeoutMs` or disable discovery.
15861602
See [Codex harness reference](/plugins/codex-harness-reference#model-discovery).
15871603

1604+
**Codex plugin state has reached its row limit:** run `openclaw doctor` to
1605+
check for bindings left behind by deleted or expired OpenClaw sessions. Stop
1606+
the Gateway, then run `openclaw doctor --fix` to remove proven orphaned session
1607+
bindings after session repair. Doctor preserves supervised bindings, active
1608+
leases, ambiguous ownership, and bindings whose session store cannot be read.
1609+
This cleanup does not delete native Codex thread history or managed-thread
1610+
advisory records.
1611+
15881612
**WebSocket transport fails immediately:** check `appServer.url`,
15891613
`authToken`, headers, and that the remote app-server speaks the same Codex
15901614
app-server protocol version. Codex WebSocket transport remains experimental

‎docs/plugins/sdk-agent-harness.md‎

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,14 @@ Harnesses may use the plan for decisions that need to match OpenClaw behavior,
118118
but treat it as host-owned attempt state: do not mutate it or use it to switch
119119
providers/models inside a turn.
120120

121+
For auxiliary session control calls, `resolveSessionModelRef` from
122+
`openclaw/plugin-sdk/model-session-runtime` resolves the current model selection.
123+
`prepareAgentRuntimeAuth` from `openclaw/plugin-sdk/agent-harness-runtime` selects
124+
its auth route and ordered credential attempts from the caller's loaded auth
125+
snapshot. Preserve the selected attempt's profile, API, and fallback restrictions
126+
when materializing credentials; this keeps control calls on the same billing
127+
route as agent turns.
128+
121129
### Request-transport contract
122130

123131
`supports(ctx)` receives the resolved model transport in `ctx.modelProvider`.
@@ -599,8 +607,22 @@ The OpenClaw transcript remains the compatibility layer for:
599607
- switching back to the built-in OpenClaw harness on a later turn
600608
- generic `/new`, `/reset`, and session deletion behavior
601609

602-
If your harness stores a sidecar binding, implement `reset(...)` so OpenClaw
603-
can clear it when the owning OpenClaw session is reset.
610+
Store native bindings in plugin state. Implement `reset(...)` for an in-place
611+
session reset and `withSessionDeletion(params, run)` for removal of a session
612+
key, including expiry and maintenance. A physical session ID changing at the
613+
same key is a transfer, not deletion; preserve any compaction adoption path.
614+
615+
`withSessionDeletion` acquires the native owner's lease before calling
616+
`run({ commit, rollback })`. Core invokes the synchronous `commit()` at the
617+
session row deletion boundary and `rollback()` if the transaction fails.
618+
Rollback must also tolerate a failed or unapplied commit. Keep asynchronous
619+
subscription cleanup after `run` so it does not hold the SQLite writer queue;
620+
do not restore bindings for errors after the session transaction committed.
621+
622+
Recheck `params.assertCurrent()` after awaited work and immediately before
623+
mutating native state. The callback belongs to one registered harness lifetime;
624+
retaining it after the operation closes does not retain authority. Post-delete
625+
hooks are notifications, not the owner of durable binding removal.
604626

605627
## Tool and media results
606628

‎docs/plugins/sdk-migration.md‎

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -97,15 +97,24 @@ including empty results without range metadata. Only an explicit
9797
missing files; registered-input normalization remains available through the
9898
next Plugin SDK major.
9999

100-
### Channel state migration declarations
100+
### Plugin state migration declarations
101101

102-
Channel plugins should declare `doctorContract.stateMigrations: true` in
102+
Plugins should declare `doctorContract.stateMigrations: true` in
103103
`openclaw.plugin.json` and export `stateMigrations` from their doctor-contract
104104
artifact. Plan-based migrations can use
105105
`definePluginDoctorMigrationFromPlans(...)` from
106106
`openclaw/plugin-sdk/runtime-doctor-migrations` to preserve existing move, copy, preview,
107107
and plugin-state import behavior.
108108

109+
Use `phase: "after-session-repair"` when a migration needs canonical session
110+
ownership evidence. Ordinary Doctor detects these migrations; `--fix` applies
111+
them after session repair under SQLite maintenance ownership. The context
112+
provides bounded `readPluginStateEntriesInKeyRange` and
113+
`readSessionIdentityEvidenceBatch` reads, plus
114+
`deletePluginStateEntriesIfUnchanged` only during a fenced repair. Preserve
115+
unknown or ambiguous ownership. Delete only the observed raw rows; callbacks
116+
retained after maintenance ends cannot authorize later writes.
117+
109118
The setup-entry `legacyStateMigrations` option and feature flag,
110119
`setupFeatures.legacyStateMigrations`,
111120
`BundledChannelLegacyStateMigrationDetector`, and

‎extensions/codex/doctor-contract-api.ts‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,10 @@
22
* Doctor contract hooks for Codex plugin config and state migrations.
33
*/
44
import type { OpenClawConfig } from "openclaw/plugin-sdk/config-contracts";
5+
import type { PluginDoctorStateMigration } from "openclaw/plugin-sdk/runtime-doctor-migrations";
56
import { asNullableRecord } from "openclaw/plugin-sdk/string-coerce-runtime";
7+
import { codexOrphanedSessionBindingMigration } from "./src/migration/session-binding-orphans.js";
8+
import { stateMigrations as legacyStateMigrations } from "./src/migration/session-binding-sidecars.js";
69

710
type LegacyConfigRule = {
811
path: string[];
@@ -134,4 +137,7 @@ export function normalizeCompatibilityConfig({ cfg }: { cfg: OpenClawConfig }):
134137
};
135138
}
136139

137-
export { stateMigrations } from "./src/migration/session-binding-sidecars.js";
140+
export const stateMigrations: PluginDoctorStateMigration[] = [
141+
...legacyStateMigrations,
142+
codexOrphanedSessionBindingMigration,
143+
];

‎extensions/codex/harness.test.ts‎

Lines changed: 58 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,9 @@ import { createCodexAppServerAgentHarness } from "./harness.js";
2323
import { buildCodexRuntimeModelParams } from "./src/app-server/model-runtime.js";
2424
import {
2525
createCodexTestBindingStore,
26+
createCodexTestBindingStateStore,
27+
createCodexAppServerBindingStore,
28+
bindingStoreKey,
2629
sessionBindingIdentity,
2730
testCodexAppServerBindingStore,
2831
} from "./src/app-server/session-binding.test-helpers.js";
@@ -579,8 +582,9 @@ describe("Codex agent harness reset()", () => {
579582
}
580583
});
581584

582-
it("keeps deleted session generations retired", async () => {
583-
const bindingStore = createCodexTestBindingStore();
585+
it("removes deleted session bindings before the post-delete reset event", async () => {
586+
const state = createCodexTestBindingStateStore();
587+
const bindingStore = createCodexAppServerBindingStore(state);
584588
const identity = sessionBindingIdentity({
585589
agentId: "worker",
586590
sessionId: "session-1",
@@ -592,19 +596,66 @@ describe("Codex agent harness reset()", () => {
592596
});
593597
const harness = createCodexAppServerAgentHarness({ bindingStore });
594598

599+
await harness.withSessionDeletion?.(
600+
{
601+
agentId: "worker",
602+
sessionId: "session-1",
603+
sessionKey: "agent:worker:main",
604+
assertCurrent() {},
605+
},
606+
async (mutation) => {
607+
mutation.commit();
608+
expect(state.lookup(bindingStoreKey(identity))).toBeUndefined();
609+
},
610+
);
611+
595612
await harness.reset?.({
596613
agentId: "worker",
597614
sessionId: "session-1",
598615
sessionKey: "agent:worker:main",
599616
reason: "deleted",
600617
});
601618

619+
expect(state.lookup(bindingStoreKey(identity))).toBeUndefined();
620+
});
621+
622+
it("rejects supervised deletion before invoking the session transaction", async () => {
623+
const bindingStore = createCodexTestBindingStore();
624+
const identity = sessionBindingIdentity({
625+
agentId: "worker",
626+
sessionId: "supervised",
627+
sessionKey: "agent:worker:main",
628+
});
629+
await bindingStore.mutate(identity, {
630+
kind: "set",
631+
binding: {
632+
threadId: "thread-supervised",
633+
cwd: "/repo",
634+
connectionScope: "supervision",
635+
supervisionSourceThreadId: "thread-source",
636+
model: "gpt-5.5",
637+
modelProvider: "openai",
638+
preserveNativeModel: true,
639+
conversationSourceTransferComplete: true,
640+
},
641+
});
642+
const harness = createCodexAppServerAgentHarness({ bindingStore });
643+
const run = vi.fn();
602644
await expect(
603-
bindingStore.mutate(identity, {
604-
kind: "set",
605-
binding: { threadId: "thread-stale", cwd: "/repo" },
606-
}),
607-
).resolves.toBe(false);
645+
harness.withSessionDeletion?.(
646+
{
647+
agentId: "worker",
648+
sessionId: "supervised",
649+
sessionKey: "agent:worker:main",
650+
assertCurrent() {},
651+
},
652+
run,
653+
),
654+
).rejects.toThrow("owned by supervision");
655+
expect(run).not.toHaveBeenCalled();
656+
await expect(bindingStore.read(identity)).resolves.toMatchObject({
657+
threadId: "thread-supervised",
658+
});
608659
});
609660
});
610661

‎extensions/codex/harness.ts‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -318,8 +318,14 @@ export function createCodexAppServerAgentHarness(
318318
pluginConfig: options?.resolvePluginConfig?.() ?? options?.pluginConfig,
319319
});
320320
},
321+
withSessionDeletion: async (params, run) => {
322+
const { withCodexAppServerSessionDeletion } =
323+
await import("./src/app-server/session-retirement.js");
324+
params.assertCurrent();
325+
return withCodexAppServerSessionDeletion(options.bindingStore, params, run);
326+
},
321327
reset: async (params) => {
322-
if (params.sessionId) {
328+
if (params.sessionId && params.reason !== "deleted") {
323329
const [
324330
{ reclaimCurrentCodexSessionGeneration, sessionBindingIdentity },
325331
{ retireCodexAppServerSessionGeneration },
@@ -336,7 +342,7 @@ export function createCodexAppServerAgentHarness(
336342
retireCodexAppServerSessionGeneration({
337343
bindingStore: options.bindingStore,
338344
identity,
339-
mode: params.reason === "deleted" ? "retire" : "reset",
345+
mode: "reset",
340346
});
341347
let reset = await resetGeneration();
342348
if (reset === "conflict") {

‎extensions/codex/index.ts‎

Lines changed: 6 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -62,13 +62,7 @@ import {
6262
} from "./src/supervision-tools.js";
6363
import { createCodexWebSearchProvider } from "./src/web-search-provider.js";
6464

65-
const ENDED_SESSION_REASONS: ReadonlySet<string> = new Set([
66-
"new",
67-
"reset",
68-
"idle",
69-
"daily",
70-
"deleted",
71-
]);
65+
const ENDED_SESSION_REASONS: ReadonlySet<string> = new Set(["new", "reset", "idle", "daily"]);
7266

7367
export default definePluginEntry({
7468
id: "codex",
@@ -136,11 +130,13 @@ export default definePluginEntry({
136130
// store only when a proxied runtime performs the first binding operation.
137131
const lazyBindingStateStore: Pick<
138132
PluginStateSyncKeyedStore<StoredCodexAppServerBinding>,
139-
"delete" | "entries" | "lookup" | "update"
133+
"deleteIf" | "entries" | "lookup" | "registerIfAbsent" | "update"
140134
> = {
141-
delete: (key) => openBindingStateStore().delete(key),
135+
deleteIf: (key, predicate) => openBindingStateStore().deleteIf!(key, predicate),
142136
entries: () => openBindingStateStore().entries(),
143137
lookup: (key) => openBindingStateStore().lookup(key),
138+
registerIfAbsent: (key, value, options) =>
139+
openBindingStateStore().registerIfAbsent(key, value, options),
144140
get update() {
145141
const store = openBindingStateStore();
146142
return store.update?.bind(store);
@@ -389,7 +385,7 @@ export default definePluginEntry({
389385
// under a different session key. The only cross-key emitter (gateway child
390386
// creation) keeps the parent row live; same-key rollovers omit or repeat
391387
// the key and still retire, as do unknown-current-key ends (no provable
392-
// handoff) and later idle/daily/deleted ends. See #106778.
388+
// handoff) and later idle/daily ends. See #106778.
393389
const endedSessionKey = sessionKey?.trim();
394390
const nextSessionKey = event.nextSessionKey?.trim();
395391
if (endedSessionKey && nextSessionKey && nextSessionKey !== endedSessionKey) {

‎extensions/codex/src/app-server/attempt-client-cleanup.ts‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -144,12 +144,19 @@ export async function unsubscribeCodexThreadBestEffort(
144144
params: {
145145
threadId: string;
146146
timeoutMs: number;
147+
assertCurrent?: () => void;
147148
},
148149
): Promise<boolean> {
149150
try {
150-
await unsubscribeCodexAppServerLiveThread(client, params.threadId, params.timeoutMs);
151+
await unsubscribeCodexAppServerLiveThread(
152+
client,
153+
params.threadId,
154+
params.timeoutMs,
155+
params.assertCurrent,
156+
);
151157
return true;
152158
} catch (error) {
159+
params.assertCurrent?.();
153160
embeddedAgentLog.debug("codex app-server thread unsubscribe cleanup failed", {
154161
threadId: params.threadId,
155162
error,

‎extensions/codex/src/app-server/client-runtime.test.ts‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -489,6 +489,26 @@ describe("Codex app-server client runtime", () => {
489489
);
490490
});
491491

492+
it("rechecks deletion authority before sending the physical unsubscribe", async () => {
493+
const harness = createClientHarness();
494+
clients.push(harness.client);
495+
ensureCodexAppServerClientRuntime(harness.client, { agentDir: "/tmp/agent" });
496+
await retainCodexAppServerLiveThread(harness.client, "thread-deleted");
497+
const request = vi.spyOn(harness.client, "request");
498+
let current = true;
499+
const release = releaseCodexAppServerLiveThread(harness.client, "thread-deleted", () => {
500+
if (!current) {
501+
throw new Error("deletion owner closed");
502+
}
503+
});
504+
current = false;
505+
await expect(release).rejects.toThrow("deletion owner closed");
506+
expect(request).not.toHaveBeenCalled();
507+
await expect(
508+
consumeCodexAppServerLiveThread(harness.client, "thread-deleted"),
509+
).resolves.toEqual(expect.objectContaining({ release: expect.any(Function) }));
510+
});
511+
492512
it("transfers ownership only for the exact immutable thread fingerprint", async () => {
493513
const harness = createClientHarness();
494514
clients.push(harness.client);

0 commit comments

Comments
 (0)