Skip to content

Commit cf26fe3

Browse files
committed
fix(cli): diagnose Orca Codex home mismatch
1 parent 911373d commit cf26fe3

9 files changed

Lines changed: 151 additions & 3 deletions

File tree

‎src/cli/doctor.ts‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ import { gracefulStopHost } from "../lib/process-control";
1515
import { maskAccountId } from "../lib/privacy";
1616
import { loadServiceTokenFromFile } from "../lib/service-secrets";
1717
import { readCodexTokens } from "../codex/auth-collision";
18-
import { resolveCodexHomeDir as resolveCodexHomeDirImpl, isWslRuntime, listWslWindowsCodexHomes, wslAutomountRoot, type CodexHomeDeps } from "../codex/home";
18+
import { collectOrcaCodexHomeDiagnostic, resolveCodexHomeDir as resolveCodexHomeDirImpl, isWslRuntime, listWslWindowsCodexHomes, wslAutomountRoot, type CodexHomeDeps } from "../codex/home";
1919
import { findCodexOnPath, isWindowsInteropDir } from "../codex/shim";
2020
import { countPendingOpencodexHistory } from "../codex/history-provider";
2121
import { collectProjectCodexConfigWarnings, formatProjectCodexConfigWarningsForDoctor } from "../codex/project-config-warnings";
@@ -636,6 +636,16 @@ export async function runDoctor(args: string[] = []): Promise<void> {
636636
console.log(` ${row.exists ? "ok " : "-- "} ${row.label}: ${row.path}${flags ? ` (${flags})` : ""}`);
637637
}
638638

639+
const orcaHome = collectOrcaCodexHomeDiagnostic();
640+
console.log("\nCodex app home targeting");
641+
console.log(` ${orcaHome.mismatch ? "!! " : "ok "} Effective Codex home: ${orcaHome.effectiveCodexHome}`);
642+
if (orcaHome.mismatch) {
643+
console.log(` !! ${orcaHome.warning}`);
644+
console.log(` Action: ${orcaHome.action}`);
645+
} else {
646+
console.log(" No Orca-owned CODEX_HOME mismatch detected.");
647+
}
648+
639649
const doctorConfig = readConfigDiagnostics().config;
640650
const startup = collectStartupHealth(doctorConfig);
641651
console.log("\nCodex restart safety");

‎src/cli/index.ts‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@ import { maybeShowStarPrompt } from "./star-prompt";
4242
import { maybeShowUpdatePrompt } from "../update/notify";
4343
import { syncModelsToCodex } from "../codex/sync";
4444
import { normalizeUpdateChannel, runGuiUpdateWorker } from "../update/job";
45+
import { collectOrcaCodexHomeDiagnostic } from "../codex/home";
4546

4647
const args = process.argv.slice(2);
4748
const command = args[0];
@@ -615,6 +616,11 @@ async function handleStatus() {
615616
console.log(` Codex runtime: ${status.json.codexRuntime.path}`);
616617
console.log(` Codex version: ${status.json.codexRuntime.version ?? "unknown"}`);
617618
console.log(` Codex source: ${status.json.codexRuntime.source}`);
619+
console.log(` Codex home: ${status.json.codexHome.effectiveCodexHome}`);
620+
if (status.json.codexHome.warning) {
621+
console.log(` ⚠️ ${status.json.codexHome.warning}`);
622+
console.log(` Action: ${status.json.codexHome.action}`);
623+
}
618624
console.log(` Catalog clamp: ${status.json.codexRuntime.catalogClamp.active ? "active" : "inactive"}`);
619625
if (status.json.codexRuntime.catalogClamp.removedEfforts.length > 0) {
620626
console.log(` Removed efforts: ${status.json.codexRuntime.catalogClamp.removedEfforts.join(", ")}`);
@@ -688,7 +694,8 @@ switch (command) {
688694
process.exit(1);
689695
}
690696
await syncModelsToCodex(live.port);
691-
console.log("Plain `codex` now routes through opencodex again (undo with: ocx restore).");
697+
const target = collectOrcaCodexHomeDiagnostic();
698+
console.log(`Plain \`codex\` now routes through opencodex in ${target.effectiveCodexHome} (undo with: ocx restore).`);
692699
break;
693700
}
694701
const r = restoreNativeCodex();

‎src/cli/status.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import { getCodexRoutingKind } from "../codex/inject";
99
import { diagnoseCodexShim } from "../codex/shim";
1010
import { displayCodexRuntimePath, effortClampAppliesToRuntime, loadLastEffortClamp, resolveCodexRuntime } from "../codex/runtime";
1111
import { redactSecretString, redactUserPath } from "../lib/redact";
12+
import { collectOrcaCodexHomeDiagnostic, type OrcaCodexHomeDiagnostic } from "../codex/home";
1213

1314
type HealthCheck = {
1415
ok: boolean;
@@ -65,6 +66,7 @@ export type CliStatusJson = {
6566
runtimeVersion: string | null;
6667
};
6768
};
69+
codexHome: OrcaCodexHomeDiagnostic;
6870
};
6971

7072
export type CliStatusView = {
@@ -163,6 +165,7 @@ export async function collectStatus(): Promise<CliStatusView> {
163165
})();
164166
const lastClamp = loadLastEffortClamp();
165167
const clampActive = effortClampAppliesToRuntime(lastClamp, resolvedRuntime.runtime);
168+
const codexHome = collectOrcaCodexHomeDiagnostic();
166169
const warningParts: string[] = [];
167170
if (
168171
resolvedRuntime.replacedConfigured
@@ -256,6 +259,7 @@ export async function collectStatus(): Promise<CliStatusView> {
256259
codexShim: { summary: codexShimSummary },
257260
codexPlugins,
258261
codexRuntime,
262+
codexHome,
259263
},
260264
};
261265
}

‎src/codex/home.ts‎

Lines changed: 57 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { existsSync, readFileSync, readdirSync, realpathSync, statSync } from "node:fs";
22
import { homedir } from "node:os";
3-
import { join, posix, resolve } from "node:path";
3+
import { join, posix, resolve, win32 } from "node:path";
44
import { expandUserPath } from "../config";
55

66
export type CodexHomeDeps = {
@@ -144,3 +144,59 @@ export function resolveCodexHomeDir(deps: CodexHomeDeps = {}): string {
144144
if (raw) return resolve(expandUserPath(raw));
145145
return defaultCodexHome(deps);
146146
}
147+
148+
export type OrcaCodexHomeDiagnostic = {
149+
applicable: boolean;
150+
mismatch: boolean;
151+
effectiveCodexHome: string;
152+
appCodexHome: string;
153+
orcaCodexHome: string | null;
154+
warning: string | null;
155+
action: string | null;
156+
};
157+
158+
type OrcaCodexHomeDeps = CodexHomeDeps & {
159+
effectiveCodexHome?: string;
160+
appCodexHome?: string;
161+
};
162+
163+
function normalizedWindowsPath(path: string): string {
164+
return path.trim().replaceAll("/", "\\").replace(/\\+$/, "").toLowerCase();
165+
}
166+
167+
/**
168+
* High-confidence Orca/ChatGPT dual-home diagnosis. Explicit CODEX_HOME remains
169+
* authoritative; this only explains when an Orca-owned shell targets a home the
170+
* Windows ChatGPT/Codex app does not read.
171+
*/
172+
export function collectOrcaCodexHomeDiagnostic(deps: OrcaCodexHomeDeps = {}): OrcaCodexHomeDiagnostic {
173+
const platform = deps.platform ?? process.platform;
174+
const env = deps.env ?? process.env;
175+
const effectiveCodexHome = deps.effectiveCodexHome ?? resolveCodexHomeDir(deps);
176+
const appCodexHome = deps.appCodexHome
177+
?? (platform === "win32" ? win32.join((deps.homedir ?? homedir)(), ".codex") : join((deps.homedir ?? homedir)(), ".codex"));
178+
const explicitHome = env.CODEX_HOME?.trim() ?? "";
179+
const orcaCodexHome = env.ORCA_CODEX_HOME?.trim() || null;
180+
const normalizedEffective = normalizedWindowsPath(effectiveCodexHome);
181+
const normalizedOrca = orcaCodexHome ? normalizedWindowsPath(orcaCodexHome) : "";
182+
const normalizedApp = normalizedWindowsPath(appCodexHome);
183+
const applicable = platform === "win32"
184+
&& !!explicitHome
185+
&& !!orcaCodexHome
186+
&& normalizedEffective === normalizedOrca
187+
&& /(?:^|\\)orca\\codex-runtime-home\\home$/i.test(normalizedOrca);
188+
const mismatch = applicable && normalizedEffective !== normalizedApp;
189+
return {
190+
applicable,
191+
mismatch,
192+
effectiveCodexHome,
193+
appCodexHome,
194+
orcaCodexHome,
195+
warning: mismatch
196+
? `CODEX_HOME targets Orca's runtime home (${effectiveCodexHome}), while the Windows ChatGPT/Codex app uses ${appCodexHome}; OpenCodex injection will not reach that app.`
197+
: null,
198+
action: mismatch
199+
? `Run ocx for the app with CODEX_HOME=${appCodexHome} and ORCA_CODEX_HOME unset.`
200+
: null,
201+
};
202+
}

‎src/codex/sync.ts‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import { printProjectCodexConfigWarnings, groupProjectCodexConfigWarningsByPath,
33
import { refreshCodexModelCatalog } from "./refresh";
44
import { applyProxyEnv, loadConfig } from "../config";
55
import type { OcxConfig } from "../types";
6+
import { collectOrcaCodexHomeDiagnostic } from "./home";
67

78
export interface CodexSyncResult {
89
ok: boolean;
@@ -27,6 +28,16 @@ const defaultDeps: CodexSyncDeps = {
2728
injectCodexConfig,
2829
};
2930

31+
function reportCodexHomeTarget(log: Pick<Console, "log" | "error"> | null): void {
32+
if (!log) return;
33+
const target = collectOrcaCodexHomeDiagnostic();
34+
log.log(` Target Codex home: ${target.effectiveCodexHome}`);
35+
if (target.warning) {
36+
log.error(`WARNING: ${target.warning}`);
37+
log.error(`Action: ${target.action}`);
38+
}
39+
}
40+
3041
export async function syncModelsToCodex(
3142
port?: number,
3243
config: OcxConfig = loadConfig(),
@@ -38,6 +49,7 @@ export async function syncModelsToCodex(
3849
if (externalProvider) {
3950
const result = await deps.injectCodexConfig(p, config, {});
4051
log?.log(result.message);
52+
reportCodexHomeTarget(log);
4153
return {
4254
ok: result.success,
4355
added: 0,
@@ -76,6 +88,7 @@ export async function syncModelsToCodex(
7688

7789
const result = await deps.injectCodexConfig(p, config, { catalogPath: catalogPathForInjection });
7890
log?.log(result.message);
91+
reportCodexHomeTarget(log);
7992
const projectConfigWarnings = printProjectCodexConfigWarnings(log, { cwd: process.cwd() });
8093
return {
8194
ok: result.success,

‎structure/02_config-and-codex-home.md‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,21 @@ $CODEX_HOME/models_cache.json
1515
Never assume macOS-only paths. Windows, service installs, and app-launched Codex can all depend on
1616
the resolved `CODEX_HOME`.
1717

18+
OpenCodex never overrides an explicit `CODEX_HOME`. On Windows, `ocx doctor` and `ocx status`
19+
nevertheless diagnose the high-confidence Orca dual-home case: both `CODEX_HOME` and
20+
`ORCA_CODEX_HOME` select Orca's `orca/codex-runtime-home/home`, while the ChatGPT/Codex app uses the
21+
default `%USERPROFILE%\\.codex`. Sync and restore output always prints the exact target Codex home;
22+
the diagnostic tells users to invoke OpenCodex with the app home explicitly rather than silently
23+
claiming that an unrelated app was configured.
24+
25+
[Decision Log]
26+
- 목적과 의도: Make multi-home injection truthful without taking ownership of user environment variables.
27+
- 기존 구현 및 제약 조건: CODEX_HOME is an intentional override, but Orca exports it for its own bundled runtime and the Windows app reads a different home.
28+
- 검토한 주요 대안: Rewrite CODEX_HOME automatically, warn for every custom home, or detect only the Orca-owned signature and report the target path.
29+
- 선택한 방식: Preserve the override, add a narrow Windows/Orca diagnostic, and qualify sync/restore success output with the effective home.
30+
- 다른 대안 대신 이 방식을 선택한 이유: It fixes the silent failure while avoiding destructive or noisy behavior for intentional custom homes.
31+
- 장점, 단점 및 영향: Orca users get an actionable warning; other multi-home products remain unchanged until they have an equally reliable signature.
32+
1833
`atomicWriteFile` uses a temp file named `{path}.ocx.{pid}.{seq}.tmp` (process ID + incrementing
1934
sequence number) to avoid collisions when concurrent writers (e.g. `ocx stop` and the proxy's own
2035
shutdown handler) both restore Codex config simultaneously. The temp is renamed atomically into place.

‎tests/cli-restore-back.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ describe("ocx restore back", () => {
1515
expect(restoreCase).toContain("await findLiveProxy()");
1616
expect(restoreCase).toContain("await syncModelsToCodex(live.port)");
1717
expect(restoreCase.indexOf("findLiveProxy()")).toBeLessThan(restoreCase.indexOf("syncModelsToCodex(live.port)"));
18+
expect(restoreCase).toContain("target.effectiveCodexHome");
1819
// The forward switch (plain `ocx restore`) is unchanged.
1920
expect(restoreCase).toContain("restoreNativeCodex()");
2021
});

‎tests/cli-status-json.test.ts‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,13 @@ describe("CLI status JSON", () => {
7676
newerAvailable?: unknown;
7777
catalogClamp?: { active?: unknown; removedEfforts?: unknown; runtimeVersion?: unknown };
7878
};
79+
codexHome?: {
80+
effectiveCodexHome?: unknown;
81+
appCodexHome?: unknown;
82+
mismatch?: unknown;
83+
warning?: unknown;
84+
action?: unknown;
85+
};
7986
};
8087

8188
expect(parsed.schemaVersion).toBe(1);
@@ -117,6 +124,10 @@ describe("CLI status JSON", () => {
117124
expect(parsed.codexRuntime?.catalogClamp?.active).toBe(false);
118125
expect(Array.isArray(parsed.codexRuntime?.catalogClamp?.removedEfforts)).toBe(true);
119126
expect(parsed.codexRuntime?.catalogClamp?.runtimeVersion).toBeNull();
127+
expect(typeof parsed.codexHome?.effectiveCodexHome).toBe("string");
128+
expect(typeof parsed.codexHome?.appCodexHome).toBe("string");
129+
expect(typeof parsed.codexHome?.mismatch).toBe("boolean");
130+
expect(parsed.codexHome?.warning === null || typeof parsed.codexHome?.warning === "string").toBe(true);
120131

121132
const serialized = JSON.stringify(parsed).toLowerCase();
122133
for (const forbidden of ["apikey", "sk-test-secret", "token", "refreshtoken", "authorization", "email"]) {

‎tests/doctor.test.ts‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ import {
1717
resolveCodexHomeDir,
1818
type ServiceMemoryData,
1919
} from "../src/cli/doctor";
20+
import { collectOrcaCodexHomeDiagnostic } from "../src/codex/home";
2021

2122
const TEST_DIR = join(import.meta.dir, ".tmp-doctor-test");
2223
const TEST_CODEX_HOME = join(TEST_DIR, "codex");
@@ -77,6 +78,36 @@ describe("doctor", () => {
7778
expect(resolveCodexHomeDir()).toBe(join(homedir(), "custom-codex"));
7879
});
7980

81+
test("Orca home diagnostic warns only for the Windows Orca runtime mismatch", () => {
82+
const appHome = "C:\\Users\\alice\\.codex";
83+
const orcaHome = "C:\\Users\\alice\\AppData\\Roaming\\orca\\codex-runtime-home\\home";
84+
const mismatch = collectOrcaCodexHomeDiagnostic({
85+
platform: "win32",
86+
env: { CODEX_HOME: orcaHome, ORCA_CODEX_HOME: orcaHome },
87+
effectiveCodexHome: orcaHome,
88+
appCodexHome: appHome,
89+
});
90+
expect(mismatch.mismatch).toBe(true);
91+
expect(mismatch.warning).toContain("OpenCodex injection will not reach that app");
92+
expect(mismatch.action).toContain(appHome);
93+
94+
const matching = collectOrcaCodexHomeDiagnostic({
95+
platform: "win32",
96+
env: { CODEX_HOME: appHome, ORCA_CODEX_HOME: orcaHome },
97+
effectiveCodexHome: appHome,
98+
appCodexHome: appHome,
99+
});
100+
expect(matching.mismatch).toBe(false);
101+
102+
const intentionalCustom = collectOrcaCodexHomeDiagnostic({
103+
platform: "win32",
104+
env: { CODEX_HOME: "D:\\codex-work" },
105+
effectiveCodexHome: "D:\\codex-work",
106+
appCodexHome: appHome,
107+
});
108+
expect(intentionalCustom.mismatch).toBe(false);
109+
});
110+
80111
test("resolveCodexHomeDir discovers a single Windows Codex Desktop home from WSL", () => {
81112
delete process.env.CODEX_HOME;
82113
const wslHome = join(TEST_DIR, "wsl-home");

0 commit comments

Comments
 (0)