fix: atomic state writes with full state persistence

Previously only wrote dirty keys, causing data loss when multiple
modules wrote concurrently. Now writes full state atomically using
temp file + rename pattern.

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
devilreef 2026-01-16 04:36:55 +06:00
parent 410fc736c7
commit 58ef04fa68

View file

@ -60,13 +60,17 @@ export class StateStore {
return
}
// Write full state, not just dirty keys (atomicity)
const toSave: Record<string, unknown> = {}
for (const key of this.dirty) {
toSave[key] = this.state.get(key)
for (const [key, value] of this.state.entries()) {
toSave[key] = value
}
try {
await fs.writeFile(STATE_FILE, JSON.stringify(toSave, null, 2))
// Atomic write: temp file + rename
const tmpFile = `${STATE_FILE}.tmp`
await fs.writeFile(tmpFile, JSON.stringify(toSave, null, 2))
await fs.rename(tmpFile, STATE_FILE)
this.dirty.clear()
}
catch (err) {