Skip to content

Claude Code. Any Model. The most powerful AI coding agent now speaks every language.

fix(logger): put the pid in log filenames so concurrent children stop clobbering

Jack Rudenko819ed5011d16
diff --git a/packages/cli/src/logger.test.ts b/packages/cli/src/logger.test.ts
new file mode 100644
index 00000000..82f1e32b
--- /dev/null
+++ b/packages/cli/src/logger.test.ts
@@ -0,0 +1,72 @@
+import { afterEach, describe, expect, test } from "bun:test";
+import { existsSync, mkdtempSync, readdirSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { dirname, join } from "node:path";
+import { fileURLToPath, pathToFileURL } from "node:url";
+
+let tempDir: string | undefined;
+
+afterEach(() => {
+ if (tempDir && existsSync(tempDir)) {
+ rmSync(tempDir, { recursive: true, force: true });
+ }
+ tempDir = undefined;
+});
+
+describe("logger filenames", () => {
+ test("concurrent processes in the same second create distinct rotation-compatible paths", async () => {
+ tempDir = mkdtempSync(join(tmpdir(), "claudish-logger-test-"));
+ const loggerUrl = pathToFileURL(join(dirname(fileURLToPath(import.meta.url)), "logger.ts")).href;
+ const fixedTime = Date.parse("2026-09-17T00:00:00.000Z");
+ const childCode = `
+ const NativeDate = Date;
+ globalThis.Date = class extends NativeDate {
+ constructor(...args) {
+ if (args.length === 0) super(${fixedTime});
+ else super(...args);
+ }
+ static now() { return ${fixedTime}; }
+ };
+ const { initLogger } = await import(${JSON.stringify(loggerUrl)});
+ initLogger(true, "info", true);
+ process.exit(0);
+ `;
+
+ const children = [
+ Bun.spawn([process.execPath, "--eval", childCode], {
+ cwd: tempDir,
+ env: { ...process.env, HOME: tempDir },
+ stdout: "pipe",
+ stderr: "pipe",
+ }),
+ Bun.spawn([process.execPath, "--eval", childCode], {
+ cwd: tempDir,
+ env: { ...process.env, HOME: tempDir },
+ stdout: "pipe",
+ stderr: "pipe",
+ }),
+ ];
+ const outcomes = await Promise.all(
+ children.map(async (child) => ({
+ exitCode: await child.exited,
+ stderr: await new Response(child.stderr).text(),
+ }))
+ );
+
+ expect(outcomes).toEqual([
+ { exitCode: 0, stderr: "" },
+ { exitCode: 0, stderr: "" },
+ ]);
+
+ const logNames = readdirSync(join(tempDir, "logs")).sort();
+
+ expect(logNames).toHaveLength(2);
+ expect(logNames[0]).not.toBe(logNames[1]);
+ expect(new Set(logNames.map((name) => name.replace(/_\d+\.log$/, ""))).size).toBe(1);
+ for (const name of logNames) {
+ expect(name.startsWith("claudish_")).toBe(true);
+ expect(name.endsWith(".log")).toBe(true);
+ expect(name).toMatch(/^claudish_2026-09-17_00-00-00_\d+\.log$/);
+ }
+ });
+});
diff --git a/packages/cli/src/logger.ts b/packages/cli/src/logger.ts
index cb59642b..1e7c5dd7 100644
--- a/packages/cli/src/logger.ts
+++ b/packages/cli/src/logger.ts
@@ -188,6 +188,34 @@ function redactLogLine(message: string, timestamp: string): string {
return `[${timestamp}] ${message}\n`;
}
+/**
+ * The per-session part of a log filename: a UTC timestamp plus this process id.
+ *
+ * The PID is load-bearing, not decoration. The timestamp has one-second
+ * resolution and the file is opened with `writeFileSync`, which TRUNCATES. Any
+ * two claudish processes that start in the same second therefore compute the
+ * same path and each wipes what the other wrote.
+ *
+ * That is not a rare race: `team` and channel `create_session` spawn their
+ * children together, so a three-model run reliably lands three processes inside
+ * one second. Measured 2026-09-16 on exactly such a run, the surviving file held
+ * three interleaved `[Proxy] Server started` lines on three different ports and
+ * was missing the handler-creation lines for one of the children entirely —
+ * during an investigation into why that child produced no output.
+ *
+ * A concurrent run is precisely when the logs matter most, and it was the case
+ * that destroyed them.
+ */
+function logFileStamp(): string {
+ const timestamp = new Date()
+ .toISOString()
+ .replace(/[:.]/g, "-")
+ .split("T")
+ .join("_")
+ .slice(0, -5);
+ return `${timestamp}_${process.pid}`;
+}
+
/**
* Initialize file logging for this session
*/
@@ -202,13 +230,7 @@ export function initLogger(
if (!existsSync(logsDir)) {
mkdirSync(logsDir, { recursive: true });
}
- const timestamp = new Date()
- .toISOString()
- .replace(/[:.]/g, "-")
- .split("T")
- .join("_")
- .slice(0, -5);
- alwaysOnLogPath = join(logsDir, `claudish_${timestamp}.log`);
+ alwaysOnLogPath = join(logsDir, `claudish_${logFileStamp()}.log`);
writeFileSync(
alwaysOnLogPath,
`Claudish Session Log - ${new Date().toISOString()}\nMode: structural (content redacted)\n${"=".repeat(60)}\n\n`
@@ -225,13 +247,7 @@ export function initLogger(
if (!existsSync(logsDir)) {
mkdirSync(logsDir, { recursive: true });
}
- const timestamp = new Date()
- .toISOString()
- .replace(/[:.]/g, "-")
- .split("T")
- .join("_")
- .slice(0, -5);
- logFilePath = join(logsDir, `claudish_${timestamp}.log`);
+ logFilePath = join(logsDir, `claudish_${logFileStamp()}.log`);
writeFileSync(
logFilePath,
`Claudish Debug Log - ${new Date().toISOString()}\nLog Level: ${level}\n${"=".repeat(80)}\n\n`