diff --git a/CHANGELOG.md b/CHANGELOG.md index c18134742..a3288609e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ ### Fixes - Copilot: map the `task` tool to `Task` and `web_search` to `WebSearch`, so policies matching them fire on Copilot sessions instead of silently never running. The subagent tool reaches the PascalCase hooks as `Agent` (verified against Copilot CLI 1.0.117) and Copilot's session log as `task`, so both names map (#1101, from #693, #792, #844, fixes #690) +- 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) - The audit's `sleep-polling-loop` detector now counts the explicit-seconds form `sleep 30s`, which its regex used to drop, and checks every `sleep` in a command rather than only the first, so `sleep 1; sleep 60` counts too; cached transcripts are re-scanned once on the next audit, so those already in history are counted too (#1100, from #588, #845, fixes #522) diff --git a/__tests__/lib/codex-sessions-cache.test.ts b/__tests__/lib/codex-sessions-cache.test.ts new file mode 100644 index 000000000..cd28d04e8 --- /dev/null +++ b/__tests__/lib/codex-sessions-cache.test.ts @@ -0,0 +1,110 @@ +// @vitest-environment node +import { describe, it, expect, beforeEach, afterEach, vi } from "vitest"; +import { chmodSync, 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 }; +}); + +// 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; + 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(() => { + torn.dir = null; + delete process.env.__TEST_HOME; + if (originalFpHome === undefined) delete process.env.FAILPROOFAI_HOME; + else process.env.FAILPROOFAI_HOME = originalFpHome; + 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 }); + }); + + 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); + 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("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)).toBe(sessionFile); + 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([]); + }); +}); 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..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 } 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, @@ -50,10 +51,12 @@ function readCache(): Record { function writeCacheEntry(sessionId: string, path: string): void { try { - mkdirSync(dirname(CACHE_PATH), { recursive: true }); const cache = readCache(); cache[sessionId] = path; - writeFileSync(CACHE_PATH, JSON.stringify(cache), "utf-8"); + // 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 }