tokenblame 2.1.1__py3-none-any.whl
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/__init__.py +3 -0
- tokenblame/cli.py +661 -0
- tokenblame/harvesters.py +1107 -0
- tokenblame/hooks.py +272 -0
- tokenblame/joiner.py +1086 -0
- tokenblame/provenance.py +424 -0
- tokenblame/redact.py +161 -0
- tokenblame/render.py +667 -0
- tokenblame/schema.py +242 -0
- tokenblame/store.py +341 -0
- tokenblame/survival.py +352 -0
- tokenblame-2.1.1.dist-info/METADATA +161 -0
- tokenblame-2.1.1.dist-info/RECORD +17 -0
- tokenblame-2.1.1.dist-info/WHEEL +5 -0
- tokenblame-2.1.1.dist-info/entry_points.txt +2 -0
- tokenblame-2.1.1.dist-info/licenses/LICENSE +189 -0
- tokenblame-2.1.1.dist-info/top_level.txt +1 -0
tokenblame/__init__.py
ADDED
tokenblame/cli.py
ADDED
|
@@ -0,0 +1,661 @@
|
|
|
1
|
+
"""CLI entry point for ai-tokenblame (build, summary, open)."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import argparse
|
|
5
|
+
import datetime as dt
|
|
6
|
+
import json
|
|
7
|
+
import os
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
import shutil
|
|
10
|
+
import subprocess
|
|
11
|
+
import sys
|
|
12
|
+
from urllib.parse import quote
|
|
13
|
+
|
|
14
|
+
from tokenblame.harvesters import harvest_all
|
|
15
|
+
from tokenblame.hooks import init_hooks, run_doctor
|
|
16
|
+
from tokenblame.joiner import (
|
|
17
|
+
build_observatory_ir,
|
|
18
|
+
load_git_worklog,
|
|
19
|
+
load_orca_context,
|
|
20
|
+
load_warmlogic_episodes,
|
|
21
|
+
load_wb_handoffs,
|
|
22
|
+
)
|
|
23
|
+
from tokenblame.provenance import (
|
|
24
|
+
load_commit_provenance,
|
|
25
|
+
record_hook_invocation,
|
|
26
|
+
resolve_default_observatory_dir,
|
|
27
|
+
)
|
|
28
|
+
from tokenblame.redact import build_shareable_ir
|
|
29
|
+
from tokenblame.render import render_observatory_html
|
|
30
|
+
from tokenblame.schema import resolve_local_tz
|
|
31
|
+
from tokenblame.store import query_summary_from_store, write_observatory_store
|
|
32
|
+
|
|
33
|
+
DEFAULT_GWL_CURRENT = Path.home() / "Library" / "Application Support" / "git-worklog" / "site" / "current"
|
|
34
|
+
DEFAULT_WL_ROOT = Path.home() / "projects" / "warmlogic-experience"
|
|
35
|
+
DEFAULT_WB_ROOT = Path.home() / "projects" / "research-workbench"
|
|
36
|
+
DEFAULT_ORCA_DIR = Path.home() / "Library" / "Application Support" / "Orca"
|
|
37
|
+
DEFAULT_OUT_DIR = resolve_default_observatory_dir()
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def build_command(
|
|
41
|
+
gwl_dir: Path = DEFAULT_GWL_CURRENT,
|
|
42
|
+
wl_root: Path = DEFAULT_WL_ROOT,
|
|
43
|
+
out_dir: Path = DEFAULT_OUT_DIR,
|
|
44
|
+
wb_root: Path = DEFAULT_WB_ROOT,
|
|
45
|
+
orca_dir: Path = DEFAULT_ORCA_DIR,
|
|
46
|
+
shareable: bool = False,
|
|
47
|
+
extra_scan_roots: list[Path] | None = None,
|
|
48
|
+
) -> dict:
|
|
49
|
+
out_dir.mkdir(mode=0o700, parents=True, exist_ok=True)
|
|
50
|
+
os.chmod(out_dir, 0o700)
|
|
51
|
+
cache_db = out_dir / "harvest_cache.sqlite"
|
|
52
|
+
|
|
53
|
+
sessions, harvest_stats = harvest_all(cache_db=cache_db)
|
|
54
|
+
commits, repo_map = load_git_worklog(gwl_dir.resolve() if gwl_dir and gwl_dir.exists() else None)
|
|
55
|
+
episodes = load_warmlogic_episodes(wl_root if wl_root and wl_root.exists() else None)
|
|
56
|
+
handoffs = load_wb_handoffs(wb_root if wb_root and wb_root.exists() else None)
|
|
57
|
+
orca_ctx = load_orca_context(orca_dir if orca_dir and orca_dir.exists() else None)
|
|
58
|
+
provenance_records = load_commit_provenance(out_dir / "commit_provenance.jsonl")
|
|
59
|
+
|
|
60
|
+
ir = build_observatory_ir(
|
|
61
|
+
sessions=sessions,
|
|
62
|
+
commits=commits,
|
|
63
|
+
episodes=episodes,
|
|
64
|
+
repo_map=repo_map,
|
|
65
|
+
harvest_stats=harvest_stats,
|
|
66
|
+
cache_db=cache_db,
|
|
67
|
+
orca_ctx=orca_ctx,
|
|
68
|
+
handoffs=handoffs,
|
|
69
|
+
provenance_records=provenance_records,
|
|
70
|
+
extra_scan_roots=extra_scan_roots,
|
|
71
|
+
discover_repos=True,
|
|
72
|
+
)
|
|
73
|
+
html_out = render_observatory_html(ir)
|
|
74
|
+
|
|
75
|
+
ir_path = out_dir / "observatory-ir.json"
|
|
76
|
+
html_path = out_dir / "observatory.html"
|
|
77
|
+
sqlite_path = out_dir / "observatory.sqlite"
|
|
78
|
+
ir_path.write_text(json.dumps(ir, indent=2), encoding="utf-8")
|
|
79
|
+
html_path.write_text(html_out, encoding="utf-8")
|
|
80
|
+
os.chmod(ir_path, 0o600)
|
|
81
|
+
os.chmod(html_path, 0o600)
|
|
82
|
+
|
|
83
|
+
commits_for_store = [c for fd in ir.get("feed", []) for c in fd.get("commit_list", [])]
|
|
84
|
+
outcomes_for_store = [ep for fd in ir.get("feed", []) for ep in fd.get("episode_list", [])]
|
|
85
|
+
write_observatory_store(sqlite_path, ir, sessions, commits_for_store, outcomes_for_store)
|
|
86
|
+
|
|
87
|
+
result = {
|
|
88
|
+
"ir_path": str(ir_path),
|
|
89
|
+
"html_path": str(html_path),
|
|
90
|
+
"sqlite_path": str(sqlite_path),
|
|
91
|
+
"totals": ir["totals"],
|
|
92
|
+
"models_count": len(ir["models"]),
|
|
93
|
+
"discovered_repos_count": ir["discovered_repos_count"],
|
|
94
|
+
"harvest_stats": harvest_stats,
|
|
95
|
+
}
|
|
96
|
+
if shareable:
|
|
97
|
+
s_ir = build_shareable_ir(ir)
|
|
98
|
+
s_html = render_observatory_html(s_ir)
|
|
99
|
+
s_ir_path = out_dir / "shareable-ir.json"
|
|
100
|
+
s_html_path = out_dir / "shareable-observatory.html"
|
|
101
|
+
s_ir_path.write_text(json.dumps(s_ir, indent=2), encoding="utf-8")
|
|
102
|
+
s_html_path.write_text(s_html, encoding="utf-8")
|
|
103
|
+
os.chmod(s_ir_path, 0o600)
|
|
104
|
+
os.chmod(s_html_path, 0o600)
|
|
105
|
+
result["shareable_ir_path"] = str(s_ir_path)
|
|
106
|
+
result["shareable_html_path"] = str(s_html_path)
|
|
107
|
+
return result
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _load_or_build_ir(out_dir: Path, gwl_dir: Path, wl_root: Path) -> dict:
|
|
111
|
+
ir_path = out_dir / "observatory-ir.json"
|
|
112
|
+
if not ir_path.exists():
|
|
113
|
+
build_command(gwl_dir, wl_root, out_dir)
|
|
114
|
+
return json.loads(ir_path.read_text(encoding="utf-8"))
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def summary_command(
|
|
118
|
+
out_dir: Path,
|
|
119
|
+
gwl_dir: Path,
|
|
120
|
+
wl_root: Path,
|
|
121
|
+
days: int | None = None,
|
|
122
|
+
lane: str | None = None,
|
|
123
|
+
model_filter: str | None = None,
|
|
124
|
+
as_json: bool = False,
|
|
125
|
+
) -> dict:
|
|
126
|
+
cutoff_day = None
|
|
127
|
+
if days is not None and days > 0:
|
|
128
|
+
cutoff = dt.datetime.now(resolve_local_tz()).date() - dt.timedelta(days=days - 1)
|
|
129
|
+
cutoff_day = cutoff.isoformat()
|
|
130
|
+
|
|
131
|
+
sqlite_payload = query_summary_from_store(
|
|
132
|
+
db_path=out_dir / "observatory.sqlite",
|
|
133
|
+
html_path=out_dir / "observatory.html",
|
|
134
|
+
days=days,
|
|
135
|
+
cutoff_day=cutoff_day,
|
|
136
|
+
lane=lane,
|
|
137
|
+
model_filter=model_filter,
|
|
138
|
+
)
|
|
139
|
+
if sqlite_payload is not None:
|
|
140
|
+
payload = sqlite_payload
|
|
141
|
+
else:
|
|
142
|
+
ir = _load_or_build_ir(out_dir, gwl_dir, wl_root)
|
|
143
|
+
if cutoff_day is None and not lane and not model_filter:
|
|
144
|
+
payload = {
|
|
145
|
+
"generated_at": ir["generated_at"],
|
|
146
|
+
"window": "all_time",
|
|
147
|
+
"totals": ir["totals"],
|
|
148
|
+
"top_models": ir["models"][:8],
|
|
149
|
+
"top_high_burn_no_commit": [
|
|
150
|
+
{
|
|
151
|
+
"day": b["day"],
|
|
152
|
+
"model": b["model"],
|
|
153
|
+
"repo": b.get("repo_name") or b.get("lane"),
|
|
154
|
+
"generated_output": b["buckets"]["generated_output"],
|
|
155
|
+
"fresh_input": b["buckets"]["fresh_input"],
|
|
156
|
+
"cost_usd": b.get("api_equiv_cost_usd"),
|
|
157
|
+
"loop_warning": (b.get("forensics") or {}).get("loop_warning"),
|
|
158
|
+
}
|
|
159
|
+
for b in ir.get("futile_burn", [])[:5]
|
|
160
|
+
],
|
|
161
|
+
"html_path": str(out_dir / "observatory.html"),
|
|
162
|
+
}
|
|
163
|
+
else:
|
|
164
|
+
# Filtered aggregation directly over IR feed days
|
|
165
|
+
mod_agg: dict[tuple[str, str], dict] = {}
|
|
166
|
+
tot_out = tot_fresh = tot_cache = tot_sess = tot_comm = tot_ep = 0
|
|
167
|
+
tot_cost = 0.0
|
|
168
|
+
burns = []
|
|
169
|
+
for fd in ir.get("feed", []):
|
|
170
|
+
if cutoff_day and fd["day"] < cutoff_day:
|
|
171
|
+
continue
|
|
172
|
+
day_matched_comm = 0
|
|
173
|
+
for c in fd.get("commit_list", []):
|
|
174
|
+
if lane and lane.lower() not in ",".join(c.get("lanes", []) + c.get("repos", [])).lower():
|
|
175
|
+
continue
|
|
176
|
+
day_matched_comm += 1
|
|
177
|
+
tot_comm += day_matched_comm
|
|
178
|
+
for ep in fd.get("episode_list", []):
|
|
179
|
+
if lane and lane.lower() not in (ep.get("line") or "").lower():
|
|
180
|
+
continue
|
|
181
|
+
tot_ep += 1
|
|
182
|
+
for s in fd.get("session_list", []):
|
|
183
|
+
s_loc = f"{s.get('lane') or ''} {s.get('repo_name') or ''} {s.get('cwd') or ''}".lower()
|
|
184
|
+
if lane and lane.lower() not in s_loc:
|
|
185
|
+
continue
|
|
186
|
+
if model_filter and model_filter.lower() not in (s.get("model") or "").lower():
|
|
187
|
+
continue
|
|
188
|
+
bk = s["buckets"]
|
|
189
|
+
tot_sess += 1
|
|
190
|
+
tot_out += bk["generated_output"]
|
|
191
|
+
tot_fresh += bk["fresh_input"]
|
|
192
|
+
tot_cache += bk["cached_read"]
|
|
193
|
+
if s.get("api_equiv_cost_usd") is not None:
|
|
194
|
+
tot_cost += float(s["api_equiv_cost_usd"])
|
|
195
|
+
key = (s["provider"], s["model"])
|
|
196
|
+
mr = mod_agg.setdefault(key, {
|
|
197
|
+
"provider": s["provider"], "model": s["model"],
|
|
198
|
+
"sessions": 0, "generated_output": 0, "fresh_input": 0,
|
|
199
|
+
"cached_read": 0, "api_equiv_cost_usd": 0.0,
|
|
200
|
+
})
|
|
201
|
+
mr["sessions"] += 1
|
|
202
|
+
mr["generated_output"] += bk["generated_output"]
|
|
203
|
+
mr["fresh_input"] += bk["fresh_input"]
|
|
204
|
+
mr["cached_read"] += bk["cached_read"]
|
|
205
|
+
if s.get("api_equiv_cost_usd") is not None:
|
|
206
|
+
mr["api_equiv_cost_usd"] += float(s["api_equiv_cost_usd"])
|
|
207
|
+
if s.get("attribution") == "HIGH_BURN_NO_COMMIT":
|
|
208
|
+
burns.append({
|
|
209
|
+
"day": s["day"], "model": s["model"],
|
|
210
|
+
"repo": s.get("repo_name") or s.get("lane"),
|
|
211
|
+
"generated_output": bk["generated_output"],
|
|
212
|
+
"cost_usd": s.get("api_equiv_cost_usd"),
|
|
213
|
+
"loop_warning": (s.get("forensics") or {}).get("loop_warning"),
|
|
214
|
+
})
|
|
215
|
+
top_models = sorted(mod_agg.values(), key=lambda x: x["generated_output"], reverse=True)[:8]
|
|
216
|
+
for m in top_models:
|
|
217
|
+
m["api_equiv_cost_usd"] = round(m["api_equiv_cost_usd"], 2)
|
|
218
|
+
burns.sort(key=lambda x: x["generated_output"], reverse=True)
|
|
219
|
+
payload = {
|
|
220
|
+
"generated_at": ir["generated_at"],
|
|
221
|
+
"window": f"last_{days}_days" if days else "filtered",
|
|
222
|
+
"filters": {"days": days, "lane": lane, "model": model_filter},
|
|
223
|
+
"totals": {
|
|
224
|
+
"sessions": tot_sess,
|
|
225
|
+
"commits": tot_comm,
|
|
226
|
+
"outcomes": tot_ep,
|
|
227
|
+
"generated_output": tot_out,
|
|
228
|
+
"fresh_input": tot_fresh,
|
|
229
|
+
"cached_read": tot_cache,
|
|
230
|
+
"api_equiv_cost_usd": round(tot_cost, 2),
|
|
231
|
+
},
|
|
232
|
+
"top_models": top_models,
|
|
233
|
+
"top_high_burn_no_commit": burns[:5],
|
|
234
|
+
"html_path": str(out_dir / "observatory.html"),
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
if as_json:
|
|
238
|
+
print(json.dumps(payload, indent=2))
|
|
239
|
+
else:
|
|
240
|
+
t = payload["totals"]
|
|
241
|
+
mb = t.get("measured_buckets", t)
|
|
242
|
+
print(f"# AI Worklog Observatory ({payload['window']})")
|
|
243
|
+
print(f"- Generated: {payload['generated_at']}")
|
|
244
|
+
print(f"- Output: {mb['generated_output']:,} | Fresh Input: {mb['fresh_input']:,} | Cache Read: {mb['cached_read']:,} | Est. Cost: ${t.get('api_equiv_cost_usd', 0):,.2f}")
|
|
245
|
+
print("\n## Top Models")
|
|
246
|
+
for m in payload["top_models"]:
|
|
247
|
+
c_str = f"${m['api_equiv_cost_usd']:,.2f}" if m.get("api_equiv_cost_usd") is not None else "Unpriced"
|
|
248
|
+
print(f"- {m['provider']}/{m['model']}: {m['sessions']} sess | out={m['generated_output']:,} | fresh={m['fresh_input']:,} | {c_str}")
|
|
249
|
+
print(f"\nReport: file://{quote(payload['html_path'])}")
|
|
250
|
+
return payload
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def resolve_orca_binary() -> str:
|
|
254
|
+
env_cmd = os.environ.get("ORCA_CLI_COMMAND")
|
|
255
|
+
if env_cmd:
|
|
256
|
+
return env_cmd
|
|
257
|
+
app_orca = Path("/Applications/Orca.app/Contents/Resources/bin/orca")
|
|
258
|
+
if app_orca.exists():
|
|
259
|
+
return str(app_orca)
|
|
260
|
+
return shutil.which("orca") or "orca"
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
def open_command(
|
|
264
|
+
out_dir: Path,
|
|
265
|
+
gwl_dir: Path,
|
|
266
|
+
wl_root: Path,
|
|
267
|
+
refresh: bool = False,
|
|
268
|
+
dry_run: bool = False,
|
|
269
|
+
shareable: bool = False,
|
|
270
|
+
) -> dict:
|
|
271
|
+
target_name = "shareable-observatory.html" if shareable else "observatory.html"
|
|
272
|
+
if refresh or not (out_dir / target_name).exists():
|
|
273
|
+
build_command(gwl_dir, wl_root, out_dir, shareable=shareable)
|
|
274
|
+
html_path = (out_dir / target_name).resolve()
|
|
275
|
+
url = f"file://{quote(str(html_path))}"
|
|
276
|
+
orca_bin = resolve_orca_binary()
|
|
277
|
+
cmd = [orca_bin, "tab", "create", "--url", url]
|
|
278
|
+
info = {
|
|
279
|
+
"command": cmd,
|
|
280
|
+
"url": url,
|
|
281
|
+
"html_path": str(html_path),
|
|
282
|
+
"exists": html_path.exists(),
|
|
283
|
+
}
|
|
284
|
+
if dry_run:
|
|
285
|
+
print(json.dumps(info, indent=2))
|
|
286
|
+
return info
|
|
287
|
+
|
|
288
|
+
# Prefer Orca embedded tab when Orca runtime is reachable; fallback to system browser for standalone OSS users
|
|
289
|
+
orca_exists = Path(orca_bin).is_file() or shutil.which(orca_bin) is not None
|
|
290
|
+
if orca_exists:
|
|
291
|
+
status_proc = subprocess.run(
|
|
292
|
+
[orca_bin, "status", "--json"],
|
|
293
|
+
capture_output=True, text=True, timeout=10, check=False,
|
|
294
|
+
)
|
|
295
|
+
if status_proc.returncode == 0:
|
|
296
|
+
tab_proc = subprocess.run(cmd, capture_output=True, text=True, timeout=15, check=False)
|
|
297
|
+
if tab_proc.returncode != 0:
|
|
298
|
+
raise RuntimeError(f"orca tab create failed: {tab_proc.stderr.strip()}")
|
|
299
|
+
info["orca_output"] = tab_proc.stdout.strip()
|
|
300
|
+
print(json.dumps(info, indent=2))
|
|
301
|
+
return info
|
|
302
|
+
|
|
303
|
+
import webbrowser
|
|
304
|
+
webbrowser.open(url)
|
|
305
|
+
info["opened_via"] = "system_browser"
|
|
306
|
+
print(json.dumps(info, indent=2))
|
|
307
|
+
return info
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
def _write_precheck_health(out_dir: Path, status: str, exit_code: int, **extra) -> None:
|
|
311
|
+
"""Record explicit fail-closed precheck status so crashes never masquerade as clean skips (H46)."""
|
|
312
|
+
try:
|
|
313
|
+
out_dir.mkdir(mode=0o700, parents=True, exist_ok=True)
|
|
314
|
+
health_path = out_dir / "precheck_health.json"
|
|
315
|
+
payload = {
|
|
316
|
+
"checked_at": dt.datetime.now(dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
|
|
317
|
+
"status": status,
|
|
318
|
+
"exit_code": exit_code,
|
|
319
|
+
**extra,
|
|
320
|
+
}
|
|
321
|
+
health_path.write_text(json.dumps(payload, indent=2), encoding="utf-8")
|
|
322
|
+
os.chmod(health_path, 0o600)
|
|
323
|
+
except OSError:
|
|
324
|
+
pass
|
|
325
|
+
|
|
326
|
+
|
|
327
|
+
def ack_burn_alert_command(out_dir: Path) -> int:
|
|
328
|
+
"""Confirm delivery of pending_burn_alert.json and commit its candidate keys into burn_alert_state.json."""
|
|
329
|
+
pending_path = out_dir / "pending_burn_alert.json"
|
|
330
|
+
if not pending_path.exists():
|
|
331
|
+
print("no pending_burn_alert.json to acknowledge", file=sys.stderr)
|
|
332
|
+
return 1
|
|
333
|
+
try:
|
|
334
|
+
alert = json.loads(pending_path.read_text(encoding="utf-8"))
|
|
335
|
+
except (OSError, ValueError) as exc:
|
|
336
|
+
print(f"failed to read pending_burn_alert.json: {exc}", file=sys.stderr)
|
|
337
|
+
return 2
|
|
338
|
+
candidate_keys = list(alert.get("candidate_keys") or [])
|
|
339
|
+
state_path = out_dir / "burn_alert_state.json"
|
|
340
|
+
alerted_keys: list[str] = []
|
|
341
|
+
if state_path.exists():
|
|
342
|
+
try:
|
|
343
|
+
alerted_keys = list(json.loads(state_path.read_text(encoding="utf-8")).get("alerted_keys", []))
|
|
344
|
+
except (OSError, ValueError) as exc:
|
|
345
|
+
print(f"corrupt burn_alert_state.json: {exc}", file=sys.stderr)
|
|
346
|
+
return 2
|
|
347
|
+
merged = list(dict.fromkeys(alerted_keys + candidate_keys))[-2000:]
|
|
348
|
+
state_path.write_text(json.dumps({"alerted_keys": merged}, indent=2), encoding="utf-8")
|
|
349
|
+
os.chmod(state_path, 0o600)
|
|
350
|
+
alert["delivery_state"] = "DELIVERED_ACKED"
|
|
351
|
+
alert["acked_at"] = dt.datetime.now(dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
|
352
|
+
pending_path.write_text(json.dumps(alert, indent=2), encoding="utf-8")
|
|
353
|
+
os.chmod(pending_path, 0o600)
|
|
354
|
+
print(json.dumps({"acked": len(candidate_keys), "total_alerted_keys": len(merged)}, indent=2))
|
|
355
|
+
return 0
|
|
356
|
+
|
|
357
|
+
|
|
358
|
+
def precheck_burn_command(
|
|
359
|
+
out_dir: Path,
|
|
360
|
+
gwl_dir: Path,
|
|
361
|
+
wl_root: Path,
|
|
362
|
+
days: int = 2,
|
|
363
|
+
min_cost: float = 25.0,
|
|
364
|
+
min_output: int = 100_000,
|
|
365
|
+
no_refresh: bool = False,
|
|
366
|
+
defer_ack: bool = False,
|
|
367
|
+
) -> int:
|
|
368
|
+
"""Zero-LLM precheck for new HIGH_BURN_NO_COMMIT sessions.
|
|
369
|
+
|
|
370
|
+
Exit codes (fail-closed per H46):
|
|
371
|
+
0 = threshold breached (alert candidate written to pending_burn_alert.json)
|
|
372
|
+
1 = healthy / below threshold (no alert needed)
|
|
373
|
+
2 = telemetry build/read/parse error (recorded to precheck_health.json; never confused with 1)
|
|
374
|
+
"""
|
|
375
|
+
try:
|
|
376
|
+
if not no_refresh:
|
|
377
|
+
build_command(gwl_dir, wl_root, out_dir)
|
|
378
|
+
ir_path = out_dir / "observatory-ir.json"
|
|
379
|
+
if not ir_path.exists():
|
|
380
|
+
msg = "no observatory-ir.json found"
|
|
381
|
+
_write_precheck_health(out_dir, "ERROR", 2, error=msg)
|
|
382
|
+
print(msg, file=sys.stderr)
|
|
383
|
+
return 2
|
|
384
|
+
ir = json.loads(ir_path.read_text(encoding="utf-8"))
|
|
385
|
+
if not isinstance(ir, dict) or "feed" not in ir:
|
|
386
|
+
msg = "malformed observatory-ir.json: missing feed"
|
|
387
|
+
_write_precheck_health(out_dir, "ERROR", 2, error=msg)
|
|
388
|
+
print(msg, file=sys.stderr)
|
|
389
|
+
return 2
|
|
390
|
+
except Exception as exc:
|
|
391
|
+
msg = f"precheck telemetry error: {type(exc).__name__}: {exc}"
|
|
392
|
+
_write_precheck_health(out_dir, "ERROR", 2, error=msg)
|
|
393
|
+
print(msg, file=sys.stderr)
|
|
394
|
+
return 2
|
|
395
|
+
|
|
396
|
+
state_path = out_dir / "burn_alert_state.json"
|
|
397
|
+
alerted_keys: list[str] = []
|
|
398
|
+
if state_path.exists():
|
|
399
|
+
try:
|
|
400
|
+
alerted_keys = list(json.loads(state_path.read_text(encoding="utf-8")).get("alerted_keys", []))
|
|
401
|
+
except (OSError, ValueError) as exc:
|
|
402
|
+
msg = f"corrupt burn_alert_state.json: {type(exc).__name__}: {exc}"
|
|
403
|
+
_write_precheck_health(out_dir, "ERROR", 2, error=msg)
|
|
404
|
+
print(msg, file=sys.stderr)
|
|
405
|
+
return 2
|
|
406
|
+
alerted_set = set(alerted_keys)
|
|
407
|
+
|
|
408
|
+
cutoff_day = (dt.datetime.now(resolve_local_tz()).date() - dt.timedelta(days=max(1, days) - 1)).isoformat()
|
|
409
|
+
new_sessions: list[dict] = []
|
|
410
|
+
new_keys: list[str] = []
|
|
411
|
+
new_cost = 0.0
|
|
412
|
+
new_output = 0
|
|
413
|
+
|
|
414
|
+
for fd in ir.get("feed", []):
|
|
415
|
+
if fd.get("day", "") < cutoff_day:
|
|
416
|
+
continue
|
|
417
|
+
for s in fd.get("session_list", []):
|
|
418
|
+
if s.get("attribution") != "HIGH_BURN_NO_COMMIT":
|
|
419
|
+
continue
|
|
420
|
+
k = f"{s.get('provider')}:{s.get('session_id')}:{s.get('model')}:{s.get('day')}"
|
|
421
|
+
if k in alerted_set:
|
|
422
|
+
continue
|
|
423
|
+
alerted_set.add(k)
|
|
424
|
+
new_keys.append(k)
|
|
425
|
+
bk = s.get("buckets") or {}
|
|
426
|
+
out_tok = int(bk.get("generated_output") or 0)
|
|
427
|
+
cost_val = float(s.get("api_equiv_cost_usd") or 0.0)
|
|
428
|
+
new_output += out_tok
|
|
429
|
+
new_cost += cost_val
|
|
430
|
+
new_sessions.append(s)
|
|
431
|
+
|
|
432
|
+
if not new_sessions or (new_cost < min_cost and new_output < min_output):
|
|
433
|
+
_write_precheck_health(
|
|
434
|
+
out_dir,
|
|
435
|
+
"OK_NO_BREACH",
|
|
436
|
+
1,
|
|
437
|
+
cutoff_day=cutoff_day,
|
|
438
|
+
candidate_sessions=len(new_sessions),
|
|
439
|
+
candidate_output=new_output,
|
|
440
|
+
candidate_cost_usd=round(new_cost, 2),
|
|
441
|
+
)
|
|
442
|
+
print("no new high-burn threshold breach")
|
|
443
|
+
return 1
|
|
444
|
+
|
|
445
|
+
new_sessions.sort(
|
|
446
|
+
key=lambda r: (r["buckets"]["generated_output"] + r["buckets"]["fresh_input"]),
|
|
447
|
+
reverse=True,
|
|
448
|
+
)
|
|
449
|
+
html_path = (out_dir / "observatory.html").resolve()
|
|
450
|
+
delivery_state = "PENDING_ACK" if defer_ack else "CANDIDATE_EMITTED_UNCONFIRMED"
|
|
451
|
+
alert_payload = {
|
|
452
|
+
"detected_at": dt.datetime.now(dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
|
|
453
|
+
"cutoff_day": cutoff_day,
|
|
454
|
+
"thresholds": {"min_cost": min_cost, "min_output": min_output, "days": days},
|
|
455
|
+
"delivery_state": delivery_state,
|
|
456
|
+
"candidate_keys": new_keys,
|
|
457
|
+
"new_sessions_count": len(new_sessions),
|
|
458
|
+
"new_generated_output": new_output,
|
|
459
|
+
"new_api_equiv_cost_usd": round(new_cost, 2),
|
|
460
|
+
"top_sessions": [
|
|
461
|
+
{
|
|
462
|
+
"day": s.get("day"),
|
|
463
|
+
"provider": s.get("provider"),
|
|
464
|
+
"model": s.get("model"),
|
|
465
|
+
"repo_name": s.get("repo_name"),
|
|
466
|
+
"lane": s.get("lane"),
|
|
467
|
+
"generated_output": s["buckets"]["generated_output"],
|
|
468
|
+
"fresh_input": s["buckets"]["fresh_input"],
|
|
469
|
+
"api_equiv_cost_usd": s.get("api_equiv_cost_usd"),
|
|
470
|
+
}
|
|
471
|
+
for s in new_sessions[:8]
|
|
472
|
+
],
|
|
473
|
+
"html_url": f"file://{quote(str(html_path))}",
|
|
474
|
+
}
|
|
475
|
+
pending_path = out_dir / "pending_burn_alert.json"
|
|
476
|
+
pending_path.write_text(json.dumps(alert_payload, indent=2), encoding="utf-8")
|
|
477
|
+
os.chmod(pending_path, 0o600)
|
|
478
|
+
|
|
479
|
+
if not defer_ack:
|
|
480
|
+
updated_keys = (alerted_keys + new_keys)[-2000:]
|
|
481
|
+
state_path.write_text(json.dumps({"alerted_keys": updated_keys}, indent=2), encoding="utf-8")
|
|
482
|
+
os.chmod(state_path, 0o600)
|
|
483
|
+
|
|
484
|
+
_write_precheck_health(
|
|
485
|
+
out_dir,
|
|
486
|
+
"ALERT_PENDING",
|
|
487
|
+
0,
|
|
488
|
+
cutoff_day=cutoff_day,
|
|
489
|
+
delivery_state=delivery_state,
|
|
490
|
+
new_sessions_count=len(new_sessions),
|
|
491
|
+
new_generated_output=new_output,
|
|
492
|
+
new_api_equiv_cost_usd=round(new_cost, 2),
|
|
493
|
+
)
|
|
494
|
+
print(json.dumps(alert_payload, indent=2))
|
|
495
|
+
return 0
|
|
496
|
+
|
|
497
|
+
|
|
498
|
+
def record_hook_command(
|
|
499
|
+
provider: str,
|
|
500
|
+
spool_file: Path,
|
|
501
|
+
emit_empty_json: bool = False,
|
|
502
|
+
) -> int:
|
|
503
|
+
"""Fast, fail-safe hook receiver reading stdin JSON and spooling 1:1 commit receipts."""
|
|
504
|
+
try:
|
|
505
|
+
raw = sys.stdin.read() if not sys.stdin.isatty() else ""
|
|
506
|
+
if raw.strip():
|
|
507
|
+
record_hook_invocation(raw, provider=provider, spool_path=spool_file)
|
|
508
|
+
except Exception:
|
|
509
|
+
pass
|
|
510
|
+
if emit_empty_json:
|
|
511
|
+
print("{}")
|
|
512
|
+
return 0
|
|
513
|
+
|
|
514
|
+
|
|
515
|
+
def main(argv=None) -> int:
|
|
516
|
+
parser = argparse.ArgumentParser(prog="tokenblame")
|
|
517
|
+
parser.add_argument("--tz", type=str, default=None, help="IANA timezone override (default: OS local timezone)")
|
|
518
|
+
sub = parser.add_subparsers(dest="cmd", required=False)
|
|
519
|
+
|
|
520
|
+
b = sub.add_parser("build", help="Harvest tokens, join 3 layers, and render observatory.html")
|
|
521
|
+
b.add_argument("--gwl-dir", type=Path, default=DEFAULT_GWL_CURRENT)
|
|
522
|
+
b.add_argument("--wl-root", type=Path, default=DEFAULT_WL_ROOT)
|
|
523
|
+
b.add_argument("--wb-root", type=Path, default=DEFAULT_WB_ROOT)
|
|
524
|
+
b.add_argument("--orca-dir", type=Path, default=DEFAULT_ORCA_DIR)
|
|
525
|
+
b.add_argument("--out-dir", type=Path, default=DEFAULT_OUT_DIR)
|
|
526
|
+
b.add_argument("--shareable", action="store_true", help="Also emit deep-redacted shareable-observatory.html & shareable-ir.json")
|
|
527
|
+
b.add_argument("--scan-root", type=Path, action="append", dest="scan_roots", default=None, help="Additional parent directory to scan for Git repos")
|
|
528
|
+
b.add_argument("--tz", type=str, default=None, help="IANA timezone override (default: OS local timezone)")
|
|
529
|
+
|
|
530
|
+
s = sub.add_parser("summary", help="Print compact JSON or Markdown summary from tokenblame.sqlite / observatory-ir.json")
|
|
531
|
+
s.add_argument("--days", type=int, default=None)
|
|
532
|
+
s.add_argument("--lane", type=str, default=None)
|
|
533
|
+
s.add_argument("--model", type=str, default=None)
|
|
534
|
+
s.add_argument("--json", action="store_true", dest="as_json")
|
|
535
|
+
s.add_argument("--gwl-dir", type=Path, default=DEFAULT_GWL_CURRENT)
|
|
536
|
+
s.add_argument("--wl-root", type=Path, default=DEFAULT_WL_ROOT)
|
|
537
|
+
s.add_argument("--out-dir", type=Path, default=DEFAULT_OUT_DIR)
|
|
538
|
+
s.add_argument("--tz", type=str, default=None, help="IANA timezone override (default: OS local timezone)")
|
|
539
|
+
|
|
540
|
+
o = sub.add_parser("open", help="Open observatory.html in Orca embedded browser or system browser")
|
|
541
|
+
o.add_argument("--refresh", action="store_true")
|
|
542
|
+
o.add_argument("--dry-run", action="store_true")
|
|
543
|
+
o.add_argument("--shareable", action="store_true")
|
|
544
|
+
o.add_argument("--gwl-dir", type=Path, default=DEFAULT_GWL_CURRENT)
|
|
545
|
+
o.add_argument("--wl-root", type=Path, default=DEFAULT_WL_ROOT)
|
|
546
|
+
o.add_argument("--out-dir", type=Path, default=DEFAULT_OUT_DIR)
|
|
547
|
+
o.add_argument("--tz", type=str, default=None, help="IANA timezone override (default: OS local timezone)")
|
|
548
|
+
|
|
549
|
+
p = sub.add_parser("precheck-burn", help="Deterministic fail-closed precheck for high-burn alerts (0=alert,1=ok,2=error)")
|
|
550
|
+
p.add_argument("--days", type=int, default=2)
|
|
551
|
+
p.add_argument("--min-cost", type=float, default=25.0)
|
|
552
|
+
p.add_argument("--min-output", type=int, default=100_000)
|
|
553
|
+
p.add_argument("--no-refresh", action="store_true")
|
|
554
|
+
p.add_argument("--defer-ack", action="store_true", help="Do not commit dedup keys until ack-burn-alert runs")
|
|
555
|
+
p.add_argument("--gwl-dir", type=Path, default=DEFAULT_GWL_CURRENT)
|
|
556
|
+
p.add_argument("--wl-root", type=Path, default=DEFAULT_WL_ROOT)
|
|
557
|
+
p.add_argument("--out-dir", type=Path, default=DEFAULT_OUT_DIR)
|
|
558
|
+
p.add_argument("--tz", type=str, default=None, help="IANA timezone override (default: OS local timezone)")
|
|
559
|
+
|
|
560
|
+
ab = sub.add_parser("ack-burn-alert", help="Commit pending_burn_alert.json candidate keys after confirmed delivery")
|
|
561
|
+
ab.add_argument("--out-dir", type=Path, default=DEFAULT_OUT_DIR)
|
|
562
|
+
|
|
563
|
+
rh = sub.add_parser("record-hook", help="Record post-tool commit provenance out-of-repo (fail-safe)")
|
|
564
|
+
rh.add_argument("--provider", type=str, default="claude")
|
|
565
|
+
rh.add_argument("--spool-file", type=Path, default=DEFAULT_OUT_DIR / "commit_provenance.jsonl")
|
|
566
|
+
rh.add_argument("--emit-empty-json", action="store_true")
|
|
567
|
+
|
|
568
|
+
ini = sub.add_parser("init", help="Safely install (or --uninstall) 1:1 commit provenance hooks for detected agents")
|
|
569
|
+
ini.add_argument("--claude", action="store_true", help="Target Claude Code (~/.claude/settings.json)")
|
|
570
|
+
ini.add_argument("--gemini", action="store_true", help="Target Gemini CLI (~/.gemini/settings.json)")
|
|
571
|
+
ini.add_argument("--uninstall", action="store_true", help="Remove TokenBlame hooks while preserving user hooks")
|
|
572
|
+
ini.add_argument("--dry-run", action="store_true", help="Preview hook changes without writing files")
|
|
573
|
+
ini.add_argument("--home-dir", type=Path, default=None, help="Override home directory (for testing)")
|
|
574
|
+
ini.add_argument("--json", action="store_true", dest="as_json")
|
|
575
|
+
|
|
576
|
+
doc = sub.add_parser("doctor", help="Inspect runtime prerequisites, agent transcript roots, hooks, and SQLite store")
|
|
577
|
+
doc.add_argument("--out-dir", type=Path, default=DEFAULT_OUT_DIR)
|
|
578
|
+
doc.add_argument("--home-dir", type=Path, default=None, help="Override home directory (for testing)")
|
|
579
|
+
doc.add_argument("--tz", type=str, default=None, help="IANA timezone override (default: OS local timezone)")
|
|
580
|
+
doc.add_argument("--json", action="store_true", dest="as_json")
|
|
581
|
+
|
|
582
|
+
args = parser.parse_args(argv)
|
|
583
|
+
tz_override = getattr(args, "tz", None)
|
|
584
|
+
if tz_override:
|
|
585
|
+
try:
|
|
586
|
+
resolve_local_tz(tz_override)
|
|
587
|
+
except Exception as exc:
|
|
588
|
+
print(f"invalid --tz value {tz_override!r}: {exc}", file=sys.stderr)
|
|
589
|
+
return 2
|
|
590
|
+
os.environ["TOKENBLAME_TZ"] = tz_override
|
|
591
|
+
|
|
592
|
+
if args.cmd is None:
|
|
593
|
+
build_command()
|
|
594
|
+
summary_command(DEFAULT_OUT_DIR, DEFAULT_GWL_CURRENT, DEFAULT_WL_ROOT, days=30)
|
|
595
|
+
return 0
|
|
596
|
+
if args.cmd == "build":
|
|
597
|
+
res = build_command(
|
|
598
|
+
args.gwl_dir,
|
|
599
|
+
args.wl_root,
|
|
600
|
+
args.out_dir,
|
|
601
|
+
args.wb_root,
|
|
602
|
+
args.orca_dir,
|
|
603
|
+
shareable=args.shareable,
|
|
604
|
+
extra_scan_roots=args.scan_roots,
|
|
605
|
+
)
|
|
606
|
+
print(json.dumps(res, indent=2))
|
|
607
|
+
return 0
|
|
608
|
+
if args.cmd == "summary":
|
|
609
|
+
summary_command(args.out_dir, args.gwl_dir, args.wl_root, args.days, args.lane, args.model, args.as_json)
|
|
610
|
+
return 0
|
|
611
|
+
if args.cmd == "open":
|
|
612
|
+
open_command(args.out_dir, args.gwl_dir, args.wl_root, args.refresh, args.dry_run, shareable=args.shareable)
|
|
613
|
+
return 0
|
|
614
|
+
if args.cmd == "precheck-burn":
|
|
615
|
+
return precheck_burn_command(
|
|
616
|
+
args.out_dir, args.gwl_dir, args.wl_root,
|
|
617
|
+
args.days, args.min_cost, args.min_output, args.no_refresh, args.defer_ack,
|
|
618
|
+
)
|
|
619
|
+
if args.cmd == "ack-burn-alert":
|
|
620
|
+
return ack_burn_alert_command(args.out_dir)
|
|
621
|
+
if args.cmd == "record-hook":
|
|
622
|
+
return record_hook_command(args.provider, args.spool_file, args.emit_empty_json)
|
|
623
|
+
if args.cmd == "init":
|
|
624
|
+
selected: list[str] = []
|
|
625
|
+
if args.claude:
|
|
626
|
+
selected.append("claude")
|
|
627
|
+
if args.gemini:
|
|
628
|
+
selected.append("gemini_cli")
|
|
629
|
+
res = init_hooks(
|
|
630
|
+
home_dir=args.home_dir,
|
|
631
|
+
providers=tuple(selected) if selected else ("auto",),
|
|
632
|
+
uninstall=args.uninstall,
|
|
633
|
+
dry_run=args.dry_run,
|
|
634
|
+
)
|
|
635
|
+
if args.as_json:
|
|
636
|
+
print(json.dumps(res, indent=2))
|
|
637
|
+
else:
|
|
638
|
+
if not res["results"]:
|
|
639
|
+
print("No supported agent config directories (~/.claude or ~/.gemini) detected.")
|
|
640
|
+
for item in res["results"]:
|
|
641
|
+
bak = f" (backup: {item['backup_path']})" if item.get("backup_path") else ""
|
|
642
|
+
print(f"[{item['provider']}] {item['status']}: {item['settings_path']}{bak}")
|
|
643
|
+
return 0 if all(r.get("status") != "error" for r in res["results"]) else 2
|
|
644
|
+
if args.cmd == "doctor":
|
|
645
|
+
rep = run_doctor(home_dir=args.home_dir, out_dir=args.out_dir, tz_name=tz_override)
|
|
646
|
+
if args.as_json:
|
|
647
|
+
print(json.dumps(rep, indent=2))
|
|
648
|
+
else:
|
|
649
|
+
print(f"# TokenBlame Doctor ({rep['status']})")
|
|
650
|
+
print(f"- Python: {rep['python_version']} | git: {'ok' if rep['git_available'] else 'MISSING'} | TZ: {rep['timezone']}")
|
|
651
|
+
detected = ", ".join(k for k, v in rep["agents_detected"].items() if v) or "none"
|
|
652
|
+
print(f"- Agent log roots detected: {detected}")
|
|
653
|
+
hooks_s = ", ".join(f"{k}={v}" for k, v in rep["hooks_status"].items())
|
|
654
|
+
print(f"- 1:1 Provenance hooks: {hooks_s}")
|
|
655
|
+
print(f"- Store: {rep['out_dir']} (sqlite={'yes' if rep['sqlite_store_exists'] else 'no'}, spool_records={rep['provenance_spool_records']})")
|
|
656
|
+
return 0 if rep["status"] == "OK" else 1
|
|
657
|
+
return 2
|
|
658
|
+
|
|
659
|
+
|
|
660
|
+
if __name__ == "__main__":
|
|
661
|
+
raise SystemExit(main())
|