codex-plugin-cc icon indicating copy to clipboard operation
codex-plugin-cc copied to clipboard

session-lifecycle-hook: SessionStart appends env exports without dedup - env file grows unboundedly on resume/compact, breaking Bash on Windows (8191-char limit)

Open tfukahori opened this issue 4 months ago • 15 comments

Summary

scripts/session-lifecycle-hook.mjs appends its three export lines to CLAUDE_ENV_FILE on every SessionStart event without checking whether they are already present. Claude Code re-fires SessionStart on every session resume and compaction, so in a long-running session the env file grows without bound.

Because Claude Code prepends the entire env file to every Bash tool invocation, the accumulated duplicates eventually push the composed bash -c string past the Windows 8191-character command-line limit. The command gets truncated mid-token, and every Bash call longer than a few hundred bytes fails with:

/usr/bin/bash: -c: line 70: unexpected EOF while looking for matching `''

The failures look random (long gh pr create commands, heredocs, etc. fail; short commands succeed), which makes this very hard to diagnose from the outside.

Observed impact (real session, plugin v1.0.6, Windows 11)

  • ~/.claude/session-env/<session-id>/sessionstart-hook-1.sh contained the same 3 export lines duplicated 23× (~7.4 KB) after a long session with many compactions/resumes.
  • Measured via echo ${#BASH_EXECUTION_STRING}: a 103-character command produced an 8042-character bash -c string (lines 1–69 of it were the duplicated exports).
  • Remaining budget for the actual command was ~250 characters; anything longer was truncated at the 8191-char boundary → shell syntax error.
  • Bisected empirically: an all-ASCII true "AAA…" probe passed at ~360 total bytes and failed at ~400, consistent with the 8191 limit given the ~7.9 KB prefix.

Root cause

appendEnvVar() in scripts/session-lifecycle-hook.mjs:

function appendEnvVar(name, value) {
  if (!process.env.CLAUDE_ENV_FILE || value == null || value === "") {
    return;
  }
  fs.appendFileSync(process.env.CLAUDE_ENV_FILE, `export ${name}=${shellEscape(value)}\n`, "utf8");
}

handleSessionStart() calls this for CODEX_COMPANION_SESSION_ID, CODEX_COMPANION_TRANSCRIPT_PATH, and CLAUDE_PLUGIN_DATA on each SessionStart — including source: "resume" / "compact" re-fires — with no dedup.

Suggested fix (verified locally)

Make the append idempotent:

function appendEnvVar(name, value) {
  if (!process.env.CLAUDE_ENV_FILE || value == null || value === "") {
    return;
  }
  const line = `export ${name}=${shellEscape(value)}\n`;
  try {
    if (fs.readFileSync(process.env.CLAUDE_ENV_FILE, "utf8").includes(line)) {
      return;
    }
  } catch {
    // file may not exist yet; fall through to append
  }
  fs.appendFileSync(process.env.CLAUDE_ENV_FILE, line, "utf8");
}

Verified by invoking the hook three times with the same SessionStart payload against a scratch CLAUDE_ENV_FILE: the file stays at exactly 3 lines (unpatched: 9).

An alternative would be to rewrite the file wholesale on each SessionStart (the three values are session-scoped constants), which also self-heals files already bloated by previous plugin versions.

Environment

  • Plugin: codex@openai-codex 1.0.6 (marketplace refreshed; 1.0.6 is current latest)
  • Claude Code on Windows 11 (Git Bash as the Bash tool shell — the 8191-char limit is what turns the unbounded growth into hard failures, but the growth itself is platform-independent)

tfukahori avatar Jul 18 '26 18:07 tfukahori

Same problem same fix.

ghbaud avatar Jul 23 '26 21:07 ghbaud

Hi, I'm going to work on this issue.

I'll implement a focused append-only deduplication fix that preserves unrelated environment-file content, and add regression coverage for repeated SessionStart invocations.

Please let me know if you'd prefer the wholesale rewrite approach instead.

dinhnguyenminhhoang avatar Jul 26 '26 07:07 dinhnguyenminhhoang

Independent confirmation from a separate investigation, plus a methodological note that might be useful for whoever's finishing the fix.

Reproduced the identical defect in appendEnvVar/handleSessionStart, plugin v1.0.6, Windows 11 + Git Bash — confirmed by direct source read, byte-identical in both the stock openai-codex package and a locally-modified fork, so this isn't fork-specific. Observed 30x repetition (88-line composed wrapper) in one session and 74x repetition (223-line wrapper) in a second, longer-running session on the same machine — consistent with "keeps accumulating across every resume/compaction, never resets, no upper bound."

On the 8191-character boundary, one data point that might be useful, framed honestly: I tried to corroborate it independently by capturing several of my own composed -c wrapper strings live and replaying the isolated text directly through bash.exe. My captures ranged 8161-8521 characters, straddling your reported boundary, but the replay outcomes didn't cleanly track it — the under-8191 capture failed (cascading errors, not an EOF), while several over-8191 captures ran to completion without error. So on my own machine/session, offline replay of an isolated capture doesn't reproduce your exact failure mode either above or below the line — which lines up with a separate, still-open finding in my own investigation: a captured wrapper string, even when it's the actual live text pulled via process-table inspection during a real failure, doesn't reproduce the live EOF signature when replayed outside the harness. Not disputing your bisection — it's a clean result on your system and the general "longer accumulated prefix -> more failures" pattern holds clearly on mine too (a 74x/~20,700-character session failed on effectively every Bash-tool call, including ones with zero quote characters) — just flagging that whatever the exact truncation/corruption mechanism is, it may not be reliably reproducible via simple offline replay of a captured string, which could matter if anyone's using that as a verification method for the fix.

One related-but-distinct defect worth flagging, independent of the accumulation bug: when the user's Bash-tool command contains a literal ", I captured a case where it gets backslash-escaped when embedded in the wrapper's eval '...', which doesn't delimit correctly inside single quotes and corrupts the embedded command's own quoting. Couldn't find this transform anywhere in this plugin's editable source (checked session-lifecycle-hook.mjs, args.mjs, app-server.mjs, claude-session-transfer.mjs, codex-companion.mjs) — looks like it lives in Claude Code's own core rather than here, so I've written that part up separately on anthropics/claude-code#81732 along with the findings above, in case it's useful to cross-link.

Small thing worth a mention for whoever ships the fix: #322 reported and closed this exact bug back in May ("COMPLETED"), and it's clearly back in 1.0.6 — might be worth a regression test alongside the dedup fix this time.

Thanks for having a fix already in progress on this — genuinely nasty one to trace from the outside.

Yogitmeister avatar Aug 05 '26 17:08 Yogitmeister

Update on the "related-but-distinct defect" from my last comment (the " -> \" escaping mismatch) -- walking back "independent of the accumulation bug" specifically, since that's now genuinely in question.

A fresh session with none of the accumulated-export bloat ran the same quote-containing command shapes that triggered the mismatch before -- all ran clean, no failure. The escaping transform itself is still a real, directly-observed mechanism (captured live, replayed to show the concrete effect), but every time I'd previously seen it produce a failure, the session was also carrying this issue's accumulation bloat. So it's now unclear whether the escaping mismatch is independently sufficient to cause a failure, or whether the accumulation was doing the actual work and the mismatch was a real-but-non-fatal quirk riding along on the same bloated wrapper.

Practical implication for the fix in progress: once the dedup fix lands, it's probably worth checking whether quote-containing commands still need anything else, rather than assuming they do. Didn't want this sitting as a confirmed-independent claim if it isn't one.

Yogitmeister avatar Aug 05 '26 18:08 Yogitmeister

I ran into this on Linux as well — it is not Windows-specific. Here it doesn't truncate anything, it stops Claude Code from starting a shell at all:

 Error: Could not start /bin/bash: the command line plus environment exceed the OS exec argument limit (E2BIG).
 At spawn: command line 133.3KB across 3 args (largest single arg 133.3KB); environment 4.5KB across 81 vars
 (largest: LS_COLORS at 1.4KB)

strace showed what was being passed:

3959524 execve("/bin/bash", ["/bin/bash", "-c", "source /home/luke/.claude/shell-snapshots/snapshot-bash-1786999219649-uxu0jx.sh 2>/dev/null || true && export CODEX_COMPANION_SESSION_ID='<UUID elided>'\nexport CODEX_COMPANION_TRANSCRIPT_PATH='/home/luke/.claude/projects/<project elided>/<UUID elided>.jsonl'\nexport CLAUDE_PLUGIN_DATA='/home/luke/.claude/plugins/data/codex-openai-codex'\nexport CODEX_COMPANION_SESSION_ID='<UUID elided>'\nexport CODEX_COMPANION_TRANSCRIPT_PATH='/home/luke/.claude/projects/<project elided>/<UUID elided>.jsonl'\nexport CLAUDE_PLUGIN_DATA='/home/luke/.claude/plugins/data/codex-openai-codex'\nexport CODEX_COMPANION_SESSION_ID='<UUID elided>'\n

... repeated many hundreds of times ...

\nexport CLAUDE_PLUGIN_DATA='/home/luke/.claude/plugins/data/codex-openai-codex'\n: && shopt -u extglob 2>/dev/null || true && { \\builtin unalias -- 'unsetenv'; \\builtin unset -f -- 'unsetenv'; } >/dev/null 2>&1 || true && eval 'echo hello world' < /dev/null && pwd -P >| /tmp/claude-16f6-cwd"], 0x2ee91d90f00 /* 80 vars */) = -1 E2BIG (Argument list too long)

That comes from appendEnvVar in session-lifecycle-hook.mjs (observed on v1.0.5; the code is byte-identical on main at v1.0.6):

function appendEnvVar(name, value) {
  if (!process.env.CLAUDE_ENV_FILE || value == null || value === "") return;
  fs.appendFileSync(process.env.CLAUDE_ENV_FILE, `export ${name}=${shellEscape(value)}\n`, "utf8");
}

handleSessionStart calls it three times; SessionStart fires on startup, on resume and on every compaction; nothing ever prunes. Only the last assignment of a name has any effect, so every earlier copy is pure dead weight.

Claude's assessment and fix:


Why it kills the shell outright on Linux

CLAUDE_ENV_FILE is ~/.claude/session-env/<session-id>/sessionstart-hook-0.sh — one file per session — and Claude Code inlines the whole file into the single bash -c <script> argument. Linux caps a single argv element at MAX_ARG_STRLEN = 32 pages = 131072 bytes. That is a separate limit from ARG_MAX and ulimit -s doesn't move it. My file had reached 136770 bytes, so execve failed and every Bash tool call failed — the length of the actual command was irrelevant, echo hello world failed just as hard as a long one.

So the Windows 8191-character report and this are the same defect hitting two different downstream limits.

Two things that made this hard to diagnose

  1. Claude can't introspect the argument injected into its own Bash tool, and once that tool is dead there's no shell left to debug with. A PreToolUse hook still runs — separate bash <script> spawn, without the oversized argument — which is what eventually broke the deadlock.
  2. The plugin executes out of ~/.claude/plugins/cache/<marketplace>/<plugin>/<version>/scripts/, not the marketplace checkout. Patching the marketplace copy does nothing at all. Worth knowing for anyone hotfixing locally before a release lands.

The patch Claude applied

--- a/plugins/codex/scripts/session-lifecycle-hook.mjs
+++ b/plugins/codex/scripts/session-lifecycle-hook.mjs
@@ -32,11 +32,48 @@
   return `'${String(value).replace(/'/g, `'\"'\"'`)}'`;
 }
 
-function appendEnvVar(name, value) {
-  if (!process.env.CLAUDE_ENV_FILE || value == null || value === "") {
+const MANAGED_ENV_VARS = [SESSION_ID_ENV, TRANSCRIPT_PATH_ENV, PLUGIN_DATA_ENV];
+
+function isManagedExport(line) {
+  return MANAGED_ENV_VARS.some((name) => line.startsWith(`export ${name}=`));
+}
+
+function writeManagedEnvVars(entries) {
+  const envFile = process.env.CLAUDE_ENV_FILE;
+  if (!envFile) {
     return;
   }
-  fs.appendFileSync(process.env.CLAUDE_ENV_FILE, `export ${name}=${shellEscape(value)}\n`, "utf8");
+
+  let existing = "";
+  try {
+    existing = fs.readFileSync(envFile, "utf8");
+  } catch (error) {
+    if (error?.code !== "ENOENT") {
+      throw error;
+    }
+  }
+
+  // Keep every line another plugin wrote, verbatim; drop only our own.
+  const lines = existing.split(/\r?\n/).filter((line) => line !== "" && !isManagedExport(line));
+
+  for (const [name, value] of entries) {
+    if (value != null && value !== "") {
+      lines.push(`export ${name}=${shellEscape(value)}`);
+    }
+  }
+
+  // Write and rename so a concurrent reader sees the old file or the new one,
+  // never a half-written one.
+  const tmpFile = `${envFile}.${process.pid}.tmp`;
+  fs.writeFileSync(tmpFile, lines.length > 0 ? `${lines.join("\n")}\n` : "", "utf8");
+  fs.renameSync(tmpFile, envFile);
 }
 
 function cleanupSessionJobs(cwd, sessionId) {
@@ -75,9 +112,11 @@
 }
 
 function handleSessionStart(input) {
-  appendEnvVar(SESSION_ID_ENV, input.session_id);
-  appendEnvVar(TRANSCRIPT_PATH_ENV, input.transcript_path);
-  appendEnvVar(PLUGIN_DATA_ENV, process.env[PLUGIN_DATA_ENV]);
+  writeManagedEnvVars([
+    [SESSION_ID_ENV, input.session_id],
+    [TRANSCRIPT_PATH_ENV, input.transcript_path],
+    [PLUGIN_DATA_ENV, process.env[PLUGIN_DATA_ENV]]
+  ]);
 }
 
 async function handleSessionEnd(input) {

Rewrite rather than append: drop this plugin's own export lines, keep every other line verbatim, append the current values, then write-and-rename so a concurrent reader sees either the old file or the new one and never a half-written one.

Measurements

Harness: seed the env file with one unrelated co-tenant line (export OTHER_PLUGIN_VALUE='keep-me'), then fire the real hook repeatedly with the same session_id — which is what actually happens, since the env file is keyed by session id in its own path, so the values never change within one file.

after N firings upstream 1.0.5 / 1.0.6 PR #558 patch above
0 (seed) 1 line / 36 B 1 / 36 1 / 36
1 4 / 302 4 / 302 4 / 302
2 7 / 568 4 / 302 4 / 302
3 10 / 834 4 / 302 4 / 302
4 13 / 1100 4 / 302 4 / 302
5 16 / 1366 4 / 302 4 / 302

Upstream grows by 3 lines / 266 bytes per firing without bound. Both fixes hold it flat, and the co-tenant line survives in both.

But that's the easy half. The case that matters is a file that is already bloated — which is the state every user who hits this issue is in. Same harness, file first grown to 151 lines / 13336 bytes by 50 upstream firings:

after N firings on an already-bloated file PR #558 patch above
1 151 lines / 13336 B 4 / 302
2 151 / 13336 4 / 302
3 151 / 13336 4 / 302

On the two open PRs

#558 and #386 do the same thing: scan backwards for the last export <name>= line, return early if it is byte-identical, otherwise append. Neither ever removes a line. Because the env file is per-session, the last assignment of each name in a bloated file is byte-identical to what the hook would write — so both PRs take the early return, and the file stays oversized forever. A user already over the limit stays broken until they delete the file by hand.

Whatever lands should prune this plugin's own lines at least once, not just stop adding new ones — that is what #657 does. And since #322 reported and closed this same bug in May, a regression test that fires SessionStart several times and asserts the line count doesn't move seems worth having.

One caveat on the patch above

It is a read-modify-write on a file other plugins may append to, so a sibling SessionStart hook appending between the read and the rename would lose that write. Upstream's append is atomic and has no such window. The exposure is small — the whole read-filter-write-rename is microseconds, once per session-start event — but it is real, and it's the reason both PRs stayed append-only.

If that window is unacceptable, the two can be combined: prune the plugin's own lines once, then write the values to a plugin-owned file and leave a single constant [ -f … ] && . … line in the shared file. Steady state then needs no write to the shared file at all, and a changed value is picked up by rewriting the owned file, which nobody else touches.

I've opened #657 with the patch above (plus a skip-the-write-when-nothing-changed check) and four regression tests, all of which fail on main.

lukehutch avatar Aug 17 '26 21:08 lukehutch

Another data point on v1.0.6 (Windows 11, Claude Code desktop, Git Bash 5.3.9), plus a user-side mitigation that does not require patching the plugin.

Observed: one long-lived session (resumed/compacted many times) reached 37 copies of the three export lines — 111 lines / 11,492 bytes in ~/.claude/session-env/<session-id>/sessionstart-hook-1.sh. Every Bash tool call, including echo ok, then failed with /usr/bin/bash: -c: line 78: unexpected EOF while looking for matching ''`. Bisecting the inlined script by line count reproduced the cutoff exactly at the 8,191-char boundary: the first 75 lines (7,734 chars) pass, 80 lines (8,279 chars) fail, and 8,191 chars falls inside line 80's single-quoted path. Note that Claude Code reads the env file once at session start, so trimming the file only takes effect after the session is reopened.

Mitigation without touching the plugin (survives plugin updates; also protects against any other hook with the same append-only behaviour): register a tiny SessionStart hook of your own in ~/.claude/settings.json that de-duplicates $CLAUDE_ENV_FILE in place, keeping first occurrence order. Whether it runs before or after this plugin's hook, the file stays bounded at "unique lines + at most one fresh set".

# dedupe_env_file_hook.py — SessionStart hook
import os, sys
p = os.environ.get("CLAUDE_ENV_FILE", "")
if p and os.path.isfile(p):
    seen, kept = set(), []
    for line in open(p, encoding="utf-8").read().splitlines():
        if line not in seen:
            seen.add(line); kept.append(line)
    open(p, "w", encoding="utf-8", newline="\n").write("\n".join(kept) + "\n")
sys.stdin.read(); sys.exit(0)
"SessionStart": [{ "hooks": [
  { "type": "command", "command": "python", "args": ["/path/to/dedupe_env_file_hook.py"], "timeout": 5 }
]}]

Any of #386 / #558 / #657 / #668 / #748 would fix the root cause; until one lands, the hook above keeps Bash alive.

ldk00315-jpg avatar Sep 18 '26 04:09 ldk00315-jpg

Still reproducible on 1.0.6 (db52e28, current main), Windows 11 + Git Bash, Claude Code desktop.

Measured on a long session with many compactions: session-env/<id>/sessionstart-hook-5.sh reached 201 lines / 22.7 KB (the same 3 exports repeated 67 times). Every Bash call then failed with bash: -c: line 71: unexpected EOF while looking for matching '''.

The threshold: spawnSync('C:/Program Files/Git/bin/bash.exe', ['-c', script]) gets the full script at 7,950 chars and an empty one at 8,294, which matches the ~8 KB Windows command-line limit. Each SessionStart appends ~336 bytes here (long Windows paths), so Bash breaks after about 24 compactions or resumes.

A local patch equivalent to #748 (drop the previous export NAME= line, then write) keeps the file at 3 lines across repeated runs. A test that runs the hook 5 times against a temp CLAUDE_ENV_FILE goes red on the current appendFileSync.

One note on #748: it writes ${envFile}.${pid}.tmp into the session-env directory. If the hook is killed by its 5 s timeout (#670) between write and rename, that leftover file sits next to the env files. Writing in place avoids it.

Duplicates of this issue: #661, #664, #778.

Gimmyhat avatar Sep 23 '26 05:09 Gimmyhat

One more data point, plus a caveat about the hook-based mitigation posted above.

Repro: plugin 1.0.6 (db52e28), Claude Code 2.1.280 (desktop app), Windows 11 + Git Bash. After 22 SessionStart events in one session (resumes and compactions), the codex env file held 22 copies of the three exports (66 lines, ~7.6 KB). Every Bash tool call, including those from subagents, then failed with bash: -c: line 69: unexpected EOF while looking for matching `''. Trimming the file on disk did not help until Claude Code was restarted.

Caveat on the mitigation: on 2.1.280, each SessionStart hook gets its own env file, named after the hook's position among the matching hooks (session-env/<session-id>/sessionstart-hook-<N>.sh). In our session, the codex hook wrote to sessionstart-hook-8.sh at startup and to sessionstart-hook-3.sh on resume and compaction. A hook that only de-duplicates its own $CLAUDE_ENV_FILE therefore never touches the codex plugin's file.

A variant that scans the directory avoids this. It only rewrites files made entirely of one-line export statements, so multi-line snippets written by other hooks are never altered:

// session-env-dedupe.mjs: SessionStart hook, registered without a matcher
import { readdirSync, readFileSync, writeFileSync } from 'node:fs';
import { dirname, join } from 'node:path';

const EXPORT_LINE = /^export [A-Za-z_][A-Za-z0-9_]*=/;

try {
  const envFile = process.env.CLAUDE_ENV_FILE;
  if (envFile) {
    const dir = dirname(envFile);
    for (const name of readdirSync(dir)) {
      if (!name.endsWith('.sh')) continue;
      const file = join(dir, name);
      try {
        const lines = readFileSync(file, 'utf8').split(/\r?\n/).filter(Boolean);
        // Only rewrite files made entirely of one-line exports (never touch if/fi etc.).
        if (!lines.every((line) => EXPORT_LINE.test(line))) continue;
        const kept = [...new Set([...lines].reverse())].reverse(); // keep the last copy of each line
        if (kept.length < lines.length) writeFileSync(file, `${kept.join('\n')}\n`);
      } catch {}
    }
  }
} catch {}
"SessionStart": [
  { "hooks": [{ "type": "command", "command": "node /path/to/session-env-dedupe.mjs", "timeout": 5 }] }
]

Against a copy of the bloated directory, it reduced the 66-line file to 3 lines and left the other files unchanged. A session that is already broken still needs a restart, since the fix only takes effect when the environment script is rebuilt.

Another duplicate since the list above: #783. All five fix PRs (#386, #558, #657, #668, #748) are still open and mergeable. Merging any one of them would resolve this issue and its duplicates.

Bishinken avatar Sep 26 '26 17:09 Bishinken

+1, still reproducible on 1.0.6 (main @ db52e28). On Windows this is session-fatal: Claude Code inlines the env file into every bash -c, Git Bash truncates -c at 8,186 chars, so after ~23 SessionStart events (start/resume/compact) every Bash call fails.

ilusiumgame avatar Oct 05 '26 10:10 ilusiumgame

Independent reproduction, plus a new data point on the 8192-boundary question.

Environment: plugin codex@openai-codex 1.0.6, Claude Code 2.1.296 CLI on Windows, Git Bash (both PortableGit and C:\Program Files\Git, msys-2.0.dll 3.6.6).

Observed: session-env file contained the same 3 exports duplicated 31x (93 lines / 8804 bytes). Once it crossed ~8 KB every Bash tool call died with -c: line N: unexpected EOF while looking for matching ''— including single-line commands containing zero quote characters (e.g.cd ... && git status --short | head -30`). The reported line number drifted (77 → 103 → 97 → 89 → 85 across calls) because it tracks wherever byte ~8192 lands in the growing file — the cut lands mid-quote. Other sessions on the same machine had env files at 22.7 KB / 8.2 KB / 7.1 KB.

Re: @Yogitmeister's replay caveat — on this machine offline replay did reproduce deterministically: bash -n <file> passes, while bash -c "<same bytes>" fails at exactly the line containing byte offset 8192 (that line spans chars 8155–8235 → reported "line 87"). node -e receives the same >9 KB argv intact, so the loss is inside the MSYS2 runtime's argv handling on 3.6.6, not CreateProcess. Machines where replay doesn't reproduce may just be running a different msys2-runtime — worth capturing the msys-2.0.dll version when bisecting.

Local mitigation: dedup inside appendEnvVar (same shape as #558) + rewrote bloated env files to unique lines; also patched the marketplace copy so plugin reinstalls here don't reintroduce it.

kkkano avatar Oct 12 '26 05:10 kkkano

Additional observations from the Claude desktop app on Windows 11 (Code tab, codex@openai-codex 1.0.6).

Several of my sessions had the same three exports repeated dozens of times. In my main desktop session, even echo ok failed:

/usr/bin/bash: -c: line 77: unexpected EOF while looking for matching `''

I also reproduced it with Claude Code CLI: I pre-seeded a fresh session's env file with repeated exports before starting it, and Bash failed with the same error. After deduplicating the file and resuming the session, Bash worked again.

lowbyyj avatar Oct 29 '26 02:10 lowbyyj

Still on main as of 2026-11-04 (plugin 1.0.6): appendEnvVar and handleSessionStart in plugins/codex/scripts/session-lifecycle-hook.mjs are unchanged, and running the hook three times against one CLAUDE_ENV_FILE gives 3, 6, then 9 lines. #322 asked for the same fix and was closed as completed, but the code still appends.

One more data point, from the Claude Code desktop app on Windows 11 with Git for Windows 2.55.0.windows.5 (MSYS 3.6.10). After 16 starts of one session, session-env/<id>/ held 64 lines and 7412 bytes: 3 lines per start from this plugin and 1 from another hook. That left room for 338 characters of quoted command. One more reopen and the cut fell before the command, so even echo ok failed.

For triage: #661, #664, #778, #783, #788, #810, #819, #824, #827 and #830 report the same growth. Open PRs that address it: #386, #558, #657, #668, #748. Merging one of them is the cheapest of the three fixes involved. The other two are on the Claude Code side (anthropics/claude-code#103861) and in the runtime (git-for-windows/git#6516).

One thing to check when choosing: the latest value has to win. A check like includes(line) skips a value that goes A, B, A and leaves B in force, so compare with the last assignment of that name, or rewrite the file.

germanelias13 avatar Nov 04 '26 16:11 germanelias13

Another reproduction on plugin 1.0.6, with Claude Code 2.1.318 on Windows 11 and Git Bash.

One long session that compacted and resumed many times left %USERPROFILE%\.claude\session-env\<session-id>\sessionstart-hook-1.sh holding the same three lines 27 times (81 lines, 7,695 bytes). A fresh session's file is about 285 bytes:

export CODEX_COMPANION_SESSION_ID='<session-id>'
export CODEX_COMPANION_TRANSCRIPT_PATH='<transcript path>'
export CLAUDE_PLUGIN_DATA='<plugin data path>'

Every Bash tool command, and the user's own ! commands, then failed with:

/usr/bin/bash: -c: line 82: unexpected EOF while looking for matching `''

The reported line number grew from 79 to 82 as the file grew. PowerShell tool calls were unaffected. That fits the bash -c command-line length explanation already in this issue, though I did not measure the composed string.

appendEnvVar in scripts/session-lifecycle-hook.mjs is unchanged in 1.0.6: it calls fs.appendFileSync(process.env.CLAUDE_ENV_FILE, ...) once per variable and never checks for an existing export NAME= line. Making it keep one line per variable name (or skip a line already present) would fix this.

Workaround: delete or trim the session's env file and restart the session.

jm-warren avatar Nov 05 '26 01:11 jm-warren

Another reproduction on 1.0.6, with two things I haven't seen in this thread yet: how common the bloat is across all sessions on one machine, and a failure mode where the command runs but is reported as failed.

Environment: codex@openai-codex 1.0.6, Claude Code 2.1.322, Windows 11, Git for Windows 2.55.0.windows.3 (MSYS runtime 3.6.9). The installed scripts/session-lifecycle-hook.mjs matches main at db52e28 (identical after normalising line endings), so appendEnvVar is still the plain appendFileSync.

How common it is

A read-only scan of every ~/.claude/session-env/<session-id>/sessionstart-hook-*.sh on one machine (2026-11-11):

Sessions / env files 266 / 277
Files with more than one copy of the three exports 78 (28%)
Files with 10 or more copies 22
Files with 20 or more copies 12
Largest file 68 copies, 204 lines, 19,854 bytes
Size of one copy about 290 bytes (278 to 399)
Sessions whose env files already exceed 8,186 bytes 6

So this is not one unusually long session. More than a quarter of the env files here have duplicates, and six sessions are past the point where any Bash command can run.

The command can run and still be reported as failed

Just under the limit, the cut does not land in the command. It lands in the pwd -P >| <temp dir>/<cwd file> that Claude Code appends after it. The command runs to completion, then bash prints:

/usr/bin/bash: line 79: <temp dir>/: Is a directory

and the tool call returns exit code 1. An agent that sees the failure may run the command again, which is a problem for anything that is not idempotent. unexpected EOF while looking for matching only appears once the cut reaches the command itself.

In the session where I measured this, 26 copies were loaded. Commands up to about 85 characters ran cleanly, a 102-character command ran but came back as failed with the message above, and from about 160 characters commands were not run at all.

Choosing among the open PRs

From reading the diffs:

  • #386 and #558 skip the append when the last assignment already has the same value. That stops the growth, but a file that is already bloated stays as it is.
  • #657, #668 and #748 remove the plugin's earlier lines and write one line per variable, so a bloated file shrinks back the next time SessionStart fires.

With 78 files already affected on a single machine, the second behaviour seems worth having. Otherwise the six sessions above stay broken until someone trims the files by hand.

Workaround in the meantime

I use a user-level SessionStart hook along the lines of the directory-scanning one posted above. I ran it against copies of all the real env files: every bloated file shrank (the largest from 19,854 to 564 bytes) and the final value of each variable was unchanged. As others have noted, a session that is already running may keep using the old contents, so reopening it is the reliable way to recover.

Chaogga0116 avatar Nov 11 '26 03:11 Chaogga0116