loop-engineering icon indicating copy to clipboard operation
loop-engineering copied to clipboard

[bug] loop-context silently resets corrupt daily spend state

Open shixi-li opened this issue 3 weeks ago • 0 comments

Describe the bug

recordDailySpend treats every state read or JSON parse error as a missing file. A truncated daily-spend.<pattern>.json is therefore overwritten with only the newest delta, silently losing the amount already accumulated that UTC day. A valid JSON object with a missing counter can instead persist null after adding to undefined.

The problem affects the state used by --daily-budget-from-pattern. A controller can receive a continue decision after the saved total has been reset. This is separate from the concurrent-writer fix merged in #521 and the open Node runtime resolution PR #757.

Steps to reproduce

On main 1de5ca08d60f464b1a745bbf9c898d3bc7f45dd8, run this from tools/loop-context using the tracked dist files (optional rebuild: npm ci && npm run build). It exercises the state module used by the CLI without requiring loop-cost or model/service credentials:

node --input-type=module <<'JS'
import { mkdtemp, readFile, writeFile, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { recordDailySpend } from './dist/daily-spend.js';
const dir = await mkdtemp(path.join(tmpdir(), 'loop-spend-repro-'));
const file = path.join(dir, 'daily-spend.ci-sweeper.json');
const broken = '{"date":';
try {
  await writeFile(file, broken);
  try {
    const state = await recordDailySpend(dir, 'ci-sweeper', 1);
    console.log({ accepted: true, tokensUsedToday: state.tokensUsedToday });
  } catch (err) {
    console.log({ accepted: false, error: err.message });
  }
  console.log({ originalBytesPreserved: (await readFile(file, 'utf8')) === broken });
} finally {
  await rm(dir, { recursive: true, force: true });
}
JS

Expected behavior

Only a genuinely absent state file should initialize a new total. An unreadable, malformed, or structurally invalid existing state should produce an actionable error and preserve its bytes for inspection or recovery. The CLI should exit 1 without a continue decision.

Valid first-run initialization, UTC date rollover, accumulation, and concurrent updates should continue to work. Invalid token deltas or arithmetic overflow should not be allowed to corrupt the next saved total.

Actual behavior

The truncated JSON reproduction succeeds with tokensUsedToday: 1 and originalBytesPreserved: false. A real CLI check similarly returns exit 0 / ok after replacing the damaged state; missing tokensUsedToday can result in null on disk. Read failures are also swallowed by the same catch-all.

The damaged files in this report are synthetic fault fixtures. No production state, real billing records, or model calls were used.

Environment

macOS; Node 24.21.0; npm 11.19.0; @cobusgreyling/loop-context 1.5.0; source commit above.

shixi-li avatar Nov 11 '26 04:11 shixi-li