Skip to content

thedotmack/claude-mem / plugin/skills/agent-cost-report

agent-cost-report

Verified

Believable agent cost report for any period, default the last 7 full days PT, not counting today. Measured tokens from Claude Code transcripts priced at OpenRouter list prices (ESTIMATED), measured provider spend when a sanctioned source exists, note-taker cost separate, Timing-style HTML/PDF plus report.json, line-items.csv, evidence.json.

FileKindSize
.gitignoreother100 B
CHECKSUMS.txtmarkdown2.1 KB
SKILL.mdskill md21.3 KB
VERIFICATION.mdmarkdown12.3 KB
scripts/acr.pyexecutablescript12.2 KB
scripts/acr/__init__.pyscript105 B
scripts/acr/behavior.pyscript17.5 KB
scripts/acr/classify.pyscript5.5 KB
scripts/acr/costs.pyscript6.3 KB
scripts/acr/devices.pyscript5.4 KB
scripts/acr/evidence.pyscript9.2 KB
scripts/acr/labels.pyscript7.6 KB
scripts/acr/measure.pyscript5.6 KB
scripts/acr/mistakes.pyscript23.1 KB
scripts/acr/owner.pyscript2.9 KB
scripts/acr/patterns.pyscript26.0 KB
scripts/acr/period.pyscript3.8 KB
scripts/acr/prices.pyscript5.0 KB
scripts/acr/render.pyscript52.7 KB
scripts/acr/rollup.pyscript31.7 KB
scripts/acr/rules.jsonconfig3.5 KB
scripts/acr/rules.pyscript4.5 KB
scripts/acr/sample.pyscript3.6 KB
scripts/acr/snapshot.pyscript2.0 KB
scripts/acr/sync.pyscript3.7 KB
scripts/acr/transcripts.pyscript7.4 KB
scripts/acr/wins.pyscript21.0 KB
scripts/tests/_db.pyscript3.6 KB
scripts/tests/_paths.pyscript337 B
scripts/tests/fixtures/codex/sessions/2026/09/18/rollout-codex-1.jsonlother664 B
scripts/tests/fixtures/make_report_fixtures.pyscript2.0 KB
scripts/tests/fixtures/prices_sample.jsonconfig611 B
scripts/tests/fixtures/projects/-workspace-proj-a/sess-aaaa.jsonlother2.9 KB
scripts/tests/fixtures/projects/-workspace-proj-b/sess-bbbb.jsonlother537 B
scripts/tests/fixtures/report-1day.jsonconfig20.1 KB
scripts/tests/fixtures/report-30day.jsonconfig48.1 KB
scripts/tests/fixtures/report-7day.jsonconfig29.1 KB
scripts/tests/fixtures/report-empty.jsonconfig13.8 KB
scripts/tests/fixtures/report-session.jsonconfig16.6 KB
scripts/tests/test_behavior.pyscript29.6 KB
scripts/tests/test_devices.pyscript5.9 KB
scripts/tests/test_labels.pyscript8.6 KB
scripts/tests/test_measure.pyscript6.8 KB
scripts/tests/test_period.pyscript7.0 KB
scripts/tests/test_prices.pyscript5.3 KB
scripts/tests/test_render.pyscript12.1 KB
scripts/tests/test_render_encoding.pyscript1.5 KB
scripts/tests/test_rollup.pyscript19.3 KB
scripts/tests/test_snapshot.pyscript2.8 KB
scripts/tests/test_sync.pyscript2.5 KB
scripts/tests/test_transcript_encoding.pyscript2.7 KB
scripts/tests/test_transcripts.pyscript8.1 KB
scripts/tests/test_wins.pyscript15.7 KB
verification/precision-2026-09-26.jsonconfig308 B

scripts/acr/transcripts.py

View on GitHub
"""Measured token usage from Claude Code transcripts (plan Phase 1.4).

Claude Code reader copied verbatim from /workspace/weekly-cost-workflow/parse_transcripts.py:7-38
and the Codex reader from :39-57, then extended (plan 1.4) with `cwd`, `cache_write_5m`
(read directly from cache_creation.ephemeral_5m_input_tokens when present, else
cache_write - cache_write_1h as weekly_report.py:94) and `device = "local"`.

Every transcript is streamed line by line; no file is ever read whole.
"""
import datetime as dt
import glob
import json
import os
import platform

from .period import PT, session_block

# copied from parse_transcripts.py:16 and :40 (glob patterns)
CLAUDE_GLOB = os.path.join("~", ".claude", "projects", "**", "*.jsonl")
CODEX_GLOB = os.path.join("~", ".codex", "sessions", "**", "*.jsonl")
DEVICE = "local"  # the collector only ever sees the machine it runs on


def host_label():
    """platform.node(); never a device UUID from settings."""
    return platform.node()


# copied from parse_transcripts.py:13-14
def ts(x):
    return dt.datetime.fromisoformat(x.replace("Z", "+00:00"))


def _project_dir(f, pattern):
    """Project dir = path segment after `/.claude/projects/` (parse_transcripts.py:20).
    For a non-default glob root (tests) the first segment relative to the root is the same thing."""
    if "/.claude/projects/" in f:
        return f.split("/.claude/projects/")[1].split("/")[0]  # copied from parse_transcripts.py:20
    root = os.path.expanduser(pattern).split("**")[0]
    return os.path.relpath(f, root).split(os.sep)[0]


def collect_claude(s, e, session=None, pattern=CLAUDE_GLOB):
    """Claude Code assistant lines in [s, e) deduped on (message.id, requestId).

    s/e: aware datetimes (end exclusive), or None when `session` is given (no period filter,
    plan 1.2). Returns (rows, stats)."""
    seen = set(); rows = []; dropped = 0
    # copied from parse_transcripts.py:16-17 (mtime prefilter); skipped when there is no window
    files = [f for f in glob.glob(os.path.expanduser(pattern), recursive=True)
             if s is None or dt.datetime.fromtimestamp(os.path.getmtime(f), PT) >= s]
    for f in files:
        proj = _project_dir(f, pattern)
        with open(f, encoding="utf-8", errors="ignore") as fh:
            # copied from parse_transcripts.py:21-38, with the extensions marked (+)
            for line in fh:
                if '"usage"' not in line: continue
                if session is not None and session not in line: continue  # (+) cheap --session prefilter
                try: d = json.loads(line)
                except Exception: continue
                m = d.get("message") or {}
                u = m.get("usage")
                if d.get("type") != "assistant" or not u or not d.get("timestamp"): continue
                sid = d.get("sessionId") or d.get("session_id")
                if session is not None and sid != session: continue  # (+) --session filter
                t = ts(d["timestamp"])
                if s is not None and not (s <= t < e): continue
                key = (m.get("id"), d.get("requestId"))
                if key in seen: dropped += 1; continue
                seen.add(key)
                cc = u.get("cache_creation") or {}
                cache_write = u.get("cache_creation_input_tokens", 0) or 0
                cache_write_1h = cc.get("ephemeral_1h_input_tokens", 0) or 0
                cw5 = cc.get("ephemeral_5m_input_tokens")  # (+) direct when present
                cache_write_5m = cw5 if cw5 is not None else cache_write - cache_write_1h  # (+) fallback, weekly_report.py:94
                rows.append(dict(src="claude-code", file=f, dir=proj, cwd=d.get("cwd"), session=sid,
                    sidechain=bool(d.get("isSidechain")), model=m.get("model"), ts=t.astimezone(PT).isoformat(),
                    input=u.get("input_tokens", 0) or 0, output=u.get("output_tokens", 0) or 0,
                    cache_write=cache_write, cache_write_1h=cache_write_1h, cache_write_5m=cache_write_5m,
                    cache_read=u.get("cache_read_input_tokens", 0) or 0,
                    cost_usd_reported=d.get("costUSD"), device=DEVICE))
    return rows, dict(files_seen=len(files), dedup_dropped=dropped)


def collect_codex(s, e, session=None, pattern=CODEX_GLOB):
    """Codex: token_count events carry a cumulative total_token_usage per session file (parse_transcripts.py:39-57
    took the last one). Each event becomes one row holding the growth since the previous event, so usage before
    the window is subtracted and every day is charged its own tokens; a session that starts before the window
    contributes only its in-window growth."""
    rows = []; files_seen = 0
    for f in glob.glob(os.path.expanduser(pattern), recursive=True):
        if s is not None and dt.datetime.fromtimestamp(os.path.getmtime(f), PT) < s: continue
        if session is not None and os.path.basename(f) != session: continue  # (+) --session filter
        files_seen += 1
        prev = dict(input_tokens=0, cached_input_tokens=0, output_tokens=0); model = None
        with open(f, encoding="utf-8", errors="ignore") as fh:
            for line in fh:
                try: d = json.loads(line)
                except Exception: continue
                p = d.get("payload") or {}
                if d.get("type") == "turn_context": model = p.get("model", model)
                if p.get("type") == "token_count" and p.get("info"):
                    t = ts(d["timestamp"]); u = p["info"].get("total_token_usage") or {}
                    cur = {k: int(u.get(k, 0) or 0) for k in prev}
                    delta = {k: max(cur[k] - prev[k], 0) for k in prev}; prev = cur       # cumulative counter: growth since the last event
                    if not any(delta.values()) or (s is not None and not (s <= t < e)): continue
                    rows.append(dict(src="codex", file=f, dir="codex", cwd=None, session=os.path.basename(f), sidechain=False, model=model,
                        ts=t.astimezone(PT).isoformat(), input=max(delta["input_tokens"] - delta["cached_input_tokens"], 0),
                        output=delta["output_tokens"], cache_write=0, cache_write_1h=0, cache_write_5m=0, cache_read=delta["cached_input_tokens"],
                        cost_usd_reported=None, device=DEVICE))
    return rows, dict(files_seen=files_seen)


def collect(window=None, session=None, claude_glob=CLAUDE_GLOB, codex_glob=CODEX_GLOB, window_block=None):
    """Run both readers. `window` is a period.Window, or None with `session` set.
    Returns the usage.json document: {window, collector, rows}."""
    if window is None and session is None:
        raise ValueError("collect needs a window or a session id")
    s, e = (window.start, window.end) if window is not None else (None, None)
    claude_rows, cstats = collect_claude(s, e, session=session, pattern=claude_glob)
    codex_rows, xstats = collect_codex(s, e, session=session, pattern=codex_glob)
    rows = claude_rows + codex_rows
    if window_block is None:
        window_block = window.block() if window is not None else session_block(session)
    wblock = window_block
    collector = dict(host_label=host_label(), glob=[claude_glob, codex_glob],
                     files_seen=cstats["files_seen"] + xstats["files_seen"],
                     files_seen_by_src={"claude-code": cstats["files_seen"], "codex": xstats["files_seen"]},
                     rows=len(rows), dedup_dropped=cstats["dedup_dropped"], window=wblock)
    return dict(window=wblock, collector=collector, rows=rows)
deprecation-and-migrationaddyosmani/agent-skillsManages deprecation and migration. Use when removing old systems, APIs, or features. Use when migrating users from one implementation to another. Use when migrating a database schema in production, such as renaming or dropping a column without downtime (expand/contract). Use when deciding whether to maintain or sunset existing code.Stars: 119kUpdated Claude CodeCodexVerifiedInstall
performance-optimizationaddyosmani/agent-skillsOptimizes application performance across frontend, backend, queries, and databases. Use when performance requirements exist, when you suspect performance regressions, when Core Web Vitals or load times need improvement, when N+1 query patterns need fixing, or when profiling reveals bottlenecks.Stars: 119kUpdated Claude CodeCodexVerifiedInstall
agent-cost-reportthedotmack/claude-memBelievable agent cost report for any period, default the last 7 full days PT, not counting today. Measured tokens from Claude Code transcripts priced at OpenRouter list prices (ESTIMATED), measured provider spend when a sanctioned source exists, note-taker cost separate, Timing-style HTML/PDF plus report.json, line-items.csv, evidence.json.Stars: 118kUpdated Claude CodeCodexVerifiedInstall
backup-setupthedotmack/claude-memSet up, check, or restore local claude-mem database snapshots. Use when the user says "set up backups", "back up my memories", "backup status", or "restore my database".Stars: 118kUpdated Claude CodeCodexVerifiedInstall