@alexgreensh/token-optimizer 0.0.0-stage → 5.13.50

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 (161) hide show
  1. package/.claude-plugin/marketplace.json +76 -0
  2. package/.claude-plugin/plugin.json +21 -0
  3. package/LICENSE +130 -0
  4. package/LICENSE-SMALL-BUSINESS.md +62 -0
  5. package/PRIVACY.md +200 -0
  6. package/README.md +13 -2
  7. package/hooks/codex-hooks.json +4 -0
  8. package/hooks/hooks.json +182 -0
  9. package/hooks/module_runner.py +149 -0
  10. package/hooks/posttooluse_runner.py +1110 -0
  11. package/hooks/python-launcher.sh +816 -0
  12. package/hooks/run.py +776 -0
  13. package/hooks/sessionstart_runner.py +629 -0
  14. package/hooks/stop_runner.py +408 -0
  15. package/hooks/userpromptsubmit_runner.py +722 -0
  16. package/hooks/windows-launcher.py +163 -0
  17. package/install-cloud.sh +23 -0
  18. package/package.json +29 -4
  19. package/skills/fleet-auditor/SKILL.md +150 -0
  20. package/skills/fleet-auditor/references/fleet-systems.md +167 -0
  21. package/skills/fleet-auditor/references/report-template.md +50 -0
  22. package/skills/fleet-auditor/references/waste-patterns.md +126 -0
  23. package/skills/fleet-auditor/scripts/fleet.py +3612 -0
  24. package/skills/fleet-auditor/scripts/shared.py +277 -0
  25. package/skills/resume-checkpoint/SKILL.md +52 -0
  26. package/skills/resume-checkpoint/scripts/pull_checkpoint.py +188 -0
  27. package/skills/token-coach/SKILL.md +129 -0
  28. package/skills/token-coach/assets/coach-dashboard-tab.html +45 -0
  29. package/skills/token-coach/examples/coaching-session-agentic.md +62 -0
  30. package/skills/token-coach/examples/coaching-session-heavy-setup.md +46 -0
  31. package/skills/token-coach/examples/coaching-session-new-project.md +38 -0
  32. package/skills/token-coach/references/agentic-systems.md +147 -0
  33. package/skills/token-coach/references/coach-patterns.md +120 -0
  34. package/skills/token-coach/references/coaching-scripts.md +146 -0
  35. package/skills/token-coach/references/deterministic-stages.md +102 -0
  36. package/skills/token-coach/references/keepwarm-consent.md +48 -0
  37. package/skills/token-coach/references/quick-reference.md +155 -0
  38. package/skills/token-dashboard/SKILL.md +72 -0
  39. package/skills/token-optimizer/SKILL.md +150 -0
  40. package/skills/token-optimizer/assets/dashboard.html +7251 -0
  41. package/skills/token-optimizer/examples/claude-md-optimized.md +40 -0
  42. package/skills/token-optimizer/examples/hooks-starter.json +179 -0
  43. package/skills/token-optimizer/examples/permissions-deny-template.json +24 -0
  44. package/skills/token-optimizer/pricing/prices.json +695 -0
  45. package/skills/token-optimizer/references/agent-prompts.md +687 -0
  46. package/skills/token-optimizer/references/cli-reference.md +92 -0
  47. package/skills/token-optimizer/references/codex-workflow.md +188 -0
  48. package/skills/token-optimizer/references/cursor-workflow.md +74 -0
  49. package/skills/token-optimizer/references/error-recovery.md +37 -0
  50. package/skills/token-optimizer/references/implementation-playbook.md +416 -0
  51. package/skills/token-optimizer/references/keepwarm-consent.md +48 -0
  52. package/skills/token-optimizer/references/opencode-workflow.md +72 -0
  53. package/skills/token-optimizer/references/optimization-checklist.md +714 -0
  54. package/skills/token-optimizer/references/phase0-setup.md +142 -0
  55. package/skills/token-optimizer/references/presentation-workflow.md +72 -0
  56. package/skills/token-optimizer/references/session-continuity.md +19 -0
  57. package/skills/token-optimizer/references/token-flow-architecture.md +629 -0
  58. package/skills/token-optimizer/scripts/activity_tracker.py +143 -0
  59. package/skills/token-optimizer/scripts/antigravity_doctor.py +548 -0
  60. package/skills/token-optimizer/scripts/antigravity_hook_bridge.py +511 -0
  61. package/skills/token-optimizer/scripts/antigravity_install.py +376 -0
  62. package/skills/token-optimizer/scripts/antigravity_proto.py +413 -0
  63. package/skills/token-optimizer/scripts/antigravity_session.py +346 -0
  64. package/skills/token-optimizer/scripts/antigravity_state.py +486 -0
  65. package/skills/token-optimizer/scripts/archive_result.py +1725 -0
  66. package/skills/token-optimizer/scripts/bash_compress.py +2490 -0
  67. package/skills/token-optimizer/scripts/bash_compress_hook.py +766 -0
  68. package/skills/token-optimizer/scripts/bash_hook.py +61 -0
  69. package/skills/token-optimizer/scripts/bash_whitelist.py +243 -0
  70. package/skills/token-optimizer/scripts/benchmark.py +1765 -0
  71. package/skills/token-optimizer/scripts/build_output_compress.py +776 -0
  72. package/skills/token-optimizer/scripts/cloud_kit.py +991 -0
  73. package/skills/token-optimizer/scripts/codex_command_compress.py +434 -0
  74. package/skills/token-optimizer/scripts/codex_compact_prompt.py +273 -0
  75. package/skills/token-optimizer/scripts/codex_doctor.py +454 -0
  76. package/skills/token-optimizer/scripts/codex_hook_bridge.py +311 -0
  77. package/skills/token-optimizer/scripts/codex_install.py +810 -0
  78. package/skills/token-optimizer/scripts/codex_io.py +119 -0
  79. package/skills/token-optimizer/scripts/codex_log_index.py +219 -0
  80. package/skills/token-optimizer/scripts/codex_models.py +34 -0
  81. package/skills/token-optimizer/scripts/codex_session.py +1186 -0
  82. package/skills/token-optimizer/scripts/codex_state.py +707 -0
  83. package/skills/token-optimizer/scripts/codex_statusline.py +303 -0
  84. package/skills/token-optimizer/scripts/command_filters.py +386 -0
  85. package/skills/token-optimizer/scripts/compression_backfill.py +600 -0
  86. package/skills/token-optimizer/scripts/compression_log.py +230 -0
  87. package/skills/token-optimizer/scripts/context_intel.py +331 -0
  88. package/skills/token-optimizer/scripts/context_pressure.py +115 -0
  89. package/skills/token-optimizer/scripts/copilot_doctor.py +406 -0
  90. package/skills/token-optimizer/scripts/copilot_hook_bridge.py +709 -0
  91. package/skills/token-optimizer/scripts/copilot_install.py +277 -0
  92. package/skills/token-optimizer/scripts/copilot_session.py +496 -0
  93. package/skills/token-optimizer/scripts/copilot_state.py +569 -0
  94. package/skills/token-optimizer/scripts/copilot_vscode.py +832 -0
  95. package/skills/token-optimizer/scripts/cowork_doctor.py +270 -0
  96. package/skills/token-optimizer/scripts/cowork_install.py +380 -0
  97. package/skills/token-optimizer/scripts/credential_patterns.py +1514 -0
  98. package/skills/token-optimizer/scripts/cursor_doctor.py +602 -0
  99. package/skills/token-optimizer/scripts/cursor_hook_bridge.py +843 -0
  100. package/skills/token-optimizer/scripts/cursor_install.py +423 -0
  101. package/skills/token-optimizer/scripts/cursor_session.py +303 -0
  102. package/skills/token-optimizer/scripts/cursor_state.py +348 -0
  103. package/skills/token-optimizer/scripts/delta_diff.py +110 -0
  104. package/skills/token-optimizer/scripts/detectors/__init__.py +2 -0
  105. package/skills/token-optimizer/scripts/detectors/bad_decomposition.py +78 -0
  106. package/skills/token-optimizer/scripts/detectors/cache_instability.py +504 -0
  107. package/skills/token-optimizer/scripts/detectors/looping.py +88 -0
  108. package/skills/token-optimizer/scripts/detectors/output_waste.py +143 -0
  109. package/skills/token-optimizer/scripts/detectors/overpowered.py +116 -0
  110. package/skills/token-optimizer/scripts/detectors/pdf_ingestion.py +52 -0
  111. package/skills/token-optimizer/scripts/detectors/registry.py +65 -0
  112. package/skills/token-optimizer/scripts/detectors/respond_to_bash.py +76 -0
  113. package/skills/token-optimizer/scripts/detectors/retry_churn.py +83 -0
  114. package/skills/token-optimizer/scripts/detectors/tool_cascade.py +62 -0
  115. package/skills/token-optimizer/scripts/detectors/wasteful_thinking.py +75 -0
  116. package/skills/token-optimizer/scripts/detectors/weak_model.py +55 -0
  117. package/skills/token-optimizer/scripts/detectors/websearch_routing.py +72 -0
  118. package/skills/token-optimizer/scripts/deterministic_candidates.py +1458 -0
  119. package/skills/token-optimizer/scripts/devin_compress.py +790 -0
  120. package/skills/token-optimizer/scripts/devin_doctor.py +403 -0
  121. package/skills/token-optimizer/scripts/devin_hooks.py +453 -0
  122. package/skills/token-optimizer/scripts/devin_install.py +1086 -0
  123. package/skills/token-optimizer/scripts/devin_source.py +119 -0
  124. package/skills/token-optimizer/scripts/devin_state.py +330 -0
  125. package/skills/token-optimizer/scripts/devin_verify.py +67 -0
  126. package/skills/token-optimizer/scripts/grok_doctor.py +560 -0
  127. package/skills/token-optimizer/scripts/grok_hook_bridge.py +699 -0
  128. package/skills/token-optimizer/scripts/grok_install.py +397 -0
  129. package/skills/token-optimizer/scripts/grok_session.py +317 -0
  130. package/skills/token-optimizer/scripts/grok_state.py +299 -0
  131. package/skills/token-optimizer/scripts/hermes_doctor.py +479 -0
  132. package/skills/token-optimizer/scripts/hermes_hook_bridge.py +285 -0
  133. package/skills/token-optimizer/scripts/hermes_install.py +668 -0
  134. package/skills/token-optimizer/scripts/hermes_session.py +691 -0
  135. package/skills/token-optimizer/scripts/hermes_state.py +448 -0
  136. package/skills/token-optimizer/scripts/hook_io.py +120 -0
  137. package/skills/token-optimizer/scripts/hook_runtime.py +713 -0
  138. package/skills/token-optimizer/scripts/injection.py +156 -0
  139. package/skills/token-optimizer/scripts/install_reconcile.py +952 -0
  140. package/skills/token-optimizer/scripts/measure.py +58739 -0
  141. package/skills/token-optimizer/scripts/outline.py +53 -0
  142. package/skills/token-optimizer/scripts/pipeline_analyzer.py +723 -0
  143. package/skills/token-optimizer/scripts/plugin_env.py +562 -0
  144. package/skills/token-optimizer/scripts/py_trust.py +80 -0
  145. package/skills/token-optimizer/scripts/quality_cache_gate.py +320 -0
  146. package/skills/token-optimizer/scripts/read_cache.py +2489 -0
  147. package/skills/token-optimizer/scripts/recovery_output.py +110 -0
  148. package/skills/token-optimizer/scripts/refetch_fingerprint.py +236 -0
  149. package/skills/token-optimizer/scripts/refetch_guard.py +244 -0
  150. package/skills/token-optimizer/scripts/routing_advisor.py +389 -0
  151. package/skills/token-optimizer/scripts/runtime_env.py +1893 -0
  152. package/skills/token-optimizer/scripts/session_store.py +979 -0
  153. package/skills/token-optimizer/scripts/spawn_utils.py +122 -0
  154. package/skills/token-optimizer/scripts/statusline.js +660 -0
  155. package/skills/token-optimizer/scripts/structure_map.py +2880 -0
  156. package/skills/token-optimizer/scripts/structure_map_ts.py +676 -0
  157. package/skills/token-optimizer/scripts/structure_replay.py +1556 -0
  158. package/skills/token-optimizer/scripts/thrash_guard.py +604 -0
  159. package/skills/token-optimizer/scripts/token_estimate.py +80 -0
  160. package/skills/token-optimizer/scripts/tool_search_diagnostic.py +61 -0
  161. package/skills/token-optimizer/scripts/utf8_io.py +219 -0
@@ -0,0 +1,3612 @@
1
+ #!/usr/bin/env python3
2
+ """Fleet Auditor: Cross-Platform Agent Token Waste Auditor.
3
+
4
+ Detects agent systems (Claude Code, Codex, OpenClaw, NanoClaw, Hermes, OpenCode, IronClaw),
5
+ collects token usage data, identifies waste patterns, and recommends fixes with
6
+ dollar savings estimates.
7
+
8
+ Zero external dependencies. Python 3.10+.
9
+
10
+ Usage:
11
+ python3 fleet.py detect # What systems are installed?
12
+ python3 fleet.py scan [--system X] [--days 30] # Collect into fleet.db
13
+ python3 fleet.py audit [--system X] [--days 30] # Waste detection
14
+ python3 fleet.py report [--system X] [--json] # Full report with $ savings
15
+ python3 fleet.py dashboard [--serve] # Generate fleet dashboard
16
+ """
17
+ from __future__ import annotations
18
+
19
+ import json
20
+ import math
21
+ import os
22
+ import re
23
+ import shlex
24
+ import sqlite3
25
+ import subprocess
26
+ import sys
27
+ import time
28
+ from dataclasses import dataclass, field
29
+ from datetime import datetime, timedelta, timezone
30
+ from pathlib import Path
31
+ from typing import Any
32
+
33
+ # Windows console-flash guard. A console-subsystem child spawned from a
34
+ # console-less parent -- which is exactly what the Claude Desktop app is -- makes
35
+ # Windows allocate a BRAND NEW console for it, i.e. the cmd window that flashes
36
+ # on screen. CREATE_NO_WINDOW suppresses that allocation. The attribute only
37
+ # exists on Windows builds of CPython, so getattr(..., 0) makes passing it a
38
+ # no-op everywhere else (creationflags=0 is the documented default).
39
+ _NO_WINDOW = getattr(subprocess, "CREATE_NO_WINDOW", 0)
40
+
41
+ # ---------------------------------------------------------------------------
42
+ # Resolve shared.py: works from skill dir, plugin cache, or standalone
43
+ # ---------------------------------------------------------------------------
44
+ _SCRIPT_DIR = Path(__file__).resolve().parent
45
+ sys.path.insert(0, str(_SCRIPT_DIR))
46
+ _TOKEN_OPTIMIZER_SCRIPT_DIR = _SCRIPT_DIR.parent.parent / "token-optimizer" / "scripts"
47
+ if _TOKEN_OPTIMIZER_SCRIPT_DIR.exists():
48
+ sys.path.insert(0, str(_TOKEN_OPTIMIZER_SCRIPT_DIR))
49
+ from shared import ( # noqa: E402 — must follow sys.path.insert above
50
+ HOME,
51
+ CLAUDE_DIR,
52
+ normalize_model_name,
53
+ iter_jsonl,
54
+ parse_timestamp,
55
+ find_claude_jsonl_files,
56
+ find_subagent_jsonl_files,
57
+ clean_project_name,
58
+ init_sqlite_db,
59
+ estimate_tokens_from_file,
60
+ estimate_tokens_from_text,
61
+ )
62
+
63
+ try: # noqa: E402
64
+ import codex_session # type: ignore
65
+ from runtime_env import codex_home, detect_runtime, runtime_home # type: ignore
66
+ except Exception: # pragma: no cover - optional Codex adapter dependency
67
+ codex_session = None
68
+
69
+ def detect_runtime() -> str:
70
+ return "claude"
71
+
72
+ def runtime_home() -> Path:
73
+ return CLAUDE_DIR
74
+
75
+ def codex_home() -> Path:
76
+ return HOME / ".codex"
77
+
78
+ try: # noqa: E402
79
+ import tomllib
80
+ except ModuleNotFoundError: # pragma: no cover - Python <3.11
81
+ tomllib = None
82
+
83
+
84
+ # Measurements show wrapper overhead is negligible (synced with measure.py)
85
+ SKILL_WRAPPER_OVERHEAD = 0
86
+
87
+ def _estimate_skill_frontmatter_tokens(skill_md: Path) -> int:
88
+ """Estimate tokens of a skill's YAML frontmatter only.
89
+
90
+ Claude Code loads only each skill's frontmatter (name + description)
91
+ into the session at startup. The SKILL.md body is loaded on demand
92
+ when the user invokes the skill via the Skill tool. Measuring the
93
+ full file over-counts overhead by ~10-20x.
94
+
95
+ Adds SKILL_WRAPPER_OVERHEAD (35 tokens) for the boilerplate Claude
96
+ wraps around each skill entry, and enforces a minimum floor of 50
97
+ tokens (matching measure.py's estimate_tokens_from_frontmatter).
98
+
99
+ Falls back to 100 tokens (the documented average) if frontmatter
100
+ cannot be parsed.
101
+ """
102
+ try:
103
+ text = skill_md.read_text(encoding="utf-8", errors="replace")
104
+ except (OSError, PermissionError):
105
+ return 100
106
+ # Strip UTF-8 BOM that Windows editors may insert
107
+ text = text.lstrip('\ufeff')
108
+ if not text.startswith("---"):
109
+ return 100
110
+ # Look for the closing --- after the opening one
111
+ end_idx = text.find("\n---", 4)
112
+ if end_idx == -1:
113
+ return 100
114
+ frontmatter = text[: end_idx + 4]
115
+ return max(estimate_tokens_from_text(frontmatter) + SKILL_WRAPPER_OVERHEAD, 50)
116
+
117
+ # ---------------------------------------------------------------------------
118
+ # Constants
119
+ # ---------------------------------------------------------------------------
120
+
121
+ FLEET_DB_DIR = runtime_home() / "_backups" / "token-optimizer"
122
+ FLEET_DB = FLEET_DB_DIR / "fleet.db"
123
+ FLEET_DASHBOARD_PATH = FLEET_DB_DIR / "fleet-dashboard.html"
124
+
125
+ SCHEMA_VERSION = "1"
126
+
127
+ # ---------------------------------------------------------------------------
128
+ # Pricing (USD per token)
129
+ # ---------------------------------------------------------------------------
130
+
131
+ DEFAULT_PRICING: dict[str, dict[str, float]] = {
132
+ # Claude (Fable 5 / Opus 4.8 / Sonnet 4.6 / Haiku 4.5 pricing, verified 2026-05-30)
133
+ # cache_write = 5-minute TTL (1.25x input); cache_write_1h = 1-hour TTL (2x input).
134
+ "fable": {"input": 10.0/1e6, "output": 50.0/1e6, "cache_read": 1.0/1e6, "cache_write": 12.5/1e6, "cache_write_1h": 20.0/1e6},
135
+ "opus": {"input": 5.0/1e6, "output": 25.0/1e6, "cache_read": 0.5/1e6, "cache_write": 6.25/1e6, "cache_write_1h": 10.0/1e6},
136
+ # Generations priced off-family (verified 2026-09-24): Fable/Mythos 5.1 cache reads are
137
+ # 0.025x input; Opus 5.5 is $4/$20 with 0.05x reads. See _pricing_key().
138
+ "fable-5-1": {"input": 10.0/1e6, "output": 50.0/1e6, "cache_read": 0.25/1e6, "cache_write": 12.5/1e6, "cache_write_1h": 20.0/1e6},
139
+ "opus-5-5": {"input": 4.0/1e6, "output": 20.0/1e6, "cache_read": 0.2/1e6, "cache_write": 5.0/1e6, "cache_write_1h": 8.0/1e6},
140
+ "sonnet": {"input": 3.0/1e6, "output": 15.0/1e6, "cache_read": 0.3/1e6, "cache_write": 3.75/1e6, "cache_write_1h": 6.0/1e6},
141
+ "haiku": {"input": 1.0/1e6, "output": 5.0/1e6, "cache_read": 0.1/1e6, "cache_write": 1.25/1e6, "cache_write_1h": 2.0/1e6},
142
+ "gpt-5-codex": {"input": 1.25/1e6, "output": 10.0/1e6, "cache_read": 0.125/1e6, "cache_write": 0},
143
+ "gpt-5.1-codex": {"input": 1.25/1e6, "output": 10.0/1e6, "cache_read": 0.125/1e6, "cache_write": 0},
144
+ "gpt-5.1-codex-mini": {"input": 0.25/1e6, "output": 2.0/1e6, "cache_read": 0.025/1e6, "cache_write": 0},
145
+ "gpt-5.1": {"input": 1.25/1e6, "output": 10.0/1e6, "cache_read": 0.125/1e6, "cache_write": 0},
146
+ "gpt-5.2": {"input": 1.75/1e6, "output": 14.0/1e6, "cache_read": 0.175/1e6, "cache_write": 0},
147
+ "gpt-5.2-codex": {"input": 1.75/1e6, "output": 14.0/1e6, "cache_read": 0.175/1e6, "cache_write": 0},
148
+ "gpt-5.3-codex": {"input": 1.75/1e6, "output": 14.0/1e6, "cache_read": 0.175/1e6, "cache_write": 0},
149
+ "gpt-5": {"input": 1.25/1e6, "output": 10.0/1e6, "cache_read": 0.125/1e6, "cache_write": 0},
150
+ "gpt-5-mini": {"input": 0.25/1e6, "output": 2.0/1e6, "cache_read": 0.025/1e6, "cache_write": 0},
151
+ "gpt-5-nano": {"input": 0.05/1e6, "output": 0.40/1e6, "cache_read": 0.005/1e6, "cache_write": 0},
152
+ "gpt-5.4": {"input": 2.5/1e6, "output": 15.0/1e6, "cache_read": 0.25/1e6, "cache_write": 0},
153
+ "gpt-5.4-mini": {"input": 0.75/1e6, "output": 4.5/1e6, "cache_read": 0.075/1e6, "cache_write": 0},
154
+ "gpt-5.4-nano": {"input": 0.20/1e6, "output": 1.25/1e6, "cache_read": 0.02/1e6, "cache_write": 0},
155
+ "gpt-5.5": {"input": 5.0/1e6, "output": 30.0/1e6, "cache_read": 0.50/1e6, "cache_write": 0},
156
+ "gpt-5.5-pro": {"input": 30.0/1e6, "output": 180.0/1e6, "cache_read": 30.0/1e6, "cache_write": 0},
157
+ "gpt-6-astra": {"input": 10.0/1e6, "output": 50.0/1e6, "cache_read": 1.0/1e6, "cache_write": 12.50/1e6},
158
+ "gpt-5.6-sol": {"input": 5.0/1e6, "output": 30.0/1e6, "cache_read": 0.50/1e6, "cache_write": 6.25/1e6},
159
+ "gpt-5.6-terra": {"input": 2.0/1e6, "output": 12.0/1e6, "cache_read": 0.20/1e6, "cache_write": 2.50/1e6},
160
+ "gpt-5.6-luna": {"input": 0.20/1e6, "output": 1.20/1e6, "cache_read": 0.02/1e6, "cache_write": 0.25/1e6},
161
+ "gpt-4.1": {"input": 2.0/1e6, "output": 8.0/1e6, "cache_read": 0.50/1e6, "cache_write": 0},
162
+ "gpt-4.1-mini": {"input": 0.40/1e6, "output": 1.60/1e6, "cache_read": 0.10/1e6, "cache_write": 0},
163
+ "gpt-4.1-nano": {"input": 0.10/1e6, "output": 0.40/1e6, "cache_read": 0.025/1e6, "cache_write": 0},
164
+ "gpt-4o": {"input": 2.5/1e6, "output": 10.0/1e6, "cache_read": 1.25/1e6, "cache_write": 0},
165
+ "gpt-4o-mini": {"input": 0.15/1e6, "output": 0.6/1e6, "cache_read": 0.075/1e6, "cache_write": 0},
166
+ "o3-pro": {"input": 20.0/1e6, "output": 80.0/1e6, "cache_read": 5.0/1e6, "cache_write": 0},
167
+ "o3-mini": {"input": 1.10/1e6, "output": 4.40/1e6, "cache_read": 0.55/1e6, "cache_write": 0},
168
+ "o3": {"input": 2.0/1e6, "output": 8.0/1e6, "cache_read": 0.50/1e6, "cache_write": 0},
169
+ "o4-mini": {"input": 1.10/1e6, "output": 4.40/1e6, "cache_read": 0.275/1e6, "cache_write": 0},
170
+ "gemini-3.5-flash": {"input": 1.50/1e6, "output": 9.0/1e6, "cache_read": 0.15/1e6, "cache_write": 0},
171
+ "gemini-3.1-pro-preview": {"input": 2.0/1e6, "output": 12.0/1e6, "cache_read": 0.20/1e6, "cache_write": 0},
172
+ "gemini-3.1-flash-lite": {"input": 0.25/1e6, "output": 1.50/1e6, "cache_read": 0.025/1e6, "cache_write": 0},
173
+ "gemini-3.1-pro": {"input": 2.0/1e6, "output": 12.0/1e6, "cache_read": 0.20/1e6, "cache_write": 0},
174
+ "gemini-3-pro": {"input": 2.0/1e6, "output": 12.0/1e6, "cache_read": 0.20/1e6, "cache_write": 0},
175
+ "gemini-3-flash": {"input": 0.50/1e6, "output": 3.0/1e6, "cache_read": 0.05/1e6, "cache_write": 0},
176
+ "gemini-2.5-pro": {"input": 1.25/1e6, "output": 10.0/1e6, "cache_read": 0.125/1e6, "cache_write": 0},
177
+ "gemini-2.5-flash": {"input": 0.30/1e6, "output": 2.50/1e6, "cache_read": 0.03/1e6, "cache_write": 0},
178
+ "gemini-2.5-flash-lite": {"input": 0.10/1e6, "output": 0.40/1e6, "cache_read": 0.01/1e6, "cache_write": 0},
179
+ }
180
+
181
+ # Sonnet 5 introductory pricing ($2/$10; cache_read 0.2, cache_write 2.5[5m]/4.0[1h]) is in
182
+ # effect through 2026-08-31; the STANDARD rate ($3/$15) resumes 2026-09-01. DEFAULT_PRICING
183
+ # holds the canonical standard card; while the window is open we swap the introductory card in so
184
+ # fleet cost/waste dollars stay accurate today AND flip back automatically at UTC midnight (in
185
+ # lockstep with measure.py + the TS ports). Production reads the wall clock;
186
+ # TOKEN_OPTIMIZER_PRICING_AS_OF (YYYY-MM-DD) pins it for tests. The single "sonnet" bucket cannot
187
+ # isolate Sonnet 5, so Sonnet 4.6 is repriced too (accepted 2026-07-10). Mirrors measure.py.
188
+ _SONNET_STANDARD_RATES = {"input": 3.0/1e6, "output": 15.0/1e6, "cache_read": 0.3/1e6, "cache_write": 3.75/1e6, "cache_write_1h": 6.0/1e6}
189
+ _SONNET_INTRO_RATES = {"input": 2.0/1e6, "output": 10.0/1e6, "cache_read": 0.2/1e6, "cache_write": 2.5/1e6, "cache_write_1h": 4.0/1e6}
190
+ _SONNET_INTRO_PRICING_UNTIL = datetime(2026, 9, 1, tzinfo=timezone.utc)
191
+
192
+
193
+ def _apply_sonnet_intro_pricing(as_of=None):
194
+ """Swap the sonnet card to the introductory rate while it is in effect (idempotent). A naive
195
+ `as_of`/env date is treated as UTC. Returns True when introductory pricing is active."""
196
+ override = os.environ.get("TOKEN_OPTIMIZER_PRICING_AS_OF")
197
+ if as_of is None and override:
198
+ try:
199
+ as_of = datetime.strptime(override, "%Y-%m-%d")
200
+ except ValueError:
201
+ as_of = None
202
+ d = as_of or datetime.now(timezone.utc)
203
+ if d.tzinfo is None:
204
+ d = d.replace(tzinfo=timezone.utc)
205
+ intro = True # date gate retired; $2/$10 is the standard rate
206
+ DEFAULT_PRICING["sonnet"] = dict(_SONNET_INTRO_RATES if intro else _SONNET_STANDARD_RATES)
207
+ return intro
208
+
209
+
210
+ _apply_sonnet_intro_pricing()
211
+
212
+ # gpt-5.6-sol promotional pricing (date-gated). OpenAI documents the $4/$20 rate
213
+ # as "available at least through November 21, 2026." DEFAULT_PRICING holds the
214
+ # STANDARD card ($5/$30); while the promo window is open we swap the promo card
215
+ # in so fleet cost/waste dollars stay accurate today AND flip back automatically
216
+ # after 2026-11-21. Mirrors measure.py _apply_gpt56_sol_promo_pricing.
217
+ _GPT56_SOL_STANDARD_RATES = {"input": 5.0/1e6, "output": 30.0/1e6, "cache_read": 0.50/1e6, "cache_write": 6.25/1e6}
218
+ _GPT56_SOL_PROMO_RATES = {"input": 4.0/1e6, "output": 20.0/1e6, "cache_read": 0.40/1e6, "cache_write": 5.0/1e6}
219
+ _GPT56_SOL_PROMO_UNTIL = datetime(2026, 11, 21, tzinfo=timezone.utc)
220
+
221
+
222
+ def _apply_gpt56_sol_promo_pricing(as_of=None):
223
+ """Swap the gpt-5.6-sol card to the promotional rate while it is in effect (idempotent)."""
224
+ override = os.environ.get("TOKEN_OPTIMIZER_PRICING_AS_OF")
225
+ if as_of is None and override:
226
+ try:
227
+ as_of = datetime.strptime(override, "%Y-%m-%d")
228
+ except ValueError:
229
+ as_of = None
230
+ d = as_of or datetime.now(timezone.utc)
231
+ if d.tzinfo is None:
232
+ d = d.replace(tzinfo=timezone.utc)
233
+ if d < _GPT56_SOL_PROMO_UNTIL:
234
+ DEFAULT_PRICING["gpt-5.6-sol"] = dict(_GPT56_SOL_PROMO_RATES)
235
+ return True
236
+ DEFAULT_PRICING["gpt-5.6-sol"] = dict(_GPT56_SOL_STANDARD_RATES)
237
+ return False
238
+
239
+
240
+ _apply_gpt56_sol_promo_pricing()
241
+
242
+ _pricing_override: dict | None = None
243
+ # Models the user priced themselves in pricing.json: their flat card wins over
244
+ # the bundled over-100K tier (calculate_cost per_request).
245
+ _pricing_override_keys: set[str] = set()
246
+
247
+
248
+ def _load_pricing() -> dict[str, dict[str, float]]:
249
+ """Load pricing with optional user override from pricing.json."""
250
+ global _pricing_override
251
+ if _pricing_override is not None:
252
+ return _pricing_override
253
+
254
+ pricing = dict(DEFAULT_PRICING)
255
+ pricing.update(_bundled_prices())
256
+ _pricing_override_keys.clear()
257
+ override_path = FLEET_DB_DIR / "pricing.json"
258
+ if override_path.exists():
259
+ try:
260
+ with open(override_path, "r", encoding="utf-8") as f:
261
+ user_pricing = json.load(f)
262
+ if not isinstance(user_pricing, dict):
263
+ user_pricing = {}
264
+ for model, rates in user_pricing.items():
265
+ if not isinstance(rates, dict):
266
+ continue
267
+ # Normalize the user's key the same way lookups are normalized, so
268
+ # adding "MiniMax-M3" (the name the unpriced warning shows) actually
269
+ # prices the run keyed as "minimax-m3".
270
+ model = _override_key(str(model))
271
+ merged = {**pricing.get(model, {}), **rates}
272
+ if "cache_write_1h" not in rates and ("input" in rates or "cache_write" in rates):
273
+ if merged.get("input"):
274
+ merged["cache_write_1h"] = merged["input"] * 2
275
+ elif merged.get("cache_write"):
276
+ merged["cache_write_1h"] = merged["cache_write"] * 1.6
277
+ pricing[model] = merged
278
+ _pricing_override_keys.add(model)
279
+ except (json.JSONDecodeError, PermissionError, OSError, TypeError, AttributeError):
280
+ pass
281
+ _pricing_override = pricing
282
+ return pricing
283
+
284
+
285
+ _BUNDLED_PRICES_PATH = Path(__file__).resolve().parent.parent.parent / "token-optimizer" / "pricing" / "prices.json"
286
+ _PRICE_KEY_RE = re.compile(r"^[a-z0-9][a-z0-9._-]{0,63}$")
287
+ _CLAUDE_GENERATION_RE = re.compile(
288
+ r"(fable|mythos|opus|sonnet|haiku)[-._]?(\d+)(?:[-._](\d{1,2}))?(?![0-9])")
289
+ # Claude 3-era ids put the version before the family ("claude-3-5-sonnet-20241022").
290
+ _CLAUDE_LEGACY_ID_RE = re.compile(r"claude-(\d)(?:[-.](\d))?-(opus|sonnet|haiku)(?![a-z])")
291
+
292
+
293
+ def _bundled_prices() -> dict[str, dict[str, float]]:
294
+ """Per-token cards from the auto-refreshed pricing/prices.json (read-only).
295
+
296
+ Same file measure.py reads, so fleet costs never drift from the dashboard.
297
+ Claude generation cards are hyphenated here ("opus_5_5" -> "opus-5-5").
298
+ Returns {} when the file is missing, oversized or malformed.
299
+ """
300
+ try:
301
+ if _BUNDLED_PRICES_PATH.stat().st_size > 2 * 1024 * 1024:
302
+ return {}
303
+ doc = json.loads(_BUNDLED_PRICES_PATH.read_text(encoding="utf-8"))
304
+ except (OSError, ValueError):
305
+ return {}
306
+ if not isinstance(doc, dict) or doc.get("schema") != 1:
307
+ return {}
308
+ out: dict[str, dict[str, float]] = {}
309
+ for section in ("anthropic", "openai", "gemini"):
310
+ cards = doc.get(section)
311
+ if not isinstance(cards, dict):
312
+ continue
313
+ for key, card in cards.items():
314
+ if not isinstance(key, str) or not _PRICE_KEY_RE.match(key) or not isinstance(card, dict):
315
+ continue
316
+ rates = {}
317
+ for field in ("input", "output", "cache_read", "cache_write", "cache_write_1h"):
318
+ v = card.get(field)
319
+ if v is None:
320
+ continue
321
+ if isinstance(v, bool) or not isinstance(v, (int, float)) or not math.isfinite(v) or not 0 <= v <= 1000:
322
+ rates = {}
323
+ break
324
+ rates[field] = float(v) / 1e6
325
+ if "input" not in rates or "output" not in rates:
326
+ continue
327
+ rates.setdefault("cache_read", rates["input"] if section != "anthropic" else rates["input"] * 0.1)
328
+ rates.setdefault("cache_write", rates["input"] * 1.25 if section == "anthropic" else 0.0)
329
+ if section == "anthropic":
330
+ rates.setdefault("cache_write_1h", rates["input"] * 2)
331
+ out[key.replace("_", "-") if section == "anthropic" else key] = rates
332
+ return out
333
+
334
+
335
+ # Claude Haiku 5.5 is priced by prompt length: a single request whose full prompt
336
+ # (input + cache reads + cache writes) is over 100K tokens pays 5x on every rate.
337
+ # Same threshold and cards as measure.py (prices.json "anthropic_long_context").
338
+ ANTHROPIC_LONG_CONTEXT_INPUT_THRESHOLD = 100_000
339
+
340
+
341
+ def _bundled_long_context_prices() -> dict[str, dict[str, float]]:
342
+ """Per-token over-100K Anthropic cards from prices.json, keyed like _bundled_prices."""
343
+ try:
344
+ if _BUNDLED_PRICES_PATH.stat().st_size > 2 * 1024 * 1024:
345
+ return {}
346
+ doc = json.loads(_BUNDLED_PRICES_PATH.read_text(encoding="utf-8"))
347
+ except (OSError, ValueError):
348
+ return {}
349
+ if not isinstance(doc, dict) or doc.get("schema") != 1:
350
+ return {}
351
+ cards = doc.get("anthropic_long_context")
352
+ if not isinstance(cards, dict):
353
+ return {}
354
+ out: dict[str, dict[str, float]] = {}
355
+ for key, card in cards.items():
356
+ if not isinstance(key, str) or not _PRICE_KEY_RE.match(key) or not isinstance(card, dict):
357
+ continue
358
+ rates = {}
359
+ for field in ("input", "output", "cache_read", "cache_write", "cache_write_1h"):
360
+ v = card.get(field)
361
+ if v is None:
362
+ continue
363
+ if isinstance(v, bool) or not isinstance(v, (int, float)) or not math.isfinite(v) or not 0 <= v <= 1000:
364
+ rates = {}
365
+ break
366
+ rates[field] = float(v) / 1e6
367
+ if "input" in rates and "output" in rates:
368
+ rates.setdefault("cache_read", rates["input"] * 0.1)
369
+ rates.setdefault("cache_write", rates["input"] * 1.25)
370
+ rates.setdefault("cache_write_1h", rates["input"] * 2)
371
+ out[key.replace("_", "-")] = rates
372
+ return out
373
+
374
+
375
+ def _claude_generation_key(model_id: str) -> str | None:
376
+ """'claude-opus-5-5' / 'opus-5-5' -> 'opus-5-5'; None when no generation."""
377
+ m = str(model_id or "").lower()
378
+ legacy = _CLAUDE_LEGACY_ID_RE.search(m)
379
+ if legacy:
380
+ major, minor, family = legacy.groups()
381
+ return f"{family}-{major}-{minor}" if minor else f"{family}-{major}"
382
+ g = _CLAUDE_GENERATION_RE.search(m)
383
+ if not g:
384
+ return None
385
+ family, major, minor = g.groups()
386
+ return f"{family}-{major}-{minor}" if minor else f"{family}-{major}"
387
+
388
+
389
+ def _override_key(model_id: str) -> str:
390
+ """Key a user override in pricing.json lands on.
391
+
392
+ Uses the same generation granularity as lookups, so {"opus-5-5": ...}
393
+ reprices Opus 5.5 only, instead of being folded into the "opus" family card
394
+ and silently repricing every other Opus generation.
395
+ """
396
+ return _claude_generation_key(model_id) or normalize_model_name(model_id) or model_id.lower()
397
+
398
+
399
+ # Same families the TS engines prefix-match: any GPT, any o-series, any Gemini.
400
+ _PREFIX_PRICED_RE = re.compile(r"^(gpt-|o\d|gemini-)")
401
+
402
+
403
+ def _pricing_key(model_id: str) -> str:
404
+ """Rate-card key for a raw model id, finer than the family label.
405
+
406
+ Claude generations are priced differently (Opus 5.5 $4/$20, Opus 4.1
407
+ $15/$75, Fable 5.1 cache reads $0.25), so try "opus-5-5", then "opus-5",
408
+ then the family. Other providers match the longest priced id prefix, so a
409
+ dated snapshot prices as its base model. Mirrors measure.py.
410
+ """
411
+ pricing = _load_pricing()
412
+ m = str(model_id or "").lower()
413
+ legacy = _CLAUDE_LEGACY_ID_RE.search(m)
414
+ if legacy:
415
+ major, minor, family = legacy.groups()
416
+ keys = [f"{family}-{major}-{minor}", f"{family}-{major}"] if minor else [f"{family}-{major}"]
417
+ if family == "sonnet":
418
+ keys.append("sonnet-legacy")
419
+ for key in keys:
420
+ if key in pricing:
421
+ return key
422
+ return normalize_model_name(model_id) or model_id
423
+ g = _CLAUDE_GENERATION_RE.search(m)
424
+ if g:
425
+ family, major, minor = g.groups()
426
+ for fam in ((family, "fable") if family == "mythos" else (family,)):
427
+ for key in ((f"{fam}-{major}-{minor}", f"{fam}-{major}") if minor else (f"{fam}-{major}",)):
428
+ if key in pricing:
429
+ return key
430
+ if family == "mythos":
431
+ return "fable"
432
+ else:
433
+ bare = m.rsplit("/", 1)[-1].rsplit(":", 1)[-1]
434
+ for key in sorted(pricing, key=len, reverse=True):
435
+ if _PREFIX_PRICED_RE.match(key) and (bare == key or bare.startswith(key + "-")):
436
+ return key
437
+ return normalize_model_name(model_id) or model_id
438
+
439
+
440
+ def calculate_cost(tokens: "TokenBreakdown", model: str,
441
+ cache_write_1h: int = 0, cache_write_5m: int = 0,
442
+ per_request: bool = False) -> float:
443
+ """Calculate USD cost for a token breakdown at given model rates.
444
+
445
+ ``per_request=True`` says ``tokens`` is ONE API request: a model with an
446
+ over-100K card (Claude Haiku 5.5) then pays it when that request's full
447
+ prompt (input + cache reads + cache writes) exceeds the threshold. Totals
448
+ over many requests must leave it False, or every long session would be
449
+ repriced as if it were a single huge prompt.
450
+
451
+ For Claude models, pass cache_write_1h / cache_write_5m to apply the correct
452
+ per-TTL-tier rate (1h = 2x input; 5m = 1.25x input). When the split is
453
+ unavailable (both 0) the full tokens.cache_write uses the 5m rate.
454
+ """
455
+ pricing = _load_pricing()
456
+ rates = pricing.get(model)
457
+ if not rates:
458
+ return 0.0
459
+ if (per_request and model not in _pricing_override_keys
460
+ and tokens.input + tokens.cache_read + tokens.cache_write
461
+ > ANTHROPIC_LONG_CONTEXT_INPUT_THRESHOLD):
462
+ rates = _bundled_long_context_prices().get(model, rates)
463
+ cost = 0.0
464
+ cost += tokens.input * rates.get("input", 0)
465
+ cost += tokens.output * rates.get("output", 0)
466
+ cost += tokens.cache_read * rates.get("cache_read", 0)
467
+ # Split cache-write cost by TTL tier when data is available.
468
+ if cache_write_1h or cache_write_5m:
469
+ unsplit = max(0, tokens.cache_write - cache_write_1h - cache_write_5m)
470
+ cost += cache_write_1h * rates.get("cache_write_1h", rates.get("cache_write", 0))
471
+ cost += (cache_write_5m + unsplit) * rates.get("cache_write", 0)
472
+ else:
473
+ cost += tokens.cache_write * rates.get("cache_write", 0)
474
+ return cost
475
+
476
+
477
+ def model_is_priced(model: str) -> bool:
478
+ """True when we have a pricing row for ``model``.
479
+
480
+ ``calculate_cost`` returns 0.0 both for genuinely-free usage and for models
481
+ with no pricing row (self-hosted, gateway aliases like ``MiniMax-M3``,
482
+ OpenRouter names). Callers use this to tell "$0 because free" apart from
483
+ "$0 because unpriced" and surface the gap instead of reporting fake $0.
484
+ Model is normalized (lowercased) before lookup so it matches pricing keys.
485
+ """
486
+ return _load_pricing().get(model) is not None
487
+
488
+
489
+ def _recorded_cost(*values) -> float | None:
490
+ """Return the first value that is a REAL recorded cost, else None.
491
+
492
+ A source DB (e.g. Hermes) records its own cost for gateway models our
493
+ pricing table can't price. "Recorded" means present, numeric, finite, and
494
+ >= 0 — a recorded $0 is authoritative (free/comped), NOT an excuse to
495
+ re-price it. Empty strings, None, NaN, inf, negatives, and garbage
496
+ all fall through so the caller can price or flag instead of fabricating or
497
+ crashing on a bad cell.
498
+ """
499
+ for v in values:
500
+ if v is None or v == "":
501
+ continue
502
+ try:
503
+ f = float(v)
504
+ except (TypeError, ValueError):
505
+ continue
506
+ if f >= 0 and math.isfinite(f):
507
+ return f
508
+ return None
509
+
510
+
511
+ def unpriced_summary(runs) -> dict[str, int]:
512
+ """{model: session_count} for runs whose $0 cost is unknown, not free.
513
+
514
+ A run counts when it has real token usage but $0 cost on a model with no
515
+ pricing row — i.e. the $0 is a gap, not a fact. Shared by ``cmd_scan`` and
516
+ ``cmd_audit`` so both surfaces flag the same thing the same way.
517
+
518
+ Known limit: a run whose source DB *recorded* a genuine $0 (comped/free) on an
519
+ unpriced model is over-flagged here — we can't yet tell a recorded $0 from a
520
+ computed-because-unpriced $0 without a cost-source column. The over-warn is
521
+ safe (it points the user at pricing they can add or ignore), not a wrong total.
522
+ """
523
+ out: dict[str, int] = {}
524
+ for r in runs:
525
+ # Require a real model name: an empty/blank model can't be priced OR named
526
+ # in the warning, and the dashboard SQL excludes it (model != '') — skip it
527
+ # here too so all three surfaces agree.
528
+ if not r.model:
529
+ continue
530
+ if r.cost_usd == 0.0 and r.tokens.total > 0 and not model_is_priced(r.model):
531
+ out[r.model] = out.get(r.model, 0) + 1
532
+ return out
533
+
534
+
535
+ # ---------------------------------------------------------------------------
536
+ # Data Model
537
+ # ---------------------------------------------------------------------------
538
+
539
+
540
+ def _with_measure_cli(text: str) -> str:
541
+ """Swap a bare ``python3 measure.py`` in a fix snippet for the resolved script.
542
+
543
+ The sibling token-optimizer skill holds measure.py; when it is not there
544
+ (a standalone fleet-auditor install) the bare form is left as written.
545
+ """
546
+ script = Path(__file__).resolve().parents[2] / "token-optimizer" / "scripts" / "measure.py"
547
+ if not script.is_file():
548
+ return text
549
+ try:
550
+ from refetch_fingerprint import hint_python, shell_path, _windows_hints
551
+ quoted, python = shell_path(str(script)), hint_python()
552
+ windows = _windows_hints()
553
+ except ImportError:
554
+ quoted, python, windows = shlex.quote(str(script)), "python3", False
555
+ # `VAR=x cmd` is Bash only: on Windows the runtime is a leading --runtime flag.
556
+ text = re.sub(
557
+ r"TOKEN_OPTIMIZER_RUNTIME=(\w+) python3 measure\.py",
558
+ (lambda m: f"{python} {quoted} --runtime {m.group(1)}") if windows
559
+ else (lambda m: f"TOKEN_OPTIMIZER_RUNTIME={m.group(1)} {python} {quoted}"),
560
+ text)
561
+ return text.replace("python3 measure.py", f"{python} {quoted}")
562
+
563
+
564
+ @dataclass
565
+ class TokenBreakdown:
566
+ input: int = 0
567
+ output: int = 0
568
+ cache_read: int = 0
569
+ cache_write: int = 0
570
+
571
+ @property
572
+ def total(self) -> int:
573
+ return self.input + self.output + self.cache_read + self.cache_write
574
+
575
+
576
+ @dataclass
577
+ class AgentRun:
578
+ system: str # "claude", "codex", "openclaw", "hermes", "opencode", "nanoclaw", "ironclaw"
579
+ session_id: str = ""
580
+ agent_name: str = ""
581
+ project: str = ""
582
+ timestamp: datetime = field(default_factory=lambda: datetime.now(timezone.utc))
583
+ duration_seconds: float = 0.0
584
+ tokens: TokenBreakdown = field(default_factory=TokenBreakdown)
585
+ cost_usd: float = 0.0
586
+ model: str = "" # Normalized: "opus", "sonnet", "haiku", etc.
587
+ context_window_size: int = 200_000
588
+ run_type: str = "manual" # "heartbeat", "task", "cron", "manual", "delegate"
589
+ outcome: str = "success" # "success", "failure", "empty", "loop", "abandoned"
590
+ message_count: int = 0
591
+ tools_used: list = field(default_factory=list)
592
+ source_path: str = ""
593
+ error_message: str | None = None
594
+ exit_code: int | None = None
595
+
596
+
597
+ @dataclass
598
+ class WasteFinding:
599
+ system: str
600
+ agent_name: str = ""
601
+ waste_type: str = ""
602
+ tier: int = 1
603
+ severity: str = "medium" # "low", "medium", "high", "critical"
604
+ confidence: float = 0.8
605
+ description: str = ""
606
+ monthly_waste_usd: float = 0.0
607
+ monthly_waste_tokens: int = 0
608
+ recommendation: str = ""
609
+ fix_snippet: str = ""
610
+ evidence: dict = field(default_factory=dict)
611
+
612
+
613
+ # ---------------------------------------------------------------------------
614
+ # SQLite Schema
615
+ # ---------------------------------------------------------------------------
616
+
617
+ _FLEET_SCHEMA = """
618
+ CREATE TABLE IF NOT EXISTS fleet_runs (
619
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
620
+ source_path TEXT NOT NULL,
621
+ system TEXT NOT NULL,
622
+ session_id TEXT,
623
+ date TEXT NOT NULL,
624
+ agent_name TEXT,
625
+ project TEXT,
626
+ duration_seconds REAL,
627
+ input_tokens INTEGER,
628
+ output_tokens INTEGER,
629
+ cache_read_tokens INTEGER,
630
+ cache_write_tokens INTEGER,
631
+ cost_usd REAL,
632
+ model TEXT,
633
+ context_window_size INTEGER,
634
+ run_type TEXT,
635
+ outcome TEXT,
636
+ message_count INTEGER,
637
+ error_message TEXT,
638
+ exit_code INTEGER,
639
+ collected_at TEXT,
640
+ UNIQUE(system, source_path, session_id)
641
+ );
642
+
643
+ CREATE TABLE IF NOT EXISTS fleet_waste (
644
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
645
+ system TEXT NOT NULL,
646
+ agent_name TEXT,
647
+ waste_type TEXT NOT NULL,
648
+ tier INTEGER NOT NULL,
649
+ severity TEXT,
650
+ confidence REAL,
651
+ description TEXT,
652
+ monthly_waste_usd REAL,
653
+ monthly_waste_tokens INTEGER,
654
+ recommendation TEXT,
655
+ fix_snippet TEXT,
656
+ evidence_json TEXT,
657
+ detected_at TEXT
658
+ );
659
+
660
+ CREATE TABLE IF NOT EXISTS fleet_daily (
661
+ date TEXT,
662
+ system TEXT,
663
+ run_count INTEGER,
664
+ total_input INTEGER,
665
+ total_output INTEGER,
666
+ total_cost REAL,
667
+ empty_heartbeat_count INTEGER,
668
+ PRIMARY KEY (date, system)
669
+ );
670
+
671
+ CREATE TABLE IF NOT EXISTS fleet_meta (
672
+ key TEXT PRIMARY KEY,
673
+ value TEXT
674
+ );
675
+ """
676
+
677
+
678
+ def _init_fleet_db() -> sqlite3.Connection:
679
+ """Initialize fleet.db with schema and version tracking."""
680
+ conn = init_sqlite_db(FLEET_DB, _FLEET_SCHEMA)
681
+ # Set schema version if not present
682
+ cur = conn.execute("SELECT value FROM fleet_meta WHERE key = 'schema_version'")
683
+ row = cur.fetchone()
684
+ if not row:
685
+ conn.execute(
686
+ "INSERT INTO fleet_meta (key, value) VALUES (?, ?)",
687
+ ("schema_version", SCHEMA_VERSION),
688
+ )
689
+ conn.commit()
690
+ return conn
691
+
692
+
693
+ def _is_run_collected(conn: sqlite3.Connection, system: str, source_path: str, session_id: str) -> bool:
694
+ """Check if a specific run has already been collected."""
695
+ cur = conn.execute(
696
+ "SELECT 1 FROM fleet_runs WHERE system = ? AND source_path = ? AND session_id = ?",
697
+ (system, source_path, session_id),
698
+ )
699
+ return cur.fetchone() is not None
700
+
701
+
702
+ def _insert_run(conn: sqlite3.Connection, run: AgentRun):
703
+ """Insert an AgentRun into fleet_runs."""
704
+ conn.execute(
705
+ """INSERT OR IGNORE INTO fleet_runs
706
+ (source_path, system, session_id, date, agent_name, project,
707
+ duration_seconds, input_tokens, output_tokens, cache_read_tokens,
708
+ cache_write_tokens, cost_usd, model, context_window_size,
709
+ run_type, outcome, message_count, error_message, exit_code, collected_at)
710
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
711
+ (
712
+ run.source_path,
713
+ run.system,
714
+ run.session_id,
715
+ run.timestamp.strftime("%Y-%m-%d"),
716
+ run.agent_name,
717
+ run.project,
718
+ run.duration_seconds,
719
+ run.tokens.input,
720
+ run.tokens.output,
721
+ run.tokens.cache_read,
722
+ run.tokens.cache_write,
723
+ run.cost_usd,
724
+ run.model,
725
+ run.context_window_size,
726
+ run.run_type,
727
+ run.outcome,
728
+ run.message_count,
729
+ run.error_message,
730
+ run.exit_code,
731
+ datetime.now(timezone.utc).isoformat(),
732
+ ),
733
+ )
734
+
735
+
736
+ def _insert_waste(conn: sqlite3.Connection, finding: WasteFinding):
737
+ """Insert a WasteFinding into fleet_waste."""
738
+ conn.execute(
739
+ """INSERT INTO fleet_waste
740
+ (system, agent_name, waste_type, tier, severity, confidence,
741
+ description, monthly_waste_usd, monthly_waste_tokens,
742
+ recommendation, fix_snippet, evidence_json, detected_at)
743
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
744
+ (
745
+ finding.system,
746
+ finding.agent_name,
747
+ finding.waste_type,
748
+ finding.tier,
749
+ finding.severity,
750
+ finding.confidence,
751
+ finding.description,
752
+ finding.monthly_waste_usd,
753
+ finding.monthly_waste_tokens,
754
+ finding.recommendation,
755
+ finding.fix_snippet,
756
+ json.dumps(finding.evidence) if finding.evidence else None,
757
+ datetime.now(timezone.utc).isoformat(),
758
+ ),
759
+ )
760
+
761
+
762
+ def _update_daily_aggregates(conn: sqlite3.Connection):
763
+ """Rebuild fleet_daily from fleet_runs."""
764
+ conn.execute("DELETE FROM fleet_daily")
765
+ conn.execute("""
766
+ INSERT INTO fleet_daily (date, system, run_count, total_input, total_output, total_cost, empty_heartbeat_count)
767
+ SELECT
768
+ date, system,
769
+ COUNT(*) as run_count,
770
+ SUM(input_tokens) as total_input,
771
+ SUM(output_tokens) as total_output,
772
+ SUM(cost_usd) as total_cost,
773
+ SUM(CASE WHEN run_type = 'heartbeat' AND outcome = 'empty' THEN 1 ELSE 0 END) as empty_heartbeat_count
774
+ FROM fleet_runs
775
+ GROUP BY date, system
776
+ """)
777
+ conn.commit()
778
+
779
+
780
+ # ===================================================================
781
+ # ADAPTER PATTERN
782
+ # ===================================================================
783
+
784
+ class BaseAdapter:
785
+ """Base class for agent system adapters.
786
+
787
+ Each adapter implements three methods:
788
+ - detect() -> (bool, float, str): Is this system installed? (found, confidence 0-1, detail)
789
+ - scan(since, conn) -> (list[AgentRun], list[str]): Collect runs since date. Returns (runs, errors).
790
+ - parse_config() -> dict: Extract system configuration for Tier 1 analysis.
791
+ """
792
+
793
+ name: str = "base"
794
+ display_name: str = "Base"
795
+
796
+ def detect(self) -> tuple[bool, float, str]:
797
+ """Detect if this system is installed.
798
+
799
+ Returns (found, confidence, detail_message).
800
+ Confidence: 0.0-1.0 where 1.0 = definitely installed with data.
801
+ """
802
+ return False, 0.0, "Not implemented"
803
+
804
+ def scan(self, since: datetime, conn: sqlite3.Connection | None = None) -> tuple[list[AgentRun], list[str]]:
805
+ """Scan for agent runs since the given datetime.
806
+
807
+ Returns (runs, errors) where errors is a list of non-fatal error messages.
808
+ If conn is provided, skips already-collected runs.
809
+ """
810
+ return [], []
811
+
812
+ def parse_config(self) -> dict:
813
+ """Parse system configuration for Tier 1 waste analysis.
814
+
815
+ Returns dict with system-specific config details like:
816
+ - model settings, skill counts, cron configs, tool definitions
817
+ """
818
+ return {}
819
+
820
+
821
+ class ClaudeCodeAdapter(BaseAdapter):
822
+ """Adapter for Claude Code (~/.claude/projects/)."""
823
+
824
+ name = "claude"
825
+ display_name = "Claude Code"
826
+
827
+ def detect(self) -> tuple[bool, float, str]:
828
+ projects_dir = CLAUDE_DIR / "projects"
829
+ if not projects_dir.exists():
830
+ return False, 0.0, "~/.claude/projects/ not found"
831
+
832
+ # Count JSONL files
833
+ jsonl_count = 0
834
+ for pd in projects_dir.iterdir():
835
+ if pd.is_dir():
836
+ jsonl_count += sum(1 for _ in pd.glob("*.jsonl"))
837
+ if jsonl_count > 5:
838
+ break
839
+
840
+ if jsonl_count == 0:
841
+ return True, 0.3, "~/.claude/projects/ exists but no session logs found"
842
+
843
+ return True, 1.0, f"Found {jsonl_count}+ session logs in ~/.claude/projects/"
844
+
845
+ def scan(self, since: datetime, conn: sqlite3.Connection | None = None) -> tuple[list[AgentRun], list[str]]:
846
+ days = max(1, int((datetime.now(timezone.utc) - since).total_seconds() / 86400) + 1)
847
+ files = find_claude_jsonl_files(days=days)
848
+
849
+ runs = []
850
+ errors = []
851
+
852
+ for filepath, mtime, project_dir_name in files:
853
+ session_id = filepath.stem
854
+
855
+ # Skip already collected
856
+ if conn and _is_run_collected(conn, "claude", str(filepath), session_id):
857
+ continue
858
+
859
+ run = self._parse_session(filepath, project_dir_name)
860
+ if run:
861
+ runs.append(run)
862
+
863
+ # Also scan subagent files
864
+ for sub_path in find_subagent_jsonl_files(filepath):
865
+ sub_id = f"{session_id}/sub/{sub_path.stem}"
866
+ if conn and _is_run_collected(conn, "claude", str(sub_path), sub_id):
867
+ continue
868
+ sub_run = self._parse_session(sub_path, project_dir_name, is_subagent=True, parent_session=session_id)
869
+ if sub_run:
870
+ runs.append(sub_run)
871
+
872
+ return runs, errors
873
+
874
+ def _parse_session(self, filepath: Path, project_dir_name: str,
875
+ is_subagent: bool = False, parent_session: str = "") -> AgentRun | None:
876
+ """Parse a single Claude Code JSONL session file into an AgentRun."""
877
+ total_input = 0
878
+ total_output = 0
879
+ total_cache_read = 0
880
+ total_cache_create = 0
881
+ total_cache_create_1h = 0
882
+ total_cache_create_5m = 0
883
+ exact_cost = 0.0
884
+ model_usage: dict[str, int] = {}
885
+ message_count = 0
886
+ api_calls = 0
887
+ current_req_key: str | None = None
888
+ current_usage: dict[str, Any] | None = None
889
+ tools_used_set: set[str] = set()
890
+ first_ts: datetime | None = None
891
+ last_ts: datetime | None = None
892
+ version = None
893
+
894
+ def add_usage(usage: dict[str, Any]) -> None:
895
+ nonlocal total_input, total_output, total_cache_read, total_cache_create
896
+ nonlocal total_cache_create_1h, total_cache_create_5m, api_calls, exact_cost
897
+ inp_tok = int(usage["input"])
898
+ out_tok = int(usage["output"])
899
+ cr = int(usage["cache_read"])
900
+ cc = int(usage["cache_write"])
901
+ cc_1h = int(usage["cache_write_1h"])
902
+ cc_5m = int(usage["cache_write_5m"])
903
+ total_input += inp_tok
904
+ total_output += out_tok
905
+ total_cache_read += cr
906
+ total_cache_create += cc
907
+ total_cache_create_1h += cc_1h
908
+ total_cache_create_5m += cc_5m
909
+ api_calls += 1
910
+ model_id = str(usage.get("model") or "unknown")
911
+ model_usage[model_id] = model_usage.get(model_id, 0) + inp_tok + cr + cc + out_tok
912
+ exact_cost += calculate_cost(
913
+ TokenBreakdown(input=inp_tok, output=out_tok, cache_read=cr, cache_write=cc),
914
+ _pricing_key(model_id),
915
+ cache_write_1h=cc_1h,
916
+ cache_write_5m=cc_5m,
917
+ per_request=True,
918
+ )
919
+
920
+ def flush_current_usage() -> None:
921
+ nonlocal current_req_key, current_usage
922
+ if current_usage is not None:
923
+ add_usage(current_usage)
924
+ current_req_key = None
925
+ current_usage = None
926
+
927
+ for record in iter_jsonl(filepath):
928
+ # Version
929
+ if version is None:
930
+ v = record.get("version")
931
+ if v:
932
+ version = v
933
+
934
+ # Timestamp
935
+ ts = parse_timestamp(record.get("timestamp"))
936
+ if ts:
937
+ if first_ts is None:
938
+ first_ts = ts
939
+ last_ts = ts
940
+
941
+ rec_type = record.get("type")
942
+
943
+ # Count messages
944
+ if rec_type in ("user", "assistant"):
945
+ message_count += 1
946
+
947
+ # Extract tool usage + token data from assistant messages
948
+ if rec_type == "assistant":
949
+ msg = record.get("message", {})
950
+ content = msg.get("content", [])
951
+ if isinstance(content, list):
952
+ for block in content:
953
+ if isinstance(block, dict) and block.get("type") == "tool_use":
954
+ tools_used_set.add(block.get("name", ""))
955
+
956
+ usage = msg.get("usage", {})
957
+ if usage:
958
+ inp_tok = usage.get("input_tokens", 0) or 0
959
+ out_tok = usage.get("output_tokens", 0) or 0
960
+ cr = usage.get("cache_read_input_tokens", 0) or 0
961
+ # Parse 1h/5m TTL split from cache_creation sub-object or flat keys.
962
+ cache_creation = usage.get("cache_creation", {})
963
+ if not isinstance(cache_creation, dict):
964
+ cache_creation = {}
965
+ cc_1h = (
966
+ cache_creation.get("ephemeral_1h_input_tokens", 0)
967
+ or usage.get("ephemeral_1h_input_tokens", 0)
968
+ or 0
969
+ )
970
+ cc_5m = (
971
+ cache_creation.get("ephemeral_5m_input_tokens", 0)
972
+ or usage.get("ephemeral_5m_input_tokens", 0)
973
+ or 0
974
+ )
975
+ cc = usage.get("cache_creation_input_tokens", 0) or (cc_1h + cc_5m)
976
+ model_id = msg.get("model", "unknown")
977
+ req_id = record.get("requestId")
978
+ current = {
979
+ "input": inp_tok,
980
+ "output": out_tok,
981
+ "cache_read": cr,
982
+ "cache_write": cc,
983
+ "cache_write_1h": cc_1h,
984
+ "cache_write_5m": cc_5m,
985
+ "model": model_id,
986
+ }
987
+ if not req_id:
988
+ flush_current_usage()
989
+ add_usage(current)
990
+ continue
991
+ key = str(req_id)
992
+ if current_req_key != key:
993
+ flush_current_usage()
994
+ current_req_key = key
995
+ current_usage = current
996
+ continue
997
+ previous = current_usage
998
+ if previous is None:
999
+ current_usage = current
1000
+ continue
1001
+ previous["input"] = max(previous["input"], inp_tok)
1002
+ previous["output"] = max(previous["output"], out_tok)
1003
+ previous["cache_read"] = max(previous["cache_read"], cr)
1004
+ previous["cache_write"] = max(previous["cache_write"], cc)
1005
+ previous["cache_write_1h"] = max(previous["cache_write_1h"], cc_1h)
1006
+ previous["cache_write_5m"] = max(previous["cache_write_5m"], cc_5m)
1007
+ if model_id and model_id != "unknown":
1008
+ previous["model"] = model_id
1009
+
1010
+ if message_count == 0:
1011
+ return None
1012
+
1013
+ # Claude Code streaming writes cumulative usage chunks per requestId.
1014
+ # Chunks are emitted consecutively, so keep one in-flight accumulator and
1015
+ # flush it when the request id changes.
1016
+ flush_current_usage()
1017
+
1018
+ # Duration
1019
+ duration_seconds = 0.0
1020
+ if first_ts and last_ts:
1021
+ duration_seconds = max(0.0, (last_ts - first_ts).total_seconds())
1022
+
1023
+ # Dominant model
1024
+ dominant_model_raw = max(model_usage, key=model_usage.get) if model_usage else "unknown"
1025
+ model = normalize_model_name(dominant_model_raw) or dominant_model_raw
1026
+
1027
+ # Context window heuristic
1028
+ context_window = 200_000
1029
+ if model in ("fable", "opus", "sonnet") or "1m" in dominant_model_raw.lower():
1030
+ context_window = 1_000_000
1031
+
1032
+ # input_tokens from API = uncached input only
1033
+ # cache_read_input_tokens = tokens read from cache
1034
+ # cache_creation_input_tokens = tokens written to cache
1035
+ # Total context sent = uncached + cache_read + cache_create
1036
+ # Each priced at its own rate, so store separately.
1037
+ tokens = TokenBreakdown(
1038
+ input=total_input, # Uncached input only
1039
+ output=total_output,
1040
+ cache_read=total_cache_read,
1041
+ cache_write=total_cache_create,
1042
+ )
1043
+
1044
+ # Determine outcome (use total context = uncached + cache_read + cache_create)
1045
+ total_context = total_input + total_cache_read + total_cache_create
1046
+ outcome = "success"
1047
+ if message_count <= 2 and total_output < 200:
1048
+ outcome = "abandoned"
1049
+ elif total_output < 100 and total_context > 50_000:
1050
+ outcome = "empty"
1051
+
1052
+ # Determine run type
1053
+ run_type = "delegate" if is_subagent else "manual"
1054
+
1055
+ cost = calculate_cost(tokens, _pricing_key(dominant_model_raw),
1056
+ cache_write_1h=total_cache_create_1h,
1057
+ cache_write_5m=total_cache_create_5m)
1058
+ if exact_cost > 0:
1059
+ cost = exact_cost
1060
+
1061
+ return AgentRun(
1062
+ system="claude",
1063
+ session_id=filepath.stem if not is_subagent else f"{parent_session}/sub/{filepath.stem}",
1064
+ agent_name="subagent" if is_subagent else "main",
1065
+ project=clean_project_name(project_dir_name),
1066
+ timestamp=first_ts or datetime.now(timezone.utc),
1067
+ duration_seconds=duration_seconds,
1068
+ tokens=tokens,
1069
+ cost_usd=cost,
1070
+ model=model,
1071
+ context_window_size=context_window,
1072
+ run_type=run_type,
1073
+ outcome=outcome,
1074
+ message_count=message_count,
1075
+ tools_used=sorted(tools_used_set),
1076
+ source_path=str(filepath),
1077
+ )
1078
+
1079
+ def parse_config(self) -> dict:
1080
+ """Parse Claude Code configuration for Tier 1 analysis."""
1081
+ config: dict[str, Any] = {
1082
+ "skills": [],
1083
+ "mcp_servers": [],
1084
+ "claude_md_tokens": 0,
1085
+ "memory_md_tokens": 0,
1086
+ "commands": [],
1087
+ "hooks": {},
1088
+ }
1089
+
1090
+ # Skills
1091
+ # Only the YAML frontmatter (name + description) is loaded into the
1092
+ # session at startup. SKILL.md bodies load on demand when the user
1093
+ # invokes the skill. Measuring the full file over-counts by ~10-20x
1094
+ # and inflates skill_bloat findings.
1095
+ skills_dir = CLAUDE_DIR / "skills"
1096
+ if skills_dir.exists():
1097
+ for sd in skills_dir.iterdir():
1098
+ if sd.is_dir():
1099
+ skill_md = sd / "SKILL.md"
1100
+ if skill_md.exists():
1101
+ config["skills"].append({
1102
+ "name": sd.name,
1103
+ "tokens": _estimate_skill_frontmatter_tokens(skill_md),
1104
+ })
1105
+
1106
+ # CLAUDE.md
1107
+ claude_md = CLAUDE_DIR / "CLAUDE.md"
1108
+ if claude_md.exists():
1109
+ config["claude_md_tokens"] = estimate_tokens_from_file(claude_md)
1110
+
1111
+ # MEMORY.md files
1112
+ projects_dir = CLAUDE_DIR / "projects"
1113
+ if projects_dir.exists():
1114
+ for pd in projects_dir.iterdir():
1115
+ mem_file = pd / "memory" / "MEMORY.md"
1116
+ if mem_file.exists():
1117
+ config["memory_md_tokens"] = max(
1118
+ config["memory_md_tokens"],
1119
+ estimate_tokens_from_file(mem_file),
1120
+ )
1121
+
1122
+ # MCP servers from settings
1123
+ settings_path = CLAUDE_DIR / "settings.json"
1124
+ if settings_path.exists():
1125
+ try:
1126
+ with open(settings_path, "r", encoding="utf-8") as f:
1127
+ settings = json.load(f)
1128
+ mcp = settings.get("mcpServers", {})
1129
+ config["mcp_servers"] = list(mcp.keys())
1130
+
1131
+ # Hooks
1132
+ hooks = settings.get("hooks", {})
1133
+ config["hooks"] = hooks
1134
+ except (json.JSONDecodeError, PermissionError):
1135
+ pass
1136
+
1137
+ # Commands
1138
+ cmd_dir = CLAUDE_DIR / "commands"
1139
+ if cmd_dir.exists():
1140
+ for cf in cmd_dir.glob("*.md"):
1141
+ config["commands"].append(cf.stem)
1142
+
1143
+ return config
1144
+
1145
+
1146
+ class CodexAdapter(BaseAdapter):
1147
+ """Adapter for Codex (~/.codex/sessions/ and ~/.codex/archived_sessions/)."""
1148
+
1149
+ name = "codex"
1150
+ display_name = "Codex"
1151
+
1152
+ def detect(self) -> tuple[bool, float, str]:
1153
+ if codex_session is None:
1154
+ return False, 0.0, "Codex parser unavailable"
1155
+ home = codex_home()
1156
+ roots = [home / "sessions", home / "archived_sessions"]
1157
+ if not home.exists():
1158
+ return False, 0.0, "~/.codex/ not found"
1159
+ jsonl_count = 0
1160
+ for root in roots:
1161
+ if root.exists():
1162
+ for _ in root.rglob("*.jsonl"):
1163
+ jsonl_count += 1
1164
+ if jsonl_count > 5:
1165
+ break
1166
+ if jsonl_count > 5:
1167
+ break
1168
+ if jsonl_count == 0:
1169
+ return True, 0.3, "~/.codex/ exists but no session logs found"
1170
+ return True, 1.0, f"Found {jsonl_count}+ session logs in ~/.codex/sessions/"
1171
+
1172
+ def scan(self, since: datetime, conn: sqlite3.Connection | None = None) -> tuple[list[AgentRun], list[str]]:
1173
+ if codex_session is None:
1174
+ return [], ["Codex parser unavailable"]
1175
+ days = max(1, int((datetime.now(timezone.utc) - since).total_seconds() / 86400) + 1)
1176
+ files = codex_session.find_all_jsonl_files(days=days)
1177
+ runs: list[AgentRun] = []
1178
+ errors: list[str] = []
1179
+
1180
+ for filepath, _mtime, project_name in files:
1181
+ session_id = filepath.stem
1182
+ if conn and _is_run_collected(conn, "codex", str(filepath), session_id):
1183
+ continue
1184
+ try:
1185
+ parsed = codex_session.parse_session_jsonl(filepath)
1186
+ except Exception as exc:
1187
+ errors.append(f"{filepath}: {exc}")
1188
+ continue
1189
+ if not parsed:
1190
+ continue
1191
+ run = self._parsed_to_run(filepath, project_name, parsed)
1192
+ if run:
1193
+ runs.append(run)
1194
+ return runs, errors
1195
+
1196
+ def _parsed_to_run(self, filepath: Path, project_name: str, parsed: dict[str, Any]) -> AgentRun | None:
1197
+ input_total = int(parsed.get("total_input_tokens") or 0)
1198
+ cache_read = int(parsed.get("total_cache_read") or 0)
1199
+ output = int(parsed.get("total_output_tokens") or 0)
1200
+ if input_total <= 0 and output <= 0 and int(parsed.get("message_count") or 0) == 0:
1201
+ return None
1202
+
1203
+ model_usage = parsed.get("model_usage") or {}
1204
+ dominant_model_raw = max(model_usage, key=model_usage.get) if model_usage else "codex"
1205
+ model = normalize_model_name(str(dominant_model_raw)) or str(dominant_model_raw)
1206
+ tokens = TokenBreakdown(
1207
+ input=max(0, input_total - cache_read),
1208
+ output=output,
1209
+ cache_read=cache_read,
1210
+ cache_write=int(parsed.get("total_cache_create") or 0),
1211
+ )
1212
+ message_count = int(parsed.get("message_count") or 0)
1213
+ outcome = "success"
1214
+ if message_count <= 2 and output < 200:
1215
+ outcome = "abandoned"
1216
+ elif output < 100 and input_total > 50_000:
1217
+ outcome = "empty"
1218
+
1219
+ first_ts = parse_timestamp(parsed.get("first_ts"))
1220
+ return AgentRun(
1221
+ system="codex",
1222
+ session_id=str(parsed.get("slug") or filepath.stem),
1223
+ agent_name="main",
1224
+ project=project_name or filepath.parent.name,
1225
+ timestamp=first_ts or datetime.fromtimestamp(filepath.stat().st_mtime, timezone.utc),
1226
+ duration_seconds=float(parsed.get("duration_minutes") or 0) * 60,
1227
+ tokens=tokens,
1228
+ cost_usd=calculate_cost(tokens, _pricing_key(str(dominant_model_raw))),
1229
+ model=model,
1230
+ context_window_size=int(parsed.get("model_context_window") or 200_000),
1231
+ run_type="manual",
1232
+ outcome=outcome,
1233
+ message_count=message_count,
1234
+ tools_used=sorted((parsed.get("tool_calls") or {}).keys()),
1235
+ source_path=str(filepath),
1236
+ )
1237
+
1238
+ def parse_config(self) -> dict:
1239
+ config: dict[str, Any] = {
1240
+ "skills": [],
1241
+ "mcp_servers": [],
1242
+ "claude_md_tokens": 0,
1243
+ "instruction_file_label": "AGENTS.md",
1244
+ "memory_md_tokens": 0,
1245
+ "commands": [],
1246
+ "hooks": {},
1247
+ }
1248
+ home = codex_home()
1249
+
1250
+ for base in (home / "skills", home / "plugins" / "cache"):
1251
+ if not base.exists():
1252
+ continue
1253
+ for skill_md in base.rglob("SKILL.md"):
1254
+ config["skills"].append({
1255
+ "name": skill_md.parent.name,
1256
+ "tokens": _estimate_skill_frontmatter_tokens(skill_md),
1257
+ })
1258
+
1259
+ agents_tokens = 0
1260
+ for agents_name in ("AGENTS.override.md", "AGENTS.md"):
1261
+ agents_path = home / agents_name
1262
+ if agents_path.exists():
1263
+ agents_tokens += estimate_tokens_from_file(agents_path)
1264
+ config["claude_md_tokens"] = agents_tokens
1265
+
1266
+ memories_dir = home / "memories"
1267
+ if memories_dir.exists():
1268
+ for mem_file in memories_dir.rglob("*.md"):
1269
+ config["memory_md_tokens"] = max(
1270
+ config["memory_md_tokens"],
1271
+ estimate_tokens_from_file(mem_file),
1272
+ )
1273
+
1274
+ config_path = home / "config.toml"
1275
+ if config_path.exists() and tomllib is not None:
1276
+ try:
1277
+ with config_path.open("rb") as handle:
1278
+ cfg = tomllib.load(handle)
1279
+ mcp = cfg.get("mcp_servers", {})
1280
+ if isinstance(mcp, dict):
1281
+ config["mcp_servers"] = list(mcp.keys())
1282
+ except (OSError, tomllib.TOMLDecodeError):
1283
+ pass
1284
+
1285
+ hooks_path = Path.cwd() / ".codex" / "hooks.json"
1286
+ if hooks_path.exists():
1287
+ try:
1288
+ hooks_data = json.loads(hooks_path.read_text(encoding="utf-8"))
1289
+ hooks = hooks_data.get("hooks", {})
1290
+ config["hooks"] = hooks if isinstance(hooks, dict) else {}
1291
+ except (json.JSONDecodeError, OSError):
1292
+ pass
1293
+
1294
+ return config
1295
+
1296
+
1297
+ # Stubs for Phase 1.5+ adapters
1298
+ class OpenClawAdapter(BaseAdapter):
1299
+ name = "openclaw"
1300
+ display_name = "OpenClaw"
1301
+
1302
+ def detect(self) -> tuple[bool, float, str]:
1303
+ for p in [HOME / ".openclaw", HOME / ".clawdbot", HOME / ".moltbot"]:
1304
+ if p.exists():
1305
+ sessions_json = p / "agents" if (p / "agents").is_dir() else None
1306
+ if sessions_json:
1307
+ return True, 0.8, f"Found {p.name} directory with agents/"
1308
+ return True, 0.4, f"Found {p.name} directory (no agents/ yet)"
1309
+ return False, 0.0, "No OpenClaw directories found"
1310
+
1311
+ def scan(self, since: datetime, conn: sqlite3.Connection | None = None) -> tuple[list[AgentRun], list[str]]:
1312
+ return [], ["OpenClaw fleet collection is not implemented in this Python adapter; use the OpenClaw dashboard for OpenClaw runs."]
1313
+
1314
+
1315
+ class NanoClawAdapter(BaseAdapter):
1316
+ name = "nanoclaw"
1317
+ display_name = "NanoClaw"
1318
+
1319
+ def detect(self) -> tuple[bool, float, str]:
1320
+ nc_dir = HOME / ".nanoclaw"
1321
+ if nc_dir.exists():
1322
+ return True, 0.6, "Found ~/.nanoclaw/"
1323
+ return False, 0.0, "~/.nanoclaw/ not found"
1324
+
1325
+
1326
+ class HermesAdapter(BaseAdapter):
1327
+ name = "hermes"
1328
+ display_name = "Hermes"
1329
+
1330
+ # Columns we read if present. state.db schema drifts across Hermes versions,
1331
+ # so scan() intersects this with the live table and never assumes a column.
1332
+ _WANT_COLUMNS = (
1333
+ "id", "model", "started_at", "ended_at", "end_reason",
1334
+ "message_count", "tool_call_count", "input_tokens", "output_tokens",
1335
+ "cache_read_tokens", "cache_write_tokens", "reasoning_tokens",
1336
+ "estimated_cost_usd", "actual_cost_usd", "cost_status", "cwd", "source",
1337
+ )
1338
+
1339
+ def detect(self) -> tuple[bool, float, str]:
1340
+ state_db = HOME / ".hermes" / "state.db"
1341
+ if state_db.exists():
1342
+ return True, 1.0, "Found ~/.hermes/state.db"
1343
+ hermes_dir = HOME / ".hermes"
1344
+ if hermes_dir.exists():
1345
+ return True, 0.4, "Found ~/.hermes/ (no state.db)"
1346
+ return False, 0.0, "~/.hermes/ not found"
1347
+
1348
+ def scan(self, since: datetime, conn: sqlite3.Connection | None = None) -> tuple[list[AgentRun], list[str]]:
1349
+ """Read runs from ~/.hermes/state.db.
1350
+
1351
+ BaseAdapter.scan() returned ([], []) so Hermes silently reported zero even
1352
+ under heavy use. We open the DB read-only (mode=ro): it can never write to
1353
+ Hermes's own state, and unlike immutable=1 it still reads committed WAL
1354
+ rows, so a scan run against a LIVE Hermes sees its most recent sessions
1355
+ instead of silently dropping everything since the last checkpoint.
1356
+ """
1357
+ state_db = HOME / ".hermes" / "state.db"
1358
+ if not state_db.exists():
1359
+ return [], ["~/.hermes/state.db not found"]
1360
+
1361
+ runs: list[AgentRun] = []
1362
+ errors: list[str] = []
1363
+ db: sqlite3.Connection | None = None
1364
+ try:
1365
+ # as_uri() percent-encodes spaces / reserved chars in the path so a
1366
+ # home dir like "/Users/Alex Green/" doesn't corrupt the URI.
1367
+ db = sqlite3.connect(f"{state_db.as_uri()}?mode=ro", uri=True, timeout=5)
1368
+ db.row_factory = sqlite3.Row
1369
+ available = {r[1] for r in db.execute("PRAGMA table_info(sessions)").fetchall()}
1370
+ if not available:
1371
+ return [], ["~/.hermes/state.db has no 'sessions' table"]
1372
+ cols = [c for c in self._WANT_COLUMNS if c in available]
1373
+ if "id" not in cols or "started_at" not in available:
1374
+ # Without an id / started_at we can't dedup or window; bail loudly
1375
+ # rather than importing every row on every scan.
1376
+ return [], ["~/.hermes/state.db 'sessions' missing id/started_at columns"]
1377
+ since_ts = since.timestamp()
1378
+ rows = db.execute(
1379
+ f"SELECT {', '.join(cols)} FROM sessions WHERE started_at >= ?",
1380
+ (since_ts,),
1381
+ ).fetchall()
1382
+ except sqlite3.Error as exc:
1383
+ return [], [f"~/.hermes/state.db read failed: {exc}"]
1384
+ finally:
1385
+ if db is not None:
1386
+ db.close()
1387
+
1388
+ for row in rows:
1389
+ try:
1390
+ run = self._row_to_run(row, row.keys())
1391
+ except (ValueError, TypeError) as exc:
1392
+ errors.append(f"hermes session {row['id'] if 'id' in row.keys() else '?'}: {exc}")
1393
+ continue
1394
+ if run is None:
1395
+ continue
1396
+ # Re-check the window in Python: a TEXT-stored started_at (older Hermes
1397
+ # schemas) compares lexically against the float bind in the SQL WHERE,
1398
+ # so old rows can leak past it. _row_to_run has already parsed the real
1399
+ # timestamp — trust that, not the storage-class comparison.
1400
+ if run.timestamp and run.timestamp < since:
1401
+ continue
1402
+ if conn and _is_run_collected(conn, "hermes", run.source_path, run.session_id):
1403
+ continue
1404
+ runs.append(run)
1405
+ return runs, errors
1406
+
1407
+ @staticmethod
1408
+ def _to_dt(value) -> datetime | None:
1409
+ """Hermes stores started_at/ended_at as REAL epoch seconds, but older
1410
+ rows or exports may carry an ISO string — accept both."""
1411
+ if value is None or value == "":
1412
+ return None
1413
+ if isinstance(value, (int, float)):
1414
+ try:
1415
+ return datetime.fromtimestamp(float(value), timezone.utc)
1416
+ except (OverflowError, OSError, ValueError):
1417
+ return None
1418
+ return parse_timestamp(str(value))
1419
+
1420
+ def _row_to_run(self, row: sqlite3.Row, keys) -> AgentRun | None:
1421
+ def g(name, default=0):
1422
+ return row[name] if name in keys and row[name] is not None else default
1423
+
1424
+ input_total = int(g("input_tokens"))
1425
+ output = int(g("output_tokens"))
1426
+ cache_read = int(g("cache_read_tokens"))
1427
+ cache_write = int(g("cache_write_tokens"))
1428
+ message_count = int(g("message_count"))
1429
+ if input_total <= 0 and output <= 0 and cache_read <= 0 and message_count == 0:
1430
+ return None
1431
+
1432
+ model_raw = str(g("model", "") or "")
1433
+ model = normalize_model_name(model_raw) or model_raw or "unknown"
1434
+ # Hermes stores input_tokens and cache_read_tokens as SEPARATE columns
1435
+ # (a cache-heavy run has cache_read >> input_tokens), so input_tokens is
1436
+ # already the fresh-input count. Do NOT subtract cache_read — that floored
1437
+ # cache-heavy gateway runs to 0 input, corrupting the very numbers
1438
+ # the pricing guard exists to surface. (Codex's total_input_tokens IS inclusive, hence its
1439
+ # subtraction; Hermes is not.)
1440
+ tokens = TokenBreakdown(
1441
+ input=max(0, input_total),
1442
+ output=output,
1443
+ cache_read=cache_read,
1444
+ cache_write=cache_write,
1445
+ )
1446
+
1447
+ # Prefer Hermes's own recorded cost — it prices gateway models (MiniMax,
1448
+ # Kimi, DeepSeek...) our DEFAULT_PRICING can't, so they don't collapse to a
1449
+ # fake $0. A recorded value (incl. $0) is authoritative; only a
1450
+ # genuinely absent/garbage cost falls back to our table.
1451
+ db_cost = _recorded_cost(g("actual_cost_usd", None), g("estimated_cost_usd", None))
1452
+ cost = db_cost if db_cost is not None else calculate_cost(tokens, _pricing_key(model_raw) if model_raw else model)
1453
+
1454
+ started = self._to_dt(g("started_at", None))
1455
+ ended = self._to_dt(g("ended_at", None))
1456
+ duration = 0.0
1457
+ if started and ended and ended >= started:
1458
+ duration = (ended - started).total_seconds()
1459
+
1460
+ outcome = "success"
1461
+ if message_count <= 2 and output < 200:
1462
+ outcome = "abandoned"
1463
+ elif output < 100 and input_total > 50_000:
1464
+ outcome = "empty"
1465
+
1466
+ cwd = str(g("cwd", "") or "")
1467
+ return AgentRun(
1468
+ system="hermes",
1469
+ session_id=str(g("id", "")),
1470
+ # Keep Hermes's own source label (cli/api/subagent...) instead of
1471
+ # flattening every run to "main" — audit detectors group by agent_name.
1472
+ agent_name=str(g("source", "") or "") or "main",
1473
+ # Full cwd, not just the basename: two projects can share a leaf name
1474
+ # (~/work/foo vs ~/play/foo) and would otherwise merge in the dashboard.
1475
+ project=cwd or "unknown",
1476
+ timestamp=started or datetime.now(timezone.utc),
1477
+ duration_seconds=duration,
1478
+ tokens=tokens,
1479
+ cost_usd=cost,
1480
+ model=model,
1481
+ run_type="manual",
1482
+ outcome=outcome,
1483
+ message_count=message_count,
1484
+ source_path=f"hermes:state.db#{g('id', '')}",
1485
+ )
1486
+
1487
+
1488
+ class OpenCodeAdapter(BaseAdapter):
1489
+ name = "opencode"
1490
+ display_name = "OpenCode"
1491
+
1492
+ def detect(self) -> tuple[bool, float, str]:
1493
+ # Check env var first
1494
+ data_dir = os.environ.get("OPENCODE_DATA_DIR")
1495
+ if data_dir and Path(data_dir).exists():
1496
+ return True, 0.9, f"Found $OPENCODE_DATA_DIR at {data_dir}"
1497
+
1498
+ oc_dir = HOME / ".local" / "share" / "opencode"
1499
+ if oc_dir.exists():
1500
+ return True, 0.8, "Found ~/.local/share/opencode/"
1501
+ appdata = os.environ.get("APPDATA", "")
1502
+ if appdata:
1503
+ win_dir = Path(appdata) / "opencode"
1504
+ if win_dir.exists():
1505
+ return True, 0.8, f"Found {win_dir}"
1506
+ return False, 0.0, "No OpenCode data directory found"
1507
+
1508
+
1509
+ class IronClawAdapter(BaseAdapter):
1510
+ name = "ironclaw"
1511
+ display_name = "IronClaw"
1512
+
1513
+ def detect(self) -> tuple[bool, float, str]:
1514
+ ic_dir = HOME / ".ironclaw"
1515
+ if ic_dir.exists():
1516
+ return True, 0.3, "Found ~/.ironclaw/ (needs connection config for full scan)"
1517
+ return False, 0.0, "~/.ironclaw/ not found"
1518
+
1519
+
1520
+ # Adapter registry
1521
+ ADAPTER_REGISTRY: list[type[BaseAdapter]] = [
1522
+ ClaudeCodeAdapter,
1523
+ CodexAdapter,
1524
+ OpenClawAdapter,
1525
+ NanoClawAdapter,
1526
+ HermesAdapter,
1527
+ OpenCodeAdapter,
1528
+ IronClawAdapter,
1529
+ ]
1530
+
1531
+
1532
+ # ===================================================================
1533
+ # WASTE PATTERN DETECTORS
1534
+ # ===================================================================
1535
+
1536
+ class BaseDetector:
1537
+ """Base class for waste pattern detectors."""
1538
+
1539
+ name: str = ""
1540
+ tier: int = 1
1541
+ description: str = ""
1542
+
1543
+ def detect(self, runs: list[AgentRun], config: dict, system: str) -> list[WasteFinding]:
1544
+ """Run detection and return findings. Empty list = no waste found."""
1545
+ return []
1546
+
1547
+
1548
+ # --- Tier 1: Static Config Analysis ---
1549
+
1550
+ class HeartbeatModelWaste(BaseDetector):
1551
+ """Detect expensive models used for heartbeat/cron runs."""
1552
+ name = "heartbeat_model_waste"
1553
+ tier = 1
1554
+ description = "Expensive model for heartbeat/cron tasks"
1555
+
1556
+ def detect(self, runs: list[AgentRun], config: dict, system: str) -> list[WasteFinding]:
1557
+ findings = []
1558
+ heartbeat_runs = [r for r in runs if r.run_type in ("heartbeat", "cron")]
1559
+ if not heartbeat_runs:
1560
+ return findings
1561
+
1562
+ expensive_hb = [r for r in heartbeat_runs if r.model in ("fable", "opus", "sonnet")]
1563
+ if not expensive_hb:
1564
+ return findings
1565
+
1566
+ total_cost = sum(r.cost_usd for r in expensive_hb)
1567
+ days_spanned = max(1, len({r.timestamp.strftime("%Y-%m-%d") for r in expensive_hb}))
1568
+ monthly_cost = (total_cost / days_spanned) * 30
1569
+
1570
+ # Calculate savings if switched to haiku
1571
+ haiku_cost = 0.0
1572
+ for r in expensive_hb:
1573
+ haiku_cost += calculate_cost(r.tokens, "haiku")
1574
+ haiku_monthly = (haiku_cost / days_spanned) * 30
1575
+ savings = monthly_cost - haiku_monthly
1576
+
1577
+ if savings < 0.10:
1578
+ return findings
1579
+
1580
+ # v5.11.1: derive the "# was:" comment from the actual expensive
1581
+ # heartbeat models found, instead of the hardcoded "opus/sonnet" (which
1582
+ # was wrong whenever the waste was, e.g., fable-only).
1583
+ models_found = sorted({r.model for r in expensive_hb})
1584
+ was_comment = "/".join(models_found) if models_found else "expensive model"
1585
+
1586
+ findings.append(WasteFinding(
1587
+ system=system,
1588
+ waste_type=self.name,
1589
+ tier=self.tier,
1590
+ severity="high" if savings > 5.0 else "medium",
1591
+ confidence=0.9,
1592
+ description=f"{len(expensive_hb)} heartbeat/cron runs using {expensive_hb[0].model} instead of Haiku",
1593
+ monthly_waste_usd=savings,
1594
+ monthly_waste_tokens=sum(r.tokens.total for r in expensive_hb),
1595
+ recommendation=f"Route heartbeat/cron tasks to Haiku. Saves ~${savings:.2f}/month.",
1596
+ fix_snippet=f'# In your agent config, set heartbeat model:\nmodel: "haiku" # was: {was_comment}',
1597
+ evidence={"expensive_count": len(expensive_hb), "models_used": models_found},
1598
+ ))
1599
+ return findings
1600
+
1601
+
1602
+ class SkillBloat(BaseDetector):
1603
+ """Detect too many skills loaded per agent."""
1604
+ name = "skill_bloat"
1605
+ tier = 1
1606
+ description = "Too many skills loaded (~100 tokens each, every API call)"
1607
+
1608
+ def detect(self, runs: list[AgentRun], config: dict, system: str) -> list[WasteFinding]:
1609
+ skills = config.get("skills", [])
1610
+ if len(skills) <= 10:
1611
+ return []
1612
+
1613
+ total_skill_tokens = sum(s.get("tokens", 100) for s in skills)
1614
+ # ~100 tokens per skill per API call, estimate 20 API calls per session average
1615
+ monthly_sessions = 30 # rough estimate
1616
+ monthly_waste = total_skill_tokens * 20 * monthly_sessions
1617
+
1618
+ if system == "codex":
1619
+ monthly_cost = 0.0
1620
+ fix_snippet = _with_measure_cli("# Disable truly stale user skills with:\n# TOKEN_OPTIMIZER_RUNTIME=codex python3 measure.py codex-skill disable --path <skill-dir>")
1621
+ else:
1622
+ cost_per_token = 3.0 / 1e6 # sonnet input rate as baseline
1623
+ monthly_cost = monthly_waste * cost_per_token
1624
+ fix_snippet = _with_measure_cli("# Move unused skills out of ~/.claude/skills/\n# Check which skills you actually use:\n# python3 measure.py trends --days 30")
1625
+
1626
+ return [WasteFinding(
1627
+ system=system,
1628
+ waste_type=self.name,
1629
+ tier=self.tier,
1630
+ severity="medium" if len(skills) <= 20 else "high",
1631
+ confidence=0.8,
1632
+ description=f"{len(skills)} skills loaded ({total_skill_tokens:,} tokens overhead per API call)",
1633
+ monthly_waste_usd=monthly_cost,
1634
+ monthly_waste_tokens=monthly_waste,
1635
+ recommendation="Archive unused skills. Each removed skill saves ~100 tokens per API call across all sessions.",
1636
+ fix_snippet=fix_snippet,
1637
+ evidence={"skill_count": len(skills), "skill_names": [s.get("name", "?") for s in skills]},
1638
+ )]
1639
+
1640
+
1641
+ class ToolDefinitionBloat(BaseDetector):
1642
+ """Detect tool definitions consuming >20% of context."""
1643
+ name = "tool_definition_bloat"
1644
+ tier = 1
1645
+ description = "Tool definitions consuming excessive context"
1646
+
1647
+ def detect(self, runs: list[AgentRun], config: dict, system: str) -> list[WasteFinding]:
1648
+ mcp_servers = config.get("mcp_servers", [])
1649
+ if len(mcp_servers) <= 3:
1650
+ return []
1651
+
1652
+ # Estimate: ~150 tokens per eager tool, ~15 per deferred, ~10 tools per server
1653
+ # Assume 30% eager, 70% deferred after ToolSearch
1654
+ tools_per_server = 10
1655
+ total_tools = len(mcp_servers) * tools_per_server
1656
+ eager_tools = int(total_tools * 0.3)
1657
+ deferred_tools = total_tools - eager_tools
1658
+ tool_tokens = (eager_tools * 150) + (deferred_tools * 15)
1659
+
1660
+ # Check if >20% of smallest likely context window
1661
+ context_pct = (tool_tokens / 200_000) * 100
1662
+ if context_pct < 15:
1663
+ return []
1664
+
1665
+ return [WasteFinding(
1666
+ system=system,
1667
+ waste_type=self.name,
1668
+ tier=self.tier,
1669
+ severity="high" if context_pct > 30 else "medium",
1670
+ confidence=0.6, # Rough estimate
1671
+ description=f"~{len(mcp_servers)} MCP servers with ~{total_tools} tools consuming ~{tool_tokens:,} tokens ({context_pct:.0f}% of 200K context)",
1672
+ monthly_waste_tokens=tool_tokens * 20 * 30, # per call * calls/session * sessions/month
1673
+ monthly_waste_usd=0, # Hard to monetize config overhead accurately
1674
+ recommendation="Disable unused MCP servers. Use ToolSearch (deferred loading) for large tool sets.",
1675
+ fix_snippet=(
1676
+ "# Check which MCP servers are actually used:\n"
1677
+ "# Codex: review ~/.codex/config.toml [mcp_servers]\n"
1678
+ "# Claude Code: review ~/.claude/settings.json mcpServers section"
1679
+ ),
1680
+ evidence={"mcp_count": len(mcp_servers), "servers": mcp_servers[:10]},
1681
+ )]
1682
+
1683
+
1684
+ class MemoryConfigOverhead(BaseDetector):
1685
+ """Detect memory/config files exceeding 5,000 tokens."""
1686
+ name = "memory_config_overhead"
1687
+ tier = 1
1688
+ description = "Injected config files exceeding 5,000 tokens"
1689
+
1690
+ def detect(self, runs: list[AgentRun], config: dict, system: str) -> list[WasteFinding]:
1691
+ findings = []
1692
+
1693
+ instruction_label = config.get("instruction_file_label", "CLAUDE.md")
1694
+ claude_md_tokens = config.get("claude_md_tokens", 0)
1695
+ if claude_md_tokens > 5000:
1696
+ findings.append(WasteFinding(
1697
+ system=system,
1698
+ waste_type=self.name,
1699
+ tier=self.tier,
1700
+ severity="medium" if claude_md_tokens <= 10000 else "high",
1701
+ confidence=0.9,
1702
+ description=f"{instruction_label} is {claude_md_tokens:,} tokens (injected every API call)",
1703
+ monthly_waste_tokens=claude_md_tokens * 20 * 30,
1704
+ monthly_waste_usd=0,
1705
+ recommendation=f"Slim {instruction_label} to <2,000 tokens. Move reference material to files loaded on demand.",
1706
+ fix_snippet=f"# Run token-optimizer for guided {instruction_label} optimization",
1707
+ evidence={"claude_md_tokens": claude_md_tokens},
1708
+ ))
1709
+
1710
+ memory_tokens = config.get("memory_md_tokens", 0)
1711
+ if memory_tokens > 5000:
1712
+ findings.append(WasteFinding(
1713
+ system=system,
1714
+ waste_type=self.name,
1715
+ tier=self.tier,
1716
+ severity="medium",
1717
+ confidence=0.9,
1718
+ description=f"MEMORY.md is {memory_tokens:,} tokens (injected every API call)",
1719
+ monthly_waste_tokens=memory_tokens * 20 * 30,
1720
+ monthly_waste_usd=0,
1721
+ recommendation="Prune MEMORY.md. Keep it under 200 lines. Move details to individual memory files.",
1722
+ evidence={"memory_md_tokens": memory_tokens},
1723
+ ))
1724
+
1725
+ return findings
1726
+
1727
+
1728
+ class StaleCronConfig(BaseDetector):
1729
+ """Detect cron jobs hitting dead or archived repos."""
1730
+ name = "stale_cron"
1731
+ tier = 1
1732
+ description = "Cron jobs configured for non-existent paths"
1733
+
1734
+ def detect(self, runs: list[AgentRun], config: dict, system: str) -> list[WasteFinding]:
1735
+ # Claude Code doesn't have native cron, but hooks can serve as cron-like triggers
1736
+ # This detector is more relevant for OpenClaw/Hermes but we check hook paths here
1737
+ hooks = config.get("hooks", {})
1738
+ if not hooks:
1739
+ return []
1740
+
1741
+ findings = []
1742
+ for hook_name, hook_list in hooks.items():
1743
+ if not isinstance(hook_list, list):
1744
+ continue
1745
+ for hook in hook_list:
1746
+ if not isinstance(hook, dict):
1747
+ continue
1748
+ cmd = hook.get("command", "")
1749
+ # Check if command references a path that doesn't exist
1750
+ if cmd:
1751
+ parts = cmd.split()
1752
+ for part in parts:
1753
+ if part.startswith("/") and not part.startswith("/usr") and not part.startswith("/bin"):
1754
+ if not Path(part).exists() and not part.startswith("$"):
1755
+ findings.append(WasteFinding(
1756
+ system=system,
1757
+ waste_type=self.name,
1758
+ tier=self.tier,
1759
+ severity="low",
1760
+ confidence=0.5,
1761
+ description=f"Hook '{hook_name}' references non-existent path: {part}",
1762
+ recommendation="Remove or fix the hook referencing a dead path.",
1763
+ evidence={"hook": hook_name, "command": cmd, "missing_path": part},
1764
+ ))
1765
+ return findings
1766
+
1767
+
1768
+ class BlockingHookDetector(BaseDetector):
1769
+ """Detect Stop hooks that re-invoke the model via decision:block on every turn."""
1770
+ name = "blocking_hook"
1771
+ tier = 1
1772
+ description = "Stop hook re-invokes model every turn via decision:block"
1773
+
1774
+ def detect(self, runs: list[AgentRun], config: dict, system: str) -> list[WasteFinding]:
1775
+ hooks = config.get("hooks", {})
1776
+ if not hooks:
1777
+ return []
1778
+
1779
+ findings = []
1780
+ for hook_name, hook_list in hooks.items():
1781
+ if not isinstance(hook_list, list):
1782
+ continue
1783
+ for entry in hook_list:
1784
+ # Handle both flat {command: ...} and nested {hooks: [{command: ...}]}
1785
+ cmds_to_check = []
1786
+ if isinstance(entry, dict):
1787
+ if "command" in entry:
1788
+ cmds_to_check.append(entry["command"])
1789
+ for inner in entry.get("hooks", []):
1790
+ if isinstance(inner, dict):
1791
+ cmds_to_check.append(inner.get("command", ""))
1792
+
1793
+ for cmd in cmds_to_check:
1794
+ if not cmd:
1795
+ continue
1796
+ if '"decision"' in cmd and '"block"' in cmd:
1797
+ recent_runs = [r for r in runs
1798
+ if (datetime.now(timezone.utc) - r.timestamp).days <= 30]
1799
+ avg_turns = (sum(r.message_count for r in recent_runs) / max(len(recent_runs), 1)
1800
+ if recent_runs else 20)
1801
+ est_per_turn_tokens = 80
1802
+ est_monthly_cost = 0.0
1803
+ if recent_runs:
1804
+ days = max(1, len({r.timestamp.strftime("%Y-%m-%d") for r in recent_runs}))
1805
+ sessions_per_month = (len(recent_runs) / days) * 30
1806
+ est_monthly_tokens = sessions_per_month * avg_turns * est_per_turn_tokens
1807
+ est_monthly_cost = est_monthly_tokens * 3.0 / 1_000_000
1808
+
1809
+ findings.append(WasteFinding(
1810
+ system=system,
1811
+ waste_type=self.name,
1812
+ tier=self.tier,
1813
+ severity="medium" if est_monthly_cost > 1.0 else "low",
1814
+ confidence=0.8,
1815
+ description=(
1816
+ f"{hook_name} hook uses decision:block, re-invoking the model "
1817
+ f"on every turn (~{est_per_turn_tokens} tok/turn, "
1818
+ f"~{avg_turns:.0f} turns/session)"
1819
+ ),
1820
+ recommendation=(
1821
+ f"Remove the decision:block pattern from the {hook_name} hook. "
1822
+ "Use additionalContext injection instead of blocking+re-invoking."
1823
+ ),
1824
+ evidence={"hook_event": hook_name, "command_preview": cmd[:100]},
1825
+ monthly_waste_tokens=int(est_monthly_cost / 3.0 * 1_000_000),
1826
+ monthly_waste_usd=round(est_monthly_cost, 2),
1827
+ ))
1828
+ if any(kw in cmd for kw in ("curl ", " anthropic", " openai", " gemini")):
1829
+ findings.append(WasteFinding(
1830
+ system=system,
1831
+ waste_type="heavyweight_hook",
1832
+ tier=self.tier,
1833
+ severity="low",
1834
+ confidence=0.6,
1835
+ description=f"{hook_name} hook calls external API on every invocation",
1836
+ recommendation="Consider caching API responses or moving to an async pattern.",
1837
+ evidence={"hook_event": hook_name, "command_preview": cmd[:80]},
1838
+ ))
1839
+ return findings
1840
+
1841
+
1842
+ class HeartbeatOverFrequency(BaseDetector):
1843
+ """Detect heartbeat intervals < 5 minutes."""
1844
+ name = "heartbeat_over_frequency"
1845
+ tier = 1
1846
+ description = "Heartbeat interval too frequent (< 5 minutes)"
1847
+
1848
+ def detect(self, runs: list[AgentRun], config: dict, system: str) -> list[WasteFinding]:
1849
+ heartbeats = sorted(
1850
+ [r for r in runs if r.run_type in ("heartbeat", "cron")],
1851
+ key=lambda r: r.timestamp,
1852
+ )
1853
+ if len(heartbeats) < 3:
1854
+ return []
1855
+
1856
+ # Check intervals between consecutive heartbeats
1857
+ short_intervals = []
1858
+ for i in range(1, len(heartbeats)):
1859
+ gap = (heartbeats[i].timestamp - heartbeats[i - 1].timestamp).total_seconds()
1860
+ if 0 < gap < 300: # Less than 5 minutes
1861
+ short_intervals.append(gap)
1862
+
1863
+ if len(short_intervals) < 3:
1864
+ return []
1865
+
1866
+ avg_interval = sum(short_intervals) / len(short_intervals)
1867
+ # Estimate waste: each heartbeat costs ~input tokens at model rate
1868
+ avg_cost_per_hb = sum(r.cost_usd for r in heartbeats) / len(heartbeats)
1869
+ # How many extra heartbeats per month if interval is X instead of 5min?
1870
+ runs_per_hour_actual = 3600 / avg_interval
1871
+ runs_per_hour_optimal = 3600 / 300 # 12 per hour
1872
+ extra_runs_per_hour = max(0, runs_per_hour_actual - runs_per_hour_optimal)
1873
+ # Assume 16 active hours per day
1874
+ monthly_extra = extra_runs_per_hour * 16 * 30
1875
+ monthly_waste = monthly_extra * avg_cost_per_hb
1876
+
1877
+ if monthly_waste < 0.10:
1878
+ return []
1879
+
1880
+ return [WasteFinding(
1881
+ system=system,
1882
+ waste_type=self.name,
1883
+ tier=self.tier,
1884
+ severity="medium" if monthly_waste < 2.0 else "high",
1885
+ confidence=0.7,
1886
+ description=f"Heartbeats averaging {avg_interval:.0f}s interval ({len(short_intervals)} intervals < 5 min)",
1887
+ monthly_waste_usd=monthly_waste,
1888
+ recommendation=f"Increase heartbeat interval to 5+ minutes. Current average: {avg_interval:.0f}s.",
1889
+ fix_snippet="# Increase heartbeat interval in agent config:\nheartbeat_interval: 300 # 5 minutes",
1890
+ evidence={"avg_interval_seconds": avg_interval, "short_count": len(short_intervals)},
1891
+ )]
1892
+
1893
+
1894
+ # --- Tier 2: Session Log Analysis ---
1895
+
1896
+ class EmptyHeartbeatRuns(BaseDetector):
1897
+ """Detect heartbeat runs with high input but near-zero output."""
1898
+ name = "empty_heartbeat"
1899
+ tier = 2
1900
+ description = "High input, <100 output, no state change (the #1 waste pattern)"
1901
+
1902
+ def detect(self, runs: list[AgentRun], config: dict, system: str) -> list[WasteFinding]:
1903
+ # Look for runs with high total context but near-zero output.
1904
+ # tokens.input = uncached only, so use .total for full context loaded.
1905
+ empty_runs = [
1906
+ r for r in runs
1907
+ if r.tokens.total > 5000 and r.tokens.output < 100 and r.message_count <= 4
1908
+ ]
1909
+
1910
+ if not empty_runs:
1911
+ return []
1912
+
1913
+ # Filter false positives: require substantial context load or explicit "empty" outcome
1914
+ confirmed_empty = [r for r in empty_runs if r.tokens.total > 50_000 or r.outcome == "empty"]
1915
+
1916
+ if len(confirmed_empty) < 2:
1917
+ return []
1918
+
1919
+ total_waste_cost = sum(r.cost_usd for r in confirmed_empty)
1920
+ days = max(1, len({r.timestamp.strftime("%Y-%m-%d") for r in confirmed_empty}))
1921
+ monthly_cost = (total_waste_cost / days) * 30
1922
+ monthly_tokens = sum(r.tokens.total for r in confirmed_empty)
1923
+
1924
+ return [WasteFinding(
1925
+ system=system,
1926
+ waste_type=self.name,
1927
+ tier=self.tier,
1928
+ severity="critical" if monthly_cost > 10 else "high" if monthly_cost > 2 else "medium",
1929
+ confidence=0.85,
1930
+ description=f"{len(confirmed_empty)} empty runs: high context load, near-zero useful output",
1931
+ monthly_waste_usd=monthly_cost,
1932
+ monthly_waste_tokens=monthly_tokens,
1933
+ recommendation="Add guard conditions to skip runs when there's nothing to do. Route idle checks to Haiku.",
1934
+ fix_snippet='# Add early-exit check in heartbeat script:\nif ! has_pending_work; then exit 0; fi',
1935
+ evidence={
1936
+ "empty_count": len(confirmed_empty),
1937
+ "avg_input": int(sum(r.tokens.input for r in confirmed_empty) / len(confirmed_empty)),
1938
+ "avg_output": int(sum(r.tokens.output for r in confirmed_empty) / len(confirmed_empty)),
1939
+ },
1940
+ )]
1941
+
1942
+
1943
+ class SessionHistoryBloat(BaseDetector):
1944
+ """Detect sessions where context grows monotonically without compaction."""
1945
+ name = "session_history_bloat"
1946
+ tier = 2
1947
+ description = "Context tokens growing without compaction"
1948
+
1949
+ def detect(self, runs: list[AgentRun], config: dict, system: str) -> list[WasteFinding]:
1950
+ # Look for long sessions (many messages) with high token totals
1951
+ long_sessions = [r for r in runs if r.message_count > 30 and r.tokens.total > 500_000]
1952
+
1953
+ if not long_sessions:
1954
+ return []
1955
+
1956
+ total_bloat_tokens = sum(r.tokens.input for r in long_sessions)
1957
+ # Estimate what compacted sessions would have cost (roughly 40% savings)
1958
+ savings_tokens = int(total_bloat_tokens * 0.4)
1959
+ days = max(1, len({r.timestamp.strftime("%Y-%m-%d") for r in long_sessions}))
1960
+ if system == "codex":
1961
+ recommendation = "Use /compact at phase boundaries and install Codex compact prompt guidance plus balanced hooks."
1962
+ fix_snippet = _with_measure_cli("TOKEN_OPTIMIZER_RUNTIME=codex python3 measure.py codex-install --project .")
1963
+ else:
1964
+ recommendation = ("Compact earlier than the auto-compact line (about 967K tokens on 1M models unless you set /autocompact): run /compact when the conversation is long or changes topic. "
1965
+ "Set up Smart Compaction for automatic protection.")
1966
+ fix_snippet = _with_measure_cli("# Install Smart Compaction:\npython3 measure.py setup-smart-compact")
1967
+
1968
+ return [WasteFinding(
1969
+ system=system,
1970
+ waste_type=self.name,
1971
+ tier=self.tier,
1972
+ severity="medium",
1973
+ confidence=0.6,
1974
+ description=f"{len(long_sessions)} long sessions without apparent compaction (30+ messages, 500K+ input tokens)",
1975
+ monthly_waste_tokens=int((savings_tokens / days) * 30),
1976
+ recommendation=recommendation,
1977
+ fix_snippet=fix_snippet,
1978
+ evidence={"long_session_count": len(long_sessions), "total_input_tokens": total_bloat_tokens},
1979
+ )]
1980
+
1981
+
1982
+ class LoopDetection(BaseDetector):
1983
+ """Detect sessions with many messages but trivially small output (stuck loops)."""
1984
+ name = "loop_detection"
1985
+ tier = 2
1986
+ description = "Many messages with near-zero output (stuck agent loops)"
1987
+
1988
+ def detect(self, runs: list[AgentRun], config: dict, system: str) -> list[WasteFinding]:
1989
+ # Signal: many messages but almost zero TOTAL output, suggesting the agent
1990
+ # is stuck retrying without producing anything useful.
1991
+ # IMPORTANT: In Claude Code, output_tokens in JSONL only counts text output,
1992
+ # not tool calls. Many productive sessions have low output_tokens because
1993
+ # the real work happens via tool_use blocks. So we need very strict thresholds.
1994
+ # Only flag sessions with truly pathological output: <2 tokens per message average.
1995
+ loop_suspects = [
1996
+ r for r in runs
1997
+ if r.message_count > 20
1998
+ and r.tokens.output < (r.message_count * 2) # <2 tokens output per message
1999
+ and r.tokens.total > 100_000 # Heavy context loaded
2000
+ and r.outcome not in ("empty", "abandoned")
2001
+ and r.run_type == "manual" # Skip subagents (different output patterns)
2002
+ ]
2003
+
2004
+ if len(loop_suspects) < 2:
2005
+ return []
2006
+
2007
+ # Estimate waste: these sessions loaded heavy context for nothing
2008
+ total_waste = sum(r.cost_usd for r in loop_suspects)
2009
+ days = max(1, len({r.timestamp.strftime("%Y-%m-%d") for r in loop_suspects}))
2010
+ monthly_cost = (total_waste / days) * 30
2011
+
2012
+ if monthly_cost < 1.00:
2013
+ return []
2014
+
2015
+ return [WasteFinding(
2016
+ system=system,
2017
+ waste_type=self.name,
2018
+ tier=self.tier,
2019
+ severity="medium" if monthly_cost < 10 else "high",
2020
+ confidence=0.6,
2021
+ description=f"{len(loop_suspects)} sessions with 15+ messages but near-zero output (potential stuck loops)",
2022
+ monthly_waste_usd=monthly_cost,
2023
+ monthly_waste_tokens=sum(r.tokens.total for r in loop_suspects),
2024
+ recommendation="Check these sessions for retry storms or stuck tool calls. Consider adding timeout/loop-break logic.",
2025
+ evidence={
2026
+ "suspect_count": len(loop_suspects),
2027
+ "avg_messages": int(sum(r.message_count for r in loop_suspects) / len(loop_suspects)),
2028
+ "avg_output": int(sum(r.tokens.output for r in loop_suspects) / len(loop_suspects)),
2029
+ },
2030
+ )]
2031
+
2032
+
2033
+ class AbandonedSessions(BaseDetector):
2034
+ """Detect sessions with 1-2 messages then stop (wasted startup cost)."""
2035
+ name = "abandoned_sessions"
2036
+ tier = 2
2037
+ description = "1-2 messages then abandoned (wasted context loading cost)"
2038
+
2039
+ def detect(self, runs: list[AgentRun], config: dict, system: str) -> list[WasteFinding]:
2040
+ abandoned = [
2041
+ r for r in runs
2042
+ if r.message_count <= 2
2043
+ and r.tokens.total > 10_000 # Had significant context loading
2044
+ and r.run_type == "manual" # Not a legitimate heartbeat/cron
2045
+ ]
2046
+
2047
+ if len(abandoned) < 3:
2048
+ return []
2049
+
2050
+ total_waste = sum(r.cost_usd for r in abandoned)
2051
+ days = max(1, len({r.timestamp.strftime("%Y-%m-%d") for r in abandoned}))
2052
+ monthly_cost = (total_waste / days) * 30
2053
+
2054
+ if monthly_cost < 0.20:
2055
+ return []
2056
+
2057
+ return [WasteFinding(
2058
+ system=system,
2059
+ waste_type=self.name,
2060
+ tier=self.tier,
2061
+ severity="low" if monthly_cost < 1.0 else "medium",
2062
+ confidence=0.7,
2063
+ description=f"{len(abandoned)} sessions abandoned after 1-2 messages (startup cost wasted)",
2064
+ monthly_waste_usd=monthly_cost,
2065
+ monthly_waste_tokens=sum(r.tokens.total for r in abandoned),
2066
+ recommendation="Consider batching quick questions into fewer sessions to amortize startup cost.",
2067
+ evidence={"abandoned_count": len(abandoned), "avg_input": int(sum(r.tokens.input for r in abandoned) / len(abandoned))},
2068
+ )]
2069
+
2070
+
2071
+ # Detector registry
2072
+ DETECTOR_REGISTRY: list[type[BaseDetector]] = [
2073
+ # Tier 1: Static Config
2074
+ HeartbeatModelWaste,
2075
+ HeartbeatOverFrequency,
2076
+ BlockingHookDetector,
2077
+ SkillBloat,
2078
+ ToolDefinitionBloat,
2079
+ MemoryConfigOverhead,
2080
+ StaleCronConfig,
2081
+ # Tier 2: Session Analysis
2082
+ EmptyHeartbeatRuns,
2083
+ SessionHistoryBloat,
2084
+ LoopDetection,
2085
+ AbandonedSessions,
2086
+ ]
2087
+
2088
+
2089
+ # ===================================================================
2090
+ # COMMANDS
2091
+ # ===================================================================
2092
+
2093
+ def cmd_detect(args: list[str]):
2094
+ """Detect installed agent systems."""
2095
+ as_json = "--json" in args
2096
+ results = []
2097
+
2098
+ for adapter_cls in ADAPTER_REGISTRY:
2099
+ adapter = adapter_cls()
2100
+ found, confidence, detail = adapter.detect()
2101
+ results.append({
2102
+ "system": adapter.name,
2103
+ "display_name": adapter.display_name,
2104
+ "found": found,
2105
+ "confidence": confidence,
2106
+ "detail": detail,
2107
+ })
2108
+
2109
+ if as_json:
2110
+ print(json.dumps(results, indent=2))
2111
+ return
2112
+
2113
+ found_any = False
2114
+ print("\n Fleet Auditor: System Detection")
2115
+ print(" " + "=" * 40)
2116
+ for r in results:
2117
+ if r["found"]:
2118
+ found_any = True
2119
+ conf_label = "HIGH" if r["confidence"] >= 0.8 else "MEDIUM" if r["confidence"] >= 0.5 else "LOW"
2120
+ print(f" {r['display_name']:15s} [{conf_label}] {r['detail']}")
2121
+ if not found_any:
2122
+ print(" No agent systems detected.")
2123
+ print(" Supported: Claude Code, Codex, OpenClaw, NanoClaw, Hermes, OpenCode, IronClaw")
2124
+ print()
2125
+
2126
+
2127
+ def cmd_scan(args: list[str]):
2128
+ """Collect agent runs into fleet.db."""
2129
+ days = 30
2130
+ target_system = None
2131
+ as_json = "--json" in args
2132
+ quiet = "--quiet" in args or "-q" in args
2133
+
2134
+ for i, a in enumerate(args):
2135
+ if a == "--days" and i + 1 < len(args):
2136
+ try:
2137
+ days = int(args[i + 1])
2138
+ except ValueError:
2139
+ pass
2140
+ elif a == "--system" and i + 1 < len(args):
2141
+ target_system = args[i + 1]
2142
+
2143
+ since = datetime.now(timezone.utc) - timedelta(days=days)
2144
+ conn = _init_fleet_db()
2145
+
2146
+ total_new = 0
2147
+ total_errors = []
2148
+ scan_results = []
2149
+ # Collect every scanned run so we can flag models whose $0 is unknown
2150
+ # (no pricing row), not free — computed once via unpriced_summary() below.
2151
+ all_scanned_runs: list[AgentRun] = []
2152
+
2153
+ for adapter_cls in ADAPTER_REGISTRY:
2154
+ adapter = adapter_cls()
2155
+ if target_system and adapter.name != target_system:
2156
+ continue
2157
+
2158
+ found, confidence, _ = adapter.detect()
2159
+ if not found or confidence < 0.3:
2160
+ continue
2161
+
2162
+ t0 = time.time()
2163
+ runs, errors = adapter.scan(since, conn)
2164
+ elapsed = time.time() - t0
2165
+
2166
+ new_count = 0
2167
+ for run in runs:
2168
+ all_scanned_runs.append(run)
2169
+ if not _is_run_collected(conn, run.system, run.source_path, run.session_id):
2170
+ _insert_run(conn, run)
2171
+ new_count += 1
2172
+
2173
+ conn.commit()
2174
+ total_new += new_count
2175
+ total_errors.extend(errors)
2176
+
2177
+ scan_results.append({
2178
+ "system": adapter.name,
2179
+ "scanned": len(runs),
2180
+ "new": new_count,
2181
+ "errors": len(errors),
2182
+ "elapsed_ms": int(elapsed * 1000),
2183
+ })
2184
+
2185
+ # Update daily aggregates
2186
+ _update_daily_aggregates(conn)
2187
+ conn.close()
2188
+
2189
+ # One warning naming every unpriced model, so a $0.00 total reads as
2190
+ # "unknown, not free" and the user knows where to add rates.
2191
+ unpriced_sessions = unpriced_summary(all_scanned_runs)
2192
+ if unpriced_sessions:
2193
+ names = ", ".join(sorted(unpriced_sessions))
2194
+ n = sum(unpriced_sessions.values())
2195
+ total_errors.append(
2196
+ f"{n} session(s) on {len(unpriced_sessions)} unpriced model(s) ({names}): "
2197
+ f"cost shown as $0.00 is UNKNOWN, not free. Add rates to "
2198
+ f"{FLEET_DB_DIR / 'pricing.json'} to price them."
2199
+ )
2200
+
2201
+ if as_json:
2202
+ print(json.dumps({
2203
+ "total_new": total_new,
2204
+ "systems": scan_results,
2205
+ "errors": total_errors,
2206
+ "unpriced_models": unpriced_sessions,
2207
+ }, indent=2))
2208
+ return
2209
+
2210
+ if not quiet:
2211
+ print(f"\n Fleet Scan: {total_new} new runs collected ({days}-day window)")
2212
+ for sr in scan_results:
2213
+ print(f" {sr['system']:12s} {sr['new']:4d} new / {sr['scanned']:4d} scanned ({sr['elapsed_ms']}ms)")
2214
+ if total_errors:
2215
+ print(f" Warnings: {len(total_errors)}")
2216
+ for e in total_errors[:5]:
2217
+ print(f" - {e}")
2218
+ if unpriced_sessions:
2219
+ names = ", ".join(sorted(unpriced_sessions))
2220
+ n = sum(unpriced_sessions.values())
2221
+ print(f" ⚠ Unpriced: {n} session(s) on {names} priced at $0.00 (unknown, not free).")
2222
+ print(f" Add rates to {FLEET_DB_DIR / 'pricing.json'}.")
2223
+ print()
2224
+
2225
+
2226
+ def cmd_audit(args: list[str]):
2227
+ """Run waste detection on collected data."""
2228
+ days = 30
2229
+ target_system = None
2230
+ as_json = "--json" in args
2231
+ min_confidence = 0.4
2232
+
2233
+ for i, a in enumerate(args):
2234
+ if a == "--days" and i + 1 < len(args):
2235
+ try:
2236
+ days = int(args[i + 1])
2237
+ except ValueError:
2238
+ pass
2239
+ elif a == "--system" and i + 1 < len(args):
2240
+ target_system = args[i + 1]
2241
+
2242
+ # First, ensure we have data
2243
+ if not FLEET_DB.exists():
2244
+ print(" No fleet.db found. Run 'fleet.py scan' first.")
2245
+ sys.exit(1)
2246
+
2247
+ conn = _init_fleet_db()
2248
+
2249
+ # Load runs from DB
2250
+ cutoff = (datetime.now(timezone.utc) - timedelta(days=days)).strftime("%Y-%m-%d")
2251
+ query = "SELECT * FROM fleet_runs WHERE date >= ?"
2252
+ params: list = [cutoff]
2253
+ if target_system:
2254
+ query += " AND system = ?"
2255
+ params.append(target_system)
2256
+
2257
+ rows = conn.execute(query, params).fetchall()
2258
+ col_names = [desc[0] for desc in conn.execute(query, params).description] if rows else []
2259
+
2260
+ # Reconstruct AgentRun objects
2261
+ runs_by_system: dict[str, list[AgentRun]] = {}
2262
+ for row in rows:
2263
+ rd = dict(zip(col_names, row))
2264
+ system = rd["system"]
2265
+ run = AgentRun(
2266
+ system=system,
2267
+ session_id=rd.get("session_id", ""),
2268
+ agent_name=rd.get("agent_name", ""),
2269
+ project=rd.get("project", ""),
2270
+ timestamp=datetime.fromisoformat(rd["date"]) if rd.get("date") else datetime.now(timezone.utc),
2271
+ duration_seconds=rd.get("duration_seconds", 0) or 0,
2272
+ tokens=TokenBreakdown(
2273
+ input=rd.get("input_tokens", 0) or 0,
2274
+ output=rd.get("output_tokens", 0) or 0,
2275
+ cache_read=rd.get("cache_read_tokens", 0) or 0,
2276
+ cache_write=rd.get("cache_write_tokens", 0) or 0,
2277
+ ),
2278
+ cost_usd=rd.get("cost_usd", 0) or 0,
2279
+ model=rd.get("model", ""),
2280
+ context_window_size=rd.get("context_window_size", 200_000) or 200_000,
2281
+ run_type=rd.get("run_type", "manual") or "manual",
2282
+ outcome=rd.get("outcome", "success") or "success",
2283
+ message_count=rd.get("message_count", 0) or 0,
2284
+ tools_used=[],
2285
+ source_path=rd.get("source_path", ""),
2286
+ error_message=rd.get("error_message"),
2287
+ exit_code=rd.get("exit_code"),
2288
+ )
2289
+ runs_by_system.setdefault(system, []).append(run)
2290
+
2291
+ # The dashboard/audit repro: flag runs priced at $0 only
2292
+ # because the model is unpriced, so the audit doesn't present a fake $0 total.
2293
+ audit_unpriced = unpriced_summary([r for rs in runs_by_system.values() for r in rs])
2294
+
2295
+ # Clear old waste findings
2296
+ conn.execute("DELETE FROM fleet_waste")
2297
+
2298
+ # Run detectors per system
2299
+ all_findings: list[WasteFinding] = []
2300
+
2301
+ for system, system_runs in runs_by_system.items():
2302
+ # Get config for Tier 1 detectors
2303
+ config = {}
2304
+ for adapter_cls in ADAPTER_REGISTRY:
2305
+ if adapter_cls.name == system:
2306
+ config = adapter_cls().parse_config()
2307
+ break
2308
+
2309
+ for detector_cls in DETECTOR_REGISTRY:
2310
+ detector = detector_cls()
2311
+ findings = detector.detect(system_runs, config, system)
2312
+ for f in findings:
2313
+ if f.confidence >= min_confidence:
2314
+ all_findings.append(f)
2315
+ _insert_waste(conn, f)
2316
+
2317
+ conn.commit()
2318
+ conn.close()
2319
+
2320
+ if as_json:
2321
+ output = []
2322
+ for f in all_findings:
2323
+ output.append({
2324
+ "system": f.system,
2325
+ "waste_type": f.waste_type,
2326
+ "tier": f.tier,
2327
+ "severity": f.severity,
2328
+ "confidence": f.confidence,
2329
+ "description": f.description,
2330
+ "monthly_waste_usd": f.monthly_waste_usd,
2331
+ "monthly_waste_tokens": f.monthly_waste_tokens,
2332
+ "recommendation": f.recommendation,
2333
+ "fix_snippet": f.fix_snippet,
2334
+ "evidence": f.evidence,
2335
+ })
2336
+ # Keep the documented list contract; unpriced surfaces in the text report
2337
+ # and in `scan --json` (machine-readable there).
2338
+ print(json.dumps(output, indent=2))
2339
+ return
2340
+
2341
+ # Text report
2342
+ print("\n Fleet Audit: Waste Pattern Analysis")
2343
+ print(" " + "=" * 50)
2344
+ if audit_unpriced:
2345
+ names = ", ".join(sorted(audit_unpriced))
2346
+ n = sum(audit_unpriced.values())
2347
+ print(f" ⚠ Unpriced: {n} session(s) on {names} counted at $0.00 (unknown, not free).")
2348
+ print(f" Costs and waste figures below UNDERSTATE these. Add rates to {FLEET_DB_DIR / 'pricing.json'}.")
2349
+
2350
+ if not all_findings:
2351
+ print(" No waste patterns detected. Your fleet looks clean!")
2352
+ print()
2353
+ return
2354
+
2355
+ # Sort by monthly waste (highest first), then severity
2356
+ severity_rank = {"critical": 0, "high": 1, "medium": 2, "low": 3}
2357
+ all_findings.sort(key=lambda f: (severity_rank.get(f.severity, 4), -f.monthly_waste_usd))
2358
+
2359
+ total_monthly_waste = sum(f.monthly_waste_usd for f in all_findings)
2360
+
2361
+ for i, f in enumerate(all_findings, 1):
2362
+ print(f"\n {i}. [{f.severity.upper():8s}] {f.description}")
2363
+ print(f" System: {f.system} | Tier {f.tier} | Confidence: {f.confidence:.0%}")
2364
+ if f.monthly_waste_usd > 0:
2365
+ print(f" Est. waste: ${f.monthly_waste_usd:.2f}/month")
2366
+ if f.monthly_waste_tokens > 0:
2367
+ print(f" Tokens: {f.monthly_waste_tokens:,}/month")
2368
+ print(f" Fix: {f.recommendation}")
2369
+ if f.fix_snippet:
2370
+ for line in f.fix_snippet.split("\n"):
2371
+ print(f" {line}")
2372
+
2373
+ if total_monthly_waste > 0:
2374
+ print(f"\n {'=' * 50}")
2375
+ print(f" Total estimated waste: ${total_monthly_waste:.2f}/month")
2376
+ print()
2377
+
2378
+
2379
+ def cmd_report(args: list[str]):
2380
+ """Generate a full fleet report combining scan + audit data."""
2381
+ days = 30
2382
+ target_system = None
2383
+ as_json = "--json" in args
2384
+
2385
+ for i, a in enumerate(args):
2386
+ if a == "--days" and i + 1 < len(args):
2387
+ try:
2388
+ days = int(args[i + 1])
2389
+ except ValueError:
2390
+ pass
2391
+ elif a == "--system" and i + 1 < len(args):
2392
+ target_system = args[i + 1]
2393
+
2394
+ if not FLEET_DB.exists():
2395
+ print(" No fleet.db found. Run 'fleet.py scan' first.")
2396
+ sys.exit(1)
2397
+
2398
+ conn = _init_fleet_db()
2399
+ cutoff = (datetime.now(timezone.utc) - timedelta(days=days)).strftime("%Y-%m-%d")
2400
+
2401
+ # Summary stats
2402
+ where = "WHERE date >= ?"
2403
+ params: list = [cutoff]
2404
+ if target_system:
2405
+ where += " AND system = ?"
2406
+ params.append(target_system)
2407
+
2408
+ stats = conn.execute(f"""
2409
+ SELECT
2410
+ system,
2411
+ COUNT(*) as runs,
2412
+ SUM(input_tokens) as total_input,
2413
+ SUM(output_tokens) as total_output,
2414
+ SUM(cost_usd) as total_cost,
2415
+ SUM(CASE WHEN outcome = 'empty' THEN 1 ELSE 0 END) as empty_runs,
2416
+ SUM(CASE WHEN outcome = 'abandoned' THEN 1 ELSE 0 END) as abandoned_runs,
2417
+ AVG(duration_seconds) as avg_duration,
2418
+ COUNT(DISTINCT date) as active_days
2419
+ FROM fleet_runs
2420
+ {where}
2421
+ GROUP BY system
2422
+ """, params).fetchall()
2423
+
2424
+ # Waste findings
2425
+ waste_rows = conn.execute("""
2426
+ SELECT system, waste_type, severity, description, monthly_waste_usd, recommendation
2427
+ FROM fleet_waste
2428
+ ORDER BY monthly_waste_usd DESC
2429
+ """).fetchall()
2430
+
2431
+ conn.close()
2432
+
2433
+ if as_json:
2434
+ report = {
2435
+ "period_days": days,
2436
+ "systems": [],
2437
+ "waste_findings": [],
2438
+ "total_cost": 0,
2439
+ "total_waste": 0,
2440
+ }
2441
+ for row in stats:
2442
+ system_data = {
2443
+ "system": row[0], "runs": row[1],
2444
+ "total_input": row[2] or 0, "total_output": row[3] or 0,
2445
+ "total_cost": row[4] or 0, "empty_runs": row[5] or 0,
2446
+ "abandoned_runs": row[6] or 0, "avg_duration_s": row[7] or 0,
2447
+ "active_days": row[8] or 0,
2448
+ }
2449
+ report["systems"].append(system_data)
2450
+ report["total_cost"] += system_data["total_cost"]
2451
+ for wr in waste_rows:
2452
+ report["waste_findings"].append({
2453
+ "system": wr[0], "type": wr[1], "severity": wr[2],
2454
+ "description": wr[3], "monthly_waste_usd": wr[4] or 0,
2455
+ "recommendation": wr[5],
2456
+ })
2457
+ report["total_waste"] += wr[4] or 0
2458
+ print(json.dumps(report, indent=2))
2459
+ return
2460
+
2461
+ # Text report
2462
+ print("\n Fleet Report")
2463
+ print(" " + "=" * 60)
2464
+ print(f" Period: last {days} days")
2465
+
2466
+ total_cost = 0.0
2467
+ total_runs = 0
2468
+
2469
+ for row in stats:
2470
+ system, runs, inp, out, cost, empty, abandoned, avg_dur, active_days = row
2471
+ cost = cost or 0
2472
+ total_cost += cost
2473
+ total_runs += runs
2474
+
2475
+ adapter_name = system
2476
+ for ac in ADAPTER_REGISTRY:
2477
+ if ac.name == system:
2478
+ adapter_name = ac.display_name
2479
+ break
2480
+
2481
+ print(f"\n {adapter_name}")
2482
+ print(f" Runs: {runs} ({active_days or 0} active days)")
2483
+ print(f" Tokens: {(inp or 0):,} input / {(out or 0):,} output")
2484
+ print(f" Cost: ${cost:.2f}")
2485
+ if empty:
2486
+ print(f" Empty runs: {empty} ({empty/runs*100:.0f}%)")
2487
+ if abandoned:
2488
+ print(f" Abandoned: {abandoned}")
2489
+ if avg_dur:
2490
+ print(f" Avg duration: {avg_dur/60:.1f} min")
2491
+
2492
+ print(f"\n {'=' * 60}")
2493
+ print(f" Total: {total_runs} runs, ${total_cost:.2f}")
2494
+
2495
+ if waste_rows:
2496
+ total_waste = sum((wr[4] or 0) for wr in waste_rows)
2497
+ print(f"\n Waste detected: ${total_waste:.2f}/month potential savings")
2498
+ print(" Run 'fleet.py audit' for detailed recommendations.")
2499
+ print()
2500
+
2501
+
2502
+ def cmd_dashboard(args: list[str]):
2503
+ """Generate and open the fleet dashboard."""
2504
+ serve = "--serve" in args
2505
+ serve_port = 8080
2506
+ serve_host = "127.0.0.1"
2507
+
2508
+ for i, a in enumerate(args):
2509
+ if a == "--port" and i + 1 < len(args):
2510
+ try:
2511
+ serve_port = int(args[i + 1])
2512
+ except ValueError:
2513
+ pass
2514
+ elif a == "--host" and i + 1 < len(args):
2515
+ serve_host = args[i + 1]
2516
+
2517
+ if not FLEET_DB.exists():
2518
+ print(" No fleet.db found. Run 'fleet.py scan' first.")
2519
+ sys.exit(1)
2520
+
2521
+ # Load data for dashboard
2522
+ conn = _init_fleet_db()
2523
+ daily_rows = conn.execute(
2524
+ "SELECT date, system, run_count, total_input, total_output, total_cost, empty_heartbeat_count "
2525
+ "FROM fleet_daily ORDER BY date"
2526
+ ).fetchall()
2527
+
2528
+ waste_rows = conn.execute(
2529
+ "SELECT system, waste_type, tier, severity, confidence, description, "
2530
+ "monthly_waste_usd, monthly_waste_tokens, recommendation, fix_snippet "
2531
+ "FROM fleet_waste ORDER BY monthly_waste_usd DESC"
2532
+ ).fetchall()
2533
+
2534
+ system_stats = conn.execute("""
2535
+ SELECT system, COUNT(*), SUM(cost_usd), SUM(input_tokens), SUM(output_tokens),
2536
+ AVG(duration_seconds), COUNT(DISTINCT date),
2537
+ SUM(CASE WHEN outcome='empty' THEN 1 ELSE 0 END),
2538
+ SUM(CASE WHEN outcome='abandoned' THEN 1 ELSE 0 END)
2539
+ FROM fleet_runs GROUP BY system
2540
+ """).fetchall()
2541
+
2542
+ # Model mix per system
2543
+ model_mix = conn.execute("""
2544
+ SELECT system, model, COUNT(*), SUM(cost_usd)
2545
+ FROM fleet_runs WHERE model IS NOT NULL AND model != ''
2546
+ GROUP BY system, model ORDER BY SUM(cost_usd) DESC
2547
+ """).fetchall()
2548
+
2549
+ # Top projects by cost
2550
+ top_projects = conn.execute("""
2551
+ SELECT project, COUNT(*), SUM(cost_usd), SUM(input_tokens + cache_read_tokens + cache_write_tokens)
2552
+ FROM fleet_runs WHERE project IS NOT NULL AND project != ''
2553
+ GROUP BY project ORDER BY SUM(cost_usd) DESC LIMIT 10
2554
+ """).fetchall()
2555
+
2556
+ # Models with real tokens but $0 cost because they have no pricing row.
2557
+ # Surface them so the dashboard's Total Cost reads as understated, not real.
2558
+ # NULL-safe: `cost_usd = 0` alone would drop NULL-cost rows (SQL NULL equality),
2559
+ # and a single NULL token column would NULL the whole row's `a+b+c+d` sum. Per-
2560
+ # column SUM ignores NULLs, and OR-IS-NULL matches audit's `... or 0` coercion.
2561
+ unpriced_rows = conn.execute("""
2562
+ SELECT model, COUNT(*),
2563
+ SUM(COALESCE(input_tokens, 0)) + SUM(COALESCE(output_tokens, 0))
2564
+ + SUM(COALESCE(cache_read_tokens, 0)) + SUM(COALESCE(cache_write_tokens, 0))
2565
+ FROM fleet_runs
2566
+ WHERE (cost_usd = 0 OR cost_usd IS NULL) AND model IS NOT NULL AND model != ''
2567
+ GROUP BY model
2568
+ """).fetchall()
2569
+ unpriced_models = {
2570
+ r[0]: r[1] for r in unpriced_rows
2571
+ if (r[2] or 0) > 0 and not model_is_priced(r[0])
2572
+ }
2573
+
2574
+ conn.close()
2575
+
2576
+ # Generate dashboard HTML
2577
+ dashboard_html = _generate_dashboard_html(
2578
+ daily_rows, waste_rows, system_stats, model_mix, top_projects, unpriced_models)
2579
+
2580
+ FLEET_DASHBOARD_PATH.parent.mkdir(parents=True, exist_ok=True)
2581
+ # Atomic: write a sibling temp file and rename it onto the final path.
2582
+ # The old truncate-in-place write meant a second invocation could hand the
2583
+ # browser (still resolving the file association from the first one) a
2584
+ # zero-byte or half-written page, and on Windows a reader holding the file
2585
+ # without FILE_SHARE_WRITE made the truncate raise. os.replace is atomic on
2586
+ # POSIX and MoveFileExW+REPLACE_EXISTING on Windows.
2587
+ _tmp_dashboard = FLEET_DASHBOARD_PATH.with_name(
2588
+ FLEET_DASHBOARD_PATH.name + f".tmp.{os.getpid()}"
2589
+ )
2590
+ try:
2591
+ with open(_tmp_dashboard, "w", encoding="utf-8") as f:
2592
+ f.write(dashboard_html)
2593
+ os.replace(_tmp_dashboard, FLEET_DASHBOARD_PATH)
2594
+ except BaseException:
2595
+ try:
2596
+ _tmp_dashboard.unlink()
2597
+ except OSError:
2598
+ pass
2599
+ raise
2600
+
2601
+ print(f" Fleet dashboard generated: {FLEET_DASHBOARD_PATH}")
2602
+
2603
+ if serve:
2604
+ _serve_dashboard(serve_host, serve_port)
2605
+ else:
2606
+ _open_in_browser(FLEET_DASHBOARD_PATH)
2607
+
2608
+
2609
+ def _generate_dashboard_html(daily_rows, waste_rows, system_stats, model_mix, top_projects,
2610
+ unpriced_models=None) -> str:
2611
+ """Generate standalone fleet dashboard HTML matching Token Optimizer design system."""
2612
+ import html as html_mod
2613
+ unpriced_models = unpriced_models or {}
2614
+
2615
+ # Prepare data
2616
+ daily_data = [{"date": r[0], "system": r[1], "runs": r[2], "input": r[3] or 0,
2617
+ "output": r[4] or 0, "cost": r[5] or 0, "empty_hb": r[6] or 0} for r in daily_rows]
2618
+
2619
+ waste_data = [{"system": r[0], "type": r[1], "tier": r[2], "severity": r[3], "confidence": r[4],
2620
+ "description": r[5], "monthly_usd": r[6] or 0, "monthly_tokens": r[7] or 0,
2621
+ "recommendation": r[8], "fix": r[9] or ""} for r in waste_rows]
2622
+
2623
+ systems_data = [{"system": r[0], "runs": r[1], "cost": r[2] or 0, "input": r[3] or 0,
2624
+ "output": r[4] or 0, "avg_dur": r[5] or 0, "active_days": r[6] or 0,
2625
+ "empty": r[7] or 0, "abandoned": r[8] or 0} for r in system_stats]
2626
+
2627
+ # Model mix grouped by system
2628
+ model_data = {}
2629
+ for r in model_mix:
2630
+ model_data.setdefault(r[0], []).append({"model": r[1], "runs": r[2], "cost": r[3] or 0})
2631
+
2632
+ project_data = [{"project": r[0], "runs": r[1], "cost": r[2] or 0, "tokens": r[3] or 0} for r in top_projects]
2633
+
2634
+ total_cost = sum(s["cost"] for s in systems_data)
2635
+ total_waste = sum(w["monthly_usd"] for w in waste_data)
2636
+ total_runs = sum(s["runs"] for s in systems_data)
2637
+ total_active_days = max((s["active_days"] for s in systems_data), default=0)
2638
+ sev_counts = {"critical": 0, "high": 0, "medium": 0, "low": 0}
2639
+ for w in waste_data:
2640
+ sev_counts[w["severity"]] = sev_counts.get(w["severity"], 0) + 1
2641
+
2642
+ def esc(s):
2643
+ return html_mod.escape(str(s))
2644
+
2645
+ def fmt_tokens(n):
2646
+ if n >= 1_000_000_000:
2647
+ return f"{n/1e9:.1f}B"
2648
+ if n >= 1_000_000:
2649
+ return f"{n/1e6:.1f}M"
2650
+ if n >= 1_000:
2651
+ return f"{n/1e3:.1f}K"
2652
+ return str(n)
2653
+
2654
+ def fmt_cost(n):
2655
+ if n >= 1000:
2656
+ return f"${n:,.0f}"
2657
+ return f"${n:.2f}"
2658
+
2659
+ # System display names
2660
+ sys_names = {ac.name: ac.display_name for ac in [cls() for cls in ADAPTER_REGISTRY]}
2661
+
2662
+ # Daily chart data as JSON
2663
+ daily_json = json.dumps(daily_data)
2664
+ model_json = json.dumps(model_data)
2665
+
2666
+ # Build system cards
2667
+ sys_html = ""
2668
+ for s in systems_data:
2669
+ name = sys_names.get(s["system"], s["system"])
2670
+ pct_empty = (s["empty"] / s["runs"] * 100) if s["runs"] > 0 else 0
2671
+ sys_html += f'''
2672
+ <div class="card">
2673
+ <div class="card-header"><span>{esc(name)}</span><span class="label">{esc(s["system"])}</span></div>
2674
+ <div class="metric-large">{fmt_cost(s["cost"])}</div>
2675
+ <div class="metric-sub">{s["runs"]:,} runs over {s["active_days"]} days</div>
2676
+ <div class="mini-stats">
2677
+ <div class="mini-stat-item"><span class="mini-val">{s["avg_dur"]/60:.0f}m</span><span class="mini-label">avg duration</span></div>
2678
+ <div class="mini-stat-item"><span class="mini-val">{pct_empty:.0f}%</span><span class="mini-label">empty runs</span></div>
2679
+ <div class="mini-stat-item"><span class="mini-val">{s["abandoned"]}</span><span class="mini-label">abandoned</span></div>
2680
+ </div>
2681
+ </div>'''
2682
+
2683
+ # Build waste cards
2684
+ waste_html = ""
2685
+ severity_colors = {"critical": "var(--c-danger)", "high": "var(--c-warning)", "medium": "var(--c-accent-cyan)", "low": "var(--c-text-dim)"}
2686
+ for i, w in enumerate(waste_data):
2687
+ waste_html += f'''
2688
+ <div class="waste-card {esc(w["severity"])}">
2689
+ <div class="waste-header">
2690
+ <div>
2691
+ <span class="waste-severity {esc(w["severity"])}">{esc(w["severity"])}</span>
2692
+ <span class="waste-system">{esc(sys_names.get(w["system"], w["system"]))}</span>
2693
+ </div>
2694
+ {f'<span class="waste-savings">{fmt_cost(w["monthly_usd"])}/mo</span>' if w["monthly_usd"] > 0.01 else ''}
2695
+ </div>
2696
+ <div class="waste-desc">{esc(w["description"])}</div>
2697
+ <div class="waste-rec">{esc(w["recommendation"])}</div>
2698
+ {f'<div class="waste-fix">{esc(w["fix"])}</div>' if w["fix"] else ''}
2699
+ </div>'''
2700
+
2701
+ # Build project rows
2702
+ proj_html = ""
2703
+ for p in project_data[:8]:
2704
+ proj_html += f'''
2705
+ <div class="proj-row">
2706
+ <span class="proj-name">{esc(p["project"])}</span>
2707
+ <span class="proj-stat">{p["runs"]:,} runs</span>
2708
+ <span class="proj-stat">{fmt_tokens(p["tokens"])} tok</span>
2709
+ <span class="proj-cost">{fmt_cost(p["cost"])}</span>
2710
+ </div>'''
2711
+
2712
+ # Banner + Total-Cost asterisk when unpriced models are present, so the
2713
+ # dollar figure isn't read as complete/real.
2714
+ unpriced_banner = ""
2715
+ cost_asterisk = ""
2716
+ if unpriced_models:
2717
+ n_sessions = sum(unpriced_models.values())
2718
+ names = ", ".join(esc(m) for m in sorted(unpriced_models))
2719
+ cost_asterisk = "*"
2720
+ unpriced_banner = f'''
2721
+ <div class="unpriced-banner">
2722
+ <strong>&#9888; Cost is understated.</strong>
2723
+ {n_sessions} session(s) ran on {len(unpriced_models)} model(s) with no pricing data
2724
+ ({names}), counted here as <strong>$0.00 &mdash; unknown, not free</strong>.
2725
+ Add rates to <code>{esc(str(FLEET_DB_DIR / "pricing.json"))}</code> to price them.
2726
+ </div>'''
2727
+
2728
+ # Main dashboard link
2729
+ main_dash = FLEET_DB_DIR / "dashboard.html"
2730
+ back_link = f'<a class="nav-item nav-back" href="file://{main_dash}">Token Optimizer</a>' if main_dash.exists() else ''
2731
+
2732
+ return f'''<!DOCTYPE html>
2733
+ <html lang="en">
2734
+ <head>
2735
+ <meta charset="UTF-8">
2736
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
2737
+ <title>Fleet Auditor</title>
2738
+ <link rel="preconnect" href="https://fonts.googleapis.com">
2739
+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
2740
+ <link href="https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@300;500&family=Space+Grotesk:wght@300;400;500;600;700&display=swap" rel="stylesheet">
2741
+ <style>
2742
+ *, *::before, *::after {{ box-sizing: border-box; margin: 0; padding: 0; outline: none; }}
2743
+ :root {{
2744
+ --c-bg: #0a0b10;
2745
+ --c-surface: #13151a;
2746
+ --c-surface-hover: #1c1f26;
2747
+ --c-accent-cyan: #00f0ff;
2748
+ --c-accent-blue: #0066ff;
2749
+ --c-accent-glow: rgba(0, 240, 255, 0.4);
2750
+ --c-text-main: #ffffff;
2751
+ --c-text-dim: #7d8ca3;
2752
+ --c-border: rgba(255, 255, 255, 0.08);
2753
+ --c-success: #22c55e;
2754
+ --c-warning: #f59e0b;
2755
+ --c-danger: #ef4444;
2756
+ --font-sans: 'Space Grotesk', sans-serif;
2757
+ --font-mono: 'JetBrains Mono', monospace;
2758
+ --s-1: 4px; --s-2: 8px; --s-3: 16px; --s-4: 24px; --s-5: 32px; --s-6: 64px;
2759
+ --glow-sm: 0 0 10px var(--c-accent-glow);
2760
+ --glow-text: 0 0 8px rgba(0, 240, 255, 0.6);
2761
+ }}
2762
+ body {{
2763
+ background-color: var(--c-bg);
2764
+ color: var(--c-text-main);
2765
+ font-family: var(--font-sans);
2766
+ font-weight: 300;
2767
+ font-size: 18px;
2768
+ line-height: 1.5;
2769
+ min-height: 100vh;
2770
+ overflow-x: hidden;
2771
+ -webkit-font-smoothing: antialiased;
2772
+ background-image: radial-gradient(circle at 50% 0%, #1a253a 0%, var(--c-bg) 60%);
2773
+ }}
2774
+ body::before {{
2775
+ content: "";
2776
+ position: fixed;
2777
+ top: 0; left: 0; width: 100%; height: 100%;
2778
+ background-image:
2779
+ linear-gradient(rgba(255,255,255,0.03) 1px, transparent 1px),
2780
+ linear-gradient(90deg, rgba(255,255,255,0.03) 1px, transparent 1px);
2781
+ background-size: 40px 40px;
2782
+ pointer-events: none;
2783
+ z-index: 0;
2784
+ }}
2785
+ h1, h2, h3, h4 {{ font-weight: 400; }}
2786
+ ::-webkit-scrollbar {{ width: 6px; }}
2787
+ ::-webkit-scrollbar-track {{ background: var(--c-bg); }}
2788
+ ::-webkit-scrollbar-thumb {{ background: #333; border-radius: 3px; }}
2789
+ ::-webkit-scrollbar-thumb:hover {{ background: #555; }}
2790
+
2791
+ .layout {{
2792
+ display: grid;
2793
+ grid-template-columns: 260px 1fr 340px;
2794
+ height: 100vh;
2795
+ width: 100vw;
2796
+ max-width: 1800px;
2797
+ margin: 0 auto;
2798
+ position: relative;
2799
+ z-index: 1;
2800
+ }}
2801
+
2802
+ /* NAV */
2803
+ .nav-col {{
2804
+ padding: var(--s-4);
2805
+ border-right: 1px solid var(--c-border);
2806
+ display: flex;
2807
+ flex-direction: column;
2808
+ justify-content: space-between;
2809
+ background: linear-gradient(90deg, transparent, rgba(0,0,0,0.2));
2810
+ backdrop-filter: blur(10px);
2811
+ }}
2812
+ .brand {{
2813
+ font-family: var(--font-sans);
2814
+ font-weight: 700;
2815
+ font-size: 24px;
2816
+ margin-bottom: var(--s-5);
2817
+ display: flex;
2818
+ align-items: center;
2819
+ gap: var(--s-2);
2820
+ color: var(--c-text-main);
2821
+ letter-spacing: -0.02em;
2822
+ }}
2823
+ .brand span {{
2824
+ width: 12px; height: 12px;
2825
+ background: var(--c-accent-cyan);
2826
+ border-radius: 2px;
2827
+ display: inline-block;
2828
+ box-shadow: var(--glow-sm);
2829
+ }}
2830
+ .nav-menu {{ display: flex; flex-direction: column; gap: 2px; }}
2831
+ .nav-item {{
2832
+ padding: 12px var(--s-2);
2833
+ cursor: pointer;
2834
+ opacity: 0.6;
2835
+ transition: all 0.3s cubic-bezier(0.2, 0.8, 0.2, 1);
2836
+ text-decoration: none;
2837
+ color: var(--c-text-main);
2838
+ display: flex;
2839
+ justify-content: space-between;
2840
+ align-items: center;
2841
+ font-family: var(--font-sans);
2842
+ text-transform: uppercase;
2843
+ letter-spacing: 0.1em;
2844
+ font-size: 15px;
2845
+ border-left: 2px solid transparent;
2846
+ }}
2847
+ .nav-item:hover, .nav-item.active {{
2848
+ opacity: 1;
2849
+ background: linear-gradient(90deg, rgba(0,240,255,0.05), transparent);
2850
+ border-left-color: var(--c-accent-cyan);
2851
+ text-shadow: var(--glow-text);
2852
+ }}
2853
+ .nav-item.active {{ font-weight: 600; }}
2854
+ .nav-badge {{
2855
+ font-family: var(--font-mono);
2856
+ font-size: 13px;
2857
+ color: var(--c-accent-cyan);
2858
+ border: 1px solid var(--c-accent-cyan);
2859
+ padding: 0 4px;
2860
+ border-radius: 2px;
2861
+ text-shadow: 0 0 5px var(--c-accent-cyan);
2862
+ }}
2863
+ .nav-separator {{
2864
+ height: 1px;
2865
+ background: var(--c-border);
2866
+ margin: var(--s-2) 0;
2867
+ }}
2868
+ .nav-back {{
2869
+ opacity: 0.4;
2870
+ font-size: 13px;
2871
+ margin-top: var(--s-3);
2872
+ border-left: 2px solid transparent;
2873
+ }}
2874
+ .nav-back:hover {{ opacity: 0.8; border-left-color: var(--c-text-dim); }}
2875
+ .user-profile {{
2876
+ font-size: 15px;
2877
+ color: var(--c-text-dim);
2878
+ border-top: 1px solid var(--c-border);
2879
+ padding-top: var(--s-3);
2880
+ font-family: var(--font-mono);
2881
+ }}
2882
+ .user-profile i {{ font-style: italic; color: var(--c-accent-cyan); }}
2883
+
2884
+ /* MAIN */
2885
+ .main-col {{
2886
+ padding: var(--s-5);
2887
+ overflow-y: auto;
2888
+ display: flex;
2889
+ flex-direction: column;
2890
+ gap: var(--s-5);
2891
+ }}
2892
+ .view {{ display: none; }}
2893
+ .view.active {{ display: flex; flex-direction: column; gap: var(--s-5); }}
2894
+ .section-header {{ margin-bottom: var(--s-2); }}
2895
+ .label {{
2896
+ font-size: 14px;
2897
+ text-transform: uppercase;
2898
+ letter-spacing: 0.15em;
2899
+ color: var(--c-text-dim);
2900
+ font-family: var(--font-mono);
2901
+ font-weight: 500;
2902
+ }}
2903
+ .section-header h1 {{
2904
+ font-family: var(--font-sans);
2905
+ font-weight: 300;
2906
+ font-size: 48px;
2907
+ margin: var(--s-2) 0;
2908
+ line-height: 1;
2909
+ letter-spacing: -0.02em;
2910
+ background: linear-gradient(180deg, #fff, #aaa);
2911
+ -webkit-background-clip: text;
2912
+ -webkit-text-fill-color: transparent;
2913
+ }}
2914
+ .section-header p {{
2915
+ font-size: 12px;
2916
+ color: var(--c-text-dim);
2917
+ max-width: 460px;
2918
+ line-height: 1.6;
2919
+ font-family: var(--font-mono);
2920
+ }}
2921
+
2922
+ /* CARDS */
2923
+ .card {{
2924
+ background: var(--c-surface);
2925
+ border: 1px solid var(--c-border);
2926
+ border-radius: 12px;
2927
+ padding: var(--s-4);
2928
+ transition: border-color 0.3s;
2929
+ }}
2930
+ .card:hover {{ border-color: rgba(255,255,255,0.15); }}
2931
+ .card-header {{
2932
+ display: flex;
2933
+ justify-content: space-between;
2934
+ align-items: center;
2935
+ margin-bottom: var(--s-3);
2936
+ font-size: 15px;
2937
+ }}
2938
+ .card-header span:first-child {{ font-weight: 500; }}
2939
+ .dashboard-grid {{
2940
+ display: grid;
2941
+ grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
2942
+ gap: var(--s-3);
2943
+ }}
2944
+ .metric-large {{
2945
+ font-family: var(--font-mono);
2946
+ font-size: 36px;
2947
+ font-weight: 500;
2948
+ color: var(--c-accent-cyan);
2949
+ text-shadow: var(--glow-text);
2950
+ margin-bottom: var(--s-1);
2951
+ }}
2952
+ .metric-sub {{
2953
+ font-size: 13px;
2954
+ color: var(--c-text-dim);
2955
+ font-family: var(--font-mono);
2956
+ }}
2957
+ .mini-stats {{
2958
+ display: flex;
2959
+ gap: var(--s-4);
2960
+ margin-top: var(--s-3);
2961
+ padding-top: var(--s-3);
2962
+ border-top: 1px solid var(--c-border);
2963
+ }}
2964
+ .mini-stat-item {{ display: flex; flex-direction: column; }}
2965
+ .mini-val {{
2966
+ font-family: var(--font-mono);
2967
+ font-size: 16px;
2968
+ color: var(--c-text-main);
2969
+ }}
2970
+ .mini-label {{
2971
+ font-size: 11px;
2972
+ text-transform: uppercase;
2973
+ letter-spacing: 0.1em;
2974
+ color: var(--c-text-dim);
2975
+ }}
2976
+
2977
+ /* HERO STATS */
2978
+ .stat-row {{
2979
+ display: grid;
2980
+ grid-template-columns: repeat(4, 1fr);
2981
+ gap: var(--s-3);
2982
+ margin-bottom: var(--s-4);
2983
+ }}
2984
+ .stat-card {{
2985
+ background: var(--c-surface);
2986
+ border: 1px solid var(--c-border);
2987
+ border-radius: 12px;
2988
+ padding: var(--s-4);
2989
+ text-align: center;
2990
+ }}
2991
+ .stat-card-value {{
2992
+ font-family: var(--font-mono);
2993
+ font-size: 32px;
2994
+ font-weight: 500;
2995
+ color: var(--c-accent-cyan);
2996
+ text-shadow: var(--glow-text);
2997
+ }}
2998
+ .stat-card-label {{
2999
+ font-size: 11px;
3000
+ text-transform: uppercase;
3001
+ letter-spacing: 0.15em;
3002
+ color: var(--c-text-dim);
3003
+ margin-top: var(--s-1);
3004
+ }}
3005
+
3006
+ /* WASTE */
3007
+ .waste-card {{
3008
+ background: var(--c-surface);
3009
+ border: 1px solid var(--c-border);
3010
+ border-radius: 12px;
3011
+ padding: var(--s-4);
3012
+ margin-bottom: var(--s-3);
3013
+ border-left: 3px solid var(--c-text-dim);
3014
+ transition: border-color 0.3s;
3015
+ }}
3016
+ .waste-card.critical {{ border-left-color: var(--c-danger); }}
3017
+ .waste-card.high {{ border-left-color: var(--c-warning); }}
3018
+ .waste-card.medium {{ border-left-color: var(--c-accent-cyan); }}
3019
+ .waste-header {{
3020
+ display: flex;
3021
+ justify-content: space-between;
3022
+ align-items: center;
3023
+ margin-bottom: var(--s-2);
3024
+ }}
3025
+ .waste-severity {{
3026
+ font-size: 11px;
3027
+ font-weight: 600;
3028
+ text-transform: uppercase;
3029
+ letter-spacing: 0.1em;
3030
+ padding: 2px 8px;
3031
+ border-radius: 3px;
3032
+ margin-right: var(--s-2);
3033
+ }}
3034
+ .waste-severity.critical {{ background: rgba(239,68,68,0.2); color: var(--c-danger); }}
3035
+ .waste-severity.high {{ background: rgba(245,158,11,0.2); color: var(--c-warning); }}
3036
+ .waste-severity.medium {{ background: rgba(0,240,255,0.1); color: var(--c-accent-cyan); }}
3037
+ .waste-severity.low {{ background: rgba(125,140,163,0.1); color: var(--c-text-dim); }}
3038
+ .waste-system {{ font-size: 13px; color: var(--c-text-dim); }}
3039
+ .waste-desc {{ font-size: 16px; margin-bottom: var(--s-2); }}
3040
+ .waste-rec {{ font-size: 14px; color: var(--c-text-dim); margin-bottom: var(--s-2); }}
3041
+ .waste-savings {{
3042
+ font-family: var(--font-mono);
3043
+ font-size: 16px;
3044
+ color: var(--c-success);
3045
+ text-shadow: 0 0 6px rgba(34,197,94,0.4);
3046
+ }}
3047
+ .waste-fix {{
3048
+ margin-top: var(--s-2);
3049
+ padding: var(--s-2) var(--s-3);
3050
+ background: rgba(0,0,0,0.3);
3051
+ border-radius: 6px;
3052
+ font-family: var(--font-mono);
3053
+ font-size: 13px;
3054
+ color: var(--c-text-dim);
3055
+ white-space: pre-wrap;
3056
+ line-height: 1.6;
3057
+ }}
3058
+
3059
+ /* CHART (daily cost bars) */
3060
+ .chart-container {{ padding: var(--s-2) 0; }}
3061
+ .bar-chart {{
3062
+ display: flex;
3063
+ align-items: flex-end;
3064
+ gap: 2px;
3065
+ height: 120px;
3066
+ padding-top: var(--s-2);
3067
+ }}
3068
+ .bar {{
3069
+ flex: 1;
3070
+ background: var(--c-accent-cyan);
3071
+ border-radius: 2px 2px 0 0;
3072
+ min-width: 4px;
3073
+ opacity: 0.7;
3074
+ transition: opacity 0.2s;
3075
+ position: relative;
3076
+ }}
3077
+ .bar:hover {{ opacity: 1; }}
3078
+ .bar-label {{
3079
+ display: flex;
3080
+ justify-content: space-between;
3081
+ font-size: 11px;
3082
+ color: var(--c-text-dim);
3083
+ font-family: var(--font-mono);
3084
+ margin-top: var(--s-1);
3085
+ }}
3086
+
3087
+ /* PROJECTS */
3088
+ .proj-row {{
3089
+ display: flex;
3090
+ align-items: center;
3091
+ gap: var(--s-3);
3092
+ padding: var(--s-2) 0;
3093
+ border-bottom: 1px solid var(--c-border);
3094
+ font-size: 14px;
3095
+ }}
3096
+ .proj-row:last-child {{ border-bottom: none; }}
3097
+ .proj-name {{ flex: 1; font-weight: 400; }}
3098
+ .proj-stat {{ color: var(--c-text-dim); font-family: var(--font-mono); font-size: 13px; min-width: 80px; text-align: right; }}
3099
+ .proj-cost {{ font-family: var(--font-mono); font-size: 13px; color: var(--c-accent-cyan); min-width: 70px; text-align: right; }}
3100
+
3101
+ /* MODEL BAR */
3102
+ .model-bar {{
3103
+ display: flex;
3104
+ height: 24px;
3105
+ border-radius: 6px;
3106
+ overflow: hidden;
3107
+ margin-bottom: var(--s-2);
3108
+ }}
3109
+ .model-segment {{ transition: width 0.5s; }}
3110
+ .model-segment.fable {{ background: #e11d48; }}
3111
+ .model-segment.opus {{ background: #a855f7; }}
3112
+ .model-segment.sonnet {{ background: #3b82f6; }}
3113
+ .model-segment.haiku {{ background: #22c55e; }}
3114
+ .model-segment.other {{ background: #6b7280; }}
3115
+ .model-legend {{
3116
+ display: flex;
3117
+ gap: var(--s-3);
3118
+ flex-wrap: wrap;
3119
+ font-size: 12px;
3120
+ font-family: var(--font-mono);
3121
+ color: var(--c-text-dim);
3122
+ }}
3123
+ .model-legend-item {{ display: flex; align-items: center; gap: 6px; }}
3124
+ .model-legend-dot {{ width: 8px; height: 8px; border-radius: 2px; }}
3125
+ .model-legend-dot.fable {{ background: #e11d48; }}
3126
+ .model-legend-dot.opus {{ background: #a855f7; }}
3127
+ .model-legend-dot.sonnet {{ background: #3b82f6; }}
3128
+ .model-legend-dot.haiku {{ background: #22c55e; }}
3129
+ .model-legend-dot.other {{ background: #6b7280; }}
3130
+
3131
+ /* RIGHT PANEL */
3132
+ .config-col {{
3133
+ border-left: 1px solid var(--c-border);
3134
+ padding: var(--s-4);
3135
+ background: rgba(10,11,16,0.8);
3136
+ display: flex;
3137
+ flex-direction: column;
3138
+ gap: var(--s-4);
3139
+ overflow-y: auto;
3140
+ }}
3141
+ .section-title {{
3142
+ font-size: 14px;
3143
+ text-transform: uppercase;
3144
+ letter-spacing: 0.2em;
3145
+ margin-bottom: var(--s-3);
3146
+ color: var(--c-text-dim);
3147
+ padding-bottom: var(--s-1);
3148
+ border-bottom: 1px solid var(--c-border);
3149
+ font-family: var(--font-mono);
3150
+ }}
3151
+ .summary-metric {{
3152
+ font-family: var(--font-mono);
3153
+ font-size: 18px;
3154
+ color: var(--c-text-dim);
3155
+ margin-bottom: var(--s-3);
3156
+ }}
3157
+ .summary-metric .num {{
3158
+ color: var(--c-accent-cyan);
3159
+ text-shadow: var(--glow-text);
3160
+ }}
3161
+ .version-footer {{
3162
+ margin-top: auto;
3163
+ padding-top: var(--s-4);
3164
+ border-top: 1px solid var(--c-border);
3165
+ font-size: 13px;
3166
+ color: var(--c-text-dim);
3167
+ display: flex;
3168
+ justify-content: space-between;
3169
+ align-items: center;
3170
+ }}
3171
+ .version-footer a {{ color: var(--c-accent-cyan); text-decoration: none; }}
3172
+ .social-icons {{ display: flex; gap: var(--s-2); }}
3173
+ .social-link {{ color: var(--c-text-dim); transition: color 0.2s; }}
3174
+ .social-link:hover {{ color: var(--c-accent-cyan); }}
3175
+
3176
+ .empty-state {{
3177
+ text-align: center;
3178
+ padding: var(--s-6) var(--s-4);
3179
+ color: var(--c-text-dim);
3180
+ font-family: var(--font-mono);
3181
+ font-size: 14px;
3182
+ }}
3183
+
3184
+ @media (max-width: 1100px) {{
3185
+ .layout {{ grid-template-columns: 1fr; height: auto; }}
3186
+ .nav-col {{ display: none; }}
3187
+ .config-col {{ display: none; }}
3188
+ .stat-row {{ grid-template-columns: repeat(2, 1fr); }}
3189
+ }}
3190
+ .unpriced-banner {{
3191
+ background: rgba(245, 158, 11, 0.08);
3192
+ border: 1px solid var(--c-warning);
3193
+ border-radius: 8px;
3194
+ padding: var(--s-3);
3195
+ margin-bottom: var(--s-4);
3196
+ font-size: 15px;
3197
+ color: var(--c-text-main);
3198
+ line-height: 1.6;
3199
+ }}
3200
+ .unpriced-banner code {{
3201
+ font-family: var(--font-mono);
3202
+ font-size: 13px;
3203
+ color: var(--c-warning);
3204
+ word-break: break-all;
3205
+ }}
3206
+ </style>
3207
+ </head>
3208
+ <body>
3209
+
3210
+ <div class="layout">
3211
+ <!-- NAV -->
3212
+ <nav class="nav-col">
3213
+ <div>
3214
+ <div class="brand"><span></span> Fleet Auditor</div>
3215
+ <div class="nav-menu">
3216
+ <a class="nav-item active" data-view="overview">Overview</a>
3217
+ <a class="nav-item" data-view="waste">Waste <span class="nav-badge">{len(waste_data)}</span></a>
3218
+ <a class="nav-item" data-view="systems">Systems</a>
3219
+ <a class="nav-item" data-view="daily">Daily</a>
3220
+ <div class="nav-separator"></div>
3221
+ {back_link}
3222
+ </div>
3223
+ </div>
3224
+ <div class="user-profile">generated: <i>{datetime.now().strftime("%Y-%m-%d %H:%M")}</i></div>
3225
+ </nav>
3226
+
3227
+ <!-- MAIN -->
3228
+ <main class="main-col">
3229
+ <!-- Overview -->
3230
+ <div class="view active" id="view-overview">
3231
+ <div class="section-header">
3232
+ <div class="label">Fleet Token Audit</div>
3233
+ <h1>Overview</h1>
3234
+ <p>Cross-platform agent token usage and waste detection.</p>
3235
+ </div>
3236
+ {unpriced_banner}
3237
+ <div class="stat-row">
3238
+ <div class="stat-card">
3239
+ <div class="stat-card-value">{total_runs:,}</div>
3240
+ <div class="stat-card-label">Total Runs</div>
3241
+ </div>
3242
+ <div class="stat-card">
3243
+ <div class="stat-card-value">{fmt_cost(total_cost)}{cost_asterisk}</div>
3244
+ <div class="stat-card-label">Total Cost{" (understated)" if unpriced_models else ""}</div>
3245
+ </div>
3246
+ <div class="stat-card">
3247
+ <div class="stat-card-value">{len(systems_data)}</div>
3248
+ <div class="stat-card-label">Systems</div>
3249
+ </div>
3250
+ <div class="stat-card">
3251
+ <div class="stat-card-value" style="color: var(--c-success)">{fmt_cost(total_waste)}/mo</div>
3252
+ <div class="stat-card-label">Potential Savings</div>
3253
+ </div>
3254
+ </div>
3255
+
3256
+ <div class="dashboard-grid">
3257
+ {sys_html if sys_html else '<div class="empty-state">No systems scanned yet.<br>Run: python3 fleet.py scan</div>'}
3258
+ </div>
3259
+ </div>
3260
+
3261
+ <!-- Waste -->
3262
+ <div class="view" id="view-waste">
3263
+ <div class="section-header">
3264
+ <div class="label">Waste Detection</div>
3265
+ <h1>Findings</h1>
3266
+ <p>Identified waste patterns with dollar savings estimates and fix snippets.</p>
3267
+ </div>
3268
+ {waste_html if waste_html else '<div class="empty-state">No waste patterns detected.<br>Run: python3 fleet.py audit</div>'}
3269
+ </div>
3270
+
3271
+ <!-- Systems -->
3272
+ <div class="view" id="view-systems">
3273
+ <div class="section-header">
3274
+ <div class="label">System Breakdown</div>
3275
+ <h1>Systems</h1>
3276
+ <p>Per-system usage, model mix, and top projects.</p>
3277
+ </div>
3278
+ <div class="dashboard-grid">
3279
+ {sys_html if sys_html else '<div class="empty-state">No data yet.</div>'}
3280
+ </div>
3281
+ <div class="card" id="model-mix-card" style="margin-top: var(--s-3);">
3282
+ <div class="card-header"><span>Model Mix</span><span class="label">Cost distribution by model</span></div>
3283
+ <div id="model-mix-content"></div>
3284
+ </div>
3285
+ <div class="card" style="margin-top: var(--s-3);">
3286
+ <div class="card-header"><span>Top Projects</span><span class="label">By total cost</span></div>
3287
+ {proj_html if proj_html else '<div class="empty-state" style="padding: var(--s-3);">No project data.</div>'}
3288
+ </div>
3289
+ </div>
3290
+
3291
+ <!-- Daily -->
3292
+ <div class="view" id="view-daily">
3293
+ <div class="section-header">
3294
+ <div class="label">Time Series</div>
3295
+ <h1>Daily</h1>
3296
+ <p>Daily cost and run count over the scan window.</p>
3297
+ </div>
3298
+ <div class="card">
3299
+ <div class="card-header"><span>Daily Cost</span></div>
3300
+ <div class="chart-container">
3301
+ <div class="bar-chart" id="daily-chart"></div>
3302
+ <div class="bar-label" id="daily-labels"></div>
3303
+ </div>
3304
+ </div>
3305
+ <div class="card" style="margin-top: var(--s-3);">
3306
+ <div class="card-header"><span>Daily Runs</span></div>
3307
+ <div class="chart-container">
3308
+ <div class="bar-chart" id="runs-chart"></div>
3309
+ <div class="bar-label" id="runs-labels"></div>
3310
+ </div>
3311
+ </div>
3312
+ </div>
3313
+ </main>
3314
+
3315
+ <!-- RIGHT PANEL -->
3316
+ <aside class="config-col">
3317
+ <div class="section-title">Fleet Summary</div>
3318
+ <div class="summary-metric"><span class="num">{total_runs:,}</span> runs</div>
3319
+ <div class="summary-metric"><span class="num">{fmt_cost(total_cost)}</span> total</div>
3320
+ <div class="summary-metric"><span class="num">{total_active_days}</span> active days</div>
3321
+
3322
+ <div class="section-title">Waste Breakdown</div>
3323
+ <div class="summary-metric" style="font-size:14px;">
3324
+ {"".join(f'<div style="margin-bottom:4px;"><span style="color:{severity_colors.get(sev, "var(--c-text-dim)")}">{count}</span> {sev}</div>' for sev, count in sev_counts.items() if count > 0) or '<span style="color:var(--c-success)">Clean fleet</span>'}
3325
+ </div>
3326
+ <div class="summary-metric">
3327
+ Potential savings: <span class="num">{fmt_cost(total_waste)}/mo</span>
3328
+ </div>
3329
+
3330
+ <div class="section-title">Quick Commands</div>
3331
+ <div style="font-family: var(--font-mono); font-size: 12px; color: var(--c-text-dim); line-height: 2;">
3332
+ <div>fleet.py detect</div>
3333
+ <div>fleet.py scan --days 30</div>
3334
+ <div>fleet.py audit --json</div>
3335
+ <div>fleet.py report</div>
3336
+ <div>fleet.py dashboard</div>
3337
+ </div>
3338
+
3339
+ <div class="version-footer">
3340
+ <div>Built by <a href="https://linkedin.com/in/alexgreensh" target="_blank" rel="noopener">Alex Greenshpun</a></div>
3341
+ <div class="social-icons">
3342
+ <a href="https://github.com/alexgreensh/token-optimizer" target="_blank" rel="noopener" title="GitHub" class="social-link">
3343
+ <svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor"><path d="M12 0C5.37 0 0 5.37 0 12c0 5.31 3.435 9.795 8.205 11.385.6.105.825-.255.825-.57 0-.285-.015-1.23-.015-2.235-3.015.555-3.795-.735-4.035-1.41-.135-.345-.72-1.41-1.23-1.695-.42-.225-1.02-.78-.015-.795.945-.015 1.62.87 1.845 1.23 1.08 1.815 2.805 1.305 3.495.99.105-.78.42-1.305.765-1.605-2.67-.3-5.46-1.335-5.46-5.925 0-1.305.465-2.385 1.23-3.225-.12-.3-.54-1.53.12-3.18 0 0 1.005-.315 3.3 1.23.96-.27 1.98-.405 3-.405s2.04.135 3 .405c2.295-1.56 3.3-1.23 3.3-1.23.66 1.65.24 2.88.12 3.18.765.84 1.23 1.905 1.23 3.225 0 4.605-2.805 5.625-5.475 5.925.435.375.81 1.095.81 2.22 0 1.605-.015 2.895-.015 3.3 0 .315.225.69.825.57A12.02 12.02 0 0024 12c0-6.63-5.37-12-12-12z"/></svg>
3344
+ </a>
3345
+ <a href="https://linkedin.com/in/alexgreensh" target="_blank" rel="noopener" title="LinkedIn" class="social-link">
3346
+ <svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor"><path d="M20.447 20.452h-3.554v-5.569c0-1.328-.027-3.037-1.852-3.037-1.853 0-2.136 1.445-2.136 2.939v5.667H9.351V9h3.414v1.561h.046c.477-.9 1.637-1.85 3.37-1.85 3.601 0 4.267 2.37 4.267 5.455v6.286zM5.337 7.433a2.062 2.062 0 01-2.063-2.065 2.064 2.064 0 112.063 2.065zm1.782 13.019H3.555V9h3.564v11.452zM22.225 0H1.771C.792 0 0 .774 0 1.729v20.542C0 23.227.792 24 1.771 24h20.451C23.2 24 24 23.227 24 22.271V1.729C24 .774 23.2 0 22.222 0h.003z"/></svg>
3347
+ </a>
3348
+ </div>
3349
+ </div>
3350
+ </aside>
3351
+ </div>
3352
+
3353
+ <script>
3354
+ var dailyData = {daily_json};
3355
+ var modelData = {model_json};
3356
+
3357
+ function esc(s) {{ return String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;'); }}
3358
+ function fmtCost(n) {{ return n >= 1000 ? '$' + n.toLocaleString(undefined, {{maximumFractionDigits:0}}) : '$' + n.toFixed(2); }}
3359
+
3360
+ // Nav switching
3361
+ document.querySelectorAll('.nav-item[data-view]').forEach(function(lnk) {{
3362
+ lnk.addEventListener('click', function(e) {{
3363
+ e.preventDefault();
3364
+ var v = this.getAttribute('data-view');
3365
+ document.querySelectorAll('.view').forEach(function(el) {{ el.classList.remove('active'); }});
3366
+ document.querySelectorAll('.nav-item').forEach(function(n) {{ n.classList.remove('active'); }});
3367
+ var target = document.getElementById('view-' + v);
3368
+ if (target) target.classList.add('active');
3369
+ this.classList.add('active');
3370
+ document.querySelector('.main-col').scrollTop = 0;
3371
+ }});
3372
+ }});
3373
+
3374
+ // Daily cost chart
3375
+ (function() {{
3376
+ var chart = document.getElementById('daily-chart');
3377
+ var labels = document.getElementById('daily-labels');
3378
+ if (!chart || !dailyData.length) return;
3379
+
3380
+ // Aggregate by date
3381
+ var byDate = {{}};
3382
+ dailyData.forEach(function(d) {{
3383
+ byDate[d.date] = (byDate[d.date] || 0) + d.cost;
3384
+ }});
3385
+ var dates = Object.keys(byDate).sort();
3386
+ var maxCost = Math.max.apply(null, dates.map(function(d) {{ return byDate[d]; }})) || 1;
3387
+
3388
+ dates.forEach(function(date) {{
3389
+ var bar = document.createElement('div');
3390
+ bar.className = 'bar';
3391
+ bar.style.height = Math.max(2, (byDate[date] / maxCost) * 100) + '%';
3392
+ bar.title = date + ': ' + fmtCost(byDate[date]);
3393
+ chart.appendChild(bar);
3394
+ }});
3395
+
3396
+ if (dates.length > 0) {{
3397
+ labels.innerHTML = '<span>' + dates[0] + '</span><span>' + dates[dates.length - 1] + '</span>';
3398
+ }}
3399
+
3400
+ // Runs chart
3401
+ var runsChart = document.getElementById('runs-chart');
3402
+ var runsLabels = document.getElementById('runs-labels');
3403
+ if (!runsChart) return;
3404
+ var byDateRuns = {{}};
3405
+ dailyData.forEach(function(d) {{
3406
+ byDateRuns[d.date] = (byDateRuns[d.date] || 0) + d.runs;
3407
+ }});
3408
+ var maxRuns = Math.max.apply(null, dates.map(function(d) {{ return byDateRuns[d] || 0; }})) || 1;
3409
+ dates.forEach(function(date) {{
3410
+ var bar = document.createElement('div');
3411
+ bar.className = 'bar';
3412
+ bar.style.height = Math.max(2, ((byDateRuns[date] || 0) / maxRuns) * 100) + '%';
3413
+ bar.style.background = '#3b82f6';
3414
+ bar.title = date + ': ' + (byDateRuns[date] || 0) + ' runs';
3415
+ runsChart.appendChild(bar);
3416
+ }});
3417
+ if (dates.length > 0) {{
3418
+ runsLabels.innerHTML = '<span>' + dates[0] + '</span><span>' + dates[dates.length - 1] + '</span>';
3419
+ }}
3420
+ }})();
3421
+
3422
+ // Model mix
3423
+ (function() {{
3424
+ var container = document.getElementById('model-mix-content');
3425
+ if (!container) return;
3426
+ var html = '';
3427
+
3428
+ for (var sys in modelData) {{
3429
+ var models = modelData[sys];
3430
+ var totalCost = 0;
3431
+ models.forEach(function(m) {{ totalCost += m.cost; }});
3432
+ if (totalCost <= 0) continue;
3433
+
3434
+ html += '<div style="margin-bottom: var(--s-3);"><div style="font-size:13px;color:var(--c-text-dim);margin-bottom:4px;">' + esc(sys) + '</div>';
3435
+ html += '<div class="model-bar">';
3436
+ models.forEach(function(m) {{
3437
+ var pct = (m.cost / totalCost * 100).toFixed(1);
3438
+ var cls = m.model.replace(/[^a-z0-9-]/g, '');
3439
+ html += '<div class="model-segment ' + cls + '" style="width:' + pct + '%" title="' + esc(m.model) + ': ' + pct + '% (' + fmtCost(m.cost) + ')"></div>';
3440
+ }});
3441
+ html += '</div><div class="model-legend">';
3442
+ models.forEach(function(m) {{
3443
+ var pct = (m.cost / totalCost * 100).toFixed(0);
3444
+ var cls = m.model.replace(/[^a-z0-9-]/g, '');
3445
+ html += '<div class="model-legend-item"><div class="model-legend-dot ' + cls + '"></div>' + esc(m.model) + ' ' + pct + '% (' + fmtCost(m.cost) + ')</div>';
3446
+ }});
3447
+ html += '</div></div>';
3448
+ }}
3449
+
3450
+ container.innerHTML = html || '<div class="empty-state" style="padding:var(--s-3);">No model data.</div>';
3451
+ }})();
3452
+ </script>
3453
+ </body>
3454
+ </html>'''
3455
+
3456
+
3457
+ def _open_in_browser(path: Path):
3458
+ """Open a file in the default browser.
3459
+
3460
+ Windows: ``os.startfile`` -- the same helper ``measure.py::_open_in_browser``
3461
+ uses. Two earlier shapes were both wrong.
3462
+
3463
+ 1. ``subprocess.run(["start", path], shell=True)`` (the original shape): ``shell=True``
3464
+ routes through ``cmd.exe /c``, a console-subsystem binary, so a
3465
+ console-less host (the Claude Desktop app) gets a brand-new console
3466
+ allocated -- the cmd window users saw flash. ``start`` is also a
3467
+ cmd BUILTIN, so without the shell there is no ``start.exe`` to exec.
3468
+ 2. ``subprocess.run(["cmd", "/c", "start", "", path], creationflags=...)``
3469
+ (the first fix): dropping ``shell=True`` removed PYTHON's shell, not
3470
+ cmd.exe's PARSER. ``subprocess.list2cmdline`` quotes an argument only when
3471
+ it contains a space, tab or quote -- never on ``&``, ``^``, ``|``, ``(``,
3472
+ ``)``. ``&`` is a LEGAL Windows account-name character, so a real path
3473
+ like ``C:\\Users\\R&D\\...\\fleet-dashboard.html`` reached cmd UNQUOTED,
3474
+ cmd split it at the ``&`` and executed the tail as a second command
3475
+ relative to the CWD. ``%VAR%`` expands even inside quotes, and the bare
3476
+ image name ``cmd`` resolves CWD-FIRST under CreateProcessW, so an
3477
+ untrusted working directory could supply the interpreter. The path is
3478
+ derived from ``CLAUDE_CONFIG_DIR`` (deliberately unconfined) and
3479
+ ``HOME``/``USERPROFILE``, so this was command injection, not just
3480
+ breakage.
3481
+
3482
+ ``os.startfile`` calls ShellExecuteW with the path as a real ARGUMENT: no
3483
+ command line is built, no parser sees the metacharacters, no console is
3484
+ allocated (so the no-flash fix needs no creationflags on this branch at all), and the
3485
+ browser it hands off to is a GUI app that stays visible.
3486
+
3487
+ ``open`` / ``xdg-open`` keep ``creationflags=_NO_WINDOW``; it is ``0`` off
3488
+ Windows, where ``creationflags=0`` is the documented default, so POSIX
3489
+ behaviour is unchanged.
3490
+
3491
+ Failures are reported (the no-flash bug stayed hidden for months behind ``check=False``
3492
+ and a discarded returncode): any opener error prints the file:// URL to open
3493
+ by hand, matching ``measure.py``.
3494
+ """
3495
+ import platform as _platform
3496
+ system = _platform.system()
3497
+ filepath = str(path)
3498
+ try:
3499
+ if system == "Darwin":
3500
+ subprocess.run(["open", filepath], check=True, timeout=10, creationflags=_NO_WINDOW)
3501
+ elif system == "Linux":
3502
+ subprocess.run(["xdg-open", filepath], check=True, timeout=10, creationflags=_NO_WINDOW)
3503
+ elif system == "Windows":
3504
+ os.startfile(filepath) # noqa: S606 -- ShellExecuteW, no command line, no console
3505
+ else:
3506
+ raise OSError(f"Unsupported platform: {system}")
3507
+ except (subprocess.CalledProcessError, subprocess.TimeoutExpired, OSError, FileNotFoundError):
3508
+ print("\n Could not auto-open browser. Open manually:")
3509
+ print(f" {Path(filepath).as_uri()}")
3510
+
3511
+
3512
+ def _serve_dashboard(host: str, port: int):
3513
+ """Serve the fleet dashboard over HTTP: that one page and nothing else.
3514
+
3515
+ The old handler served the whole data folder, so fleet.db and the pricing
3516
+ overrides were downloadable, and with no Host check a DNS-rebinding page in
3517
+ the user's browser could read them. Now only the dashboard is served, and a
3518
+ request whose Host is not this server's own name is refused.
3519
+ """
3520
+ import http.server
3521
+
3522
+ allowed_hosts = {"127.0.0.1", "localhost", "[::1]", host.lower()}
3523
+ page = FLEET_DASHBOARD_PATH
3524
+
3525
+ class _DashboardOnly(http.server.BaseHTTPRequestHandler):
3526
+ def _host_ok(self) -> bool:
3527
+ raw = (self.headers.get("Host") or "").strip().lower()
3528
+ # "[::1]:8080" -> "[::1]"; "localhost:8080" -> "localhost"
3529
+ name = raw[: raw.find("]") + 1] if raw.startswith("[") else raw.split(":", 1)[0]
3530
+ return name in allowed_hosts
3531
+
3532
+ def do_GET(self): # noqa: N802 (http.server API)
3533
+ if not self._host_ok():
3534
+ self.send_error(403, "Forbidden host")
3535
+ return
3536
+ if self.path.split("?", 1)[0] not in ("/", "/fleet-dashboard.html"):
3537
+ self.send_error(404)
3538
+ return
3539
+ try:
3540
+ body = page.read_bytes()
3541
+ except OSError:
3542
+ self.send_error(404)
3543
+ return
3544
+ self.send_response(200)
3545
+ self.send_header("Content-Type", "text/html; charset=utf-8")
3546
+ self.send_header("Content-Length", str(len(body)))
3547
+ self.send_header("Cache-Control", "no-store")
3548
+ self.end_headers()
3549
+ self.wfile.write(body)
3550
+
3551
+ def log_message(self, fmt, *a): # keep the terminal quiet
3552
+ pass
3553
+
3554
+ with http.server.HTTPServer((host, port), _DashboardOnly) as server:
3555
+ print(f" Serving fleet dashboard at http://{host}:{port}/fleet-dashboard.html")
3556
+ print(" Press Ctrl+C to stop.")
3557
+ try:
3558
+ server.serve_forever()
3559
+ except KeyboardInterrupt:
3560
+ print("\n Server stopped.")
3561
+
3562
+
3563
+ # ===================================================================
3564
+ # CLI ENTRY POINT
3565
+ # ===================================================================
3566
+
3567
+ def fleet_cli(args: list[str] | None = None):
3568
+ """Main CLI entry point. Can be called from measure.py via lazy import."""
3569
+ if args is None:
3570
+ args = sys.argv[1:]
3571
+
3572
+ if not args or args[0] == "--help" or args[0] == "-h":
3573
+ print("""
3574
+ Fleet Auditor: Cross-Platform Agent Token Waste Auditor
3575
+
3576
+ Commands:
3577
+ detect Detect installed agent systems
3578
+ scan [--system X] [--days 30] Collect agent runs into fleet.db
3579
+ audit [--system X] [--days 30] Run waste pattern detection
3580
+ report [--system X] [--json] Full report with cost breakdown
3581
+ dashboard [--serve] Generate and open fleet dashboard
3582
+
3583
+ Flags:
3584
+ --json Output as JSON
3585
+ --days N Look back N days (default: 30)
3586
+ --system X Filter to one system (claude, openclaw, hermes, etc.)
3587
+ --serve Start HTTP server for dashboard
3588
+ --quiet, -q Suppress non-essential output
3589
+ """)
3590
+ return
3591
+
3592
+ cmd = args[0]
3593
+ cmd_args = args[1:]
3594
+
3595
+ if cmd == "detect":
3596
+ cmd_detect(cmd_args)
3597
+ elif cmd == "scan":
3598
+ cmd_scan(cmd_args)
3599
+ elif cmd == "audit":
3600
+ cmd_audit(cmd_args)
3601
+ elif cmd == "report":
3602
+ cmd_report(cmd_args)
3603
+ elif cmd == "dashboard":
3604
+ cmd_dashboard(cmd_args)
3605
+ else:
3606
+ print(f" Unknown command: {cmd}")
3607
+ print(" Run 'fleet.py --help' for usage.")
3608
+ sys.exit(1)
3609
+
3610
+
3611
+ if __name__ == "__main__":
3612
+ fleet_cli()