Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
fix(transcript-index): persist the index atomically, 0600, and only when it is behind
Brandon Bridges09716525e6f4
diff --git a/src/core/transcript-index.test.ts b/src/core/transcript-index.test.tsnew file mode 100644index 000000000..a9705e0e6--- /dev/null+++ b/src/core/transcript-index.test.ts@@ -0,0 +1,83 @@+// Persistence of the transcript index (audit #7). Only the path-explicit helpers are exercised:+// `initTranscriptIndex` walks the real ~/.claude/projects, which a unit test must never read.+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { promises as fs } from 'fs'+import { mkdtemp, readFile, rm, stat, writeFile } from 'fs/promises'+import { tmpdir } from 'os'+import { join } from 'path'++import { loadPersistedIndex, persistIndex } from './transcript-index'+import type { TranscriptIndexEntry } from './transcript-index-core'++const entry = (id: string, text: string): TranscriptIndexEntry => ({+ sessionId: id,+ transcriptPath: `/p/${id}.jsonl`,+ cwd: '/c',+ mtime: 1,+ title: id,+ text+})++function errWithCode(code: string): NodeJS.ErrnoException {+ return Object.assign(new Error(`${code}: injected`), { code })+}++let dir: string+let file: string+beforeEach(async () => {+ dir = await mkdtemp(join(tmpdir(), 'nt-transcript-index-'))+ file = join(dir, 'transcript-index.json')+})+afterEach(async () => {+ vi.restoreAllMocks()+ await rm(dir, { recursive: true, force: true })+})++describe('persistIndex', () => {+ it('round-trips through loadPersistedIndex', async () => {+ const index = [entry('a', 'alpha'), entry('b', 'beta')]+ expect(await persistIndex(file, index)).toBe(true)+ expect(loadPersistedIndex(file)).toEqual(index)+ })++ it('a failure between the temp write and the rename leaves the old index intact', async () => {+ // The bare writeFile this replaced truncated the target first, so dying mid-write left+ // unparseable JSON → an empty index → a ~779 MB, ~3.2 s cold rescan on the next launch.+ const old = [entry('a', 'old text')]+ expect(await persistIndex(file, old)).toBe(true)+ const before = await readFile(file, 'utf8')++ let tempWritten = false+ vi.spyOn(fs, 'rename').mockImplementation((async (from: string) => {+ // The temp really was written in full before the "crash" — the failure is between the two.+ tempWritten = (await readFile(from, 'utf8')).includes('new text')+ throw errWithCode('EIO')+ }) as unknown as typeof fs.rename)++ expect(await persistIndex(file, [entry('a', 'new text'), entry('b', 'more')])).toBe(false)+ expect(tempWritten).toBe(true)+ expect(await readFile(file, 'utf8')).toBe(before)+ expect(loadPersistedIndex(file)).toEqual(old)+ // writeFileAtomic removes its own temp on a failure it survives.+ expect((await fs.readdir(dir)).filter((f) => f.endsWith('.tmp'))).toEqual([])+ })++ it.skipIf(process.platform === 'win32')(+ 'writes the file 0600 — it holds transcript text (POSIX mode bits; Windows has none to check)',+ async () => {+ await writeFile(file, '[]', { mode: 0o644 }) // the old 0644 file is replaced, not chmod-inherited+ expect(await persistIndex(file, [entry('a', 'x')])).toBe(true)+ expect((await stat(file)).mode & 0o777).toBe(0o600)+ }+ )+})++describe('loadPersistedIndex', () => {+ it('reads missing, truncated or non-array files as an empty index', async () => {+ expect(loadPersistedIndex(file)).toEqual([])+ await writeFile(file, '[{"sessionId":"a","tran')+ expect(loadPersistedIndex(file)).toEqual([])+ await writeFile(file, '{"not":"an array"}')+ expect(loadPersistedIndex(file)).toEqual([])+ })+})diff --git a/src/core/transcript-index.ts b/src/core/transcript-index.tsindex 6313c7411..92ad8fd72 100644--- a/src/core/transcript-index.ts+++ b/src/core/transcript-index.ts@@ -9,6 +9,7 @@ import { platform } from './platform'import type { ClaudeAccount } from '../shared/types'import { accountConfigDir, normalizeLinkedConfigDir } from './claude-accounts-core'import { SESSION_ID_RE } from './transcript-reader'+import { sweepStaleTempFiles, writeFileAtomic } from './fs-atomic'import {extractEntryFields,planRefresh,@@ -22,6 +23,10 @@ export const TRANSCRIPT_INDEX_REFRESH_MS = 5 * 60 * 1000const READ_CAP_BYTES = 5 * 1024 * 1024 // mirror transcript-reader: never read more than the taillet entries: TranscriptIndexEntry[] = []+// True while the in-memory index holds changes the file does not. Cleared only by a write that+// landed, so a failed persist is retried on the next refresh instead of waiting for an unrelated+// transcript change — and a refresh that changed nothing still costs no 16 MB rewrite.+let dirty = falselet timer: NodeJS.Timeout | undefinedlet accountsGetter: (() => ClaudeAccount[]) | undefined@@ -114,9 +119,10 @@ async function readTail(filePath: string): Promise<string> {}}-function loadPersisted(): TranscriptIndexEntry[] {+/** Read a persisted index. Anything unreadable is an empty index: the next refresh rebuilds it. */+export function loadPersistedIndex(file: string): TranscriptIndexEntry[] {try {- const raw = fs.readFileSync(indexFilePath(), 'utf8')+ const raw = fs.readFileSync(file, 'utf8')const data = JSON.parse(raw)return Array.isArray(data) ? (data as TranscriptIndexEntry[]) : []} catch {@@ -124,15 +130,38 @@ function loadPersisted(): TranscriptIndexEntry[] {}}-async function persist(): Promise<void> {+/**+ * Persist the index; resolves false (never throws) when the write did not land.+ *+ * It was a bare `writeFile` of ~16 MB every 5 minutes while agents are active. A crash or power+ * loss mid-write left truncated JSON, which loads as an empty index and forces a cold rescan —+ * measured at ~779 MB read and ~3.2 s (audit #7, main-3/agents-3/persistence-io-2). Temp + rename+ * means a reader sees the old index or the new one, never half of either. Mode 0600 because the+ * file holds transcript text (it was 0644).+ */+export async function persistIndex(+ file: string,+ index: TranscriptIndexEntry[]+): Promise<boolean> {try {- await fs.promises.writeFile(indexFilePath(), JSON.stringify(entries), 'utf8')+ await writeFileAtomic(file, JSON.stringify(index), { mode: 0o600 })+ return true} catch {- /* best-effort */+ return false // best-effort: the caller keeps the index dirty and tries again next refresh}}-async function refresh(): Promise<void> {+// One refresh at a time. A cold scan of a large tree can outlast the interval, and two overlapping+// runs would race their persists (and the `dirty` flag) as well as reading every file twice.+let refreshing: Promise<void> | undefined+function refresh(): Promise<void> {+ refreshing ??= refreshOnce().finally(() => {+ refreshing = undefined+ })+ return refreshing+}++async function refreshOnce(): Promise<void> {const scan = await scanTranscripts()const { toRead, keep } = planRefresh(entries, scan)// Only persist when the index actually changed (new/updated entries or dropped ones).@@ -151,7 +180,8 @@ async function refresh(): Promise<void> {})}entries = fresh- if (changed) await persist()+ if (changed) dirty = true+ if (dirty) dirty = !(await persistIndex(indexFilePath(), entries))}export function searchTranscripts(query: string): TranscriptHit[] {@@ -163,7 +193,11 @@ export function searchTranscripts(query: string): TranscriptHit[] {export function initTranscriptIndex(getAccounts?: () => ClaudeAccount[]): void {accountsGetter = getAccounts- entries = loadPersisted()+ entries = loadPersistedIndex(indexFilePath())+ // Collect the legacy ownerless `<file>.tmp` shape once it is a day old. A pid-bearing temp left by+ // a crash inside writeFileAtomic is deliberately NOT collected (fs-atomic cannot prove its writer+ // dead across PID namespaces), so such an orphan stays until removed by hand.+ void sweepStaleTempFiles(indexFilePath())void refresh()timer = setInterval(() => void refresh(), TRANSCRIPT_INDEX_REFRESH_MS)if (timer.unref) timer.unref()