[Bug] Stats ledger is overwritten with an empty one when stats.json cannot be parsed or has a newer version
Description
If stats.json is corrupt, or was written by a newer Nanocoder (version 3), reading it fails and the next save writes a fresh empty ledger. Lifetime totals are lost.
Environment
- OS: Windows 11 Home 10.0.26300
- Node version: v22.22.3
- Nanocoder version: 1.32.0 (built from main at f92cce9c)
- Provider: Not provider-specific
- Model: Not model-specific
Steps to Reproduce
- Set
NANOCODER_DATA_DIRto an empty folder and writestats.json:{"version":3,"createdAt":1,"totalSessions":500,"totalPrompts":9000,"totalTokens":123456789,"totalCost":321,"daily":[],"monthly":[]} - Run a script that calls
recordUserPrompt('p', 'm', '2026-11-13')andflushStatsLedgerSync(). - Read
stats.json.
Expected Behavior
A file with unknown data is left alone (or backed up) and the user is told. totalSessions stays 500.
Actual Behavior
Everything from the old file is gone.
Logs/Screenshots
after flush: {"version":2,"totalSessions":0,"totalPrompts":1,"totalTokens":0}
Additional Context
- [x] I have searched existing issues to ensure this is not a duplicate
- [x] I can reproduce this issue consistently
- [x] This issue occurs with the latest version of nanocoder (main)
Suggested fix:
source/stats/storage.ts:175(version check) and:273(catch): return a "do not write" result for corrupt or newer files.source/stats/record.ts:111and:133: skip the write (or copy tostats.json.bakfirst) when the read was not clean.- Add tests for a corrupt file and for version 3.
Related: #1824 / PR #2030 (async flush; touches the same code).
I'd like to pick this up. Plan, following the suggested fix: the loader returns a "do not write" result for a corrupt or newer-version file, the record path skips the flush in that case (after copying the file to stats.json.bak), plus tests for a corrupt file and a version-3 file. Could you assign it to me?