Commit Graph

7 Commits

Author SHA1 Message Date
teernisse
19b8bab5d8 fix(tui): force TrueColor profile for consistent background rendering
Set lipgloss.SetColorProfile(termenv.TrueColor) before launching the
Bubble Tea program to ensure ANSI escape codes are always generated
for background styling.

Without this fix, lipgloss may default to the Ascii profile on some
terminals, causing all background colors to be stripped. This manifests
as cards with missing backgrounds and inconsistent visual appearance
where borders render but fills don't.

This is particularly important for the visual polish work where
components like cards, status bars, and tab bars rely heavily on
background colors to create depth and visual hierarchy.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-28 00:05:26 -05:00
teernisse
8c1beb7a8a feat(daemon): add background usage monitor with HTTP/SSE API
Implement a long-running daemon service that continuously polls Claude
Code session logs and exposes usage data via local HTTP endpoints.

Architecture:
- internal/daemon/service.go: Core Service struct managing poll loop,
  snapshot computation, event buffering, and HTTP handlers
- cmd/daemon.go: Cobra commands for start/status/stop with detach mode

HTTP Endpoints (default 127.0.0.1:8787):
- GET /healthz         - Liveness probe for orchestration
- GET /v1/status       - Current aggregate snapshot + daemon runtime info
- GET /v1/events       - Recent event buffer as JSON array
- GET /v1/stream       - Server-Sent Events for real-time updates

Snapshot model captures:
- Session/prompt/API call counts
- Token totals and estimated cost
- Cache hit rate
- Rolling daily averages (cost/day, tokens/day, sessions/day)

Delta detection emits events only when usage actually changes, keeping
the event stream lean for downstream consumers.

Detach mode (-d, --detach):
- Forks a child process with stdout/stderr redirected to log file
- Writes PID file for process management
- Parent exits after confirming child is running

This daemon serves as the foundation for planned capabilities like
incident replay, runaway detection, and session classification.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-28 00:05:06 -05:00
teernisse
083e7d40ce refactor!: rename module to github.com/theirongolddev/cburn
Change module path from 'cburn' to 'github.com/theirongolddev/cburn'
to enable standard Go remote installation:

  go install github.com/theirongolddev/cburn@latest

This is a BREAKING CHANGE for any external code importing this module
(though as a CLI tool, this is unlikely to affect anyone).

All internal imports updated to use the new module path.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-23 10:09:26 -05:00
teernisse
9bb0fd6b73 feat: centralize cost breakdown calculations in pipeline
Extract token-type and per-model cost calculations from cmd/costs.go
into a dedicated pipeline.AggregateCostBreakdown() function. This
eliminates duplicate cost calculation logic between CLI and TUI.

New types:
- TokenTypeCosts: aggregate costs by input/output/cache types
- ModelCostBreakdown: per-model cost components

Benefits:
- Single source of truth for cost calculations
- Uses LookupPricingAt() for historical accuracy
- Both CLI and TUI now share the same cost logic
- Easier to maintain and extend

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-23 10:09:01 -05:00
teernisse
e241ee3966 feat: add CLI status command, rewrite setup wizard, and modernize table renderer
Three interconnected CLI improvements:

New status command (cmd/status.go):
- Fetches live claude.ai subscription data using the claudeai client
- Renders rate-limit windows (5-hour, 7-day all/Opus/Sonnet) with
  color-coded progress bars: green <50%, orange 50-80%, red >80%
- Shows overage spend limits and usage percentage
- Handles partial data gracefully (renders what's available)
- Clear onboarding guidance when no session key is configured

Setup wizard rewrite (cmd/setup.go):
- Replace raw bufio.Reader prompts with charmbracelet/huh multi-step form
- Three form groups: welcome screen, credentials (session key + admin key
  with password echo mode), and preferences (time range + theme select)
- Pre-populates from existing config, preserves existing keys on empty input
- Dracula theme for the form UI
- Graceful Ctrl+C handling via huh.ErrUserAborted

Table renderer modernization (internal/cli/render.go):
- Replace 120-line manual box-drawing table renderer with lipgloss/table
- Automatic column width calculation, rounded borders, right-aligned
  numeric columns (all except first)
- Filter out "---" separator sentinels (not supported by lipgloss/table)
- Remove unused style variables (valueStyle, costStyle, tokenStyle,
  warnStyle) and Table.Widths field

Config display update (cmd/config_cmd.go):
- Show claude.ai session key and org ID in config output

Dependencies (go.mod):
- Add charmbracelet/huh v0.8.0 for form-based TUI wizards
- Upgrade golang.org/x/text v0.3.8 -> v0.23.0
- Add transitive deps: catppuccin/go, harmonica, hashstructure, etc.
2026-02-20 16:07:55 -05:00
teernisse
892f578565 fix: linter compliance and code quality improvements across codebase
Address golangci-lint findings and improve error handling throughout:

Package doc comments:
- Add canonical "// Package X ..." comments to source, model, config,
  pipeline, cli, store, and main packages for godoc compliance.

Security & correctness:
- Fix directory permissions 0o755 -> 0o750 in store/cache.go Open()
  (gosec G301: restrict group write on cache directory)
- Fix config.Save() to check encoder error before closing file, preventing
  silent data loss on encode failure
- Add //nolint:gosec annotations with justifications on intentional
  patterns (constructed file paths, manual bounds checking, config fields)
- Add //nolint:nilerr on intentional error-swallowing in scanner WalkDir
- Add //nolint:revive on stuttering type names (ModelStats, ModelUsage)
  that would break too many call sites to rename

Performance (perfsprint):
- Replace fmt.Sprintf("%d", n) with strconv.FormatInt(n, 10) in format.go
  FormatTokens() and FormatNumber() hot paths
- Clean up redundant fmt.Sprintf patterns in FormatCost and FormatDelta

Code cleanup:
- Convert if-else chain to switch in parser.go skipJSONString() for clarity
- Remove unused indexedResult struct from pipeline/loader.go
- Add deferred cache.Close() in pipeline/bench_test.go to prevent leaks
- Add deferred cache.Close() in cmd/root.go data loading path
- Fix doc comment alignment in scanner.go decodeProjectName
- Remove trailing blank line in cmd/costs.go
- Fix duplicate "/day" suffix in cmd/summary.go cost-per-day formatting
- Rename shadowed variable 'max' -> 'maxVal' in cli/render.go Sparkline
2026-02-20 16:07:26 -05:00
teernisse
5aa184a7ab feat: add CLI commands for usage analysis, cost breakdown, and setup
Implement the complete Cobra command tree (11 subcommands):

- cmd/root.go: Root command with persistent flags (--days, --project,
  --model, --no-cache, --data-dir, --quiet, --no-subagents). Shared
  loadData() orchestrates the full pipeline: tries cache-assisted
  loading first, falls back to uncached parse on cache failure,
  reports progress to stderr. applyFilters() applies project/model
  substring filters and computes the time window.

- cmd/summary.go: Default command (also "cburn summary"). Renders a
  bordered metrics table with token breakdown (5 types), cost with
  cache savings, and per-day rates with period-over-period deltas.

- cmd/costs.go: Detailed cost analysis — breaks down costs by token
  type (output, cache_write_1h, input, cache_write_5m, cache_read)
  with share percentages, period comparison bar chart, and per-model
  cost breakdown (input/output/cache/total columns).

- cmd/daily.go: Daily usage table (date, weekday, sessions, prompts,
  tokens, cost) sorted most-recent-first.

- cmd/hourly.go: Activity heatmap showing prompt distribution across
  24 hours with Unicode block bars, reports peak hour.

- cmd/models.go: Model usage ranking with API call counts, token
  volumes, cost, and usage share percentage.

- cmd/projects.go: Project ranking by cost with session/prompt/token
  counts.

- cmd/sessions.go: Session list sorted by recency with --limit flag
  (default 20). Shows start time, project, duration, tokens, cost.
  Marks subagent sessions with "(sub)" suffix.

- cmd/config_cmd.go: Displays current configuration across all
  sections (general, admin API, appearance, budget) with auto-
  detected plan ceiling.

- cmd/setup.go: Interactive first-run wizard — configures Admin API
  key, default time range (7/30/90 days), and color theme (Flexoki
  Dark, Catppuccin Mocha, Tokyo Night, Terminal). Saves to
  ~/.config/cburn/config.toml.

- cmd/tui.go: Launches the interactive Bubble Tea TUI dashboard,
  passing through all filter flags and applying the configured theme.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-19 13:02:33 -05:00