From 89e039ac76ae3e94ef32f855ccb8a94c13e9449a Mon Sep 17 00:00:00 2001 From: AshSgDe29071999 Date: Thu, 13 Aug 2026 18:03:52 +0530 Subject: [PATCH 1/7] fix: write Codex session cache via atomic rename writeCacheEntry used writeFileSync on the live JSON map. A torn write turns the next read into invalid JSON and wipes every cached path. Write to a pid-unique temp file, rename into place, and unlink the temp on failure. Fixes #689 (cherry picked from commit a1375c8d916e19a7a114497af83a8ad449c33831) --- __tests__/lib/codex-sessions.test.ts | 29 +++++++++++++++++++++++++--- lib/codex-sessions.ts | 11 +++++++++-- 2 files changed, 35 insertions(+), 5 deletions(-) diff --git a/__tests__/lib/codex-sessions.test.ts b/__tests__/lib/codex-sessions.test.ts index e995a5172..1a5175614 100644 --- a/__tests__/lib/codex-sessions.test.ts +++ b/__tests__/lib/codex-sessions.test.ts @@ -1,7 +1,7 @@ // @vitest-environment node import { describe, it, expect, beforeEach, afterEach, vi } from "vitest"; -import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs"; -import { join } from "node:path"; +import { mkdtempSync, mkdirSync, rmSync, writeFileSync, existsSync, readFileSync, readdirSync } from "node:fs"; +import { dirname, join } from "node:path"; import { tmpdir } from "node:os"; const line = (obj: Record): string => JSON.stringify(obj); @@ -195,6 +195,7 @@ describe("lib/codex-sessions: findCodexTranscript", () => { let originalHome: string | undefined; let fakeHome: string; let findCodexTranscript: typeof import("@/lib/codex-sessions").findCodexTranscript; + let _getCacheFilePath: typeof import("@/lib/codex-sessions")._getCacheFilePath; beforeEach(async () => { originalHome = process.env.HOME; @@ -206,7 +207,7 @@ describe("lib/codex-sessions: findCodexTranscript", () => { const actual = await vi.importActual("node:os"); return { ...actual, homedir: () => fakeHome }; }); - ({ findCodexTranscript } = await import("@/lib/codex-sessions")); + ({ findCodexTranscript, _getCacheFilePath } = await import("@/lib/codex-sessions")); }); afterEach(() => { @@ -246,6 +247,28 @@ describe("lib/codex-sessions: findCodexTranscript", () => { const result = findCodexTranscript(sid); expect(result).toBe(file); }); + + it("writes the session cache atomically and leaves no .tmp files", () => { + const sid = "019dd672-cccc-7a30-8671-deadbeefcafe"; + const today = new Date(); + const y = String(today.getUTCFullYear()); + const m = String(today.getUTCMonth() + 1).padStart(2, "0"); + const d = String(today.getUTCDate()).padStart(2, "0"); + const dir = join(fakeHome, ".codex", "sessions", y, m, d); + mkdirSync(dir, { recursive: true }); + const file = join(dir, `rollout-${sid}.jsonl`); + writeFileSync(file, "{}\n"); + + expect(findCodexTranscript(sid)).toBe(file); + + const cachePath = _getCacheFilePath(); + expect(existsSync(cachePath)).toBe(true); + const parsed = JSON.parse(readFileSync(cachePath, "utf-8")) as Record; + expect(parsed[sid]).toBe(file); + + const leftovers = readdirSync(dirname(cachePath)).filter((name) => name.endsWith(".tmp")); + expect(leftovers).toEqual([]); + }); }); // Imports at the bottom for the test helpers above; primary imports happen diff --git a/lib/codex-sessions.ts b/lib/codex-sessions.ts index f30fd6980..080929ac0 100644 --- a/lib/codex-sessions.ts +++ b/lib/codex-sessions.ts @@ -15,7 +15,7 @@ * parser produces (`lib/log-entries.ts`) so the existing log viewer renders * Codex sessions without any UI-side branching. */ -import { readFileSync, readdirSync, existsSync, writeFileSync, mkdirSync, statSync } from "node:fs"; +import { readFileSync, readdirSync, existsSync, writeFileSync, mkdirSync, statSync, renameSync, unlinkSync } from "node:fs"; import { readFile } from "node:fs/promises"; import { dirname, join } from "node:path"; import { homedir } from "node:os"; @@ -49,13 +49,20 @@ function readCache(): Record { } function writeCacheEntry(sessionId: string, path: string): void { + const tmp = `${CACHE_PATH}.${process.pid}.tmp`; try { mkdirSync(dirname(CACHE_PATH), { recursive: true }); const cache = readCache(); cache[sessionId] = path; - writeFileSync(CACHE_PATH, JSON.stringify(cache), "utf-8"); + writeFileSync(tmp, JSON.stringify(cache), "utf-8"); + renameSync(tmp, CACHE_PATH); } catch { // Cache is best-effort + try { + unlinkSync(tmp); + } catch { + // ignore leftover cleanup failure + } } } From b60000a0c915e0227e64c25ceb62e2ed7a7aa6f2 Mon Sep 17 00:00:00 2001 From: lakshya-dhariwal Date: Sun, 27 Sep 2026 19:18:37 +0530 Subject: [PATCH 2/7] fix(lib): write codex session cache atomically (#689) (cherry picked from commit 0911062a3761889e4b563f475869b719aae35c82) --- lib/codex-sessions.ts | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/lib/codex-sessions.ts b/lib/codex-sessions.ts index 080929ac0..392d9e151 100644 --- a/lib/codex-sessions.ts +++ b/lib/codex-sessions.ts @@ -49,6 +49,10 @@ function readCache(): Record { } function writeCacheEntry(sessionId: string, path: string): void { + // Atomic write: dump to a per-process temp file in the same directory, then + // rename over the cache. rename(2) is atomic on POSIX/NTFS, so a reader can + // never see a torn JSON payload, and two concurrent writers leave the + // last-complete file behind instead of an interleaved one. const tmp = `${CACHE_PATH}.${process.pid}.tmp`; try { mkdirSync(dirname(CACHE_PATH), { recursive: true }); @@ -57,11 +61,11 @@ function writeCacheEntry(sessionId: string, path: string): void { writeFileSync(tmp, JSON.stringify(cache), "utf-8"); renameSync(tmp, CACHE_PATH); } catch { - // Cache is best-effort + // Cache is best-effort; don't leave a partial temp file behind. try { unlinkSync(tmp); } catch { - // ignore leftover cleanup failure + // temp file already gone } } } From d4d2ac750d901ba48ac9172a77f897f3c6654ad2 Mon Sep 17 00:00:00 2001 From: lakshya-dhariwal Date: Sun, 27 Sep 2026 19:24:24 +0530 Subject: [PATCH 3/7] test(lib): cover atomic codex cache write and temp-file cleanup (cherry picked from commit 25cf716049e70ba3c8fcfa0bfaa166615c8b6761) --- __tests__/lib/codex-sessions-cache.test.ts | 59 ++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 __tests__/lib/codex-sessions-cache.test.ts diff --git a/__tests__/lib/codex-sessions-cache.test.ts b/__tests__/lib/codex-sessions-cache.test.ts new file mode 100644 index 000000000..e5acbeafc --- /dev/null +++ b/__tests__/lib/codex-sessions-cache.test.ts @@ -0,0 +1,59 @@ +// @vitest-environment node +import { describe, it, expect, beforeEach, afterEach, vi } from "vitest"; +import { mkdtempSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; +import { tmpdir } from "node:os"; + +// findCodexTranscript walks ~/.codex/sessions and writes its cache under +// FAILPROOFAI_HOME/state - point both at a scratch dir. +vi.mock("node:os", async (importOriginal) => { + const actual = await importOriginal(); + return { ...actual, homedir: () => process.env.__TEST_HOME as string }; +}); + +describe("lib/codex-sessions: findCodexTranscript cache writes", () => { + let home: string; + let fpHome: string; + let sessionFile: string; + const sessionId = "atomic-cache-test-session"; + + beforeEach(() => { + home = mkdtempSync(join(tmpdir(), "codex-home-")); + fpHome = mkdtempSync(join(tmpdir(), "codex-fp-")); + process.env.__TEST_HOME = home; + process.env.FAILPROOFAI_HOME = fpHome; + const today = new Date(); + const dir = join( + home, ".codex", "sessions", + String(today.getUTCFullYear()), + String(today.getUTCMonth() + 1).padStart(2, "0"), + String(today.getUTCDate()).padStart(2, "0"), + ); + mkdirSync(dir, { recursive: true }); + sessionFile = join(dir, `rollout-${sessionId}.jsonl`); + writeFileSync(sessionFile, "", "utf-8"); + vi.resetModules(); + }); + + afterEach(() => { + delete process.env.__TEST_HOME; + delete process.env.FAILPROOFAI_HOME; + rmSync(home, { recursive: true, force: true }); + rmSync(fpHome, { recursive: true, force: true }); + }); + + it("writes a readable cache entry for the discovered transcript", async () => { + const { findCodexTranscript } = await import("@/lib/codex-sessions"); + expect(findCodexTranscript(sessionId)).toBe(sessionFile); + const cachePath = join(fpHome, "state", "codex-session-paths.json"); + const cache = JSON.parse(readFileSync(cachePath, "utf-8")) as Record; + expect(cache[sessionId]).toBe(sessionFile); + }); + + it("leaves no .tmp files behind after the write", async () => { + const { findCodexTranscript } = await import("@/lib/codex-sessions"); + findCodexTranscript(sessionId); + const stateDir = join(fpHome, "state"); + expect(readdirSync(stateDir).filter((f) => f.endsWith(".tmp"))).toEqual([]); + }); +}); From 59df87b23425d99ad333f2e740d1ec44c007d322 Mon Sep 17 00:00:00 2001 From: lakshya-dhariwal Date: Sun, 27 Sep 2026 19:43:29 +0530 Subject: [PATCH 4/7] test(lib): cover cache write and rename failure cleanup (cherry picked from commit 3d34b96f10e8af6940402d3161aa1725fb40dfe4) --- __tests__/lib/codex-sessions-cache.test.ts | 27 +++++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/__tests__/lib/codex-sessions-cache.test.ts b/__tests__/lib/codex-sessions-cache.test.ts index e5acbeafc..fa5a5a23c 100644 --- a/__tests__/lib/codex-sessions-cache.test.ts +++ b/__tests__/lib/codex-sessions-cache.test.ts @@ -1,6 +1,6 @@ // @vitest-environment node import { describe, it, expect, beforeEach, afterEach, vi } from "vitest"; -import { mkdtempSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { chmodSync, mkdtempSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { tmpdir } from "node:os"; @@ -38,6 +38,12 @@ describe("lib/codex-sessions: findCodexTranscript cache writes", () => { afterEach(() => { delete process.env.__TEST_HOME; delete process.env.FAILPROOFAI_HOME; + chmodSync(fpHome, 0o700); + try { + chmodSync(join(fpHome, "state"), 0o700); + } catch { + // state dir never created + } rmSync(home, { recursive: true, force: true }); rmSync(fpHome, { recursive: true, force: true }); }); @@ -50,6 +56,25 @@ describe("lib/codex-sessions: findCodexTranscript cache writes", () => { expect(cache[sessionId]).toBe(sessionFile); }); + it("removes the temp file when the write itself fails", async () => { + const stateDir = join(fpHome, "state"); + mkdirSync(stateDir, { recursive: true }); + chmodSync(stateDir, 0o500); + const { findCodexTranscript } = await import("@/lib/codex-sessions"); + expect(() => findCodexTranscript(sessionId)).not.toThrow(); + expect(readdirSync(stateDir).filter((f) => f.endsWith(".tmp"))).toEqual([]); + }); + + it("removes the temp file when the rename fails", async () => { + // A non-empty directory where the cache file belongs makes rename(2) fail + // after the temp write succeeded - the path that used to leak .tmp files. + const stateDir = join(fpHome, "state"); + mkdirSync(join(stateDir, "codex-session-paths.json", "blocking"), { recursive: true }); + const { findCodexTranscript } = await import("@/lib/codex-sessions"); + expect(() => findCodexTranscript(sessionId)).not.toThrow(); + expect(readdirSync(stateDir).filter((f) => f.endsWith(".tmp"))).toEqual([]); + }); + it("leaves no .tmp files behind after the write", async () => { const { findCodexTranscript } = await import("@/lib/codex-sessions"); findCodexTranscript(sessionId); From 4bca30a60c4fc10f19ffc8a3c3a389ceaa70731d Mon Sep 17 00:00:00 2001 From: NiveditJain Date: Mon, 30 Nov 2026 17:20:21 +0530 Subject: [PATCH 5/7] Use the shared atomic-write helper for the Codex cache; test the torn write Both community fixes wrote the temp file and renamed it inline. The repo already has lib/atomic-write.ts for exactly this, used by a dozen other state files, so writeCacheEntry now calls writeJsonAtomically. It also gives the temp file a random suffix beside the pid, and makes the cache 0600 like the rest of ~/.failproofai/state. Neither PR tested the bug itself: that a write which fails halfway leaves the previous cache whole. The new test makes writeFileSync write half its data and then fail with ENOSPC. It fails on main, where the half-written JSON makes readCache() start over from {}, and passes with the fix. The two happy-path tests from the cache test file are dropped. The test in codex-sessions.test.ts already checks the same things: the entry is readable and no .tmp file is left. The afterEach also restores FAILPROOFAI_HOME rather than deleting it. Co-Authored-By: Claude Opus 5.5 --- __tests__/lib/codex-sessions-cache.test.ts | 47 ++++++++++++++++------ lib/codex-sessions.ts | 24 ++++------- 2 files changed, 43 insertions(+), 28 deletions(-) diff --git a/__tests__/lib/codex-sessions-cache.test.ts b/__tests__/lib/codex-sessions-cache.test.ts index fa5a5a23c..62e49cfdf 100644 --- a/__tests__/lib/codex-sessions-cache.test.ts +++ b/__tests__/lib/codex-sessions-cache.test.ts @@ -11,13 +11,30 @@ vi.mock("node:os", async (importOriginal) => { return { ...actual, homedir: () => process.env.__TEST_HOME as string }; }); +// While `torn.dir` is set, a writeFileSync into that directory writes half its +// data and then fails, the way a full disk or a killed process leaves a file. +const torn = vi.hoisted(() => ({ dir: null as string | null })); +vi.mock("node:fs", async (importOriginal) => { + const actual = await importOriginal(); + const writeFileSync: typeof actual.writeFileSync = (file, data, options) => { + if (torn.dir && typeof file === "string" && file.startsWith(torn.dir) && typeof data === "string") { + actual.writeFileSync(file, data.slice(0, Math.floor(data.length / 2)), options); + throw Object.assign(new Error("ENOSPC: no space left on device, write"), { code: "ENOSPC" }); + } + actual.writeFileSync(file, data, options); + }; + return { ...actual, writeFileSync, default: { ...actual, writeFileSync } }; +}); + describe("lib/codex-sessions: findCodexTranscript cache writes", () => { let home: string; let fpHome: string; let sessionFile: string; + let originalFpHome: string | undefined; const sessionId = "atomic-cache-test-session"; beforeEach(() => { + originalFpHome = process.env.FAILPROOFAI_HOME; home = mkdtempSync(join(tmpdir(), "codex-home-")); fpHome = mkdtempSync(join(tmpdir(), "codex-fp-")); process.env.__TEST_HOME = home; @@ -36,8 +53,10 @@ describe("lib/codex-sessions: findCodexTranscript cache writes", () => { }); afterEach(() => { + torn.dir = null; delete process.env.__TEST_HOME; - delete process.env.FAILPROOFAI_HOME; + if (originalFpHome === undefined) delete process.env.FAILPROOFAI_HOME; + else process.env.FAILPROOFAI_HOME = originalFpHome; chmodSync(fpHome, 0o700); try { chmodSync(join(fpHome, "state"), 0o700); @@ -48,12 +67,23 @@ describe("lib/codex-sessions: findCodexTranscript cache writes", () => { rmSync(fpHome, { recursive: true, force: true }); }); - it("writes a readable cache entry for the discovered transcript", async () => { + it("keeps the previous cache whole when a write fails halfway", async () => { + const stateDir = join(fpHome, "state"); + const cachePath = join(stateDir, "codex-session-paths.json"); + mkdirSync(stateDir, { recursive: true }); + const earlier = { "earlier-session": join(home, "earlier.jsonl") }; + writeFileSync(cachePath, JSON.stringify(earlier), "utf-8"); + const { findCodexTranscript } = await import("@/lib/codex-sessions"); + torn.dir = stateDir; + // The cache is best-effort: the transcript is still found. expect(findCodexTranscript(sessionId)).toBe(sessionFile); - const cachePath = join(fpHome, "state", "codex-session-paths.json"); - const cache = JSON.parse(readFileSync(cachePath, "utf-8")) as Record; - expect(cache[sessionId]).toBe(sessionFile); + torn.dir = null; + + // Written in place, the cache would now hold half a JSON document, which + // readCache() discards as {} - every cached session lost (#689). + expect(JSON.parse(readFileSync(cachePath, "utf-8"))).toEqual(earlier); + expect(readdirSync(stateDir).filter((f) => f.endsWith(".tmp"))).toEqual([]); }); it("removes the temp file when the write itself fails", async () => { @@ -74,11 +104,4 @@ describe("lib/codex-sessions: findCodexTranscript cache writes", () => { expect(() => findCodexTranscript(sessionId)).not.toThrow(); expect(readdirSync(stateDir).filter((f) => f.endsWith(".tmp"))).toEqual([]); }); - - it("leaves no .tmp files behind after the write", async () => { - const { findCodexTranscript } = await import("@/lib/codex-sessions"); - findCodexTranscript(sessionId); - const stateDir = join(fpHome, "state"); - expect(readdirSync(stateDir).filter((f) => f.endsWith(".tmp"))).toEqual([]); - }); }); diff --git a/lib/codex-sessions.ts b/lib/codex-sessions.ts index 392d9e151..409fd6d34 100644 --- a/lib/codex-sessions.ts +++ b/lib/codex-sessions.ts @@ -15,11 +15,12 @@ * parser produces (`lib/log-entries.ts`) so the existing log viewer renders * Codex sessions without any UI-side branching. */ -import { readFileSync, readdirSync, existsSync, writeFileSync, mkdirSync, statSync, renameSync, unlinkSync } from "node:fs"; +import { readFileSync, readdirSync, existsSync, statSync } from "node:fs"; import { readFile } from "node:fs/promises"; -import { dirname, join } from "node:path"; +import { join } from "node:path"; import { homedir } from "node:os"; import { runtimeCache } from "./runtime-cache"; +import { writeJsonAtomically } from "./atomic-write"; import { baseEntry, formatTimestamp, @@ -49,24 +50,15 @@ function readCache(): Record { } function writeCacheEntry(sessionId: string, path: string): void { - // Atomic write: dump to a per-process temp file in the same directory, then - // rename over the cache. rename(2) is atomic on POSIX/NTFS, so a reader can - // never see a torn JSON payload, and two concurrent writers leave the - // last-complete file behind instead of an interleaved one. - const tmp = `${CACHE_PATH}.${process.pid}.tmp`; try { - mkdirSync(dirname(CACHE_PATH), { recursive: true }); const cache = readCache(); cache[sessionId] = path; - writeFileSync(tmp, JSON.stringify(cache), "utf-8"); - renameSync(tmp, CACHE_PATH); + // Temp file beside the cache, then rename over it: a write that dies + // halfway leaves the previous cache whole, instead of a torn JSON file + // that readCache() would discard along with every entry in it (#689). + writeJsonAtomically(CACHE_PATH, cache); } catch { - // Cache is best-effort; don't leave a partial temp file behind. - try { - unlinkSync(tmp); - } catch { - // temp file already gone - } + // Cache is best-effort } } From eec0e1f96199f9a07aefa6fc76a71a37b2eae405 Mon Sep 17 00:00:00 2001 From: NiveditJain Date: Mon, 30 Nov 2026 17:21:00 +0530 Subject: [PATCH 6/7] Add the changelog entry for the Codex cache write (#1102) Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7678d21d0..20601b6cc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,7 @@ ### Fixes +- The Codex session cache (`state/codex-session-paths.json`) is written to a temp file and renamed into place. A write cut short by a full disk or a killed hook used to leave a torn file, and the next read discarded every cached session (#1102, from #692, #847, fixes #689) - Drop the `skills` submodule and its daily Dependabot `gitsubmodule` entry. Nothing in this repo read it, nor did the npm package or any workflow, and the job in `FailproofAI/skills` that kept it current failed on every merge once the version-bot App was gone. The skills reach users through `npx skills add FailproofAI/skills`, which this pin never fed (#1075) - Delete `sync-fp-cloud-cli-skill.yml` and `sync-failproofai-sdk-skill.yml`, red on every run since August because the `SKILLS_SYNC_PAT` they pushed to `FailproofAI/skills` with was never created; that repo now pulls both skills from this public one with its own token, so nothing here holds a credential that writes to it. The fp-cloud-cli skill's description is cut from 1118 to 995 characters, under the 1024 that the skills repo's validator enforces and past which Copilot drops a skill (#1068) - Add a global `--no-color` flag, the same as `NO_COLOR=1`, accepted before or after any command; `failproofai policies` already honors `NO_COLOR` (#1067, from #695, #700, #848, fixes #688) From 4d645edb669b506863857b9a81d9ba701a6c0e88 Mon Sep 17 00:00:00 2001 From: NiveditJain Date: Mon, 30 Nov 2026 17:25:55 +0530 Subject: [PATCH 7/7] Name the read-only state dir test for what it checks In a read-only state dir the temp file is never created, so the test passed even with the helper's cleanup removed. What it does check is that the lookup still returns the transcript when the cache cannot be written. The test is renamed to say that, and asserts the return value. The halfway-write and rename-failure tests are the ones that catch a missing cleanup. Co-Authored-By: Claude Opus 5.5 --- __tests__/lib/codex-sessions-cache.test.ts | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/__tests__/lib/codex-sessions-cache.test.ts b/__tests__/lib/codex-sessions-cache.test.ts index 62e49cfdf..cd28d04e8 100644 --- a/__tests__/lib/codex-sessions-cache.test.ts +++ b/__tests__/lib/codex-sessions-cache.test.ts @@ -86,12 +86,15 @@ describe("lib/codex-sessions: findCodexTranscript cache writes", () => { expect(readdirSync(stateDir).filter((f) => f.endsWith(".tmp"))).toEqual([]); }); - it("removes the temp file when the write itself fails", async () => { + it("still finds the transcript when the state dir is read-only", async () => { + // The temp file cannot even be created here, so this checks that the + // failure is swallowed, not the cleanup (the halfway test above covers + // that). Root can write a 0500 dir, so as root this passes trivially. const stateDir = join(fpHome, "state"); mkdirSync(stateDir, { recursive: true }); chmodSync(stateDir, 0o500); const { findCodexTranscript } = await import("@/lib/codex-sessions"); - expect(() => findCodexTranscript(sessionId)).not.toThrow(); + expect(findCodexTranscript(sessionId)).toBe(sessionFile); expect(readdirSync(stateDir).filter((f) => f.endsWith(".tmp"))).toEqual([]); });