Skip to content

Commit b394b03

Browse files
committed
fix(claude): remove a CRLF hook block instead of reporting a false success
Two defects CodeRabbit found on #2144. uninstallShellHook matched the owned block with LF-only newlines. A .zshrc with CRLF endings -- ordinary on a home directory an editor or another OS has touched -- did not match, so the file was rewritten unchanged while the caller was told the hook was removed. The hook kept sourcing on every new interactive shell and the reported state said it did not. The pattern now accepts CR?LF and verifies the marker is gone before claiming removal; a block shaped differently is reported failed. Both cli/index.ts call sites discarded the result, so state: "failed" -- the one outcome the user has to act on -- was never surfaced. They now print the reason and where to look.
1 parent a0635ea commit b394b03

3 files changed

Lines changed: 66 additions & 4 deletions

File tree

‎src/cli/index.ts‎

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,18 @@ import { maybeShowUpdatePrompt } from "../update/notify";
5656
import { syncModelsToCodex } from "../codex/sync";
5757
import { setIntegrationEnabled, shouldSyncCodexOnStart, shouldSyncGrokOnStart, syncCodexOnStartIfEnabled } from "../codex/desired-state";
5858

59+
/**
60+
* A failed shell-hook reconcile is not cosmetic: a stale hook keeps sourcing
61+
* `claude-env.sh` from every new interactive shell, pointing at a proxy or a CLI that may no
62+
* longer exist. `reconcileShellHook` already reports `state: "failed"`, but both call sites
63+
* discarded it, so the one outcome the user has to act on was the one they never saw.
64+
*/
65+
function reportShellHookFailure(result: { state: "installed" | "absent" | "failed"; reason?: string }): void {
66+
if (result.state !== "failed") return;
67+
console.warn(` Claude shell hook not reconciled${result.reason ? `: ${result.reason}` : ""}`);
68+
console.warn(" Check ~/.zshrc for the '# opencodex claude-env hook' block.");
69+
}
70+
5971

6072
import { removeOwnedConfigState } from "../lib/config-ownership";
6173
import { withProcessRuntimeProvenance } from "../lib/bun-runtime";
@@ -368,7 +380,7 @@ async function handleStart(options: { block?: boolean } = {}) {
368380
const systemEnv = await injectSystemEnv(port, config).catch(() => ({ injected: false }));
369381
// The hook is useful only for an installed Claude Code CLI. Reconcile instead of
370382
// appending unconditionally so stale OpenCodex-owned hooks are removed as well.
371-
reconcileShellHook(systemEnv.injected);
383+
reportShellHookFailure(reconcileShellHook(systemEnv.injected));
372384

373385
await maybeShowStarPrompt(); // once-only Yes/No GitHub-star prompt on first interactive start
374386
// Post-startup sync drives the readiness gate AND the #1046 stale app-server
@@ -456,7 +468,7 @@ async function handleEnsure(options: { existingIsSuccess?: boolean } = {}): Prom
456468
if (synced?.status === "skipped") console.log(" Codex integration OFF; startup left Codex native.");
457469
// Ensure env file exists for already-running proxy (may have been deleted or pre-dates this feature).
458470
const systemEnv = await injectSystemEnv(live.port, config).catch(() => ({ injected: false }));
459-
reconcileShellHook(systemEnv.injected);
471+
reportShellHookFailure(reconcileShellHook(systemEnv.injected));
460472
// Refresh the Grok Build fence too (same contract as start). live.hostname is the
461473
// hostname the running proxy actually bound — config.hostname may have drifted.
462474
try {

‎src/server/system-env.ts‎

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -118,8 +118,16 @@ export function uninstallShellHook(): { removed: boolean; reason?: string } {
118118
try {
119119
const content = readFileSync(zshrcPath, "utf8");
120120
if (!content.includes(SHELL_HOOK_MARKER)) return { removed: false, reason: "not installed" };
121-
// Remove the hook block (marker line + source line + surrounding newlines)
122-
const cleaned = content.replace(/\n?# opencodex claude-env hook\n\[.*claude-env\.sh.*\n?/g, "\n");
121+
// Match CR?LF, not LF alone. A .zshrc with CRLF line endings — ordinary on a home
122+
// directory an editor or another OS has touched — did not match, so the file was
123+
// rewritten unchanged and the caller was told the hook was removed. Reporting success
124+
// while the hook still sources on every new shell is the worse of the two failures.
125+
const cleaned = content.replace(/\r?\n?# opencodex claude-env hook\r?\n\[.*claude-env\.sh.*(?:\r?\n)?/g, "\n");
126+
// Verify instead of assuming: if the marker survives, the block is shaped in a way this
127+
// pattern does not own, and the honest answer is failure rather than a silent no-op.
128+
if (cleaned.includes(SHELL_HOOK_MARKER)) {
129+
return { removed: false, reason: "hook block present but not in the expected shape; remove it manually" };
130+
}
123131
writeFileSync(zshrcPath, cleaned, { encoding: "utf8", mode: 0o644 });
124132
return { removed: true };
125133
} catch (error) {

‎tests/claude-shell-hook.test.ts‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,48 @@ describe("Claude Code shell-hook reconciliation", () => {
103103
expect(readFileSync(zshrcPath, "utf8")).not.toContain("opencodex claude-env hook");
104104
});
105105

106+
// A .zshrc with CRLF endings is ordinary on a home directory an editor or another OS has
107+
// touched. The removal pattern matched LF only, so the file was rewritten unchanged while
108+
// the caller was told the hook was gone — the worse outcome, because the hook keeps
109+
// sourcing on every new shell and the reported state says it does not.
110+
test("removes a CRLF-terminated hook block instead of reporting a false success", () => {
111+
installClaudeCli();
112+
reconcileShellHook(true);
113+
const installed = readFileSync(zshrcPath, "utf8");
114+
writeFileSync(zshrcPath, installed.replace(/\n/g, "\r\n"), "utf8");
115+
116+
const result = reconcileShellHook(false);
117+
118+
expect(readFileSync(zshrcPath, "utf8")).not.toContain("opencodex claude-env hook");
119+
expect(result.state).toBe("absent");
120+
});
121+
122+
test("unrelated CRLF lines survive the removal", () => {
123+
installClaudeCli();
124+
writeFileSync(zshrcPath, "export FOO=1\n", "utf8");
125+
reconcileShellHook(true);
126+
const installed = readFileSync(zshrcPath, "utf8");
127+
writeFileSync(zshrcPath, installed.replace(/\n/g, "\r\n"), "utf8");
128+
129+
reconcileShellHook(false);
130+
const after = readFileSync(zshrcPath, "utf8");
131+
132+
expect(after).toContain("export FOO=1");
133+
expect(after).not.toContain("claude-env.sh");
134+
});
135+
136+
test("a marker block this pattern does not own is reported failed, not removed", () => {
137+
installClaudeCli();
138+
// The marker is there but the next line is not the block we wrote, so it is not ours to
139+
// delete. Answering "removed" here would be a claim the user acts on and it would be false.
140+
writeFileSync(zshrcPath, "# opencodex claude-env hook\n# hand-edited by the user\n", "utf8");
141+
142+
const result = reconcileShellHook(false);
143+
144+
expect(result.state).toBe("failed");
145+
expect(readFileSync(zshrcPath, "utf8")).toContain("hand-edited by the user");
146+
});
147+
106148
test("ignores empty PATH segments instead of trusting a workspace-local claude file", () => {
107149
writeFileSync(join(root, "claude"), "#!/bin/sh\nexit 0\n", { mode: 0o755 });
108150
const previousCwd = process.cwd();

0 commit comments

Comments
 (0)