@alexgreensh/token-optimizer 5.13.65 → 5.13.67

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 (44) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/hooks/hooks.json +0 -10
  4. package/hooks/module_runner.py +62 -13
  5. package/hooks/userpromptsubmit_runner.py +13 -1
  6. package/package.json +1 -1
  7. package/skills/token-optimizer/examples/hooks-starter.json +0 -10
  8. package/skills/token-optimizer/scripts/_measure/__init__.py +16 -0
  9. package/skills/token-optimizer/scripts/_measure/_compat.py +200 -0
  10. package/skills/token-optimizer/scripts/_measure/_vendor/README.md +9 -0
  11. package/skills/token-optimizer/scripts/_measure/_vendor/__init__.py +23 -0
  12. package/skills/token-optimizer/scripts/_measure/_vendor/tomli/LICENSE +21 -0
  13. package/skills/token-optimizer/scripts/_measure/_vendor/tomli/__init__.py +8 -0
  14. package/skills/token-optimizer/scripts/_measure/_vendor/tomli/_parser.py +770 -0
  15. package/skills/token-optimizer/scripts/_measure/_vendor/tomli/_re.py +112 -0
  16. package/skills/token-optimizer/scripts/_measure/_vendor/tomli/_types.py +10 -0
  17. package/skills/token-optimizer/scripts/_measure/_vendor/tomli/py.typed +1 -0
  18. package/skills/token-optimizer/scripts/_measure/audit.py +6949 -0
  19. package/skills/token-optimizer/scripts/_measure/cache_policy.py +7050 -0
  20. package/skills/token-optimizer/scripts/_measure/cli.py +2722 -0
  21. package/skills/token-optimizer/scripts/_measure/continuity.py +4630 -0
  22. package/skills/token-optimizer/scripts/_measure/daemon.py +6773 -0
  23. package/skills/token-optimizer/scripts/_measure/dashboard.py +4358 -0
  24. package/skills/token-optimizer/scripts/_measure/lifecycle.py +6145 -0
  25. package/skills/token-optimizer/scripts/_measure/pricing.py +2101 -0
  26. package/skills/token-optimizer/scripts/_measure/quality_archive.py +7138 -0
  27. package/skills/token-optimizer/scripts/_measure/runtime.py +1231 -0
  28. package/skills/token-optimizer/scripts/_measure/savings.py +7702 -0
  29. package/skills/token-optimizer/scripts/_measure/sessions.py +4784 -0
  30. package/skills/token-optimizer/scripts/_measure/trends.py +2432 -0
  31. package/skills/token-optimizer/scripts/antigravity_hook_bridge.py +11 -3
  32. package/skills/token-optimizer/scripts/bash_compress.py +3 -3
  33. package/skills/token-optimizer/scripts/bash_compress_hook.py +6 -7
  34. package/skills/token-optimizer/scripts/cloud_kit.py +7 -8
  35. package/skills/token-optimizer/scripts/codex_compact_prompt.py +2 -2
  36. package/skills/token-optimizer/scripts/codex_doctor.py +14 -0
  37. package/skills/token-optimizer/scripts/command_filters.py +630 -19
  38. package/skills/token-optimizer/scripts/devin_source.py +2 -1
  39. package/skills/token-optimizer/scripts/hermes_doctor.py +13 -0
  40. package/skills/token-optimizer/scripts/hermes_install.py +11 -0
  41. package/skills/token-optimizer/scripts/measure.py +2430 -60930
  42. package/skills/token-optimizer/scripts/read_cache.py +20 -21
  43. package/skills/token-optimizer/scripts/reset_epoch.py +177 -0
  44. package/skills/token-optimizer/scripts/session_store.py +11 -48
@@ -0,0 +1,4784 @@
1
+ """Definition-only implementations; mutable state belongs to measure."""
2
+ from __future__ import annotations
3
+ from . import _compat
4
+
5
+
6
+ def _find_all_jsonl_files(days=None):
7
+ """Find all JSONL session files across all projects within the given day window."""
8
+ _measure_facade = _compat.facade()
9
+ if _measure_facade._use_codex_session_adapter():
10
+ return _measure_facade.codex_session.find_all_jsonl_files(days if days is not None else 36500)
11
+
12
+ # Hermes (cross-platform universality): Hermes sessions live in
13
+ # ~/.hermes/state.db and are ingested into trends.db via hermes-rollup /
14
+ # _collect_hermes_sessions — they are NOT stored as ~/.claude/projects
15
+ # JSONL. Returning [] here keeps the JSONL fallback path of
16
+ # _collect_trends_data() (reached by the hermes-exempted `dashboard`
17
+ # command when trends.db is empty) from scanning ~/.claude, and is
18
+ # defense-in-depth for the dispatch-blocked scan subcommands.
19
+ if _measure_facade._use_hermes_session_adapter():
20
+ return []
21
+ # Antigravity sessions are read from ~/.gemini via antigravity-rollup and
22
+ # _collect_antigravity_sessions, never ~/.claude/projects JSONL.
23
+ if _measure_facade._use_antigravity_session_adapter():
24
+ return []
25
+
26
+ # Cursor (cross-platform universality, same as Hermes): sessions
27
+ # live in the hook tally and are ingested via cursor-rollup, not
28
+ # ~/.claude/projects JSONL. Returning [] keeps the JSONL fallback path of
29
+ # the cursor-exempted dashboard command from scanning ~/.claude.
30
+ if _measure_facade._use_cursor_session_adapter():
31
+ return []
32
+
33
+ projects_base = _measure_facade.CLAUDE_DIR / "projects"
34
+ if not projects_base.exists():
35
+ return []
36
+
37
+ cutoff = _measure_facade.datetime.now().timestamp() - (days * 86400) if days is not None else float("-inf")
38
+ results = []
39
+ for project_dir in projects_base.iterdir():
40
+ if not project_dir.is_dir():
41
+ continue
42
+ for jf in project_dir.glob("*.jsonl"):
43
+ try:
44
+ mtime = jf.stat().st_mtime
45
+ if mtime >= cutoff:
46
+ results.append((jf, mtime, project_dir.name))
47
+ except OSError:
48
+ continue
49
+ results.sort(key=lambda x: ((_measure_facade := _compat.facade()), x[1])[1], reverse=True)
50
+ return results
51
+
52
+
53
+ def _find_subagent_jsonl_files(session_jsonl_path):
54
+ """Find subagent JSONL files for a given session.
55
+
56
+ Claude Code stores subagent logs in {session-uuid}/subagents/*.jsonl
57
+ next to the parent {session-uuid}.jsonl file.
58
+ """
59
+ _measure_facade = _compat.facade()
60
+ session_dir = session_jsonl_path.parent / session_jsonl_path.stem
61
+ subagent_dir = session_dir / "subagents"
62
+ if not subagent_dir.is_dir():
63
+ return []
64
+ results = []
65
+ for jf in subagent_dir.glob("*.jsonl"):
66
+ try:
67
+ if jf.stat().st_size > 0:
68
+ results.append(jf)
69
+ except OSError:
70
+ continue
71
+ return results
72
+
73
+
74
+ def _extract_skills_and_agents_from_subagent(filepath):
75
+ """Parse a subagent JSONL file for Skill and Task tool calls only.
76
+
77
+ Returns (skills_dict, subagents_dict) without extracting token usage.
78
+ Model-level token attribution is handled separately in collect_sessions()
79
+ via _parse_session_jsonl() on each subagent file (the model attribution fix).
80
+ """
81
+ _measure_facade = _compat.facade()
82
+ skills = {}
83
+ subagents = {}
84
+ try:
85
+ if _measure_facade.os.stat(filepath).st_size > _measure_facade.codex_session.MAX_PARSE_FILE_BYTES:
86
+ return skills, subagents
87
+ except OSError:
88
+ return skills, subagents
89
+ try:
90
+ with open(filepath, "r", encoding="utf-8", errors="replace") as f:
91
+ for line in f:
92
+ if len(line) > _measure_facade.codex_session.MAX_JSONL_LINE_CHARS:
93
+ continue
94
+ try:
95
+ record = _measure_facade.json.loads(line)
96
+ except _measure_facade.json.JSONDecodeError:
97
+ continue
98
+ if not isinstance(record, dict):
99
+ continue
100
+ if record.get("type") != "assistant":
101
+ continue
102
+ msg = record.get("message", {})
103
+ if not isinstance(msg, dict):
104
+ continue
105
+ content = msg.get("content", [])
106
+ if not isinstance(content, list):
107
+ continue
108
+ for block in content:
109
+ if not isinstance(block, dict) or block.get("type") != "tool_use":
110
+ continue
111
+ tool_name = block.get("name", "")
112
+ inp = block.get("input", {})
113
+ if not isinstance(inp, dict):
114
+ inp = {}
115
+ if tool_name == "Skill":
116
+ skill = inp.get("skill", "unknown")
117
+ skills[skill] = skills.get(skill, 0) + 1
118
+ elif tool_name in ("Task", "Agent"):
119
+ # Current Claude Code names the sub-agent tool "Agent";
120
+ # older transcripts used "Task". Match both, exactly, so
121
+ # the TaskCreate/TaskUpdate todo tools are not miscounted.
122
+ agent_type = inp.get("subagent_type", "unknown")
123
+ subagents[agent_type] = subagents.get(agent_type, 0) + 1
124
+ except (PermissionError, OSError):
125
+ pass
126
+ return skills, subagents
127
+
128
+
129
+ def _extract_agent_type(subagent_file):
130
+ """Extract the agent type for a subagent JSONL file.
131
+
132
+ Priority: .meta.json agentType > filename pattern > filename stem.
133
+ Auto-compaction agents (filename contains 'acompact') are labeled explicitly.
134
+ """
135
+ _measure_facade = _compat.facade()
136
+ sf = _measure_facade.Path(subagent_file) if not isinstance(subagent_file, _measure_facade.Path) else subagent_file
137
+
138
+ # Auto-compaction agents are internal, not user-dispatched
139
+ if "acompact" in sf.stem:
140
+ return "Auto-Compaction"
141
+
142
+ # Check .meta.json (written by Claude Code for user-dispatched agents)
143
+ meta_path = sf.with_suffix(".meta.json")
144
+ if meta_path.exists():
145
+ try:
146
+ with open(meta_path, "r", encoding="utf-8") as mf:
147
+ meta = _measure_facade.json.load(mf)
148
+ agent_type = meta.get("agentType", "")
149
+ if agent_type:
150
+ return agent_type
151
+ except (_measure_facade.json.JSONDecodeError, OSError):
152
+ pass
153
+
154
+ return "unknown"
155
+
156
+
157
+ def _analyze_subagent_costs(session_jsonl_path, tier=None):
158
+ """Parse subagent JSONL files for a session and return cost breakdown.
159
+
160
+ Returns list of dicts grouped by agent type: [{name, tokens, cost_usd, model, count}]
161
+ Auto-compaction agents are separated from user-dispatched agents.
162
+ """
163
+ _measure_facade = _compat.facade()
164
+ if tier is None:
165
+ tier = _measure_facade._load_pricing_tier()
166
+ subagent_files = _measure_facade._find_subagent_jsonl_files(_measure_facade.Path(session_jsonl_path))
167
+
168
+ # Collect per-file costs, then group by agent type
169
+ by_type = {} # {agent_type: {tokens, cost_usd, model_tokens, count}}
170
+ for sf in subagent_files:
171
+ parsed = _measure_facade._parse_session_jsonl(str(sf))
172
+ if not parsed or parsed.get("total_input_tokens", 0) == 0:
173
+ continue
174
+ dom_model = max(parsed["model_usage"], key=parsed["model_usage"].get) if parsed["model_usage"] else "unknown"
175
+ total_input = parsed["total_input_tokens"]
176
+ chr_val = parsed.get("cache_hit_rate", 0)
177
+ cache_read = _measure_facade._safe_int(total_input * chr_val)
178
+ cost = _measure_facade._get_model_cost(dom_model, max(0, total_input - cache_read),
179
+ parsed["total_output_tokens"], cache_read, 0, tier=tier)
180
+
181
+ agent_type = _measure_facade._extract_agent_type(sf)
182
+ norm_model = _measure_facade._normalize_model_name(dom_model) or dom_model
183
+
184
+ if agent_type not in by_type:
185
+ by_type[agent_type] = {"tokens": 0, "cost_usd": 0.0, "models": {}, "count": 0}
186
+ entry = by_type[agent_type]
187
+ entry["tokens"] += total_input + parsed["total_output_tokens"]
188
+ entry["cost_usd"] += cost
189
+ entry["count"] += 1
190
+ entry["models"][norm_model] = entry["models"].get(norm_model, 0) + 1
191
+
192
+ results = []
193
+ for agent_type, data in by_type.items():
194
+ # Pick the most common model for this agent type
195
+ dominant_model = max(data["models"], key=data["models"].get) if data["models"] else "unknown"
196
+ label = agent_type
197
+ if data["count"] > 1:
198
+ label = f"{agent_type} ({data['count']}x)"
199
+ results.append({
200
+ "name": label,
201
+ "tokens": data["tokens"],
202
+ "cost_usd": round(data["cost_usd"], 4),
203
+ "model": dominant_model,
204
+ "count": data["count"],
205
+ })
206
+ results.sort(key=lambda x: ((_measure_facade := _compat.facade()), x["cost_usd"])[1], reverse=True)
207
+ return results
208
+
209
+
210
+ def _extract_costly_prompts(jsonl_path, tier=None, top_n=None):
211
+ """Extract user prompts paired with the cost of the subsequent assistant turn.
212
+
213
+ Returns list of dicts: [{text, tokens_in, tokens_out, cost_usd, model, timestamp}]
214
+ sorted by cost descending, limited to top_n.
215
+ """
216
+ _measure_facade = _compat.facade()
217
+ if tier is None:
218
+ tier = _measure_facade._load_pricing_tier()
219
+ prompts = []
220
+ pending_prompt = None
221
+
222
+ try:
223
+ if _measure_facade.os.stat(jsonl_path).st_size > _measure_facade.codex_session.MAX_PARSE_FILE_BYTES:
224
+ return prompts
225
+ except OSError:
226
+ return prompts
227
+
228
+ try:
229
+ with open(jsonl_path, "r", encoding="utf-8", errors="replace") as f:
230
+ for line in f:
231
+ if len(line) > _measure_facade.codex_session.MAX_JSONL_LINE_CHARS:
232
+ continue
233
+ try:
234
+ record = _measure_facade.json.loads(line)
235
+ except _measure_facade.json.JSONDecodeError:
236
+ continue
237
+ if not isinstance(record, dict):
238
+ continue
239
+
240
+ rec_type = record.get("type")
241
+
242
+ if rec_type == "user":
243
+ # Check it's a real user prompt, not a tool result
244
+ msg = record.get("message", {})
245
+ is_sidechain = record.get("isSidechain", False)
246
+ if is_sidechain:
247
+ continue
248
+ content = msg.get("content") if isinstance(msg, dict) else msg
249
+ if isinstance(content, list):
250
+ # Skip if all items are tool_result
251
+ types = [i.get("type") for i in content if isinstance(i, dict)]
252
+ if types and all(t == "tool_result" for t in types):
253
+ continue
254
+ # Same filter as checkpoints: harness text (meta records,
255
+ # compact summaries, command caveats) is not a prompt.
256
+ text = _measure_facade._task_user_text(record)
257
+ if text and len(text) > 5:
258
+ pending_prompt = {
259
+ "text": text[:300],
260
+ "timestamp": record.get("timestamp"),
261
+ }
262
+
263
+ elif rec_type == "assistant" and pending_prompt:
264
+ msg = record.get("message", {})
265
+ if not isinstance(msg, dict):
266
+ msg = {}
267
+ usage = msg.get("usage", {})
268
+ if usage and isinstance(usage, dict):
269
+ inp = _measure_facade._safe_int(usage.get("input_tokens", 0))
270
+ out = _measure_facade._safe_int(usage.get("output_tokens", 0))
271
+ cr = _measure_facade._safe_int(usage.get("cache_read_input_tokens", 0))
272
+ cc = _measure_facade._safe_int(usage.get("cache_creation_input_tokens", 0))
273
+ model = _measure_facade._record_model(msg)
274
+ cost = _measure_facade._price_usage_parts(
275
+ _measure_facade._billed_usage_parts(usage, model, tier=tier),
276
+ tier=tier, per_request=True, ttl_split=False)
277
+ pending_prompt["tokens_in"] = inp + cr + cc
278
+ pending_prompt["tokens_out"] = out
279
+ pending_prompt["fresh_input"] = inp
280
+ pending_prompt["cache_read"] = cr
281
+ pending_prompt["cache_create"] = cc
282
+ pending_prompt["cost_usd"] = round(cost, 4)
283
+ pending_prompt["model"] = _measure_facade._normalize_model_name(model) or model
284
+ prompts.append(pending_prompt)
285
+ pending_prompt = None
286
+
287
+ except (OSError, PermissionError):
288
+ pass
289
+
290
+ prompts.sort(key=lambda x: ((_measure_facade := _compat.facade()), x.get("cost_usd", 0))[1], reverse=True)
291
+ return prompts[:top_n]
292
+
293
+
294
+ def _clean_project_name(raw_project):
295
+ """Map Claude Code dashed directory names to human-readable labels.
296
+
297
+ e.g. "-Users-jane" -> "home"
298
+ "-Users-jane-projects-acme-api" -> "acme/api"
299
+ "-Users-jane-myproject" -> "myproject"
300
+ """
301
+ _measure_facade = _compat.facade()
302
+ if not raw_project:
303
+ return "unknown"
304
+ # Strip the leading "-Users-<username>-" prefix
305
+ cleaned = _measure_facade.re.sub(r"^-Users-[^-]+-?", "", raw_project)
306
+ if not cleaned:
307
+ return "home"
308
+ # Split remaining path segments and take the last 1-2 meaningful ones
309
+ parts = cleaned.split("-")
310
+ # Filter out empty parts
311
+ parts = [p for p in parts if p]
312
+ if not parts:
313
+ return "home"
314
+ # If the path is long, use last 2 segments joined by /
315
+ if len(parts) > 2:
316
+ return "/".join(parts[-2:])
317
+ return "/".join(parts)
318
+
319
+
320
+ def _extract_topic(text):
321
+ """Extract a clean topic from the first user message text.
322
+
323
+ Strips common prefixes like 'Implement the following plan:' and
324
+ extracts the plan title if present. Truncates to 120 chars.
325
+ """
326
+ _measure_facade = _compat.facade()
327
+ if not text or not isinstance(text, str):
328
+ return None
329
+ # Strip leading whitespace/newlines
330
+ text = text.strip()
331
+ # Strip ANSI/VT escape sequences — session-log text is attacker-influenceable
332
+ text = _measure_facade._strip_ansi(text)
333
+ # Remove common prefixes
334
+ prefixes = [
335
+ "Implement the following plan:",
336
+ "Implement the following plan\n",
337
+ "Please implement the following plan:",
338
+ "Execute the following plan:",
339
+ ]
340
+ for prefix in prefixes:
341
+ if text.lower().startswith(prefix.lower()):
342
+ text = text[len(prefix):].strip()
343
+ break
344
+ # If it starts with a markdown heading, extract that as the topic
345
+ for line in text.split("\n"):
346
+ line = line.strip()
347
+ if line.startswith("#"):
348
+ text = line.lstrip("# ").strip()
349
+ break
350
+ if line:
351
+ text = line
352
+ break
353
+ # The topic is user text persisted to session_log/quality-cache and
354
+ # rendered into checkpoints — credentials must not ride along. If the
355
+ # shared redactor is unavailable or refuses, drop the topic rather than
356
+ # persist it raw. Redact BEFORE truncating: a secret that straddles the
357
+ # cut is a prefix no pattern recognises.
358
+ try:
359
+ from credential_patterns import redact_credentials as _topic_redact
360
+ text = _topic_redact(text)
361
+ except Exception:
362
+ return None
363
+ if len(text) > 120:
364
+ text = text[:117] + "..."
365
+ return text or None
366
+
367
+
368
+ def _leading_user_text(message):
369
+ """Return the leading user-authored text of a user message, or ''.
370
+
371
+ A real slash invocation IS the whole user turn, so we look only at the first
372
+ text the user actually typed. tool_result blocks (tool returns are written as
373
+ user-role records) are excluded, so a search hit or a pasted transcript
374
+ fragment that happens to echo a <command-name> block is not read as an
375
+ invocation.
376
+ """
377
+ _measure_facade = _compat.facade()
378
+ content = message.get("content") if isinstance(message, dict) else message
379
+ if isinstance(content, str):
380
+ return content
381
+ if isinstance(content, list):
382
+ for block in content:
383
+ if not isinstance(block, dict):
384
+ return ""
385
+ btype = block.get("type")
386
+ if btype == "text":
387
+ return block.get("text", "") or ""
388
+ # A tool_result (or any non-text) leading block means this user record
389
+ # is not a typed invocation.
390
+ return ""
391
+ return ""
392
+
393
+
394
+ def _resolve_installed_skill(name):
395
+ """Map a slash-command name to the INSTALLED skill's directory name, or None.
396
+
397
+ Mirrors the never-used normalization (exact dir name / SKILL.md name via
398
+ name_to_dir / namespaced ``plugin:skill``). Returns None for anything that is
399
+ not an installed skill -- built-in commands (/clear, /compact, ...) and custom
400
+ non-skill commands resolve to None, so they never pollute skill-usage stats.
401
+ """
402
+ _measure_facade = _compat.facade()
403
+ if not name:
404
+ return None
405
+ try:
406
+ comp = _measure_facade._cached_measure_components()
407
+ skills = comp.get("skills", {})
408
+ installed = set(skills.get("names", []))
409
+ name_to_dir = skills.get("name_to_dir", {}) or {}
410
+ except Exception:
411
+ return None
412
+ if name in installed:
413
+ return name
414
+ if name in name_to_dir:
415
+ return name_to_dir[name]
416
+ if ":" in name:
417
+ parent, _, child = name.partition(":")
418
+ for cand in (parent, child):
419
+ if cand in installed:
420
+ return cand
421
+ if cand in name_to_dir:
422
+ return name_to_dir[cand]
423
+ return None
424
+
425
+
426
+ def _sidechain_path_reason(filepath):
427
+ """Return the structural sidechain reason for a nested agent transcript."""
428
+ _measure_facade = _compat.facade()
429
+ path = _measure_facade.Path(filepath)
430
+ if "subagents" in path.parts or (path.name.startswith("agent-") and path.suffix == ".jsonl"):
431
+ return "nested_path"
432
+ return None
433
+
434
+
435
+ def _osrc_prompt_text(record):
436
+ """Extract only human-authored text from one user record."""
437
+ _measure_facade = _compat.facade()
438
+ if record.get("type") != "user":
439
+ return ""
440
+ message = record.get("message") or {}
441
+ content = message.get("content") if isinstance(message, dict) else message
442
+ if isinstance(content, str):
443
+ return content
444
+ if isinstance(content, list):
445
+ return "\n".join(
446
+ block.get("text") or ""
447
+ if isinstance(block, dict) and block.get("type") == "text"
448
+ else block
449
+ if isinstance(block, str)
450
+ else ""
451
+ for block in content
452
+ )
453
+ return ""
454
+
455
+
456
+ def _usage_request_key(record, msg=None):
457
+ """Identity of the API request an assistant record belongs to.
458
+
459
+ Claude Code writes `requestId` on every record of a request. Transcripts
460
+ produced by the SDK or imported from a cloud session carry only the
461
+ Anthropic `message.id`, which is equally stable across the streamed chunks
462
+ of one reply. Returns None when the record has neither, so the caller can
463
+ keep it as its own request instead of collapsing unrelated records.
464
+ """
465
+ _measure_facade = _compat.facade()
466
+ req_id = record.get("requestId")
467
+ if req_id:
468
+ return str(req_id)
469
+ if msg is None:
470
+ msg = record.get("message")
471
+ if isinstance(msg, dict):
472
+ mid = msg.get("id")
473
+ if mid:
474
+ return str(mid)
475
+ return None
476
+
477
+
478
+ def _request_local_day(ts_s):
479
+ """Local calendar date of an ISO timestamp, or None when it does not parse."""
480
+ _measure_facade = _compat.facade()
481
+ if not (ts_s and isinstance(ts_s, str)):
482
+ return None
483
+ try:
484
+ return _measure_facade.datetime.fromisoformat(ts_s.replace("Z", "+00:00")).astimezone().strftime("%Y-%m-%d")
485
+ except (ValueError, TypeError, OverflowError, OSError):
486
+ return None
487
+
488
+
489
+ def _empty_model_buckets():
490
+ _measure_facade = _compat.facade()
491
+ return {"fresh_input": 0, "cache_read": 0, "cache_create": 0,
492
+ "cache_create_1h": 0, "cache_create_5m": 0, "output": 0}
493
+
494
+
495
+ def _net_request_is_empty(u):
496
+ """True for a request entry that adds nothing to a session: another session
497
+ already counted the call and every token of it."""
498
+ _measure_facade = _compat.facade()
499
+ return (not u.get("n", 1)
500
+ and not any(int(u.get(f) or 0) for f in ("inp", "out", "cr", "cc", "cc_1h", "cc_5m")))
501
+
502
+
503
+ def _aggregate_request_usage(requests):
504
+ """Roll a {request key: usage} map up into session totals.
505
+
506
+ `requests` holds the final (streaming-MAX) usage of each API request. Every
507
+ per-session figure derived from usage (token totals, per-model buckets,
508
+ per-day buckets, API call count) comes from here, so a parse, a merge of
509
+ several files and a filtered view of either all agree. Returns
510
+ (totals, request_days).
511
+ """
512
+ _measure_facade = _compat.facade()
513
+ totals = {
514
+ "total_input": 0, "total_output": 0, "total_cache_read": 0,
515
+ "total_cache_create": 0, "total_cache_create_1h": 0,
516
+ "total_cache_create_5m": 0, "api_calls": 0, "api_call_timestamps": [],
517
+ "model_usage": {}, "model_usage_breakdown": {}, "daily_usage": {},
518
+ }
519
+ request_days = {}
520
+ for key, u in requests.items():
521
+ if _measure_facade._net_request_is_empty(u):
522
+ continue
523
+ totals["total_input"] += u["inp"]
524
+ totals["total_output"] += u["out"]
525
+ totals["total_cache_read"] += u["cr"]
526
+ totals["total_cache_create"] += u["cc"]
527
+ totals["total_cache_create_1h"] += u["cc_1h"]
528
+ totals["total_cache_create_5m"] += u["cc_5m"]
529
+ ts_s = u.get("ts")
530
+ if not u.get("advisor") and u.get("n", 1):
531
+ # An advisor part belongs to its request: not another API call.
532
+ # `n` is 0 when another session already counted the call itself.
533
+ totals["api_calls"] += 1
534
+ if ts_s and isinstance(ts_s, str):
535
+ try:
536
+ totals["api_call_timestamps"].append(
537
+ _measure_facade.datetime.fromisoformat(ts_s.replace("Z", "+00:00")))
538
+ except (ValueError, TypeError):
539
+ pass
540
+ model = u["model"]
541
+ billable = u["inp"] + u["cc"] + u["out"] # fresh + cache_create + output
542
+ totals["model_usage"][model] = totals["model_usage"].get(model, 0) + billable
543
+ bd = totals["model_usage_breakdown"].setdefault(model, _measure_facade._empty_model_buckets())
544
+ bd["fresh_input"] += u["inp"]
545
+ bd["cache_read"] += u["cr"]
546
+ bd["cache_create"] += u["cc"]
547
+ bd["cache_create_1h"] += u["cc_1h"]
548
+ bd["cache_create_5m"] += u["cc_5m"]
549
+ bd["output"] += u["out"]
550
+ # Bucket each request by the LOCAL date it ran, so a session that spans
551
+ # midnight bills each day for its own requests instead of dumping the
552
+ # whole session onto its last-active day (#200). Records without a
553
+ # parseable timestamp are left out here; callers fall back to the
554
+ # session date for the unbucketed remainder.
555
+ day = u["day"] if "day" in u else _measure_facade._request_local_day(ts_s)
556
+ request_days[key] = day
557
+ if day:
558
+ dbd = totals["daily_usage"].setdefault(day, {}).setdefault(model, _measure_facade._empty_model_buckets())
559
+ dbd["fresh_input"] += u["inp"]
560
+ dbd["cache_read"] += u["cr"]
561
+ dbd["cache_create"] += u["cc"]
562
+ dbd["cache_create_1h"] += u["cc_1h"]
563
+ dbd["cache_create_5m"] += u["cc_5m"]
564
+ dbd["output"] += u["out"]
565
+ return totals, request_days
566
+
567
+
568
+ def _parse_session_jsonl(filepath, window_start=None, window_end=None):
569
+ """Parse a single JSONL session file in one streaming pass.
570
+
571
+ Returns a dict with extracted session metrics, or None if the file
572
+ is empty or unparseable. Results are memoized by (path, mtime, size)
573
+ so a single process invocation never re-parses the same unchanged file
574
+ (e.g. backfill + collect both touching the same transcript).
575
+ """
576
+ # Memoization: skip re-parse if the file hasn't changed since we last saw it.
577
+ _measure_facade = _compat.facade()
578
+ try:
579
+ st = _measure_facade.os.stat(filepath)
580
+ cache_key = (str(filepath), st.st_mtime_ns, st.st_size, window_start, window_end)
581
+ if cache_key in _measure_facade._parse_session_jsonl_cache:
582
+ return _measure_facade._parse_session_jsonl_cache[cache_key]
583
+ except OSError:
584
+ cache_key = None # stat failed — parse without caching
585
+
586
+ if _measure_facade._use_codex_session_adapter(filepath):
587
+ if window_start is not None or window_end is not None:
588
+ return None # This adapter does not yet support activity slicing.
589
+ result = _measure_facade.codex_session.parse_session_jsonl(filepath)
590
+ if cache_key is not None:
591
+ if len(_measure_facade._parse_session_jsonl_cache) >= _measure_facade._PARSE_CACHE_MAX:
592
+ _measure_facade._parse_session_jsonl_cache.clear()
593
+ _measure_facade._parse_session_jsonl_cache[cache_key] = result
594
+ return result
595
+
596
+ daily_metrics = {}
597
+ skills_used = {}
598
+ subagents_used = {}
599
+ tool_calls = {}
600
+ request_usage_map = {} # v5.4.9: per-requestId MAX usage (streaming-aware)
601
+ total_input = 0
602
+ total_output = 0
603
+ total_cache_read = 0
604
+ total_cache_create = 0
605
+ total_cache_create_1h = 0
606
+ total_cache_create_5m = 0
607
+ model_usage = {} # v5.4.8: billable tokens (fresh_input + cache_create + output)
608
+ model_usage_breakdown = {} # v5.4.8: per-model {fresh_input, cache_read, cache_create, output}
609
+ daily_usage = {} # local date -> per-model breakdown, for per-day cost attribution
610
+ request_days = {} # request key -> local date (None when untimestamped)
611
+ reported_input = 0 # official /stats-compatible, no streaming dedup
612
+ reported_output = 0
613
+ reported_model_usage = {}
614
+ version = None
615
+ slug = None
616
+ topic = None
617
+ first_ts = None
618
+ last_ts = None
619
+ api_call_timestamps = []
620
+ message_count = 0
621
+ _counted_message_ids = set() # dedup streamed assistant chunks -> one reply
622
+ _conversation_records = 0 # RAW user/assistant records seen (transcript-is-real test)
623
+ api_calls = 0
624
+ sidechain_reason = _measure_facade._sidechain_path_reason(filepath)
625
+ is_sidechain = sidechain_reason is not None
626
+ first_user_record_seen = False
627
+
628
+ # Bound the work like the Codex adapter's _iter_json_records: a multi-GB
629
+ # transcript or one pathological line must not dominate a parse. st is set
630
+ # when the initial os.stat above succeeded; skip oversized files outright
631
+ # and oversized lines individually.
632
+ if cache_key is not None and st.st_size > _measure_facade.codex_session.MAX_PARSE_FILE_BYTES:
633
+ return None
634
+
635
+ try:
636
+ with open(filepath, "r", encoding="utf-8", errors="replace") as f:
637
+ for line in f:
638
+ if len(line) > _measure_facade.codex_session.MAX_JSONL_LINE_CHARS:
639
+ continue
640
+ try:
641
+ record = _measure_facade.json.loads(line)
642
+ except _measure_facade.json.JSONDecodeError:
643
+ continue
644
+ if not isinstance(record, dict):
645
+ # Valid JSON but not an object (42, "x", true, null, [...])
646
+ # — a truncated/corrupt transcript line, not a record.
647
+ continue
648
+
649
+ # A subagent sidechain transcript is flagged on its records; any
650
+ # such record marks the whole file as a sidechain (not a human
651
+ # working session) so the cost comparison can exclude it.
652
+ if record.get("isSidechain") is True:
653
+ is_sidechain = True
654
+ sidechain_reason = "isSidechain"
655
+
656
+ # Detect outsourcerer delegation sessions by content marker.
657
+ # The outsourcerer skill injects an OSRC::PROGRESS protocol
658
+ # block into the delegation PROMPT, so the marker only proves
659
+ # delegation when it appears in a human prompt.
660
+ #
661
+ # Scanning the whole record (the pre-fix behaviour) also matched
662
+ # the marker inside tool RESULTS and assistant text, so an
663
+ # orchestrator session that merely *watches* a delegate (running
664
+ # `outsourcerer.sh status/watch/result`, whose output echoes
665
+ # OSRC::PROGRESS) was itself misfiled as the delegation. That
666
+ # mislabelled 234 of a user's sessions holding 57% of all input
667
+ # tokens -- the longest human working sessions -- and pulled them
668
+ # out of the human pool the cost comparison runs on.
669
+ #
670
+ # Only `type == "user"` records count, and within them only real
671
+ # prompt text: a user record whose content blocks are tool_result
672
+ # is the transport for a tool's output, not something a human
673
+ # typed.
674
+ if record.get("type") == "user" and not first_user_record_seen:
675
+ _prompt = _measure_facade._osrc_prompt_text(record)
676
+ if _prompt:
677
+ first_user_record_seen = True
678
+ if _prompt and not is_sidechain:
679
+ if "OSRC::PROGRESS" in _prompt or "OSRC::DONE" in _prompt:
680
+ is_sidechain = True
681
+ sidechain_reason = "osrc_prompt"
682
+
683
+ # Extract version (take the first non-None we see)
684
+ if version is None:
685
+ v = record.get("version")
686
+ if v:
687
+ version = v
688
+
689
+ # Extract slug (first record that has one)
690
+ if slug is None:
691
+ s = record.get("slug")
692
+ if s:
693
+ slug = s
694
+
695
+ # Window reports must slice activity, including sessions that began
696
+ # before reset. Classify sidechains before filtering their records.
697
+ if window_start is not None or window_end is not None:
698
+ try:
699
+ activity_ts = _measure_facade.datetime.fromisoformat(
700
+ str(record.get("timestamp")).replace("Z", "+00:00"))
701
+ if activity_ts.tzinfo is None:
702
+ activity_ts = activity_ts.replace(tzinfo=_measure_facade.timezone.utc)
703
+ except (ValueError, TypeError):
704
+ continue
705
+ if window_start is not None and activity_ts < window_start:
706
+ continue
707
+ if window_end is not None and activity_ts >= window_end:
708
+ continue
709
+
710
+ # Extract timestamp
711
+ ts_str = record.get("timestamp")
712
+ if ts_str and isinstance(ts_str, str):
713
+ try:
714
+ ts = _measure_facade.datetime.fromisoformat(ts_str.replace("Z", "+00:00"))
715
+ if first_ts is None:
716
+ first_ts = ts
717
+ last_ts = ts
718
+ except (ValueError, TypeError):
719
+ pass
720
+
721
+ record_day = _measure_facade._request_local_day(ts_str)
722
+ prior_messages = message_count
723
+ prior_maps = [dict(v) for v in (skills_used, subagents_used, tool_calls)]
724
+ rec_type = record.get("type")
725
+
726
+ # Topic and checkpoint task share a human-task-only view. Keep
727
+ # raw user text for message scoring and slash-skill accounting.
728
+ if rec_type == "user" and topic is None:
729
+ topic = _measure_facade._extract_topic(_measure_facade._task_user_text(record))
730
+
731
+ if rec_type in ("user", "assistant"):
732
+ _conversation_records += 1
733
+
734
+ # Count user/assistant messages.
735
+ #
736
+ # Two things inflated this against any external message count
737
+ # (Claude Code's own /stats panel reported 181,935 where we
738
+ # reported 196,069 for the same window):
739
+ #
740
+ # 1. STREAMING DUPLICATES. Claude Code writes MULTIPLE assistant
741
+ # records per `requestId` while streaming -- the same reply,
742
+ # chunk by chunk. Counting records counted one reply many
743
+ # times (3,819 raw vs 2,239 deduped on one real session).
744
+ # Token accounting already dedups these per requestId a few
745
+ # lines below; the message counter never did.
746
+ # 2. TOOL-RESULT TRANSPORT. A `user` record whose content blocks
747
+ # are all `tool_result` is how a tool's OUTPUT is carried back
748
+ # to the model. Nobody typed it, so it is not a message.
749
+ #
750
+ # `message_count` feeds per-session quality scoring and every
751
+ # per-session average on the dashboard, so both inflations pushed
752
+ # those averages down. Count a reply ONCE, and only count a user
753
+ # record a human actually authored.
754
+ if rec_type == "assistant":
755
+ _mid = None
756
+ _m = record.get("message")
757
+ if isinstance(_m, dict):
758
+ _mid = _m.get("id") or record.get("requestId")
759
+ _mid = _mid or record.get("requestId")
760
+ if _mid is None:
761
+ message_count += 1 # no id to dedup on: count it
762
+ elif _mid not in _counted_message_ids:
763
+ _counted_message_ids.add(_mid)
764
+ message_count += 1
765
+ elif rec_type == "user":
766
+ _m = record.get("message")
767
+ _c = _m.get("content") if isinstance(_m, dict) else _m
768
+ if isinstance(_c, list) and _c and all(
769
+ isinstance(b, dict) and b.get("type") == "tool_result" for b in _c
770
+ ):
771
+ pass # tool output, not a human turn
772
+ elif record.get("isMeta") or record.get("isCompactSummary"):
773
+ pass # harness-written, not a human turn
774
+ else:
775
+ message_count += 1
776
+
777
+ # Count slash-command invocations of INSTALLED skills as usage. A
778
+ # skill run via /name (e.g. /briefing) emits no Skill tool_use, so
779
+ # it would otherwise be scored "unused". Gate strictly so nothing
780
+ # else leaks into skill stats: a real invocation IS the whole user
781
+ # turn, so require the command block to be the LEADING user-authored
782
+ # text (a pasted fragment in prose or a tool_result echo is not),
783
+ # require the <command-args> sibling Claude Code always emits, and
784
+ # count ONLY names that resolve to an installed skill (so /clear,
785
+ # /compact and other non-skill commands never pollute skill stats).
786
+ if rec_type == "user":
787
+ _lead = _measure_facade._leading_user_text(record.get("message", {})).lstrip()
788
+ if _lead.startswith("<command-name>") and "<command-args>" in _lead:
789
+ for _cn in _measure_facade._SLASH_COMMAND_RE.findall(_lead):
790
+ _sk = _measure_facade._resolve_installed_skill(_cn)
791
+ if _sk:
792
+ skills_used[_sk] = skills_used.get(_sk, 0) + 1
793
+
794
+ # Extract tool usage from assistant messages
795
+ if rec_type == "assistant":
796
+ msg = record.get("message", {})
797
+ if not isinstance(msg, dict):
798
+ msg = {}
799
+ content = msg.get("content", [])
800
+
801
+ if isinstance(content, list):
802
+ for block in content:
803
+ if not isinstance(block, dict):
804
+ continue
805
+ if block.get("type") != "tool_use":
806
+ continue
807
+
808
+ tool_name = block.get("name", "")
809
+ tool_calls[tool_name] = tool_calls.get(tool_name, 0) + 1
810
+
811
+ inp = block.get("input", {})
812
+ if not isinstance(inp, dict):
813
+ inp = {}
814
+ if tool_name == "Skill":
815
+ skill = inp.get("skill", "unknown")
816
+ skills_used[skill] = skills_used.get(skill, 0) + 1
817
+ elif tool_name in ("Task", "Agent"):
818
+ # Current Claude Code names the sub-agent tool
819
+ # "Agent"; older transcripts used "Task". Match
820
+ # both exactly so TaskCreate/TaskUpdate (todo
821
+ # tools) are never miscounted as sub-agents.
822
+ agent_type = inp.get("subagent_type", "unknown")
823
+ subagents_used[agent_type] = subagents_used.get(agent_type, 0) + 1
824
+
825
+ # v5.4.9 (P1 fix): Streaming-aware dedup. Claude Code writes
826
+ # MULTIPLE assistant records per requestId during streaming;
827
+ # each one's usage.output_tokens is the CUMULATIVE count up
828
+ # to that chunk. The previous dedup (skip-if-seen) kept the
829
+ # FIRST record, which captured only the initial partial
830
+ # count and discarded the final cumulative total — causing
831
+ # a 3-10x under-count of output. Identified by verifying
832
+ # 48,595 requestIds across 30d had monotonically increasing
833
+ # output values in local JSONL. Fix: track per-requestId
834
+ # MAX usage and apply it at end of file.
835
+ req_id = _measure_facade._usage_request_key(record, msg)
836
+ usage = msg.get("usage", {})
837
+ if usage and isinstance(usage, dict):
838
+ # _safe_int, not raw int(): json.loads accepts the
839
+ # non-standard Infinity/NaN literals, and int(inf) /
840
+ # int(nan) raise OverflowError/ValueError — a hostile
841
+ # or corrupt transcript must degrade to 0, not crash.
842
+ inp_tok = _measure_facade._safe_int(usage.get("input_tokens", 0))
843
+ out_tok = _measure_facade._safe_int(usage.get("output_tokens", 0))
844
+ cr = _measure_facade._safe_int(usage.get("cache_read_input_tokens", 0))
845
+ cache_creation = usage.get("cache_creation", {})
846
+ if not isinstance(cache_creation, dict):
847
+ cache_creation = {}
848
+ cc_1h = _measure_facade._safe_int(
849
+ cache_creation.get("ephemeral_1h_input_tokens", 0)
850
+ or usage.get("ephemeral_1h_input_tokens", 0)
851
+ )
852
+ cc_5m = _measure_facade._safe_int(
853
+ cache_creation.get("ephemeral_5m_input_tokens", 0)
854
+ or usage.get("ephemeral_5m_input_tokens", 0)
855
+ )
856
+ cc = _measure_facade._safe_int(usage.get("cache_creation_input_tokens", 0)) or (cc_1h + cc_5m)
857
+ model = _measure_facade._record_model(msg)
858
+ # Claude Code's /stats basis sums every assistant usage
859
+ # record, including streamed chunks, and excludes cache
860
+ # read/write classes. Keep it beside the deduped billed
861
+ # basis used for pricing and cost analysis.
862
+ reported_input += inp_tok
863
+ reported_output += out_tok
864
+ reported_model_usage[model] = (
865
+ reported_model_usage.get(model, 0)
866
+ + inp_tok
867
+ + out_tok
868
+ )
869
+ # Records with neither a requestId nor a message id must
870
+ # never collapse with each other — use the map's own
871
+ # size as a monotonic per-session counter.
872
+ key = req_id if req_id else f"__noreq__{len(request_usage_map)}"
873
+ # Advisor iterations bill at the advisor's own model:
874
+ # each is a separate entry under "<request>#advisor<n>"
875
+ # so streamed copies still dedup by MAX per entry.
876
+ parts = _measure_facade._billed_usage_parts(usage, model)
877
+ for part_index, (part_model, b) in enumerate(parts):
878
+ part_key = key if part_index == 0 else f"{key}#advisor{part_index}"
879
+ prev = request_usage_map.get(part_key)
880
+ if prev is None:
881
+ request_usage_map[part_key] = {
882
+ "inp": b["inp"], "out": b["out"], "cr": b["cr"],
883
+ "cc": b["cc"], "cc_1h": b["cc_1h"],
884
+ "cc_5m": b["cc_5m"], "model": part_model,
885
+ "ts": ts_str,
886
+ }
887
+ if part_index:
888
+ request_usage_map[part_key]["advisor"] = True
889
+ else:
890
+ # Streaming: keep MAX of each token category.
891
+ # Model + timestamp: prefer later (non-empty) values.
892
+ for field in _measure_facade._USAGE_BUCKET_KEYS:
893
+ prev[field] = max(prev[field], b[field])
894
+ if part_model and part_model != "unknown":
895
+ prev["model"] = part_model
896
+ if ts_str:
897
+ prev["ts"] = ts_str
898
+
899
+ if record_day:
900
+ metric = daily_metrics.setdefault(record_day, {
901
+ "message_count": 0, "skills": {}, "subagents": {}, "tool_calls": {},
902
+ "duration_minutes": 0})
903
+ metric["message_count"] += message_count - prior_messages
904
+ for name, before, after in zip(("skills", "subagents", "tool_calls"), prior_maps,
905
+ (skills_used, subagents_used, tool_calls)):
906
+ for key, value in after.items():
907
+ delta = value - before.get(key, 0)
908
+ if delta:
909
+ metric[name][key] = metric[name].get(key, 0) + delta
910
+ epoch = _measure_facade.datetime.fromisoformat(ts_str.replace("Z", "+00:00")).timestamp()
911
+ metric["first"] = min(metric.get("first", epoch), epoch)
912
+ metric["last"] = max(metric.get("last", epoch), epoch)
913
+ metric["duration_minutes"] = (metric["last"] - metric["first"]) / 60
914
+
915
+ except (PermissionError, OSError):
916
+ return None
917
+
918
+ # "Is this a real transcript?" must stay a question about RECORDS, not about
919
+ # the (now deduped) message count. `message_count` no longer counts streamed
920
+ # duplicates or tool_result transport, so a legitimate transcript made only
921
+ # of tool results would otherwise score 0 here and be discarded entirely --
922
+ # which silently dropped whole sessions from every population.
923
+ if _conversation_records == 0:
924
+ if cache_key is not None:
925
+ if len(_measure_facade._parse_session_jsonl_cache) >= _measure_facade._PARSE_CACHE_MAX:
926
+ _measure_facade._parse_session_jsonl_cache.clear()
927
+ _measure_facade._parse_session_jsonl_cache[cache_key] = None
928
+ return None
929
+
930
+ # Streaming-aware dedup: each entry in request_usage_map holds the final
931
+ # cumulative usage for one API call. Summing these gives the session's true
932
+ # total without streaming-chunk under-counting.
933
+ for _key, _u in request_usage_map.items():
934
+ _u["day"] = _measure_facade._request_local_day(_u.get("ts"))
935
+ _agg, request_days = _measure_facade._aggregate_request_usage(request_usage_map)
936
+ total_input = _agg["total_input"]
937
+ total_output = _agg["total_output"]
938
+ total_cache_read = _agg["total_cache_read"]
939
+ total_cache_create = _agg["total_cache_create"]
940
+ total_cache_create_1h = _agg["total_cache_create_1h"]
941
+ total_cache_create_5m = _agg["total_cache_create_5m"]
942
+ api_calls = _agg["api_calls"]
943
+ api_call_timestamps = _agg["api_call_timestamps"]
944
+ model_usage = _agg["model_usage"]
945
+ model_usage_breakdown = _agg["model_usage_breakdown"]
946
+ daily_usage = _measure_facade._daily_usage_from_merged(request_usage_map)
947
+
948
+ # Calculate duration
949
+ duration_minutes = 0
950
+ if first_ts and last_ts:
951
+ delta = (last_ts - first_ts).total_seconds()
952
+ duration_minutes = max(0, delta / 60)
953
+
954
+ # Full input = uncached + cache reads + cache creation
955
+ total_full_input = total_input + total_cache_read + total_cache_create
956
+
957
+ # Cache hit rate
958
+ cache_hit_rate = 0.0
959
+ if total_full_input > 0:
960
+ cache_hit_rate = total_cache_read / total_full_input
961
+ gap_stats = _measure_facade._compute_call_gap_stats(api_call_timestamps)
962
+
963
+ result = {
964
+ "version": version,
965
+ "slug": slug,
966
+ "topic": topic,
967
+ "duration_minutes": duration_minutes,
968
+ "total_input_tokens": total_full_input,
969
+ "total_output_tokens": total_output,
970
+ "total_cache_read": total_cache_read,
971
+ "total_cache_create": total_cache_create,
972
+ "total_cache_create_1h": total_cache_create_1h,
973
+ "total_cache_create_5m": total_cache_create_5m,
974
+ "cache_hit_rate": cache_hit_rate,
975
+ "avg_call_gap_seconds": gap_stats["avg"],
976
+ "max_call_gap_seconds": gap_stats["max"],
977
+ "p95_call_gap_seconds": gap_stats["p95"],
978
+ "model_usage": model_usage,
979
+ "model_usage_breakdown": model_usage_breakdown,
980
+ "daily_usage": daily_usage,
981
+ "daily_metrics": daily_metrics,
982
+ # Per-request usage (streaming-deduped) so a caller can dedupe requests
983
+ # that Claude Code writes into more than one transcript of a session.
984
+ "request_usage": {
985
+ k: dict(u, day=request_days.get(k)) for k, u in request_usage_map.items()
986
+ },
987
+ "reported_input_tokens": reported_input,
988
+ "reported_output_tokens": reported_output,
989
+ "reported_model_usage": reported_model_usage,
990
+ "skills_used": skills_used,
991
+ "subagents_used": subagents_used,
992
+ "tool_calls": tool_calls,
993
+ "message_count": message_count,
994
+ "api_calls": api_calls,
995
+ "first_ts": first_ts.isoformat() if first_ts else None,
996
+ "is_sidechain": is_sidechain,
997
+ "sidechain_reason": sidechain_reason,
998
+ }
999
+ if cache_key is not None:
1000
+ if len(_measure_facade._parse_session_jsonl_cache) >= _measure_facade._PARSE_CACHE_MAX:
1001
+ _measure_facade._parse_session_jsonl_cache.clear()
1002
+ _measure_facade._parse_session_jsonl_cache[cache_key] = result
1003
+ return result
1004
+
1005
+
1006
+ def parse_session_turns(filepath):
1007
+ """Parse a JSONL session file and return per-turn token data.
1008
+
1009
+ Returns a list of dicts, one per API call:
1010
+ {turn_index, role, input_tokens, output_tokens, cache_read,
1011
+ cache_creation, model, timestamp, tools_used, cost_usd}
1012
+
1013
+ Returns empty list if file is empty/unparseable.
1014
+ """
1015
+ _measure_facade = _compat.facade()
1016
+ if _measure_facade._use_codex_session_adapter(filepath):
1017
+ turns = _measure_facade.codex_session.parse_session_turns(filepath)
1018
+ for turn in turns:
1019
+ cost = _measure_facade._get_model_cost(
1020
+ turn.get("model"),
1021
+ max(0, turn.get("input_tokens", 0) - turn.get("cache_read", 0)),
1022
+ turn.get("output_tokens", 0),
1023
+ turn.get("cache_read", 0),
1024
+ turn.get("cache_creation", 0),
1025
+ )
1026
+ turn["cost_usd"] = round(cost, 6)
1027
+ turn["cost_source"] = "openai_api_pricing" if cost > 0 else "unavailable"
1028
+ return turns
1029
+
1030
+ turns = []
1031
+ turn_index = 0
1032
+ tier = _measure_facade._load_pricing_tier()
1033
+ prev_call_ts = None
1034
+ turn_by_key = {}
1035
+ parts_by_key = {}
1036
+
1037
+ # Bound the work like the Codex adapter's _iter_json_records (see
1038
+ # _parse_session_jsonl): skip oversized files and oversized lines.
1039
+ try:
1040
+ if _measure_facade.os.stat(filepath).st_size > _measure_facade.codex_session.MAX_PARSE_FILE_BYTES:
1041
+ return turns
1042
+ except OSError:
1043
+ return turns
1044
+
1045
+ try:
1046
+ with open(filepath, "r", encoding="utf-8", errors="replace") as f:
1047
+ for line in f:
1048
+ if len(line) > _measure_facade.codex_session.MAX_JSONL_LINE_CHARS:
1049
+ continue
1050
+ try:
1051
+ record = _measure_facade.json.loads(line)
1052
+ except _measure_facade.json.JSONDecodeError:
1053
+ continue
1054
+ if not isinstance(record, dict):
1055
+ # Valid JSON but not an object — corrupt transcript line.
1056
+ continue
1057
+
1058
+ rec_type = record.get("type")
1059
+ if rec_type != "assistant":
1060
+ continue
1061
+
1062
+ msg = record.get("message", {})
1063
+ if not isinstance(msg, dict):
1064
+ continue
1065
+ usage = msg.get("usage", {})
1066
+ if not usage or not isinstance(usage, dict):
1067
+ continue
1068
+
1069
+ # _safe_int: Infinity/NaN usage literals degrade to 0 instead of
1070
+ # raising OverflowError/ValueError out of _get_model_cost's int().
1071
+ inp_tok = _measure_facade._safe_int(usage.get("input_tokens", 0))
1072
+ out_tok = _measure_facade._safe_int(usage.get("output_tokens", 0))
1073
+ cr = _measure_facade._safe_int(usage.get("cache_read_input_tokens", 0))
1074
+ cache_creation = usage.get("cache_creation", {})
1075
+ if not isinstance(cache_creation, dict):
1076
+ cache_creation = {}
1077
+ cc_1h = _measure_facade._safe_int(
1078
+ cache_creation.get("ephemeral_1h_input_tokens", 0)
1079
+ or usage.get("ephemeral_1h_input_tokens", 0)
1080
+ )
1081
+ cc_5m = _measure_facade._safe_int(
1082
+ cache_creation.get("ephemeral_5m_input_tokens", 0)
1083
+ or usage.get("ephemeral_5m_input_tokens", 0)
1084
+ )
1085
+ cc = _measure_facade._safe_int(usage.get("cache_creation_input_tokens", 0)) or (cc_1h + cc_5m)
1086
+ model = _measure_facade._record_model(msg)
1087
+
1088
+ # Extract tools used in this turn
1089
+ tools = []
1090
+ content = msg.get("content", [])
1091
+ if isinstance(content, list):
1092
+ for block in content:
1093
+ if isinstance(block, dict) and block.get("type") == "tool_use":
1094
+ tools.append(block.get("name", ""))
1095
+
1096
+ # One API request is one turn. Its streamed records share a
1097
+ # request id (or message id) and each carries the cumulative
1098
+ # usage so far, so they fold into the first turn of that request.
1099
+ req_key = _measure_facade._usage_request_key(record, msg)
1100
+ prior_turn = turn_by_key.get(req_key) if req_key else None
1101
+
1102
+ ts_str = record.get("timestamp")
1103
+ gap_since_prev_seconds = None
1104
+ if prior_turn is None and ts_str and isinstance(ts_str, str):
1105
+ try:
1106
+ call_ts = _measure_facade.datetime.fromisoformat(ts_str.replace("Z", "+00:00"))
1107
+ if prev_call_ts is not None:
1108
+ gap_since_prev_seconds = int(round(max(0, (call_ts - prev_call_ts).total_seconds())))
1109
+ prev_call_ts = call_ts
1110
+ except (ValueError, TypeError):
1111
+ pass
1112
+ parts = _measure_facade._billed_usage_parts(usage, model, tier=tier)
1113
+ cost = _measure_facade._price_usage_parts(parts, tier=tier, per_request=True)
1114
+
1115
+ turn = {
1116
+ "turn_index": turn_index,
1117
+ "role": "assistant",
1118
+ "input_tokens": inp_tok,
1119
+ "output_tokens": out_tok,
1120
+ "cache_read": cr,
1121
+ "cache_creation": cc,
1122
+ "cache_creation_1h": cc_1h,
1123
+ "cache_creation_5m": cc_5m,
1124
+ "model": model,
1125
+ "timestamp": ts_str,
1126
+ "gap_since_prev_seconds": gap_since_prev_seconds,
1127
+ "tools_used": tools,
1128
+ "cost_usd": round(cost, 6),
1129
+ }
1130
+ ctx_usage = _measure_facade._context_usage(usage)
1131
+ if ctx_usage is not usage:
1132
+ # Cached prefix the next turn can reuse: the final executor
1133
+ # only, matching the live keep-warm arm (#287).
1134
+ turn["ctx_cache"] = (
1135
+ _measure_facade._context_token_count(ctx_usage)
1136
+ - _measure_facade._safe_int(ctx_usage.get("input_tokens")))
1137
+ resume_usage = _measure_facade._resume_usage(usage)
1138
+ if resume_usage is not usage:
1139
+ # Billing stays aggregate; pause warmth uses the first
1140
+ # executor, before any cache writes inside this response.
1141
+ resume_read = _measure_facade._safe_int(resume_usage.get("cache_read_input_tokens"))
1142
+ turn["resume_cache_read"] = resume_read
1143
+ turn["resume_cache_creation"] = (
1144
+ _measure_facade._context_token_count(resume_usage) - resume_read
1145
+ - _measure_facade._safe_int(resume_usage.get("input_tokens")))
1146
+ if prior_turn is not None:
1147
+ latest_context = turn["output_tokens"] >= prior_turn["output_tokens"]
1148
+ for field in ("input_tokens", "output_tokens", "cache_read",
1149
+ "cache_creation", "cache_creation_1h", "cache_creation_5m"):
1150
+ prior_turn[field] = max(prior_turn[field], turn[field])
1151
+ prior_turn["tools_used"] += [
1152
+ t for t in tools if t not in prior_turn["tools_used"]]
1153
+ if model and model != "unknown":
1154
+ prior_turn["model"] = model
1155
+ for field in ("ctx_cache", "resume_cache_read", "resume_cache_creation"):
1156
+ if field in turn and (latest_context or field not in prior_turn):
1157
+ prior_turn[field] = turn[field]
1158
+ merged_parts = parts_by_key[req_key]
1159
+ for index, (part_model, buckets) in enumerate(parts):
1160
+ if index == len(merged_parts):
1161
+ merged_parts.append((part_model, dict(buckets)))
1162
+ else:
1163
+ old_model, old_buckets = merged_parts[index]
1164
+ for field in _measure_facade._USAGE_BUCKET_KEYS:
1165
+ old_buckets[field] = max(old_buckets[field], buckets[field])
1166
+ if part_model and part_model != "unknown":
1167
+ old_model = part_model
1168
+ merged_parts[index] = (old_model, old_buckets)
1169
+ prior_turn["cost_usd"] = round(_measure_facade._price_usage_parts(
1170
+ merged_parts, tier=tier, per_request=True), 6)
1171
+ continue
1172
+ turns.append(turn)
1173
+ if req_key:
1174
+ turn_by_key[req_key] = turn
1175
+ parts_by_key[req_key] = parts
1176
+ turn_index += 1
1177
+
1178
+ except (PermissionError, OSError):
1179
+ pass
1180
+
1181
+ return turns
1182
+
1183
+
1184
+ def score_session_quality(session_data):
1185
+ """Score a single session's quality on a 0-100 scale.
1186
+
1187
+ Uses a simplified version of the 5-signal quality score:
1188
+ - Context fill at session end (25%)
1189
+ - Message count risk (25%)
1190
+ - Cache hit rate (20%)
1191
+ - Output/input ratio (15%)
1192
+ - Compaction events (15%)
1193
+
1194
+ session_data should include: total_input_tokens, total_output_tokens,
1195
+ message_count, cache_hit_rate, api_calls, and optionally total_cache_read.
1196
+ """
1197
+ _measure_facade = _compat.facade()
1198
+ score = 0.0
1199
+
1200
+ # Signal 1: Context fill (25%)
1201
+ # Lower fill = better (more room for work)
1202
+ context_window = _measure_facade.detect_context_window()[0]
1203
+ total_input = session_data.get("total_input_tokens", 0)
1204
+ fill_ratio = total_input / context_window if context_window > 0 else 0
1205
+ if fill_ratio < 0.3:
1206
+ fill_score = 100
1207
+ elif fill_ratio < 0.5:
1208
+ fill_score = 80
1209
+ elif fill_ratio < 0.7:
1210
+ fill_score = 55
1211
+ elif fill_ratio < 0.85:
1212
+ fill_score = 30
1213
+ else:
1214
+ fill_score = 10
1215
+ score += fill_score * 0.25
1216
+
1217
+ # Signal 2: Message count risk (25%)
1218
+ # More messages = higher risk of quality degradation
1219
+ msg_count = session_data.get("message_count", 0)
1220
+ if msg_count <= 20:
1221
+ msg_score = 100
1222
+ elif msg_count <= 40:
1223
+ msg_score = 80
1224
+ elif msg_count <= 60:
1225
+ msg_score = 55
1226
+ elif msg_count <= 100:
1227
+ msg_score = 30
1228
+ else:
1229
+ msg_score = 10
1230
+ score += msg_score * 0.25
1231
+
1232
+ # Signal 3: Cache hit rate (20%)
1233
+ # Higher cache = better (reusing context efficiently)
1234
+ chr_ = session_data.get("cache_hit_rate", 0)
1235
+ if chr_ >= 0.8:
1236
+ cache_score = 100
1237
+ elif chr_ >= 0.6:
1238
+ cache_score = 80
1239
+ elif chr_ >= 0.4:
1240
+ cache_score = 55
1241
+ elif chr_ >= 0.2:
1242
+ cache_score = 30
1243
+ else:
1244
+ cache_score = 10
1245
+ score += cache_score * 0.20
1246
+
1247
+ # Signal 4: Output/input ratio (15%)
1248
+ # Very low ratio = wasteful (loading lots of context, producing little)
1249
+ total_output = session_data.get("total_output_tokens", 0)
1250
+ if total_input > 0:
1251
+ oi_ratio = total_output / total_input
1252
+ else:
1253
+ oi_ratio = 1.0
1254
+ if oi_ratio >= 0.05:
1255
+ oi_score = 100
1256
+ elif oi_ratio >= 0.02:
1257
+ oi_score = 70
1258
+ elif oi_ratio >= 0.01:
1259
+ oi_score = 40
1260
+ else:
1261
+ oi_score = 15
1262
+ score += oi_score * 0.15
1263
+
1264
+ # Signal 5: API calls vs messages (15%)
1265
+ # Healthy: roughly 1 API call per 2 messages
1266
+ api_calls = session_data.get("api_calls", 0)
1267
+ if msg_count > 0 and api_calls > 0:
1268
+ calls_per_msg = api_calls / msg_count
1269
+ if calls_per_msg <= 0.6:
1270
+ api_score = 100
1271
+ elif calls_per_msg <= 0.8:
1272
+ api_score = 75
1273
+ else:
1274
+ api_score = 50
1275
+ else:
1276
+ api_score = 50
1277
+ score += api_score * 0.15
1278
+
1279
+ final = int(round(min(100, max(0, score))))
1280
+
1281
+ return {"score": final, "band": _measure_facade.score_to_band(final), "grade": _measure_facade.score_to_grade(final)}
1282
+
1283
+
1284
+ def _record_model(msg):
1285
+ """A transcript record's model id as text. A hand-edited or foreign
1286
+ record can carry a number or an object there, and one such record must not
1287
+ crash the whole collect; it is simply an unknown model."""
1288
+ _measure_facade = _compat.facade()
1289
+ model = msg.get("model") if isinstance(msg, dict) else None
1290
+ return model if isinstance(model, str) and model else "unknown"
1291
+
1292
+
1293
+ def _normalize_model_name(model_id):
1294
+ """Collapse model IDs like 'claude-sonnet-4-6' into 'sonnet'.
1295
+
1296
+ Returns None for synthetic/internal model IDs that should be skipped.
1297
+ """
1298
+ _measure_facade = _compat.facade()
1299
+ if not isinstance(model_id, str) or not model_id or model_id.startswith("<"):
1300
+ return None
1301
+ m = model_id.lower()
1302
+ if "fable" in m:
1303
+ return "fable"
1304
+ if "opus" in m:
1305
+ return "opus"
1306
+ if "sonnet" in m:
1307
+ # Sonnet 5 (released 2026-06-30) is $2/$10; every earlier Sonnet is $3/$15.
1308
+ # One shared bucket misprices whichever generation it is not calibrated to --
1309
+ # and the pre-2026-07 baseline windows are ALL Sonnet 4.6 or older, so the
1310
+ # frozen "before" arm was being priced 33% under its real historical cost.
1311
+ # Anything not explicitly an older generation keeps the current "sonnet" card,
1312
+ # so an unrecognised future Sonnet is never silently priced as legacy.
1313
+ if _measure_facade._SONNET_LEGACY_RE.search(m):
1314
+ return "sonnet_legacy"
1315
+ return "sonnet"
1316
+ if "haiku" in m:
1317
+ return "haiku"
1318
+ return model_id
1319
+
1320
+
1321
+ def _claude_price_key(model_id, claude_models):
1322
+ """Rate-card key for a Claude model id, finer than _normalize_model_name.
1323
+
1324
+ Display labels and savings mixes stay on the family buckets ("opus",
1325
+ "fable"), but generations are priced differently (Opus 5.5 is $4/$20,
1326
+ Opus 4.1 is $15/$75, Fable 5.1 reads cache at $0.25), so pricing looks for
1327
+ a generation card first ("opus_5_5", then "opus_5"), then the family.
1328
+ Generation cards come from pricing/prices.json, so a new model is priced
1329
+ the day the table has it. Mythos shares the Fable cards when it has none.
1330
+ """
1331
+ _measure_facade = _compat.facade()
1332
+ if not model_id or not isinstance(model_id, str):
1333
+ return None
1334
+ legacy = _measure_facade._CLAUDE_LEGACY_ID_RE.search(model_id.lower())
1335
+ if legacy:
1336
+ major, minor, family = legacy.groups()
1337
+ for key in ((f"{family}_{major}_{minor}", f"{family}_{major}") if minor else (f"{family}_{major}",)):
1338
+ if key in claude_models:
1339
+ return key
1340
+ return _measure_facade._normalize_model_name(model_id) # Sonnet 3.x lands on sonnet_legacy
1341
+ m = _measure_facade._CLAUDE_GENERATION_RE.search(model_id.lower())
1342
+ if m:
1343
+ family, major, minor = m.groups()
1344
+ families = (family, "fable") if family == "mythos" else (family,)
1345
+ for fam in families:
1346
+ for key in ((f"{fam}_{major}_{minor}", f"{fam}_{major}") if minor else (f"{fam}_{major}",)):
1347
+ if key in claude_models:
1348
+ return key
1349
+ if family == "mythos" and "fable" in claude_models:
1350
+ return "fable"
1351
+ elif "mythos" in str(model_id).lower() and "fable" in claude_models:
1352
+ return "fable"
1353
+ # A bare `haiku` keeps the family card (Haiku 4.5 rates), matching the
1354
+ # 200K window _claude_model_window gives it: the alias is provider-
1355
+ # dependent, and "haiku" is also the family-bucket label that routing and
1356
+ # model-mix callers pass in, so it must not float to the 5.5 card.
1357
+ return _measure_facade._normalize_model_name(model_id)
1358
+
1359
+
1360
+ def _load_overhead_snapshots():
1361
+ """Load any saved token-optimizer snapshots for overhead trajectory.
1362
+
1363
+ Returns snapshots sorted chronologically by timestamp.
1364
+ """
1365
+ _measure_facade = _compat.facade()
1366
+ snapshots = []
1367
+ if not _measure_facade.SNAPSHOT_DIR.exists():
1368
+ return snapshots
1369
+ for sf in sorted(_measure_facade.SNAPSHOT_DIR.glob("snapshot_*.json")):
1370
+ try:
1371
+ with open(sf, "r", encoding="utf-8") as f:
1372
+ data = _measure_facade.json.load(f)
1373
+ snapshots.append({
1374
+ "label": data.get("label", sf.stem),
1375
+ "timestamp": data.get("timestamp", ""),
1376
+ "total": data.get("totals", {}).get("estimated_total", 0),
1377
+ })
1378
+ except (_measure_facade.json.JSONDecodeError, PermissionError, OSError):
1379
+ continue
1380
+ # Sort by timestamp so trajectory reads chronologically
1381
+ snapshots.sort(key=lambda s: ((_measure_facade := _compat.facade()), s["timestamp"])[1])
1382
+ return snapshots
1383
+
1384
+
1385
+ def _is_file_collected(conn, jsonl_path, check_mtime=None):
1386
+ """Check stored IDs; file collectors also check delegated transcript changes."""
1387
+ _measure_facade = _compat.facade()
1388
+ row = conn.execute(
1389
+ "SELECT collected_at FROM session_log WHERE jsonl_path = ?",
1390
+ (str(jsonl_path),),
1391
+ ).fetchone()
1392
+ if row is None and check_mtime:
1393
+ # A copy that already lost dedupe to a more complete copy counts as
1394
+ # collected until it changes; if it grows, it is parsed and compared again.
1395
+ try:
1396
+ row = conn.execute(
1397
+ "SELECT collected_at FROM session_log_aliases WHERE jsonl_path = ?",
1398
+ (str(jsonl_path),),
1399
+ ).fetchone()
1400
+ except _measure_facade.sqlite3.Error:
1401
+ row = None
1402
+ if row is None:
1403
+ return False
1404
+ if not check_mtime:
1405
+ return True # Other adapters use synthetic IDs, not filesystem paths.
1406
+ try:
1407
+ collected = _measure_facade.datetime.fromisoformat(row[0]).timestamp()
1408
+ path = _measure_facade.Path(jsonl_path)
1409
+ paths = [path, *_measure_facade._find_subagent_jsonl_files(path)]
1410
+ return all(path.stat().st_mtime <= collected for path in paths)
1411
+ except (OSError, TypeError, ValueError):
1412
+ return False
1413
+
1414
+
1415
+ def _adapter_activity_ts(parsed):
1416
+ """Latest activity of an adapter session (its end/updated time, else its
1417
+ start) as an aware datetime, or None. A resumed chat must land on the day
1418
+ it was last used, like a Claude transcript, not the day it started."""
1419
+ _measure_facade = _compat.facade()
1420
+ best = None
1421
+ for field in ("last_ts", "first_ts"):
1422
+ raw = parsed.get(field)
1423
+ if not raw:
1424
+ continue
1425
+ try:
1426
+ dt = _measure_facade.datetime.fromisoformat(raw)
1427
+ except (TypeError, ValueError):
1428
+ continue
1429
+ if dt.tzinfo is None:
1430
+ dt = dt.astimezone()
1431
+ if best is None or dt > best:
1432
+ best = dt
1433
+ return best
1434
+
1435
+
1436
+ def _store_adapter_activity(conn, dedup_key, parsed):
1437
+ """Keep adapter provenance; only split totals with actual day evidence.
1438
+
1439
+ A normalized single-day session can be attributed without request records.
1440
+ Multi-day sessions without daily usage remain incomplete, never spread or
1441
+ assigned wholesale to the collector's date.
1442
+ """
1443
+ _measure_facade = _compat.facade()
1444
+ row = conn.execute("SELECT input_tokens,output_tokens,daily_metrics_json FROM session_log WHERE jsonl_path=?", (dedup_key,)).fetchone()
1445
+ if row is None or tuple(row[:2]) != (parsed.get("total_input_tokens"), parsed.get("total_output_tokens")):
1446
+ return 0
1447
+ bounds = sorted(filter(None, (_measure_facade._request_local_day(parsed.get("first_ts")),
1448
+ _measure_facade._request_local_day(parsed.get("last_ts")))))
1449
+ usage = parsed.get("daily_usage")
1450
+ calls = parsed.get("daily_calls") or {}
1451
+ if usage is None and len(bounds) == 2 and bounds[0] == bounds[1]:
1452
+ usage = {bounds[0]: parsed.get("model_usage_breakdown") or {}}
1453
+ calls = {bounds[0]: parsed.get("api_calls", 0)}
1454
+ # The adapter writes the same map as combined and parent evidence; retained
1455
+ # metadata can still extend beyond either its usage or parsed timestamps.
1456
+ days = _measure_facade._activity_bounds(usage, _measure_facade._safe_json_dict(row[2]))
1457
+ first = min(bounds + days) if bounds or days else None
1458
+ last = max(bounds + days) if bounds or days else None
1459
+ raw = _measure_facade.json.dumps(usage) if usage is not None else None
1460
+ params = (first, last, last or "", raw, raw, _measure_facade.json.dumps(calls), dedup_key)
1461
+ current = conn.execute(
1462
+ "SELECT first_activity_day,last_activity_day,date,daily_usage_json,parent_daily_usage_json,daily_calls_json "
1463
+ "FROM session_log WHERE jsonl_path=?", (dedup_key,)).fetchone()
1464
+ if current and tuple(current) == params[:-1]:
1465
+ return 0
1466
+ conn.execute(
1467
+ "UPDATE session_log SET first_activity_day=?,last_activity_day=?,date=?,daily_usage_json=?, "
1468
+ "parent_daily_usage_json=?,daily_calls_json=? WHERE jsonl_path=?", params)
1469
+ return 1
1470
+
1471
+
1472
+ def _insert_normalized_session(conn, dedup_key, parsed, platform, project_fallback, quiet=None):
1473
+ """Insert or upgrade one normalized session row; returns 1 on new/upgraded.
1474
+
1475
+ Owns the 33-column session_log INSERT and the in-place upgrade. An existing
1476
+ row is upgraded whenever its stored ``incomplete`` flag differs from the
1477
+ incoming one (0/1), so:
1478
+ - an idle-finalized row (incomplete=0) whose chat resumes activity
1479
+ (incomplete=1) flips back, instead of freezing (for
1480
+ long-lived IDE chats);
1481
+ - a crashed/active row (incomplete=1) that later sees sessionEnd flips to
1482
+ complete (incomplete=0) with refreshed totals.
1483
+ Uses INSERT OR IGNORE so the dedup key (`<platform>:<slug>`) is idempotent.
1484
+ """
1485
+ _measure_facade = _compat.facade()
1486
+ slug = parsed.get("slug") or ""
1487
+ if not slug:
1488
+ return 0
1489
+
1490
+ active = _measure_facade._adapter_activity_ts(parsed)
1491
+ date = active.astimezone().strftime("%Y-%m-%d") if active else ""
1492
+
1493
+ project_name = str(parsed.get("cwd") or project_fallback)
1494
+ is_incomplete = 1 if parsed.get("incomplete") else 0
1495
+
1496
+ values = (
1497
+ date,
1498
+ project_name,
1499
+ parsed["duration_minutes"],
1500
+ parsed["total_input_tokens"],
1501
+ parsed["total_output_tokens"],
1502
+ parsed["message_count"],
1503
+ parsed.get("api_calls", 0),
1504
+ parsed["cache_hit_rate"],
1505
+ parsed.get("total_cache_create_1h", 0),
1506
+ parsed.get("total_cache_create_5m", 0),
1507
+ 1,
1508
+ parsed.get("avg_call_gap_seconds"),
1509
+ parsed.get("max_call_gap_seconds"),
1510
+ parsed.get("p95_call_gap_seconds"),
1511
+ _measure_facade.json.dumps(parsed.get("skills_used", {})),
1512
+ _measure_facade.json.dumps(parsed.get("subagents_used", {})),
1513
+ _measure_facade.json.dumps(parsed.get("tool_calls", {})),
1514
+ _measure_facade.json.dumps(parsed.get("model_usage", {})),
1515
+ _measure_facade.json.dumps(parsed.get("model_usage", {})),
1516
+ _measure_facade.json.dumps(parsed.get("model_usage_breakdown", {})),
1517
+ parsed.get("version"),
1518
+ parsed.get("slug"),
1519
+ parsed.get("topic"),
1520
+ _measure_facade.datetime.now().isoformat(),
1521
+ parsed.get("quality_score", 0),
1522
+ parsed.get("quality_grade", "F"),
1523
+ 0,
1524
+ parsed.get("cost_usd", 0.0),
1525
+ parsed.get("cost_source"),
1526
+ parsed.get("credits"),
1527
+ platform,
1528
+ is_incomplete,
1529
+ )
1530
+
1531
+ if _measure_facade._is_file_collected(conn, dedup_key):
1532
+ try:
1533
+ existing = conn.execute(
1534
+ "SELECT incomplete FROM session_log WHERE jsonl_path = ?",
1535
+ (dedup_key,),
1536
+ ).fetchone()
1537
+ except _measure_facade.sqlite3.Error:
1538
+ existing = None
1539
+ if existing is not None and int(existing[0]) == is_incomplete:
1540
+ return _measure_facade._store_adapter_activity(conn, dedup_key, parsed)
1541
+ try:
1542
+ conn.execute(
1543
+ """UPDATE session_log SET
1544
+ date=?, project=?, duration_minutes=?, input_tokens=?,
1545
+ output_tokens=?, message_count=?, api_calls=?, cache_hit_rate=?,
1546
+ cache_create_1h_tokens=?, cache_create_5m_tokens=?, cache_ttl_scanned=?,
1547
+ avg_call_gap_seconds=?, max_call_gap_seconds=?, p95_call_gap_seconds=?,
1548
+ skills_json=?, subagents_json=?, tool_calls_json=?, model_usage_json=?,
1549
+ all_model_usage_json=?, model_usage_breakdown_json=?, version=?, slug=?,
1550
+ topic=?, collected_at=?, quality_score=?, quality_grade=?,
1551
+ stale_waste_tokens=?, cost_usd=?, cost_source=?, credits=?,
1552
+ platform=?, incomplete=?
1553
+ WHERE jsonl_path=?""",
1554
+ values + (dedup_key,),
1555
+ )
1556
+ _measure_facade._store_adapter_activity(conn, dedup_key, parsed)
1557
+ return 1
1558
+ except _measure_facade.sqlite3.Error as exc:
1559
+ if not quiet:
1560
+ print(f"[Token Optimizer] could not upgrade a {platform} session: {exc}")
1561
+ return 0
1562
+
1563
+ try:
1564
+ cur = conn.execute(
1565
+ """INSERT OR IGNORE INTO session_log
1566
+ (jsonl_path, date, project, duration_minutes, input_tokens,
1567
+ output_tokens, message_count, api_calls, cache_hit_rate,
1568
+ cache_create_1h_tokens, cache_create_5m_tokens, cache_ttl_scanned,
1569
+ avg_call_gap_seconds, max_call_gap_seconds, p95_call_gap_seconds,
1570
+ skills_json, subagents_json, tool_calls_json, model_usage_json,
1571
+ all_model_usage_json, model_usage_breakdown_json, version, slug, topic, collected_at,
1572
+ quality_score, quality_grade, stale_waste_tokens,
1573
+ cost_usd, cost_source, credits, platform, incomplete)
1574
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
1575
+ (dedup_key,) + values,
1576
+ )
1577
+ except _measure_facade.sqlite3.Error as exc:
1578
+ if not quiet:
1579
+ print(f"[Token Optimizer] skipped a {platform} session: {exc}")
1580
+ return 0
1581
+ if cur.rowcount == 1:
1582
+ _measure_facade._store_adapter_activity(conn, dedup_key, parsed)
1583
+ return 1
1584
+ return 0
1585
+
1586
+
1587
+ def _safe_json_dict(raw):
1588
+ _measure_facade = _compat.facade()
1589
+ try:
1590
+ data = _measure_facade.json.loads(raw) if raw else {}
1591
+ return data if isinstance(data, dict) else {}
1592
+ except (_measure_facade.json.JSONDecodeError, TypeError, ValueError):
1593
+ return {}
1594
+
1595
+
1596
+ def _rebuild_aggregate_tables(conn):
1597
+ """Recompute daily aggregate tables from session_log to avoid double counts.
1598
+
1599
+ The daily_stats portion is a single SQL aggregate (94x faster than the
1600
+ row-by-row INSERT-on-conflict loop on 50K rows, and O(1) memory instead
1601
+ of O(N)). The skill/model/subagent daily tables still need JSON parsing
1602
+ in Python (SQLite has no json_each for arbitrary shapes here), so those
1603
+ are batched with executemany per date group instead of one INSERT per row.
1604
+ """
1605
+ _measure_facade = _compat.facade()
1606
+ _measure_facade.ensure_activity_schema(conn)
1607
+ conn.execute("DELETE FROM daily_stats")
1608
+ conn.execute("DELETE FROM model_daily")
1609
+ conn.execute("DELETE FROM skill_daily")
1610
+ conn.execute("DELETE FROM subagent_daily")
1611
+
1612
+ # daily_stats: single SQL aggregate. worst_grade uses MIN on a custom
1613
+ # collation surrogate (INSTR('FDCBAS', grade)) computed in SQL via a
1614
+ # subquery. The per-day worst grade is the one with the smallest INSTR
1615
+ # (F=1 is worst, A=5, S=6, NULL excluded).
1616
+ conn.execute(
1617
+ """INSERT INTO daily_stats
1618
+ (date, session_count, total_input, total_output,
1619
+ total_duration, avg_cache_hit, avg_quality_score, worst_grade)
1620
+ SELECT date,
1621
+ COUNT(*),
1622
+ COALESCE(SUM(input_tokens), 0),
1623
+ COALESCE(SUM(output_tokens), 0),
1624
+ COALESCE(SUM(duration_minutes), 0),
1625
+ COALESCE(AVG(cache_hit_rate), 0),
1626
+ COALESCE(AVG(quality_score), 0),
1627
+ SUBSTR('FDCBAS', MIN(NULLIF(INSTR('FDCBAS', quality_grade),0)),1)
1628
+ FROM session_activity
1629
+ GROUP BY date"""
1630
+ )
1631
+
1632
+ # skill_daily / model_daily / subagent_daily: still need JSON parsing in
1633
+ # Python. Batch with executemany per date group to avoid per-row
1634
+ # statement overhead. Only fetch the JSON columns + date.
1635
+ rows = conn.execute(
1636
+ """SELECT date, skills_json, subagents_json,
1637
+ model_usage_json, all_model_usage_json
1638
+ FROM session_activity"""
1639
+ ).fetchall()
1640
+ skill_batch = []
1641
+ model_batch = []
1642
+ subagent_batch = []
1643
+ for date, skills_json, subagents_json, model_usage_json, all_model_usage_json in rows:
1644
+ for skill, invocations in _measure_facade._safe_json_dict(skills_json).items():
1645
+ skill_batch.append((date, skill, 1, int(invocations or 0)))
1646
+ model_usage_for_daily = _measure_facade._safe_json_dict(all_model_usage_json)
1647
+ if not model_usage_for_daily:
1648
+ model_usage_for_daily = _measure_facade._safe_json_dict(model_usage_json)
1649
+ for model_id, tokens in model_usage_for_daily.items():
1650
+ normalized = _measure_facade._normalize_model_name(model_id)
1651
+ if normalized is None:
1652
+ continue
1653
+ model_batch.append((date, normalized, int(tokens or 0)))
1654
+ for agent_type, count in _measure_facade._safe_json_dict(subagents_json).items():
1655
+ subagent_batch.append((date, agent_type, int(count or 0)))
1656
+ if skill_batch:
1657
+ conn.executemany(
1658
+ """INSERT INTO skill_daily (date, skill, session_count, invocations)
1659
+ VALUES (?, ?, ?, ?)
1660
+ ON CONFLICT(date, skill) DO UPDATE SET
1661
+ session_count = session_count + excluded.session_count,
1662
+ invocations = invocations + excluded.invocations""",
1663
+ skill_batch,
1664
+ )
1665
+ if model_batch:
1666
+ conn.executemany(
1667
+ """INSERT INTO model_daily (date, model, total_tokens)
1668
+ VALUES (?, ?, ?)
1669
+ ON CONFLICT(date, model) DO UPDATE SET
1670
+ total_tokens = total_tokens + excluded.total_tokens""",
1671
+ model_batch,
1672
+ )
1673
+ if subagent_batch:
1674
+ conn.executemany(
1675
+ """INSERT INTO subagent_daily (date, agent_type, spawn_count)
1676
+ VALUES (?, ?, ?)
1677
+ ON CONFLICT(date, agent_type) DO UPDATE SET
1678
+ spawn_count = spawn_count + excluded.spawn_count""",
1679
+ subagent_batch,
1680
+ )
1681
+
1682
+
1683
+ def _needs_model_daily_rebuild(conn):
1684
+ """Check if DB predates the model attribution fix (schema version < 2)."""
1685
+ _measure_facade = _compat.facade()
1686
+ try:
1687
+ ver = conn.execute("PRAGMA user_version").fetchone()[0]
1688
+ return ver < 2
1689
+ except _measure_facade.sqlite3.Error:
1690
+ return False
1691
+
1692
+
1693
+ def _needs_streaming_dedup_rebuild(conn):
1694
+ """v5.4.9: check if DB was built before the streaming-dedup + subagent
1695
+ roll-up fix (schema version < 3). Pre-v5.4.9 sessions stored
1696
+ output_tokens from the FIRST streaming chunk instead of the final
1697
+ cumulative value, and excluded subagent output entirely."""
1698
+ _measure_facade = _compat.facade()
1699
+ try:
1700
+ ver = conn.execute("PRAGMA user_version").fetchone()[0]
1701
+ return ver < 3
1702
+ except _measure_facade.sqlite3.Error:
1703
+ return False
1704
+
1705
+
1706
+ def _migrate_model_daily(conn, quiet=None):
1707
+ """One-time migration for the model attribution fix: wipe model_daily so it rebuilds correctly.
1708
+
1709
+ Only deletes model_daily (lightweight aggregate table). session_log is
1710
+ preserved. New sessions collected after this get correct model attribution.
1711
+ Users wanting full historical accuracy can run `collect --rebuild`.
1712
+ """
1713
+ _measure_facade = _compat.facade()
1714
+ try:
1715
+ # Set version FIRST to break retry loop on failure (Error Handling H1).
1716
+ conn.execute("PRAGMA user_version = 3")
1717
+ conn.commit()
1718
+ conn.execute("DELETE FROM model_daily")
1719
+ conn.commit()
1720
+ if not quiet:
1721
+ print("[Token Optimizer] Migrated model_daily for corrected model attribution.")
1722
+ print(" New sessions will have correct model mix. For full historical accuracy:")
1723
+ print(_measure_facade._hint(" python3 measure.py collect --rebuild"))
1724
+ except _measure_facade.sqlite3.Error as e:
1725
+ print(f" [Token Optimizer] model_daily migration failed: {e}", file=_measure_facade.sys.stderr)
1726
+
1727
+
1728
+ def _migrate_streaming_dedup(conn, quiet=None):
1729
+ """v5.4.9 one-time migration: wipe ALL aggregate tables so the next
1730
+ session-end-flush rebuilds with streaming-aware MAX-dedup and subagent
1731
+ roll-up. session_log stores per-session output_tokens which was wrong
1732
+ pre-v5.4.9, so we wipe that too. Reparsing happens automatically on
1733
+ next `collect` (triggered by SessionEnd hook or /token-dashboard).
1734
+
1735
+ v5.4.13: set user_version FIRST (before DELETE) to prevent a
1736
+ migration loop where a failed COMMIT leaves user_version < 3 and
1737
+ triggers a full data wipe on every subsequent SessionStart. If the
1738
+ DELETE then fails, user_version is already 3 so the migration won't
1739
+ re-fire — the data stays stale but doesn't get wiped repeatedly.
1740
+ """
1741
+ _measure_facade = _compat.facade()
1742
+ try:
1743
+ # Set version FIRST to break the retry loop on failure.
1744
+ conn.execute("PRAGMA user_version = 3")
1745
+ conn.commit()
1746
+ conn.execute("DELETE FROM session_log")
1747
+ conn.execute("DELETE FROM session_log_aliases")
1748
+ conn.execute("DELETE FROM usage_request_claims")
1749
+ conn.execute("DELETE FROM daily_stats")
1750
+ conn.execute("DELETE FROM model_daily")
1751
+ conn.execute("DELETE FROM skill_daily")
1752
+ conn.execute("DELETE FROM subagent_daily")
1753
+ # Drop event tables too: their session_id/session_uuid references would
1754
+ # otherwise dangle (no FK constraints) and silently inflate savings.
1755
+ conn.execute("DELETE FROM savings_events")
1756
+ conn.execute("DELETE FROM compression_events")
1757
+ conn.execute("DELETE FROM counted_reread")
1758
+ conn.commit()
1759
+ if not quiet:
1760
+ print("[Token Optimizer] Migrated to v5.4.9 streaming-aware token counting.")
1761
+ print(" Old data cleared. Your next session will rebuild automatically.")
1762
+ except _measure_facade.sqlite3.Error as e:
1763
+ print(f" [Token Optimizer] migration failed: {e}", file=_measure_facade.sys.stderr)
1764
+
1765
+
1766
+ def _hermes_refresh_session_totals(conn, dedup_key, parsed):
1767
+ """Refresh an existing Hermes row's per-session numbers from a newer snapshot.
1768
+
1769
+ Returns True when the row was updated. The rule is monotonic: Hermes's
1770
+ state.db message and token counters only grow during a session, so the new
1771
+ snapshot wins only when it is >= the stored row on every counter and > on
1772
+ at least one. Quality and skills columns keep their own rules (they need a
1773
+ rollup's live reading) and are not touched here.
1774
+ """
1775
+ _measure_facade = _compat.facade()
1776
+ stored = conn.execute(
1777
+ "SELECT message_count, input_tokens, output_tokens, api_calls "
1778
+ "FROM session_log WHERE jsonl_path = ?",
1779
+ (dedup_key,),
1780
+ ).fetchone()
1781
+ if stored is None:
1782
+ return False
1783
+ new = (
1784
+ int(parsed.get("message_count") or 0),
1785
+ int(parsed.get("total_input_tokens") or 0),
1786
+ int(parsed.get("total_output_tokens") or 0),
1787
+ int(parsed.get("api_calls") or 0),
1788
+ )
1789
+ old = tuple(int(v or 0) for v in stored)
1790
+ if any(n < o for n, o in zip(new, old)) or new == old:
1791
+ return False
1792
+ conn.execute(
1793
+ """UPDATE session_log
1794
+ SET duration_minutes = ?, input_tokens = ?, output_tokens = ?,
1795
+ message_count = ?, api_calls = ?, cache_hit_rate = ?,
1796
+ cache_create_1h_tokens = ?, cache_create_5m_tokens = ?,
1797
+ avg_call_gap_seconds = ?, max_call_gap_seconds = ?,
1798
+ p95_call_gap_seconds = ?, subagents_json = ?, tool_calls_json = ?,
1799
+ model_usage_json = ?, all_model_usage_json = ?,
1800
+ model_usage_breakdown_json = ?, version = ?, topic = ?,
1801
+ collected_at = ?
1802
+ WHERE jsonl_path = ?""",
1803
+ (
1804
+ parsed["duration_minutes"],
1805
+ parsed["total_input_tokens"],
1806
+ parsed["total_output_tokens"],
1807
+ parsed["message_count"],
1808
+ parsed.get("api_calls", 0),
1809
+ parsed["cache_hit_rate"],
1810
+ parsed.get("total_cache_create_1h", 0),
1811
+ parsed.get("total_cache_create_5m", 0),
1812
+ parsed.get("avg_call_gap_seconds"),
1813
+ parsed.get("max_call_gap_seconds"),
1814
+ parsed.get("p95_call_gap_seconds"),
1815
+ _measure_facade.json.dumps(parsed.get("subagents_used", {})),
1816
+ _measure_facade.json.dumps(parsed.get("tool_calls", {})),
1817
+ _measure_facade.json.dumps(parsed.get("model_usage", {})),
1818
+ _measure_facade.json.dumps(parsed.get("model_usage", {})),
1819
+ _measure_facade.json.dumps(parsed.get("model_usage_breakdown", {})),
1820
+ parsed.get("version"),
1821
+ parsed.get("topic"),
1822
+ _measure_facade.datetime.now().isoformat(),
1823
+ dedup_key,
1824
+ ),
1825
+ )
1826
+ _measure_facade._store_adapter_activity(conn, dedup_key, parsed)
1827
+ return True
1828
+
1829
+
1830
+ def _collect_hermes_sessions(days=None, quiet=None, rebuild=None):
1831
+ """Collect Hermes sessions from state.db into the trends DB.
1832
+
1833
+ Mirrors collect_sessions() but sources rows from hermes_state.recent_sessions()
1834
+ + hermes_session.normalize_session() instead of JSONL files.
1835
+ Uses session slug as the dedup key (jsonl_path column) so idempotent.
1836
+ """
1837
+ _measure_facade = _compat.facade()
1838
+ import hermes_state as _hs # noqa: PLC0415
1839
+
1840
+ conn = _measure_facade._init_trends_db()
1841
+ try:
1842
+ if rebuild:
1843
+ if not quiet:
1844
+ print("[Token Optimizer] Rebuilding Hermes trends DB...")
1845
+ conn.execute("PRAGMA user_version = 3")
1846
+ conn.execute("DELETE FROM session_log")
1847
+ conn.execute("DELETE FROM session_log_aliases")
1848
+ conn.execute("DELETE FROM daily_stats")
1849
+ conn.execute("DELETE FROM model_daily")
1850
+ conn.execute("DELETE FROM skill_daily")
1851
+ conn.execute("DELETE FROM subagent_daily")
1852
+ # Drop event tables too: their session_id/session_uuid references would
1853
+ # otherwise dangle (no FK constraints) and silently inflate savings.
1854
+ conn.execute("DELETE FROM savings_events")
1855
+ conn.execute("DELETE FROM compression_events")
1856
+ conn.execute("DELETE FROM counted_reread")
1857
+ conn.commit()
1858
+
1859
+ rows = _hs.recent_sessions(days=days)
1860
+ if not rows:
1861
+ if not quiet:
1862
+ print(f"No Hermes sessions found in the last {days} days.")
1863
+ return 0
1864
+
1865
+ new_count = 0
1866
+ updated_count = 0
1867
+ for row in rows:
1868
+ session_id = str(row.get("id") or "")
1869
+ live_context_tokens = _measure_facade.__dict__.get("_HERMES_ROLLUP_CONTEXT", {}).get(session_id)
1870
+ parsed = _measure_facade.hermes_session.normalize_session(row, context_tokens=live_context_tokens)
1871
+ if not parsed:
1872
+ continue
1873
+ # Skill loads the plugin counted from Hermes's on_skill_lifecycle
1874
+ # hook (state.db does not record them).
1875
+ rollup_skills = _measure_facade.__dict__.get("_HERMES_ROLLUP_SKILLS", {}).get(session_id)
1876
+ if rollup_skills:
1877
+ parsed["skills_used"] = dict(rollup_skills)
1878
+
1879
+ slug = parsed.get("slug") or ""
1880
+ dedup_key = f"hermes:{slug}" if slug else None
1881
+ if not dedup_key:
1882
+ continue
1883
+
1884
+ if _measure_facade._is_file_collected(conn, dedup_key):
1885
+ new_count += _measure_facade._store_adapter_activity(conn, dedup_key, parsed)
1886
+ # A collect that ran while the session was still live stored
1887
+ # its totals at that point. Hermes's state.db counters only
1888
+ # grow, so refresh the per-session numbers whenever this
1889
+ # snapshot is at least as far along on every counter and ahead
1890
+ # on one. A snapshot behind on any counter is stale (e.g. a
1891
+ # dashboard collect that read state.db before a finished
1892
+ # rollup wrote) and never overwrites the newer row. Totals are
1893
+ # replaced, never added, and the aggregates are rebuilt from
1894
+ # session_log, so a refresh cannot double count.
1895
+ if _measure_facade._hermes_refresh_session_totals(conn, dedup_key, parsed):
1896
+ updated_count += 1
1897
+ # A rollup carries the session's live occupancy, which an
1898
+ # earlier mid-session collect could not see. Refresh the stored
1899
+ # grade in place so the first write does not freeze a
1900
+ # fill-blind score for the life of the DB. Non-rollup
1901
+ # collections (no live reading) keep the dedup's first write.
1902
+ if live_context_tokens is not None:
1903
+ conn.execute(
1904
+ """UPDATE session_log
1905
+ SET quality_score = ?, quality_grade = ?
1906
+ WHERE jsonl_path = ?""",
1907
+ (
1908
+ parsed.get("quality_score", 0),
1909
+ parsed.get("quality_grade", "F"),
1910
+ dedup_key,
1911
+ ),
1912
+ )
1913
+ updated_count += 1
1914
+ if rollup_skills:
1915
+ conn.execute(
1916
+ "UPDATE session_log SET skills_json = ? WHERE jsonl_path = ?",
1917
+ (_measure_facade.json.dumps(parsed["skills_used"]), dedup_key),
1918
+ )
1919
+ updated_count += 1
1920
+ continue
1921
+
1922
+ started_at = row.get("started_at")
1923
+ try:
1924
+ date = (
1925
+ _measure_facade.datetime.fromtimestamp(float(started_at)).strftime("%Y-%m-%d")
1926
+ if started_at is not None
1927
+ else _measure_facade.datetime.now().strftime("%Y-%m-%d")
1928
+ )
1929
+ except (TypeError, ValueError, OSError):
1930
+ date = _measure_facade.datetime.now().strftime("%Y-%m-%d")
1931
+ project_name = str(row.get("cwd") or "hermes")
1932
+
1933
+ cur = conn.execute(
1934
+ """INSERT OR IGNORE INTO session_log
1935
+ (jsonl_path, date, project, duration_minutes, input_tokens,
1936
+ output_tokens, message_count, api_calls, cache_hit_rate,
1937
+ cache_create_1h_tokens, cache_create_5m_tokens, cache_ttl_scanned,
1938
+ avg_call_gap_seconds, max_call_gap_seconds, p95_call_gap_seconds,
1939
+ skills_json, subagents_json, tool_calls_json, model_usage_json,
1940
+ all_model_usage_json, model_usage_breakdown_json, version, slug, topic, collected_at,
1941
+ quality_score, quality_grade, stale_waste_tokens, platform)
1942
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
1943
+ (
1944
+ dedup_key, date, project_name,
1945
+ parsed["duration_minutes"],
1946
+ parsed["total_input_tokens"],
1947
+ parsed["total_output_tokens"],
1948
+ parsed["message_count"],
1949
+ parsed.get("api_calls", 0),
1950
+ parsed["cache_hit_rate"],
1951
+ parsed.get("total_cache_create_1h", 0),
1952
+ parsed.get("total_cache_create_5m", 0),
1953
+ 1,
1954
+ parsed.get("avg_call_gap_seconds"),
1955
+ parsed.get("max_call_gap_seconds"),
1956
+ parsed.get("p95_call_gap_seconds"),
1957
+ _measure_facade.json.dumps(parsed.get("skills_used", {})),
1958
+ _measure_facade.json.dumps(parsed.get("subagents_used", {})),
1959
+ _measure_facade.json.dumps(parsed.get("tool_calls", {})),
1960
+ _measure_facade.json.dumps(parsed.get("model_usage", {})),
1961
+ _measure_facade.json.dumps(parsed.get("model_usage", {})),
1962
+ _measure_facade.json.dumps(parsed.get("model_usage_breakdown", {})),
1963
+ parsed.get("version"),
1964
+ parsed.get("slug"),
1965
+ parsed.get("topic"),
1966
+ _measure_facade.datetime.now().isoformat(),
1967
+ parsed.get("quality_score", 0),
1968
+ parsed.get("quality_grade", "F"),
1969
+ 0,
1970
+ "hermes",
1971
+ ),
1972
+ )
1973
+ if cur.rowcount != 1:
1974
+ continue
1975
+ _measure_facade._store_adapter_activity(conn, dedup_key, parsed)
1976
+ new_count += 1
1977
+
1978
+ # Q2: only rebuild aggregates when rows were actually inserted or
1979
+ # refreshed (daily_stats carries avg_quality_score / worst_grade).
1980
+ if new_count > 0 or updated_count > 0:
1981
+ _measure_facade._rebuild_aggregate_tables(conn)
1982
+ conn.commit()
1983
+ conn.execute("PRAGMA user_version = 3")
1984
+ conn.commit()
1985
+ finally:
1986
+ conn.close()
1987
+
1988
+ if not quiet:
1989
+ total = _measure_facade.conn_total_sessions() if _measure_facade.TRENDS_DB.exists() else new_count
1990
+ print(f"[Token Optimizer] Collected {new_count} new Hermes sessions. Total in DB: {total}")
1991
+ return new_count
1992
+
1993
+
1994
+ def _parse_hermes_rollup_skills(args):
1995
+ """Parse ``--session`` + ``--skills-json`` out of hermes-rollup CLI args.
1996
+
1997
+ Returns ``{session_id: {skill_name: loads}}`` or ``{}``. The JSON comes
1998
+ from the plugin's in-memory count; anything malformed is dropped, names
1999
+ are capped at 128 characters and counts must be positive integers.
2000
+ """
2001
+ _measure_facade = _compat.facade()
2002
+ session = ""
2003
+ raw = ""
2004
+ i = 0
2005
+ while i < len(args):
2006
+ if args[i] == "--session" and i + 1 < len(args):
2007
+ session = args[i + 1]
2008
+ i += 2
2009
+ elif args[i] == "--skills-json" and i + 1 < len(args):
2010
+ raw = args[i + 1]
2011
+ i += 2
2012
+ else:
2013
+ i += 1
2014
+ if not session or not raw or len(raw) > 65_536:
2015
+ return {}
2016
+ try:
2017
+ data = _measure_facade.json.loads(raw)
2018
+ except ValueError:
2019
+ return {}
2020
+ if not isinstance(data, dict):
2021
+ return {}
2022
+ skills = {}
2023
+ for name, count in list(data.items())[:_measure_facade._HERMES_SKILLS_MAX]:
2024
+ if (isinstance(name, str) and name.strip() and isinstance(count, int)
2025
+ and not isinstance(count, bool) and count > 0):
2026
+ skills[name.strip()[:128]] = min(count, 1_000_000)
2027
+ return {session: skills} if skills else {}
2028
+
2029
+
2030
+ def _parse_hermes_rollup_context(args):
2031
+ """Parse ``--session``/``--context-tokens`` out of hermes-rollup CLI args.
2032
+
2033
+ Returns ``{session_id: context_tokens}`` when both are present and the
2034
+ token count is a positive integer; ``{}`` otherwise. A zero, negative, or
2035
+ non-numeric value is not a real occupancy reading — it degrades to
2036
+ "unavailable" so the collected row omits fill instead of storing a fake
2037
+ 0% fill. ``--platform``/``--reason`` are accepted and skipped so the
2038
+ bridge's exact call signature never causes an error.
2039
+ """
2040
+ _measure_facade = _compat.facade()
2041
+ session = ""
2042
+ context_tokens = None
2043
+ i = 0
2044
+ while i < len(args):
2045
+ if args[i] == "--session" and i + 1 < len(args):
2046
+ session = args[i + 1]
2047
+ i += 2
2048
+ elif args[i] == "--context-tokens" and i + 1 < len(args):
2049
+ try:
2050
+ value = int(args[i + 1])
2051
+ except ValueError:
2052
+ value = 0
2053
+ context_tokens = value if value > 0 else None
2054
+ i += 2
2055
+ elif args[i] in ("--platform", "--reason") and i + 1 < len(args):
2056
+ i += 2
2057
+ else:
2058
+ i += 1
2059
+ return {session: context_tokens} if session and context_tokens is not None else {}
2060
+
2061
+
2062
+ def _hermes_transcript_dir():
2063
+ _measure_facade = _compat.facade()
2064
+ return _measure_facade.CHECKPOINT_DIR.parent / "hermes-transcripts"
2065
+
2066
+
2067
+ def _sweep_hermes_transcripts(directory, now=None):
2068
+ _measure_facade = _compat.facade()
2069
+ now = _measure_facade.time.time() if now is None else now
2070
+ try:
2071
+ for p in directory.glob("*.jsonl"):
2072
+ try:
2073
+ if not p.is_symlink() and now - p.stat().st_mtime > _measure_facade._HERMES_TRANSCRIPT_STALE_SECONDS:
2074
+ p.unlink()
2075
+ except OSError:
2076
+ continue
2077
+ except OSError:
2078
+ pass
2079
+
2080
+
2081
+ def hermes_checkpoint(session_id, trigger=None, fill_pct=None, cwd=None):
2082
+ """Write a session checkpoint for a Hermes session.
2083
+
2084
+ Hermes keeps its transcript in state.db, not a JSONL file. Read the
2085
+ session's messages read-only, translate them into the record shape the
2086
+ shared checkpoint engine reads, and hand that to ``compact_capture``. The
2087
+ translated file lives in Token Optimizer's own private directory for the
2088
+ duration of the call only.
2089
+
2090
+ Returns the checkpoint path, or None (no session id, no messages, or the
2091
+ engine declined). Never falls back to guessing another transcript: a
2092
+ Claude Code session on the same machine must never become a Hermes
2093
+ checkpoint.
2094
+ """
2095
+ _measure_facade = _compat.facade()
2096
+ sid = str(session_id or "").strip()
2097
+ if not sid:
2098
+ return None
2099
+ try:
2100
+ import hermes_state as _hs # noqa: PLC0415
2101
+ import hermes_session as _hsess # noqa: PLC0415
2102
+ except Exception:
2103
+ return None
2104
+ records = _hsess.messages_to_transcript_records(_hs.session_messages(sid, limit=500))
2105
+ if not records:
2106
+ return None
2107
+ if not cwd:
2108
+ # The session's own working directory, so the checkpoint's git line
2109
+ # describes the user's project, not wherever this process started.
2110
+ row_cwd = (_hs.get_session(sid, live=True) or {}).get("cwd")
2111
+ try:
2112
+ if isinstance(row_cwd, str) and row_cwd and _measure_facade.Path(row_cwd).is_dir():
2113
+ cwd = row_cwd
2114
+ except (OSError, ValueError):
2115
+ cwd = None
2116
+ directory = _measure_facade._hermes_transcript_dir()
2117
+ try:
2118
+ directory.mkdir(parents=True, exist_ok=True)
2119
+ try:
2120
+ _measure_facade.os.chmod(str(directory), 0o700)
2121
+ except OSError:
2122
+ pass
2123
+ except OSError:
2124
+ return None
2125
+ _measure_facade._sweep_hermes_transcripts(directory)
2126
+ fd, tmp_name = _measure_facade.tempfile.mkstemp(prefix=".hermes-", suffix=".jsonl", dir=str(directory))
2127
+ tmp_path = _measure_facade.Path(tmp_name)
2128
+ try:
2129
+ with _measure_facade.os.fdopen(fd, "w", encoding="utf-8") as fh:
2130
+ for record in records:
2131
+ fh.write(_measure_facade.json.dumps(record, ensure_ascii=False) + "\n")
2132
+ return _measure_facade.compact_capture(
2133
+ session_id=sid,
2134
+ trigger=trigger,
2135
+ cwd=cwd,
2136
+ fill_pct=fill_pct,
2137
+ _trusted_transcript=tmp_path,
2138
+ )
2139
+ finally:
2140
+ try:
2141
+ tmp_path.unlink()
2142
+ except OSError:
2143
+ pass
2144
+
2145
+
2146
+ def _hermes_checkpoint_cli(args):
2147
+ """``hermes-checkpoint --session <id> [--trigger T] [--fill-pct N] [--cwd DIR] [--quiet]``."""
2148
+ _measure_facade = _compat.facade()
2149
+ sid = ""
2150
+ trigger = "stop"
2151
+ fill_pct = None
2152
+ cwd = None
2153
+ i = 0
2154
+ while i < len(args):
2155
+ a = args[i]
2156
+ if a == "--session" and i + 1 < len(args):
2157
+ sid = args[i + 1]
2158
+ i += 2
2159
+ elif a == "--trigger" and i + 1 < len(args):
2160
+ trigger = args[i + 1]
2161
+ i += 2
2162
+ elif a == "--fill-pct" and i + 1 < len(args):
2163
+ try:
2164
+ fill_pct = float(args[i + 1])
2165
+ except ValueError:
2166
+ fill_pct = None
2167
+ i += 2
2168
+ elif a == "--cwd" and i + 1 < len(args):
2169
+ cwd = args[i + 1] or None
2170
+ i += 2
2171
+ else:
2172
+ i += 1
2173
+ quiet = "--quiet" in args or "-q" in args
2174
+ if cwd is not None:
2175
+ try:
2176
+ if not _measure_facade.Path(cwd).is_dir():
2177
+ cwd = None
2178
+ except (OSError, ValueError):
2179
+ cwd = None
2180
+ result = _measure_facade.hermes_checkpoint(sid, trigger=trigger, fill_pct=fill_pct, cwd=cwd)
2181
+ if result and not quiet:
2182
+ print(f"[Token Optimizer] Checkpoint saved: {result}")
2183
+ return result
2184
+
2185
+
2186
+ def hermes_turn_context(payload):
2187
+ """Per-turn model context for a Hermes session, in one process.
2188
+
2189
+ Same engines Claude Code's SessionStart / UserPromptSubmit hooks run:
2190
+ - first turn: the new-session checkpoint pointer (compact_restore)
2191
+ - every turn: the topic-matched prior-session hint (_continuity_prompt_hint)
2192
+ - when the plugin passes a live fill reading: the lean-output nudge
2193
+ (_verbosity_nudge_text). Hermes has no session-efficiency signal, so
2194
+ only the strong tier (75-89% fill) can apply; the plugin paces it.
2195
+
2196
+ ``payload`` keys: session_id, prompt, first_turn, fill_pct, score.
2197
+ Returns {"parts": [...], "verbosity": bool}. Never raises.
2198
+ """
2199
+ _measure_facade = _compat.facade()
2200
+ out = {"parts": [], "verbosity": False}
2201
+ if not isinstance(payload, dict):
2202
+ return out
2203
+ sid = str(payload.get("session_id") or "").strip()
2204
+ if not sid:
2205
+ return out
2206
+ if payload.get("first_turn"):
2207
+ from contextlib import redirect_stdout as _redirect_stdout # noqa: PLC0415
2208
+
2209
+ buf = _measure_facade.io.StringIO()
2210
+ try:
2211
+ with _redirect_stdout(buf):
2212
+ _measure_facade.compact_restore(session_id=sid, new_session_only=True)
2213
+ except Exception:
2214
+ pass
2215
+ pointer = buf.getvalue().strip()
2216
+ if pointer:
2217
+ out["parts"].append(pointer)
2218
+ prompt = str(payload.get("prompt") or "").strip()
2219
+ if prompt:
2220
+ try:
2221
+ hint = (_measure_facade._continuity_prompt_hint(prompt_text=prompt[:4000], session_id=sid) or "").strip()
2222
+ except Exception:
2223
+ hint = ""
2224
+ if hint:
2225
+ out["parts"].append(hint)
2226
+ fill = payload.get("fill_pct")
2227
+ if isinstance(fill, (int, float)) and not isinstance(fill, bool):
2228
+ score = payload.get("score")
2229
+ score = float(score) if isinstance(score, (int, float)) and not isinstance(score, bool) else 100.0
2230
+ # No efficiency signal on Hermes: 100 keeps the gentle tier off.
2231
+ window = payload.get("context_window")
2232
+ cached = ({"model_context_window": int(window)}
2233
+ if isinstance(window, int) and not isinstance(window, bool) and window > 0 else {})
2234
+ nudge = _measure_facade._verbosity_nudge_text(float(fill), score, 100, cached)
2235
+ if nudge:
2236
+ out["parts"].append(nudge)
2237
+ out["verbosity"] = True
2238
+ return out
2239
+
2240
+
2241
+ def _resolve_copilot_home_wsl_aware(mnt_root=None):
2242
+ """Resolve the Copilot home with a WSL-root /mnt/ exception.
2243
+
2244
+ Thin wrapper around ``runtime_env.copilot_home`` so the WSL ``/mnt/``
2245
+ opt-in has a SINGLE source of truth (``runtime_env._safe_home_from_env``
2246
+ → ``_wsl_mnt_safe_home``). The opt-in is now STRICTER than the previous
2247
+ shipped version: it is gated on actual WSL detection
2248
+ (``runtime_env._is_wsl_context`` reads ``/proc/version`` /
2249
+ ``/proc/sys/kernel/osrelease`` for the ``microsoft``/``WSL`` markers) so
2250
+ native-Linux ``/mnt`` mounts stay on the strict safe-home path and
2251
+ behavior there is byte-identical to before.
2252
+
2253
+ Precedence (handled inside ``runtime_env.copilot_home``):
2254
+ 1. TOKEN_OPTIMIZER_COPILOT_HOME (TO's own override) — strict under-$HOME
2255
+ guard, or the WSL-root /mnt/ opt-in. The only var users should set.
2256
+ 2. COPILOT_HOME (Copilot's own var) — back-compat location hint; a /mnt/
2257
+ value earns a guardrail warning because native-Windows Copilot reads
2258
+ the same var and a /mnt value breaks its own logging.
2259
+ 3. WSL-root auto-detect — probe /mnt/c/Users/*/.copilot for the sole
2260
+ Windows profile, so no env var is needed.
2261
+ 4. Otherwise → $HOME/.copilot.
2262
+
2263
+ ``mnt_root`` is a Path override for the WSL mount root, defaulting to
2264
+ ``/mnt``. It is a FUNCTION PARAMETER (not an env var) so it can ONLY be
2265
+ set by code calling this function directly (tests pass a temp dir since
2266
+ macOS can't create /mnt/c/...). The ``copilot-home`` subcommand never
2267
+ passes it, so production always uses the real ``/mnt`` — there is no env
2268
+ var a user could set to widen the /mnt/ confinement.
2269
+
2270
+ Returns a Path. Never raises — falls back to copilot_home() on any error.
2271
+ """
2272
+ _measure_facade = _compat.facade()
2273
+ from runtime_env import copilot_home as _ch # noqa: PLC0415
2274
+
2275
+ return _ch(mnt_root=mnt_root)
2276
+
2277
+
2278
+ def _write_copilot_restore_context(sessions, quiet=None):
2279
+ """Maintain the continuity file the sessionStart hook injects.
2280
+
2281
+ Summarizes the most recent completed CLI session so a new Copilot session
2282
+ starts grounded. Capped well under the bridge's 16KB read limit.
2283
+ """
2284
+ _measure_facade = _compat.facade()
2285
+ try:
2286
+ from runtime_env import copilot_home as _ch # noqa: PLC0415
2287
+
2288
+ cli = [s for s in sessions if s.get("token_source") == "copilot_cli_events"]
2289
+ if not cli:
2290
+ return
2291
+ # Prefer sessions with a real timestamp; only fall back to a dated-None
2292
+ # session when none have one (sort key keeps real ts ahead of None).
2293
+ latest = max(cli, key=lambda s: ((_measure_facade := _compat.facade()), (s.get("first_ts") is not None, s.get("first_ts") or ""))[1])
2294
+
2295
+ def _clean(value):
2296
+ # These come from Copilot's reverse-engineered event stream and are
2297
+ # injected verbatim into the model's context — strip newlines/control
2298
+ # chars and cap length so a crafted topic/cwd can't inject directives.
2299
+ _measure_facade = _compat.facade()
2300
+ text = str(value or "")
2301
+ text = "".join(ch for ch in text if ch == " " or ch.isprintable())
2302
+ return text[:200]
2303
+
2304
+ lines = ["[Token Optimizer] Continuity from your previous Copilot session:"]
2305
+ if latest.get("topic"):
2306
+ lines.append(f"- Topic: {_clean(latest['topic'])}")
2307
+ if latest.get("cwd"):
2308
+ lines.append(f"- Working dir: {_clean(latest['cwd'])}")
2309
+ lines.append(
2310
+ f"- Model: {_clean(latest.get('model', 'unknown'))}; "
2311
+ f"{latest.get('total_input_tokens', 0):,} in / "
2312
+ f"{latest.get('total_output_tokens', 0):,} out tokens"
2313
+ )
2314
+ if latest.get("incomplete"):
2315
+ lines.append("- NOTE: that session ended without a clean shutdown (crash/kill).")
2316
+ path = _ch() / "token-optimizer" / "restore-context.md"
2317
+ path.parent.mkdir(parents=True, exist_ok=True)
2318
+ # mkstemp + replace: an interrupted write or a cross-device replace
2319
+ # never leaves an orphan tmp file behind.
2320
+ import tempfile # noqa: PLC0415
2321
+
2322
+ fd, tmp_name = tempfile.mkstemp(prefix=".restore-context.", suffix=".tmp", dir=str(path.parent))
2323
+ try:
2324
+ with _measure_facade.os.fdopen(fd, "w", encoding="utf-8") as fh:
2325
+ fh.write("\n".join(lines) + "\n")
2326
+ _measure_facade.os.replace(tmp_name, str(path))
2327
+ except OSError:
2328
+ try:
2329
+ _measure_facade.os.unlink(tmp_name)
2330
+ except OSError:
2331
+ pass
2332
+ raise
2333
+ except Exception as exc:
2334
+ if not quiet:
2335
+ print(f"[Token Optimizer] restore-context update skipped: {exc}")
2336
+
2337
+
2338
+ def _grok_summary():
2339
+ """Token/cost-led session summary for Grok Build.
2340
+
2341
+ Grok Build ships authoritative per-turn usage (updates.jsonl) with a USD
2342
+ cost in 1e10 ticks, so both tokens and cost lead here — unlike Copilot's
2343
+ credits-only summary.
2344
+ """
2345
+ _measure_facade = _compat.facade()
2346
+ import grok_state as _gs # noqa: PLC0415
2347
+ import grok_session # noqa: PLC0415
2348
+ from runtime_env import grok_home as _gh # noqa: PLC0415
2349
+
2350
+ raw_sessions = list(_gs.read_all_sessions())
2351
+ normalized = [s for s in (grok_session.normalize_session(r) for r in raw_sessions) if s]
2352
+
2353
+ print("Token Optimizer — Grok Build summary")
2354
+ if not normalized:
2355
+ print()
2356
+ print(" No Grok Build sessions found yet.")
2357
+ print(f" Sessions live under {_gh()}/sessions/.")
2358
+ print()
2359
+ print(" Full trends: measure.py grok-rollup (sessions land in trends.db).")
2360
+ return
2361
+
2362
+ total_cost = sum(s.get("cost_usd") or 0.0 for s in normalized)
2363
+ cost_known = sum(1 for s in normalized if s.get("cost_source") == "grok_cost_usd_ticks")
2364
+ total_in = sum(s.get("total_input_tokens", 0) for s in normalized)
2365
+ total_out = sum(s.get("total_output_tokens", 0) for s in normalized)
2366
+ incomplete = sum(1 for s in normalized if s.get("incomplete"))
2367
+ estimated = sum(1 for s in normalized if s.get("estimated"))
2368
+ models = {}
2369
+ for s in normalized:
2370
+ for m, v in (s.get("model_usage") or {}).items():
2371
+ models[m] = models.get(m, 0) + v
2372
+ top_models = sorted(models.items(), key=lambda kv: ((_measure_facade := _compat.facade()), -kv[1])[1])[:3]
2373
+
2374
+ print()
2375
+ print(f" {len(normalized)} session(s)")
2376
+ if cost_known:
2377
+ print(f" Cost: ~${total_cost:,.2f} ({cost_known} session(s) with authoritative cost)")
2378
+ else:
2379
+ print(" Cost: no authoritative billing data recorded (costUsdTicks scrubbed)")
2380
+ print(f" Tokens: {total_in:,} in / {total_out:,} out")
2381
+ if top_models:
2382
+ print(" Models: " + ", ".join(f"{_measure_facade._strip_ansi(str(m))} ({v:,})" for m, v in top_models))
2383
+ if incomplete:
2384
+ print(f" {incomplete} session(s) ended without clean shutdown (usageIsIncomplete)")
2385
+ if estimated:
2386
+ print(f" {estimated} session(s) use estimated token counts (~est.)")
2387
+ print()
2388
+ print(" Full trends: measure.py grok-rollup (sessions land in trends.db).")
2389
+
2390
+
2391
+ def _collect_grok_sessions(days=None, quiet=None, rebuild=None):
2392
+ """Collect Grok Build sessions from $GROK_HOME/sessions into the trends DB.
2393
+
2394
+ Mirrors _collect_copilot_sessions: dedup via the jsonl_path column
2395
+ (``grok:<session-uuid>``), platform ``grok``, idempotent. Cost is
2396
+ token-derived from the authoritative costUsdTicks field (not credits).
2397
+ """
2398
+ _measure_facade = _compat.facade()
2399
+ import grok_state as _gs # noqa: PLC0415
2400
+ import grok_session # noqa: PLC0415
2401
+
2402
+ try:
2403
+ conn = _measure_facade._init_trends_db()
2404
+ except _measure_facade.sqlite3.DatabaseError:
2405
+ if _measure_facade.TRENDS_DB.exists():
2406
+ try:
2407
+ stamp = int(_measure_facade.datetime.now().timestamp())
2408
+ _measure_facade.TRENDS_DB.rename(_measure_facade.TRENDS_DB.with_suffix(f".db.corrupt.{stamp}"))
2409
+ except OSError:
2410
+ pass
2411
+ conn = _measure_facade._init_trends_db()
2412
+ try:
2413
+ if rebuild:
2414
+ if not quiet:
2415
+ print("[Token Optimizer] Rebuilding Grok trends DB...")
2416
+ conn.execute("PRAGMA user_version = 3")
2417
+ conn.execute("DELETE FROM session_log WHERE jsonl_path LIKE 'grok:%'")
2418
+ conn.commit()
2419
+
2420
+ try:
2421
+ raw_sessions = list(_gs.read_all_sessions())
2422
+ except Exception as exc:
2423
+ if not quiet:
2424
+ print(f"[Token Optimizer] Grok Build scan failed: {exc}")
2425
+ raw_sessions = []
2426
+
2427
+ cutoff = _measure_facade.datetime.now().timestamp() - days * 86400
2428
+ new_count = 0
2429
+ normalized = []
2430
+ for raw in raw_sessions:
2431
+ parsed = grok_session.normalize_session(raw)
2432
+ if not parsed:
2433
+ continue
2434
+ normalized.append(parsed)
2435
+
2436
+ slug = parsed.get("slug") or ""
2437
+ if not slug:
2438
+ continue
2439
+ dedup_key = f"grok:{slug}"
2440
+ is_incomplete = 1 if parsed.get("incomplete") else 0
2441
+ if _measure_facade._is_file_collected(conn, dedup_key):
2442
+ new_count += _measure_facade._store_adapter_activity(conn, dedup_key, parsed)
2443
+ if not is_incomplete:
2444
+ try:
2445
+ existing = conn.execute(
2446
+ "SELECT incomplete FROM session_log WHERE jsonl_path = ?",
2447
+ (dedup_key,),
2448
+ ).fetchone()
2449
+ except _measure_facade.sqlite3.Error:
2450
+ existing = None
2451
+ if existing is not None and existing[0]:
2452
+ try:
2453
+ conn.execute(
2454
+ """UPDATE session_log SET
2455
+ input_tokens=?, output_tokens=?, message_count=?,
2456
+ api_calls=?, cache_hit_rate=?, cache_create_1h_tokens=?,
2457
+ duration_minutes=?, quality_score=?, quality_grade=?,
2458
+ cost_usd=?, cost_source=?, credits=?, incomplete=0
2459
+ WHERE jsonl_path=? AND incomplete=1""",
2460
+ (
2461
+ parsed["total_input_tokens"], parsed["total_output_tokens"],
2462
+ parsed["message_count"], parsed.get("api_calls", 0),
2463
+ parsed["cache_hit_rate"], parsed.get("total_cache_create_1h", 0),
2464
+ parsed["duration_minutes"], parsed.get("quality_score", 0),
2465
+ parsed.get("quality_grade", "F"), parsed.get("cost_usd", 0.0),
2466
+ parsed.get("cost_source"), parsed.get("credits"), dedup_key,
2467
+ ),
2468
+ )
2469
+ _measure_facade._store_adapter_activity(conn, dedup_key, parsed)
2470
+ new_count += 1
2471
+ except _measure_facade.sqlite3.Error as exc:
2472
+ if not quiet:
2473
+ print(f"[Token Optimizer] could not upgrade a Grok session: {exc}")
2474
+ continue
2475
+
2476
+ active = _measure_facade._adapter_activity_ts(parsed)
2477
+ if active and active.timestamp() < cutoff:
2478
+ continue
2479
+ date = active.astimezone().strftime("%Y-%m-%d") if active else ""
2480
+ project_name = str(parsed.get("cwd") or "grok")
2481
+
2482
+ try:
2483
+ cur = conn.execute(
2484
+ """INSERT OR IGNORE INTO session_log
2485
+ (jsonl_path, date, project, duration_minutes, input_tokens,
2486
+ output_tokens, message_count, api_calls, cache_hit_rate,
2487
+ cache_create_1h_tokens, cache_create_5m_tokens, cache_ttl_scanned,
2488
+ avg_call_gap_seconds, max_call_gap_seconds, p95_call_gap_seconds,
2489
+ skills_json, subagents_json, tool_calls_json, model_usage_json,
2490
+ all_model_usage_json, model_usage_breakdown_json, version, slug, topic, collected_at,
2491
+ quality_score, quality_grade, stale_waste_tokens,
2492
+ cost_usd, cost_source, credits, platform, incomplete)
2493
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
2494
+ (
2495
+ dedup_key, date, project_name,
2496
+ parsed["duration_minutes"],
2497
+ parsed["total_input_tokens"],
2498
+ parsed["total_output_tokens"],
2499
+ parsed["message_count"],
2500
+ parsed.get("api_calls", 0),
2501
+ parsed["cache_hit_rate"],
2502
+ parsed.get("total_cache_create_1h", 0),
2503
+ parsed.get("total_cache_create_5m", 0),
2504
+ 1,
2505
+ parsed.get("avg_call_gap_seconds"),
2506
+ parsed.get("max_call_gap_seconds"),
2507
+ parsed.get("p95_call_gap_seconds"),
2508
+ _measure_facade.json.dumps(parsed.get("skills_used", {})),
2509
+ _measure_facade.json.dumps(parsed.get("subagents_used", {})),
2510
+ _measure_facade.json.dumps(parsed.get("tool_calls", {})),
2511
+ _measure_facade.json.dumps(parsed.get("model_usage", {})),
2512
+ _measure_facade.json.dumps(parsed.get("model_usage", {})),
2513
+ _measure_facade.json.dumps(parsed.get("model_usage_breakdown", {})),
2514
+ parsed.get("version"),
2515
+ parsed.get("slug"),
2516
+ parsed.get("topic"),
2517
+ _measure_facade.datetime.now().isoformat(),
2518
+ parsed.get("quality_score", 0),
2519
+ parsed.get("quality_grade", "F"),
2520
+ 0,
2521
+ parsed.get("cost_usd", 0.0),
2522
+ parsed.get("cost_source"),
2523
+ parsed.get("credits"),
2524
+ "grok",
2525
+ is_incomplete,
2526
+ ),
2527
+ )
2528
+ except _measure_facade.sqlite3.Error as exc:
2529
+ if not quiet:
2530
+ print(f"[Token Optimizer] skipped a Grok session: {exc}")
2531
+ continue
2532
+ if cur.rowcount != 1:
2533
+ continue
2534
+ _measure_facade._store_adapter_activity(conn, dedup_key, parsed)
2535
+ new_count += 1
2536
+
2537
+ if new_count > 0:
2538
+ _measure_facade._rebuild_aggregate_tables(conn)
2539
+ conn.commit()
2540
+ conn.execute("PRAGMA user_version = 3")
2541
+ conn.commit()
2542
+ finally:
2543
+ conn.close()
2544
+
2545
+ if not quiet:
2546
+ print(f"[Token Optimizer] Collected {new_count} new Grok Build sessions.")
2547
+ return new_count
2548
+
2549
+
2550
+ def _copilot_summary():
2551
+ """Credits-led session summary for GitHub Copilot (CLI + VS Code planes).
2552
+
2553
+ Cost leads: Copilot ships its own fill indicators, but since the
2554
+ June 2026 AI-Credits billing switch nothing answers "what did this cost me".
2555
+ """
2556
+ _measure_facade = _compat.facade()
2557
+ import copilot_state as _cps # noqa: PLC0415
2558
+
2559
+ try:
2560
+ import copilot_vscode as _cpv # noqa: PLC0415
2561
+ except ImportError:
2562
+ _cpv = None
2563
+
2564
+ planes = (
2565
+ ("Copilot CLI", list(_cps.read_all_sessions())),
2566
+ ("VS Code Copilot", list(_cpv.read_sessions()) if _cpv is not None else []),
2567
+ )
2568
+
2569
+ print("Token Optimizer — GitHub Copilot summary")
2570
+ any_data = False
2571
+ for label, raw_sessions in planes:
2572
+ normalized = [s for s in (_measure_facade.copilot_session.normalize_session(r) for r in raw_sessions) if s]
2573
+ if not normalized:
2574
+ continue
2575
+ any_data = True
2576
+ total_cost = sum(s.get("cost_usd") or 0.0 for s in normalized)
2577
+ credits = sum(s.get("credits") or 0.0 for s in normalized if s.get("credits"))
2578
+ total_in = sum(s.get("total_input_tokens", 0) for s in normalized)
2579
+ total_out = sum(s.get("total_output_tokens", 0) for s in normalized)
2580
+ incomplete = sum(1 for s in normalized if s.get("incomplete"))
2581
+ estimated = sum(1 for s in normalized if s.get("estimated"))
2582
+ models = {}
2583
+ for s in normalized:
2584
+ for m, v in (s.get("model_usage") or {}).items():
2585
+ models[m] = models.get(m, 0) + v
2586
+ top_models = sorted(models.items(), key=lambda kv: ((_measure_facade := _compat.facade()), -kv[1])[1])[:3]
2587
+
2588
+ print()
2589
+ print(f" {label}: {len(normalized)} session(s)")
2590
+ if credits:
2591
+ print(f" AI credits: {credits:,.2f} (~${total_cost:,.2f})")
2592
+ elif total_cost:
2593
+ print(f" Cost: ~${total_cost:,.2f} (premium requests)")
2594
+ else:
2595
+ print(" Cost: no billing data recorded by Copilot for these sessions")
2596
+ print(f" Tokens: {total_in:,} in / {total_out:,} out")
2597
+ if top_models:
2598
+ print(" Models: " + ", ".join(f"{_measure_facade._strip_ansi(str(m))} ({v:,})" for m, v in top_models))
2599
+ if incomplete:
2600
+ print(f" {incomplete} session(s) ended without clean shutdown (partial data)")
2601
+ if estimated:
2602
+ print(f" {estimated} session(s) use estimated token counts (~est.)")
2603
+ if not any_data:
2604
+ print()
2605
+ print(" No Copilot sessions found yet.")
2606
+ print(" CLI: run a `copilot` session. VS Code: enable the two")
2607
+ print(' "github.copilot.chat.agentDebugLog" settings for per-request cost.')
2608
+ print()
2609
+ print(" Full trends: measure.py copilot-rollup (sessions land in trends.db;")
2610
+ print(" cost figures are Copilot's own, never a repriced token estimate).")
2611
+
2612
+
2613
+ def _collect_copilot_sessions(days=None, quiet=None, rebuild=None):
2614
+ """Collect Copilot sessions (CLI + VS Code planes) into the trends DB.
2615
+
2616
+ Mirrors _collect_hermes_sessions. The two planes are separate session
2617
+ populations with distinct dedup keys — never merged, never summed.
2618
+ Idempotent via the jsonl_path dedup column.
2619
+
2620
+ TODO(dedup): the 28-column INSERT here and in _collect_hermes_sessions is
2621
+ copy-paste; extract _insert_normalized_session() on the next touch to
2622
+ either collector (date resolution + dedup-key stay platform-specific).
2623
+ """
2624
+ _measure_facade = _compat.facade()
2625
+ import copilot_state as _cps # noqa: PLC0415
2626
+
2627
+ try:
2628
+ import copilot_vscode as _cpv # noqa: PLC0415
2629
+ except ImportError:
2630
+ _cpv = None
2631
+
2632
+ try:
2633
+ conn = _measure_facade._init_trends_db()
2634
+ except _measure_facade.sqlite3.DatabaseError:
2635
+ # Corrupt trends.db (disk error, partial write): quarantine it and
2636
+ # start fresh rather than crashing the silent stop-hook rollup.
2637
+ if _measure_facade.TRENDS_DB.exists():
2638
+ try:
2639
+ stamp = int(_measure_facade.datetime.now().timestamp())
2640
+ _measure_facade.TRENDS_DB.rename(_measure_facade.TRENDS_DB.with_suffix(f".db.corrupt.{stamp}"))
2641
+ except OSError:
2642
+ pass
2643
+ conn = _measure_facade._init_trends_db()
2644
+ try:
2645
+ if rebuild:
2646
+ if not quiet:
2647
+ print("[Token Optimizer] Rebuilding Copilot trends DB...")
2648
+ conn.execute("PRAGMA user_version = 3")
2649
+ # Scope the wipe to Copilot rows ONLY — session_log is shared with
2650
+ # Claude/Codex/Hermes/OpenCode. An unscoped DELETE would nuke every
2651
+ # runtime's history. Aggregates are fully recomputed from the
2652
+ # surviving session_log rows below.
2653
+ conn.execute("DELETE FROM session_log WHERE jsonl_path LIKE 'copilot:%'")
2654
+ conn.commit()
2655
+
2656
+ try:
2657
+ raw_sessions = list(_cps.read_all_sessions())
2658
+ except Exception as exc:
2659
+ if not quiet:
2660
+ print(f"[Token Optimizer] Copilot CLI scan failed: {exc}")
2661
+ raw_sessions = []
2662
+ if _cpv is not None:
2663
+ try:
2664
+ raw_sessions.extend(_cpv.read_sessions())
2665
+ except Exception as exc:
2666
+ if not quiet:
2667
+ print(f"[Token Optimizer] VS Code Copilot scan skipped: {exc}")
2668
+
2669
+ cutoff = _measure_facade.datetime.now().timestamp() - days * 86400
2670
+ new_count = 0
2671
+ normalized = []
2672
+ for raw in raw_sessions:
2673
+ parsed = _measure_facade.copilot_session.normalize_session(raw)
2674
+ if not parsed:
2675
+ continue
2676
+ normalized.append(parsed)
2677
+
2678
+ slug = parsed.get("slug") or ""
2679
+ if not slug:
2680
+ continue
2681
+ dedup_key = f"copilot:{slug}"
2682
+ is_incomplete = 1 if parsed.get("incomplete") else 0
2683
+ if _measure_facade._is_file_collected(conn, dedup_key):
2684
+ new_count += _measure_facade._store_adapter_activity(conn, dedup_key, parsed)
2685
+ # Already recorded — but if the stored row was partial (the
2686
+ # session was still active / crashed when first rolled up) and
2687
+ # we now have COMPLETE totals, upgrade it in place. Otherwise
2688
+ # leave it (INSERT-OR-IGNORE semantics).
2689
+ if not is_incomplete:
2690
+ try:
2691
+ existing = conn.execute(
2692
+ "SELECT incomplete FROM session_log WHERE jsonl_path = ?",
2693
+ (dedup_key,),
2694
+ ).fetchone()
2695
+ except _measure_facade.sqlite3.Error:
2696
+ existing = None
2697
+ if existing is not None and existing[0]:
2698
+ try:
2699
+ conn.execute(
2700
+ """UPDATE session_log SET
2701
+ input_tokens=?, output_tokens=?, message_count=?,
2702
+ api_calls=?, cache_hit_rate=?, cache_create_1h_tokens=?,
2703
+ duration_minutes=?, quality_score=?, quality_grade=?,
2704
+ cost_usd=?, cost_source=?, credits=?, incomplete=0
2705
+ WHERE jsonl_path=? AND incomplete=1""",
2706
+ (
2707
+ parsed["total_input_tokens"], parsed["total_output_tokens"],
2708
+ parsed["message_count"], parsed.get("api_calls", 0),
2709
+ parsed["cache_hit_rate"], parsed.get("total_cache_create_1h", 0),
2710
+ parsed["duration_minutes"], parsed.get("quality_score", 0),
2711
+ parsed.get("quality_grade", "F"), parsed.get("cost_usd", 0.0),
2712
+ parsed.get("cost_source"), parsed.get("credits"), dedup_key,
2713
+ ),
2714
+ )
2715
+ _measure_facade._store_adapter_activity(conn, dedup_key, parsed)
2716
+ new_count += 1 # an upgrade is meaningful progress
2717
+ except _measure_facade.sqlite3.Error as exc:
2718
+ if not quiet:
2719
+ print(f"[Token Optimizer] could not upgrade a Copilot session: {exc}")
2720
+ continue
2721
+
2722
+ active = _measure_facade._adapter_activity_ts(parsed)
2723
+ if active and active.timestamp() < cutoff:
2724
+ continue
2725
+ # Timestamps are UTC; the local calendar day buckets like the JSONL
2726
+ # collectors (local mtime), so a late-evening session is not a day off.
2727
+ date = active.astimezone().strftime("%Y-%m-%d") if active else ""
2728
+ project_name = str(parsed.get("cwd") or "copilot")
2729
+
2730
+ try:
2731
+ cur = conn.execute(
2732
+ """INSERT OR IGNORE INTO session_log
2733
+ (jsonl_path, date, project, duration_minutes, input_tokens,
2734
+ output_tokens, message_count, api_calls, cache_hit_rate,
2735
+ cache_create_1h_tokens, cache_create_5m_tokens, cache_ttl_scanned,
2736
+ avg_call_gap_seconds, max_call_gap_seconds, p95_call_gap_seconds,
2737
+ skills_json, subagents_json, tool_calls_json, model_usage_json,
2738
+ all_model_usage_json, model_usage_breakdown_json, version, slug, topic, collected_at,
2739
+ quality_score, quality_grade, stale_waste_tokens,
2740
+ cost_usd, cost_source, credits, platform, incomplete)
2741
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
2742
+ (
2743
+ dedup_key, date, project_name,
2744
+ parsed["duration_minutes"],
2745
+ parsed["total_input_tokens"],
2746
+ parsed["total_output_tokens"],
2747
+ parsed["message_count"],
2748
+ parsed.get("api_calls", 0),
2749
+ parsed["cache_hit_rate"],
2750
+ parsed.get("total_cache_create_1h", 0),
2751
+ parsed.get("total_cache_create_5m", 0),
2752
+ 1,
2753
+ parsed.get("avg_call_gap_seconds"),
2754
+ parsed.get("max_call_gap_seconds"),
2755
+ parsed.get("p95_call_gap_seconds"),
2756
+ _measure_facade.json.dumps(parsed.get("skills_used", {})),
2757
+ _measure_facade.json.dumps(parsed.get("subagents_used", {})),
2758
+ _measure_facade.json.dumps(parsed.get("tool_calls", {})),
2759
+ _measure_facade.json.dumps(parsed.get("model_usage", {})),
2760
+ # all_model_usage_json must stay {model: int} — the
2761
+ # aggregate rebuilder sums it as model_daily totals.
2762
+ _measure_facade.json.dumps(parsed.get("model_usage", {})),
2763
+ _measure_facade.json.dumps(parsed.get("model_usage_breakdown", {})),
2764
+ parsed.get("version"),
2765
+ parsed.get("slug"),
2766
+ parsed.get("topic"),
2767
+ _measure_facade.datetime.now().isoformat(),
2768
+ parsed.get("quality_score", 0),
2769
+ parsed.get("quality_grade", "F"),
2770
+ 0,
2771
+ # Copilot cost is platform-reported, not token-derived.
2772
+ parsed.get("cost_usd", 0.0),
2773
+ parsed.get("cost_source"),
2774
+ parsed.get("credits"),
2775
+ "copilot",
2776
+ is_incomplete,
2777
+ ),
2778
+ )
2779
+ except _measure_facade.sqlite3.Error as exc:
2780
+ # One malformed session must never abort the whole rollup — it
2781
+ # runs quiet from the stop hook, so a single bad row would
2782
+ # silently drop every other session in the batch.
2783
+ if not quiet:
2784
+ print(f"[Token Optimizer] skipped a Copilot session: {exc}")
2785
+ continue
2786
+ if cur.rowcount != 1:
2787
+ continue
2788
+ _measure_facade._store_adapter_activity(conn, dedup_key, parsed)
2789
+ new_count += 1
2790
+
2791
+ if new_count > 0:
2792
+ _measure_facade._rebuild_aggregate_tables(conn)
2793
+ conn.commit()
2794
+ conn.execute("PRAGMA user_version = 3")
2795
+ conn.commit()
2796
+ finally:
2797
+ conn.close()
2798
+
2799
+ _measure_facade._write_copilot_restore_context(normalized, quiet=quiet)
2800
+
2801
+ if not quiet:
2802
+ print(f"[Token Optimizer] Collected {new_count} new Copilot sessions.")
2803
+ return new_count
2804
+
2805
+
2806
+ def _write_cursor_restore_context(sessions, quiet=None):
2807
+ """Maintain per-workspace continuity files the sessionStart hook injects.
2808
+
2809
+ Unlike Copilot (one terminal, one session), the Cursor IDE runs many
2810
+ concurrent chats across repos. A single global restore file would seed every
2811
+ new chat with whichever conversation rolled up last — unrelated context paid
2812
+ on a platform with no savings headline. So files are keyed by workspace root
2813
+ (``sha1(workspace_root)``) under ``restore-context/``; the bridge injects only
2814
+ the file matching its own workspace root.
2815
+ """
2816
+ _measure_facade = _compat.facade()
2817
+ try:
2818
+ import hashlib # noqa: PLC0415
2819
+ import tempfile # noqa: PLC0415
2820
+
2821
+ from runtime_env import cursor_home as _ch # noqa: PLC0415
2822
+
2823
+ # Group the most recent COMPLETE session per workspace root. The key
2824
+ # must match what the sessionStart hook looks up: workspace_roots[0]
2825
+ # (the repo root Cursor exports) first, then cwd as a fallback. Using
2826
+ # cwd alone would key the file by a tool's working_directory (often a
2827
+ # subdirectory) while sessionStart looks up the repo root — a silent
2828
+ # never-match.
2829
+ by_ws: dict = {}
2830
+ for s in sessions:
2831
+ if s.get("incomplete"):
2832
+ continue # never seed continuity from a crash/kill session
2833
+ wroots = s.get("workspace_roots")
2834
+ if isinstance(wroots, list) and wroots and isinstance(wroots[0], str) and wroots[0]:
2835
+ root = wroots[0]
2836
+ else:
2837
+ root = str(s.get("cwd") or s.get("slug") or "")
2838
+ if not root:
2839
+ continue
2840
+ by_ws.setdefault(root, []).append(s)
2841
+
2842
+ def _clean(value):
2843
+ _measure_facade = _compat.facade()
2844
+ text = str(value or "")
2845
+ text = "".join(ch for ch in text if ch == " " or ch.isprintable())
2846
+ return text[:200]
2847
+
2848
+ base = _ch() / "token-optimizer" / "restore-context"
2849
+ base.mkdir(parents=True, exist_ok=True)
2850
+ for root, group in by_ws.items():
2851
+ latest = max(group, key=lambda s: ((_measure_facade := _compat.facade()), (s.get("first_ts") is not None, s.get("first_ts") or ""))[1])
2852
+ lines = [f"[Token Optimizer] Continuity from your previous Cursor session in {_clean(root)}:"]
2853
+ if latest.get("model"):
2854
+ lines.append(
2855
+ f"- Model: {_clean(latest['model'])}; "
2856
+ f"{latest.get('total_input_tokens', 0):,} in / "
2857
+ f"{latest.get('total_output_tokens', 0):,} out tokens"
2858
+ )
2859
+ digest = hashlib.sha1(root.encode("utf-8", "replace")).hexdigest()
2860
+ path = base / f"{digest}.md"
2861
+ fd, tmp_name = tempfile.mkstemp(prefix=".restore-context.", suffix=".tmp", dir=str(base))
2862
+ try:
2863
+ with _measure_facade.os.fdopen(fd, "w", encoding="utf-8") as fh:
2864
+ fh.write("\n".join(lines) + "\n")
2865
+ _measure_facade.os.replace(tmp_name, str(path))
2866
+ except OSError:
2867
+ try:
2868
+ _measure_facade.os.unlink(tmp_name)
2869
+ except OSError:
2870
+ pass
2871
+ raise
2872
+ except Exception as exc:
2873
+ if not quiet:
2874
+ print(f"[Token Optimizer] Cursor restore-context update skipped: {exc}")
2875
+
2876
+
2877
+ def _cursor_summary():
2878
+ """Token/quality session summary for Cursor (honest: no local cost)."""
2879
+ _measure_facade = _compat.facade()
2880
+ try:
2881
+ from runtime_env import cursor_home as _ch # noqa: PLC0415
2882
+ except ImportError:
2883
+ _ch = None
2884
+ import cursor_state as _cst # noqa: PLC0415
2885
+
2886
+ home = _ch() if _ch is not None else _measure_facade.Path.home() / ".cursor"
2887
+ tallies = [t for p in _cst.find_tallies(home) if (t := _cst.read_tally(p)) is not None]
2888
+ normalized = [s for t in tallies if (s := _measure_facade.cursor_session.normalize_session(t))]
2889
+
2890
+ print("Token Optimizer — Cursor summary")
2891
+ if not normalized:
2892
+ print()
2893
+ print(" No Cursor sessions found yet.")
2894
+ print(" Upgrade to a Cursor build with hook support, then run:")
2895
+ print(" bash install.sh --cursor")
2896
+ print(" and start a session. The hook tally appears after the first tool call.")
2897
+ return
2898
+
2899
+ total_in = sum(s.get("total_input_tokens", 0) for s in normalized)
2900
+ total_out = sum(s.get("total_output_tokens", 0) for s in normalized)
2901
+ incomplete = sum(1 for s in normalized if s.get("incomplete"))
2902
+ estimated = sum(1 for s in normalized if s.get("estimated"))
2903
+ compactions = sum(s.get("compactions", 0) for s in normalized)
2904
+ surfaces = {}
2905
+ for s in normalized:
2906
+ sur = s.get("surface") or "unknown"
2907
+ surfaces[sur] = surfaces.get(sur, 0) + 1
2908
+
2909
+ print(f" {len(normalized)} session(s)")
2910
+ print(f" Tokens: {total_in:,} in / {total_out:,} out")
2911
+ if compactions:
2912
+ print(f" Compactions captured: {compactions}")
2913
+ if surfaces:
2914
+ print(" Surfaces: " + ", ".join(f"{k} ({v})" for k, v in sorted(surfaces.items())))
2915
+ if incomplete:
2916
+ print(f" {incomplete} session(s) still active (hook tally only)")
2917
+ if estimated:
2918
+ print(
2919
+ f" {estimated} session(s) use estimated token counts "
2920
+ "(state.vscdb tokenCount is best-effort; transcripts carry no usage)"
2921
+ )
2922
+ print()
2923
+ print(" Cost: Cursor stores no local billing data — no savings headline is")
2924
+ print(" rendered here by design (bash compression events are still counted).")
2925
+ print(" Full trends: measure.py cursor-rollup.")
2926
+
2927
+
2928
+ def _collect_cursor_sessions(days=None, quiet=None, rebuild=None):
2929
+ """Collect Cursor sessions (hook tally + data planes) into the trends DB.
2930
+
2931
+ Mirrors _collect_copilot_sessions. The hook tally is authoritative for
2932
+ calls/turns/compactions/model/cwd/timestamps; tokens come from state.vscdb
2933
+ (best-effort) or a chars-over-four transcript estimate. Idempotent via the
2934
+ jsonl_path dedup column (`cursor:<conversation_id>`), with in-place upgrade
2935
+ via _insert_normalized_session.
2936
+ """
2937
+ _measure_facade = _compat.facade()
2938
+ import cursor_state as _cst # noqa: PLC0415
2939
+
2940
+ try:
2941
+ from runtime_env import cursor_home as _ch # noqa: PLC0415
2942
+ except ImportError:
2943
+ _ch = None
2944
+
2945
+ try:
2946
+ conn = _measure_facade._init_trends_db()
2947
+ except _measure_facade.sqlite3.DatabaseError:
2948
+ if _measure_facade.TRENDS_DB.exists():
2949
+ try:
2950
+ stamp = int(_measure_facade.datetime.now().timestamp())
2951
+ _measure_facade.TRENDS_DB.rename(_measure_facade.TRENDS_DB.with_suffix(f".db.corrupt.{stamp}"))
2952
+ except OSError:
2953
+ pass
2954
+ conn = _measure_facade._init_trends_db()
2955
+ try:
2956
+ if rebuild:
2957
+ if not quiet:
2958
+ print("[Token Optimizer] Rebuilding Cursor trends DB...")
2959
+ conn.execute("PRAGMA user_version = 3")
2960
+ conn.execute("DELETE FROM session_log WHERE jsonl_path LIKE 'cursor:%'")
2961
+ conn.commit()
2962
+
2963
+ home = _ch() if _ch is not None else _measure_facade.Path.home() / ".cursor"
2964
+ tallies = []
2965
+ for p in _cst.find_tallies(home):
2966
+ t = _cst.read_tally(p)
2967
+ if t is not None:
2968
+ tallies.append(_cst.idle_finalise(t))
2969
+
2970
+ cutoff = _measure_facade.datetime.now().timestamp() - days * 86400
2971
+ composer_ids = [
2972
+ str(t.get("conversation_id") or t.get("session_id") or "") for t in tallies
2973
+ ]
2974
+ try:
2975
+ bubble_tokens = _cst.read_state_vscdb_tokens(composer_ids)
2976
+ except Exception:
2977
+ bubble_tokens = {}
2978
+
2979
+ new_count = 0
2980
+ normalized = []
2981
+ for t in tallies:
2982
+ cid = str(t.get("conversation_id") or t.get("session_id") or "")
2983
+ if not cid:
2984
+ continue
2985
+ t = dict(t)
2986
+ t["bubble_tokens"] = bubble_tokens.get(cid)
2987
+ try:
2988
+ t["transcript_tokens"] = _cst.transcript_estimate(t.get("transcript_path"), home)
2989
+ except Exception:
2990
+ t["transcript_tokens"] = None
2991
+ parsed = _measure_facade.cursor_session.normalize_session(t)
2992
+ if not parsed:
2993
+ continue
2994
+ normalized.append(parsed)
2995
+
2996
+ active = _measure_facade._adapter_activity_ts(parsed)
2997
+ if active and active.timestamp() < cutoff:
2998
+ continue
2999
+
3000
+ dedup_key = f"cursor:{cid}"
3001
+ if _measure_facade._insert_normalized_session(conn, dedup_key, parsed, "cursor", "cursor", quiet=quiet):
3002
+ new_count += 1
3003
+
3004
+ if new_count > 0:
3005
+ _measure_facade._rebuild_aggregate_tables(conn)
3006
+ conn.commit()
3007
+ conn.execute("PRAGMA user_version = 3")
3008
+ conn.commit()
3009
+ finally:
3010
+ conn.close()
3011
+
3012
+ _measure_facade._write_cursor_restore_context(normalized, quiet=quiet)
3013
+
3014
+ if not quiet:
3015
+ print(f"[Token Optimizer] Collected {new_count} new Cursor sessions.")
3016
+ return new_count
3017
+
3018
+
3019
+ def _antigravity_restore_clean(value) -> str:
3020
+ """R22 filter: printable-only, single-line, 200-char cap.
3021
+
3022
+ Conversation titles and workspace paths are untrusted input injected into
3023
+ the next session's context, so newlines/control chars are stripped and the
3024
+ length is capped exactly like the Copilot continuity filter.
3025
+ """
3026
+ _measure_facade = _compat.facade()
3027
+ text = str(value or "")
3028
+ text = "".join(ch for ch in text if ch == " " or ch.isprintable())
3029
+ return " ".join(text.split())[:200]
3030
+
3031
+
3032
+ def _write_antigravity_restore_context(sessions, quiet=None):
3033
+ """Maintain the continuity file the PreInvocation hook injects.
3034
+
3035
+ Summarizes the most recent completed Antigravity session so a new session
3036
+ starts grounded. Capped well under the bridge's 16KB read limit.
3037
+ """
3038
+ _measure_facade = _compat.facade()
3039
+ try:
3040
+ from runtime_env import antigravity_home # noqa: PLC0415
3041
+
3042
+ complete = [s for s in sessions if not s.get("incomplete")]
3043
+ pool = complete or sessions
3044
+ if not pool:
3045
+ return
3046
+ latest = max(
3047
+ pool,
3048
+ key=lambda s: ((_measure_facade := _compat.facade()), (s.get("first_ts") is not None, s.get("first_ts") or ""))[1],
3049
+ )
3050
+
3051
+ lines = ["[Token Optimizer] Continuity from your previous Antigravity session:"]
3052
+ if latest.get("topic"):
3053
+ lines.append(f"- Topic: {_measure_facade._antigravity_restore_clean(latest['topic'])}")
3054
+ if latest.get("cwd"):
3055
+ lines.append(f"- Working dir: {_measure_facade._antigravity_restore_clean(latest['cwd'])}")
3056
+ lines.append(
3057
+ f"- Model: {_measure_facade._antigravity_restore_clean(latest.get('model', 'unknown'))}; "
3058
+ f"{latest.get('total_input_tokens', 0):,} in / "
3059
+ f"{latest.get('total_output_tokens', 0):,} out tokens"
3060
+ )
3061
+ if latest.get("incomplete"):
3062
+ lines.append("- NOTE: that session ended without a clean shutdown (crash/kill).")
3063
+
3064
+ path = antigravity_home() / "token-optimizer" / "restore-context.md"
3065
+ path.parent.mkdir(parents=True, exist_ok=True)
3066
+ import tempfile # noqa: PLC0415
3067
+
3068
+ fd, tmp_name = tempfile.mkstemp(prefix=".restore-context.", suffix=".tmp", dir=str(path.parent))
3069
+ try:
3070
+ with _measure_facade.os.fdopen(fd, "w", encoding="utf-8") as fh:
3071
+ fh.write("\n".join(lines) + "\n")
3072
+ _measure_facade.os.replace(tmp_name, str(path))
3073
+ except OSError:
3074
+ try:
3075
+ _measure_facade.os.unlink(tmp_name)
3076
+ except OSError:
3077
+ pass
3078
+ raise
3079
+ except Exception as exc:
3080
+ if not quiet:
3081
+ print(f"[Token Optimizer] restore-context update skipped: {exc}")
3082
+
3083
+
3084
+ def _price_antigravity_session(session):
3085
+ """Price known model buckets separately; identify incomplete rate coverage."""
3086
+ _measure_facade = _compat.facade()
3087
+ if session.get("cost_source") != "antigravity_list_price_estimate":
3088
+ return
3089
+ breakdown = session.get("model_usage_breakdown") or {}
3090
+ session["cost_usd"] = sum(
3091
+ _measure_facade._get_model_cost(model, part.get("fresh_input", 0), part.get("output", 0),
3092
+ cache_read=part.get("cache_read", 0), per_request=bool(parts.get("requests")))
3093
+ for model, parts in breakdown.items() for part in (parts.get("requests") or [parts])
3094
+ )
3095
+ if any(not _measure_facade._is_priced_model(model) for model in breakdown):
3096
+ session["cost_source"] = "antigravity_list_price_partial"
3097
+
3098
+
3099
+ def _antigravity_summary():
3100
+ """Per-surface session summary for Antigravity plus decoder health."""
3101
+ _measure_facade = _compat.facade()
3102
+ import antigravity_state as _ags # noqa: PLC0415
3103
+
3104
+ print("Token Optimizer — Google Antigravity summary")
3105
+ raw_by_surface: dict[str, list] = {}
3106
+ undecodable = 0
3107
+ decodable = 0
3108
+ for raw in _ags.read_all_sessions():
3109
+ raw_by_surface.setdefault(str(raw.get("surface") or "unknown"), []).append(raw)
3110
+ undecodable += raw.get("undecodable_rows", 0)
3111
+ decodable += len(raw.get("generations") or [])
3112
+
3113
+ any_data = False
3114
+ for surface in ("antigravity-cli", "antigravity", "antigravity-ide"):
3115
+ if surface not in raw_by_surface:
3116
+ continue
3117
+ normalized = [s for s in (_measure_facade.antigravity_session.normalize_session(r) for r in raw_by_surface[surface]) if s]
3118
+ if not normalized:
3119
+ continue
3120
+ any_data = True
3121
+ # Price list-price sessions at Gemini card rates so the "estimated cost"
3122
+ # line is a real dollar figure, not the normalizer's placeholder zero
3123
+ # (the normalizer never prices — KTD12; the collector does it).
3124
+ for s in normalized:
3125
+ _measure_facade._price_antigravity_session(s)
3126
+ total_in = sum(s.get("total_input_tokens", 0) for s in normalized)
3127
+ total_out = sum(s.get("total_output_tokens", 0) for s in normalized)
3128
+ total_cache = sum(s.get("total_cache_read", 0) for s in normalized)
3129
+ cost = sum(s.get("cost_usd") or 0.0 for s in normalized)
3130
+ credits = sum(s.get("credits") or 0.0 for s in normalized if s.get("credits"))
3131
+ incomplete = sum(1 for s in normalized if s.get("incomplete"))
3132
+ models: dict[str, int] = {}
3133
+ for s in normalized:
3134
+ for m, v in (s.get("model_usage") or {}).items():
3135
+ models[m] = models.get(m, 0) + v
3136
+ top_models = sorted(models.items(), key=lambda kv: ((_measure_facade := _compat.facade()), -kv[1])[1])[:3]
3137
+
3138
+ print()
3139
+ print(f" {surface}: {len(normalized)} session(s)")
3140
+ if credits:
3141
+ print(f" Antigravity credits: {credits:,.2f}")
3142
+ elif cost > 0.0:
3143
+ partial = any(s.get("cost_source") == "antigravity_list_price_partial" for s in normalized)
3144
+ print(f" Estimated cost: ~${cost:,.2f} (list prices" + (", known models only" if partial else "") + ")")
3145
+ else:
3146
+ print(" Cost: unavailable (no model with a known Gemini rate card)")
3147
+ print(f" Tokens: {total_in:,} in / {total_out:,} out / {total_cache:,} cache-read")
3148
+ if top_models:
3149
+ print(" Models: " + ", ".join(f"{_measure_facade._strip_ansi(str(m))} ({v:,})" for m, v in top_models))
3150
+ if incomplete:
3151
+ print(f" {incomplete} session(s) ended without clean shutdown (partial data)")
3152
+ if not any_data:
3153
+ print()
3154
+ print(" No Antigravity sessions found yet.")
3155
+ if decodable or undecodable:
3156
+ try:
3157
+ from antigravity_proto import DECODER_VERSION # noqa: PLC0415
3158
+ except Exception:
3159
+ DECODER_VERSION = "ag-v1"
3160
+ print()
3161
+ print(f" Decoder health: {decodable} decodable, {undecodable} undecodable "
3162
+ f"gen_metadata row(s) (decoder {DECODER_VERSION}).")
3163
+ print()
3164
+ print(" Full trends: measure.py antigravity-rollup (sessions land in trends.db).")
3165
+
3166
+
3167
+ def _collect_antigravity_sessions(days=None, quiet=None, rebuild=None):
3168
+ """Collect Antigravity sessions into the trends DB, priced per R8.
3169
+
3170
+ Mirrors _collect_copilot_sessions. The three surfaces are separate session
3171
+ populations with distinct dedup keys (``antigravity:<surface>:<conversation_id>``)
3172
+ — never merged, never summed. Idempotent via the jsonl_path dedup column.
3173
+ """
3174
+ _measure_facade = _compat.facade()
3175
+ import antigravity_state as _ags # noqa: PLC0415
3176
+
3177
+ # R20: no consent record -> no collection, no restore-context write.
3178
+ try:
3179
+ from runtime_env import antigravity_home # noqa: PLC0415
3180
+
3181
+ consent_path = antigravity_home() / "token-optimizer" / "config.json"
3182
+ consent = False
3183
+ if consent_path.is_file():
3184
+ cfg = _measure_facade.json.loads(consent_path.read_text(encoding="utf-8"))
3185
+ consent = bool(isinstance(cfg, dict) and cfg.get("antigravity_consent"))
3186
+ except (OSError, _measure_facade.json.JSONDecodeError, ValueError):
3187
+ consent = False
3188
+ if not consent:
3189
+ if not quiet:
3190
+ print("[Token Optimizer] Antigravity data collection is consent-gated; "
3191
+ "run `bash install.sh --antigravity` to record consent.")
3192
+ return 0
3193
+
3194
+ try:
3195
+ conn = _measure_facade._init_trends_db()
3196
+ except _measure_facade.sqlite3.DatabaseError:
3197
+ if _measure_facade.TRENDS_DB.exists():
3198
+ try:
3199
+ stamp = int(_measure_facade.datetime.now().timestamp())
3200
+ _measure_facade.TRENDS_DB.rename(_measure_facade.TRENDS_DB.with_suffix(f".db.corrupt.{stamp}"))
3201
+ except OSError:
3202
+ pass
3203
+ conn = _measure_facade._init_trends_db()
3204
+ try:
3205
+ if rebuild:
3206
+ if not quiet:
3207
+ print("[Token Optimizer] Rebuilding Antigravity trends rows...")
3208
+ conn.execute("PRAGMA user_version = 3")
3209
+ conn.execute("DELETE FROM session_log WHERE jsonl_path LIKE 'antigravity:%'")
3210
+ conn.commit()
3211
+
3212
+ try:
3213
+ raw_sessions = list(_ags.read_all_sessions())
3214
+ except Exception as exc:
3215
+ if not quiet:
3216
+ print(f"[Token Optimizer] Antigravity scan failed: {exc}")
3217
+ raw_sessions = []
3218
+
3219
+ cutoff = _measure_facade.datetime.now().timestamp() - days * 86400
3220
+ new_count = 0
3221
+ normalized = []
3222
+ for raw in raw_sessions:
3223
+ parsed = _measure_facade.antigravity_session.normalize_session(raw)
3224
+ if not parsed:
3225
+ continue
3226
+ normalized.append(parsed)
3227
+
3228
+ # R8 pricing: only the list-price-estimate path is denominated in
3229
+ # USD; credits are Antigravity's own figure and stay USD-less.
3230
+ _measure_facade._price_antigravity_session(parsed)
3231
+
3232
+ dedup_key = parsed.get("dedup_key")
3233
+ if not dedup_key:
3234
+ continue
3235
+ is_incomplete = 1 if parsed.get("incomplete") else 0
3236
+ if _measure_facade._is_file_collected(conn, dedup_key):
3237
+ new_count += _measure_facade._store_adapter_activity(conn, dedup_key, parsed)
3238
+ if not is_incomplete and parsed.get("generation_details_complete"):
3239
+ model_usage = _measure_facade.json.dumps(parsed.get("model_usage", {}))
3240
+ breakdown = _measure_facade.json.dumps(parsed.get("model_usage_breakdown", {}))
3241
+ cost = parsed.get("cost_usd", 0.0)
3242
+ source = parsed.get("cost_source")
3243
+ cur = conn.execute(
3244
+ """UPDATE session_log SET model_usage_json=?, all_model_usage_json=?,
3245
+ model_usage_breakdown_json=?, cost_usd=?, cost_source=?
3246
+ WHERE jsonl_path=? AND (incomplete=1 OR (input_tokens=? AND output_tokens=?))
3247
+ AND (model_usage_json IS NOT ? OR
3248
+ all_model_usage_json IS NOT ? OR model_usage_breakdown_json IS NOT ? OR
3249
+ cost_usd IS NOT ? OR cost_source IS NOT ?)""",
3250
+ (model_usage, model_usage, breakdown, cost, source, dedup_key,
3251
+ parsed["total_input_tokens"], parsed["total_output_tokens"],
3252
+ model_usage, model_usage, breakdown, cost, source),
3253
+ )
3254
+ new_count += cur.rowcount
3255
+ if not is_incomplete:
3256
+ try:
3257
+ existing = conn.execute(
3258
+ "SELECT incomplete FROM session_log WHERE jsonl_path = ?",
3259
+ (dedup_key,),
3260
+ ).fetchone()
3261
+ except _measure_facade.sqlite3.Error:
3262
+ existing = None
3263
+ if existing is not None and existing[0]:
3264
+ try:
3265
+ conn.execute(
3266
+ """UPDATE session_log SET
3267
+ input_tokens=?, output_tokens=?, message_count=?,
3268
+ api_calls=?, cache_hit_rate=?, cache_create_1h_tokens=?,
3269
+ duration_minutes=?, quality_score=?, quality_grade=?,
3270
+ cost_usd=?, cost_source=?, credits=?, incomplete=0
3271
+ WHERE jsonl_path=? AND incomplete=1""",
3272
+ (
3273
+ parsed["total_input_tokens"], parsed["total_output_tokens"],
3274
+ parsed["message_count"], parsed.get("api_calls", 0),
3275
+ parsed["cache_hit_rate"], parsed.get("total_cache_create_1h", 0),
3276
+ parsed["duration_minutes"], parsed.get("quality_score", 0),
3277
+ parsed.get("quality_grade", "F"), parsed.get("cost_usd", 0.0),
3278
+ parsed.get("cost_source"), parsed.get("credits"), dedup_key,
3279
+ ),
3280
+ )
3281
+ _measure_facade._store_adapter_activity(conn, dedup_key, parsed)
3282
+ new_count += 1
3283
+ except _measure_facade.sqlite3.Error as exc:
3284
+ if not quiet:
3285
+ print(f"[Token Optimizer] could not upgrade an Antigravity session: {exc}")
3286
+ continue
3287
+
3288
+ active = _measure_facade._adapter_activity_ts(parsed)
3289
+ if active and active.timestamp() < cutoff:
3290
+ continue
3291
+ date = active.astimezone().strftime("%Y-%m-%d") if active else ""
3292
+ project_name = str(parsed.get("cwd") or "antigravity")
3293
+
3294
+ try:
3295
+ cur = conn.execute(
3296
+ """INSERT OR IGNORE INTO session_log
3297
+ (jsonl_path, date, project, duration_minutes, input_tokens,
3298
+ output_tokens, message_count, api_calls, cache_hit_rate,
3299
+ cache_create_1h_tokens, cache_create_5m_tokens, cache_ttl_scanned,
3300
+ avg_call_gap_seconds, max_call_gap_seconds, p95_call_gap_seconds,
3301
+ skills_json, subagents_json, tool_calls_json, model_usage_json,
3302
+ all_model_usage_json, model_usage_breakdown_json, version, slug, topic, collected_at,
3303
+ quality_score, quality_grade, stale_waste_tokens,
3304
+ cost_usd, cost_source, credits, platform, incomplete)
3305
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
3306
+ (
3307
+ dedup_key, date, project_name,
3308
+ parsed["duration_minutes"],
3309
+ parsed["total_input_tokens"],
3310
+ parsed["total_output_tokens"],
3311
+ parsed["message_count"],
3312
+ parsed.get("api_calls", 0),
3313
+ parsed["cache_hit_rate"],
3314
+ parsed.get("total_cache_create_1h", 0),
3315
+ parsed.get("total_cache_create_5m", 0),
3316
+ 1,
3317
+ parsed.get("avg_call_gap_seconds"),
3318
+ parsed.get("max_call_gap_seconds"),
3319
+ parsed.get("p95_call_gap_seconds"),
3320
+ _measure_facade.json.dumps(parsed.get("skills_used", {})),
3321
+ _measure_facade.json.dumps(parsed.get("subagents_used", {})),
3322
+ _measure_facade.json.dumps(parsed.get("tool_calls", {})),
3323
+ _measure_facade.json.dumps(parsed.get("model_usage", {})),
3324
+ _measure_facade.json.dumps(parsed.get("model_usage", {})),
3325
+ _measure_facade.json.dumps(parsed.get("model_usage_breakdown", {})),
3326
+ parsed.get("version"),
3327
+ parsed.get("slug"),
3328
+ parsed.get("topic"),
3329
+ _measure_facade.datetime.now().isoformat(),
3330
+ parsed.get("quality_score", 0),
3331
+ parsed.get("quality_grade", "F"),
3332
+ 0,
3333
+ parsed.get("cost_usd", 0.0),
3334
+ parsed.get("cost_source"),
3335
+ parsed.get("credits"),
3336
+ "antigravity",
3337
+ is_incomplete,
3338
+ ),
3339
+ )
3340
+ except _measure_facade.sqlite3.Error as exc:
3341
+ if not quiet:
3342
+ print(f"[Token Optimizer] skipped an Antigravity session: {exc}")
3343
+ continue
3344
+ if cur.rowcount != 1:
3345
+ continue
3346
+ _measure_facade._store_adapter_activity(conn, dedup_key, parsed)
3347
+ new_count += 1
3348
+
3349
+ if new_count > 0:
3350
+ _measure_facade._rebuild_aggregate_tables(conn)
3351
+ conn.commit()
3352
+ conn.execute("PRAGMA user_version = 3")
3353
+ conn.commit()
3354
+ finally:
3355
+ conn.close()
3356
+
3357
+ _measure_facade._write_antigravity_restore_context(normalized, quiet=quiet)
3358
+
3359
+ if not quiet:
3360
+ print(f"[Token Optimizer] Collected {new_count} new Antigravity sessions.")
3361
+ return new_count
3362
+
3363
+
3364
+ def _merge_daily_usage(into, other):
3365
+ """Add one daily_usage map ({date: {model: buckets}}) into another in place."""
3366
+ _measure_facade = _compat.facade()
3367
+ for day, models in (other or {}).items():
3368
+ if not isinstance(models, dict):
3369
+ continue
3370
+ dst_day = into.setdefault(day, {})
3371
+ for model, parts in models.items():
3372
+ if not isinstance(parts, dict):
3373
+ continue
3374
+ dst = dst_day.setdefault(model, {})
3375
+ for key, val in parts.items():
3376
+ dst[key] = int(dst.get(key) or 0) + int(val or 0)
3377
+ return into
3378
+
3379
+
3380
+ def _session_merged_requests(filepath, parsed, subagent_files):
3381
+ """Every API request of a session across its parent and subagent files and
3382
+ every other copy of it, merged by requestId (largest usage wins,
3383
+ streaming-safe). A request Claude Code wrote into two files counts once,
3384
+ identical copies add nothing, and copies that diverged (each holding
3385
+ requests the other lacks) lose nothing. None for adapter output that has
3386
+ no per-request detail."""
3387
+ _measure_facade = _compat.facade()
3388
+ per_file = [(str(filepath), parsed)]
3389
+ per_file += [(str(copy), _measure_facade._parse_session_jsonl(copy)) for copy in _measure_facade._session_copy_files(filepath)]
3390
+ per_file += [(str(sub_jf), _measure_facade._parse_session_jsonl(sub_jf)) for sub_jf in subagent_files]
3391
+ if not all(p is None or "request_usage" in p for _, p in per_file):
3392
+ return None
3393
+ merged = {}
3394
+ for path, p in per_file:
3395
+ for key, u in ((p or {}).get("request_usage") or {}).items():
3396
+ if str(key).startswith("__noreq__"):
3397
+ # No requestId: keyed by file name and position, so the same
3398
+ # record in two copies of one file still counts once.
3399
+ key = f"{_measure_facade.Path(path).name}:{key}"
3400
+ prev = merged.get(key)
3401
+ if prev is None:
3402
+ merged[key] = dict(u)
3403
+ continue
3404
+ for field in ("inp", "out", "cr", "cc", "cc_1h", "cc_5m"):
3405
+ prev[field] = max(int(prev.get(field) or 0), int(u.get(field) or 0))
3406
+ # Same request seen twice: attributes must not depend on file order.
3407
+ # A real model beats "unknown"; the earliest dated day wins.
3408
+ days = [d for d in (prev.get("day"), u.get("day")) if d]
3409
+ prev["day"] = min(days) if days else None
3410
+ models = sorted(m for m in (prev.get("model"), u.get("model")) if m and m != "unknown")
3411
+ prev["model"] = models[0] if models else (prev.get("model") or u.get("model"))
3412
+ return merged
3413
+
3414
+
3415
+ def _stable_hash63(text):
3416
+ """Stable 63-bit integer for a string (fits a signed SQLite INTEGER)."""
3417
+ _measure_facade = _compat.facade()
3418
+ digest = _measure_facade.hashlib.blake2b(str(text).encode("utf-8", "replace"), digest_size=8).digest()
3419
+ return int.from_bytes(digest, "big") >> 1
3420
+
3421
+
3422
+ def _request_base_key(key):
3423
+ """The identity under which a request's usage is shared between sessions, or
3424
+ None when it cannot be shared. Records with neither a request id nor a
3425
+ message id are keyed by file position, so they never match another file.
3426
+ An advisor part ("<request>#advisorN") is its own entry with its own usage."""
3427
+ _measure_facade = _compat.facade()
3428
+ key = str(key)
3429
+ if key.startswith("__noreq__") or ":__noreq__" in key:
3430
+ return None
3431
+ return key
3432
+
3433
+
3434
+ def _usage_owner_id(filepath):
3435
+ """Identity under which a session claims its requests: the session UUID, so
3436
+ every copy of one session is one owner, else the transcript path."""
3437
+ _measure_facade = _compat.facade()
3438
+ return _measure_facade._canonical_session_uuid(filepath) or str(filepath)
3439
+
3440
+
3441
+ def _live_usage_owners(conn):
3442
+ """Owner hashes of every session that currently has a row (or a tracked copy)."""
3443
+ _measure_facade = _compat.facade()
3444
+ live = set()
3445
+ for table in ("session_log", "session_log_aliases"):
3446
+ try:
3447
+ for uuid, path in conn.execute(f"SELECT session_uuid, jsonl_path FROM {table}"):
3448
+ if uuid:
3449
+ live.add(_measure_facade._stable_hash63(uuid))
3450
+ if path:
3451
+ live.add(_measure_facade._stable_hash63(path))
3452
+ except _measure_facade.sqlite3.Error:
3453
+ continue
3454
+ return live
3455
+
3456
+
3457
+ def _empty_share():
3458
+ _measure_facade = _compat.facade()
3459
+ share = dict.fromkeys(_measure_facade._SHARE_FIELDS, 0)
3460
+ share["n"] = 0
3461
+ return share
3462
+
3463
+
3464
+ def _claim_state(conn, owner_id, keys, live_owners):
3465
+ """What the stored sessions have counted of the requests in `keys`.
3466
+
3467
+ A request Claude Code copied into a resumed or forked session's transcript
3468
+ is the same API call, and a streamed reply can be longer in one copy than
3469
+ in another. Sessions therefore share a request's largest usage between
3470
+ them (see `_net_of_counted`). Returns (others, own): the summed shares of
3471
+ the other sessions, and this session's own earlier share. A share held by a
3472
+ session that no longer has a row is ignored, so usage is never dropped on
3473
+ the strength of a claim nobody holds.
3474
+ """
3475
+ _measure_facade = _compat.facade()
3476
+ me = _measure_facade._stable_hash63(owner_id)
3477
+ by_hash = {}
3478
+ for key in keys:
3479
+ base = _measure_facade._request_base_key(key)
3480
+ if base is not None:
3481
+ by_hash[_measure_facade._stable_hash63(base)] = base
3482
+ others, own = {}, {}
3483
+ hashes = list(by_hash)
3484
+ for i in range(0, len(hashes), 500):
3485
+ batch = hashes[i:i + 500]
3486
+ try:
3487
+ rows = conn.execute(
3488
+ "SELECT request_hash, owner_hash, calls, inp, out, cr, cc, cc_1h, cc_5m, model, day "
3489
+ "FROM usage_request_claims WHERE request_hash IN (%s)" % ",".join("?" * len(batch)),
3490
+ batch).fetchall()
3491
+ except _measure_facade.sqlite3.Error:
3492
+ return {}, {}
3493
+ for request_hash, owner_hash, calls, *fields in rows:
3494
+ if owner_hash == me:
3495
+ target = own
3496
+ elif owner_hash in live_owners:
3497
+ target = others
3498
+ else:
3499
+ continue
3500
+ share = target.setdefault(by_hash[request_hash], _measure_facade._empty_share())
3501
+ share["n"] += int(calls or 0)
3502
+ for name, value in zip(_measure_facade._SHARE_FIELDS, fields[:len(_measure_facade._SHARE_FIELDS)]):
3503
+ share[name] += int(value or 0)
3504
+ if target is own:
3505
+ share["model"], share["day"] = fields[len(_measure_facade._SHARE_FIELDS)], fields[len(_measure_facade._SHARE_FIELDS) + 1]
3506
+ return others, own
3507
+
3508
+
3509
+ def _net_of_counted(requests, counted, own=None):
3510
+ """The part of each request this session adds on top of what is already
3511
+ counted: per field, its own figure minus the others' total, never below 0.
3512
+ A share this session recorded earlier is kept, so collecting it again
3513
+ cannot shrink it, whether the transcript is collected for an unrelated
3514
+ reason or has lost part of the reply. The shares of every session sum to
3515
+ the largest figure any copy holds, whichever session is collected first or
3516
+ collected again later. An entry the others already cover completely comes
3517
+ back empty (`n` 0, all fields 0)."""
3518
+ _measure_facade = _compat.facade()
3519
+ own = own or {}
3520
+ net = {}
3521
+ for key, u in requests.items():
3522
+ base = _measure_facade._request_base_key(key)
3523
+ share = counted.get(base) if base is not None else None
3524
+ prior = own.get(base) if base is not None else None
3525
+ entry = dict(u)
3526
+ if share or prior:
3527
+ prior = prior or {}
3528
+ for name in _measure_facade._SHARE_FIELDS:
3529
+ raw = int(u.get(name) or 0)
3530
+ entry[name] = max(int(prior.get(name) or 0), raw - (share[name] if share else 0), 0)
3531
+ entry["n"] = max(int(prior.get("n") or 0), 0 if (share and share["n"] >= 1) else 1)
3532
+ if prior:
3533
+ # What was recorded about the request (its day and model) stands;
3534
+ # a later observation only fills what was missing.
3535
+ entry["day"] = prior.get("day") or u.get("day")
3536
+ recorded = prior.get("model")
3537
+ entry["model"] = (recorded if recorded and recorded != "unknown"
3538
+ and not str(recorded).startswith("<")
3539
+ else (u.get("model") or recorded))
3540
+ else:
3541
+ entry["n"] = 1
3542
+ net[key] = entry
3543
+ return net
3544
+
3545
+
3546
+ def _retained_requests(conn, owner_id, keys):
3547
+ """The session's recorded shares of requests its transcripts no longer hold.
3548
+
3549
+ Transcripts rotate and copies get removed. What a session was already
3550
+ credited for stays in its totals; the requests still in the files are
3551
+ counted next to it. Shares come back as request entries (keyed so they are
3552
+ never treated as shareable) carrying the model and day they were billed to.
3553
+ """
3554
+ _measure_facade = _compat.facade()
3555
+ present = {_measure_facade._stable_hash63(b) for b in (_measure_facade._request_base_key(k) for k in keys) if b is not None}
3556
+ try:
3557
+ rows = conn.execute(
3558
+ "SELECT request_hash, calls, inp, out, cr, cc, cc_1h, cc_5m, model, day "
3559
+ "FROM usage_request_claims WHERE owner_hash = ?", (_measure_facade._stable_hash63(owner_id),)).fetchall()
3560
+ except _measure_facade.sqlite3.Error:
3561
+ return {}
3562
+ kept = {}
3563
+ for request_hash, calls, *fields, model, day in rows:
3564
+ if request_hash in present or not (calls or any(fields)):
3565
+ continue
3566
+ entry = dict(zip(_measure_facade._SHARE_FIELDS, (int(v or 0) for v in fields)))
3567
+ entry.update(n=int(calls or 0), model=model or "unknown", day=day)
3568
+ kept[f"__noreq__kept:{request_hash}"] = entry
3569
+ return kept
3570
+
3571
+
3572
+ def _claim_requests(conn, owner_id, net_requests):
3573
+ """Record this session's share of each request (as returned by `_net_of_counted`)."""
3574
+ _measure_facade = _compat.facade()
3575
+ me = _measure_facade._stable_hash63(owner_id)
3576
+ rows = {}
3577
+ for key, u in net_requests.items():
3578
+ base = _measure_facade._request_base_key(key)
3579
+ if base is None:
3580
+ continue
3581
+ calls = 0 if u.get("advisor") else int(u.get("n", 1) or 0)
3582
+ rows[_measure_facade._stable_hash63(base)] = (
3583
+ _measure_facade._stable_hash63(base), me, calls,
3584
+ *(int(u.get(name) or 0) for name in _measure_facade._SHARE_FIELDS), u.get("model"), u.get("day"))
3585
+ if not rows:
3586
+ return
3587
+ try:
3588
+ conn.executemany(
3589
+ "INSERT OR REPLACE INTO usage_request_claims "
3590
+ "(request_hash, owner_hash, calls, inp, out, cr, cc, cc_1h, cc_5m, model, day) "
3591
+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", list(rows.values()))
3592
+ except _measure_facade.sqlite3.Error:
3593
+ pass
3594
+
3595
+
3596
+ def _net_and_record(requests, ledger):
3597
+ """In-memory form of the claims for a pass over several transcripts: returns
3598
+ the net usage of `requests` against `ledger`, plus the shares counted before
3599
+ this call (empty when nothing overlapped), and adds the net to the ledger."""
3600
+ _measure_facade = _compat.facade()
3601
+ counted = {}
3602
+ for key in requests:
3603
+ base = _measure_facade._request_base_key(key)
3604
+ if base is not None and base in ledger:
3605
+ counted[base] = dict(ledger[base])
3606
+ net = _measure_facade._net_of_counted(requests, counted)
3607
+ for key, u in net.items():
3608
+ base = _measure_facade._request_base_key(key)
3609
+ if base is None:
3610
+ continue
3611
+ share = ledger.setdefault(base, _measure_facade._empty_share())
3612
+ share["n"] += int(u.get("n", 1) or 0)
3613
+ for name in _measure_facade._SHARE_FIELDS:
3614
+ share[name] += int(u.get(name) or 0)
3615
+ return net, counted
3616
+
3617
+
3618
+ def _parsed_with_requests(parsed, requests):
3619
+ """A copy of a parsed transcript restated from the given per-request usage,
3620
+ every usage-derived figure recomputed. `parsed` itself is never modified."""
3621
+ _measure_facade = _compat.facade()
3622
+ agg, _days = _measure_facade._aggregate_request_usage(requests)
3623
+ full_input = agg["total_input"] + agg["total_cache_read"] + agg["total_cache_create"]
3624
+ out = dict(parsed)
3625
+ out.update({
3626
+ "total_input_tokens": full_input,
3627
+ "total_output_tokens": agg["total_output"],
3628
+ "total_cache_read": agg["total_cache_read"],
3629
+ "total_cache_create": agg["total_cache_create"],
3630
+ "total_cache_create_1h": agg["total_cache_create_1h"],
3631
+ "total_cache_create_5m": agg["total_cache_create_5m"],
3632
+ "cache_hit_rate": (agg["total_cache_read"] / full_input) if full_input > 0 else 0.0,
3633
+ "model_usage": agg["model_usage"],
3634
+ "model_usage_breakdown": agg["model_usage_breakdown"],
3635
+ "daily_usage": _measure_facade._daily_usage_from_merged(requests),
3636
+ "api_calls": agg["api_calls"],
3637
+ "request_usage": requests,
3638
+ })
3639
+ return out
3640
+
3641
+
3642
+ def _parsed_net_of_counted(parsed, counted, own=None):
3643
+ """`parsed` restated without what other sessions already counted of its requests."""
3644
+ _measure_facade = _compat.facade()
3645
+ requests = (parsed or {}).get("request_usage")
3646
+ if not requests or not (counted or own):
3647
+ return parsed
3648
+ return _measure_facade._parsed_with_requests(parsed, _measure_facade._net_of_counted(requests, counted, own))
3649
+
3650
+
3651
+ def _parsed_net_of_ledger(parsed, ledger):
3652
+ """`parsed` net of the requests earlier transcripts in a multi-file pass
3653
+ already counted; this file's requests are then added to `ledger`. Files
3654
+ without per-request detail pass through. The pass-wide total is the largest
3655
+ usage of each request, whatever the order of the files."""
3656
+ _measure_facade = _compat.facade()
3657
+ requests = (parsed or {}).get("request_usage")
3658
+ if not requests:
3659
+ return parsed
3660
+ net, counted = _measure_facade._net_and_record(requests, ledger)
3661
+ if not counted:
3662
+ return parsed
3663
+ return _measure_facade._parsed_with_requests(parsed, net)
3664
+
3665
+
3666
+ def _stale_usage_row_paths(conn):
3667
+ """Transcript paths of stored rows written before the current usage
3668
+ attribution. Collect re-parses them from their transcript, so a row that
3669
+ over-counted repeated requests corrects itself; a row whose transcript is
3670
+ gone is never visited and keeps its stored numbers."""
3671
+ _measure_facade = _compat.facade()
3672
+ try:
3673
+ return {str(r[0]) for r in conn.execute(
3674
+ "SELECT jsonl_path FROM session_log WHERE jsonl_path IS NOT NULL "
3675
+ "AND (usage_parser_version IS NULL OR usage_parser_version < ?)",
3676
+ (_measure_facade._USAGE_PARSER_VERSION,))}
3677
+ except _measure_facade.sqlite3.Error:
3678
+ return set()
3679
+
3680
+
3681
+ def _stamp_usage_parser_version(conn, filepath):
3682
+ """Mark a row as current when a re-parse has nothing to change, so it is not
3683
+ re-parsed on every collect."""
3684
+ _measure_facade = _compat.facade()
3685
+ try:
3686
+ conn.execute(
3687
+ "UPDATE session_log SET usage_parser_version = ? WHERE jsonl_path = ?",
3688
+ (_measure_facade._USAGE_PARSER_VERSION, str(filepath)))
3689
+ except _measure_facade.sqlite3.Error:
3690
+ pass
3691
+
3692
+
3693
+ def _daily_usage_from_merged(merged):
3694
+ """Per-day, per-model token buckets of a merged request set."""
3695
+ _measure_facade = _compat.facade()
3696
+ combined = {}
3697
+ for u in merged.values():
3698
+ if _measure_facade._net_request_is_empty(u):
3699
+ continue
3700
+ # Keep unknown activity visible for the coverage disclosure.
3701
+ day = u.get("day") or _measure_facade.UNDATED_USAGE_KEY
3702
+ bucket = combined.setdefault(day, {}).setdefault(
3703
+ u.get("model") or "unknown", _measure_facade._empty_model_buckets())
3704
+ bucket["fresh_input"] += int(u.get("inp") or 0)
3705
+ bucket["cache_read"] += int(u.get("cr") or 0)
3706
+ bucket["cache_create"] += int(u.get("cc") or 0)
3707
+ bucket["cache_create_1h"] += int(u.get("cc_1h") or 0)
3708
+ bucket["cache_create_5m"] += int(u.get("cc_5m") or 0)
3709
+ bucket["output"] += int(u.get("out") or 0)
3710
+ return combined
3711
+
3712
+
3713
+ def _session_daily_metrics(parsed, subagent_files):
3714
+ _measure_facade = _compat.facade()
3715
+ metrics = _measure_facade.copy.deepcopy(parsed.get("daily_metrics") or {})
3716
+ for path in subagent_files:
3717
+ child = _measure_facade._parse_session_jsonl(path) or {}
3718
+ for day, values in (child.get("daily_metrics") or {}).items():
3719
+ target = metrics.setdefault(day, {"message_count": 0, "duration_minutes": 0,
3720
+ "skills": {}, "subagents": {}, "tool_calls": {}})
3721
+ for name in ("skills", "subagents"):
3722
+ for key, count in values.get(name, {}).items():
3723
+ target.setdefault(name, {})[key] = target.get(name, {}).get(key, 0) + count
3724
+ return metrics
3725
+
3726
+
3727
+ def _session_daily_usage(filepath, parsed=None, subagent_files=None, conn=None, live_owners=None):
3728
+ """Daily usage for a session transcript plus all of its subagent transcripts.
3729
+
3730
+ Claude Code sometimes writes the same API request into more than one of a
3731
+ session's files (the parent and a subagent, or two subagents). Requests are
3732
+ therefore merged by request id across every file first, keeping the largest
3733
+ usage seen (streaming-safe), so a shared request is billed once. With a
3734
+ database connection, what another stored session already counts of a request
3735
+ is left out as well.
3736
+ """
3737
+ _measure_facade = _compat.facade()
3738
+ parsed = parsed if parsed is not None else _measure_facade._parse_session_jsonl(filepath)
3739
+ if subagent_files is None:
3740
+ subagent_files = _measure_facade._session_subagent_files(filepath)
3741
+ merged = _measure_facade._session_merged_requests(filepath, parsed, subagent_files)
3742
+ if merged is None:
3743
+ # Adapter output without per-request detail: sum the per-file buckets.
3744
+ combined = {}
3745
+ for p in [parsed] + [_measure_facade._parse_session_jsonl(sub_jf) for sub_jf in subagent_files]:
3746
+ _measure_facade._merge_daily_usage(combined, (p or {}).get("daily_usage") or {})
3747
+ return combined
3748
+ if conn is not None:
3749
+ if live_owners is None:
3750
+ live_owners = _measure_facade._live_usage_owners(conn)
3751
+ owner_id = _measure_facade._usage_owner_id(filepath)
3752
+ counted, own = _measure_facade._claim_state(conn, owner_id, merged, live_owners)
3753
+ if counted or own:
3754
+ merged = _measure_facade._net_of_counted(merged, counted, own)
3755
+ if _measure_facade._stable_hash63(owner_id) in live_owners:
3756
+ merged = {**merged, **_measure_facade._retained_requests(conn, owner_id, merged)}
3757
+ return _measure_facade._daily_usage_from_merged(merged)
3758
+
3759
+
3760
+ def _session_activity_evidence(filepath, parsed=None, subagent_files=None, conn=None, live_owners=None):
3761
+ """Every dated per-day field collect would store for one transcript.
3762
+
3763
+ Returns {"daily_usage", "parent_usage", "calls", "metrics", "bounds"} or
3764
+ None when the transcript cannot be parsed. `daily_usage` is the combined
3765
+ parent+delegated map deduplicated by request id; `parent_usage` is the
3766
+ parent file's own buckets after the same claim netting collect applies, so
3767
+ a backfilled row carries the same provenance a fresh collect would write.
3768
+ `bounds` is the sorted union of combined, parent and metadata days, matching
3769
+ the collector's first/last activity derivation.
3770
+ """
3771
+ _measure_facade = _compat.facade()
3772
+ parsed = parsed if parsed is not None else _measure_facade._parse_session_jsonl(filepath)
3773
+ if parsed is None:
3774
+ return None
3775
+ if subagent_files is None:
3776
+ subagent_files = _measure_facade._session_subagent_files(filepath)
3777
+ metrics = _measure_facade._session_daily_metrics(parsed, subagent_files)
3778
+ merged = _measure_facade._session_merged_requests(filepath, parsed, subagent_files)
3779
+ parent_parsed = parsed
3780
+ if merged is None:
3781
+ # Adapter output without per-request detail: sum the per-file buckets.
3782
+ daily_usage = {}
3783
+ for p in [parsed] + [_measure_facade._parse_session_jsonl(sub_jf) for sub_jf in subagent_files]:
3784
+ _measure_facade._merge_daily_usage(daily_usage, (p or {}).get("daily_usage") or {})
3785
+ call_requests = parsed.get("request_usage") or {}
3786
+ else:
3787
+ net_merged = merged
3788
+ call_requests = merged
3789
+ if conn is not None:
3790
+ if live_owners is None:
3791
+ live_owners = _measure_facade._live_usage_owners(conn)
3792
+ owner_id = _measure_facade._usage_owner_id(filepath)
3793
+ counted, own = _measure_facade._claim_state(conn, owner_id, merged, live_owners)
3794
+ if counted or own:
3795
+ net_merged = _measure_facade._net_of_counted(merged, counted, own)
3796
+ parent_parsed = _measure_facade._parsed_net_of_counted(parsed, counted, own)
3797
+ if _measure_facade._stable_hash63(owner_id) in live_owners:
3798
+ retained = _measure_facade._retained_requests(conn, owner_id, merged)
3799
+ if retained:
3800
+ net_merged = {**net_merged, **retained}
3801
+ parent_parsed = _measure_facade._parsed_with_requests(
3802
+ parent_parsed,
3803
+ {**(parent_parsed.get("request_usage") or {}), **retained})
3804
+ daily_usage = _measure_facade._daily_usage_from_merged(net_merged)
3805
+ call_requests = net_merged
3806
+ calls = dict(parent_parsed.get("daily_calls") or {})
3807
+ for u in call_requests.values():
3808
+ if not u.get("advisor") and u.get("n", 1) and u.get("day"):
3809
+ day = u["day"]
3810
+ calls[day] = calls.get(day, 0) + 1
3811
+ bounds = _measure_facade._activity_bounds(daily_usage, parent_parsed.get("daily_usage"), metrics)
3812
+ return {"daily_usage": daily_usage,
3813
+ "parent_usage": parent_parsed.get("daily_usage") or {},
3814
+ "calls": calls, "metrics": metrics, "bounds": bounds}
3815
+
3816
+
3817
+ def _session_rank(message_count, input_tokens, output_tokens):
3818
+ """How complete a copy of a session is. Copies are prefixes of the live file,
3819
+ so the larger one is the superset. Shared by both dedupe paths so they always
3820
+ pick the same winner."""
3821
+ _measure_facade = _compat.facade()
3822
+ return (int(message_count or 0), int(input_tokens or 0), int(output_tokens or 0))
3823
+
3824
+
3825
+ def _session_dir_index(projects_dir):
3826
+ """Map session stem -> project dirs holding a copy of that session (its
3827
+ transcript, its folder of subagents, or both).
3828
+
3829
+ One directory listing per project, cached for a minute, so looking up a
3830
+ session's copies elsewhere costs a dict hit instead of a stat of every
3831
+ project dir for every session (1.6M stats on a large history).
3832
+ """
3833
+ _measure_facade = _compat.facade()
3834
+ key = str(projects_dir)
3835
+ now = _measure_facade.time.monotonic()
3836
+ cached = _measure_facade._SESSION_DIR_INDEX.get(key)
3837
+ if cached and now - cached[0] < _measure_facade._SESSION_DIR_INDEX_TTL:
3838
+ return cached[1]
3839
+ index = {}
3840
+ try:
3841
+ projects = [e for e in _measure_facade.os.scandir(projects_dir) if e.is_dir()]
3842
+ except OSError:
3843
+ projects = []
3844
+ for proj in projects:
3845
+ try:
3846
+ with _measure_facade.os.scandir(proj.path) as entries:
3847
+ found = set()
3848
+ for e in entries:
3849
+ name = e.name[:-6] if e.name.endswith(".jsonl") else e.name
3850
+ if name not in found and _measure_facade._canonical_session_uuid(name):
3851
+ found.add(name)
3852
+ index.setdefault(name, []).append(_measure_facade.Path(proj.path))
3853
+ except OSError:
3854
+ continue
3855
+ _measure_facade._SESSION_DIR_INDEX.clear()
3856
+ _measure_facade._SESSION_DIR_INDEX[key] = (now, index)
3857
+ return index
3858
+
3859
+
3860
+ def _session_copy_files(filepath):
3861
+ """Other transcripts of the same session under sibling project dirs
3862
+ (worktree dir, sandboxed-config mirror, synced folder)."""
3863
+ _measure_facade = _compat.facade()
3864
+ filepath = _measure_facade.Path(filepath)
3865
+ projects_dir = filepath.parent.parent
3866
+ if not (_measure_facade._canonical_session_uuid(filepath) and projects_dir.name == "projects"):
3867
+ return []
3868
+ copies = []
3869
+ for sib in _measure_facade._session_dir_index(projects_dir).get(filepath.stem, ()):
3870
+ copy_path = sib / filepath.name
3871
+ if sib != filepath.parent and copy_path.is_file():
3872
+ copies.append(copy_path)
3873
+ return copies
3874
+
3875
+
3876
+ def _session_subagent_files(filepath):
3877
+ """Subagent transcripts for a session across every copy of it.
3878
+
3879
+ A session resumed in a git worktree keeps writing subagents under that
3880
+ worktree's project dir, so after deduping to one row the winner must still
3881
+ see the other copies' subagents. Requests are merged by requestId
3882
+ downstream, so a subagent file present in two copies is never billed twice.
3883
+ """
3884
+ _measure_facade = _compat.facade()
3885
+ filepath = _measure_facade.Path(filepath)
3886
+ files = list(_measure_facade._find_subagent_jsonl_files(filepath))
3887
+ seen = {f.name for f in files}
3888
+ projects_dir = filepath.parent.parent
3889
+ if _measure_facade._canonical_session_uuid(filepath) and projects_dir.name == "projects":
3890
+ siblings = [d for d in _measure_facade._session_dir_index(projects_dir).get(filepath.stem, ()) if d != filepath.parent]
3891
+ for sib in siblings:
3892
+ sub_dir = sib / filepath.stem / "subagents"
3893
+ if not sub_dir.is_dir():
3894
+ continue
3895
+ for jf in sub_dir.glob("*.jsonl"):
3896
+ try:
3897
+ if jf.name not in seen and jf.stat().st_size > 0:
3898
+ files.append(jf)
3899
+ seen.add(jf.name)
3900
+ except OSError:
3901
+ continue
3902
+ return files
3903
+
3904
+
3905
+ def _canonical_session_uuid(filepath):
3906
+ """Session UUID for a transcript path, or None when the stem is not one."""
3907
+ _measure_facade = _compat.facade()
3908
+ try:
3909
+ return _measure_facade._extract_session_uuid(_measure_facade.Path(filepath).stem)[0]
3910
+ except Exception:
3911
+ return None
3912
+
3913
+
3914
+ def _dedupe_session_rows(conn):
3915
+ """Collapse session_log rows that are copies of the same session (#200).
3916
+
3917
+ session_log is keyed by jsonl_path, but one session can sit under several
3918
+ paths: a git-worktree project dir, a mirror under a sandboxed
3919
+ CLAUDE_CONFIG_DIR, a resumed copy. Each copy used to count as its own
3920
+ session, inflating every total 2-3x. Keep the most complete row per
3921
+ session_uuid (a copy is a prefix of the live file, so the larger one is the
3922
+ superset). Rows are derived from transcripts on disk, so nothing is lost.
3923
+ """
3924
+ _measure_facade = _compat.facade()
3925
+ try:
3926
+ rows = conn.execute(
3927
+ """SELECT id, session_uuid, message_count, input_tokens, output_tokens, jsonl_path, collected_at
3928
+ FROM session_log
3929
+ WHERE session_uuid IN (
3930
+ SELECT session_uuid FROM session_log
3931
+ WHERE session_uuid IS NOT NULL AND session_uuid != ''
3932
+ GROUP BY session_uuid HAVING COUNT(*) > 1)"""
3933
+ ).fetchall()
3934
+ except _measure_facade.sqlite3.Error:
3935
+ return 0
3936
+ best = {}
3937
+ for rid, uuid, msgs, inp, out, path, _collected in rows:
3938
+ if _measure_facade._extract_session_uuid(uuid or "")[0] is None:
3939
+ continue
3940
+ on_disk = bool(path) and _measure_facade.os.path.exists(path)
3941
+ # Most complete copy wins; on a tie, the one whose transcript still
3942
+ # exists (its per-day data can be rebuilt), then the newest row.
3943
+ rank = (*_measure_facade._session_rank(msgs, inp, out), on_disk, int(rid))
3944
+ if uuid not in best or rank > best[uuid][0]:
3945
+ best[uuid] = (rank, rid, on_disk)
3946
+ losers = [
3947
+ (rid,) for rid, uuid, *_ in rows
3948
+ if uuid in best and rid != best[uuid][1]
3949
+ ]
3950
+ if not losers:
3951
+ return 0
3952
+ # Recompute the winner's per-day data so it includes the losers' subagents
3953
+ # (_session_subagent_files) -- only when its transcript can be re-read.
3954
+ winners = [(b[1],) for b in best.values() if b[2]]
3955
+ loser_ids = {rid for (rid,) in losers}
3956
+ aliases = [(path, uuid, collected) for rid, uuid, _m, _i, _o, path, collected in rows if rid in loser_ids]
3957
+ try:
3958
+ conn.executemany(
3959
+ "INSERT OR REPLACE INTO session_log_aliases (jsonl_path, session_uuid, collected_at) VALUES (?, ?, ?)",
3960
+ aliases)
3961
+ conn.executemany("DELETE FROM session_log WHERE id = ?", losers)
3962
+ conn.executemany("UPDATE session_log SET daily_usage_json = NULL WHERE id = ?", winners)
3963
+ except _measure_facade.sqlite3.Error:
3964
+ return 0
3965
+ return len(losers)
3966
+
3967
+
3968
+ def _collect_drain_mode():
3969
+ """"full" inside the detached upgrade drain, "inline" for a user-run
3970
+ collect, None on the hook path (and under pytest, where a test opts in by
3971
+ patching this function)."""
3972
+ _measure_facade = _compat.facade()
3973
+ if _measure_facade.os.environ.get("TOKEN_OPTIMIZER_UPGRADE_DRAIN", "").strip() == "1":
3974
+ return "full"
3975
+ if _measure_facade.os.environ.get("PYTEST_CURRENT_TEST"):
3976
+ return None
3977
+ try:
3978
+ return None if _measure_facade._running_under_hook() else "inline"
3979
+ except Exception:
3980
+ return None
3981
+
3982
+
3983
+ def _upgrade_drain_key():
3984
+ """One drain per counted-pricing version and usage-parser version."""
3985
+ _measure_facade = _compat.facade()
3986
+ return f"counted{_measure_facade._COUNTED_PRICING_VERSION}-usage{_measure_facade._USAGE_PARSER_VERSION}"
3987
+
3988
+
3989
+ def _upgrade_meta_get(conn, key):
3990
+ _measure_facade = _compat.facade()
3991
+ try:
3992
+ conn.execute("CREATE TABLE IF NOT EXISTS token_optimizer_meta "
3993
+ "(key TEXT PRIMARY KEY, value TEXT)")
3994
+ row = conn.execute("SELECT value FROM token_optimizer_meta WHERE key = ?", (key,)).fetchone()
3995
+ return row[0] if row else None
3996
+ except _measure_facade.sqlite3.Error:
3997
+ return None
3998
+
3999
+
4000
+ def _upgrade_meta_set(conn, key, value):
4001
+ _measure_facade = _compat.facade()
4002
+ try:
4003
+ conn.execute("CREATE TABLE IF NOT EXISTS token_optimizer_meta "
4004
+ "(key TEXT PRIMARY KEY, value TEXT)")
4005
+ conn.execute("INSERT OR REPLACE INTO token_optimizer_meta (key, value) VALUES (?, ?)",
4006
+ (key, str(value)))
4007
+ conn.commit()
4008
+ except _measure_facade.sqlite3.Error:
4009
+ pass
4010
+
4011
+
4012
+ def _upgrade_drain_mark_done(conn):
4013
+ _measure_facade = _compat.facade()
4014
+ _measure_facade._upgrade_meta_set(conn, _measure_facade._UPGRADE_DRAIN_META, _measure_facade._upgrade_drain_key())
4015
+
4016
+
4017
+ def _upgrade_drain_after_pass(conn, backlog):
4018
+ """After a bounded collect pass: once per version, hand any re-scoring
4019
+ backlog to a detached drain. A pass with no backlog records the version as
4020
+ drained. Returns True when a drain child was started. Never raises."""
4021
+ _measure_facade = _compat.facade()
4022
+ try:
4023
+ key = _measure_facade._upgrade_drain_key()
4024
+ if _measure_facade._upgrade_meta_get(conn, _measure_facade._UPGRADE_DRAIN_META) == key:
4025
+ return False
4026
+ if not backlog:
4027
+ _measure_facade._upgrade_drain_mark_done(conn)
4028
+ return False
4029
+ # Under pytest the child would run against the real ~/.claude.
4030
+ if _measure_facade.os.environ.get("PYTEST_CURRENT_TEST") and not _measure_facade.os.environ.get(
4031
+ "TOKEN_OPTIMIZER_TEST_ALLOW_DRAIN_SPAWN"):
4032
+ return False
4033
+ raw = _measure_facade._upgrade_meta_get(conn, _measure_facade._UPGRADE_DRAIN_ATTEMPTS_META) or ""
4034
+ attempts = int(raw.split(":", 1)[1]) if raw.startswith(key + ":") else 0
4035
+ if attempts >= _measure_facade._UPGRADE_DRAIN_MAX_ATTEMPTS:
4036
+ return False
4037
+ if not _measure_facade._upgrade_drain_claim_lock():
4038
+ return False
4039
+ if _measure_facade._spawn_upgrade_drain():
4040
+ _measure_facade._upgrade_meta_set(conn, _measure_facade._UPGRADE_DRAIN_ATTEMPTS_META, f"{key}:{attempts + 1}")
4041
+ return True
4042
+ _measure_facade._upgrade_drain_release_lock()
4043
+ return False
4044
+ except Exception:
4045
+ return False
4046
+
4047
+
4048
+ def _upgrade_drain_claim_lock():
4049
+ """Claim the drain lock file (O_EXCL); reclaim one left by a dead child."""
4050
+ _measure_facade = _compat.facade()
4051
+ marker = _measure_facade.SNAPSHOT_DIR / _measure_facade._UPGRADE_DRAIN_LOCK_NAME
4052
+ try:
4053
+ _measure_facade.SNAPSHOT_DIR.mkdir(parents=True, exist_ok=True)
4054
+ try:
4055
+ fd = _measure_facade.os.open(str(marker), _measure_facade.os.O_CREAT | _measure_facade.os.O_EXCL | _measure_facade.os.O_WRONLY, 0o600)
4056
+ except FileExistsError:
4057
+ if _measure_facade.time.time() - marker.stat().st_mtime <= _measure_facade._UPGRADE_DRAIN_LOCK_STALE_SECONDS:
4058
+ return False
4059
+ _measure_facade.os.unlink(str(marker))
4060
+ fd = _measure_facade.os.open(str(marker), _measure_facade.os.O_CREAT | _measure_facade.os.O_EXCL | _measure_facade.os.O_WRONLY, 0o600)
4061
+ with _measure_facade.os.fdopen(fd, "w") as handle:
4062
+ handle.write(str(_measure_facade.os.getpid()))
4063
+ return True
4064
+ except OSError:
4065
+ return False
4066
+
4067
+
4068
+ def _upgrade_drain_release_lock():
4069
+ _measure_facade = _compat.facade()
4070
+ try:
4071
+ (_measure_facade.SNAPSHOT_DIR / _measure_facade._UPGRADE_DRAIN_LOCK_NAME).unlink()
4072
+ except OSError:
4073
+ pass
4074
+
4075
+
4076
+ def _spawn_upgrade_drain():
4077
+ """Start `measure.py upgrade-drain` fully detached (POSIX new session,
4078
+ Windows DETACHED_PROCESS with no console window). Never raises."""
4079
+ _measure_facade = _compat.facade()
4080
+ try:
4081
+ env = dict(_measure_facade.os.environ)
4082
+ env["TOKEN_OPTIMIZER_UPGRADE_DRAIN"] = "1"
4083
+ env["TOKEN_OPTIMIZER_INTERACTIVE"] = "1"
4084
+ env.pop("TOKEN_OPTIMIZER_HOOK", None)
4085
+ popen_kw = {} if _measure_facade.os.name == "nt" else {"start_new_session": True}
4086
+ child = _measure_facade.subprocess.Popen(
4087
+ [_measure_facade.sys.executable, _measure_facade.os.path.abspath(_measure_facade.__file__), "upgrade-drain", "--quiet"],
4088
+ stdin=_measure_facade.subprocess.DEVNULL,
4089
+ stdout=_measure_facade.subprocess.DEVNULL,
4090
+ stderr=_measure_facade.subprocess.DEVNULL,
4091
+ close_fds=True,
4092
+ env=env,
4093
+ creationflags=(getattr(_measure_facade.subprocess, "DETACHED_PROCESS", 0) | _measure_facade._NO_WINDOW),
4094
+ **popen_kw,
4095
+ )
4096
+ try:
4097
+ (_measure_facade.SNAPSHOT_DIR / _measure_facade._UPGRADE_DRAIN_LOCK_NAME).write_text(str(child.pid))
4098
+ except OSError:
4099
+ pass
4100
+ return True
4101
+ except Exception as exc:
4102
+ try:
4103
+ _measure_facade._log_spawn_failure("upgrade drain spawn failed: %s: %s" % (type(exc).__name__, exc))
4104
+ except Exception:
4105
+ pass
4106
+ return False
4107
+
4108
+
4109
+ def _upgrade_drain_days():
4110
+ """Days the one-time drain re-reads: all history since install, so routing
4111
+ and the since-install total cover every month. At least the usual 90-day
4112
+ collect window; ten years when no install date is known."""
4113
+ _measure_facade = _compat.facade()
4114
+ try:
4115
+ d = _measure_facade._install_date()
4116
+ if d:
4117
+ return max(90, min(3650, (_measure_facade.datetime.now() - _measure_facade.datetime.fromisoformat(d)).days + 2))
4118
+ except Exception:
4119
+ pass
4120
+ return 3650
4121
+
4122
+
4123
+ def _run_upgrade_drain(days=None, quiet=None):
4124
+ """Body of `measure.py upgrade-drain`: one uncapped collect (usage re-parse,
4125
+ per-day usage, counted ledger and markers), then release the lock."""
4126
+ _measure_facade = _compat.facade()
4127
+ _measure_facade.os.environ["TOKEN_OPTIMIZER_UPGRADE_DRAIN"] = "1"
4128
+ try:
4129
+ return _measure_facade.collect_sessions(days=days or _measure_facade._upgrade_drain_days(), quiet=quiet)
4130
+ finally:
4131
+ _measure_facade._upgrade_drain_release_lock()
4132
+
4133
+
4134
+ def collect_sessions(days=None, quiet=None, rebuild=None):
4135
+ """Parse new JSONL files and insert into SQLite. Zero token cost.
4136
+
4137
+ Refreshes changed files in place. Safe to run repeatedly.
4138
+ With rebuild=True, drops and re-collects all data (e.g., after a
4139
+ measurement fix such as model attribution).
4140
+ """
4141
+ _measure_facade = _compat.facade()
4142
+ if _measure_facade._use_hermes_session_adapter():
4143
+ return _measure_facade._collect_hermes_sessions(days=days, quiet=quiet, rebuild=rebuild)
4144
+
4145
+ if _measure_facade._use_copilot_session_adapter():
4146
+ return _measure_facade._collect_copilot_sessions(days=days, quiet=quiet, rebuild=rebuild)
4147
+
4148
+ if _measure_facade._use_cursor_session_adapter():
4149
+ return _measure_facade._collect_cursor_sessions(days=days, quiet=quiet, rebuild=rebuild)
4150
+
4151
+ if _measure_facade._use_antigravity_session_adapter():
4152
+ return _measure_facade._collect_antigravity_sessions(days=days, quiet=quiet, rebuild=rebuild)
4153
+
4154
+ if _measure_facade._use_grok_session_adapter():
4155
+ return _measure_facade._collect_grok_sessions(days=days, quiet=quiet, rebuild=rebuild)
4156
+
4157
+ conn = _measure_facade._init_trends_db()
4158
+ _session_log_has_origin = bool(_measure_facade._origin_insert_parts(conn, "session_log")[0])
4159
+ _session_log_has_usage_version = "usage_parser_version" in {
4160
+ r[1] for r in conn.execute("PRAGMA table_info(session_log)").fetchall()}
4161
+
4162
+ # Capture the existing comparison before refreshing historical session rows.
4163
+ # The user's baseline must not move as collection catches up.
4164
+ if not rebuild and not (_measure_facade.SNAPSHOT_DIR / "workload_anchor.json").exists():
4165
+ _measure_facade._session_weight_pool_savings(
4166
+ (_measure_facade.datetime.now() - _measure_facade.timedelta(days=30)).date().isoformat())
4167
+
4168
+ # One-time migration for the model attribution fix: wipe model_daily (safe, fast, no data loss)
4169
+ if _measure_facade._needs_model_daily_rebuild(conn):
4170
+ _measure_facade._migrate_model_daily(conn, quiet=quiet)
4171
+
4172
+ # v5.4.9 one-time migration: streaming-dedup + subagent roll-up changed
4173
+ # how output_tokens and model_usage are computed. Pre-v5.4.9 data is wrong.
4174
+ # Wipe everything so the loop below re-parses all JSONL files with the
4175
+ # corrected logic. This makes `rebuild=True` implicit on first v5.4.9 run.
4176
+ if _measure_facade._needs_streaming_dedup_rebuild(conn):
4177
+ _measure_facade._migrate_streaming_dedup(conn, quiet=quiet)
4178
+ rebuild = True # force re-parse of all sessions
4179
+
4180
+ if rebuild:
4181
+ if not quiet:
4182
+ print("[Token Optimizer] Rebuilding trends DB (re-parsing all sessions)...")
4183
+ # Mark version FIRST so a killed process doesn't re-trigger
4184
+ conn.execute("PRAGMA user_version = 3")
4185
+ conn.execute("DELETE FROM session_log")
4186
+ conn.execute("DELETE FROM session_log_aliases")
4187
+ conn.execute("DELETE FROM usage_request_claims")
4188
+ conn.execute("DELETE FROM daily_stats")
4189
+ conn.execute("DELETE FROM model_daily")
4190
+ conn.execute("DELETE FROM skill_daily")
4191
+ conn.execute("DELETE FROM subagent_daily")
4192
+ # Drop event tables too: their session_id/session_uuid references would
4193
+ # otherwise dangle (no FK constraints) and silently inflate savings.
4194
+ conn.execute("DELETE FROM savings_events")
4195
+ conn.execute("DELETE FROM compression_events")
4196
+ conn.execute("DELETE FROM counted_reread")
4197
+ conn.commit()
4198
+ files = _measure_facade._find_all_jsonl_files(None)
4199
+ if not files:
4200
+ if not quiet:
4201
+ print(f"No session logs found in the last {days} days.")
4202
+ conn.close()
4203
+ return 0
4204
+
4205
+ try:
4206
+ _measure_facade._dedupe_session_rows(conn)
4207
+ except _measure_facade.sqlite3.Error:
4208
+ pass
4209
+
4210
+ new_count = 0
4211
+ live_owners = _measure_facade._live_usage_owners(conn)
4212
+ stale_usage_rows = _measure_facade._stale_usage_row_paths(conn)
4213
+ drain = _measure_facade._collect_drain_mode()
4214
+ budgets = _measure_facade._COLLECT_DRAIN_BUDGETS.get(drain, _measure_facade._COLLECT_DRAIN_BUDGETS[None])
4215
+ parse_deadline = (_measure_facade.time.monotonic() + budgets["parse_seconds"]
4216
+ if budgets["parse_seconds"] is not None else None)
4217
+ commit_batch = budgets["commit_batch"] or _measure_facade._COLLECT_COMMIT_BATCH
4218
+ parse_truncated = False
4219
+ for filepath, mtime, project_name in files:
4220
+ if (_measure_facade._is_file_collected(conn, filepath, check_mtime=True)
4221
+ and str(filepath) not in stale_usage_rows):
4222
+ continue
4223
+
4224
+ # Bounded per-run collection: never parse more than _COLLECT_MAX_PER_RUN new
4225
+ # sessions in one flush. `files` is newest-first, so recent sessions are always
4226
+ # collected and any large backlog drains over subsequent flushes rather than
4227
+ # blocking turn-end. (rebuild re-collects everything, so it opts out.)
4228
+ # A drain run (see _collect_drain_mode) has no count cap; an inline drain
4229
+ # stops at its wall-clock budget instead.
4230
+ if (budgets["count_capped"] and _measure_facade._COLLECT_MAX_PER_RUN and not rebuild
4231
+ and new_count >= _measure_facade._COLLECT_MAX_PER_RUN):
4232
+ parse_truncated = True
4233
+ break
4234
+ if parse_deadline is not None and not rebuild and _measure_facade.time.monotonic() > parse_deadline:
4235
+ parse_truncated = True
4236
+ break
4237
+
4238
+ collection_started = _measure_facade.datetime.now().isoformat()
4239
+ # Rollups must not mutate the parser cache when only a child grows.
4240
+ parsed = _measure_facade.copy.deepcopy(_measure_facade._parse_session_jsonl(filepath))
4241
+ if not parsed:
4242
+ _measure_facade._stamp_usage_parser_version(conn, filepath)
4243
+ continue
4244
+ owner_id = _measure_facade._usage_owner_id(filepath)
4245
+
4246
+ # Scan subagent JSONL files for skills, agents, and model usage.
4247
+ # Single pass over subagent files to avoid duplicate glob. Includes
4248
+ # subagents stored under other copies of this session (worktrees).
4249
+ subagent_files = _measure_facade._session_subagent_files(filepath)
4250
+ # Keep parsed["daily_metrics"] parent-only: _session_daily_metrics merges
4251
+ # subagent days into a copy, and mutating the memoized parse result would
4252
+ # double-count subagent metrics on any later pass over the same file.
4253
+ session_daily_metrics = _measure_facade._session_daily_metrics(parsed, subagent_files)
4254
+ for sub_jf in subagent_files:
4255
+ sub_skills, sub_agents = _measure_facade._extract_skills_and_agents_from_subagent(sub_jf)
4256
+ for sk, cnt in sub_skills.items():
4257
+ parsed["skills_used"][sk] = parsed["skills_used"].get(sk, 0) + cnt
4258
+ for ag, cnt in sub_agents.items():
4259
+ parsed["subagents_used"][ag] = parsed["subagents_used"].get(ag, 0) + cnt
4260
+
4261
+ # a follow-up fix: Build combined model usage (parent + subagents) for
4262
+ # model_daily attribution. Kept SEPARATE from parsed["model_usage"]
4263
+ # which stays parent-only for: session_log storage, dom_model
4264
+ # selection, and cost calculations. Merging into model_usage would
4265
+ # flip dom_model to a cheaper subagent model, mispricing sessions.
4266
+ #
4267
+ # v5.4.9: ALSO aggregate subagent input/output/cache tokens into the
4268
+ # session-level totals so session_log.output_tokens (and the dashboard
4269
+ # "Billable Tokens" headline derived from it) captures work the main
4270
+ # thread delegated to agents. Without this, sessions that fan out
4271
+ # heavily via Task tool appeared to use ~0 tokens.
4272
+ all_model_usage = dict(parsed["model_usage"])
4273
+ for sub_jf in subagent_files:
4274
+ sub_parsed = _measure_facade._parse_session_jsonl(sub_jf)
4275
+ if not sub_parsed:
4276
+ continue
4277
+ # Aggregate model_usage (for model_daily)
4278
+ if sub_parsed.get("model_usage"):
4279
+ for model_id, tokens in sub_parsed["model_usage"].items():
4280
+ if model_id.startswith("<"): # skip synthetic IDs
4281
+ continue
4282
+ all_model_usage[model_id] = (
4283
+ all_model_usage.get(model_id, 0) + tokens
4284
+ )
4285
+ # v5.4.9: also roll subagent token totals up into session_log
4286
+ parsed["total_input_tokens"] = (parsed.get("total_input_tokens") or 0) + (sub_parsed.get("total_input_tokens") or 0)
4287
+ parsed["total_output_tokens"] = (parsed.get("total_output_tokens") or 0) + (sub_parsed.get("total_output_tokens") or 0)
4288
+ parsed["total_cache_create_1h"] = (parsed.get("total_cache_create_1h") or 0) + (sub_parsed.get("total_cache_create_1h") or 0)
4289
+ parsed["total_cache_create_5m"] = (parsed.get("total_cache_create_5m") or 0) + (sub_parsed.get("total_cache_create_5m") or 0)
4290
+ # Recompute cache_hit_rate over combined totals:
4291
+ # total_full_input already includes cache_read + cache_create per _parse_session_jsonl
4292
+ # but the stored cache_hit_rate is parent-only. Leave as-is (parent-derived)
4293
+ # since mixing subagent hit rates isn't meaningful for per-session display.
4294
+
4295
+ merged = _measure_facade._session_merged_requests(filepath, parsed, subagent_files)
4296
+ # What another stored session already counts of a request (a resumed or
4297
+ # forked transcript repeats its parent's history, and a copy can hold a
4298
+ # longer streamed reply) is left out of this one; this session adds only
4299
+ # the difference, so the sessions together hold each request's largest usage.
4300
+ counted, retained, own_shares = {}, {}, {}
4301
+ if merged is not None:
4302
+ if _measure_facade._stable_hash63(owner_id) in live_owners:
4303
+ retained = _measure_facade._retained_requests(conn, owner_id, merged)
4304
+ else:
4305
+ # Shares recorded by a session that has no row any more are not history.
4306
+ try:
4307
+ conn.execute("DELETE FROM usage_request_claims WHERE owner_hash = ?",
4308
+ (_measure_facade._stable_hash63(owner_id),))
4309
+ except _measure_facade.sqlite3.Error:
4310
+ pass
4311
+ counted, own_shares = _measure_facade._claim_state(conn, owner_id, merged, live_owners)
4312
+ if counted or own_shares:
4313
+ merged = _measure_facade._net_of_counted(merged, counted, own_shares)
4314
+ parsed = _measure_facade._parsed_net_of_counted(parsed, counted, own_shares)
4315
+ if retained:
4316
+ merged = {**merged, **retained}
4317
+ parsed = _measure_facade._parsed_with_requests(
4318
+ parsed, {**(parsed.get("request_usage") or {}), **retained})
4319
+ if merged is not None:
4320
+ daily_usage = _measure_facade._daily_usage_from_merged(merged)
4321
+ else:
4322
+ daily_usage = _measure_facade._session_daily_usage(filepath, parsed=parsed, subagent_files=subagent_files)
4323
+ if subagent_files or counted or retained or own_shares or _measure_facade._session_copy_files(filepath):
4324
+ # The per-file sums above count a request written into both the
4325
+ # parent and a subagent file twice; restate the stored token totals
4326
+ # from the same request-merged set the cost uses.
4327
+ if merged is not None:
4328
+ parsed["total_input_tokens"] = sum(int(u.get("inp") or 0) + int(u.get("cr") or 0) + int(u.get("cc") or 0)
4329
+ for u in merged.values())
4330
+ parsed["total_output_tokens"] = sum(int(u.get("out") or 0) for u in merged.values())
4331
+ parsed["total_cache_create_1h"] = sum(int(u.get("cc_1h") or 0) for u in merged.values())
4332
+ parsed["total_cache_create_5m"] = sum(int(u.get("cc_5m") or 0) for u in merged.values())
4333
+ all_model_usage = {}
4334
+ for u in merged.values():
4335
+ if _measure_facade._net_request_is_empty(u):
4336
+ continue
4337
+ model_id = u.get("model") or "unknown"
4338
+ if model_id.startswith("<"):
4339
+ continue
4340
+ all_model_usage[model_id] = all_model_usage.get(model_id, 0) + (
4341
+ int(u.get("inp") or 0) + int(u.get("cc") or 0) + int(u.get("out") or 0))
4342
+
4343
+ parent_daily = parsed.get("daily_usage") or {}
4344
+ activity_bounds = _measure_facade._activity_bounds(daily_usage, parent_daily, session_daily_metrics)
4345
+ date = activity_bounds[-1] if activity_bounds else ""
4346
+ skills_used = parsed["skills_used"]
4347
+ subagents_used = parsed["subagents_used"]
4348
+
4349
+ # One row per session (#200): if this session is already stored under
4350
+ # another path (worktree dir, sandboxed-config mirror), keep whichever
4351
+ # copy is more complete instead of counting the session twice.
4352
+ session_uuid = _measure_facade._canonical_session_uuid(filepath)
4353
+ # Origin of this row. A session first collected in a cloud VM keeps
4354
+ # 'cloud' when a more complete copy (a teleported transcript) replaces
4355
+ # it, so the one surviving row still says where the session ran.
4356
+ row_origin = _measure_facade.run_origin()
4357
+ if session_uuid:
4358
+ other = conn.execute(
4359
+ "SELECT id, message_count, input_tokens, output_tokens FROM session_log "
4360
+ "WHERE session_uuid = ? AND jsonl_path != ?",
4361
+ (session_uuid, str(filepath)),
4362
+ ).fetchall()
4363
+ try:
4364
+ if conn.execute(
4365
+ "SELECT 1 FROM session_log WHERE session_uuid = ? AND origin = 'cloud' LIMIT 1",
4366
+ (session_uuid,),
4367
+ ).fetchone():
4368
+ row_origin = "cloud"
4369
+ except _measure_facade.sqlite3.Error:
4370
+ pass
4371
+ mine = _measure_facade._session_rank(parsed.get("message_count"), parsed.get("total_input_tokens"),
4372
+ parsed.get("total_output_tokens"))
4373
+ # A tie keeps the stored copy, matching _dedupe_session_rows.
4374
+ if any(_measure_facade._session_rank(r[1], r[2], r[3]) >= mine for r in other):
4375
+ conn.execute(
4376
+ "INSERT OR REPLACE INTO session_log_aliases (jsonl_path, session_uuid, collected_at) "
4377
+ "VALUES (?, ?, ?)", (str(filepath), session_uuid, collection_started))
4378
+ # This copy changed since last seen and may hold requests the
4379
+ # stored copy lacks; its per-day usage (merged across copies) is
4380
+ # recomputed by the next backfill.
4381
+ conn.execute(
4382
+ "UPDATE session_log SET daily_usage_json = NULL WHERE session_uuid = ? AND jsonl_path != ?",
4383
+ (session_uuid, str(filepath)))
4384
+ _measure_facade._stamp_usage_parser_version(conn, filepath)
4385
+ continue
4386
+ else:
4387
+ other = []
4388
+
4389
+ # Compute quality score at collection time for persistence
4390
+ sq = _measure_facade.score_session_quality(parsed)
4391
+ # B1: persist reclaimable stale-read waste (opportunity tier, not realized).
4392
+ stale_waste = _measure_facade._session_stale_waste_tokens(filepath)
4393
+
4394
+ # Resolve the platform for this session. Codex transcripts carry
4395
+ # "runtime": "codex" in their parsed dict; Claude transcripts do not
4396
+ # set the key, so detect_runtime() (which returns the active runtime,
4397
+ # e.g. "claude" or "opencode") is the correct fallback.
4398
+ session_platform = parsed.get("runtime") or _measure_facade.detect_runtime()
4399
+
4400
+ # Insert session_log. ``origin`` rides along only when the column
4401
+ # exists: if the migration lost its busy wait, every insert naming a
4402
+ # missing column would fail and the whole collect would store nothing
4403
+ # (review #10). Same rule as the event writers (_origin_insert_parts).
4404
+ o_col, o_mark, o_val, o_upd = "", "", (), ""
4405
+ if _session_log_has_origin:
4406
+ o_col += ", origin"
4407
+ o_mark += ", ?"
4408
+ o_val += (row_origin,)
4409
+ o_upd += ",\n origin=COALESCE(session_log.origin, excluded.origin)"
4410
+ if _session_log_has_usage_version:
4411
+ o_col += ", usage_parser_version"
4412
+ o_mark += ", ?"
4413
+ o_val += (_measure_facade._USAGE_PARSER_VERSION,)
4414
+ o_upd += ",\n usage_parser_version=excluded.usage_parser_version"
4415
+ cur = conn.execute(
4416
+ """INSERT INTO session_log
4417
+ (jsonl_path, date, project, duration_minutes, input_tokens,
4418
+ output_tokens, message_count, api_calls, cache_hit_rate,
4419
+ cache_create_1h_tokens, cache_create_5m_tokens, cache_ttl_scanned,
4420
+ avg_call_gap_seconds, max_call_gap_seconds, p95_call_gap_seconds,
4421
+ skills_json, subagents_json, tool_calls_json, model_usage_json,
4422
+ all_model_usage_json, model_usage_breakdown_json, version, slug, topic, collected_at,
4423
+ quality_score, quality_grade, stale_waste_tokens, is_sidechain,
4424
+ sidechain_reason, reported_input_tokens, reported_output_tokens,
4425
+ reported_model_usage_json, platform, session_uuid, daily_usage_json""" + o_col + """)
4426
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?""" + o_mark + """)
4427
+ ON CONFLICT(jsonl_path) DO UPDATE SET
4428
+ date=excluded.date,
4429
+ project=excluded.project,
4430
+ duration_minutes=excluded.duration_minutes,
4431
+ input_tokens=excluded.input_tokens,
4432
+ output_tokens=excluded.output_tokens,
4433
+ message_count=excluded.message_count,
4434
+ api_calls=excluded.api_calls,
4435
+ cache_hit_rate=excluded.cache_hit_rate,
4436
+ cache_create_1h_tokens=excluded.cache_create_1h_tokens,
4437
+ cache_create_5m_tokens=excluded.cache_create_5m_tokens,
4438
+ cache_ttl_scanned=excluded.cache_ttl_scanned,
4439
+ avg_call_gap_seconds=excluded.avg_call_gap_seconds,
4440
+ max_call_gap_seconds=excluded.max_call_gap_seconds,
4441
+ p95_call_gap_seconds=excluded.p95_call_gap_seconds,
4442
+ skills_json=excluded.skills_json,
4443
+ subagents_json=excluded.subagents_json,
4444
+ tool_calls_json=excluded.tool_calls_json,
4445
+ model_usage_json=excluded.model_usage_json,
4446
+ all_model_usage_json=excluded.all_model_usage_json,
4447
+ model_usage_breakdown_json=excluded.model_usage_breakdown_json,
4448
+ version=excluded.version,
4449
+ slug=excluded.slug,
4450
+ topic=excluded.topic,
4451
+ collected_at=excluded.collected_at,
4452
+ quality_score=excluded.quality_score,
4453
+ quality_grade=excluded.quality_grade,
4454
+ stale_waste_tokens=excluded.stale_waste_tokens,
4455
+ is_sidechain=excluded.is_sidechain,
4456
+ sidechain_reason=excluded.sidechain_reason,
4457
+ reported_input_tokens=excluded.reported_input_tokens,
4458
+ reported_output_tokens=excluded.reported_output_tokens,
4459
+ reported_model_usage_json=excluded.reported_model_usage_json,
4460
+ platform=excluded.platform,
4461
+ session_uuid=COALESCE(excluded.session_uuid, session_log.session_uuid),
4462
+ daily_usage_json=excluded.daily_usage_json""" + o_upd + """
4463
+ WHERE session_log.collected_at IS NULL
4464
+ OR excluded.collected_at >= session_log.collected_at""",
4465
+ (
4466
+ str(filepath), date, project_name,
4467
+ parsed["duration_minutes"],
4468
+ parsed["total_input_tokens"],
4469
+ parsed["total_output_tokens"],
4470
+ parsed["message_count"],
4471
+ parsed.get("api_calls", 0),
4472
+ parsed["cache_hit_rate"],
4473
+ parsed.get("total_cache_create_1h", 0),
4474
+ parsed.get("total_cache_create_5m", 0),
4475
+ 1,
4476
+ parsed.get("avg_call_gap_seconds"),
4477
+ parsed.get("max_call_gap_seconds"),
4478
+ parsed.get("p95_call_gap_seconds"),
4479
+ _measure_facade.json.dumps(skills_used),
4480
+ _measure_facade.json.dumps(subagents_used),
4481
+ _measure_facade.json.dumps(parsed["tool_calls"]),
4482
+ _measure_facade.json.dumps(parsed["model_usage"]),
4483
+ _measure_facade.json.dumps(all_model_usage),
4484
+ _measure_facade.json.dumps(parsed.get("model_usage_breakdown", {})),
4485
+ parsed["version"],
4486
+ parsed.get("slug"),
4487
+ parsed.get("topic"),
4488
+ collection_started,
4489
+ sq["score"],
4490
+ sq["grade"],
4491
+ int(stale_waste or 0),
4492
+ 1 if parsed.get("is_sidechain") else 0,
4493
+ parsed.get("sidechain_reason"),
4494
+ int(parsed.get("reported_input_tokens", 0) or 0),
4495
+ int(parsed.get("reported_output_tokens", 0) or 0),
4496
+ _measure_facade.json.dumps(parsed.get("reported_model_usage", {})),
4497
+ session_platform,
4498
+ session_uuid,
4499
+ _measure_facade.json.dumps(daily_usage),
4500
+ ) + o_val,
4501
+ )
4502
+ if cur.rowcount != 1:
4503
+ continue
4504
+ calls = dict(parsed.get("daily_calls") or {})
4505
+ for u in (merged or parsed.get("request_usage") or {}).values():
4506
+ if not u.get("advisor") and u.get("n", 1) and u.get("day"):
4507
+ day = u["day"]
4508
+ calls[day] = calls.get(day, 0) + 1
4509
+ conn.execute(
4510
+ "UPDATE session_log SET first_activity_day=?, last_activity_day=?, transcript_mtime=?, "
4511
+ "parent_daily_usage_json=?, daily_calls_json=?, daily_metrics_json=? WHERE jsonl_path=?",
4512
+ (activity_bounds[0] if activity_bounds else None, activity_bounds[-1] if activity_bounds else None, mtime,
4513
+ _measure_facade.json.dumps(parent_daily), _measure_facade.json.dumps(calls), _measure_facade.json.dumps(session_daily_metrics), str(filepath)))
4514
+ if merged is not None:
4515
+ _measure_facade._claim_requests(conn, owner_id, merged)
4516
+ live_owners.add(_measure_facade._stable_hash63(owner_id))
4517
+ live_owners.add(_measure_facade._stable_hash63(str(filepath)))
4518
+ if session_uuid:
4519
+ # Retire the older copies only now that this row has landed; an
4520
+ # upsert the WHERE guard rejected must not leave the session with
4521
+ # no current row.
4522
+ if other:
4523
+ losers = conn.execute(
4524
+ "SELECT jsonl_path, collected_at FROM session_log WHERE session_uuid = ? AND jsonl_path != ?",
4525
+ (session_uuid, str(filepath)),
4526
+ ).fetchall()
4527
+ conn.executemany(
4528
+ "INSERT OR REPLACE INTO session_log_aliases (jsonl_path, session_uuid, collected_at) "
4529
+ "VALUES (?, ?, ?)", [(r[0], session_uuid, r[1]) for r in losers])
4530
+ conn.executemany("DELETE FROM session_log WHERE id = ?", [(r[0],) for r in other])
4531
+ conn.execute("DELETE FROM session_log_aliases WHERE jsonl_path = ?", (str(filepath),))
4532
+
4533
+ new_count += 1
4534
+ # Bank progress every batch so an interrupted deep backfill (a hook timeout
4535
+ # mid-parse) persists what it already collected instead of rolling back the
4536
+ # whole transaction. _is_file_collected skips banked files on the next run, so
4537
+ # the backfill converges over a few cycles rather than looping forever.
4538
+ if new_count % commit_batch == 0:
4539
+ try:
4540
+ conn.commit()
4541
+ except _measure_facade.sqlite3.Error:
4542
+ pass
4543
+
4544
+ # Bounded backfill of derived metrics for previously-collected sessions that
4545
+ # are missing columns added by a later upgrade (e.g. quality_score, call gaps).
4546
+ # Called ONCE after the collection loop with a small cap (50) so a new column
4547
+ # never re-triggers a full-history re-parse storm. The rolling window converges
4548
+ # over a few flushes instead of blocking turn-end for minutes.
4549
+ try:
4550
+ _measure_facade._backfill_session_metrics(conn, days=days, limit=50)
4551
+ except Exception:
4552
+ pass
4553
+ daily_truncated = False
4554
+ try:
4555
+ _daily_started = _measure_facade.time.monotonic()
4556
+ _measure_facade._backfill_daily_usage(conn, days=days if drain == "full" else min(days, 90),
4557
+ budget_seconds=budgets["daily_seconds"])
4558
+ daily_truncated = _measure_facade.time.monotonic() - _daily_started >= budgets["daily_seconds"]
4559
+ except Exception:
4560
+ pass
4561
+ try:
4562
+ _measure_facade._pretool_anchor_step(budget_seconds=5.0)
4563
+ except Exception:
4564
+ pass
4565
+
4566
+ # Keep the counted-cumulative ledger fresh in the SAME bounded
4567
+ # collect pass (never at dashboard-regen time). Both helpers carry their
4568
+ # own per-pass caps + soft deadline and are fail-open, so a slow transcript
4569
+ # can never hold the flush; the backlog converges over passes.
4570
+ counted_pending = 0
4571
+ try:
4572
+ if drain == "full":
4573
+ counted_pending = int(_measure_facade._counted_backfill_all(conn, quiet=quiet).get("pending_sessions", 0) or 0)
4574
+ else:
4575
+ counted_pending = int(_measure_facade._update_counted_cumulative(
4576
+ conn, max_sessions=budgets["counted_sessions"],
4577
+ deadline_seconds=budgets["counted_seconds"],
4578
+ quiet=quiet).get("pending_sessions", 0) or 0)
4579
+ if drain == "inline":
4580
+ _measure_facade._counted_marker_backfill(conn, max_files=None,
4581
+ deadline_seconds=budgets["counted_seconds"], quiet=quiet)
4582
+ else:
4583
+ _measure_facade._counted_marker_backfill(conn, quiet=quiet)
4584
+ except Exception:
4585
+ pass
4586
+ try:
4587
+ if drain == "full":
4588
+ _measure_facade._upgrade_drain_mark_done(conn)
4589
+ elif not rebuild:
4590
+ _measure_facade._upgrade_drain_after_pass(
4591
+ conn, backlog=bool(parse_truncated or daily_truncated or counted_pending))
4592
+ except Exception:
4593
+ pass
4594
+
4595
+ # ATOMICITY INVARIANT: _rebuild_aggregate_tables does DELETE-then-reINSERT and must
4596
+ # NOT commit internally. The whole wipe+rebuild is one transaction that commits only on
4597
+ # the next line, so a _HookTimeout (BaseException) mid-rebuild rolls back cleanly and the
4598
+ # prior aggregates survive intact. NEVER insert a conn.commit() between the DELETE and the
4599
+ # re-INSERTs -- a half-applied commit would leave the dashboard reading empty aggregates.
4600
+ _measure_facade._rebuild_aggregate_tables(conn)
4601
+ conn.commit()
4602
+ # Ensure schema version is set (idempotent, also set in migration and rebuild)
4603
+ conn.execute("PRAGMA user_version = 3")
4604
+ conn.commit() # PRAGMA write must be committed explicitly
4605
+ conn.close()
4606
+
4607
+ if not quiet:
4608
+ total = _measure_facade.conn_total_sessions() if _measure_facade.TRENDS_DB.exists() else new_count
4609
+ print(f"[Token Optimizer] Collected {new_count} new sessions. Total in DB: {total}")
4610
+ return new_count
4611
+
4612
+
4613
+ def conn_total_sessions():
4614
+ """Quick count of total sessions in the DB.
4615
+
4616
+ Uses Total Recall's DB-lock pattern: WAL mode + 5s busy_timeout + retry.
4617
+ """
4618
+ _measure_facade = _compat.facade()
4619
+ try:
4620
+ conn = _measure_facade.sqlite3.connect(str(_measure_facade.TRENDS_DB))
4621
+ conn.execute("PRAGMA journal_mode=WAL")
4622
+ conn.execute("PRAGMA busy_timeout=5000")
4623
+ conn.execute("PRAGMA wal_autocheckpoint=1000")
4624
+ conn.execute("PRAGMA journal_size_limit=67108864")
4625
+ cur = conn.execute("SELECT COUNT(*) FROM session_log")
4626
+ count = cur.fetchone()[0]
4627
+ conn.close()
4628
+ return count
4629
+ except (_measure_facade.sqlite3.Error, OSError):
4630
+ return 0
4631
+
4632
+
4633
+ def _read_path_upkeep(conn, days):
4634
+ """Best-effort catch-up writes before a dashboard read.
4635
+
4636
+ Each step waits at most ~200ms for the write lock and the rest are skipped
4637
+ once one is contended, so a render never stalls behind a running collector;
4638
+ the collector does the same work on its next flush.
4639
+ """
4640
+ _measure_facade = _compat.facade()
4641
+ conn.execute("PRAGMA busy_timeout=200")
4642
+ try:
4643
+ # Collapse duplicate sessions left by older versions and rebuild the
4644
+ # per-day summary tables if any went, so this render never mixes
4645
+ # deduped rows with still-doubled aggregates. Dedupe first, so the
4646
+ # backfill never spends its budget on rows about to be deleted.
4647
+ if _measure_facade._dedupe_session_rows(conn):
4648
+ _measure_facade._rebuild_aggregate_tables(conn)
4649
+ conn.commit()
4650
+ _measure_facade._backfill_session_metrics(conn, days=days)
4651
+ _measure_facade._backfill_daily_usage(conn, days=days, budget_seconds=3.0)
4652
+ except _measure_facade.sqlite3.Error:
4653
+ try:
4654
+ conn.rollback()
4655
+ except _measure_facade.sqlite3.Error:
4656
+ pass
4657
+ finally:
4658
+ try:
4659
+ conn.execute("PRAGMA busy_timeout=5000")
4660
+ except _measure_facade.sqlite3.Error:
4661
+ pass
4662
+
4663
+
4664
+ def _session_price_buckets(mb, pricing_tier):
4665
+ """(priced_tokens, unpriced_tokens) for a per-model breakdown."""
4666
+ _measure_facade = _compat.facade()
4667
+ priced = unpriced = 0
4668
+ for model_name, parts in (mb or {}).items():
4669
+ if not isinstance(parts, dict):
4670
+ continue
4671
+ model_tokens = (
4672
+ int(parts.get("fresh_input") or 0)
4673
+ + int(parts.get("cache_read") or 0)
4674
+ + int(parts.get("cache_create") or 0)
4675
+ + int(parts.get("output") or 0)
4676
+ )
4677
+ if _measure_facade._is_priced_model(model_name, tier=pricing_tier):
4678
+ priced += model_tokens
4679
+ else:
4680
+ unpriced += model_tokens
4681
+ return priced, unpriced
4682
+
4683
+
4684
+ def _price_session_row(sr, pricing_tier):
4685
+ """Price one session_log row: THE per-session cost for the dashboard and
4686
+ for `session-cost`, so the two can never disagree.
4687
+
4688
+ *sr* needs date, input_tokens, output_tokens, cache_hit_rate,
4689
+ cache_create_1h_tokens, cache_create_5m_tokens, model_usage_json,
4690
+ model_usage_breakdown_json and daily_usage_json. Every model is priced at
4691
+ its own generation card (_get_model_cost -> _claude_price_key).
4692
+
4693
+ Returns a dict:
4694
+ main_cost parent-thread cost (stored per-model breakdown; a dominant-model
4695
+ estimate for rows that carry none)
4696
+ total_cost the whole session. With per-day usage (parent + subagents,
4697
+ requests merged by requestId so a shared one bills once) it is
4698
+ the sum of the days; without it, main_cost.
4699
+ slices [[date, cost, priced, unpriced, input, output], ...] every
4700
+ billed day, uncut by any window
4701
+ has_daily whether total_cost includes the subagents
4702
+ priced_tokens / unpriced_tokens, dom_model, model_usage, breakdown,
4703
+ daily_usage
4704
+ """
4705
+ _measure_facade = _compat.facade()
4706
+ inp_total = sr["input_tokens"] or 0
4707
+ out_total = sr["output_tokens"] or 0
4708
+ chr_val = sr["cache_hit_rate"] or 0
4709
+ cache_read_est = _measure_facade._safe_int(inp_total * chr_val)
4710
+ cache_create_1h = sr["cache_create_1h_tokens"] or 0
4711
+ cache_create_5m = sr["cache_create_5m_tokens"] or 0
4712
+ cache_create_total = cache_create_1h + cache_create_5m
4713
+ uncached_est = max(0, inp_total - cache_read_est - cache_create_total)
4714
+
4715
+ mu = _measure_facade._safe_json_dict(sr["model_usage_json"])
4716
+ dom_model = max(mu, key=mu.get) if mu else "unknown"
4717
+ mb = _measure_facade._safe_json_dict(sr["model_usage_breakdown_json"])
4718
+ du = _measure_facade._safe_json_dict(sr["daily_usage_json"])
4719
+ if not du and "parent_daily_usage_json" in sr.keys():
4720
+ du = _measure_facade._safe_json_dict(sr["parent_daily_usage_json"])
4721
+
4722
+ if mb:
4723
+ session_priced_tokens, session_unpriced_tokens = _measure_facade._session_price_buckets(mb, pricing_tier)
4724
+ else:
4725
+ model_tokens = inp_total + out_total
4726
+ if _measure_facade._is_priced_model(dom_model, tier=pricing_tier):
4727
+ session_priced_tokens, session_unpriced_tokens = model_tokens, 0
4728
+ else:
4729
+ session_priced_tokens, session_unpriced_tokens = 0, model_tokens
4730
+ # Main-thread cost from the stored session breakdown. Used as-is for rows
4731
+ # without per-day data (non-JSONL adapters, transcript gone).
4732
+ split = bool(cache_create_1h or cache_create_5m)
4733
+ session_cost = _measure_facade._cost_from_model_breakdown(mb, tier=pricing_tier,
4734
+ cache_create_1h=cache_create_1h if split else None,
4735
+ cache_create_5m=cache_create_5m if split else None)
4736
+ if session_cost == 0.0:
4737
+ # Use the stored 1h/5m split when available; fall back to 5m-only rate otherwise.
4738
+ if split:
4739
+ session_cost = _measure_facade._get_model_cost(dom_model, uncached_est, out_total, cache_read_est, cache_create_total,
4740
+ tier=pricing_tier, cache_create_1h=cache_create_1h, cache_create_5m=cache_create_5m)
4741
+ else:
4742
+ session_cost = _measure_facade._get_model_cost(dom_model, uncached_est, out_total, cache_read_est, cache_create_total, tier=pricing_tier)
4743
+ if session_cost == 0.0 and session_priced_tokens == 0 and session_unpriced_tokens == 0 and (inp_total or out_total):
4744
+ session_unpriced_tokens = inp_total + out_total
4745
+
4746
+ # Unknown days remain in lifetime pricing but never acquire a window date.
4747
+ slices = [] # (date, cost, priced, unpriced, input_tokens, output_tokens)
4748
+ valid_days = frozenset(_measure_facade._activity_days(du))
4749
+ if du:
4750
+ by_day = {}
4751
+ for day, day_mb in du.items():
4752
+ if not isinstance(day_mb, dict):
4753
+ continue
4754
+ if day not in valid_days:
4755
+ continue
4756
+ _measure_facade._merge_daily_usage(by_day.setdefault(day, {}), {"_": day_mb})
4757
+ for day in sorted(by_day):
4758
+ day_mb = by_day[day].get("_", {})
4759
+ day_cost = _measure_facade._cost_from_model_breakdown(day_mb, tier=pricing_tier)
4760
+ day_priced, day_unpriced = _measure_facade._session_price_buckets(day_mb, pricing_tier)
4761
+ day_in = sum(
4762
+ int(p.get("fresh_input") or 0) + int(p.get("cache_read") or 0) + int(p.get("cache_create") or 0)
4763
+ for p in day_mb.values() if isinstance(p, dict))
4764
+ day_out = sum(int(p.get("output") or 0) for p in day_mb.values() if isinstance(p, dict))
4765
+ slices.append([day, day_cost, day_priced, day_unpriced, day_in, day_out])
4766
+ total_cost = sum(
4767
+ _measure_facade._cost_from_model_breakdown(models, tier=pricing_tier)
4768
+ for models in du.values() if isinstance(models, dict))
4769
+ else:
4770
+ total_cost = session_cost
4771
+ slices = [] # A lifetime estimate has no dated-window placement.
4772
+ return {
4773
+ "main_cost": session_cost,
4774
+ "total_cost": total_cost,
4775
+ "slices": slices,
4776
+ "has_daily": bool(du),
4777
+ "activity_complete": bool(du) and len(valid_days) == len(du),
4778
+ "priced_tokens": sum(sl[2] for sl in slices),
4779
+ "unpriced_tokens": sum(sl[3] for sl in slices),
4780
+ "dom_model": dom_model,
4781
+ "model_usage": mu,
4782
+ "breakdown": mb,
4783
+ "daily_usage": du,
4784
+ }