Chore: Record tokens and EUR cost per ticket in the dev log #5

Merged
claude-bot Bot merged 1 commits from chore/4-ticket-cost into main 2026-11-15 14:58:09 +01:00
3 changed files with 149 additions and 3 deletions

No files matched your search

+133
View File
@@ -0,0 +1,133 @@
#!/usr/bin/env python3
"""Token usage and API-equivalent cost of the agent's work in a time window, for the dev log.
Not part of the Deverenz product. Reads Claude Code's session transcripts for this
project and sums the token usage of every model response between --since and --until.
Cost is what the same usage would cost at Anthropic API list prices, converted to EUR
with the ECB reference rate; on a subscription it is not what was actually paid.
Usage:
.claude/scripts/ticket-cost.py --since 2026-11-15T10:00:00Z [--until 2026-11-15T14:00:00Z]
.claude/scripts/ticket-cost.py --since ... --usd-eur 0.86 # skip the ECB lookup
"""
# pyright: strict
import argparse
import json
import re
import sys
import urllib.request
from datetime import UTC, datetime
from pathlib import Path
# USD per million tokens: input, output, cache read, cache write 5m, cache write 1h.
# Source: Anthropic pricing as of 2026-11-03. Update when prices change.
PRICES: dict[str, tuple[float, float, float, float, float]] = {
"claude-opus-5-5": (4.00, 20.00, 0.20, 5.00, 8.00),
"claude-sonnet-5-5": (2.00, 10.00, 0.10, 2.50, 4.00),
"claude-haiku-5-5": (0.10, 0.50, 0.01, 0.125, 0.20), # prompts <= 100K tokens
"claude-fable-5-2": (8.00, 40.00, 0.20, 10.00, 16.00),
}
FAST_MODE_FACTOR = 2.0
ECB_URL = "https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml"
def transcript_dir() -> Path:
repo = Path(__file__).resolve().parents[2]
return Path.home() / ".claude" / "projects" / re.sub(r"[^A-Za-z0-9]", "-", str(repo))
def parse_time(value: str) -> datetime:
parsed = datetime.fromisoformat(value)
return parsed if parsed.tzinfo else parsed.astimezone() # naive input = local time
def usd_to_eur() -> float:
with urllib.request.urlopen(ECB_URL, timeout=10) as response:
xml = response.read().decode()
match = re.search(r"currency='USD' rate='([0-9.]+)'", xml)
if not match:
raise RuntimeError("USD rate not found in ECB feed")
return 1 / float(match.group(1)) # ECB quotes USD per EUR
Counts = tuple[int, int, int, int, int] # same order as PRICES
def parse_response(line: str) -> tuple[str, str, datetime, Counts, bool] | None:
"""(response id, model, time, token counts, fast mode) of one transcript line, or None."""
entry = json.loads(line)
message = entry.get("message")
if entry.get("type") != "assistant" or not isinstance(message, dict):
return None
usage = message.get("usage")
if not message.get("id") or not usage or not entry.get("timestamp"):
return None
cache_write = usage.get("cache_creation") or {}
write_5m = cache_write.get("ephemeral_5m_input_tokens", 0)
write_1h = cache_write.get("ephemeral_1h_input_tokens", 0)
if not cache_write: # older entries without the TTL breakdown
write_5m = usage.get("cache_creation_input_tokens", 0)
counts: Counts = (
usage.get("input_tokens", 0),
usage.get("output_tokens", 0),
usage.get("cache_read_input_tokens", 0),
write_5m,
write_1h,
)
time = parse_time(entry["timestamp"])
return message["id"], message.get("model", ""), time, counts, usage.get("speed") == "fast"
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--since", required=True, help="ISO time, e.g. 2026-11-15T10:00:00Z")
parser.add_argument("--until", help="ISO time (default: now)")
parser.add_argument("--usd-eur", type=float, help="fixed USD->EUR rate instead of the ECB lookup")
args = parser.parse_args()
since = parse_time(args.since)
until = parse_time(args.until) if args.until else datetime.now(UTC)
seen: set[str] = set()
tokens = {"input": 0, "output": 0, "cache_read": 0, "cache_write": 0}
cost_usd = 0.0
sessions: set[str] = set()
unpriced: set[str] = set()
# Subagent transcripts live in subdirectories, hence rglob.
for path in sorted(transcript_dir().rglob("*.jsonl")):
for line in path.open(encoding="utf-8"):
parsed = parse_response(line)
# One response is split over several lines that repeat the same usage.
if parsed is None or parsed[0] in seen or not since <= parsed[2] <= until:
continue
msg_id, model, _, counts, fast = parsed
seen.add(msg_id)
sessions.add(path.stem)
tokens["input"] += counts[0]
tokens["output"] += counts[1]
tokens["cache_read"] += counts[2]
tokens["cache_write"] += counts[3] + counts[4]
if model in PRICES:
factor = FAST_MODE_FACTOR if fast else 1.0
cost_usd += factor * sum(n * p for n, p in zip(counts, PRICES[model], strict=True)) / 1e6
elif sum(counts):
unpriced.add(model)
rate = args.usd_eur if args.usd_eur is not None else usd_to_eur()
total = sum(tokens.values())
print(f"Window: {since.isoformat()} .. {until.isoformat()}")
print(f"Sessions: {len(sessions)}, responses: {len(seen)}")
print(
f"Tokens: {total:,} (input {tokens['input']:,}, output {tokens['output']:,}, "
f"cache read {tokens['cache_read']:,}, cache write {tokens['cache_write']:,})"
)
print(f"Cost: ~EUR {cost_usd * rate:.2f} API-equivalent (USD {cost_usd:.2f} at {rate:.4f} EUR/USD)")
if unpriced:
print(f"Warning: no price for {', '.join(sorted(unpriced))}; not included in cost", file=sys.stderr)
return 0
if __name__ == "__main__":
sys.exit(main())
+3 -1
View File
@@ -88,4 +88,6 @@ The same permissions apply in every phase: nothing is pushed to `main`, and real
## Metrics
Recorded in the [dev log](devlog.md) for each ticket: time, cost, agent mistakes and what caught them (test, types, lint, agent review, human review, real run), number of rework rounds, and one thing learned.
Recorded in the [dev log](devlog.md) for each ticket: tokens and cost, agent mistakes and what caught them (test, types, lint, agent review, human review, real run), number of rework rounds, and one thing learned.
Tokens and cost come from `.claude/scripts/ticket-cost.py`, which sums the Claude Code transcripts from the start of work on the ticket to the merge. Cost is in EUR at API list prices (ECB rate of the day). On a subscription that is not the amount paid; it is a comparable measure between tickets. Time is not recorded: the agent cannot see the developer's time for writing, research and review, and wall-clock time from branch to merge mostly measures waiting.
+13 -2
View File
@@ -2,13 +2,24 @@
One entry per finished roadmap step, newest first. The agent drafts the entry, the developer corrects it. Rules for the workflow are in [agentic-workflow.md](agentic-workflow.md).
## 2026-11-15 · Setup: Add project docs and agent workflow setup
- **Issue / PR:** #1 / #3
- **Phase:** 1
- **Tokens / cost:** 12.3M tokens (146k output, 11.5M cache read) · ~€9.21 API-equivalent. Covers all sessions up to the merge, i.e. the whole setup work.
- **Rework rounds:** 0
- **Agent mistakes and what caught them:**
- None in the commit/PR step. No CI yet, so only the commit-msg hook and a manual secret scan (grep for tokens, keys, local IPs, personal details) ran.
- **What worked well:** Showing the staged file list and scanning for secrets before the commit. The board, labels and `gitea.sh` worked end to end: PR opened, `Closes #1` closed the issue on merge, ticket moved to Done via the API.
- **Learned:** Gitea's "There is no key available to sign this commit" refers to the merge commit the server would create; the instance has no signing key. It is informational and does not block merging.
- **Workflow change proposed:** Record tokens and EUR cost from the transcripts (`ticket-cost.py`) instead of time and cost from `/usage`. The agent cannot read `/usage`, and time leaves out the developer's own work. Approved by the developer.
<!--
## YYYY-MM-DD · Step N: <title>
- **Issue / PR:** #
- **Phase:** 1
- **Time:** ~h
- **Cost:** (from /cost or /usage)
- **Tokens / cost:** (from `.claude/scripts/ticket-cost.py --since <work started> --until <merged>`)
- **Rework rounds:** 0
- **Agent mistakes and what caught them:**
- <mistake> → caught by <test | types | lint | agent review | human review | real run | nothing (found later)>