mirror of
https://github.com/AgentSeal/codeburn.git
synced 2026-12-03 03:29:51 +00:00
fix(hermes): keep post-finalization session growth on the observation day
Hermes rows are lifetime totals stamped at started_at. After a day is sealed, later growth was dropped. A sidecar ledger records last-seen totals per (profile, sessionId) and emits weight-0 observation-time deltas so sealed days stay put while today's growth still lands. Closes #916
This commit is contained in:
parent
c9dab7deb6
commit
8446d3f81e
11 changed files with 1312 additions and 63 deletions
|
|
@ -42,6 +42,8 @@
|
|||
- **The resident `codeburn serve` child.** The first real panel request is also the cache warm-up, so startup never runs an artificial warm-up query beside a duplicate one-shot child; each served command carries its own read-only option allowlist, and anything outside it falls back to a normal spawn; the child exits when its stdin closes, so it can never outlive the app. Requests whose response exceeds the 16 MiB frame limit still replace the child, but that deliberate kill no longer spends the resident's unexpected-death budget. (#972)
|
||||
|
||||
### Fixed
|
||||
- **Hermes sessions that keep running after a day is sealed no longer lose later token and cost growth.** A sidecar ledger under the CodeBurn cache records last-seen lifetime totals per `(profile, sessionId)` and emits observation-time deltas (weight 0) so a sealed day stays put while today's growth still lands. An all-zero reset is visible to the cursor after discovery filtering, so a later 40 is `+40` rather than a silent shrink. Explicit `$0` is treated as recorded. Ledger publication failures are retryable and hold the daily watermark. (#916)
|
||||
|
||||
- **Subscription SKUs are classified from real product ids, and a false-positive built-in can be opted out.** `codex-auto-review` consumes ordinary Codex usage ([openai/codex#32224](https://github.com/openai/codex/issues/32224)) and is priced as GPT-5.5 on #1056, so treating it as $0 hid real spend — it left the flat-rate list. Warp's product id is `auto`, not the synthetic `warp`. `kimi-for-coding-highspeed` (the SKU #968 was filed around) is now honestly $0. `big-pickle` was dropped: it appears under OpenCode, not as a cited ClinePass codename. `codeburn model-flat-rate --remove` now opts out of a built-in, so a wrong classifier entry can warn again without waiting for a release. The daily-cache config hash now always includes the flat-rate section (even when empty), so the first run after upgrade re-derives every stored day once from the warm session cache. (#968, #1050)
|
||||
- **Codex MCP and skill usage is attributed from every shape Codex records a shell command in.** `mcp-cli call <server> <tool>` was only recognized when the command arrived as `function_call` arguments (#656). Codex has two other shapes for the same exec: its custom-tool transport records the shell tool as a `custom_tool_call` whose payload is an `input` program rather than `arguments`, and its item model repeats a finished command as `event_msg`/`item_completed` carrying a `CommandExecution` item with an argv `command`. Both reached the Bash counter and neither reached the matcher, so a CLI-wrapped MCP call stayed absent from the MCP breakdown exactly as before the fix. All three shapes now feed one classification pipeline. The same pipeline learns skills: Codex has no skill tool, so loading one is a shell read of the skill's `SKILL.md`, and those reads landed entirely under Bash with the Skills dimension empty. A read counts as a skill load only when the command segment starts with a file-reading binary (`cat`/`bat`/`sed`/`head`/`tail`/`less`/`more`) and the path it reads ends in `<name>/SKILL.md`; the skill is `<name>`, the same key `pi` derives for a native skill read (#588) and the same vocabulary the Claude parser records from the `Skill` tool. A `grep`/`rg`/`ls` that merely mentions a `SKILL.md` is a search near the file, not a skill load, and stays plain Bash. This is attribution only — no call, token or cost figure moves, and a command carried by both a response item and an item-model item is attributed once. On a 1,397-rollout corpus: Skills went from empty to 7 skills over 35 turns (55 attributions), Bash was unchanged at 42,170, and cost, calls, tokens, sessions, daily, models and projects came back identical. Cached Codex sessions re-parse once (`CODEX_CACHE_VERSION` 13 → 14 and the codex parse version both move; without them the fix is invisible on a warm cache). Thanks @chr-evensen. (#478)
|
||||
- **`gpt-5.6-codex` and `gpt-5.6-codex-max` now have their own pricing rows.** Neither id is in LiteLLM yet, and both were missing from the bundled snapshot — flagged during #1075 verification on a real corpus (285 sessions, 5,446 calls). `getModelCosts` already resolved both through the `gpt-5.6` prefix fallback, so live pricing was already correct once a session priced fresh; every prior Codex-suffixed id LiteLLM does carry bills identically to its bare-model sibling of the same generation (`gpt-5-codex` == `gpt-5`, `gpt-5.1-codex` == `gpt-5.1-codex-max` == `gpt-5.1`, `gpt-5.2-codex` == `gpt-5.2`, `gpt-5.3-codex` == `gpt-5.3`), which is the evidence both new rows mirror rather than inventing a rate. The gap that does not self-heal is the daily cache: it has no per-provider invalidation, so a day finalized while either id had no billable rate keeps that $0 forever. Raising `MIN_SUPPORTED_VERSION` (v23 -> v24) forces the one-time re-derivation, a lossless no-op for days already correct. (#1077)
|
||||
|
|
|
|||
|
|
@ -2,9 +2,10 @@
|
|||
// requests. A copilot shutdown rollup, synthesized residual, or store row
|
||||
// paired with its per-turn call (`supplementaryAccounting`, assigned at serve
|
||||
// time) carries real tokens and cost but is not a distinct behavioral
|
||||
// request. Every user-visible calls/turns counter weighs calls through these
|
||||
// helpers so no surface can disagree with the session summaries or the
|
||||
// sealed daily history. Token and cost sums intentionally keep every call —
|
||||
// request. Hermes observation-time deltas persist the same flag. Every
|
||||
// user-visible calls/turns counter weighs calls through these helpers so no
|
||||
// surface can disagree with the session summaries or the sealed daily
|
||||
// history. Token and cost sums intentionally keep every call —
|
||||
// supplementary accounting must never be filtered out, only weightless.
|
||||
|
||||
type WeightedCall = { supplementaryAccounting?: boolean }
|
||||
|
|
|
|||
445
src/hermes-session-ledger.ts
Normal file
445
src/hermes-session-ledger.ts
Normal file
|
|
@ -0,0 +1,445 @@
|
|||
import { open, rename, unlink, mkdir } from 'fs/promises'
|
||||
import { existsSync, readFileSync } from 'fs'
|
||||
import { randomBytes } from 'crypto'
|
||||
import { join } from 'path'
|
||||
|
||||
import { getCodeburnCacheDir } from './cache-dir.js'
|
||||
import type { CachedCall, ProviderSection } from './session-cache.js'
|
||||
|
||||
export const HERMES_SESSION_LEDGER_FILENAME = 'hermes-session-ledger.v1.json'
|
||||
export const HERMES_SESSION_LEDGER_VERSION = 1 as const
|
||||
|
||||
export type HermesCostBasis = 'actual' | 'estimated' | 'calculated'
|
||||
|
||||
export type HermesTokenTotals = {
|
||||
inputTokens: number
|
||||
outputTokens: number
|
||||
cacheReadTokens: number
|
||||
cacheWriteTokens: number
|
||||
reasoningTokens: number
|
||||
}
|
||||
|
||||
export type HermesObservation = HermesTokenTotals & {
|
||||
/** 0 = first behavioral observation; 1+ = later weight-0 observations. */
|
||||
index: number
|
||||
timestamp: string
|
||||
costUSD: number
|
||||
costBasis: HermesCostBasis
|
||||
supplementaryAccounting: boolean
|
||||
}
|
||||
|
||||
export type HermesLastSeen = HermesTokenTotals & {
|
||||
costUSD: number
|
||||
costBasis: HermesCostBasis
|
||||
}
|
||||
|
||||
export type HermesSessionCursor = {
|
||||
profile: string
|
||||
sessionId: string
|
||||
lastSeen: HermesLastSeen
|
||||
observations: HermesObservation[]
|
||||
}
|
||||
|
||||
export type HermesSessionLedger = {
|
||||
version: typeof HERMES_SESSION_LEDGER_VERSION
|
||||
cursors: Record<string, Record<string, HermesSessionCursor>>
|
||||
}
|
||||
|
||||
export class HermesLedgerPublicationError extends Error {
|
||||
override readonly name = 'HermesLedgerPublicationError'
|
||||
constructor(message: string, options?: { cause?: unknown }) {
|
||||
super(message, options)
|
||||
}
|
||||
}
|
||||
|
||||
export function isHermesLedgerPublicationError(err: unknown): boolean {
|
||||
return err instanceof HermesLedgerPublicationError
|
||||
}
|
||||
|
||||
const ZERO_TOKENS: HermesTokenTotals = {
|
||||
inputTokens: 0,
|
||||
outputTokens: 0,
|
||||
cacheReadTokens: 0,
|
||||
cacheWriteTokens: 0,
|
||||
reasoningTokens: 0,
|
||||
}
|
||||
|
||||
let nowFn: () => Date = () => new Date()
|
||||
let memory: HermesSessionLedger | null = null
|
||||
let memoryDir: string | null = null
|
||||
|
||||
export function setHermesLedgerNow(fn: () => Date): void {
|
||||
nowFn = fn
|
||||
}
|
||||
|
||||
export function resetHermesLedgerNow(): void {
|
||||
nowFn = () => new Date()
|
||||
}
|
||||
|
||||
export function hermesLedgerNow(): Date {
|
||||
return nowFn()
|
||||
}
|
||||
|
||||
export function hermesSessionLedgerPath(): string {
|
||||
return join(getCodeburnCacheDir(), HERMES_SESSION_LEDGER_FILENAME)
|
||||
}
|
||||
|
||||
export function emptyHermesSessionLedger(): HermesSessionLedger {
|
||||
return { version: HERMES_SESSION_LEDGER_VERSION, cursors: {} }
|
||||
}
|
||||
|
||||
export function resetHermesSessionLedgerForTests(): void {
|
||||
memory = null
|
||||
memoryDir = null
|
||||
nowFn = () => new Date()
|
||||
}
|
||||
|
||||
export function parseHermesDedupKey(key: string): { profile: string; sessionId: string; observationIndex?: number } | null {
|
||||
if (!key.startsWith('hermes:')) return null
|
||||
const rest = key.slice('hermes:'.length)
|
||||
const obsMatch = rest.match(/^(.*):obs:(\d+)$/)
|
||||
const body = obsMatch ? obsMatch[1]! : rest
|
||||
const colon = body.indexOf(':')
|
||||
if (colon <= 0) return null
|
||||
const profile = body.slice(0, colon)
|
||||
const sessionId = body.slice(colon + 1)
|
||||
if (!profile || !sessionId) return null
|
||||
return {
|
||||
profile,
|
||||
sessionId,
|
||||
observationIndex: obsMatch ? Number(obsMatch[2]) : undefined,
|
||||
}
|
||||
}
|
||||
|
||||
export function isHermesObservationKey(key: string): boolean {
|
||||
return key.startsWith('hermes:') && /:obs:\d+$/.test(key)
|
||||
}
|
||||
|
||||
export function hermesBaselineKey(profile: string, sessionId: string): string {
|
||||
return `hermes:${profile}:${sessionId}`
|
||||
}
|
||||
|
||||
export function hermesObservationKey(profile: string, sessionId: string, n: number): string {
|
||||
return `hermes:${profile}:${sessionId}:obs:${n}`
|
||||
}
|
||||
|
||||
export function getHermesCursor(ledger: HermesSessionLedger, profile: string, sessionId: string): HermesSessionCursor | undefined {
|
||||
return ledger.cursors[profile]?.[sessionId]
|
||||
}
|
||||
|
||||
export function listHermesCursorSessionIds(ledger: HermesSessionLedger, profile: string): string[] {
|
||||
return Object.keys(ledger.cursors[profile] ?? {})
|
||||
}
|
||||
|
||||
export function zeroHermesTokens(): HermesTokenTotals {
|
||||
return { ...ZERO_TOKENS }
|
||||
}
|
||||
|
||||
function tokenList(t: HermesTokenTotals): number[] {
|
||||
return [t.inputTokens, t.outputTokens, t.cacheReadTokens, t.cacheWriteTokens, t.reasoningTokens]
|
||||
}
|
||||
|
||||
function tokensGte(curr: HermesTokenTotals, last: HermesTokenTotals): boolean {
|
||||
const a = tokenList(curr)
|
||||
const b = tokenList(last)
|
||||
return a.every((v, i) => v >= b[i]!)
|
||||
}
|
||||
|
||||
function tokensEqual(a: HermesTokenTotals, b: HermesTokenTotals): boolean {
|
||||
return tokenList(a).every((v, i) => v === tokenList(b)[i])
|
||||
}
|
||||
|
||||
function subtractTokens(curr: HermesTokenTotals, last: HermesTokenTotals): HermesTokenTotals {
|
||||
return {
|
||||
inputTokens: curr.inputTokens - last.inputTokens,
|
||||
outputTokens: curr.outputTokens - last.outputTokens,
|
||||
cacheReadTokens: curr.cacheReadTokens - last.cacheReadTokens,
|
||||
cacheWriteTokens: curr.cacheWriteTokens - last.cacheWriteTokens,
|
||||
reasoningTokens: curr.reasoningTokens - last.reasoningTokens,
|
||||
}
|
||||
}
|
||||
|
||||
function hasPositiveTokenDelta(delta: HermesTokenTotals): boolean {
|
||||
return tokenList(delta).some(v => v > 0)
|
||||
}
|
||||
|
||||
export type HermesSnapshot = {
|
||||
profile: string
|
||||
sessionId: string
|
||||
startedAt: string
|
||||
observedAt: string
|
||||
tokens: HermesTokenTotals
|
||||
costUSD: number
|
||||
costBasis: HermesCostBasis
|
||||
}
|
||||
|
||||
export function applyHermesSnapshot(
|
||||
existing: HermesSessionCursor | undefined,
|
||||
snapshot: HermesSnapshot,
|
||||
): { cursor: HermesSessionCursor; dirty: boolean } {
|
||||
if (!existing) {
|
||||
const first: HermesObservation = {
|
||||
index: 0,
|
||||
timestamp: snapshot.startedAt,
|
||||
...snapshot.tokens,
|
||||
costUSD: snapshot.costUSD,
|
||||
costBasis: snapshot.costBasis,
|
||||
supplementaryAccounting: false,
|
||||
}
|
||||
return {
|
||||
cursor: {
|
||||
profile: snapshot.profile,
|
||||
sessionId: snapshot.sessionId,
|
||||
lastSeen: {
|
||||
...snapshot.tokens,
|
||||
costUSD: snapshot.costUSD,
|
||||
costBasis: snapshot.costBasis,
|
||||
},
|
||||
observations: [first],
|
||||
},
|
||||
dirty: true,
|
||||
}
|
||||
}
|
||||
|
||||
const last = existing.lastSeen
|
||||
const sameCost = snapshot.costUSD === last.costUSD && snapshot.costBasis === last.costBasis
|
||||
if (tokensEqual(snapshot.tokens, last) && sameCost) {
|
||||
return { cursor: existing, dirty: false }
|
||||
}
|
||||
|
||||
// Shrink, including all-zero: new baseline. Do not emit a negative. Keep sealed history.
|
||||
if (!tokensGte(snapshot.tokens, last)) {
|
||||
return {
|
||||
cursor: {
|
||||
...existing,
|
||||
lastSeen: {
|
||||
...snapshot.tokens,
|
||||
costUSD: snapshot.costUSD,
|
||||
costBasis: snapshot.costBasis,
|
||||
},
|
||||
},
|
||||
dirty: true,
|
||||
}
|
||||
}
|
||||
|
||||
const tokenDelta = subtractTokens(snapshot.tokens, last)
|
||||
const positiveTokens = hasPositiveTokenDelta(tokenDelta)
|
||||
const costGrew = snapshot.costUSD >= last.costUSD
|
||||
const costDelta = costGrew ? snapshot.costUSD - last.costUSD : 0
|
||||
|
||||
if (!positiveTokens && costDelta === 0) {
|
||||
// Tokens held (or only cost reset / basis change). Advance last-seen, no observation.
|
||||
return {
|
||||
cursor: {
|
||||
...existing,
|
||||
lastSeen: {
|
||||
...snapshot.tokens,
|
||||
costUSD: snapshot.costUSD,
|
||||
costBasis: snapshot.costBasis,
|
||||
},
|
||||
},
|
||||
dirty: true,
|
||||
}
|
||||
}
|
||||
|
||||
const nextIndex = existing.observations.reduce((max, obs) => Math.max(max, obs.index), 0) + 1
|
||||
const observation: HermesObservation = {
|
||||
index: nextIndex,
|
||||
timestamp: snapshot.observedAt,
|
||||
...tokenDelta,
|
||||
costUSD: costDelta,
|
||||
costBasis: snapshot.costBasis,
|
||||
supplementaryAccounting: true,
|
||||
}
|
||||
return {
|
||||
cursor: {
|
||||
...existing,
|
||||
lastSeen: {
|
||||
...snapshot.tokens,
|
||||
costUSD: snapshot.costUSD,
|
||||
costBasis: snapshot.costBasis,
|
||||
},
|
||||
observations: [...existing.observations, observation],
|
||||
},
|
||||
dirty: true,
|
||||
}
|
||||
}
|
||||
|
||||
function putCursor(ledger: HermesSessionLedger, cursor: HermesSessionCursor): HermesSessionLedger {
|
||||
return {
|
||||
version: HERMES_SESSION_LEDGER_VERSION,
|
||||
cursors: {
|
||||
...ledger.cursors,
|
||||
[cursor.profile]: {
|
||||
...(ledger.cursors[cursor.profile] ?? {}),
|
||||
[cursor.sessionId]: cursor,
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
function isNum(v: unknown): v is number {
|
||||
return typeof v === 'number' && Number.isFinite(v)
|
||||
}
|
||||
|
||||
function isCostBasis(v: unknown): v is HermesCostBasis {
|
||||
return v === 'actual' || v === 'estimated' || v === 'calculated'
|
||||
}
|
||||
|
||||
function validateTokens(o: Record<string, unknown>): o is Record<string, unknown> & HermesTokenTotals {
|
||||
return isNum(o['inputTokens'])
|
||||
&& isNum(o['outputTokens'])
|
||||
&& isNum(o['cacheReadTokens'])
|
||||
&& isNum(o['cacheWriteTokens'])
|
||||
&& isNum(o['reasoningTokens'])
|
||||
}
|
||||
|
||||
function validateObservation(v: unknown): v is HermesObservation {
|
||||
if (!v || typeof v !== 'object') return false
|
||||
const o = v as Record<string, unknown>
|
||||
return validateTokens(o)
|
||||
&& isNum(o['index'])
|
||||
&& typeof o['timestamp'] === 'string'
|
||||
&& isNum(o['costUSD'])
|
||||
&& isCostBasis(o['costBasis'])
|
||||
&& typeof o['supplementaryAccounting'] === 'boolean'
|
||||
}
|
||||
|
||||
function validateCursor(v: unknown): v is HermesSessionCursor {
|
||||
if (!v || typeof v !== 'object') return false
|
||||
const o = v as Record<string, unknown>
|
||||
if (typeof o['profile'] !== 'string' || typeof o['sessionId'] !== 'string') return false
|
||||
if (!o['lastSeen'] || typeof o['lastSeen'] !== 'object') return false
|
||||
const last = o['lastSeen'] as Record<string, unknown>
|
||||
if (!validateTokens(last) || !isNum(last['costUSD']) || !isCostBasis(last['costBasis'])) return false
|
||||
if (!Array.isArray(o['observations']) || !o['observations'].every(validateObservation)) return false
|
||||
return true
|
||||
}
|
||||
|
||||
function validateLedger(raw: unknown): raw is HermesSessionLedger {
|
||||
if (!raw || typeof raw !== 'object') return false
|
||||
const o = raw as Record<string, unknown>
|
||||
if (o['version'] !== HERMES_SESSION_LEDGER_VERSION) return false
|
||||
if (!o['cursors'] || typeof o['cursors'] !== 'object' || Array.isArray(o['cursors'])) return false
|
||||
for (const profileCursors of Object.values(o['cursors'] as Record<string, unknown>)) {
|
||||
if (!profileCursors || typeof profileCursors !== 'object' || Array.isArray(profileCursors)) return false
|
||||
if (!Object.values(profileCursors as Record<string, unknown>).every(validateCursor)) return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
function readLedgerFromDisk(): HermesSessionLedger {
|
||||
const path = hermesSessionLedgerPath()
|
||||
if (!existsSync(path)) return emptyHermesSessionLedger()
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(readFileSync(path, 'utf-8'))
|
||||
if (!validateLedger(parsed)) return emptyHermesSessionLedger()
|
||||
return parsed
|
||||
} catch {
|
||||
return emptyHermesSessionLedger()
|
||||
}
|
||||
}
|
||||
|
||||
export function loadHermesSessionLedger(): HermesSessionLedger {
|
||||
const dir = getCodeburnCacheDir()
|
||||
if (memory && memoryDir === dir) return memory
|
||||
const loaded = readLedgerFromDisk()
|
||||
memory = loaded
|
||||
memoryDir = dir
|
||||
return loaded
|
||||
}
|
||||
|
||||
async function writeFileAtomic(finalPath: string, payload: string): Promise<void> {
|
||||
const tempPath = `${finalPath}.${randomBytes(8).toString('hex')}.tmp`
|
||||
const handle = await open(tempPath, 'w', 0o600)
|
||||
try {
|
||||
await handle.writeFile(payload, { encoding: 'utf-8' })
|
||||
await handle.sync()
|
||||
} finally {
|
||||
await handle.close()
|
||||
}
|
||||
try {
|
||||
for (let attempt = 0; attempt < 3; attempt++) {
|
||||
try {
|
||||
await rename(tempPath, finalPath)
|
||||
return
|
||||
} catch (err) {
|
||||
const code = (err as NodeJS.ErrnoException).code
|
||||
if ((code !== 'EPERM' && code !== 'EBUSY') || attempt === 2) throw err
|
||||
await new Promise(resolve => { setTimeout(resolve, 10 * (attempt + 1)) })
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
await unlink(tempPath).catch(() => undefined)
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
export async function persistHermesSessionLedger(ledger: HermesSessionLedger): Promise<void> {
|
||||
const dir = getCodeburnCacheDir()
|
||||
const finalPath = join(dir, HERMES_SESSION_LEDGER_FILENAME)
|
||||
try {
|
||||
await mkdir(dir, { recursive: true })
|
||||
await writeFileAtomic(finalPath, JSON.stringify(ledger))
|
||||
} catch (err) {
|
||||
throw new HermesLedgerPublicationError(
|
||||
`failed to publish Hermes session ledger at ${finalPath}`,
|
||||
{ cause: err },
|
||||
)
|
||||
}
|
||||
memory = ledger
|
||||
memoryDir = dir
|
||||
}
|
||||
|
||||
export async function recordHermesSnapshot(snapshot: HermesSnapshot): Promise<HermesSessionCursor> {
|
||||
const ledger = loadHermesSessionLedger()
|
||||
const existing = getHermesCursor(ledger, snapshot.profile, snapshot.sessionId)
|
||||
const { cursor, dirty } = applyHermesSnapshot(existing, snapshot)
|
||||
if (dirty) await persistHermesSessionLedger(putCursor(ledger, cursor))
|
||||
return cursor
|
||||
}
|
||||
|
||||
function cachedCallToSnapshotTokens(call: CachedCall): HermesTokenTotals {
|
||||
return {
|
||||
inputTokens: call.usage.inputTokens,
|
||||
outputTokens: call.usage.outputTokens,
|
||||
cacheReadTokens: call.usage.cacheReadInputTokens,
|
||||
cacheWriteTokens: call.usage.cacheCreationInputTokens,
|
||||
reasoningTokens: call.usage.reasoningTokens,
|
||||
}
|
||||
}
|
||||
|
||||
export async function seedHermesCursorsFromProviderSection(section: ProviderSection): Promise<void> {
|
||||
const ledger = loadHermesSessionLedger()
|
||||
let next = ledger
|
||||
let dirty = false
|
||||
for (const file of Object.values(section.files)) {
|
||||
for (const turn of file.turns) {
|
||||
for (const call of turn.calls) {
|
||||
if (call.provider !== 'hermes') continue
|
||||
const parsed = parseHermesDedupKey(call.deduplicationKey)
|
||||
if (!parsed || parsed.observationIndex != null) continue
|
||||
if (getHermesCursor(next, parsed.profile, parsed.sessionId)) continue
|
||||
const tokens = cachedCallToSnapshotTokens(call)
|
||||
const costUSD = call.costUSD ?? 0
|
||||
const costBasis: HermesCostBasis = call.isEstimated ? 'calculated' : 'actual'
|
||||
const cursor: HermesSessionCursor = {
|
||||
profile: parsed.profile,
|
||||
sessionId: parsed.sessionId,
|
||||
lastSeen: { ...tokens, costUSD, costBasis },
|
||||
observations: [{
|
||||
index: 0,
|
||||
timestamp: call.timestamp,
|
||||
...tokens,
|
||||
costUSD,
|
||||
costBasis,
|
||||
supplementaryAccounting: false,
|
||||
}],
|
||||
}
|
||||
next = putCursor(next, cursor)
|
||||
dirty = true
|
||||
}
|
||||
}
|
||||
}
|
||||
if (dirty) await persistHermesSessionLedger(next)
|
||||
}
|
||||
|
|
@ -11,6 +11,11 @@ import { antigravityCascadeIdFromPath, flushAntigravityCache, shouldReparseAntig
|
|||
import { getClaudeConfigDirs, getDesktopSessionsDirs } from './providers/claude.js'
|
||||
import { isSqliteBusyError } from './sqlite.js'
|
||||
import { getCodeburnCacheDir } from './cache-dir.js'
|
||||
import {
|
||||
isHermesLedgerPublicationError,
|
||||
isHermesObservationKey,
|
||||
seedHermesCursorsFromProviderSection,
|
||||
} from './hermes-session-ledger.js'
|
||||
import {
|
||||
type CachedCall,
|
||||
type CachedFile,
|
||||
|
|
@ -2541,6 +2546,7 @@ function providerCallToCachedCall(call: ParsedProviderCall): CachedCall {
|
|||
...(call.requestMultiplier != null ? { requestMultiplier: call.requestMultiplier } : {}),
|
||||
...(call.compactedAt ? { compactedAt: call.compactedAt } : {}),
|
||||
...(call.initiator ? { initiator: call.initiator } : {}),
|
||||
...(call.supplementaryAccounting ? { supplementaryAccounting: true } : {}),
|
||||
activeDurationMs: call.activeDurationMs,
|
||||
activeGeneratedTokens: call.activeGeneratedTokens,
|
||||
toolWaitMs: call.toolWaitMs,
|
||||
|
|
@ -2700,6 +2706,9 @@ function cachedCallToApiCall(call: CachedCall): ParsedApiCall {
|
|||
activeDurationMs: call.activeDurationMs,
|
||||
activeGeneratedTokens: call.activeGeneratedTokens,
|
||||
toolWaitMs: call.toolWaitMs,
|
||||
...(call.supplementaryAccounting || isHermesObservationKey(call.deduplicationKey)
|
||||
? { supplementaryAccounting: true }
|
||||
: {}),
|
||||
})
|
||||
}
|
||||
|
||||
|
|
@ -3230,6 +3239,19 @@ export async function parseProviderSources(
|
|||
const antigravityCacheDir = providerName === 'antigravity' ? getCodeburnCacheDir() : undefined
|
||||
|
||||
const section = getOrCreateProviderSection(diskCache, providerName)
|
||||
if (providerName === 'hermes' && !readOnly) {
|
||||
try {
|
||||
// Isolated migration: seed missing cursors from the already-loaded
|
||||
// hermes section before any source is deleted in this parse loop.
|
||||
await seedHermesCursorsFromProviderSection(section)
|
||||
} catch (err) {
|
||||
if (isHermesLedgerPublicationError(err)) {
|
||||
deferredRetryableSource = true
|
||||
} else {
|
||||
throw err
|
||||
}
|
||||
}
|
||||
}
|
||||
const allDiscoveredFiles = new Set<string>()
|
||||
const servedSources = [...sources]
|
||||
|
||||
|
|
@ -3503,7 +3525,7 @@ export async function parseProviderSources(
|
|||
didParse = true
|
||||
markCacheDirty(diskCache, providerName, source.path)
|
||||
} catch (err) {
|
||||
if (isSqliteBusyError(err)) {
|
||||
if (isSqliteBusyError(err) || isHermesLedgerPublicationError(err)) {
|
||||
// Deferred, not failed: the cache keeps serving this source's
|
||||
// previous rows and the next refresh retries. But the data this
|
||||
// read would have added is MISSING from this parse, so the run is a
|
||||
|
|
|
|||
|
|
@ -7,6 +7,20 @@ import { calculateCost, getShortModelName } from '../models.js'
|
|||
import { isSqliteAvailable, getSqliteLoadError, openDatabase, isSqliteBusyError, type SqliteDatabase } from '../sqlite.js'
|
||||
import type { ProbeRoot, Provider, SessionSource, SessionParser, ParsedProviderCall } from './types.js'
|
||||
import type { ToolCall } from '../types.js'
|
||||
import {
|
||||
getHermesCursor,
|
||||
hermesBaselineKey,
|
||||
hermesLedgerNow,
|
||||
hermesObservationKey,
|
||||
listHermesCursorSessionIds,
|
||||
loadHermesSessionLedger,
|
||||
recordHermesSnapshot,
|
||||
zeroHermesTokens,
|
||||
isHermesLedgerPublicationError,
|
||||
type HermesCostBasis,
|
||||
type HermesObservation,
|
||||
type HermesTokenTotals,
|
||||
} from '../hermes-session-ledger.js'
|
||||
|
||||
type HermesSessionRow = {
|
||||
id: string
|
||||
|
|
@ -430,6 +444,80 @@ function resolveHermesWorkspace(
|
|||
return { project: provider, provider }
|
||||
}
|
||||
|
||||
function tokenSum(tokens: HermesTokenTotals): number {
|
||||
return tokens.inputTokens + tokens.outputTokens + tokens.cacheReadTokens + tokens.cacheWriteTokens + tokens.reasoningTokens
|
||||
}
|
||||
|
||||
function resolveHermesCost(
|
||||
row: HermesSessionRow | undefined,
|
||||
model: string,
|
||||
tokens: HermesTokenTotals,
|
||||
): { costUSD: number; costIsEstimated: boolean; costBasis: HermesCostBasis } {
|
||||
const calculatedCost = calculateCost(
|
||||
model,
|
||||
tokens.inputTokens,
|
||||
tokens.outputTokens + tokens.reasoningTokens,
|
||||
tokens.cacheWriteTokens,
|
||||
tokens.cacheReadTokens,
|
||||
0,
|
||||
)
|
||||
// This slice treats explicit $0 as recorded. null still falls through.
|
||||
if (row && row.actual_cost_usd != null) {
|
||||
return { costUSD: row.actual_cost_usd, costIsEstimated: false, costBasis: 'actual' }
|
||||
}
|
||||
if (row && row.estimated_cost_usd != null) {
|
||||
return { costUSD: row.estimated_cost_usd, costIsEstimated: false, costBasis: 'estimated' }
|
||||
}
|
||||
return { costUSD: calculatedCost, costIsEstimated: true, costBasis: 'calculated' }
|
||||
}
|
||||
|
||||
function observationToCall(
|
||||
observation: HermesObservation,
|
||||
args: {
|
||||
profile: string
|
||||
sessionId: string
|
||||
model: string
|
||||
tools: string[]
|
||||
bashCommands: string[]
|
||||
toolSequence: ToolCall[][]
|
||||
userMessage: string
|
||||
project: string
|
||||
projectPath?: string
|
||||
prLinks?: string[]
|
||||
costIsEstimated: boolean
|
||||
},
|
||||
): ParsedProviderCall {
|
||||
const later = observation.index > 0
|
||||
return {
|
||||
provider: 'hermes',
|
||||
model: args.model,
|
||||
inputTokens: observation.inputTokens,
|
||||
outputTokens: observation.outputTokens,
|
||||
cacheCreationInputTokens: observation.cacheWriteTokens,
|
||||
cacheReadInputTokens: observation.cacheReadTokens,
|
||||
cachedInputTokens: observation.cacheReadTokens,
|
||||
reasoningTokens: observation.reasoningTokens,
|
||||
webSearchRequests: 0,
|
||||
costUSD: observation.costUSD,
|
||||
costIsEstimated: later ? false : args.costIsEstimated,
|
||||
tools: later ? [] : args.tools,
|
||||
bashCommands: later ? [] : args.bashCommands,
|
||||
timestamp: observation.timestamp,
|
||||
speed: 'standard',
|
||||
deduplicationKey: later
|
||||
? hermesObservationKey(args.profile, args.sessionId, observation.index)
|
||||
: hermesBaselineKey(args.profile, args.sessionId),
|
||||
turnId: later ? `${args.sessionId}:obs:${observation.index}` : `${args.sessionId}:session`,
|
||||
toolSequence: later || args.toolSequence.length === 0 ? undefined : args.toolSequence,
|
||||
userMessage: later ? '' : args.userMessage,
|
||||
sessionId: args.sessionId,
|
||||
project: args.project,
|
||||
projectPath: args.projectPath,
|
||||
...(later || !args.prLinks?.length ? {} : { prLinks: args.prLinks }),
|
||||
...(later ? { supplementaryAccounting: true } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
function inferProject(messages: HermesMessageRow[], fallback: string): { project: string; projectPath?: string } {
|
||||
const cwdPattern = /^Current working directory:\s*([a-zA-Z]:\\[^\r\n`"]+|\/[^\r\n`"\\]+)/m
|
||||
for (const msg of messages) {
|
||||
|
|
@ -471,11 +559,25 @@ async function discoverFromDb(dbPath: string, profile: string): Promise<SessionS
|
|||
LIMIT 10000`,
|
||||
)
|
||||
|
||||
return rows.map(row => ({
|
||||
const sources = rows.map(row => ({
|
||||
path: encodeSourcePath(dbPath, row.id),
|
||||
project: displayProjectForProfile(profile),
|
||||
provider: 'hermes',
|
||||
provider: 'hermes' as const,
|
||||
}))
|
||||
// After the >0 filter, reconcile every already-ledgered identity against
|
||||
// this state.db so an all-zero (or missing) row still reaches the cursor.
|
||||
// Without this, 150→0 is invisible and the later 40 is treated as a shrink.
|
||||
const discoveredIds = new Set(rows.map(row => row.id))
|
||||
const ledger = loadHermesSessionLedger()
|
||||
for (const sessionId of listHermesCursorSessionIds(ledger, profile)) {
|
||||
if (discoveredIds.has(sessionId)) continue
|
||||
sources.push({
|
||||
path: encodeSourcePath(dbPath, sessionId),
|
||||
project: displayProjectForProfile(profile),
|
||||
provider: 'hermes',
|
||||
})
|
||||
}
|
||||
return sources
|
||||
} catch (err) {
|
||||
if (isSqliteBusyError(err)) throw err
|
||||
process.stderr.write(`codeburn: error querying Hermes database: ${err instanceof Error ? err.message : err}\n`)
|
||||
|
|
@ -505,7 +607,9 @@ function createParser(source: SessionSource, seenKeys: Set<string>, hermesHome:
|
|||
return
|
||||
}
|
||||
|
||||
let result: ParsedProviderCall | undefined
|
||||
let result: {
|
||||
calls: ParsedProviderCall[]
|
||||
} | undefined
|
||||
try {
|
||||
if (!validateSchema(db)) return
|
||||
const columns = getSessionColumns(db)
|
||||
|
|
@ -533,7 +637,39 @@ function createParser(source: SessionSource, seenKeys: Set<string>, hermesHome:
|
|||
[decoded.sessionId],
|
||||
)
|
||||
const row = rows[0]
|
||||
if (!row) return
|
||||
const ledger = loadHermesSessionLedger()
|
||||
const existingCursor = getHermesCursor(ledger, profile, decoded.sessionId)
|
||||
if (!row) {
|
||||
if (!existingCursor) return
|
||||
const baselineKey = hermesBaselineKey(profile, decoded.sessionId)
|
||||
if (seenKeys.has(baselineKey)) return
|
||||
seenKeys.add(baselineKey)
|
||||
const cursor = await recordHermesSnapshot({
|
||||
profile,
|
||||
sessionId: decoded.sessionId,
|
||||
startedAt: existingCursor.observations[0]?.timestamp || hermesLedgerNow().toISOString(),
|
||||
observedAt: hermesLedgerNow().toISOString(),
|
||||
tokens: zeroHermesTokens(),
|
||||
costUSD: 0,
|
||||
costBasis: 'calculated',
|
||||
})
|
||||
for (const observation of cursor.observations) {
|
||||
if (observation.index > 0) seenKeys.add(hermesObservationKey(profile, decoded.sessionId, observation.index))
|
||||
}
|
||||
result = {
|
||||
calls: cursor.observations.map(observation => observationToCall(observation, {
|
||||
profile,
|
||||
sessionId: decoded.sessionId,
|
||||
model: 'unknown',
|
||||
tools: [],
|
||||
bashCommands: [],
|
||||
toolSequence: [],
|
||||
userMessage: '',
|
||||
project: displayProjectForProfile(profile),
|
||||
costIsEstimated: false,
|
||||
})),
|
||||
}
|
||||
} else {
|
||||
|
||||
const messageColumns = getMessageColumns(db)
|
||||
const orderColumns = ['timestamp', 'id'].filter(name => messageColumns.has(name))
|
||||
|
|
@ -556,15 +692,22 @@ function createParser(source: SessionSource, seenKeys: Set<string>, hermesHome:
|
|||
const cacheReadTokens = row.cache_read_tokens ?? 0
|
||||
const cacheWriteTokens = row.cache_write_tokens ?? 0
|
||||
const reasoningTokens = row.reasoning_tokens ?? 0
|
||||
if (inputTokens + outputTokens + cacheReadTokens + cacheWriteTokens + reasoningTokens === 0) return
|
||||
const tokens: HermesTokenTotals = {
|
||||
inputTokens,
|
||||
outputTokens,
|
||||
cacheReadTokens,
|
||||
cacheWriteTokens,
|
||||
reasoningTokens,
|
||||
}
|
||||
if (tokenSum(tokens) === 0 && !existingCursor) return
|
||||
|
||||
const model = row.model ?? 'unknown'
|
||||
const { tools, toolSequence, bashCommands } = collectTools(messages)
|
||||
const workspace = resolveHermesWorkspace(row, messages)
|
||||
const timestamp = parseTimestamp(row.started_at)
|
||||
const dedupKey = `hermes:${profile}:${row.id}`
|
||||
if (seenKeys.has(dedupKey)) return
|
||||
seenKeys.add(dedupKey)
|
||||
const baselineKey = hermesBaselineKey(profile, row.id)
|
||||
if (seenKeys.has(baselineKey)) return
|
||||
seenKeys.add(baselineKey)
|
||||
|
||||
const identity = workspace.projectPath
|
||||
? githubOwnerRepoFromRoot(workspace.projectPath)
|
||||
|
|
@ -576,62 +719,50 @@ function createParser(source: SessionSource, seenKeys: Set<string>, hermesHome:
|
|||
identity,
|
||||
)
|
||||
|
||||
// Hermes bills reasoning tokens at the output rate (same as Gemini).
|
||||
// The LiteLLM model table is used as a fallback when Hermes has not
|
||||
// stored an actual or estimated cost for the session.
|
||||
const calculatedCost = calculateCost(
|
||||
model,
|
||||
inputTokens,
|
||||
outputTokens + reasoningTokens,
|
||||
cacheWriteTokens,
|
||||
cacheReadTokens,
|
||||
0,
|
||||
)
|
||||
const recordedCost =
|
||||
(row.actual_cost_usd ?? 0) > 0 ? row.actual_cost_usd!
|
||||
: (row.estimated_cost_usd ?? 0) > 0 ? row.estimated_cost_usd!
|
||||
: null
|
||||
// When Hermes stored no cost (e.g. subscription-billed sessions), the
|
||||
// figure is our LiteLLM-priced estimate from the session token totals.
|
||||
const costUSD = recordedCost ?? calculatedCost
|
||||
const costIsEstimated = recordedCost === null
|
||||
|
||||
result = {
|
||||
provider: workspace.provider,
|
||||
model,
|
||||
inputTokens,
|
||||
outputTokens,
|
||||
cacheCreationInputTokens: cacheWriteTokens,
|
||||
cacheReadInputTokens: cacheReadTokens,
|
||||
cachedInputTokens: cacheReadTokens,
|
||||
reasoningTokens,
|
||||
webSearchRequests: 0,
|
||||
costUSD,
|
||||
costIsEstimated,
|
||||
tools,
|
||||
bashCommands,
|
||||
timestamp,
|
||||
speed: 'standard',
|
||||
deduplicationKey: dedupKey,
|
||||
turnId: `${row.id}:session`,
|
||||
toolSequence: toolSequence.length > 0 ? toolSequence : undefined,
|
||||
userMessage: firstUserMessage(messages),
|
||||
const cost = resolveHermesCost(row, model, tokens)
|
||||
const cursor = await recordHermesSnapshot({
|
||||
profile,
|
||||
sessionId: row.id,
|
||||
project: workspace.project,
|
||||
projectPath: workspace.projectPath,
|
||||
...(prLinks.length > 0 ? { prLinks } : {}),
|
||||
startedAt: timestamp || hermesLedgerNow().toISOString(),
|
||||
observedAt: hermesLedgerNow().toISOString(),
|
||||
tokens,
|
||||
costUSD: cost.costUSD,
|
||||
costBasis: cost.costBasis,
|
||||
})
|
||||
for (const observation of cursor.observations) {
|
||||
if (observation.index > 0) seenKeys.add(hermesObservationKey(profile, row.id, observation.index))
|
||||
}
|
||||
result = {
|
||||
calls: cursor.observations.map(observation => observationToCall(observation, {
|
||||
profile,
|
||||
sessionId: row.id,
|
||||
model,
|
||||
tools,
|
||||
bashCommands,
|
||||
toolSequence,
|
||||
userMessage: firstUserMessage(messages),
|
||||
project: workspace.project,
|
||||
projectPath: workspace.projectPath,
|
||||
prLinks,
|
||||
costIsEstimated: cost.costIsEstimated,
|
||||
})),
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
// A transient lock on the live state.db must propagate so the caller
|
||||
// retries, not get swallowed into an empty (negatively cached) result.
|
||||
if (isSqliteBusyError(err)) throw err
|
||||
process.stderr.write(`codeburn: error querying Hermes database: ${err instanceof Error ? err.message : err}\n`)
|
||||
// A transient lock on the live state.db, or a ledger publication
|
||||
// failure, must propagate so the caller retries — not get swallowed
|
||||
// into an empty (negatively cached) result.
|
||||
if (isSqliteBusyError(err) || isHermesLedgerPublicationError(err)) throw err
|
||||
const detail = err instanceof Error ? err.message : err
|
||||
process.stderr.write(`codeburn: error querying Hermes database: ${detail}\n`)
|
||||
return
|
||||
} finally {
|
||||
db.close()
|
||||
}
|
||||
|
||||
if (result) yield result
|
||||
if (result) {
|
||||
for (const call of result.calls) yield call
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -82,6 +82,9 @@ export type ParsedProviderCall = {
|
|||
projectPath?: string
|
||||
// GitHub PR URLs observed in this call's transcript (Hermes and similar).
|
||||
prLinks?: string[]
|
||||
// Hermes observation-time deltas persist this flag (and reconstruct it at
|
||||
// serve time from a `:obs:` key). Copilot still assigns it only at serve time.
|
||||
supplementaryAccounting?: boolean
|
||||
// Exact provider-recorded cwd, kept separately because projectPath may later
|
||||
// canonicalize a linked worktree to its main repository.
|
||||
workingDirectory?: string
|
||||
|
|
|
|||
|
|
@ -65,6 +65,10 @@ export type CachedCall = {
|
|||
// Copilot session-store rows only: the store's `initiator` label when
|
||||
// present. See ParsedProviderCall.initiator.
|
||||
initiator?: string
|
||||
// Hermes observation-time deltas persist this so a warm read does not
|
||||
// depend on the `:obs:` key regex alone. Copilot still assigns the flag
|
||||
// at serve time and does not persist it.
|
||||
supplementaryAccounting?: boolean
|
||||
}
|
||||
|
||||
export type CachedTurn = {
|
||||
|
|
@ -625,6 +629,7 @@ function validateCall(c: unknown): c is CachedCall {
|
|||
&& isOptionalBool(o['userModified'])
|
||||
&& isOptionalNum(o['toolErrors'])
|
||||
&& isOptionalNum(o['editFailed'])
|
||||
&& isOptionalBool(o['supplementaryAccounting'])
|
||||
&& validateUsage(o['usage'])
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -158,9 +158,10 @@ export type ParsedApiCall = {
|
|||
toolWaitMs?: number
|
||||
/// Supplementary accounting: this call's tokens/cost are real but the call is
|
||||
/// not a distinct behavioral request (copilot shutdown rollups and store rows
|
||||
/// that pair with an already-counted per-turn call). Aggregates keep its
|
||||
/// tokens/cost but skip it in apiCalls / model-call / turn counts. Transient:
|
||||
/// assigned at serve time, never cached.
|
||||
/// that pair with an already-counted per-turn call; Hermes observation-time
|
||||
/// deltas). Aggregates keep its tokens/cost but skip it in apiCalls /
|
||||
/// model-call / turn counts. Hermes deltas persist the flag on CachedCall;
|
||||
/// Copilot remains serve-time / never cached.
|
||||
supplementaryAccounting?: boolean
|
||||
}
|
||||
|
||||
|
|
|
|||
246
tests/hermes-session-ledger.test.ts
Normal file
246
tests/hermes-session-ledger.test.ts
Normal file
|
|
@ -0,0 +1,246 @@
|
|||
import { mkdir, mkdtemp, rm } from 'fs/promises'
|
||||
import { join } from 'path'
|
||||
import { tmpdir } from 'os'
|
||||
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
|
||||
|
||||
import {
|
||||
applyHermesSnapshot,
|
||||
hermesBaselineKey,
|
||||
hermesObservationKey,
|
||||
hermesSessionLedgerPath,
|
||||
isHermesLedgerPublicationError,
|
||||
isHermesObservationKey,
|
||||
loadHermesSessionLedger,
|
||||
parseHermesDedupKey,
|
||||
persistHermesSessionLedger,
|
||||
recordHermesSnapshot,
|
||||
resetHermesSessionLedgerForTests,
|
||||
seedHermesCursorsFromProviderSection,
|
||||
setHermesLedgerNow,
|
||||
type HermesSnapshot,
|
||||
} from '../src/hermes-session-ledger.js'
|
||||
import type { CachedCall, ProviderSection } from '../src/session-cache.js'
|
||||
|
||||
let cacheDir: string
|
||||
let originalCacheDir: string | undefined
|
||||
|
||||
beforeEach(async () => {
|
||||
cacheDir = await mkdtemp(join(tmpdir(), 'hermes-ledger-unit-'))
|
||||
originalCacheDir = process.env['CODEBURN_CACHE_DIR']
|
||||
process.env['CODEBURN_CACHE_DIR'] = cacheDir
|
||||
resetHermesSessionLedgerForTests()
|
||||
})
|
||||
|
||||
afterEach(async () => {
|
||||
resetHermesSessionLedgerForTests()
|
||||
if (originalCacheDir === undefined) delete process.env['CODEBURN_CACHE_DIR']
|
||||
else process.env['CODEBURN_CACHE_DIR'] = originalCacheDir
|
||||
await rm(cacheDir, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
function snap(overrides: Partial<HermesSnapshot> = {}): HermesSnapshot {
|
||||
const { tokens: tokenOverrides, ...rest } = overrides
|
||||
return {
|
||||
profile: 'default',
|
||||
sessionId: 's1',
|
||||
startedAt: '2026-08-21T10:00:00.000Z',
|
||||
observedAt: '2026-08-22T10:00:00.000Z',
|
||||
costUSD: 0.10,
|
||||
costBasis: 'actual',
|
||||
...rest,
|
||||
tokens: {
|
||||
inputTokens: 100,
|
||||
outputTokens: 0,
|
||||
cacheReadTokens: 0,
|
||||
cacheWriteTokens: 0,
|
||||
reasoningTokens: 0,
|
||||
...tokenOverrides,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
describe('hermes session ledger unit', () => {
|
||||
it('parses baseline and observation keys', () => {
|
||||
expect(parseHermesDedupKey('hermes:default:abc')).toEqual({ profile: 'default', sessionId: 'abc' })
|
||||
expect(parseHermesDedupKey('hermes:coder:abc:obs:1')).toEqual({
|
||||
profile: 'coder',
|
||||
sessionId: 'abc',
|
||||
observationIndex: 1,
|
||||
})
|
||||
expect(isHermesObservationKey('hermes:default:abc')).toBe(false)
|
||||
expect(isHermesObservationKey('hermes:default:abc:obs:2')).toBe(true)
|
||||
expect(hermesBaselineKey('default', 'abc')).toBe('hermes:default:abc')
|
||||
expect(hermesObservationKey('default', 'abc', 1)).toBe('hermes:default:abc:obs:1')
|
||||
})
|
||||
|
||||
it('first observation is behavioral lifetime at started_at', () => {
|
||||
const { cursor, dirty } = applyHermesSnapshot(undefined, snap())
|
||||
expect(dirty).toBe(true)
|
||||
expect(cursor.observations).toHaveLength(1)
|
||||
expect(cursor.observations[0]).toMatchObject({
|
||||
index: 0,
|
||||
timestamp: '2026-08-21T10:00:00.000Z',
|
||||
inputTokens: 100,
|
||||
costUSD: 0.10,
|
||||
supplementaryAccounting: false,
|
||||
})
|
||||
expect(cursor.lastSeen.inputTokens).toBe(100)
|
||||
})
|
||||
|
||||
it('growth emits a positive delta only', () => {
|
||||
const first = applyHermesSnapshot(undefined, snap()).cursor
|
||||
const { cursor, dirty } = applyHermesSnapshot(first, snap({
|
||||
tokens: { inputTokens: 150, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0, reasoningTokens: 0 },
|
||||
costUSD: 0.15,
|
||||
}))
|
||||
expect(dirty).toBe(true)
|
||||
expect(cursor.observations).toHaveLength(2)
|
||||
expect(cursor.observations[1]!.index).toBe(1)
|
||||
expect(cursor.observations[1]!.timestamp).toBe('2026-08-22T10:00:00.000Z')
|
||||
expect(cursor.observations[1]!.inputTokens).toBe(50)
|
||||
expect(cursor.observations[1]!.costUSD).toBeCloseTo(0.05)
|
||||
expect(cursor.observations[1]!.supplementaryAccounting).toBe(true)
|
||||
expect(cursor.lastSeen).toMatchObject({ inputTokens: 150, costUSD: 0.15 })
|
||||
})
|
||||
|
||||
it('equal totals re-emit stored observations with no new row', () => {
|
||||
const first = applyHermesSnapshot(undefined, snap()).cursor
|
||||
const { cursor, dirty } = applyHermesSnapshot(first, snap())
|
||||
expect(dirty).toBe(false)
|
||||
expect(cursor.observations).toHaveLength(1)
|
||||
expect(cursor).toBe(first)
|
||||
})
|
||||
|
||||
it('150 → 0 advances last-seen to zero and emits no observation', () => {
|
||||
const first = applyHermesSnapshot(undefined, snap({
|
||||
tokens: { inputTokens: 150, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0, reasoningTokens: 0 },
|
||||
costUSD: 0.15,
|
||||
})).cursor
|
||||
const { cursor, dirty } = applyHermesSnapshot(first, snap({
|
||||
tokens: { inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0, reasoningTokens: 0 },
|
||||
costUSD: 0,
|
||||
}))
|
||||
expect(dirty).toBe(true)
|
||||
expect(cursor.observations).toHaveLength(1)
|
||||
expect(cursor.lastSeen.inputTokens).toBe(0)
|
||||
expect(cursor.lastSeen.costUSD).toBe(0)
|
||||
})
|
||||
|
||||
it('0 → 40 after a zero reset emits one +40 weight-0 observation', () => {
|
||||
const first = applyHermesSnapshot(undefined, snap({
|
||||
tokens: { inputTokens: 150, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0, reasoningTokens: 0 },
|
||||
})).cursor
|
||||
const zeroed = applyHermesSnapshot(first, snap({
|
||||
tokens: { inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0, reasoningTokens: 0 },
|
||||
costUSD: 0,
|
||||
})).cursor
|
||||
const { cursor } = applyHermesSnapshot(zeroed, snap({
|
||||
tokens: { inputTokens: 40, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0, reasoningTokens: 0 },
|
||||
costUSD: 0.04,
|
||||
}))
|
||||
expect(cursor.observations).toHaveLength(2)
|
||||
expect(cursor.observations[1]).toMatchObject({
|
||||
index: 1,
|
||||
inputTokens: 40,
|
||||
costUSD: 0.04,
|
||||
supplementaryAccounting: true,
|
||||
})
|
||||
expect(cursor.observations.some(o => o.inputTokens < 0 || o.costUSD < 0)).toBe(false)
|
||||
})
|
||||
|
||||
it('a cost-basis shrink is a cost reset without a negative', () => {
|
||||
const first = applyHermesSnapshot(undefined, snap()).cursor
|
||||
const { cursor } = applyHermesSnapshot(first, snap({
|
||||
tokens: { inputTokens: 150, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0, reasoningTokens: 0 },
|
||||
costUSD: 0.05,
|
||||
costBasis: 'estimated',
|
||||
}))
|
||||
expect(cursor.observations).toHaveLength(2)
|
||||
expect(cursor.observations[1]).toMatchObject({
|
||||
inputTokens: 50,
|
||||
costUSD: 0,
|
||||
supplementaryAccounting: true,
|
||||
})
|
||||
expect(cursor.lastSeen.costUSD).toBe(0.05)
|
||||
expect(cursor.lastSeen.costBasis).toBe('estimated')
|
||||
})
|
||||
|
||||
it('clock is injectable for observation timestamps', async () => {
|
||||
setHermesLedgerNow(() => new Date('2026-08-22T15:30:00.000Z'))
|
||||
const cursor = await recordHermesSnapshot(snap({
|
||||
observedAt: new Date('2026-08-22T15:30:00.000Z').toISOString(),
|
||||
}))
|
||||
const grown = await recordHermesSnapshot(snap({
|
||||
tokens: { inputTokens: 120, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0, reasoningTokens: 0 },
|
||||
costUSD: 0.12,
|
||||
observedAt: new Date('2026-08-22T15:30:00.000Z').toISOString(),
|
||||
}))
|
||||
expect(grown.observations[1]!.timestamp).toBe('2026-08-22T15:30:00.000Z')
|
||||
expect(cursor.observations[0]!.timestamp).toBe('2026-08-21T10:00:00.000Z')
|
||||
})
|
||||
|
||||
it('seed writes one behavioral observation and does not overwrite existing keys', async () => {
|
||||
const call: CachedCall = {
|
||||
provider: 'hermes',
|
||||
model: 'gpt-5.5',
|
||||
usage: {
|
||||
inputTokens: 100,
|
||||
outputTokens: 0,
|
||||
cacheCreationInputTokens: 0,
|
||||
cacheReadInputTokens: 0,
|
||||
cachedInputTokens: 0,
|
||||
reasoningTokens: 0,
|
||||
webSearchRequests: 0,
|
||||
cacheCreationOneHourTokens: 0,
|
||||
},
|
||||
costUSD: 0.10,
|
||||
speed: 'standard',
|
||||
timestamp: '2026-08-21T10:00:00.000Z',
|
||||
tools: ['Read'],
|
||||
bashCommands: [],
|
||||
skills: [],
|
||||
subagentTypes: [],
|
||||
deduplicationKey: 'hermes:default:seeded',
|
||||
}
|
||||
const section: ProviderSection = {
|
||||
envFingerprint: 'test',
|
||||
files: {
|
||||
'/tmp/state.db#hermes-session=seeded': {
|
||||
fingerprint: { dev: 1, ino: 1, mtimeMs: 1, sizeBytes: 1 },
|
||||
mcpInventory: [],
|
||||
turns: [{ timestamp: call.timestamp, sessionId: 'seeded', userMessage: 'hi', calls: [call] }],
|
||||
},
|
||||
},
|
||||
}
|
||||
await seedHermesCursorsFromProviderSection(section)
|
||||
const first = loadHermesSessionLedger()
|
||||
expect(first.cursors['default']!['seeded']!.observations).toHaveLength(1)
|
||||
expect(first.cursors['default']!['seeded']!.observations[0]).toMatchObject({
|
||||
index: 0,
|
||||
timestamp: '2026-08-21T10:00:00.000Z',
|
||||
inputTokens: 100,
|
||||
supplementaryAccounting: false,
|
||||
})
|
||||
|
||||
section.files['/tmp/state.db#hermes-session=seeded']!.turns[0]!.calls[0] = {
|
||||
...call,
|
||||
usage: { ...call.usage, inputTokens: 999 },
|
||||
timestamp: '2026-08-22T10:00:00.000Z',
|
||||
}
|
||||
await seedHermesCursorsFromProviderSection(section)
|
||||
const second = loadHermesSessionLedger()
|
||||
expect(second.cursors['default']!['seeded']!.observations).toHaveLength(1)
|
||||
expect(second.cursors['default']!['seeded']!.lastSeen.inputTokens).toBe(100)
|
||||
})
|
||||
|
||||
it('publication failure is a typed retryable error', async () => {
|
||||
await mkdir(hermesSessionLedgerPath())
|
||||
let caught: unknown
|
||||
try {
|
||||
await persistHermesSessionLedger({ version: 1, cursors: {} })
|
||||
} catch (err) {
|
||||
caught = err
|
||||
}
|
||||
expect(isHermesLedgerPublicationError(caught)).toBe(true)
|
||||
})
|
||||
})
|
||||
389
tests/providers/hermes-ledger.test.ts
Normal file
389
tests/providers/hermes-ledger.test.ts
Normal file
|
|
@ -0,0 +1,389 @@
|
|||
import { mkdir, mkdtemp, rm, unlink } from 'fs/promises'
|
||||
import { homedir } from 'os'
|
||||
import { join, resolve } from 'path'
|
||||
import { createRequire } from 'node:module'
|
||||
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { createHermesProvider } from '../../src/providers/hermes.js'
|
||||
import { isSqliteAvailable } from '../../src/sqlite.js'
|
||||
import { aggregateProjectsIntoDays, dateKey } from '../../src/day-aggregator.js'
|
||||
import { behavioralTurnCount } from '../../src/behavioral-weight.js'
|
||||
import {
|
||||
getHermesCursor,
|
||||
hermesSessionLedgerPath,
|
||||
loadHermesSessionLedger,
|
||||
resetHermesSessionLedgerForTests,
|
||||
} from '../../src/hermes-session-ledger.js'
|
||||
import type { ParsedProviderCall } from '../../src/providers/types.js'
|
||||
|
||||
const requireForTest = createRequire(import.meta.url)
|
||||
|
||||
type TestDb = {
|
||||
exec(sql: string): void
|
||||
prepare(sql: string): { run(...params: unknown[]): void }
|
||||
close(): void
|
||||
}
|
||||
|
||||
const CLEANHOME_ROOT = '/tmp/cb-cleanhome'
|
||||
const REAL_HERMES_HOME = resolve(join(homedir(), '.hermes'))
|
||||
|
||||
let hermesHome: string
|
||||
let cacheDir: string
|
||||
let originalHermesHome: string | undefined
|
||||
let originalCodeburnCacheDir: string | undefined
|
||||
|
||||
beforeEach(async () => {
|
||||
await mkdir(CLEANHOME_ROOT, { recursive: true })
|
||||
hermesHome = await mkdtemp(join(CLEANHOME_ROOT, 'home-'))
|
||||
cacheDir = await mkdtemp(join(CLEANHOME_ROOT, 'cache-'))
|
||||
expect(resolve(hermesHome)).not.toBe(REAL_HERMES_HOME)
|
||||
originalHermesHome = process.env['HERMES_HOME']
|
||||
originalCodeburnCacheDir = process.env['CODEBURN_CACHE_DIR']
|
||||
process.env['HERMES_HOME'] = hermesHome
|
||||
process.env['CODEBURN_CACHE_DIR'] = cacheDir
|
||||
resetHermesSessionLedgerForTests()
|
||||
})
|
||||
|
||||
afterEach(async () => {
|
||||
resetHermesSessionLedgerForTests()
|
||||
if (originalHermesHome === undefined) delete process.env['HERMES_HOME']
|
||||
else process.env['HERMES_HOME'] = originalHermesHome
|
||||
if (originalCodeburnCacheDir === undefined) delete process.env['CODEBURN_CACHE_DIR']
|
||||
else process.env['CODEBURN_CACHE_DIR'] = originalCodeburnCacheDir
|
||||
await rm(hermesHome, { recursive: true, force: true })
|
||||
await rm(cacheDir, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
function createHermesDb(homeDir: string): string {
|
||||
const { DatabaseSync: Database } = requireForTest('node:sqlite')
|
||||
const dbPath = join(homeDir, 'state.db')
|
||||
const db = new Database(dbPath)
|
||||
db.exec(`
|
||||
CREATE TABLE sessions (
|
||||
id TEXT PRIMARY KEY,
|
||||
source TEXT,
|
||||
model TEXT,
|
||||
cwd TEXT,
|
||||
git_repo_root TEXT,
|
||||
billing_provider TEXT,
|
||||
input_tokens INTEGER DEFAULT 0,
|
||||
output_tokens INTEGER DEFAULT 0,
|
||||
cache_read_tokens INTEGER DEFAULT 0,
|
||||
cache_write_tokens INTEGER DEFAULT 0,
|
||||
reasoning_tokens INTEGER DEFAULT 0,
|
||||
estimated_cost_usd REAL,
|
||||
actual_cost_usd REAL,
|
||||
api_call_count INTEGER DEFAULT 0,
|
||||
tool_call_count INTEGER DEFAULT 0,
|
||||
started_at REAL,
|
||||
ended_at REAL,
|
||||
title TEXT
|
||||
)
|
||||
`)
|
||||
db.exec(`
|
||||
CREATE TABLE messages (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
session_id TEXT NOT NULL,
|
||||
role TEXT NOT NULL,
|
||||
content TEXT,
|
||||
tool_call_id TEXT,
|
||||
tool_calls TEXT,
|
||||
tool_name TEXT,
|
||||
timestamp REAL NOT NULL
|
||||
)
|
||||
`)
|
||||
db.close()
|
||||
return dbPath
|
||||
}
|
||||
|
||||
async function createProfileHermesDb(home: string, profile: string): Promise<string> {
|
||||
const profileDir = join(home, 'profiles', profile)
|
||||
await mkdir(profileDir, { recursive: true })
|
||||
return createHermesDb(profileDir)
|
||||
}
|
||||
|
||||
function withTestDb(dbPath: string, fn: (db: TestDb) => void): void {
|
||||
const { DatabaseSync: Database } = requireForTest('node:sqlite')
|
||||
const db = new Database(dbPath)
|
||||
try {
|
||||
fn(db)
|
||||
} finally {
|
||||
db.close()
|
||||
}
|
||||
}
|
||||
|
||||
function insertSession(db: TestDb, values: {
|
||||
id: string
|
||||
inputTokens: number
|
||||
outputTokens?: number
|
||||
actualCost?: number | null
|
||||
estimatedCost?: number | null
|
||||
startedAt: number
|
||||
model?: string
|
||||
}): void {
|
||||
db.prepare(
|
||||
`INSERT INTO sessions (
|
||||
id, source, model, input_tokens, output_tokens, cache_read_tokens, cache_write_tokens,
|
||||
reasoning_tokens, estimated_cost_usd, actual_cost_usd, api_call_count, tool_call_count,
|
||||
started_at, title
|
||||
) VALUES (?, 'cli', ?, ?, ?, 0, 0, 0, ?, ?, 1, 0, ?, ?)`,
|
||||
).run(
|
||||
values.id,
|
||||
values.model ?? 'gpt-5.5',
|
||||
values.inputTokens,
|
||||
values.outputTokens ?? 0,
|
||||
values.estimatedCost ?? null,
|
||||
values.actualCost ?? null,
|
||||
values.startedAt,
|
||||
values.id,
|
||||
)
|
||||
}
|
||||
|
||||
function updateSession(db: TestDb, id: string, values: {
|
||||
inputTokens: number
|
||||
actualCost?: number | null
|
||||
}): void {
|
||||
db.prepare('UPDATE sessions SET input_tokens = ?, actual_cost_usd = ? WHERE id = ?')
|
||||
.run(values.inputTokens, values.actualCost ?? null, id)
|
||||
}
|
||||
|
||||
function localDay(offsetDays: number, hour = 10): { date: Date; unixSec: number; key: string; iso: string } {
|
||||
const date = new Date()
|
||||
date.setHours(hour, 0, 0, 0)
|
||||
date.setDate(date.getDate() + offsetDays)
|
||||
return {
|
||||
date,
|
||||
unixSec: date.getTime() / 1000,
|
||||
key: `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`,
|
||||
iso: date.toISOString(),
|
||||
}
|
||||
}
|
||||
|
||||
async function loadParser() {
|
||||
process.env['HERMES_HOME'] = hermesHome
|
||||
process.env['CODEBURN_CACHE_DIR'] = cacheDir
|
||||
vi.resetModules()
|
||||
resetHermesSessionLedgerForTests()
|
||||
return import('../../src/parser.js')
|
||||
}
|
||||
|
||||
async function parseDiscovered(): Promise<{ sources: { path: string }[]; calls: ParsedProviderCall[] }> {
|
||||
const provider = createHermesProvider(hermesHome)
|
||||
const sources = await provider.discoverSessions()
|
||||
const calls: ParsedProviderCall[] = []
|
||||
const seen = new Set<string>()
|
||||
for (const source of sources) {
|
||||
for await (const call of provider.createSessionParser(source, seen).parse()) {
|
||||
calls.push(call)
|
||||
}
|
||||
}
|
||||
return { sources, calls }
|
||||
}
|
||||
|
||||
const skipUnlessSqlite = isSqliteAvailable() ? describe : describe.skip
|
||||
|
||||
skipUnlessSqlite('hermes post-finalization ledger proofs', () => {
|
||||
it('P1: sealed day D keeps 100/$0.10/1/1; D+1 is +50/$0.05/0/0', async () => {
|
||||
const dayD = localDay(-1)
|
||||
const dbPath = createHermesDb(hermesHome)
|
||||
withTestDb(dbPath, (db) => {
|
||||
insertSession(db, { id: 'p1', inputTokens: 100, actualCost: 0.10, startedAt: dayD.unixSec })
|
||||
db.prepare('INSERT INTO messages (session_id, role, content, timestamp) VALUES (?, ?, ?, ?)')
|
||||
.run('p1', 'user', 'keep going', dayD.unixSec + 1)
|
||||
})
|
||||
|
||||
const parser = await loadParser()
|
||||
parser.clearSessionCache()
|
||||
const firstProjects = await parser.parseAllSessions(undefined, 'hermes')
|
||||
const { ensureCacheHydrated, loadDailyCache } = await import('../../src/daily-cache.js')
|
||||
await ensureCacheHydrated(
|
||||
(range) => parser.parseAllSessions(range, 'hermes'),
|
||||
aggregateProjectsIntoDays,
|
||||
'',
|
||||
parser.isSessionHydrationComplete,
|
||||
)
|
||||
const sealed = await loadDailyCache()
|
||||
expect(sealed.lastComputedDate).toBe(dayD.key)
|
||||
const sealedDay = sealed.days.find(d => d.date === dayD.key)
|
||||
expect(sealedDay?.inputTokens).toBe(100)
|
||||
expect(sealedDay?.cost).toBeCloseTo(0.10)
|
||||
expect(sealedDay?.calls).toBe(1)
|
||||
expect(sealedDay?.sessions).toBe(1)
|
||||
|
||||
withTestDb(dbPath, (db) => {
|
||||
updateSession(db, 'p1', { inputTokens: 150, actualCost: 0.15 })
|
||||
})
|
||||
parser.clearSessionCache()
|
||||
const grown = await parser.parseAllSessions(undefined, 'hermes')
|
||||
const days = aggregateProjectsIntoDays(grown)
|
||||
const todayKey = dateKey(new Date().toISOString())
|
||||
const dEntry = days.find(d => d.date === dayD.key)
|
||||
const todayEntry = days.find(d => d.date === todayKey)
|
||||
expect(dEntry?.inputTokens).toBe(100)
|
||||
expect(dEntry?.cost).toBeCloseTo(0.10)
|
||||
expect(dEntry?.calls).toBe(1)
|
||||
expect(dEntry?.sessions).toBe(1)
|
||||
expect(todayEntry?.inputTokens).toBe(50)
|
||||
expect(todayEntry?.cost).toBeCloseTo(0.05)
|
||||
expect(todayEntry?.calls).toBe(0)
|
||||
expect(todayEntry?.sessions ?? 0).toBe(0)
|
||||
|
||||
const session = grown.flatMap(p => p.sessions)[0]!
|
||||
expect(session.apiCalls).toBe(1)
|
||||
expect(behavioralTurnCount(session.turns)).toBe(1)
|
||||
expect(session.totalInputTokens).toBe(150)
|
||||
expect(session.totalCostUSD).toBeCloseTo(0.15)
|
||||
|
||||
await ensureCacheHydrated(
|
||||
(range) => parser.parseAllSessions(range, 'hermes'),
|
||||
aggregateProjectsIntoDays,
|
||||
'',
|
||||
parser.isSessionHydrationComplete,
|
||||
)
|
||||
const stillSealed = await loadDailyCache()
|
||||
const stillD = stillSealed.days.find(d => d.date === dayD.key)
|
||||
expect(stillD?.inputTokens).toBe(100)
|
||||
expect(stillD?.calls).toBe(1)
|
||||
expect(firstProjects.length).toBeGreaterThan(0)
|
||||
})
|
||||
|
||||
it('P2: same sessionId in default and coder are two cursors', async () => {
|
||||
const started = localDay(0).unixSec
|
||||
const rootDb = createHermesDb(hermesHome)
|
||||
const coderDb = await createProfileHermesDb(hermesHome, 'coder')
|
||||
withTestDb(rootDb, (db) => {
|
||||
insertSession(db, { id: 'shared', inputTokens: 100, actualCost: 0.10, startedAt: started })
|
||||
})
|
||||
withTestDb(coderDb, (db) => {
|
||||
insertSession(db, { id: 'shared', inputTokens: 80, actualCost: 0.08, startedAt: started })
|
||||
})
|
||||
|
||||
await parseDiscovered()
|
||||
const ledger = loadHermesSessionLedger()
|
||||
expect(getHermesCursor(ledger, 'default', 'shared')?.lastSeen.inputTokens).toBe(100)
|
||||
expect(getHermesCursor(ledger, 'coder', 'shared')?.lastSeen.inputTokens).toBe(80)
|
||||
|
||||
withTestDb(rootDb, (db) => {
|
||||
updateSession(db, 'shared', { inputTokens: 130, actualCost: 0.13 })
|
||||
})
|
||||
const { calls } = await parseDiscovered()
|
||||
const later = loadHermesSessionLedger()
|
||||
expect(getHermesCursor(later, 'default', 'shared')?.lastSeen.inputTokens).toBe(130)
|
||||
expect(getHermesCursor(later, 'coder', 'shared')?.lastSeen.inputTokens).toBe(80)
|
||||
expect(calls.filter(c => c.deduplicationKey.includes(':obs:')).every(c => c.deduplicationKey.startsWith('hermes:default:'))).toBe(true)
|
||||
})
|
||||
|
||||
it('P3: 150→0 last-seen 0 no observation; 0→40 one +40 weight-0 via discoverFromDb', async () => {
|
||||
const started = localDay(-1).unixSec
|
||||
const dbPath = createHermesDb(hermesHome)
|
||||
withTestDb(dbPath, (db) => {
|
||||
insertSession(db, { id: 'p3', inputTokens: 150, actualCost: 0.15, startedAt: started })
|
||||
})
|
||||
|
||||
const first = await parseDiscovered()
|
||||
expect(first.sources.some(s => s.path.includes('p3'))).toBe(true)
|
||||
expect(first.calls).toHaveLength(1)
|
||||
expect(first.calls[0]!.deduplicationKey).toBe('hermes:default:p3')
|
||||
expect(getHermesCursor(loadHermesSessionLedger(), 'default', 'p3')?.lastSeen.inputTokens).toBe(150)
|
||||
|
||||
withTestDb(dbPath, (db) => {
|
||||
updateSession(db, 'p3', { inputTokens: 0, actualCost: 0 })
|
||||
})
|
||||
const zeroed = await parseDiscovered()
|
||||
expect(zeroed.sources.some(s => s.path.endsWith('#hermes-session=p3') || s.path.includes('hermes-session=p3'))).toBe(true)
|
||||
expect(zeroed.calls.filter(c => c.deduplicationKey.includes(':obs:'))).toHaveLength(0)
|
||||
expect(getHermesCursor(loadHermesSessionLedger(), 'default', 'p3')?.lastSeen.inputTokens).toBe(0)
|
||||
expect(getHermesCursor(loadHermesSessionLedger(), 'default', 'p3')?.observations).toHaveLength(1)
|
||||
|
||||
withTestDb(dbPath, (db) => {
|
||||
updateSession(db, 'p3', { inputTokens: 40, actualCost: 0.04 })
|
||||
})
|
||||
const grown = await parseDiscovered()
|
||||
const deltas = grown.calls.filter(c => c.deduplicationKey.includes(':obs:'))
|
||||
expect(deltas).toHaveLength(1)
|
||||
expect(deltas[0]).toMatchObject({
|
||||
inputTokens: 40,
|
||||
costUSD: 0.04,
|
||||
supplementaryAccounting: true,
|
||||
tools: [],
|
||||
userMessage: '',
|
||||
})
|
||||
expect(deltas[0]!.deduplicationKey).toBe('hermes:default:p3:obs:1')
|
||||
expect(getHermesCursor(loadHermesSessionLedger(), 'default', 'p3')?.observations).toHaveLength(2)
|
||||
expect(getHermesCursor(loadHermesSessionLedger(), 'default', 'p3')?.observations.some(o => o.inputTokens < 0)).toBe(false)
|
||||
})
|
||||
|
||||
it('P4: explicit $0 actual is recorded, not LiteLLM fallback', async () => {
|
||||
const dbPath = createHermesDb(hermesHome)
|
||||
withTestDb(dbPath, (db) => {
|
||||
insertSession(db, { id: 'p4', inputTokens: 80, actualCost: 0, startedAt: localDay(0).unixSec })
|
||||
})
|
||||
const { calls } = await parseDiscovered()
|
||||
expect(calls).toHaveLength(1)
|
||||
expect(calls[0]!.costUSD).toBe(0)
|
||||
expect(calls[0]!.costIsEstimated).toBe(false)
|
||||
expect(getHermesCursor(loadHermesSessionLedger(), 'default', 'p4')?.lastSeen.costBasis).toBe('actual')
|
||||
})
|
||||
|
||||
it('P5: seed from a cached lifetime call does not dump lifetime at now', async () => {
|
||||
const started = localDay(-1)
|
||||
const dbPath = createHermesDb(hermesHome)
|
||||
withTestDb(dbPath, (db) => {
|
||||
insertSession(db, { id: 'p5', inputTokens: 100, actualCost: 0.10, startedAt: started.unixSec })
|
||||
})
|
||||
|
||||
const parser = await loadParser()
|
||||
const ledgerMod = await import('../../src/hermes-session-ledger.js')
|
||||
parser.clearSessionCache()
|
||||
await parser.parseAllSessions(undefined, 'hermes')
|
||||
|
||||
await unlink(ledgerMod.hermesSessionLedgerPath())
|
||||
ledgerMod.resetHermesSessionLedgerForTests()
|
||||
|
||||
parser.clearSessionCache()
|
||||
await parser.parseAllSessions(undefined, 'hermes')
|
||||
const seeded = ledgerMod.loadHermesSessionLedger()
|
||||
const cursor = ledgerMod.getHermesCursor(seeded, 'default', 'p5')
|
||||
expect(cursor?.observations).toHaveLength(1)
|
||||
expect(cursor?.observations[0]?.supplementaryAccounting).toBe(false)
|
||||
expect(cursor?.observations[0]?.inputTokens).toBe(100)
|
||||
expect(dateKey(cursor!.observations[0]!.timestamp)).toBe(started.key)
|
||||
})
|
||||
|
||||
it('P6: unwritable ledger is retryable and does not advance lastComputedDate', async () => {
|
||||
const dayD = localDay(-1)
|
||||
const dbPath = createHermesDb(hermesHome)
|
||||
withTestDb(dbPath, (db) => {
|
||||
insertSession(db, { id: 'p6', inputTokens: 100, actualCost: 0.10, startedAt: dayD.unixSec })
|
||||
})
|
||||
await mkdir(hermesSessionLedgerPath())
|
||||
|
||||
const parser = await loadParser()
|
||||
parser.clearSessionCache()
|
||||
await parser.parseAllSessions(undefined, 'hermes')
|
||||
expect(parser.isSessionHydrationComplete()).toBe(false)
|
||||
|
||||
const { ensureCacheHydrated, loadDailyCache } = await import('../../src/daily-cache.js')
|
||||
await ensureCacheHydrated(
|
||||
(range) => parser.parseAllSessions(range, 'hermes'),
|
||||
aggregateProjectsIntoDays,
|
||||
'',
|
||||
parser.isSessionHydrationComplete,
|
||||
)
|
||||
const daily = await loadDailyCache()
|
||||
expect(daily.lastComputedDate).not.toBe(dayD.key)
|
||||
expect(daily.complete).not.toBe(true)
|
||||
})
|
||||
|
||||
it('P7: first observation key stays hermes:default:<id> with no :obs:', async () => {
|
||||
const dbPath = createHermesDb(hermesHome)
|
||||
withTestDb(dbPath, (db) => {
|
||||
insertSession(db, { id: 'p7-id', inputTokens: 10, actualCost: 0.01, startedAt: localDay(0).unixSec })
|
||||
})
|
||||
const { calls } = await parseDiscovered()
|
||||
expect(calls[0]!.deduplicationKey).toBe('hermes:default:p7-id')
|
||||
expect(calls[0]!.deduplicationKey.includes(':obs:')).toBe(false)
|
||||
expect(calls[0]!.turnId).toBe('p7-id:session')
|
||||
expect(calls[0]!.supplementaryAccounting).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
|
@ -28,6 +28,10 @@ beforeEach(async () => {
|
|||
cacheDir = await mkdtemp(join(tmpdir(), 'hermes-provider-cache-'))
|
||||
originalHermesHome = process.env['HERMES_HOME']
|
||||
originalCodeburnCacheDir = process.env['CODEBURN_CACHE_DIR']
|
||||
process.env['HERMES_HOME'] = tmpDir
|
||||
process.env['CODEBURN_CACHE_DIR'] = cacheDir
|
||||
const { resetHermesSessionLedgerForTests } = await import('../../src/hermes-session-ledger.js')
|
||||
resetHermesSessionLedgerForTests()
|
||||
})
|
||||
|
||||
afterEach(async () => {
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue