nanocoder icon indicating copy to clipboard operation
nanocoder copied to clipboard

[Bug] Stats ledger is overwritten with an empty one when stats.json cannot be parsed or has a newer version

Open addyCooks opened this issue 2 weeks ago • 1 comments

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

  1. Set NANOCODER_DATA_DIR to an empty folder and write stats.json: {"version":3,"createdAt":1,"totalSessions":500,"totalPrompts":9000,"totalTokens":123456789,"totalCost":321,"daily":[],"monthly":[]}
  2. Run a script that calls recordUserPrompt('p', 'm', '2026-11-13') and flushStatsLedgerSync().
  3. 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:111 and :133: skip the write (or copy to stats.json.bak first) 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).

addyCooks avatar Nov 14 '26 06:11 addyCooks

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?

qwist1233-cpu avatar Nov 14 '26 08:11 qwist1233-cpu