Skip to content

Commit 89b8503

Browse files
committed
fix(codex): stop reporting every history failure as a Codex DB lock
The history Worker collapsed every non-converged outcome - a genuine SQLite busy, a permission denial, an unsafe coordinator path, an unavailable coordinator database, or a dead/timed-out Worker - into one message blaming the Codex app/IDE for holding state_5.sqlite. On Windows that reads as a false lock when nothing holds the file (issue #1191), and it made every other failure undiagnosable. - The H/K/N lock modules now compare the requested lock path against its realpath case-insensitively on Windows (samePathIdentity), matching the case-insensitive path identity Windows actually has, instead of refusing legitimate spellings as unsafe-path. - The Windows runtime root is canonicalized via realpath after creation, so differently-cased or junctioned LocalAppData spellings land on one lock namespace. - restoreLegacyOpenaiHistory now reports its failure reason (busy or permission) instead of a bare failed flag, so recover-history gets the same honest classification. - Apply, restore, and recover-history messages now distinguish genuine lock/busy from unsafe-path, unavailable coordinator DB, permission denial, worker error (with the real message), worker death, and worker timeout, each pointing at 'ocx doctor' when the app is not the cause.
1 parent 44dce33 commit 89b8503

12 files changed

Lines changed: 284 additions & 20 deletions

‎src/cli/index.ts‎

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,12 @@
22
import { spawn } from "node:child_process";
33
import { currentExternalCodexModelProvider, restoreNativeCodex, restoreNativeCodexAsync, shouldInjectApiAuthHeader } from "../codex/inject";
44
import { stripGrokConfig } from "../grok/inject";
5-
import { resolveCodexHistoryJobTarget, runCodexHistoryJob } from "../codex/history-job";
5+
import {
6+
describeHistoryJobFailure,
7+
resolveCodexHistoryJobTarget,
8+
runCodexHistoryJob,
9+
type CodexHistoryJobOutcome,
10+
} from "../codex/history-job";
611
import { reconcileJournal } from "../codex/journal";
712
import {
813
codexAutoStartEnabled,
@@ -784,7 +789,10 @@ async function handleRecoverHistory() {
784789
: { rows: 0, files: 0, failed: true as const };
785790
if (r.failed) {
786791
console.error(
787-
"⚠️ Recovery SKIPPED: the Codex history DB is locked (Codex app/IDE open?). Close it and rerun this command.",
792+
`⚠️ Recovery SKIPPED: ${describeHistoryJobFailure(
793+
outcome as Extract<CodexHistoryJobOutcome, { kind: "blocked" | "failed" }>,
794+
"recover-legacy",
795+
)}`,
788796
);
789797
process.exit(1);
790798
}

‎src/codex/catalog-write-serialization.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ import {
3232
CodexUserIdentityRefusal,
3333
resolveCodexCatalogSerializationDatabasePath,
3434
resolveEffectiveUserIdentity,
35+
samePathIdentity,
3536
} from "./user-identity";
3637

3738
/**
@@ -180,7 +181,7 @@ export function withCatalogWriteSerialization<T>(
180181
}
181182
const opened = lstatSync(databasePath);
182183
if (opened.isSymbolicLink() || !opened.isFile()
183-
|| realpathSync.native(databasePath) !== databasePath) {
184+
|| !samePathIdentity(realpathSync.native(databasePath), databasePath)) {
184185
return { kind: "unavailable", reason: "unsafe-path" };
185186
}
186187

‎src/codex/history-job.ts‎

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -135,6 +135,60 @@ export function deriveCodexHistoryOperation(intent: {
135135
return intent.legacyMode ? "apply-opencodex" : "migrate-openai";
136136
}
137137

138+
/**
139+
* The honest failure clause for one history job outcome.
140+
*
141+
* The caller adds its own framing ("sync SKIPPED", "could NOT be restored").
142+
* The point of the surface argument is that a genuine lock keeps today's
143+
* actionable wording, while every other reason stops blaming the Codex app:
144+
* an unsafe-path refusal, an unavailable coordinator database, a permission
145+
* denial, or a dead worker is a different problem with a different remedy.
146+
*/
147+
export function describeHistoryJobFailure(
148+
outcome: Extract<CodexHistoryJobOutcome, { kind: "blocked" | "failed" }>,
149+
surface: "apply" | "restore" | "recover-legacy",
150+
legacyMode = false,
151+
): string {
152+
if (outcome.kind === "blocked") {
153+
switch (outcome.reason) {
154+
case "busy":
155+
if (surface === "apply") {
156+
return legacyMode
157+
? "the history DB is locked (Codex app/IDE open?). Close it and rerun 'ocx start'."
158+
: "the history DB is locked (Codex app/IDE open?). It is retried automatically (while the proxy runs and on every 'ocx start'); to force it now, close the Codex app and run 'ocx sync'.";
159+
}
160+
if (surface === "recover-legacy") {
161+
return "the Codex history DB is locked (Codex app/IDE open?). Close it and rerun this command.";
162+
}
163+
return "the Codex app appears to be holding the history database. Close Codex and run `ocx restore` again.";
164+
case "unsafe-path":
165+
return "opencodex refused its history lock path (unsafe coordinator namespace); this is not a Codex app lock. Run 'ocx doctor' and check the opencodex runtime directory.";
166+
case "database":
167+
return "the history coordinator database is unavailable; this is not a Codex app lock. Run 'ocx doctor'.";
168+
case "desired_disabled":
169+
return "Codex integration is disabled, so the history operation was skipped.";
170+
case "desired_enabled":
171+
return "Codex integration is enabled, so the history operation was skipped.";
172+
}
173+
}
174+
if (outcome.historyFailureReason === "busy") {
175+
return surface === "restore"
176+
? "the Codex app appears to be holding the history database. Close Codex and run `ocx restore` again."
177+
: "the history DB is locked (Codex app/IDE open?).";
178+
}
179+
if (outcome.historyFailureReason === "permission") {
180+
return "permission was denied while writing Codex history; this is not a Codex app lock. Run 'ocx doctor'.";
181+
}
182+
switch (outcome.reason) {
183+
case "worker-error":
184+
return `the history worker failed (${outcome.message}). Run 'ocx doctor'.`;
185+
case "worker-died":
186+
return "the history worker exited unexpectedly; this is not a Codex app lock. Run 'ocx doctor'.";
187+
case "timeout":
188+
return "the history worker timed out; this is not a Codex app lock. Run 'ocx doctor'.";
189+
}
190+
}
191+
138192
function classifyWorkerResult(result: HistoryWorkerResult): CodexHistoryJobOutcome {
139193
if (result.type === "blocked") return { kind: "blocked", reason: result.reason };
140194
if (result.type === "error") {

‎src/codex/history-lock.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ import {
3737
CodexUserIdentityRefusal,
3838
resolveCodexHistorySerializationDatabasePath,
3939
resolveEffectiveUserIdentity,
40+
samePathIdentity,
4041
} from "./user-identity";
4142

4243
/**
@@ -183,7 +184,7 @@ export function withHistoryWriteSerialization<T>(
183184
}
184185
const opened = lstatSync(databasePath);
185186
if (opened.isSymbolicLink() || !opened.isFile()
186-
|| realpathSync.native(databasePath) !== databasePath) {
187+
|| !samePathIdentity(realpathSync.native(databasePath), databasePath)) {
187188
return { kind: "unavailable", reason: "unsafe-path" };
188189
}
189190

‎src/codex/history-provider.ts‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -722,16 +722,17 @@ function restoreCodexHistoryProvider(stateDbPath: string, backupPath: string): C
722722
}
723723
}
724724

725-
export function restoreLegacyOpenaiHistory(stateDbPath = STATE_DB_PATH): { rows: number; files: number; failed?: true } {
725+
export function restoreLegacyOpenaiHistory(stateDbPath = STATE_DB_PATH): CodexHistorySyncResult {
726726
if (!existsSync(stateDbPath)) return { rows: 0, files: 0 };
727-
return withHistoryRetry(() => {
727+
const retried = withHistoryRetryResult(() => {
728728
const db = openStateDb(stateDbPath);
729729
try {
730730
return ejectRemainingOpencodexHistory(db);
731731
} finally {
732732
db.close();
733733
}
734-
}) ?? { rows: 0, files: 0, failed: true };
734+
});
735+
return retried.ok ? retried.value : { rows: 0, files: 0, failed: true, failureReason: retried.reason };
735736
}
736737

737738
/**

‎src/codex/inject.ts‎

Lines changed: 76 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -38,9 +38,11 @@ import { withCatalogWriteSerialization } from "./catalog-write-serialization";
3838
import { restoreCodexCatalogWithPermit } from "./catalog/sync";
3939
import { syncCodexHistoryProvider, type CodexHistoryFailureReason } from "./history-provider";
4040
import {
41+
describeHistoryJobFailure,
4142
deriveCodexHistoryOperation,
4243
resolveCodexHistoryJobTarget,
4344
runCodexHistoryJob,
45+
type CodexHistoryJobOutcome,
4446
} from "./history-job";
4547
import {
4648
OCX_SECTION_MARKER,
@@ -1018,11 +1020,7 @@ export async function injectCodexConfig(
10181020
config?.syncResumeHistory === false
10191021
? ` Codex resume history: left unchanged (syncResumeHistory=false).\n`
10201022
: history.failed
1021-
? legacyMode
1022-
? ` ⚠️ Codex resume history sync SKIPPED: the history DB is locked (Codex app/IDE open?). Close it and rerun 'ocx start'.\n`
1023-
: // Honest in every caller context: the daemon retries in the background while it runs,
1024-
// and this inject path re-runs the migration on every future start/sync anyway.
1025-
` ⚠️ Codex resume history migration deferred: the history DB is locked (Codex app/IDE open?). It is retried automatically (while the proxy runs and on every 'ocx start'); to force it now, close the Codex app and run 'ocx sync'.\n`
1023+
? formatApplyHistoryFailure(historyOutcome, legacyMode)
10261024
: legacyMode
10271025
? ` Codex resume history: ${history.rows} thread(s) made visible for opencodex; originals backed up for restore.\n`
10281026
: migratedRows > 0
@@ -1234,7 +1232,7 @@ export interface CodexNativeRestoreResult {
12341232
};
12351233
}
12361234

1237-
function failedHistoryRestore(reason?: CodexHistoryFailureReason): CodexRestoreHistoryResult {
1235+
function failedHistoryRestore(reason?: CodexHistoryFailureReason, detail?: string): CodexRestoreHistoryResult {
12381236
return {
12391237
state: "failed",
12401238
changed: false,
@@ -1244,10 +1242,62 @@ function failedHistoryRestore(reason?: CodexHistoryFailureReason): CodexRestoreH
12441242
ejectedRows: 0,
12451243
message: reason === "permission"
12461244
? "Codex resume history could NOT be restored because permission was denied."
1247-
: "Codex resume history could NOT be restored — the Codex app appears to be holding the history database.",
1245+
: reason === "busy"
1246+
? "Codex resume history could NOT be restored — the Codex app appears to be holding the history database."
1247+
: detail
1248+
? `Codex resume history could NOT be restored: ${detail}`
1249+
: "Codex resume history could NOT be restored — the Codex app appears to be holding the history database.",
12481250
};
12491251
}
12501252

1253+
/**
1254+
* Restore failure wording for a Worker outcome.
1255+
*
1256+
* Only a genuine busy result blames the Codex app. An unsafe-path refusal, an
1257+
* unavailable coordinator database, a permission denial, or a dead/timed-out
1258+
* worker is a different problem; the old collapse made every one of those read
1259+
* as "the Codex app is holding the database" (issue #1191).
1260+
*/
1261+
function failedHistoryRestoreFromOutcome(
1262+
outcome: Extract<CodexHistoryJobOutcome, { kind: "blocked" | "failed" }>,
1263+
): CodexRestoreHistoryResult {
1264+
if (outcome.kind === "blocked") {
1265+
switch (outcome.reason) {
1266+
case "busy":
1267+
return failedHistoryRestore("busy");
1268+
case "unsafe-path":
1269+
return failedHistoryRestore(
1270+
undefined,
1271+
"opencodex refused its history lock path (unsafe coordinator namespace); this is not a Codex app lock. Run 'ocx doctor' and check the opencodex runtime directory.",
1272+
);
1273+
case "database":
1274+
return failedHistoryRestore(
1275+
undefined,
1276+
"the history coordinator database is unavailable; this is not a Codex app lock. Run 'ocx doctor'.",
1277+
);
1278+
case "desired_disabled":
1279+
case "desired_enabled":
1280+
return failedHistoryRestore();
1281+
}
1282+
}
1283+
if (outcome.historyFailureReason === "busy") return failedHistoryRestore("busy");
1284+
if (outcome.historyFailureReason === "permission") return failedHistoryRestore("permission");
1285+
switch (outcome.reason) {
1286+
case "worker-error":
1287+
return failedHistoryRestore(undefined, `the history worker failed (${outcome.message}). Run 'ocx doctor'.`);
1288+
case "worker-died":
1289+
return failedHistoryRestore(
1290+
undefined,
1291+
"the history worker exited unexpectedly; this is not a Codex app lock. Run 'ocx doctor'.",
1292+
);
1293+
case "timeout":
1294+
return failedHistoryRestore(
1295+
undefined,
1296+
"the history worker timed out; this is not a Codex app lock. Run 'ocx doctor'.",
1297+
);
1298+
}
1299+
}
1300+
12511301
function externalProviderRestoreResult(activeProvider: string): CodexNativeRestoreResult {
12521302
const message = `External Codex provider ${tomlString(activeProvider)} preserved; no native restore was needed.`;
12531303
return {
@@ -1483,10 +1533,10 @@ export async function restoreNativeCodexAsync(
14831533
? "Codex integration was disabled; history restoration was skipped."
14841534
: "Codex integration was enabled; history restoration was skipped.",
14851535
}
1486-
: outcome.kind === "blocked" && outcome.reason === "busy"
1487-
? failedHistoryRestore("busy")
1536+
: outcome.kind === "blocked"
1537+
? failedHistoryRestoreFromOutcome(outcome)
14881538
: outcome.kind === "failed"
1489-
? failedHistoryRestore(outcome.historyFailureReason)
1539+
? failedHistoryRestoreFromOutcome(outcome)
14901540
: failedHistoryRestore();
14911541
const base = catalog.removed > 0
14921542
? `${config.message} Catalog restored to ${catalog.kept} native model(s) (dropped ${catalog.removed} proxy-routed).`
@@ -1556,3 +1606,19 @@ export function restoreNativeCodex(options: { skipHistory?: boolean; revalidateD
15561606
export function getCodexConfigPath(): string {
15571607
return CODEX_CONFIG_PATH;
15581608
}
1609+
1610+
/**
1611+
* Frame one failed apply history job honestly.
1612+
*
1613+
* A genuine lock keeps the established deferred/SKIPPED wording; any other
1614+
* reason names itself instead of blaming the Codex app/IDE.
1615+
*/
1616+
function formatApplyHistoryFailure(outcome: CodexHistoryJobOutcome, legacyMode: boolean): string {
1617+
const failure = outcome as Extract<CodexHistoryJobOutcome, { kind: "blocked" | "failed" }>;
1618+
const headline = legacyMode
1619+
? "Codex resume history sync SKIPPED"
1620+
: outcome.kind === "blocked" && outcome.reason === "busy"
1621+
? "Codex resume history migration deferred"
1622+
: "Codex resume history NOT changed";
1623+
return ` ⚠️ ${headline}: ${describeHistoryJobFailure(failure, "apply", legacyMode)}\n`;
1624+
}

‎src/codex/transition-state.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ import {
3434
CodexUserIdentityRefusal,
3535
resolveCodexCoordinatorDatabasePath,
3636
resolveEffectiveUserIdentity,
37+
samePathIdentity,
3738
} from "./user-identity";
3839

3940
const COORDINATOR_SCHEMA_VERSION = 1;
@@ -433,7 +434,7 @@ export function openCodexCoordinatorTransaction(finalDatabasePath: string): Code
433434
const entry = lstatSync(finalDatabasePath);
434435
if (entry.isSymbolicLink() || !entry.isFile()
435436
|| `${entry.dev}:${entry.ino}` !== initialIdentity
436-
|| realpathSync.native(finalDatabasePath) !== finalDatabasePath) {
437+
|| !samePathIdentity(realpathSync.native(finalDatabasePath), finalDatabasePath)) {
437438
throw new CodexUserIdentityRefusal("The coordinator database path was substituted.");
438439
}
439440
};

‎src/codex/user-identity.ts‎

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -160,7 +160,35 @@ function resolveWindowsRuntimeRoot(identity: Extract<UserIdentity, { platform: "
160160
} catch (cause) {
161161
refuse("The Windows coordinator namespace cannot be created.", cause);
162162
}
163-
return root;
163+
// Canonicalize before anything is keyed on the path: a junctioned or
164+
// differently-cased LocalAppData must land on ONE namespace, or two processes
165+
// that share the real directory would build different lock paths and never
166+
// contend. The lock modules also compare this path against realpath, so a
167+
// non-canonical spelling here would read as "unsafe" on every acquisition.
168+
try {
169+
return realpathSync.native(root);
170+
} catch (cause) {
171+
refuse("The Windows coordinator namespace cannot be resolved.", cause);
172+
}
173+
}
174+
175+
/**
176+
* Windows path identity is case-insensitive; everywhere else it is exact.
177+
*
178+
* The lock modules compare a requested lock path against its own realpath, and
179+
* byte equality refuses legitimate Windows spellings (drive-letter case, mixed
180+
* component casing) as "unsafe". This is the same semantics
181+
* `history-provider.ts` already applies to manifest paths; the platform
182+
* argument exists so both branches are testable on any host.
183+
*/
184+
export function samePathIdentity(
185+
a: string,
186+
b: string,
187+
platform: NodeJS.Platform = process.platform,
188+
): boolean {
189+
const left = resolve(a);
190+
const right = resolve(b);
191+
return platform === "win32" ? left.toLowerCase() === right.toLowerCase() : left === right;
164192
}
165193

166194
export const resolveCodexCoordinatorDatabasePath: ResolveCodexCoordinatorDatabasePath = (

0 commit comments

Comments
 (0)