@alexgreensh/token-optimizer 5.13.68 → 5.13.69

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 (57) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/hooks/module_runner.py +1 -1
  4. package/package.json +1 -1
  5. package/skills/fleet-auditor/references/fleet-systems.md +38 -0
  6. package/skills/fleet-auditor/scripts/fleet.py +63 -92
  7. package/skills/fleet-auditor/scripts/fleet_base.py +106 -0
  8. package/skills/fleet-auditor/scripts/fleet_cursor_adapter.py +376 -0
  9. package/skills/token-coach/SKILL.md +21 -23
  10. package/skills/token-dashboard/SKILL.md +5 -4
  11. package/skills/token-optimizer/SKILL.md +1 -1
  12. package/skills/token-optimizer/assets/dashboard.html +101 -50
  13. package/skills/token-optimizer/references/cli-reference.md +1 -1
  14. package/skills/token-optimizer/references/cursor-workflow.md +1 -1
  15. package/skills/token-optimizer/references/phase0-setup.md +1 -1
  16. package/skills/token-optimizer/references/presentation-workflow.md +1 -1
  17. package/skills/token-optimizer/scripts/_measure/__init__.py +1 -1
  18. package/skills/token-optimizer/scripts/_measure/cli.py +86 -0
  19. package/skills/token-optimizer/scripts/_measure/daemon.py +13 -25
  20. package/skills/token-optimizer/scripts/_measure/dashboard.py +63 -37
  21. package/skills/token-optimizer/scripts/_measure/dashboard_history.py +79 -0
  22. package/skills/token-optimizer/scripts/_measure/lifecycle.py +6 -7
  23. package/skills/token-optimizer/scripts/_measure/savings.py +20 -70
  24. package/skills/token-optimizer/scripts/_measure/sessions.py +58 -20
  25. package/skills/token-optimizer/scripts/_measure/weekly_activity.py +69 -0
  26. package/skills/token-optimizer/scripts/antigravity_install.py +4 -0
  27. package/skills/token-optimizer/scripts/bash_compress.py +8 -40
  28. package/skills/token-optimizer/scripts/bash_compress_hook.py +6 -0
  29. package/skills/token-optimizer/scripts/bash_search_results.py +43 -0
  30. package/skills/token-optimizer/scripts/cloud_kit.py +1 -1
  31. package/skills/token-optimizer/scripts/codex_doctor.py +1 -1
  32. package/skills/token-optimizer/scripts/copilot_install.py +4 -0
  33. package/skills/token-optimizer/scripts/credential_patterns.py +4 -19
  34. package/skills/token-optimizer/scripts/credential_url_patterns.py +42 -0
  35. package/skills/token-optimizer/scripts/cursor_audit.py +723 -0
  36. package/skills/token-optimizer/scripts/cursor_bridge_checkpoint.py +213 -0
  37. package/skills/token-optimizer/scripts/cursor_bridge_payload.py +170 -0
  38. package/skills/token-optimizer/scripts/cursor_bridge_rewrite.py +106 -0
  39. package/skills/token-optimizer/scripts/cursor_bridge_rollup.py +115 -0
  40. package/skills/token-optimizer/scripts/cursor_coach.py +485 -0
  41. package/skills/token-optimizer/scripts/cursor_doctor.py +89 -9
  42. package/skills/token-optimizer/scripts/cursor_hook_bridge.py +393 -276
  43. package/skills/token-optimizer/scripts/cursor_install.py +106 -19
  44. package/skills/token-optimizer/scripts/cursor_quality.py +505 -0
  45. package/skills/token-optimizer/scripts/cursor_read_cache.py +597 -0
  46. package/skills/token-optimizer/scripts/cursor_session.py +26 -5
  47. package/skills/token-optimizer/scripts/cursor_state.py +8 -0
  48. package/skills/token-optimizer/scripts/cursor_statusline.py +372 -0
  49. package/skills/token-optimizer/scripts/cursor_thrash.py +78 -0
  50. package/skills/token-optimizer/scripts/cursor_transcript.py +223 -0
  51. package/skills/token-optimizer/scripts/devin_source.py +12 -2
  52. package/skills/token-optimizer/scripts/devin_verify.py +7 -6
  53. package/skills/token-optimizer/scripts/grok_install.py +4 -0
  54. package/skills/token-optimizer/scripts/hermes_doctor.py +4 -1
  55. package/skills/token-optimizer/scripts/hermes_install.py +4 -1
  56. package/skills/token-optimizer/scripts/measure.py +2 -2
  57. package/skills/token-optimizer/scripts/thrash_guard.py +10 -5
@@ -0,0 +1,376 @@
1
+ """Cursor adapter for the fleet auditor (Token Optimizer's Cursor data planes).
2
+
3
+ Split out of fleet.py to keep it under the repo's 1,000-line file-size ratchet
4
+ (scripts/check_file_size.py). Base classes come from fleet_base (single class
5
+ identity whether fleet.py is imported or run as __main__). HOME is NOT imported
6
+ from fleet: fleet.py injects _HOME_RESOLVER at import time, a lambda reading
7
+ its own module global, so the tests' monkeypatch of fleet.HOME keeps working
8
+ and `python3 fleet.py` never double-loads a second fleet module. Standalone
9
+ import falls back to Path.home().
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import json
15
+ import os
16
+ import re
17
+ import sqlite3
18
+ from datetime import datetime, timezone
19
+ from pathlib import Path
20
+
21
+ from shared import normalize_model_name # noqa: E402 (fleet.py sets sys.path first)
22
+
23
+ from fleet_base import AgentRun, BaseAdapter, TokenBreakdown, _is_run_collected
24
+
25
+ try: # noqa: E402
26
+ import cursor_session as _cursor_session # type: ignore
27
+ import cursor_state as _cursor_state # type: ignore
28
+ except Exception: # pragma: no cover - optional Cursor adapter dependency
29
+ # Standalone copies (no token-optimizer/scripts beside this file) still
30
+ # collect Cursor tallies through the adapter's native fallback reader.
31
+ _cursor_session = None
32
+ _cursor_state = None
33
+
34
+ _HOME_RESOLVER = None # injected by fleet.py at import: lambda reading fleet's HOME global
35
+
36
+ def _cursor_home() -> Path:
37
+ """Cursor's home directory for the fleet collector.
38
+
39
+ TOKEN_OPTIMIZER_CURSOR_HOME wins when it passes the same confinement
40
+ runtime_env.cursor_home() applies to the hook bridge (absolute, existing,
41
+ non-symlink dir, confined under the home root, plus the WSL /mnt opt-in);
42
+ a rejected override falls back to the default so the reader and the bridge
43
+ agree on one home. Cursor has no documented CURSOR_HOME of its own.
44
+ """
45
+ root = _HOME_RESOLVER() if _HOME_RESOLVER is not None else Path.home()
46
+ override = os.environ.get("TOKEN_OPTIMIZER_CURSOR_HOME", "").strip()
47
+ if override:
48
+ candidate = Path(override).expanduser()
49
+ if _cursor_home_override_safe(candidate, root):
50
+ return candidate
51
+ return root / ".cursor"
52
+
53
+
54
+ def _cursor_home_override_safe(candidate: Path, root: Path) -> bool:
55
+ """Mirror runtime_env's safe-home checks, scoped to fleet's HOME root.
56
+
57
+ runtime_env._is_safe_home_dir confines overrides under runtime_env's own
58
+ home root; fleet's root is _HOME_RESOLVER() (== Path.home() in production,
59
+ a tmp dir in tests), so the containment check is re-implemented here.
60
+ runtime_env is imported lazily only for the WSL /mnt opt-in and may be
61
+ absent in standalone copies of this adapter.
62
+ """
63
+ try:
64
+ home = Path(root).resolve(strict=False)
65
+ resolved = candidate.resolve(strict=False)
66
+ if (candidate.is_absolute()
67
+ and resolved != home
68
+ and resolved.is_relative_to(home)
69
+ and candidate.is_dir()
70
+ and not candidate.is_symlink()):
71
+ return True
72
+ except (OSError, RuntimeError, ValueError):
73
+ pass
74
+ try:
75
+ import runtime_env as _re # noqa: PLC0415
76
+
77
+ return _re._wsl_mnt_safe_home(candidate) is not None
78
+ except Exception:
79
+ return False
80
+
81
+
82
+ def _cursor_trends_db_candidates(home: Path) -> list[Path]:
83
+ """Candidate rollup trends.db locations, in priority order.
84
+
85
+ measure.py's cursor-rollup writes to $TOKEN_OPTIMIZER_SNAPSHOT_DIR/trends.db
86
+ when that override is set, else <runtime_home>/_backups/token-optimizer/
87
+ trends.db — under the cursor runtime that is <cursor_home>/_backups/...
88
+ """
89
+ candidates: list[Path] = []
90
+ snap = os.environ.get("TOKEN_OPTIMIZER_SNAPSHOT_DIR", "").strip()
91
+ if snap:
92
+ candidates.append(Path(snap).expanduser() / "trends.db")
93
+ candidates.append(home / "_backups" / "token-optimizer" / "trends.db")
94
+ return candidates
95
+
96
+
97
+ class CursorAdapter(BaseAdapter):
98
+ """Adapter for Cursor via Token Optimizer's own Cursor data planes.
99
+
100
+ Reads (never writes) the two planes the Cursor hook bridge and rollup
101
+ already produce:
102
+
103
+ - Tallies: ``<cursor_home>/token-optimizer/sessions/<conversation_id>.json``
104
+ — the authoritative record (turns, tool calls, models, compactions, cwd,
105
+ timestamps). Written by cursor_hook_bridge._update_tally.
106
+ - Rollup trends: ``<cursor_home>/_backups/token-optimizer/trends.db``
107
+ ``session_log`` rows (``platform='cursor'``) carrying the token figures
108
+ the rollup already resolved (state.vscdb tokenCount, else a transcript
109
+ estimate, else zero).
110
+
111
+ Honesty rules (R15 / KD3): Cursor exposes no local billing data, so
112
+ cost_usd is always 0.0 and cost surfaces render "no cost data" — never a
113
+ computed or implied $0.00 and never a pricing-table lookup. A tally with
114
+ no trends row is collected with token_source='cursor_tally_only' and zero
115
+ tokens, and scan() SAYS the figures are unknown — a silent zero is a
116
+ defect (#149 class).
117
+ """
118
+
119
+ name = "cursor"
120
+ display_name = "Cursor"
121
+
122
+ _MAX_TALLY_FILES = 10_000
123
+ _MAX_TALLY_BYTES = 4 * 1024 * 1024
124
+
125
+ def _tally_dir(self, home: Path) -> Path:
126
+ return home / "token-optimizer" / "sessions"
127
+
128
+ # -- detection ----------------------------------------------------------
129
+
130
+ def detect(self) -> tuple[bool, float, str]:
131
+ home = _cursor_home()
132
+ tally_dir = self._tally_dir(home)
133
+ if tally_dir.is_dir():
134
+ try:
135
+ n = sum(1 for p in tally_dir.iterdir() if p.is_file() and p.suffix == ".json")
136
+ except OSError:
137
+ n = 0
138
+ if n:
139
+ return True, 1.0, f"Found {n} Token Optimizer tally file(s) in {tally_dir}"
140
+ if home.exists():
141
+ return True, 0.3, (f"Found {home} but no Token Optimizer session tallies — "
142
+ f"install the Cursor hooks (measure.py cursor-install) and run a session")
143
+ return False, 0.0, f"{home} not found"
144
+
145
+ # -- data-plane readers -------------------------------------------------
146
+
147
+ def _read_tally_native(self, path: Path) -> dict | None:
148
+ """Fallback tally reader for standalone copies (no cursor_state import).
149
+
150
+ Mirrors cursor_state.read_tally's defensive posture: bounded bytes,
151
+ JSON object required, None on any failure. The idle-finalisation pass
152
+ is cursor_state's and is skipped here (documented drift risk).
153
+ """
154
+ try:
155
+ if path.stat().st_size > self._MAX_TALLY_BYTES:
156
+ return None
157
+ data = json.loads(path.read_text(encoding="utf-8", errors="replace"))
158
+ return data if isinstance(data, dict) else None
159
+ except (OSError, json.JSONDecodeError, ValueError):
160
+ return None
161
+
162
+ def _read_tallies(self, home: Path) -> tuple[list[tuple[Path, dict]], list[str]]:
163
+ sessions_dir = self._tally_dir(home)
164
+ tallies: list[tuple[Path, dict]] = []
165
+ errors: list[str] = []
166
+ try:
167
+ paths = sorted(p for p in sessions_dir.iterdir() if p.is_file() and p.suffix == ".json")
168
+ except OSError as exc:
169
+ return [], [f"cannot list {sessions_dir}: {exc}"]
170
+ for path in paths[: self._MAX_TALLY_FILES]:
171
+ if _cursor_state is not None:
172
+ tally = _cursor_state.read_tally(path)
173
+ if tally is not None:
174
+ tally = _cursor_state.idle_finalise(tally)
175
+ else:
176
+ tally = self._read_tally_native(path)
177
+ if tally is None:
178
+ errors.append(f"skipped unreadable tally {path.name} (corrupt or oversized)")
179
+ continue
180
+ tallies.append((path, tally))
181
+ if len(paths) > self._MAX_TALLY_FILES:
182
+ errors.append(f"tally cap {self._MAX_TALLY_FILES} reached; remaining tallies skipped this pass")
183
+ return tallies, errors
184
+
185
+ def _trends_rows(self, home: Path) -> tuple[dict[str, dict], str | None]:
186
+ """Read platform='cursor' session_log rows, keyed by conversation_id.
187
+
188
+ Returns (rows, note): note is None on success, else a human string
189
+ explaining the absence (no DB / no table / no columns) so scan() can
190
+ report it instead of silently zeroing tokens. Opened mode=ro: the
191
+ collector can never write to the rollup's DB.
192
+ """
193
+ db_path = next((p for p in _cursor_trends_db_candidates(home) if p.is_file()), None)
194
+ if db_path is None:
195
+ return {}, (f"trends.db not found under {home / '_backups' / 'token-optimizer'} "
196
+ f"— token figures unknown; run measure.py cursor-rollup to resolve them")
197
+ try:
198
+ conn = sqlite3.connect(f"{db_path.resolve().as_uri()}?mode=ro", uri=True, timeout=2)
199
+ conn.row_factory = sqlite3.Row
200
+ except sqlite3.Error as exc:
201
+ return {}, f"trends.db at {db_path} would not open read-only: {exc}"
202
+ try:
203
+ available = {r[1] for r in conn.execute("PRAGMA table_info(session_log)").fetchall()}
204
+ want = {"jsonl_path", "input_tokens", "output_tokens", "message_count",
205
+ "quality_score", "quality_grade", "cost_source"}
206
+ if not {"jsonl_path", "input_tokens", "output_tokens"} <= available:
207
+ return {}, f"trends.db at {db_path} lacks the session_log columns the collector needs"
208
+ cols = sorted(want & available)
209
+ if "platform" in available:
210
+ query = f"SELECT {', '.join(cols)} FROM session_log WHERE platform = 'cursor'"
211
+ else:
212
+ query = f"SELECT {', '.join(cols)} FROM session_log WHERE jsonl_path LIKE 'cursor:%'"
213
+ rows = {}
214
+ for row in conn.execute(query):
215
+ key = str(row["jsonl_path"] or "")
216
+ if not key.startswith("cursor:"):
217
+ continue
218
+ rows[key[len("cursor:"):]] = {c: row[c] for c in cols}
219
+ return rows, None
220
+ except sqlite3.Error as exc:
221
+ return {}, f"trends.db at {db_path} read failed: {exc}"
222
+ finally:
223
+ conn.close()
224
+
225
+ # -- collection ----------------------------------------------------------
226
+
227
+ def scan(self, since: datetime, conn: sqlite3.Connection | None = None) -> tuple[list[AgentRun], list[str]]:
228
+ home = _cursor_home()
229
+ if not self._tally_dir(home).is_dir():
230
+ return [], [f"{self._tally_dir(home)} not found — Token Optimizer has recorded no Cursor "
231
+ f"sessions (install: measure.py cursor-install, then run a session; 0 is not a measurement)"]
232
+
233
+ tallies, errors = self._read_tallies(home)
234
+ trends, note = self._trends_rows(home)
235
+ if note:
236
+ errors.append(note)
237
+
238
+ runs: list[AgentRun] = []
239
+ missing_tokens = 0
240
+ since_ts = since.timestamp()
241
+ for tally_path, tally in tallies:
242
+ cid = str(tally.get("conversation_id") or tally.get("session_id") or "")
243
+ if not cid:
244
+ errors.append(f"skipped tally {tally_path.name}: no conversation_id")
245
+ continue
246
+ try:
247
+ first_ts = float(tally["first_ts"]) if tally.get("first_ts") is not None else None
248
+ updated_at = float(tally["updated_at"]) if tally.get("updated_at") is not None else None
249
+ except (TypeError, ValueError, OverflowError):
250
+ first_ts = updated_at = None
251
+ last_activity = updated_at if updated_at is not None else first_ts
252
+ if last_activity is None:
253
+ errors.append(f"skipped cursor tally {cid}: no usable timestamps")
254
+ continue
255
+ # Window on LAST activity, not start: long-lived IDE composer chats
256
+ # span days and stay relevant while they are active.
257
+ if last_activity < since_ts:
258
+ continue
259
+ source_path = f"cursor:tally#{cid}"
260
+ if conn and _is_run_collected(conn, "cursor", source_path, cid):
261
+ continue
262
+
263
+ def _count(key) -> int:
264
+ try:
265
+ return max(0, int(tally.get(key) or 0))
266
+ except (TypeError, ValueError, OverflowError):
267
+ return 0
268
+
269
+ turns = _count("turns")
270
+ tool_calls = _count("tool_calls")
271
+
272
+ models = tally.get("models") if isinstance(tally.get("models"), dict) else {}
273
+ model_raw = ""
274
+ if models:
275
+ try:
276
+ model_raw = str(max(models, key=lambda k: int(models.get(k) or 0)))
277
+ except (TypeError, ValueError):
278
+ model_raw = ""
279
+ model = (normalize_model_name(model_raw) or model_raw) if model_raw else "unknown"
280
+ if _cursor_session is not None:
281
+ ctx_window = _cursor_session.context_window_for_model(model_raw or model)
282
+ else:
283
+ ctx_window = 128_000 # matches cursor_session's conservative default
284
+
285
+ row = trends.get(cid)
286
+ if row is None:
287
+ missing_tokens += 1
288
+ tokens = TokenBreakdown()
289
+ token_source = "cursor_tally_only"
290
+ else:
291
+ try:
292
+ tokens = TokenBreakdown(
293
+ input=max(0, int(row.get("input_tokens") or 0)),
294
+ output=max(0, int(row.get("output_tokens") or 0)),
295
+ cache_read=0, # Cursor hooks report no cache breakdown (yet)
296
+ cache_write=0,
297
+ )
298
+ except (TypeError, ValueError, OverflowError):
299
+ # Schema-defensive: a drifted/crafted row degrades to
300
+ # tally-only honesty instead of killing the scan.
301
+ missing_tokens += 1
302
+ tokens = TokenBreakdown()
303
+ row = None
304
+ token_source = "cursor_rollup" if row is not None else "cursor_tally_only"
305
+
306
+ duration = 0.0
307
+ if first_ts is not None and updated_at is not None and updated_at >= first_ts:
308
+ duration = updated_at - first_ts
309
+
310
+ project = "unknown"
311
+ if isinstance(tally.get("cwd"), str) and tally["cwd"]:
312
+ project = tally["cwd"]
313
+ else:
314
+ roots = tally.get("workspace_roots")
315
+ if isinstance(roots, list) and roots and isinstance(roots[0], str) and roots[0]:
316
+ project = roots[0]
317
+
318
+ outcome = "success"
319
+ if turns == 0 and tool_calls == 0:
320
+ outcome = "empty"
321
+
322
+ try:
323
+ started = datetime.fromtimestamp(
324
+ first_ts if first_ts is not None else last_activity, timezone.utc)
325
+ except (OSError, OverflowError, ValueError):
326
+ # A crafted/pathological tally float must not kill the scan.
327
+ errors.append(f"skipped cursor tally {cid}: out-of-range timestamp")
328
+ continue
329
+
330
+ runs.append(AgentRun(
331
+ system="cursor",
332
+ session_id=cid,
333
+ agent_name="main",
334
+ project=project,
335
+ timestamp=started,
336
+ duration_seconds=duration,
337
+ tokens=tokens,
338
+ cost_usd=0.0, # Cursor exposes no local billing data — never priced.
339
+ model=model,
340
+ context_window_size=ctx_window,
341
+ run_type="manual",
342
+ outcome=outcome,
343
+ message_count=turns,
344
+ source_path=source_path,
345
+ token_source=token_source,
346
+ ))
347
+
348
+ if missing_tokens:
349
+ errors.append(
350
+ f"{missing_tokens} cursor session(s) have no trends row yet; their token figures are "
351
+ f"unknown (shown as 0) — run measure.py cursor-rollup to resolve them"
352
+ )
353
+ return runs, errors
354
+
355
+ def parse_config(self) -> dict:
356
+ home = _cursor_home()
357
+ hooks_path = home / "hooks.json"
358
+ to_bridge = False
359
+ try:
360
+ # Shape-proof check: the bridge path appears anywhere in the file.
361
+ raw = hooks_path.read_text(encoding="utf-8", errors="replace")[:1_000_000]
362
+ to_bridge = "token-optimizer" in raw
363
+ except OSError:
364
+ pass
365
+ return {
366
+ "home": str(home),
367
+ "hooks_json_present": hooks_path.is_file(),
368
+ "to_bridge_installed": to_bridge,
369
+ "trends_db_present": any(p.is_file() for p in _cursor_trends_db_candidates(home)),
370
+ # Tier-1 detectors read these keys; Cursor has no comparable config
371
+ # surface today, so they stay empty and no detector can false-fire.
372
+ "skills": [],
373
+ "mcp_servers": [],
374
+ "hooks": {},
375
+ }
376
+
@@ -2,15 +2,11 @@
2
2
  name: token-coach
3
3
  description: Coaches a token-efficient Claude Code or Codex setup from the user's own usage data. Use when planning a build, fixing a slow or costly setup, or deciding which workflow steps need a model.
4
4
  ---
5
-
6
5
  # Token Coach
7
-
8
6
  A coaching conversation about where the user's tokens go and what to change, grounded in numbers measured on their machine. The deliverable is a short, prioritised action plan the user agrees with. For a full audit that edits their setup, hand over to `token-optimizer`.
9
-
10
7
  Token Optimizer's own skills (`token-optimizer`, `token-coach`, `token-dashboard`, `fleet-auditor`, `resume-checkpoint`) are the measurement layer, so leave them out of every unused-skill, archive or consolidation suggestion, however rarely they run.
11
8
 
12
9
  ## 1. Collect the data
13
-
14
10
  Run exactly this first. It finds the newest installed copy, so a stale plugin cache never answers. Each Bash call is a fresh shell, so env vars do not persist: the block echoes the resolved values, and every later command must use them verbatim.
15
11
 
16
12
  ```bash
@@ -26,6 +22,7 @@ if [ -z "$RUNTIME" ]; then
26
22
  elif [ -n "$TOKEN_OPTIMIZER_ANTIGRAVITY_HOME" ]; then RUNTIME="antigravity"
27
23
  elif [ -n "$GROK_HOME" ] || [ -n "$TOKEN_OPTIMIZER_GROK_HOME" ]; then RUNTIME="grok"
28
24
  elif [ -n "$CLAUDECODE" ] || [ -n "$CLAUDE_CODE_ENTRYPOINT" ] || [ -n "$CLAUDE_CODE_SESSION_ID" ]; then RUNTIME="claude"
25
+ elif [ -d "$HOME/.cursor/token-optimizer" ]; then RUNTIME="cursor"
29
26
  elif [ -d "$HOME/.config/opencode" ] && [ ! -d "$HOME/.codex" ]; then RUNTIME="opencode"
30
27
  elif [ -d "$HOME/.codex" ]; then RUNTIME="codex"
31
28
  else RUNTIME="claude"
@@ -47,6 +44,11 @@ while IFS= read -r _cand; do
47
44
  done <<EOF
48
45
  $(find -L "$HOME/.claude/skills" "$HOME/.claude/plugins/cache" "$HOME/.claude/token-optimizer" "$HOME/.codex/skills" "$HOME/.codex/plugins/cache" "$HOME/.config/opencode/plugins/cache" "$HOME/.config/opencode/plugins" -type f -name measure.py -path '*token-optimizer*/scripts/measure.py' 2>/dev/null)
49
46
  EOF
47
+ # Cursor-only installs have a locator for the canonical measure.py.
48
+ if [ -z "$MEASURE_PY" ]; then
49
+ _cursor_loc="${TOKEN_OPTIMIZER_CURSOR_HOME:-$HOME/.cursor}/token-optimizer/plugin/measure-path"
50
+ [ -f "$_cursor_loc" ] && MEASURE_PY="$(head -n1 "$_cursor_loc" 2>/dev/null)"
51
+ fi
50
52
  if [ -z "$MEASURE_PY" ] || [ ! -f "$MEASURE_PY" ]; then echo "[Error] measure.py not found. Is Token Optimizer installed?"; exit 1; fi
51
53
 
52
54
  # Resolve an interpreter that really runs Python. On native-Windows Git Bash
@@ -76,24 +78,28 @@ printf 'MEASURE_PY=%q\n' "$MEASURE_PY" >&2
76
78
  printf 'PY=%q\n' "$PY" >&2
77
79
  printf 'COACH_DIR=%q\n' "$COACH_DIR" >&2
78
80
  ```
79
-
80
81
  Then gather, skipping any command that fails (older installs lack some):
81
82
 
82
83
  ```bash
83
- "$PY" "$MEASURE_PY" coach --json # snapshot, patterns, history, questions
84
- "$PY" "$MEASURE_PY" quality current --json # this session's quality score and issues
85
- "$PY" "$MEASURE_PY" subagent-cache status --json # Claude Code: subagent cache lifetime and its payoff
86
- "$PY" "$MEASURE_PY" compact-advice --json # Claude Code: would an earlier compact window pay off
87
- "$PY" "$MEASURE_PY" recommendations --json # Claude Code: the daily usage-recommendations record
84
+ # These commands scan only Claude Code / Codex.
85
+ if [ "$RUNTIME" = "claude" ] || [ "$RUNTIME" = "codex" ]; then
86
+ "$PY" "$MEASURE_PY" coach --json # snapshot, patterns, history, questions
87
+ "$PY" "$MEASURE_PY" quality current --json # this session's quality score and issues
88
+ "$PY" "$MEASURE_PY" subagent-cache status --json # Claude Code: subagent cache lifetime and its payoff
89
+ "$PY" "$MEASURE_PY" compact-advice --json # Claude Code: would an earlier compact window pay off
90
+ "$PY" "$MEASURE_PY" recommendations --json # Claude Code: the daily usage-recommendations record
91
+ fi
88
92
  [ "$RUNTIME" = "codex" ] && "$PY" "$MEASURE_PY" codex-doctor --project "$PWD" --json
93
+ # Cursor: native coach, hook evidence and session summary.
94
+ [ "$RUNTIME" = "cursor" ] && "$PY" "$MEASURE_PY" cursor-coach --json
95
+ [ "$RUNTIME" = "cursor" ] && "$PY" "$MEASURE_PY" cursor-doctor --json
96
+ [ "$RUNTIME" = "cursor" ] && "$PY" "$MEASURE_PY" cursor-summary
89
97
  ```
90
-
98
+ Under Cursor, `coach --json` does not run (it scans the Claude Code setup); `cursor-coach --json` is the data source instead. It carries `snapshot` (sessions analyzed, turns/tool calls/compactions, token provenance counts, the cost block that always reads `cursor_no_cost_data`), `patterns_good`/`patterns_bad` built from real session evidence (hot pre-compaction fill, repeated compactions, recorded tool failures, unknown token footprints), `history` from the rollup's Cursor rows, `questions`, and a `health_score` built from per-session quality scores whose `signals_active`/`signals_omitted` say exactly which evidence backed them - plus what the user tells you.
91
99
  What the coach JSON holds: `snapshot` (current overhead), `patterns_good` and `patterns_bad` (named patterns with detail and fix), `history` (7-day against earlier: quality, session length, cache hit rate, grade spread, cost per session, short against long sessions, compression gap, share of sessions that switched model), `deterministic_candidates` when present (work the user repeats that a script could do), and `usage_recommendations` on Claude Code (the daily-measured record: one item each for the compact window and the subagent cache lifetime, plus `wins` once the user acted on an earlier recommendation and the numbers moved). Field-by-field meaning and the numbers to quote: [references/quick-reference.md](references/quick-reference.md).
92
-
93
100
  Every number you quote comes from these outputs or from the quick reference. When the data is thin or a command returned nothing, say so and coach from what the user tells you; an invented figure costs the user's trust in every real one.
94
101
 
95
102
  ## 2. Ask what they want
96
-
97
103
  Ask one question and wait for the answer before showing findings:
98
104
 
99
105
  > What's your goal today?
@@ -102,7 +108,6 @@ Ask one question and wait for the answer before showing findings:
102
108
  > c) Designing a multi-agent system
103
109
  > d) Quick health check
104
110
  > e) Review a workflow or automation: which steps need a model at all
105
-
106
111
  Skip the question when the request already answers it.
107
112
 
108
113
  ## 3. Load what that goal needs
@@ -113,11 +118,9 @@ Skip the question when the request already answers it.
113
118
  | c | [references/agentic-systems.md](references/agentic-systems.md), quick reference | `examples/coaching-session-agentic.md` |
114
119
  | d | quick reference only | none, keep it fast |
115
120
  | e | [references/deterministic-stages.md](references/deterministic-stages.md) | none |
116
-
117
121
  For a, b and c also read [references/coaching-scripts.md](references/coaching-scripts.md) for how each conversation tends to run. All paths are under `$COACH_DIR`. The examples show tone and pacing; the user's data decides the content.
118
122
 
119
123
  ## 4. Coach
120
-
121
124
  This is a conversation. One or two findings, then a question; the user steers the rest.
122
125
 
123
126
  - **Open with what hurts most.** A session quality score under 70 comes first ("quality is 58 of 100, and stale tool results are holding 40K tokens"). Otherwise a worsening trend beats a static number: falling quality, growing session length, a dropping cache hit rate.
@@ -128,23 +131,18 @@ This is a conversation. One or two findings, then a question; the user steers th
128
131
  - **Usage recommendations.** When `usage_recommendations` carries a `recommend` item, lead with it: it is today's measured answer, already gated on enough data. When `wins` is non-empty, name the measured change "since you changed it" and quote both numbers; never claim the change caused it.
129
132
  - **Goal e, or any time `deterministic_candidates` is non-empty:** walk the workflow step by step and sort each step into "inputs decide the output, so plain code" and "needs judgement, so a model", following the deterministic-stages reference.
130
133
  - **Codex users** hear Codex terms only: `AGENTS.md`, Codex memories, balanced Codex hooks, reasoning effort and the model picker, compact prompt guidance. Claude model names and `CLAUDE.md` mean nothing to them.
131
-
134
+ - **Cursor users** hear Cursor terms only: `.cursor/rules` and `AGENTS.md` (there is no `CLAUDE.md`/`MEMORY.md` surface), and the hooks in `~/.cursor/hooks.json`. Cursor exposes no local billing data, so coach in tokens and never in dollars — a $0 is "no data", never "free". Quote token provenance with the number: rollup-resolved (`state.vscdb`, best-effort), transcript estimate, or tally-only unknown. Context-fill claims need a real occupancy snapshot (the numbers preCompact records); a lifetime token sum is never a fill. When `cursor-doctor` reports a channel `unknown` or `shadow`, say so — never imply a protection ran that has no delivery evidence on this install.
132
135
  Sound like a knowledgeable friend. Two to four exchanges is typical; follow the user's questions over any script.
133
136
 
134
137
  ## 5. Agree the action plan
135
-
136
138
  Close with three to five actions ordered by impact. Each has a bold name, one line on what to do, the estimated saving and where that estimate comes from, and whether it is a quick win or a deeper change. Include, when they apply:
137
139
 
138
140
  - Quality under 70 on Claude Code: `"$PY" "$MEASURE_PY" setup-smart-compact`. On Codex: `TOKEN_OPTIMIZER_RUNTIME=codex "$PY" "$MEASURE_PY" codex-install --project .`
139
141
  - Quality under 50: `/compact` or `/clear` before more work.
140
142
  - Steps to move from a model to a script, each with the mechanism (hook, script, scheduled job).
141
-
142
143
  Then check the plan against the data: every figure traces to a command output or the quick reference, and no action touches Token Optimizer's own skills. Fix what fails and check again before sending.
143
-
144
- Offer `/token-optimizer` when they want the changes made for them, and the dashboard (`"$PY" "$MEASURE_PY" dashboard`; on Codex quote the `Dashboard:` line it prints, never a remembered path) when they want to watch the trend.
144
+ Offer `/token-optimizer` when they want the changes made for them, and the dashboard (`"$PY" "$MEASURE_PY" dashboard --user`; on Codex quote the `Dashboard:` line it prints, never a remembered path) when they want to watch the trend.
145
145
 
146
146
  ## Keep-Warm (Claude Code, asked once)
147
-
148
147
  After the plan, run `"$PY" "$MEASURE_PY" keepwarm-consent-status`. Only when `should_ask` is true, follow [references/keepwarm-consent.md](references/keepwarm-consent.md) exactly: it spends the user's money, so the wording and the order of commands are fixed.
149
-
150
148
  Written for and checked on Claude Opus 5.5 and Sonnet 5.5, and GPT-5.6 on Codex.
@@ -100,12 +100,13 @@ printf 'PY=%q\n' "$PY" >&2
100
100
  ```bash
101
101
  # TOKEN_OPTIMIZER_INTERACTIVE=1 marks this as a user-initiated open, so the 20s
102
102
  # hook budget does not cut off a heavy rebuild on a large history. The user is
103
- # waiting for this open, so it runs unbounded.
104
- TOKEN_OPTIMIZER_INTERACTIVE=1 "$PY" "$MEASURE_PY" collect --quiet && \
105
- TOKEN_OPTIMIZER_INTERACTIVE=1 "$PY" "$MEASURE_PY" dashboard
103
+ # waiting for this open, so it runs unbounded. --user is the argv twin of the
104
+ # env var for shells where `VAR=1 cmd` does not parse (Windows).
105
+ TOKEN_OPTIMIZER_INTERACTIVE=1 "$PY" "$MEASURE_PY" collect --quiet --user && \
106
+ TOKEN_OPTIMIZER_INTERACTIVE=1 "$PY" "$MEASURE_PY" dashboard --user
106
107
  ```
107
108
 
108
- This collects the latest session data into the trends database, regenerates the dashboard HTML, and opens it in your default browser.
109
+ This collects the latest session data into the trends database, regenerates the dashboard HTML using the last selected history window (30 days until changed), and opens it in your default browser. If the user asks for a different window, add `--days N` or `--days all` to the dashboard command; later refreshes retain that choice.
109
110
 
110
111
  4. **Tell the user** the dashboard is open. Probe the daemon before mentioning any URL:
111
112
  - Probe daemon: `"$PY" "$MEASURE_PY" daemon-status 2>/dev/null`
@@ -113,7 +113,7 @@ Work through these in order and tick each off; a skipped phase stays in the list
113
113
 
114
114
  **2. Synthesis.** One agent on the strongest available model reads every audit file and writes `{COORD_PATH}/analysis/optimization-plan.md`. If it fails, present the raw audit files.
115
115
 
116
- **3. Present.** Generate the dashboard and show the findings as the presentation workflow describes, then wait: `"$PY" "$MEASURE_PY" dashboard --coord-path "$COORD_PATH"`
116
+ **3. Present.** Generate the dashboard and show the findings as the presentation workflow describes, then wait: `"$PY" "$MEASURE_PY" dashboard --user --coord-path "$COORD_PATH"`
117
117
 
118
118
  **4. Implement.** Only what the user approved, one change at a time, following the playbook (actions 4A-4P: CLAUDE.md, MEMORY.md, skills, file exclusion, MCP, hooks, cache, rules, settings, descriptions, compact instructions, model routing, smart compaction, quality check, version-aware optimizations, smart routing). Templates are in `examples/`. Also offer, with the measured numbers:
119
119