mirror of
https://github.com/AgentSeal/codeburn.git
synced 2026-12-03 03:29:51 +00:00
Merge main into feat/omp-support-model-aliases
Second merge of main since the PR was opened. Main moved 30+ commits
(0.8.5 bump, plan tracking feature, MiniMax pricing, menubar
prefetchAll walk-back, aicrowd cache rewrite revert) so the branch
needed another reconciliation before merging to main.
Two new conflicts resolved. Took main's text in both cases per the
policy of favoring main when the feature work is neutral:
README.md Kept main's Node 20+ / better-sqlite3
Requirements wording and main's shorter src/
tree listing. Added OMP to the Requirements
line.
src/providers/pi.ts Main dropped the discovery-cache snapshot and
the rich source-metadata fields as part of the
aicrowd revert. Took main's simpler structure
and only kept the providerName parameter so
OMP sources still report the correct provider
in the session source and dedup key.
Earlier fixups carried forward from the prior merge commit:
- Object.hasOwn guards in resolveAlias against prototype-pollution
via a model literally named '__proto__'.
- source.provider in the dedup key prefix so OMP rows no longer
stamp 'pi:'.
- Combined pi.js imports in providers/index.ts.
- Trailing newline on pi.ts.
- Unknown-model fallback in cursor-agent.ts from yesterday's PR #117
fixup (preserved via main).
353 tests pass (count dropped from 378 because main deleted the
parse-progress / parser-cache / provider-colors / source-cache test
files alongside the cache-rewrite revert).
Feature work by @cgrossde.
This commit is contained in:
commit
4f1138290e
38 changed files with 481 additions and 3332 deletions
23
.github/workflows/firstlook.yml
vendored
Normal file
23
.github/workflows/firstlook.yml
vendored
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
name: firstlook
|
||||
on:
|
||||
pull_request:
|
||||
types: [opened, reopened, synchronize]
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
pr-number:
|
||||
description: 'PR number to scan (leave empty for all open PRs)'
|
||||
required: false
|
||||
type: string
|
||||
|
||||
jobs:
|
||||
assess:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
pull-requests: write
|
||||
contents: read
|
||||
steps:
|
||||
- uses: getagentseal/firstlook@main
|
||||
with:
|
||||
pr-number: ${{ inputs.pr-number }}
|
||||
skip-users: 'dependabot[bot],renovate[bot]'
|
||||
fail-on: 'unknown'
|
||||
37
CHANGELOG.md
37
CHANGELOG.md
|
|
@ -1,37 +1,18 @@
|
|||
# Changelog
|
||||
|
||||
## 0.8.4 - 2026-04-20
|
||||
## 0.8.5 - 2026-04-21
|
||||
|
||||
### Fixed
|
||||
- **Menubar hang on large session histories.** Menubar-json now uses the source cache instead of re-parsing all files on every poll.
|
||||
- **Stale Today totals after 0.8.2.** The persistent source cache introduced in 0.8.2 caused Today's cost to under-report and sometimes drop between polls during active Claude Code sessions. The cache keyed entries on `(mtime, size)` fingerprints that diverged from Claude's append-mostly JSONL model, producing empty or partial entries that were served on subsequent polls. Reverted the cache rewrite to the v0.8.1 full-reparse path for Claude sessions. Both the menubar and `codeburn status` now return consistent, monotonically-increasing Today totals.
|
||||
- **Menubar and terminal status disagreed on Today.** A turn that straddled midnight (user message in one day, response in the next) was bucketed by user timestamp in one code path and by assistant timestamp in another, producing different Today values in the two surfaces. Both paths now count a turn on the day its first assistant call ran.
|
||||
- **Kept from 0.8.2-0.8.4:** subscription plan tracking, pricing accuracy and CSV injection hardening, cursor-agent provider, menubar prefetch and timezone alignment. Only the cache rewrite and its follow-up patches were reverted.
|
||||
|
||||
## 0.8.3 - 2026-04-20
|
||||
### Removed
|
||||
- `--no-cache` flag on `report`, `today`, `month`, `status`, `export`, `optimize`, and `compare`. The flag existed to bypass the persistent source cache which no longer exists. If your scripts pass `--no-cache`, drop it; the parse runs fresh every time now.
|
||||
|
||||
### Fixed
|
||||
- **Source cache empty-session poisoning.** Cache entries with zero sessions are now treated as cache misses, forcing a fresh re-parse instead of silently dropping the session data.
|
||||
- **Date range skip on changed files.** The date range exclusion now runs only after the fingerprint matches, so files that have grown with new data are never incorrectly skipped.
|
||||
- **TUI auto-refresh not updating.** The 30-second refresh timer now bypasses the in-memory CachedWindow, which was permanently stale because the date range end is always end-of-day.
|
||||
- **Menubar showing stale or decreasing costs.** Fixed cache invalidation so the menubar receives correct, up-to-date cost data.
|
||||
- **Swift menubar observation race.** Explicit UI refresh calls after each data fetch prevent missed updates from the one-shot observation callback.
|
||||
|
||||
## 0.8.2 - 2026-04-20
|
||||
|
||||
### Added
|
||||
- **Persistent parse cache for all providers.** Repeated CLI runs now reuse parsed source summaries across fresh processes instead of reparsing raw logs every time. Cache lives at `~/.cache/codeburn/source-cache-v1/` with atomic writes and 0600 file permissions. Credit: @spMohanty (PR #116).
|
||||
- **`--no-cache` on parse-backed commands.** `report`, `today`, `month`, `status`, `export`, `optimize`, and `compare` can bypass cached entries for that run and rebuild them from raw logs. Credit: @spMohanty (PR #116).
|
||||
- **`Updating cache` stderr progress.** Non-JSON cold or partial cache rebuilds now show progress while CodeBurn refreshes changed sources. Credit: @spMohanty (PR #116).
|
||||
- **`codeburn plan` subscription tracking.** Set your plan (`claude-pro`, `claude-max`, `cursor-pro`, or custom) to see a usage progress bar in the dashboard. Includes 7-day trailing median projection and billing-cycle-aware period math. Credit: @tmchow (PR #74).
|
||||
|
||||
### Changed
|
||||
- **Cursor now uses the shared parse cache.** The provider-specific Cursor cache path is gone; SQLite-backed provider data now flows through the same persistent cache layer as the other providers. Credit: @spMohanty (PR #116).
|
||||
|
||||
### Fixed
|
||||
- **Model pricing: removed bidirectional fuzzy match.** `canonical.startsWith(key) || key.startsWith(canonical)` could match unrelated models. Now uses one-directional prefix only. Credit: @hobostay (PR #77).
|
||||
- **Zero-cost models incorrectly filtered.** `!entry.input_cost_per_token` treated `0` as missing. Now checks `=== undefined` so free-tier models retain their pricing entry. Credit: @hobostay (PR #77).
|
||||
- **File descriptor leak in `readSessionLines`.** Generator now calls `stream.destroy()` in a `finally` block so early abandonment does not leak open handles. Credit: @hobostay (PR #77).
|
||||
- **CSV injection guard extended.** Tab and carriage return characters at cell start are now escaped alongside `=`, `+`, `-`, `@`. Credit: @hobostay (PR #77).
|
||||
- **Crash on empty export periods.** Optional chaining prevents `undefined` access when a period has no projects. Credit: @hobostay (PR #77).
|
||||
- **Config read crash on malformed JSON.** Restored catch-all error handling in `readConfig` so a corrupt `config.json` returns defaults instead of crashing.
|
||||
### Notes
|
||||
- 0.8.2, 0.8.3, and 0.8.4 on npm contain the buggy cache. Upgrade with `npm i -g codeburn@latest` or `npm i -g codeburn@0.8.5`.
|
||||
- This release uses a full reparse on every invocation, matching v0.8.1 behavior. On large corpora (5,000+ session files) expect 3 to 10 seconds per invocation. An incremental refresh design that preserves correctness is planned for a follow-up release.
|
||||
|
||||
## 0.8.0 - 2026-04-19
|
||||
|
||||
|
|
|
|||
77
README.md
77
README.md
|
|
@ -10,7 +10,7 @@
|
|||
<a href="https://www.npmjs.com/package/codeburn"><img src="https://img.shields.io/npm/v/codeburn.svg" alt="npm version" /></a>
|
||||
<a href="https://www.npmjs.com/package/codeburn"><img src="https://img.shields.io/npm/dt/codeburn.svg" alt="total downloads" /></a>
|
||||
<a href="https://github.com/getagentseal/codeburn/blob/main/LICENSE"><img src="https://img.shields.io/npm/l/codeburn.svg" alt="license" /></a>
|
||||
<a href="https://github.com/getagentseal/codeburn"><img src="https://img.shields.io/badge/node-%3E%3D22-brightgreen.svg" alt="node version" /></a>
|
||||
<a href="https://github.com/getagentseal/codeburn"><img src="https://img.shields.io/badge/node-%3E%3D20-brightgreen.svg" alt="node version" /></a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
|
|
@ -35,9 +35,9 @@ npx codeburn
|
|||
|
||||
### Requirements
|
||||
|
||||
- Node.js 22+
|
||||
- Node.js 20+
|
||||
- Claude Code (`~/.claude/projects/`), Codex (`~/.codex/sessions/`), Cursor, OpenCode, Pi (`~/.pi/agent/sessions/`), OMP (`~/.omp/agent/sessions/`), and/or GitHub Copilot (`~/.copilot/session-state/`)
|
||||
- For Cursor/OpenCode support: uses Node's built-in `node:sqlite` (Node 22+)
|
||||
- For Cursor/OpenCode support: `better-sqlite3` is installed automatically as an optional dependency
|
||||
|
||||
## Usage
|
||||
|
||||
|
|
@ -80,25 +80,6 @@ codeburn today --format json | jq '.overview.cost'
|
|||
|
||||
For the lighter `status --format json` (today + month totals only) or file-based exports (`export -f json`), see above.
|
||||
|
||||
## Cache behavior
|
||||
|
||||
CodeBurn now keeps a persistent parse cache under `~/.cache/codeburn/source-cache-v1/`.
|
||||
It applies to every provider. Unchanged sources load from cache across fresh CLI runs,
|
||||
while changed sources are refreshed on demand so rolling windows like `today` stay current
|
||||
as new log entries land.
|
||||
|
||||
Use `--no-cache` on any command that reads session data to ignore cached entries for that
|
||||
run and rebuild them from raw logs:
|
||||
|
||||
```bash
|
||||
codeburn today --no-cache
|
||||
codeburn report --period all --no-cache
|
||||
codeburn export --no-cache
|
||||
```
|
||||
|
||||
When a non-JSON command needs to rebuild part of the cache, CodeBurn shows an
|
||||
`Updating cache` progress bar on stderr. JSON output stays clean on stdout.
|
||||
|
||||
## Providers
|
||||
|
||||
CodeBurn auto-detects which AI coding tools you use. If multiple providers have session data on disk, press `p` in the dashboard to toggle between them.
|
||||
|
|
@ -162,7 +143,7 @@ Either flag alone is valid. Inverted or malformed dates exit with a clear error.
|
|||
|
||||
Codex tool names are normalized to match Claude's conventions (`exec_command` shows as `Bash`, `read_file` as `Read`, etc.) so the activity classifier and tool breakdown work across providers.
|
||||
|
||||
Cursor reads token usage from its local SQLite database via Node's built-in `node:sqlite`. Since Cursor's "Auto" mode hides the actual model used, costs are estimated using Sonnet pricing (labeled "Auto (Sonnet est.)" in the dashboard). The Cursor view shows a **Languages** panel (extracted from code blocks) instead of Core Tools/Shell/MCP panels, since Cursor does not log individual tool calls. Parsed results are cached through the shared persistent cache layer.
|
||||
Cursor reads token usage from its local SQLite database. Since Cursor's "Auto" mode hides the actual model used, costs are estimated using Sonnet pricing (labeled "Auto (Sonnet est.)" in the dashboard). The Cursor view shows a **Languages** panel (extracted from code blocks) instead of Core Tools/Shell/MCP panels, since Cursor does not log individual tool calls. First run on a large Cursor database may take up to a minute; results are cached and subsequent runs are instant.
|
||||
|
||||
GitHub Copilot only logs output tokens in its session state, so Copilot cost rows sit below actual API cost. The model is tracked via `session.model_change` events; messages before the first model change are skipped to avoid silent misattribution.
|
||||
|
||||
|
|
@ -358,36 +339,28 @@ CodeBurn reads these files, deduplicates messages (by API message ID for Claude,
|
|||
|
||||
```
|
||||
src/
|
||||
cli.ts Commander.js entry point
|
||||
dashboard.tsx Ink TUI (React for terminals)
|
||||
parser.ts JSONL reader, dedup, date filter, provider orchestration
|
||||
models.ts LiteLLM pricing, cost calculation
|
||||
classifier.ts 13-category task classifier
|
||||
compare-stats.ts Model comparison engine (metrics, category breakdown, working style)
|
||||
types.ts Type definitions
|
||||
format.ts Text rendering (status bar)
|
||||
menubar-json.ts Payload builder consumed by the native macOS menubar app in mac/
|
||||
export.ts CSV/JSON multi-period export
|
||||
config.ts Config file management (~/.config/codeburn/)
|
||||
currency.ts Currency conversion, exchange rates, Intl formatting
|
||||
sqlite.ts SQLite adapter (node:sqlite)
|
||||
source-cache.ts Persistent parse cache (manifest + per-source entries)
|
||||
discovery-cache.ts Provider directory scan caching
|
||||
parse-progress.ts Stderr progress bar for cache rebuilds
|
||||
provider-colors.ts Provider color and label constants
|
||||
plans.ts Subscription plan presets and validators
|
||||
plan-usage.ts Billing period math and usage projection
|
||||
fs-utils.ts Bounded file readers with stream support
|
||||
cli.ts Commander.js entry point
|
||||
dashboard.tsx Ink TUI (React for terminals)
|
||||
parser.ts JSONL reader, dedup, date filter, provider orchestration
|
||||
models.ts LiteLLM pricing, cost calculation
|
||||
classifier.ts 13-category task classifier
|
||||
compare-stats.ts Model comparison engine (metrics, category breakdown, working style)
|
||||
types.ts Type definitions
|
||||
format.ts Text rendering (status bar)
|
||||
menubar-json.ts Payload builder consumed by the native macOS menubar app in mac/
|
||||
export.ts CSV/JSON multi-period export
|
||||
config.ts Config file management (~/.config/codeburn/)
|
||||
currency.ts Currency conversion, exchange rates, Intl formatting
|
||||
sqlite.ts SQLite adapter (lazy-loads better-sqlite3)
|
||||
cursor-cache.ts Cursor result cache (file-based, auto-invalidating)
|
||||
providers/
|
||||
types.ts Provider interface definitions
|
||||
index.ts Provider registry (lazy-loads Cursor, cursor-agent, OpenCode)
|
||||
claude.ts Claude Code session discovery
|
||||
codex.ts Codex session discovery and JSONL parsing
|
||||
copilot.ts GitHub Copilot session state parsing
|
||||
cursor.ts Cursor SQLite parsing, language extraction
|
||||
cursor-agent.ts cursor-agent CLI transcript parsing
|
||||
opencode.ts OpenCode SQLite session discovery and parsing
|
||||
pi.ts Pi/OMP agent JSONL session discovery and parsing
|
||||
types.ts Provider interface definitions
|
||||
index.ts Provider registry (lazy-loads Cursor, OpenCode)
|
||||
claude.ts Claude Code session discovery
|
||||
codex.ts Codex session discovery and JSONL parsing
|
||||
cursor.ts Cursor SQLite parsing, language extraction
|
||||
opencode.ts OpenCode SQLite session discovery and parsing
|
||||
pi.ts Pi/OMP agent JSONL session discovery and parsing
|
||||
```
|
||||
|
||||
## Star History
|
||||
|
|
|
|||
20
bin/codeburn
20
bin/codeburn
|
|
@ -1,20 +0,0 @@
|
|||
#!/usr/bin/env node
|
||||
|
||||
import { homedir } from "node:os";
|
||||
|
||||
try {
|
||||
process.cwd();
|
||||
} catch (error) {
|
||||
if (
|
||||
error &&
|
||||
typeof error === "object" &&
|
||||
"code" in error &&
|
||||
(error).code === "ENOENT"
|
||||
) {
|
||||
process.chdir(homedir());
|
||||
} else {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
await import("../dist/cli.js");
|
||||
|
|
@ -89,15 +89,6 @@ final class AppStore {
|
|||
}
|
||||
}
|
||||
|
||||
/// Prefetch all periods so tab switching is instant. Skips any period already cached.
|
||||
func prefetchAll() async {
|
||||
for period in Period.allCases {
|
||||
let key = PayloadCacheKey(period: period, provider: .all)
|
||||
if cache[key] != nil { continue }
|
||||
await refreshQuietly(period: period)
|
||||
}
|
||||
}
|
||||
|
||||
/// Background refresh for a period other than the visible one (e.g. keeping today fresh for the menubar badge).
|
||||
/// Does not toggle isLoading, so the popover's loading overlay is unaffected.
|
||||
/// Always uses the .all provider since the menubar badge shows total spend.
|
||||
|
|
|
|||
|
|
@ -72,12 +72,11 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSPopoverDelegate {
|
|||
private func startRefreshLoop() {
|
||||
refreshTask = Task { [weak self] in
|
||||
guard let s = self else { return }
|
||||
// First cycle: fetch current view, then prefetch all periods in background
|
||||
// First cycle: fetch today so the status icon has a number within seconds of launch.
|
||||
await s.store.refreshQuietly(period: .today)
|
||||
s.refreshStatusButton()
|
||||
await s.store.refresh(includeOptimize: true)
|
||||
s.refreshStatusButton()
|
||||
await s.store.prefetchAll()
|
||||
|
||||
while !Task.isCancelled {
|
||||
try? await Task.sleep(nanoseconds: refreshIntervalNanos)
|
||||
|
|
@ -88,6 +87,13 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSPopoverDelegate {
|
|||
s.refreshStatusButton()
|
||||
}
|
||||
}
|
||||
|
||||
// Period tabs are fetched lazily when the user first clicks them in the popover.
|
||||
// An earlier version prefetched every period on launch to make tab switching instant,
|
||||
// but on large session corpora that spawned four concurrent codeburn subprocesses
|
||||
// competing with the main refresh loop for disk and parser time, and the status label
|
||||
// drifted stale for minutes. A per-tab first-click cost of a few seconds is the better
|
||||
// tradeoff on user machines that track thousands of sessions.
|
||||
}
|
||||
|
||||
private func observeStore() {
|
||||
|
|
|
|||
|
|
@ -1,15 +1,14 @@
|
|||
{
|
||||
"name": "codeburn",
|
||||
"version": "0.8.4",
|
||||
"version": "0.8.5",
|
||||
"description": "See where your AI coding tokens go - by task, tool, model, and project",
|
||||
"type": "module",
|
||||
"main": "./dist/cli.js",
|
||||
"bin": {
|
||||
"codeburn": "bin/codeburn"
|
||||
"codeburn": "dist/cli.js"
|
||||
},
|
||||
"files": [
|
||||
"dist",
|
||||
"bin"
|
||||
"dist"
|
||||
],
|
||||
"scripts": {
|
||||
"build": "tsup",
|
||||
|
|
|
|||
73
src/cli.ts
73
src/cli.ts
|
|
@ -12,7 +12,6 @@ import { aggregateProjectsIntoDays, buildPeriodDataFromDays, dateKey } from './d
|
|||
import { CATEGORY_LABELS, type DateRange, type ProjectSummary, type TaskCategory } from './types.js'
|
||||
import { renderDashboard } from './dashboard.js'
|
||||
import { parseDateRangeFlags } from './cli-date.js'
|
||||
import { createTerminalProgressReporter } from './parse-progress.js'
|
||||
import { runOptimize, scanAndDetect } from './optimize.js'
|
||||
import { renderCompare } from './compare.js'
|
||||
import { getAllProviders } from './providers/index.js'
|
||||
|
|
@ -121,14 +120,10 @@ function toJsonPlanSummary(planUsage: PlanUsage): JsonPlanSummary {
|
|||
}
|
||||
}
|
||||
|
||||
async function runJsonReport(period: Period, provider: string, project: string[], exclude: string[], noCache = false): Promise<void> {
|
||||
async function runJsonReport(period: Period, provider: string, project: string[], exclude: string[]): Promise<void> {
|
||||
await loadPricing()
|
||||
const { range, label } = getDateRange(period)
|
||||
const projects = filterProjectsByName(
|
||||
await parseAllSessions(range, provider, { noCache, progress: null }),
|
||||
project,
|
||||
exclude,
|
||||
)
|
||||
const projects = filterProjectsByName(await parseAllSessions(range, provider), project, exclude)
|
||||
const report: ReturnType<typeof buildJsonReport> & { plan?: JsonPlanSummary } = buildJsonReport(projects, label, period)
|
||||
const planUsage = await getPlanUsageOrNull()
|
||||
if (planUsage) {
|
||||
|
|
@ -137,17 +132,6 @@ async function runJsonReport(period: Period, provider: string, project: string[]
|
|||
console.log(JSON.stringify(report, null, 2))
|
||||
}
|
||||
|
||||
function noCacheRequested(opts: { cache?: boolean }): boolean {
|
||||
return opts.cache === false
|
||||
}
|
||||
|
||||
function buildParseOptions(noCache: boolean, enableProgress: boolean) {
|
||||
return {
|
||||
noCache,
|
||||
progress: createTerminalProgressReporter(enableProgress),
|
||||
}
|
||||
}
|
||||
|
||||
const program = new Command()
|
||||
.name('codeburn')
|
||||
.description('See where your AI coding tokens go - by task, tool, model, and project')
|
||||
|
|
@ -306,10 +290,8 @@ program
|
|||
.option('--format <format>', 'Output format: tui, json', 'tui')
|
||||
.option('--project <name>', 'Show only projects matching name (repeatable)', collect, [])
|
||||
.option('--exclude <name>', 'Exclude projects matching name (repeatable)', collect, [])
|
||||
.option('--no-cache', 'Rebuild the parsed source cache for this run')
|
||||
.option('--refresh <seconds>', 'Auto-refresh interval in seconds (0 to disable)', parseInt, 30)
|
||||
.action(async (opts) => {
|
||||
const noCache = noCacheRequested(opts)
|
||||
let customRange: DateRange | null = null
|
||||
try {
|
||||
customRange = parseDateRangeFlags(opts.from, opts.to)
|
||||
|
|
@ -325,17 +307,17 @@ program
|
|||
if (customRange) {
|
||||
const label = `${opts.from ?? 'all'} to ${opts.to ?? 'today'}`
|
||||
const projects = filterProjectsByName(
|
||||
await parseAllSessions(customRange, opts.provider, { noCache, progress: null }),
|
||||
await parseAllSessions(customRange, opts.provider),
|
||||
opts.project,
|
||||
opts.exclude,
|
||||
)
|
||||
console.log(JSON.stringify(buildJsonReport(projects, label, 'custom'), null, 2))
|
||||
} else {
|
||||
await runJsonReport(period, opts.provider, opts.project, opts.exclude, noCache)
|
||||
await runJsonReport(period, opts.provider, opts.project, opts.exclude)
|
||||
}
|
||||
return
|
||||
}
|
||||
await renderDashboard(period, opts.provider, opts.refresh, opts.project, opts.exclude, customRange, noCache)
|
||||
await renderDashboard(period, opts.provider, opts.refresh, opts.project, opts.exclude, customRange)
|
||||
})
|
||||
|
||||
function buildPeriodData(label: string, projects: ProjectSummary[]): PeriodData {
|
||||
|
|
@ -387,11 +369,8 @@ program
|
|||
.option('--exclude <name>', 'Exclude projects matching name (repeatable)', collect, [])
|
||||
.option('--period <period>', 'Primary period for menubar-json: today, week, 30days, month, all', 'today')
|
||||
.option('--no-optimize', 'Skip optimize findings (menubar-json only, faster)')
|
||||
.option('--no-cache', 'Rebuild the parsed source cache for this run')
|
||||
.action(async (opts) => {
|
||||
await loadPricing()
|
||||
const noCache = noCacheRequested(opts)
|
||||
const parseOptions = buildParseOptions(noCache, opts.format === 'terminal')
|
||||
const pf = opts.provider
|
||||
const fp = (p: ProjectSummary[]) => filterProjectsByName(p, opts.project, opts.exclude)
|
||||
if (opts.format === 'menubar-json') {
|
||||
|
|
@ -426,7 +405,7 @@ program
|
|||
|
||||
if (gapStart.getTime() <= yesterdayEnd.getTime()) {
|
||||
const gapRange: DateRange = { start: gapStart, end: yesterdayEnd }
|
||||
const gapProjects = filterProjectsByName(await parseAllSessions(gapRange, 'all', { noCache, progress: null }), opts.project, opts.exclude)
|
||||
const gapProjects = filterProjectsByName(await parseAllSessions(gapRange, 'all'), opts.project, opts.exclude)
|
||||
const gapDays = aggregateProjectsIntoDays(gapProjects)
|
||||
c = addNewDays(c, gapDays, yesterdayStr)
|
||||
await saveDailyCache(c)
|
||||
|
|
@ -443,7 +422,7 @@ program
|
|||
|
||||
if (isAllProviders) {
|
||||
const todayRange: DateRange = { start: todayStart, end: now }
|
||||
const todayProjects = fp(await parseAllSessions(todayRange, 'all', { noCache, progress: null }))
|
||||
const todayProjects = fp(await parseAllSessions(todayRange, 'all'))
|
||||
const todayDays = aggregateProjectsIntoDays(todayProjects)
|
||||
const rangeStartStr = toDateString(periodInfo.range.start)
|
||||
const rangeEndStr = toDateString(periodInfo.range.end)
|
||||
|
|
@ -454,7 +433,7 @@ program
|
|||
scanProjects = todayProjects
|
||||
scanRange = todayRange
|
||||
} else {
|
||||
const projects = fp(await parseAllSessions(periodInfo.range, pf, { noCache, progress: null }))
|
||||
const projects = fp(await parseAllSessions(periodInfo.range, pf))
|
||||
currentData = buildPeriodData(periodInfo.label, projects)
|
||||
scanProjects = projects
|
||||
scanRange = periodInfo.range
|
||||
|
|
@ -468,7 +447,7 @@ program
|
|||
const providers: ProviderCost[] = []
|
||||
if (isAllProviders) {
|
||||
const todayRangeForProviders: DateRange = { start: todayStart, end: now }
|
||||
const todayDaysForProviders = aggregateProjectsIntoDays(fp(await parseAllSessions(todayRangeForProviders, 'all', { noCache, progress: null })))
|
||||
const todayDaysForProviders = aggregateProjectsIntoDays(fp(await parseAllSessions(todayRangeForProviders, 'all')))
|
||||
const rangeStartStr = toDateString(periodInfo.range.start)
|
||||
const allDaysForProviders = [
|
||||
...getDaysInRange(cache, rangeStartStr, yesterdayStr),
|
||||
|
|
@ -499,7 +478,7 @@ program
|
|||
// in the cache, so the filtered view shows zero tokens (heatmap/trend still works on cost).
|
||||
const historyStartStr = toDateString(new Date(todayStart.getTime() - BACKFILL_DAYS * MS_PER_DAY))
|
||||
const allCacheDays = getDaysInRange(cache, historyStartStr, yesterdayStr)
|
||||
const allTodayDaysForHistory = aggregateProjectsIntoDays(fp(await parseAllSessions({ start: todayStart, end: now }, 'all', { noCache, progress: null })))
|
||||
const allTodayDaysForHistory = aggregateProjectsIntoDays(fp(await parseAllSessions({ start: todayStart, end: now }, 'all')))
|
||||
const fullHistory = [...allCacheDays, ...allTodayDaysForHistory]
|
||||
const dailyHistory = fullHistory.map(d => {
|
||||
if (isAllProviders) {
|
||||
|
|
@ -544,8 +523,8 @@ program
|
|||
}
|
||||
|
||||
if (opts.format === 'json') {
|
||||
const todayData = buildPeriodData('today', fp(await parseAllSessions(getDateRange('today').range, pf, { noCache, progress: null })))
|
||||
const monthData = buildPeriodData('month', fp(await parseAllSessions(getDateRange('month').range, pf, { noCache, progress: null })))
|
||||
const todayData = buildPeriodData('today', fp(await parseAllSessions(getDateRange('today').range, pf)))
|
||||
const monthData = buildPeriodData('month', fp(await parseAllSessions(getDateRange('month').range, pf)))
|
||||
const { code, rate } = getCurrency()
|
||||
const payload: {
|
||||
currency: string
|
||||
|
|
@ -565,7 +544,7 @@ program
|
|||
return
|
||||
}
|
||||
|
||||
const monthProjects = fp(await parseAllSessions(getDateRange('month').range, pf, parseOptions))
|
||||
const monthProjects = fp(await parseAllSessions(getDateRange('month').range, pf))
|
||||
console.log(renderStatusBar(monthProjects))
|
||||
})
|
||||
|
||||
|
|
@ -576,15 +555,13 @@ program
|
|||
.option('--format <format>', 'Output format: tui, json', 'tui')
|
||||
.option('--project <name>', 'Show only projects matching name (repeatable)', collect, [])
|
||||
.option('--exclude <name>', 'Exclude projects matching name (repeatable)', collect, [])
|
||||
.option('--no-cache', 'Rebuild the parsed source cache for this run')
|
||||
.option('--refresh <seconds>', 'Auto-refresh interval in seconds (0 to disable)', parseInt, 30)
|
||||
.action(async (opts) => {
|
||||
const noCache = noCacheRequested(opts)
|
||||
if (opts.format === 'json') {
|
||||
await runJsonReport('today', opts.provider, opts.project, opts.exclude, noCache)
|
||||
await runJsonReport('today', opts.provider, opts.project, opts.exclude)
|
||||
return
|
||||
}
|
||||
await renderDashboard('today', opts.provider, opts.refresh, opts.project, opts.exclude, null, noCache)
|
||||
await renderDashboard('today', opts.provider, opts.refresh, opts.project, opts.exclude)
|
||||
})
|
||||
|
||||
program
|
||||
|
|
@ -594,15 +571,13 @@ program
|
|||
.option('--format <format>', 'Output format: tui, json', 'tui')
|
||||
.option('--project <name>', 'Show only projects matching name (repeatable)', collect, [])
|
||||
.option('--exclude <name>', 'Exclude projects matching name (repeatable)', collect, [])
|
||||
.option('--no-cache', 'Rebuild the parsed source cache for this run')
|
||||
.option('--refresh <seconds>', 'Auto-refresh interval in seconds (0 to disable)', parseInt, 30)
|
||||
.action(async (opts) => {
|
||||
const noCache = noCacheRequested(opts)
|
||||
if (opts.format === 'json') {
|
||||
await runJsonReport('month', opts.provider, opts.project, opts.exclude, noCache)
|
||||
await runJsonReport('month', opts.provider, opts.project, opts.exclude)
|
||||
return
|
||||
}
|
||||
await renderDashboard('month', opts.provider, opts.refresh, opts.project, opts.exclude, null, noCache)
|
||||
await renderDashboard('month', opts.provider, opts.refresh, opts.project, opts.exclude)
|
||||
})
|
||||
|
||||
program
|
||||
|
|
@ -613,16 +588,14 @@ program
|
|||
.option('--provider <provider>', 'Filter by provider: all, claude, codex, cursor', 'all')
|
||||
.option('--project <name>', 'Show only projects matching name (repeatable)', collect, [])
|
||||
.option('--exclude <name>', 'Exclude projects matching name (repeatable)', collect, [])
|
||||
.option('--no-cache', 'Rebuild the parsed source cache for this run')
|
||||
.action(async (opts) => {
|
||||
await loadPricing()
|
||||
const parseOptions = buildParseOptions(noCacheRequested(opts), true)
|
||||
const pf = opts.provider
|
||||
const fp = (p: ProjectSummary[]) => filterProjectsByName(p, opts.project, opts.exclude)
|
||||
const periods: PeriodExport[] = [
|
||||
{ label: 'Today', projects: fp(await parseAllSessions(getDateRange('today').range, pf, parseOptions)) },
|
||||
{ label: '7 Days', projects: fp(await parseAllSessions(getDateRange('week').range, pf, parseOptions)) },
|
||||
{ label: '30 Days', projects: fp(await parseAllSessions(getDateRange('30days').range, pf, parseOptions)) },
|
||||
{ label: 'Today', projects: fp(await parseAllSessions(getDateRange('today').range, pf)) },
|
||||
{ label: '7 Days', projects: fp(await parseAllSessions(getDateRange('week').range, pf)) },
|
||||
{ label: '30 Days', projects: fp(await parseAllSessions(getDateRange('30days').range, pf)) },
|
||||
]
|
||||
|
||||
if (periods.every(p => p.projects.length === 0)) {
|
||||
|
|
@ -892,11 +865,10 @@ program
|
|||
.description('Find token waste and get exact fixes')
|
||||
.option('-p, --period <period>', 'Analysis period: today, week, 30days, month, all', '30days')
|
||||
.option('--provider <provider>', 'Filter by provider: all, claude, codex, cursor', 'all')
|
||||
.option('--no-cache', 'Rebuild the parsed source cache for this run')
|
||||
.action(async (opts) => {
|
||||
await loadPricing()
|
||||
const { range, label } = getDateRange(opts.period)
|
||||
const projects = await parseAllSessions(range, opts.provider, buildParseOptions(noCacheRequested(opts), true))
|
||||
const projects = await parseAllSessions(range, opts.provider)
|
||||
await runOptimize(projects, label, range)
|
||||
})
|
||||
|
||||
|
|
@ -905,11 +877,10 @@ program
|
|||
.description('Compare two AI models side-by-side')
|
||||
.option('-p, --period <period>', 'Analysis period: today, week, 30days, month, all', 'all')
|
||||
.option('--provider <provider>', 'Filter by provider: all, claude, codex, cursor', 'all')
|
||||
.option('--no-cache', 'Rebuild the parsed source cache for this run')
|
||||
.action(async (opts) => {
|
||||
await loadPricing()
|
||||
const { range } = getDateRange(opts.period)
|
||||
await renderCompare(range, opts.provider, noCacheRequested(opts))
|
||||
await renderCompare(range, opts.provider)
|
||||
})
|
||||
|
||||
program.parse()
|
||||
|
|
|
|||
|
|
@ -5,7 +5,6 @@ import type { ModelStats, ComparisonRow, CategoryComparison, WorkingStyleRow } f
|
|||
import { aggregateModelStats, computeComparison, computeCategoryComparison, computeWorkingStyle, scanSelfCorrections } from './compare-stats.js'
|
||||
import { formatCost } from './format.js'
|
||||
import { parseAllSessions } from './parser.js'
|
||||
import { createTerminalProgressReporter } from './parse-progress.js'
|
||||
import { getAllProviders } from './providers/index.js'
|
||||
import type { ProjectSummary, DateRange } from './types.js'
|
||||
|
||||
|
|
@ -442,17 +441,14 @@ export function CompareView({ projects, onBack }: CompareViewProps) {
|
|||
)
|
||||
}
|
||||
|
||||
export async function renderCompare(range: DateRange, provider: string, noCache = false): Promise<void> {
|
||||
export async function renderCompare(range: DateRange, provider: string): Promise<void> {
|
||||
const isTTY = process.stdin.isTTY && process.stdout.isTTY
|
||||
if (!isTTY) {
|
||||
process.stdout.write('Model comparison requires an interactive terminal.\n')
|
||||
return
|
||||
}
|
||||
|
||||
const projects = await parseAllSessions(range, provider, {
|
||||
noCache,
|
||||
progress: createTerminalProgressReporter(true),
|
||||
})
|
||||
const projects = await parseAllSessions(range, provider)
|
||||
const { waitUntilExit } = render(
|
||||
<CompareView projects={projects} onBack={() => process.exit(0)} />
|
||||
)
|
||||
|
|
|
|||
63
src/cursor-cache.ts
Normal file
63
src/cursor-cache.ts
Normal file
|
|
@ -0,0 +1,63 @@
|
|||
import { readFile, writeFile, mkdir, stat } from 'fs/promises'
|
||||
import { join } from 'path'
|
||||
import { homedir } from 'os'
|
||||
|
||||
import type { ParsedProviderCall } from './providers/types.js'
|
||||
|
||||
type ResultCache = {
|
||||
dbMtimeMs: number
|
||||
dbSizeBytes: number
|
||||
calls: ParsedProviderCall[]
|
||||
}
|
||||
|
||||
const CACHE_FILE = 'cursor-results.json'
|
||||
|
||||
function getCacheDir(): string {
|
||||
return join(homedir(), '.cache', 'codeburn')
|
||||
}
|
||||
|
||||
function getCachePath(): string {
|
||||
return join(getCacheDir(), CACHE_FILE)
|
||||
}
|
||||
|
||||
async function getDbFingerprint(dbPath: string): Promise<{ mtimeMs: number; size: number } | null> {
|
||||
try {
|
||||
const s = await stat(dbPath)
|
||||
return { mtimeMs: s.mtimeMs, size: s.size }
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
export async function readCachedResults(dbPath: string): Promise<ParsedProviderCall[] | null> {
|
||||
try {
|
||||
const fp = await getDbFingerprint(dbPath)
|
||||
if (!fp) return null
|
||||
|
||||
const raw = await readFile(getCachePath(), 'utf-8')
|
||||
const cache = JSON.parse(raw) as ResultCache
|
||||
|
||||
if (cache.dbMtimeMs === fp.mtimeMs && cache.dbSizeBytes === fp.size) {
|
||||
return cache.calls
|
||||
}
|
||||
return null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
export async function writeCachedResults(dbPath: string, calls: ParsedProviderCall[]): Promise<void> {
|
||||
try {
|
||||
const fp = await getDbFingerprint(dbPath)
|
||||
if (!fp) return
|
||||
|
||||
const dir = getCacheDir()
|
||||
await mkdir(dir, { recursive: true })
|
||||
const cache: ResultCache = {
|
||||
dbMtimeMs: fp.mtimeMs,
|
||||
dbSizeBytes: fp.size,
|
||||
calls,
|
||||
}
|
||||
await writeFile(getCachePath(), JSON.stringify(cache), 'utf-8')
|
||||
} catch {}
|
||||
}
|
||||
|
|
@ -4,31 +4,20 @@ import React, { useState, useCallback, useEffect, useRef } from 'react'
|
|||
import { render, Box, Text, useInput, useApp, useWindowSize } from 'ink'
|
||||
import { CATEGORY_LABELS, type DateRange, type ProjectSummary, type TaskCategory } from './types.js'
|
||||
import { formatCost, formatTokens } from './format.js'
|
||||
import { parseAllSessions, filterProjectsByDateRange, filterProjectsByName } from './parser.js'
|
||||
import { parseAllSessions, filterProjectsByName } from './parser.js'
|
||||
import { loadPricing } from './models.js'
|
||||
import { getAllProviders } from './providers/index.js'
|
||||
import { scanAndDetect, type WasteFinding, type WasteAction, type OptimizeResult } from './optimize.js'
|
||||
import { estimateContextBudget, discoverProjectCwd, type ContextBudget } from './context-budget.js'
|
||||
import { dateKey } from './day-aggregator.js'
|
||||
import { createTerminalProgressReporter } from './parse-progress.js'
|
||||
import { CompareView } from './compare.js'
|
||||
import { getPlanUsageOrNull, type PlanUsage } from './plan-usage.js'
|
||||
import { planDisplayName } from './plans.js'
|
||||
import { providerColor, providerLabel } from './provider-colors.js'
|
||||
import { join } from 'path'
|
||||
|
||||
type Period = 'today' | 'week' | '30days' | 'month' | 'all'
|
||||
type View = 'dashboard' | 'optimize' | 'compare'
|
||||
|
||||
type CachedWindow = {
|
||||
period: Period
|
||||
range: {
|
||||
start: Date
|
||||
end: Date
|
||||
}
|
||||
projects: ProjectSummary[]
|
||||
}
|
||||
|
||||
const PERIODS: Period[] = ['today', 'week', '30days', 'month', 'all']
|
||||
const PERIOD_LABELS: Record<Period, string> = {
|
||||
today: 'Today',
|
||||
|
|
@ -66,6 +55,15 @@ const PANEL_COLORS = {
|
|||
bash: '#F5A05B',
|
||||
}
|
||||
|
||||
const PROVIDER_COLORS: Record<string, string> = {
|
||||
claude: '#FF8C42',
|
||||
codex: '#5BF5A0',
|
||||
cursor: '#00B4D8',
|
||||
opencode: '#A78BFA',
|
||||
pi: '#F472B6',
|
||||
all: '#FF8C42',
|
||||
}
|
||||
|
||||
const CATEGORY_COLORS: Record<TaskCategory, string> = {
|
||||
coding: '#5B9EF5',
|
||||
debugging: '#F55B5B',
|
||||
|
|
@ -117,10 +115,6 @@ function getDateRange(period: Period): { start: Date; end: Date } {
|
|||
}
|
||||
}
|
||||
|
||||
function rangeCovers(outer: { start: Date; end: Date }, inner: { start: Date; end: Date }): boolean {
|
||||
return outer.start <= inner.start && outer.end >= inner.end
|
||||
}
|
||||
|
||||
type Layout = { dashWidth: number; wide: boolean; halfWidth: number; barWidth: number }
|
||||
|
||||
function getLayout(columns?: number): Layout {
|
||||
|
|
@ -495,6 +489,16 @@ function BashBreakdown({ projects, pw, bw }: { projects: ProjectSummary[]; pw: n
|
|||
)
|
||||
}
|
||||
|
||||
const PROVIDER_DISPLAY_NAMES: Record<string, string> = {
|
||||
all: 'All',
|
||||
claude: 'Claude',
|
||||
codex: 'Codex',
|
||||
cursor: 'Cursor',
|
||||
opencode: 'OpenCode',
|
||||
pi: 'Pi',
|
||||
}
|
||||
function getProviderDisplayName(name: string): string { return PROVIDER_DISPLAY_NAMES[name] ?? name }
|
||||
|
||||
function PeriodTabs({ active, providerName, showProvider }: { active: Period; providerName?: string; showProvider?: boolean }) {
|
||||
return (
|
||||
<Box justifyContent="space-between" paddingX={1}>
|
||||
|
|
@ -505,7 +509,9 @@ function PeriodTabs({ active, providerName, showProvider }: { active: Period; pr
|
|||
</Text>
|
||||
))}
|
||||
</Box>
|
||||
{showProvider && providerName && <Box><Text color={DIM}>| </Text><Text color={ORANGE} bold>[p]</Text><Text bold color={providerColor(providerName)}> {providerLabel(providerName)}</Text></Box>}
|
||||
{showProvider && providerName && (
|
||||
<Box><Text color={DIM}>| </Text><Text color={ORANGE} bold>[p]</Text><Text bold color={PROVIDER_COLORS[providerName] ?? ORANGE}> {getProviderDisplayName(providerName)}</Text></Box>
|
||||
)}
|
||||
</Box>
|
||||
)
|
||||
}
|
||||
|
|
@ -614,7 +620,7 @@ function DashboardContent({ projects, period, columns, activeProvider, budgets,
|
|||
)
|
||||
}
|
||||
|
||||
function InteractiveDashboard({ initialProjects, initialPeriod, initialProvider, initialPlanUsage, refreshSeconds, projectFilter, excludeFilter, noCache }: {
|
||||
function InteractiveDashboard({ initialProjects, initialPeriod, initialProvider, initialPlanUsage, refreshSeconds, projectFilter, excludeFilter }: {
|
||||
initialProjects: ProjectSummary[]
|
||||
initialPeriod: Period
|
||||
initialProvider: string
|
||||
|
|
@ -622,7 +628,6 @@ function InteractiveDashboard({ initialProjects, initialPeriod, initialProvider,
|
|||
refreshSeconds?: number
|
||||
projectFilter?: string[]
|
||||
excludeFilter?: string[]
|
||||
noCache?: boolean
|
||||
}) {
|
||||
const { exit } = useApp()
|
||||
const [period, setPeriod] = useState<Period>(initialPeriod)
|
||||
|
|
@ -643,156 +648,9 @@ function InteractiveDashboard({ initialProjects, initialPeriod, initialProvider,
|
|||
).size
|
||||
const compareAvailable = modelCount >= 2
|
||||
const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null)
|
||||
const cacheByProviderRef = useRef(new Map<string, CachedWindow[]>())
|
||||
const reloadSeqRef = useRef(0)
|
||||
const preloadingRef = useRef(new Map<string, Promise<ProjectSummary[]>>())
|
||||
const reloadGenerationRef = useRef(0)
|
||||
const findingCount = optimizeResult?.findings.length ?? 0
|
||||
|
||||
const providerCacheKey = useCallback((provider: string) => `${provider}:${noCache ? 'nocache' : 'cache'}`, [noCache])
|
||||
const getRangeWidth = useCallback((range: { start: Date; end: Date }) => range.end.getTime() - range.start.getTime(), [])
|
||||
const makeCacheToken = useCallback((provider: string, period: Period) => `${providerCacheKey(provider)}:${period}`, [providerCacheKey])
|
||||
|
||||
const storeCachedWindow = useCallback((provider: string, period: Period, range: { start: Date; end: Date }, projects: ProjectSummary[]) => {
|
||||
if (noCache) return
|
||||
const key = providerCacheKey(provider)
|
||||
const windows = cacheByProviderRef.current.get(key) ?? []
|
||||
const normalizedRange = { start: new Date(range.start), end: new Date(range.end) }
|
||||
const existing = windows.findIndex(
|
||||
existing => existing.period === period && existing.range.start.getTime() === normalizedRange.start.getTime() && existing.range.end.getTime() === normalizedRange.end.getTime(),
|
||||
)
|
||||
if (existing >= 0) windows.splice(existing, 1)
|
||||
windows.push({ period, range: normalizedRange, projects })
|
||||
windows.sort((a, b) => a.range.start.getTime() - b.range.start.getTime())
|
||||
cacheByProviderRef.current.set(key, windows)
|
||||
}, [noCache, providerCacheKey])
|
||||
|
||||
const findCachedWindow = useCallback((provider: string, range: { start: Date; end: Date }) => {
|
||||
const candidates = cacheByProviderRef.current.get(providerCacheKey(provider)) ?? []
|
||||
let best: CachedWindow | undefined
|
||||
for (const candidate of candidates) {
|
||||
if (!rangeCovers(candidate.range, range)) continue
|
||||
if (!best) { best = candidate; continue }
|
||||
if (getRangeWidth(candidate.range) < getRangeWidth(best.range)) {
|
||||
best = candidate
|
||||
} else if (candidate.period !== best.period && getRangeWidth(candidate.range) === getRangeWidth(best.range) && candidate.range.start > best.range.start) {
|
||||
best = candidate
|
||||
}
|
||||
}
|
||||
return best
|
||||
}, [getRangeWidth, providerCacheKey])
|
||||
|
||||
const preloadWindow = useCallback(async (periodToLoad: Period, provider: string) => {
|
||||
if (noCache) return
|
||||
const preloadKey = makeCacheToken(provider, periodToLoad)
|
||||
const range = getDateRange(periodToLoad)
|
||||
const cached = findCachedWindow(provider, range)
|
||||
if (cached) return
|
||||
const inFlight = preloadingRef.current.get(preloadKey)
|
||||
if (inFlight) return
|
||||
|
||||
const promise = (async () => {
|
||||
const projects = await parseAllSessions(range, provider, { noCache, progress: null })
|
||||
if (!noCache) {
|
||||
storeCachedWindow(provider, periodToLoad, range, projects)
|
||||
}
|
||||
return projects
|
||||
})()
|
||||
|
||||
preloadingRef.current.set(preloadKey, promise)
|
||||
try {
|
||||
await promise
|
||||
} finally {
|
||||
preloadingRef.current.delete(preloadKey)
|
||||
}
|
||||
}, [findCachedWindow, makeCacheToken, noCache, storeCachedWindow])
|
||||
|
||||
const reloadData = useCallback(async (p: Period, prov: string, options?: { silent?: boolean; skipCache?: boolean }) => {
|
||||
const range = getDateRange(p)
|
||||
const request = ++reloadSeqRef.current
|
||||
const token = makeCacheToken(prov, p)
|
||||
const cachedWindow = options?.skipCache ? undefined : findCachedWindow(prov, range)
|
||||
if (!options?.silent) {
|
||||
setOptimizeResult(null)
|
||||
}
|
||||
|
||||
if (cachedWindow) {
|
||||
const projectsFromCache = filterProjectsByName(
|
||||
filterProjectsByDateRange(cachedWindow.projects, range),
|
||||
projectFilter,
|
||||
excludeFilter,
|
||||
)
|
||||
if (!options?.silent && request === reloadSeqRef.current) {
|
||||
setProjects(projectsFromCache)
|
||||
}
|
||||
if (!options?.silent) {
|
||||
const usage = await getPlanUsageOrNull()
|
||||
if (request !== reloadSeqRef.current) return
|
||||
setPlanUsage(usage ?? undefined)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
const inFlight = preloadingRef.current.get(token)
|
||||
if (inFlight) {
|
||||
if (!options?.silent) setLoading(true)
|
||||
try {
|
||||
const projects = await inFlight
|
||||
if (!noCache) {
|
||||
storeCachedWindow(prov, p, range, projects)
|
||||
}
|
||||
if (request !== reloadSeqRef.current) return
|
||||
const filtered = filterProjectsByName(projects, projectFilter, excludeFilter)
|
||||
if (!options?.silent) {
|
||||
setProjects(filtered)
|
||||
}
|
||||
} finally {
|
||||
if (!options?.silent && request === reloadSeqRef.current) setLoading(false)
|
||||
}
|
||||
if (!options?.silent) {
|
||||
const usage = await getPlanUsageOrNull()
|
||||
if (request !== reloadSeqRef.current) return
|
||||
setPlanUsage(usage ?? undefined)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if (!options?.silent) setLoading(true)
|
||||
try {
|
||||
const projects = await parseAllSessions(range, prov, { noCache, progress: null })
|
||||
if (!noCache) {
|
||||
storeCachedWindow(prov, p, range, projects)
|
||||
}
|
||||
if (request !== reloadSeqRef.current) return
|
||||
const filtered = filterProjectsByName(projects, projectFilter, excludeFilter)
|
||||
if (!options?.silent) {
|
||||
setProjects(filtered)
|
||||
}
|
||||
} finally {
|
||||
if (!options?.silent && request === reloadSeqRef.current) setLoading(false)
|
||||
}
|
||||
if (!options?.silent) {
|
||||
const usage = await getPlanUsageOrNull()
|
||||
if (request !== reloadSeqRef.current) return
|
||||
setPlanUsage(usage ?? undefined)
|
||||
}
|
||||
}, [excludeFilter, findCachedWindow, getPlanUsageOrNull, noCache, projectFilter, storeCachedWindow])
|
||||
|
||||
useEffect(() => {
|
||||
if (noCache) return
|
||||
const initialRange = getDateRange(initialPeriod)
|
||||
const initialKey = providerCacheKey(initialProvider)
|
||||
const existing = cacheByProviderRef.current.get(initialKey) ?? []
|
||||
const alreadyCached = existing.some(entry => rangeCovers(entry.range, initialRange))
|
||||
if (!alreadyCached) {
|
||||
storeCachedWindow(initialProvider, initialPeriod, initialRange, initialProjects)
|
||||
}
|
||||
}, [initialPeriod, initialProvider, initialProjects, noCache, providerCacheKey, storeCachedWindow])
|
||||
|
||||
useEffect(() => {
|
||||
if (noCache || period === '30days') return
|
||||
void preloadWindow('30days', activeProvider)
|
||||
}, [noCache, period, activeProvider, preloadWindow])
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false
|
||||
async function detect() {
|
||||
|
|
@ -833,9 +691,34 @@ function InteractiveDashboard({ initialProjects, initialPeriod, initialProvider,
|
|||
return () => { cancelled = true }
|
||||
}, [projects, period, optimizeAvailable])
|
||||
|
||||
const reloadData = useCallback(async (p: Period, prov: string) => {
|
||||
const generation = ++reloadGenerationRef.current
|
||||
setLoading(true)
|
||||
setOptimizeResult(null)
|
||||
try {
|
||||
const range = getDateRange(p)
|
||||
const data = await parseAllSessions(range, prov)
|
||||
if (reloadGenerationRef.current !== generation) return
|
||||
|
||||
const filteredProjects = filterProjectsByName(data, projectFilter, excludeFilter)
|
||||
if (reloadGenerationRef.current !== generation) return
|
||||
|
||||
setProjects(filteredProjects)
|
||||
const usage = await getPlanUsageOrNull()
|
||||
if (reloadGenerationRef.current !== generation) return
|
||||
setPlanUsage(usage ?? undefined)
|
||||
} catch (error) {
|
||||
console.error(error)
|
||||
} finally {
|
||||
if (reloadGenerationRef.current === generation) {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
}, [projectFilter, excludeFilter])
|
||||
|
||||
useEffect(() => {
|
||||
if (!refreshSeconds || refreshSeconds <= 0) return
|
||||
const id = setInterval(() => { reloadData(period, activeProvider, { skipCache: true }) }, refreshSeconds * 1000)
|
||||
const id = setInterval(() => { reloadData(period, activeProvider) }, refreshSeconds * 1000)
|
||||
return () => clearInterval(id)
|
||||
}, [refreshSeconds, period, activeProvider, reloadData])
|
||||
|
||||
|
|
@ -916,36 +799,15 @@ function StaticDashboard({ projects, period, activeProvider, planUsage }: { proj
|
|||
)
|
||||
}
|
||||
|
||||
export async function renderDashboard(
|
||||
period: Period = 'week',
|
||||
provider: string = 'all',
|
||||
refreshSeconds?: number,
|
||||
projectFilter?: string[],
|
||||
excludeFilter?: string[],
|
||||
customRange?: DateRange | null,
|
||||
noCache = false,
|
||||
): Promise<void> {
|
||||
export async function renderDashboard(period: Period = 'week', provider: string = 'all', refreshSeconds?: number, projectFilter?: string[], excludeFilter?: string[], customRange?: DateRange | null): Promise<void> {
|
||||
await loadPricing()
|
||||
const isTTY = process.stdin.isTTY && process.stdout.isTTY
|
||||
const range = customRange ?? getDateRange(period)
|
||||
const filteredProjects = filterProjectsByName(
|
||||
await parseAllSessions(range, provider, { noCache, progress: createTerminalProgressReporter(isTTY) }),
|
||||
projectFilter,
|
||||
excludeFilter,
|
||||
)
|
||||
const filteredProjects = filterProjectsByName(await parseAllSessions(range, provider), projectFilter, excludeFilter)
|
||||
const planUsage = await getPlanUsageOrNull()
|
||||
const isTTY = process.stdin.isTTY && process.stdout.isTTY
|
||||
if (isTTY) {
|
||||
const { waitUntilExit } = render(
|
||||
<InteractiveDashboard
|
||||
initialProjects={filteredProjects}
|
||||
initialPeriod={period}
|
||||
initialProvider={provider}
|
||||
initialPlanUsage={planUsage ?? undefined}
|
||||
refreshSeconds={refreshSeconds}
|
||||
projectFilter={projectFilter}
|
||||
excludeFilter={excludeFilter}
|
||||
noCache={noCache}
|
||||
/>
|
||||
<InteractiveDashboard initialProjects={filteredProjects} initialPeriod={period} initialProvider={provider} initialPlanUsage={planUsage ?? undefined} refreshSeconds={refreshSeconds} projectFilter={projectFilter} excludeFilter={excludeFilter} />
|
||||
)
|
||||
await waitUntilExit()
|
||||
} else {
|
||||
|
|
|
|||
|
|
@ -1,200 +0,0 @@
|
|||
import { createHash, randomBytes } from 'crypto'
|
||||
import { existsSync } from 'fs'
|
||||
import { mkdir, open, readFile, rename, unlink } from 'fs/promises'
|
||||
import { homedir } from 'os'
|
||||
import { dirname, join } from 'path'
|
||||
|
||||
import type { SessionSource } from './providers/types.js'
|
||||
|
||||
const DISCOVERY_CACHE_VERSION = 1
|
||||
|
||||
const DISCOVERY_DIRECTORY_MARKER_PREFIX = '__dir__:'
|
||||
|
||||
function traceDiscoveryCacheRead(op: string, filePath: string, note?: string): void {
|
||||
if (process.env['CODEBURN_FILE_TRACE'] !== '1') return
|
||||
const suffix = note ? ` ${note}` : ''
|
||||
process.stderr.write(`codeburn-trace discovery ${op} ${filePath}${suffix}\n`)
|
||||
}
|
||||
|
||||
export type DiscoverySnapshotEntry = {
|
||||
path: string
|
||||
mtimeMs: number
|
||||
dirSignature?: string
|
||||
}
|
||||
|
||||
export type DiscoveryCacheEntry = {
|
||||
version: number
|
||||
provider: string
|
||||
scope: string
|
||||
snapshot: DiscoverySnapshotEntry[]
|
||||
sources: SessionSource[]
|
||||
}
|
||||
|
||||
function cacheRoot(): string {
|
||||
const base = process.env['CODEBURN_CACHE_DIR'] ?? join(homedir(), '.cache', 'codeburn')
|
||||
return join(base, 'discovery-cache-v1')
|
||||
}
|
||||
|
||||
function cacheFilename(provider: string, scope: string): string {
|
||||
return `${createHash('sha1').update(`${provider}:${scope}`).digest('hex')}.json`
|
||||
}
|
||||
|
||||
function cachePath(provider: string, scope: string): string {
|
||||
return join(cacheRoot(), cacheFilename(provider, scope))
|
||||
}
|
||||
|
||||
function isPlainObject(value: unknown): value is Record<string, unknown> {
|
||||
return !!value && typeof value === 'object' && !Array.isArray(value)
|
||||
}
|
||||
|
||||
function isFiniteNumber(value: unknown): value is number {
|
||||
return typeof value === 'number' && Number.isFinite(value)
|
||||
}
|
||||
|
||||
function isDiscoverySnapshotEntry(value: unknown): value is DiscoverySnapshotEntry {
|
||||
return isPlainObject(value)
|
||||
&& typeof value.path === 'string'
|
||||
&& isFiniteNumber(value.mtimeMs)
|
||||
}
|
||||
|
||||
function isSessionSource(value: unknown): value is SessionSource {
|
||||
return isPlainObject(value)
|
||||
&& typeof value.path === 'string'
|
||||
&& typeof value.project === 'string'
|
||||
&& typeof value.provider === 'string'
|
||||
&& (value.fingerprintPath === undefined || typeof value.fingerprintPath === 'string')
|
||||
&& (value.cacheStrategy === undefined || value.cacheStrategy === 'full-reparse' || value.cacheStrategy === 'append-jsonl')
|
||||
&& (value.progressLabel === undefined || typeof value.progressLabel === 'string')
|
||||
&& (value.parserVersion === undefined || typeof value.parserVersion === 'string')
|
||||
}
|
||||
|
||||
function isDiscoveryCacheEntry(value: unknown): value is DiscoveryCacheEntry {
|
||||
return isPlainObject(value)
|
||||
&& value.version === DISCOVERY_CACHE_VERSION
|
||||
&& typeof value.provider === 'string'
|
||||
&& typeof value.scope === 'string'
|
||||
&& Array.isArray(value.snapshot)
|
||||
&& value.snapshot.every(isDiscoverySnapshotEntry)
|
||||
&& Array.isArray(value.sources)
|
||||
&& value.sources.every(isSessionSource)
|
||||
}
|
||||
|
||||
function normalizeSnapshot(snapshot: DiscoverySnapshotEntry[]): DiscoverySnapshotEntry[] {
|
||||
return [...snapshot].sort((left, right) => left.path.localeCompare(right.path))
|
||||
}
|
||||
|
||||
function snapshotsMatch(left: DiscoverySnapshotEntry[], right: DiscoverySnapshotEntry[]): boolean {
|
||||
if (left.length !== right.length) return false
|
||||
return left.every((entry, index) => {
|
||||
const other = right[index]
|
||||
return !!other
|
||||
&& entry.path === other.path
|
||||
&& entry.mtimeMs === other.mtimeMs
|
||||
&& entry.dirSignature === other.dirSignature
|
||||
})
|
||||
}
|
||||
|
||||
function makeDirectoryMarker(path: string, dirSignature?: string): DiscoverySnapshotEntry {
|
||||
return {
|
||||
path: `${DISCOVERY_DIRECTORY_MARKER_PREFIX}${path}`,
|
||||
mtimeMs: 0,
|
||||
dirSignature,
|
||||
}
|
||||
}
|
||||
|
||||
export function isDiscoveryDirectoryMarker(path: string): boolean {
|
||||
return path.startsWith(DISCOVERY_DIRECTORY_MARKER_PREFIX)
|
||||
}
|
||||
|
||||
export function directoryPathFromMarker(markerPath: string): string | null {
|
||||
return markerPath.startsWith(DISCOVERY_DIRECTORY_MARKER_PREFIX)
|
||||
? markerPath.slice(DISCOVERY_DIRECTORY_MARKER_PREFIX.length)
|
||||
: null
|
||||
}
|
||||
|
||||
async function loadDiscoveryCacheEntry(provider: string, scope: string): Promise<DiscoveryCacheEntry | null> {
|
||||
const path = cachePath(provider, scope)
|
||||
if (!existsSync(path)) return null
|
||||
traceDiscoveryCacheRead('entry:read', path, `provider=${provider} scope=${scope}`)
|
||||
|
||||
try {
|
||||
const raw = await readFile(path, 'utf-8')
|
||||
const parsed: unknown = JSON.parse(raw)
|
||||
if (!isDiscoveryCacheEntry(parsed) || parsed.provider !== provider || parsed.scope !== scope) return null
|
||||
return parsed
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
async function atomicWriteJson(path: string, value: unknown): Promise<void> {
|
||||
await mkdir(dirname(path), { recursive: true })
|
||||
const temp = `${path}.${randomBytes(8).toString('hex')}.tmp`
|
||||
const handle = await open(temp, 'w', 0o600)
|
||||
try {
|
||||
await handle.writeFile(JSON.stringify(value), { encoding: 'utf-8' })
|
||||
await handle.sync()
|
||||
} finally {
|
||||
await handle.close()
|
||||
}
|
||||
|
||||
try {
|
||||
await rename(temp, path)
|
||||
} catch (err) {
|
||||
try {
|
||||
await unlink(temp)
|
||||
} catch {}
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
export async function loadDiscoveryCache(
|
||||
provider: string,
|
||||
scope: string,
|
||||
snapshot: DiscoverySnapshotEntry[],
|
||||
): Promise<SessionSource[] | null> {
|
||||
const path = cachePath(provider, scope)
|
||||
if (!existsSync(path)) return null
|
||||
|
||||
try {
|
||||
const raw = await readFile(path, 'utf-8')
|
||||
const parsed: unknown = JSON.parse(raw)
|
||||
if (!isDiscoveryCacheEntry(parsed)) return null
|
||||
if (parsed.provider !== provider || parsed.scope !== scope) return null
|
||||
|
||||
const normalizedSnapshot = normalizeSnapshot(snapshot)
|
||||
const cachedSnapshot = normalizeSnapshot(parsed.snapshot)
|
||||
if (!snapshotsMatch(normalizedSnapshot, cachedSnapshot)) return null
|
||||
|
||||
return parsed.sources
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
export async function loadDiscoveryCacheEntryUnchecked(
|
||||
provider: string,
|
||||
scope: string,
|
||||
): Promise<DiscoveryCacheEntry | null> {
|
||||
return loadDiscoveryCacheEntry(provider, scope)
|
||||
}
|
||||
|
||||
export async function saveDiscoveryCache(
|
||||
provider: string,
|
||||
scope: string,
|
||||
snapshot: DiscoverySnapshotEntry[],
|
||||
sources: SessionSource[],
|
||||
): Promise<void> {
|
||||
await mkdir(cacheRoot(), { recursive: true })
|
||||
await atomicWriteJson(cachePath(provider, scope), {
|
||||
version: DISCOVERY_CACHE_VERSION,
|
||||
provider,
|
||||
scope,
|
||||
snapshot: normalizeSnapshot(snapshot),
|
||||
sources,
|
||||
} satisfies DiscoveryCacheEntry)
|
||||
}
|
||||
|
||||
export function discoveryDirectoryMarker(prefixPath: string, dirSignature?: string): DiscoverySnapshotEntry {
|
||||
return makeDirectoryMarker(prefixPath, dirSignature)
|
||||
}
|
||||
|
|
@ -34,12 +34,15 @@ export function renderStatusBar(projects: ProjectSummary[]): string {
|
|||
for (const project of projects) {
|
||||
for (const session of project.sessions) {
|
||||
for (const turn of session.turns) {
|
||||
if (!turn.timestamp) continue
|
||||
// Bucket by the session timestamp's local date so the user's "today" and "this month"
|
||||
// match the wall clock on their machine. Session timestamps are stored as UTC ISO
|
||||
// strings; naively slicing `timestamp.slice(0,10)` bucketed them by UTC date, which
|
||||
// showed `Today $0` during the UTC-midnight-to-local-midnight window.
|
||||
const day = localDateString(new Date(turn.timestamp))
|
||||
if (turn.assistantCalls.length === 0) continue
|
||||
// Bucket by the first assistant call's local date -- the moment the cost was
|
||||
// incurred. Bucketing by `turn.timestamp` (the user message time) drops turns
|
||||
// that straddle midnight (user asked at 23:58, response arrived at 00:30) and
|
||||
// disagrees with parseAllSessions' dateRange filter which is also on assistant
|
||||
// time.
|
||||
const bucketTs = turn.assistantCalls[0]!.timestamp
|
||||
if (!bucketTs) continue
|
||||
const day = localDateString(new Date(bucketTs))
|
||||
const turnCost = turn.assistantCalls.reduce((s, c) => s + c.costUSD, 0)
|
||||
const turnCalls = turn.assistantCalls.length
|
||||
if (day === today) { todayCost += turnCost; todayCalls += turnCalls }
|
||||
|
|
|
|||
|
|
@ -93,31 +93,3 @@ export async function* readSessionLines(filePath: string): AsyncGenerator<string
|
|||
stream.destroy()
|
||||
}
|
||||
}
|
||||
|
||||
export async function* readSessionLinesFromOffset(filePath: string, startOffset: number): AsyncGenerator<string> {
|
||||
let size: number
|
||||
try {
|
||||
size = (await stat(filePath)).size
|
||||
} catch (err) {
|
||||
warn(`stat failed for ${filePath}: ${(err as NodeJS.ErrnoException).code ?? 'unknown'}`)
|
||||
return
|
||||
}
|
||||
|
||||
if (size > MAX_SESSION_FILE_BYTES) {
|
||||
warn(`skipped oversize file ${filePath} (${size} bytes > cap ${MAX_SESSION_FILE_BYTES})`)
|
||||
return
|
||||
}
|
||||
|
||||
const stream = createReadStream(filePath, {
|
||||
encoding: 'utf-8',
|
||||
start: Math.max(0, startOffset),
|
||||
})
|
||||
const rl = createInterface({ input: stream, crlfDelay: Infinity })
|
||||
try {
|
||||
for await (const line of rl) yield line
|
||||
} catch (err) {
|
||||
warn(`stream read failed for ${filePath}: ${(err as NodeJS.ErrnoException).code ?? 'unknown'}`)
|
||||
} finally {
|
||||
stream.destroy()
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -49,6 +49,8 @@ const FALLBACK_PRICING: Record<string, ModelCosts> = {
|
|||
'gpt-4.1-nano': { inputCostPerToken: 0.1e-6, outputCostPerToken: 0.4e-6, cacheWriteCostPerToken: 0.1e-6, cacheReadCostPerToken: 0.025e-6, webSearchCostPerRequest: WEB_SEARCH_COST, fastMultiplier: 1 },
|
||||
'o3': { inputCostPerToken: 10e-6, outputCostPerToken: 40e-6, cacheWriteCostPerToken: 10e-6, cacheReadCostPerToken: 2.5e-6, webSearchCostPerRequest: WEB_SEARCH_COST, fastMultiplier: 1 },
|
||||
'o4-mini': { inputCostPerToken: 1.1e-6, outputCostPerToken: 4.4e-6, cacheWriteCostPerToken: 1.1e-6, cacheReadCostPerToken: 0.275e-6, webSearchCostPerRequest: WEB_SEARCH_COST, fastMultiplier: 1 },
|
||||
'MiniMax-M2.7-highspeed': { inputCostPerToken: 0.6e-6, outputCostPerToken: 2.4e-6, cacheWriteCostPerToken: 0.375e-6, cacheReadCostPerToken: 0.06e-6, webSearchCostPerRequest: WEB_SEARCH_COST, fastMultiplier: 1 },
|
||||
'MiniMax-M2.7': { inputCostPerToken: 0.3e-6, outputCostPerToken: 1.2e-6, cacheWriteCostPerToken: 0.375e-6, cacheReadCostPerToken: 0.06e-6, webSearchCostPerRequest: WEB_SEARCH_COST, fastMultiplier: 1 },
|
||||
}
|
||||
|
||||
let pricingCache: Map<string, ModelCosts> | null = null
|
||||
|
|
@ -227,6 +229,8 @@ export function getShortModelName(model: string): string {
|
|||
'gemini-2.5-pro': 'Gemini 2.5 Pro',
|
||||
'o4-mini': 'o4-mini',
|
||||
'o3': 'o3',
|
||||
'MiniMax-M2.7-highspeed': 'MiniMax M2.7 Highspeed',
|
||||
'MiniMax-M2.7': 'MiniMax M2.7',
|
||||
}
|
||||
for (const [key, name] of Object.entries(shortNames)) {
|
||||
if (canonical.startsWith(key)) return name
|
||||
|
|
|
|||
|
|
@ -1,86 +0,0 @@
|
|||
import { stripVTControlCharacters } from 'node:util'
|
||||
|
||||
import { Chalk } from 'chalk'
|
||||
|
||||
import type { SourceProgressReporter } from './parser.js'
|
||||
import { providerColor, providerLabel } from './provider-colors.js'
|
||||
|
||||
function getBarWidth(columns: number | undefined): number {
|
||||
if (!columns || columns >= 80) return 16
|
||||
if (columns >= 56) return 12
|
||||
return 8
|
||||
}
|
||||
|
||||
function renderBar(current: number, total: number, width: number): { filled: number; empty: number } {
|
||||
if (total <= 0) return { filled: 0, empty: width }
|
||||
|
||||
const filled = Math.max(0, Math.min(width, Math.round((current / total) * width)))
|
||||
return { filled, empty: Math.max(0, width - filled) }
|
||||
}
|
||||
|
||||
function mapChalkLevel(colorDepth: number): 0 | 1 | 2 | 3 {
|
||||
if (colorDepth >= 24) return 3
|
||||
if (colorDepth >= 8) return 2
|
||||
if (colorDepth >= 1) return 1
|
||||
return 0
|
||||
}
|
||||
|
||||
export function createTerminalProgressReporter(
|
||||
enabled: boolean,
|
||||
stream: NodeJS.WriteStream = process.stderr,
|
||||
): SourceProgressReporter | null {
|
||||
if (!enabled || !stream.isTTY) return null
|
||||
|
||||
let total = 0
|
||||
let current = 0
|
||||
let lastProvider = 'all'
|
||||
let lastLineLength = 0
|
||||
let active = false
|
||||
const colorDepth = typeof stream.getColorDepth === 'function' ? stream.getColorDepth() : 0
|
||||
const chalk = new Chalk({ level: mapChalkLevel(colorDepth) })
|
||||
|
||||
function buildFrame(provider: string, done = false): string {
|
||||
const columns = 'columns' in stream ? (stream as NodeJS.WriteStream & { columns?: number }).columns : process.stderr.columns
|
||||
const width = getBarWidth(columns)
|
||||
const label = providerLabel(provider)
|
||||
const { filled, empty } = renderBar(current, total, width)
|
||||
const accent = providerColor(provider)
|
||||
const line = [
|
||||
chalk.dim('Updating'),
|
||||
chalk.bold.hex(accent)(label),
|
||||
chalk.dim('cache'),
|
||||
`[${chalk.hex(accent)('█'.repeat(filled))}${chalk.hex('#666666')('░'.repeat(empty))}]`,
|
||||
`${current}/${total}`,
|
||||
].join(' ')
|
||||
const visible = stripVTControlCharacters(line)
|
||||
const pad = lastLineLength > visible.length ? ' '.repeat(lastLineLength - visible.length) : ''
|
||||
lastLineLength = Math.max(lastLineLength, visible.length)
|
||||
return `${line}${pad}${done ? '\n' : '\r'}`
|
||||
}
|
||||
|
||||
return {
|
||||
start(nextTotal: number) {
|
||||
total = nextTotal
|
||||
current = 0
|
||||
lastProvider = 'all'
|
||||
lastLineLength = 0
|
||||
active = nextTotal > 0
|
||||
},
|
||||
advance(provider: string) {
|
||||
if (!active) return
|
||||
lastProvider = provider
|
||||
current += 1
|
||||
stream.write(buildFrame(provider))
|
||||
},
|
||||
finish(provider?: string) {
|
||||
if (!active) return
|
||||
if (current === 0) return
|
||||
stream.write(buildFrame(provider ?? lastProvider, true))
|
||||
active = false
|
||||
total = 0
|
||||
current = 0
|
||||
lastProvider = 'all'
|
||||
lastLineLength = 0
|
||||
},
|
||||
}
|
||||
}
|
||||
1023
src/parser.ts
1023
src/parser.ts
File diff suppressed because it is too large
Load diff
|
|
@ -1,27 +0,0 @@
|
|||
export const PROVIDER_COLORS: Record<string, string> = {
|
||||
all: '#FF8C42',
|
||||
claude: '#FF8C42',
|
||||
codex: '#5BF5A0',
|
||||
cursor: '#00B4D8',
|
||||
opencode: '#A78BFA',
|
||||
pi: '#F472B6',
|
||||
copilot: '#6495ED',
|
||||
}
|
||||
|
||||
const PROVIDER_LABELS: Record<string, string> = {
|
||||
all: 'All',
|
||||
claude: 'Claude',
|
||||
codex: 'Codex',
|
||||
cursor: 'Cursor',
|
||||
opencode: 'OpenCode',
|
||||
pi: 'Pi',
|
||||
copilot: 'Copilot',
|
||||
}
|
||||
|
||||
export function providerLabel(name: string): string {
|
||||
return PROVIDER_LABELS[name] ?? name
|
||||
}
|
||||
|
||||
export function providerColor(name: string): string {
|
||||
return PROVIDER_COLORS[name] ?? '#CCCCCC'
|
||||
}
|
||||
|
|
@ -2,7 +2,6 @@ import { readdir, stat } from 'fs/promises'
|
|||
import { basename, join } from 'path'
|
||||
import { homedir } from 'os'
|
||||
|
||||
import { type DiscoverySnapshotEntry, loadDiscoveryCache, saveDiscoveryCache } from '../discovery-cache.js'
|
||||
import { readSessionFile } from '../fs-utils.js'
|
||||
import { calculateCost } from '../models.js'
|
||||
import type { Provider, SessionSource, SessionParser, ParsedProviderCall } from './types.js'
|
||||
|
|
@ -87,49 +86,8 @@ async function isValidCodexSession(filePath: string): Promise<{ valid: boolean;
|
|||
return { valid, meta: valid ? entry : undefined }
|
||||
}
|
||||
|
||||
async function collectCodexDiscoverySnapshot(sessionsDir: string): Promise<DiscoverySnapshotEntry[]> {
|
||||
const snapshot: DiscoverySnapshotEntry[] = []
|
||||
|
||||
let years: string[]
|
||||
try {
|
||||
years = await readdir(sessionsDir)
|
||||
} catch {
|
||||
return snapshot
|
||||
}
|
||||
|
||||
for (const year of years) {
|
||||
if (!/^\d{4}$/.test(year)) continue
|
||||
const yearDir = join(sessionsDir, year)
|
||||
const yearStat = await stat(yearDir).catch(() => null)
|
||||
if (!yearStat?.isDirectory()) continue
|
||||
|
||||
const months = await readdir(yearDir).catch(() => [] as string[])
|
||||
for (const month of months) {
|
||||
if (!/^\d{2}$/.test(month)) continue
|
||||
const monthDir = join(yearDir, month)
|
||||
const monthStat = await stat(monthDir).catch(() => null)
|
||||
if (!monthStat?.isDirectory()) continue
|
||||
|
||||
const days = await readdir(monthDir).catch(() => [] as string[])
|
||||
for (const day of days) {
|
||||
if (!/^\d{2}$/.test(day)) continue
|
||||
const dayDir = join(monthDir, day)
|
||||
const dayStat = await stat(dayDir).catch(() => null)
|
||||
if (!dayStat?.isDirectory()) continue
|
||||
snapshot.push({ path: dayDir, mtimeMs: dayStat.mtimeMs })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return snapshot
|
||||
}
|
||||
|
||||
async function discoverSessionsInDir(codexDir: string): Promise<SessionSource[]> {
|
||||
const sessionsDir = join(codexDir, 'sessions')
|
||||
const snapshot = await collectCodexDiscoverySnapshot(sessionsDir)
|
||||
const cached = await loadDiscoveryCache('codex', sessionsDir, snapshot)
|
||||
if (cached) return cached
|
||||
|
||||
const sources: SessionSource[] = []
|
||||
|
||||
let years: string[]
|
||||
|
|
@ -164,21 +122,12 @@ async function discoverSessionsInDir(codexDir: string): Promise<SessionSource[]>
|
|||
if (!valid || !meta) continue
|
||||
|
||||
const cwd = meta.payload?.cwd ?? 'unknown'
|
||||
sources.push({
|
||||
path: filePath,
|
||||
project: sanitizeProject(cwd),
|
||||
provider: 'codex',
|
||||
fingerprintPath: filePath,
|
||||
cacheStrategy: 'append-jsonl',
|
||||
progressLabel: basename(filePath),
|
||||
parserVersion: 'codex:v1',
|
||||
})
|
||||
sources.push({ path: filePath, project: sanitizeProject(cwd), provider: 'codex' })
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
await saveDiscoveryCache('codex', sessionsDir, snapshot, sources)
|
||||
return sources
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -2,7 +2,6 @@ import { readdir, stat } from 'fs/promises'
|
|||
import { basename, dirname, join } from 'path'
|
||||
import { homedir } from 'os'
|
||||
|
||||
import { type DiscoverySnapshotEntry, loadDiscoveryCache, saveDiscoveryCache } from '../discovery-cache.js'
|
||||
import { readSessionFile } from '../fs-utils.js'
|
||||
import { calculateCost } from '../models.js'
|
||||
import type { Provider, SessionSource, SessionParser, ParsedProviderCall } from './types.js'
|
||||
|
|
@ -158,42 +157,7 @@ function createParser(source: SessionSource, seenKeys: Set<string>): SessionPars
|
|||
}
|
||||
}
|
||||
|
||||
async function collectCopilotDiscoverySnapshot(sessionStateDir: string): Promise<DiscoverySnapshotEntry[]> {
|
||||
const snapshot: DiscoverySnapshotEntry[] = []
|
||||
|
||||
let sessionDirs: string[]
|
||||
try {
|
||||
sessionDirs = await readdir(sessionStateDir)
|
||||
} catch {
|
||||
return snapshot
|
||||
}
|
||||
|
||||
for (const sessionId of sessionDirs) {
|
||||
const sessionDir = join(sessionStateDir, sessionId)
|
||||
const dirStat = await stat(sessionDir).catch(() => null)
|
||||
if (!dirStat?.isDirectory()) continue
|
||||
|
||||
const eventsPath = join(sessionDir, 'events.jsonl')
|
||||
const eventsStat = await stat(eventsPath).catch(() => null)
|
||||
if (!eventsStat?.isFile()) continue
|
||||
|
||||
snapshot.push({ path: eventsPath, mtimeMs: eventsStat.mtimeMs })
|
||||
|
||||
const workspacePath = join(sessionDir, 'workspace.yaml')
|
||||
const workspaceStat = await stat(workspacePath).catch(() => null)
|
||||
if (workspaceStat?.isFile()) {
|
||||
snapshot.push({ path: workspacePath, mtimeMs: workspaceStat.mtimeMs })
|
||||
}
|
||||
}
|
||||
|
||||
return snapshot
|
||||
}
|
||||
|
||||
async function discoverSessionsInDir(sessionStateDir: string): Promise<SessionSource[]> {
|
||||
const snapshot = await collectCopilotDiscoverySnapshot(sessionStateDir)
|
||||
const cached = await loadDiscoveryCache('copilot', sessionStateDir, snapshot)
|
||||
if (cached) return cached
|
||||
|
||||
const sources: SessionSource[] = []
|
||||
|
||||
let sessionDirs: string[]
|
||||
|
|
@ -215,18 +179,9 @@ async function discoverSessionsInDir(sessionStateDir: string): Promise<SessionSo
|
|||
if (cwd) project = basename(cwd)
|
||||
}
|
||||
|
||||
sources.push({
|
||||
path: eventsPath,
|
||||
project,
|
||||
provider: 'copilot',
|
||||
fingerprintPath: eventsPath,
|
||||
cacheStrategy: 'append-jsonl',
|
||||
progressLabel: basename(eventsPath),
|
||||
parserVersion: 'copilot:v1',
|
||||
})
|
||||
sources.push({ path: eventsPath, project, provider: 'copilot' })
|
||||
}
|
||||
|
||||
await saveDiscoveryCache('copilot', sessionStateDir, snapshot, sources)
|
||||
return sources
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -403,10 +403,6 @@ export function createCursorAgentProvider(baseDirOverride?: string): Provider {
|
|||
path: transcriptPath,
|
||||
project: projectId,
|
||||
provider: 'cursor-agent',
|
||||
fingerprintPath: transcriptPath,
|
||||
cacheStrategy: 'full-reparse',
|
||||
progressLabel: `cursor-agent:${basename(transcript.name)}`,
|
||||
parserVersion: 'cursor-agent:v1',
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ import { join } from 'path'
|
|||
import { homedir } from 'os'
|
||||
|
||||
import { calculateCost } from '../models.js'
|
||||
import { readCachedResults, writeCachedResults } from '../cursor-cache.js'
|
||||
import { isSqliteAvailable, getSqliteLoadError, openDatabase, type SqliteDatabase } from '../sqlite.js'
|
||||
import type { Provider, SessionSource, SessionParser, ParsedProviderCall } from './types.js'
|
||||
|
||||
|
|
@ -214,6 +215,16 @@ function createParser(source: SessionSource, seenKeys: Set<string>): SessionPars
|
|||
return
|
||||
}
|
||||
|
||||
const cached = await readCachedResults(source.path)
|
||||
if (cached) {
|
||||
for (const call of cached) {
|
||||
if (seenKeys.has(call.deduplicationKey)) continue
|
||||
seenKeys.add(call.deduplicationKey)
|
||||
yield call
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
let db: SqliteDatabase
|
||||
try {
|
||||
db = openDatabase(source.path)
|
||||
|
|
@ -230,6 +241,8 @@ function createParser(source: SessionSource, seenKeys: Set<string>): SessionPars
|
|||
|
||||
const { calls } = parseBubbles(db, seenKeys)
|
||||
|
||||
await writeCachedResults(source.path, calls)
|
||||
|
||||
for (const call of calls) {
|
||||
yield call
|
||||
}
|
||||
|
|
@ -259,15 +272,7 @@ export function createCursorProvider(dbPathOverride?: string): Provider {
|
|||
const dbPath = dbPathOverride ?? getCursorDbPath()
|
||||
if (!existsSync(dbPath)) return []
|
||||
|
||||
return [{
|
||||
path: dbPath,
|
||||
project: 'cursor',
|
||||
provider: 'cursor',
|
||||
fingerprintPath: dbPath,
|
||||
cacheStrategy: 'full-reparse',
|
||||
progressLabel: 'Cursor state.vscdb',
|
||||
parserVersion: 'cursor:v1',
|
||||
}]
|
||||
return [{ path: dbPath, project: 'cursor', provider: 'cursor' }]
|
||||
},
|
||||
|
||||
createSessionParser(source: SessionSource, seenKeys: Set<string>): SessionParser {
|
||||
|
|
|
|||
|
|
@ -271,10 +271,6 @@ async function discoverFromDb(dbPath: string): Promise<SessionSource[]> {
|
|||
path: `${dbPath}:${row.id}`,
|
||||
project: row.directory ? sanitize(row.directory) : sanitize(row.title),
|
||||
provider: 'opencode',
|
||||
fingerprintPath: dbPath,
|
||||
cacheStrategy: 'full-reparse',
|
||||
progressLabel: `opencode:${row.id}`,
|
||||
parserVersion: 'opencode:v1',
|
||||
}))
|
||||
} catch {
|
||||
return []
|
||||
|
|
|
|||
|
|
@ -2,7 +2,6 @@ import { readdir, stat } from 'fs/promises'
|
|||
import { basename, join } from 'path'
|
||||
import { homedir } from 'os'
|
||||
|
||||
import { type DiscoverySnapshotEntry, loadDiscoveryCache, saveDiscoveryCache } from '../discovery-cache.js'
|
||||
import { readSessionFile } from '../fs-utils.js'
|
||||
import { calculateCost } from '../models.js'
|
||||
import { extractBashCommands } from '../bash-utils.js'
|
||||
|
|
@ -73,31 +72,7 @@ async function readFirstEntry(filePath: string): Promise<PiEntry | null> {
|
|||
}
|
||||
}
|
||||
|
||||
async function collectPiDiscoverySnapshot(sessionsDir: string): Promise<DiscoverySnapshotEntry[]> {
|
||||
const snapshot: DiscoverySnapshotEntry[] = []
|
||||
|
||||
let projectDirs: string[]
|
||||
try {
|
||||
projectDirs = await readdir(sessionsDir)
|
||||
} catch {
|
||||
return snapshot
|
||||
}
|
||||
|
||||
for (const dirName of projectDirs) {
|
||||
const dirPath = join(sessionsDir, dirName)
|
||||
const dirStat = await stat(dirPath).catch(() => null)
|
||||
if (!dirStat?.isDirectory()) continue
|
||||
snapshot.push({ path: dirPath, mtimeMs: dirStat.mtimeMs })
|
||||
}
|
||||
|
||||
return snapshot
|
||||
}
|
||||
|
||||
async function discoverSessionsInDir(sessionsDir: string, providerName: string): Promise<SessionSource[]> {
|
||||
const snapshot = await collectPiDiscoverySnapshot(sessionsDir)
|
||||
const cached = await loadDiscoveryCache(providerName, sessionsDir, snapshot)
|
||||
if (cached) return cached
|
||||
|
||||
const sources: SessionSource[] = []
|
||||
|
||||
let projectDirs: string[]
|
||||
|
|
@ -129,19 +104,10 @@ async function discoverSessionsInDir(sessionsDir: string, providerName: string):
|
|||
if (!first || first.type !== 'session') continue
|
||||
|
||||
const cwd = first.cwd ?? dirName
|
||||
sources.push({
|
||||
path: filePath,
|
||||
project: basename(cwd),
|
||||
provider: providerName,
|
||||
fingerprintPath: filePath,
|
||||
cacheStrategy: 'append-jsonl',
|
||||
progressLabel: basename(filePath),
|
||||
parserVersion: `${providerName}:v1`,
|
||||
})
|
||||
sources.push({ path: filePath, project: basename(cwd), provider: providerName })
|
||||
}
|
||||
}
|
||||
|
||||
await saveDiscoveryCache(providerName, sessionsDir, snapshot, sources)
|
||||
return sources
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,13 +1,7 @@
|
|||
export type SourceCacheStrategy = 'full-reparse' | 'append-jsonl'
|
||||
|
||||
export type SessionSource = {
|
||||
path: string
|
||||
project: string
|
||||
provider: string
|
||||
fingerprintPath?: string
|
||||
cacheStrategy?: SourceCacheStrategy
|
||||
progressLabel?: string
|
||||
parserVersion?: string
|
||||
}
|
||||
|
||||
export type SessionParser = {
|
||||
|
|
|
|||
|
|
@ -1,426 +0,0 @@
|
|||
import { createHash, randomBytes } from 'crypto'
|
||||
import { existsSync } from 'fs'
|
||||
import { mkdir, open, readFile, rename, stat, unlink } from 'fs/promises'
|
||||
import { homedir } from 'os'
|
||||
import { dirname, join } from 'path'
|
||||
|
||||
import type { SessionSummary } from './types.js'
|
||||
|
||||
export const SOURCE_CACHE_VERSION = 1
|
||||
|
||||
function traceCacheRead(op: string, filePath: string, note?: string): void {
|
||||
if (process.env['CODEBURN_FILE_TRACE'] !== '1') return
|
||||
const suffix = note ? ` ${note}` : ''
|
||||
process.stderr.write(`codeburn-trace source-cache ${op} ${filePath}${suffix}\n`)
|
||||
}
|
||||
|
||||
const APPEND_TAIL_WINDOW_BYTES = 16 * 1024
|
||||
|
||||
type SourceCacheStrategy = 'full-reparse' | 'append-jsonl'
|
||||
|
||||
type SourceFingerprint = {
|
||||
mtimeMs: number
|
||||
sizeBytes: number
|
||||
}
|
||||
|
||||
type AppendState = {
|
||||
endOffset: number
|
||||
tailHash: string
|
||||
lastEntryType?: string
|
||||
}
|
||||
|
||||
export type SourceCacheEntry = {
|
||||
version: number
|
||||
provider: string
|
||||
logicalPath: string
|
||||
fingerprintPath: string
|
||||
cacheStrategy: SourceCacheStrategy
|
||||
parserVersion: string
|
||||
fingerprint: SourceFingerprint
|
||||
sessions: SessionSummary[]
|
||||
appendState?: AppendState
|
||||
}
|
||||
|
||||
export type SourceCacheManifest = {
|
||||
version: number
|
||||
entries: Record<string, SourceCacheManifestEntry>
|
||||
}
|
||||
|
||||
export type SourceCacheManifestEntry = {
|
||||
file: string
|
||||
provider: string
|
||||
logicalPath: string
|
||||
lastSeenParserVersion?: string
|
||||
cacheStrategy?: SourceCacheStrategy
|
||||
fingerprintPath?: string
|
||||
fingerprint?: SourceFingerprint
|
||||
firstTimestamp?: string
|
||||
lastTimestamp?: string
|
||||
appendState?: AppendState
|
||||
}
|
||||
|
||||
type ReadSourceCacheEntryOptions = {
|
||||
allowStaleFingerprint?: boolean
|
||||
}
|
||||
|
||||
type SourceRange = {
|
||||
firstTimestamp?: string
|
||||
lastTimestamp?: string
|
||||
}
|
||||
|
||||
function sourceCacheKey(provider: string, logicalPath: string): string {
|
||||
return `${provider}:${logicalPath}`
|
||||
}
|
||||
|
||||
export function getManifestEntry(manifest: SourceCacheManifest, provider: string, logicalPath: string): SourceCacheManifestEntry | null {
|
||||
return manifest.entries[sourceCacheKey(provider, logicalPath)] ?? null
|
||||
}
|
||||
|
||||
function isPlainObject(value: unknown): value is Record<string, unknown> {
|
||||
return !!value && typeof value === 'object' && !Array.isArray(value)
|
||||
}
|
||||
|
||||
function isFiniteNumber(value: unknown): value is number {
|
||||
return typeof value === 'number' && Number.isFinite(value)
|
||||
}
|
||||
|
||||
function isManifestEntry(value: unknown): value is SourceCacheManifest['entries'][string] {
|
||||
const isAppendStateValue = (entry: unknown): entry is AppendState =>
|
||||
isPlainObject(entry)
|
||||
&& typeof entry.endOffset === 'number'
|
||||
&& Number.isFinite(entry.endOffset)
|
||||
&& typeof entry.tailHash === 'string'
|
||||
&& (entry.lastEntryType === undefined || typeof entry.lastEntryType === 'string')
|
||||
|
||||
const isFingerprint = (entry: unknown): entry is SourceFingerprint => isPlainObject(entry)
|
||||
&& Number.isFinite(entry.mtimeMs)
|
||||
&& typeof entry.mtimeMs === 'number'
|
||||
&& Number.isFinite(entry.sizeBytes)
|
||||
&& typeof entry.sizeBytes === 'number'
|
||||
|
||||
return isPlainObject(value)
|
||||
&& typeof value.file === 'string'
|
||||
&& /^[a-f0-9]{40}\.json$/.test(value.file)
|
||||
&& typeof value.provider === 'string'
|
||||
&& typeof value.logicalPath === 'string'
|
||||
&& (value.lastSeenParserVersion === undefined || typeof value.lastSeenParserVersion === 'string')
|
||||
&& (value.cacheStrategy === undefined || value.cacheStrategy === 'full-reparse' || value.cacheStrategy === 'append-jsonl')
|
||||
&& (value.fingerprintPath === undefined || typeof value.fingerprintPath === 'string')
|
||||
&& (value.fingerprint === undefined || isFingerprint(value.fingerprint))
|
||||
&& (value.firstTimestamp === undefined || typeof value.firstTimestamp === 'string')
|
||||
&& (value.lastTimestamp === undefined || typeof value.lastTimestamp === 'string')
|
||||
&& (value.appendState === undefined || isAppendStateValue(value.appendState))
|
||||
}
|
||||
|
||||
function isSessionSummary(value: unknown): value is SessionSummary {
|
||||
return isPlainObject(value)
|
||||
&& typeof value.sessionId === 'string'
|
||||
&& typeof value.project === 'string'
|
||||
&& typeof value.firstTimestamp === 'string'
|
||||
&& typeof value.lastTimestamp === 'string'
|
||||
&& isFiniteNumber(value.totalCostUSD)
|
||||
&& isFiniteNumber(value.totalInputTokens)
|
||||
&& isFiniteNumber(value.totalOutputTokens)
|
||||
&& isFiniteNumber(value.totalCacheReadTokens)
|
||||
&& isFiniteNumber(value.totalCacheWriteTokens)
|
||||
&& isFiniteNumber(value.apiCalls)
|
||||
&& Array.isArray(value.turns)
|
||||
&& value.turns.every(isParsedTurn)
|
||||
&& isBreakdownMap(value.modelBreakdown, isModelBreakdownEntry)
|
||||
&& isBreakdownMap(value.toolBreakdown, isCallsBreakdownEntry)
|
||||
&& isBreakdownMap(value.mcpBreakdown, isCallsBreakdownEntry)
|
||||
&& isBreakdownMap(value.bashBreakdown, isCallsBreakdownEntry)
|
||||
&& isBreakdownMap(value.categoryBreakdown, isCategoryBreakdownEntry)
|
||||
}
|
||||
|
||||
function isTokenUsage(value: unknown): value is { inputTokens: number; outputTokens: number; cacheCreationInputTokens: number; cacheReadInputTokens: number; cachedInputTokens: number; reasoningTokens: number; webSearchRequests: number } {
|
||||
return isPlainObject(value)
|
||||
&& isFiniteNumber(value.inputTokens)
|
||||
&& isFiniteNumber(value.outputTokens)
|
||||
&& isFiniteNumber(value.cacheCreationInputTokens)
|
||||
&& isFiniteNumber(value.cacheReadInputTokens)
|
||||
&& isFiniteNumber(value.cachedInputTokens)
|
||||
&& isFiniteNumber(value.reasoningTokens)
|
||||
&& isFiniteNumber(value.webSearchRequests)
|
||||
}
|
||||
|
||||
function isParsedApiCall(value: unknown): boolean {
|
||||
return isPlainObject(value)
|
||||
&& typeof value.provider === 'string'
|
||||
&& typeof value.model === 'string'
|
||||
&& isTokenUsage(value.usage)
|
||||
&& isFiniteNumber(value.costUSD)
|
||||
&& Array.isArray(value.tools)
|
||||
&& value.tools.every(tool => typeof tool === 'string')
|
||||
&& Array.isArray(value.mcpTools)
|
||||
&& value.mcpTools.every(tool => typeof tool === 'string')
|
||||
&& typeof value.hasAgentSpawn === 'boolean'
|
||||
&& typeof value.hasPlanMode === 'boolean'
|
||||
&& (value.speed === 'standard' || value.speed === 'fast')
|
||||
&& typeof value.timestamp === 'string'
|
||||
&& Array.isArray(value.bashCommands)
|
||||
&& value.bashCommands.every(command => typeof command === 'string')
|
||||
&& typeof value.deduplicationKey === 'string'
|
||||
}
|
||||
|
||||
function isParsedTurn(value: unknown): boolean {
|
||||
return isPlainObject(value)
|
||||
&& typeof value.userMessage === 'string'
|
||||
&& Array.isArray(value.assistantCalls)
|
||||
&& value.assistantCalls.every(isParsedApiCall)
|
||||
&& typeof value.timestamp === 'string'
|
||||
&& typeof value.sessionId === 'string'
|
||||
}
|
||||
|
||||
function isModelBreakdownEntry(value: unknown): value is { calls: number; costUSD: number; tokens: TokenUsage } {
|
||||
return isPlainObject(value)
|
||||
&& isFiniteNumber(value.calls)
|
||||
&& isFiniteNumber(value.costUSD)
|
||||
&& isTokenUsage(value.tokens)
|
||||
}
|
||||
|
||||
type TokenUsage = { inputTokens: number; outputTokens: number; cacheCreationInputTokens: number; cacheReadInputTokens: number; cachedInputTokens: number; reasoningTokens: number; webSearchRequests: number }
|
||||
|
||||
function isCallsBreakdownEntry(value: unknown): value is { calls: number } {
|
||||
return isPlainObject(value) && isFiniteNumber(value.calls)
|
||||
}
|
||||
|
||||
function isCategoryBreakdownEntry(value: unknown): value is { turns: number; costUSD: number; retries: number; editTurns: number; oneShotTurns: number } {
|
||||
return isPlainObject(value)
|
||||
&& isFiniteNumber(value.turns)
|
||||
&& isFiniteNumber(value.costUSD)
|
||||
&& isFiniteNumber(value.retries)
|
||||
&& isFiniteNumber(value.editTurns)
|
||||
&& isFiniteNumber(value.oneShotTurns)
|
||||
}
|
||||
|
||||
function isBreakdownMap<T>(value: unknown, predicate: (entry: unknown) => entry is T): value is Record<string, T> {
|
||||
return isPlainObject(value) && Object.values(value).every(predicate)
|
||||
}
|
||||
|
||||
function isAppendState(value: unknown): value is AppendState {
|
||||
return isPlainObject(value)
|
||||
&& typeof value.endOffset === 'number'
|
||||
&& Number.isFinite(value.endOffset)
|
||||
&& typeof value.tailHash === 'string'
|
||||
&& (value.lastEntryType === undefined || typeof value.lastEntryType === 'string')
|
||||
}
|
||||
|
||||
function rangeFromSessions(sessions: SessionSummary[]): SourceRange {
|
||||
if (sessions.length === 0) return {}
|
||||
|
||||
let firstTs = sessions[0]?.firstTimestamp
|
||||
let lastTs = sessions[sessions.length - 1]?.lastTimestamp
|
||||
for (const session of sessions) {
|
||||
if (!firstTs || session.firstTimestamp < firstTs) firstTs = session.firstTimestamp
|
||||
if (!lastTs || session.lastTimestamp > lastTs) lastTs = session.lastTimestamp
|
||||
}
|
||||
|
||||
return {
|
||||
firstTimestamp: firstTs,
|
||||
lastTimestamp: lastTs,
|
||||
}
|
||||
}
|
||||
|
||||
async function readTailStateHash(filePath: string, endOffset: number): Promise<string | null> {
|
||||
if (endOffset <= 0) return null
|
||||
const start = Math.max(0, endOffset - APPEND_TAIL_WINDOW_BYTES)
|
||||
const length = Math.max(0, endOffset - start)
|
||||
if (length <= 0) return null
|
||||
|
||||
const handle = await open(filePath, 'r')
|
||||
const buffer = Buffer.alloc(length)
|
||||
|
||||
try {
|
||||
await handle.read(buffer, 0, length, start)
|
||||
} finally {
|
||||
await handle.close()
|
||||
}
|
||||
|
||||
const chunk = buffer.toString('utf-8').replace(/[\r\n]+$/, '')
|
||||
if (chunk.length === 0) return null
|
||||
|
||||
const lastNewline = chunk.lastIndexOf('\n')
|
||||
const lastLine = lastNewline >= 0 ? chunk.slice(lastNewline + 1) : chunk
|
||||
return lastLine.trim() ? createHash('sha1').update(lastLine).digest('hex') : null
|
||||
}
|
||||
|
||||
function isDateRangeOverlap(
|
||||
firstTimestamp: string | undefined,
|
||||
lastTimestamp: string | undefined,
|
||||
rangeStart: number,
|
||||
rangeEnd: number,
|
||||
): boolean | null {
|
||||
if (!firstTimestamp || !lastTimestamp) return null
|
||||
|
||||
const firstMs = new Date(firstTimestamp).getTime()
|
||||
const lastMs = new Date(lastTimestamp).getTime()
|
||||
if (Number.isNaN(firstMs) || Number.isNaN(lastMs)) return null
|
||||
|
||||
return lastMs >= rangeStart && firstMs <= rangeEnd
|
||||
}
|
||||
|
||||
function isSourceCacheEntry(value: unknown): value is SourceCacheEntry {
|
||||
return isPlainObject(value)
|
||||
&& typeof value.version === 'number'
|
||||
&& typeof value.provider === 'string'
|
||||
&& typeof value.logicalPath === 'string'
|
||||
&& typeof value.fingerprintPath === 'string'
|
||||
&& (value.cacheStrategy === 'full-reparse' || value.cacheStrategy === 'append-jsonl')
|
||||
&& typeof value.parserVersion === 'string'
|
||||
&& isPlainObject(value.fingerprint)
|
||||
&& Number.isFinite(value.fingerprint.mtimeMs)
|
||||
&& typeof value.fingerprint.mtimeMs === 'number'
|
||||
&& Number.isFinite(value.fingerprint.sizeBytes)
|
||||
&& typeof value.fingerprint.sizeBytes === 'number'
|
||||
&& Array.isArray(value.sessions)
|
||||
&& value.sessions.every(isSessionSummary)
|
||||
&& (value.appendState === undefined || isAppendState(value.appendState))
|
||||
}
|
||||
|
||||
function cacheRoot(): string {
|
||||
const base = process.env['CODEBURN_CACHE_DIR'] ?? join(homedir(), '.cache', 'codeburn')
|
||||
return join(base, 'source-cache-v1')
|
||||
}
|
||||
|
||||
function manifestPath(): string {
|
||||
return join(cacheRoot(), 'manifest.json')
|
||||
}
|
||||
|
||||
function entryDir(): string {
|
||||
return join(cacheRoot(), 'entries')
|
||||
}
|
||||
|
||||
function entryFilename(provider: string, logicalPath: string): string {
|
||||
return `${createHash('sha1').update(sourceCacheKey(provider, logicalPath)).digest('hex')}.json`
|
||||
}
|
||||
|
||||
export function emptySourceCacheManifest(): SourceCacheManifest {
|
||||
return { version: SOURCE_CACHE_VERSION, entries: {} }
|
||||
}
|
||||
|
||||
export async function computeFileFingerprint(filePath: string): Promise<SourceFingerprint> {
|
||||
const meta = await stat(filePath)
|
||||
return { mtimeMs: meta.mtimeMs, sizeBytes: meta.size }
|
||||
}
|
||||
|
||||
export async function loadSourceCacheManifest(): Promise<SourceCacheManifest> {
|
||||
traceCacheRead('manifest:read', manifestPath())
|
||||
if (!existsSync(manifestPath())) return emptySourceCacheManifest()
|
||||
|
||||
try {
|
||||
const raw = await readFile(manifestPath(), 'utf-8')
|
||||
const parsed: unknown = JSON.parse(raw)
|
||||
if (!isPlainObject(parsed) || parsed.version !== SOURCE_CACHE_VERSION || !isPlainObject(parsed.entries)) {
|
||||
return emptySourceCacheManifest()
|
||||
}
|
||||
|
||||
const entries: SourceCacheManifest['entries'] = {}
|
||||
for (const [key, value] of Object.entries(parsed.entries)) {
|
||||
if (!isManifestEntry(value)) return emptySourceCacheManifest()
|
||||
entries[key] = value
|
||||
}
|
||||
|
||||
return { version: SOURCE_CACHE_VERSION, entries }
|
||||
} catch {
|
||||
return emptySourceCacheManifest()
|
||||
}
|
||||
}
|
||||
|
||||
async function atomicWriteJson(path: string, value: unknown): Promise<void> {
|
||||
await mkdir(dirname(path), { recursive: true })
|
||||
const temp = `${path}.${randomBytes(8).toString('hex')}.tmp`
|
||||
const handle = await open(temp, 'w', 0o600)
|
||||
try {
|
||||
await handle.writeFile(JSON.stringify(value), { encoding: 'utf-8' })
|
||||
await handle.sync()
|
||||
} finally {
|
||||
await handle.close()
|
||||
}
|
||||
|
||||
try {
|
||||
await rename(temp, path)
|
||||
} catch (err) {
|
||||
try {
|
||||
await unlink(temp)
|
||||
} catch {}
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
export async function saveSourceCacheManifest(manifest: SourceCacheManifest): Promise<void> {
|
||||
await mkdir(cacheRoot(), { recursive: true })
|
||||
await atomicWriteJson(manifestPath(), manifest)
|
||||
}
|
||||
|
||||
export async function readSourceCacheEntry(
|
||||
manifest: SourceCacheManifest,
|
||||
provider: string,
|
||||
logicalPath: string,
|
||||
options: ReadSourceCacheEntryOptions = {},
|
||||
): Promise<SourceCacheEntry | null> {
|
||||
const meta = manifest.entries[sourceCacheKey(provider, logicalPath)]
|
||||
if (!meta) return null
|
||||
if (meta.provider !== provider || meta.logicalPath !== logicalPath) return null
|
||||
|
||||
const expectedFile = entryFilename(provider, logicalPath)
|
||||
if (meta.file !== expectedFile) return null
|
||||
|
||||
try {
|
||||
const raw = await readFile(join(entryDir(), meta.file), 'utf-8')
|
||||
traceCacheRead('entry:read', join(entryDir(), meta.file), `provider=${provider} logicalPath=${logicalPath}`)
|
||||
const entry: unknown = JSON.parse(raw)
|
||||
if (!isSourceCacheEntry(entry) || entry.version !== SOURCE_CACHE_VERSION) return null
|
||||
if (entry.provider !== provider || entry.logicalPath !== logicalPath) return null
|
||||
|
||||
if (!options.allowStaleFingerprint) {
|
||||
const currentFingerprint = await computeFileFingerprint(entry.fingerprintPath)
|
||||
if (
|
||||
currentFingerprint.mtimeMs !== entry.fingerprint.mtimeMs
|
||||
|| currentFingerprint.sizeBytes !== entry.fingerprint.sizeBytes
|
||||
) {
|
||||
const sizeMatches = currentFingerprint.sizeBytes === entry.fingerprint.sizeBytes
|
||||
if (!(
|
||||
entry.cacheStrategy === 'append-jsonl'
|
||||
&& entry.appendState
|
||||
&& sizeMatches
|
||||
)) {
|
||||
return null
|
||||
}
|
||||
|
||||
const liveTailHash = await readTailStateHash(entry.fingerprintPath, entry.appendState.endOffset)
|
||||
if (liveTailHash !== entry.appendState.tailHash) return null
|
||||
}
|
||||
}
|
||||
|
||||
return entry
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
export async function writeSourceCacheEntry(manifest: SourceCacheManifest, entry: SourceCacheEntry): Promise<void> {
|
||||
await mkdir(entryDir(), { recursive: true })
|
||||
const file = entryFilename(entry.provider, entry.logicalPath)
|
||||
await atomicWriteJson(join(entryDir(), file), entry)
|
||||
const range = rangeFromSessions(entry.sessions)
|
||||
manifest.entries[sourceCacheKey(entry.provider, entry.logicalPath)] = {
|
||||
file,
|
||||
provider: entry.provider,
|
||||
logicalPath: entry.logicalPath,
|
||||
lastSeenParserVersion: entry.parserVersion,
|
||||
cacheStrategy: entry.cacheStrategy,
|
||||
fingerprintPath: entry.fingerprintPath,
|
||||
fingerprint: entry.fingerprint,
|
||||
...range,
|
||||
appendState: entry.appendState,
|
||||
}
|
||||
}
|
||||
|
||||
export function isManifestDateRangeOverlap(
|
||||
manifestEntry: SourceCacheManifestEntry | null,
|
||||
dateRange?: { start: Date; end: Date },
|
||||
): boolean | null {
|
||||
if (!manifestEntry || !dateRange) return null
|
||||
return isDateRangeOverlap(manifestEntry.firstTimestamp, manifestEntry.lastTimestamp, dateRange.start.getTime(), dateRange.end.getTime())
|
||||
}
|
||||
|
|
@ -38,11 +38,6 @@ function makeCall(timestamp: string, costUSD: number, model = 'Opus 4.7', provid
|
|||
}
|
||||
}
|
||||
|
||||
function localDateKey(iso: string): string {
|
||||
const d = new Date(iso)
|
||||
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
|
||||
}
|
||||
|
||||
describe('aggregateProjectsIntoDays', () => {
|
||||
it('buckets api calls by calendar date derived from timestamp', () => {
|
||||
const projects: ProjectSummary[] = [
|
||||
|
|
@ -135,13 +130,12 @@ describe('aggregateProjectsIntoDays', () => {
|
|||
})
|
||||
|
||||
it('counts a session under its firstTimestamp date', () => {
|
||||
const firstTimestamp = '2026-04-09T23:59:00Z'
|
||||
const projects: ProjectSummary[] = [
|
||||
makeProject({
|
||||
sessions: [{
|
||||
sessionId: 's1',
|
||||
project: 'p',
|
||||
firstTimestamp,
|
||||
firstTimestamp: '2026-04-09T23:59:00Z',
|
||||
lastTimestamp: '2026-04-10T00:10:00Z',
|
||||
totalCostUSD: 1,
|
||||
totalInputTokens: 0, totalOutputTokens: 0, totalCacheReadTokens: 0, totalCacheWriteTokens: 0,
|
||||
|
|
@ -153,7 +147,7 @@ describe('aggregateProjectsIntoDays', () => {
|
|||
}),
|
||||
]
|
||||
const days = aggregateProjectsIntoDays(projects)
|
||||
expect(days[0]!.date).toBe(localDateKey(firstTimestamp))
|
||||
expect(days[0]!.date).toBe('2026-04-09')
|
||||
expect(days[0]!.sessions).toBe(1)
|
||||
})
|
||||
|
||||
|
|
@ -261,4 +255,48 @@ describe('buildPeriodDataFromDays', () => {
|
|||
expect(pd.categories).toEqual([])
|
||||
expect(pd.models).toEqual([])
|
||||
})
|
||||
|
||||
it('attributes a midnight-straddling turn to the first assistant call date, not the user message date', () => {
|
||||
// Regression for the bug that shipped in 0.8.2-0.8.4: when a user message
|
||||
// sat on one side of midnight and the assistant response landed on the other,
|
||||
// day-aggregator.ts bucketed by assistant time but renderStatusBar bucketed
|
||||
// by user time, so the menubar and `codeburn status` disagreed on Today.
|
||||
// The invariant for both surfaces: a turn is counted on the day its first
|
||||
// assistant call actually ran.
|
||||
const userTs = '2026-04-20T23:58:00Z'
|
||||
const assistantTs = '2026-04-21T00:30:00Z'
|
||||
const assistantLocal = new Date(assistantTs)
|
||||
const expectedDate = `${assistantLocal.getFullYear()}-${String(assistantLocal.getMonth() + 1).padStart(2, '0')}-${String(assistantLocal.getDate()).padStart(2, '0')}`
|
||||
|
||||
const projects: ProjectSummary[] = [
|
||||
makeProject({
|
||||
sessions: [{
|
||||
sessionId: 's1',
|
||||
project: 'p',
|
||||
firstTimestamp: userTs,
|
||||
lastTimestamp: assistantTs,
|
||||
totalCostUSD: 5,
|
||||
totalInputTokens: 0, totalOutputTokens: 0, totalCacheReadTokens: 0, totalCacheWriteTokens: 0,
|
||||
apiCalls: 1,
|
||||
turns: [{
|
||||
userMessage: 'ask',
|
||||
timestamp: userTs,
|
||||
sessionId: 's1',
|
||||
category: 'coding',
|
||||
retries: 0,
|
||||
hasEdits: false,
|
||||
assistantCalls: [makeCall(assistantTs, 5)],
|
||||
}],
|
||||
modelBreakdown: {}, toolBreakdown: {}, mcpBreakdown: {}, bashBreakdown: {},
|
||||
categoryBreakdown: {} as never,
|
||||
}],
|
||||
}),
|
||||
]
|
||||
|
||||
const days = aggregateProjectsIntoDays(projects)
|
||||
const costDay = days.find(d => d.cost === 5)
|
||||
expect(costDay, 'turn cost must be bucketed somewhere').toBeDefined()
|
||||
expect(costDay!.date).toBe(expectedDate)
|
||||
expect(costDay!.calls).toBe(1)
|
||||
})
|
||||
})
|
||||
|
|
|
|||
|
|
@ -8,7 +8,6 @@ import {
|
|||
STREAM_THRESHOLD_BYTES,
|
||||
readSessionFile,
|
||||
readSessionLines,
|
||||
readSessionLinesFromOffset,
|
||||
} from '../src/fs-utils.js'
|
||||
|
||||
describe('readSessionFile', () => {
|
||||
|
|
@ -97,33 +96,3 @@ describe('readSessionLines', () => {
|
|||
await gen.return(undefined)
|
||||
})
|
||||
})
|
||||
|
||||
describe('readSessionLinesFromOffset', () => {
|
||||
const tmpDirs: string[] = []
|
||||
|
||||
afterEach(async () => {
|
||||
while (tmpDirs.length > 0) {
|
||||
const d = tmpDirs.pop()
|
||||
if (d) await rm(d, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
async function tmpPath(content: string): Promise<string> {
|
||||
const base = await mkdtemp(join(tmpdir(), 'codeburn-fs-offset-'))
|
||||
tmpDirs.push(base)
|
||||
const p = join(base, 'offset.txt')
|
||||
await writeFile(p, content, 'utf-8')
|
||||
return p
|
||||
}
|
||||
|
||||
it('starts at the requested byte offset', async () => {
|
||||
const p = await tmpPath('alpha\nbeta\ngamma\n')
|
||||
const lines: string[] = []
|
||||
|
||||
for await (const line of readSessionLinesFromOffset(p, Buffer.byteLength('alpha\n', 'utf-8'))) {
|
||||
lines.push(line)
|
||||
}
|
||||
|
||||
expect(lines).toEqual(['beta', 'gamma'])
|
||||
})
|
||||
})
|
||||
|
|
|
|||
48
tests/minimax.test.ts
Normal file
48
tests/minimax.test.ts
Normal file
|
|
@ -0,0 +1,48 @@
|
|||
import { describe, it, expect } from 'vitest'
|
||||
|
||||
import { getModelCosts, getShortModelName } from '../src/models.js'
|
||||
|
||||
// Verifies MiniMax pricing loaded from FALLBACK_PRICING (no network call).
|
||||
// pricingCache stays null until loadPricing() runs, so getModelCosts falls
|
||||
// through to FALLBACK_PRICING which is what we want to validate here.
|
||||
|
||||
describe('MiniMax model pricing', () => {
|
||||
it('returns pricing for MiniMax-M2.7', () => {
|
||||
const costs = getModelCosts('MiniMax-M2.7')
|
||||
expect(costs).not.toBeNull()
|
||||
expect(costs!.inputCostPerToken).toBe(0.3e-6)
|
||||
expect(costs!.outputCostPerToken).toBe(1.2e-6)
|
||||
expect(costs!.cacheReadCostPerToken).toBe(0.06e-6)
|
||||
expect(costs!.cacheWriteCostPerToken).toBe(0.375e-6)
|
||||
expect(costs!.fastMultiplier).toBe(1)
|
||||
})
|
||||
|
||||
it('returns pricing for MiniMax-M2.7-highspeed', () => {
|
||||
const costs = getModelCosts('MiniMax-M2.7-highspeed')
|
||||
expect(costs).not.toBeNull()
|
||||
expect(costs!.inputCostPerToken).toBe(0.6e-6)
|
||||
expect(costs!.outputCostPerToken).toBe(2.4e-6)
|
||||
expect(costs!.cacheReadCostPerToken).toBe(0.06e-6)
|
||||
expect(costs!.cacheWriteCostPerToken).toBe(0.375e-6)
|
||||
expect(costs!.fastMultiplier).toBe(1)
|
||||
})
|
||||
|
||||
it('highspeed pricing is distinct from base model pricing', () => {
|
||||
const base = getModelCosts('MiniMax-M2.7')
|
||||
const fast = getModelCosts('MiniMax-M2.7-highspeed')
|
||||
expect(fast!.inputCostPerToken).toBeGreaterThan(base!.inputCostPerToken)
|
||||
expect(fast!.outputCostPerToken).toBeGreaterThan(base!.outputCostPerToken)
|
||||
})
|
||||
|
||||
it('returns short name for MiniMax-M2.7', () => {
|
||||
expect(getShortModelName('MiniMax-M2.7')).toBe('MiniMax M2.7')
|
||||
})
|
||||
|
||||
it('returns short name for MiniMax-M2.7-highspeed', () => {
|
||||
expect(getShortModelName('MiniMax-M2.7-highspeed')).toBe('MiniMax M2.7 Highspeed')
|
||||
})
|
||||
|
||||
it('handles MiniMax model ID with date suffix', () => {
|
||||
expect(getShortModelName('MiniMax-M2.7-20260101')).toBe('MiniMax M2.7')
|
||||
})
|
||||
})
|
||||
|
|
@ -1,77 +0,0 @@
|
|||
import { stripVTControlCharacters } from 'node:util'
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import { createTerminalProgressReporter } from '../src/parse-progress.js'
|
||||
|
||||
describe('createTerminalProgressReporter', () => {
|
||||
it('renders a provider-aware cache bar with global counts', () => {
|
||||
const writes: string[] = []
|
||||
const stream = {
|
||||
isTTY: true,
|
||||
columns: 60,
|
||||
write: vi.fn((chunk: string) => {
|
||||
writes.push(chunk)
|
||||
return true
|
||||
}),
|
||||
} as unknown as NodeJS.WriteStream
|
||||
|
||||
const reporter = createTerminalProgressReporter(true, stream)
|
||||
reporter?.start(1899)
|
||||
reporter?.advance('claude')
|
||||
reporter?.advance('claude')
|
||||
reporter?.finish('claude')
|
||||
|
||||
const text = stripVTControlCharacters(writes.join(''))
|
||||
expect(text).toContain('Updating Claude cache')
|
||||
expect(text).toContain('2/1899')
|
||||
expect(text).toContain('[')
|
||||
expect(text).not.toContain('.jsonl')
|
||||
})
|
||||
|
||||
it('shrinks the bar on narrow terminals', () => {
|
||||
const writes: string[] = []
|
||||
const stream = {
|
||||
isTTY: true,
|
||||
columns: 34,
|
||||
write: vi.fn((chunk: string) => {
|
||||
writes.push(chunk)
|
||||
return true
|
||||
}),
|
||||
} as unknown as NodeJS.WriteStream
|
||||
|
||||
const reporter = createTerminalProgressReporter(true, stream)
|
||||
reporter?.start(100)
|
||||
reporter?.advance('codex')
|
||||
|
||||
const text = stripVTControlCharacters(writes.join(''))
|
||||
expect(text).toContain('Updating Codex cache')
|
||||
expect(text).toContain('1/100')
|
||||
expect(text).toMatch(/\[[█░]{8}\]/)
|
||||
})
|
||||
|
||||
it('returns null for non-tty streams', () => {
|
||||
const stream = { isTTY: false, write: vi.fn() } as unknown as NodeJS.WriteStream
|
||||
expect(createTerminalProgressReporter(true, stream)).toBeNull()
|
||||
})
|
||||
|
||||
it('uses stream color depth to configure output styling', () => {
|
||||
const writes: string[] = []
|
||||
const getColorDepth = vi.fn(() => 8)
|
||||
const stream = {
|
||||
isTTY: true,
|
||||
columns: 80,
|
||||
getColorDepth,
|
||||
write: vi.fn((chunk: string) => {
|
||||
writes.push(chunk)
|
||||
return true
|
||||
}),
|
||||
} as unknown as NodeJS.WriteStream
|
||||
|
||||
const reporter = createTerminalProgressReporter(true, stream)
|
||||
reporter?.start(2)
|
||||
reporter?.advance('claude')
|
||||
|
||||
expect(getColorDepth).toHaveBeenCalledTimes(1)
|
||||
expect(writes.join('')).toContain('Updating')
|
||||
})
|
||||
})
|
||||
|
|
@ -1,475 +0,0 @@
|
|||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { appendFile, mkdir, mkdtemp, readFile, rm, writeFile } from 'fs/promises'
|
||||
import { tmpdir } from 'os'
|
||||
import { join } from 'path'
|
||||
|
||||
import type { ParsedProviderCall, Provider, SessionSource } from '../src/providers/types.js'
|
||||
|
||||
let root = ''
|
||||
let sourcePath = ''
|
||||
let parseCalls = 0
|
||||
let claudeRoot = ''
|
||||
let claudeSessionPath = ''
|
||||
|
||||
function makeCall(index: number): ParsedProviderCall {
|
||||
const second = String(index).padStart(2, '0')
|
||||
return {
|
||||
provider: 'fake',
|
||||
model: 'gpt-5',
|
||||
inputTokens: 10,
|
||||
outputTokens: 20,
|
||||
cacheCreationInputTokens: 0,
|
||||
cacheReadInputTokens: 0,
|
||||
cachedInputTokens: 0,
|
||||
reasoningTokens: 0,
|
||||
webSearchRequests: 0,
|
||||
costUSD: 0.01,
|
||||
tools: ['Edit'],
|
||||
bashCommands: [],
|
||||
timestamp: `2026-04-20T09:00:${second}.000Z`,
|
||||
speed: 'standard',
|
||||
deduplicationKey: `fake:${index}`,
|
||||
userMessage: `prompt ${index}`,
|
||||
sessionId: 'fake-session',
|
||||
}
|
||||
}
|
||||
|
||||
beforeEach(async () => {
|
||||
root = await mkdtemp(join(tmpdir(), 'codeburn-parser-cache-'))
|
||||
sourcePath = join(root, 'fake.jsonl')
|
||||
claudeRoot = join(root, '.claude')
|
||||
claudeSessionPath = join(claudeRoot, 'projects', 'demo-project', 'session.jsonl')
|
||||
parseCalls = 0
|
||||
process.env['CODEBURN_CACHE_DIR'] = join(root, 'cache')
|
||||
process.env['CLAUDE_CONFIG_DIR'] = claudeRoot
|
||||
await writeFile(sourcePath, 'one\n', 'utf-8')
|
||||
await mkdir(join(claudeRoot, 'projects', 'demo-project'), { recursive: true })
|
||||
await writeFile(claudeSessionPath, [
|
||||
JSON.stringify({
|
||||
type: 'user',
|
||||
timestamp: '2026-04-20T09:00:00.000Z',
|
||||
sessionId: 'sess-1',
|
||||
message: { role: 'user', content: 'first' },
|
||||
}),
|
||||
JSON.stringify({
|
||||
type: 'assistant',
|
||||
timestamp: '2026-04-20T09:00:01.000Z',
|
||||
message: {
|
||||
id: 'msg-1',
|
||||
model: 'claude-sonnet-4-6',
|
||||
role: 'assistant',
|
||||
type: 'message',
|
||||
content: [],
|
||||
usage: { input_tokens: 10, output_tokens: 20 },
|
||||
},
|
||||
}),
|
||||
].join('\n') + '\n', 'utf-8')
|
||||
})
|
||||
|
||||
afterEach(async () => {
|
||||
delete process.env['CODEBURN_CACHE_DIR']
|
||||
delete process.env['CLAUDE_CONFIG_DIR']
|
||||
await rm(root, { recursive: true, force: true })
|
||||
vi.resetModules()
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
describe('parseAllSessions source cache', () => {
|
||||
it('uses one global progress lifecycle across provider refreshes', async () => {
|
||||
const fakeSource = {
|
||||
path: sourcePath,
|
||||
fingerprintPath: sourcePath,
|
||||
project: 'fake-project',
|
||||
provider: 'fake',
|
||||
cacheStrategy: 'full-reparse',
|
||||
} as SessionSource
|
||||
const claudeSource = {
|
||||
path: join(claudeRoot, 'projects', 'demo-project'),
|
||||
project: 'demo-project',
|
||||
provider: 'claude',
|
||||
} as SessionSource
|
||||
|
||||
const fakeProvider: Provider = {
|
||||
name: 'fake',
|
||||
displayName: 'Fake',
|
||||
modelDisplayName: model => model,
|
||||
toolDisplayName: tool => tool,
|
||||
discoverSessions: async () => [fakeSource],
|
||||
createSessionParser() {
|
||||
return {
|
||||
async *parse() {
|
||||
parseCalls += 1
|
||||
const lineCount = (await readFile(sourcePath, 'utf-8')).trim().split('\n').filter(Boolean).length
|
||||
for (let i = 0; i < lineCount; i += 1) yield makeCall(i)
|
||||
},
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
vi.doMock('../src/providers/index.js', () => ({
|
||||
discoverAllSessions: async (providerFilter?: string) => {
|
||||
if (providerFilter === 'fake') return [fakeSource]
|
||||
return [claudeSource, fakeSource]
|
||||
},
|
||||
getProvider: async () => fakeProvider,
|
||||
}))
|
||||
|
||||
const { parseAllSessions } = await import('../src/parser.js')
|
||||
|
||||
const progress = {
|
||||
start: vi.fn(),
|
||||
advance: vi.fn(),
|
||||
finish: vi.fn(),
|
||||
}
|
||||
|
||||
const first = await parseAllSessions(undefined, undefined, { progress })
|
||||
expect(first).toEqual(expect.any(Array))
|
||||
expect(parseCalls).toBe(1)
|
||||
expect(progress.start).toHaveBeenCalledTimes(1)
|
||||
expect(progress.start).toHaveBeenCalledWith(2)
|
||||
expect(progress.advance).toHaveBeenCalledWith('claude')
|
||||
expect(progress.advance).toHaveBeenCalledWith('fake')
|
||||
expect(progress.finish).toHaveBeenCalledTimes(1)
|
||||
expect(progress.finish).toHaveBeenCalledWith('fake')
|
||||
|
||||
const second = await parseAllSessions(undefined, 'fake')
|
||||
expect(second[0]?.totalApiCalls).toBe(1)
|
||||
expect(parseCalls).toBe(1)
|
||||
|
||||
await writeFile(sourcePath, 'one\ntwo\n', 'utf-8')
|
||||
const third = await parseAllSessions(undefined, 'fake')
|
||||
expect(third[0]?.totalApiCalls).toBe(2)
|
||||
expect(parseCalls).toBe(2)
|
||||
|
||||
const rebuilt = await parseAllSessions(undefined, 'fake', { noCache: true })
|
||||
expect(rebuilt[0]?.totalApiCalls).toBe(2)
|
||||
expect(parseCalls).toBe(3)
|
||||
})
|
||||
|
||||
it('reuses a broader cached window for a narrower date range', async () => {
|
||||
const providerName = 'fake-range-reuse'
|
||||
const fakeSource = {
|
||||
path: sourcePath,
|
||||
fingerprintPath: sourcePath,
|
||||
project: 'fake-project',
|
||||
provider: providerName,
|
||||
cacheStrategy: 'full-reparse',
|
||||
} as SessionSource
|
||||
|
||||
const fakeProvider: Provider = {
|
||||
name: providerName,
|
||||
displayName: 'Fake',
|
||||
modelDisplayName: model => model,
|
||||
toolDisplayName: tool => tool,
|
||||
discoverSessions: async () => [fakeSource],
|
||||
createSessionParser() {
|
||||
return {
|
||||
async *parse() {
|
||||
parseCalls += 1
|
||||
yield { ...makeCall(0), timestamp: '2026-04-20T10:00:00.000Z', deduplicationKey: `${providerName}:day1` }
|
||||
yield { ...makeCall(1), timestamp: '2026-04-21T10:00:00.000Z', deduplicationKey: `${providerName}:day2` }
|
||||
},
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
vi.doMock('../src/providers/index.js', () => ({
|
||||
discoverAllSessions: async () => [fakeSource],
|
||||
getProvider: async () => fakeProvider,
|
||||
}))
|
||||
|
||||
vi.resetModules()
|
||||
const { parseAllSessions: parseWithCache } = await import('../src/parser.js')
|
||||
|
||||
const wide = {
|
||||
start: new Date('2026-04-19T00:00:00.000Z'),
|
||||
end: new Date('2026-04-21T23:59:59.999Z'),
|
||||
}
|
||||
const narrow = {
|
||||
start: new Date('2026-04-20T00:00:00.000Z'),
|
||||
end: new Date('2026-04-20T23:59:59.999Z'),
|
||||
}
|
||||
|
||||
const wideProjects = await parseWithCache(wide, providerName)
|
||||
expect(wideProjects[0]?.totalApiCalls).toBe(2)
|
||||
expect(parseCalls).toBe(1)
|
||||
|
||||
const narrowProjects = await parseWithCache(narrow, providerName)
|
||||
expect(narrowProjects[0]?.totalApiCalls).toBe(1)
|
||||
expect(parseCalls).toBe(1)
|
||||
})
|
||||
|
||||
it('does not deduplicate claude turns across different session files', async () => {
|
||||
const sharedMsgId = 'msg_shared_duplicate_123'
|
||||
const secondSessionPath = join(claudeRoot, 'projects', 'demo-project', 'session-2.jsonl')
|
||||
await Promise.all([
|
||||
writeFile(claudeSessionPath, [
|
||||
JSON.stringify({
|
||||
type: 'user',
|
||||
timestamp: '2026-04-20T09:00:00.000Z',
|
||||
sessionId: 'sess-1',
|
||||
message: { role: 'user', content: 'first' },
|
||||
}),
|
||||
JSON.stringify({
|
||||
type: 'assistant',
|
||||
timestamp: '2026-04-20T09:00:01.000Z',
|
||||
message: {
|
||||
id: sharedMsgId,
|
||||
model: 'claude-sonnet-4-6',
|
||||
role: 'assistant',
|
||||
type: 'message',
|
||||
content: [],
|
||||
usage: { input_tokens: 10, output_tokens: 20 },
|
||||
},
|
||||
}),
|
||||
].join('\n') + '\n'),
|
||||
writeFile(secondSessionPath, [
|
||||
JSON.stringify({
|
||||
type: 'user',
|
||||
timestamp: '2026-04-20T09:05:00.000Z',
|
||||
sessionId: 'sess-2',
|
||||
message: { role: 'user', content: 'second' },
|
||||
}),
|
||||
JSON.stringify({
|
||||
type: 'assistant',
|
||||
timestamp: '2026-04-20T09:05:01.000Z',
|
||||
message: {
|
||||
id: sharedMsgId,
|
||||
model: 'claude-sonnet-4-6',
|
||||
role: 'assistant',
|
||||
type: 'message',
|
||||
content: [],
|
||||
usage: { input_tokens: 11, output_tokens: 21 },
|
||||
},
|
||||
}),
|
||||
].join('\n') + '\n'),
|
||||
])
|
||||
|
||||
vi.doUnmock('../src/providers/index.js')
|
||||
vi.resetModules()
|
||||
const { parseAllSessions } = await import('../src/parser.js')
|
||||
|
||||
const first = await parseAllSessions(undefined, 'claude')
|
||||
const project = first.find(project => project.project === 'demo-project')
|
||||
expect(project?.totalApiCalls).toBe(2)
|
||||
|
||||
const second = await parseAllSessions(undefined, 'claude')
|
||||
const cachedProject = second.find(project => project.project === 'demo-project')
|
||||
expect(cachedProject?.totalApiCalls).toBe(2)
|
||||
})
|
||||
|
||||
it('filters cached full sessions down to the requested date range', async () => {
|
||||
const fakeSource = {
|
||||
path: sourcePath,
|
||||
fingerprintPath: sourcePath,
|
||||
project: 'fake-project',
|
||||
provider: 'fake',
|
||||
cacheStrategy: 'full-reparse',
|
||||
progressLabel: 'fake.jsonl',
|
||||
} as SessionSource
|
||||
|
||||
const fakeProvider: Provider = {
|
||||
name: 'fake',
|
||||
displayName: 'Fake',
|
||||
modelDisplayName: model => model,
|
||||
toolDisplayName: tool => tool,
|
||||
discoverSessions: async () => [fakeSource],
|
||||
createSessionParser() {
|
||||
return {
|
||||
async *parse() {
|
||||
yield makeCall(0)
|
||||
yield { ...makeCall(1), timestamp: '2026-04-21T10:00:00.000Z', deduplicationKey: 'fake:next-day' }
|
||||
},
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
vi.doMock('../src/providers/index.js', () => ({
|
||||
discoverAllSessions: async () => [fakeSource],
|
||||
getProvider: async () => fakeProvider,
|
||||
}))
|
||||
|
||||
const { parseAllSessions } = await import('../src/parser.js')
|
||||
await parseAllSessions(undefined, 'fake')
|
||||
|
||||
const onlyFirstDay = await parseAllSessions({
|
||||
start: new Date('2026-04-20T00:00:00.000Z'),
|
||||
end: new Date('2026-04-20T23:59:59.999Z'),
|
||||
}, 'fake')
|
||||
|
||||
expect(onlyFirstDay[0]?.totalApiCalls).toBe(1)
|
||||
})
|
||||
|
||||
it('refreshes appended Claude log entries on the next run', async () => {
|
||||
vi.doUnmock('../src/providers/index.js')
|
||||
vi.resetModules()
|
||||
const { parseAllSessions } = await import('../src/parser.js')
|
||||
|
||||
const first = await parseAllSessions(undefined, 'claude')
|
||||
expect(first.find(project => project.project === 'demo-project')?.totalApiCalls).toBe(1)
|
||||
|
||||
await appendFile(claudeSessionPath, [
|
||||
JSON.stringify({
|
||||
type: 'user',
|
||||
timestamp: '2026-04-20T09:05:00.000Z',
|
||||
sessionId: 'sess-1',
|
||||
message: { role: 'user', content: 'second' },
|
||||
}),
|
||||
JSON.stringify({
|
||||
type: 'assistant',
|
||||
timestamp: '2026-04-20T09:05:01.000Z',
|
||||
message: {
|
||||
id: 'msg-2',
|
||||
model: 'claude-sonnet-4-6',
|
||||
role: 'assistant',
|
||||
type: 'message',
|
||||
content: [],
|
||||
usage: { input_tokens: 11, output_tokens: 21 },
|
||||
},
|
||||
}),
|
||||
].join('\n') + '\n', 'utf-8')
|
||||
|
||||
const second = await parseAllSessions(undefined, 'claude')
|
||||
expect(second.find(project => project.project === 'demo-project')?.totalApiCalls).toBe(2)
|
||||
})
|
||||
|
||||
it('falls back to a full Claude reparse when cached tail verification fails', async () => {
|
||||
vi.doUnmock('../src/providers/index.js')
|
||||
vi.resetModules()
|
||||
const { parseAllSessions } = await import('../src/parser.js')
|
||||
await parseAllSessions(undefined, 'claude')
|
||||
|
||||
const cacheRoot = join(root, 'cache', 'source-cache-v1')
|
||||
const manifest = JSON.parse(await readFile(join(cacheRoot, 'manifest.json'), 'utf-8')) as {
|
||||
entries: Record<string, { file: string }>
|
||||
}
|
||||
const entryPath = join(cacheRoot, 'entries', manifest.entries[`claude:${claudeSessionPath}`]!.file)
|
||||
const entry = JSON.parse(await readFile(entryPath, 'utf-8')) as {
|
||||
appendState?: { tailHash?: string }
|
||||
}
|
||||
entry.appendState = { ...entry.appendState, tailHash: 'broken-tail-hash' }
|
||||
await writeFile(entryPath, JSON.stringify(entry), 'utf-8')
|
||||
|
||||
await appendFile(claudeSessionPath, [
|
||||
JSON.stringify({
|
||||
type: 'user',
|
||||
timestamp: '2026-04-20T09:05:00.000Z',
|
||||
sessionId: 'sess-1',
|
||||
message: { role: 'user', content: 'second' },
|
||||
}),
|
||||
JSON.stringify({
|
||||
type: 'assistant',
|
||||
timestamp: '2026-04-20T09:05:01.000Z',
|
||||
message: {
|
||||
id: 'msg-2',
|
||||
model: 'claude-sonnet-4-6',
|
||||
role: 'assistant',
|
||||
type: 'message',
|
||||
content: [],
|
||||
usage: { input_tokens: 11, output_tokens: 21 },
|
||||
},
|
||||
}),
|
||||
].join('\n') + '\n', 'utf-8')
|
||||
|
||||
vi.resetModules()
|
||||
const readSessionFileCalls: string[] = []
|
||||
const readSessionLinesFromOffsetCalls: Array<[string, number]> = []
|
||||
vi.doMock('../src/fs-utils.js', async () => {
|
||||
const actual = await vi.importActual<typeof import('../src/fs-utils.js')>('../src/fs-utils.js')
|
||||
return {
|
||||
...actual,
|
||||
readSessionFile: vi.fn(async (filePath: string) => {
|
||||
readSessionFileCalls.push(filePath)
|
||||
return actual.readSessionFile(filePath)
|
||||
}),
|
||||
readSessionLinesFromOffset: vi.fn(async function* (filePath: string, startOffset: number) {
|
||||
readSessionLinesFromOffsetCalls.push([filePath, startOffset])
|
||||
for await (const line of actual.readSessionLinesFromOffset(filePath, startOffset)) {
|
||||
yield line
|
||||
}
|
||||
}),
|
||||
}
|
||||
})
|
||||
|
||||
const { parseAllSessions: reparsedParseAllSessions } = await import('../src/parser.js')
|
||||
const reparsed = await reparsedParseAllSessions(undefined, 'claude')
|
||||
|
||||
expect(reparsed.find(project => project.project === 'demo-project')?.totalApiCalls).toBe(2)
|
||||
expect(readSessionFileCalls).toContain(claudeSessionPath)
|
||||
expect(readSessionLinesFromOffsetCalls).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('keeps appended assistant-only Claude entries inside the existing turn', async () => {
|
||||
vi.doUnmock('../src/providers/index.js')
|
||||
vi.resetModules()
|
||||
const { parseAllSessions } = await import('../src/parser.js')
|
||||
|
||||
const first = await parseAllSessions(undefined, 'claude')
|
||||
const initialSession = first.find(project => project.project === 'demo-project')?.sessions[0]
|
||||
expect(initialSession?.turns).toHaveLength(1)
|
||||
|
||||
await appendFile(claudeSessionPath, JSON.stringify({
|
||||
type: 'assistant',
|
||||
timestamp: '2026-04-20T09:05:01.000Z',
|
||||
message: {
|
||||
id: 'msg-2',
|
||||
model: 'claude-sonnet-4-6',
|
||||
role: 'assistant',
|
||||
type: 'message',
|
||||
content: [],
|
||||
usage: { input_tokens: 11, output_tokens: 21 },
|
||||
},
|
||||
}) + '\n', 'utf-8')
|
||||
|
||||
const second = await parseAllSessions(undefined, 'claude')
|
||||
const session = second.find(project => project.project === 'demo-project')?.sessions[0]
|
||||
|
||||
expect(session?.apiCalls).toBe(2)
|
||||
expect(session?.turns).toHaveLength(1)
|
||||
expect(session?.turns[0]?.userMessage).toBe('first')
|
||||
expect(session?.turns[0]?.assistantCalls).toHaveLength(2)
|
||||
})
|
||||
|
||||
it('caches Claude session files that contain no turns', async () => {
|
||||
await writeFile(claudeSessionPath, [
|
||||
JSON.stringify({
|
||||
type: 'user',
|
||||
timestamp: '2026-04-20T09:00:00.000Z',
|
||||
sessionId: 'sess-empty',
|
||||
message: { role: 'user', content: 'no assistant response' },
|
||||
}),
|
||||
].join('\n') + '\n', 'utf-8')
|
||||
|
||||
const readSessionFileCalls: string[] = []
|
||||
vi.doMock('../src/fs-utils.js', async () => {
|
||||
const actual = await vi.importActual<typeof import('../src/fs-utils.js')>('../src/fs-utils.js')
|
||||
return {
|
||||
...actual,
|
||||
readSessionFile: vi.fn(async (filePath: string) => {
|
||||
readSessionFileCalls.push(filePath)
|
||||
return actual.readSessionFile(filePath)
|
||||
}),
|
||||
}
|
||||
})
|
||||
|
||||
vi.resetModules()
|
||||
const { parseAllSessions } = await import('../src/parser.js')
|
||||
|
||||
const first = await parseAllSessions(undefined, 'claude')
|
||||
const cacheRoot = join(root, 'cache', 'source-cache-v1')
|
||||
const manifest = JSON.parse(await readFile(join(cacheRoot, 'manifest.json'), 'utf-8')) as {
|
||||
entries: Record<string, { file: string }>
|
||||
}
|
||||
const entryKey = `claude:${claudeSessionPath}`
|
||||
expect(manifest.entries[entryKey]).toBeDefined()
|
||||
const cacheEntry = JSON.parse(await readFile(join(cacheRoot, 'entries', manifest.entries[entryKey]!.file), 'utf-8')) as { sessions: unknown[] }
|
||||
|
||||
expect(first.find(project => project.project === 'demo-project')?.totalApiCalls).toBeUndefined()
|
||||
expect(readSessionFileCalls.filter(path => path === claudeSessionPath)).toHaveLength(1)
|
||||
expect(cacheEntry.sessions).toHaveLength(0)
|
||||
|
||||
const second = await parseAllSessions(undefined, 'claude')
|
||||
expect(second.find(project => project.project === 'demo-project')?.totalApiCalls).toBeUndefined()
|
||||
expect(readSessionFileCalls.filter(path => path === claudeSessionPath)).toHaveLength(1)
|
||||
})
|
||||
})
|
||||
|
|
@ -1,29 +0,0 @@
|
|||
import { describe, it, expect } from 'vitest'
|
||||
|
||||
import { PROVIDER_COLORS, providerColor, providerLabel } from '../src/provider-colors.js'
|
||||
|
||||
describe('provider presentation metadata', () => {
|
||||
it('exports the shared provider palette', () => {
|
||||
expect(PROVIDER_COLORS).toEqual({
|
||||
all: '#FF8C42',
|
||||
claude: '#FF8C42',
|
||||
codex: '#5BF5A0',
|
||||
cursor: '#00B4D8',
|
||||
opencode: '#A78BFA',
|
||||
pi: '#F472B6',
|
||||
copilot: '#6495ED',
|
||||
})
|
||||
})
|
||||
|
||||
it('maps provider names to labels', () => {
|
||||
expect(providerLabel('all')).toBe('All')
|
||||
expect(providerLabel('opencode')).toBe('OpenCode')
|
||||
expect(providerLabel('unknown')).toBe('unknown')
|
||||
})
|
||||
|
||||
it('maps provider names to colors with a neutral fallback', () => {
|
||||
expect(providerColor('all')).toBe('#FF8C42')
|
||||
expect(providerColor('opencode')).toBe('#A78BFA')
|
||||
expect(providerColor('unknown')).toBe('#CCCCCC')
|
||||
})
|
||||
})
|
||||
|
|
@ -1,21 +1,18 @@
|
|||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
|
||||
import { describe, it, expect, beforeEach, afterEach } from 'vitest'
|
||||
import { mkdtemp, mkdir, writeFile, rm } from 'fs/promises'
|
||||
import { join } from 'path'
|
||||
import { tmpdir } from 'os'
|
||||
|
||||
import { createCodexProvider } from '../../src/providers/codex.js'
|
||||
import * as fsUtils from '../../src/fs-utils.js'
|
||||
import type { ParsedProviderCall } from '../../src/providers/types.js'
|
||||
|
||||
let tmpDir: string
|
||||
|
||||
beforeEach(async () => {
|
||||
tmpDir = await mkdtemp(join(tmpdir(), 'codex-test-'))
|
||||
process.env['CODEBURN_CACHE_DIR'] = join(tmpDir, 'cache')
|
||||
})
|
||||
|
||||
afterEach(async () => {
|
||||
delete process.env['CODEBURN_CACHE_DIR']
|
||||
await rm(tmpDir, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
|
|
@ -139,28 +136,6 @@ describe('codex provider - session discovery', () => {
|
|||
const sessions = await provider.discoverSessions()
|
||||
expect(sessions).toEqual([])
|
||||
})
|
||||
|
||||
it('reuses cached discovery results when the directory tree is unchanged', async () => {
|
||||
await writeSession(tmpDir, '2026-04-14', 'rollout-cached.jsonl', [
|
||||
sessionMeta({ cwd: '/Users/test/myproject' }),
|
||||
tokenCount({ last: { input: 100, output: 50 }, total: { total: 150 } }),
|
||||
])
|
||||
|
||||
const provider = createCodexProvider(tmpDir)
|
||||
const readSpy = vi.spyOn(fsUtils, 'readSessionFile')
|
||||
|
||||
const first = await provider.discoverSessions()
|
||||
const firstReadCount = readSpy.mock.calls.length
|
||||
const second = await provider.discoverSessions()
|
||||
const secondReadCount = readSpy.mock.calls.length
|
||||
|
||||
expect(first).toHaveLength(1)
|
||||
expect(second).toEqual(first)
|
||||
expect(firstReadCount).toBeGreaterThan(0)
|
||||
expect(secondReadCount).toBe(firstReadCount)
|
||||
|
||||
readSpy.mockRestore()
|
||||
})
|
||||
})
|
||||
|
||||
describe('codex provider - JSONL parsing', () => {
|
||||
|
|
|
|||
|
|
@ -1,10 +1,9 @@
|
|||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
|
||||
import { describe, it, expect, beforeEach, afterEach } from 'vitest'
|
||||
import { mkdtemp, mkdir, writeFile, rm } from 'fs/promises'
|
||||
import { join } from 'path'
|
||||
import { tmpdir } from 'os'
|
||||
|
||||
import { copilot, createCopilotProvider } from '../../src/providers/copilot.js'
|
||||
import * as fsUtils from '../../src/fs-utils.js'
|
||||
import type { ParsedProviderCall } from '../../src/providers/types.js'
|
||||
|
||||
let tmpDir: string
|
||||
|
|
@ -41,11 +40,9 @@ function assistantMessage(opts: { messageId: string; outputTokens: number; tools
|
|||
describe('copilot provider - JSONL parsing', () => {
|
||||
beforeEach(async () => {
|
||||
tmpDir = await mkdtemp(join(tmpdir(), 'copilot-test-'))
|
||||
process.env['CODEBURN_CACHE_DIR'] = join(tmpDir, 'cache')
|
||||
})
|
||||
|
||||
afterEach(async () => {
|
||||
delete process.env['CODEBURN_CACHE_DIR']
|
||||
await rm(tmpDir, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
|
|
@ -222,25 +219,6 @@ describe('copilot provider - discoverSessions', () => {
|
|||
const sessions = await provider.discoverSessions()
|
||||
expect(sessions).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('reuses cached discovery results when session directories are unchanged', async () => {
|
||||
await createSessionDir('sess-disc-cached', [modelChange('gpt-4.1')], '/home/user/myapp')
|
||||
|
||||
const provider = createCopilotProvider(tmpDir)
|
||||
const readSpy = vi.spyOn(fsUtils, 'readSessionFile')
|
||||
|
||||
const first = await provider.discoverSessions()
|
||||
const firstReadCount = readSpy.mock.calls.length
|
||||
const second = await provider.discoverSessions()
|
||||
const secondReadCount = readSpy.mock.calls.length
|
||||
|
||||
expect(first).toHaveLength(1)
|
||||
expect(second).toEqual(first)
|
||||
expect(firstReadCount).toBeGreaterThan(0)
|
||||
expect(secondReadCount).toBe(firstReadCount)
|
||||
|
||||
readSpy.mockRestore()
|
||||
})
|
||||
})
|
||||
|
||||
describe('copilot provider - metadata', () => {
|
||||
|
|
|
|||
|
|
@ -107,9 +107,6 @@ describe('cursor-agent provider', () => {
|
|||
expect(sources).toHaveLength(1)
|
||||
expect(sources[0]!.provider).toBe('cursor-agent')
|
||||
expect(sources[0]!.path).toBe(transcriptPath)
|
||||
expect(sources[0]!.fingerprintPath).toBe(transcriptPath)
|
||||
expect(sources[0]!.cacheStrategy).toBe('full-reparse')
|
||||
expect(sources[0]!.parserVersion).toBe('cursor-agent:v1')
|
||||
})
|
||||
|
||||
it('discovers transcripts across multiple projects', async () => {
|
||||
|
|
|
|||
|
|
@ -1,15 +1,6 @@
|
|||
import { beforeEach, afterEach, describe, expect, it } from 'vitest'
|
||||
import { mkdtemp, mkdir, rm, writeFile } from 'fs/promises'
|
||||
import { join } from 'path'
|
||||
import { tmpdir } from 'os'
|
||||
|
||||
import { describe, it, expect, beforeEach } from 'vitest'
|
||||
import { getAllProviders } from '../../src/providers/index.js'
|
||||
import { createCursorProvider } from '../../src/providers/cursor.js'
|
||||
import { createOpenCodeProvider } from '../../src/providers/opencode.js'
|
||||
import type { Provider } from '../../src/providers/types.js'
|
||||
import { isSqliteAvailable } from '../../src/sqlite.js'
|
||||
|
||||
const skipUnlessSqlite = isSqliteAvailable() ? describe : describe.skip
|
||||
|
||||
describe('cursor provider', () => {
|
||||
let cursorProvider: Provider
|
||||
|
|
@ -77,83 +68,10 @@ describe('cursor sqlite adapter', () => {
|
|||
})
|
||||
})
|
||||
|
||||
skipUnlessSqlite('shared cache metadata', () => {
|
||||
let tmpDir: string
|
||||
|
||||
beforeEach(async () => {
|
||||
tmpDir = await mkdtemp(join(tmpdir(), 'provider-cache-meta-'))
|
||||
})
|
||||
|
||||
afterEach(async () => {
|
||||
await rm(tmpDir, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
async function createOpenCodeTestDb(dir: string): Promise<string> {
|
||||
const ocDir = join(dir, 'opencode')
|
||||
const dbPath = join(ocDir, 'opencode.db')
|
||||
const { DatabaseSync: Database } = require('node:sqlite')
|
||||
|
||||
await mkdir(ocDir, { recursive: true })
|
||||
const db = new Database(dbPath)
|
||||
db.exec(`
|
||||
CREATE TABLE session (
|
||||
id TEXT PRIMARY KEY, project_id TEXT NOT NULL, parent_id TEXT,
|
||||
slug TEXT NOT NULL, directory TEXT NOT NULL, title TEXT NOT NULL,
|
||||
version TEXT NOT NULL, time_created INTEGER, time_updated INTEGER,
|
||||
time_archived INTEGER
|
||||
)
|
||||
`)
|
||||
db.exec(`
|
||||
CREATE TABLE message (
|
||||
id TEXT PRIMARY KEY, session_id TEXT NOT NULL,
|
||||
time_created INTEGER, time_updated INTEGER, data TEXT NOT NULL
|
||||
)
|
||||
`)
|
||||
db.exec(`
|
||||
CREATE TABLE part (
|
||||
id TEXT PRIMARY KEY, message_id TEXT NOT NULL,
|
||||
session_id TEXT NOT NULL, time_created INTEGER,
|
||||
time_updated INTEGER, data TEXT NOT NULL
|
||||
)
|
||||
`)
|
||||
db.prepare(`
|
||||
INSERT INTO session (id, project_id, slug, directory, title, version, time_created)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)
|
||||
`).run('sess-1', 'proj-1', 'slug-1', '/home/user/myproject', 'My Project', '1.0', 1700000000000)
|
||||
db.close()
|
||||
return dbPath
|
||||
}
|
||||
|
||||
it('cursor exposes the sqlite database as its fingerprint path', async () => {
|
||||
const dbPath = join(tmpDir, 'state.vscdb')
|
||||
await writeFile(dbPath, '')
|
||||
|
||||
const cursor = createCursorProvider(dbPath)
|
||||
const sources = await cursor.discoverSessions()
|
||||
|
||||
expect(sources).toHaveLength(1)
|
||||
for (const source of sources) {
|
||||
expect(source.cacheStrategy).toBe('full-reparse')
|
||||
expect(source.fingerprintPath).toBe(source.path)
|
||||
expect(source.progressLabel).toBe('Cursor state.vscdb')
|
||||
expect(source.parserVersion).toBe('cursor:v1')
|
||||
}
|
||||
})
|
||||
|
||||
it('opencode sources fingerprint the backing database, not the logical dbPath:sessionId key', async () => {
|
||||
const dbPath = await createOpenCodeTestDb(tmpDir)
|
||||
|
||||
const opencode = createOpenCodeProvider(tmpDir)
|
||||
const sources = await opencode.discoverSessions()
|
||||
|
||||
expect(sources).toHaveLength(1)
|
||||
for (const source of sources) {
|
||||
expect(source.cacheStrategy).toBe('full-reparse')
|
||||
expect(source.fingerprintPath).toBeTruthy()
|
||||
expect(source.fingerprintPath).toBe(dbPath)
|
||||
expect(source.fingerprintPath).not.toBe(source.path)
|
||||
expect(source.progressLabel).toBe('opencode:sess-1')
|
||||
expect(source.parserVersion).toBe('opencode:v1')
|
||||
}
|
||||
describe('cursor cache', () => {
|
||||
it('returns null when no cache exists', async () => {
|
||||
const { readCachedResults } = await import('../../src/cursor-cache.js')
|
||||
const result = await readCachedResults('/nonexistent/path.db')
|
||||
expect(result).toBeNull()
|
||||
})
|
||||
})
|
||||
|
|
|
|||
|
|
@ -1,24 +1,18 @@
|
|||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
|
||||
import { describe, it, expect, beforeEach, afterEach } from 'vitest'
|
||||
import { mkdtemp, mkdir, writeFile, rm } from 'fs/promises'
|
||||
import { join } from 'path'
|
||||
import { tmpdir } from 'os'
|
||||
|
||||
import { createPiProvider } from '../../src/providers/pi.js'
|
||||
import * as fsUtils from '../../src/fs-utils.js'
|
||||
import type { ParsedProviderCall } from '../../src/providers/types.js'
|
||||
|
||||
let tmpDir: string
|
||||
let cacheDir: string
|
||||
|
||||
beforeEach(async () => {
|
||||
tmpDir = await mkdtemp(join(tmpdir(), 'pi-test-'))
|
||||
cacheDir = await mkdtemp(join(tmpdir(), 'pi-cache-'))
|
||||
process.env['CODEBURN_CACHE_DIR'] = cacheDir
|
||||
})
|
||||
|
||||
afterEach(async () => {
|
||||
delete process.env['CODEBURN_CACHE_DIR']
|
||||
await rm(cacheDir, { recursive: true, force: true })
|
||||
await rm(tmpDir, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
|
|
@ -152,29 +146,6 @@ describe('pi provider - session discovery', () => {
|
|||
const sessions = await provider.discoverSessions()
|
||||
expect(sessions).toEqual([])
|
||||
})
|
||||
|
||||
it('reuses cached discovery results when project directories are unchanged', async () => {
|
||||
const projectDir = join(tmpDir, '--Users-test-myproject--')
|
||||
await writeSession(projectDir, 'cached.jsonl', [
|
||||
sessionMeta({ cwd: '/Users/test/myproject' }),
|
||||
assistantMessage({}),
|
||||
])
|
||||
|
||||
const provider = createPiProvider(tmpDir)
|
||||
const readSpy = vi.spyOn(fsUtils, 'readSessionFile')
|
||||
|
||||
const first = await provider.discoverSessions()
|
||||
const firstReadCount = readSpy.mock.calls.length
|
||||
const second = await provider.discoverSessions()
|
||||
const secondReadCount = readSpy.mock.calls.length
|
||||
|
||||
expect(first).toHaveLength(1)
|
||||
expect(second).toEqual(first)
|
||||
expect(firstReadCount).toBeGreaterThan(0)
|
||||
expect(secondReadCount).toBe(firstReadCount)
|
||||
|
||||
readSpy.mockRestore()
|
||||
})
|
||||
})
|
||||
|
||||
describe('pi provider - JSONL parsing', () => {
|
||||
|
|
|
|||
|
|
@ -1,363 +0,0 @@
|
|||
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
|
||||
import { createHash } from 'crypto'
|
||||
import { existsSync } from 'fs'
|
||||
import { mkdir, mkdtemp, readFile, readdir, rm, writeFile } from 'fs/promises'
|
||||
import { tmpdir } from 'os'
|
||||
import { join } from 'path'
|
||||
|
||||
import {
|
||||
SOURCE_CACHE_VERSION,
|
||||
emptySourceCacheManifest,
|
||||
loadSourceCacheManifest,
|
||||
saveSourceCacheManifest,
|
||||
readSourceCacheEntry,
|
||||
writeSourceCacheEntry,
|
||||
computeFileFingerprint,
|
||||
type SourceCacheEntry,
|
||||
} from '../src/source-cache.js'
|
||||
import type { SessionSummary } from '../src/types.js'
|
||||
|
||||
let root = ''
|
||||
|
||||
function emptySession(sessionId: string, overrides: Partial<SessionSummary> = {}): SessionSummary {
|
||||
return {
|
||||
sessionId,
|
||||
project: 'project',
|
||||
firstTimestamp: '2026-04-10T00:00:00Z',
|
||||
lastTimestamp: '2026-04-10T00:00:00Z',
|
||||
totalCostUSD: 0,
|
||||
totalInputTokens: 0,
|
||||
totalOutputTokens: 0,
|
||||
totalCacheReadTokens: 0,
|
||||
totalCacheWriteTokens: 0,
|
||||
apiCalls: 0,
|
||||
turns: [],
|
||||
modelBreakdown: {},
|
||||
toolBreakdown: {},
|
||||
mcpBreakdown: {},
|
||||
bashBreakdown: {},
|
||||
categoryBreakdown: {},
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
beforeEach(async () => {
|
||||
root = await mkdtemp(join(tmpdir(), 'codeburn-source-cache-'))
|
||||
process.env['CODEBURN_CACHE_DIR'] = root
|
||||
})
|
||||
|
||||
afterEach(async () => {
|
||||
delete process.env['CODEBURN_CACHE_DIR']
|
||||
if (root) await rm(root, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
describe('source cache manifest', () => {
|
||||
it('returns an empty manifest when no file exists', async () => {
|
||||
await expect(loadSourceCacheManifest()).resolves.toEqual(emptySourceCacheManifest())
|
||||
})
|
||||
|
||||
it('returns an empty manifest when the manifest shape is invalid', async () => {
|
||||
await mkdir(join(root, 'source-cache-v1'), { recursive: true })
|
||||
await writeFile(join(root, 'source-cache-v1', 'manifest.json'), JSON.stringify({
|
||||
version: SOURCE_CACHE_VERSION,
|
||||
entries: { bad: { file: 123, provider: 'fake' } },
|
||||
}), 'utf-8')
|
||||
|
||||
await expect(loadSourceCacheManifest()).resolves.toEqual(emptySourceCacheManifest())
|
||||
})
|
||||
|
||||
it('returns an empty manifest when an entry filename is unsafe', async () => {
|
||||
await mkdir(join(root, 'source-cache-v1'), { recursive: true })
|
||||
await writeFile(join(root, 'source-cache-v1', 'manifest.json'), JSON.stringify({
|
||||
version: SOURCE_CACHE_VERSION,
|
||||
entries: {
|
||||
bad: {
|
||||
file: '../escape.json',
|
||||
provider: 'fake',
|
||||
logicalPath: join(root, 'source.jsonl'),
|
||||
},
|
||||
},
|
||||
}), 'utf-8')
|
||||
|
||||
await expect(loadSourceCacheManifest()).resolves.toEqual(emptySourceCacheManifest())
|
||||
})
|
||||
|
||||
it('round-trips a manifest and entry', async () => {
|
||||
const sourcePath = join(root, 'source.jsonl')
|
||||
await writeFile(sourcePath, '{"ok":true}\n', 'utf-8')
|
||||
const fingerprint = await computeFileFingerprint(sourcePath)
|
||||
const entry: SourceCacheEntry = {
|
||||
version: SOURCE_CACHE_VERSION,
|
||||
provider: 'fake',
|
||||
logicalPath: sourcePath,
|
||||
fingerprintPath: sourcePath,
|
||||
cacheStrategy: 'full-reparse',
|
||||
parserVersion: 'fake-v1',
|
||||
fingerprint,
|
||||
sessions: [],
|
||||
}
|
||||
|
||||
const manifest = await loadSourceCacheManifest()
|
||||
await writeSourceCacheEntry(manifest, entry)
|
||||
await saveSourceCacheManifest(manifest)
|
||||
|
||||
const loadedManifest = await loadSourceCacheManifest()
|
||||
const loadedEntry = await readSourceCacheEntry(loadedManifest, 'fake', sourcePath)
|
||||
expect(loadedEntry).toEqual(entry)
|
||||
})
|
||||
|
||||
it('returns null when the fingerprint no longer matches', async () => {
|
||||
const sourcePath = join(root, 'source.jsonl')
|
||||
await writeFile(sourcePath, 'one\n', 'utf-8')
|
||||
const fingerprint = await computeFileFingerprint(sourcePath)
|
||||
const entry: SourceCacheEntry = {
|
||||
version: SOURCE_CACHE_VERSION,
|
||||
provider: 'fake',
|
||||
logicalPath: sourcePath,
|
||||
fingerprintPath: sourcePath,
|
||||
cacheStrategy: 'full-reparse',
|
||||
parserVersion: 'fake-v1',
|
||||
fingerprint,
|
||||
sessions: [],
|
||||
}
|
||||
|
||||
const manifest = await loadSourceCacheManifest()
|
||||
await writeSourceCacheEntry(manifest, entry)
|
||||
await saveSourceCacheManifest(manifest)
|
||||
|
||||
await writeFile(sourcePath, 'one\ntwo\n', 'utf-8')
|
||||
const loaded = await readSourceCacheEntry(await loadSourceCacheManifest(), 'fake', sourcePath)
|
||||
expect(loaded).toBeNull()
|
||||
})
|
||||
|
||||
it('returns null when the cached entry shape is invalid', async () => {
|
||||
const sourcePath = join(root, 'source.jsonl')
|
||||
await writeFile(sourcePath, 'one\n', 'utf-8')
|
||||
const manifest = await loadSourceCacheManifest()
|
||||
const file = `${createHash('sha1').update(`fake:${sourcePath}`).digest('hex')}.json`
|
||||
manifest.entries[`fake:${sourcePath}`] = { file, provider: 'fake', logicalPath: sourcePath }
|
||||
await saveSourceCacheManifest(manifest)
|
||||
await mkdir(join(root, 'source-cache-v1', 'entries'), { recursive: true })
|
||||
await writeFile(join(root, 'source-cache-v1', 'entries', file), JSON.stringify({
|
||||
version: SOURCE_CACHE_VERSION,
|
||||
provider: 'fake',
|
||||
logicalPath: sourcePath,
|
||||
fingerprintPath: sourcePath,
|
||||
cacheStrategy: 'full-reparse',
|
||||
parserVersion: 'fake-v1',
|
||||
fingerprint: { mtimeMs: 'nope', sizeBytes: 4 },
|
||||
sessions: [],
|
||||
}), 'utf-8')
|
||||
|
||||
const loaded = await readSourceCacheEntry(await loadSourceCacheManifest(), 'fake', sourcePath)
|
||||
expect(loaded).toBeNull()
|
||||
})
|
||||
|
||||
it('returns null when the manifest metadata does not match the lookup request', async () => {
|
||||
const sourcePath = join(root, 'source.jsonl')
|
||||
await writeFile(sourcePath, 'one\n', 'utf-8')
|
||||
const fingerprint = await computeFileFingerprint(sourcePath)
|
||||
const file = `${createHash('sha1').update(`fake:${sourcePath}`).digest('hex')}.json`
|
||||
const manifest = await loadSourceCacheManifest()
|
||||
manifest.entries[`fake:${sourcePath}`] = {
|
||||
file,
|
||||
provider: 'other',
|
||||
logicalPath: sourcePath,
|
||||
}
|
||||
await saveSourceCacheManifest(manifest)
|
||||
await mkdir(join(root, 'source-cache-v1', 'entries'), { recursive: true })
|
||||
await writeFile(join(root, 'source-cache-v1', 'entries', file), JSON.stringify({
|
||||
version: SOURCE_CACHE_VERSION,
|
||||
provider: 'fake',
|
||||
logicalPath: sourcePath,
|
||||
fingerprintPath: sourcePath,
|
||||
cacheStrategy: 'full-reparse',
|
||||
parserVersion: 'fake-v1',
|
||||
fingerprint,
|
||||
sessions: [],
|
||||
}), 'utf-8')
|
||||
|
||||
const loaded = await readSourceCacheEntry(await loadSourceCacheManifest(), 'fake', sourcePath)
|
||||
expect(loaded).toBeNull()
|
||||
})
|
||||
|
||||
it('returns null when a nested assistant call is malformed', async () => {
|
||||
const sourcePath = join(root, 'source.jsonl')
|
||||
await writeFile(sourcePath, 'one\n', 'utf-8')
|
||||
const fingerprint = await computeFileFingerprint(sourcePath)
|
||||
const entry: SourceCacheEntry = {
|
||||
version: SOURCE_CACHE_VERSION,
|
||||
provider: 'fake',
|
||||
logicalPath: sourcePath,
|
||||
fingerprintPath: sourcePath,
|
||||
cacheStrategy: 'full-reparse',
|
||||
parserVersion: 'fake-v1',
|
||||
fingerprint,
|
||||
sessions: [
|
||||
emptySession('session-1', {
|
||||
turns: [{
|
||||
userMessage: 'hello',
|
||||
assistantCalls: [{
|
||||
provider: 'fake',
|
||||
model: 'model',
|
||||
usage: {
|
||||
inputTokens: 1,
|
||||
outputTokens: 1,
|
||||
cacheCreationInputTokens: 0,
|
||||
cacheReadInputTokens: 0,
|
||||
cachedInputTokens: 0,
|
||||
reasoningTokens: 0,
|
||||
webSearchRequests: 0,
|
||||
},
|
||||
costUSD: 1,
|
||||
tools: [],
|
||||
mcpTools: [],
|
||||
hasAgentSpawn: false,
|
||||
hasPlanMode: false,
|
||||
speed: 'standard',
|
||||
timestamp: '2026-04-10T00:00:00Z',
|
||||
bashCommands: [],
|
||||
deduplicationKey: 'k',
|
||||
}],
|
||||
timestamp: '2026-04-10T00:00:00Z',
|
||||
sessionId: 'session-1',
|
||||
}],
|
||||
}),
|
||||
],
|
||||
}
|
||||
|
||||
const manifest = await loadSourceCacheManifest()
|
||||
await writeSourceCacheEntry(manifest, entry)
|
||||
await saveSourceCacheManifest(manifest)
|
||||
|
||||
await writeFile(join(root, 'source-cache-v1', 'entries', `${createHash('sha1').update(`fake:${sourcePath}`).digest('hex')}.json`), JSON.stringify({
|
||||
...entry,
|
||||
sessions: [{
|
||||
...entry.sessions[0],
|
||||
turns: [{
|
||||
...entry.sessions[0].turns[0],
|
||||
assistantCalls: [{
|
||||
...entry.sessions[0].turns[0].assistantCalls[0],
|
||||
usage: { ...entry.sessions[0].turns[0].assistantCalls[0].usage, inputTokens: 'bad' },
|
||||
}],
|
||||
}],
|
||||
}],
|
||||
}), 'utf-8')
|
||||
|
||||
const loaded = await readSourceCacheEntry(await loadSourceCacheManifest(), 'fake', sourcePath)
|
||||
expect(loaded).toBeNull()
|
||||
})
|
||||
|
||||
it('returns null when append state is malformed', async () => {
|
||||
const sourcePath = join(root, 'source.jsonl')
|
||||
await writeFile(sourcePath, 'one\n', 'utf-8')
|
||||
const fingerprint = await computeFileFingerprint(sourcePath)
|
||||
const entry = {
|
||||
version: SOURCE_CACHE_VERSION,
|
||||
provider: 'fake',
|
||||
logicalPath: sourcePath,
|
||||
fingerprintPath: sourcePath,
|
||||
cacheStrategy: 'append-jsonl' as const,
|
||||
parserVersion: 'fake-v1',
|
||||
fingerprint,
|
||||
sessions: [],
|
||||
appendState: { endOffset: 'bad', tailHash: 'abc' },
|
||||
}
|
||||
|
||||
const manifest = await loadSourceCacheManifest()
|
||||
await writeSourceCacheEntry(manifest, entry as SourceCacheEntry)
|
||||
await saveSourceCacheManifest(manifest)
|
||||
|
||||
const loaded = await readSourceCacheEntry(await loadSourceCacheManifest(), 'fake', sourcePath)
|
||||
expect(loaded).toBeNull()
|
||||
})
|
||||
|
||||
it('returns null when a breakdown map contains malformed values', async () => {
|
||||
const sourcePath = join(root, 'source.jsonl')
|
||||
await writeFile(sourcePath, 'one\n', 'utf-8')
|
||||
const fingerprint = await computeFileFingerprint(sourcePath)
|
||||
const entry: SourceCacheEntry = {
|
||||
version: SOURCE_CACHE_VERSION,
|
||||
provider: 'fake',
|
||||
logicalPath: sourcePath,
|
||||
fingerprintPath: sourcePath,
|
||||
cacheStrategy: 'full-reparse',
|
||||
parserVersion: 'fake-v1',
|
||||
fingerprint,
|
||||
sessions: [
|
||||
emptySession('session-2', {
|
||||
modelBreakdown: {
|
||||
modelA: {
|
||||
calls: 'bad',
|
||||
costUSD: 0,
|
||||
tokens: {
|
||||
inputTokens: 0,
|
||||
outputTokens: 0,
|
||||
cacheCreationInputTokens: 0,
|
||||
cacheReadInputTokens: 0,
|
||||
cachedInputTokens: 0,
|
||||
reasoningTokens: 0,
|
||||
webSearchRequests: 0,
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
],
|
||||
}
|
||||
|
||||
const manifest = await loadSourceCacheManifest()
|
||||
await writeSourceCacheEntry(manifest, entry)
|
||||
await saveSourceCacheManifest(manifest)
|
||||
|
||||
const loaded = await readSourceCacheEntry(await loadSourceCacheManifest(), 'fake', sourcePath)
|
||||
expect(loaded).toBeNull()
|
||||
})
|
||||
|
||||
it('writes atomically without leaving temp files behind', async () => {
|
||||
const sourcePath = join(root, 'source.jsonl')
|
||||
await writeFile(sourcePath, 'x\n', 'utf-8')
|
||||
const manifest = await loadSourceCacheManifest()
|
||||
await writeSourceCacheEntry(manifest, {
|
||||
version: SOURCE_CACHE_VERSION,
|
||||
provider: 'fake',
|
||||
logicalPath: sourcePath,
|
||||
fingerprintPath: sourcePath,
|
||||
cacheStrategy: 'full-reparse',
|
||||
parserVersion: 'fake-v1',
|
||||
fingerprint: await computeFileFingerprint(sourcePath),
|
||||
sessions: [],
|
||||
})
|
||||
await saveSourceCacheManifest(manifest)
|
||||
|
||||
const files = JSON.parse(await readFile(join(root, 'source-cache-v1', 'manifest.json'), 'utf-8'))
|
||||
expect(files.version).toBe(SOURCE_CACHE_VERSION)
|
||||
expect(existsSync(join(root, 'source-cache-v1', 'entries'))).toBe(true)
|
||||
const cacheFiles = await readdir(join(root, 'source-cache-v1'))
|
||||
const entryFiles = await readdir(join(root, 'source-cache-v1', 'entries'))
|
||||
expect(cacheFiles.some(f => f.endsWith('.tmp'))).toBe(false)
|
||||
expect(entryFiles.some(f => f.endsWith('.tmp'))).toBe(false)
|
||||
})
|
||||
|
||||
it('does not mutate the manifest when the entry write fails', async () => {
|
||||
const sourcePath = join(root, 'source.jsonl')
|
||||
await writeFile(sourcePath, 'x\n', 'utf-8')
|
||||
const manifest = await loadSourceCacheManifest()
|
||||
const provider = 'fake'
|
||||
const logicalPath = sourcePath
|
||||
const file = `${createHash('sha1').update(`${provider}:${logicalPath}`).digest('hex')}.json`
|
||||
await mkdir(join(root, 'source-cache-v1', 'entries', file), { recursive: true })
|
||||
|
||||
await expect(writeSourceCacheEntry(manifest, {
|
||||
version: SOURCE_CACHE_VERSION,
|
||||
provider,
|
||||
logicalPath,
|
||||
fingerprintPath: sourcePath,
|
||||
cacheStrategy: 'full-reparse',
|
||||
parserVersion: 'fake-v1',
|
||||
fingerprint: await computeFileFingerprint(sourcePath),
|
||||
sessions: [],
|
||||
})).rejects.toBeTruthy()
|
||||
|
||||
expect(manifest.entries[`fake:${sourcePath}`]).toBeUndefined()
|
||||
})
|
||||
})
|
||||
Loading…
Add table
Add a link
Reference in a new issue