tokenwise-cli 0.1.1__tar.gz → 0.1.3__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. tokenwise_cli-0.1.3/.claude/settings.local.json +11 -0
  2. {tokenwise_cli-0.1.1 → tokenwise_cli-0.1.3}/.github/workflows/ci.yml +3 -3
  3. tokenwise_cli-0.1.3/.github/workflows/release.yml +114 -0
  4. {tokenwise_cli-0.1.1 → tokenwise_cli-0.1.3}/PKG-INFO +6 -9
  5. {tokenwise_cli-0.1.1 → tokenwise_cli-0.1.3}/README.md +2 -5
  6. {tokenwise_cli-0.1.1 → tokenwise_cli-0.1.3}/pyproject.toml +3 -3
  7. tokenwise_cli-0.1.3/src/tokenwise/__init__.py +1 -0
  8. tokenwise_cli-0.1.3/src/tokenwise/analyzer.py +241 -0
  9. {tokenwise_cli-0.1.1 → tokenwise_cli-0.1.3}/src/tokenwise/cli.py +27 -18
  10. {tokenwise_cli-0.1.1 → tokenwise_cli-0.1.3}/src/tokenwise/dashboard.py +6 -4
  11. tokenwise_cli-0.1.3/src/tokenwise/parser.py +281 -0
  12. tokenwise_cli-0.1.3/src/tokenwise/pricing.py +130 -0
  13. {tokenwise_cli-0.1.1 → tokenwise_cli-0.1.3}/src/tokenwise/security.py +2 -2
  14. {tokenwise_cli-0.1.1 → tokenwise_cli-0.1.3}/src/tokenwise/storage.py +3 -3
  15. {tokenwise_cli-0.1.1 → tokenwise_cli-0.1.3}/tests/test_analyzer.py +82 -1
  16. {tokenwise_cli-0.1.1 → tokenwise_cli-0.1.3}/tests/test_dashboard.py +2 -2
  17. {tokenwise_cli-0.1.1 → tokenwise_cli-0.1.3}/tests/test_parser.py +124 -0
  18. {tokenwise_cli-0.1.1 → tokenwise_cli-0.1.3}/tests/test_pricing.py +86 -10
  19. {tokenwise_cli-0.1.1 → tokenwise_cli-0.1.3}/tests/test_security.py +25 -3
  20. {tokenwise_cli-0.1.1 → tokenwise_cli-0.1.3}/tests/test_storage.py +1 -0
  21. tokenwise_cli-0.1.1/.github/workflows/release.yml +0 -96
  22. tokenwise_cli-0.1.1/src/tokenwise/__init__.py +0 -1
  23. tokenwise_cli-0.1.1/src/tokenwise/analyzer.py +0 -216
  24. tokenwise_cli-0.1.1/src/tokenwise/parser.py +0 -166
  25. tokenwise_cli-0.1.1/src/tokenwise/pricing.py +0 -76
  26. {tokenwise_cli-0.1.1 → tokenwise_cli-0.1.3}/.github/workflows/codeql.yml +0 -0
  27. {tokenwise_cli-0.1.1 → tokenwise_cli-0.1.3}/.github/workflows/dependency-review.yml +0 -0
  28. {tokenwise_cli-0.1.1 → tokenwise_cli-0.1.3}/.github/workflows/scorecard.yml +0 -0
  29. {tokenwise_cli-0.1.1 → tokenwise_cli-0.1.3}/.gitignore +0 -0
  30. {tokenwise_cli-0.1.1 → tokenwise_cli-0.1.3}/CONTRIBUTING.md +0 -0
  31. {tokenwise_cli-0.1.1 → tokenwise_cli-0.1.3}/LICENSE +0 -0
  32. {tokenwise_cli-0.1.1 → tokenwise_cli-0.1.3}/Makefile +0 -0
  33. {tokenwise_cli-0.1.1 → tokenwise_cli-0.1.3}/SECURITY.md +0 -0
  34. {tokenwise_cli-0.1.1 → tokenwise_cli-0.1.3}/THREAT_MODEL.md +0 -0
  35. {tokenwise_cli-0.1.1 → tokenwise_cli-0.1.3}/tests/__init__.py +0 -0
  36. {tokenwise_cli-0.1.1 → tokenwise_cli-0.1.3}/tests/test_cli.py +0 -0
@@ -0,0 +1,11 @@
1
+ {
2
+ "permissions": {
3
+ "allow": [
4
+ "Bash(.venv313/bin/tokenwise --help)",
5
+ "Bash(awk '{print $6,$7,$8}')",
6
+ "Bash(.venv313/bin/tokenwise week *)",
7
+ "Bash(.venv313/bin/python -m pytest -q)",
8
+ "Skill(claude-api)"
9
+ ]
10
+ }
11
+ }
@@ -83,9 +83,9 @@ jobs:
83
83
  run: bandit -r src/ -c pyproject.toml
84
84
 
85
85
  - name: pip-audit (vulnerability scan)
86
- # CVE-2026-3219 affects pip itself with no available fix version.
87
- # It is not a dependency of tokenwise (runtime or dev).
88
- run: pip-audit --ignore-vuln CVE-2026-3219
86
+ # CVE-2026-3219 and CVE-2026-6357 affect pip itself; not a tokenwise dependency.
87
+ # --skip-editable excludes the local tokenwise-cli package (not on PyPI).
88
+ run: pip-audit --skip-editable --ignore-vuln CVE-2026-3219 --ignore-vuln CVE-2026-6357
89
89
 
90
90
  - name: Grep check — no network imports
91
91
  run: |
@@ -0,0 +1,114 @@
1
+ name: Release
2
+
3
+ # Triggered when a version tag is pushed, e.g.:
4
+ # 1. bump `version` in pyproject.toml and `__version__` in src/tokenwise/__init__.py
5
+ # 2. commit, then: git tag v0.1.3 && git push origin v0.1.3
6
+ # The tag must match the package version or the release stops before publishing.
7
+ on:
8
+ push:
9
+ tags:
10
+ - "v*.*.*"
11
+
12
+ permissions:
13
+ contents: read
14
+
15
+ jobs:
16
+ build:
17
+ name: Test and build distribution
18
+ runs-on: ubuntu-latest
19
+
20
+ steps:
21
+ - uses: actions/checkout@v4
22
+
23
+ - name: Set up Python 3.13
24
+ uses: actions/setup-python@v5
25
+ with:
26
+ python-version: "3.13"
27
+
28
+ - name: Check tag matches package version
29
+ run: |
30
+ tag="${GITHUB_REF_NAME#v}"
31
+ pkg=$(python -c "import tomllib; print(tomllib.load(open('pyproject.toml','rb'))['project']['version'])")
32
+ mod=$(python -c "import re; print(re.search(r'__version__ = \"(.+?)\"', open('src/tokenwise/__init__.py').read()).group(1))")
33
+ echo "tag=$tag pyproject=$pkg __version__=$mod"
34
+ if [ "$tag" != "$pkg" ] || [ "$tag" != "$mod" ]; then
35
+ echo "::error::Tag v$tag does not match pyproject.toml ($pkg) and __init__.py ($mod)"
36
+ exit 1
37
+ fi
38
+
39
+ - name: Install dependencies
40
+ run: pip install -e ".[dev]" build twine
41
+
42
+ - name: Run tests
43
+ run: pytest -q
44
+
45
+ - name: Build wheel and sdist
46
+ run: python -m build
47
+
48
+ - name: Check distribution metadata
49
+ run: twine check --strict dist/*
50
+
51
+ - name: Upload distribution artifacts
52
+ uses: actions/upload-artifact@v4
53
+ with:
54
+ name: dist
55
+ path: dist/
56
+
57
+ publish-pypi:
58
+ name: Publish to PyPI
59
+ needs: build
60
+ runs-on: ubuntu-latest
61
+ environment:
62
+ name: pypi
63
+ url: https://pypi.org/project/tokenwise-cli/${{ github.ref_name }}/
64
+
65
+ permissions:
66
+ id-token: write # OIDC Trusted Publishing — no API token stored anywhere
67
+
68
+ steps:
69
+ - name: Download distribution artifacts
70
+ uses: actions/download-artifact@v4
71
+ with:
72
+ name: dist
73
+ path: dist/
74
+
75
+ # One-time setup on PyPI (the project already exists, so add a publisher
76
+ # to it rather than a "pending" one):
77
+ # https://pypi.org/manage/project/tokenwise-cli/settings/publishing/
78
+ # - Owner: S0umith29
79
+ # - Repository name: tokenwise
80
+ # - Workflow name: release.yml
81
+ # - Environment name: pypi
82
+ - name: Publish to PyPI
83
+ uses: pypa/gh-action-pypi-publish@release/v1
84
+
85
+ github-release:
86
+ name: Sign and create GitHub Release
87
+ # Only after PyPI accepted the upload, so a failed publish leaves no release.
88
+ needs: publish-pypi
89
+ runs-on: ubuntu-latest
90
+
91
+ permissions:
92
+ contents: write # create the GitHub Release
93
+ id-token: write # Sigstore keyless signing
94
+
95
+ steps:
96
+ - name: Download distribution artifacts
97
+ uses: actions/download-artifact@v4
98
+ with:
99
+ name: dist
100
+ path: dist/
101
+
102
+ - name: Sign artifacts with Sigstore
103
+ uses: sigstore/gh-action-sigstore-python@v3
104
+ with:
105
+ inputs: dist/*.whl dist/*.tar.gz
106
+
107
+ - name: Create GitHub Release with signed artifacts
108
+ uses: softprops/action-gh-release@v2
109
+ with:
110
+ generate_release_notes: true
111
+ files: |
112
+ dist/*.whl
113
+ dist/*.tar.gz
114
+ dist/*.sigstore.json
@@ -1,9 +1,9 @@
1
- Metadata-Version: 2.4
1
+ Metadata-Version: 2.5
2
2
  Name: tokenwise-cli
3
- Version: 0.1.1
3
+ Version: 0.1.3
4
4
  Summary: Track and reduce your Claude/Anthropic API costs from the terminal
5
- Project-URL: Homepage, https://github.com/sowmithkuppa/tokenwise
6
- Project-URL: Bug Tracker, https://github.com/sowmithkuppa/tokenwise/issues
5
+ Project-URL: Homepage, https://github.com/S0umith29/tokenwise
6
+ Project-URL: Bug Tracker, https://github.com/S0umith29/tokenwise/issues
7
7
  License: MIT License
8
8
 
9
9
  Copyright (c) 2026 Sowmith Kuppa
@@ -50,9 +50,6 @@ Description-Content-Type: text/markdown
50
50
  [![Python](https://img.shields.io/pypi/pyversions/tokenwise-cli)](https://pypi.org/project/tokenwise-cli/)
51
51
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
52
52
 
53
- <!-- GIF placeholder -->
54
- ![tokenwise dashboard demo](https://via.placeholder.com/800x400.png?text=tokenwise+dashboard+demo+GIF+here)
55
-
56
53
  ---
57
54
 
58
55
  ## Security
@@ -169,9 +166,9 @@ tokenwise export --csv > usage.csv
169
166
 
170
167
  ## How it works
171
168
 
172
- Claude Code writes JSONL logs to `~/.claude/projects/<project-slug>/<session-id>.jsonl`. Each assistant message includes a `usage` object with `input_tokens`, `output_tokens`, `cache_creation_input_tokens`, and `cache_read_input_tokens`. `tokenwise` parses these, applies current Anthropic pricing, and aggregates the results.
169
+ Claude Code writes JSONL logs to `~/.claude/projects/<project-slug>/<session-id>.jsonl` (plus `<session-id>/subagents/*.jsonl` for subagent runs). Each assistant message includes a `usage` object with `input_tokens`, `output_tokens`, `cache_creation_input_tokens`, and `cache_read_input_tokens`. `tokenwise` parses these, applies current Anthropic pricing per message, and aggregates the results by project and by local calendar day.
173
170
 
174
- Parsed data is cached in `~/.tokenwise/cache.json` (permissions `0o600`) so repeated runs are instant.
171
+ Claude Code logs the same message several times (once per content block, and again when a session is resumed), so `tokenwise` counts each message ID only once.
175
172
 
176
173
  ---
177
174
 
@@ -9,9 +9,6 @@
9
9
  [![Python](https://img.shields.io/pypi/pyversions/tokenwise-cli)](https://pypi.org/project/tokenwise-cli/)
10
10
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
11
11
 
12
- <!-- GIF placeholder -->
13
- ![tokenwise dashboard demo](https://via.placeholder.com/800x400.png?text=tokenwise+dashboard+demo+GIF+here)
14
-
15
12
  ---
16
13
 
17
14
  ## Security
@@ -128,9 +125,9 @@ tokenwise export --csv > usage.csv
128
125
 
129
126
  ## How it works
130
127
 
131
- Claude Code writes JSONL logs to `~/.claude/projects/<project-slug>/<session-id>.jsonl`. Each assistant message includes a `usage` object with `input_tokens`, `output_tokens`, `cache_creation_input_tokens`, and `cache_read_input_tokens`. `tokenwise` parses these, applies current Anthropic pricing, and aggregates the results.
128
+ Claude Code writes JSONL logs to `~/.claude/projects/<project-slug>/<session-id>.jsonl` (plus `<session-id>/subagents/*.jsonl` for subagent runs). Each assistant message includes a `usage` object with `input_tokens`, `output_tokens`, `cache_creation_input_tokens`, and `cache_read_input_tokens`. `tokenwise` parses these, applies current Anthropic pricing per message, and aggregates the results by project and by local calendar day.
132
129
 
133
- Parsed data is cached in `~/.tokenwise/cache.json` (permissions `0o600`) so repeated runs are instant.
130
+ Claude Code logs the same message several times (once per content block, and again when a session is resumed), so `tokenwise` counts each message ID only once.
134
131
 
135
132
  ---
136
133
 
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "tokenwise-cli"
7
- version = "0.1.1"
7
+ version = "0.1.3"
8
8
  description = "Track and reduce your Claude/Anthropic API costs from the terminal"
9
9
  readme = "README.md"
10
10
  license = { file = "LICENSE" }
@@ -36,8 +36,8 @@ dev = [
36
36
  tokenwise = "tokenwise.cli:main"
37
37
 
38
38
  [project.urls]
39
- Homepage = "https://github.com/sowmithkuppa/tokenwise"
40
- "Bug Tracker" = "https://github.com/sowmithkuppa/tokenwise/issues"
39
+ Homepage = "https://github.com/S0umith29/tokenwise"
40
+ "Bug Tracker" = "https://github.com/S0umith29/tokenwise/issues"
41
41
 
42
42
  [tool.hatch.build.targets.wheel]
43
43
  packages = ["src/tokenwise"]
@@ -0,0 +1 @@
1
+ __version__ = "0.1.3"
@@ -0,0 +1,241 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass, field
4
+ from datetime import date, datetime
5
+
6
+ from .parser import Session
7
+ from .pricing import compute_cost
8
+
9
+
10
+ def local_date(ts: datetime) -> date:
11
+ """Calendar day of ``ts`` in the user's local timezone (matches date.today())."""
12
+ return ts.astimezone().date()
13
+
14
+
15
+ @dataclass
16
+ class DayUsage:
17
+ input_tokens: int = 0
18
+ output_tokens: int = 0
19
+ cache_write_tokens: int = 0
20
+ cache_read_tokens: int = 0
21
+ cost_usd: float = 0.0
22
+ turns: int = 0
23
+
24
+
25
+ @dataclass
26
+ class SessionStats:
27
+ session_id: str
28
+ project_slug: str
29
+ project_name: str
30
+ model: str
31
+ start_time: datetime | None
32
+ input_tokens: int
33
+ output_tokens: int
34
+ cache_write_tokens: int
35
+ cache_read_tokens: int
36
+ cost_usd: float
37
+ turns: int
38
+ # Usage split by the local calendar day each turn happened on. A session
39
+ # that runs past midnight counts toward both days.
40
+ daily: dict[date, DayUsage] = field(default_factory=dict)
41
+
42
+ @property
43
+ def total_tokens(self) -> int:
44
+ return (
45
+ self.input_tokens
46
+ + self.output_tokens
47
+ + self.cache_write_tokens
48
+ + self.cache_read_tokens
49
+ )
50
+
51
+ @property
52
+ def waste_ratio(self) -> float:
53
+ """High ratio = lots of context for little output (potentially wasteful)."""
54
+ context = self.input_tokens + self.cache_read_tokens
55
+ if context == 0:
56
+ return 0.0
57
+ return context / max(self.output_tokens, 1)
58
+
59
+
60
+ @dataclass
61
+ class ProjectStats:
62
+ project_name: str
63
+ project_slug: str
64
+ sessions: int = 0
65
+ input_tokens: int = 0
66
+ output_tokens: int = 0
67
+ cache_write_tokens: int = 0
68
+ cache_read_tokens: int = 0
69
+ cost_usd: float = 0.0
70
+
71
+ @property
72
+ def total_tokens(self) -> int:
73
+ return (
74
+ self.input_tokens
75
+ + self.output_tokens
76
+ + self.cache_write_tokens
77
+ + self.cache_read_tokens
78
+ )
79
+
80
+
81
+ @dataclass
82
+ class DailySummary:
83
+ date: date
84
+ sessions: int = 0
85
+ input_tokens: int = 0
86
+ output_tokens: int = 0
87
+ cache_write_tokens: int = 0
88
+ cache_read_tokens: int = 0
89
+ cost_usd: float = 0.0
90
+
91
+ @property
92
+ def total_tokens(self) -> int:
93
+ return (
94
+ self.input_tokens
95
+ + self.output_tokens
96
+ + self.cache_write_tokens
97
+ + self.cache_read_tokens
98
+ )
99
+
100
+
101
+ @dataclass
102
+ class AnalysisResult:
103
+ all_sessions: list[SessionStats]
104
+ by_project: dict[str, ProjectStats]
105
+ by_day: dict[date, DailySummary]
106
+ total_cost_usd: float
107
+ total_tokens: int
108
+
109
+
110
+ def _session_to_stats(session: Session) -> SessionStats:
111
+ daily: dict[date, DayUsage] = {}
112
+ for t in session.turns:
113
+ u = t.usage
114
+ d = daily.setdefault(local_date(t.timestamp), DayUsage())
115
+ d.input_tokens += u.input_tokens
116
+ d.output_tokens += u.output_tokens
117
+ d.cache_write_tokens += u.cache_creation_input_tokens
118
+ d.cache_read_tokens += u.cache_read_input_tokens
119
+ d.turns += 1
120
+ # Price each turn at its own model: sessions can switch models.
121
+ d.cost_usd += compute_cost(
122
+ t.model,
123
+ u.input_tokens,
124
+ u.output_tokens,
125
+ u.cache_creation_input_tokens,
126
+ u.cache_read_input_tokens,
127
+ cache_write_1h_tokens=u.cache_write_1h_tokens,
128
+ )
129
+
130
+ return SessionStats(
131
+ session_id=session.session_id,
132
+ project_slug=session.project_slug,
133
+ project_name=session.project_name,
134
+ model=session.primary_model,
135
+ start_time=session.start_time,
136
+ input_tokens=session.total_input,
137
+ output_tokens=session.total_output,
138
+ cache_write_tokens=session.total_cache_write,
139
+ cache_read_tokens=session.total_cache_read,
140
+ cost_usd=sum(d.cost_usd for d in daily.values()),
141
+ turns=len(session.turns),
142
+ daily=daily,
143
+ )
144
+
145
+
146
+ def _session_days(stats: SessionStats) -> dict[date, DayUsage]:
147
+ """Per-day usage, falling back to the start day for stats built without it."""
148
+ if stats.daily:
149
+ return stats.daily
150
+ if stats.start_time is None:
151
+ return {}
152
+ return {
153
+ local_date(stats.start_time): DayUsage(
154
+ input_tokens=stats.input_tokens,
155
+ output_tokens=stats.output_tokens,
156
+ cache_write_tokens=stats.cache_write_tokens,
157
+ cache_read_tokens=stats.cache_read_tokens,
158
+ cost_usd=stats.cost_usd,
159
+ turns=stats.turns,
160
+ )
161
+ }
162
+
163
+
164
+ def _aggregate(all_stats: list[SessionStats]) -> AnalysisResult:
165
+ by_project: dict[str, ProjectStats] = {}
166
+ by_day: dict[date, DailySummary] = {}
167
+
168
+ for stats in all_stats:
169
+ key = stats.project_slug
170
+ if key not in by_project:
171
+ by_project[key] = ProjectStats(
172
+ project_name=stats.project_name,
173
+ project_slug=stats.project_slug,
174
+ )
175
+ p = by_project[key]
176
+ p.sessions += 1
177
+ p.input_tokens += stats.input_tokens
178
+ p.output_tokens += stats.output_tokens
179
+ p.cache_write_tokens += stats.cache_write_tokens
180
+ p.cache_read_tokens += stats.cache_read_tokens
181
+ p.cost_usd += stats.cost_usd
182
+
183
+ for day, u in _session_days(stats).items():
184
+ if day not in by_day:
185
+ by_day[day] = DailySummary(date=day)
186
+ d = by_day[day]
187
+ d.sessions += 1
188
+ d.input_tokens += u.input_tokens
189
+ d.output_tokens += u.output_tokens
190
+ d.cache_write_tokens += u.cache_write_tokens
191
+ d.cache_read_tokens += u.cache_read_tokens
192
+ d.cost_usd += u.cost_usd
193
+
194
+ return AnalysisResult(
195
+ all_sessions=all_stats,
196
+ by_project=by_project,
197
+ by_day=by_day,
198
+ total_cost_usd=sum(s.cost_usd for s in all_stats),
199
+ total_tokens=sum(s.total_tokens for s in all_stats),
200
+ )
201
+
202
+
203
+ def analyze(sessions: list[Session]) -> AnalysisResult:
204
+ return _aggregate([_session_to_stats(s) for s in sessions])
205
+
206
+
207
+ def _clip_session(stats: SessionStats, start: date, end: date) -> SessionStats | None:
208
+ """Return ``stats`` restricted to the days in [start, end], or None if none."""
209
+ days = {d: u for d, u in _session_days(stats).items() if start <= d <= end}
210
+ if not days:
211
+ return None
212
+ if days == stats.daily:
213
+ return stats
214
+ return SessionStats(
215
+ session_id=stats.session_id,
216
+ project_slug=stats.project_slug,
217
+ project_name=stats.project_name,
218
+ model=stats.model,
219
+ start_time=stats.start_time,
220
+ input_tokens=sum(u.input_tokens for u in days.values()),
221
+ output_tokens=sum(u.output_tokens for u in days.values()),
222
+ cache_write_tokens=sum(u.cache_write_tokens for u in days.values()),
223
+ cache_read_tokens=sum(u.cache_read_tokens for u in days.values()),
224
+ cost_usd=sum(u.cost_usd for u in days.values()),
225
+ turns=sum(u.turns for u in days.values()),
226
+ daily=days,
227
+ )
228
+
229
+
230
+ def filter_by_date_range(
231
+ result: AnalysisResult,
232
+ start: date,
233
+ end: date,
234
+ ) -> AnalysisResult:
235
+ """Keep only usage that happened between ``start`` and ``end`` (local days, inclusive)."""
236
+ clipped = [_clip_session(s, start, end) for s in result.all_sessions]
237
+ return _aggregate([s for s in clipped if s is not None])
238
+
239
+
240
+ def top_wasteful_sessions(result: AnalysisResult, n: int = 10) -> list[SessionStats]:
241
+ return sorted(result.all_sessions, key=lambda s: s.waste_ratio, reverse=True)[:n]
@@ -6,8 +6,16 @@ from datetime import date, timedelta
6
6
 
7
7
  import click
8
8
  from rich.console import Console
9
-
10
- from .analyzer import AnalysisResult, analyze, filter_by_date_range, top_wasteful_sessions
9
+ from rich.markup import escape
10
+
11
+ from .analyzer import (
12
+ AnalysisResult,
13
+ SessionStats,
14
+ analyze,
15
+ filter_by_date_range,
16
+ local_date,
17
+ top_wasteful_sessions,
18
+ )
11
19
  from .dashboard import (
12
20
  build_daily_table,
13
21
  build_projects_table,
@@ -25,6 +33,11 @@ assert_no_network_imports()
25
33
  _err = Console(stderr=True)
26
34
 
27
35
 
36
+ def _by_start_desc(s: SessionStats) -> float:
37
+ # Sort key that never compares a datetime with a date (TypeError).
38
+ return s.start_time.timestamp() if s.start_time else float("-inf")
39
+
40
+
28
41
  def _load() -> AnalysisResult:
29
42
  if not CLAUDE_PROJECTS_DIR.exists():
30
43
  _err.print(
@@ -51,7 +64,7 @@ def today() -> None:
51
64
  today_date = date.today()
52
65
  filtered = filter_by_date_range(result, today_date, today_date)
53
66
 
54
- console.print(build_summary_panel(filtered, label="Today"))
67
+ console.print(build_summary_panel(result))
55
68
  console.print()
56
69
  console.print(build_projects_table(filtered))
57
70
 
@@ -63,7 +76,7 @@ def week() -> None:
63
76
  start = date.today() - timedelta(days=6)
64
77
  filtered = filter_by_date_range(result, start, date.today())
65
78
 
66
- console.print(build_summary_panel(filtered, label="Last 7 Days"))
79
+ console.print(build_summary_panel(result))
67
80
  console.print()
68
81
  console.print(build_daily_table(filtered, days=7))
69
82
  console.print()
@@ -83,20 +96,20 @@ def project(name: str) -> None:
83
96
  }
84
97
 
85
98
  if not matches:
86
- _err.print(f"[red]No project matching '{name}' found.[/red]")
87
- available = ", ".join(s.project_name for s in result.by_project.values())
99
+ _err.print(f"[red]No project matching '{escape(name)}' found.[/red]")
100
+ available = ", ".join(escape(s.project_name) for s in result.by_project.values())
88
101
  _err.print(f"Available: {available}")
89
102
  sys.exit(1)
90
103
 
91
104
  for slug, stats in matches.items():
92
105
  sessions = [s for s in result.all_sessions if s.project_slug == slug]
93
- sessions.sort(key=lambda s: s.start_time or date.min, reverse=True)
106
+ sessions.sort(key=_by_start_desc, reverse=True)
94
107
 
95
108
  from rich import box
96
109
  from rich.table import Table
97
110
 
98
111
  table = Table(
99
- title=f"[bold]{stats.project_name}[/bold] — {len(sessions)} sessions",
112
+ title=f"[bold]{escape(stats.project_name)}[/bold] — {len(sessions)} sessions",
100
113
  box=box.SIMPLE_HEAD,
101
114
  header_style="bold cyan",
102
115
  )
@@ -111,8 +124,8 @@ def project(name: str) -> None:
111
124
  from .dashboard import _fmt_cost, _fmt_tokens
112
125
 
113
126
  for s in sessions[:20]:
114
- date_str = s.start_time.strftime("%Y-%m-%d %H:%M") if s.start_time else "—"
115
- model_short = s.model.replace("claude-", "").replace("-20", " '")
127
+ date_str = s.start_time.astimezone().strftime("%Y-%m-%d %H:%M") if s.start_time else "—"
128
+ model_short = escape(s.model.replace("claude-", "").replace("-20", " '"))
116
129
  table.add_row(
117
130
  date_str,
118
131
  model_short,
@@ -150,11 +163,7 @@ def waste(top: int) -> None:
150
163
  def export(as_csv: bool) -> None:
151
164
  """Export raw session data."""
152
165
  result = _load()
153
- sessions = sorted(
154
- result.all_sessions,
155
- key=lambda s: s.start_time or date.min,
156
- reverse=True,
157
- )
166
+ sessions = sorted(result.all_sessions, key=_by_start_desc, reverse=True)
158
167
 
159
168
  if as_csv:
160
169
  writer = csv.writer(sys.stdout)
@@ -175,7 +184,7 @@ def export(as_csv: bool) -> None:
175
184
  for s in sessions:
176
185
  writer.writerow(
177
186
  [
178
- s.start_time.date() if s.start_time else "",
187
+ local_date(s.start_time) if s.start_time else "",
179
188
  s.project_name,
180
189
  s.session_id,
181
190
  s.model,
@@ -200,8 +209,8 @@ def export(as_csv: bool) -> None:
200
209
  table.add_column("Cost", justify="right")
201
210
  for s in sessions[:50]:
202
211
  table.add_row(
203
- str(s.start_time.date()) if s.start_time else "—",
204
- s.project_name,
212
+ str(local_date(s.start_time)) if s.start_time else "—",
213
+ escape(s.project_name),
205
214
  _fmt_tokens(s.total_tokens),
206
215
  _fmt_cost(s.cost_usd),
207
216
  )
@@ -6,6 +6,7 @@ from datetime import date, datetime, timedelta
6
6
 
7
7
  from rich import box
8
8
  from rich.console import Console
9
+ from rich.markup import escape
9
10
  from rich.panel import Panel
10
11
  from rich.table import Table
11
12
 
@@ -43,7 +44,8 @@ def _sparkline(values: list[float], width: int = 8) -> str:
43
44
  return "".join(bars[int(v / hi * 8)] for v in values[-width:])
44
45
 
45
46
 
46
- def build_summary_panel(result: AnalysisResult, label: str = "All Time") -> Panel:
47
+ def build_summary_panel(result: AnalysisResult) -> Panel:
48
+ """Today / This Week / All Time totals. Pass the *unfiltered* result."""
47
49
  today = date.today()
48
50
  today_result = filter_by_date_range(result, today, today)
49
51
  week_start = today - timedelta(days=6)
@@ -86,7 +88,7 @@ def build_projects_table(result: AnalysisResult, top_n: int = 10) -> Table:
86
88
 
87
89
  for p in projects:
88
90
  table.add_row(
89
- f"[bold]{p.project_name}[/bold]",
91
+ f"[bold]{escape(p.project_name)}[/bold]",
90
92
  str(p.sessions),
91
93
  _fmt_tokens(p.input_tokens),
92
94
  _fmt_tokens(p.output_tokens),
@@ -151,9 +153,9 @@ def build_waste_table(sessions: list[SessionStats], n: int = 10) -> Table:
151
153
  ratio = s.waste_ratio
152
154
  ratio_str = f"{ratio:.0f}x"
153
155
  color = _HOT_COLOR if ratio > 100 else _WARN_COLOR if ratio > 30 else "white"
154
- date_str = s.start_time.strftime("%b %d") if s.start_time else "—"
156
+ date_str = s.start_time.astimezone().strftime("%b %d") if s.start_time else "—"
155
157
  table.add_row(
156
- s.project_name,
158
+ escape(s.project_name),
157
159
  date_str,
158
160
  _fmt_tokens(s.input_tokens + s.cache_read_tokens),
159
161
  _fmt_tokens(s.output_tokens),