agent-efficiency 1.4.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. agent_efficiency/__init__.py +15 -0
  2. agent_efficiency/_bundle/mcp/server.py +519 -0
  3. agent_efficiency/_bundle/rules/AGENT_RULES.md +9 -0
  4. agent_efficiency/_bundle/scripts/ae_cli.py +327 -0
  5. agent_efficiency/_bundle/scripts/ae_init.py +267 -0
  6. agent_efficiency/_bundle/scripts/ae_manage.py +578 -0
  7. agent_efficiency/_bundle/scripts/install.py +308 -0
  8. agent_efficiency/_bundle/scripts/pretool_hook.py +350 -0
  9. agent_efficiency/_bundle/scripts/render_demo_svg.py +180 -0
  10. agent_efficiency/_bundle/scripts/setup_hooks.py +330 -0
  11. agent_efficiency/_bundle/scripts/sync_shared.py +85 -0
  12. agent_efficiency/_bundle/scripts/validate_skills.py +150 -0
  13. agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/SKILL.md +80 -0
  14. agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/config/models.json +237 -0
  15. agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/examples/workflow.md +77 -0
  16. agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/references/routing-and-escalation.md +63 -0
  17. agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/references/state-and-handoff.md +84 -0
  18. agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/scripts/_ae_core/__init__.py +90 -0
  19. agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/scripts/_ae_core/io_lock.py +199 -0
  20. agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/scripts/_ae_core/savings.py +249 -0
  21. agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/scripts/_ae_core/security.py +235 -0
  22. agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/scripts/_ae_core/usage.py +195 -0
  23. agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/scripts/agent_state.py +266 -0
  24. agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/scripts/context_doctor.py +780 -0
  25. agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/scripts/llm_adapter.py +306 -0
  26. agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/scripts/route_task.py +496 -0
  27. agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/scripts/state_ops.py +580 -0
  28. agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/scripts/state_render.py +428 -0
  29. agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/scripts/state_store.py +440 -0
  30. agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/scripts/transcript_audit.py +854 -0
  31. agent_efficiency/_bundle/skills/local-context-index/SKILL.md +71 -0
  32. agent_efficiency/_bundle/skills/local-context-index/references/cli-reference.md +112 -0
  33. agent_efficiency/_bundle/skills/local-context-index/scripts/_ae_core/__init__.py +90 -0
  34. agent_efficiency/_bundle/skills/local-context-index/scripts/_ae_core/io_lock.py +199 -0
  35. agent_efficiency/_bundle/skills/local-context-index/scripts/_ae_core/savings.py +249 -0
  36. agent_efficiency/_bundle/skills/local-context-index/scripts/_ae_core/security.py +235 -0
  37. agent_efficiency/_bundle/skills/local-context-index/scripts/_ae_core/usage.py +195 -0
  38. agent_efficiency/_bundle/skills/local-context-index/scripts/compact_run.py +395 -0
  39. agent_efficiency/_bundle/skills/local-context-index/scripts/context_index.py +341 -0
  40. agent_efficiency/_bundle/skills/local-context-index/scripts/idx_db.py +393 -0
  41. agent_efficiency/_bundle/skills/local-context-index/scripts/idx_ignore.py +184 -0
  42. agent_efficiency/_bundle/skills/local-context-index/scripts/idx_indexer.py +330 -0
  43. agent_efficiency/_bundle/skills/local-context-index/scripts/idx_lsp.py +213 -0
  44. agent_efficiency/_bundle/skills/local-context-index/scripts/idx_parsers.py +769 -0
  45. agent_efficiency/_bundle/skills/local-context-index/scripts/idx_search.py +498 -0
  46. agent_efficiency/_bundle/skills/local-context-index/scripts/idx_slice.py +610 -0
  47. agent_efficiency/_bundle/skills/local-context-index/scripts/idx_trace.py +553 -0
  48. agent_efficiency/_bundle/skills/local-context-index/scripts/idx_workspace.py +219 -0
  49. agent_efficiency/_bundle/skills/prompt-cache-manager/SKILL.md +52 -0
  50. agent_efficiency/_bundle/skills/prompt-cache-manager/references/provider-caching.md +52 -0
  51. agent_efficiency/_bundle/skills/prompt-cache-manager/scripts/_ae_core/__init__.py +90 -0
  52. agent_efficiency/_bundle/skills/prompt-cache-manager/scripts/_ae_core/io_lock.py +199 -0
  53. agent_efficiency/_bundle/skills/prompt-cache-manager/scripts/_ae_core/savings.py +249 -0
  54. agent_efficiency/_bundle/skills/prompt-cache-manager/scripts/_ae_core/security.py +235 -0
  55. agent_efficiency/_bundle/skills/prompt-cache-manager/scripts/_ae_core/usage.py +195 -0
  56. agent_efficiency/_bundle/skills/prompt-cache-manager/scripts/cache_payload.py +278 -0
  57. agent_efficiency/_bundle/skills/prompt-cache-manager/scripts/prompt_cache.py +488 -0
  58. agent_efficiency/cli.py +23 -0
  59. agent_efficiency/mcp_entry.py +25 -0
  60. agent_efficiency-1.4.2.dist-info/METADATA +267 -0
  61. agent_efficiency-1.4.2.dist-info/RECORD +64 -0
  62. agent_efficiency-1.4.2.dist-info/WHEEL +4 -0
  63. agent_efficiency-1.4.2.dist-info/entry_points.txt +4 -0
  64. agent_efficiency-1.4.2.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,854 @@
1
+ #!/usr/bin/env python3
2
+ """AgentEfficiency — Local IDE session transcript, repeat-read waste, USD cost & trend analyzer.
3
+
4
+ Strictly read-only on local transcript files (Antigravity, Claude Code, Codex, Gemini CLI);
5
+ redacts secrets before reporting. Computes verified API usage, estimated USD costs & cache savings,
6
+ repeat-read wasted tokens, top tool consumers, and chronological before-vs-after trends.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import argparse
11
+ import json
12
+ import re
13
+ import sys
14
+ import time
15
+ from collections import Counter, defaultdict
16
+ from pathlib import Path
17
+ from typing import Any, Dict, Iterable, List, Optional, Sequence, Tuple
18
+
19
+ _SCRIPT_DIR = str(Path(__file__).resolve().parent)
20
+ if _SCRIPT_DIR not in sys.path:
21
+ sys.path.insert(0, _SCRIPT_DIR)
22
+
23
+ from _ae_core import configure_utf8_stdio, estimate_tokens, parse_provider_usage, redact_secrets, sanitize_inline # noqa: E402
24
+
25
+ _HOME = Path.home()
26
+ _DISCOVERY_SPECS: Dict[str, List[Tuple[Path, str]]] = {
27
+ "antigravity": [(_HOME / ".gemini" / "antigravity" / "brain", "*/.system_generated/logs/transcript.jsonl")],
28
+ "claude": [(_HOME / ".claude" / "projects", "*/*.jsonl")],
29
+ "codex": [(_HOME / ".codex" / "sessions", "**/*.jsonl")],
30
+ "gemini": [(_HOME / ".gemini" / "tmp", "**/chats/*.json")],
31
+ "cursor": [(_HOME / ".cursor" / "projects", "*/agent-transcripts/*.jsonl")],
32
+ "opencode": [(_HOME / ".local" / "share" / "opencode" / "storage", "**/*.json")],
33
+ "cline": [
34
+ (_HOME / "Library" / "Application Support" / "Code" / "User" / "globalStorage" / "saoudrizwan.claude-dev" / "tasks", "*/api_conversation_history.json"),
35
+ (_HOME / ".config" / "Code" / "User" / "globalStorage" / "saoudrizwan.claude-dev" / "tasks", "*/api_conversation_history.json"),
36
+ ],
37
+ }
38
+
39
+ # Explicit maintenance tiers: Tier-1 parsers are fixture-tested in CI; Tier-2 adapters are best-effort
40
+ CLIENT_SUPPORT_TIERS: Dict[str, str] = {
41
+ "claude": "tier1",
42
+ "antigravity": "tier1",
43
+ "codex": "tier1",
44
+ "gemini": "tier1",
45
+ "cursor": "tier2",
46
+ "opencode": "tier2",
47
+ "cline": "tier2",
48
+ }
49
+ _SCHEMA_DRIFT_MIN_RECORDS = 5
50
+
51
+ _FILE_PATH_RE = re.compile(r"(?:/[^\s\"'`<>|]+?\.(?:py|ts|tsx|js|jsx|mjs|cjs|go|rs|java|kt|rb|md|json|yaml|yml|toml|sql|sh|c|cpp|h|swift|vue|svelte))")
52
+
53
+ # (substring_pattern, label, input_$/1M, output_$/1M, cache_read_mult, cache_write_mult)
54
+ _MODEL_PRICING: List[Tuple[str, str, float, float, float, float]] = [
55
+ ("opus-4", "claude-opus-4", 15.0, 75.0, 0.10, 1.25),
56
+ ("opus", "claude-opus", 15.0, 75.0, 0.10, 1.25),
57
+ ("sonnet-4", "claude-sonnet-4", 3.0, 15.0, 0.10, 1.25),
58
+ ("sonnet", "claude-sonnet", 3.0, 15.0, 0.10, 1.25),
59
+ ("haiku-4", "claude-haiku-4", 1.0, 5.0, 0.10, 1.25),
60
+ ("haiku", "claude-haiku", 1.0, 5.0, 0.10, 1.25),
61
+ ("flash-lite", "gemini-flash-lite", 0.10, 0.40, 0.25, 1.0),
62
+ ("flash_lite", "gemini-flash-lite", 0.10, 0.40, 0.25, 1.0),
63
+ ("flash", "gemini-flash", 0.30, 2.50, 0.25, 1.0),
64
+ ("gemini-4", "gemini-4", 1.25, 10.0, 0.25, 1.0),
65
+ ("gemini-3", "gemini-3", 1.25, 10.0, 0.25, 1.0),
66
+ ("gemini", "gemini-pro", 1.25, 10.0, 0.25, 1.0),
67
+ ("gpt-5-mini", "gpt-5-mini", 0.40, 1.60, 0.50, 1.0),
68
+ ("gpt-4o-mini", "gpt-4o-mini", 0.15, 0.60, 0.50, 1.0),
69
+ ("o4-mini", "o4-mini", 1.10, 4.40, 0.25, 1.0),
70
+ ("gpt-5", "gpt-5", 2.0, 8.0, 0.50, 1.0),
71
+ ("o3", "o3", 2.0, 8.0, 0.25, 1.0),
72
+ ]
73
+
74
+ _SOURCE_DEFAULT_PRICING: Dict[str, Tuple[str, float, float, float, float]] = {
75
+ "antigravity": ("gemini-pro (est)", 1.25, 10.0, 0.25, 1.0),
76
+ "gemini": ("gemini-pro (est)", 1.25, 10.0, 0.25, 1.0),
77
+ "claude": ("claude-sonnet (est)", 3.0, 15.0, 0.10, 1.25),
78
+ "codex": ("gpt-5 (est)", 2.0, 8.0, 0.50, 1.0),
79
+ "cursor": ("claude-sonnet (est)", 3.0, 15.0, 0.10, 1.25),
80
+ "opencode": ("claude-sonnet (est)", 3.0, 15.0, 0.10, 1.25),
81
+ "cline": ("claude-sonnet (est)", 3.0, 15.0, 0.10, 1.25),
82
+ }
83
+
84
+ _USER_PRICING_CACHE: Optional[List[Tuple[str, str, float, float, float, float]]] = None
85
+
86
+
87
+ def _load_user_pricing() -> List[Tuple[str, str, float, float, float, float]]:
88
+ global _USER_PRICING_CACHE
89
+ if _USER_PRICING_CACHE is not None:
90
+ return _USER_PRICING_CACHE
91
+ out: List[Tuple[str, str, float, float, float, float]] = []
92
+ cfg = Path.home() / ".agent-efficiency" / "pricing.json"
93
+ if cfg.is_file():
94
+ try:
95
+ raw = json.loads(cfg.read_text(encoding="utf-8"))
96
+ if isinstance(raw, dict):
97
+ for needle, vals in raw.items():
98
+ if isinstance(vals, dict):
99
+ out.append((
100
+ str(needle).lower(),
101
+ str(vals.get("label", needle)),
102
+ float(vals.get("input", 3.0)),
103
+ float(vals.get("output", 15.0)),
104
+ float(vals.get("cache_read_mult", 0.10)),
105
+ float(vals.get("cache_write_mult", 1.25)),
106
+ ))
107
+ except Exception:
108
+ pass
109
+ _USER_PRICING_CACHE = out
110
+ return out
111
+
112
+
113
+ def _resolve_pricing(model_name: str, source: str) -> Tuple[str, float, float, float, float]:
114
+ ml = (model_name or "").lower()
115
+ if ml:
116
+ for table in (_load_user_pricing(), _MODEL_PRICING):
117
+ for needle, label, inp, outp, rmult, wmult in table:
118
+ if needle in ml:
119
+ return model_name, inp, outp, rmult, wmult
120
+ return _SOURCE_DEFAULT_PRICING.get(source, ("balanced-default (est)", 2.5, 10.0, 0.20, 1.10))
121
+
122
+
123
+ def discover_transcripts(source: str = "auto", explicit_path: Optional[Path] = None, limit: int = 5) -> List[Tuple[str, Path]]:
124
+ """Find the most recent local IDE transcript files."""
125
+ if explicit_path is not None:
126
+ ep = explicit_path.expanduser().resolve()
127
+ if ep.is_file():
128
+ return [("custom", ep)]
129
+ if ep.is_dir():
130
+ cands = sorted(
131
+ [p for p in list(ep.rglob("*.jsonl")) + list(ep.rglob("*.json")) if p.is_file()],
132
+ key=lambda p: p.stat().st_mtime,
133
+ reverse=True,
134
+ )
135
+ return [("custom", p) for p in cands[: max(1, limit)]]
136
+ return []
137
+
138
+ sources = list(_DISCOVERY_SPECS.keys()) if source == "auto" else [source]
139
+ found: List[Tuple[float, str, Path]] = []
140
+ for src_name in sources:
141
+ for base, pattern in _DISCOVERY_SPECS.get(src_name, []):
142
+ if not base.is_dir():
143
+ continue
144
+ try:
145
+ for p in base.glob(pattern):
146
+ if p.is_file() and not p.is_symlink():
147
+ try:
148
+ found.append((p.stat().st_mtime, src_name, p))
149
+ except OSError:
150
+ pass
151
+ except OSError:
152
+ continue
153
+ found.sort(key=lambda x: x[0], reverse=True)
154
+ return [(s, p) for _mt, s, p in found[: max(1, limit)]]
155
+
156
+
157
+ def _iter_records(path: Path) -> Iterable[Dict[str, Any]]:
158
+ raw = path.read_text(encoding="utf-8", errors="replace")
159
+ if path.suffix.lower() == ".jsonl":
160
+ for line in raw.splitlines():
161
+ line = line.strip()
162
+ if not line:
163
+ continue
164
+ try:
165
+ obj = json.loads(line)
166
+ if isinstance(obj, dict):
167
+ yield obj
168
+ except Exception:
169
+ continue
170
+ else:
171
+ try:
172
+ obj = json.loads(raw)
173
+ except Exception:
174
+ return
175
+ if isinstance(obj, list):
176
+ for item in obj:
177
+ if isinstance(item, dict):
178
+ yield item
179
+ elif isinstance(obj, dict):
180
+ for key in ("messages", "turns", "events", "history"):
181
+ if isinstance(obj.get(key), list):
182
+ for item in obj[key]:
183
+ if isinstance(item, dict):
184
+ yield item
185
+ return
186
+ yield obj
187
+
188
+
189
+ def _extract_model_hint(rec: Dict[str, Any]) -> Optional[str]:
190
+ for cand in (
191
+ rec.get("model"),
192
+ rec.get("model_name"),
193
+ (rec.get("message") or {}).get("model") if isinstance(rec.get("message"), dict) else None,
194
+ (rec.get("metadata") or {}).get("model") if isinstance(rec.get("metadata"), dict) else None,
195
+ ):
196
+ if isinstance(cand, str) and cand.strip():
197
+ return cand.strip()
198
+ return None
199
+
200
+
201
+ def _extract_usage_dicts(rec: Dict[str, Any]) -> List[Dict[str, Any]]:
202
+ found: List[Dict[str, Any]] = []
203
+ # Note: Antigravity logs uncached `input_tokens` separately from `cache_read_tokens` (additive, like Anthropic).
204
+ if rec.get("input_tokens") is not None or rec.get("output_tokens") is not None or rec.get("cache_read_tokens") is not None:
205
+ flat: Dict[str, Any] = {}
206
+ if rec.get("input_tokens") is not None:
207
+ flat["input_tokens"] = rec["input_tokens"]
208
+ if rec.get("output_tokens") is not None:
209
+ flat["output_tokens"] = rec["output_tokens"]
210
+ if rec.get("cache_read_tokens") is not None:
211
+ flat["cache_read_input_tokens"] = rec["cache_read_tokens"]
212
+ if flat:
213
+ found.append(flat)
214
+ for candidate in (
215
+ rec.get("usage"),
216
+ rec.get("usageMetadata"),
217
+ (rec.get("message") or {}).get("usage") if isinstance(rec.get("message"), dict) else None,
218
+ (rec.get("payload") or {}).get("usage") if isinstance(rec.get("payload"), dict) else None,
219
+ (rec.get("metadata") or {}).get("usage") if isinstance(rec.get("metadata"), dict) else None,
220
+ ):
221
+ if isinstance(candidate, dict) and candidate:
222
+ found.append(candidate)
223
+ return found
224
+
225
+
226
+ def _extract_tool_events(rec: Dict[str, Any]) -> List[Tuple[str, str, str]]:
227
+ """Extract (tool_name, args_hint, output_text) tuples across Antigravity/Claude/Codex/Gemini transcript schemas."""
228
+ events: List[Tuple[str, str, str]] = []
229
+
230
+ if isinstance(rec.get("tool_calls"), list):
231
+ for tc in rec["tool_calls"]:
232
+ if isinstance(tc, dict) and isinstance(tc.get("name"), str):
233
+ args_obj = tc.get("args") or tc.get("arguments") or {}
234
+ args_s = json.dumps(args_obj, ensure_ascii=False) if not isinstance(args_obj, str) else args_obj
235
+ events.append((tc["name"], args_s, ""))
236
+
237
+ rtype = rec.get("type")
238
+ if (
239
+ isinstance(rtype, str)
240
+ and rtype.lower() not in (
241
+ "user", "assistant", "planner", "planner_response", "model", "thought",
242
+ "system", "system_message", "user_input", "generic", "checkpoint", "context_summary",
243
+ )
244
+ and rec.get("content") is not None
245
+ and not isinstance(rec.get("tool_calls"), list)
246
+ ):
247
+ out_obj = rec.get("content")
248
+ out_s = json.dumps(out_obj, ensure_ascii=False) if not isinstance(out_obj, str) else out_obj
249
+ events.append((rtype, "", out_s))
250
+
251
+ tname = rec.get("tool") or rec.get("tool_name") or rec.get("toolName") or rec.get("name")
252
+ if isinstance(tname, str) and tname and any(k in rec for k in ("output", "result", "response", "content", "arguments", "args", "input")):
253
+ args_obj = rec.get("arguments") or rec.get("args") or rec.get("input") or {}
254
+ out_obj = rec.get("output") if rec.get("output") is not None else (rec.get("result") if rec.get("result") is not None else rec.get("response", ""))
255
+ args_str = json.dumps(args_obj, ensure_ascii=False) if not isinstance(args_obj, str) else args_obj
256
+ out_str = json.dumps(out_obj, ensure_ascii=False) if not isinstance(out_obj, str) else out_obj
257
+ events.append((tname, args_str, out_str))
258
+
259
+ msg = rec.get("message") if isinstance(rec.get("message"), dict) else rec
260
+ content = msg.get("content") if isinstance(msg, dict) else None
261
+ if isinstance(content, list):
262
+ for blk in content:
263
+ if not isinstance(blk, dict):
264
+ continue
265
+ btype = blk.get("type")
266
+ if btype == "tool_use":
267
+ bn = str(blk.get("name") or "tool")
268
+ bi = json.dumps(blk.get("input") or {}, ensure_ascii=False)
269
+ events.append((bn, bi, ""))
270
+ elif btype == "tool_result":
271
+ rc = blk.get("content", "")
272
+ if isinstance(rc, list):
273
+ rc = "\n".join(str(x.get("text", x)) if isinstance(x, dict) else str(x) for x in rc)
274
+ elif not isinstance(rc, str):
275
+ rc = json.dumps(rc, ensure_ascii=False)
276
+ events.append((str(blk.get("tool_name") or "tool_result"), "", rc))
277
+ return events
278
+
279
+
280
+ def _is_read_tool(tname: str) -> bool:
281
+ tl = tname.lower()
282
+ return any(k in tl for k in ("read", "view", "cat")) and not any(w in tl for w in ("write", "edit", "replace", "patch"))
283
+
284
+
285
+ def _is_shell_tool(tname: str) -> bool:
286
+ tl = tname.lower()
287
+ return any(k in tl for k in ("command", "bash", "shell", "terminal", "exec"))
288
+
289
+
290
+ def _parse_read_args(args_s: str) -> List[Tuple[str, bool, str, Optional[int]]]:
291
+ """Return list of `(path, is_full_read, range_label, line_span)` parsed from tool call arguments."""
292
+ results: List[Tuple[str, bool, str, Optional[int]]] = []
293
+ if not args_s:
294
+ return results
295
+ try:
296
+ obj = json.loads(args_s)
297
+ except Exception:
298
+ obj = None
299
+ if isinstance(obj, dict):
300
+ fp = obj.get("Path") or obj.get("file_path") or obj.get("path") or obj.get("AbsolutePath") or obj.get("TargetFile")
301
+ if isinstance(fp, str) and fp.strip():
302
+ clean_fp = fp.strip().strip('"').strip("'")
303
+ s_ln = obj.get("StartLine") or obj.get("start_line") or obj.get("offset")
304
+ e_ln = obj.get("EndLine") or obj.get("end_line") or obj.get("limit")
305
+ is_full = s_ln is None and e_ln is None
306
+ rng = "full" if is_full else f"{s_ln or 1}-{e_ln or 'end'}"
307
+ span: Optional[int] = None
308
+ try:
309
+ if s_ln is not None and e_ln is not None:
310
+ span = max(1, int(str(e_ln).strip('"')) - int(str(s_ln).strip('"')) + 1)
311
+ except ValueError:
312
+ span = None
313
+ results.append((clean_fp, is_full, rng, span))
314
+ return results
315
+ for fp in dict.fromkeys(_FILE_PATH_RE.findall(args_s)):
316
+ results.append((fp.strip('"').strip("'"), True, "full", None))
317
+ return results
318
+
319
+
320
+ def _fallback_read_tokens(fp: str, is_full: bool, span: Optional[int]) -> int:
321
+ """When compact transcripts elide read_file bodies, estimate tokens safely from local file stat (read-only)."""
322
+ if span is not None:
323
+ return max(10, span * 10)
324
+ if is_full and fp.startswith("/"):
325
+ try:
326
+ p = Path(fp)
327
+ if p.is_file() and not p.is_symlink():
328
+ return max(1, min(46080, p.stat().st_size) // 4)
329
+ except OSError:
330
+ pass
331
+ return 0
332
+
333
+
334
+ def analyze_transcript(path: Path, source: str = "custom") -> Dict[str, Any]:
335
+ api_in = api_cached = api_write = api_out = 0
336
+ api_calls = 0
337
+ est_total_tok = 0
338
+ tool_tokens: Dict[str, int] = defaultdict(int)
339
+ tool_calls: Counter[str] = Counter()
340
+ heavy_calls: List[Dict[str, Any]] = []
341
+ read_events: Dict[str, List[Dict[str, Any]]] = defaultdict(list)
342
+ pending_reads: List[Dict[str, Any]] = []
343
+ models_seen: Counter[str] = Counter()
344
+ record_count = 0
345
+
346
+ try:
347
+ st_mtime = path.stat().st_mtime
348
+ except OSError:
349
+ st_mtime = 0.0
350
+
351
+ for rec in _iter_records(path):
352
+ record_count += 1
353
+ rec_raw_tok = estimate_tokens(json.dumps(rec, ensure_ascii=False))
354
+ est_total_tok += rec_raw_tok
355
+
356
+ mh = _extract_model_hint(rec)
357
+ if mh:
358
+ models_seen[mh] += 1
359
+
360
+ for u in _extract_usage_dicts(rec):
361
+ p = parse_provider_usage(u)
362
+ if p["input_tokens"] > 0 or p["output_tokens"] > 0:
363
+ api_calls += 1
364
+ api_in += p["input_tokens"]
365
+ api_cached += p["cache_read_tokens"]
366
+ api_write += p["cache_write_tokens"]
367
+ api_out += p["output_tokens"]
368
+
369
+ for tname, args_s, out_s in _extract_tool_events(rec):
370
+ out_tok = estimate_tokens(out_s)
371
+ arg_tok = estimate_tokens(args_s)
372
+ t_tok = out_tok + arg_tok
373
+ tool_tokens[tname] += t_tok
374
+ tool_calls[tname] += 1
375
+ if t_tok >= 400:
376
+ hint = sanitize_inline(redact_secrets(args_s or out_s))[:90]
377
+ heavy_calls.append({"tool": tname, "tokens_est": t_tok, "preview": hint})
378
+
379
+ if _is_read_tool(tname):
380
+ parsed = _parse_read_args(args_s)
381
+ if parsed:
382
+ for fp, is_full, rng, span in parsed:
383
+ ev = {"is_full": is_full, "range": rng, "span": span, "tokens_est": out_tok if out_s else 0}
384
+ read_events[fp].append(ev)
385
+ if not out_s:
386
+ pending_reads.append(ev)
387
+ elif out_s and pending_reads:
388
+ pending_reads.pop(0)["tokens_est"] = out_tok
389
+ elif tname.lower() == "tool_result" and out_s and pending_reads:
390
+ pending_reads.pop(0)["tokens_est"] = out_tok
391
+
392
+ heavy_calls.sort(key=lambda x: -x["tokens_est"])
393
+
394
+ repeated_reads: List[Dict[str, Any]] = []
395
+ for fp, evs in read_events.items():
396
+ for e in evs:
397
+ if e["tokens_est"] == 0:
398
+ e["tokens_est"] = _fallback_read_tokens(fp, e["is_full"], e.get("span"))
399
+ if len(evs) >= 2:
400
+ full_cnt = sum(1 for e in evs if e["is_full"])
401
+ tot_r_tok = sum(e["tokens_est"] for e in evs)
402
+ # Every read beyond the first is duplicate read cost (especially repeated full-file reads)
403
+ wasted_tok = sum(e["tokens_est"] for e in evs[1:])
404
+ repeated_reads.append({
405
+ "path": fp,
406
+ "reads": len(evs),
407
+ "full_reads": full_cnt,
408
+ "ranges": [e["range"] for e in evs[:8]],
409
+ "total_read_tokens_est": tot_r_tok,
410
+ "wasted_tokens_est": wasted_tok,
411
+ })
412
+ repeated_reads.sort(key=lambda x: (-x["wasted_tokens_est"], -x["full_reads"], -x["reads"], x["path"]))
413
+ repeat_read_waste_tok = sum(r["wasted_tokens_est"] for r in repeated_reads)
414
+ repeated_full_reads_extra = sum(max(0, r["full_reads"] - 1) for r in repeated_reads)
415
+ unique_files_read = len(read_events)
416
+ total_read_calls = sum(len(evs) for evs in read_events.values())
417
+ repeated_files_count = len(repeated_reads)
418
+
419
+ top_tools = [
420
+ {"tool": t, "calls": tool_calls[t], "tokens_est": tok}
421
+ for t, tok in sorted(tool_tokens.items(), key=lambda kv: -kv[1])[:10]
422
+ ]
423
+
424
+ shell_tok = sum(tok for t, tok in tool_tokens.items() if _is_shell_tool(t))
425
+ read_tok = sum(tok for t, tok in tool_tokens.items() if _is_read_tool(t))
426
+
427
+ dominant_model = models_seen.most_common(1)[0][0] if models_seen else ""
428
+ model_lbl, in_price, out_price, r_mult, w_mult = _resolve_pricing(dominant_model, source)
429
+ if api_in > 0 or api_out > 0:
430
+ uncached_in = max(0, api_in - api_cached - api_write)
431
+ est_cost_usd = (uncached_in * in_price + api_cached * in_price * r_mult + api_write * in_price * w_mult + api_out * out_price) / 1_000_000.0
432
+ est_cost_no_cache = (api_in * in_price + api_out * out_price) / 1_000_000.0
433
+ est_cache_savings = max(0.0, est_cost_no_cache - est_cost_usd)
434
+ cost_basis = "api_usage"
435
+ else:
436
+ est_cost_usd = (est_total_tok * in_price) / 1_000_000.0
437
+ est_cost_no_cache = est_cost_usd
438
+ est_cache_savings = 0.0
439
+ cost_basis = "estimated_transcript_text"
440
+
441
+ tool_events_parsed = sum(tool_calls.values())
442
+ support_tier = CLIENT_SUPPORT_TIERS.get(source, "custom")
443
+ schema_warning: Optional[str] = None
444
+ if record_count >= _SCHEMA_DRIFT_MIN_RECORDS and tool_events_parsed == 0 and api_calls == 0:
445
+ tier_note = " (best-effort Tier-2 adapter)" if support_tier == "tier2" else ""
446
+ schema_warning = (
447
+ f"Parsed {record_count} record(s) from '{source}'{tier_note} ({path.name}) but extracted "
448
+ "0 tool events and 0 API usage entries — client transcript schema may have changed."
449
+ )
450
+
451
+ recommendations: List[str] = []
452
+ if schema_warning:
453
+ recommendations.append(schema_warning)
454
+ if shell_tok >= 1200:
455
+ recommendations.append(f"Shell/command outputs consumed ~{shell_tok:,} tok — wrap noisy test/build commands via `ae run -- <cmd>` (or `context_index.py run`) for 80–95% reduction.")
456
+ if repeated_reads:
457
+ top_r = repeated_reads[0]
458
+ waste_note = f", ~{repeat_read_waste_tok:,} wasted tok" if repeat_read_waste_tok > 0 else ""
459
+ recommendations.append(f"{len(repeated_reads)} file(s) were read multiple times (e.g. {top_r['path']} x{top_r['reads']}{waste_note}) — use `ae slice`/`outline` + `record-inspection`.")
460
+ if read_tok >= 4000:
461
+ recommendations.append(f"File reads consumed ~{read_tok:,} tok — prefer `ae search`/`outline`/`slice` over full-file reads.")
462
+ hit_rate = round((api_cached / api_in) * 100.0, 2) if api_in > 0 else None
463
+ if hit_rate is not None and hit_rate < 40.0 and api_in >= 10000:
464
+ recommendations.append(f"Verified cache hit rate is only {hit_rate}% — check for volatile tokens in system/project prompts with `prompt_cache.py lint`.")
465
+
466
+ return {
467
+ "source": source,
468
+ "support_tier": support_tier,
469
+ "path": str(path),
470
+ "mtime": st_mtime,
471
+ "modified_at": time.strftime("%Y-%m-%dT%H:%M:%S", time.localtime(st_mtime)) if st_mtime else None,
472
+ "records": record_count,
473
+ "tool_events_parsed": tool_events_parsed,
474
+ "schema_warning": schema_warning,
475
+ "estimated_transcript_tokens": est_total_tok,
476
+ "shell_tokens_est": shell_tok,
477
+ "read_tokens_est": read_tok,
478
+ "unique_files_read": unique_files_read,
479
+ "total_read_calls": total_read_calls,
480
+ "repeated_files_count": repeated_files_count,
481
+ "repeat_read_waste_tokens_est": repeat_read_waste_tok,
482
+ "repeated_full_reads_extra": repeated_full_reads_extra,
483
+ "api_usage_found": api_calls > 0,
484
+ "api_usage": {
485
+ "calls": api_calls,
486
+ "input_tokens": api_in,
487
+ "cache_read_tokens": api_cached,
488
+ "cache_write_tokens": api_write,
489
+ "output_tokens": api_out,
490
+ "cache_hit_rate_pct": hit_rate,
491
+ },
492
+ "cost_estimate": {
493
+ "model": model_lbl,
494
+ "basis": cost_basis,
495
+ "est_cost_usd": round(est_cost_usd, 4),
496
+ "est_cost_without_cache_usd": round(est_cost_no_cache, 4),
497
+ "est_cache_savings_usd": round(est_cache_savings, 4),
498
+ },
499
+ "top_tools": top_tools,
500
+ "top_heavy_calls": heavy_calls[:8],
501
+ "repeated_file_reads": repeated_reads[:10],
502
+ "recommendations": recommendations,
503
+ }
504
+
505
+
506
+ def _pct_delta(before: float, after: float) -> Optional[float]:
507
+ if before <= 0:
508
+ return None
509
+ return round(((after - before) / before) * 100.0, 1)
510
+
511
+
512
+ def _compute_trend(sessions: Sequence[Dict[str, Any]], compare_window: Optional[int] = None) -> Optional[Dict[str, Any]]:
513
+ if len(sessions) < 2:
514
+ return None
515
+ chrono = sorted(sessions, key=lambda s: (s.get("mtime", 0.0), s.get("path", "")))
516
+ if compare_window is not None and compare_window > 0 and len(chrono) >= 2:
517
+ w = min(compare_window, len(chrono) // 2)
518
+ if w >= 1:
519
+ older = chrono[-2 * w : -w]
520
+ newer = chrono[-w:]
521
+ else:
522
+ older, newer = chrono[:1], chrono[1:]
523
+ else:
524
+ mid = len(chrono) // 2
525
+ older, newer = chrono[:mid], chrono[mid:]
526
+
527
+ def _avg(group: Sequence[Dict[str, Any]], fn: Any) -> float:
528
+ vals = [fn(s) for s in group]
529
+ return sum(vals) / max(1, len(vals))
530
+
531
+ def _weighted_cache_hit(group: Sequence[Dict[str, Any]]) -> Optional[float]:
532
+ tot_in = sum(int(s["api_usage"]["input_tokens"]) for s in group if s.get("api_usage", {}).get("input_tokens", 0) > 0)
533
+ tot_cached = sum(int(s["api_usage"]["cache_read_tokens"]) for s in group if s.get("api_usage", {}).get("input_tokens", 0) > 0)
534
+ if tot_in <= 0:
535
+ return None
536
+ return (tot_cached / tot_in) * 100.0
537
+
538
+ b_tok = _avg(older, lambda s: s["estimated_transcript_tokens"])
539
+ a_tok = _avg(newer, lambda s: s["estimated_transcript_tokens"])
540
+ b_shell = _avg(older, lambda s: s["shell_tokens_est"])
541
+ a_shell = _avg(newer, lambda s: s["shell_tokens_est"])
542
+ b_read = _avg(older, lambda s: s["read_tokens_est"])
543
+ a_read = _avg(newer, lambda s: s["read_tokens_est"])
544
+ b_rep = _avg(older, lambda s: s["repeat_read_waste_tokens_est"])
545
+ a_rep = _avg(newer, lambda s: s["repeat_read_waste_tokens_est"])
546
+ b_cost = _avg(older, lambda s: s["cost_estimate"]["est_cost_usd"])
547
+ a_cost = _avg(newer, lambda s: s["cost_estimate"]["est_cost_usd"])
548
+ b_hit = _weighted_cache_hit(older)
549
+ a_hit = _weighted_cache_hit(newer)
550
+
551
+ return {
552
+ "older_sessions": len(older),
553
+ "newer_sessions": len(newer),
554
+ "cache_hit_basis": "token_weighted",
555
+ "metrics": {
556
+ "avg_transcript_tokens": {"before": round(b_tok, 1), "after": round(a_tok, 1), "delta_pct": _pct_delta(b_tok, a_tok)},
557
+ "avg_shell_tokens": {"before": round(b_shell, 1), "after": round(a_shell, 1), "delta_pct": _pct_delta(b_shell, a_shell)},
558
+ "avg_read_tokens": {"before": round(b_read, 1), "after": round(a_read, 1), "delta_pct": _pct_delta(b_read, a_read)},
559
+ "avg_repeat_read_waste_tokens": {"before": round(b_rep, 1), "after": round(a_rep, 1), "delta_pct": _pct_delta(b_rep, a_rep)},
560
+ "avg_est_cost_usd": {"before": round(b_cost, 4), "after": round(a_cost, 4), "delta_pct": _pct_delta(b_cost, a_cost)},
561
+ "avg_cache_hit_rate_pct": {
562
+ "before": round(b_hit, 2) if b_hit is not None else None,
563
+ "after": round(a_hit, 2) if a_hit is not None else None,
564
+ "delta_pp": round(a_hit - b_hit, 2) if (a_hit is not None and b_hit is not None) else None,
565
+ },
566
+ },
567
+ }
568
+
569
+
570
+ def audit_sessions(
571
+ source: str = "auto",
572
+ explicit_path: Optional[Path] = None,
573
+ limit: int = 5,
574
+ compare_window: Optional[int] = None,
575
+ ) -> Dict[str, Any]:
576
+ targets = discover_transcripts(source=source, explicit_path=explicit_path, limit=limit)
577
+ sessions = [analyze_transcript(p, src) for src, p in targets]
578
+ tot_api_in = sum(s["api_usage"]["input_tokens"] for s in sessions)
579
+ tot_api_cached = sum(s["api_usage"]["cache_read_tokens"] for s in sessions)
580
+ tot_api_out = sum(s["api_usage"]["output_tokens"] for s in sessions)
581
+ tot_est = sum(s["estimated_transcript_tokens"] for s in sessions)
582
+ tot_rep_waste = sum(s["repeat_read_waste_tokens_est"] for s in sessions)
583
+ tot_rep_full = sum(s["repeated_full_reads_extra"] for s in sessions)
584
+ tot_cost = round(sum(s["cost_estimate"]["est_cost_usd"] for s in sessions), 4)
585
+ tot_cost_no_cache = round(sum(s["cost_estimate"]["est_cost_without_cache_usd"] for s in sessions), 4)
586
+ tot_cache_savings = round(sum(s["cost_estimate"]["est_cache_savings_usd"] for s in sessions), 4)
587
+
588
+ agg_tools: Dict[str, int] = defaultdict(int)
589
+ agg_repeats: Dict[str, Dict[str, Any]] = {}
590
+ for s in sessions:
591
+ for tt in s["top_tools"]:
592
+ agg_tools[tt["tool"]] += tt["tokens_est"]
593
+ for rr in s["repeated_file_reads"]:
594
+ cur = agg_repeats.setdefault(rr["path"], {"path": rr["path"], "reads": 0, "full_reads": 0, "wasted_tokens_est": 0, "sessions": 0})
595
+ cur["reads"] += rr["reads"]
596
+ cur["full_reads"] += rr["full_reads"]
597
+ cur["wasted_tokens_est"] += rr["wasted_tokens_est"]
598
+ cur["sessions"] += 1
599
+
600
+ top_repeated = sorted(agg_repeats.values(), key=lambda x: (-x["wasted_tokens_est"], -x["full_reads"], -x["reads"], x["path"]))[:8]
601
+ tot_shell = sum(s["shell_tokens_est"] for s in sessions)
602
+ tot_reads = sum(s["read_tokens_est"] for s in sessions)
603
+ tot_unique_reads = sum(int(s.get("unique_files_read", 0)) for s in sessions)
604
+ tot_read_calls = sum(int(s.get("total_read_calls", 0)) for s in sessions)
605
+ tot_rep_files = sum(int(s.get("repeated_files_count", 0)) for s in sessions)
606
+ overall_hit = round((tot_api_cached / tot_api_in) * 100.0, 2) if tot_api_in > 0 else None
607
+
608
+ schema_warnings = [s["schema_warning"] for s in sessions if s.get("schema_warning")]
609
+ all_recs: List[str] = []
610
+ if schema_warnings:
611
+ all_recs.append(f"Schema-drift warning on {len(schema_warnings)} session(s): {schema_warnings[0]}")
612
+ if tot_shell >= 1200:
613
+ all_recs.append(f"Shell/command outputs consumed ~{tot_shell:,} tok across {len(sessions)} session(s) — wrap noisy test/build commands via `ae run -- <cmd>` (or `context_index.py run`) for 80–95% reduction.")
614
+ if top_repeated:
615
+ tr0 = top_repeated[0]
616
+ w_note = f", ~{tot_rep_waste:,} total wasted tok" if tot_rep_waste > 0 else ""
617
+ all_recs.append(f"{len(agg_repeats)} file(s) were read multiple times (top: `{tr0['path']}` x{tr0['reads']}{w_note}) — use `ae slice`/`outline` + `record-inspection`.")
618
+ if tot_reads >= 4000:
619
+ all_recs.append(f"File reads consumed ~{tot_reads:,} tok — prefer `ae search`/`outline`/`slice` over full-file reads.")
620
+ if overall_hit is not None and overall_hit < 40.0 and tot_api_in >= 10000:
621
+ all_recs.append(f"Overall cache hit rate is only {overall_hit}% — audit system/project prompts with `prompt_cache.py lint`.")
622
+ trend = _compute_trend(sessions, compare_window=compare_window)
623
+
624
+ return {
625
+ "source": source,
626
+ "support_tiers": dict(CLIENT_SUPPORT_TIERS),
627
+ "sessions_analyzed": len(sessions),
628
+ "schema_warnings": schema_warnings,
629
+ "totals": {
630
+ "estimated_transcript_tokens": tot_est,
631
+ "api_input_tokens": tot_api_in,
632
+ "api_cache_read_tokens": tot_api_cached,
633
+ "api_output_tokens": tot_api_out,
634
+ "overall_cache_hit_rate_pct": overall_hit,
635
+ "est_cost_usd": tot_cost,
636
+ "est_cost_without_cache_usd": tot_cost_no_cache,
637
+ "est_cache_savings_usd": tot_cache_savings,
638
+ "shell_output_tokens_est": tot_shell,
639
+ "read_output_tokens_est": tot_reads,
640
+ "unique_files_read": tot_unique_reads,
641
+ "total_read_calls": tot_read_calls,
642
+ "repeated_files_count": tot_rep_files,
643
+ "repeat_read_waste_tokens_est": tot_rep_waste,
644
+ "repeated_full_reads_extra": tot_rep_full,
645
+ },
646
+ "top_tools_across_sessions": [{"tool": t, "tokens_est": tok} for t, tok in sorted(agg_tools.items(), key=lambda kv: -kv[1])[:8]],
647
+ "top_repeated_reads": top_repeated,
648
+ "trend": trend,
649
+ "recommendations": all_recs[:6],
650
+ "sessions": sessions,
651
+ }
652
+
653
+
654
+ def format_compact_audit(report: Dict[str, Any]) -> str:
655
+ if report["sessions_analyzed"] == 0:
656
+ return f"No local IDE session transcripts found for source='{report['source']}'."
657
+ t = report["totals"]
658
+ lines = [
659
+ f"# IDE Session Token Audit ({report['sessions_analyzed']} session(s), source={report['source']})",
660
+ f"- Est. transcript tokens: ~{t['estimated_transcript_tokens']:,}",
661
+ ]
662
+ if t["api_input_tokens"] > 0:
663
+ lines.append(f"- Verified API tokens (cumulative across turns): in={t['api_input_tokens']:,} | cache_read={t['api_cache_read_tokens']:,} ({t['overall_cache_hit_rate_pct']}%) | out={t['api_output_tokens']:,}")
664
+ sav_note = f" (cache saved ~${t['est_cache_savings_usd']:.4f} vs ${t['est_cost_without_cache_usd']:.4f})" if t["est_cache_savings_usd"] > 0 else ""
665
+ lines.append(f"- Est. cost: ~${t['est_cost_usd']:.4f}{sav_note}")
666
+ lines.append(
667
+ f"- Tool outputs (raw, pre-replay): reads=~{t.get('read_output_tokens_est', 0):,} tok "
668
+ f"({t.get('unique_files_read', 0)} unique files, {t.get('total_read_calls', 0)} total calls, {t.get('repeated_files_count', 0)} repeated) | "
669
+ f"shell=~{t.get('shell_output_tokens_est', 0):,} tok"
670
+ )
671
+ if t["repeat_read_waste_tokens_est"] > 0 or t["repeated_full_reads_extra"] > 0:
672
+ lines.append(f"- Repeat-read waste: ~{t['repeat_read_waste_tokens_est']:,} tok across {t['repeated_full_reads_extra']} extra full-file re-read(s)")
673
+ if report["top_tools_across_sessions"]:
674
+ lines.append("- Top tool consumers: " + ", ".join(f"{x['tool']}(~{x['tokens_est']:,} tok)" for x in report["top_tools_across_sessions"][:5]))
675
+ if report.get("top_repeated_reads"):
676
+ lines.append("")
677
+ lines.append("## Repeated File Reads (Detector)")
678
+ for rr in report["top_repeated_reads"][:5]:
679
+ w = f", ~{rr['wasted_tokens_est']:,} wasted tok" if rr["wasted_tokens_est"] > 0 else ""
680
+ lines.append(f"- `{rr['path']}`: {rr['reads']}x ({rr['full_reads']} full{w})")
681
+ tr = report.get("trend")
682
+ if tr:
683
+ m = tr["metrics"]
684
+ lines.append("")
685
+ lines.append(f"## Before vs After Trend (older {tr['older_sessions']} vs newer {tr['newer_sessions']} sessions)")
686
+ for key, label, unit in (
687
+ ("avg_transcript_tokens", "Avg transcript tokens", "tok"),
688
+ ("avg_shell_tokens", "Avg shell/run output", "tok"),
689
+ ("avg_read_tokens", "Avg file read volume", "tok"),
690
+ ("avg_repeat_read_waste_tokens", "Avg repeat-read waste", "tok"),
691
+ ("avg_est_cost_usd", "Avg est. cost/session", "USD"),
692
+ ):
693
+ d = m[key]
694
+ if d["before"] == 0 and d["after"] == 0:
695
+ continue
696
+ dp = f" ({d['delta_pct']:+.1f}%)" if d["delta_pct"] is not None else ""
697
+ if unit == "USD":
698
+ lines.append(f"- {label}: ${d['before']:.4f} -> ${d['after']:.4f}{dp}")
699
+ else:
700
+ lines.append(f"- {label}: ~{d['before']:,.0f} -> ~{d['after']:,.0f} {unit}{dp}")
701
+ ch = m["avg_cache_hit_rate_pct"]
702
+ if ch["before"] is not None and ch["after"] is not None:
703
+ lines.append(f"- Avg cache hit rate: {ch['before']:.1f}% -> {ch['after']:.1f}% ({ch['delta_pp']:+.1f} pp)")
704
+ if report.get("schema_warnings"):
705
+ lines.extend(["", "## Schema-Drift Warnings", *[f"- [WARN] {w}" for w in report["schema_warnings"][:4]]])
706
+ if report["recommendations"]:
707
+ lines.extend(["", "## Optimization Opportunities", *[f"- {r}" for r in report["recommendations"]]])
708
+ return "\n".join(lines)
709
+
710
+
711
+ def _fmt_tok(n: float) -> str:
712
+ v = int(round(n))
713
+ if v >= 1_000_000:
714
+ return f"{v / 1_000_000:.2f}M"
715
+ if v >= 1_000:
716
+ return f"{v / 1_000:.1f}k"
717
+ return str(v)
718
+
719
+
720
+ def _bar(fraction: float, width: int = 16) -> str:
721
+ f = max(0.0, min(1.0, fraction))
722
+ k = int(round(f * width))
723
+ return "█" * k + "░" * (width - k)
724
+
725
+
726
+ def _box_row(text: str, width: int = 62) -> str:
727
+ clipped = text if len(text) <= width else (text[: max(1, width - 1)] + "…")
728
+ return f"│{clipped:<{width}}│"
729
+
730
+
731
+ def format_card_audit(report: Dict[str, Any]) -> str:
732
+ """Render a visual, shareable terminal receipt of IDE token waste, USD cost, and before/after trends."""
733
+ if report["sessions_analyzed"] == 0:
734
+ return (
735
+ "┌──────────────────────────────────────────────────────────────┐\n"
736
+ + _box_row(" AgentEfficiency Session Audit") + "\n"
737
+ + "├──────────────────────────────────────────────────────────────┤\n"
738
+ + _box_row(f" No local transcripts found for source='{report['source']}'.") + "\n"
739
+ + _box_row(" Supports: Claude Code, Antigravity, Codex, Gemini, Cursor,") + "\n"
740
+ + _box_row(" OpenCode, Cline (or pass `--path <logfile>`).") + "\n"
741
+ + "└──────────────────────────────────────────────────────────────┘"
742
+ )
743
+ t = report["totals"]
744
+ n = int(report["sessions_analyzed"])
745
+ sessions = report.get("sessions") or []
746
+ tot_shell = sum(int(s.get("shell_tokens_est", 0)) for s in sessions)
747
+ tot_reads = sum(int(s.get("read_tokens_est", 0)) for s in sessions)
748
+ rep_waste = int(t["repeat_read_waste_tokens_est"])
749
+ sources_seen = sorted({str(s.get("source", report["source"])) for s in sessions})
750
+ src_lbl = ",".join(sources_seen)
751
+
752
+ cost_s = f"${t['est_cost_usd']:.2f}" if t["est_cost_usd"] >= 0.01 else f"${t['est_cost_usd']:.4f}"
753
+ sav_s = f"${t['est_cache_savings_usd']:.2f}" if t["est_cache_savings_usd"] >= 0.01 else f"${t['est_cache_savings_usd']:.4f}"
754
+ hit = t.get("overall_cache_hit_rate_pct")
755
+
756
+ lines = [
757
+ "┌──────────────────────────────────────────────────────────────┐",
758
+ _box_row(f" AgentEfficiency Session Audit · {n} session(s) ({src_lbl})"),
759
+ "├──────────────────────────────────────────────────────────────┤",
760
+ _box_row(f" Est. Cost : {cost_s:<10} (cache saved ~{sav_s})"),
761
+ ]
762
+ if t["api_input_tokens"] > 0:
763
+ hit_str = f"{hit:.1f}%" if hit is not None else "n/a"
764
+ hit_bar = _bar((hit or 0.0) / 100.0, width=14)
765
+ lines.append(_box_row(f" Cache Hit : {hit_bar} {hit_str:>6} (cumul. in {_fmt_tok(t['api_input_tokens'])})"))
766
+ else:
767
+ lines.append(_box_row(f" Transcript : ~{_fmt_tok(t['estimated_transcript_tokens'])} tok across {n} session(s)"))
768
+
769
+ lines.append("├──────────────────────────────────────────────────────────────┤")
770
+ lines.append(_box_row(
771
+ f" Tool Outputs (raw): {t.get('unique_files_read', 0)} uniq files, "
772
+ f"{t.get('total_read_calls', 0)} reads ({t.get('repeated_files_count', 0)} rep)"
773
+ ))
774
+ peak_w = max(1, tot_shell, tot_reads, rep_waste)
775
+ for lbl, val in (
776
+ ("File Reads ", tot_reads),
777
+ ("Shell/Tests ", tot_shell),
778
+ ("Repeat Waste", rep_waste),
779
+ ):
780
+ lines.append(_box_row(f" {lbl} {_bar(val / peak_w, width=18)} ~{_fmt_tok(val):>7} tok"))
781
+
782
+ if report.get("top_repeated_reads"):
783
+ lines.append("├──────────────────────────────────────────────────────────────┤")
784
+ lines.append(_box_row(" Top Repeated File Reads:"))
785
+ for rr in report["top_repeated_reads"][:3]:
786
+ fname = Path(rr["path"]).name[:28]
787
+ w_s = f"~{_fmt_tok(rr['wasted_tokens_est'])} waste" if rr["wasted_tokens_est"] > 0 else f"{rr['full_reads']} full"
788
+ lines.append(_box_row(f" • {fname:<28} {rr['reads']:>2}x ({w_s})"))
789
+
790
+ tr = report.get("trend")
791
+ if tr:
792
+ m = tr["metrics"]
793
+ lines.append("├──────────────────────────────────────────────────────────────┤")
794
+ lines.append(_box_row(f" Trend (older {tr['older_sessions']} vs newer {tr['newer_sessions']} sessions):"))
795
+ for key, lbl, unit in (
796
+ ("avg_shell_tokens", "Shell logs ", "tok"),
797
+ ("avg_repeat_read_waste_tokens", "Repeat waste", "tok"),
798
+ ("avg_est_cost_usd", "Cost/sess ", "USD"),
799
+ ):
800
+ d = m[key]
801
+ if d["before"] == 0 and d["after"] == 0:
802
+ continue
803
+ dp = d.get("delta_pct")
804
+ arrow = "↓" if (dp is not None and dp < 0) else ("↑" if (dp is not None and dp > 0) else "→")
805
+ dp_s = f"{arrow} {dp:+.1f}%" if dp is not None else ""
806
+ if unit == "USD":
807
+ row = f" {lbl:<12} ${d['before']:.3f} -> ${d['after']:.3f} {dp_s}"
808
+ else:
809
+ row = f" {lbl:<12} {_fmt_tok(d['before']):>6} -> {_fmt_tok(d['after']):<6} {dp_s}"
810
+ lines.append(_box_row(row))
811
+ ch = m["avg_cache_hit_rate_pct"]
812
+ if ch["before"] is not None and ch["after"] is not None:
813
+ arrow = "↑" if (ch["delta_pp"] or 0) > 0 else "↓"
814
+ lines.append(_box_row(f" Cache (wtd) {ch['before']:.1f}% -> {ch['after']:.1f}% {arrow} {ch['delta_pp']:+.1f} pp"))
815
+
816
+ if report.get("schema_warnings"):
817
+ lines.append("├──────────────────────────────────────────────────────────────┤")
818
+ lines.append(_box_row(f" [WARN] Schema drift in {len(report['schema_warnings'])} session(s) (0 events parsed)"))
819
+ lines.append("├──────────────────────────────────────────────────────────────┤")
820
+ lines.append(_box_row(" Next step: run `ae init` (auto-wrap tests) & `ae doctor`"))
821
+ lines.append("└──────────────────────────────────────────────────────────────┘")
822
+ if report.get("recommendations"):
823
+ lines.append("")
824
+ lines.append("Optimization Opportunities:")
825
+ for r in report["recommendations"][:4]:
826
+ lines.append(f" - {r}")
827
+ return "\n".join(lines)
828
+
829
+
830
+ def main(argv: Optional[Sequence[str]] = None) -> int:
831
+ configure_utf8_stdio()
832
+ ap = argparse.ArgumentParser(description="Analyze local IDE agent transcripts for token waste, repeat reads, USD cost & trends.")
833
+ ap.add_argument(
834
+ "--source",
835
+ choices=["auto", "antigravity", "claude", "codex", "gemini", "cursor", "opencode", "cline", "path"],
836
+ default="auto",
837
+ )
838
+ ap.add_argument("--path", type=Path, default=None, help="Explicit transcript file or directory")
839
+ ap.add_argument("--limit", type=int, default=6, help="Number of recent sessions to analyze (default 6 for trend split)")
840
+ ap.add_argument("--compare-window", type=int, default=None, help="Compare newest N vs prior N sessions for trend")
841
+ ap.add_argument("--format", choices=["compact", "card", "json"], default="compact")
842
+ args = ap.parse_args(argv)
843
+ rep = audit_sessions(source=args.source, explicit_path=args.path, limit=args.limit, compare_window=args.compare_window)
844
+ if args.format == "json":
845
+ print(json.dumps(rep, indent=2, ensure_ascii=False))
846
+ elif args.format == "card":
847
+ print(format_card_audit(rep))
848
+ else:
849
+ print(format_compact_audit(rep))
850
+ return 0
851
+
852
+
853
+ if __name__ == "__main__":
854
+ raise SystemExit(main())