Skip to content

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.

fix(storage): atomic writes that survive Windows — retrying rename + unique temp names

enesa2909f2ab2f0
diff --git a/docs/atomic-writes.md b/docs/atomic-writes.md
new file mode 100644
index 000000000..ca1c0b267
--- /dev/null
+++ b/docs/atomic-writes.md
@@ -0,0 +1,135 @@
+# Atomic writes
+
+**The honest limit first: `renameAtomic` does not make a write reliable. It makes a write that
+would have been lost to a passing antivirus scan land instead.** A disk that is full, a directory
+that is read-only, or a file some process holds open indefinitely will still fail — loudly, which
+is the point. Nothing here protects against a machine losing power between two saves.
+
+Implementation: [`src/core/fs-atomic.ts`](../src/core/fs-atomic.ts). Tests:
+`src/core/fs-atomic.test.ts` (behaviour) and `src/core/fs-atomic.guard.test.ts` (the scan that
+keeps every store on the helper).
+
+## What every store does
+
+A store that persists JSON writes a temp file first and renames it over the target, so a reader
+sees either the old bytes or the new ones and never a half-written file:
+
+```ts
+await fs.writeFile(tmp, JSON.stringify(store), { mode: 0o600 })
+await renameAtomic(tmp, target)
+```
+
+That is correct on POSIX, where `rename(2)` is atomic and replaces the destination
+unconditionally.
+
+## Why the plain version loses data on Windows
+
+`MoveFileEx` fails with a sharing violation — Node reports it as **`EPERM`**, sometimes `EACCES` or
+`EBUSY` — whenever the **destination** is open by anyone at that instant. Not held open for long:
+opened. The things that open a file the moment you finish writing it are not exotic:
+
+| What | Why it has the file open |
+|---|---|
+| Windows Defender real-time scanning | scans each newly written file |
+| Windows Search indexer | indexes it |
+| OneDrive / a backup client | a user profile is usually synced |
+| Our own concurrent writers | two saves racing one destination |
+
+So on Windows a routine save could throw and the data was simply lost — intermittently,
+unreproducibly, and **more often on the machines that are best protected**. The stores affected
+are not peripheral: the user's canvas layout, their settings, their sealed credentials and their
+pinned remote devices.
+
+Twenty-odd files did this, across three spellings — `fs.rename`, `renameSync`, and a `rename`
+destructured from `node:fs/promises`. Every one of them reads as a correct atomic write, because
+on the platform most of this app was written on it *is* one. That is why the rule is enforced by a
+scan test rather than by convention: a store added next year gets the retry because the test
+refuses the alternative, not because its author read this page.
+
+## What the helper does, and deliberately does not
+
+**Retries the rename, briefly.** Five attempts over about 310 ms. Each attempt is still one
+indivisible rename, so retrying cannot tear a write — it only tries the same operation again once
+whoever held the destination has let go. Scanner windows are milliseconds, so the first retry
+almost always wins; the tail exists for a sync client mid-upload.
+
+**Does not serialize application decisions.** Unique temps and rename retry guarantee complete
+bytes, not correct ordering between two snapshots loaded before either write. A shared store with
+multiple read-modify-write callers still needs one mutation funnel (or an equivalent
+revision/compare-and-swap protocol) of its own.
+
+**Does not retry forever.** A genuinely locked file must fail. Several callers have contracts that
+depend on a failed save being reported as one. A save that eventually lands is worth less than an
+accurate answer about whether it did.
+
+**Does not retry every error.** `ENOENT` means the temp file is gone, which is a caller bug;
+retrying delays a clearer error and then reports the same thing. `ENOSPC` will not improve by
+waiting.
+
+**Does not branch on platform.** The retry is a no-op on POSIX, where these codes do not arise from
+this operation. Branching would mean the behaviour under test on a developer's Mac was not the
+behaviour shipped to a user on Windows.
+
+**Never swallows the final failure.** The last error is rethrown with its original `code`.
+
+## The second bug at the same sites
+
+Independent of the platform question: a **fixed** temp name (always `<file>.tmp`) shared by
+concurrent writers. One writer's rename then publishes the other's half-written bytes, or moves the
+temp out from under it so the loser fails with a confusing `ENOENT`.
+
+`writeFileAtomic` and `tempNameFor` generate a per-call unique name
+(`<target>.<pid>.<seq>.<uuid>.tmp`). The UUID is the uniqueness guarantee. PID and sequence remain
+because they make ownership cleanup and diagnostics possible, but they are not globally unique:
+two containers can both be PID 1, worker isolates share a PID with independent module counters,
+and an OS can reuse a PID while crash litter remains. `Date.now()` does **not** make a name unique
+either — two bridge calls, shutdown flushes, or WS clients can enter a save inside one millisecond.
+The guard deliberately rejects pid-plus-clock and pid-plus-counter names.
+
+"Only one instance exists" and "the write queue serializes this" are true within one process and
+silent about a second — and a second is not hypothetical: the Server Edition takes a `--data-dir`,
+so two servers can be aimed at one directory and a desktop app can share it.
+
+**A unique name owes cleanup.** A fixed name self-healed — the next save simply overwrote the
+litter. A unique one does not, so every caller must remove its own temp on failure.
+`writeFileAtomic` does that for you; a site that builds its own write sequence must do it by hand.
+
+Cleanup must not reverse the fix. A different pid only means "another process", not "a dead
+process": desktop multi-instance mode and two `nodeterm-server --data-dir X` processes can share a
+directory intentionally, including across PID namespaces where signal-0/`ESRCH` proves nothing.
+`sweepStaleTempFiles` therefore never auto-deletes any pid-bearing temp; only the exact historical
+ownerless `<file>.tmp` shape can be swept, after a conservative 24-hour grace.
+
+## Deletes whose purpose is to stop something
+
+`removeAtomic` retries the same transient Windows codes for `unlink`, and treats only `ENOENT` as
+"gone". The trap it closes is reporting, not retrying: such a delete is normally written as an
+unlink wrapped in a bare catch commented "already absent", which is correct for the failure the
+author had in mind and wrong for every other one — `EPERM` means the file is still sitting there.
+`clearAtomicTarget` extends that contract for credential clears: it reports incomplete while any
+recognized temp remains or the directory cannot be inspected, instead of telling the UI a
+credential is gone while its bearer bytes remain next door.
+
+## The rule, and how it is enforced
+
+> No store publishes a file with a bare `fs.rename`. Use `renameAtomic`, or `writeFileAtomic` if
+> the whole temp-write-publish cycle is what you want.
+
+`src/core/fs-atomic.guard.test.ts` scans `src/core`, `src/main` and `src/server`, and fails on any
+bare rename in all three spellings. The only exemption is `core/fs-atomic.ts` itself. It flags a
+bare `rename`/`renameSync` only when the file actually imported that name from `fs` — several
+stores have a `rename()` method of their own, and a guard that cries wolf is a guard somebody
+deletes.
+
+The temp-name half checks the PROPERTY, not the helper: an inline `randomUUID()` path is also
+correct. The guard strips comments before matching, so a file may still *discuss* `fs.rename` in
+prose. It also asserts it found a source tree at all — a scan that matches nothing otherwise
+reports clean, which is the same class of silent failure as the bug.
+
+## Surfaces
+
+| Surface | Status |
+|---|---|
+| **Desktop** (Electron) | Covered. Windows is the platform this exists for; on macOS/Linux the retry is inert and behaviour is unchanged. |
+| **Server Edition** | Covered for core stores — the helper is in `src/core`, so both shells get it. Its usual host is Linux, where the retry is inert, but a Windows-hosted server gets the same protection. |
+| **Mobile companion** | No client change; it holds no local stores of its own. |
diff --git a/src/core/agent-status-mirror.ts b/src/core/agent-status-mirror.ts
index c2def3e9b..4601a827e 100644
--- a/src/core/agent-status-mirror.ts
+++ b/src/core/agent-status-mirror.ts
@@ -1,5 +1,6 @@
import fs from 'fs'
import path from 'path'
+import { writeFileAtomic } from './fs-atomic'
import { platform } from './platform'
import type { AgentId } from '@shared/agents/config'
import type { AgentState, NormalizedAgentEvent } from '@shared/agents/normalize'
@@ -635,7 +636,6 @@ const STALE_SWEEP_MS = 60_000
let sweepTimer: ReturnType<typeof setInterval> | null = null
let targetFile: string | null = null
let writeTimer: NodeJS.Timeout | null = null
-let writeSeq = 0
const flushListeners = new Set<(doc: MirrorFile) => void>()
// Supplies the host-level settings block, consulted fresh on every flush (so a mid-session
// permission-mode / account change is picked up without re-wiring). Null = no block written.
@@ -1772,12 +1772,10 @@ export async function flush(): Promise<void> {
// A listener must never break the local write (or its sibling listeners).
}
}
- const tmp = `${file}.${process.pid}.${++writeSeq}.tmp`
try {
- await fs.promises.writeFile(tmp, JSON.stringify(doc), { mode: 0o600 })
- await fs.promises.rename(tmp, file)
+ await writeFileAtomic(file, JSON.stringify(doc), { mode: 0o600 })
} catch {
- await fs.promises.rm(tmp, { force: true }).catch(() => {})
+ // best-effort: listeners already got the doc; a failed local write cleans up its own temp
}
}
diff --git a/src/core/agents/hooks/codex-trust.ts b/src/core/agents/hooks/codex-trust.ts
index bb705cdb8..bb88427a3 100644
--- a/src/core/agents/hooks/codex-trust.ts
+++ b/src/core/agents/hooks/codex-trust.ts
@@ -5,8 +5,8 @@
* Self-contained: only node fs/path/crypto. We port just the functions our
* installer needs (trust hashing/keys, byte-preserving config.toml edits) and
* deliberately drop the project-trust path (upsertProjectTrustLevel) — out
- * of scope. `escapeRegex` and the tiny atomic-rename fs helpers are inlined
- * (rather than pulling in unrelated modules).
+ * of scope. `escapeRegex` is inlined (rather than pulling in unrelated
+ * modules); the rename itself goes through core/fs-atomic.ts.
*/
import {
copyFileSync,
@@ -14,12 +14,12 @@ import {
mkdirSync,
readFileSync,
realpathSync,
- renameSync,
unlinkSync,
writeFileSync
} from 'fs'
import { dirname, join } from 'path'
import { createHash, randomUUID } from 'crypto'
+import { renameAtomicSync } from '../../fs-atomic'
// Why: Codex 0.129+ gates each hook on a `trusted_hash` entry in
// ~/.codex/config.toml under [hooks.state."<key>"]. Without it the hook is in
@@ -517,9 +517,9 @@ function skipTomlLiteralString(line: string, startIndex: number): number {
// Why: atomic-rename + .bak rotation — a half-written config.toml can brick a
// user's Codex install, so write to tmp and rename. Random-suffix tmp name
-// avoids cross-process races on rapid reinstalls.
-// NOTE: the Windows-retry copy/rename helpers are inlined as plain
-// copyFileSync/renameSync here — POSIX (macOS) is the target.
+// avoids cross-process races on rapid reinstalls. The rename goes through
+// renameAtomicSync (core/fs-atomic.ts) so a Windows sharing violation retries
+// instead of losing the write; the .bak copy stays a plain copyFileSync.
export function writeConfigAtomically(configPath: string, contents: string): void {
const dir = dirname(configPath)
mkdirSync(dir, { recursive: true })
@@ -533,7 +533,7 @@ export function writeConfigAtomically(configPath: string, contents: string): voi
// a plain copyFileSync is sufficient.)
copyFileSync(configPath, `${configPath}.bak`)
}
- renameSync(tmpPath, configPath)
+ renameAtomicSync(tmpPath, configPath)
renamed = true
} finally {
if (!renamed && existsSync(tmpPath)) {
diff --git a/src/core/agents/hooks/codex.ts b/src/core/agents/hooks/codex.ts
index 58ba26659..fcd45e7de 100644
--- a/src/core/agents/hooks/codex.ts
+++ b/src/core/agents/hooks/codex.ts
@@ -22,10 +22,10 @@ import {
writeFileSync,
mkdirSync,
chmodSync,
- renameSync,
unlinkSync
} from 'fs'
import { randomUUID } from 'crypto'
+import { renameAtomicSync } from '../../fs-atomic'
import { buildManagedScript } from './managed-script'
import {
computeTrustedHash,
@@ -205,7 +205,7 @@ function writeHooksJson(file: string, config: HooksConfig): void {
let renamed = false
try {
writeFileSync(tmp, `${JSON.stringify(config, null, 2)}\n`, 'utf8')
- renameSync(tmp, file)
+ renameAtomicSync(tmp, file)
renamed = true
} finally {
if (!renamed && existsSync(tmp)) {
@@ -233,7 +233,7 @@ function writeManagedScript(file: string): void {
} catch {
/* fail open */
}
- renameSync(tmp, file)
+ renameAtomicSync(tmp, file)
renamed = true
} finally {
if (!renamed && existsSync(tmp)) {
diff --git a/src/core/agents/node-auth-secret.ts b/src/core/agents/node-auth-secret.ts
index 55118f80d..779f6df6f 100644
--- a/src/core/agents/node-auth-secret.ts
+++ b/src/core/agents/node-auth-secret.ts
@@ -1,6 +1,7 @@
import { randomBytes } from 'crypto'
import { promises as fs } from 'fs'
import path from 'path'
+import { renameAtomic, tempNameFor } from '../fs-atomic'
import { platform } from '../platform'
/**
@@ -62,11 +63,11 @@ function decodeSealed(raw: string): Buffer {
/** Write bytes atomically: unique tmp with flag 'wx', chmod 0600, rename into place,
* unlink the tmp in finally. A reader never observes a partial file. */
async function persistFile(file: string, data: string | Buffer): Promise<void> {
- const tmp = `${file}.${process.pid}.${Date.now()}.tmp`
+ const tmp = tempNameFor(file)
await fs.mkdir(path.dirname(file), { recursive: true })
try {
await fs.writeFile(tmp, data, { mode: 0o600, flag: 'wx' })
- await fs.rename(tmp, file)
+ await renameAtomic(tmp, file)
await fs.chmod(file, 0o600)
} finally {
await fs.unlink(tmp).catch(() => {})
diff --git a/src/core/agents/node-token-files.ts b/src/core/agents/node-token-files.ts
index 70206ff12..7aeb6dc10 100644
--- a/src/core/agents/node-token-files.ts
+++ b/src/core/agents/node-token-files.ts
@@ -1,5 +1,6 @@
-import { mkdirSync, chmodSync, existsSync, writeFileSync, renameSync, rmSync } from 'fs'
+import { mkdirSync, chmodSync, existsSync, writeFileSync, rmSync } from 'fs'
import path from 'path'
+import { renameAtomicSync, tempNameFor } from '../fs-atomic'
import { platform } from '../platform'
import { isSafeNodeId } from './node-auth-token'
@@ -34,10 +35,10 @@ export function writeNodeTokenFile(nodeId: string, token: string): boolean {
mkdirSync(dir, { recursive: true, mode: 0o700 })
chmodSync(dir, 0o700) // an existing dir keeps its old mode otherwise
const file = path.join(dir, nodeId)
- const tmp = path.join(dir, `.${nodeId}.${process.pid}.${Date.now()}.tmp`)
+ const tmp = tempNameFor(file)
try {
writeFileSync(tmp, `${token}\n`, { encoding: 'utf8', mode: 0o600, flag: 'wx' })
- renameSync(tmp, file)
+ renameAtomicSync(tmp, file)
chmodSync(file, 0o600)
} finally {
try {
diff --git a/src/core/agents/pending-approvals.ts b/src/core/agents/pending-approvals.ts
index 36cc6e3bd..4997defe8 100644
--- a/src/core/agents/pending-approvals.ts
+++ b/src/core/agents/pending-approvals.ts
@@ -11,6 +11,7 @@
import fs from 'fs'
import os from 'os'
import path from 'path'
+import { writeFileAtomic } from '../fs-atomic'
import { normalizeClaude, type NormalizedAgentEvent } from '../../shared/agents/normalize'
/** pendingId shape the script generates (`<node>-<ms>-<pid>`) and the ONLY thing we interpolate
@@ -47,14 +48,12 @@ export async function writePendingAnswerLocal(
if (decision !== 'allow' && decision !== 'deny') return false
const dir = pendingDir(homeDir)
const file = path.join(dir, `${pendingId}.answer`)
- const tmp = `${file}.${process.pid}.tmp`
try {
await fs.promises.mkdir(dir, { recursive: true, mode: 0o700 })
- await fs.promises.writeFile(tmp, decision, { mode: 0o600 })
- await fs.promises.rename(tmp, file)
+ // writeFileAtomic: unique tmp + retrying rename (core/fs-atomic.ts); removes its temp on failure.
+ await writeFileAtomic(file, decision, { mode: 0o600 })
return true
} catch {
- await fs.promises.rm(tmp, { force: true }).catch(() => {})
return false
}
}
diff --git a/src/core/board-log.ts b/src/core/board-log.ts
index b6582c598..21212add0 100644
--- a/src/core/board-log.ts
+++ b/src/core/board-log.ts
@@ -1,6 +1,7 @@
import fs from 'fs'
import path from 'path'
import { watch, type FSWatcher } from 'fs'
+import { renameAtomicSync } from './fs-atomic'
import { BOARD_LOG_TEXT_MAX, type BoardLogEntry } from '@shared/types'
// Re-exported so callers of this module (and its tests) can reach the cap alongside buildLine.
@@ -145,7 +146,7 @@ export class BoardLogStore {
* Move the log aside when this append would take it past `MAX_BOARD_LOG_BYTES`.
*
* Rotates BEFORE the write, so the bound holds for the file as it exists on disk rather than one
- * entry late. `renameSync` over an existing `.1` replaces it — one generation, deliberately: two
+ * entry late. The rename over an existing `.1` replaces it — one generation, deliberately: two
* would double the worst case for a file that lives inside the user's repository.
*
* Never throws: a log that cannot be rotated must still be APPENDED to (the caller's `try` then
@@ -156,7 +157,7 @@ export class BoardLogStore {
try {
const size = fs.statSync(file).size
if (size + incoming <= MAX_BOARD_LOG_BYTES) return
- fs.renameSync(file, `${file}.1`)
+ renameAtomicSync(file, `${file}.1`)
} catch {
// No file yet (the common case), or an unstattable/unrenamable one — append regardless.
}
diff --git a/src/core/codex-identity-proxy.ts b/src/core/codex-identity-proxy.ts
index ce0c955bd..00fa867de 100644
--- a/src/core/codex-identity-proxy.ts
+++ b/src/core/codex-identity-proxy.ts
@@ -27,12 +27,12 @@ import {
mkdirSync,
readFileSync,
readdirSync,
- renameSync,
unlinkSync,
writeFileSync
} from 'fs'
import path from 'path'
import { createHmac, timingSafeEqual } from 'crypto'
+import { renameAtomicSync } from './fs-atomic'
import { platform } from './platform'
/**
@@ -202,7 +202,7 @@ export function writeCodexThreadIdentity(
encoding: 'utf8',
mode: 0o600
})
- renameSync(tmp, file)
+ renameAtomicSync(tmp, file)
renamed = true
} finally {
if (!renamed) {
diff --git a/src/core/fs-atomic.guard.test.ts b/src/core/fs-atomic.guard.test.ts
new file mode 100644
index 000000000..dbf77d6d0
--- /dev/null
+++ b/src/core/fs-atomic.guard.test.ts
@@ -0,0 +1,505 @@
+// Two rules, both about temp-then-rename, both invisible for the life of the project:
+// 1. no store publishes with a bare rename (any spelling) — the Windows data-loss bug;
+// 2. no local `.tmp` publisher builds a name two writers can share — the corruption bug beside it.
+//
+// Twenty-eight files wrote temp-then-rename, which is correct on POSIX and silently lossy on Windows: the rename
+// fails with EPERM whenever anything has the destination open, and the things that open a file we
+// just wrote are Defender, the search indexer, OneDrive, and our own concurrent writers. See
+// `fs-atomic.ts` for the full account.
+//
+// Nothing caught it. Every one of those files was reviewed, several were security-reviewed, and the
+// only signal in the entire suite was one store's concurrency test — which had been failing on
+// Windows for as long as the store existed and passing everywhere else. A reviewer reading any
+// individual file sees a correct atomic write, because on the platform most of this was written on
+// it IS one.
+//
+// So the rule is enforced by scan rather than by memory: a new store added next year gets the
+// retry because this test refuses the alternative, not because its author had read this file.
+
+import { describe, expect, it } from 'vitest'
+import { readFileSync, readdirSync, statSync } from 'fs'
+import { join, relative } from 'path'
+
+const ROOTS = ['core', 'main', 'server'].map((d) => join(__dirname, '..', d))
+const SOURCE_ROOT = join(__dirname, '..')
+
+/** Guard comparisons use one separator regardless of the host running Vitest. */
+function normalizedSourcePath(value: string): string {
+ return value.replace(/\\/g, '/')
+}
+
+function sourceRelativePath(file: string): string {
+ return normalizedSourcePath(relative(SOURCE_ROOT, file))
+}
+
+function sources(dir: string, out: string[] = []): string[] {
+ for (const entry of readdirSync(dir)) {
+ const p = join(dir, entry)
+ if (statSync(p).isDirectory()) {
+ if (entry !== 'node_modules') sources(p, out)
+ } else if (/\.ts$/.test(entry) && !/\.test\.ts$/.test(entry)) {
+ out.push(p)
+ }
+ }
+ return out
+}
+
+/**
+ * Files allowed to call `fs.rename` directly, each with the reason.
+ *
+ * Kept deliberately short. Every entry is a place the retry does not apply, not a place somebody
+ * did not get round to — an exemption that means "later" belongs in an issue, not here.
+ */
+const RENAME_ALLOWED = new Map<string, string>([
+ ['core/fs-atomic.ts', 'the async/core helper; this is its one real rename']
+])
+
+function isRenameAllowed(relativeFile: string): boolean {
+ return RENAME_ALLOWED.has(normalizedSourcePath(relativeFile))
+}
+
+describe('every store publishes through renameAtomic', () => {
+ const files = ROOTS.flatMap((r) => sources(r))
+
+ it('finds the source tree (a zero-file scan would pass silently)', () => {
+ // The failure this whole file is about, one level up: a scan that matches nothing reports
+ // clean. If a directory is renamed and this drops to nothing, it must go red, not quiet.
+ expect(files.length).toBeGreaterThan(100)
+ })
+
+ // Every spelling of the call, because the first version of this test knew only `fs.rename(` and
+ // went GREEN over eight real offenders — including `atomic-json-store.ts`, a file whose name is
+ // the thing it was failing to do. A guard that matches one spelling of a hazard is worse than
+ // none: it converts "nobody has checked" into "this has been checked", which is what stops the
+ // next person looking.
+ //
+ // fs.rename(…) the namespace import
+ // renameSync(…) the sync variant, on startup and hook-install paths
+ // rename(tmp, …) destructured from 'node:fs/promises'
+ //
+ // `renameAtomic`/`renameAtomicSync` must not match, hence the trailing `\s*\(` and the
+ // preceding-character guards.
+ interface FsRenameBindings {
+ namespaces: Set<string>
+ asyncCalls: Set<string>
+ syncCalls: Set<string>
+ }
+
+ const FS_MODULE = /^(node:)?fs(\/promises)?$/
+ const identifier = /^[A-Za-z_$][\w$]*$/
+ const escaped = (value: string): string => value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
+
+ /** Resolve the LOCAL bindings imported from fs. Hard-coding `fs`/`fsp` let a harmless alias
+ * change (`import nodeFs ...`) turn the guard green over the same dangerous call. */
+ function fsRenameBindings(text: string): FsRenameBindings {
+ const found: FsRenameBindings = {
+ namespaces: new Set(),
+ asyncCalls: new Set(),
+ syncCalls: new Set()
+ }
+ for (const match of text.matchAll(
+ /import\s+(?:\*\s+as\s+)?([A-Za-z_$][\w$]*)\s+from\s+['"]([^'"]+)['"]/g
+ )) {
+ if (FS_MODULE.test(match[2])) found.namespaces.add(match[1])
+ }
+ for (const match of text.matchAll(/import\s*\{([\s\S]*?)\}\s*from\s*['"]([^'"]+)['"]/g)) {
+ if (!FS_MODULE.test(match[2])) continue
+ for (const rawMember of match[1].split(',')) {
+ const promises = rawMember
+ .trim()
+ .match(/^promises(?:\s+as\s+([A-Za-z_$][\w$]*))?$/)
+ if (promises && !/\/promises$/.test(match[2])) {
+ found.namespaces.add(promises[1] ?? 'promises')
+ continue
+ }
+ const member = rawMember.trim().match(/^(rename|renameSync)(?:\s+as\s+([A-Za-z_$][\w$]*))?$/)
+ if (!member) continue
+ const local = member[2] ?? member[1]
+ if (!identifier.test(local)) continue
+ ;(member[1] === 'rename' ? found.asyncCalls : found.syncCalls).add(local)
+ }
+ }
+ // TypeScript sources occasionally retain CommonJS imports at process boundaries. They get
+ // the same alias resolution rather than becoming a quiet escape hatch.
+ for (const match of text.matchAll(
+ /\b(?:const|let)\s+([A-Za-z_$][\w$]*)\s*=\s*require\(\s*['"]([^'"]+)['"]\s*\)/g
+ )) {
+ if (FS_MODULE.test(match[2])) found.namespaces.add(match[1])
+ }
+ return found
+ }
+
+ function renameHits(text: string): string[] {
+ const code = text
+ .replace(/\/\*[\s\S]*?\*\//g, '')
+ .replace(/(^|[^:])\/\/.*$/gm, '$1')
+ .replace(/import\s*[\s\S]*?\s+from\s*['"][^'"]+['"]/g, '')
+ const bindings = fsRenameBindings(text)
+ const hits: string[] = []
+ for (const namespace of bindings.namespaces) {
+ const call = new RegExp(
+ `(?<![A-Za-z0-9_$.])${escaped(namespace)}(?:\\.promises)?\\.rename(?:Sync)?\\s*\\(`
+ )
+ if (call.test(code)) hits.push(`${namespace}.rename`)
+ }
+ for (const local of [...bindings.asyncCalls, ...bindings.syncCalls]) {
+ const call = new RegExp(`(?<![A-Za-z0-9_$.])${escaped(local)}\\s*\\(`)
+ if (call.test(code)) hits.push(`${local}(`)
+ }
+ return hits
+ }
+
+ it('no bare rename, in ANY spelling, outside the helper', () => {
+ const offenders: string[] = []
+ for (const f of files) {
+ const text = readFileSync(f, 'utf8')
+ const rel = sourceRelativePath(f)
+ if (isRenameAllowed(rel)) continue
+ const hits = renameHits(text)
+ if (hits.length) offenders.push(`${rel} [${hits.join(', ')}]`)
+ }
+ expect(
+ offenders,
+ 'these publish a file with a bare rename, which loses the write on Windows whenever the ' +
+ 'destination is momentarily open — use renameAtomic/renameAtomicSync from core/fs-atomic.ts'
+ ).toEqual([])
+ })
+
+ it('the guard would actually catch each spelling', () => {
+ // Proving the needles bite, on strings rather than by breaking real files.
+ expect(renameHits("import fs from 'fs'\nawait fs.rename(a, b)")).not.toEqual([])
+ expect(renameHits("import nodeFs from 'node:fs'\nnodeFs.renameSync(a, b)")).not.toEqual([])
+ expect(renameHits("import fs from 'fs'\nawait fs.promises.rename(a, b)")).not.toEqual([])
+ expect(renameHits("import { promises as disk } from 'node:fs'\nawait disk.rename(a, b)"))
+ .not.toEqual([])
+ expect(renameHits("import { renameSync } from 'fs'\nrenameSync(tmp, file)")).not.toEqual([])
+ expect(renameHits("import { rename as move } from 'node:fs/promises'\nawait move(a, b)")).not.toEqual([])
+ expect(renameHits("const disk = require('fs')\ndisk.renameSync(a, b)")).not.toEqual([])
+ // …and that the replacements do NOT trip it. `renameAtomic` contains `rename`, so this is the
+ // assertion standing between the guard and flagging every file it just fixed.
+ expect(renameHits("import { renameAtomic } from './fs-atomic'\nawait renameAtomic(a, b)"))
+ .toEqual([])
+ expect(renameHits("import { renameAtomicSync } from './fs-atomic'\nrenameAtomicSync(a, b)"))
+ .toEqual([])
+ })
+
+ it('the fs-import qualifier separates a real rename from a method called rename', () => {
+ // The false positives that made this necessary were all real: kids-mode, School-mode and the
+ // Ollama chat store each expose a `rename()` of their own.
+ const fsImport = "import { mkdir, rename, writeFile } from 'node:fs/promises'"
+ expect([...fsRenameBindings(fsImport).asyncCalls]).toEqual(['rename'])
+ expect([...fsRenameBindings("import { renameSync } from 'fs'").syncCalls]).toEqual(['renameSync'])
+ expect(fsRenameBindings("import { mkdir, writeFile } from 'node:fs/promises'").asyncCalls.size)
+ .toBe(0)
+ // Not from fs at all — a store's own method, or a helper of the same name.
+ expect(fsRenameBindings("import { rename } from './my-store'").asyncCalls.size).toBe(0)
+ // Must not be satisfied by a longer member that merely contains the name.
+ expect(fsRenameBindings("import { renameAtomic } from './fs-atomic'").asyncCalls.size).toBe(0)
+ expect(fsRenameBindings("import { renameSync } from 'fs'").asyncCalls.size).toBe(0)
+ })
+
+ it('normalizes helper exemptions on both POSIX and Windows-shaped paths', () => {
+ expect(normalizedSourcePath('core/fs-atomic.ts')).toBe('core/fs-atomic.ts')
+ expect(normalizedSourcePath(String.raw`core\fs-atomic.ts`)).toBe('core/fs-atomic.ts')
+ expect(isRenameAllowed('core/fs-atomic.ts')).toBe(true)
+ expect(isRenameAllowed(String.raw`core\fs-atomic.ts`)).toBe(true)
+ expect(isRenameAllowed('nested/core/fs-atomic.ts')).toBe(false)
+ expect(isRenameAllowed('core/fs-atomic.ts.bak')).toBe(false)
+ const scanned = new Set(files.map(sourceRelativePath))
+ for (const allowed of RENAME_ALLOWED.keys()) expect(scanned.has(allowed)).toBe(true)
+ })
+})
+
+describe('no local .tmp publisher uses a shared temp name', () => {
+ const files = ROOTS.flatMap((r) => sources(r))
+
+ it('every local temp path carries random UUID entropy', () => {
+ // The second bug at the same sites, independent of the platform question: a FIXED temp name
+ // means two writers share one path, so one rename publishes the other's half-written bytes —
+ // or moves the temp out from under it, and the loser fails with a confusing ENOENT.
+ //
+ // Five sites had it, and each had a reason it was thought safe: "only one instance exists",
+ // "the write queue serializes this". Every one of those was true within one PROCESS and
+ // silent about a second. The Server Edition takes a --data-dir, so two can be aimed at one
+ // directory; scrollback-store had a counter and no pid, which is that gap exactly.
+ //
+ // Deliberately NOT "must call tempNameFor": an inline randomUUID name is also correct. The
+ // rule is the collision-resistant property, not one spelling of the helper call.
+ const offenders: string[] = []
+ for (const f of files) {
+ const text = readFileSync(f, 'utf8')
+ const rel = sourceRelativePath(f)
+ for (const name of tempNameExpressions(text)) {
+ if (isUniqueTempName(name, rel, text)) continue
+ offenders.push(`${rel} \`${name}\``)
+ }
+ }
+ expect(
+ offenders,
+ 'these build a temp path two writers can share — use tempNameFor() from core/fs-atomic.ts, ' +
+ 'and remember a unique name must be cleaned up on failure because it never self-heals ' +
+ 'the way a fixed one did'
+ ).toEqual([])
+ })
+
+ it('the needle tells a shared name from a safe one', () => {
+ expect(tempNameExpressions(' const tmp = `${this.path}.tmp`')).toHaveLength(1)
+ expect(tempNameExpressions(' const tmp = `${this.path}.tmp-${process.pid}-${Date.now()}`')).toHaveLength(1)
+ expect(tempNameExpressions(' const tmp = path.join(dir, `.${nodeId}.${process.pid}.${Date.now()}.tmp`)')).toHaveLength(1)
+ expect(tempNameExpressions(' const tmp = join(dir, `.${Date.now()}-${randomUUID()}.tmp`)')).toHaveLength(1)
+ expect(tempNameExpressions(' return `${target}.${pid}.${sequence}.${uuid()}.tmp`')).toHaveLength(1)
+ expect(tempNameExpressions(
+ ' const tmp: string = path.join(\n dir,\n `${file}.${Date.now()}.tmp`\n )'
+ )).toEqual(['${file}.${Date.now()}.tmp'])
+ expect(tempNameExpressions(" const tmp = file + '.tmp'")).toEqual(["file + '.tmp'"])
+ expect(tempNameExpressions(" const tmp =\n file +\n '.tmp'"))
+ .toEqual(["file + '.tmp'"])
+ const importsUuid = "import { randomUUID } from 'crypto'"
+ const importsUuidAlias = "import { randomUUID as freshId } from 'node:crypto'"
+ const importsDefaultCrypto = "import crypto from 'node:crypto'"
+ const importsNamespaceCrypto = "import * as entropy from 'crypto'"
+ expect(isUniqueTempName('${this.path}.tmp', 'core/store.ts', '')).toBe(false)
+ expect(isUniqueTempName(
+ '${file}.${process.pid}.${++writeSeq}.${randomUUID()}.tmp',
+ 'core/store.ts',
+ importsUuid
+ )).toBe(true)
+ expect(isUniqueTempName(
+ '${file}.${process.pid}.${++this.writeSeq}.${uuid()}.tmp',
+ 'core/fs-atomic.ts',
+ ''
+ )).toBe(true)
+ expect(isUniqueTempName('${file}.${Date.now()}-${randomUUID()}.tmp', 'core/store.ts', importsUuid))
+ .toBe(true)
+ expect(isUniqueTempName(
+ '${file}.${freshId()}.tmp',
+ 'core/store.ts',
+ importsUuidAlias
+ )).toBe(true)
+ expect(isUniqueTempName(
+ '${file}.${crypto.randomUUID()}.tmp',
+ 'server/upload.ts',
+ importsDefaultCrypto
+ )).toBe(true)
+ expect(isUniqueTempName(
+ '${file}.${entropy.randomUUID()}.tmp',
+ 'server/upload.ts',
+ importsNamespaceCrypto
+ )).toBe(true)
+ expect(isUniqueTempName(
+ '${file}.${diskEntropy.randomUUID()}.tmp',
+ 'server/upload.ts',
+ "const diskEntropy = require('node:crypto')"
+ )).toBe(true)
+ expect(isUniqueTempName(
+ '${file}.${freshId()}.tmp',
+ 'server/upload.ts',
+ "const { randomUUID: freshId } = require('crypto')"
+ )).toBe(true)
+ // A function merely NAMED uuid/randomUUID is not entropy. Only the two helpers may use their
+ // behavior-tested injected uuid seam; inline sites must call a binding imported from crypto.
+ expect(isUniqueTempName('${file}.${uuid()}.tmp', 'core/other.ts', '')).toBe(false)
+ expect(isUniqueTempName('${file}.${randomUUID()}.tmp', 'core/other.ts', '')).toBe(false)
+ expect(isUniqueTempName(
+ '${file}.${crypto.randomUUID()}.tmp',
+ 'core/other.ts',
+ "import crypto from './crypto'"
+ )).toBe(false)
+ expect(isUniqueTempName(
+ '${file}.${fake.randomUUID()}.tmp',
+ 'core/other.ts',
+ importsUuid
+ )).toBe(false)
+ expect(isUniqueTempName(
+ '${file}.${randomUUID()}.tmp',
+ 'core/other.ts',
+ importsNamespaceCrypto
+ )).toBe(false)
+ expect(isUniqueTempName(
+ '${file}.${crypto.randomUUID}.tmp',
+ 'core/other.ts',
+ importsDefaultCrypto
+ )).toBe(false)
+ expect(isUniqueTempName(
+ '${file}.${crypto.randomUUID()}.tmp',
+ 'core/other.ts',
+ "const crypto = { randomUUID: () => 'fixed' }"
+ )).toBe(false)
+ expect(isUniqueTempName(
+ '${file}.${"crypto.randomUUID("}.tmp',
+ 'core/other.ts',
+ importsDefaultCrypto
+ )).toBe(false)
+ expect(isUniqueTempName(
+ '${file}.${crypto.randomUUID()}.tmp',
+ 'core/other.ts',
+ "// import crypto from 'node:crypto'"
+ )).toBe(false)
+ // A clock tick is shared by every writer in that millisecond. A pid only separates processes;
+ // neither one separates two calls in the same process.
+ expect(isUniqueTempName('${file}.${Date.now()}.tmp', 'core/store.ts', '')).toBe(false)
+ expect(isUniqueTempName('${file}.${process.pid}.${Date.now()}.tmp', 'core/store.ts', '')).toBe(false)
+ expect(isUniqueTempName('${file}.tmp-${process.pid}-${Date.now()}', 'core/store.ts', '')).toBe(false)
+ expect(isUniqueTempName('${file}.${process.pid}.tmp', 'core/store.ts', '')).toBe(false)
+ expect(isUniqueTempName('${file}.${++writeSeq}.tmp', 'core/store.ts', '')).toBe(false)
+ expect(isUniqueTempName('${file}.${process.pid}.${writeSeq}.tmp', 'core/store.ts', '')).toBe(false)
+ expect(isUniqueTempName('${file}.${process.pid}.${++writeSeq}.tmp', 'core/store.ts', '')).toBe(false)
+ expect(isUniqueTempName('${file}.${process.pid}.${writeSeq++ % 2}.tmp', 'core/store.ts', ''))
+ .toBe(false)
+ expect(isUniqueTempName("file + '.tmp'", 'core/store.ts', '')).toBe(false)
+ expect(isUniqueTempName(
+ "file + '.' + randomUUID() + '.tmp'",
+ 'core/store.ts',
+ importsUuid
+ )).toBe(true)
+ })
+})
+
+/** Find temp-path templates returned by a helper or assigned directly/through path.join, including
+ * typed/multiline joins and the common `tmp = file + '.tmp'` concatenation. Each join is bounded
+ * by its semicolon/backtick and each concatenation by its declaration line, so an unrelated later
+ * string cannot become false entropy. The historical node-token collision lived inside path.join;
+ * the old direct-only needle silently missed it. */
+function tempNameExpressions(text: string): string[] {
+ const templates = [...text.matchAll(
+ /^\s*(?:(?:const|let)\s+\w+(?:\s*:\s*[^=;\r\n]+)?\s*=\s*(?:(?:path\.)?join\([^`;]*?)?|return\s+)`([^`]*(?:\.tmp|tmp-)[^`]*)`/gm
+ )].map((match) => match[1])
+ const concatenations: string[] = []
+ const lines = text.split(/\r?\n/)
+ for (let index = 0; index < lines.length; index++) {
+ const declaration = /^\s*(?:const|let)\s+\w*(?:tmp|temp)\w*(?:\s*:\s*[^=]+)?\s*=\s*(.*)$/i
+ .exec(lines[index])
+ if (!declaration) continue
+ let expression = declaration[1]
+ let next = index + 1
+ const continues = (): boolean => {
+ const compact = expression.trim()
+ const opens = (expression.match(/[([{]/g) ?? []).length
+ const closes = (expression.match(/[)\]}]/g) ?? []).length
+ return compact === '' || /[+,(]$/.test(compact) || opens > closes || /^\s*\+/.test(lines[next] ?? '')
+ }
+ while (next < lines.length && continues()) {
+ expression += ` ${lines[next].trim()}`
+ next++
+ }
+ if (/['"][^'"]*(?:\.tmp|tmp-)[^'"]*['"]/.test(expression)) {
+ concatenations.push(expression.trim().replace(/\s+/g, ' '))
+ index = next - 1
+ }
+ }
+ return [...templates, ...concatenations]
+}
+
+interface CryptoRandomUuidBindings {
+ namespaces: Set<string>
+ directCalls: Set<string>
+}
+
+const CRYPTO_MODULE = /^(node:)?crypto$/
+const IDENTIFIER = /^[A-Za-z_$][\w$]*$/
+
+function escapeRegExp(value: string): string {
+ return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
+}
+
+/** Resolve only bindings that come from Node's crypto module. Matching the call spelling alone
+ * let an unrelated object named `crypto` or `fake.randomUUID()` satisfy the uniqueness guard. */
+function cryptoRandomUuidBindings(source: string): CryptoRandomUuidBindings {
+ const found: CryptoRandomUuidBindings = {
+ namespaces: new Set(),
+ directCalls: new Set()
+ }
+
+ const code = source
+ .replace(/\/\*[\s\S]*?\*\//g, '')
+ .replace(/(^|[^:])\/\/.*$/gm, '$1')
+
+ for (const match of code.matchAll(
+ /^\s*import\s+([\s\S]*?)\s+from\s+['"]([^'"]+)['"]\s*;?/gm
+ )) {
+ if (!CRYPTO_MODULE.test(match[2])) continue
+ const clause = match[1].trim()
+ if (/^type\b/.test(clause)) continue
+
+ const defaultImport = clause.match(/^([A-Za-z_$][\w$]*)(?:\s*,|$)/)
+ if (defaultImport) found.namespaces.add(defaultImport[1])
+
+ const namespaceImport = clause.match(/(?:^|,)\s*\*\s+as\s+([A-Za-z_$][\w$]*)\s*$/)
+ if (namespaceImport) found.namespaces.add(namespaceImport[1])
+
+ const namedImports = clause.match(/\{([\s\S]*?)\}/)
+ if (!namedImports) continue
+ for (const rawMember of namedImports[1].split(',')) {
+ const member = rawMember.trim().match(
+ /^randomUUID(?:\s+as\s+([A-Za-z_$][\w$]*))?$/
+ )
+ const local = member?.[1] ?? (member ? 'randomUUID' : '')
+ if (IDENTIFIER.test(local)) found.directCalls.add(local)
+ }
+ }
+
+ for (const match of code.matchAll(
+ /^\s*import\s+([A-Za-z_$][\w$]*)\s*=\s*require\(\s*['"]([^'"]+)['"]\s*\)/gm
+ )) {
+ if (CRYPTO_MODULE.test(match[2])) found.namespaces.add(match[1])
+ }
+
+ // A few process-boundary files retain CommonJS imports. They get the same binding check rather
+ // than turning `require('crypto')` into a quiet false-red or an arbitrary local alias green.
+ for (const match of code.matchAll(
+ /^\s*(?:const|let)\s+([A-Za-z_$][\w$]*)\s*=\s*require\(\s*['"]([^'"]+)['"]\s*\)/gm
+ )) {
+ if (CRYPTO_MODULE.test(match[2])) found.namespaces.add(match[1])
+ }
+ for (const match of code.matchAll(
+ /^\s*(?:const|let)\s*\{([^}]*)\}\s*=\s*require\(\s*['"]([^'"]+)['"]\s*\)/gm
+ )) {
+ if (!CRYPTO_MODULE.test(match[2])) continue
+ for (const rawMember of match[1].split(',')) {
+ const member = rawMember.trim().match(
+ /^randomUUID(?:\s*:\s*([A-Za-z_$][\w$]*))?$/
+ )
+ const local = member?.[1] ?? (member ? 'randomUUID' : '')
+ if (IDENTIFIER.test(local)) found.directCalls.add(local)
+ }
+ }
+
+ return found
+}
+
+/** A random UUID is the unique dimension. PID+counter is valuable ownership metadata, but two
+ * containers can both be PID 1 with a fresh module counter, worker isolates share a PID with
+ * separate counters, and an OS can reuse a PID while crash litter remains. */
+function isUniqueTempName(name: string, relativeFile: string, source: string): boolean {
+ const helperWithBehavioralUuidChut = relativeFile === 'core/fs-atomic.ts'
+ const bindings = cryptoRandomUuidBindings(source)
+ const interpolationBodies = [...name.matchAll(/\$\{([^}]*)\}/g)].map((match) =>
+ match[1]
+ .replace(/'(?:\\.|[^'\\])*'|"(?:\\.|[^"\\])*"/g, '')
+ .replace(/\/\*[\s\S]*?\*\//g, '')
+ .replace(/\/\/.*$/g, '')
+ )
+ const inspectedBodies = interpolationBodies.length > 0
+ ? interpolationBodies
+ : [name
+ .replace(/'(?:\\.|[^'\\])*'|"(?:\\.|[^"\\])*"/g, '')
+ .replace(/\/\*[\s\S]*?\*\//g, '')
+ .replace(/\/\/.*$/g, '')]
+
+ if (helperWithBehavioralUuidChut) {
+ if (inspectedBodies.some((body) => /(?<![A-Za-z0-9_$.])uuid\s*\(/.test(body))) {
+ return true
+ }
+ }
+ for (const namespace of bindings.namespaces) {
+ const call = new RegExp(
+ `(?<![A-Za-z0-9_$.])${escapeRegExp(namespace)}\\.randomUUID\\s*\\(`
+ )
+ if (inspectedBodies.some((body) => call.test(body))) return true
+ }
+ for (const directCall of bindings.directCalls) {
+ const call = new RegExp(`(?<![A-Za-z0-9_$.])${escapeRegExp(directCall)}\\s*\\(`)
+ if (inspectedBodies.some((body) => call.test(body))) return true
+ }
+ return false
+}
diff --git a/src/core/fs-atomic.test.ts b/src/core/fs-atomic.test.ts
new file mode 100644
index 000000000..87ce9b4dd
--- /dev/null
+++ b/src/core/fs-atomic.test.ts
@@ -0,0 +1,474 @@
+// The retry has to be proved against a rename that FAILS and then succeeds, not merely against a
+// rename that works — the whole point is behaviour on a platform most of this suite never runs on.
+// So the transient failure is injected rather than waited for.
+
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { promises as fs, writeFileSync, readFileSync, renameSync } from 'fs'
+import { mkdtemp, readFile, rm } from 'fs/promises'
+import { tmpdir } from 'os'
+import { join } from 'path'
+
+import {
+ clearAtomicTarget,
+ removeAtomic,
+ renameAtomic,
+ renameAtomicSync,
+ STALE_TEMP_AGE_MS,
+ sweepStaleTempFiles,
+ tempNameFor,
+ writeFileAtomic
+} from './fs-atomic'
+
+let dir: string
+beforeEach(async () => {
+ dir = await mkdtemp(join(tmpdir(), 'nt-atomic-'))
+})
+afterEach(async () => {
+ vi.restoreAllMocks()
+ await rm(dir, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 })
+})
+
+function errWithCode(code: string): NodeJS.ErrnoException {
+ const e: NodeJS.ErrnoException = new Error(`${code}: injected`)
+ e.code = code
+ return e
+}
+
+describe('renameAtomic survives a destination held open', () => {
+ it('retries a Windows sharing violation and succeeds', async () => {
+ const target = join(dir, 'store.json')
+ const tmp = join(dir, 'store.json.tmp')
+ await fs.writeFile(tmp, 'new')
+
+ const real = fs.rename
+ let calls = 0
+ vi.spyOn(fs, 'rename').mockImplementation((async (a: never, b: never) => {
+ // Two scanners in a row, then the handle is released. EPERM is what Windows actually
+ // reports for a sharing violation on MoveFileEx.
+ if (++calls <= 2) throw errWithCode('EPERM')
+ return (real as (a: never, b: never) => Promise<void>)(a, b)
+ }) as typeof fs.rename)
+
+ await renameAtomic(tmp, target)
+ expect(calls).toBe(3)
+ expect(await readFile(target, 'utf-8')).toBe('new')
+ })
+
+ it.each(['EPERM', 'EACCES', 'EBUSY'])('treats %s as transient', async (code) => {
+ const target = join(dir, 'store.json')
+ const tmp = join(dir, 'store.json.tmp')
+ await fs.writeFile(tmp, 'new')
+ const real = fs.rename
+ let calls = 0
+ vi.spyOn(fs, 'rename').mockImplementation((async (a: never, b: never) => {
+ if (++calls === 1) throw errWithCode(code)
+ return (real as (a: never, b: never) => Promise<void>)(a, b)
+ }) as typeof fs.rename)
+ await renameAtomic(tmp, target)
+ expect(calls).toBe(2)
+ })
+
+ it('does NOT retry an error that waiting cannot fix', async () => {
+ // ENOENT means the temp is gone — a bug in the caller. Retrying delays a clearer error by a
+ // third of a second and reports the same failure.
+ let calls = 0
+ vi.spyOn(fs, 'rename').mockImplementation((async () => {
+ calls++
+ throw errWithCode('ENOENT')
+ }) as typeof fs.rename)
+ await expect(renameAtomic(join(dir, 'a'), join(dir, 'b'))).rejects.toThrow(/ENOENT/)
+ expect(calls).toBe(1)
+ })
+
+ it('gives up rather than hanging, and rethrows the REAL error', async () => {
+ // A permanently locked file must fail: several callers report a failed save as not persisted,
+ // and that contract is worth more than a save that eventually lands.
+ let calls = 0
+ vi.spyOn(fs, 'rename').mockImplementation((async () => {
+ calls++
+ throw errWithCode('EPERM')
+ }) as typeof fs.rename)
+ const err = await renameAtomic(join(dir, 'a'), join(dir, 'b')).catch((e) => e)
+ expect(err.code, 'the original code must survive, not a wrapper').toBe('EPERM')
+ expect(calls, 'bounded: five attempts, not an unbounded loop').toBe(5)
+ })
+})
+
+describe('renameAtomicSync', () => {
+ // The sync twin exists for paths that cannot be async — hook installers on the startup path, the
+ // codex trust-hash write, the per-node token file. It is easy to add the async helper and leave
+ // these behind, which is precisely what the first version of this work did: the guard knew only
+ // `fs.rename(` and stayed green over eight `renameSync` and destructured-`rename` sites.
+ //
+ // The rename is injected because a spy cannot be attached to an ESM namespace export — see the
+ // parameter's own comment in fs-atomic.ts.
+ it('retries a sharing violation and succeeds', () => {
+ const target = join(dir, 'store.json')
+ const tmp = join(dir, 'store.json.tmp')
+ writeFileSync(tmp, 'new')
+ let calls = 0
+ renameAtomicSync(tmp, target, (a, b) => {
+ // Two scanners in a row, then the handle is released.
+ if (++calls <= 2) throw errWithCode('EPERM')
+ renameSync(a, b)
+ })
+ expect(calls).toBe(3)
+ expect(readFileSync(target, 'utf-8')).toBe('new')
+ })
+
+ it.each(['EPERM', 'EACCES', 'EBUSY'])('treats %s as transient', (code) => {
+ const target = join(dir, 'store.json')
+ const tmp = join(dir, 'store.json.tmp')
+ writeFileSync(tmp, 'new')
+ let calls = 0
+ renameAtomicSync(tmp, target, (a, b) => {
+ if (++calls === 1) throw errWithCode(code)
+ renameSync(a, b)
+ })
+ expect(calls).toBe(2)
+ })
+
+ it('does not retry an error waiting cannot fix', () => {
+ let calls = 0
+ expect(() =>
+ renameAtomicSync(join(dir, 'a'), join(dir, 'b'), () => {
+ calls++
+ throw errWithCode('ENOENT')
+ })
+ ).toThrow(/ENOENT/)
+ expect(calls).toBe(1)
+ })
+
+ it('gives up rather than blocking forever, and rethrows the REAL error', () => {
+ // It blocks the thread while it waits, so an unbounded loop here would hang the app rather
+ // than merely losing a save.
+ let calls = 0
+ let err: NodeJS.ErrnoException | undefined
+ try {
+ renameAtomicSync(join(dir, 'a'), join(dir, 'b'), () => {
+ calls++
+ throw errWithCode('EPERM')
+ })
+ } catch (e) {
+ err = e as NodeJS.ErrnoException
+ }
+ expect(err?.code).toBe('EPERM')
+ expect(calls, 'bounded: five attempts').toBe(5)
+ })
+
+ it('actually waits between attempts, rather than spinning through instantly', () => {
+ // `Atomics.wait` is a real sleep. Swap it for a no-op and every retry fires in the same
+ // millisecond, which defeats the point — the destination needs TIME to be released.
+ const started = Date.now()
+ try {
+ renameAtomicSync(join(dir, 'a'), join(dir, 'b'), () => {
+ throw errWithCode('EPERM')
+ })
+ } catch {
+ /* expected */
+ }
+ // Four sleeps: 10 + 25 + 75 + 200. Asserting under the total to stay clear of timer slop.
+ expect(Date.now() - started).toBeGreaterThanOrEqual(200)
+ })
+
+ it('uses the real renameSync when nothing is injected', () => {
+ // The default parameter is the production path; without this the injected tests above would
+ // all pass while the shipped function renamed nothing.
+ const target = join(dir, 'real.json')
+ const tmp = join(dir, 'real.json.tmp')
+ writeFileSync(tmp, 'shipped')
+ renameAtomicSync(tmp, target)
+ expect(readFileSync(target, 'utf-8')).toBe('shipped')
+ })
+})
+
+describe('writeFileAtomic', () => {
+ it('publishes the new bytes', async () => {
+ const target = join(dir, 'store.json')
+ await writeFileAtomic(target, '{"a":1}')
+ expect(await readFile(target, 'utf-8')).toBe('{"a":1}')
+ })
+
+ it('leaves the OLD file byte-for-byte intact when the write fails', async () => {
+ // The half every `persisted:false` contract depends on: a failed save must not also destroy
+ // what was already there.
+ const target = join(dir, 'store.json')
+ await writeFileAtomic(target, 'original')
+ vi.spyOn(fs, 'rename').mockImplementation((async () => {
+ throw errWithCode('ENOSPC')
+ }) as typeof fs.rename)
+ await expect(writeFileAtomic(target, 'replacement')).rejects.toThrow(/ENOSPC/)
+ expect(await readFile(target, 'utf-8')).toBe('original')
+ })
+
+ it('removes its own temp on failure', async () => {
+ // A unique temp name never self-heals the way a fixed one did, where the next save reused it.
+ const target = join(dir, 'store.json')
+ vi.spyOn(fs, 'rename').mockImplementation((async () => {
+ throw errWithCode('ENOSPC')
+ }) as typeof fs.rename)
+ await writeFileAtomic(target, 'x').catch(() => {})
+ const left = (await fs.readdir(dir)).filter((f) => f.endsWith('.tmp'))
+ expect(left).toEqual([])
+ })
+
+ it('gives concurrent writers different temp files', async () => {
+ // With one shared `<file>.tmp`, a writer's rename publishes the other's half-written bytes.
+ const target = join(dir, 'store.json')
+ const seen: string[] = []
+ const real = fs.writeFile
+ vi.spyOn(fs, 'writeFile').mockImplementation((async (p: never, ...rest: never[]) => {
+ seen.push(String(p))
+ return (real as (p: never, ...r: never[]) => Promise<void>)(p, ...rest)
+ }) as typeof fs.writeFile)
+ await Promise.all([writeFileAtomic(target, 'a'), writeFileAtomic(target, 'b')])
+ expect(new Set(seen).size, `both writers used ${seen.join(' and ')}`).toBe(2)
+ })
+
+ it('the published result is one writer\'s bytes, never a splice of both', async () => {
+ const target = join(dir, 'store.json')
+ const a = JSON.stringify({ pubkeys: Array.from({ length: 64 }, (_, i) => `A${'a'.repeat(42)}${i}`) })
+ const b = JSON.stringify({ pubkeys: ['B'] })
+ await Promise.all([writeFileAtomic(target, a), writeFileAtomic(target, b)])
+ const got = await readFile(target, 'utf-8')
+ expect([a, b]).toContain(got)
+ })
+})
+
+describe('removeAtomic', () => {
+ it('reports success when the file is genuinely gone', async () => {
+ const f = join(dir, 'gone.json')
+ writeFileSync(f, 'x')
+ expect(await removeAtomic(f)).toBe(true)
+ })
+
+ it('treats ENOENT as success — the caller wanted it absent and it is', async () => {
+ expect(await removeAtomic(join(dir, 'never-existed.json'))).toBe(true)
+ })
+
+ it('reports FAILURE when the file is still there', async () => {
+ // The whole point. A delete whose purpose is to stop something happening — the relay
+ // advertisement, so phones stop minting tokens against a host that is off — must not report
+ // success while the file sits there. The old shape was an unlink in a bare catch commented
+ // "already absent", which is true of ENOENT and false of every other code.
+ vi.spyOn(fs, 'unlink').mockImplementation((async () => {
+ throw errWithCode('EPERM')
+ }) as typeof fs.unlink)
+ expect(await removeAtomic(join(dir, 'held-open.json'))).toBe(false)
+ })
+
+ it('retries a transient lock before giving up', async () => {
+ const f = join(dir, 'busy.json')
+ writeFileSync(f, 'x')
+ const real = fs.unlink
+ let calls = 0
+ vi.spyOn(fs, 'unlink').mockImplementation((async (p: never) => {
+ if (++calls <= 2) throw errWithCode('EBUSY')
+ return (real as (p: never) => Promise<void>)(p)
+ }) as typeof fs.unlink)
+ expect(await removeAtomic(f)).toBe(true)
+ expect(calls).toBe(3)
+ })
+
+ it('does not spend the retry budget on an error waiting cannot fix', async () => {
+ let calls = 0
+ vi.spyOn(fs, 'unlink').mockImplementation((async () => {
+ calls++
+ throw errWithCode('EISDIR')
+ }) as typeof fs.unlink)
+ expect(await removeAtomic(join(dir, 'a-directory'))).toBe(false)
+ expect(calls).toBe(1)
+ })
+})
+
+describe('unique temp names and abandoned-temp collection', () => {
+ it('separates same-millisecond calls and colliding PID namespaces/module counters', () => {
+ const now = vi.spyOn(Date, 'now').mockReturnValue(1_700_000_000_000)
+ const a = tempNameFor(join(dir, 'secret.json'))
+ const b = tempNameFor(join(dir, 'secret.json'))
+ expect(a).not.toBe(b)
+ expect(a).toContain(`.${process.pid}.`)
+ expect(b).toContain(`.${process.pid}.`)
+
+ const sameNamespace = { pid: 1, sequence: 1 }
+ const defaultUuidA = tempNameFor(join(dir, 'secret.json'), sameNamespace)
+ const defaultUuidB = tempNameFor(join(dir, 'secret.json'), sameNamespace)
+ expect(defaultUuidA).not.toBe(defaultUuidB)
+ const containerA = tempNameFor(join(dir, 'secret.json'), {
+ ...sameNamespace,
+ uuid: () => 'uuid-a'
+ })
+ const containerB = tempNameFor(join(dir, 'secret.json'), {
+ ...sameNamespace,
+ uuid: () => 'uuid-b'
+ })
+ expect(containerA).not.toBe(containerB)
+ expect(containerA).toContain('.1.1.uuid-a.tmp')
+ expect(containerB).toContain('.1.1.uuid-b.tmp')
+ now.mockRestore()
+ })
+
+ it('keeps every fresh temp, even when its owner is already dead', async () => {
+ const target = join(dir, 'secret.json')
+ const legacy = `${target}.tmp`
+ const foreign = `${target}.4242.1.tmp`
+ await Promise.all([fs.writeFile(legacy, 'legacy'), fs.writeFile(foreign, 'foreign')])
+ const writtenAt = Math.min((await fs.lstat(legacy)).mtimeMs, (await fs.lstat(foreign)).mtimeMs)
+
+ await sweepStaleTempFiles(target, {
+ now: writtenAt + STALE_TEMP_AGE_MS - 1
+ })
+
+ expect((await fs.readdir(dir)).sort()).toEqual(['secret.json.4242.1.tmp', 'secret.json.tmp'])
+ })
+
+ it('removes only an aged ownerless legacy temp and preserves every PID-bearing shape', async () => {
+ const target = join(dir, 'secret.json')
+ const legacy = `${target}.tmp`
+ const priorPidShape = `${target}.1111.1.tmp`
+ const current = `${target}.2222.2.22222222-2222-4222-8222-222222222222.tmp`
+ const ours = `${target}.${process.pid}.3.33333333-3333-4333-8333-333333333333.tmp`
+ const unknown = `${target}.not-an-owner.tmp`
+ const unrelated = join(dir, 'other-file!.tmp') // same basename length as secret.json
+ await Promise.all(
+ [legacy, priorPidShape, current, ours, unknown, unrelated].map((file) => fs.writeFile(file, file))
+ )
+ const writtenAt = Math.max(
+ ...(await Promise.all(
+ [legacy, priorPidShape, current, ours, unknown, unrelated].map((file) => fs.lstat(file))
+ ))
+ .map((stat) => stat.mtimeMs)
+ )
+
+ await sweepStaleTempFiles(target, { now: writtenAt + STALE_TEMP_AGE_MS })
+
+ expect((await fs.readdir(dir)).sort()).toEqual([
+ `secret.json.${process.pid}.3.33333333-3333-4333-8333-333333333333.tmp`,
+ 'other-file!.tmp',
+ 'secret.json.1111.1.tmp',
+ 'secret.json.2222.2.22222222-2222-4222-8222-222222222222.tmp',
+ 'secret.json.not-an-owner.tmp'
+ ].sort())
+ })
+
+ it('does not use namespace-local signal zero to judge an aged PID-bearing temp', async () => {
+ const target = join(dir, 'secret.json')
+ const foreign = `${target}.3333.1.11111111-1111-4111-8111-111111111111.tmp`
+ await fs.writeFile(foreign, 'foreign')
+ const writtenAt = (await fs.lstat(foreign)).mtimeMs
+ const kill = vi.spyOn(process, 'kill').mockImplementation(() => {
+ throw errWithCode('ESRCH')
+ })
+
+ await sweepStaleTempFiles(target, { now: writtenAt + STALE_TEMP_AGE_MS })
+
+ expect(kill).not.toHaveBeenCalled()
+ expect(await fs.readFile(foreign, 'utf8')).toBe('foreign')
+ })
+})
+
+describe('clearAtomicTarget', () => {
+ it('removes the canonical file but reports a young current temp as retained', async () => {
+ const target = join(dir, 'secret.json')
+ const foreign = `${target}.4242.1.11111111-1111-4111-8111-111111111111.tmp`
+ await Promise.all([fs.writeFile(target, 'canonical'), fs.writeFile(foreign, 'bearer')])
+ const writtenAt = (await fs.lstat(foreign)).mtimeMs
+
+ const result = await clearAtomicTarget(target, {
+ now: writtenAt + STALE_TEMP_AGE_MS - 1
+ })
+
+ expect(result).toEqual({
+ cleared: false,
+ canonicalRemoved: true,
+ retainedTempCount: 1,
+ inspectionComplete: true
+ })
+ await expect(fs.access(target)).rejects.toMatchObject({ code: 'ENOENT' })
+ expect(await fs.readFile(foreign, 'utf8')).toBe('bearer')
+ })
+
+ it('does not delete or bless an aged temp whose owner may be in another PID namespace', async () => {
+ const target = join(dir, 'secret.json')
+ const foreign = `${target}.5151.1.22222222-2222-4222-8222-222222222222.tmp`
+ await fs.writeFile(foreign, 'bearer')
+ const writtenAt = (await fs.lstat(foreign)).mtimeMs
+
+ const result = await clearAtomicTarget(target, { now: writtenAt + STALE_TEMP_AGE_MS })
+
+ expect(result.cleared).toBe(false)
+ expect(result.retainedTempCount).toBe(1)
+ expect(await fs.readFile(foreign, 'utf8')).toBe('bearer')
+ })
+
+ it('reports an aged temp whose deletion failed instead of swallowing the incomplete clear', async () => {
+ const target = join(dir, 'secret.json')
+ const legacy = `${target}.tmp`
+ await fs.writeFile(legacy, 'bearer')
+ const writtenAt = (await fs.lstat(legacy)).mtimeMs
+ const realRm = fs.rm
+ vi.spyOn(fs, 'rm').mockImplementation((async (file: any, options?: any) => {
+ if (String(file) === legacy) throw errWithCode('EACCES')
+ return (realRm as any)(file, options)
+ }) as typeof fs.rm)
+
+ const result = await clearAtomicTarget(target, { now: writtenAt + STALE_TEMP_AGE_MS })
+
+ expect(result.cleared).toBe(false)
+ expect(result.retainedTempCount).toBe(1)
+ expect(await fs.readFile(legacy, 'utf8')).toBe('bearer')
+ })
+
+ it('reports success only after an aged ownerless temp and the canonical file are gone', async () => {
+ const target = join(dir, 'secret.json')
+ const legacy = `${target}.tmp`
+ await Promise.all([fs.writeFile(target, 'canonical'), fs.writeFile(legacy, 'bearer')])
+ const writtenAt = (await fs.lstat(legacy)).mtimeMs
+
+ const result = await clearAtomicTarget(target, { now: writtenAt + STALE_TEMP_AGE_MS })
+
+ expect(result).toEqual({
+ cleared: true,
+ canonicalRemoved: true,
+ retainedTempCount: 0,
+ inspectionComplete: true
+ })
+ expect(await fs.readdir(dir)).toEqual([])
+ })
+
+ it('does not mistake an arbitrary dot-free token for a UUID temp', async () => {
+ const target = join(dir, 'secret.json')
+ const lookalike = `${target}.6262.1.not-a-uuid.tmp`
+ await Promise.all([fs.writeFile(target, 'canonical'), fs.writeFile(lookalike, 'unrelated')])
+
+ const result = await clearAtomicTarget(target)
+
+ expect(result).toEqual({
+ cleared: true,
+ canonicalRemoved: true,
+ retainedTempCount: 0,
+ inspectionComplete: true
+ })
+ expect(await fs.readFile(lookalike, 'utf8')).toBe('unrelated')
+ })
+
+ it('reports a canonical file republished between unlink and inspection as uncleared', async () => {
+ const target = join(dir, 'secret.json')
+ await fs.writeFile(target, 'old')
+ const realReaddir = fs.readdir
+ let reads = 0
+ vi.spyOn(fs, 'readdir').mockImplementation((async (directory: any, options?: any) => {
+ reads++
+ // First read is the conservative sweep; second is the post-unlink completeness scan.
+ if (reads === 2) await fs.writeFile(target, 'republished')
+ return (realReaddir as any)(directory, options)
+ }) as typeof fs.readdir)
+
+ const result = await clearAtomicTarget(target)
+
+ expect(result.cleared).toBe(false)
+ expect(result.canonicalRemoved).toBe(false)
+ expect(result.retainedTempCount).toBe(0)
+ expect(await fs.readFile(target, 'utf8')).toBe('republished')
+ })
+})
diff --git a/src/core/fs-atomic.ts b/src/core/fs-atomic.ts
new file mode 100644
index 000000000..af8c4dd8c
--- /dev/null
+++ b/src/core/fs-atomic.ts
@@ -0,0 +1,354 @@
+// Atomic file writes that survive Windows.
+//
+// Every store in this app persists the same way: write a temp file, then rename it over the
+// target, so a reader sees either the old bytes or the new ones and never a half-written file.
+// That is correct on POSIX, where `rename(2)` is atomic and replaces the destination
+// unconditionally.
+//
+// It is NOT sufficient on Windows, and the difference is quiet. `MoveFileEx` fails with a sharing
+// violation — surfacing through Node as `EPERM` (sometimes `EACCES`/`EBUSY`) — whenever the
+// DESTINATION is open by anyone at that instant. Not held open for long: opened. The usual
+// culprits are not exotic:
+//
+// - Windows Defender's real-time scanner opens each file we just wrote, to scan it;
+// - the search indexer does the same;
+// - a backup or sync client (OneDrive over a user profile, very common) holds a read handle;
+// - two of our own concurrent writers race their renames onto one destination.
+//
+// The last one was reproducible on demand and exposed this: the approved-devices store originally
+// had three un-queued writers, and its old overlapping-save test failed on Windows with
+// `EPERM: operation not permitted, rename`. The store now also serializes its read-modify-write
+// decisions, but retrying rename remains required for scanners/indexers and independent processes.
+//
+// The consequence is worse than a failed save. These are the stores holding the user's canvas
+// layout, their settings, their pinned remote devices and their sealed credentials. On Windows a
+// scanner touching the file at the wrong millisecond turned a routine save into a thrown error,
+// and the save was simply lost — intermittently, unreproducibly, and more often on exactly the
+// machines that are most protected.
+//
+// One file already knew. `src/core/github/cache.ts` carried a full write-up of this — naming
+// EPERM, naming NTFS, and citing a direct measurement: "two concurrent writers to one path failed
+// with EPERM in roughly 3 of 5 runs on this host" — and had its own bounded retry loop. It had had
+// it for some time. The knowledge sat in that one file and reached none of the other twenty-odd
+// stores doing the identical thing a few directories away, because a comment cannot propagate and
+// nothing scanned for the pattern. That is the argument for the guard test beside this file rather
+// than for another comment: a written explanation protects the file it is written in.
+//
+// The fix is the standard one: retry the rename briefly. Each attempt is still a single atomic
+// rename, so retrying cannot tear a write — it only tries the same indivisible operation again
+// once whoever held the destination has let go. The window these scanners hold is milliseconds.
+//
+// What this deliberately does NOT do:
+// - It does not retry forever. A genuinely locked file must fail, and fail loudly: several
+// callers (revocation.ts's `persisted:false`, for one) have contracts that depend on a failed
+// save being reported as a failed save.
+// - It does not retry every error. `ENOENT` means the temp file is gone, which is a bug in the
+// caller, and retrying only delays a clearer error. `ENOSPC` will not improve by waiting.
+// - It does not swallow the final failure. The last error is thrown with its original code.
+
+import { promises as fs, renameSync } from 'fs'
+import { randomUUID } from 'crypto'
+import path from 'path'
+
+/**
+ * Errors that mean "someone else has the destination open right now", rather than "this will
+ * never work". Windows reports a sharing violation as EPERM most often, EACCES and EBUSY
+ * occasionally, depending on which layer refused.
+ */
+const TRANSIENT = new Set(['EPERM', 'EACCES', 'EBUSY'])
+
+/** Backoff between rename attempts, in ms. Five tries over ~310 ms total.
+ *
+ * Sized against what actually holds the file: an antivirus or indexer scan of a small JSON file
+ * finishes in single-digit milliseconds, so the first retry usually wins. The long tail exists
+ * for a sync client mid-upload. It stays under a third of a second because these calls sit
+ * behind user actions — a save that blocks for seconds is its own defect. */
+const RETRY_DELAYS_MS = [10, 25, 75, 200]
+
+function codeOf(e: unknown): string {
+ return typeof e === 'object' && e && 'code' in e ? String((e as { code: unknown }).code) : ''
+}
+
+const sleep = (ms: number): Promise<void> => new Promise((r) => setTimeout(r, ms))
+
+/**
+ * Rename `tmp` over `target`, retrying briefly if the destination is momentarily held open.
+ *
+ * Use this instead of `fs.rename` for every temp-then-publish write. The retry is a no-op on
+ * POSIX, where these codes do not arise from this operation, so there is no reason to branch on
+ * platform — and branching would mean the behaviour under test on a developer's Mac was not the
+ * behaviour shipped to a user on Windows.
+ */
+export async function renameAtomic(tmp: string, target: string): Promise<void> {
+ for (let attempt = 0; ; attempt++) {
+ try {
+ await fs.rename(tmp, target)
+ return
+ } catch (e) {
+ // Out of attempts, or an error waiting will not fix: give the caller the real error, with
+ // its original code, so `persisted:false` contracts and error messages stay accurate.
+ if (attempt >= RETRY_DELAYS_MS.length || !TRANSIENT.has(codeOf(e))) throw e
+ await sleep(RETRY_DELAYS_MS[attempt])
+ }
+ }
+}
+
+/**
+ * The synchronous twin, for the paths that cannot be async: hook installers that run during
+ * startup, the codex trust-hash write, the per-node token file. Same retry, same codes, same
+ * refusal to loop forever.
+ *
+ * It blocks the thread while it waits, which is the honest cost of a synchronous API and the
+ * reason the budget is the same ~310 ms rather than something more generous. `Atomics.wait` is a
+ * real sleep rather than a spin, so the wait does not also burn a core — Node permits it on the
+ * main thread (browsers do not).
+ *
+ * `rename` is a parameter only because a spy cannot be attached to an ESM namespace export, so a
+ * test has no other way to make this fail on a platform where it does not. Production never
+ * passes it. Injecting it here rather than exporting a mutable hook keeps the seam typed and
+ * visible, and keeps every other caller exercising the real default.
+ */
+export function renameAtomicSync(
+ tmp: string,
+ target: string,
+ rename: (from: string, to: string) => void = renameSync
+): void {
+ for (let attempt = 0; ; attempt++) {
+ try {
+ rename(tmp, target)
+ return
+ } catch (e) {
+ if (attempt >= RETRY_DELAYS_MS.length || !TRANSIENT.has(codeOf(e))) throw e
+ Atomics.wait(SLEEP_SLOT, 0, 0, RETRY_DELAYS_MS[attempt])
+ }
+ }
+}
+
+/** A slot that is never written, so `Atomics.wait` always waits out its full timeout. */
+const SLEEP_SLOT = new Int32Array(new SharedArrayBuffer(4))
+
+/**
+ * Minimum age before a startup/save sweep may consider temp litter abandoned.
+ *
+ * The grace is intentionally long. PID-bearing temps are never collected automatically because
+ * local process liveness says nothing reliable about a writer in another PID namespace. The age
+ * applies only to the historical ownerless `<target>.tmp` shape.
+ */
+export const STALE_TEMP_AGE_MS = 24 * 60 * 60 * 1000
+
+export interface SweepStaleTempOptions {
+ /** Test seam; production uses the wall clock. */
+ now?: number
+}
+
+interface AtomicTempCandidate {
+ ownerPid?: number
+}
+
+/** Recognize only the temp formats this module has actually published. Prefix checking is part of
+ * the decision: two unrelated basenames can have the same length, and slicing first made one
+ * store's sweeper mistake the other's file for its own. */
+function atomicTempCandidate(base: string, entry: string): AtomicTempCandidate | null {
+ if (!entry.startsWith(base)) return null
+ const suffix = entry.slice(base.length)
+ if (suffix === '.tmp') return {}
+ // Accept the historical pid+sequence name and ONLY the canonical v4 UUID shape emitted now.
+ // A broad "anything without a dot" token made unrelated lookalikes part of cleanup policy.
+ const owned = /^\.(\d+)\.\d+(?:\.[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12})?\.tmp$/.exec(suffix)
+ return owned ? { ownerPid: Number(owned[1]) } : null
+}
+
+/**
+ * Best-effort collection of abandoned temp files next to `target`.
+ *
+ * Current temp names are `<target>.<pid>.<seq>.<uuid>.tmp`; the prior pid+sequence form is also
+ * recognized during upgrades. A different pid is NOT proof that a writer died: desktop
+ * multi-instance mode and two Server Edition processes may deliberately share a data directory.
+ * A pid-bearing temp is never removed automatically. Signal-0/ESRCH is namespace-local, so it
+ * cannot prove that a writer on a shared Docker/Server volume is dead; PID reuse makes the inverse
+ * equally unreliable. Credential Clear reports such a temp as incomplete instead. The legacy
+ * fixed `<target>.tmp` name has no owner or UUID and predates cross-process-safe writers, so the
+ * long age grace is the only evidence available for collecting that one exact shape.
+ *
+ * Unknown temp-name shapes are left alone. Every current writer removes its own temp on failure;
+ * this sweep exists only for process death and must never recreate the writer-vs-sweeper race that
+ * unique names fixed.
+ */
+export async function sweepStaleTempFiles(
+ target: string,
+ opts: SweepStaleTempOptions = {}
+): Promise<void> {
+ const now = opts.now ?? Date.now()
+ try {
+ const directory = path.dirname(target)
+ const base = path.basename(target)
+ for (const entry of await fs.readdir(directory)) {
+ const candidate = atomicTempCandidate(base, entry)
+ if (!candidate) continue
+
+ const temp = path.join(directory, entry)
+ let mtimeMs: number
+ try {
+ mtimeMs = (await fs.lstat(temp)).mtimeMs
+ } catch {
+ continue
+ }
+ if (!Number.isFinite(mtimeMs) || now - mtimeMs < STALE_TEMP_AGE_MS) continue
+
+ // Foreign ownership cannot be proved dead across PID namespaces; fail conservative.
+ if (candidate.ownerPid !== undefined) continue
+ await fs.rm(temp, { force: true }).catch(() => undefined)
+ }
+ } catch {
+ // A directory we cannot read is not a reason to fail the load/save that requested the sweep.
+ }
+}
+
+/**
+ * Delete `target`, retrying the same transient Windows codes, and treating "already gone" as
+ * success. Returns false if it is still there afterwards.
+ *
+ * Deleting has the identical Windows hazard as renaming — a scanner or sync client holding the
+ * file open makes `unlink` fail with `EPERM` — but it usually matters less, because a failed
+ * delete leaves litter and says so, where a failed rename lost the write silently.
+ *
+ * The case it matters for is a delete whose PURPOSE is to stop something happening. Removing the
+ * relay advertisement is one: it exists so phones stop minting tokens against a host that will
+ * never answer, so a delete that quietly fails leaves the user's "phone access off" unenforced.
+ *
+ * The trap this closes is not the retry, it is the reporting. Such a delete is normally written
+ * as an unlink wrapped in a bare catch commented "already absent", which is correct for the
+ * failure the author had in mind and wrong for every other one: ENOENT really is fine, and EPERM
+ * means the file is still sitting there. Only ENOENT counts as gone here.
+ */
+export async function removeAtomic(target: string): Promise<boolean> {
+ for (let attempt = 0; ; attempt++) {
+ try {
+ await fs.unlink(target)
+ return true
+ } catch (e) {
+ const code = codeOf(e)
+ if (code === 'ENOENT') return true // genuinely absent — the caller's goal is met
+ if (attempt >= RETRY_DELAYS_MS.length || !TRANSIENT.has(code)) return false
+ await sleep(RETRY_DELAYS_MS[attempt])
+ }
+ }
+}
+
+/** The counter keeps names readable and ordered within this module instance. It is not the unique
+ * dimension: workers and separate PID namespaces can share a pid and start their counters at 1. */
+let writeSeq = 0
+
+export interface TempNameOptions {
+ /** Deterministic seams for behavior tests that model separate PID namespaces/module instances. */
+ pid?: number
+ sequence?: number
+ uuid?: () => string
+}
+
+export interface ClearAtomicTargetResult {
+ /** True only when the canonical path is absent and no recognized publication temp remains. */
+ cleared: boolean
+ /** Whether the canonical path was removed (or was already absent). */
+ canonicalRemoved: boolean
+ /** Recognized legacy/current temps retained because they may be live or could not be removed. */
+ retainedTempCount: number
+ /** False when the parent directory could not be inspected, so absence cannot be claimed. */
+ inspectionComplete: boolean
+}
+
+/**
+ * Remove an atomic target without claiming a credential clear that did not actually finish.
+ *
+ * The ordinary sweep remains conservative: a pid-bearing temp may be a live writer in another PID
+ * namespace at any age and must not be deleted merely because signal 0 reports ESRCH here. Clear removes
+ * the canonical file, then reports every recognized temp still present. Callers can surface an
+ * explicit incomplete-clear error instead of telling the UI that a PAT/cookie is gone while its
+ * bearer bytes remain next door. This is a point-in-time result, not a cross-process lock; a
+ * foreign writer that publishes after the inspection still has last-publisher semantics.
+ */
+export async function clearAtomicTarget(
+ target: string,
+ opts: SweepStaleTempOptions = {}
+): Promise<ClearAtomicTargetResult> {
+ await sweepStaleTempFiles(target, opts)
+ const removeSucceeded = await removeAtomic(target)
+ const directory = path.dirname(target)
+ const base = path.basename(target)
+ let retainedTempCount = 0
+ let inspectionComplete = true
+ try {
+ const entries = await fs.readdir(directory)
+ retainedTempCount = entries.filter((entry) => atomicTempCandidate(base, entry) !== null).length
+ } catch (error) {
+ if (codeOf(error) !== 'ENOENT') inspectionComplete = false
+ }
+ // A foreign writer can rename its temp onto the canonical path after our unlink and before the
+ // directory scan. Temp-count zero is therefore not enough: recheck the destination last so this
+ // point-in-time result cannot report success over a credential that has already reappeared.
+ let canonicalAbsent = removeSucceeded
+ if (canonicalAbsent) {
+ try {
+ await fs.lstat(target)
+ canonicalAbsent = false
+ } catch (error) {
+ if (codeOf(error) !== 'ENOENT') canonicalAbsent = false
+ }
+ }
+ return {
+ cleared: canonicalAbsent && inspectionComplete && retainedTempCount === 0,
+ canonicalRemoved: canonicalAbsent,
+ retainedTempCount,
+ inspectionComplete
+ }
+}
+
+/**
+ * A temp path for publishing over `target`, unique per call.
+ *
+ * The second bug that lives at every temp-then-rename site, independent of the platform question
+ * above: a **fixed** name (always `<file>.tmp`). Two writers then share one temp path, so one
+ * writer's rename publishes the other's half-written bytes — or moves the temp out from under it,
+ * and the loser fails with a confusing `ENOENT` that says nothing about what actually happened.
+ *
+ * The UUID is the uniqueness guarantee. PID plus a module counter is useful ownership/diagnostic
+ * metadata, but is not globally unique: two containers can both be PID 1, worker isolates share a
+ * PID while loading separate module counters, and an OS can reuse a PID after crash litter remains.
+ *
+ * The cost of uniqueness is that a temp never self-heals the way a fixed one did, where the next
+ * save simply overwrote the litter. Every caller therefore owes its own cleanup on failure —
+ * `writeFileAtomic` does it for you, and a site that builds its own sequence must do it by hand.
+ */
+export function tempNameFor(target: string, opts: TempNameOptions = {}): string {
+ const pid = opts.pid ?? process.pid
+ const sequence = opts.sequence ?? ++writeSeq
+ const uuid = opts.uuid ?? randomUUID
+ return `${target}.${pid}.${sequence}.${uuid()}.tmp`
+}
+
+/**
+ * Write `data` to `target` atomically: unique temp file, then a retrying rename.
+ *
+ * The temp name is unique per call, which matters wherever more than one writer can reach a store
+ * with nothing queueing them. With one shared `<file>.tmp`, a writer's rename publishes the
+ * other's half-written bytes — or moves the temp out from under it, so the loser's rename fails
+ * with a confusing ENOENT.
+ *
+ * A failed write removes its own temp (a unique name never self-heals the way a fixed one did,
+ * where the next save simply reused it) and rethrows. The OLD file is left byte-for-byte intact
+ * either way, which is the half callers depend on when they report a save as not persisted.
+ */
+export async function writeFileAtomic(
+ target: string,
+ data: string,
+ opts: { mode?: number } = {}
+): Promise<void> {
+ const tmp = tempNameFor(target)
+ try {
+ await fs.writeFile(tmp, data, { encoding: 'utf-8', ...opts })
+ await renameAtomic(tmp, target)
+ } catch (e) {
+ await fs.rm(tmp, { force: true }).catch(() => {})
+ throw e
+ }
+}
diff --git a/src/core/github/cache.ts b/src/core/github/cache.ts
index 0b0630bbf..ebdd70de5 100644
--- a/src/core/github/cache.ts
+++ b/src/core/github/cache.ts
@@ -2,6 +2,7 @@ import { createHash } from 'node:crypto'
import { promises as fs } from 'node:fs'
import path from 'node:path'
import type { GitHubIssue } from '../../shared/github-issues'
+import { renameAtomic, tempNameFor } from '../fs-atomic'
import { parseGitHubRepository } from './config'
const DIRECTORY = 'github-issues-cache'
@@ -33,11 +34,6 @@ export class GitHubCacheError extends Error {
}
}
-/** Paired with `process.pid` in the temp name in `writePrivate`: the counter makes a name unique
- * WITHIN this process, the pid makes it unique ACROSS processes (it restarts at 0 in every new
- * one). Same scheme as agent-status-mirror's local write. */
-let writeSeq = 0
-
function safeInteger(value: unknown): value is number {
return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0
}
@@ -248,20 +244,20 @@ export class GitHubIssueCache {
private async writePrivate(file: string, content: string): Promise<void> {
await fs.mkdir(path.dirname(file), { recursive: true })
- // The temp name is unique per call because two writers reach the same `<digest>.json` from
+ // The temp name must be unique per call because two writers reach the same `<digest>.json` from
// different serialization domains: src/core/github/service.ts serializes mutations per
// `${projectId}:${issueNumber}` (mutationChain) but single-flights refreshes per repository, so
// a mutation's `saveComplete` and a refresh's `saveComplete` for one (userId, repository) are
// ordered by nothing at all. Binding writes are looser still — `prepareState` runs under
- // `statePreparations`, a Set that admits several at once, and they share a binding file. With a
- // shared name one writer's rename publishes the other's half-written document, or moves the
- // file out from under it entirely and the loser's rename fails. The pid covers the other
- // direction: two processes on one data dir have no lock, and their counters both start at 0.
- const temporary = `${file}.${process.pid}.${++writeSeq}.tmp`
+ // `statePreparations`, a Set that admits several at once, and they share a binding file.
+ // tempNameFor + renameAtomic (core/fs-atomic.ts) carry both halves of the fix: a collision-proof
+ // name, and the bounded retry for Windows sharing violations — see fs-atomic.ts for the account
+ // this file's original write-up became.
+ const temporary = tempNameFor(file)
try {
await fs.writeFile(temporary, content, { encoding: 'utf-8', mode: 0o600 })
await fs.chmod(temporary, 0o600)
- await fs.rename(temporary, file)
+ await renameAtomic(temporary, file)
} catch (error) {
// A unique name never self-heals the way the fixed one did (the next write just reused it),
// so a failed write has to remove its own temp — the more so as the two mutation saves in
diff --git a/src/core/github/control-store.ts b/src/core/github/control-store.ts
index 2a605dafe..98dd69ea1 100644
--- a/src/core/github/control-store.ts
+++ b/src/core/github/control-store.ts
@@ -5,6 +5,7 @@ import type {
GitHubControlState,
GitHubProjectApproval
} from '../../shared/github-issues'
+import { renameAtomic, tempNameFor } from '../fs-atomic'
import { parseGitHubRepository } from './config'
const FILE_NAME = 'github-issues-control.json'
@@ -155,15 +156,20 @@ export class GitHubControlStore {
private async write(state: GitHubControlState): Promise<void> {
await fs.mkdir(this.userDataDir, { recursive: true })
- // The fixed temp name is safe only because there is exactly ONE store instance per data dir and
- // every write reaches here through THAT instance's mutate() writeQueue. A second instance on the
- // same dir, or a caller that skips the queue, needs a unique `<file>.<pid>.<seq>.tmp` name (see
- // workspace-store's writeAtomic) — otherwise two writers share this one temp and one rename
- // publishes the other's half-written bytes.
- const temporary = `${this.filePath}.tmp`
- await fs.writeFile(temporary, JSON.stringify(state), { encoding: 'utf-8', mode: 0o600 })
- await fs.chmod(temporary, 0o600)
- await fs.rename(temporary, this.filePath)
+ // Unique temp + retrying rename (core/fs-atomic.ts). mutate()'s writeQueue serializes writes
+ // WITHIN this instance, but a second instance on the same data dir (Server Edition --data-dir)
+ // shares nothing with it — the fixed `<file>.tmp` name this used to carry let two such writers
+ // publish each other's half-written bytes. The unique name never self-heals, so a failed write
+ // removes its own temp before rethrowing.
+ const temporary = tempNameFor(this.filePath)
+ try {
+ await fs.writeFile(temporary, JSON.stringify(state), { encoding: 'utf-8', mode: 0o600 })
+ await fs.chmod(temporary, 0o600)
+ await renameAtomic(temporary, this.filePath)
+ } catch (error) {
+ await fs.rm(temporary, { force: true }).catch(() => {})
+ throw error
+ }
await fs.chmod(this.filePath, 0o600)
}
}
diff --git a/src/core/scrollback-store.ts b/src/core/scrollback-store.ts
index 13fa83a60..5d86f0a0f 100644
--- a/src/core/scrollback-store.ts
+++ b/src/core/scrollback-store.ts
@@ -1,6 +1,7 @@
import fs from 'fs'
import path from 'path'
import { createHash } from 'crypto'
+import { renameAtomic, tempNameFor } from './fs-atomic'
import { platform } from './platform'
// On a machine reboot the tmux server dies, so the live scrollback is lost. We persist a
@@ -37,17 +38,16 @@ function trailing(data: string): Buffer {
// All async (fs.promises): snapshots fire per session on a 15s timer and in bursts when many
// nodes detach at once (project switch / quit) — sync writes here blocked the main event loop,
// which stalls PTY streaming and all IPC.
-let writeSeq = 0
export async function writeScrollback(persistKey: string, data: string): Promise<void> {
if (!data) return
const file = snapshotPath(persistKey)
// Unique tmp per call: overlapping writes for the same key (timer tick + detach snapshot)
// must not interleave into one tmp file and rename a torn write into place.
- const tmp = `${file}.${++writeSeq}.tmp`
+ const tmp = tempNameFor(file)
try {
await fs.promises.mkdir(dir(), { recursive: true })
await fs.promises.writeFile(tmp, trailing(data))
- await fs.promises.rename(tmp, file)
+ await renameAtomic(tmp, file)
} catch {
// best-effort: a failed snapshot just means no cold-restore replay for this node
await fs.promises.rm(tmp, { force: true }).catch(() => {})
diff --git a/src/core/settings-store.ts b/src/core/settings-store.ts
index 3b0598e11..25e48fac3 100644
--- a/src/core/settings-store.ts
+++ b/src/core/settings-store.ts
@@ -1,5 +1,6 @@
-import { promises as fs, readFileSync } from "fs";
+import { readFileSync } from "fs";
import path from "path";
+import { writeFileAtomic } from "./fs-atomic";
import { IPC } from "../shared/ipc";
import { platform } from "./platform";
import { DEFAULT_SETTINGS, type Settings } from "../shared/types";
@@ -35,11 +36,6 @@ function mergeSettings(saved: Partial<Settings> | null | undefined): Settings {
return merged;
}
-/** Paired with `process.pid` in the temp name below: the counter makes a name unique WITHIN this
- * process, the pid makes it unique ACROSS processes (it restarts at 0 in every new one). Same
- * scheme as agent-status-mirror's local write. */
-let writeSeq = 0;
-
/**
* Stores user settings in settings.json. Keeps a synchronous cache so the PtyManager
* can read shell/tmux preferences immediately at terminal creation.
@@ -104,30 +100,16 @@ export class SettingsStore {
// (src/renderer/state/settings.ts); on the Server Edition every WS frame is dispatched
// concurrently (src/server/ws.ts), so even one browser tab can have two saves in the air.
// With a shared name, one writer's rename publishes the other's half-written bytes, or moves
- // the file out from under it entirely. The pid covers the other direction: two
- // `nodeterm-server --data-dir X` processes share the dir with no lock, and their counters
- // both start at 0.
- const tmp = `${this.filePath}.${process.pid}.${++writeSeq}.tmp`;
- try {
- // 0600 at open(2), before any bytes land, and the rename carries it onto settings.json.
- // Two reasons: the temp name is predictable (`<file>.<pid>.<seq>.tmp`), so a same-uid
- // process could pre-create it as a symlink for this write to follow; and every other
- // writer in this family already creates owner-only — this one was the outlier, which is
- // exactly what CodeQL's js/insecure-temporary-file was pointing at.
- await fs.writeFile(tmp, JSON.stringify(this.cache, null, 2), {
- encoding: "utf-8",
- mode: 0o600,
- });
- await fs.rename(tmp, this.filePath);
- } catch (e) {
- // A unique name never self-heals the way the fixed one did (the next save just reused it),
- // so a failed write has to remove its own temp. The error still propagates, so a failed
- // save stays a failed save — and the listeners below still only run on success. There is
- // deliberately no sweep of orphans from killed processes as provider-cookie does: an
- // orphaned settings temp is config litter, not a live credential.
- await fs.rm(tmp, { force: true }).catch(() => {});
- throw e;
- }
+ // the file out from under it entirely. writeFileAtomic covers all of it: a per-call unique
+ // temp, 0600 at open(2) before any bytes land (the rename carries it onto settings.json —
+ // CodeQL's js/insecure-temporary-file flagged the old default-mode outlier here), a rename
+ // that retries Windows sharing violations, and temp cleanup on failure. The error still
+ // propagates, so a failed save stays a failed save — and the listeners below still only run
+ // on success. There is deliberately no sweep of orphans from killed processes as
+ // provider-cookie does: an orphaned settings temp is config litter, not a live credential.
+ await writeFileAtomic(this.filePath, JSON.stringify(this.cache, null, 2), {
+ mode: 0o600,
+ });
for (const cb of this.listeners) {
try {
cb(this.cache);
diff --git a/src/core/speech/whisper-models.ts b/src/core/speech/whisper-models.ts
index 97a1f62ac..5f1b9a691 100644
--- a/src/core/speech/whisper-models.ts
+++ b/src/core/speech/whisper-models.ts
@@ -1,6 +1,7 @@
import { createWriteStream } from 'node:fs'
-import { mkdir, readdir, rename, rm, stat } from 'node:fs/promises'
+import { mkdir, readdir, rm, stat } from 'node:fs/promises'
import { join } from 'node:path'
+import { renameAtomic } from '../fs-atomic'
import { Writable } from 'node:stream'
import { WHISPER_DOWNLOAD_BASE, WHISPER_MODELS, whisperModel } from '../../shared/speech'
@@ -98,7 +99,7 @@ export class WhisperModelStore {
}
await writer.close()
if (abort.signal.aborted) throw new Error('download cancelled')
- await rename(partPath, this.modelPath(id))
+ await renameAtomic(partPath, this.modelPath(id))
this.onProgress?.(id, 100)
} catch (err) {
sink.destroy()
diff --git a/src/core/usage/provider-cookie.ts b/src/core/usage/provider-cookie.ts
index c5be2a7c2..21bc960c2 100644
--- a/src/core/usage/provider-cookie.ts
+++ b/src/core/usage/provider-cookie.ts
@@ -16,6 +16,7 @@
// still found.
import { promises as fs } from 'fs'
import path from 'path'
+import { renameAtomic, tempNameFor } from '../fs-atomic'
import { platform } from '../platform'
/** Owner read/write only. The whole reason these are separate files. */
@@ -44,16 +45,10 @@ export async function readProviderCookie(provider: CookieProvider): Promise<stri
}
}
-/** Paired with `process.pid` in the temp name: the counter makes a name unique WITHIN this process,
- * the pid makes it unique ACROSS processes (it restarts at 0 in every new one — two
- * `nodeterm-server --data-dir X` processes share the dir with no lock). Same scheme as
- * agent-status-mirror's local write. */
-let writeSeq = 0
-
/**
* Remove temp files no writer in THIS process owns: the legacy fixed `<file>.tmp` (written by
- * builds before per-call names) and any `<file>.<pid>.<seq>.tmp` whose pid is not ours. Best
- * effort — a failure here must never break a save.
+ * builds before per-call names) and any `<file>.<pid>.<seq>[.<uuid>].tmp` whose pid is not ours.
+ * Best effort — a failure here must never break a save.
*
* Unlike settings.json, an orphan here is a live credential at 0600 that nothing will ever
* overwrite, so it has to be collected rather than left. Temps bearing our own pid are untouchable:
@@ -69,8 +64,8 @@ async function sweepStaleTmp(target: string): Promise<void> {
const base = path.basename(target)
for (const entry of await fs.readdir(dir)) {
if (!entry.startsWith(base) || !entry.endsWith('.tmp')) continue
- const middle = entry.slice(base.length, -'.tmp'.length) // '' or '.<pid>.<seq>'
- const owner = /^\.(\d+)\.\d+$/.exec(middle)?.[1]
+ const middle = entry.slice(base.length, -'.tmp'.length) // '' or '.<pid>.<seq>[.<uuid>]'
+ const owner = /^\.(\d+)\.\d+(?:\.[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12})?$/.exec(middle)?.[1]
if (middle === '' || (owner && owner !== String(process.pid))) {
await fs.rm(path.join(dir, entry), { force: true }).catch(() => undefined)
}
@@ -112,10 +107,10 @@ async function writeCookieNow(provider: CookieProvider, cookie: string): Promise
await fs.rm(target, { force: true })
return
}
- const tmp = `${target}.${process.pid}.${++writeSeq}.tmp`
+ const tmp = tempNameFor(target)
try {
await fs.writeFile(tmp, JSON.stringify({ cookie }), { encoding: 'utf-8', mode: MODE })
- await fs.rename(tmp, target)
+ await renameAtomic(tmp, target)
} catch (e) {
// A failed write MUST remove its own temp, because here a leaked temp IS a leaked cookie: a
// unique name is never written again, so only this cleanup (or a later run's sweep above, once
diff --git a/src/core/workspace-store.ts b/src/core/workspace-store.ts
index 8f7971156..c0e4ab5f0 100644
--- a/src/core/workspace-store.ts
+++ b/src/core/workspace-store.ts
@@ -1,6 +1,7 @@
import { promises as fs } from 'fs'
import { randomUUID } from 'node:crypto'
import path from 'path'
+import { renameAtomic, writeFileAtomic } from './fs-atomic'
import { IPC } from '../shared/ipc'
import { platform } from './platform'
import {
@@ -46,35 +47,27 @@ interface LoadedEntry {
file?: ProjectFileV1
}
-let tmpSeq = 0
async function writeAtomic(filePath: string, content: string): Promise<void> {
- // Unique per write: writers that bypass each other's queue (a second app instance, the SSH
+ // Unique temp per write: writers that bypass each other's queue (a second app instance, the SSH
// poll's index write) must never share a tmp file — interleaved writes into one shared tmp
- // published spliced JSON under the atomic rename.
- const tmp = `${filePath}.${process.pid}.${++tmpSeq}.tmp`
- try {
- await fs.writeFile(tmp, content, 'utf-8')
- await fs.rename(tmp, filePath)
- } catch (e) {
- // A unique name never self-heals the way the old fixed one did (the next save just reused
- // it), so a failed write removes its own temp — project.json temps live in the USER'S repo,
- // where litter is visible. The error still propagates; per-file callers swallow it by design.
- await fs.rm(tmp, { force: true }).catch(() => {})
- throw e
- }
+ // published spliced JSON under the atomic rename. writeFileAtomic also removes its own temp on
+ // failure (project.json temps live in the USER'S repo, where litter is visible) and retries the
+ // rename over Windows sharing violations. The error still propagates; per-file callers swallow
+ // it by design.
+ await writeFileAtomic(filePath, content)
}
/** Remove tmp litter next to `target` left by writers that died mid-write: the legacy fixed
- * `<file>.tmp` name and any `<file>.<pid>.<seq>.tmp` from another (dead) pid. Our own pid's
- * temps are in-flight writes and stay. Same family rule as provider-cookie's sweep. */
+ * `<file>.tmp` name and any `<file>.<pid>.<seq>[.<uuid>].tmp` from another (dead) pid. Our own
+ * pid's temps are in-flight writes and stay. Same family rule as provider-cookie's sweep. */
async function sweepStaleTmp(target: string): Promise<void> {
try {
const dir = path.dirname(target)
const base = path.basename(target)
for (const entry of await fs.readdir(dir)) {
if (!entry.startsWith(base) || !entry.endsWith('.tmp')) continue
- const middle = entry.slice(base.length, -'.tmp'.length) // '' or '.<pid>.<seq>'
- const owner = /^\.(\d+)\.\d+$/.exec(middle)?.[1]
+ const middle = entry.slice(base.length, -'.tmp'.length) // '' or '.<pid>.<seq>[.<uuid>]'
+ const owner = /^\.(\d+)\.\d+(?:\.[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12})?$/.exec(middle)?.[1]
if (middle === '' || (owner && owner !== String(process.pid))) {
await fs.rm(path.join(dir, entry), { force: true }).catch(() => undefined)
}
@@ -180,7 +173,7 @@ export class WorkspaceStore {
if (sideline) {
const backup = `${path.basename(this.indexPath)}.corrupt-${Date.now()}`
try {
- await fs.rename(this.indexPath, path.join(platform().userDataDir, backup))
+ await renameAtomic(this.indexPath, path.join(platform().userDataDir, backup))
// Only AFTER the rename succeeded: the note promises a backup exists.
this.noteCorruptIndex(backup)
} catch { /* best effort — never destroy data */ }
@@ -405,7 +398,7 @@ export class WorkspaceStore {
} catch { /* not JSON — sideline below */ }
if (sideline) {
try {
- await fs.rename(file, `${file}.corrupt-${Date.now()}`)
+ await renameAtomic(file, `${file}.corrupt-${Date.now()}`)
} catch { /* best effort — never destroy data */ }
}
return null
diff --git a/src/main/github-control.ts b/src/main/github-control.ts
index 75289683e..1405a5f07 100644
--- a/src/main/github-control.ts
+++ b/src/main/github-control.ts
@@ -1,5 +1,6 @@
import { promises as fs } from 'node:fs'
import path from 'node:path'
+import { renameAtomic, tempNameFor } from '../core/fs-atomic'
import type { GitHubSecretStore } from '../core/github/credentials'
import type { SecretStore } from '../core/secret-store'
import type { GitHubSecretAvailability } from '../shared/github-issues'
@@ -29,17 +30,10 @@ function validToken(token: string): boolean {
return token.trim() === token && token.length > 0 && token.length <= 4096 && !/[\r\n\0]/.test(token)
}
-/** Paired with `process.pid` in the temp name below: the counter makes a name unique WITHIN this
- * process, the pid makes it unique ACROSS processes (it restarts at 0 in every new one — and
- * `NT_MULTI=1` without `NT_USER_DATA` skips the single-instance lock while keeping the default
- * userData dir, so two instances can share this file, see src/main/index.ts). Same scheme as
- * agent-status-mirror's local write. */
-let writeSeq = 0
-
/**
* Remove temp files no writer in THIS process owns: the legacy fixed `<file>.tmp` (written by
- * builds before per-call names) and any `<file>.<pid>.<seq>.tmp` whose pid is not ours. Best
- * effort — a failure here must never break a save.
+ * builds before per-call names) and any `<file>.<pid>.<seq>[.<uuid>].tmp` whose pid is not ours.
+ * Best effort — a failure here must never break a save.
*
* The token file is not config: an orphan here is a live PAT at 0600 that nothing will ever
* overwrite, because a unique name is never written twice. So it has to be collected rather than
@@ -55,8 +49,10 @@ async function sweepStaleTmp(target: string): Promise<void> {
const base = path.basename(target)
for (const entry of await fs.readdir(directory)) {
if (!entry.startsWith(base) || !entry.endsWith('.tmp')) continue
- const middle = entry.slice(base.length, -'.tmp'.length) // '' or '.<pid>.<seq>'
- const owner = /^\.(\d+)\.\d+$/.exec(middle)?.[1]
+ const middle = entry.slice(base.length, -'.tmp'.length) // '' or '.<pid>.<seq>[.<uuid>]'
+ const owner =
+ /^\.(\d+)\.\d+(?:\.[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12})?$/
+ .exec(middle)?.[1]
if (middle === '' || (owner && owner !== String(process.pid))) {
await fs.rm(path.join(directory, entry), { force: true }).catch(() => undefined)
}
@@ -74,11 +70,11 @@ async function atomicWrite(file: string, document: TokenDocument): Promise<void>
// userDataDir (every process's counter starts at 0, hence the pid) and a crash between
// tmp-write and rename. With a shared name one writer's rename publishes the other's
// half-written PAT, or moves the file out from under it entirely and the loser's rename fails.
- const temporary = `${file}.${process.pid}.${++writeSeq}.tmp`
+ const temporary = tempNameFor(file)
try {
await fs.writeFile(temporary, JSON.stringify(document), { encoding: 'utf-8', mode: 0o600 })
await fs.chmod(temporary, 0o600)
- await fs.rename(temporary, file)
+ await renameAtomic(temporary, file)
} catch (error) {
// A failed write MUST remove its own temp, because here a leaked temp IS a leaked PAT: a
// unique name is never written again, so only this cleanup (or a later run's sweep above, once
diff --git a/src/main/pairing-service.ts b/src/main/pairing-service.ts
index a833953b5..f7a40ab9b 100644
--- a/src/main/pairing-service.ts
+++ b/src/main/pairing-service.ts
@@ -35,6 +35,7 @@ import {
type RelayPairingBlock
} from './pairing-core'
import type { DeviceRevokeResult, DeviceRevokeServerOutcome, Settings } from '../shared/types'
+import { renameAtomic, tempNameFor } from '../core/fs-atomic'
import { publicKeyToB64, deriveSharedKey, encrypt, decrypt, type KeyPair } from './remote/e2ee'
import { hostIdFromPublicKeyB64 } from './remote/relay-id'
import { getDeviceId } from '../core/device-id'
@@ -250,15 +251,11 @@ async function readAgentJson(): Promise<Record<string, unknown>> {
}
}
-/** Paired with `process.pid` in the temp names below: the counter makes a name unique WITHIN this
- * process, the pid makes it unique ACROSS processes (it restarts at 0 in every new one). Same
- * scheme as agent-status-mirror's local write (src/core/agent-status-mirror.ts). */
-let writeSeq = 0
-
/**
* Remove agent.json temps no writer in THIS process owns: the legacy fixed `agent.json.tmp`
- * (written by builds from before per-call names) and any `agent.json.<pid>.<seq>.tmp` whose pid is
- * not ours. Best effort — a failure here must never break (or skip) the write that follows.
+ * (written by builds from before per-call names) and any `agent.json.<pid>.<seq>[.<uuid>].tmp`
+ * whose pid is not ours. Best effort — a failure here must never break (or skip) the write that
+ * follows.
*
* agent.json is not config: every device entry carries the `agentToken` bearer the phone presents
* on the host-agent WebSocket, so an orphan is a live credential at 0600 that nothing will ever
@@ -274,8 +271,10 @@ async function sweepStaleAgentTmp(): Promise<void> {
const base = path.basename(AGENT_JSON_PATH)
for (const entry of await fs.readdir(AGENT_DIR)) {
if (!entry.startsWith(base) || !entry.endsWith('.tmp')) continue
- const middle = entry.slice(base.length, -'.tmp'.length) // '' or '.<pid>.<seq>'
- const owner = /^\.(\d+)\.\d+$/.exec(middle)?.[1]
+ const middle = entry.slice(base.length, -'.tmp'.length) // '' or '.<pid>.<seq>[.<uuid>]'
+ const owner =
+ /^\.(\d+)\.\d+(?:\.[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12})?$/
+ .exec(middle)?.[1]
if (middle === '' || (owner && owner !== String(process.pid))) {
await fs.rm(path.join(AGENT_DIR, entry), { force: true }).catch(() => undefined)
}
@@ -390,20 +389,19 @@ export function createPairingService(relayDeps?: PairingRelayDeps): PairingServi
* Lives INSIDE the factory, below `serialize`, so no code path outside this closure can reach
* it unchained — the same by-construction guarantee as GitHubControlStore's private write().
* Overlapping entry points (the pairing POST, renderer revokes) are ordered by the chain; the
- * per-call temp name covers the writers the chain cannot see — the host agent is a separate
- * PROCESS writing this same ~/.nodeterm (`writeSeq` stays module-level so a second service
- * instance in THIS process keeps counting instead of restarting into colliding names), and a
- * crash between tmp-write and rename.
+ * per-call temp name (`tempNameFor`: pid + module counter + UUID) covers the writers the chain
+ * cannot see — the host agent is a separate PROCESS writing this same ~/.nodeterm, a second
+ * service instance in THIS process, and a crash between tmp-write and rename.
*/
async function writeAgentJson(obj: Record<string, unknown>): Promise<void> {
await fs.mkdir(AGENT_DIR, { recursive: true, mode: 0o700 })
await fs.chmod(AGENT_DIR, 0o700).catch(() => {})
await sweepStaleAgentTmp()
- const tmp = `${AGENT_JSON_PATH}.${process.pid}.${++writeSeq}.tmp`
+ const tmp = tempNameFor(AGENT_JSON_PATH)
try {
await fs.writeFile(tmp, JSON.stringify(obj, null, 2) + '\n', { mode: 0o600 })
await fs.chmod(tmp, 0o600).catch(() => {})
- await fs.rename(tmp, AGENT_JSON_PATH)
+ await renameAtomic(tmp, AGENT_JSON_PATH)
} catch (e) {
// A unique name never self-heals the way the fixed one did (the next write just reused it),
// and here a leaked temp IS a leaked credential: only this cleanup — or a later run's sweep,
@@ -438,11 +436,11 @@ export function createPairingService(relayDeps?: PairingRelayDeps): PairingServi
}
const next = filterAuthorizedKeys(content, deviceId)
if (next === content) return
- const tmp = `${AUTH_KEYS_PATH}.${process.pid}.${++writeSeq}.tmp`
+ const tmp = tempNameFor(AUTH_KEYS_PATH)
try {
await fs.writeFile(tmp, next, { mode: 0o600 })
await fs.chmod(tmp, 0o600).catch(() => {})
- await fs.rename(tmp, AUTH_KEYS_PATH)
+ await renameAtomic(tmp, AUTH_KEYS_PATH)
} catch (e) {
// A unique name never self-heals the way the fixed one did (the next write just reused it),
// so a failed write has to remove its own temp — otherwise every failed revoke leaves
diff --git a/src/main/remote-ssh/ssh-project.ts b/src/main/remote-ssh/ssh-project.ts
index 5cf630b76..3bf7065eb 100644
--- a/src/main/remote-ssh/ssh-project.ts
+++ b/src/main/remote-ssh/ssh-project.ts
@@ -7,6 +7,7 @@ import { getMainWindow, sendToMain } from '../main-window'
import { parseLsDirs, posixQuote, quoteRemotePath, remoteTmuxConf, sshHostKey, type SshConnection } from '../../shared/ssh'
import type { DownloadResult, SshPassphraseRequest, SshProjectStatusEvent } from '../../shared/types'
import { candidateName, safeDownloadBasename } from '../../core/download-name'
+import { renameAtomic } from '../../core/fs-atomic'
import { findExecutableSync, shellPathNow } from '../../core/exec-path'
import { isSafeRemoteHome } from '../../core/remote-safety'
import { mediaCachePruneList, remoteMediaCacheName } from '../../core/remote-ssh/media-cache'
@@ -799,7 +800,7 @@ export class SshProjectManager {
await fs.rm(partPath, { recursive: true, force: true }).catch(() => {})
return { ok: false, error: 'The transfer failed. Is the file still there, and readable?' }
}
- await fs.rename(partPath, finalPath)
+ await renameAtomic(partPath, finalPath)
return { ok: true, localPath: finalPath, dir: isDir }
} catch {
return { ok: false, error: 'The download could not be completed.' }
@@ -864,7 +865,7 @@ export class SshProjectManager {
await fs.rm(partPath, { force: true }).catch(() => {})
return { ok: false, error: 'The transfer failed. Is the file still there, and readable?' }
}
- await fs.rename(partPath, dest)
+ await renameAtomic(partPath, dest)
void this.pruneMediaCache(cacheDir, path.basename(dest))
return { ok: true, localPath: dest }
} catch {
diff --git a/src/main/remote/approved-devices.ts b/src/main/remote/approved-devices.ts
index 22cc9f776..fccdd9697 100644
--- a/src/main/remote/approved-devices.ts
+++ b/src/main/remote/approved-devices.ts
@@ -7,6 +7,7 @@
import { promises as fs } from 'fs'
import path from 'path'
import { app } from 'electron'
+import { writeFileAtomic } from '../../core/fs-atomic'
import {
emptyApprovedDevices,
parseApprovedDevices,
@@ -26,13 +27,9 @@ export async function loadApprovedDevices(): Promise<ApprovedDevices> {
}
}
-/** Paired with `process.pid` in the temp name below: the counter makes a name unique WITHIN this
- * process, the pid makes it unique ACROSS processes (it restarts at 0 in every new one). Same
- * scheme as agent-status-mirror's local write (src/core/agent-status-mirror.ts). */
-let writeSeq = 0
-
/**
- * Persist the pinned-device list atomically (temp + rename, 0600).
+ * Persist the pinned-device list atomically (unique temp + retrying rename, 0600) via
+ * `writeFileAtomic`.
*
* The temp name is unique per call because three writers reach this from the main process with
* nothing queueing them: the standing host's fire-and-forget pin on approval (standing-host.ts,
@@ -41,21 +38,13 @@ let writeSeq = 0
* a writer's rename publishes the other's half-written list — or moves the file out from under it,
* so the loser's rename fails.
*
+ * A failed write removes its own temp and rethrows, and the OLD file is left byte-for-byte
+ * intact — revocation.ts's `persisted:false` contract depends on both halves.
+ *
* No orphan sweep here, unlike the PAT stores (src/main/github-control.ts, src/server/github-control.ts)
* or agent.json (src/main/pairing-service.ts): those orphan temps hold live credentials, but these are
* PUBLIC keys, so a stray temp is litter rather than a leak.
*/
export async function saveApprovedDevices(store: ApprovedDevices): Promise<void> {
- const target = file()
- const tmp = `${target}.${process.pid}.${++writeSeq}.tmp`
- try {
- await fs.writeFile(tmp, JSON.stringify(store), { encoding: 'utf-8', mode: 0o600 })
- await fs.rename(tmp, target)
- } catch (e) {
- // A unique name never self-heals the way the fixed one did (the next save just reused it), so a
- // failed write has to remove its own temp. The error still propagates, and the OLD file is left
- // byte-for-byte intact — revocation.ts's `persisted:false` contract depends on both halves.
- await fs.rm(tmp, { force: true }).catch(() => {})
- throw e
- }
+ await writeFileAtomic(file(), JSON.stringify(store), { mode: 0o600 })
}
diff --git a/src/main/remote/relay-advertise.ts b/src/main/remote/relay-advertise.ts
index db74fa76f..19756dc90 100644
--- a/src/main/remote/relay-advertise.ts
+++ b/src/main/remote/relay-advertise.ts
@@ -13,6 +13,7 @@
import { promises as fs } from 'fs'
import os from 'os'
import path from 'path'
+import { removeAtomic, writeFileAtomic } from '../../core/fs-atomic'
const FILE = path.join(os.homedir(), '.nodeterm', 'relay.json')
@@ -28,19 +29,15 @@ export interface RelayAdvertisement {
export async function writeRelayAdvertisement(ad: RelayAdvertisement): Promise<void> {
try {
await fs.mkdir(path.dirname(FILE), { recursive: true, mode: 0o700 })
- const tmp = `${FILE}.tmp`
- await fs.writeFile(tmp, JSON.stringify(ad, null, 2) + '\n', { mode: 0o600 })
- await fs.rename(tmp, FILE)
+ await writeFileAtomic(FILE, JSON.stringify(ad, null, 2) + '\n', { mode: 0o600 })
} catch {
// Advertisement is opportunistic; pairing-time provisioning still works.
}
}
-/** Remove the advertisement (host stopped / toggle off) so phones stop offering adoption. */
+/** Remove the advertisement (host stopped / toggle off) so phones stop offering adoption.
+ * `removeAtomic` retries transient Windows sharing violations and treats "already absent"
+ * (ENOENT) as success; it never throws. */
export async function removeRelayAdvertisement(): Promise<void> {
- try {
- await fs.unlink(FILE)
- } catch {
- // Already absent — fine.
- }
+ await removeAtomic(FILE)
}
diff --git a/src/main/ssh-store.ts b/src/main/ssh-store.ts
index ae023c01e..c70012574 100644
--- a/src/main/ssh-store.ts
+++ b/src/main/ssh-store.ts
@@ -2,6 +2,7 @@ import { promises as fs, readFileSync } from 'fs'
import os from 'os'
import path from 'path'
import { app, ipcMain } from 'electron'
+import { writeFileAtomic } from '../core/fs-atomic'
import { IPC } from '../shared/ipc'
import { parseSshConfig, type ParsedSshHost, type SshServer } from '../shared/ssh'
@@ -12,7 +13,7 @@ import { parseSshConfig, type ParsedSshHost, type SshServer } from '../shared/ss
export class SshStore {
private cache: SshServer[] = []
private readonly path: string
- /** Serializes flushes so concurrent un-awaited saves can't race on the shared temp file. */
+ /** Serializes flushes so concurrent un-awaited saves publish in order. */
private writeChain: Promise<void> = Promise.resolve()
constructor(filePath?: string) {
@@ -45,17 +46,16 @@ export class SshStore {
}
private flush(): Promise<void> {
- // Snapshot the cache now; chain after any in-flight write so the shared temp
- // file is never written/renamed by two flushes at once.
+ // Snapshot the cache now; chain after any in-flight write so flushes from this
+ // instance publish in order, oldest first.
const snapshot = JSON.stringify(this.cache, null, 2)
- const tmp = `${this.path}.tmp`
this.writeChain = this.writeChain
.catch(() => {})
.then(async () => {
// 0o600: this holds the user's SSH host inventory (hosts/users/identity-file paths) —
- // owner read/write only, not world-readable.
- await fs.writeFile(tmp, snapshot, { encoding: 'utf-8', mode: 0o600 })
- await fs.rename(tmp, this.path)
+ // owner read/write only, not world-readable. writeFileAtomic gives each flush its own
+ // temp name and retries the rename over transient Windows sharing violations.
+ await writeFileAtomic(this.path, snapshot, { mode: 0o600 })
})
return this.writeChain
}
diff --git a/src/server/github-control.ts b/src/server/github-control.ts
index b2b49e4a2..e96ded0a2 100644
--- a/src/server/github-control.ts
+++ b/src/server/github-control.ts
@@ -1,5 +1,6 @@
import { promises as fs } from 'node:fs'
import path from 'node:path'
+import { renameAtomic, tempNameFor } from '../core/fs-atomic'
import type { GitHubSecretStore } from '../core/github/credentials'
import type { SecretStore } from '../core/secret-store'
import type { CorePlatform } from '../core/platform'
@@ -18,16 +19,10 @@ function validToken(token: string): boolean {
return token.trim() === token && token.length > 0 && token.length <= 4096 && !/[\r\n\0]/.test(token)
}
-/** Paired with `process.pid` in the temp name below: the counter makes a name unique WITHIN this
- * process, the pid makes it unique ACROSS processes (it restarts at 0 in every new one — two
- * `nodeterm-server --data-dir X` processes share the dir with no lock). Same scheme as
- * agent-status-mirror's local write. */
-let writeSeq = 0
-
/**
* Remove temp files no writer in THIS process owns: the legacy fixed `<file>.tmp` (written by
- * builds before per-call names) and any `<file>.<pid>.<seq>.tmp` whose pid is not ours. Best
- * effort — a failure here must never break a save.
+ * builds before per-call names) and any `<file>.<pid>.<seq>[.<uuid>].tmp` whose pid is not ours.
+ * Best effort — a failure here must never break a save.
*
* The token file is not config: an orphan here is a live PAT at 0600 that nothing will ever
* overwrite, because a unique name is never written twice. So it has to be collected rather than
@@ -43,8 +38,10 @@ async function sweepStaleTmp(target: string): Promise<void> {
const base = path.basename(target)
for (const entry of await fs.readdir(directory)) {
if (!entry.startsWith(base) || !entry.endsWith('.tmp')) continue
- const middle = entry.slice(base.length, -'.tmp'.length) // '' or '.<pid>.<seq>'
- const owner = /^\.(\d+)\.\d+$/.exec(middle)?.[1]
+ const middle = entry.slice(base.length, -'.tmp'.length) // '' or '.<pid>.<seq>[.<uuid>]'
+ const owner =
+ /^\.(\d+)\.\d+(?:\.[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12})?$/
+ .exec(middle)?.[1]
if (middle === '' || (owner && owner !== String(process.pid))) {
await fs.rm(path.join(directory, entry), { force: true }).catch(() => undefined)
}
@@ -92,14 +89,14 @@ export class ServerSecretStore implements SecretStore {
// process on the same dir (every process's counter starts at 0, hence the pid) and a crash
// between tmp-write and rename. With a shared name one writer's rename publishes the other's
// half-written PAT, or moves the file out from under it entirely and the loser's rename fails.
- const temporary = `${this.filePath}.${process.pid}.${++writeSeq}.tmp`
+ const temporary = tempNameFor(this.filePath)
try {
await fs.writeFile(temporary, JSON.stringify({ version: 1, token }), {
encoding: 'utf-8',
mode: 0o600
})
await fs.chmod(temporary, 0o600)
- await fs.rename(temporary, this.filePath)
+ await renameAtomic(temporary, this.filePath)
} catch (error) {
// A failed write MUST remove its own temp, because here a leaked temp IS a leaked PAT: a
// unique name is never written again, so only this cleanup (or a later run's sweep above,