Claude Code. Any Model. The most powerful AI coding agent now speaks every language.
fix(session): read CLAUDE_CONFIG_DIR for the transcript projects dir
Jack Rudenko980964b840f3
diff --git a/packages/cli/src/session/session-discovery.test.ts b/packages/cli/src/session/session-discovery.test.tsindex 07980837..8d72f907 100644--- a/packages/cli/src/session/session-discovery.test.ts+++ b/packages/cli/src/session/session-discovery.test.ts@@ -7,8 +7,10 @@ import {ACTIVE_WINDOW_MS,type SessionRow,isActive,+ projectsDir,sessionLabel,slugForPath,+ transcriptPathFor,} from "./session-discovery.js";const fixtureHome = mkdtempSync(join(tmpdir(), "claudish-session-discovery-"));@@ -31,15 +33,19 @@ function sessionFixture(cwd: string, id: string, mtimeMs: number): void {utimesSync(file, new Date(mtimeMs), new Date(mtimeMs));}-function findLatestInFixture(cwd: string, sinceMs: number): string | null {+function findLatestInFixture(+ cwd: string,+ sinceMs: number,+ envOverride: Record<string, string> = { HOME: fixtureHome }+): string | null {const script = `import { findLatestSessionId } from "./src/session/session-discovery.ts";process.stdout.write(findLatestSessionId(${JSON.stringify(cwd)}, ${sinceMs}) ?? "");`;+ const env: Record<string, string | undefined> = { ...process.env, ...envOverride };+ // An outer CLAUDE_CONFIG_DIR would outrank the fixture HOME.+ if (!("CLAUDE_CONFIG_DIR" in envOverride)) delete env.CLAUDE_CONFIG_DIR;const result = Bun.spawnSync([process.execPath, "-e", script], {cwd: join(import.meta.dir, "../.."),- env: {- ...process.env,- HOME: fixtureHome,- },+ env,});expect(result.exitCode).toBe(0);const id = result.stdout.toString().trim();@@ -74,6 +80,26 @@ describe("session discovery pure helpers", () => {expect(slugForPath("/tmp/a b@c+d")).toBe("-tmp-a-b-c-d");});+ test("projectsDir reads CLAUDE_CONFIG_DIR from the environment it is given", () => {+ expect(projectsDir({ CLAUDE_CONFIG_DIR: "/cfg/claude", HOME: "/home/u" })).toBe(+ "/cfg/claude/projects"+ );+ });++ test("projectsDir falls back to $HOME/.claude when CLAUDE_CONFIG_DIR is unset or empty", () => {+ expect(projectsDir({ HOME: "/home/u" })).toBe("/home/u/.claude/projects");+ expect(projectsDir({ HOME: "/home/u", CLAUDE_CONFIG_DIR: "" })).toBe(+ "/home/u/.claude/projects"+ );+ });++ test("transcriptPathFor joins under the projects directory it is handed", () => {+ const root = projectsDir({ CLAUDE_CONFIG_DIR: "/cfg" });+ expect(transcriptPathFor("/no/such/dir_x", "u-1", root)).toBe(+ "/cfg/projects/-no-such-dir-x/u-1.jsonl"+ );+ });+test("slugForPath is the parent proof's projectDirNameFor, so the two cannot drift", () => {for (const p of ["/a/b_c.d", "/x y/@z", "/Users/x/.claude/worktrees/y"]) {expect(slugForPath(p)).toBe(projectDirNameFor(p));@@ -124,4 +150,20 @@ describe("findLatestSessionId", () => {expect(findLatestInFixture(cwd, sinceMs)).toBe(newerId);});++ test("looks under CLAUDE_CONFIG_DIR, not the home directory, when it is set", () => {+ const cwd = "/tmp/project-under-config-dir";+ const id = "55555555-5555-4555-8555-555555555555";+ const createdAt = Date.now();+ sessionFixture(cwd, id, createdAt + 1_000);+ const emptyHome = join(fixtureHome, "empty-home");+ mkdirSync(emptyHome, { recursive: true });++ expect(+ findLatestInFixture(cwd, createdAt, {+ HOME: emptyHome,+ CLAUDE_CONFIG_DIR: join(fixtureHome, ".claude"),+ })+ ).toBe(id);+ });});diff --git a/packages/cli/src/session/session-discovery.ts b/packages/cli/src/session/session-discovery.tsindex 7a089707..90459888 100644--- a/packages/cli/src/session/session-discovery.ts+++ b/packages/cli/src/session/session-discovery.ts@@ -21,15 +21,25 @@import { execFile, execFileSync } from "node:child_process";import { closeSync, openSync, readSync, readdirSync, realpathSync, statSync } from "node:fs";-import { homedir } from "node:os";import { basename, join } from "node:path";-import { projectDirNameFor } from "../channel/parent-proof.js";+import { claudeConfigDir, projectDirNameFor } from "../channel/parent-proof.js";/** Head bytes scanned for the `entrypoint` marker. See `isAgentSession`. */const ENTRYPOINT_BYTES = 8192;-/** Where Claude Code keeps transcripts. */-export const PROJECTS_DIR = join(homedir(), ".claude", "projects");+/**+ * Where Claude Code keeps transcripts: `<config dir>/projects`, the config dir being+ * `CLAUDE_CONFIG_DIR`, else `$HOME/.claude` (`claudeConfigDir`, `channel/parent-proof.ts`).+ *+ * Resolved at CALL time from the environment it is given. It used to be a module+ * constant built from `os.homedir()`, which is wrong twice: it ignored a+ * `CLAUDE_CONFIG_DIR` Claude Code honours, and Bun's `os.homedir()` ignores a `HOME`+ * set by a sandbox or launcher, which Claude Code follows. An owner that spawns a child+ * under a different environment passes that environment here.+ */+export function projectsDir(env: Record<string, string | undefined> = process.env): string {+ return join(claudeConfigDir(env), "projects");+}/*** Claude Code's directory name for a working directory: every character outside@@ -70,8 +80,15 @@ export function slugForPath(absPath: string): string {** Falls back to the path as given when it cannot be resolved — a cwd that has* since been deleted should still produce the best guess available, not null.+ *+ * `projectsRoot` is the CHILD's projects directory: `projectsDir(childEnv)` when the+ * child runs under an environment other than this process's.*/-export function transcriptPathFor(cwd: string, sessionUuid: string): string {+export function transcriptPathFor(+ cwd: string,+ sessionUuid: string,+ projectsRoot: string = projectsDir()+): string {let real = cwd;try {real = realpathSync(cwd);@@ -79,7 +96,7 @@ export function transcriptPathFor(cwd: string, sessionUuid: string): string {// Deleted, unreadable, or never existed. The unresolved slug is still the// right answer whenever no symlink was involved.}- return join(PROJECTS_DIR, slugForPath(real), `${sessionUuid}.jsonl`);+ return join(projectsRoot, slugForPath(real), `${sessionUuid}.jsonl`);}/** A resumable session. Fields below `sizeBytes` are absent until `hydrateSession`. */@@ -233,10 +250,10 @@ export function getRepoContext(cwd: string = process.cwd()): RepoContext | nullreturn { root, current, liveWorktrees, branchByPath };}-/** `~/.claude/projects` entries, or `[]` when the directory does not exist yet. */+/** `projectsDir()` entries, or `[]` when the directory does not exist yet. */function projectDirs(): string[] {try {- return readdirSync(PROJECTS_DIR, { withFileTypes: true })+ return readdirSync(projectsDir(), { withFileTypes: true }).filter((e) => e.isDirectory()).map((e) => e.name);} catch {@@ -246,7 +263,7 @@ function projectDirs(): string[] {/** Transcript files in one project directory, as `stat`-only rows. */function sessionsIn(dirName: string): SessionRow[] {- const dir = join(PROJECTS_DIR, dirName);+ const dir = join(projectsDir(), dirName);let names: string[];try {names = readdirSync(dir).filter((n) => n.endsWith(".jsonl"));