tokenblame 2.2.0__tar.gz → 2.2.2__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.
- {tokenblame-2.2.0 → tokenblame-2.2.2}/PKG-INFO +1 -1
- {tokenblame-2.2.0 → tokenblame-2.2.2}/pyproject.toml +1 -1
- {tokenblame-2.2.0 → tokenblame-2.2.2}/tests/test_observatory.py +200 -60
- {tokenblame-2.2.0 → tokenblame-2.2.2}/tokenblame/harvesters.py +160 -39
- {tokenblame-2.2.0 → tokenblame-2.2.2}/tokenblame/joiner.py +25 -15
- {tokenblame-2.2.0 → tokenblame-2.2.2}/tokenblame/provenance.py +6 -1
- {tokenblame-2.2.0 → tokenblame-2.2.2}/tokenblame/render.py +3 -1
- {tokenblame-2.2.0 → tokenblame-2.2.2}/tokenblame/survival.py +221 -49
- {tokenblame-2.2.0 → tokenblame-2.2.2}/tokenblame.egg-info/PKG-INFO +1 -1
- {tokenblame-2.2.0 → tokenblame-2.2.2}/LICENSE +0 -0
- {tokenblame-2.2.0 → tokenblame-2.2.2}/README.md +0 -0
- {tokenblame-2.2.0 → tokenblame-2.2.2}/setup.cfg +0 -0
- {tokenblame-2.2.0 → tokenblame-2.2.2}/tokenblame/__init__.py +0 -0
- {tokenblame-2.2.0 → tokenblame-2.2.2}/tokenblame/cli.py +0 -0
- {tokenblame-2.2.0 → tokenblame-2.2.2}/tokenblame/hooks.py +0 -0
- {tokenblame-2.2.0 → tokenblame-2.2.2}/tokenblame/redact.py +0 -0
- {tokenblame-2.2.0 → tokenblame-2.2.2}/tokenblame/schema.py +0 -0
- {tokenblame-2.2.0 → tokenblame-2.2.2}/tokenblame/store.py +0 -0
- {tokenblame-2.2.0 → tokenblame-2.2.2}/tokenblame.egg-info/SOURCES.txt +0 -0
- {tokenblame-2.2.0 → tokenblame-2.2.2}/tokenblame.egg-info/dependency_links.txt +0 -0
- {tokenblame-2.2.0 → tokenblame-2.2.2}/tokenblame.egg-info/entry_points.txt +0 -0
- {tokenblame-2.2.0 → tokenblame-2.2.2}/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
|
+
Version: 2.2.2
|
|
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
|
|
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "tokenblame"
|
|
7
|
-
version = "2.2.
|
|
7
|
+
version = "2.2.2"
|
|
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"
|
|
@@ -1320,68 +1320,179 @@ class TestObservatoryAdversarial(unittest.TestCase):
|
|
|
1320
1320
|
self.assertEqual(res["unobserved_files"], ["mod.py"])
|
|
1321
1321
|
|
|
1322
1322
|
def test_fixed_horizon_cohort_survival_t30_t60_t90_and_not_yet(self):
|
|
1323
|
+
import os
|
|
1323
1324
|
import subprocess
|
|
1324
|
-
from tokenblame.survival import measure_cohort_line_survival
|
|
1325
|
+
from tokenblame.survival import measure_30d_line_survival, measure_cohort_line_survival
|
|
1325
1326
|
|
|
1326
1327
|
with tempfile.TemporaryDirectory() as td:
|
|
1327
1328
|
repo = Path(td) / "cohort-repo"
|
|
1328
1329
|
repo.mkdir()
|
|
1329
|
-
def git(*args: str) -> str:
|
|
1330
|
+
def git(*args: str, ep: int | None = None) -> str:
|
|
1331
|
+
env = os.environ.copy()
|
|
1332
|
+
if ep is not None:
|
|
1333
|
+
dstr = f"{ep} +0000"
|
|
1334
|
+
env["GIT_AUTHOR_DATE"] = dstr
|
|
1335
|
+
env["GIT_COMMITTER_DATE"] = dstr
|
|
1330
1336
|
return subprocess.run(
|
|
1331
1337
|
["git", "-C", str(repo), *args],
|
|
1332
|
-
check=True, capture_output=True, text=True,
|
|
1338
|
+
check=True, capture_output=True, text=True, env=env,
|
|
1333
1339
|
).stdout.strip()
|
|
1334
1340
|
|
|
1335
1341
|
git("init", "-b", "main")
|
|
1336
1342
|
git("config", "user.name", "Dev")
|
|
1337
1343
|
git("config", "user.email", "dev@example.com")
|
|
1338
1344
|
|
|
1339
|
-
|
|
1340
|
-
|
|
1345
|
+
# Audit counterexample: Day 0 add 10 lines -> Day 50 delete all 10 lines -> Day 100 eval
|
|
1346
|
+
# True historical fixed-horizon survival MUST be: t+30d=100%, t+60d=0%, t+90d=0%, HEAD=0%!
|
|
1347
|
+
day0 = 1_750_000_000
|
|
1348
|
+
day50 = day0 + 50 * 86400
|
|
1349
|
+
day100 = day0 + 100 * 86400
|
|
1350
|
+
(repo / "ephemeral.py").write_text("".join(f"val_{i} = {i}\n" for i in range(10)), encoding="utf-8")
|
|
1341
1351
|
git("add", ".")
|
|
1342
|
-
git("commit", "-m", "
|
|
1343
|
-
|
|
1352
|
+
git("commit", "-m", "day0 add 10 lines", ep=day0)
|
|
1353
|
+
oid_day0 = git("rev-parse", "HEAD")
|
|
1344
1354
|
|
|
1345
|
-
(
|
|
1346
|
-
git("
|
|
1347
|
-
git("commit", "-m", "c65")
|
|
1348
|
-
oid_65 = git("rev-parse", "HEAD")
|
|
1355
|
+
git("rm", "ephemeral.py")
|
|
1356
|
+
git("commit", "-m", "day50 delete all 10 lines", ep=day50)
|
|
1349
1357
|
|
|
1350
|
-
|
|
1351
|
-
|
|
1352
|
-
|
|
1353
|
-
|
|
1354
|
-
|
|
1358
|
+
cohorts_ce = measure_cohort_line_survival(
|
|
1359
|
+
str(repo),
|
|
1360
|
+
[{"oid": oid_day0, "epoch_sec": float(day0), "committer_epoch": float(day0)}],
|
|
1361
|
+
as_of_epoch=float(day100),
|
|
1362
|
+
)
|
|
1363
|
+
self.assertEqual(cohorts_ce["t30d"]["retention_pct"], 100.0)
|
|
1364
|
+
self.assertEqual(cohorts_ce["t30d"]["surviving_lines"], 10)
|
|
1365
|
+
self.assertEqual(cohorts_ce["t60d"]["retention_pct"], 0.0)
|
|
1366
|
+
self.assertEqual(cohorts_ce["t90d"]["retention_pct"], 0.0)
|
|
1367
|
+
head_ce = measure_30d_line_survival(str(repo), [oid_day0])
|
|
1368
|
+
self.assertEqual(head_ce["surviving_lines"], 0)
|
|
1369
|
+
|
|
1370
|
+
# Working-tree isolation counterexample: file exists in HEAD but deleted on disk (uncommitted)
|
|
1371
|
+
(repo / "keep.py").write_text("k1 = 1\nk2 = 2\nk3 = 3\n", encoding="utf-8")
|
|
1372
|
+
git("add", "keep.py")
|
|
1373
|
+
git("commit", "-m", "add keep.py", ep=day100 - 5 * 86400)
|
|
1374
|
+
oid_keep = git("rev-parse", "HEAD")
|
|
1375
|
+
(repo / "keep.py").unlink() # Delete ONLY in working tree, NOT committed!
|
|
1376
|
+
head_wt = measure_30d_line_survival(str(repo), [oid_keep])
|
|
1377
|
+
self.assertEqual(head_wt["added_lines"], 3)
|
|
1378
|
+
self.assertEqual(head_wt["surviving_lines"], 3)
|
|
1379
|
+
|
|
1380
|
+
# Multi-commit matured vs notYet partition check (5d, 35d, 70d, 100d -> 3/1, 2/2, 1/3)
|
|
1381
|
+
recs = [
|
|
1382
|
+
{"oid": oid_day0, "epoch_sec": float(day0), "committer_epoch": float(day0)},
|
|
1383
|
+
{"oid": oid_keep, "epoch_sec": float(day100 - 5 * 86400), "committer_epoch": float(day100 - 5 * 86400)},
|
|
1384
|
+
]
|
|
1385
|
+
c_mix = measure_cohort_line_survival(str(repo), recs, as_of_epoch=float(day100))
|
|
1386
|
+
self.assertEqual(c_mix["t30d"]["matured_commits"], 1)
|
|
1387
|
+
self.assertEqual(c_mix["t30d"]["not_yet_commits"], 1)
|
|
1388
|
+
|
|
1389
|
+
# Survival cache in build_observatory_ir MUST recompute when as_of_epoch day changes on same HEAD
|
|
1390
|
+
cache_db = Path(td) / "surv_cache.sqlite"
|
|
1391
|
+
s_day0 = SessionRecord(
|
|
1392
|
+
session_id="sess-day0", provider="claude", model="claude-opus-5-5",
|
|
1393
|
+
status="MEASURED", bucket_fidelity="4_bucket", day="2025-06-15",
|
|
1394
|
+
timestamp="2025-06-15T00:00:00+00:00", epoch_sec=float(day0),
|
|
1395
|
+
cwd=str(repo.resolve()), git_sha=oid_day0,
|
|
1396
|
+
buckets=TokenBuckets(uncached_input=100, cached_read=200, visible_output=300),
|
|
1397
|
+
)
|
|
1398
|
+
c_list = [{
|
|
1399
|
+
"oid": oid_day0, "short_oid": oid_day0[:8], "day": "2025-06-15",
|
|
1400
|
+
"epoch_sec": float(day0), "committer_epoch": float(day0),
|
|
1401
|
+
"clock_ts": "2025-06-15T00:00:00+00:00", "lanes": ["Projects"],
|
|
1402
|
+
"repos": ["cohort-repo"], "repo_root": str(repo.resolve()),
|
|
1403
|
+
"subject": "day0 add 10 lines",
|
|
1404
|
+
}]
|
|
1405
|
+
ir_early = build_observatory_ir(
|
|
1406
|
+
sessions=[s_day0], commits=c_list, episodes=[],
|
|
1407
|
+
repo_map={str(repo.resolve()): ("Projects", "cohort-repo")},
|
|
1408
|
+
harvest_stats={}, cache_db=cache_db, discover_repos=False,
|
|
1409
|
+
compute_survival=True, as_of_epoch=float(day0 + 10 * 86400),
|
|
1410
|
+
)
|
|
1411
|
+
ir_matured = build_observatory_ir(
|
|
1412
|
+
sessions=[s_day0], commits=c_list, episodes=[],
|
|
1413
|
+
repo_map={str(repo.resolve()): ("Projects", "cohort-repo")},
|
|
1414
|
+
harvest_stats={}, cache_db=cache_db, discover_repos=False,
|
|
1415
|
+
compute_survival=True, as_of_epoch=float(day100),
|
|
1416
|
+
)
|
|
1417
|
+
self.assertEqual(ir_early["totals"]["durability"]["cohorts"]["t30d"]["matured_commits"], 0)
|
|
1418
|
+
self.assertEqual(ir_matured["totals"]["durability"]["cohorts"]["t30d"]["matured_commits"], 1)
|
|
1419
|
+
self.assertEqual(ir_matured["totals"]["durability"]["cohorts"]["t30d"]["retention_pct"], 100.0)
|
|
1420
|
+
|
|
1421
|
+
def test_recency_single_quiet_commit_never_claims_exact_hook_oid(self):
|
|
1422
|
+
import subprocess
|
|
1423
|
+
from tokenblame.provenance import record_hook_invocation
|
|
1355
1424
|
|
|
1356
|
-
|
|
1425
|
+
with tempfile.TemporaryDirectory() as td:
|
|
1426
|
+
repo = Path(td) / "single-quiet-repo"
|
|
1427
|
+
repo.mkdir()
|
|
1428
|
+
def git(*args: str) -> str:
|
|
1429
|
+
return subprocess.run(["git", "-C", str(repo), *args], check=True, capture_output=True, text=True).stdout.strip()
|
|
1430
|
+
|
|
1431
|
+
git("init", "-b", "main")
|
|
1432
|
+
git("config", "user.name", "Dev")
|
|
1433
|
+
git("config", "user.email", "dev@example.com")
|
|
1434
|
+
(repo / "x.py").write_text("x = 1\n", encoding="utf-8")
|
|
1357
1435
|
git("add", ".")
|
|
1358
|
-
git("commit", "-m", "
|
|
1359
|
-
|
|
1360
|
-
|
|
1361
|
-
|
|
1362
|
-
|
|
1363
|
-
{
|
|
1364
|
-
|
|
1365
|
-
|
|
1366
|
-
|
|
1367
|
-
|
|
1368
|
-
|
|
1369
|
-
|
|
1370
|
-
|
|
1371
|
-
|
|
1372
|
-
|
|
1373
|
-
|
|
1374
|
-
self.assertEqual(
|
|
1375
|
-
self.assertEqual(
|
|
1376
|
-
self.
|
|
1377
|
-
|
|
1436
|
+
git("commit", "-m", "only commit")
|
|
1437
|
+
oid1 = git("rev-parse", "HEAD")
|
|
1438
|
+
|
|
1439
|
+
now_ep = dt.datetime.now(dt.timezone.utc).timestamp()
|
|
1440
|
+
recs = record_hook_invocation(
|
|
1441
|
+
json.dumps({
|
|
1442
|
+
"session_id": "sess-single-quiet",
|
|
1443
|
+
"cwd": str(repo),
|
|
1444
|
+
"tool_name": "Bash",
|
|
1445
|
+
"tool_input": {"command": "git commit -q -m 'only commit'"},
|
|
1446
|
+
"tool_response": {"exitCode": 0, "stdout": ""},
|
|
1447
|
+
}),
|
|
1448
|
+
provider="claude",
|
|
1449
|
+
spool_path=Path(td) / "prov.jsonl",
|
|
1450
|
+
now_epoch=now_ep,
|
|
1451
|
+
)
|
|
1452
|
+
self.assertEqual(len(recs), 1)
|
|
1453
|
+
self.assertEqual(recs[0]["oid_source"], "recency_single")
|
|
1454
|
+
self.assertTrue(recs[0]["ambiguous"])
|
|
1455
|
+
|
|
1456
|
+
s = SessionRecord(
|
|
1457
|
+
session_id="sess-single-quiet", provider="claude", model="claude-opus-5-5",
|
|
1458
|
+
status="MEASURED", bucket_fidelity="4_bucket",
|
|
1459
|
+
day=dt.datetime.now(dt.timezone.utc).strftime("%Y-%m-%d"),
|
|
1460
|
+
timestamp=dt.datetime.now(dt.timezone.utc).isoformat(),
|
|
1461
|
+
epoch_sec=now_ep - 5, cwd=str(repo.resolve()),
|
|
1462
|
+
buckets=TokenBuckets(uncached_input=200, cached_read=400, visible_output=500),
|
|
1463
|
+
)
|
|
1464
|
+
ir = build_observatory_ir(
|
|
1465
|
+
sessions=[s],
|
|
1466
|
+
commits=[{
|
|
1467
|
+
"oid": oid1, "short_oid": oid1[:8], "day": s.day,
|
|
1468
|
+
"epoch_sec": now_ep, "clock_ts": s.timestamp,
|
|
1469
|
+
"lanes": ["Projects"], "repos": ["single-quiet-repo"],
|
|
1470
|
+
"repo_root": str(repo.resolve()), "subject": "only commit",
|
|
1471
|
+
}],
|
|
1472
|
+
episodes=[],
|
|
1473
|
+
repo_map={str(repo.resolve()): ("Projects", "single-quiet-repo")},
|
|
1474
|
+
harvest_stats={},
|
|
1475
|
+
provenance_records=recs,
|
|
1476
|
+
discover_repos=False,
|
|
1477
|
+
)
|
|
1478
|
+
self.assertEqual(ir["totals"]["causality_breakdown"]["EXACT_HOOK_OID"], 0)
|
|
1479
|
+
self.assertEqual(s.causality_tier, "TIME_WINDOW_HEURISTIC")
|
|
1378
1480
|
|
|
1379
1481
|
def test_exit_code_aware_failure_loop_vs_iteration_loop_without_arg_leaks(self):
|
|
1380
|
-
from tokenblame.harvesters import parse_claude_jsonl
|
|
1482
|
+
from tokenblame.harvesters import _classify_tool_outcome, parse_claude_jsonl
|
|
1483
|
+
from tokenblame.store import write_observatory_store
|
|
1484
|
+
|
|
1485
|
+
# Numeric HTTP status=200 and plain strings without explicit exit status MUST stay "unknown"
|
|
1486
|
+
self.assertEqual(_classify_tool_outcome({"status": 200}), "unknown")
|
|
1487
|
+
self.assertEqual(_classify_tool_outcome({"exitCode": 200}), "error")
|
|
1488
|
+
self.assertEqual(_classify_tool_outcome("some output without exit code"), "unknown")
|
|
1489
|
+
self.assertEqual(_classify_tool_outcome({"type": "tool_result", "content": "plain text"}), "unknown")
|
|
1490
|
+
self.assertEqual(_classify_tool_outcome("Exit code 0: ok"), "success")
|
|
1381
1491
|
|
|
1382
|
-
def _write_claude(path: Path,
|
|
1492
|
+
def _write_claude(path: Path, outcomes: list[bool | None], *, reverse_results: bool = False) -> None:
|
|
1383
1493
|
lines = []
|
|
1384
|
-
|
|
1494
|
+
pending_res = []
|
|
1495
|
+
for idx, is_err in enumerate(outcomes, start=1):
|
|
1385
1496
|
tid = f"toolu_{idx}"
|
|
1386
1497
|
lines.append(json.dumps({
|
|
1387
1498
|
"sessionId": path.stem,
|
|
@@ -1399,38 +1510,67 @@ class TestObservatoryAdversarial(unittest.TestCase):
|
|
|
1399
1510
|
"usage": {"input_tokens": 500, "cache_read_input_tokens": 2000, "output_tokens": 1200},
|
|
1400
1511
|
},
|
|
1401
1512
|
}))
|
|
1402
|
-
|
|
1403
|
-
|
|
1404
|
-
|
|
1405
|
-
|
|
1406
|
-
"
|
|
1407
|
-
|
|
1408
|
-
"
|
|
1409
|
-
|
|
1410
|
-
|
|
1411
|
-
|
|
1412
|
-
|
|
1413
|
-
|
|
1414
|
-
|
|
1513
|
+
if is_err is not None:
|
|
1514
|
+
res_line = json.dumps({
|
|
1515
|
+
"sessionId": path.stem,
|
|
1516
|
+
"timestamp": f"2026-11-26T05:0{idx}:05Z",
|
|
1517
|
+
"message": {
|
|
1518
|
+
"role": "user",
|
|
1519
|
+
"content": [{
|
|
1520
|
+
"type": "tool_result",
|
|
1521
|
+
"tool_use_id": tid,
|
|
1522
|
+
"is_error": is_err,
|
|
1523
|
+
"content": "SECRET_STDOUT_LEAK_CANARY exit code 1" if is_err else "SECRET_STDOUT_LEAK_CANARY ok",
|
|
1524
|
+
}],
|
|
1525
|
+
},
|
|
1526
|
+
})
|
|
1527
|
+
if reverse_results:
|
|
1528
|
+
pending_res.append(res_line)
|
|
1529
|
+
else:
|
|
1530
|
+
lines.append(res_line)
|
|
1531
|
+
if reverse_results:
|
|
1532
|
+
lines.extend(reversed(pending_res))
|
|
1415
1533
|
path.write_text("\n".join(lines) + "\n", encoding="utf-8")
|
|
1416
1534
|
|
|
1417
1535
|
with tempfile.TemporaryDirectory() as td:
|
|
1418
1536
|
fail_p = Path(td) / "sess-fail.jsonl"
|
|
1419
1537
|
ok_p = Path(td) / "sess-iter.jsonl"
|
|
1420
|
-
|
|
1421
|
-
|
|
1538
|
+
unk_p = Path(td) / "sess-unknown.jsonl"
|
|
1539
|
+
# Out-of-order parallel results still pair accurately by call ID
|
|
1540
|
+
_write_claude(fail_p, [True, True, True, True, True, False], reverse_results=True)
|
|
1541
|
+
_write_claude(ok_p, [False, False, False, False, False, False], reverse_results=True)
|
|
1542
|
+
# Missing / unobserved results (None) MUST NOT be classified as iteration/success!
|
|
1543
|
+
_write_claude(unk_p, [None, None, None, None, None, False])
|
|
1422
1544
|
|
|
1423
1545
|
rec_fail = parse_claude_jsonl(fail_p)[0]
|
|
1424
1546
|
rec_iter = parse_claude_jsonl(ok_p)[0]
|
|
1547
|
+
rec_unk = parse_claude_jsonl(unk_p)[0]
|
|
1425
1548
|
|
|
1426
1549
|
self.assertEqual(rec_fail.forensics["loop_kind"], "failure")
|
|
1427
|
-
self.assertIn("FAILURE_LOOP(Bash:pytest x6, err=5)", rec_fail.forensics["loop_warning"])
|
|
1428
|
-
self.assertEqual(rec_fail.forensics["
|
|
1429
|
-
self.
|
|
1430
|
-
self.assertNotIn("SECRET_STDOUT_LEAK_CANARY", json.dumps(rec_fail.forensics))
|
|
1550
|
+
self.assertIn("FAILURE_LOOP(Bash:pytest x6, err=5/6)", rec_fail.forensics["loop_warning"])
|
|
1551
|
+
self.assertEqual(rec_fail.forensics["loop_outcomes"]["observed_error"], 5)
|
|
1552
|
+
self.assertEqual(rec_fail.forensics["loop_outcomes"]["observed_success"], 1)
|
|
1431
1553
|
|
|
1432
1554
|
self.assertEqual(rec_iter.forensics["loop_kind"], "iteration")
|
|
1433
|
-
self.assertIn("ITERATION_LOOP(Bash:pytest x6)", rec_iter.forensics["loop_warning"])
|
|
1555
|
+
self.assertIn("ITERATION_LOOP(Bash:pytest x6, ok=6/6)", rec_iter.forensics["loop_warning"])
|
|
1556
|
+
|
|
1557
|
+
# 5 unknown + 1 ok -> coverage 1/6 (< 50%) -> MUST stay unclassified, NOT iteration!
|
|
1558
|
+
self.assertEqual(rec_unk.forensics["loop_kind"], "unclassified")
|
|
1559
|
+
self.assertEqual(rec_unk.forensics["loop_outcomes"]["unknown_outcome"], 5)
|
|
1560
|
+
|
|
1561
|
+
# End-to-end secret canary check across IR, HTML, and SQLite
|
|
1562
|
+
ir = build_observatory_ir(
|
|
1563
|
+
sessions=[rec_fail, rec_iter, rec_unk], commits=[], episodes=[],
|
|
1564
|
+
repo_map={}, harvest_stats={}, discover_repos=False,
|
|
1565
|
+
)
|
|
1566
|
+
html_out = render_observatory_html(ir)
|
|
1567
|
+
db_path = Path(td) / "obs.sqlite"
|
|
1568
|
+
write_observatory_store(db_path, ir, [rec_fail, rec_iter, rec_unk], [], [])
|
|
1569
|
+
db_raw = db_path.read_bytes().decode("utf-8", errors="ignore")
|
|
1570
|
+
for canary in ("SUPER_SECRET_ARG", "SECRET_STDOUT_LEAK_CANARY"):
|
|
1571
|
+
self.assertNotIn(canary, json.dumps(ir))
|
|
1572
|
+
self.assertNotIn(canary, html_out)
|
|
1573
|
+
self.assertNotIn(canary, db_raw)
|
|
1434
1574
|
|
|
1435
1575
|
|
|
1436
1576
|
if __name__ == "__main__":
|
|
@@ -16,7 +16,7 @@ from tokenblame.schema import SessionRecord, TokenBuckets, resolve_local_tz
|
|
|
16
16
|
|
|
17
17
|
SEOUL_TZ = ZoneInfo("Asia/Seoul")
|
|
18
18
|
CACHE_SCHEMA_VERSION = 2
|
|
19
|
-
PARSER_REVISION = "v2.
|
|
19
|
+
PARSER_REVISION = "v2.2"
|
|
20
20
|
COMMIT_STDOUT_RE = re.compile(
|
|
21
21
|
r"\[(?:[\w./-]+(?:\s+\(root-commit\))?|detached HEAD)\s+([0-9a-f]{7,40})\]\s+\S"
|
|
22
22
|
)
|
|
@@ -120,35 +120,85 @@ def _safe_tool_label(raw_name: Any, raw_input: Any = None) -> Optional[str]:
|
|
|
120
120
|
_EXIT_CODE_RE = re.compile(r"(?:exit(?:ed with)? code|exit_code|returncode)\s*[:=]?\s*(-?\d+)", re.IGNORECASE)
|
|
121
121
|
|
|
122
122
|
|
|
123
|
-
def
|
|
124
|
-
"""
|
|
123
|
+
def _classify_tool_outcome(text_or_obj: Any, *, explicit_result_present: bool = True) -> str:
|
|
124
|
+
"""Classify a paired tool result into `'error' | 'success' | 'unknown'` without storing content.
|
|
125
|
+
|
|
126
|
+
Never treats numeric HTTP `status` (e.g. `status=200`) as a shell exit code, and never counts
|
|
127
|
+
unobserved / missing results as `'success'`.
|
|
128
|
+
"""
|
|
129
|
+
if not explicit_result_present or text_or_obj is None:
|
|
130
|
+
return "unknown"
|
|
125
131
|
if isinstance(text_or_obj, dict):
|
|
126
132
|
if text_or_obj.get("is_error") is True or text_or_obj.get("isError") is True:
|
|
127
|
-
return
|
|
128
|
-
|
|
129
|
-
|
|
133
|
+
return "error"
|
|
134
|
+
raw_status = text_or_obj.get("status")
|
|
135
|
+
if isinstance(raw_status, str):
|
|
136
|
+
st_l = raw_status.strip().lower()
|
|
137
|
+
if st_l in ("error", "failed", "failure"):
|
|
138
|
+
return "error"
|
|
139
|
+
if st_l in ("ok", "success", "succeeded", "completed"):
|
|
140
|
+
return "success"
|
|
130
141
|
for k in ("exitCode", "exit_code", "returncode"):
|
|
131
142
|
v = text_or_obj.get(k)
|
|
132
|
-
if isinstance(v, int) and v
|
|
133
|
-
return
|
|
134
|
-
|
|
143
|
+
if isinstance(v, int) and not isinstance(v, bool):
|
|
144
|
+
return "error" if v != 0 else "success"
|
|
145
|
+
if text_or_obj.get("is_error") is False or text_or_obj.get("isError") is False:
|
|
146
|
+
# Also check nested content/output text for explicit shell exit code
|
|
147
|
+
for tk in ("content", "output", "text"):
|
|
148
|
+
tv = text_or_obj.get(tk)
|
|
149
|
+
if isinstance(tv, str):
|
|
150
|
+
sub = _classify_tool_outcome(tv, explicit_result_present=True)
|
|
151
|
+
if sub == "error":
|
|
152
|
+
return "error"
|
|
153
|
+
return "success"
|
|
154
|
+
for tk in ("content", "output", "result", "text"):
|
|
155
|
+
if tk in text_or_obj and text_or_obj[tk] is not None:
|
|
156
|
+
return _classify_tool_outcome(text_or_obj[tk], explicit_result_present=True)
|
|
157
|
+
return "unknown"
|
|
158
|
+
if isinstance(text_or_obj, list):
|
|
159
|
+
saw_explicit_ok = False
|
|
160
|
+
for item in text_or_obj:
|
|
161
|
+
if isinstance(item, dict) and isinstance(item.get("text"), str):
|
|
162
|
+
sub = _classify_tool_outcome(item["text"], explicit_result_present=True)
|
|
163
|
+
if sub == "error":
|
|
164
|
+
return "error"
|
|
165
|
+
if sub == "success":
|
|
166
|
+
saw_explicit_ok = True
|
|
167
|
+
elif isinstance(item, str):
|
|
168
|
+
sub = _classify_tool_outcome(item, explicit_result_present=True)
|
|
169
|
+
if sub == "error":
|
|
170
|
+
return "error"
|
|
171
|
+
if sub == "success":
|
|
172
|
+
saw_explicit_ok = True
|
|
173
|
+
return "success" if saw_explicit_ok else "unknown"
|
|
135
174
|
if isinstance(text_or_obj, str):
|
|
136
175
|
m = _EXIT_CODE_RE.search(text_or_obj[:400])
|
|
137
176
|
if m:
|
|
138
177
|
try:
|
|
139
|
-
return int(m.group(1)) != 0
|
|
178
|
+
return "error" if int(m.group(1)) != 0 else "success"
|
|
140
179
|
except ValueError:
|
|
141
|
-
return
|
|
142
|
-
|
|
180
|
+
return "unknown"
|
|
181
|
+
return "unknown"
|
|
182
|
+
return "unknown"
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def _extract_nonzero_exit(text_or_obj: Any) -> bool:
|
|
186
|
+
"""Backward-compatible boolean helper returning True iff outcome is `'error'`."""
|
|
187
|
+
return _classify_tool_outcome(text_or_obj, explicit_result_present=True) == "error"
|
|
143
188
|
|
|
144
189
|
|
|
145
190
|
def _build_forensics(
|
|
146
191
|
turns: list[tuple[int, int, int, int, list[str]]],
|
|
147
192
|
rec: SessionRecord,
|
|
148
193
|
tool_errors: Optional[Counter[str]] = None,
|
|
194
|
+
tool_successes: Optional[Counter[str]] = None,
|
|
149
195
|
observed_results: int = 0,
|
|
150
196
|
) -> Optional[dict[str, Any]]:
|
|
151
|
-
"""Summarize top 3 turn spikes, safe tool-basename counts, and
|
|
197
|
+
"""Summarize top 3 turn spikes, safe tool-basename counts, and observed-outcome loop classifications.
|
|
198
|
+
|
|
199
|
+
Strict pipeline: paired call-ID outcomes -> deduplicated error/success/unknown counts -> classification.
|
|
200
|
+
Never treats missing/unknown outcomes as success and never claims productivity.
|
|
201
|
+
"""
|
|
152
202
|
if not turns:
|
|
153
203
|
return None
|
|
154
204
|
tool_counter: Counter[str] = Counter()
|
|
@@ -169,6 +219,7 @@ def _build_forensics(
|
|
|
169
219
|
|
|
170
220
|
loop_warning: Optional[str] = None
|
|
171
221
|
loop_kind: Optional[str] = None
|
|
222
|
+
loop_outcome_meta: Optional[dict[str, Any]] = None
|
|
172
223
|
best_loop: Optional[tuple[int, str]] = None
|
|
173
224
|
for lbl, cnt in tool_counter.items():
|
|
174
225
|
streak = max_streak[lbl]
|
|
@@ -179,14 +230,28 @@ def _build_forensics(
|
|
|
179
230
|
best_loop = (cand_score, lbl)
|
|
180
231
|
if best_loop is not None:
|
|
181
232
|
lbl = best_loop[1]
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
233
|
+
obs_err = int((tool_errors or {}).get(lbl, 0))
|
|
234
|
+
obs_ok = int((tool_successes or {}).get(lbl, 0))
|
|
235
|
+
obs_tot = obs_err + obs_ok
|
|
236
|
+
tot_calls = max(1, tool_counter[lbl])
|
|
237
|
+
unknown_cnt = max(0, tot_calls - obs_tot)
|
|
238
|
+
coverage = round(min(1.0, obs_tot / tot_calls), 4)
|
|
239
|
+
err_ratio = round(obs_err / obs_tot, 4) if obs_tot > 0 else None
|
|
240
|
+
loop_outcome_meta = {
|
|
241
|
+
"tool": lbl,
|
|
242
|
+
"total_calls": tot_calls,
|
|
243
|
+
"observed_error": obs_err,
|
|
244
|
+
"observed_success": obs_ok,
|
|
245
|
+
"unknown_outcome": unknown_cnt,
|
|
246
|
+
"result_coverage": coverage,
|
|
247
|
+
"error_ratio_observed": err_ratio,
|
|
248
|
+
}
|
|
249
|
+
if obs_err >= 3 and obs_tot > 0 and (obs_err / obs_tot) >= 0.4:
|
|
185
250
|
loop_kind = "failure"
|
|
186
|
-
loop_warning = f"FAILURE_LOOP({lbl} x{best_loop[0]}, err={
|
|
187
|
-
elif
|
|
251
|
+
loop_warning = f"FAILURE_LOOP({lbl} x{best_loop[0]}, err={obs_err}/{obs_tot})"
|
|
252
|
+
elif obs_tot >= max(2, (tot_calls + 1) // 2) and obs_err == 0:
|
|
188
253
|
loop_kind = "iteration"
|
|
189
|
-
loop_warning = f"ITERATION_LOOP({lbl} x{best_loop[0]})"
|
|
254
|
+
loop_warning = f"ITERATION_LOOP({lbl} x{best_loop[0]}, ok={obs_ok}/{tot_calls})"
|
|
190
255
|
else:
|
|
191
256
|
loop_kind = "unclassified"
|
|
192
257
|
loop_warning = f"RETRY_LOOP({lbl} x{best_loop[0]})"
|
|
@@ -211,6 +276,8 @@ def _build_forensics(
|
|
|
211
276
|
}
|
|
212
277
|
if loop_kind is not None:
|
|
213
278
|
out_fx["loop_kind"] = loop_kind
|
|
279
|
+
if loop_outcome_meta is not None:
|
|
280
|
+
out_fx["loop_outcomes"] = loop_outcome_meta
|
|
214
281
|
if err_summary:
|
|
215
282
|
out_fx["tool_errors"] = err_summary
|
|
216
283
|
return out_fx
|
|
@@ -505,7 +572,7 @@ def parse_claude_jsonl(path: Path) -> list[SessionRecord]:
|
|
|
505
572
|
session_id = path.stem
|
|
506
573
|
transcript_oids: list[str] = []
|
|
507
574
|
tool_id_to_label: dict[str, str] = {}
|
|
508
|
-
|
|
575
|
+
paired_outcomes: dict[str, tuple[str, str]] = {}
|
|
509
576
|
observed_results = 0
|
|
510
577
|
|
|
511
578
|
try:
|
|
@@ -531,11 +598,17 @@ def parse_claude_jsonl(path: Path) -> list[SessionRecord]:
|
|
|
531
598
|
if isinstance(content, list):
|
|
532
599
|
for blk in content:
|
|
533
600
|
if isinstance(blk, dict) and blk.get("type") == "tool_result":
|
|
534
|
-
observed_results += 1
|
|
535
601
|
tid = str(blk.get("tool_use_id") or "")
|
|
536
|
-
lbl = tool_id_to_label.get(tid)
|
|
537
|
-
if
|
|
538
|
-
|
|
602
|
+
lbl = tool_id_to_label.get(tid) if tid else None
|
|
603
|
+
if not tid or not lbl:
|
|
604
|
+
continue
|
|
605
|
+
outcome = _classify_tool_outcome(blk, explicit_result_present=True)
|
|
606
|
+
if outcome in ("error", "success"):
|
|
607
|
+
# Deduplicate repeated tool_result blocks by call ID; error dominates if conflicting
|
|
608
|
+
prev = paired_outcomes.get(tid)
|
|
609
|
+
if prev is None or (prev[1] != "error" and outcome == "error"):
|
|
610
|
+
paired_outcomes[tid] = (lbl, outcome)
|
|
611
|
+
observed_results = len(paired_outcomes)
|
|
539
612
|
if not has_usage:
|
|
540
613
|
continue
|
|
541
614
|
model = msg.get("model")
|
|
@@ -620,9 +693,21 @@ def parse_claude_jsonl(path: Path) -> list[SessionRecord]:
|
|
|
620
693
|
if branch and not rec.git_branch:
|
|
621
694
|
rec.git_branch = branch
|
|
622
695
|
|
|
696
|
+
tool_errors: Counter[str] = Counter()
|
|
697
|
+
tool_successes: Counter[str] = Counter()
|
|
698
|
+
for lbl, outcome in paired_outcomes.values():
|
|
699
|
+
if outcome == "error":
|
|
700
|
+
tool_errors[lbl] += 1
|
|
701
|
+
elif outcome == "success":
|
|
702
|
+
tool_successes[lbl] += 1
|
|
703
|
+
|
|
623
704
|
for key, rec in grouped.items():
|
|
624
705
|
rec.forensics = _build_forensics(
|
|
625
|
-
turns_by_key[key],
|
|
706
|
+
turns_by_key[key],
|
|
707
|
+
rec,
|
|
708
|
+
tool_errors=tool_errors,
|
|
709
|
+
tool_successes=tool_successes,
|
|
710
|
+
observed_results=observed_results,
|
|
626
711
|
)
|
|
627
712
|
out_recs = list(grouped.values())
|
|
628
713
|
if out_recs and transcript_oids:
|
|
@@ -644,7 +729,7 @@ def parse_codex_rollout(path: Path) -> list[SessionRecord]:
|
|
|
644
729
|
turns_by_key: dict[tuple[str, str], list[tuple[int, int, int, int, list[str]]]] = {}
|
|
645
730
|
pending_tools: list[str] = []
|
|
646
731
|
call_id_to_label: dict[str, str] = {}
|
|
647
|
-
|
|
732
|
+
paired_outcomes: dict[str, tuple[str, str]] = {}
|
|
648
733
|
observed_results = 0
|
|
649
734
|
transcript_oids: list[str] = []
|
|
650
735
|
|
|
@@ -683,11 +768,17 @@ def parse_codex_rollout(path: Path) -> list[SessionRecord]:
|
|
|
683
768
|
if cid:
|
|
684
769
|
call_id_to_label[cid] = lbl
|
|
685
770
|
elif ev_type == "response_item" and payload.get("type") in ("function_call_output", "custom_tool_call_output"):
|
|
686
|
-
observed_results += 1
|
|
687
771
|
cid = str(payload.get("call_id") or "")
|
|
688
|
-
lbl = call_id_to_label.get(cid)
|
|
689
|
-
if
|
|
690
|
-
|
|
772
|
+
lbl = call_id_to_label.get(cid) if cid else None
|
|
773
|
+
if cid and lbl:
|
|
774
|
+
outcome = _classify_tool_outcome(payload, explicit_result_present=True)
|
|
775
|
+
if outcome == "unknown" and "output" in payload:
|
|
776
|
+
outcome = _classify_tool_outcome(payload.get("output"), explicit_result_present=True)
|
|
777
|
+
if outcome in ("error", "success"):
|
|
778
|
+
prev = paired_outcomes.get(cid)
|
|
779
|
+
if prev is None or (prev[1] != "error" and outcome == "error"):
|
|
780
|
+
paired_outcomes[cid] = (lbl, outcome)
|
|
781
|
+
observed_results = len(paired_outcomes)
|
|
691
782
|
elif ev_type == "event_msg" and payload.get("type") == "token_count":
|
|
692
783
|
info = payload.get("info")
|
|
693
784
|
if not isinstance(info, dict):
|
|
@@ -748,9 +839,21 @@ def parse_codex_rollout(path: Path) -> list[SessionRecord]:
|
|
|
748
839
|
except OSError:
|
|
749
840
|
return []
|
|
750
841
|
|
|
842
|
+
tool_errors: Counter[str] = Counter()
|
|
843
|
+
tool_successes: Counter[str] = Counter()
|
|
844
|
+
for lbl, outcome in paired_outcomes.values():
|
|
845
|
+
if outcome == "error":
|
|
846
|
+
tool_errors[lbl] += 1
|
|
847
|
+
elif outcome == "success":
|
|
848
|
+
tool_successes[lbl] += 1
|
|
849
|
+
|
|
751
850
|
for key, rec in grouped.items():
|
|
752
851
|
rec.forensics = _build_forensics(
|
|
753
|
-
turns_by_key[key],
|
|
852
|
+
turns_by_key[key],
|
|
853
|
+
rec,
|
|
854
|
+
tool_errors=tool_errors,
|
|
855
|
+
tool_successes=tool_successes,
|
|
856
|
+
observed_results=observed_results,
|
|
754
857
|
)
|
|
755
858
|
out_recs = list(grouped.values())
|
|
756
859
|
if out_recs and transcript_oids:
|
|
@@ -770,7 +873,7 @@ def parse_gemini_cli_chat(path: Path) -> list[SessionRecord]:
|
|
|
770
873
|
session_id = d.get("sessionId") or path.stem
|
|
771
874
|
grouped: dict[tuple[str, str], SessionRecord] = {}
|
|
772
875
|
turns_by_key: dict[tuple[str, str], list[tuple[int, int, int, int, list[str]]]] = {}
|
|
773
|
-
|
|
876
|
+
paired_outcomes: dict[str, tuple[str, str]] = {}
|
|
774
877
|
observed_results = 0
|
|
775
878
|
transcript_oids: list[str] = []
|
|
776
879
|
|
|
@@ -818,20 +921,38 @@ def parse_gemini_cli_chat(path: Path) -> list[SessionRecord]:
|
|
|
818
921
|
rec.buckets.visible_output += outp + tool
|
|
819
922
|
rec.buckets.reasoning_output += thoughts
|
|
820
923
|
t_labels: list[str] = []
|
|
821
|
-
for tc in m.get("toolCalls") or []:
|
|
924
|
+
for tc_idx, tc in enumerate(m.get("toolCalls") or []):
|
|
822
925
|
if isinstance(tc, dict):
|
|
823
926
|
lbl = _safe_tool_label(tc.get("name"), tc.get("args"))
|
|
824
927
|
if lbl and lbl not in t_labels:
|
|
825
928
|
t_labels.append(lbl)
|
|
826
|
-
if "status" in tc or "result" in tc:
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
929
|
+
if lbl and ("status" in tc or "result" in tc):
|
|
930
|
+
tc_id = str(tc.get("id") or tc.get("callId") or f"msg-{rec.request_count}-tc-{tc_idx}")
|
|
931
|
+
outcome = _classify_tool_outcome(tc, explicit_result_present=True)
|
|
932
|
+
if outcome == "unknown" and "result" in tc:
|
|
933
|
+
outcome = _classify_tool_outcome(tc.get("result"), explicit_result_present=True)
|
|
934
|
+
if outcome in ("error", "success"):
|
|
935
|
+
prev = paired_outcomes.get(tc_id)
|
|
936
|
+
if prev is None or (prev[1] != "error" and outcome == "error"):
|
|
937
|
+
paired_outcomes[tc_id] = (lbl, outcome)
|
|
938
|
+
observed_results = len(paired_outcomes)
|
|
830
939
|
turns_by_key[key].append((rec.request_count, u_in, cached, gen_out, t_labels))
|
|
831
940
|
|
|
941
|
+
tool_errors: Counter[str] = Counter()
|
|
942
|
+
tool_successes: Counter[str] = Counter()
|
|
943
|
+
for lbl, outcome in paired_outcomes.values():
|
|
944
|
+
if outcome == "error":
|
|
945
|
+
tool_errors[lbl] += 1
|
|
946
|
+
elif outcome == "success":
|
|
947
|
+
tool_successes[lbl] += 1
|
|
948
|
+
|
|
832
949
|
for key, rec in grouped.items():
|
|
833
950
|
rec.forensics = _build_forensics(
|
|
834
|
-
turns_by_key[key],
|
|
951
|
+
turns_by_key[key],
|
|
952
|
+
rec,
|
|
953
|
+
tool_errors=tool_errors,
|
|
954
|
+
tool_successes=tool_successes,
|
|
955
|
+
observed_results=observed_results,
|
|
835
956
|
)
|
|
836
957
|
out_recs = list(grouped.values())
|
|
837
958
|
if out_recs and transcript_oids:
|
|
@@ -930,7 +1051,7 @@ def parse_antigravity_transcript(
|
|
|
930
1051
|
seen_tok_steps: set[tuple[Any, Any, int, int, int]] = set()
|
|
931
1052
|
grouped: dict[tuple[str, str], SessionRecord] = {}
|
|
932
1053
|
turns_by_key: dict[tuple[str, str], list[tuple[int, int, int, int, list[str]]]] = {}
|
|
933
|
-
|
|
1054
|
+
paired_outcomes: dict[str, tuple[str, str]] = {}
|
|
934
1055
|
observed_results = 0
|
|
935
1056
|
transcript_oids: list[str] = []
|
|
936
1057
|
|
|
@@ -286,17 +286,18 @@ def _fetch_repo_commits_cached(
|
|
|
286
286
|
try:
|
|
287
287
|
proc = subprocess.run(
|
|
288
288
|
["git", "-C", repo_root, "log", "--all", "--no-merges", f"--since={since}",
|
|
289
|
-
"--format=%H\x1f%at\x1f%s", "-n", "8000"],
|
|
289
|
+
"--format=%H\x1f%at\x1f%ct\x1f%s", "-n", "8000"],
|
|
290
290
|
capture_output=True, text=True, timeout=8, check=False,
|
|
291
291
|
)
|
|
292
292
|
if proc.returncode == 0:
|
|
293
293
|
for line in proc.stdout.splitlines():
|
|
294
|
-
parts = line.split("\x1f",
|
|
295
|
-
if len(parts) !=
|
|
294
|
+
parts = line.split("\x1f", 3)
|
|
295
|
+
if len(parts) != 4:
|
|
296
296
|
continue
|
|
297
|
-
oid, at_str, subj = parts
|
|
297
|
+
oid, at_str, ct_str, subj = parts
|
|
298
298
|
try:
|
|
299
299
|
ep_sec = float(at_str)
|
|
300
|
+
committer_ep = float(ct_str)
|
|
300
301
|
local_tz = resolve_local_tz()
|
|
301
302
|
day = dt.datetime.fromtimestamp(ep_sec, tz=dt.timezone.utc).astimezone(local_tz).strftime("%Y-%m-%d")
|
|
302
303
|
iso_ts = dt.datetime.fromtimestamp(ep_sec, tz=dt.timezone.utc).astimezone(local_tz).isoformat()
|
|
@@ -307,6 +308,7 @@ def _fetch_repo_commits_cached(
|
|
|
307
308
|
"short_oid": oid[:8],
|
|
308
309
|
"day": day,
|
|
309
310
|
"epoch_sec": ep_sec,
|
|
311
|
+
"committer_epoch": committer_ep,
|
|
310
312
|
"clock_ts": iso_ts,
|
|
311
313
|
"lanes": [lane],
|
|
312
314
|
"repos": [repo_name],
|
|
@@ -463,6 +465,7 @@ def build_observatory_ir(
|
|
|
463
465
|
discover_repos: bool = True,
|
|
464
466
|
compute_survival: Optional[bool] = None,
|
|
465
467
|
nocheat_verdicts: Optional[list[dict[str, Any]]] = None,
|
|
468
|
+
as_of_epoch: Optional[float] = None,
|
|
466
469
|
) -> dict[str, Any]:
|
|
467
470
|
"""Perform full local Git discovery + 3-way attribution join with 4-tier classification."""
|
|
468
471
|
# Merge Orca worktree paths + provenance repo paths into full repo_map if enabled
|
|
@@ -570,7 +573,8 @@ def build_observatory_ir(
|
|
|
570
573
|
for pr in provenance_records or []:
|
|
571
574
|
raw_oid = str(pr.get("commit_oid") or "")
|
|
572
575
|
pr_repo = str(pr.get("repo_root") or "").rstrip("/")
|
|
573
|
-
|
|
576
|
+
oid_src = str(pr.get("oid_source") or "")
|
|
577
|
+
if not raw_oid or pr.get("ambiguous") is True or oid_src in ("recency_single", "recency_ambiguous"):
|
|
574
578
|
continue
|
|
575
579
|
matched_oids: list[str] = []
|
|
576
580
|
if raw_oid in commits_by_oid:
|
|
@@ -745,7 +749,9 @@ def build_observatory_ir(
|
|
|
745
749
|
ai_oids_by_repo: dict[str, list[str]] = {}
|
|
746
750
|
ai_commits_all_by_repo: dict[str, list[dict[str, Any]]] = {}
|
|
747
751
|
max_commit_ep = max((float(c.get("epoch_sec") or 0.0) for c in all_commits), default=0.0)
|
|
748
|
-
|
|
752
|
+
eff_as_of_ep = float(as_of_epoch) if as_of_epoch is not None else dt.datetime.now(dt.timezone.utc).timestamp()
|
|
753
|
+
as_of_day = dt.datetime.fromtimestamp(eff_as_of_ep, tz=dt.timezone.utc).strftime("%Y-%m-%d")
|
|
754
|
+
cutoff_30d_ep = eff_as_of_ep - (30.0 * 86400.0) if eff_as_of_ep > 0 else 0.0
|
|
749
755
|
|
|
750
756
|
for s in sessions:
|
|
751
757
|
if s.status == "MEASURED":
|
|
@@ -806,21 +812,25 @@ def build_observatory_ir(
|
|
|
806
812
|
continue
|
|
807
813
|
if not head_oid:
|
|
808
814
|
continue
|
|
809
|
-
|
|
810
|
-
|
|
815
|
+
recent_ai = ai_oids_by_repo.get(rroot, [])
|
|
816
|
+
all_ai_repo = ai_commits_all_by_repo.get(rroot, [])
|
|
817
|
+
oids_sig_src = "|".join(sorted(recent_ai)) + "||" + "|".join(sorted(str(x.get("oid") or "") for x in all_ai_repo))
|
|
818
|
+
oids_digest = hashlib.sha256(oids_sig_src.encode("utf-8")).hexdigest()[:12]
|
|
819
|
+
surv_cache_key = f"{head_oid}|asof:{as_of_day}|oids:{oids_digest}"
|
|
820
|
+
cached_surv = scache.get_repo_survival(rroot, surv_cache_key) if scache else None
|
|
821
|
+
if cached_surv is None or cached_surv.get("cohort_schema") != "historical_v2":
|
|
811
822
|
rev_map = (cached_surv or {}).get("reverts") if cached_surv else scan_repo_reverts(rroot, commits_grouped_by_repo[rroot])
|
|
812
|
-
recent_ai = ai_oids_by_repo.get(rroot, [])
|
|
813
823
|
lsurv = (
|
|
814
|
-
|
|
815
|
-
if
|
|
816
|
-
else
|
|
824
|
+
measure_30d_line_survival(rroot, recent_ai, snapshot_oid=head_oid)
|
|
825
|
+
if recent_ai
|
|
826
|
+
else {"added_lines": 0, "surviving_lines": 0, "unobserved_lines": 0}
|
|
817
827
|
)
|
|
818
828
|
cohorts_r = measure_cohort_line_survival(
|
|
819
|
-
rroot,
|
|
829
|
+
rroot, all_ai_repo, as_of_epoch=eff_as_of_ep, ref=head_oid
|
|
820
830
|
)
|
|
821
|
-
cached_surv = {"reverts": rev_map, "line_survival": lsurv, "cohorts": cohorts_r}
|
|
831
|
+
cached_surv = {"cohort_schema": "historical_v2", "as_of_day": as_of_day, "reverts": rev_map, "line_survival": lsurv, "cohorts": cohorts_r}
|
|
822
832
|
if scache is not None:
|
|
823
|
-
scache.put_repo_survival(rroot,
|
|
833
|
+
scache.put_repo_survival(rroot, surv_cache_key, cached_surv)
|
|
824
834
|
global_reverts.update(cached_surv.get("reverts") or {})
|
|
825
835
|
ls = cached_surv.get("line_survival") or {}
|
|
826
836
|
r_add = int(ls.get("added_lines") or 0)
|
|
@@ -338,7 +338,7 @@ def record_hook_invocation(
|
|
|
338
338
|
if not commits:
|
|
339
339
|
return []
|
|
340
340
|
oid_source = "recency_single"
|
|
341
|
-
ambiguous =
|
|
341
|
+
ambiguous = True
|
|
342
342
|
if stdout_oids:
|
|
343
343
|
matched = [
|
|
344
344
|
c for c in commits
|
|
@@ -347,6 +347,7 @@ def record_hook_invocation(
|
|
|
347
347
|
if matched:
|
|
348
348
|
commits = matched
|
|
349
349
|
oid_source = "stdout_oid"
|
|
350
|
+
ambiguous = False
|
|
350
351
|
else:
|
|
351
352
|
return []
|
|
352
353
|
elif command_hint == "git commit" and len(commits) > 1:
|
|
@@ -354,6 +355,10 @@ def record_hook_invocation(
|
|
|
354
355
|
commits = commits[:1]
|
|
355
356
|
oid_source = "recency_ambiguous"
|
|
356
357
|
ambiguous = True
|
|
358
|
+
elif len(commits) > 1:
|
|
359
|
+
commits = commits[:1]
|
|
360
|
+
oid_source = "recency_ambiguous"
|
|
361
|
+
ambiguous = True
|
|
357
362
|
|
|
358
363
|
env_map = os.environ if env is None else env
|
|
359
364
|
session_id = str(payload.get("session_id") or payload.get("sessionId") or payload.get("thread_id") or "")
|
|
@@ -542,8 +542,10 @@ def render_observatory_html(ir: dict[str, Any], *, view_mode: str = "auto") -> s
|
|
|
542
542
|
t30 = cohorts.get("t30d") or {}
|
|
543
543
|
line_surv = dur.get("line_survival_30d_pct")
|
|
544
544
|
if t30.get("retention_pct") is not None:
|
|
545
|
+
unobs_c = int(t30.get("unobserved_lines") or 0)
|
|
546
|
+
unobs_s = f", {unobs_c} unobserved" if unobs_c else ""
|
|
545
547
|
line_surv_txt = (
|
|
546
|
-
f"t+30d
|
|
548
|
+
f"t+30d snapshot: {t30['retention_pct']}% ({t30.get('matured_commits', 0)} matured, {t30.get('not_yet_commits', 0)} notYet{unobs_s})"
|
|
547
549
|
)
|
|
548
550
|
elif line_surv is not None:
|
|
549
551
|
ny = int(t30.get("not_yet_commits") or 0)
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"""Post-commit revert detection and cached
|
|
1
|
+
"""Post-commit revert detection and cached line-level survival analysis (HEAD & historical fixed-horizon)."""
|
|
2
2
|
from __future__ import annotations
|
|
3
3
|
|
|
4
4
|
from collections import Counter, defaultdict
|
|
@@ -6,7 +6,7 @@ import os
|
|
|
6
6
|
from pathlib import Path
|
|
7
7
|
import re
|
|
8
8
|
import subprocess
|
|
9
|
-
from typing import Any
|
|
9
|
+
from typing import Any, Optional
|
|
10
10
|
|
|
11
11
|
REVERT_BODY_RE = re.compile(r"This reverts commit ([0-9a-f]{7,40})\b", re.IGNORECASE)
|
|
12
12
|
REVERT_SUBJ_RE = re.compile(r'^Revert\s+"(.+)"\s*$')
|
|
@@ -26,8 +26,68 @@ def _is_substantive_line(norm: str) -> bool:
|
|
|
26
26
|
return len(norm) >= 10 and any(ch.isalnum() for ch in norm)
|
|
27
27
|
|
|
28
28
|
|
|
29
|
-
def
|
|
30
|
-
"""
|
|
29
|
+
def _resolve_ref_oid(repo_root: str, ref: str = "HEAD") -> Optional[str]:
|
|
30
|
+
"""Resolve a branch/ref/OID once to its canonical 40-char commit OID."""
|
|
31
|
+
try:
|
|
32
|
+
proc = subprocess.run(
|
|
33
|
+
["git", "--no-optional-locks", "-C", repo_root, "rev-parse", "--verify", f"{ref}^{{commit}}"],
|
|
34
|
+
capture_output=True,
|
|
35
|
+
text=True,
|
|
36
|
+
timeout=2,
|
|
37
|
+
check=False,
|
|
38
|
+
)
|
|
39
|
+
if proc.returncode == 0:
|
|
40
|
+
oid = proc.stdout.strip()
|
|
41
|
+
return oid if oid else None
|
|
42
|
+
except Exception:
|
|
43
|
+
pass
|
|
44
|
+
return None
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _ls_tree_blobs(repo_root: str, snapshot_oid: str, rel_paths: list[str]) -> Optional[dict[str, int]]:
|
|
48
|
+
"""Inspect blob existence and byte size strictly inside `snapshot_oid` (zero working-tree reads)."""
|
|
49
|
+
if not rel_paths:
|
|
50
|
+
return {}
|
|
51
|
+
try:
|
|
52
|
+
proc = subprocess.run(
|
|
53
|
+
[
|
|
54
|
+
"git",
|
|
55
|
+
"--no-optional-locks",
|
|
56
|
+
"-C",
|
|
57
|
+
repo_root,
|
|
58
|
+
"ls-tree",
|
|
59
|
+
"-l",
|
|
60
|
+
"-z",
|
|
61
|
+
snapshot_oid,
|
|
62
|
+
"--",
|
|
63
|
+
*rel_paths,
|
|
64
|
+
],
|
|
65
|
+
capture_output=True,
|
|
66
|
+
text=True,
|
|
67
|
+
timeout=3,
|
|
68
|
+
check=False,
|
|
69
|
+
)
|
|
70
|
+
if proc.returncode != 0:
|
|
71
|
+
return None
|
|
72
|
+
except Exception:
|
|
73
|
+
return None
|
|
74
|
+
|
|
75
|
+
sizes: dict[str, int] = {}
|
|
76
|
+
for rec in proc.stdout.split("\x00"):
|
|
77
|
+
if not rec or "\t" not in rec:
|
|
78
|
+
continue
|
|
79
|
+
meta, path = rec.split("\t", 1)
|
|
80
|
+
parts = meta.split()
|
|
81
|
+
if len(parts) >= 4 and parts[1] == "blob":
|
|
82
|
+
try:
|
|
83
|
+
sizes[path] = int(parts[3])
|
|
84
|
+
except ValueError:
|
|
85
|
+
continue
|
|
86
|
+
return sizes
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _is_commit_ancestor(repo_root: str, oid: str, target_ref: str = "HEAD") -> bool:
|
|
90
|
+
"""Return True if `oid` is an ancestor of `target_ref` (not rewritten by squash/rebase)."""
|
|
31
91
|
try:
|
|
32
92
|
proc = subprocess.run(
|
|
33
93
|
[
|
|
@@ -38,7 +98,7 @@ def _is_commit_ancestor(repo_root: str, oid: str) -> bool:
|
|
|
38
98
|
"merge-base",
|
|
39
99
|
"--is-ancestor",
|
|
40
100
|
oid,
|
|
41
|
-
|
|
101
|
+
target_ref,
|
|
42
102
|
],
|
|
43
103
|
capture_output=True,
|
|
44
104
|
timeout=2,
|
|
@@ -49,6 +109,47 @@ def _is_commit_ancestor(repo_root: str, oid: str) -> bool:
|
|
|
49
109
|
return True
|
|
50
110
|
|
|
51
111
|
|
|
112
|
+
def _resolve_snapshot_at_epoch(
|
|
113
|
+
repo_root: str,
|
|
114
|
+
tip_oid: str,
|
|
115
|
+
target_epoch: int,
|
|
116
|
+
commit_oid: str,
|
|
117
|
+
) -> Optional[str]:
|
|
118
|
+
"""Select the exact historical commit OID on `tip_oid`'s history at or before `target_epoch`."""
|
|
119
|
+
for extra in (["--first-parent"], []):
|
|
120
|
+
try:
|
|
121
|
+
proc = subprocess.run(
|
|
122
|
+
[
|
|
123
|
+
"git",
|
|
124
|
+
"--no-optional-locks",
|
|
125
|
+
"-C",
|
|
126
|
+
repo_root,
|
|
127
|
+
"rev-list",
|
|
128
|
+
"-n",
|
|
129
|
+
"1",
|
|
130
|
+
*extra,
|
|
131
|
+
f"--before={int(target_epoch)}",
|
|
132
|
+
tip_oid,
|
|
133
|
+
],
|
|
134
|
+
capture_output=True,
|
|
135
|
+
text=True,
|
|
136
|
+
timeout=2,
|
|
137
|
+
check=False,
|
|
138
|
+
)
|
|
139
|
+
if proc.returncode == 0:
|
|
140
|
+
snap = proc.stdout.strip()
|
|
141
|
+
if snap:
|
|
142
|
+
# Guard against clock skew where selected snapshot predates the commit itself
|
|
143
|
+
if snap == commit_oid or _is_commit_ancestor(repo_root, commit_oid, snap):
|
|
144
|
+
return snap
|
|
145
|
+
# If commit was squashed/rebased (not ancestor of tip_oid), allow snap on tip_oid
|
|
146
|
+
if not _is_commit_ancestor(repo_root, commit_oid, tip_oid):
|
|
147
|
+
return snap
|
|
148
|
+
except Exception:
|
|
149
|
+
continue
|
|
150
|
+
return None
|
|
151
|
+
|
|
152
|
+
|
|
52
153
|
def _extract_commit_added_lines(repo_root: str, oid: str, rel_p: str) -> list[str]:
|
|
53
154
|
"""Extract normalized added lines from `oid` for `rel_p` (used for squash-merge fallback)."""
|
|
54
155
|
try:
|
|
@@ -184,14 +285,36 @@ def measure_30d_line_survival(
|
|
|
184
285
|
candidate_oids: list[str],
|
|
185
286
|
max_commits: int = 30,
|
|
186
287
|
max_files: int = 18,
|
|
288
|
+
snapshot_oid: str = "HEAD",
|
|
187
289
|
) -> dict[str, Any]:
|
|
188
|
-
"""Measure exact
|
|
290
|
+
"""Measure exact line survival at pinned `snapshot_oid` via pure Git objects + `git blame --porcelain`.
|
|
291
|
+
|
|
292
|
+
Never inspects working-tree filesystem state; file presence and sizes come strictly from
|
|
293
|
+
`git ls-tree -l <snapshot_oid>`.
|
|
294
|
+
"""
|
|
295
|
+
empty: dict[str, Any] = {
|
|
296
|
+
"snapshot_oid": None,
|
|
297
|
+
"added_lines": 0,
|
|
298
|
+
"surviving_lines": 0,
|
|
299
|
+
"unobserved_lines": 0,
|
|
300
|
+
"unobserved_files": [],
|
|
301
|
+
"unobserved_commits": 0,
|
|
302
|
+
"denominator_unknown": False,
|
|
303
|
+
"per_oid": {},
|
|
304
|
+
"squash_fallback_oids": [],
|
|
305
|
+
}
|
|
189
306
|
if not candidate_oids or not os.path.isdir(repo_root):
|
|
190
|
-
return
|
|
307
|
+
return empty
|
|
191
308
|
|
|
192
309
|
sampled_oids = list(dict.fromkeys(candidate_oids))[:max_commits]
|
|
193
310
|
oid_set = set(sampled_oids)
|
|
194
311
|
|
|
312
|
+
resolved_snap = _resolve_ref_oid(repo_root, snapshot_oid)
|
|
313
|
+
if not resolved_snap:
|
|
314
|
+
empty["unobserved_commits"] = len(sampled_oids)
|
|
315
|
+
empty["denominator_unknown"] = True
|
|
316
|
+
return empty
|
|
317
|
+
|
|
195
318
|
try:
|
|
196
319
|
ns = subprocess.run(
|
|
197
320
|
[
|
|
@@ -211,9 +334,15 @@ def measure_30d_line_survival(
|
|
|
211
334
|
check=False,
|
|
212
335
|
)
|
|
213
336
|
if ns.returncode != 0:
|
|
214
|
-
|
|
337
|
+
empty["snapshot_oid"] = resolved_snap
|
|
338
|
+
empty["unobserved_commits"] = len(sampled_oids)
|
|
339
|
+
empty["denominator_unknown"] = True
|
|
340
|
+
return empty
|
|
215
341
|
except Exception:
|
|
216
|
-
|
|
342
|
+
empty["snapshot_oid"] = resolved_snap
|
|
343
|
+
empty["unobserved_commits"] = len(sampled_oids)
|
|
344
|
+
empty["denominator_unknown"] = True
|
|
345
|
+
return empty
|
|
217
346
|
|
|
218
347
|
# Map file -> {oid: added_lines}
|
|
219
348
|
file_oid_added: dict[str, dict[str, int]] = defaultdict(lambda: defaultdict(int))
|
|
@@ -239,23 +368,26 @@ def measure_30d_line_survival(
|
|
|
239
368
|
file_oid_added[rel_path][cur_oid] += added_n
|
|
240
369
|
|
|
241
370
|
if not file_oid_added:
|
|
242
|
-
|
|
371
|
+
empty["snapshot_oid"] = resolved_snap
|
|
372
|
+
return empty
|
|
373
|
+
|
|
374
|
+
# Inspect file presence & blob sizes strictly inside `resolved_snap` (zero working-tree mixing)
|
|
375
|
+
blob_sizes = _ls_tree_blobs(repo_root, resolved_snap, list(file_oid_added.keys()))
|
|
376
|
+
if blob_sizes is None:
|
|
377
|
+
empty["snapshot_oid"] = resolved_snap
|
|
378
|
+
empty["unobserved_lines"] = sum(sum(m.values()) for m in file_oid_added.values())
|
|
379
|
+
empty["unobserved_files"] = sorted(file_oid_added.keys())
|
|
380
|
+
empty["denominator_unknown"] = True
|
|
381
|
+
return empty
|
|
243
382
|
|
|
244
|
-
# Prioritize files touched by the most sampled commits; exclude oversized >256KB files
|
|
245
|
-
repo_p = Path(repo_root)
|
|
246
383
|
eligible_files: list[tuple[int, int, str, bool]] = []
|
|
247
384
|
for rel_p, oid_counts in file_oid_added.items():
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
try:
|
|
251
|
-
sz = fp.stat().st_size
|
|
252
|
-
except OSError:
|
|
253
|
-
continue
|
|
254
|
-
if sz > 262_144:
|
|
385
|
+
if rel_p in blob_sizes:
|
|
386
|
+
if blob_sizes[rel_p] > 262_144:
|
|
255
387
|
continue
|
|
256
388
|
eligible_files.append((len(oid_counts), sum(oid_counts.values()), rel_p, True))
|
|
257
|
-
|
|
258
|
-
#
|
|
389
|
+
else:
|
|
390
|
+
# Confirmed absent from Git tree at `resolved_snap` -> 0 surviving lines
|
|
259
391
|
eligible_files.append((len(oid_counts), sum(oid_counts.values()), rel_p, False))
|
|
260
392
|
|
|
261
393
|
eligible_files.sort(key=lambda x: (x[0], x[1]), reverse=True)
|
|
@@ -266,10 +398,9 @@ def measure_30d_line_survival(
|
|
|
266
398
|
squash_fallback_oids: set[str] = set()
|
|
267
399
|
unobserved_lines = 0
|
|
268
400
|
unobserved_files: list[str] = []
|
|
269
|
-
for _, _, rel_p,
|
|
401
|
+
for _, _, rel_p, exists_at_snap in selected:
|
|
270
402
|
oid_map = file_oid_added[rel_p]
|
|
271
|
-
if not
|
|
272
|
-
# Confirmed deleted at HEAD -> 0 surviving lines
|
|
403
|
+
if not exists_at_snap:
|
|
273
404
|
for oid, add_cnt in oid_map.items():
|
|
274
405
|
per_oid[oid]["added"] += add_cnt
|
|
275
406
|
continue
|
|
@@ -283,7 +414,7 @@ def measure_30d_line_survival(
|
|
|
283
414
|
repo_root,
|
|
284
415
|
"blame",
|
|
285
416
|
"--porcelain",
|
|
286
|
-
|
|
417
|
+
resolved_snap,
|
|
287
418
|
"--",
|
|
288
419
|
rel_p,
|
|
289
420
|
],
|
|
@@ -305,7 +436,7 @@ def measure_30d_line_survival(
|
|
|
305
436
|
per_oid[oid]["added"] += add_cnt
|
|
306
437
|
|
|
307
438
|
file_surviving: dict[str, int] = defaultdict(int)
|
|
308
|
-
|
|
439
|
+
unmatched_snap_lines: Counter[str] = Counter()
|
|
309
440
|
cur_blame_oid = ""
|
|
310
441
|
cur_matched_exact = False
|
|
311
442
|
for bline in bp.stdout.splitlines():
|
|
@@ -320,15 +451,15 @@ def measure_30d_line_survival(
|
|
|
320
451
|
cur_matched_exact = False
|
|
321
452
|
elif bline.startswith("\t"):
|
|
322
453
|
if not cur_matched_exact:
|
|
323
|
-
|
|
454
|
+
unmatched_snap_lines[_normalize_code_line(bline[1:])] += 1
|
|
324
455
|
|
|
325
|
-
# Pass 2
|
|
326
|
-
if
|
|
456
|
+
# Pass 2: Squash-Merge / Rebase line-fingerprint fallback for non-ancestor OIDs
|
|
457
|
+
if unmatched_snap_lines:
|
|
327
458
|
for oid, add_cnt in oid_map.items():
|
|
328
459
|
if file_surviving.get(oid, 0) > 0:
|
|
329
460
|
continue
|
|
330
461
|
if oid not in ancestor_cache:
|
|
331
|
-
ancestor_cache[oid] = _is_commit_ancestor(repo_root, oid)
|
|
462
|
+
ancestor_cache[oid] = _is_commit_ancestor(repo_root, oid, target_ref=resolved_snap)
|
|
332
463
|
if ancestor_cache[oid]:
|
|
333
464
|
continue
|
|
334
465
|
added_lines = _extract_commit_added_lines(repo_root, oid, rel_p)
|
|
@@ -336,13 +467,13 @@ def measure_30d_line_survival(
|
|
|
336
467
|
continue
|
|
337
468
|
substantive = [l for l in added_lines if _is_substantive_line(l)]
|
|
338
469
|
if substantive:
|
|
339
|
-
subst_hits = sum((Counter(substantive) &
|
|
470
|
+
subst_hits = sum((Counter(substantive) & unmatched_snap_lines).values())
|
|
340
471
|
if subst_hits == 0:
|
|
341
472
|
continue
|
|
342
473
|
matched = 0
|
|
343
474
|
for norm in added_lines:
|
|
344
|
-
if
|
|
345
|
-
|
|
475
|
+
if unmatched_snap_lines[norm] > 0:
|
|
476
|
+
unmatched_snap_lines[norm] -= 1
|
|
346
477
|
matched += 1
|
|
347
478
|
if matched > 0:
|
|
348
479
|
file_surviving[oid] += min(matched, add_cnt)
|
|
@@ -354,10 +485,13 @@ def measure_30d_line_survival(
|
|
|
354
485
|
tot_added = sum(v["added"] for v in per_oid.values())
|
|
355
486
|
tot_surv = sum(v["surviving"] for v in per_oid.values())
|
|
356
487
|
return {
|
|
488
|
+
"snapshot_oid": resolved_snap,
|
|
357
489
|
"added_lines": tot_added,
|
|
358
490
|
"surviving_lines": tot_surv,
|
|
359
491
|
"unobserved_lines": unobserved_lines,
|
|
360
492
|
"unobserved_files": unobserved_files,
|
|
493
|
+
"unobserved_commits": 0,
|
|
494
|
+
"denominator_unknown": False,
|
|
361
495
|
"per_oid": dict(per_oid),
|
|
362
496
|
"squash_fallback_oids": sorted(squash_fallback_oids),
|
|
363
497
|
}
|
|
@@ -370,18 +504,33 @@ def measure_cohort_line_survival(
|
|
|
370
504
|
horizons_days: tuple[int, ...] = (30, 60, 90),
|
|
371
505
|
max_commits: int = 30,
|
|
372
506
|
max_files: int = 18,
|
|
507
|
+
ref: str = "HEAD",
|
|
508
|
+
time_policy: str = "committer_epoch",
|
|
373
509
|
) -> dict[str, dict[str, Any]]:
|
|
374
|
-
"""Measure fixed-horizon
|
|
510
|
+
"""Measure true historical fixed-horizon cohort line survival (`t+30/60/90d`) with `notYet` separation.
|
|
511
|
+
|
|
512
|
+
For each matured commit `c` (where `as_of_epoch - commit_epoch >= H * 86400`), resolves the exact
|
|
513
|
+
historical Git snapshot OID on `ref`'s pinned history at `commit_epoch + H * 86400` and evaluates
|
|
514
|
+
file presence + `git blame --porcelain <snapshot_oid>` against that historical snapshot.
|
|
515
|
+
`added_lines` denotes observed added lines whose files were blamable at `snapshot_oid`; failed
|
|
516
|
+
reads are kept separate in `unobserved_lines` and `unobserved_commits`.
|
|
517
|
+
"""
|
|
375
518
|
out: dict[str, dict[str, Any]] = {}
|
|
376
|
-
|
|
519
|
+
tip_oid = _resolve_ref_oid(repo_root, ref) if os.path.isdir(repo_root) else None
|
|
520
|
+
if not commit_records or not tip_oid or as_of_epoch <= 0:
|
|
377
521
|
for h in horizons_days:
|
|
378
522
|
out[f"t{h}d"] = {
|
|
379
523
|
"horizon_days": h,
|
|
524
|
+
"ref": ref,
|
|
525
|
+
"tip_oid": tip_oid,
|
|
526
|
+
"time_policy": time_policy,
|
|
380
527
|
"matured_commits": 0,
|
|
381
528
|
"not_yet_commits": 0,
|
|
382
529
|
"added_lines": 0,
|
|
383
530
|
"surviving_lines": 0,
|
|
384
531
|
"unobserved_lines": 0,
|
|
532
|
+
"unobserved_commits": 0,
|
|
533
|
+
"snapshots_evaluated": [],
|
|
385
534
|
"retention_pct": None,
|
|
386
535
|
}
|
|
387
536
|
return out
|
|
@@ -389,32 +538,55 @@ def measure_cohort_line_survival(
|
|
|
389
538
|
seen: dict[str, float] = {}
|
|
390
539
|
for c in commit_records:
|
|
391
540
|
oid = str(c.get("oid") or "")
|
|
392
|
-
ep = float(c.get("epoch_sec") or 0.0)
|
|
541
|
+
ep = float(c.get("committer_epoch") or c.get("epoch_sec") or 0.0)
|
|
393
542
|
if oid and ep > 0 and oid not in seen:
|
|
394
543
|
seen[oid] = ep
|
|
395
544
|
|
|
396
|
-
# Evaluate matured commits once per unique matured set (most recent matured first)
|
|
397
545
|
ordered = sorted(seen.items(), key=lambda kv: kv[1], reverse=True)
|
|
398
546
|
for h in horizons_days:
|
|
399
547
|
min_age = float(h) * 86400.0
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
548
|
+
matured_pairs = [(oid, ep) for oid, ep in ordered if (as_of_epoch - ep) >= min_age]
|
|
549
|
+
not_yet_pairs = [(oid, ep) for oid, ep in ordered if (as_of_epoch - ep) < min_age]
|
|
550
|
+
|
|
551
|
+
add_n = 0
|
|
552
|
+
surv_n = 0
|
|
553
|
+
unobs_lines = 0
|
|
554
|
+
unobs_commits = 0
|
|
555
|
+
by_snapshot: dict[str, list[str]] = defaultdict(list)
|
|
556
|
+
|
|
557
|
+
for oid, ep in matured_pairs[:max_commits]:
|
|
558
|
+
target_ep = int(ep + min_age)
|
|
559
|
+
snap_oid = _resolve_snapshot_at_epoch(repo_root, tip_oid, target_ep, oid)
|
|
560
|
+
if not snap_oid:
|
|
561
|
+
unobs_commits += 1
|
|
562
|
+
continue
|
|
563
|
+
by_snapshot[snap_oid].append(oid)
|
|
564
|
+
|
|
565
|
+
for snap_oid, snap_oids in by_snapshot.items():
|
|
403
566
|
res = measure_30d_line_survival(
|
|
404
|
-
repo_root,
|
|
567
|
+
repo_root,
|
|
568
|
+
snap_oids,
|
|
569
|
+
max_commits=len(snap_oids),
|
|
570
|
+
max_files=max_files,
|
|
571
|
+
snapshot_oid=snap_oid,
|
|
405
572
|
)
|
|
406
|
-
add_n
|
|
407
|
-
surv_n
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
573
|
+
add_n += int(res.get("added_lines") or 0)
|
|
574
|
+
surv_n += int(res.get("surviving_lines") or 0)
|
|
575
|
+
unobs_lines += int(res.get("unobserved_lines") or 0)
|
|
576
|
+
unobs_commits += int(res.get("unobserved_commits") or 0)
|
|
577
|
+
|
|
411
578
|
out[f"t{h}d"] = {
|
|
412
579
|
"horizon_days": h,
|
|
413
|
-
"
|
|
414
|
-
"
|
|
580
|
+
"ref": ref,
|
|
581
|
+
"tip_oid": tip_oid,
|
|
582
|
+
"time_policy": time_policy,
|
|
583
|
+
"matured_commits": len(matured_pairs),
|
|
584
|
+
"not_yet_commits": len(not_yet_pairs),
|
|
415
585
|
"added_lines": add_n,
|
|
416
586
|
"surviving_lines": surv_n,
|
|
417
|
-
"unobserved_lines":
|
|
587
|
+
"unobserved_lines": unobs_lines,
|
|
588
|
+
"unobserved_commits": unobs_commits,
|
|
589
|
+
"snapshots_evaluated": sorted(by_snapshot.keys())[:10],
|
|
418
590
|
"retention_pct": round(100.0 * surv_n / add_n, 2) if add_n > 0 else None,
|
|
419
591
|
}
|
|
420
592
|
return out
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: tokenblame
|
|
3
|
-
Version: 2.2.
|
|
3
|
+
Version: 2.2.2
|
|
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
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|