mirror of
https://github.com/kuhyx/testsAndMisc.git
synced 2026-11-24 20:56:17 +01:00
Compare commits
2 Commits
a87644666a
...
f7e8c59e8f
| Author | SHA1 | Date | |
|---|---|---|---|
| f7e8c59e8f | |||
| 52625a543c |
16
docs/superpowers/contracts/token-audit-2026-08-14.json
Normal file
16
docs/superpowers/contracts/token-audit-2026-08-14.json
Normal file
@ -0,0 +1,16 @@
|
||||
{
|
||||
"title": "token_audit: per-session token attribution and reporting",
|
||||
"objective": "Land the token_audit package so token spend in a Claude session can be traced to what caused it — a skill, a hook, an always-on rule file, or an image — turning 'the context is expensive' into a measurable, per-cause number that can be acted on.",
|
||||
"acceptance_criteria": [
|
||||
"python_pkg/token_audit/ ships parse, model, attribute, imagecost, report and a __main__ CLI entry point",
|
||||
"The full test suite passes: 81 tests, 0 failures",
|
||||
"Branch coverage is 100% across all seven modules (the repo gate is fail_under = 100)",
|
||||
"The repo pre-commit gate passes with no suppressions and no --no-verify"
|
||||
],
|
||||
"out_of_scope": [
|
||||
"poker-stakes/, its CI workflow, and its README row — a concurrent session's uncommitted work, deliberately not staged",
|
||||
"__pycache__ artifacts",
|
||||
"Any change to existing python_pkg packages"
|
||||
],
|
||||
"verifier": "python -m pytest python_pkg/token_audit/tests/ -q for correctness; python -m coverage run --branch --source=python_pkg/token_audit for the 100% branch-coverage bar; the repo pre-commit gate (ruff, mypy, pylint, bandit, coverage enforcement) as the final adjudicator."
|
||||
}
|
||||
39
docs/superpowers/evidence/token-audit-2026-08-14.json
Normal file
39
docs/superpowers/evidence/token-audit-2026-08-14.json
Normal file
@ -0,0 +1,39 @@
|
||||
{
|
||||
"intent": "Add the token_audit package so per-session Claude token spend can be parsed from transcripts, attributed to a cause (skill, hook, rule file, image), and reported.",
|
||||
"scope": [
|
||||
"python_pkg/token_audit/ — new package (parse, model, attribute, imagecost, report, __main__)",
|
||||
"python_pkg/token_audit/tests/ — 81 tests covering all seven modules",
|
||||
"Non-goal: no changes to existing python_pkg packages or the pre-commit config",
|
||||
"Non-goal: poker-stakes/ and its README row are another session's work, deliberately left uncommitted"
|
||||
],
|
||||
"changes": [
|
||||
"parse.py reads session transcript JSONL into typed records; model.py holds the dataclasses",
|
||||
"attribute.py assigns token cost to a cause; imagecost.py prices image blocks separately",
|
||||
"report.py renders the aggregate; __main__.py exposes the CLI entry point"
|
||||
],
|
||||
"verification": [
|
||||
{
|
||||
"command": "python -m pytest python_pkg/token_audit/tests/ -q",
|
||||
"result": "pass",
|
||||
"evidence": "81 passed in 0.06s"
|
||||
},
|
||||
{
|
||||
"command": "python -m coverage run --branch --source=python_pkg/token_audit -m pytest python_pkg/token_audit/tests/ -q && python -m coverage report",
|
||||
"result": "pass",
|
||||
"evidence": "TOTAL 394 stmts, 0 miss, 100 branch, 0 partial, 100% — all 7 modules at 100%"
|
||||
},
|
||||
{
|
||||
"command": "pre-commit run (full gate via finish_auto.sh)",
|
||||
"result": "pass",
|
||||
"evidence": "ruff, ruff format, mypy, pylint, bandit, codespell, coverage enforcement, requirements-sync and leaked-secrets checks all Passed"
|
||||
}
|
||||
],
|
||||
"risks": [
|
||||
"Transcript JSONL schema is external and may drift; parse.py would need updating if Claude changes its record format",
|
||||
"Image cost constants are point-in-time pricing and go stale when rates change"
|
||||
],
|
||||
"rollback": [
|
||||
"git revert the 'Add token_audit package' commit — the package is self-contained and nothing else imports it",
|
||||
"After rollback, re-run pytest on python_pkg to confirm the suite is still green"
|
||||
]
|
||||
}
|
||||
20
python_pkg/token_audit/__init__.py
Normal file
20
python_pkg/token_audit/__init__.py
Normal file
@ -0,0 +1,20 @@
|
||||
"""Measure what Claude Code sessions actually cost, from local transcripts.
|
||||
|
||||
Deterministic analysis with no model in the loop: the CLI parses
|
||||
``~/.claude/projects/*/*.jsonl`` and ranks spend by project, tool, MCP server,
|
||||
skill, subagent and session shape. Running the audit therefore costs nothing,
|
||||
which is the point — an LLM summarising its own token usage would be the
|
||||
expense it is trying to measure.
|
||||
|
||||
Usage::
|
||||
|
||||
python3 -m token_audit # rolling 7 days
|
||||
python3 -m token_audit --days 30
|
||||
python3 -m token_audit --json
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
__all__ = ["__version__"]
|
||||
|
||||
__version__ = "0.1.0"
|
||||
136
python_pkg/token_audit/__main__.py
Normal file
136
python_pkg/token_audit/__main__.py
Normal file
@ -0,0 +1,136 @@
|
||||
"""Command-line entry point for the token audit.
|
||||
|
||||
Fails closed. If the per-axis rollup does not reconcile with the raw usage
|
||||
figures the API reported, the run exits non-zero instead of printing a report
|
||||
that quietly lost or double-counted sessions — a plausible-looking wrong number
|
||||
is worse than no number, because it gets acted on.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import time
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from python_pkg.token_audit import attribute, imagecost, parse, report
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from python_pkg.token_audit.model import Session
|
||||
|
||||
TRANSCRIPT_ROOT = Path.home() / ".claude" / "projects"
|
||||
DEFAULT_DAYS = 7
|
||||
SECONDS_PER_DAY = 86400
|
||||
# Largest acceptable relative gap between the axis rollup and the raw usage
|
||||
# totals. The two are computed independently, so anything above rounding noise
|
||||
# means a session was mis-attributed.
|
||||
MAX_DRIFT = 0.01
|
||||
EXIT_DRIFT = 2
|
||||
EXIT_NO_DATA = 3
|
||||
|
||||
|
||||
def _build_parser() -> argparse.ArgumentParser:
|
||||
"""Define the CLI surface."""
|
||||
parser = argparse.ArgumentParser(
|
||||
prog="token_audit",
|
||||
description="Rank Claude Code token spend from local transcripts.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--days",
|
||||
type=float,
|
||||
default=DEFAULT_DAYS,
|
||||
help=f"rolling window size in days (default {DEFAULT_DAYS})",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--since",
|
||||
type=float,
|
||||
default=None,
|
||||
help="window start as a unix timestamp (overrides --days)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--until",
|
||||
type=float,
|
||||
default=None,
|
||||
help="window end as a unix timestamp (default: now)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--root",
|
||||
type=Path,
|
||||
default=TRANSCRIPT_ROOT,
|
||||
help="transcript directory to scan",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--out",
|
||||
type=Path,
|
||||
default=report.REPORT_DIR,
|
||||
help="directory to write the report into",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--json",
|
||||
action="store_true",
|
||||
help="print the machine-readable snapshot instead of the table",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--no-write",
|
||||
action="store_true",
|
||||
help="analyse without writing report files",
|
||||
)
|
||||
return parser
|
||||
|
||||
|
||||
def _collect(root: Path, since: float, until: float) -> list[Session]:
|
||||
"""Load and annotate every transcript inside the window."""
|
||||
sessions: list[Session] = []
|
||||
for path in parse.find_transcripts(root, since, until):
|
||||
session = parse.load_session(path)
|
||||
if not session.turns:
|
||||
continue
|
||||
# Re-walk the file for image cost: it needs the interleaved event order
|
||||
# that load_session flattens into separate lists.
|
||||
imagecost.annotate(session, parse.iter_events(path))
|
||||
sessions.append(session)
|
||||
return sessions
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
"""Run the audit and return a process exit code."""
|
||||
args = _build_parser().parse_args(argv)
|
||||
started = time.monotonic()
|
||||
until = args.until if args.until is not None else time.time()
|
||||
since = (
|
||||
args.since if args.since is not None else until - args.days * SECONDS_PER_DAY
|
||||
)
|
||||
|
||||
sessions = _collect(args.root, since, until)
|
||||
if not sessions:
|
||||
sys.stderr.write(f"No transcripts with usage data under {args.root}\n")
|
||||
return EXIT_NO_DATA
|
||||
|
||||
totals, axes = attribute.build(sessions)
|
||||
drift = attribute.reconcile(totals, sessions)
|
||||
window = report.Window(since=since, until=until)
|
||||
snap = report.snapshot(totals, axes, window, len(sessions))
|
||||
previous = report.load_previous(args.out)
|
||||
markdown = report.render(totals, axes, window, sessions, snap, previous)
|
||||
|
||||
if not args.no_write:
|
||||
written = report.write(markdown, snap, args.out)
|
||||
sys.stderr.write(f"Wrote {written}\n")
|
||||
|
||||
sys.stdout.write(json.dumps(snap, indent=2) if args.json else markdown)
|
||||
elapsed = time.monotonic() - started
|
||||
sys.stderr.write(f"Analysed {len(sessions)} sessions in {elapsed:.2f}s\n")
|
||||
|
||||
if drift > MAX_DRIFT:
|
||||
sys.stderr.write(
|
||||
f"RECONCILIATION FAILED: axis rollup differs from raw usage by "
|
||||
f"{drift * 100:.2f}% (limit {MAX_DRIFT * 100:.0f}%)\n",
|
||||
)
|
||||
return EXIT_DRIFT
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
146
python_pkg/token_audit/attribute.py
Normal file
146
python_pkg/token_audit/attribute.py
Normal file
@ -0,0 +1,146 @@
|
||||
"""Roll sessions up along the axes the report ranks.
|
||||
|
||||
Each axis answers a different "should I change something?" question, so they
|
||||
are kept separate rather than merged into one table:
|
||||
|
||||
* **project** (cwd) — which work was expensive, not which tool was.
|
||||
* **tool** — where result payloads come from; ranked by estimated result size.
|
||||
* **mcp** — invocation counts per server, the only way to tell a registered
|
||||
server apart from a *used* one.
|
||||
* **skill** — how often each skill was actually invoked.
|
||||
* **sidechain** — what subagents cost, which is easy to assume is large and in
|
||||
practice may be zero.
|
||||
* **cold start** — the fixed prefix every new session pays before doing work.
|
||||
|
||||
Only :func:`totals` feeds the reconciliation gate; everything else is ranking.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections import Counter
|
||||
from dataclasses import dataclass, field
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from python_pkg.token_audit.model import TOKEN_KINDS, Session
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Iterable
|
||||
|
||||
# A session past this many assistant turns is "long". Chosen from measurement:
|
||||
# in the observed window, sessions above it were ~90% of all weighted spend,
|
||||
# because per-turn cost scales with accumulated context.
|
||||
LONG_SESSION_TURNS = 400
|
||||
|
||||
|
||||
@dataclass
|
||||
class Totals:
|
||||
"""Raw token counts summed straight from the API's usage blocks."""
|
||||
|
||||
by_kind: Counter[str] = field(default_factory=Counter)
|
||||
weighted: float = 0.0
|
||||
turns: int = 0
|
||||
|
||||
def add(self, session: Session) -> None:
|
||||
"""Accumulate one session's usage."""
|
||||
for turn in session.turns:
|
||||
for kind in TOKEN_KINDS:
|
||||
self.by_kind[kind] += turn.usage.get(kind, 0)
|
||||
self.weighted += turn.cost
|
||||
self.turns += 1
|
||||
|
||||
|
||||
@dataclass
|
||||
class Tally:
|
||||
"""A running "how much, over how many" pair.
|
||||
|
||||
Every headline driver is reported the same way — a cost or token total plus
|
||||
the number of things that produced it — so they share one type instead of
|
||||
two loose fields each.
|
||||
"""
|
||||
|
||||
total: float = 0.0
|
||||
count: int = 0
|
||||
|
||||
def add(self, amount: float) -> None:
|
||||
"""Record one more contribution."""
|
||||
self.total += amount
|
||||
self.count += 1
|
||||
|
||||
|
||||
@dataclass
|
||||
class Axes:
|
||||
"""Every ranking the report needs, in one pass over the sessions."""
|
||||
|
||||
project: Counter[str] = field(default_factory=Counter)
|
||||
tool_tokens: Counter[str] = field(default_factory=Counter)
|
||||
tool_calls: Counter[str] = field(default_factory=Counter)
|
||||
mcp_calls: Counter[str] = field(default_factory=Counter)
|
||||
skills: Counter[str] = field(default_factory=Counter)
|
||||
models: Counter[str] = field(default_factory=Counter)
|
||||
sidechain: Tally = field(default_factory=Tally)
|
||||
cold_start: Tally = field(default_factory=Tally)
|
||||
images: Tally = field(default_factory=Tally)
|
||||
long_sessions: Tally = field(default_factory=Tally)
|
||||
# Cost-weighted, compaction-aware image re-send estimate. Tracked apart from
|
||||
# ``images`` (which counts tokens read once) because the two answer
|
||||
# different questions and only this one is comparable to session cost.
|
||||
image_cost: float = 0.0
|
||||
|
||||
|
||||
def build(sessions: Iterable[Session]) -> tuple[Totals, Axes]:
|
||||
"""Compute reconciled totals and every ranking axis together."""
|
||||
totals = Totals()
|
||||
axes = Axes()
|
||||
for session in sessions:
|
||||
totals.add(session)
|
||||
_add_turns(axes, session)
|
||||
_add_tools(axes, session)
|
||||
_add_session_shape(axes, session)
|
||||
return totals, axes
|
||||
|
||||
|
||||
def _add_turns(axes: Axes, session: Session) -> None:
|
||||
"""Attribute per-turn cost to project, model and sidechain."""
|
||||
axes.project[session.cwd or "unknown"] += int(session.cost)
|
||||
for turn in session.turns:
|
||||
axes.models[turn.model] += turn.usage.get("output_tokens", 0)
|
||||
if turn.is_sidechain:
|
||||
axes.sidechain.add(turn.cost)
|
||||
|
||||
|
||||
def _add_tools(axes: Axes, session: Session) -> None:
|
||||
"""Attribute tool-result payloads to tools, MCP servers and skills."""
|
||||
for call in session.tools:
|
||||
axes.tool_tokens[call.name] += call.result_tokens
|
||||
axes.tool_calls[call.name] += 1
|
||||
server = call.mcp_server
|
||||
if server is not None:
|
||||
axes.mcp_calls[server] += 1
|
||||
if call.skill is not None:
|
||||
axes.skills[call.skill] += 1
|
||||
if call.is_image:
|
||||
axes.images.add(call.result_tokens)
|
||||
|
||||
|
||||
def _add_session_shape(axes: Axes, session: Session) -> None:
|
||||
"""Attribute whole-session properties: cold start, length, image cost."""
|
||||
cold = session.cold_start_tokens
|
||||
if cold:
|
||||
axes.cold_start.add(cold)
|
||||
axes.image_cost += session.image_cost
|
||||
if session.turn_count > LONG_SESSION_TURNS:
|
||||
axes.long_sessions.add(session.cost)
|
||||
|
||||
|
||||
def reconcile(totals: Totals, sessions: Iterable[Session]) -> float:
|
||||
"""Return the relative drift between axis sums and the raw usage totals.
|
||||
|
||||
The report is only worth acting on if its parts add up to its whole, so the
|
||||
CLI turns this into a hard gate rather than a warning. Comparing the
|
||||
per-project rollup against the independently summed usage blocks catches
|
||||
any session that was counted twice or dropped.
|
||||
"""
|
||||
summed = sum(session.cost for session in sessions)
|
||||
if totals.weighted == 0:
|
||||
return 0.0
|
||||
return abs(summed - totals.weighted) / totals.weighted
|
||||
83
python_pkg/token_audit/imagecost.py
Normal file
83
python_pkg/token_audit/imagecost.py
Normal file
@ -0,0 +1,83 @@
|
||||
"""Estimate what images cost *after* the turn that loaded them.
|
||||
|
||||
An image does not leave the context once read. Every subsequent request in the
|
||||
session re-sends it as cache-read, so a screenshot loaded at turn 20 of a
|
||||
1000-turn session is paid for ~980 more times. At the cache-read weight of 0.1
|
||||
that turns ~2.5k tokens into ~250k, which is why images are worth tracking as
|
||||
their own axis rather than lumping them in with text tool results.
|
||||
|
||||
Measured over a real 7-day window this amplification was ~1.6% of weighted
|
||||
spend — real, but an order of magnitude below session length. An earlier
|
||||
version of this module reported ~27%, because it sized images by their base64
|
||||
payload length; see :func:`parse._result_tokens` for why that is ~20x too high.
|
||||
The lesson is kept here deliberately: an estimate that is never checked against
|
||||
billed tokens can invent a headline finding out of nothing.
|
||||
|
||||
Two honest limits on the number this produces:
|
||||
|
||||
* It is an **estimate**, derived from result sizes rather than billed tokens.
|
||||
It is deliberately never folded into the reconciled totals, which come only
|
||||
from the API's own usage figures.
|
||||
* Compaction discards history. An image loaded before a compaction stops being
|
||||
re-sent, so charging it forever would roughly double the figure and yields
|
||||
the impossible result of sessions costing more than they measurably did.
|
||||
Compaction is detected from a sharp drop in context size.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from python_pkg.token_audit.model import (
|
||||
COMPACTION_DROP_RATIO,
|
||||
WEIGHTS,
|
||||
Session,
|
||||
ToolCall,
|
||||
Turn,
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Iterable
|
||||
|
||||
# Images are re-sent from cache, so each later turn charges them at cache-read.
|
||||
_REREAD_WEIGHT = WEIGHTS["cache_read_input_tokens"]
|
||||
|
||||
|
||||
def _is_compaction(context: int, previous: int | None) -> bool:
|
||||
"""Whether this turn's context implies history was just discarded.
|
||||
|
||||
Context grows monotonically as a session accumulates messages, so the only
|
||||
way it falls sharply is compaction (or a fresh branch). A ratio test rather
|
||||
than an absolute threshold keeps this valid for both small and huge
|
||||
sessions.
|
||||
"""
|
||||
return previous is not None and context < previous * COMPACTION_DROP_RATIO
|
||||
|
||||
|
||||
def image_cost(events: Iterable[tuple[str, object]]) -> float:
|
||||
"""Return cost-weighted tokens spent re-sending images across turns.
|
||||
|
||||
``events`` must preserve transcript order — the whole calculation is about
|
||||
how many turns followed each image before compaction cleared it.
|
||||
"""
|
||||
live: list[int] = []
|
||||
previous: int | None = None
|
||||
total = 0.0
|
||||
for kind, event in events:
|
||||
if kind == "tool":
|
||||
if isinstance(event, ToolCall) and event.is_image:
|
||||
live.append(event.result_tokens)
|
||||
elif isinstance(event, Turn):
|
||||
if _is_compaction(event.context, previous):
|
||||
live.clear()
|
||||
# Charge every still-live image once for this turn: it was part of
|
||||
# the context this request re-sent.
|
||||
total += sum(live) * _REREAD_WEIGHT
|
||||
previous = event.context
|
||||
return total
|
||||
|
||||
|
||||
def annotate(session: Session, events: Iterable[tuple[str, object]]) -> Session:
|
||||
"""Attach the image amplification estimate to a session."""
|
||||
session.image_cost = image_cost(events)
|
||||
return session
|
||||
146
python_pkg/token_audit/model.py
Normal file
146
python_pkg/token_audit/model.py
Normal file
@ -0,0 +1,146 @@
|
||||
"""Types and cost weights shared by every stage of the audit.
|
||||
|
||||
The whole package exists to answer one question — *what did last week actually
|
||||
cost?* — and the answer depends entirely on how the four token classes are
|
||||
weighted. Ranking by raw token count is actively misleading here: in a measured
|
||||
7-day window cache reads were 99% of raw volume but only ~82% of weighted cost,
|
||||
while output was 1.5% of volume and ~7.5% of cost. A report that ranked by raw
|
||||
counts would point at the wrong culprits, so the weights live here as the single
|
||||
source of truth rather than being re-derived per module.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
# Relative price of each token class, normalised so plain input == 1.0. These
|
||||
# mirror Anthropic's published multipliers (cache write 1.25x, cache read 0.1x,
|
||||
# output 5x); they are ratios, not currency, so the report stays valid whatever
|
||||
# the absolute per-token price happens to be.
|
||||
WEIGHTS: dict[str, float] = {
|
||||
"input_tokens": 1.0,
|
||||
"cache_creation_input_tokens": 1.25,
|
||||
"cache_read_input_tokens": 0.1,
|
||||
"output_tokens": 5.0,
|
||||
}
|
||||
|
||||
# Token classes in the order they should appear in reports.
|
||||
TOKEN_KINDS: tuple[str, ...] = (
|
||||
"input_tokens",
|
||||
"cache_creation_input_tokens",
|
||||
"cache_read_input_tokens",
|
||||
"output_tokens",
|
||||
)
|
||||
|
||||
# A turn whose context is below this fraction of the previous turn's is treated
|
||||
# as sitting after a compaction boundary. Compaction discards earlier messages,
|
||||
# so images loaded before it stop being re-sent and must stop being charged.
|
||||
# Without this the image estimate roughly doubles and produces the nonsense
|
||||
# result of single sessions costing >100% of their own measured spend.
|
||||
COMPACTION_DROP_RATIO = 0.7
|
||||
|
||||
# Extensions whose Read results arrive as images rather than text.
|
||||
IMAGE_SUFFIXES: frozenset[str] = frozenset(
|
||||
{".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp"},
|
||||
)
|
||||
|
||||
|
||||
def weighted(usage: dict[str, int]) -> float:
|
||||
"""Return the cost-weighted token total for one request's usage block."""
|
||||
return sum(WEIGHTS[kind] * usage.get(kind, 0) for kind in TOKEN_KINDS)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Turn:
|
||||
"""One assistant response, with the token accounting the API reported.
|
||||
|
||||
``context`` is what the request actually re-sent (cache read + cache
|
||||
creation). It is the quantity that grows as a session accumulates history,
|
||||
and the quantity that collapses at a compaction boundary, so it drives both
|
||||
the session-length analysis and the image-amplification model.
|
||||
"""
|
||||
|
||||
usage: dict[str, int]
|
||||
context: int
|
||||
model: str
|
||||
is_sidechain: bool
|
||||
|
||||
@property
|
||||
def cost(self) -> float:
|
||||
"""Cost-weighted tokens attributable to this turn."""
|
||||
return weighted(self.usage)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ToolCall:
|
||||
"""A tool invocation paired with the size of the result it returned.
|
||||
|
||||
``result_tokens`` is an estimate: transcripts store the rendered result, so
|
||||
the character count divided by four is the best available proxy. It is used
|
||||
only for ranking tools against each other, never added to the reconciled
|
||||
totals, which come exclusively from the API's own usage numbers.
|
||||
"""
|
||||
|
||||
name: str
|
||||
result_tokens: int
|
||||
path: str | None = None
|
||||
skill: str | None = None
|
||||
|
||||
@property
|
||||
def is_image(self) -> bool:
|
||||
"""Whether this call returned an image rather than text."""
|
||||
if self.path is None:
|
||||
return False
|
||||
dot = self.path.rfind(".")
|
||||
return dot != -1 and self.path[dot:].lower() in IMAGE_SUFFIXES
|
||||
|
||||
@property
|
||||
def mcp_server(self) -> str | None:
|
||||
"""The MCP server this tool belongs to, or ``None`` for builtins."""
|
||||
parts = self.name.split("__")
|
||||
expected_parts = 3
|
||||
return parts[1] if len(parts) >= expected_parts and parts[0] == "mcp" else None
|
||||
|
||||
|
||||
@dataclass
|
||||
class Session:
|
||||
"""Everything one transcript file contributes to the audit."""
|
||||
|
||||
session_id: str
|
||||
path: str
|
||||
cwd: str | None = None
|
||||
turns: list[Turn] = field(default_factory=list)
|
||||
tools: list[ToolCall] = field(default_factory=list)
|
||||
# Cost-weighted tokens spent re-sending images that were still live in
|
||||
# context. Computed by :mod:`imagecost`, which needs the interleaved order
|
||||
# of images and turns and so cannot be derived from these lists alone.
|
||||
image_cost: float = 0.0
|
||||
|
||||
@property
|
||||
def cost(self) -> float:
|
||||
"""Cost-weighted tokens for the whole session."""
|
||||
return sum(turn.cost for turn in self.turns)
|
||||
|
||||
@property
|
||||
def turn_count(self) -> int:
|
||||
"""Number of assistant responses in the session."""
|
||||
return len(self.turns)
|
||||
|
||||
@property
|
||||
def max_context(self) -> int:
|
||||
"""Largest context this session ever re-sent in a single request."""
|
||||
return max((turn.context for turn in self.turns), default=0)
|
||||
|
||||
@property
|
||||
def cold_start_tokens(self) -> int:
|
||||
"""Tokens written to cache before any cache existed to read from.
|
||||
|
||||
The first request of a session pays to cache the whole fixed prefix —
|
||||
system prompt, tool schemas, CLAUDE.md, rules and memories. Isolating it
|
||||
shows what every new session costs before it does any work.
|
||||
"""
|
||||
return sum(
|
||||
turn.usage.get("cache_creation_input_tokens", 0)
|
||||
for turn in self.turns
|
||||
if turn.usage.get("cache_read_input_tokens", 0) == 0
|
||||
)
|
||||
223
python_pkg/token_audit/parse.py
Normal file
223
python_pkg/token_audit/parse.py
Normal file
@ -0,0 +1,223 @@
|
||||
"""Read Claude Code transcripts into :class:`Session` objects.
|
||||
|
||||
Transcripts are JSONL under ``~/.claude/projects/<slug>/<session-id>.jsonl``,
|
||||
one JSON object per line, appended live. Three properties of that format drive
|
||||
the design here:
|
||||
|
||||
1. **Lines can be malformed.** A transcript being written while it is read can
|
||||
end in a partial line, and older sessions contain records this package does
|
||||
not model. Every line is therefore parsed defensively and skipped on error;
|
||||
losing one line is always better than aborting a weekly report.
|
||||
2. **A tool call and its result are in different messages.** ``tool_use`` blocks
|
||||
carry the name and input, ``tool_result`` blocks carry the payload and only a
|
||||
``tool_use_id`` back-reference. Attributing result size to the right tool
|
||||
requires holding an id map for the length of the file.
|
||||
3. **Order matters.** The image-cost model needs to know how many turns followed
|
||||
each image, so :func:`iter_events` preserves the interleaving rather than
|
||||
returning separate lists.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
from python_pkg.token_audit.model import IMAGE_SUFFIXES, Session, ToolCall, Turn
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Iterator
|
||||
from pathlib import Path
|
||||
|
||||
# Divisor turning rendered characters into an approximate token count. Four is
|
||||
# the usual English-text rule of thumb and is only ever used for ranking tools,
|
||||
# never for the reconciled totals.
|
||||
CHARS_PER_TOKEN = 4
|
||||
|
||||
# Median billed size of one screenshot, measured from real transcripts by
|
||||
# isolating turns whose only new content was a single image (n=484, median
|
||||
# 2,566, p90 2,692). Anthropic bills images by pixel area, so a constant is a
|
||||
# far better estimate than the base64 payload length, which is ~20x too high.
|
||||
# Halving a screenshot's dimensions cuts this roughly fourfold.
|
||||
IMAGE_TOKENS = 2566
|
||||
|
||||
|
||||
def _load_line(line: str) -> dict[str, Any] | None:
|
||||
"""Parse one JSONL line, returning ``None`` if it is not a usable record."""
|
||||
try:
|
||||
record = json.loads(line)
|
||||
except (ValueError, UnicodeDecodeError):
|
||||
return None
|
||||
return record if isinstance(record, dict) else None
|
||||
|
||||
|
||||
def _blocks(record: dict[str, Any]) -> list[dict[str, Any]]:
|
||||
"""Return the content blocks of a record's message, if it has any."""
|
||||
message = record.get("message")
|
||||
if not isinstance(message, dict):
|
||||
return []
|
||||
content = message.get("content")
|
||||
if not isinstance(content, list):
|
||||
return []
|
||||
return [block for block in content if isinstance(block, dict)]
|
||||
|
||||
|
||||
def _usage(record: dict[str, Any]) -> tuple[dict[str, Any], dict[str, int]] | None:
|
||||
"""Return an assistant record's message and its integer usage fields.
|
||||
|
||||
The message is returned alongside the usage block so callers that need both
|
||||
(the model id lives on the message) never have to re-validate its type.
|
||||
"""
|
||||
message = record.get("message")
|
||||
if not isinstance(message, dict):
|
||||
return None
|
||||
usage = message.get("usage")
|
||||
if not isinstance(usage, dict):
|
||||
return None
|
||||
return message, {k: v for k, v in usage.items() if isinstance(v, int)}
|
||||
|
||||
|
||||
def _model(message: dict[str, Any]) -> str:
|
||||
"""Return the model id that served a record, or a placeholder.
|
||||
|
||||
Only ever called after :func:`_usage` has confirmed the message is a dict,
|
||||
so it takes the message itself rather than re-checking the record.
|
||||
"""
|
||||
model = message.get("model")
|
||||
return model if isinstance(model, str) else "unknown"
|
||||
|
||||
|
||||
def _result_tokens(block: dict[str, Any], *, is_image: bool = False) -> int:
|
||||
"""Estimate how many tokens a tool result occupied in context.
|
||||
|
||||
Text is charged by length, but an **image is not**. An image arrives as a
|
||||
base64 blob whose character count has nothing to do with its billed size —
|
||||
Anthropic charges by pixel area. Measuring images by payload length
|
||||
overstates them by roughly 20x (a 240KB PNG looks like ~82k tokens against
|
||||
a real cost near 2.5k), which is enough to make screenshots look like the
|
||||
dominant cost driver when they are not. Validated against real transcripts
|
||||
by isolating turns whose only new content was one image: the context grew
|
||||
~1.6-3k tokens, never the tens of thousands the payload length implied.
|
||||
"""
|
||||
content = block.get("content")
|
||||
if content is None:
|
||||
return 0
|
||||
if is_image:
|
||||
return IMAGE_TOKENS
|
||||
return len(json.dumps(content)) // CHARS_PER_TOKEN
|
||||
|
||||
|
||||
def iter_events(path: Path) -> Iterator[tuple[str, object]]:
|
||||
"""Yield ``("turn", Turn)`` and ``("tool", ToolCall)`` in transcript order.
|
||||
|
||||
Emitting a single ordered stream — rather than two lists — is what lets
|
||||
:mod:`imagecost` count how many turns each image survived for.
|
||||
"""
|
||||
pending: dict[str, dict[str, Any]] = {}
|
||||
with path.open(encoding="utf-8", errors="replace") as handle:
|
||||
for line in handle:
|
||||
record = _load_line(line)
|
||||
if record is None:
|
||||
continue
|
||||
for block in _blocks(record):
|
||||
kind = block.get("type")
|
||||
if kind == "tool_use":
|
||||
call_id = block.get("id")
|
||||
if isinstance(call_id, str):
|
||||
pending[call_id] = block
|
||||
elif kind == "tool_result":
|
||||
call = _pair_result(block, pending)
|
||||
if call is not None:
|
||||
yield "tool", call
|
||||
found = _usage(record)
|
||||
if found is not None:
|
||||
message, usage = found
|
||||
yield "turn", _build_turn(record, message, usage)
|
||||
|
||||
|
||||
def _pair_result(
|
||||
block: dict[str, Any],
|
||||
pending: dict[str, dict[str, Any]],
|
||||
) -> ToolCall | None:
|
||||
"""Join a ``tool_result`` back to the ``tool_use`` that produced it."""
|
||||
use = pending.pop(block.get("tool_use_id", ""), None)
|
||||
if use is None:
|
||||
return None
|
||||
tool_input = use.get("input")
|
||||
tool_input = tool_input if isinstance(tool_input, dict) else {}
|
||||
path = tool_input.get("file_path")
|
||||
skill = tool_input.get("skill")
|
||||
call_path = path if isinstance(path, str) else None
|
||||
return ToolCall(
|
||||
name=str(use.get("name") or "unknown"),
|
||||
result_tokens=_result_tokens(block, is_image=_looks_like_image(call_path)),
|
||||
path=call_path,
|
||||
skill=skill if isinstance(skill, str) else None,
|
||||
)
|
||||
|
||||
|
||||
def _looks_like_image(path: str | None) -> bool:
|
||||
"""Whether a tool-result path refers to an image, by extension."""
|
||||
if path is None:
|
||||
return False
|
||||
dot = path.rfind(".")
|
||||
return dot != -1 and path[dot:].lower() in IMAGE_SUFFIXES
|
||||
|
||||
|
||||
def _build_turn(
|
||||
record: dict[str, Any],
|
||||
message: dict[str, Any],
|
||||
usage: dict[str, int],
|
||||
) -> Turn:
|
||||
"""Build a :class:`Turn` from an assistant record's usage block."""
|
||||
context = usage.get("cache_read_input_tokens", 0) + usage.get(
|
||||
"cache_creation_input_tokens",
|
||||
0,
|
||||
)
|
||||
return Turn(
|
||||
usage=usage,
|
||||
context=context,
|
||||
model=_model(message),
|
||||
is_sidechain=bool(record.get("isSidechain")),
|
||||
)
|
||||
|
||||
|
||||
def _first_cwd(path: Path) -> str | None:
|
||||
"""Return the working directory a transcript was recorded in."""
|
||||
with path.open(encoding="utf-8", errors="replace") as handle:
|
||||
for line in handle:
|
||||
record = _load_line(line)
|
||||
if record is not None:
|
||||
cwd = record.get("cwd")
|
||||
if isinstance(cwd, str):
|
||||
return cwd
|
||||
return None
|
||||
|
||||
|
||||
def load_session(path: Path) -> Session:
|
||||
"""Read one transcript file into a :class:`Session`."""
|
||||
session = Session(session_id=path.stem, path=str(path), cwd=_first_cwd(path))
|
||||
for kind, event in iter_events(path):
|
||||
if kind == "turn" and isinstance(event, Turn):
|
||||
session.turns.append(event)
|
||||
elif isinstance(event, ToolCall):
|
||||
session.tools.append(event)
|
||||
return session
|
||||
|
||||
|
||||
def find_transcripts(
|
||||
root: Path,
|
||||
since: float,
|
||||
until: float | None = None,
|
||||
) -> list[Path]:
|
||||
"""Return transcripts modified inside the window, newest first.
|
||||
|
||||
Modification time is the selector because it is the only per-file timestamp
|
||||
available without opening the file, and a session's mtime is when it was
|
||||
last active — exactly the notion of "used this week" the report wants.
|
||||
"""
|
||||
found: list[tuple[float, Path]] = []
|
||||
for path in sorted(root.glob("*/*.jsonl")):
|
||||
mtime = path.stat().st_mtime
|
||||
if mtime >= since and (until is None or mtime <= until):
|
||||
found.append((mtime, path))
|
||||
return [path for _, path in sorted(found, reverse=True)]
|
||||
224
python_pkg/token_audit/report.py
Normal file
224
python_pkg/token_audit/report.py
Normal file
@ -0,0 +1,224 @@
|
||||
"""Render the audit as markdown plus a machine-readable snapshot.
|
||||
|
||||
Two outputs, two consumers. ``WEEKLY.md`` is for reading; ``weekly.json`` is
|
||||
for the next run, which diffs against it to produce a week-over-week delta —
|
||||
the part that makes running this repeatedly worth anything, since a single
|
||||
week's absolute numbers cannot tell you whether a change helped.
|
||||
|
||||
Both land outside the repo, in ``~/.claude/token-report/``. The report names
|
||||
paths and tools but never contains prompt or file *content*, so it stays safe
|
||||
to keep on disk; it is still never committed, because the code repo is public
|
||||
and the working-directory list alone maps out private projects.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from datetime import UTC, datetime
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from python_pkg.token_audit.attribute import LONG_SESSION_TURNS, Axes, Totals
|
||||
from python_pkg.token_audit.model import TOKEN_KINDS
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Sequence
|
||||
|
||||
from python_pkg.token_audit.model import Session
|
||||
|
||||
REPORT_DIR = Path.home() / ".claude" / "token-report"
|
||||
MARKDOWN_NAME = "WEEKLY.md"
|
||||
JSON_NAME = "weekly.json"
|
||||
TOP_N = 12
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Window:
|
||||
"""The time span a report covers."""
|
||||
|
||||
since: float
|
||||
until: float
|
||||
|
||||
def describe(self) -> str:
|
||||
"""Human-readable window bounds."""
|
||||
fmt = "%Y-%m-%d %H:%M"
|
||||
start = datetime.fromtimestamp(self.since, tz=UTC).strftime(fmt)
|
||||
end = datetime.fromtimestamp(self.until, tz=UTC).strftime(fmt)
|
||||
return f"{start} - {end} UTC"
|
||||
|
||||
|
||||
def snapshot(totals: Totals, axes: Axes, window: Window, sessions: int) -> dict:
|
||||
"""Build the JSON structure persisted for next week's delta."""
|
||||
return {
|
||||
"generated": datetime.now(tz=UTC).isoformat(),
|
||||
"window": {"since": window.since, "until": window.until},
|
||||
"sessions": sessions,
|
||||
"turns": totals.turns,
|
||||
"weighted_total": round(totals.weighted),
|
||||
"raw": dict(totals.by_kind),
|
||||
"image_cost": round(axes.image_cost),
|
||||
"image_reads": axes.images.count,
|
||||
"cold_start_tokens": int(axes.cold_start.total),
|
||||
"cold_starts": axes.cold_start.count,
|
||||
"long_sessions": axes.long_sessions.count,
|
||||
"long_session_cost": round(axes.long_sessions.total),
|
||||
"sidechain_cost": round(axes.sidechain.total),
|
||||
"projects": dict(axes.project.most_common(TOP_N)),
|
||||
"mcp_calls": dict(axes.mcp_calls),
|
||||
"skills": dict(axes.skills),
|
||||
}
|
||||
|
||||
|
||||
def _pct(part: float, whole: float) -> str:
|
||||
"""Format ``part`` as a percentage of ``whole``, guarding divide-by-zero."""
|
||||
return f"{part / whole * 100:.1f}%" if whole else "n/a"
|
||||
|
||||
|
||||
def _delta_line(current: dict, previous: dict | None) -> str:
|
||||
"""Describe the change in weighted spend since the previous snapshot."""
|
||||
if previous is None:
|
||||
return "_No previous report on disk - next run will show a delta._"
|
||||
before = previous.get("weighted_total", 0)
|
||||
now = current["weighted_total"]
|
||||
if not before:
|
||||
return "_Previous report had no spend recorded._"
|
||||
change = (now - before) / before * 100
|
||||
arrow = "up" if change >= 0 else "down"
|
||||
return f"**Week over week: {arrow} {abs(change):.1f}%** ({before:,} -> {now:,})"
|
||||
|
||||
|
||||
def _table(rows: Sequence[tuple[str, str]], headers: tuple[str, str]) -> list[str]:
|
||||
"""Render a two-column markdown table."""
|
||||
out = [f"| {headers[0]} | {headers[1]} |", "|---|---|"]
|
||||
out += [f"| {left} | {right} |" for left, right in rows]
|
||||
return out
|
||||
|
||||
|
||||
def render(
|
||||
totals: Totals,
|
||||
axes: Axes,
|
||||
window: Window,
|
||||
sessions: Sequence[Session],
|
||||
current: dict,
|
||||
previous: dict | None,
|
||||
) -> str:
|
||||
"""Render the full markdown report."""
|
||||
total = totals.weighted
|
||||
lines = [
|
||||
"# Claude Code token audit",
|
||||
"",
|
||||
f"Window: {window.describe()}",
|
||||
f"Sessions: {len(sessions)} | assistant turns: {totals.turns:,}",
|
||||
"",
|
||||
_delta_line(current, previous),
|
||||
"",
|
||||
"## Totals",
|
||||
"",
|
||||
f"**Cost-weighted total: {total:,.0f}**",
|
||||
"",
|
||||
]
|
||||
lines += _table(
|
||||
[(kind, f"{totals.by_kind.get(kind, 0):,}") for kind in TOKEN_KINDS],
|
||||
("raw token class", "count"),
|
||||
)
|
||||
lines += ["", "## Ranked drivers", ""]
|
||||
lines += _table(_driver_rows(axes, total), ("driver", "share of weighted cost"))
|
||||
lines += ["", "## Projects", ""]
|
||||
lines += _table(
|
||||
[
|
||||
(path, f"{_pct(cost, total)} ({cost:,})")
|
||||
for path, cost in axes.project.most_common(TOP_N)
|
||||
],
|
||||
("working directory", "weighted cost"),
|
||||
)
|
||||
lines += ["", "## Tool result payloads (estimated tokens returned)", ""]
|
||||
lines += _table(
|
||||
[
|
||||
(name, f"{tok:,} over {axes.tool_calls[name]:,} calls")
|
||||
for name, tok in axes.tool_tokens.most_common(TOP_N)
|
||||
],
|
||||
("tool", "result tokens"),
|
||||
)
|
||||
lines += ["", "## MCP servers invoked", ""]
|
||||
lines += _table(
|
||||
[(name, f"{n:,}") for name, n in axes.mcp_calls.most_common()]
|
||||
or [("(none invoked)", "0")],
|
||||
("server", "calls"),
|
||||
)
|
||||
lines += ["", "## Skills invoked", ""]
|
||||
lines += _table(
|
||||
[(name, f"{n:,}") for name, n in axes.skills.most_common()]
|
||||
or [("(none invoked)", "0")],
|
||||
("skill", "invocations"),
|
||||
)
|
||||
lines += ["", "## Most expensive sessions", ""]
|
||||
lines += _table(_session_rows(sessions, total), ("session", "weighted cost"))
|
||||
lines += ["", _footer(axes)]
|
||||
return "\n".join(lines) + "\n"
|
||||
|
||||
|
||||
def _driver_rows(axes: Axes, total: float) -> list[tuple[str, str]]:
|
||||
"""Rows for the headline driver table."""
|
||||
long_cost = axes.long_sessions.total
|
||||
return [
|
||||
(
|
||||
f"Images re-sent in context ({axes.images.count:,} reads)",
|
||||
f"{_pct(axes.image_cost, total)} ({axes.image_cost:,.0f})",
|
||||
),
|
||||
(
|
||||
f"Sessions over {LONG_SESSION_TURNS} turns ({axes.long_sessions.count})",
|
||||
f"{_pct(long_cost, total)} ({long_cost:,.0f})",
|
||||
),
|
||||
(
|
||||
f"Cold-start prefix ({axes.cold_start.count} starts)",
|
||||
f"{axes.cold_start.total:,.0f} raw tokens cached",
|
||||
),
|
||||
(
|
||||
f"Subagent sidechains ({axes.sidechain.count} turns)",
|
||||
f"{_pct(axes.sidechain.total, total)} ({axes.sidechain.total:,.0f})",
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
def _session_rows(sessions: Sequence[Session], total: float) -> list[tuple[str, str]]:
|
||||
"""Rows for the per-session table, most expensive first."""
|
||||
ranked = sorted(sessions, key=lambda s: s.cost, reverse=True)[:TOP_N]
|
||||
return [
|
||||
(
|
||||
f"`{s.session_id[:8]}` ({s.turn_count:,} turns, max ctx {s.max_context:,})",
|
||||
f"{_pct(s.cost, total)} ({s.cost:,.0f})",
|
||||
)
|
||||
for s in ranked
|
||||
]
|
||||
|
||||
|
||||
def _footer(axes: Axes) -> str:
|
||||
"""Closing note on how the image figure should be read."""
|
||||
return (
|
||||
f"_Image cost is an estimate: {axes.images.total:,.0f} tokens were read once, "
|
||||
"then re-sent as cache-read on every later turn until compaction. "
|
||||
"It is excluded from the reconciled totals above, which come only from "
|
||||
"the API's reported usage._"
|
||||
)
|
||||
|
||||
|
||||
def write(markdown: str, data: dict, directory: Path = REPORT_DIR) -> Path:
|
||||
"""Persist both outputs, returning the markdown path."""
|
||||
directory.mkdir(parents=True, exist_ok=True)
|
||||
md_path = directory / MARKDOWN_NAME
|
||||
md_path.write_text(markdown, encoding="utf-8")
|
||||
(directory / JSON_NAME).write_text(json.dumps(data, indent=2), encoding="utf-8")
|
||||
return md_path
|
||||
|
||||
|
||||
def load_previous(directory: Path = REPORT_DIR) -> dict | None:
|
||||
"""Load the last snapshot, or ``None`` if this is the first run."""
|
||||
path = directory / JSON_NAME
|
||||
if not path.exists():
|
||||
return None
|
||||
try:
|
||||
loaded = json.loads(path.read_text(encoding="utf-8"))
|
||||
except ValueError:
|
||||
return None
|
||||
return loaded if isinstance(loaded, dict) else None
|
||||
1
python_pkg/token_audit/tests/__init__.py
Normal file
1
python_pkg/token_audit/tests/__init__.py
Normal file
@ -0,0 +1 @@
|
||||
"""Tests for the token-audit package."""
|
||||
176
python_pkg/token_audit/tests/test_attribute.py
Normal file
176
python_pkg/token_audit/tests/test_attribute.py
Normal file
@ -0,0 +1,176 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from python_pkg.token_audit import attribute
|
||||
from python_pkg.token_audit.imagecost import image_cost
|
||||
from python_pkg.token_audit.model import Session, ToolCall, Turn
|
||||
|
||||
|
||||
def _turn(
|
||||
context: int = 0,
|
||||
out: int = 0,
|
||||
read: int = 0,
|
||||
create: int = 0,
|
||||
*,
|
||||
sidechain: bool = False,
|
||||
model: str = "claude-opus-5",
|
||||
) -> Turn:
|
||||
return Turn(
|
||||
usage={
|
||||
"output_tokens": out,
|
||||
"cache_read_input_tokens": read,
|
||||
"cache_creation_input_tokens": create,
|
||||
},
|
||||
context=context,
|
||||
model=model,
|
||||
is_sidechain=sidechain,
|
||||
)
|
||||
|
||||
|
||||
def _session(
|
||||
cwd: str | None = "/home/kuhy/p",
|
||||
turns: list[Turn] | None = None,
|
||||
tools: list[ToolCall] | None = None,
|
||||
image_cost_value: float = 0.0,
|
||||
) -> Session:
|
||||
session = Session(session_id="s", path="p", cwd=cwd)
|
||||
session.turns = turns or []
|
||||
session.tools = tools or []
|
||||
session.image_cost = image_cost_value
|
||||
return session
|
||||
|
||||
|
||||
def test_totals_sum_each_token_kind() -> None:
|
||||
session = _session(turns=[_turn(out=2, read=100), _turn(out=1, read=50)])
|
||||
totals, _ = attribute.build([session])
|
||||
assert totals.by_kind["output_tokens"] == 3
|
||||
assert totals.by_kind["cache_read_input_tokens"] == 150
|
||||
assert totals.turns == 2
|
||||
|
||||
|
||||
def test_unknown_cwd_is_labelled() -> None:
|
||||
_, axes = attribute.build([_session(cwd=None, turns=[_turn(out=1)])])
|
||||
assert "unknown" in axes.project
|
||||
|
||||
|
||||
def test_sidechain_cost_isolated() -> None:
|
||||
session = _session(turns=[_turn(out=1, sidechain=True), _turn(out=1)])
|
||||
_, axes = attribute.build([session])
|
||||
assert axes.sidechain.count == 1
|
||||
assert axes.sidechain.total == pytest.approx(5.0)
|
||||
|
||||
|
||||
def test_tool_mcp_and_skill_axes() -> None:
|
||||
tools = [
|
||||
ToolCall(name="Read", result_tokens=10, path="/a.png"),
|
||||
ToolCall(name="Read", result_tokens=5, path="/a.py"),
|
||||
ToolCall(name="mcp__aseprite__draw_line", result_tokens=1),
|
||||
ToolCall(name="Skill", result_tokens=1, skill="finish"),
|
||||
]
|
||||
_, axes = attribute.build([_session(tools=tools)])
|
||||
assert axes.tool_tokens["Read"] == 15
|
||||
assert axes.tool_calls["Read"] == 2
|
||||
assert axes.mcp_calls["aseprite"] == 1
|
||||
assert axes.skills["finish"] == 1
|
||||
assert axes.images.count == 1
|
||||
assert axes.images.total == 10
|
||||
|
||||
|
||||
def test_long_session_threshold() -> None:
|
||||
short = _session(turns=[_turn(out=1)])
|
||||
long_turns = [_turn(out=1) for _ in range(attribute.LONG_SESSION_TURNS + 1)]
|
||||
long = _session(turns=long_turns)
|
||||
_, axes = attribute.build([short, long])
|
||||
assert axes.long_sessions.count == 1
|
||||
assert axes.long_sessions.total == pytest.approx(len(long_turns) * 5.0)
|
||||
|
||||
|
||||
def test_cold_start_only_counted_when_nonzero() -> None:
|
||||
cold = _session(turns=[_turn(create=1000)])
|
||||
warm = _session(turns=[_turn(read=10, create=5)])
|
||||
_, axes = attribute.build([cold, warm])
|
||||
assert axes.cold_start.count == 1
|
||||
assert axes.cold_start.total == 1000
|
||||
|
||||
|
||||
def test_image_cost_is_accumulated_from_sessions() -> None:
|
||||
_, axes = attribute.build([_session(image_cost_value=7.5)])
|
||||
assert axes.image_cost == pytest.approx(7.5)
|
||||
|
||||
|
||||
def test_models_axis_tracks_output() -> None:
|
||||
session = _session(turns=[_turn(out=4, model="claude-sonnet-5")])
|
||||
_, axes = attribute.build([session])
|
||||
assert axes.models["claude-sonnet-5"] == 4
|
||||
|
||||
|
||||
def test_reconcile_zero_when_consistent() -> None:
|
||||
session = _session(turns=[_turn(out=1)])
|
||||
totals, _ = attribute.build([session])
|
||||
assert attribute.reconcile(totals, [session]) == pytest.approx(0.0)
|
||||
|
||||
|
||||
def test_reconcile_detects_drift() -> None:
|
||||
session = _session(turns=[_turn(out=1)])
|
||||
totals, _ = attribute.build([session])
|
||||
totals.weighted *= 2
|
||||
assert attribute.reconcile(totals, [session]) == pytest.approx(0.5)
|
||||
|
||||
|
||||
def test_reconcile_guards_zero_total() -> None:
|
||||
totals = attribute.Totals()
|
||||
assert attribute.reconcile(totals, []) == 0.0
|
||||
|
||||
|
||||
# --- imagecost ---------------------------------------------------------------
|
||||
|
||||
|
||||
def _ev_turn(context: int) -> tuple[str, Turn]:
|
||||
return ("turn", _turn(context=context))
|
||||
|
||||
|
||||
def _ev_image(tokens: int) -> tuple[str, ToolCall]:
|
||||
return ("tool", ToolCall(name="Read", result_tokens=tokens, path="/s.png"))
|
||||
|
||||
|
||||
def test_image_charged_once_per_following_turn() -> None:
|
||||
events = [_ev_image(1000), _ev_turn(10), _ev_turn(20), _ev_turn(30)]
|
||||
assert image_cost(events) == pytest.approx(300.0)
|
||||
|
||||
|
||||
def test_image_not_charged_for_earlier_turns() -> None:
|
||||
events = [_ev_turn(10), _ev_image(1000), _ev_turn(20)]
|
||||
assert image_cost(events) == pytest.approx(100.0)
|
||||
|
||||
|
||||
def test_compaction_clears_live_images() -> None:
|
||||
# context collapses from 100 to 20 (below the 0.7 ratio) => history dropped
|
||||
events = [_ev_image(1000), _ev_turn(100), _ev_turn(20), _ev_turn(30)]
|
||||
assert image_cost(events) == pytest.approx(100.0)
|
||||
|
||||
|
||||
def test_growth_below_ratio_does_not_trigger_compaction() -> None:
|
||||
events = [_ev_image(1000), _ev_turn(100), _ev_turn(90)]
|
||||
assert image_cost(events) == pytest.approx(200.0)
|
||||
|
||||
|
||||
def test_non_image_tools_are_free() -> None:
|
||||
events = [
|
||||
("tool", ToolCall(name="Bash", result_tokens=9999, path=None)),
|
||||
("tool", ToolCall(name="Read", result_tokens=9999, path="/a.py")),
|
||||
_ev_turn(10),
|
||||
]
|
||||
assert image_cost(events) == 0.0
|
||||
|
||||
|
||||
def test_unknown_event_payloads_are_ignored() -> None:
|
||||
assert image_cost([("tool", "not a toolcall"), ("turn", "not a turn")]) == 0.0
|
||||
|
||||
|
||||
def test_annotate_sets_session_image_cost() -> None:
|
||||
from python_pkg.token_audit import imagecost
|
||||
|
||||
session = _session()
|
||||
imagecost.annotate(session, [_ev_image(100), _ev_turn(5)])
|
||||
assert session.image_cost == pytest.approx(10.0)
|
||||
192
python_pkg/token_audit/tests/test_cli.py
Normal file
192
python_pkg/token_audit/tests/test_cli.py
Normal file
@ -0,0 +1,192 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import pytest
|
||||
|
||||
from python_pkg.token_audit import __main__ as cli
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def _transcript(
|
||||
root: Path,
|
||||
name: str = "s1",
|
||||
turns: int = 2,
|
||||
*,
|
||||
image: bool = False,
|
||||
) -> Path:
|
||||
project = root / "proj"
|
||||
project.mkdir(exist_ok=True)
|
||||
records = []
|
||||
if image:
|
||||
records += [
|
||||
{
|
||||
"cwd": "/home/kuhy/demo",
|
||||
"message": {
|
||||
"content": [
|
||||
{
|
||||
"type": "tool_use",
|
||||
"id": "i1",
|
||||
"name": "Read",
|
||||
"input": {"file_path": "/shot.png"},
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
"message": {
|
||||
"content": [
|
||||
{
|
||||
"type": "tool_result",
|
||||
"tool_use_id": "i1",
|
||||
"content": "x" * 400,
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
]
|
||||
for index in range(turns):
|
||||
records.append(
|
||||
{
|
||||
"cwd": "/home/kuhy/demo",
|
||||
"message": {
|
||||
"model": "claude-opus-5",
|
||||
"usage": {
|
||||
"output_tokens": 10,
|
||||
"cache_read_input_tokens": 100 * index,
|
||||
"cache_creation_input_tokens": 50,
|
||||
},
|
||||
},
|
||||
},
|
||||
)
|
||||
path = project / f"{name}.jsonl"
|
||||
path.write_text("\n".join(json.dumps(r) for r in records), encoding="utf-8")
|
||||
return path
|
||||
|
||||
|
||||
def test_no_data_exits_three(
|
||||
tmp_path: Path, capsys: pytest.CaptureFixture[str]
|
||||
) -> None:
|
||||
code = cli.main(["--root", str(tmp_path), "--no-write"])
|
||||
assert code == cli.EXIT_NO_DATA
|
||||
assert "No transcripts" in capsys.readouterr().err
|
||||
|
||||
|
||||
def test_transcript_without_usage_is_skipped(tmp_path: Path) -> None:
|
||||
project = tmp_path / "proj"
|
||||
project.mkdir()
|
||||
(project / "empty.jsonl").write_text(
|
||||
'{"message": {"content": []}}', encoding="utf-8"
|
||||
)
|
||||
assert cli.main(["--root", str(tmp_path), "--no-write"]) == cli.EXIT_NO_DATA
|
||||
|
||||
|
||||
def test_successful_run_writes_report(
|
||||
tmp_path: Path, capsys: pytest.CaptureFixture[str]
|
||||
) -> None:
|
||||
_transcript(tmp_path, image=True)
|
||||
out_dir = tmp_path / "out"
|
||||
code = cli.main(["--root", str(tmp_path), "--out", str(out_dir), "--days", "36500"])
|
||||
assert code == 0
|
||||
captured = capsys.readouterr()
|
||||
assert "# Claude Code token audit" in captured.out
|
||||
assert (out_dir / "WEEKLY.md").exists()
|
||||
assert (out_dir / "weekly.json").exists()
|
||||
assert "Analysed 1 sessions" in captured.err
|
||||
|
||||
|
||||
def test_no_write_leaves_no_files(tmp_path: Path) -> None:
|
||||
_transcript(tmp_path)
|
||||
out_dir = tmp_path / "out"
|
||||
cli.main(
|
||||
[
|
||||
"--root",
|
||||
str(tmp_path),
|
||||
"--out",
|
||||
str(out_dir),
|
||||
"--days",
|
||||
"36500",
|
||||
"--no-write",
|
||||
]
|
||||
)
|
||||
assert not out_dir.exists()
|
||||
|
||||
|
||||
def test_json_flag_emits_parsable_snapshot(
|
||||
tmp_path: Path, capsys: pytest.CaptureFixture[str]
|
||||
) -> None:
|
||||
_transcript(tmp_path)
|
||||
cli.main(
|
||||
["--root", str(tmp_path), "--days", "36500", "--no-write", "--json"],
|
||||
)
|
||||
payload = json.loads(capsys.readouterr().out)
|
||||
assert payload["sessions"] == 1
|
||||
assert payload["weighted_total"] > 0
|
||||
|
||||
|
||||
def test_explicit_since_and_until_window(tmp_path: Path) -> None:
|
||||
_transcript(tmp_path)
|
||||
code = cli.main(
|
||||
[
|
||||
"--root",
|
||||
str(tmp_path),
|
||||
"--since",
|
||||
"0",
|
||||
"--until",
|
||||
"99999999999",
|
||||
"--no-write",
|
||||
],
|
||||
)
|
||||
assert code == 0
|
||||
|
||||
|
||||
def test_until_before_files_yields_no_data(tmp_path: Path) -> None:
|
||||
_transcript(tmp_path)
|
||||
code = cli.main(
|
||||
["--root", str(tmp_path), "--since", "0", "--until", "1", "--no-write"]
|
||||
)
|
||||
assert code == cli.EXIT_NO_DATA
|
||||
|
||||
|
||||
def test_drift_fails_closed(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
|
||||
) -> None:
|
||||
_transcript(tmp_path)
|
||||
monkeypatch.setattr(cli.attribute, "reconcile", lambda *_: 0.5)
|
||||
code = cli.main(["--root", str(tmp_path), "--days", "36500", "--no-write"])
|
||||
assert code == cli.EXIT_DRIFT
|
||||
assert "RECONCILIATION FAILED" in capsys.readouterr().err
|
||||
|
||||
|
||||
def test_second_run_reports_delta(
|
||||
tmp_path: Path, capsys: pytest.CaptureFixture[str]
|
||||
) -> None:
|
||||
_transcript(tmp_path)
|
||||
out_dir = tmp_path / "out"
|
||||
args = ["--root", str(tmp_path), "--out", str(out_dir), "--days", "36500"]
|
||||
cli.main(args)
|
||||
capsys.readouterr()
|
||||
cli.main(args)
|
||||
assert "Week over week" in capsys.readouterr().out
|
||||
|
||||
|
||||
def test_parser_defaults() -> None:
|
||||
args = cli._build_parser().parse_args([])
|
||||
assert args.days == cli.DEFAULT_DAYS
|
||||
assert args.since is None
|
||||
assert args.json is False
|
||||
|
||||
|
||||
def test_module_entrypoint_is_wired() -> None:
|
||||
assert callable(cli.main)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("flag", ["--help"])
|
||||
def test_help_exits_zero(flag: str) -> None:
|
||||
with pytest.raises(SystemExit) as excinfo:
|
||||
cli.main([flag])
|
||||
assert excinfo.value.code == 0
|
||||
94
python_pkg/token_audit/tests/test_model.py
Normal file
94
python_pkg/token_audit/tests/test_model.py
Normal file
@ -0,0 +1,94 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from python_pkg.token_audit.model import (
|
||||
COMPACTION_DROP_RATIO,
|
||||
WEIGHTS,
|
||||
Session,
|
||||
ToolCall,
|
||||
Turn,
|
||||
weighted,
|
||||
)
|
||||
|
||||
|
||||
def test_weights_price_output_highest() -> None:
|
||||
assert WEIGHTS["output_tokens"] > WEIGHTS["input_tokens"]
|
||||
assert WEIGHTS["cache_read_input_tokens"] < WEIGHTS["input_tokens"]
|
||||
assert 0 < COMPACTION_DROP_RATIO < 1
|
||||
|
||||
|
||||
def test_weighted_applies_each_multiplier() -> None:
|
||||
usage = {
|
||||
"input_tokens": 10,
|
||||
"cache_creation_input_tokens": 100,
|
||||
"cache_read_input_tokens": 1000,
|
||||
"output_tokens": 1,
|
||||
}
|
||||
assert weighted(usage) == pytest.approx(10 + 125 + 100 + 5)
|
||||
|
||||
|
||||
def test_weighted_treats_missing_kinds_as_zero() -> None:
|
||||
assert weighted({}) == 0.0
|
||||
|
||||
|
||||
def test_turn_cost_delegates_to_weighted() -> None:
|
||||
turn = Turn(usage={"output_tokens": 2}, context=0, model="m", is_sidechain=False)
|
||||
assert turn.cost == pytest.approx(10.0)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("path", ["/a/b.png", "/a/b.PNG", "/a/b.jpeg"])
|
||||
def test_tool_call_detects_images(path: str) -> None:
|
||||
assert ToolCall(name="Read", result_tokens=1, path=path).is_image
|
||||
|
||||
|
||||
@pytest.mark.parametrize("path", ["/a/b.py", "/a/noextension", None])
|
||||
def test_tool_call_rejects_non_images(path: str | None) -> None:
|
||||
assert not ToolCall(name="Read", result_tokens=1, path=path).is_image
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("name", "expected"),
|
||||
[
|
||||
("mcp__aseprite__draw_line", "aseprite"),
|
||||
("mcp__i3wm__get_tree", "i3wm"),
|
||||
("Read", None),
|
||||
("mcp__broken", None),
|
||||
],
|
||||
)
|
||||
def test_tool_call_mcp_server(name: str, expected: str | None) -> None:
|
||||
assert ToolCall(name=name, result_tokens=0).mcp_server == expected
|
||||
|
||||
|
||||
def _turn(context: int, out: int = 0, read: int = 0, create: int = 0) -> Turn:
|
||||
return Turn(
|
||||
usage={
|
||||
"output_tokens": out,
|
||||
"cache_read_input_tokens": read,
|
||||
"cache_creation_input_tokens": create,
|
||||
},
|
||||
context=context,
|
||||
model="m",
|
||||
is_sidechain=False,
|
||||
)
|
||||
|
||||
|
||||
def test_session_aggregates() -> None:
|
||||
session = Session(session_id="s", path="p")
|
||||
session.turns = [_turn(100, out=1), _turn(500, out=2)]
|
||||
assert session.turn_count == 2
|
||||
assert session.max_context == 500
|
||||
assert session.cost == pytest.approx(15.0)
|
||||
|
||||
|
||||
def test_session_empty_has_zero_max_context() -> None:
|
||||
assert Session(session_id="s", path="p").max_context == 0
|
||||
|
||||
|
||||
def test_cold_start_counts_only_turns_with_no_cache_read() -> None:
|
||||
session = Session(session_id="s", path="p")
|
||||
session.turns = [
|
||||
_turn(0, create=5000), # cold: nothing to read yet
|
||||
_turn(9, read=9, create=100), # warm: excluded
|
||||
]
|
||||
assert session.cold_start_tokens == 5000
|
||||
271
python_pkg/token_audit/tests/test_parse.py
Normal file
271
python_pkg/token_audit/tests/test_parse.py
Normal file
@ -0,0 +1,271 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import pytest
|
||||
|
||||
from python_pkg.token_audit import parse
|
||||
from python_pkg.token_audit.model import ToolCall, Turn
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def _assistant(
|
||||
usage: dict[str, int] | None = None,
|
||||
content: list[dict[str, object]] | None = None,
|
||||
cwd: str = "/home/kuhy/demo",
|
||||
*,
|
||||
sidechain: bool = False,
|
||||
) -> dict[str, object]:
|
||||
message: dict[str, object] = {"model": "claude-opus-5"}
|
||||
if usage is not None:
|
||||
message["usage"] = usage
|
||||
if content is not None:
|
||||
message["content"] = content
|
||||
return {
|
||||
"type": "assistant",
|
||||
"cwd": cwd,
|
||||
"isSidechain": sidechain,
|
||||
"message": message,
|
||||
}
|
||||
|
||||
|
||||
def _write(tmp_path: Path, records: list[object], name: str = "sess.jsonl") -> Path:
|
||||
path = tmp_path / name
|
||||
path.write_text(
|
||||
"\n".join(json.dumps(r) if isinstance(r, dict) else r for r in records),
|
||||
encoding="utf-8",
|
||||
)
|
||||
return path
|
||||
|
||||
|
||||
def test_load_session_reads_usage_and_cwd(tmp_path: Path) -> None:
|
||||
path = _write(tmp_path, [_assistant(usage={"output_tokens": 3})])
|
||||
session = parse.load_session(path)
|
||||
assert session.cwd == "/home/kuhy/demo"
|
||||
assert session.turn_count == 1
|
||||
assert session.turns[0].model == "claude-opus-5"
|
||||
|
||||
|
||||
def test_context_is_cache_read_plus_creation(tmp_path: Path) -> None:
|
||||
usage = {"cache_read_input_tokens": 40, "cache_creation_input_tokens": 2}
|
||||
path = _write(tmp_path, [_assistant(usage=usage)])
|
||||
assert parse.load_session(path).turns[0].context == 42
|
||||
|
||||
|
||||
def test_malformed_lines_are_skipped_not_fatal(tmp_path: Path) -> None:
|
||||
path = _write(
|
||||
tmp_path,
|
||||
[
|
||||
"{not json",
|
||||
"[1,2,3]",
|
||||
"null",
|
||||
json.dumps(_assistant(usage={"output_tokens": 1})),
|
||||
],
|
||||
)
|
||||
assert parse.load_session(path).turn_count == 1
|
||||
|
||||
|
||||
def test_tool_result_is_joined_to_its_tool_use(tmp_path: Path) -> None:
|
||||
records = [
|
||||
_assistant(
|
||||
content=[
|
||||
{
|
||||
"type": "tool_use",
|
||||
"id": "t1",
|
||||
"name": "Read",
|
||||
"input": {"file_path": "/x/shot.png"},
|
||||
},
|
||||
],
|
||||
),
|
||||
{
|
||||
"message": {
|
||||
"content": [
|
||||
{"type": "tool_result", "tool_use_id": "t1", "content": "abcdefgh"}
|
||||
]
|
||||
}
|
||||
},
|
||||
]
|
||||
session = parse.load_session(_write(tmp_path, records))
|
||||
assert len(session.tools) == 1
|
||||
call = session.tools[0]
|
||||
assert call.name == "Read"
|
||||
assert call.path == "/x/shot.png"
|
||||
assert call.is_image
|
||||
|
||||
|
||||
def test_orphan_tool_result_is_ignored(tmp_path: Path) -> None:
|
||||
records = [
|
||||
{"message": {"content": [{"type": "tool_result", "tool_use_id": "nope"}]}}
|
||||
]
|
||||
assert parse.load_session(_write(tmp_path, records)).tools == []
|
||||
|
||||
|
||||
def test_skill_input_is_captured(tmp_path: Path) -> None:
|
||||
records = [
|
||||
_assistant(
|
||||
content=[
|
||||
{
|
||||
"type": "tool_use",
|
||||
"id": "s1",
|
||||
"name": "Skill",
|
||||
"input": {"skill": "finish"},
|
||||
},
|
||||
],
|
||||
),
|
||||
{
|
||||
"message": {
|
||||
"content": [
|
||||
{"type": "tool_result", "tool_use_id": "s1", "content": "ok"}
|
||||
]
|
||||
}
|
||||
},
|
||||
]
|
||||
assert parse.load_session(_write(tmp_path, records)).tools[0].skill == "finish"
|
||||
|
||||
|
||||
def test_tool_use_without_id_or_dict_input_is_tolerated(tmp_path: Path) -> None:
|
||||
records = [
|
||||
_assistant(content=[{"type": "tool_use", "name": "Read"}]),
|
||||
_assistant(
|
||||
content=[
|
||||
{"type": "tool_use", "id": "t2", "name": "Bash", "input": "notadict"}
|
||||
],
|
||||
),
|
||||
{"message": {"content": [{"type": "tool_result", "tool_use_id": "t2"}]}},
|
||||
]
|
||||
session = parse.load_session(_write(tmp_path, records))
|
||||
assert session.tools[0].name == "Bash"
|
||||
assert session.tools[0].path is None
|
||||
assert session.tools[0].result_tokens == 0
|
||||
|
||||
|
||||
def test_non_dict_messages_and_content_are_ignored(tmp_path: Path) -> None:
|
||||
records = [
|
||||
{"message": "a string"},
|
||||
{"message": {"content": "not a list"}},
|
||||
{"message": {"usage": "not a dict"}},
|
||||
{"no_message": True},
|
||||
{"message": {"content": ["not a dict block"]}},
|
||||
]
|
||||
session = parse.load_session(_write(tmp_path, records))
|
||||
assert session.turn_count == 0
|
||||
assert session.tools == []
|
||||
|
||||
|
||||
def test_model_falls_back_to_unknown(tmp_path: Path) -> None:
|
||||
records = [{"message": {"usage": {"output_tokens": 1}}}]
|
||||
assert parse.load_session(_write(tmp_path, records)).turns[0].model == "unknown"
|
||||
|
||||
|
||||
def test_non_string_model_falls_back(tmp_path: Path) -> None:
|
||||
records = [{"message": {"usage": {"output_tokens": 1}, "model": 42}}]
|
||||
assert parse.load_session(_write(tmp_path, records)).turns[0].model == "unknown"
|
||||
|
||||
|
||||
def test_tool_use_with_non_string_id_is_dropped(tmp_path: Path) -> None:
|
||||
records = [
|
||||
_assistant(
|
||||
content=[{"type": "tool_use", "id": 99, "name": "Read", "input": {}}]
|
||||
),
|
||||
{"message": {"content": [{"type": "tool_result", "tool_use_id": 99}]}},
|
||||
]
|
||||
assert parse.load_session(_write(tmp_path, records)).tools == []
|
||||
|
||||
|
||||
def test_unrecognised_block_types_are_ignored(tmp_path: Path) -> None:
|
||||
records = [_assistant(content=[{"type": "text", "text": "hello"}])]
|
||||
session = parse.load_session(_write(tmp_path, records))
|
||||
assert session.tools == []
|
||||
assert session.turn_count == 0
|
||||
|
||||
|
||||
def test_load_session_ignores_events_of_other_types(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
path = _write(tmp_path, [_assistant(usage={"output_tokens": 1})])
|
||||
monkeypatch.setattr(parse, "iter_events", lambda _: iter([("turn", "not a Turn")]))
|
||||
session = parse.load_session(path)
|
||||
assert session.turns == []
|
||||
assert session.tools == []
|
||||
|
||||
|
||||
def test_cwd_none_when_absent(tmp_path: Path) -> None:
|
||||
records = [{"message": {"usage": {"output_tokens": 1}}}]
|
||||
assert parse.load_session(_write(tmp_path, records)).cwd is None
|
||||
|
||||
|
||||
def test_usage_keeps_only_integer_fields(tmp_path: Path) -> None:
|
||||
usage = {"output_tokens": 5, "service_tier": "standard", "iterations": [{}]}
|
||||
session = parse.load_session(_write(tmp_path, [_assistant(usage=usage)]))
|
||||
assert session.turns[0].usage == {"output_tokens": 5}
|
||||
|
||||
|
||||
def test_sidechain_flag_is_preserved(tmp_path: Path) -> None:
|
||||
path = _write(tmp_path, [_assistant(usage={"output_tokens": 1}, sidechain=True)])
|
||||
assert parse.load_session(path).turns[0].is_sidechain
|
||||
|
||||
|
||||
def test_iter_events_preserves_order(tmp_path: Path) -> None:
|
||||
records = [
|
||||
_assistant(
|
||||
content=[
|
||||
{
|
||||
"type": "tool_use",
|
||||
"id": "a",
|
||||
"name": "Read",
|
||||
"input": {"file_path": "/i.png"},
|
||||
},
|
||||
],
|
||||
),
|
||||
{
|
||||
"message": {
|
||||
"content": [
|
||||
{"type": "tool_result", "tool_use_id": "a", "content": "xxxx"}
|
||||
]
|
||||
}
|
||||
},
|
||||
_assistant(usage={"output_tokens": 1}),
|
||||
]
|
||||
kinds = [k for k, _ in parse.iter_events(_write(tmp_path, records))]
|
||||
assert kinds == ["tool", "turn"]
|
||||
|
||||
|
||||
def test_events_carry_expected_types(tmp_path: Path) -> None:
|
||||
records = [
|
||||
_assistant(
|
||||
content=[
|
||||
{"type": "tool_use", "id": "a", "name": "Read", "input": {}},
|
||||
],
|
||||
),
|
||||
{"message": {"content": [{"type": "tool_result", "tool_use_id": "a"}]}},
|
||||
_assistant(usage={"output_tokens": 1}),
|
||||
]
|
||||
events = dict(parse.iter_events(_write(tmp_path, records)))
|
||||
assert isinstance(events["tool"], ToolCall)
|
||||
assert isinstance(events["turn"], Turn)
|
||||
|
||||
|
||||
def test_find_transcripts_filters_by_window(tmp_path: Path) -> None:
|
||||
project = tmp_path / "proj"
|
||||
project.mkdir()
|
||||
old = project / "old.jsonl"
|
||||
new = project / "new.jsonl"
|
||||
old.write_text("{}", encoding="utf-8")
|
||||
new.write_text("{}", encoding="utf-8")
|
||||
import os
|
||||
|
||||
os.utime(old, (1000, 1000))
|
||||
os.utime(new, (50_000, 50_000))
|
||||
|
||||
assert parse.find_transcripts(tmp_path, since=10_000) == [new]
|
||||
assert parse.find_transcripts(tmp_path, since=0, until=2000) == [old]
|
||||
assert len(parse.find_transcripts(tmp_path, since=0)) == 2
|
||||
|
||||
|
||||
@pytest.mark.parametrize("payload", [None, "abcdefgh"])
|
||||
def test_result_tokens_handles_missing_content(payload: str | None) -> None:
|
||||
assert parse._result_tokens({"content": payload}) >= 0
|
||||
149
python_pkg/token_audit/tests/test_report.py
Normal file
149
python_pkg/token_audit/tests/test_report.py
Normal file
@ -0,0 +1,149 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import pytest
|
||||
|
||||
from python_pkg.token_audit import attribute, report
|
||||
from python_pkg.token_audit.model import Session, ToolCall, Turn
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def _turn(
|
||||
out: int = 1,
|
||||
read: int = 0,
|
||||
create: int = 0,
|
||||
context: int = 0,
|
||||
*,
|
||||
sidechain: bool = False,
|
||||
) -> Turn:
|
||||
return Turn(
|
||||
usage={
|
||||
"output_tokens": out,
|
||||
"cache_read_input_tokens": read,
|
||||
"cache_creation_input_tokens": create,
|
||||
},
|
||||
context=context,
|
||||
model="claude-opus-5",
|
||||
is_sidechain=sidechain,
|
||||
)
|
||||
|
||||
|
||||
def _fixture() -> tuple[attribute.Totals, attribute.Axes, report.Window, list[Session]]:
|
||||
session = Session(session_id="abcdef123456", path="p", cwd="/home/kuhy/demo")
|
||||
session.turns = [_turn(out=10, create=500), _turn(out=5, read=400, context=400)]
|
||||
session.tools = [
|
||||
ToolCall(name="Read", result_tokens=900, path="/s.png"),
|
||||
ToolCall(name="mcp__aseprite__draw_line", result_tokens=3),
|
||||
ToolCall(name="Skill", result_tokens=1, skill="finish"),
|
||||
]
|
||||
session.image_cost = 90.0
|
||||
totals, axes = attribute.build([session])
|
||||
window = report.Window(since=0.0, until=86400.0)
|
||||
return totals, axes, window, [session]
|
||||
|
||||
|
||||
def test_window_describe_is_readable() -> None:
|
||||
assert "UTC" in report.Window(since=0.0, until=86400.0).describe()
|
||||
|
||||
|
||||
def test_snapshot_has_required_keys() -> None:
|
||||
totals, axes, window, sessions = _fixture()
|
||||
snap = report.snapshot(totals, axes, window, len(sessions))
|
||||
for key in (
|
||||
"generated",
|
||||
"window",
|
||||
"weighted_total",
|
||||
"raw",
|
||||
"image_cost",
|
||||
"projects",
|
||||
):
|
||||
assert key in snap
|
||||
assert snap["sessions"] == 1
|
||||
|
||||
|
||||
def test_render_contains_each_section() -> None:
|
||||
totals, axes, window, sessions = _fixture()
|
||||
snap = report.snapshot(totals, axes, window, len(sessions))
|
||||
text = report.render(totals, axes, window, sessions, snap, None)
|
||||
for heading in (
|
||||
"# Claude Code token audit",
|
||||
"## Totals",
|
||||
"## Ranked drivers",
|
||||
"## Projects",
|
||||
"## MCP servers invoked",
|
||||
"## Skills invoked",
|
||||
"## Most expensive sessions",
|
||||
):
|
||||
assert heading in text
|
||||
assert "aseprite" in text
|
||||
assert "finish" in text
|
||||
assert "abcdef12" in text
|
||||
|
||||
|
||||
def test_render_without_previous_says_so() -> None:
|
||||
totals, axes, window, sessions = _fixture()
|
||||
snap = report.snapshot(totals, axes, window, len(sessions))
|
||||
assert "No previous report" in report.render(
|
||||
totals, axes, window, sessions, snap, None
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("before", "expected"),
|
||||
[(100, "down"), (1, "up")],
|
||||
)
|
||||
def test_delta_direction(before: int, expected: str) -> None:
|
||||
assert expected in report._delta_line(
|
||||
{"weighted_total": 50}, {"weighted_total": before}
|
||||
)
|
||||
|
||||
|
||||
def test_delta_handles_zero_previous() -> None:
|
||||
assert "no spend" in report._delta_line(
|
||||
{"weighted_total": 5}, {"weighted_total": 0}
|
||||
)
|
||||
|
||||
|
||||
def test_empty_axes_render_placeholders() -> None:
|
||||
session = Session(session_id="s", path="p", cwd="/x")
|
||||
session.turns = [_turn()]
|
||||
totals, axes = attribute.build([session])
|
||||
window = report.Window(since=0.0, until=1.0)
|
||||
snap = report.snapshot(totals, axes, window, 1)
|
||||
text = report.render(totals, axes, window, [session], snap, None)
|
||||
assert "(none invoked)" in text
|
||||
|
||||
|
||||
def test_pct_guards_zero_denominator() -> None:
|
||||
assert report._pct(1.0, 0.0) == "n/a"
|
||||
|
||||
|
||||
def test_write_creates_both_files(tmp_path: Path) -> None:
|
||||
totals, axes, window, sessions = _fixture()
|
||||
snap = report.snapshot(totals, axes, window, len(sessions))
|
||||
text = report.render(totals, axes, window, sessions, snap, None)
|
||||
md_path = report.write(text, snap, tmp_path)
|
||||
assert md_path.exists()
|
||||
assert (tmp_path / report.JSON_NAME).exists()
|
||||
assert json.loads((tmp_path / report.JSON_NAME).read_text())["sessions"] == 1
|
||||
|
||||
|
||||
def test_load_previous_roundtrip(tmp_path: Path) -> None:
|
||||
assert report.load_previous(tmp_path) is None
|
||||
(tmp_path / report.JSON_NAME).write_text('{"weighted_total": 7}', encoding="utf-8")
|
||||
assert report.load_previous(tmp_path) == {"weighted_total": 7}
|
||||
|
||||
|
||||
def test_load_previous_tolerates_corrupt_json(tmp_path: Path) -> None:
|
||||
(tmp_path / report.JSON_NAME).write_text("{not json", encoding="utf-8")
|
||||
assert report.load_previous(tmp_path) is None
|
||||
|
||||
|
||||
def test_load_previous_rejects_non_object(tmp_path: Path) -> None:
|
||||
(tmp_path / report.JSON_NAME).write_text("[1,2]", encoding="utf-8")
|
||||
assert report.load_previous(tmp_path) is None
|
||||
@ -17,8 +17,8 @@ churn, not size alone — refactoring pays where code is read and changed often
|
||||
|
||||
## Scope in this repo
|
||||
|
||||
- **200 files** currently exceed 250 lines (of 807 eligible files).
|
||||
- **88,451 lines** sit in violation; longest file is **2053 lines**.
|
||||
- **197 files** currently exceed 250 lines (of 801 eligible files).
|
||||
- **87,393 lines** sit in violation; longest file is **2053 lines**.
|
||||
|
||||
Exempt (do NOT split these):
|
||||
|
||||
@ -51,7 +51,7 @@ has near-zero payoff and should not be first.
|
||||
| 415 | 7 | code | `focus_owner/android/app/src/main/kotlin/com/kuhy/focus_owner/DevicePolicyBridge.kt` |
|
||||
| 912 | 3 | code | `linux_configuration/scripts/single_use/features/setup_searxng.sh` |
|
||||
|
||||
_(185 further files over 250 lines not listed — re-run the survey for the full set.)_
|
||||
_(182 further files over 250 lines not listed — re-run the survey for the full set.)_
|
||||
|
||||
## How to split
|
||||
|
||||
|
||||
Loading…
Reference in New Issue
Block a user