tokenblame 2.2.3__tar.gz → 2.2.4__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (28) hide show
  1. {tokenblame-2.2.3 → tokenblame-2.2.4}/PKG-INFO +10 -8
  2. {tokenblame-2.2.3 → tokenblame-2.2.4}/README.md +9 -7
  3. {tokenblame-2.2.3 → tokenblame-2.2.4}/pyproject.toml +1 -1
  4. {tokenblame-2.2.3 → tokenblame-2.2.4}/tests/test_observatory.py +5 -4
  5. tokenblame-2.2.4/tests/test_v224_repair.py +411 -0
  6. {tokenblame-2.2.3 → tokenblame-2.2.4}/tokenblame/__init__.py +1 -1
  7. {tokenblame-2.2.3 → tokenblame-2.2.4}/tokenblame/joiner.py +22 -12
  8. {tokenblame-2.2.3 → tokenblame-2.2.4}/tokenblame/render.py +38 -4
  9. {tokenblame-2.2.3 → tokenblame-2.2.4}/tokenblame/schema.py +6 -1
  10. {tokenblame-2.2.3 → tokenblame-2.2.4}/tokenblame/survival.py +67 -2
  11. {tokenblame-2.2.3 → tokenblame-2.2.4}/tokenblame.egg-info/PKG-INFO +10 -8
  12. {tokenblame-2.2.3 → tokenblame-2.2.4}/tokenblame.egg-info/SOURCES.txt +1 -0
  13. {tokenblame-2.2.3 → tokenblame-2.2.4}/LICENSE +0 -0
  14. {tokenblame-2.2.3 → tokenblame-2.2.4}/setup.cfg +0 -0
  15. {tokenblame-2.2.3 → tokenblame-2.2.4}/tests/test_integrity.py +0 -0
  16. {tokenblame-2.2.3 → tokenblame-2.2.4}/tests/test_review_r2.py +0 -0
  17. {tokenblame-2.2.3 → tokenblame-2.2.4}/tokenblame/cli.py +0 -0
  18. {tokenblame-2.2.3 → tokenblame-2.2.4}/tokenblame/config.py +0 -0
  19. {tokenblame-2.2.3 → tokenblame-2.2.4}/tokenblame/fsutil.py +0 -0
  20. {tokenblame-2.2.3 → tokenblame-2.2.4}/tokenblame/gitenv.py +0 -0
  21. {tokenblame-2.2.3 → tokenblame-2.2.4}/tokenblame/harvesters.py +0 -0
  22. {tokenblame-2.2.3 → tokenblame-2.2.4}/tokenblame/hooks.py +0 -0
  23. {tokenblame-2.2.3 → tokenblame-2.2.4}/tokenblame/provenance.py +0 -0
  24. {tokenblame-2.2.3 → tokenblame-2.2.4}/tokenblame/redact.py +0 -0
  25. {tokenblame-2.2.3 → tokenblame-2.2.4}/tokenblame/store.py +0 -0
  26. {tokenblame-2.2.3 → tokenblame-2.2.4}/tokenblame.egg-info/dependency_links.txt +0 -0
  27. {tokenblame-2.2.3 → tokenblame-2.2.4}/tokenblame.egg-info/entry_points.txt +0 -0
  28. {tokenblame-2.2.3 → tokenblame-2.2.4}/tokenblame.egg-info/top_level.txt +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: tokenblame
3
- Version: 2.2.3
3
+ Version: 2.2.4
4
4
  Summary: Offline AI coding token ledger with out-of-repo Git commit provenance, Squash-Merge-resilient HEAD line retention, and allowlisted burn forensics
5
5
  Author: espressolee
6
6
  License-Expression: Apache-2.0
@@ -23,10 +23,10 @@ Description-Content-Type: text/markdown
23
23
  License-File: LICENSE
24
24
  Dynamic: license-file
25
25
 
26
- # TokenBlame (`v2.2.3`)
26
+ # TokenBlame (`v2.2.4`)
27
27
 
28
28
  **Don't just count AI coding tokens — blame them.**
29
- *Zero-config, 100% offline multi-agent token ledger with out-of-repo Git commit provenance, fixed-horizon (`t+30/60/90d`) & Squash-Merge-resilient line retention, and exit-code-aware burn forensics.*
29
+ *Zero-config, 100% offline multi-agent token ledger with out-of-repo Git commit provenance, sampled fixed-horizon (`t+30/60/90d`) line retention with disclosed coverage, and exit-code-aware burn forensics.*
30
30
 
31
31
  ![TokenBlame Overview — Shareable Redacted Edition](docs/assets/tokenblame-overview.png)
32
32
 
@@ -42,10 +42,11 @@ Token accounting, commit attribution, and code survival each have strong existin
42
42
  | **`Git AI` (OSS / Teams)** | Line-level AI authorship + Teams PR cost, rework & churn analytics | Yes (spec covers buckets & 90d DB; team analytics in Teams tier) | Line-level authorship + PR cost/churn | Git notes / metadata | Rust / Cloud |
43
43
  | **`Entire`** | Session checkpoints & token hotspot diagnostics | Yes (`fresh` / `cache` / `output` / `subagent`) | Session checkpoints linked to commits | Checkpoint metadata | Go |
44
44
  | **`survived`** | Fixed-horizon `t+30/60/90d` code survival (with `notYet` cohort separation) | No | Fixed-horizon commit survival | None | TypeScript |
45
- | **`TokenBlame` (`v2.2.3`)** | **Local offline multi-agent cost + commit provenance + `t+30/60/90d` cohorts & HEAD retention + exit-code burn loops** | **Yes** (4-bucket + strict unbucketed separation) | **Out-of-repo `record-hook` spool + revert, HEAD retention & matured cohorts (`notYet` separated)** | **None** | **Python 3.11+ stdlib only** |
45
+ | **`TokenBlame` (`v2.2.4`)** | **Local offline multi-agent cost + commit provenance + `t+30/60/90d` cohorts & HEAD retention + exit-code burn loops** | **Yes** (4-bucket + strict unbucketed separation) | **Out-of-repo `record-hook` spool + revert, sampled HEAD retention & sampled matured cohorts (`notYet` separated, measured/eligible commits shown)** | **None** | **Python 3.11+ stdlib only** |
46
46
 
47
47
  > **Honest measurement scope:**
48
48
  > - **HEAD Line Retention vs. Fixed-Horizon Cohorts (`t+30/60/90d`):** `line_survival_30d_pct` tracks HEAD retention of lines from the recent 30-day window (with Squash-Merge / Rebase fallback and `unobserved_lines` kept separate on `git blame` errors). Alongside it, `durability.cohorts` (`t30d`, `t60d`, `t90d`) measures **matured** fixed-horizon cohorts explicitly separated from immature `notYet` commits.
49
+ > - **Sampled, with disclosed coverage:** retention is computed on a sample, not on every matured commit. At most 30 repositories, 30 commits per repository per horizon and 18 paths per historical snapshot are measured; binary/no-added-line files, some extensions and files over 262,144 bytes are excluded. Each cohort carries `eligible_commits`, `selected_commits`, `measured_commits`, `changed_paths` / `eligible_paths` / `selected_paths` / `measured_paths`, exclusions by reason, `unobserved_lines` / `unobserved_paths` and `fallback_used` (squash text-match fallback). The card prints measured/eligible commits and the line numerator/denominator; a rate with no observed lines is shown as unavailable, never as a percentage.
49
50
  > - **Diagnostic Signals ≠ Causal Proof:** `FAILURE_LOOP` (nonzero exit/error streaks), `ITERATION_LOOP` (zero-error verification repeats), uncommitted high-burn sessions, and line retention are investigative signals — not automatic proofs of wasted effort, code correctness, or causal ROI.
50
51
 
51
52
  ---
@@ -86,7 +87,8 @@ tokenblame summary --days 30 --lane my-repo --json
86
87
  # Check environment, detected agent logs, timezone, and hook status:
87
88
  tokenblame doctor
88
89
 
89
- # One-click 1:1 provenance hook setup (with automatic backup & --uninstall):
90
+ # One-click provenance hook setup for Claude Code and Gemini CLI only (Codex and Antigravity are not auto-installed;
91
+ # automatic backup & --uninstall):
90
92
  tokenblame init
91
93
  tokenblame init --dry-run
92
94
  tokenblame init --uninstall
@@ -104,7 +106,7 @@ By default, TokenBlame discovers local Git repos under `~/projects`, `~/code`, `
104
106
 
105
107
  ## Optional 1:1 Commit Provenance Hook (`record-hook`)
106
108
 
107
- To upgrade concurrent same-repo agent sessions from time-window heuristics (`[-2h, +12h]`) to deterministic **1:1 `EXACT_HOOK_OID`** attribution without adding files, trailers, or git notes to your repositories:
109
+ To upgrade concurrent same-repo agent sessions from time-window heuristics (`[-2h, +12h]`) to **`EXACT_HOOK_OID`** attribution without adding files, trailers, or git notes to your repositories. A receipt counts as exact only when its original full commit OID is present among the scanned commits and its session ID matches a harvested session; a commit that was rewritten after the receipt (rebase, amend) is **not** matched by author time or subject and falls back to the lower tiers. Exactness is per session (one cost row per session), not per commit:
108
110
 
109
111
  ### Claude Code (`~/.claude/settings.json`)
110
112
  ```json
@@ -149,8 +151,8 @@ To upgrade concurrent same-repo agent sessions from time-window heuristics (`[-2
149
151
  ## Epistemic Integrity Guarantees
150
152
 
151
153
  - **Strict Fidelity Separation:** Unexposed IDE transcripts or legacy unbucketed SQLite threads are never blended into exact 4-bucket totals; estimated byte-volume side ledgers (`ESTIMATED_TRANSCRIPT`) are reported separately.
152
- - **Honest API-Equivalent Pricing:** Uses pinned official token rates (`input`, `cache_write`, `cache_read`, `output`), labels alias/fast-mode tiers explicitly, and leaves unpriced preview models as `unpriced` rather than fabricating USD totals.
153
- - **Transparent Causality Tiers:** Separately badges `1:1 HOOK`, `SHA_META`, `WINDOW_HEURISTIC`, and `DAY_EPISODE` links so attribution strength is never overstated.
154
+ - **Honest API-Equivalent Pricing:** Uses a pinned rate table (`input`, `cache_write`, `cache_read`, `output`), labels alias/fast-mode tiers explicitly, and leaves unpriced preview models as `unpriced` rather than fabricating USD totals. Rates are a static per-model snapshot with no per-request date, service-tier or modality. `gemini-2.5-flash` uses the Standard *text* rates from the 2026-12-01 Google AI Studio capture and is tagged `standard_text_assumed`, not `official`; audio, Batch and Free-tier usage, and Google's 2026-12-01 automatic routing to another model, are not modelled.
155
+ - **Transparent Causality Tiers:** Separately badges `1:1 HOOK` (receipt OID matched an existing commit and session ID), `SHA_META`, `WINDOW_HEURISTIC`, and `DAY_EPISODE` links. `DAY_EPISODE` has no commit evidence and still maps to the `VERIFIED_OUTCOME` attribution label for compatibility.
154
156
 
155
157
  ---
156
158
 
@@ -1,7 +1,7 @@
1
- # TokenBlame (`v2.2.3`)
1
+ # TokenBlame (`v2.2.4`)
2
2
 
3
3
  **Don't just count AI coding tokens — blame them.**
4
- *Zero-config, 100% offline multi-agent token ledger with out-of-repo Git commit provenance, fixed-horizon (`t+30/60/90d`) & Squash-Merge-resilient line retention, and exit-code-aware burn forensics.*
4
+ *Zero-config, 100% offline multi-agent token ledger with out-of-repo Git commit provenance, sampled fixed-horizon (`t+30/60/90d`) line retention with disclosed coverage, and exit-code-aware burn forensics.*
5
5
 
6
6
  ![TokenBlame Overview — Shareable Redacted Edition](docs/assets/tokenblame-overview.png)
7
7
 
@@ -17,10 +17,11 @@ Token accounting, commit attribution, and code survival each have strong existin
17
17
  | **`Git AI` (OSS / Teams)** | Line-level AI authorship + Teams PR cost, rework & churn analytics | Yes (spec covers buckets & 90d DB; team analytics in Teams tier) | Line-level authorship + PR cost/churn | Git notes / metadata | Rust / Cloud |
18
18
  | **`Entire`** | Session checkpoints & token hotspot diagnostics | Yes (`fresh` / `cache` / `output` / `subagent`) | Session checkpoints linked to commits | Checkpoint metadata | Go |
19
19
  | **`survived`** | Fixed-horizon `t+30/60/90d` code survival (with `notYet` cohort separation) | No | Fixed-horizon commit survival | None | TypeScript |
20
- | **`TokenBlame` (`v2.2.3`)** | **Local offline multi-agent cost + commit provenance + `t+30/60/90d` cohorts & HEAD retention + exit-code burn loops** | **Yes** (4-bucket + strict unbucketed separation) | **Out-of-repo `record-hook` spool + revert, HEAD retention & matured cohorts (`notYet` separated)** | **None** | **Python 3.11+ stdlib only** |
20
+ | **`TokenBlame` (`v2.2.4`)** | **Local offline multi-agent cost + commit provenance + `t+30/60/90d` cohorts & HEAD retention + exit-code burn loops** | **Yes** (4-bucket + strict unbucketed separation) | **Out-of-repo `record-hook` spool + revert, sampled HEAD retention & sampled matured cohorts (`notYet` separated, measured/eligible commits shown)** | **None** | **Python 3.11+ stdlib only** |
21
21
 
22
22
  > **Honest measurement scope:**
23
23
  > - **HEAD Line Retention vs. Fixed-Horizon Cohorts (`t+30/60/90d`):** `line_survival_30d_pct` tracks HEAD retention of lines from the recent 30-day window (with Squash-Merge / Rebase fallback and `unobserved_lines` kept separate on `git blame` errors). Alongside it, `durability.cohorts` (`t30d`, `t60d`, `t90d`) measures **matured** fixed-horizon cohorts explicitly separated from immature `notYet` commits.
24
+ > - **Sampled, with disclosed coverage:** retention is computed on a sample, not on every matured commit. At most 30 repositories, 30 commits per repository per horizon and 18 paths per historical snapshot are measured; binary/no-added-line files, some extensions and files over 262,144 bytes are excluded. Each cohort carries `eligible_commits`, `selected_commits`, `measured_commits`, `changed_paths` / `eligible_paths` / `selected_paths` / `measured_paths`, exclusions by reason, `unobserved_lines` / `unobserved_paths` and `fallback_used` (squash text-match fallback). The card prints measured/eligible commits and the line numerator/denominator; a rate with no observed lines is shown as unavailable, never as a percentage.
24
25
  > - **Diagnostic Signals ≠ Causal Proof:** `FAILURE_LOOP` (nonzero exit/error streaks), `ITERATION_LOOP` (zero-error verification repeats), uncommitted high-burn sessions, and line retention are investigative signals — not automatic proofs of wasted effort, code correctness, or causal ROI.
25
26
 
26
27
  ---
@@ -61,7 +62,8 @@ tokenblame summary --days 30 --lane my-repo --json
61
62
  # Check environment, detected agent logs, timezone, and hook status:
62
63
  tokenblame doctor
63
64
 
64
- # One-click 1:1 provenance hook setup (with automatic backup & --uninstall):
65
+ # One-click provenance hook setup for Claude Code and Gemini CLI only (Codex and Antigravity are not auto-installed;
66
+ # automatic backup & --uninstall):
65
67
  tokenblame init
66
68
  tokenblame init --dry-run
67
69
  tokenblame init --uninstall
@@ -79,7 +81,7 @@ By default, TokenBlame discovers local Git repos under `~/projects`, `~/code`, `
79
81
 
80
82
  ## Optional 1:1 Commit Provenance Hook (`record-hook`)
81
83
 
82
- To upgrade concurrent same-repo agent sessions from time-window heuristics (`[-2h, +12h]`) to deterministic **1:1 `EXACT_HOOK_OID`** attribution without adding files, trailers, or git notes to your repositories:
84
+ To upgrade concurrent same-repo agent sessions from time-window heuristics (`[-2h, +12h]`) to **`EXACT_HOOK_OID`** attribution without adding files, trailers, or git notes to your repositories. A receipt counts as exact only when its original full commit OID is present among the scanned commits and its session ID matches a harvested session; a commit that was rewritten after the receipt (rebase, amend) is **not** matched by author time or subject and falls back to the lower tiers. Exactness is per session (one cost row per session), not per commit:
83
85
 
84
86
  ### Claude Code (`~/.claude/settings.json`)
85
87
  ```json
@@ -124,8 +126,8 @@ To upgrade concurrent same-repo agent sessions from time-window heuristics (`[-2
124
126
  ## Epistemic Integrity Guarantees
125
127
 
126
128
  - **Strict Fidelity Separation:** Unexposed IDE transcripts or legacy unbucketed SQLite threads are never blended into exact 4-bucket totals; estimated byte-volume side ledgers (`ESTIMATED_TRANSCRIPT`) are reported separately.
127
- - **Honest API-Equivalent Pricing:** Uses pinned official token rates (`input`, `cache_write`, `cache_read`, `output`), labels alias/fast-mode tiers explicitly, and leaves unpriced preview models as `unpriced` rather than fabricating USD totals.
128
- - **Transparent Causality Tiers:** Separately badges `1:1 HOOK`, `SHA_META`, `WINDOW_HEURISTIC`, and `DAY_EPISODE` links so attribution strength is never overstated.
129
+ - **Honest API-Equivalent Pricing:** Uses a pinned rate table (`input`, `cache_write`, `cache_read`, `output`), labels alias/fast-mode tiers explicitly, and leaves unpriced preview models as `unpriced` rather than fabricating USD totals. Rates are a static per-model snapshot with no per-request date, service-tier or modality. `gemini-2.5-flash` uses the Standard *text* rates from the 2026-12-01 Google AI Studio capture and is tagged `standard_text_assumed`, not `official`; audio, Batch and Free-tier usage, and Google's 2026-12-01 automatic routing to another model, are not modelled.
130
+ - **Transparent Causality Tiers:** Separately badges `1:1 HOOK` (receipt OID matched an existing commit and session ID), `SHA_META`, `WINDOW_HEURISTIC`, and `DAY_EPISODE` links. `DAY_EPISODE` has no commit evidence and still maps to the `VERIFIED_OUTCOME` attribution label for compatibility.
129
131
 
130
132
  ---
131
133
 
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "tokenblame"
7
- version = "2.2.3"
7
+ version = "2.2.4"
8
8
  description = "Offline AI coding token ledger with out-of-repo Git commit provenance, Squash-Merge-resilient HEAD line retention, and allowlisted burn forensics"
9
9
  readme = "README.md"
10
10
  license = "Apache-2.0"
@@ -411,7 +411,7 @@ class TestObservatoryAdversarial(unittest.TestCase):
411
411
  self.assertEqual(s_b.linked_oids, [])
412
412
  self.assertEqual(ir["totals"]["causality_breakdown"]["EXACT_HOOK_OID"], 1)
413
413
 
414
- def test_rebase_preserves_1to1_hook_attribution(self):
414
+ def test_rebase_does_not_promote_rewritten_oid_to_exact(self):
415
415
  repo_root = "/Users/me/projects/rebase-repo"
416
416
  author_ep = 1795665000.0
417
417
  old_oid = "1" * 40
@@ -445,9 +445,10 @@ class TestObservatoryAdversarial(unittest.TestCase):
445
445
  repo_map={repo_root: ("Projects", "rebase-repo")},
446
446
  harvest_stats={}, provenance_records=prov, discover_repos=False,
447
447
  )
448
- self.assertEqual(s.causality_tier, "EXACT_HOOK_OID")
449
- self.assertEqual(s.linked_oids, [new_oid])
450
- self.assertEqual(s.attribution, "VERIFIED_OUTCOME")
448
+ # v2.2.4 (audit A2): the receipt's original OID is absent, so a rewritten commit with equal
449
+ # author epoch + subject is never EXACT. The independent time-window tier may still link it.
450
+ self.assertNotEqual(s.causality_tier, "EXACT_HOOK_OID")
451
+ self.assertEqual(s.causality_tier, "TIME_WINDOW_HEURISTIC")
451
452
 
452
453
  def test_failed_git_commit_does_not_claim_stale_head(self):
453
454
  import os
@@ -0,0 +1,411 @@
1
+ """v2.2.4 repairs for Item 177 audit findings (A2-A4 attribution, B1 pricing, C1-C3 survival).
2
+
3
+ Every test builds a real Git repository inside a fresh temp dir and runs each subprocess with
4
+ `cwd=` set to a fresh empty temp dir (never the repo root, HOME or the process cwd).
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import hashlib
9
+ import os
10
+ import sqlite3
11
+ import subprocess
12
+ import tempfile
13
+ import unittest
14
+ from pathlib import Path
15
+ from typing import Any
16
+
17
+ from tokenblame.joiner import build_observatory_ir
18
+ from tokenblame.redact import build_shareable_ir
19
+ from tokenblame.render import render_observatory_html
20
+ from tokenblame.schema import SessionRecord, TokenBuckets
21
+ from tokenblame.store import write_observatory_store
22
+ from tokenblame.survival import measure_cohort_line_survival, measure_30d_line_survival
23
+
24
+ BASE_EP = 1_750_000_000
25
+
26
+
27
+ class _Repo:
28
+ def __init__(self, root: Path, scratch_cwd: Path):
29
+ self.root = root
30
+ self.cwd = scratch_cwd
31
+ root.mkdir()
32
+ self.git("init", "-b", "main")
33
+ self.git("config", "user.name", "Dev")
34
+ self.git("config", "user.email", "dev@example.com")
35
+
36
+ def git(self, *args: str, ep: int | None = None, check: bool = True) -> str:
37
+ env = os.environ.copy()
38
+ if ep is not None:
39
+ env["GIT_AUTHOR_DATE"] = f"{ep} +0000"
40
+ env["GIT_COMMITTER_DATE"] = f"{ep} +0000"
41
+ r = subprocess.run(
42
+ ["git", "-C", str(self.root), *args],
43
+ check=check, capture_output=True, text=True, env=env, cwd=str(self.cwd),
44
+ )
45
+ return r.stdout.strip()
46
+
47
+ def write(self, rel: str, text: str) -> None:
48
+ p = self.root / rel
49
+ p.parent.mkdir(parents=True, exist_ok=True)
50
+ p.write_text(text, encoding="utf-8")
51
+
52
+ def commit(self, msg: str, ep: int) -> str:
53
+ self.git("add", ".")
54
+ self.git("commit", "-m", msg, ep=ep)
55
+ return self.git("rev-parse", "HEAD")
56
+
57
+
58
+ def _commit_dict(repo: _Repo, oid: str) -> dict[str, Any]:
59
+ ep = int(repo.git("show", "-s", "--format=%at", oid))
60
+ subj = repo.git("show", "-s", "--format=%s", oid)
61
+ return {
62
+ "oid": oid, "short_oid": oid[:8], "day": "2026-11-26", "epoch_sec": float(ep),
63
+ "committer_epoch": float(ep), "clock_ts": "2026-11-26T15:01:00+09:00",
64
+ "lanes": ["Projects"], "repos": ["fx"], "repo_root": str(repo.root), "subject": subj,
65
+ }
66
+
67
+
68
+ def _prov(repo: _Repo, receipt_oid: str, sid: str, like_oid: str) -> dict[str, Any]:
69
+ ep = int(repo.git("show", "-s", "--format=%at", like_oid))
70
+ subj = repo.git("show", "-s", "--format=%s", like_oid)
71
+ return {
72
+ "schema": "gwl-commit-provenance/1.0", "epoch_sec": float(ep), "commit_oid": receipt_oid,
73
+ "author_epoch": ep, "committer_epoch": ep,
74
+ "subject_sha256": hashlib.sha256(subj.encode("utf-8")).hexdigest(),
75
+ "repo_root": str(repo.root), "provider": "claude", "session_id": sid,
76
+ "oid_source": "stdout_oid",
77
+ }
78
+
79
+
80
+ def _session(repo: _Repo, sid: str, ep: float = 0.0) -> SessionRecord:
81
+ # epoch far from the commit so the TIME_WINDOW tier cannot mask an exact claim
82
+ return SessionRecord(
83
+ session_id=sid, provider="claude", model="claude-opus-5-5", status="MEASURED",
84
+ bucket_fidelity="4_bucket", day="2026-11-26", timestamp="2026-11-26T15:00:00+09:00",
85
+ epoch_sec=ep or float(BASE_EP + 10_000_000), cwd=str(repo.root),
86
+ buckets=TokenBuckets(visible_output=18_000),
87
+ )
88
+
89
+
90
+ def _build(repo: _Repo, sessions, commit_oids, prov):
91
+ return build_observatory_ir(
92
+ sessions=sessions, commits=[_commit_dict(repo, o) for o in commit_oids], episodes=[],
93
+ repo_map={str(repo.root): ("Projects", "fx")}, harvest_stats={},
94
+ provenance_records=prov, discover_repos=False,
95
+ )
96
+
97
+
98
+ class AttributionRepairTests(unittest.TestCase):
99
+ def setUp(self):
100
+ self._td = tempfile.TemporaryDirectory()
101
+ base = Path(self._td.name)
102
+ scratch = base / "scratch"
103
+ scratch.mkdir()
104
+ self.repo = _Repo(base / "fx", scratch)
105
+
106
+ def tearDown(self):
107
+ self._td.cleanup()
108
+
109
+ def _assert_not_exact(self, ir, s):
110
+ self.assertNotEqual(s.causality_tier, "EXACT_HOOK_OID")
111
+ self.assertEqual(ir["totals"]["causality_breakdown"]["EXACT_HOOK_OID"], 0)
112
+ for ir_x in (ir, build_shareable_ir(ir, salt="s")):
113
+ html = render_observatory_html(ir_x)
114
+ self.assertNotIn("1:1 HOOK", html)
115
+ self.assertIn("<b>0</b> 1:1 Hook", html)
116
+
117
+ def test_a1_original_oid_present_is_exact(self):
118
+ r = self.repo
119
+ r.write("a.py", "original_value = 123\n")
120
+ orig = r.commit("feat: add original", BASE_EP)
121
+ s = _session(r, "sess-1")
122
+ ir = _build(r, [s], [orig], [_prov(r, orig, "sess-1", orig)])
123
+ self.assertEqual(s.causality_tier, "EXACT_HOOK_OID")
124
+ self.assertEqual(s.linked_oids, [orig])
125
+ self.assertEqual(ir["totals"]["causality_breakdown"]["EXACT_HOOK_OID"], 1)
126
+ self.assertIn("1:1 HOOK", render_observatory_html(ir))
127
+
128
+ def test_a2_same_patch_rewrite_is_not_exact(self):
129
+ r = self.repo
130
+ r.write("a.py", "original_value = 123\n")
131
+ orig = r.commit("feat: add original", BASE_EP)
132
+ r.git("commit", "--amend", "--no-edit", "--date", f"{BASE_EP} +0000", ep=BASE_EP + 77)
133
+ rewritten = r.git("rev-parse", "HEAD")
134
+ self.assertNotEqual(orig, rewritten)
135
+ # the original is outside the collected commits (only the rewrite is scanned)
136
+ s = _session(r, "sess-1")
137
+ ir = _build(r, [s], [rewritten], [_prov(r, orig, "sess-1", rewritten)])
138
+ self._assert_not_exact(ir, s)
139
+
140
+ def test_a3_changed_content_same_metadata_is_not_exact(self):
141
+ r = self.repo
142
+ r.write("a.py", "original_value = 123\n")
143
+ orig = r.commit("feat: add work", BASE_EP)
144
+ r.git("reset", "--hard", "HEAD~0")
145
+ r.git("checkout", "--orphan", "other")
146
+ r.git("rm", "-rf", ".")
147
+ r.write("b.py", "unrelated_counter = 999\n")
148
+ other = r.commit("feat: add work", BASE_EP)
149
+ self.assertNotEqual(orig, other)
150
+ s = _session(r, "sess-1")
151
+ ir = _build(r, [s], [other], [_prov(r, orig, "sess-1", other)])
152
+ self._assert_not_exact(ir, s)
153
+ self.assertNotIn(other, s.linked_oids if s.causality_tier == "EXACT_HOOK_OID" else [])
154
+
155
+ def test_a4_ambiguous_candidates_are_not_exact(self):
156
+ r = self.repo
157
+ r.write("a.py", "original_value = 123\n")
158
+ orig = r.commit("feat: add work", BASE_EP)
159
+ cands = []
160
+ for i in range(2):
161
+ r.git("checkout", "--orphan", f"c{i}")
162
+ r.git("rm", "-rf", ".")
163
+ r.write(f"f{i}.py", f"v{i} = {i}\n")
164
+ cands.append(r.commit("feat: add work", BASE_EP))
165
+ s = _session(r, "sess-1")
166
+ ir = _build(r, [s], cands, [_prov(r, orig, "sess-1", cands[0])])
167
+ self._assert_not_exact(ir, s)
168
+ self.assertEqual(s.linked_oids, [])
169
+
170
+ def test_a4_sqlite_summary_has_no_exact_for_rewrite(self):
171
+ r = self.repo
172
+ r.write("a.py", "original_value = 123\n")
173
+ orig = r.commit("feat: add original", BASE_EP)
174
+ r.git("commit", "--amend", "--no-edit", ep=BASE_EP + 5)
175
+ rewritten = r.git("rev-parse", "HEAD")
176
+ s = _session(r, "sess-1")
177
+ ir = _build(r, [s], [rewritten], [_prov(r, orig, "sess-1", rewritten)])
178
+ db = Path(self._td.name) / "o.sqlite"
179
+ write_observatory_store(db, ir, [s], [], [])
180
+ conn = sqlite3.connect(str(db))
181
+ try:
182
+ rows = conn.execute("SELECT causality_tier FROM sessions_fact").fetchall()
183
+ finally:
184
+ conn.close()
185
+ self.assertTrue(rows)
186
+ self.assertNotIn(("EXACT_HOOK_OID",), rows)
187
+
188
+ def test_contested_exact_claim_stays_demoted(self):
189
+ r = self.repo
190
+ r.write("a.py", "x = 1\n")
191
+ orig = r.commit("feat: x", BASE_EP)
192
+ sa, sb = _session(r, "sess-A"), _session(r, "sess-B")
193
+ prov = [_prov(r, orig, "sess-A", orig), _prov(r, orig, "sess-B", orig)]
194
+ ir = _build(r, [sa, sb], [orig], prov)
195
+ self.assertNotEqual(sa.causality_tier, "EXACT_HOOK_OID")
196
+ self.assertNotEqual(sb.causality_tier, "EXACT_HOOK_OID")
197
+ self.assertEqual(ir["totals"]["causality_breakdown"]["EXACT_HOOK_OID"], 0)
198
+
199
+
200
+ class PricingRepairTests(unittest.TestCase):
201
+ def test_b1_gemini_25_flash_uses_staged_standard_text_rates_and_is_not_official(self):
202
+ from tokenblame.schema import resolve_model_pricing
203
+
204
+ rates, src = resolve_model_pricing("gemini-2.5-flash")
205
+ self.assertEqual(rates, (0.30, 0.30, 0.03, 2.50))
206
+ self.assertNotEqual(src, "official_snapshot")
207
+ b = TokenBuckets(uncached_input=1_000_000, cached_read=1_000_000,
208
+ visible_output=600_000, reasoning_output=400_000)
209
+ self.assertAlmostEqual(b.estimate_cost_usd("gemini-2.5-flash"), 2.83, places=6)
210
+
211
+ def test_b1_card_does_not_label_gemini_row_official(self):
212
+ s = SessionRecord(
213
+ session_id="g1", provider="gemini_cli", model="gemini-2.5-flash", status="MEASURED",
214
+ bucket_fidelity="4_bucket", day="2026-11-26", timestamp="2026-11-26T15:00:00+09:00",
215
+ epoch_sec=float(BASE_EP), cwd="/nonexistent",
216
+ buckets=TokenBuckets(uncached_input=1_000_000, cached_read=1_000_000,
217
+ visible_output=600_000, reasoning_output=400_000),
218
+ )
219
+ ir = build_observatory_ir(sessions=[s], commits=[], episodes=[], repo_map={}, harvest_stats={},
220
+ discover_repos=False)
221
+ pc = ir["totals"]["pricing_coverage"]
222
+ self.assertEqual(pc["official_sessions"], 0)
223
+ self.assertEqual(pc["alias_or_fast_sessions"], 1)
224
+ self.assertEqual(ir["totals"]["api_equiv_cost_usd"], 2.83)
225
+ html = render_observatory_html(ir)
226
+ self.assertNotIn(">official</span>", html)
227
+
228
+
229
+ DAY = 86400
230
+
231
+
232
+ def _survival_ir(repo: _Repo, oids, as_of: float, sid: str = "sess-1", compute: bool = True):
233
+ s = _session(repo, sid)
234
+ prov = [_prov(repo, o, sid, o) for o in oids]
235
+ return build_observatory_ir(
236
+ sessions=[s], commits=[_commit_dict(repo, o) for o in oids], episodes=[],
237
+ repo_map={str(repo.root): ("Projects", "fx")}, harvest_stats={},
238
+ provenance_records=prov, discover_repos=False, compute_survival=compute, as_of_epoch=as_of,
239
+ )
240
+
241
+
242
+ class SurvivalCoverageTests(unittest.TestCase):
243
+ def setUp(self):
244
+ self._td = tempfile.TemporaryDirectory()
245
+ base = Path(self._td.name)
246
+ scratch = base / "scratch"
247
+ scratch.mkdir()
248
+ self.repo = _Repo(base / "fx", scratch)
249
+
250
+ def tearDown(self):
251
+ self._td.cleanup()
252
+
253
+ def test_c1_matured_vs_measured_commits_disclosed(self):
254
+ r = self.repo
255
+ oids = []
256
+ text = ""
257
+ for i in range(35):
258
+ text += f"line_{i} = {i}\n"
259
+ r.write("m.py", text)
260
+ oids.append(r.commit(f"feat: step {i}", BASE_EP + i * 60))
261
+ as_of = float(BASE_EP + 100 * DAY)
262
+ recs = [{"oid": o, "committer_epoch": float(BASE_EP + i * 60)} for i, o in enumerate(oids)]
263
+ t30 = measure_cohort_line_survival(str(r.root), recs, as_of_epoch=as_of)["t30d"]
264
+ self.assertEqual(t30["matured_commits"], 35)
265
+ self.assertEqual(t30["eligible_commits"], 35)
266
+ self.assertEqual(t30["selected_commits"], 30)
267
+ self.assertEqual(t30["measured_commits"], 30)
268
+ self.assertEqual((t30["surviving_lines"], t30["added_lines"]), (30, 30))
269
+ ir = _survival_ir(r, oids, as_of)
270
+ c = ir["totals"]["durability"]["cohorts"]["t30d"]
271
+ self.assertEqual((c["eligible_commits"], c["selected_commits"], c["measured_commits"]), (35, 30, 30))
272
+ for ir_x in (ir, build_shareable_ir(ir, salt="s")):
273
+ html = render_observatory_html(ir_x)
274
+ self.assertIn("30/35 matured commits measured", html)
275
+ self.assertIn("30/30 sampled lines", html)
276
+
277
+ def _c2_repo(self):
278
+ r = self.repo
279
+ for i in range(22):
280
+ r.write(f"p{i:02d}.py", "".join(f"p{i}_v{j} = {j}\n" for j in range(40 - i)))
281
+ r.write("notes.md", "# doc\nmore\n")
282
+ r.write("big.py", "a" * 270_022 + "\n")
283
+ c0 = r.commit("feat: wide change", BASE_EP)
284
+ r.git("rm", "p00.py") # a selected path that is confirmed absent at HEAD
285
+ r.commit("chore: drop p00", BASE_EP + DAY)
286
+ return c0
287
+
288
+ def test_c2_path_coverage_exclusions_and_fault(self):
289
+ from unittest import mock
290
+ import tokenblame.survival as sv
291
+
292
+ c0 = self._c2_repo()
293
+ nat = measure_30d_line_survival(str(self.repo.root), [c0])
294
+ self.assertEqual(nat["changed_paths"], 24)
295
+ self.assertEqual(nat["eligible_paths"], 22)
296
+ self.assertEqual(nat["selected_paths"], 18)
297
+ self.assertEqual(nat["measured_paths"], 18)
298
+ self.assertEqual(nat["excluded_paths"], {"extension": 1, "size": 1, "cap": 4})
299
+ self.assertEqual(nat["unobserved_lines"], 0)
300
+
301
+ real = sv._git_run
302
+
303
+ def faulty(cmd, **kw):
304
+ if "blame" in cmd and cmd[-1] == "p05.py":
305
+ return subprocess.CompletedProcess(cmd, 128, "", "fatal: injected")
306
+ return real(cmd, **kw)
307
+
308
+ with mock.patch.object(sv, "_git_run", faulty):
309
+ res = measure_30d_line_survival(str(self.repo.root), [c0])
310
+ self.assertEqual(res["selected_paths"], 18)
311
+ self.assertEqual(res["measured_paths"], 17)
312
+ self.assertEqual(res["unobserved_paths"], 1)
313
+ self.assertEqual(res["unobserved_lines"], 35)
314
+ self.assertEqual(res["measured_commits"], 1)
315
+ self.assertEqual(res["eligible_commits"], 1)
316
+ # cohort + card carry the same counters
317
+ recs = [{"oid": c0, "committer_epoch": float(BASE_EP)}]
318
+ with mock.patch.object(sv, "_git_run", faulty):
319
+ t30 = measure_cohort_line_survival(str(self.repo.root), recs, as_of_epoch=float(BASE_EP + 60 * DAY))["t30d"]
320
+ self.assertEqual((t30["changed_paths"], t30["selected_paths"], t30["measured_paths"]), (24, 18, 17))
321
+ self.assertEqual(t30["unobserved_lines"], 35)
322
+
323
+ def test_c2_card_shows_path_coverage(self):
324
+ from unittest import mock
325
+ import tokenblame.survival as sv
326
+
327
+ c0 = self._c2_repo()
328
+ real = sv._git_run
329
+
330
+ def faulty(cmd, **kw):
331
+ if "blame" in cmd and cmd[-1] == "p05.py":
332
+ return subprocess.CompletedProcess(cmd, 128, "", "fatal: injected")
333
+ return real(cmd, **kw)
334
+
335
+ with mock.patch.object(sv, "_git_run", faulty):
336
+ ir = _survival_ir(self.repo, [c0], float(BASE_EP + 60 * DAY))
337
+ html = render_observatory_html(ir)
338
+ self.assertIn("17/18 selected paths measured (of 24 changed)", html)
339
+ self.assertIn("35 lines unobserved", html)
340
+ self.assertIn("ext 1, size 1, cap 4", html)
341
+
342
+ def test_c3_squash_fallback_flag_surfaces(self):
343
+ r = self.repo
344
+ r.write("f.py", "base_value = 0\n")
345
+ base = r.commit("chore: base", BASE_EP - DAY)
346
+ r.git("checkout", "-b", "side")
347
+ r.write("f.py", "base_value = 0\nside_feature_value = 42\n")
348
+ side = r.commit("feat: side", BASE_EP)
349
+ r.git("checkout", "main")
350
+ r.write("f.py", "base_value = 0\nside_feature_value = 42\n") # squash-equivalent on main
351
+ r.commit("feat: squashed side", BASE_EP + DAY)
352
+ head = measure_30d_line_survival(str(r.root), [side])
353
+ self.assertEqual(head["squash_fallback_oids"], [side])
354
+ self.assertEqual(head["fallback_commits"], 1)
355
+ recs = [{"oid": side, "committer_epoch": float(BASE_EP)}]
356
+ t30 = measure_cohort_line_survival(str(r.root), recs, as_of_epoch=float(BASE_EP + 100 * DAY))["t30d"]
357
+ self.assertEqual((t30["surviving_lines"], t30["added_lines"]), (1, 1))
358
+ self.assertTrue(t30["fallback_used"])
359
+ ir = _survival_ir(r, [side], float(BASE_EP + 100 * DAY))
360
+ self.assertTrue(ir["totals"]["durability"]["cohorts"]["t30d"]["fallback_used"])
361
+ self.assertIn("squash-fallback used", render_observatory_html(ir))
362
+ del base
363
+
364
+ def test_all_unobserved_has_unavailable_rate_not_a_percentage(self):
365
+ from unittest import mock
366
+ import tokenblame.survival as sv
367
+
368
+ r = self.repo
369
+ r.write("m.py", "a = 1\nb = 2\n")
370
+ c0 = r.commit("feat: m", BASE_EP)
371
+ real = sv._git_run
372
+
373
+ def fail_blame(cmd, **kw):
374
+ if "blame" in cmd:
375
+ return subprocess.CompletedProcess(cmd, 128, "", "fatal: injected")
376
+ return real(cmd, **kw)
377
+
378
+ with mock.patch.object(sv, "_git_run", fail_blame):
379
+ ir = _survival_ir(r, [c0], float(BASE_EP + 60)) # not matured -> HEAD instance only
380
+ d = ir["totals"]["durability"]
381
+ self.assertIsNone(d["line_survival_30d_pct"])
382
+ self.assertEqual(d["sampled_30d_unobserved_lines"], 2)
383
+ html = render_observatory_html(ir)
384
+ self.assertIn("line retention unavailable", html)
385
+ self.assertNotIn("0.0% HEAD line retention", html)
386
+
387
+ def test_legacy_cached_entry_is_recomputed_not_trusted(self):
388
+ r = self.repo
389
+ r.write("m.py", "a = 1\n")
390
+ c0 = r.commit("feat: m", BASE_EP)
391
+ cache_db = Path(self._td.name) / "c.sqlite"
392
+ s = _session(r, "sess-1")
393
+ kw = dict(
394
+ sessions=[s], commits=[_commit_dict(r, c0)], episodes=[],
395
+ repo_map={str(r.root): ("Projects", "fx")}, harvest_stats={},
396
+ provenance_records=[_prov(r, c0, "sess-1", c0)], discover_repos=False,
397
+ compute_survival=True, as_of_epoch=float(BASE_EP + 60 * DAY), cache_db=cache_db,
398
+ )
399
+ build_observatory_ir(**kw)
400
+ con = sqlite3.connect(str(cache_db))
401
+ try:
402
+ tables = [t[0] for t in con.execute("SELECT name FROM sqlite_master WHERE type='table'")]
403
+ finally:
404
+ con.close()
405
+ self.assertTrue(tables)
406
+ ir = build_observatory_ir(**{**kw, "sessions": [_session(r, "sess-1")]})
407
+ self.assertIn("selected_commits", ir["totals"]["durability"]["cohorts"]["t30d"])
408
+
409
+
410
+ if __name__ == "__main__":
411
+ unittest.main()
@@ -1,3 +1,3 @@
1
1
  """ai-tokenblame: 3-Layer AI Engineering Worklog & Token Observatory."""
2
2
 
3
- __version__ = "2.2.3" # must equal pyproject.toml (checked by tests/test_integrity.py)
3
+ __version__ = "2.2.4" # must equal pyproject.toml (checked by tests/test_integrity.py)
@@ -21,6 +21,8 @@ from tokenblame.provenance import resolve_main_from_git_file as _resolve_main_fr
21
21
  from tokenblame.schema import SCHEMA_VERSION, SessionRecord, TokenBuckets, resolve_local_tz
22
22
  from tokenblame.survival import (
23
23
  REVERT_SUBJ_RE,
24
+ _empty_coverage,
25
+ _merge_coverage,
24
26
  measure_30d_line_survival,
25
27
  measure_cohort_line_survival,
26
28
  scan_repo_reverts,
@@ -605,7 +607,6 @@ def build_observatory_ir(
605
607
  # Index commits by OID prefix, repo-scoped prefix, rebase signature, and sorted epoch
606
608
  commits_by_prefix: dict[str, str] = {}
607
609
  commits_by_repo_prefix: dict[tuple[str, str], str] = {}
608
- commits_by_rebase_sig: dict[tuple[str, int, str], list[str]] = {}
609
610
  repo_epoch_index: dict[str, tuple[list[float], list[str]]] = {}
610
611
  tmp_by_repo: dict[str, list[tuple[float, str]]] = {}
611
612
 
@@ -620,8 +621,6 @@ def build_observatory_ir(
620
621
  commits_by_repo_prefix[(rroot, pref)] = oid
621
622
  if rroot and ep_sec > 0:
622
623
  tmp_by_repo.setdefault(rroot, []).append((ep_sec, oid))
623
- subj_sha = hashlib.sha256(str(c.get("subject") or "").encode("utf-8", errors="replace")).hexdigest()
624
- commits_by_rebase_sig.setdefault((rroot, int(ep_sec), subj_sha), []).append(oid)
625
624
 
626
625
  for rroot, pairs in tmp_by_repo.items():
627
626
  pairs.sort(key=lambda x: x[0])
@@ -658,14 +657,12 @@ def build_observatory_ir(
658
657
  # with no `oid_source` (older ledgers) or a recency guess are never exact evidence.
659
658
  if not raw_oid or pr.get("ambiguous") is True or oid_src != "stdout_oid":
660
659
  continue
661
- matched_oids: list[str] = []
662
- if raw_oid in commits_by_oid:
663
- matched_oids = [raw_oid]
664
- elif pr_repo and pr.get("author_epoch") and pr.get("subject_sha256"):
665
- sig = (pr_repo, int(pr["author_epoch"]), str(pr["subject_sha256"]))
666
- matched_oids = list(commits_by_rebase_sig.get(sig, []))
667
- if not matched_oids:
660
+ # v2.2.4: only the ORIGINAL full OID present among collected commits is exact. A rewritten
661
+ # commit (rebase/amend) that merely shares author epoch + subject is NOT evidence of the same
662
+ # change (audit A2-A4), so it is left to the lower, independent tiers.
663
+ if raw_oid not in commits_by_oid:
668
664
  continue
665
+ matched_oids: list[str] = [raw_oid]
669
666
 
670
667
  # Exact hook attribution requires a direct session_id match; unmatched receipts
671
668
  # fall through to TIME_WINDOW_HEURISTIC rather than claiming EXACT_HOOK_OID.
@@ -899,10 +896,15 @@ def build_observatory_ir(
899
896
  "added_lines": 0,
900
897
  "surviving_lines": 0,
901
898
  "unobserved_lines": 0,
899
+ "unobserved_commits": 0,
902
900
  "retention_pct": None,
901
+ **_empty_coverage(),
902
+ "fallback_used": False,
903
+ "repos_measured": 0,
903
904
  }
904
905
  for h in (30, 60, 90)
905
906
  }
907
+ head_cov: dict[str, Any] = _empty_coverage()
906
908
 
907
909
  if eff_survival and all_repos:
908
910
  commits_grouped_by_repo: dict[str, list[dict[str, Any]]] = {}
@@ -940,7 +942,8 @@ def build_observatory_ir(
940
942
  ref_key = _repo_cache_key(rroot, head_oid, _worktree_heads(rroot))
941
943
  surv_cache_key = f"{ref_key}|asof:{as_of_day}|oids:{oids_digest}"
942
944
  cached_surv = scache.get_repo_survival(rroot, surv_cache_key) if scache else None
943
- if cached_surv is None or cached_surv.get("cohort_schema") != "historical_v2":
945
+ # historical_v3 adds coverage counters; older cached entries are recomputed, not guessed
946
+ if cached_surv is None or cached_surv.get("cohort_schema") != "historical_v3":
944
947
  rev_map = (cached_surv or {}).get("reverts") if cached_surv else scan_repo_reverts(rroot, commits_grouped_by_repo[rroot])
945
948
  lsurv = (
946
949
  measure_30d_line_survival(rroot, recent_ai, snapshot_oid=head_oid)
@@ -950,7 +953,7 @@ def build_observatory_ir(
950
953
  cohorts_r = measure_cohort_line_survival(
951
954
  rroot, all_ai_repo, as_of_epoch=eff_as_of_ep, ref=head_oid
952
955
  )
953
- cached_surv = {"cohort_schema": "historical_v2", "as_of_day": as_of_day, "reverts": rev_map, "line_survival": lsurv, "cohorts": cohorts_r}
956
+ cached_surv = {"cohort_schema": "historical_v3", "as_of_day": as_of_day, "reverts": rev_map, "line_survival": lsurv, "cohorts": cohorts_r}
954
957
  if scache is not None:
955
958
  scache.put_repo_survival(rroot, surv_cache_key, cached_surv)
956
959
  global_reverts.update(cached_surv.get("reverts") or {})
@@ -963,8 +966,13 @@ def build_observatory_ir(
963
966
  sampled_30d_added += r_add
964
967
  sampled_30d_surviving += r_surv
965
968
  sampled_30d_unobserved += r_unobs
969
+ _merge_coverage(head_cov, ls)
966
970
  for ck, cv in (cached_surv.get("cohorts") or {}).items():
967
971
  if ck in cohort_agg and isinstance(cv, dict):
972
+ _merge_coverage(cohort_agg[ck], cv)
973
+ cohort_agg[ck]["unobserved_commits"] += int(cv.get("unobserved_commits") or 0)
974
+ if int(cv.get("added_lines") or 0) > 0:
975
+ cohort_agg[ck]["repos_measured"] += 1
968
976
  cohort_agg[ck]["matured_commits"] += int(cv.get("matured_commits") or 0)
969
977
  cohort_agg[ck]["not_yet_commits"] += int(cv.get("not_yet_commits") or 0)
970
978
  cohort_agg[ck]["added_lines"] += int(cv.get("added_lines") or 0)
@@ -991,6 +999,7 @@ def build_observatory_ir(
991
999
  s.outcome_durability = "ACTIVE"
992
1000
 
993
1001
  for ck, cv in cohort_agg.items():
1002
+ cv["fallback_used"] = cv["fallback_commits"] > 0
994
1003
  if cv["added_lines"] > 0:
995
1004
  cv["retention_pct"] = round(100.0 * cv["surviving_lines"] / cv["added_lines"], 2)
996
1005
 
@@ -1005,6 +1014,7 @@ def build_observatory_ir(
1005
1014
  "sampled_30d_surviving_lines": sampled_30d_surviving,
1006
1015
  "sampled_30d_unobserved_lines": sampled_30d_unobserved,
1007
1016
  "line_survival_30d_pct": round(100.0 * sampled_30d_surviving / sampled_30d_added, 2) if sampled_30d_added > 0 else None,
1017
+ "sampled_30d_coverage": {**head_cov, "fallback_used": head_cov["fallback_commits"] > 0},
1008
1018
  "line_retention_metric_scope": "current_head_retention_of_recent_30d_commits",
1009
1019
  "cohorts": cohort_agg,
1010
1020
  }
@@ -249,6 +249,7 @@ def _pricing_badge(src: str) -> str:
249
249
  cls_map = {
250
250
  "official_snapshot": ("ok", "official"),
251
251
  "official_fast_mode": ("warn", "fast 2x"),
252
+ "standard_text_assumed": ("commit", "std-text assumed"),
252
253
  "verified_sol_alias": ("commit", "sol-alias"),
253
254
  "sol_tier_alias": ("commit", "sol-tier"),
254
255
  "astra_tier_alias": ("commit", "astra-tier"),
@@ -550,16 +551,49 @@ def render_observatory_html(ir: dict[str, Any], *, view_mode: str = "auto") -> s
550
551
  cohorts = dur.get("cohorts") or {}
551
552
  t30 = cohorts.get("t30d") or {}
552
553
  line_surv = dur.get("line_survival_30d_pct")
554
+ def _cov_txt(c: dict[str, Any], unit: str) -> str:
555
+ """Compact sampled-coverage detail; legacy dicts without counters say so instead of guessing."""
556
+ if "selected_commits" not in c:
557
+ return "coverage unknown (legacy cache)"
558
+ ex = c.get("excluded_paths") or {}
559
+ parts = [
560
+ f"{int(c.get('measured_commits') or 0)}/{int(c.get('eligible_commits') or 0)} {unit} measured",
561
+ f"{int(c.get('measured_paths') or 0)}/{int(c.get('selected_paths') or 0)} selected paths measured "
562
+ f"(of {int(c.get('changed_paths') or 0)} changed)",
563
+ ]
564
+ ex_n = sum(int(ex.get(k) or 0) for k in ("extension", "size", "cap"))
565
+ if ex_n:
566
+ parts.append(
567
+ f"{ex_n} paths excluded (ext {int(ex.get('extension') or 0)}, size {int(ex.get('size') or 0)}, cap {int(ex.get('cap') or 0)})"
568
+ )
569
+ if int(c.get("unobserved_lines") or 0):
570
+ parts.append(f"{int(c['unobserved_lines'])} lines unobserved")
571
+ if int(c.get("unobserved_paths") or 0):
572
+ parts.append(f"{int(c['unobserved_paths'])} paths unobserved")
573
+ if c.get("fallback_used"):
574
+ parts.append(f"squash-fallback used ({int(c.get('fallback_commits') or 0)} commits)")
575
+ return ", ".join(parts)
576
+
577
+ head_cov_d = {**(dur.get("sampled_30d_coverage") or {}), "unobserved_lines": dur.get("sampled_30d_unobserved_lines") or 0}
553
578
  if t30.get("retention_pct") is not None:
554
- unobs_c = int(t30.get("unobserved_lines") or 0)
555
- unobs_s = f", {unobs_c} unobserved" if unobs_c else ""
556
579
  line_surv_txt = (
557
- f"t+30d snapshot: {t30['retention_pct']}% ({t30.get('matured_commits', 0)} matured, {t30.get('not_yet_commits', 0)} notYet{unobs_s})"
580
+ f"t+30d snapshot: {t30['retention_pct']}% "
581
+ f"({int(t30.get('surviving_lines') or 0)}/{int(t30.get('added_lines') or 0)} sampled lines; "
582
+ f"{t30.get('matured_commits', 0)} matured, {t30.get('not_yet_commits', 0)} notYet; "
583
+ f"{_cov_txt({**t30}, 'matured commits')})"
558
584
  )
559
585
  elif line_surv is not None:
560
586
  ny = int(t30.get("not_yet_commits") or 0)
561
587
  ny_s = f" · {ny} notYet" if ny else ""
562
- line_surv_txt = f"{line_surv}% HEAD line retention (recent 30d commits{ny_s})"
588
+ line_surv_txt = (
589
+ f"{line_surv}% HEAD line retention ({int(dur.get('sampled_30d_surviving_lines') or 0)}/"
590
+ f"{int(dur.get('sampled_30d_added_lines') or 0)} sampled lines; recent 30d commits{ny_s}; "
591
+ f"{_cov_txt(head_cov_d, 'recent commits')})"
592
+ )
593
+ elif int(t30.get("unobserved_lines") or 0) or int(dur.get("sampled_30d_unobserved_lines") or 0):
594
+ line_surv_txt = (
595
+ f"line retention unavailable (0 observed lines; {_cov_txt(t30 if int(t30.get('unobserved_lines') or 0) else head_cov_d, 'commits')})"
596
+ )
563
597
  else:
564
598
  line_surv_txt = "HEAD revert check"
565
599
  eyebrow_txt = (
@@ -59,7 +59,12 @@ MODEL_RATE_CARD_PER_1M: dict[str, tuple[float, float, float, float, str]] = {
59
59
  "gemini-3-pro-preview": (2.00, 2.00, 0.20, 12.00, "official_snapshot"),
60
60
  "gemini-3.1-pro": (2.00, 2.00, 0.20, 12.00, "official_snapshot"),
61
61
  "gemini-3-flash-preview": (0.50, 0.50, 0.05, 3.00, "official_snapshot"),
62
- "gemini-2.5-flash": (0.15, 0.15, 0.015, 0.60, "official_snapshot"),
62
+ # v2.2.4 (audit B1): Standard paid *text* tier from the staged Google AI Studio pricing capture
63
+ # (https://aistudio.google.com/docs/pricing#gemini-2.5-flash, captured 2026-12-01): $0.30 in /
64
+ # $2.50 out / $0.03 cached read per 1M. Audio ($1.00 in, $0.10 cached) is not modelled, Batch and
65
+ # Free tiers were not opened, and there is no per-request date/route, so this is an explicit
66
+ # assumption, not an `official_snapshot`.
67
+ "gemini-2.5-flash": (0.30, 0.30, 0.03, 2.50, "standard_text_assumed"),
63
68
  }
64
69
 
65
70
  _ANTHROPIC_FAST_ELIGIBLE = frozenset({"claude-opus-4-8", "claude-opus-5", "claude-opus-5-5"})
@@ -289,6 +289,30 @@ def scan_repo_reverts(
289
289
  return reverted_map
290
290
 
291
291
 
292
+ _COVERAGE_INT_KEYS = (
293
+ "eligible_commits", "selected_commits", "measured_commits",
294
+ "changed_paths", "eligible_paths", "selected_paths", "measured_paths", "unobserved_paths",
295
+ "fallback_commits",
296
+ )
297
+ _EXCLUSION_KEYS = ("extension", "size", "cap")
298
+
299
+
300
+ def _empty_coverage() -> dict[str, Any]:
301
+ """Coverage counters shared by the HEAD-instance and per-horizon cohort results."""
302
+ cov: dict[str, Any] = {k: 0 for k in _COVERAGE_INT_KEYS}
303
+ cov["excluded_paths"] = {k: 0 for k in _EXCLUSION_KEYS}
304
+ return cov
305
+
306
+
307
+ def _merge_coverage(dst: dict[str, Any], src: dict[str, Any]) -> None:
308
+ """Add `src` coverage counters into `dst` (missing keys in legacy dicts count as 0)."""
309
+ for k in _COVERAGE_INT_KEYS:
310
+ dst[k] = int(dst.get(k) or 0) + int(src.get(k) or 0)
311
+ ex = dst.setdefault("excluded_paths", {k: 0 for k in _EXCLUSION_KEYS})
312
+ for k in _EXCLUSION_KEYS:
313
+ ex[k] = int(ex.get(k) or 0) + int((src.get("excluded_paths") or {}).get(k) or 0)
314
+
315
+
292
316
  def measure_30d_line_survival(
293
317
  repo_root: str,
294
318
  candidate_oids: list[str],
@@ -311,12 +335,16 @@ def measure_30d_line_survival(
311
335
  "denominator_unknown": False,
312
336
  "per_oid": {},
313
337
  "squash_fallback_oids": [],
338
+ **_empty_coverage(),
314
339
  }
315
340
  if not candidate_oids or not os.path.isdir(repo_root):
316
341
  return empty
317
342
 
318
- sampled_oids = list(dict.fromkeys(candidate_oids))[:max_commits]
343
+ unique_oids = list(dict.fromkeys(candidate_oids))
344
+ sampled_oids = unique_oids[:max_commits]
319
345
  oid_set = set(sampled_oids)
346
+ empty["eligible_commits"] = len(unique_oids)
347
+ empty["selected_commits"] = len(sampled_oids)
320
348
 
321
349
  resolved_snap = _resolve_ref_oid(repo_root, snapshot_oid)
322
350
  if not resolved_snap:
@@ -355,6 +383,7 @@ def measure_30d_line_survival(
355
383
 
356
384
  # Map file -> {oid: added_lines}
357
385
  file_oid_added: dict[str, dict[str, int]] = defaultdict(lambda: defaultdict(int))
386
+ ext_excluded: set[str] = set()
358
387
  cur_oid = ""
359
388
  for line in ns.stdout.splitlines():
360
389
  if line.startswith("COMMIT:"):
@@ -372,10 +401,16 @@ def measure_30d_line_survival(
372
401
  if added_n <= 0:
373
402
  continue
374
403
  rel_path = parts[2].strip()
375
- if not rel_path or Path(rel_path).suffix.lower() in _SKIP_SURVIVAL_EXTS:
404
+ if not rel_path:
405
+ continue
406
+ if Path(rel_path).suffix.lower() in _SKIP_SURVIVAL_EXTS:
407
+ ext_excluded.add(rel_path)
376
408
  continue
377
409
  file_oid_added[rel_path][cur_oid] += added_n
378
410
 
411
+ empty["excluded_paths"] = {"extension": len(ext_excluded), "size": 0, "cap": 0}
412
+ # every path that gained lines in the sampled commits (before any exclusion)
413
+ empty["changed_paths"] = len(file_oid_added) + len(ext_excluded)
379
414
  if not file_oid_added:
380
415
  empty["snapshot_oid"] = resolved_snap
381
416
  return empty
@@ -390,9 +425,11 @@ def measure_30d_line_survival(
390
425
  return empty
391
426
 
392
427
  eligible_files: list[tuple[int, int, str, bool]] = []
428
+ size_excluded = 0
393
429
  for rel_p, oid_counts in file_oid_added.items():
394
430
  if rel_p in blob_sizes:
395
431
  if blob_sizes[rel_p] > 262_144:
432
+ size_excluded += 1
396
433
  continue
397
434
  eligible_files.append((len(oid_counts), sum(oid_counts.values()), rel_p, True))
398
435
  else:
@@ -401,6 +438,8 @@ def measure_30d_line_survival(
401
438
 
402
439
  eligible_files.sort(key=lambda x: (x[0], x[1]), reverse=True)
403
440
  selected = eligible_files[:max_files]
441
+ empty["excluded_paths"]["size"] = size_excluded
442
+ empty["excluded_paths"]["cap"] = max(0, len(eligible_files) - len(selected))
404
443
 
405
444
  per_oid: dict[str, dict[str, int]] = defaultdict(lambda: {"added": 0, "surviving": 0})
406
445
  ancestor_cache: dict[str, bool] = {}
@@ -494,6 +533,17 @@ def measure_30d_line_survival(
494
533
  tot_added = sum(v["added"] for v in per_oid.values())
495
534
  tot_surv = sum(v["surviving"] for v in per_oid.values())
496
535
  return {
536
+ "eligible_commits": len(unique_oids),
537
+ "selected_commits": len(sampled_oids),
538
+ # a measured commit has >=1 observed added line in the sampled denominator
539
+ "measured_commits": sum(1 for v in per_oid.values() if v["added"] > 0),
540
+ "changed_paths": empty["changed_paths"],
541
+ "eligible_paths": len(eligible_files),
542
+ "selected_paths": len(selected),
543
+ "measured_paths": len(selected) - len(unobserved_files),
544
+ "unobserved_paths": len(unobserved_files),
545
+ "excluded_paths": dict(empty["excluded_paths"]),
546
+ "fallback_commits": len(squash_fallback_oids),
497
547
  "snapshot_oid": resolved_snap,
498
548
  "added_lines": tot_added,
499
549
  "surviving_lines": tot_surv,
@@ -541,6 +591,9 @@ def measure_cohort_line_survival(
541
591
  "unobserved_commits": 0,
542
592
  "snapshots_evaluated": [],
543
593
  "retention_pct": None,
594
+ **_empty_coverage(),
595
+ "fallback_used": False,
596
+ "coverage_schema": "v2",
544
597
  }
545
598
  return out
546
599
 
@@ -562,6 +615,9 @@ def measure_cohort_line_survival(
562
615
  unobs_lines = 0
563
616
  unobs_commits = 0
564
617
  by_snapshot: dict[str, list[str]] = defaultdict(list)
618
+ cov = _empty_coverage()
619
+ cov["eligible_commits"] = len(matured_pairs)
620
+ cov["selected_commits"] = len(matured_pairs[:max_commits])
565
621
 
566
622
  for oid, ep in matured_pairs[:max_commits]:
567
623
  target_ep = int(ep + min_age)
@@ -583,8 +639,17 @@ def measure_cohort_line_survival(
583
639
  surv_n += int(res.get("surviving_lines") or 0)
584
640
  unobs_lines += int(res.get("unobserved_lines") or 0)
585
641
  unobs_commits += int(res.get("unobserved_commits") or 0)
642
+ # path totals are path-snapshot observations (one per path per evaluated snapshot)
643
+ for k in ("measured_commits", "changed_paths", "eligible_paths", "selected_paths", "measured_paths",
644
+ "unobserved_paths", "fallback_commits"):
645
+ cov[k] += int(res.get(k) or 0)
646
+ for k in _EXCLUSION_KEYS:
647
+ cov["excluded_paths"][k] += int((res.get("excluded_paths") or {}).get(k) or 0)
586
648
 
587
649
  out[f"t{h}d"] = {
650
+ **cov,
651
+ "fallback_used": cov["fallback_commits"] > 0,
652
+ "coverage_schema": "v2",
588
653
  "horizon_days": h,
589
654
  "ref": ref,
590
655
  "tip_oid": tip_oid,
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: tokenblame
3
- Version: 2.2.3
3
+ Version: 2.2.4
4
4
  Summary: Offline AI coding token ledger with out-of-repo Git commit provenance, Squash-Merge-resilient HEAD line retention, and allowlisted burn forensics
5
5
  Author: espressolee
6
6
  License-Expression: Apache-2.0
@@ -23,10 +23,10 @@ Description-Content-Type: text/markdown
23
23
  License-File: LICENSE
24
24
  Dynamic: license-file
25
25
 
26
- # TokenBlame (`v2.2.3`)
26
+ # TokenBlame (`v2.2.4`)
27
27
 
28
28
  **Don't just count AI coding tokens — blame them.**
29
- *Zero-config, 100% offline multi-agent token ledger with out-of-repo Git commit provenance, fixed-horizon (`t+30/60/90d`) & Squash-Merge-resilient line retention, and exit-code-aware burn forensics.*
29
+ *Zero-config, 100% offline multi-agent token ledger with out-of-repo Git commit provenance, sampled fixed-horizon (`t+30/60/90d`) line retention with disclosed coverage, and exit-code-aware burn forensics.*
30
30
 
31
31
  ![TokenBlame Overview — Shareable Redacted Edition](docs/assets/tokenblame-overview.png)
32
32
 
@@ -42,10 +42,11 @@ Token accounting, commit attribution, and code survival each have strong existin
42
42
  | **`Git AI` (OSS / Teams)** | Line-level AI authorship + Teams PR cost, rework & churn analytics | Yes (spec covers buckets & 90d DB; team analytics in Teams tier) | Line-level authorship + PR cost/churn | Git notes / metadata | Rust / Cloud |
43
43
  | **`Entire`** | Session checkpoints & token hotspot diagnostics | Yes (`fresh` / `cache` / `output` / `subagent`) | Session checkpoints linked to commits | Checkpoint metadata | Go |
44
44
  | **`survived`** | Fixed-horizon `t+30/60/90d` code survival (with `notYet` cohort separation) | No | Fixed-horizon commit survival | None | TypeScript |
45
- | **`TokenBlame` (`v2.2.3`)** | **Local offline multi-agent cost + commit provenance + `t+30/60/90d` cohorts & HEAD retention + exit-code burn loops** | **Yes** (4-bucket + strict unbucketed separation) | **Out-of-repo `record-hook` spool + revert, HEAD retention & matured cohorts (`notYet` separated)** | **None** | **Python 3.11+ stdlib only** |
45
+ | **`TokenBlame` (`v2.2.4`)** | **Local offline multi-agent cost + commit provenance + `t+30/60/90d` cohorts & HEAD retention + exit-code burn loops** | **Yes** (4-bucket + strict unbucketed separation) | **Out-of-repo `record-hook` spool + revert, sampled HEAD retention & sampled matured cohorts (`notYet` separated, measured/eligible commits shown)** | **None** | **Python 3.11+ stdlib only** |
46
46
 
47
47
  > **Honest measurement scope:**
48
48
  > - **HEAD Line Retention vs. Fixed-Horizon Cohorts (`t+30/60/90d`):** `line_survival_30d_pct` tracks HEAD retention of lines from the recent 30-day window (with Squash-Merge / Rebase fallback and `unobserved_lines` kept separate on `git blame` errors). Alongside it, `durability.cohorts` (`t30d`, `t60d`, `t90d`) measures **matured** fixed-horizon cohorts explicitly separated from immature `notYet` commits.
49
+ > - **Sampled, with disclosed coverage:** retention is computed on a sample, not on every matured commit. At most 30 repositories, 30 commits per repository per horizon and 18 paths per historical snapshot are measured; binary/no-added-line files, some extensions and files over 262,144 bytes are excluded. Each cohort carries `eligible_commits`, `selected_commits`, `measured_commits`, `changed_paths` / `eligible_paths` / `selected_paths` / `measured_paths`, exclusions by reason, `unobserved_lines` / `unobserved_paths` and `fallback_used` (squash text-match fallback). The card prints measured/eligible commits and the line numerator/denominator; a rate with no observed lines is shown as unavailable, never as a percentage.
49
50
  > - **Diagnostic Signals ≠ Causal Proof:** `FAILURE_LOOP` (nonzero exit/error streaks), `ITERATION_LOOP` (zero-error verification repeats), uncommitted high-burn sessions, and line retention are investigative signals — not automatic proofs of wasted effort, code correctness, or causal ROI.
50
51
 
51
52
  ---
@@ -86,7 +87,8 @@ tokenblame summary --days 30 --lane my-repo --json
86
87
  # Check environment, detected agent logs, timezone, and hook status:
87
88
  tokenblame doctor
88
89
 
89
- # One-click 1:1 provenance hook setup (with automatic backup & --uninstall):
90
+ # One-click provenance hook setup for Claude Code and Gemini CLI only (Codex and Antigravity are not auto-installed;
91
+ # automatic backup & --uninstall):
90
92
  tokenblame init
91
93
  tokenblame init --dry-run
92
94
  tokenblame init --uninstall
@@ -104,7 +106,7 @@ By default, TokenBlame discovers local Git repos under `~/projects`, `~/code`, `
104
106
 
105
107
  ## Optional 1:1 Commit Provenance Hook (`record-hook`)
106
108
 
107
- To upgrade concurrent same-repo agent sessions from time-window heuristics (`[-2h, +12h]`) to deterministic **1:1 `EXACT_HOOK_OID`** attribution without adding files, trailers, or git notes to your repositories:
109
+ To upgrade concurrent same-repo agent sessions from time-window heuristics (`[-2h, +12h]`) to **`EXACT_HOOK_OID`** attribution without adding files, trailers, or git notes to your repositories. A receipt counts as exact only when its original full commit OID is present among the scanned commits and its session ID matches a harvested session; a commit that was rewritten after the receipt (rebase, amend) is **not** matched by author time or subject and falls back to the lower tiers. Exactness is per session (one cost row per session), not per commit:
108
110
 
109
111
  ### Claude Code (`~/.claude/settings.json`)
110
112
  ```json
@@ -149,8 +151,8 @@ To upgrade concurrent same-repo agent sessions from time-window heuristics (`[-2
149
151
  ## Epistemic Integrity Guarantees
150
152
 
151
153
  - **Strict Fidelity Separation:** Unexposed IDE transcripts or legacy unbucketed SQLite threads are never blended into exact 4-bucket totals; estimated byte-volume side ledgers (`ESTIMATED_TRANSCRIPT`) are reported separately.
152
- - **Honest API-Equivalent Pricing:** Uses pinned official token rates (`input`, `cache_write`, `cache_read`, `output`), labels alias/fast-mode tiers explicitly, and leaves unpriced preview models as `unpriced` rather than fabricating USD totals.
153
- - **Transparent Causality Tiers:** Separately badges `1:1 HOOK`, `SHA_META`, `WINDOW_HEURISTIC`, and `DAY_EPISODE` links so attribution strength is never overstated.
154
+ - **Honest API-Equivalent Pricing:** Uses a pinned rate table (`input`, `cache_write`, `cache_read`, `output`), labels alias/fast-mode tiers explicitly, and leaves unpriced preview models as `unpriced` rather than fabricating USD totals. Rates are a static per-model snapshot with no per-request date, service-tier or modality. `gemini-2.5-flash` uses the Standard *text* rates from the 2026-12-01 Google AI Studio capture and is tagged `standard_text_assumed`, not `official`; audio, Batch and Free-tier usage, and Google's 2026-12-01 automatic routing to another model, are not modelled.
155
+ - **Transparent Causality Tiers:** Separately badges `1:1 HOOK` (receipt OID matched an existing commit and session ID), `SHA_META`, `WINDOW_HEURISTIC`, and `DAY_EPISODE` links. `DAY_EPISODE` has no commit evidence and still maps to the `VERIFIED_OUTCOME` attribution label for compatibility.
154
156
 
155
157
  ---
156
158
 
@@ -4,6 +4,7 @@ pyproject.toml
4
4
  tests/test_integrity.py
5
5
  tests/test_observatory.py
6
6
  tests/test_review_r2.py
7
+ tests/test_v224_repair.py
7
8
  tokenblame/__init__.py
8
9
  tokenblame/cli.py
9
10
  tokenblame/config.py
File without changes
File without changes
File without changes