Skip to content

Commit 44b0a04

Browse files
committed
fix(codex): keep doctor probe read-only and dedupe failure wording
1 parent e9d58d8 commit 44b0a04

6 files changed

Lines changed: 179 additions & 61 deletions

File tree

‎src/cli/doctor.ts‎

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -25,10 +25,9 @@ import { NativeProfileError } from "../codex/native-profile-types";
2525
import { collectOrcaCodexHomeDiagnostic, resolveCodexHomeDir as resolveCodexHomeDirImpl, isWslRuntime, listWslWindowsCodexHomes, wslAutomountRoot, type CodexHomeDeps } from "../codex/home";
2626
import { findCodexOnPath, isWindowsInteropDir } from "../codex/shim";
2727
import { countPendingOpencodexHistory } from "../codex/history-provider";
28-
import { getCodexHome } from "../codex/paths";
2928
import {
3029
CodexUserIdentityRefusal,
31-
resolveCodexHistorySerializationDatabasePath,
30+
probeCodexCoordinatorNamespace,
3231
resolveEffectiveUserIdentity,
3332
} from "../codex/user-identity";
3433
import { collectProjectCodexConfigWarnings, formatProjectCodexConfigWarningsForDoctor } from "../codex/project-config-warnings";
@@ -909,13 +908,17 @@ export async function runDoctor(args: string[] = []): Promise<void> {
909908
// busy timeout) — reports state, never mutates.
910909
console.log("\nCodex history migration");
911910
// The history failure messages point here; make the visit worthwhile by
912-
// probing the coordinator namespace the locks live in. Resolution exercises
913-
// identity, runtime-root, and permission checks without taking any lock.
911+
// probing the coordinator namespace the locks live in. The probe exercises
912+
// identity, runtime-root, and permission checks without taking any lock or
913+
// creating anything (a doctor run must observe, not initialize).
914914
try {
915915
const identity = resolveEffectiveUserIdentity();
916-
const codexHome = getCodexHome();
917-
resolveCodexHistorySerializationDatabasePath(identity, codexHome, join(codexHome, "state_5.sqlite"));
918-
console.log(" ok history coordinator namespace resolves");
916+
const probe = probeCodexCoordinatorNamespace(identity);
917+
if (probe.status === "missing") {
918+
console.log(" ok history coordinator namespace not created yet (no history operation has run)");
919+
} else {
920+
console.log(" ok history coordinator namespace resolves");
921+
}
919922
} catch (cause) {
920923
const reason = cause instanceof CodexUserIdentityRefusal ? cause.message : String(cause);
921924
console.log(` -- history coordinator namespace refused: ${reason}`);

‎src/codex/history-job.ts‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -205,7 +205,14 @@ export function describeHistoryJobFailure(
205205
*/
206206
function redactWorkerMessage(message: string): string {
207207
const home = homedir();
208-
return home.length > 1 ? message.split(home).join("~") : message;
208+
if (home.length <= 1) return message;
209+
// Windows spellings vary in case and separator; an exact match would leave
210+
// the account name in the message.
211+
if (process.platform === "win32") {
212+
const escaped = home.replace(/[.*+?^${}()|[\]\\]/g, "\\$&").replace(/\\\\/g, "[\\\\/]");
213+
return message.replace(new RegExp(escaped, "gi"), "~");
214+
}
215+
return message.split(home).join("~");
209216
}
210217

211218
function classifyWorkerResult(result: HistoryWorkerResult): CodexHistoryJobOutcome {

‎src/codex/inject.ts‎

Lines changed: 14 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -1262,7 +1262,7 @@ function failedHistoryRestore(reason?: CodexHistoryFailureReason, detail?: strin
12621262
? "Codex resume history could NOT be restored — the Codex app appears to be holding the history database."
12631263
: detail
12641264
? `Codex resume history could NOT be restored: ${detail}`
1265-
: "Codex resume history could NOT be restored — the Codex app appears to be holding the history database.",
1265+
: "Codex resume history could NOT be restored; the reason was not recorded. Run 'ocx doctor'.",
12661266
};
12671267
}
12681268

@@ -1272,55 +1272,20 @@ function failedHistoryRestore(reason?: CodexHistoryFailureReason, detail?: strin
12721272
* Only a genuine busy result blames the Codex app. An unsafe-path refusal, an
12731273
* unavailable coordinator database, a permission denial, or a dead/timed-out
12741274
* worker is a different problem; the old collapse made every one of those read
1275-
* as "the Codex app is holding the database" (issue #1191).
1275+
* as "the Codex app is holding the database" (issue #1191). `busy` and
1276+
* `permission` keep the restore-specific sentence built by
1277+
* `failedHistoryRestore`; every other reason reuses the single formatter so
1278+
* the two modules cannot drift apart.
12761279
*/
1277-
function failedHistoryRestoreFromOutcome(
1280+
export function failedHistoryRestoreFromOutcome(
12781281
outcome: Extract<CodexHistoryJobOutcome, { kind: "blocked" | "failed" }>,
12791282
): CodexRestoreHistoryResult {
1280-
if (outcome.kind === "blocked") {
1281-
switch (outcome.reason) {
1282-
case "busy":
1283-
return failedHistoryRestore("busy");
1284-
case "unsafe-path":
1285-
return failedHistoryRestore(
1286-
undefined,
1287-
"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.",
1288-
);
1289-
case "database":
1290-
return failedHistoryRestore(
1291-
undefined,
1292-
"the history coordinator database is unavailable; this is not a Codex app lock. Run 'ocx doctor'.",
1293-
);
1294-
case "desired_disabled":
1295-
case "desired_enabled":
1296-
// Unreachable today: the async restore caller intercepts both desired-
1297-
// state reasons before this mapper runs. If that ever changes, name
1298-
// the actual cause instead of falling back to the lock wording this
1299-
// function exists to get rid of (issue #1191).
1300-
return failedHistoryRestore(
1301-
undefined,
1302-
outcome.reason === "desired_disabled"
1303-
? "Codex integration is disabled, so the history operation was skipped."
1304-
: "Codex integration is enabled, so the history operation was skipped.",
1305-
);
1306-
}
1307-
}
1308-
if (outcome.historyFailureReason === "busy") return failedHistoryRestore("busy");
1309-
if (outcome.historyFailureReason === "permission") return failedHistoryRestore("permission");
1310-
switch (outcome.reason) {
1311-
case "worker-error":
1312-
return failedHistoryRestore(undefined, `the history worker failed (${outcome.message}). Run 'ocx doctor'.`);
1313-
case "worker-died":
1314-
return failedHistoryRestore(
1315-
undefined,
1316-
"the history worker exited unexpectedly; this is not a Codex app lock. Run 'ocx doctor'.",
1317-
);
1318-
case "timeout":
1319-
return failedHistoryRestore(
1320-
undefined,
1321-
"the history worker timed out; this is not a Codex app lock. Run 'ocx doctor'.",
1322-
);
1283+
if (outcome.kind === "blocked" && outcome.reason === "busy") return failedHistoryRestore("busy");
1284+
if (outcome.kind === "failed" && outcome.historyFailureReason === "busy") return failedHistoryRestore("busy");
1285+
if (outcome.kind === "failed" && outcome.historyFailureReason === "permission") {
1286+
return failedHistoryRestore("permission");
13231287
}
1288+
return failedHistoryRestore(undefined, describeHistoryJobFailure(outcome, "restore"));
13241289
}
13251290

13261291
function externalProviderRestoreResult(activeProvider: string): CodexNativeRestoreResult {
@@ -1558,11 +1523,9 @@ export async function restoreNativeCodexAsync(
15581523
? "Codex integration was disabled; history restoration was skipped."
15591524
: "Codex integration was enabled; history restoration was skipped.",
15601525
}
1561-
: outcome.kind === "blocked"
1526+
: outcome.kind === "blocked" || outcome.kind === "failed"
15621527
? failedHistoryRestoreFromOutcome(outcome)
1563-
: outcome.kind === "failed"
1564-
? failedHistoryRestoreFromOutcome(outcome)
1565-
: failedHistoryRestore();
1528+
: failedHistoryRestore();
15661529
const base = catalog.removed > 0
15671530
? `${config.message} Catalog restored to ${catalog.kept} native model(s) (dropped ${catalog.removed} proxy-routed).`
15681531
: config.message;
@@ -1638,7 +1601,7 @@ export function getCodexConfigPath(): string {
16381601
* A genuine lock keeps the established deferred/SKIPPED wording; any other
16391602
* reason names itself instead of blaming the Codex app/IDE.
16401603
*/
1641-
function formatApplyHistoryFailure(outcome: CodexHistoryJobOutcome, legacyMode: boolean): string {
1604+
export function formatApplyHistoryFailure(outcome: CodexHistoryJobOutcome, legacyMode: boolean): string {
16421605
// A busy database is a deferral no matter which half observed it: the lock
16431606
// contended (blocked/busy), or the worker acquired the lock and then found
16441607
// SQLite busy (failed with a busy history reason). Only those keep the

‎src/codex/user-identity.ts‎

Lines changed: 71 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -123,7 +123,7 @@ function ensurePrivatePosixDirectory(path: string, uid: number): void {
123123
assertPrivatePosixDirectory(path, uid);
124124
}
125125

126-
function resolvePosixRuntimeRoot(uid: number): string {
126+
function resolveTrustedPosixTmp(): string {
127127
let realTmp: string;
128128
try {
129129
realTmp = realpathSync.native(POSIX_TMP_PATH);
@@ -138,12 +138,82 @@ function resolvePosixRuntimeRoot(uid: number): string {
138138
if (cause instanceof CodexUserIdentityRefusal) throw cause;
139139
refuse("The system temporary directory cannot be trusted.", cause);
140140
}
141+
return realTmp;
142+
}
141143

144+
function resolvePosixRuntimeRoot(uid: number): string {
145+
const realTmp = resolveTrustedPosixTmp();
142146
const root = join(realTmp, `opencodex-runtime-v1-${uid}`);
143147
ensurePrivatePosixDirectory(root, uid);
144148
return root;
145149
}
146150

151+
export type CoordinatorNamespaceProbe =
152+
| { readonly status: "ok"; readonly root: string }
153+
| { readonly status: "missing" };
154+
155+
/**
156+
* Read-only namespace probe for diagnostics (`ocx doctor`).
157+
*
158+
* Unlike the runtime resolvers, this never creates the root or the lock
159+
* directories: a doctor run must observe the namespace, not initialize it.
160+
* A missing namespace is reported as `missing` instead of refused, so a fresh
161+
* machine does not read as a broken one; an existing but unsafe namespace is
162+
* refused exactly like the creating path would refuse it.
163+
*/
164+
export function probeCodexCoordinatorNamespace(identity: UserIdentity): CoordinatorNamespaceProbe {
165+
if (identity.platform === "posix") {
166+
const root = join(resolveTrustedPosixTmp(), `opencodex-runtime-v1-${identity.uid}`);
167+
let entry;
168+
try {
169+
entry = lstatSync(root);
170+
} catch (cause) {
171+
const code = cause && typeof cause === "object" && "code" in cause
172+
? String((cause as { code?: unknown }).code)
173+
: "";
174+
if (code === "ENOENT") return { status: "missing" };
175+
refuse("The Codex coordinator namespace cannot be inspected.", cause);
176+
}
177+
if (entry.isSymbolicLink() || !entry.isDirectory()) {
178+
refuse("The Codex coordinator namespace is not a real directory.");
179+
}
180+
if (entry.uid !== identity.uid || (entry.mode & 0o777) !== POSIX_PRIVATE_MODE) {
181+
refuse("The Codex coordinator namespace has unsafe ownership or permissions.");
182+
}
183+
return { status: "ok", root };
184+
}
185+
186+
if (!SID_PATTERN.test(identity.sid)) refuse("The coordinator identity contains an invalid SID.");
187+
const localAppData = powershellValue(
188+
"[Environment]::GetFolderPath([Environment+SpecialFolder]::LocalApplicationData)",
189+
);
190+
if (!isAbsolute(localAppData)) refuse("Windows LocalAppData resolution returned a relative path.");
191+
const root = resolve(localAppData, "OpenCodex", "Runtime", "v1", identity.sid.toUpperCase());
192+
let entry;
193+
try {
194+
entry = lstatSync(root);
195+
} catch (cause) {
196+
const code = cause && typeof cause === "object" && "code" in cause
197+
? String((cause as { code?: unknown }).code)
198+
: "";
199+
if (code === "ENOENT") return { status: "missing" };
200+
refuse("The Windows coordinator namespace cannot be inspected.", cause);
201+
}
202+
if (entry.isSymbolicLink() || !entry.isDirectory()) {
203+
refuse("The Windows coordinator namespace is not a real directory.");
204+
}
205+
try {
206+
const real = realpathSync.native(root);
207+
if (!samePathIdentity(real, root, "win32")) {
208+
refuse("The Windows coordinator namespace is redirected by a junction or reparse point.");
209+
}
210+
return { status: "ok", root: real };
211+
} catch (cause) {
212+
if (cause instanceof CodexUserIdentityRefusal) throw cause;
213+
refuse("The Windows coordinator namespace cannot be resolved.", cause);
214+
}
215+
}
216+
147217
function resolveWindowsRuntimeRoot(identity: Extract<UserIdentity, { platform: "win32" }>): string {
148218
if (!SID_PATTERN.test(identity.sid)) refuse("The coordinator identity contains an invalid SID.");
149219
const localAppData = powershellValue(
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
import { expect, test } from "bun:test";
2+
3+
import {
4+
failedHistoryRestoreFromOutcome,
5+
formatApplyHistoryFailure,
6+
} from "../src/codex/inject";
7+
8+
test("apply keeps the deferred headline for busy outcomes from either half", () => {
9+
const blockedBusy = { kind: "blocked", reason: "busy" } as const;
10+
expect(formatApplyHistoryFailure(blockedBusy, false)).toContain("migration deferred");
11+
expect(formatApplyHistoryFailure(blockedBusy, false)).toContain("history DB is locked");
12+
13+
const workerBusy = {
14+
kind: "failed",
15+
reason: "worker-error",
16+
message: "database is locked",
17+
historyFailureReason: "busy",
18+
} as const;
19+
expect(formatApplyHistoryFailure(workerBusy, false)).toContain("migration deferred");
20+
expect(formatApplyHistoryFailure(workerBusy, false)).toContain("retried automatically");
21+
});
22+
23+
test("apply says NOT changed for non-busy failures", () => {
24+
const unsafe = { kind: "blocked", reason: "unsafe-path" } as const;
25+
expect(formatApplyHistoryFailure(unsafe, false)).toContain("NOT changed");
26+
expect(formatApplyHistoryFailure(unsafe, false)).toContain("not a Codex app lock");
27+
28+
const workerError = { kind: "failed", reason: "worker-error", message: "unable to open database file" } as const;
29+
expect(formatApplyHistoryFailure(workerError, false)).toContain("NOT changed");
30+
expect(formatApplyHistoryFailure(workerError, false)).toContain("unable to open database file");
31+
});
32+
33+
test("restore blames the Codex app only for genuine busy reasons", () => {
34+
const blockedBusy = { kind: "blocked", reason: "busy" } as const;
35+
expect(failedHistoryRestoreFromOutcome(blockedBusy).message).toContain("holding the history database");
36+
37+
const workerBusy = {
38+
kind: "failed",
39+
reason: "worker-error",
40+
message: "database is locked",
41+
historyFailureReason: "busy",
42+
} as const;
43+
expect(failedHistoryRestoreFromOutcome(workerBusy).message).toContain("holding the history database");
44+
});
45+
46+
test("restore names other reasons instead of a lock", () => {
47+
const unsafe = { kind: "blocked", reason: "unsafe-path" } as const;
48+
const unsafeMessage = failedHistoryRestoreFromOutcome(unsafe).message;
49+
expect(unsafeMessage).toContain("unsafe coordinator namespace");
50+
expect(unsafeMessage).not.toContain("holding the history database");
51+
52+
const permission = {
53+
kind: "failed",
54+
reason: "worker-error",
55+
message: "history_transition_failed",
56+
historyFailureReason: "permission",
57+
} as const;
58+
expect(failedHistoryRestoreFromOutcome(permission).message).toContain("permission was denied");
59+
60+
const workerError = { kind: "failed", reason: "worker-error", message: "unable to open database file" } as const;
61+
const workerMessage = failedHistoryRestoreFromOutcome(workerError).message;
62+
expect(workerMessage).toContain("unable to open database file");
63+
expect(workerMessage).not.toContain("holding the history database");
64+
});

‎tests/codex-user-identity.test.ts‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { afterEach, beforeEach, expect, test } from "bun:test";
2-
import { mkdirSync, mkdtempSync, realpathSync, rmSync } from "node:fs";
2+
import { existsSync, mkdirSync, mkdtempSync, realpathSync, rmSync } from "node:fs";
33
import { join, parse } from "node:path";
44
import { tmpdir } from "node:os";
55
import { pathToFileURL } from "node:url";
@@ -9,6 +9,7 @@ import {
99
resolveCodexCatalogSerializationDatabasePath,
1010
resolveCodexHistorySerializationDatabasePath,
1111
resolveEffectiveUserIdentity,
12+
probeCodexCoordinatorNamespace,
1213
samePathIdentity,
1314
} from "../src/codex/user-identity";
1415

@@ -77,6 +78,16 @@ test("samePathIdentity is case-insensitive on Windows and exact elsewhere", () =
7778
expect(samePathIdentity("/tmp/a/b.sqlite", "/tmp/A/b.sqlite", "linux")).toBe(false);
7879
});
7980

81+
test("the coordinator namespace probe is read-only", () => {
82+
if (process.platform === "win32") return;
83+
// No real user has this uid, so the namespace cannot exist before or after.
84+
const uid = 2_147_483_647;
85+
const probe = probeCodexCoordinatorNamespace({ platform: "posix", uid });
86+
expect(probe.status).toBe("missing");
87+
const root = join(realpathSync.native("/tmp"), `opencodex-runtime-v1-${uid}`);
88+
expect(existsSync(root)).toBe(false);
89+
});
90+
8091
afterEach(() => {
8192
if (previousHome === undefined) delete process.env.HOME;
8293
else process.env.HOME = previousHome;

0 commit comments

Comments
 (0)