Repository navigation
Description
What happened
Two coupled defects in packages/storage/src/settings-store.ts, one on the write path and one on the read path:
1. write() (settings-store.ts:209-214) performs temp + rename with no durability fence at all.
private async write(settings: AppSettings): Promise<void> {
await mkdir(dirname(this.settingsPath), { recursive: true });
const tempPath = `${this.settingsPath}.${process.pid}.${Date.now()}.tmp`;
await writeFile(tempPath, JSON.stringify(settings, null, 2) + '\n', 'utf8');
await rename(tempPath, this.settingsPath);
}There is no handle.sync() on the temp file and no directory sync after the rename, so nothing orders the rename behind the file's data blocks. On a power loss or hard crash inside the write window, POSIX does not guarantee the data reached disk even though the rename did (the classic rename-without-fsync hazard — ext4's delayed-allocation zero-length files being the well-known instance), leaving settings.json present but zero-length or truncated. Additionally, the temp name is predictable (pid + Date.now()), the file is created without wx/O_EXCL, and a failed rename leaves the temp file behind.
2. readOrCreate() (settings-store.ts:92-102) only treats ENOENT as recoverable.
try {
const text = await readFile(this.settingsPath, 'utf8');
return normalizeSettings(JSON.parse(text));
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
/* first run: write defaults */
}A zero-length or truncated file makes JSON.parse throw a SyntaxError, which has no .code, so it falls into the rethrow branch: no fallback to defaults and no recovery guidance. The error propagates out of get(), and the desktop main call sites I checked invoke it without a catch (e.g. apps/desktop/src/main/runtime-host-settings-ipc-main.ts:146 and :179, apps/desktop/src/main/client-settings-ipc-main.ts:41-42), so settings loading fails outright.
Net effect: the write path can produce a corrupt file, and the read path treats corrupt as fatal. A missing settings.json gracefully gets defaults; a corrupted one bricks settings load until the user figures out they must delete <workspaceRoot>/settings.json by hand. mcp-config-store.ts:181-190 has the same ENOENT-only readOrCreate, so its read path shares the recovery gap.
How to reproduce
Real-world trigger (intermittent, low probability, deterministic consequence): change any setting, then lose power / hard reset inside the write window.
Deterministic simulation of the post-crash state:
- Locate the workspace settings file
<workspaceRoot>/settings.json(constructed atsettings-store.ts:80) - Truncate it — either empty it completely or keep the first ~20 bytes so the JSON is cut mid-token
- Start the desktop app (or call
settingsStore.get()directly)
Expected: settings load falls back to defaults, the same grace already extended to a missing file. Actual: a SyntaxError propagates out of get() and settings loading fails with no recovery path.
Environment
- Maka version or commit: 8c491e6 (main)
- OS and version: macOS 14 (the code paths are cross-platform; the missing-fsync hazard is POSIX-relevant)
- Surface: Desktop /
@maka/storagefrom source - Node.js version, if running from source: 24.x
Logs, screenshots, or additional context
The deeper issue is divergence: the same "atomic JSON file replace" pattern is implemented three times inside one package, at three different strictness levels — and the strictest one is the package's own documented standard.
| hardening | settings-store write() (:209) |
mcp-config-store write() (:197) |
credential-store writeSecretFileAtomic() (:261) |
|---|---|---|---|
| unpredictable temp name | ✗ pid+Date.now() |
✓ randomUUID() |
✓ randomUUID() |
exclusive create (wx / O_EXCL) |
✗ | ✓ | ✓ |
| 0600 temp + chmod | ✗ | ✓ | ✓ |
| fsync temp before rename | ✗ | ✗ | ✓ handle.sync() |
| fsync parent dir after rename | ✗ | ✗ | ✓ syncDirectory() |
| temp cleanup on failure | ✗ | ✓ (swallows the error) | ✓ (rethrows) |
credential-store's JSDoc states the standard explicitly:
Owner-only atomic write for a credentials file: a 0700 dir, an exclusive 0600 temp ('wx'/O_EXCL so we never follow a pre-planted symlink at a predictable path), a durability fence before and after the atomic rename, and temp cleanup on failure.
settings-store meets none of these properties; mcp-config-store meets all but the durability fence. Meanwhile the fence primitives already exist and are exported — stable-storage.ts:90-133 provides syncFile / syncDirectory / syncDirectoryChain, already used by marker-file, memory-bundle-io and the session-bundle paths — and credential-store.ts:281 even carries a private duplicate of syncDirectory.
Suggested direction (happy to take this once triaged):
- Extract one shared atomic-write helper implementing the credential-store standard (randomUUID temp,
wx, 0600, fsync file → rename → fsync dir, cleanup that rethrows) and pointsettings-storeandmcp-config-storeat it — removing the drift rather than patching each site. - Harden both
readOrCreate()implementations to distinguish "missing" from "corrupt": on corrupt, move the file aside (e.g.settings.json.corrupt-<timestamp>), rewrite defaults, and surface a warning — or at minimum throw a typed error naming the file to remove, instead of letting a bareSyntaxErrorpropagate through startup.
Activity
chinawch007 commentedon Aug 30, 2026
take
chinawch007 commentedon Sep 1, 2026
修复计划:storage 包 JSON store 写侧耐久性统一 + settings.json 损坏恢复
对应 issue:#4285(写侧无 durability fence / 损坏文件无恢复路径 / 三处原子写实现严格度漂移)。PR2 的恢复策略为方案 A:备份 + 回默认 + 恢复通知,如维护者对此有异议,请在 PR2 开工前否决。
拆分总览
fix/storage-json-store-durability-fencefix/storage-settings-corrupt-recovery前置排查(已完成)
createSettingsStore生产调用仅 runtime-host-boot.ts:367,另有 e2e/fixtures.ts:178——PR2 的签名扩展为可选参数,两者均不受影响。PR1:写侧统一加固
1. 新建共享工具 packages/storage/src/atomic-file-write.ts(内部模块)
硬约束(违反会被现有守卫拦截,均已核实):
check:asf-headers强制)syncDirectory(包内相对导入,不触发 exports 守卫),不新建副本API(协议 = credential-store.ts:263-281
writeSecretFileAtomic的标准,参数化三处差异):dir只设两档:settings 保留自身 mkdir(workspaceRoot 是用户目录,不做 0700 harden)、mcp 保留withUpdateLock的ensureDirectory,只有 credential 需要 fail-closed 目录语义——中间档没有消费者,不预设。chmod 策略作为文档化不变量写死在 helper JSDoc 中(这正是本 issue 要消灭的「漂移」):
chmodStrict在 POSIX 上等价,win32 差异(best-effort vs 跳过)不可观察——credential-store.test.ts 的 mode 断言全部skip: !isPosix'harden':chmodStrict语义(POSIX fail-loud;win32 best-effort),即 credential-store.ts:252-255ensureSecretDir的行为协议(顺序与 credential 现版一致):
[dir:'harden' 时先执行 ensureSecretDir 等价逻辑]→ 写${path}.${randomUUID()}.tmp→open('wx', fileMode)→writeFile→handle.sync()→close→chmod文件(按上述策略)→rename→syncDirectory(dirname)→ 任一步失败:rm(temp, {force:true}).catch(() => {})后重抛原错误。顺带修掉 credential 现版的小缺陷:credential-store.ts:278 的
rm未挂 catch,rm 失败会掩盖原始错误;统一路径以「catch 后重抛」保证原错误始终优先。2. 三个 store 接入与行为变化清单
write():保留原mkdir(dirname, {recursive:true}),写入主体换为writeAtomicFile(path, json, { fileMode: 0o600 })write():同参数调用;目录逻辑不动(ensureDirectory继续承担);补上缺失的文件/目录 fsync 栅栏writeSecretFileAtomic:ensureSecretDir改由 helper 的dir:'harden'承担,写入主体改为 helper 调用;删除 :283-291 的私有syncDirectory副本。credential-store.test.ts 现有测试全绿即为行为保持证明PR1 行为变化清单(在 PR 描述中显式列出,不以「零行为变化」表述兜底):
pid.Date.now/.mcp-uuiduuid3. 测试(照抄既有模式)
新 src/tests/atomic-file-write.test.ts:
dir:'harden'0700(照抄 credential-store.test.ts:114-152)wx拒绝(posix only;win32 skip 沿用 pet-pack-store.test.ts:177-186 的惯例;预植需注入 randomUUID 使 temp 路径可预测)settings-store 测试补:写后 0600(posix)、无 temp 残留;损坏文件仍 reject(PR1 不动读侧,settings-store-onboarding.test.ts:309-322 的 pin 保持原样)。
mcp-config-store 测试补:无 temp 残留;损坏 JSON reject 测试保持不变。
新测试文件用 describe + test +
import assert from 'node:assert/strict'(包内最常见组合),import 带 .js 扩展名,带许可头。4. 验证与提交
PR 标题:
fix(storage): enforce a durability fence on JSON config store writes模板:Summary(引用 issue、credential-store JSDoc 标准、三档分歧表格 + 行为变化清单)/ Verification / AI use(勾选 AI 实质贡献,commit 加
Generated-by:trailer)/ Checklist;正文Fixes #4285。PR2:settings 读侧损坏恢复(方案 A:备份 + 回默认 + 恢复通知)
1. storage 侧:settings-store.ts 恢复逻辑
工厂签名增量扩展(现有调用方 runtime-host-boot.ts:367 与 e2e/fixtures.ts:178 均不受影响):
readOrCreate(settings-store.ts:92-102)改造,读错误与解析错误分开处理:
(错误判型沿用文件内现有强转风格;包内没有
isNodeError一类 helper,不为此新造。)边界处理:
normalizeSettings永不抛错(coerce-to-default,core/src/settings.ts:848),SyntaxError 是唯一的损坏信号,无需覆盖结构校验chmod 0600;失败不阻断恢复(此时权限不比损坏前更差)withQueue串行段内,天然无并发问题;同进程二次get()走正常读路径(get() 每次都 readFile,无缓存)2. desktop 侧:注册恢复通知
createSettingsStore(workspaceRoot, { onCorruptRecovery: ({ backupPath }) => showSettingsRecoveryNotification(backupPath) })3. 测试更新
改写 settings-store-onboarding.test.ts:309-322(现 pin「损坏即抛错且字节不动」)为新语义:
.corrupt-<ts>备份文件4. PR 描述要点(预先列好,防止遗漏)
fix(storage): recover from a corrupted settings.json with backup and notificationGenerated-by:trailer;正文Refs #4285(PR1 已带 Fixes,issue 在 PR1 合并时关闭,本 PR 用 Refs)5. 验证
(apps/desktop 无 test script,已核实;desktop 侧行为由 E2E 覆盖,通知在 isolated 模式下有跳过守卫。)
执行顺序与依赖
writeAtomicFile(恢复写入走加固路径),串行开发Fixes,PR2Refs明确不做(后续 issue 素材,不塞进本 PR)
fix(storage): enforce a durability fence on JSON config store writes
fix(storage): persist atomic file modes before rename
test(windows): inventory the settings mode check
ci(windows): follow the atomic writer source closure
fix(storage): enforce durable atomic JSON config writes
chinawch007 commentedon Sep 4, 2026
Implementation note for PR #4505:
The shared writer in PR #4505 is intentionally scoped to the three legacy
JSON config stores named in this issue: settings.json, mcp.json, and
credentials.json.
It does not replace marker-file publication, whose create path uses link()
and a pre-publication hook, or the Runtime Policy document writer, which
owns bounded serialization, typed commit-outcome errors, and stale-temp
recovery.
The PR establishes the strongest write ordering available through the
current Node filesystem APIs. It does not claim platform-uniform power-loss
durability: Linux remains conditional on the filesystem/hardware fsync
contract, macOS FileHandle.sync() is not F_FULLFSYNC, and Windows has no
POSIX-equivalent parent-directory synchronization through Node.
The read-side corrupt-document recovery remains the planned follow-up.
fix(storage): unify atomic writes for JSON config stores
test(windows): inventory atomic writer skips
fix(storage): distinguish post-rename sync failures
refactor(storage): clarify atomic writer boundaries
refactor(storage): preserve store-owned file modes
42 remaining items
fix(storage): harden corrupt settings recovery and reporting
fix(mcp): preserve repair errors across IPC and TUI actions
fix(desktop): keep MCP IPC contract out of renderer runtime dependencies
fix(storage): back up corrupt settings before restoring defaults
fix(mcp): surface repair guidance for corrupt config files
fix(storage): harden corrupt settings recovery and reporting
fix(mcp): preserve repair errors across IPC and TUI actions
fix(desktop): keep MCP IPC contract out of renderer runtime dependencies
fix(storage): back up corrupt settings before restoring defaults
fix(mcp): surface repair guidance for corrupt config files
fix(storage): harden corrupt settings recovery and reporting
fix(mcp): preserve repair errors across IPC and TUI actions
fix(desktop): keep MCP IPC contract out of renderer runtime dependencies
fix(storage): storage settings corrupt recovery (#5282)