fix(core): add atomicWriteFileSync to prevent truncated files on kill (#1943)

Replaces direct fs.writeFileSync calls for STATE.md, ROADMAP.md, and
config.json with write-to-temp-then-rename so a process killed mid-write
cannot leave an unparseable truncated file. Falls back to direct write if
rename fails (e.g. cross-device). Adds regression tests for the helper.

Closes #1915

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
Tom Boucher
2026-04-07 17:27:20 -04:00
committed by GitHub
parent f6a7b9f497
commit 60fa2936dd
5 changed files with 120 additions and 9 deletions

View File

@@ -4,7 +4,7 @@
const fs = require('fs');
const path = require('path');
const { escapeRegex, loadConfig, getMilestoneInfo, getMilestonePhaseFilter, normalizeMd, planningDir, planningPaths, output, error } = require('./core.cjs');
const { escapeRegex, loadConfig, getMilestoneInfo, getMilestonePhaseFilter, normalizeMd, planningDir, planningPaths, output, error, atomicWriteFileSync } = require('./core.cjs');
const { extractFrontmatter, reconstructFrontmatter } = require('./frontmatter.cjs');
/** Shorthand — every state command needs this path */
@@ -845,7 +845,7 @@ function writeStateMd(statePath, content, cwd) {
const synced = syncStateFrontmatter(content, cwd);
const lockPath = acquireStateLock(statePath);
try {
fs.writeFileSync(statePath, normalizeMd(synced), 'utf-8');
atomicWriteFileSync(statePath, normalizeMd(synced), 'utf-8');
} finally {
releaseStateLock(lockPath);
}
@@ -863,7 +863,7 @@ function readModifyWriteStateMd(statePath, transformFn, cwd) {
const content = fs.existsSync(statePath) ? fs.readFileSync(statePath, 'utf-8') : '';
const modified = transformFn(content);
const synced = syncStateFrontmatter(modified, cwd);
fs.writeFileSync(statePath, normalizeMd(synced), 'utf-8');
atomicWriteFileSync(statePath, normalizeMd(synced), 'utf-8');
} finally {
releaseStateLock(lockPath);
}