diff --git a/src/hermes-session-ledger.ts b/src/hermes-session-ledger.ts index b05a7bb1..a146d2e3 100644 --- a/src/hermes-session-ledger.ts +++ b/src/hermes-session-ledger.ts @@ -1,5 +1,5 @@ import { open, rename, unlink, mkdir } from 'fs/promises' -import { existsSync, readFileSync } from 'fs' +import { existsSync, readFileSync, unlinkSync } from 'fs' import { randomBytes } from 'crypto' import { join } from 'path' @@ -349,7 +349,17 @@ function validateLedger(raw: unknown): raw is HermesSessionLedger { function readLedgerFromDisk(): HermesSessionLedger { const path = hermesSessionLedgerPath() - if (!existsSync(path)) return emptyHermesSessionLedger() + if (!existsSync(path)) { + // The v1 file is superseded and can never be read again: the parse-version + // bump forces a cold re-parse that rebuilds every cursor from source. + // Left behind it is dead bytes that only invite a future reader to trust + // observations recorded under an accounting this branch replaced. + const v1 = join(getCodeburnCacheDir(), 'hermes-session-ledger.v1.json') + if (existsSync(v1)) { + try { unlinkSync(v1) } catch { /* another process got there first */ } + } + return emptyHermesSessionLedger() + } try { const parsed: unknown = JSON.parse(readFileSync(path, 'utf-8')) if (!validateLedger(parsed)) return emptyHermesSessionLedger() diff --git a/tests/hermes-session-ledger.test.ts b/tests/hermes-session-ledger.test.ts index 4bf207e5..2074e245 100644 --- a/tests/hermes-session-ledger.test.ts +++ b/tests/hermes-session-ledger.test.ts @@ -1,4 +1,5 @@ import { mkdir, mkdtemp, rm, writeFile } from 'fs/promises' +import { existsSync } from 'fs' import { join } from 'path' import { tmpdir } from 'os' import { afterEach, beforeEach, describe, expect, it } from 'vitest' @@ -245,14 +246,15 @@ describe('hermes session ledger unit', () => { expect(isHermesLedgerPublicationError(caught)).toBe(true) }) - it('does not adopt a v2 ledger whose migration could re-date historical observations', async () => { - await writeFile(join(cacheDir, 'hermes-session-ledger.v2.json'), JSON.stringify({ - version: 2, + it('ignores a superseded v1 ledger and removes it from the cache dir', async () => { + const v1Path = join(cacheDir, 'hermes-session-ledger.v1.json') + await writeFile(v1Path, JSON.stringify({ + version: 1, cursors: { default: { - corrupt: { + historical: { profile: 'default', - sessionId: 'corrupt', + sessionId: 'historical', lastSeen: { inputTokens: 1, outputTokens: 0, @@ -267,7 +269,11 @@ describe('hermes session ledger unit', () => { }, }, })) + expect(existsSync(v1Path)).toBe(true) + // No v3 file: the loader starts empty, and the v1 file it can never read + // again must not survive the load. expect(loadHermesSessionLedger().cursors).toEqual({}) + expect(existsSync(v1Path)).toBe(false) }) })