@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,143 @@
1
+ """Token Optimizer v5.6 - Activity Mode Tracker.
2
+
3
+ Classifies session activity into modes (code/debug/review/infra/general) using
4
+ a sliding window of the last 10 tool calls. Mode labels feed into dynamic compact
5
+ instructions for mode-aware PRESERVE/DROP decisions.
6
+
7
+ Called from context_intel.py PostToolUse handler. Stores activity log and current
8
+ mode in the per-session SQLite store.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import re
14
+ import time
15
+ from typing import Optional
16
+
17
+ _WINDOW_SIZE = 10
18
+
19
+ _INFRA_BASH_RE = re.compile(
20
+ r"\b(?:systemctl|nginx|docker|kubectl|service|daemon|launchctl"
21
+ r"|brew|apt|apt-get|yum|dnf|pacman)\b"
22
+ )
23
+ _GIT_WRITE_RE = re.compile(r"\bgit\s+(?:push|pull|merge|rebase|cherry-pick|tag)\b")
24
+ _INSTALL_RE = re.compile(
25
+ r"\b(?:pip|npm|pnpm|yarn|bun|cargo|go)\s+(?:install|add|update|upgrade)\b"
26
+ )
27
+
28
+ # Tool name to bucket mapping
29
+ _EDIT_TOOLS = frozenset({"Edit", "Write", "MultiEdit", "NotebookEdit"})
30
+ _READ_TOOLS = frozenset({"Read", "Glob", "Grep"})
31
+ _AGENT_TOOLS = frozenset({"Agent", "TaskCreate", "TaskUpdate", "TaskGet", "TaskList"})
32
+
33
+
34
+ def classify_tool(tool_name: str, command: str = "") -> str:
35
+ """Classify a tool call into a bucket for mode detection."""
36
+ if tool_name in _EDIT_TOOLS:
37
+ return "edit"
38
+ if tool_name in _READ_TOOLS:
39
+ return "read"
40
+ if tool_name in _AGENT_TOOLS:
41
+ return "agent"
42
+ if tool_name.startswith("mcp__"):
43
+ return "mcp"
44
+ if tool_name == "Bash":
45
+ if _INFRA_BASH_RE.search(command):
46
+ return "bash_infra"
47
+ if _GIT_WRITE_RE.search(command):
48
+ return "bash_git"
49
+ if _INSTALL_RE.search(command):
50
+ return "bash_install"
51
+ return "bash_other"
52
+ if tool_name == "WebSearch" or tool_name == "WebFetch":
53
+ return "web"
54
+ return "other"
55
+
56
+
57
+ def detect_mode(recent_buckets: list[str], has_recent_errors: bool = False) -> str:
58
+ """Determine session mode from the last N tool buckets.
59
+
60
+ Modes:
61
+ code - edit-heavy (4+ edits in window)
62
+ debug - error signals present + read-heavy
63
+ review - read/grep-heavy, no edits
64
+ infra - bash infra/git/install heavy (3+ infra-class)
65
+ general - default when no pattern dominates
66
+ """
67
+ if len(recent_buckets) < 3:
68
+ return "general"
69
+
70
+ edit_count = recent_buckets.count("edit")
71
+ read_count = recent_buckets.count("read")
72
+ infra_count = sum(1 for b in recent_buckets if b in ("bash_infra", "bash_git", "bash_install"))
73
+ web_count = recent_buckets.count("web")
74
+ bash_other = recent_buckets.count("bash_other")
75
+
76
+ if infra_count >= 3:
77
+ return "infra"
78
+ if has_recent_errors and read_count >= 3 and edit_count <= 1:
79
+ return "debug"
80
+ if edit_count >= 4:
81
+ return "code"
82
+ if read_count >= 4 and edit_count == 0:
83
+ return "review"
84
+ if web_count >= 3:
85
+ return "review"
86
+ if edit_count >= 2 and (bash_other >= 2 or read_count >= 2):
87
+ return "code"
88
+
89
+ return "general"
90
+
91
+
92
+ _PRUNE_THRESHOLD = 30 # prune when table exceeds this many rows
93
+ _PRUNE_KEEP = 20 # keep the most recent N rows after pruning
94
+
95
+
96
+ def log_tool_use(store, tool_name: str, command: str = "", has_error: bool = False) -> Optional[str]:
97
+ """Log a tool use to the activity tracker and return the current mode.
98
+
99
+ Args:
100
+ store: SessionStore instance (already connected)
101
+ tool_name: Name of the tool used
102
+ command: For Bash tools, the command string
103
+ has_error: Whether the tool result contained error signals
104
+
105
+ Returns:
106
+ Current detected mode string, or None on failure
107
+ """
108
+ try:
109
+ bucket = classify_tool(tool_name, command)
110
+ conn = store._connect()
111
+
112
+ conn.execute(
113
+ "INSERT INTO activity_log (tool_name, tool_bucket, has_error, timestamp) "
114
+ "VALUES (?, ?, ?, ?)",
115
+ (tool_name[:64], bucket, 1 if has_error else 0, time.time()),
116
+ )
117
+
118
+ rows = conn.execute(
119
+ "SELECT tool_bucket, has_error FROM activity_log "
120
+ "ORDER BY id DESC LIMIT ?",
121
+ (_WINDOW_SIZE,),
122
+ ).fetchall()
123
+
124
+ row_count = conn.execute("SELECT COUNT(*) FROM activity_log").fetchone()[0]
125
+ if row_count > _PRUNE_THRESHOLD:
126
+ conn.execute(
127
+ "DELETE FROM activity_log WHERE id NOT IN "
128
+ "(SELECT id FROM activity_log ORDER BY id DESC LIMIT ?)",
129
+ (_PRUNE_KEEP,),
130
+ )
131
+
132
+ recent_buckets = [r[0] for r in rows]
133
+ has_recent_errors = any(r[1] for r in rows)
134
+ mode = detect_mode(recent_buckets, has_recent_errors)
135
+
136
+ conn.execute(
137
+ "INSERT OR REPLACE INTO session_meta (key, value) VALUES (?, ?)",
138
+ ("current_mode", mode),
139
+ )
140
+ conn.commit()
141
+ return mode
142
+ except Exception:
143
+ return None
@@ -0,0 +1,548 @@
1
+ #!/usr/bin/env python3
2
+ """Token Optimizer — Google Antigravity readiness doctor.
3
+
4
+ Per-check readiness report with fix hints (R17). The Antigravity data plane is
5
+ read-only and version-volatile, so the doctor names exactly which source is
6
+ ready and which needs a fix rather than a single pass/fail.
7
+
8
+ Checks:
9
+ agy binary on PATH + version
10
+ Antigravity home + the three surface directories
11
+ plugin directory + hooks.json shape + payload completeness
12
+ plugin enabled state in config.json (read-only)
13
+ consent record present
14
+ conversation store readable + decodable on the newest database per surface
15
+ conversation summaries database readable per surface
16
+ dashboard daemon port (24847)
17
+
18
+ Usage:
19
+ python3 antigravity_doctor.py [--json]
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import argparse
25
+ import json
26
+ import os
27
+ import shutil
28
+ import socket
29
+ import subprocess
30
+ import sys
31
+ from pathlib import Path
32
+
33
+ _SCRIPT_DIR = Path(__file__).resolve().parent
34
+ sys.path.insert(0, str(_SCRIPT_DIR))
35
+
36
+ from runtime_env import antigravity_home, measure_cli as _measure_cli, with_measure_cli as _hint # noqa: E402
37
+
38
+ DAEMON_PORT = 24847
39
+ _VERSION_TIMEOUT_SECONDS = 5
40
+
41
+
42
+ def _check(status: str, name: str, detail: str, hint: str = "") -> dict:
43
+ out = {"status": status, "name": name, "detail": detail}
44
+ if hint:
45
+ out["hint"] = hint
46
+ return out
47
+
48
+
49
+ def _binary_checks() -> list:
50
+ checks = []
51
+ override = os.environ.get("TOKEN_OPTIMIZER_ANTIGRAVITY_BIN", "").strip()
52
+ if override:
53
+ if not os.path.isabs(override):
54
+ checks.append(
55
+ _check(
56
+ "fail",
57
+ "agy binary",
58
+ f"TOKEN_OPTIMIZER_ANTIGRAVITY_BIN ({override!r}) is not an absolute path.",
59
+ "Set it to the absolute path of the agy binary.",
60
+ )
61
+ )
62
+ return checks
63
+ try:
64
+ from antigravity_install import _py_path_is_trusted
65
+ except Exception:
66
+ _py_path_is_trusted = None
67
+ if _py_path_is_trusted is None or not _py_path_is_trusted(override):
68
+ checks.append(
69
+ _check(
70
+ "fail",
71
+ "agy binary",
72
+ f"TOKEN_OPTIMIZER_ANTIGRAVITY_BIN ({override}) failed the trust check "
73
+ "(must be under a system prefix or user-owned and not group/other-writable).",
74
+ "Point it at a trusted agy binary, or unset to resolve `agy` from PATH.",
75
+ )
76
+ )
77
+ return checks
78
+ exe = override
79
+ source = f"{exe} (override)"
80
+ else:
81
+ exe = shutil.which("agy")
82
+ if not exe:
83
+ checks.append(
84
+ _check(
85
+ "fail",
86
+ "agy binary",
87
+ "`agy` not found on PATH.",
88
+ "Install Antigravity (https://antigravity.google/), or set "
89
+ "TOKEN_OPTIMIZER_ANTIGRAVITY_BIN to its location.",
90
+ )
91
+ )
92
+ return checks
93
+ source = exe
94
+
95
+ version = ""
96
+ try:
97
+ proc = subprocess.run(
98
+ [exe, "--version"],
99
+ capture_output=True,
100
+ text=True,
101
+ timeout=_VERSION_TIMEOUT_SECONDS,
102
+ )
103
+ first = (proc.stdout or proc.stderr or "").strip().splitlines()
104
+ version = first[0] if first else ""
105
+ except (OSError, subprocess.TimeoutExpired, subprocess.SubprocessError):
106
+ version = ""
107
+ if version:
108
+ checks.append(_check("ok", "agy binary", f"{source} — {version}"))
109
+ else:
110
+ checks.append(
111
+ _check(
112
+ "warn",
113
+ "agy binary",
114
+ f"{source} found but version not detected.",
115
+ "Run `agy --version` manually; auth may be required.",
116
+ )
117
+ )
118
+ return checks
119
+
120
+
121
+ def _home_checks() -> list:
122
+ checks = []
123
+ root = antigravity_home()
124
+ if not root.exists():
125
+ checks.append(
126
+ _check(
127
+ "fail",
128
+ "Antigravity home",
129
+ f"{root} does not exist.",
130
+ "Run `agy` once so it creates its home, then re-run install.",
131
+ )
132
+ )
133
+ return checks
134
+ checks.append(_check("ok", "Antigravity home", str(root)))
135
+
136
+ try:
137
+ from antigravity_state import surface_dirs
138
+ except Exception:
139
+ checks.append(
140
+ _check("warn", "surface directories", "antigravity_state unavailable.")
141
+ )
142
+ return checks
143
+ surfaces = surface_dirs(root)
144
+ present = sorted(s for s, _ in surfaces)
145
+ if not present:
146
+ checks.append(
147
+ _check(
148
+ "warn",
149
+ "surface directories",
150
+ "none of antigravity-cli / antigravity / antigravity-ide exist yet.",
151
+ "Run an Antigravity CLI/app/IDE session first.",
152
+ )
153
+ )
154
+ else:
155
+ checks.append(_check("ok", "surface directories", ", ".join(present)))
156
+ return checks
157
+
158
+
159
+ def _plugin_checks() -> list:
160
+ checks = []
161
+ try:
162
+ from antigravity_install import plugin_dir as _plugin_dir, _PAYLOAD_MODULES
163
+ except Exception:
164
+ checks.append(
165
+ _check("warn", "plugin directory", "antigravity_install unavailable.")
166
+ )
167
+ return checks
168
+
169
+ pdir = _plugin_dir(antigravity_home())
170
+ if not pdir.is_dir():
171
+ checks.append(
172
+ _check(
173
+ "warn",
174
+ "plugin directory",
175
+ f"{pdir} missing.",
176
+ _hint("Run `python3 measure.py antigravity-install`."),
177
+ )
178
+ )
179
+ return checks
180
+
181
+ hooks_path = pdir / "hooks.json"
182
+ if not hooks_path.is_file():
183
+ checks.append(
184
+ _check(
185
+ "fail",
186
+ "plugin hooks",
187
+ f"{hooks_path} missing.",
188
+ _hint("Re-run `python3 measure.py antigravity-install` to rewrite it."),
189
+ )
190
+ )
191
+ else:
192
+ try:
193
+ config = json.loads(hooks_path.read_text(encoding="utf-8"))
194
+ group = config.get("token-optimizer") if isinstance(config, dict) else None
195
+ events = sorted(group.keys()) if isinstance(group, dict) else []
196
+ expected = {"PreInvocation", "PreToolUse", "Stop"}
197
+ if not expected <= set(events):
198
+ raise ValueError(f"missing events: {sorted(expected - set(events))}")
199
+ checks.append(
200
+ _check(
201
+ "ok", "plugin hooks", f"{hooks_path} (events: {', '.join(events)})"
202
+ )
203
+ )
204
+ except (OSError, json.JSONDecodeError, ValueError) as exc:
205
+ checks.append(
206
+ _check(
207
+ "fail",
208
+ "plugin hooks",
209
+ f"{hooks_path} invalid: {exc}.",
210
+ _hint("Re-run `python3 measure.py antigravity-install` to rewrite it."),
211
+ )
212
+ )
213
+
214
+ missing = [m for m in _PAYLOAD_MODULES if not (pdir / m).is_file()]
215
+ if missing:
216
+ checks.append(
217
+ _check(
218
+ "warn",
219
+ "plugin payload",
220
+ f"Missing module(s): {', '.join(missing)}.",
221
+ _hint("Re-run `python3 measure.py antigravity-install` to refresh the payload."),
222
+ )
223
+ )
224
+ else:
225
+ checks.append(_check("ok", "plugin payload", f"{pdir} (complete)"))
226
+ return checks
227
+
228
+
229
+ def _config_enabled_check() -> list:
230
+ root = antigravity_home()
231
+ config_path = root / "config" / "config.json"
232
+ if not config_path.is_file():
233
+ return [
234
+ _check(
235
+ "ok",
236
+ "plugin enabled",
237
+ f"{config_path} absent (plugins enabled by default)",
238
+ )
239
+ ]
240
+ try:
241
+ config = json.loads(config_path.read_text(encoding="utf-8"))
242
+ except (OSError, json.JSONDecodeError, ValueError):
243
+ return [
244
+ _check(
245
+ "warn", "plugin enabled", f"{config_path} unreadable (read-only check)."
246
+ )
247
+ ]
248
+ plugins = config.get("plugins") if isinstance(config, dict) else None
249
+ entry = plugins.get("token-optimizer") if isinstance(plugins, dict) else None
250
+ enabled = entry.get("enabled") if isinstance(entry, dict) else None
251
+ if enabled is False:
252
+ return [
253
+ _check(
254
+ "fail",
255
+ "plugin enabled",
256
+ f"{config_path} marks plugins.token-optimizer.enabled = false.",
257
+ "Run `agy plugin enable token-optimizer` to re-enable.",
258
+ )
259
+ ]
260
+ return [_check("ok", "plugin enabled", f"{config_path} (enabled or default)")]
261
+
262
+
263
+ def _consent_check() -> list:
264
+ try:
265
+ from antigravity_install import data_dir as _data_dir
266
+ except Exception:
267
+ return [_check("warn", "consent record", "antigravity_install unavailable.")]
268
+ config_path = _data_dir(antigravity_home()) / "config.json"
269
+ try:
270
+ if not config_path.is_file():
271
+ return [
272
+ _check(
273
+ "warn",
274
+ "consent record",
275
+ f"{config_path} missing — bridge and rollup are inert.",
276
+ "Run `bash install.sh --antigravity` to record consent.",
277
+ )
278
+ ]
279
+ cfg = json.loads(config_path.read_text(encoding="utf-8"))
280
+ ok = bool(isinstance(cfg, dict) and cfg.get("antigravity_consent"))
281
+ except (OSError, json.JSONDecodeError, ValueError):
282
+ ok = False
283
+ if ok:
284
+ return [_check("ok", "consent record", str(config_path))]
285
+ return [
286
+ _check(
287
+ "warn",
288
+ "consent record",
289
+ f"{config_path} does not record antigravity_consent.",
290
+ "Run `bash install.sh --antigravity` to record consent.",
291
+ )
292
+ ]
293
+
294
+
295
+ def _conversation_store_checks() -> list:
296
+ checks = []
297
+ try:
298
+ from antigravity_state import surface_dirs, read_conversation
299
+ from antigravity_proto import DECODER_VERSION
300
+ except Exception:
301
+ checks.append(
302
+ _check("warn", "conversation store", "antigravity_state unavailable.")
303
+ )
304
+ return checks
305
+
306
+ root = antigravity_home()
307
+ any_surface = False
308
+ for surface, surface_path in surface_dirs(root):
309
+ conv_dir = surface_path / "conversations"
310
+ if not conv_dir.is_dir():
311
+ continue
312
+ any_surface = True
313
+ try:
314
+ dbs = sorted(
315
+ conv_dir.glob("*.db"), key=lambda p: p.stat().st_mtime, reverse=True
316
+ )
317
+ except OSError:
318
+ dbs = []
319
+ if not dbs:
320
+ checks.append(
321
+ _check(
322
+ "warn",
323
+ f"conversation store ({surface})",
324
+ f"{conv_dir} has no conversation databases yet.",
325
+ "Run an Antigravity session on this surface.",
326
+ )
327
+ )
328
+ continue
329
+ newest = dbs[0]
330
+ session = read_conversation(newest, surface=surface)
331
+ if session is None:
332
+ checks.append(
333
+ _check(
334
+ "warn",
335
+ f"conversation store ({surface})",
336
+ f"newest database {newest.name} unreadable (no gen_metadata or not SQLite).",
337
+ "Run an Antigravity session, then re-check.",
338
+ )
339
+ )
340
+ continue
341
+ total = len(session["generations"]) + session["undecodable_rows"]
342
+ detail = (
343
+ f"{len(dbs)} database(s); newest {newest.name}: "
344
+ f"{len(session['generations'])} decodable, {session['undecodable_rows']} undecodable "
345
+ f"of {total} gen_metadata rows"
346
+ )
347
+ if session["undecodable_rows"]:
348
+ checks.append(
349
+ _check(
350
+ "warn",
351
+ f"conversation store ({surface})",
352
+ detail + ".",
353
+ f"Decoder is {DECODER_VERSION}; update Token Optimizer if Antigravity changed "
354
+ "gen_metadata field numbers.",
355
+ )
356
+ )
357
+ else:
358
+ checks.append(_check("ok", f"conversation store ({surface})", detail))
359
+ if not any_surface:
360
+ checks.append(
361
+ _check(
362
+ "warn",
363
+ "conversation store",
364
+ "no surface directories with conversations/ found.",
365
+ )
366
+ )
367
+ return checks
368
+
369
+
370
+ def _summaries_checks() -> list:
371
+ checks = []
372
+ try:
373
+ from antigravity_state import surface_dirs, read_summaries
374
+ except Exception:
375
+ checks.append(
376
+ _check("warn", "summaries database", "antigravity_state unavailable.")
377
+ )
378
+ return checks
379
+ root = antigravity_home()
380
+ surfaces = surface_dirs(root)
381
+ for surface, surface_path in surfaces:
382
+ db_path = surface_path / "conversation_summaries.db"
383
+ if not db_path.is_file():
384
+ checks.append(
385
+ _check(
386
+ "warn",
387
+ f"summaries database ({surface})",
388
+ f"{db_path} absent.",
389
+ "Run an Antigravity session; summaries seed automatically.",
390
+ )
391
+ )
392
+ continue
393
+ summaries = read_summaries(surface_path)
394
+ checks.append(
395
+ _check(
396
+ "ok",
397
+ f"summaries database ({surface})",
398
+ f"{len(summaries)} conversation summary row(s)",
399
+ )
400
+ )
401
+ if not surfaces:
402
+ checks.append(
403
+ _check("warn", "summaries database", "no surface directories to inspect.")
404
+ )
405
+ return checks
406
+
407
+
408
+ def _daemon_check() -> dict:
409
+ try:
410
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
411
+ sock.settimeout(0.5)
412
+ in_use = sock.connect_ex(("127.0.0.1", DAEMON_PORT)) == 0
413
+ except OSError:
414
+ in_use = False
415
+ if in_use:
416
+ return _check("ok", "dashboard daemon", f"port {DAEMON_PORT} serving")
417
+ return _check(
418
+ "ok",
419
+ "dashboard daemon",
420
+ f"port {DAEMON_PORT} free (daemon not running — optional)",
421
+ )
422
+
423
+
424
+ def _bridge_selftest_check() -> dict:
425
+ """Invoke the installed bridge once with an empty payload.
426
+
427
+ File-and-key validation above cannot catch a wrong interpreter, a stale
428
+ payload import, or a crash-on-startup: the only proof a hook can fire is
429
+ running it. The bridge must exit 0 (fail-open contract) and emit valid
430
+ JSON on stdout.
431
+ """
432
+ try:
433
+ from antigravity_install import plugin_dir as _plugin_dir
434
+ except Exception:
435
+ return _check("warn", "bridge self-test", "antigravity_install unavailable.")
436
+ bridge = _plugin_dir(antigravity_home()) / "antigravity_hook_bridge.py"
437
+ if not bridge.is_file():
438
+ return _check(
439
+ "warn",
440
+ "bridge self-test",
441
+ f"{bridge} missing.",
442
+ _hint("Run `python3 measure.py antigravity-install`."),
443
+ )
444
+ try:
445
+ env = {
446
+ **os.environ,
447
+ "TOKEN_OPTIMIZER_RUNTIME": "antigravity",
448
+ # Probe the SAME home this doctor run is validating, never
449
+ # whatever the subprocess would resolve on its own.
450
+ "TOKEN_OPTIMIZER_ANTIGRAVITY_HOME": str(antigravity_home()),
451
+ }
452
+ proc = subprocess.Popen(
453
+ [sys.executable, str(bridge), "pre-tool-use"],
454
+ stdin=subprocess.PIPE,
455
+ stdout=subprocess.PIPE,
456
+ stderr=subprocess.PIPE,
457
+ text=True,
458
+ env=env,
459
+ )
460
+ try:
461
+ stdout, stderr = proc.communicate(input="{}", timeout=15)
462
+ except subprocess.SubprocessError:
463
+ proc.kill()
464
+ proc.wait()
465
+ raise
466
+ proc.stdout = stdout
467
+ proc.stderr = stderr
468
+ except (OSError, subprocess.SubprocessError) as exc:
469
+ return _check(
470
+ "fail",
471
+ "bridge self-test",
472
+ f"invocation failed: {exc}.",
473
+ _hint("Re-run `python3 measure.py antigravity-install` to refresh the payload."),
474
+ )
475
+ if proc.returncode != 0:
476
+ return _check(
477
+ "fail",
478
+ "bridge self-test",
479
+ f"exit {proc.returncode} (stderr: {proc.stderr.strip()[:200]}).",
480
+ _hint("Re-run `python3 measure.py antigravity-install` to refresh the payload."),
481
+ )
482
+ out = (proc.stdout or "").strip()
483
+ if out:
484
+ try:
485
+ json.loads(out)
486
+ except (json.JSONDecodeError, ValueError):
487
+ return _check(
488
+ "fail",
489
+ "bridge self-test",
490
+ f"stdout is not valid JSON; the host would read the hook as "
491
+ f"malformed (stdout: {out[:200]!r}).",
492
+ _hint("Re-run `python3 measure.py antigravity-install` to refresh the payload."),
493
+ )
494
+ return _check("ok", "bridge self-test", "exit 0, valid JSON output")
495
+
496
+
497
+ def run_checks() -> list:
498
+ checks = []
499
+ checks.extend(_binary_checks())
500
+ checks.extend(_home_checks())
501
+ checks.extend(_plugin_checks())
502
+ checks.extend(_config_enabled_check())
503
+ checks.extend(_consent_check())
504
+ checks.extend(_conversation_store_checks())
505
+ checks.extend(_summaries_checks())
506
+ checks.append(_daemon_check())
507
+ checks.append(_bridge_selftest_check())
508
+ return checks
509
+
510
+
511
+ _BADGES = {"ok": "[OK] ", "warn": "[WARN]", "fail": "[FAIL]"}
512
+
513
+
514
+ def _print_text(checks: list) -> None:
515
+ # Banner and summary are ASCII-only on purpose: measure.py re-execs into
516
+ # UTF-8 mode, but the doctor can also be invoked directly by a hook or
517
+ # shell whose stdout is an ANSI codepage. An em-dash there mojibakes into a
518
+ # replacement glyph, so keep the two stable lines safe for every console.
519
+ print("Token Optimizer - Google Antigravity doctor")
520
+ print()
521
+ for c in checks:
522
+ print(f" {_BADGES.get(c['status'], '[?] ')} {c['name']}: {c['detail']}")
523
+ if c.get("hint"):
524
+ print(f" fix: {c['hint']}")
525
+ fails = sum(1 for c in checks if c["status"] == "fail")
526
+ warns = sum(1 for c in checks if c["status"] == "warn")
527
+ print()
528
+ print(f" {len(checks)} checks - {fails} fail, {warns} warn")
529
+
530
+
531
+ def build_parser() -> argparse.ArgumentParser:
532
+ parser = argparse.ArgumentParser(description=__doc__)
533
+ parser.add_argument("--json", action="store_true")
534
+ return parser
535
+
536
+
537
+ def main(argv=None) -> int:
538
+ args = build_parser().parse_args(argv)
539
+ checks = run_checks()
540
+ if args.json:
541
+ print(json.dumps(checks, indent=1))
542
+ else:
543
+ _print_text(checks)
544
+ return 1 if any(c["status"] == "fail" for c in checks) else 0
545
+
546
+
547
+ if __name__ == "__main__":
548
+ sys.exit(main())