tokenblame 2.2.2__tar.gz → 2.2.3__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (28) hide show
  1. {tokenblame-2.2.2 → tokenblame-2.2.3}/PKG-INFO +11 -6
  2. {tokenblame-2.2.2 → tokenblame-2.2.3}/README.md +10 -5
  3. {tokenblame-2.2.2 → tokenblame-2.2.3}/pyproject.toml +1 -1
  4. tokenblame-2.2.3/tests/test_integrity.py +502 -0
  5. {tokenblame-2.2.2 → tokenblame-2.2.3}/tests/test_observatory.py +11 -5
  6. tokenblame-2.2.3/tests/test_review_r2.py +618 -0
  7. tokenblame-2.2.3/tokenblame/__init__.py +3 -0
  8. {tokenblame-2.2.2 → tokenblame-2.2.3}/tokenblame/cli.py +55 -43
  9. tokenblame-2.2.3/tokenblame/config.py +52 -0
  10. tokenblame-2.2.3/tokenblame/fsutil.py +53 -0
  11. tokenblame-2.2.3/tokenblame/gitenv.py +16 -0
  12. {tokenblame-2.2.2 → tokenblame-2.2.3}/tokenblame/harvesters.py +18 -2
  13. {tokenblame-2.2.2 → tokenblame-2.2.3}/tokenblame/joiner.py +193 -45
  14. {tokenblame-2.2.2 → tokenblame-2.2.3}/tokenblame/provenance.py +120 -47
  15. {tokenblame-2.2.2 → tokenblame-2.2.3}/tokenblame/redact.py +71 -10
  16. {tokenblame-2.2.2 → tokenblame-2.2.3}/tokenblame/render.py +17 -8
  17. {tokenblame-2.2.2 → tokenblame-2.2.3}/tokenblame/store.py +3 -1
  18. {tokenblame-2.2.2 → tokenblame-2.2.3}/tokenblame/survival.py +17 -8
  19. {tokenblame-2.2.2 → tokenblame-2.2.3}/tokenblame.egg-info/PKG-INFO +11 -6
  20. {tokenblame-2.2.2 → tokenblame-2.2.3}/tokenblame.egg-info/SOURCES.txt +5 -0
  21. tokenblame-2.2.2/tokenblame/__init__.py +0 -3
  22. {tokenblame-2.2.2 → tokenblame-2.2.3}/LICENSE +0 -0
  23. {tokenblame-2.2.2 → tokenblame-2.2.3}/setup.cfg +0 -0
  24. {tokenblame-2.2.2 → tokenblame-2.2.3}/tokenblame/hooks.py +0 -0
  25. {tokenblame-2.2.2 → tokenblame-2.2.3}/tokenblame/schema.py +0 -0
  26. {tokenblame-2.2.2 → tokenblame-2.2.3}/tokenblame.egg-info/dependency_links.txt +0 -0
  27. {tokenblame-2.2.2 → tokenblame-2.2.3}/tokenblame.egg-info/entry_points.txt +0 -0
  28. {tokenblame-2.2.2 → tokenblame-2.2.3}/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.2
3
+ Version: 2.2.3
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,7 +23,7 @@ Description-Content-Type: text/markdown
23
23
  License-File: LICENSE
24
24
  Dynamic: license-file
25
25
 
26
- # TokenBlame (`v2.2`)
26
+ # TokenBlame (`v2.2.3`)
27
27
 
28
28
  **Don't just count AI coding tokens — blame them.**
29
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.*
@@ -42,11 +42,10 @@ 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`)** | **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.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** |
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
- > - **Pre-Indexed Query Latency (`3.5ms`):** Refers specifically to filtered `tokenblame summary` reads against an already-built `observatory.sqlite`, not cold full-history harvesting or `git blame` scans.
50
49
  > - **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.
51
50
 
52
51
  ---
@@ -76,11 +75,11 @@ tokenblame
76
75
  # Also emit privacy-redacted shareable HTML + IR:
77
76
  tokenblame build --shareable
78
77
 
79
- # Open dashboard in your browser (or Orca tab when running inside Orca):
78
+ # Open dashboard in your browser (or via TOKENBLAME_OPEN_COMMAND if you set one):
80
79
  tokenblame open
81
80
  tokenblame open --shareable
82
81
 
83
- # Sub-10ms filtered queries powered by indexed observatory.sqlite:
82
+ # Filtered queries read the indexed observatory.sqlite (no re-harvest):
84
83
  tokenblame summary --days 7
85
84
  tokenblame summary --days 30 --lane my-repo --json
86
85
 
@@ -161,6 +160,12 @@ TokenBlame measures **post-hoc** token burn, retry loops, and 30-day patch survi
161
160
 
162
161
  ---
163
162
 
163
+ ### Optional plugin: NoCheat verdict summary (off by default)
164
+
165
+ If you also run the NoCheat gate and it appends receipts to `nocheat_verdicts.jsonl` in the TokenBlame data directory, set `TOKENBLAME_NOCHEAT=1` before `tokenblame build` to add a read-only PASS/BLOCK/ABSTAIN summary to the report. Without that variable the file is never read and no NoCheat section is shown. See `docs/OWNER_CONFIG.md`.
166
+
167
+ ---
168
+
164
169
  ## License
165
170
 
166
171
  Apache-2.0 — see [LICENSE](LICENSE).
@@ -1,4 +1,4 @@
1
- # TokenBlame (`v2.2`)
1
+ # TokenBlame (`v2.2.3`)
2
2
 
3
3
  **Don't just count AI coding tokens — blame them.**
4
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.*
@@ -17,11 +17,10 @@ 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`)** | **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.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** |
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
- > - **Pre-Indexed Query Latency (`3.5ms`):** Refers specifically to filtered `tokenblame summary` reads against an already-built `observatory.sqlite`, not cold full-history harvesting or `git blame` scans.
25
24
  > - **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.
26
25
 
27
26
  ---
@@ -51,11 +50,11 @@ tokenblame
51
50
  # Also emit privacy-redacted shareable HTML + IR:
52
51
  tokenblame build --shareable
53
52
 
54
- # Open dashboard in your browser (or Orca tab when running inside Orca):
53
+ # Open dashboard in your browser (or via TOKENBLAME_OPEN_COMMAND if you set one):
55
54
  tokenblame open
56
55
  tokenblame open --shareable
57
56
 
58
- # Sub-10ms filtered queries powered by indexed observatory.sqlite:
57
+ # Filtered queries read the indexed observatory.sqlite (no re-harvest):
59
58
  tokenblame summary --days 7
60
59
  tokenblame summary --days 30 --lane my-repo --json
61
60
 
@@ -136,6 +135,12 @@ TokenBlame measures **post-hoc** token burn, retry loops, and 30-day patch survi
136
135
 
137
136
  ---
138
137
 
138
+ ### Optional plugin: NoCheat verdict summary (off by default)
139
+
140
+ If you also run the NoCheat gate and it appends receipts to `nocheat_verdicts.jsonl` in the TokenBlame data directory, set `TOKENBLAME_NOCHEAT=1` before `tokenblame build` to add a read-only PASS/BLOCK/ABSTAIN summary to the report. Without that variable the file is never read and no NoCheat section is shown. See `docs/OWNER_CONFIG.md`.
141
+
142
+ ---
143
+
139
144
  ## License
140
145
 
141
146
  Apache-2.0 — see [LICENSE](LICENSE).
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "tokenblame"
7
- version = "2.2.2"
7
+ version = "2.2.3"
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"
@@ -0,0 +1,502 @@
1
+ """Integrity-claim reproductions (lane axiom/integrity, 2026-11-28).
2
+
3
+ Each test encodes the DESIRED behaviour of one claim (TOKENBLAME_ROADMAP_VS_CODE.md and the
4
+ 2026-11-29 multi-repo audit, tokenblame section). The pre-fix run against commit 334c83a is
5
+ recorded in the lane's REPORT_CODEX.md; tests that already passed there are recorded as
6
+ "not reproduced" (pinned regression guards), not as fixes.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import datetime as dt
11
+ from contextlib import redirect_stdout
12
+ import io
13
+ import json
14
+ import os
15
+ from pathlib import Path
16
+ import re
17
+ import stat
18
+ import subprocess
19
+ import tempfile
20
+ import threading
21
+ import tomllib
22
+ import unittest
23
+ from unittest import mock
24
+
25
+ from tokenblame.harvesters import PARSER_REVISION, IncrementalCache
26
+
27
+ try: # absent on the pre-fix baseline: the test then fails instead of the whole module
28
+ from tokenblame.harvesters import harvest_cache_path
29
+ except ImportError: # pragma: no cover
30
+ harvest_cache_path = None
31
+ from tokenblame.joiner import _fetch_repo_commits_cached, build_observatory_ir
32
+ from tokenblame.provenance import load_commit_provenance, record_hook_invocation
33
+ from tokenblame.redact import _sanitize_forensics
34
+ from tokenblame.schema import SessionRecord, TokenBuckets
35
+
36
+ PKG = Path(__file__).resolve().parent.parent / "tokenblame"
37
+
38
+
39
+ def _session(sid: str, epoch: float, repo_root: str) -> SessionRecord:
40
+ return SessionRecord(
41
+ session_id=sid, provider="claude", model="claude-opus-5-5",
42
+ status="MEASURED", bucket_fidelity="4_bucket", day="2026-11-26",
43
+ timestamp="2026-11-26T09:00:00+09:00", epoch_sec=epoch,
44
+ cwd=repo_root, buckets=TokenBuckets(visible_output=18_000),
45
+ )
46
+
47
+
48
+ class TestStageSeparation(unittest.TestCase):
49
+ """Claim 1: a commit 10h after the session, no receipt, must not be 'verified'."""
50
+
51
+ def _ir_for_commit_offset(self, hours: float):
52
+ repo_root = "/Users/me/projects/stage-repo"
53
+ t0 = dt.datetime.fromisoformat("2026-11-26T09:00:00+09:00").timestamp()
54
+ oid = "d" * 40
55
+ s = _session("sess-late", t0, repo_root)
56
+ commit = {
57
+ "oid": oid, "short_oid": oid[:8], "day": "2026-11-26",
58
+ "epoch_sec": t0 + hours * 3600.0,
59
+ "clock_ts": "2026-11-26T19:00:00+09:00",
60
+ "lanes": ["Projects"], "repos": ["stage-repo"], "repo_root": repo_root,
61
+ "subject": "human commit made much later",
62
+ }
63
+ ir = build_observatory_ir(
64
+ sessions=[s], commits=[commit], episodes=[],
65
+ repo_map={repo_root: ("Projects", "stage-repo")},
66
+ harvest_stats={}, provenance_records=[], discover_repos=False,
67
+ )
68
+ return s, ir
69
+
70
+ def test_late_human_commit_is_window_tier_not_verified(self):
71
+ s, _ir = self._ir_for_commit_offset(10.0)
72
+ # Observed today (expected to reproduce): tier is the time-window heuristic ...
73
+ self.assertEqual(s.causality_tier, "TIME_WINDOW_HEURISTIC")
74
+ # ... but the attribution name claims verification. Desired: it must not.
75
+ self.assertNotEqual(s.attribution, "VERIFIED_OUTCOME")
76
+
77
+ def test_stage_names_are_distinct_per_tier(self):
78
+ s, _ir = self._ir_for_commit_offset(10.0)
79
+ self.assertEqual(s.attribution, "WINDOW_OUTCOME")
80
+
81
+ def test_ir_reports_per_stage_commit_counts(self):
82
+ _s, ir = self._ir_for_commit_offset(10.0)
83
+ stages = ir["totals"].get("commit_stage_counts")
84
+ self.assertIsInstance(stages, dict)
85
+ self.assertEqual(stages.get("WINDOW"), 1)
86
+ self.assertEqual(stages.get("EXACT", 0), 0)
87
+
88
+
89
+ class TestShareableKeepsLoopNames(unittest.TestCase):
90
+ """Claim 1b: --shareable must not fold FAILURE_LOOP / ITERATION_LOOP into RETRY_LOOP."""
91
+
92
+ def test_failure_and_iteration_loop_survive_redaction(self):
93
+ for raw, head in (
94
+ ("FAILURE_LOOP(Bash:pytest x6, err=4/9)", "FAILURE_LOOP"),
95
+ ("ITERATION_LOOP(Bash:pytest x4, ok=4/8)", "ITERATION_LOOP"),
96
+ ):
97
+ out = _sanitize_forensics({"loop_warning": raw})
98
+ self.assertTrue(
99
+ str(out["loop_warning"]).startswith(head),
100
+ f"{raw!r} became {out['loop_warning']!r}",
101
+ )
102
+
103
+ def test_unsafe_loop_text_is_still_redacted(self):
104
+ out = _sanitize_forensics({"loop_warning": "FAILURE_LOOP(/Users/me/secret x3, err=1/3)"})
105
+ self.assertNotIn("/Users/me", str(out["loop_warning"]))
106
+
107
+
108
+ class TestCachePermissions(unittest.TestCase):
109
+ """Claim 3: README says artifacts are 0600; harvest_cache.sqlite is created with the umask."""
110
+
111
+ def test_harvest_cache_is_owner_only(self):
112
+ old = os.umask(0o022)
113
+ try:
114
+ with tempfile.TemporaryDirectory() as td:
115
+ db = Path(td) / "harvest_cache.sqlite"
116
+ cache = IncrementalCache(db)
117
+ cache.conn.commit()
118
+ cache.conn.close()
119
+ mode = stat.S_IMODE(db.stat().st_mode)
120
+ self.assertEqual(mode & 0o077, 0, f"mode is {oct(mode)}")
121
+ finally:
122
+ os.umask(old)
123
+
124
+
125
+ class TestNoOwnerOnlyDefaults(unittest.TestCase):
126
+ """Claim 5: the public package must not hard-code the owner's directories or tools."""
127
+
128
+ BANNED = (
129
+ r"warmlogic",
130
+ r"research-workbench",
131
+ r"Resonance",
132
+ r"Orca",
133
+ r"ORCA_",
134
+ r'"lanes",\s*"code"',
135
+ )
136
+
137
+ def test_package_source_has_no_owner_words(self):
138
+ hits = []
139
+ for p in sorted(PKG.glob("*.py")):
140
+ for n, line in enumerate(p.read_text(encoding="utf-8").splitlines(), 1):
141
+ if p.name == "provenance.py" and "orca_pane_key" in line:
142
+ continue # read-only legacy ledger field; same allowlist as tests/owner_scan.py
143
+ for pat in self.BANNED:
144
+ if re.search(pat, line, re.IGNORECASE):
145
+ hits.append(f"{p.name}:{n}: {pat}")
146
+ self.assertEqual(hits, [])
147
+
148
+
149
+ _GIT_IDENT = {
150
+ "GIT_AUTHOR_NAME": "T", "GIT_AUTHOR_EMAIL": "t@example.com",
151
+ "GIT_COMMITTER_NAME": "T", "GIT_COMMITTER_EMAIL": "t@example.com",
152
+ }
153
+
154
+
155
+ def _git(repo, *args, env_extra=None):
156
+ env = {k: v for k, v in os.environ.items() if not k.startswith("GIT_")}
157
+ env.update(_GIT_IDENT)
158
+ env.update(env_extra or {})
159
+ return subprocess.run(
160
+ ["git", "-C", str(repo), *args], check=True, capture_output=True, text=True, env=env
161
+ ).stdout.strip()
162
+
163
+
164
+ def _repo_with_commit(root: Path, name="demo", msg="fresh commit", when=None):
165
+ repo = root / name
166
+ repo.mkdir(parents=True)
167
+ _git(repo, "init", "-q", "-b", "main")
168
+ (repo / "a.txt").write_text("v1\n", encoding="utf-8")
169
+ _git(repo, "add", "a.txt")
170
+ extra = {"GIT_AUTHOR_DATE": str(int(when)), "GIT_COMMITTER_DATE": str(int(when))} if when else None
171
+ _git(repo, "commit", "-q", "-m", msg, env_extra=extra)
172
+ return repo, _git(repo, "rev-parse", "HEAD")
173
+
174
+
175
+ def _hook_payload(repo, oid, session="sess-1", msg="fresh commit", stdout=True):
176
+ resp = {"exit_code": 0}
177
+ if stdout:
178
+ resp["stdout"] = f"[main {oid[:7]}] {msg}\n 1 file changed"
179
+ return json.dumps({
180
+ "session_id": session, "cwd": str(repo),
181
+ "tool_input": {"command": f"git commit -m '{msg}'"},
182
+ "tool_response": resp,
183
+ })
184
+
185
+
186
+ class TestRecorderRepairs(unittest.TestCase):
187
+ """Roadmap item 2: ledger path protection, lock, full dedup, env hygiene, EXACT gating."""
188
+
189
+ def test_symlinked_ledger_is_not_written_through(self):
190
+ with tempfile.TemporaryDirectory() as td:
191
+ root = Path(td)
192
+ repo, oid = _repo_with_commit(root)
193
+ victim = root / "victim.txt"
194
+ victim.write_text("keep\n", encoding="utf-8")
195
+ spool = root / "ledger" / "commit_provenance.jsonl"
196
+ spool.parent.mkdir()
197
+ os.symlink(victim, spool)
198
+ out = record_hook_invocation(_hook_payload(repo, oid), "claude", spool_path=spool)
199
+ self.assertEqual(out, [])
200
+ self.assertEqual(victim.read_text(encoding="utf-8"), "keep\n")
201
+
202
+ def test_hardlinked_ledger_is_refused(self):
203
+ with tempfile.TemporaryDirectory() as td:
204
+ root = Path(td)
205
+ repo, oid = _repo_with_commit(root)
206
+ victim = root / "victim.txt"
207
+ victim.write_text("keep\n", encoding="utf-8")
208
+ spool = root / "ledger" / "commit_provenance.jsonl"
209
+ spool.parent.mkdir()
210
+ os.link(victim, spool)
211
+ out = record_hook_invocation(_hook_payload(repo, oid), "claude", spool_path=spool)
212
+ self.assertEqual(out, [])
213
+ self.assertEqual(victim.read_text(encoding="utf-8"), "keep\n")
214
+
215
+ def test_dedup_checks_the_whole_ledger_not_a_50_line_tail(self):
216
+ with tempfile.TemporaryDirectory() as td:
217
+ root = Path(td)
218
+ repo, oid = _repo_with_commit(root)
219
+ spool = root / "commit_provenance.jsonl"
220
+ first = record_hook_invocation(_hook_payload(repo, oid), "claude", spool_path=spool)
221
+ self.assertEqual(len(first), 1)
222
+ with spool.open("a", encoding="utf-8") as f:
223
+ for i in range(80):
224
+ f.write(json.dumps({"commit_oid": f"{i:040x}", "session_id": f"other-{i}"}) + "\n")
225
+ again = record_hook_invocation(_hook_payload(repo, oid), "claude", spool_path=spool)
226
+ self.assertEqual(again, [])
227
+ self.assertEqual(sum(1 for ln in spool.read_text().splitlines() if oid in ln), 1)
228
+
229
+ def test_concurrent_hooks_write_one_receipt(self):
230
+ with tempfile.TemporaryDirectory() as td:
231
+ root = Path(td)
232
+ repo, oid = _repo_with_commit(root)
233
+ spool = root / "commit_provenance.jsonl"
234
+ payload = _hook_payload(repo, oid)
235
+ barrier = threading.Barrier(8)
236
+ results = []
237
+
238
+ def worker():
239
+ barrier.wait()
240
+ results.append(len(record_hook_invocation(payload, "claude", spool_path=spool)))
241
+
242
+ threads = [threading.Thread(target=worker) for _ in range(8)]
243
+ for t in threads:
244
+ t.start()
245
+ for t in threads:
246
+ t.join()
247
+ self.assertEqual(sum(results), 1, results)
248
+ self.assertEqual(len([ln for ln in spool.read_text().splitlines() if ln.strip()]), 1)
249
+
250
+ def test_torn_last_line_does_not_swallow_the_next_receipt(self):
251
+ with tempfile.TemporaryDirectory() as td:
252
+ root = Path(td)
253
+ repo, oid = _repo_with_commit(root)
254
+ spool = root / "commit_provenance.jsonl"
255
+ spool.write_text('{"commit_oid": "torn', encoding="utf-8") # crash mid-write, no newline
256
+ written = record_hook_invocation(_hook_payload(repo, oid), "claude", spool_path=spool)
257
+ self.assertEqual(len(written), 1)
258
+ self.assertEqual([r["commit_oid"] for r in load_commit_provenance(spool)], [oid])
259
+
260
+ def test_inherited_git_env_does_not_redirect_provenance(self):
261
+ with tempfile.TemporaryDirectory() as td:
262
+ root = Path(td)
263
+ repo, oid = _repo_with_commit(root, "right")
264
+ other, _other_oid = _repo_with_commit(root, "wrong", msg="other")
265
+ spool = root / "commit_provenance.jsonl"
266
+ with mock.patch.dict(os.environ, {"GIT_DIR": str(other / ".git"), "GIT_WORK_TREE": str(other)}):
267
+ written = record_hook_invocation(_hook_payload(repo, oid), "claude", spool_path=spool)
268
+ self.assertEqual([w["commit_oid"] for w in written], [oid])
269
+
270
+ def test_every_child_git_call_uses_no_optional_locks_and_clean_env(self):
271
+ seen = []
272
+ real_run = subprocess.run
273
+
274
+ def spy(cmd, *a, **kw):
275
+ if cmd and cmd[0] == "git":
276
+ seen.append((list(cmd), kw.get("env")))
277
+ return real_run(cmd, *a, **kw)
278
+
279
+ with tempfile.TemporaryDirectory() as td:
280
+ repo, _oid = _repo_with_commit(Path(td))
281
+ with mock.patch.object(subprocess, "run", spy), mock.patch.dict(os.environ, {"GIT_INDEX_FILE": "/nonexistent"}):
282
+ _fetch_repo_commits_cached(str(repo), "Projects", "demo", None)
283
+ self.assertTrue(seen)
284
+ for cmd, env in seen:
285
+ self.assertIn("--no-optional-locks", cmd, cmd)
286
+ self.assertIsNotNone(env, cmd)
287
+ self.assertFalse([k for k in env if k.startswith("GIT_")], cmd)
288
+
289
+ def test_existing_parent_directory_is_tightened_to_0700(self):
290
+ with tempfile.TemporaryDirectory() as td:
291
+ root = Path(td)
292
+ repo, oid = _repo_with_commit(root)
293
+ parent = root / "ledger"
294
+ parent.mkdir(mode=0o755)
295
+ os.chmod(parent, 0o755)
296
+ spool = parent / "commit_provenance.jsonl"
297
+ record_hook_invocation(_hook_payload(repo, oid), "claude", spool_path=spool)
298
+ self.assertEqual(stat.S_IMODE(parent.stat().st_mode), 0o700)
299
+ self.assertEqual(stat.S_IMODE(spool.stat().st_mode), 0o600)
300
+
301
+
302
+ def _claude_session(sid, epoch, repo_root, day="2026-11-26"):
303
+ return SessionRecord(
304
+ session_id=sid, provider="claude", model="claude-opus-5-5",
305
+ status="MEASURED", bucket_fidelity="4_bucket", day=day,
306
+ timestamp="2026-11-26T09:00:00+09:00", epoch_sec=epoch,
307
+ cwd=repo_root, buckets=TokenBuckets(visible_output=18_000),
308
+ )
309
+
310
+
311
+ def _commit_dict(oid, epoch, repo_root, subject="c"):
312
+ return {
313
+ "oid": oid, "short_oid": oid[:8], "day": "2026-11-26", "epoch_sec": epoch,
314
+ "clock_ts": "2026-11-26T09:05:00+09:00", "lanes": ["Projects"], "repos": ["r"],
315
+ "repo_root": repo_root, "subject": subject,
316
+ }
317
+
318
+
319
+ def _receipt(oid, sid, repo_root, epoch, **extra):
320
+ rec = {
321
+ "commit_oid": oid, "session_id": sid, "repo_root": repo_root,
322
+ "epoch_sec": epoch, "ambiguous": False,
323
+ }
324
+ rec.update(extra)
325
+ return rec
326
+
327
+
328
+ class TestExactGating(unittest.TestCase):
329
+ REPO = "/Users/me/projects/gate-repo"
330
+
331
+ def _ir(self, sessions, commits, receipts):
332
+ return build_observatory_ir(
333
+ sessions=sessions, commits=commits, episodes=[],
334
+ repo_map={self.REPO: ("Projects", "gate-repo")},
335
+ harvest_stats={}, provenance_records=receipts, discover_repos=False,
336
+ )
337
+
338
+ def test_receipt_without_oid_source_is_never_exact(self):
339
+ t0 = dt.datetime.fromisoformat("2026-11-26T09:00:00+09:00").timestamp()
340
+ oid = "a" * 40
341
+ s = _claude_session("s-old", t0, self.REPO)
342
+ self._ir([s], [_commit_dict(oid, t0 + 300, self.REPO)], [_receipt(oid, "s-old", self.REPO, t0 + 300)])
343
+ self.assertNotEqual(s.causality_tier, "EXACT_HOOK_OID")
344
+
345
+ def test_stdout_oid_receipt_is_exact(self):
346
+ t0 = dt.datetime.fromisoformat("2026-11-26T09:00:00+09:00").timestamp()
347
+ oid = "a" * 40
348
+ s = _claude_session("s-ok", t0, self.REPO)
349
+ self._ir([s], [_commit_dict(oid, t0 + 300, self.REPO)],
350
+ [_receipt(oid, "s-ok", self.REPO, t0 + 300, oid_source="stdout_oid")])
351
+ self.assertEqual(s.causality_tier, "EXACT_HOOK_OID")
352
+ self.assertEqual(s.attribution, "VERIFIED_OUTCOME")
353
+
354
+ def test_two_sessions_claiming_one_commit_are_both_demoted(self):
355
+ t0 = dt.datetime.fromisoformat("2026-11-26T09:00:00+09:00").timestamp()
356
+ oid = "b" * 40
357
+ sa = _claude_session("s-A", t0, self.REPO)
358
+ sb = _claude_session("s-B", t0 + 5, self.REPO)
359
+ recs = [
360
+ _receipt(oid, "s-A", self.REPO, t0 + 300, oid_source="stdout_oid"),
361
+ _receipt(oid, "s-B", self.REPO, t0 + 301, oid_source="stdout_oid"),
362
+ ]
363
+ self._ir([sa, sb], [_commit_dict(oid, t0 + 300, self.REPO)], recs)
364
+ self.assertNotEqual(sa.causality_tier, "EXACT_HOOK_OID")
365
+ self.assertNotEqual(sb.causality_tier, "EXACT_HOOK_OID")
366
+ self.assertNotEqual(sa.attribution, "VERIFIED_OUTCOME")
367
+ self.assertNotEqual(sb.attribution, "VERIFIED_OUTCOME")
368
+
369
+
370
+ class TestWave1Claims(unittest.TestCase):
371
+ REPO = "/Users/me/projects/wave-repo"
372
+
373
+ def test_session_base_commit_in_git_sha_is_not_attributed(self):
374
+ t0 = dt.datetime.fromisoformat("2026-11-26T09:00:00+09:00").timestamp()
375
+ base = "c" * 40
376
+ s = _claude_session("s-codex", t0, self.REPO)
377
+ s.git_sha = base
378
+ ir = build_observatory_ir(
379
+ sessions=[s], commits=[_commit_dict(base, t0 - 5 * 86400.0, self.REPO, "human base")],
380
+ episodes=[], repo_map={self.REPO: ("Projects", "wave-repo")},
381
+ harvest_stats={}, discover_repos=False,
382
+ )
383
+ self.assertNotIn(base, s.linked_oids)
384
+ self.assertNotEqual(s.attribution, "VERIFIED_OUTCOME")
385
+ self.assertNotEqual(s.attribution, "SHA_META_OUTCOME")
386
+ self.assertEqual(ir["totals"]["commit_stage_counts"]["UNLINKED"], 1)
387
+
388
+ def test_git_sha_of_a_commit_made_during_the_session_is_sha_meta(self):
389
+ t0 = dt.datetime.fromisoformat("2026-11-26T09:00:00+09:00").timestamp()
390
+ oid = "e" * 40
391
+ s = _claude_session("s-codex2", t0, self.REPO)
392
+ s.git_sha = oid
393
+ build_observatory_ir(
394
+ sessions=[s], commits=[_commit_dict(oid, t0 + 600, self.REPO)], episodes=[],
395
+ repo_map={self.REPO: ("Projects", "wave-repo")}, harvest_stats={}, discover_repos=False,
396
+ )
397
+ self.assertEqual(s.causality_tier, "GIT_SHA_META")
398
+ self.assertEqual(s.attribution, "SHA_META_OUTCOME")
399
+
400
+ def test_shareable_hides_third_party_mcp_tool_names(self):
401
+ secret = "mcp__acme_corp_secret_billing__export_pii"
402
+ fx = {
403
+ "tool_counts": {secret: 3, "Bash": 2},
404
+ "top_spikes": [{"turn": 1, "out": 5, "fresh_in": 1, "cache_read": 0, "tools": [secret]}],
405
+ "loop_warning": f"RETRY_LOOP({secret} x9)",
406
+ }
407
+ out = _sanitize_forensics(fx)
408
+ blob = json.dumps(out)
409
+ self.assertNotIn("acme", blob)
410
+ self.assertNotIn("export_pii", blob)
411
+ self.assertEqual(out["tool_counts"].get("Bash"), 2)
412
+ self.assertTrue(str(out["loop_warning"]).startswith("RETRY_LOOP("))
413
+
414
+ def test_cache_files_are_namespaced_by_parser_revision(self):
415
+ out = Path("/x/obs")
416
+ self.assertNotEqual(harvest_cache_path(out, "v2.0"), harvest_cache_path(out, "v2.2"))
417
+ self.assertEqual(harvest_cache_path(out).name, f"harvest_cache.{PARSER_REVISION}.sqlite")
418
+
419
+ def test_sharing_one_cache_file_across_revisions_wipes_it(self):
420
+ """Mechanism behind the v2.0/v2.2 thrash: documents why the files must not be shared."""
421
+ with tempfile.TemporaryDirectory() as td:
422
+ db = Path(td) / "harvest_cache.sqlite"
423
+ with mock.patch("tokenblame.harvesters.PARSER_REVISION", "v2.0"):
424
+ c = IncrementalCache(db)
425
+ c.conn.execute(
426
+ "INSERT INTO file_cache(path, root_kind, mtime_ns, size, records_json) VALUES ('p','',1,1,'[]')"
427
+ )
428
+ c.conn.commit()
429
+ c.conn.close()
430
+ c2 = IncrementalCache(db) # current revision opens the same file
431
+ n = c2.conn.execute("SELECT COUNT(*) FROM file_cache").fetchone()[0]
432
+ c2.conn.close()
433
+ self.assertEqual(n, 0)
434
+
435
+ def test_linked_worktree_commit_invalidates_the_commit_cache(self):
436
+ with tempfile.TemporaryDirectory() as td:
437
+ root = Path(td)
438
+ repo, _oid = _repo_with_commit(root, "main-repo", "base")
439
+ cache = IncrementalCache(root / "cache.sqlite")
440
+ first = {c["oid"] for c in _fetch_repo_commits_cached(str(repo), "Projects", "main-repo", cache)}
441
+ wt = root / "wt-branch"
442
+ _git(repo, "worktree", "add", "-q", "-b", "feat", str(wt))
443
+ (wt / "b.txt").write_text("x\n", encoding="utf-8")
444
+ _git(wt, "add", "b.txt")
445
+ _git(wt, "commit", "-q", "-m", "on linked branch")
446
+ branch_oid = _git(wt, "rev-parse", "HEAD")
447
+ wt2 = root / "wt-detached"
448
+ _git(repo, "worktree", "add", "-q", "--detach", str(wt2))
449
+ (wt2 / "c.txt").write_text("y\n", encoding="utf-8")
450
+ _git(wt2, "add", "c.txt")
451
+ _git(wt2, "commit", "-q", "-m", "on detached worktree")
452
+ detached_oid = _git(wt2, "rev-parse", "HEAD")
453
+ second = {c["oid"] for c in _fetch_repo_commits_cached(str(repo), "Projects", "main-repo", cache)}
454
+ cache.close()
455
+ self.assertEqual(len(first), 1)
456
+ self.assertIn(branch_oid, second)
457
+ self.assertIn(detached_oid, second)
458
+
459
+ def test_ci_has_no_fixed_session_date(self):
460
+ ci = (Path(__file__).resolve().parent.parent / ".github" / "workflows" / "ci.yml").read_text(encoding="utf-8")
461
+ fixed = re.findall(r'"timestamp":\s*"\d{4}-\d{2}-\d{2}', ci)
462
+ self.assertEqual(fixed, [], "a literal session date ages out of `summary --days 30`")
463
+
464
+
465
+ class TestOneNameOneVersion(unittest.TestCase):
466
+ def test_package_version_matches_pyproject(self):
467
+ import tokenblame
468
+
469
+ root = Path(__file__).resolve().parent.parent
470
+ with (root / "pyproject.toml").open("rb") as config:
471
+ version = tomllib.load(config)["project"]["version"]
472
+ self.assertEqual(tokenblame.__version__, version)
473
+
474
+ def test_cli_version_matches_package(self):
475
+ import tokenblame
476
+ from tokenblame.cli import main
477
+
478
+ output = io.StringIO()
479
+ with redirect_stdout(output), self.assertRaises(SystemExit) as exit_info:
480
+ main(["--version"])
481
+ self.assertEqual(exit_info.exception.code, 0)
482
+ self.assertEqual(output.getvalue(), f"{tokenblame.__version__}\n")
483
+
484
+
485
+ class TestStageCounts(unittest.TestCase):
486
+ def test_model_rows_split_stages(self):
487
+ repo_root = "/Users/me/projects/stage2"
488
+ t0 = dt.datetime.fromisoformat("2026-11-26T09:00:00+09:00").timestamp()
489
+ oid = "f" * 40
490
+ s = _claude_session("s-w", t0, repo_root)
491
+ ir = build_observatory_ir(
492
+ sessions=[s], commits=[_commit_dict(oid, t0 + 3600, repo_root)], episodes=[],
493
+ repo_map={repo_root: ("Projects", "stage2")}, harvest_stats={}, discover_repos=False,
494
+ )
495
+ row = ir["models"][0]
496
+ self.assertEqual((row["verified_sessions"], row["sha_meta_sessions"], row["window_sessions"]), (0, 0, 1))
497
+ self.assertEqual(ir["totals"]["attribution_breakdown"]["WINDOW_OUTCOME"]["sessions"], 1)
498
+ self.assertEqual(ir["totals"]["attribution_breakdown"]["VERIFIED_OUTCOME"]["sessions"], 0)
499
+
500
+
501
+ if __name__ == "__main__":
502
+ unittest.main()