Skip to content

Commit 1a0e72b

Browse files
authored
fix(sessions): preserve distinct rooms during canonical updates (#132242)
* refactor(sessions): separate canonical mutations from Doctor repair * test(doctor): use canonical migration owners in new diagnostics * fix(doctor): load execution factories only for schema checks Read harness policy from its existing owner and defer agent-tool and MCP factories to the asynchronous schema-inspection boundary. Keep policy, normalization, per-workspace reuse, and disposal unchanged. Cold Linux proof: both complete Doctor E2E files pass 7/7 in three fresh processes with empty transform caches and unchanged 30-second deadlines. Real selected-plugin setup and legacy migration behavior stay covered. Release-note context: Doctor policy and readiness inspection no longer eagerly loads the agent execution graph. No final macOS timing claim. * refactor(doctor): remove unused execution facade exports The direct policy/type imports leave two internal re-exports without any production consumer. Remove them and have the existing selection test import policy from its implementation owner. This resolves the unchanged hard-zero export guard without changing selection behavior, test assertions, mocks, SDK contracts, or deadlines.
1 parent f9061cb commit 1a0e72b

53 files changed

Lines changed: 1150 additions & 1474 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.

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

Lines changed: 7 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -3,17 +3,16 @@ import { isIncognitoSessionKey } from "../incognito-session.js";
33
import {
44
CODEX_APP_SERVER_UNSUBSCRIBE_TIMEOUT_MS,
55
closeCodexStartupClientBestEffort,
6-
CodexAppServerUnsafeSubscriptionError,
76
unsubscribeCodexThreadBestEffort,
87
} from "./attempt-client-cleanup.js";
9-
import { retainCodexAppServerLiveThread } from "./client-runtime.js";
108
import { resolveCodexAppServerClientInstanceId } from "./client.js";
119
import { scheduleCodexNativeHookRelayUnregister } from "./native-hook-relay.js";
1210
import type { CodexAttemptActiveTurn } from "./run-attempt-active-turn.js";
1311
import type { CodexAttemptLifecycleController } from "./run-attempt-lifecycle-controller.js";
1412
import type { CodexAttemptResources } from "./run-attempt-resources.js";
1513
import type { prepareCodexAttemptTurnRequest } from "./run-attempt-turn-request.js";
1614
import type { CodexAttemptTurnState } from "./run-attempt-turn-state.js";
15+
import { retainCodexAppServerBindingSubscription } from "./thread-ownership.js";
1716

1817
export async function cleanupCodexAttempt(
1918
resources: CodexAttemptResources,
@@ -103,26 +102,14 @@ export async function cleanupCodexAttempt(
103102
) {
104103
return false;
105104
}
106-
return await retainCodexAppServerLiveThread(
105+
return await retainCodexAppServerBindingSubscription(
107106
resourceState.client,
108107
resourceState.thread.threadId,
109-
resourceState.thread.liveThreadOwnership?.release ??
110-
(async (threadId, assertCurrent) => {
111-
const released = await unsubscribeCodexThreadBestEffort(resourceState.client, {
112-
threadId,
113-
timeoutMs: CODEX_APP_SERVER_UNSUBSCRIBE_TIMEOUT_MS,
114-
assertCurrent,
115-
});
116-
if (!released) {
117-
assertCurrent?.();
118-
await closeCodexStartupClientBestEffort(resourceState.client);
119-
throw new CodexAppServerUnsafeSubscriptionError(
120-
`Codex retained thread subscription could not be released: ${threadId}`,
121-
);
122-
}
123-
}),
124-
resourceState.thread.liveThreadConfigFingerprint,
125-
connection.mutable.pluginAppServer.serviceTier,
108+
{
109+
release: resourceState.thread.liveThreadOwnership?.release,
110+
configFingerprint: resourceState.thread.liveThreadConfigFingerprint,
111+
serviceTier: connection.mutable.pluginAppServer.serviceTier,
112+
},
126113
);
127114
}))
128115
: false;

‎extensions/codex/src/app-server/session-binding.ts‎

Lines changed: 48 additions & 66 deletions
Original file line numberDiff line numberDiff line change
@@ -956,6 +956,52 @@ export function createCodexAppServerBindingStore(
956956
}
957957
};
958958

959+
const transitionSessionGeneration = async (
960+
identity: Extract<CodexAppServerBindingIdentity, { kind: "session" }>,
961+
mode: "reset" | "retire",
962+
): Promise<CodexSessionGenerationRetirementResult> => {
963+
return await runBindingMutation(async () => {
964+
const key = bindingStoreKey(identity);
965+
const ttlMs =
966+
mode === "reset"
967+
? leaseContext.getStore()?.has(key)
968+
? undefined
969+
: 1
970+
: identity.sessionKey?.trim()
971+
? undefined
972+
: PHYSICAL_SESSION_RETIRE_TTL_MS;
973+
return await transactKey(
974+
key,
975+
(current, leaseToken) => {
976+
if (!current) {
977+
return { result: "absent" as const };
978+
}
979+
if (!ownsStoredSessionGeneration(identity, current)) {
980+
return { result: "conflict" as const };
981+
}
982+
// Retirement is idempotent, but reset cannot clear a same-id deletion fence.
983+
// Only the authoritative session-store reclaim path can prove an in-place reset.
984+
if (current.state === "cleared" && current.retired === true) {
985+
return { result: mode === "retire" ? ("applied" as const) : ("conflict" as const) };
986+
}
987+
return {
988+
result: "applied" as const,
989+
next: {
990+
version: 1,
991+
state: "cleared",
992+
...(mode === "retire" ? { retired: true as const } : {}),
993+
...storedSessionGeneration(identity, current),
994+
...(current.lease && current.lease.token === leaseToken
995+
? { lease: current.lease }
996+
: {}),
997+
},
998+
};
999+
},
1000+
ttlMs,
1001+
);
1002+
});
1003+
};
1004+
9591005
return {
9601006
async read(identity) {
9611007
const key = bindingStoreKey(identity);
@@ -1206,72 +1252,8 @@ export function createCodexAppServerBindingStore(
12061252
});
12071253
},
12081254

1209-
async resetSessionGeneration(identity) {
1210-
return await runBindingMutation(async () => {
1211-
const key = bindingStoreKey(identity);
1212-
return await transactKey(
1213-
key,
1214-
(current, leaseToken) => {
1215-
if (!current) {
1216-
return { result: "absent" as const };
1217-
}
1218-
if (!ownsStoredSessionGeneration(identity, current)) {
1219-
return { result: "conflict" as const };
1220-
}
1221-
// A retired same-id row may be a deletion fence. Only the authoritative
1222-
// session-store reclaim path can prove it belongs to an in-place reset.
1223-
if (current.state === "cleared" && current.retired === true) {
1224-
return { result: "conflict" as const };
1225-
}
1226-
return {
1227-
result: "applied" as const,
1228-
next: {
1229-
version: 1,
1230-
state: "cleared",
1231-
...storedSessionGeneration(identity, current),
1232-
...(current.lease && current.lease.token === leaseToken
1233-
? { lease: current.lease }
1234-
: {}),
1235-
},
1236-
};
1237-
},
1238-
leaseContext.getStore()?.has(key) ? undefined : 1,
1239-
);
1240-
});
1241-
},
1242-
1243-
async retireSessionGeneration(identity) {
1244-
return await runBindingMutation(async () => {
1245-
const key = bindingStoreKey(identity);
1246-
return await transactKey(
1247-
key,
1248-
(current, leaseToken) => {
1249-
if (!current) {
1250-
return { result: "absent" as const };
1251-
}
1252-
if (!ownsStoredSessionGeneration(identity, current)) {
1253-
return { result: "conflict" as const };
1254-
}
1255-
if (current.state === "cleared" && current.retired === true) {
1256-
return { result: "applied" as const };
1257-
}
1258-
return {
1259-
result: "applied" as const,
1260-
next: {
1261-
version: 1,
1262-
state: "cleared",
1263-
retired: true,
1264-
...storedSessionGeneration(identity, current),
1265-
...(current.lease && current.lease.token === leaseToken
1266-
? { lease: current.lease }
1267-
: {}),
1268-
},
1269-
};
1270-
},
1271-
identity.sessionKey?.trim() ? undefined : PHYSICAL_SESSION_RETIRE_TTL_MS,
1272-
);
1273-
});
1274-
},
1255+
resetSessionGeneration: (identity) => transitionSessionGeneration(identity, "reset"),
1256+
retireSessionGeneration: (identity) => transitionSessionGeneration(identity, "retire"),
12751257

12761258
async withThreadArchiveFence(run) {
12771259
pendingArchives += 1;

‎extensions/codex/src/app-server/thread-ownership.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,7 @@ export async function withCodexConversationThreadActivity<T>(
7171
export async function retainCodexAppServerBindingSubscription(
7272
client: CodexAppServerClient,
7373
threadId: string,
74-
ownership?: CodexAppServerLiveThreadOwnership,
74+
ownership?: Partial<CodexAppServerLiveThreadOwnership>,
7575
): Promise<boolean> {
7676
return await retainCodexAppServerLiveThread(
7777
client,

‎extensions/codex/src/migration/session-binding-orphans.ts‎

Lines changed: 16 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -72,16 +72,13 @@ function readBindingCandidate(row: BindingRow, prefix: (typeof KEY_PREFIXES)[num
7272
return { row, agentId, sessionId, stable };
7373
}
7474

75-
async function scanBindings(
76-
{ context }: MigrationParams,
77-
remove?: NonNullable<PluginDoctorStateMigrationContext["deletePluginStateEntriesIfUnchanged"]>,
78-
) {
75+
async function* iterateOrphanBindingPages({
76+
context,
77+
}: MigrationParams): AsyncGenerator<BindingRow[]> {
7978
const readPage = context.readPluginStateEntriesInKeyRange;
8079
const readEvidence = context.readSessionIdentityEvidenceBatch;
81-
let deleted = 0;
82-
let changed = 0;
8380
if (!readPage || !readEvidence) {
84-
return { found: false, deleted, changed };
81+
return;
8582
}
8683
for (const prefix of KEY_PREFIXES) {
8784
let after: string | undefined;
@@ -129,12 +126,7 @@ async function scanBindings(
129126
})
130127
.map(({ row }) => row);
131128
if (stale.length > 0) {
132-
if (!remove) {
133-
return { found: true, deleted, changed };
134-
}
135-
const result = remove(CODEX_APP_SERVER_BINDING_NAMESPACE, stale);
136-
deleted += result.deleted;
137-
changed += result.changed;
129+
yield stale;
138130
}
139131
}
140132
if (rows.length < PAGE_SIZE) {
@@ -144,7 +136,6 @@ async function scanBindings(
144136
await setImmediate();
145137
}
146138
}
147-
return { found: false, deleted, changed };
148139
}
149140

150141
export const codexOrphanedSessionBindingMigration: PluginDoctorStateMigration = {
@@ -153,9 +144,10 @@ export const codexOrphanedSessionBindingMigration: PluginDoctorStateMigration =
153144
doctorOnly: true,
154145
phase: "after-session-repair",
155146
async detectLegacyState(params) {
156-
return (await scanBindings(params)).found
157-
? { preview: ["- Codex app-server bindings: remove orphaned session ownership"] }
158-
: null;
147+
for await (const _ of iterateOrphanBindingPages(params)) {
148+
return { preview: ["- Codex app-server bindings: remove orphaned session ownership"] };
149+
}
150+
return null;
159151
},
160152
async migrateLegacyState(params) {
161153
const remove = params.context.deletePluginStateEntriesIfUnchanged;
@@ -165,7 +157,13 @@ export const codexOrphanedSessionBindingMigration: PluginDoctorStateMigration =
165157
warnings: ["Codex session binding repair requires locked SQLite maintenance ownership"],
166158
};
167159
}
168-
const { deleted, changed } = await scanBindings(params, remove);
160+
let deleted = 0;
161+
let changed = 0;
162+
for await (const rows of iterateOrphanBindingPages(params)) {
163+
const result = remove(CODEX_APP_SERVER_BINDING_NAMESPACE, rows);
164+
deleted += result.deleted;
165+
changed += result.changed;
166+
}
169167
return {
170168
changes:
171169
deleted > 0 ? [`Removed ${deleted} orphaned Codex app-server session binding(s)`] : [],

‎scripts/check-database-first-legacy-stores.mts‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -245,7 +245,6 @@ const allowedRuntimeMigrationPaths = [
245245
"src/commands/doctor/",
246246
"src/commands/doctor-usage-cost-cache.ts",
247247
"src/infra/session-state-migration.ts",
248-
"src/infra/state-migrations.ts",
249248
"src/infra/state-migrations.acp-replay.ts",
250249
"src/infra/state-migrations.tui-last-session.ts",
251250
"src/infra/state-migrations.managed-outgoing-images.ts",

‎src/agents/agent-bundle-mcp-tools.ts‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
/** Public facade for bundle MCP tool materialization and session-scoped runtime management. */
2-
export type { McpToolCatalogDiagnostic } from "./agent-bundle-mcp-types.js";
32
export {
43
disposeAllSessionMcpRuntimes,
54
getOrCreateSessionMcpRuntime,

‎src/agents/harness/selection.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,11 +51,11 @@ import { callGatewayTool } from "../tools/gateway.js";
5151
import type { SystemAgentToolOptions } from "../tools/system-agent-tool.js";
5252
import { maybeCompactAgentHarnessSession as maybeCompactAgentHarnessSessionImpl } from "./compaction.js";
5353
import type { ContextEngineLogicalTurnLease } from "./context-engine-logical-turn.js";
54+
import { resolveAgentHarnessPolicy } from "./policy.js";
5455
import { clearAgentHarnesses, registerAgentHarness } from "./registry.js";
5556
import {
5657
agentHarnessBuildsOpenClawTools,
5758
agentHarnessExposesOpenClawTools,
58-
resolveAgentHarnessPolicy,
5959
resolveAvailableAgentHarnessPolicy,
6060
resolvePluginHarnessPolicyToolsAllow,
6161
runAgentHarnessAttempt,

‎src/agents/harness/selection.ts‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,6 @@ import {
5959
import type { AgentHarness, AgentHarnessSupport, AgentHarnessSupportContext } from "./types.js";
6060

6161
const log = createSubsystemLogger("agents/harness");
62-
export { resolveAgentHarnessPolicy } from "./policy.js";
6362
export { resolveAvailableAgentHarnessPolicy } from "./availability.js";
6463

6564
type AgentHarnessSelectionParams = {

‎src/boards/board-store.parity.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import { useAutoCleanupTempDirTracker } from "../../test/helpers/temp-dir.js";
55
import { replaceSessionEntrySync } from "../config/sessions/session-accessor.entry.js";
66
import { deleteSessionEntryLifecycle } from "../config/sessions/session-accessor.js";
77
import { requireNodeSqlite } from "../infra/node-sqlite.js";
8-
import { migrateLegacyMediaPersistence } from "../infra/state-migrations.js";
8+
import { migrateLegacyMediaPersistence } from "../infra/state-migrations.media-persistence.js";
99
import {
1010
closeOpenClawAgentDatabasesForTest,
1111
openOpenClawAgentDatabase,

‎src/commands/doctor-config-flow.test.ts‎

Lines changed: 0 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1519,13 +1519,6 @@ vi.mock("./doctor-config-analysis.js", () => {
15191519
};
15201520
});
15211521

1522-
vi.mock("./doctor-state-migrations.js", () => ({
1523-
autoMigrateLegacyState: vi.fn(async () => ({ changes: [], warnings: [] })),
1524-
autoMigrateLegacyStateDir: vi.fn(async () => ({ changes: [], warnings: [] })),
1525-
autoMigrateLegacyTaskStateSidecars: vi.fn(async () => ({ changes: [], warnings: [] })),
1526-
migrateLegacyMediaPersistence: vi.fn(() => ({ changes: [], warnings: [] })),
1527-
}));
1528-
15291522
function resetTerminalNoteMock() {
15301523
terminalNoteMock.mockClear();
15311524
return terminalNoteMock;

0 commit comments

Comments
 (0)