@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,485 @@
1
+ #!/usr/bin/env python3
2
+ """Cursor-native Token Coach data collection (Slice D / U7 coach gap).
3
+
4
+ Under the Cursor runtime the token-coach skill previously had only
5
+ ``cursor-doctor`` and ``cursor-summary`` - hook readiness and a session recap,
6
+ not coaching data. This module generates the coach's structured data from
7
+ Token Optimizer's OWN Cursor data planes, read-only:
8
+
9
+ - session tallies under ``<cursor_home>/token-optimizer/sessions/*.json``
10
+ (turns, tool calls, models, recorded failures, preCompact snapshots);
11
+ - session quality from ``cursor_quality.compute_cursor_quality`` (the single
12
+ Cursor scorer - per-signal provenance included);
13
+ - token figures resolved live through ``cursor_state`` (state.vscdb bubble
14
+ ``tokenCount``, else the transcript chars-over-four estimate - the same
15
+ sources and ordering ``cursor-rollup`` uses);
16
+ - the rollup's ``trends.db`` ``session_log`` rows (``platform='cursor'``) for
17
+ aggregate history;
18
+ - disk transcripts only through the tally's ``transcript_path`` (via
19
+ cursor_quality, which confines reads under ``<cursor_home>/projects``).
20
+
21
+ Honesty rules (R15 / KD3, and the disk-writer evidence):
22
+
23
+ - Cursor exposes no local billing data: the cost block says so, and nothing
24
+ here computes or implies a dollar figure. A 0 is "no data", never "free".
25
+ - Every token figure is quoted with its provenance (state.vscdb rollup /
26
+ transcript estimate / tally-only unknown).
27
+ - preCompact fill numbers are HISTORICAL pre-compaction occupancy; patterns
28
+ say "before compaction", never imply current fill.
29
+ - Cursor disk transcripts carry no tool results: "no failures recorded" is
30
+ hook coverage, not proof of clean runs, and is phrased that way.
31
+ - It never scans ~/.claude or any other runtime's files.
32
+
33
+ The output mirrors the shape the token-coach skill consumes for other
34
+ runtimes (snapshot / patterns_good / patterns_bad / history / questions /
35
+ health_score) so the coaching conversation works unchanged.
36
+ """
37
+
38
+ from __future__ import annotations
39
+
40
+ import json
41
+ import logging
42
+ import os
43
+ import sqlite3
44
+ import time
45
+ from pathlib import Path
46
+ from typing import Any, Optional
47
+
48
+ logger = logging.getLogger(__name__)
49
+
50
+ _MAX_TALLY_FILES = 10_000
51
+ _MAX_TALLY_BYTES = 4 * 1024 * 1024
52
+ _MAX_TRANSCRIPT_SESSIONS = 20 # transcript parsing for quality, most recent first
53
+
54
+ _NO_COST_DETAIL = (
55
+ "Cursor exposes no local billing data; coaching is in tokens, never "
56
+ "dollars. The Cursor CLI /usage surface shows account-level usage only."
57
+ )
58
+
59
+
60
+ def _default_cursor_home() -> Path:
61
+ # Delegate to runtime_env.cursor_home() so the TOKEN_OPTIMIZER_CURSOR_HOME
62
+ # override gets the same validation the hook bridge applies (absolute,
63
+ # existing, non-symlink, confined under $HOME / WSL /mnt opt-in). A bare
64
+ # Path(override) here let coach/audit read a different home than the
65
+ # bridge writes to.
66
+ try:
67
+ from runtime_env import cursor_home
68
+
69
+ return cursor_home()
70
+ except Exception:
71
+ return Path.home() / ".cursor"
72
+
73
+
74
+ def _safe_int(value: Any, default: int = 0) -> int:
75
+ try:
76
+ return int(float(value)) if value is not None else default
77
+ except (TypeError, ValueError, OverflowError):
78
+ return default
79
+
80
+
81
+ def _safe_float(value: Any) -> Optional[float]:
82
+ try:
83
+ return float(value) if value is not None else None
84
+ except (TypeError, ValueError, OverflowError):
85
+ return None
86
+
87
+
88
+ def _read_tally(path: Path) -> Optional[dict]:
89
+ """Bounded, defensive tally read; None on any failure."""
90
+ try:
91
+ if path.stat().st_size > _MAX_TALLY_BYTES:
92
+ return None
93
+ data = json.loads(path.read_text(encoding="utf-8", errors="replace"))
94
+ return data if isinstance(data, dict) else None
95
+ except (OSError, json.JSONDecodeError, ValueError):
96
+ return None
97
+
98
+
99
+ def collect_cursor_sessions(
100
+ cursor_home: Any = None, *, limit: int = _MAX_TALLY_FILES
101
+ ) -> tuple[list[dict], list[str]]:
102
+ """Read session tallies (newest first) plus human-readable skip notes."""
103
+ home = Path(cursor_home) if cursor_home is not None else _default_cursor_home()
104
+ sessions_dir = home / "token-optimizer" / "sessions"
105
+ tallies: list[dict] = []
106
+ skipped: list[str] = []
107
+ try:
108
+ paths = [p for p in sessions_dir.iterdir() if p.is_file() and p.suffix == ".json"]
109
+ except OSError:
110
+ return [], []
111
+
112
+ def _mtime(p: Path) -> float:
113
+ try:
114
+ return p.stat().st_mtime
115
+ except OSError:
116
+ return 0.0
117
+
118
+ paths.sort(key=_mtime, reverse=True)
119
+ for path in paths[:limit]:
120
+ tally = _read_tally(path)
121
+ if tally is None:
122
+ skipped.append(f"skipped unreadable tally {path.name} (corrupt or oversized)")
123
+ continue
124
+ tallies.append(tally)
125
+ return tallies, skipped
126
+
127
+
128
+ def _trends_db_path(home: Path) -> Optional[Path]:
129
+ snap = os.environ.get("TOKEN_OPTIMIZER_SNAPSHOT_DIR", "").strip()
130
+ candidates = []
131
+ if snap:
132
+ candidates.append(Path(snap).expanduser() / "trends.db")
133
+ candidates.append(home / "_backups" / "token-optimizer" / "trends.db")
134
+ return next((p for p in candidates if p.is_file()), None)
135
+
136
+
137
+ def _collect_history(home: Path) -> dict:
138
+ """Rollup session_log rows for Cursor, read-only; honest notes on absence."""
139
+ history: dict[str, Any] = {
140
+ "trended_sessions": 0,
141
+ "tokens_resolved_sessions": 0,
142
+ "average_quality_score": None,
143
+ "note": None,
144
+ }
145
+ db_path = _trends_db_path(home)
146
+ if db_path is None:
147
+ history["note"] = (
148
+ "trends.db not found - token figures unresolved; run "
149
+ "measure.py cursor-rollup to resolve them"
150
+ )
151
+ return history
152
+ try:
153
+ conn = sqlite3.connect(f"{db_path.resolve().as_uri()}?mode=ro", uri=True, timeout=2)
154
+ except sqlite3.Error as exc:
155
+ history["note"] = f"trends.db would not open read-only: {exc}"
156
+ return history
157
+ try:
158
+ available = {r[1] for r in conn.execute("PRAGMA table_info(session_log)").fetchall()}
159
+ want = {"jsonl_path", "input_tokens", "output_tokens", "quality_score"}
160
+ if not {"jsonl_path", "input_tokens", "output_tokens"} <= available:
161
+ history["note"] = "trends.db lacks the session_log columns the coach needs"
162
+ return history
163
+ cols = sorted(want & available)
164
+ if "platform" in available:
165
+ rows = conn.execute(
166
+ f"SELECT {', '.join(cols)} FROM session_log WHERE platform = 'cursor'"
167
+ ).fetchall()
168
+ else:
169
+ rows = conn.execute(f"SELECT {', '.join(cols)} FROM session_log").fetchall()
170
+ except sqlite3.Error as exc:
171
+ history["note"] = f"trends.db query failed: {exc}"
172
+ return history
173
+ finally:
174
+ conn.close()
175
+ idx = {name: i for i, name in enumerate(cols)}
176
+ quality_scores = []
177
+ for row in rows:
178
+ history["trended_sessions"] += 1
179
+ if _safe_int(row[idx["input_tokens"]]) > 0 or _safe_int(row[idx["output_tokens"]]) > 0:
180
+ history["tokens_resolved_sessions"] += 1
181
+ if "quality_score" in idx:
182
+ qs = _safe_float(row[idx["quality_score"]])
183
+ if qs is not None:
184
+ quality_scores.append(qs)
185
+ if quality_scores:
186
+ history["average_quality_score"] = round(sum(quality_scores) / len(quality_scores), 1)
187
+ return history
188
+
189
+
190
+ def _pattern(name: str, severity: str, detail: str, fix: str) -> dict:
191
+ return {"name": name, "severity": severity, "detail": detail, "fix": fix}
192
+
193
+
194
+ def _detect_patterns(session_view: list[dict]) -> tuple[list[dict], list[dict]]:
195
+ """Ground every pattern in collected evidence; quote provenance with numbers."""
196
+ good: list[dict] = []
197
+ bad: list[dict] = []
198
+
199
+ hot = [s for s in session_view if (s["latest_compaction_fill"] or 0) >= 0.85]
200
+ for s in hot[:3]:
201
+ bad.append(_pattern(
202
+ "Running Hot Into Compaction",
203
+ "high",
204
+ f"Session {s['label']} reached {round(s['latest_compaction_fill'] * 100)}% "
205
+ "of the context window before compaction (the host's measurement at "
206
+ "compaction time, not a live reading).",
207
+ "Compact earlier or split the work so each rebuilt context starts "
208
+ "leaner; keep .cursor/rules and AGENTS.md short so less comes back "
209
+ "after every compaction.",
210
+ ))
211
+
212
+ churn = [s for s in session_view if s["compactions"] >= 3]
213
+ for s in churn[:3]:
214
+ bad.append(_pattern(
215
+ "Repeated Compaction Churn",
216
+ "medium",
217
+ f"Session {s['label']} compacted {s['compactions']} times over "
218
+ f"{s['turns']} turns.",
219
+ "Long single-chat sessions lose working context at every "
220
+ "compaction; break the task at natural seams and start a fresh "
221
+ "chat with a short brief instead.",
222
+ ))
223
+
224
+ for s in session_view:
225
+ for tool, count in s["failures_by_tool"].items():
226
+ rate = count / s["tool_calls"] if s["tool_calls"] else 0.0
227
+ if count >= 3 or (count > 0 and rate >= 0.10):
228
+ bad.append(_pattern(
229
+ "Tool Failures Clustering",
230
+ "medium",
231
+ f"Session {s['label']}: {tool} failed {count} of "
232
+ f"{s['tool_calls']} recorded tool calls (as recorded by "
233
+ "the wired hooks).",
234
+ "Repeated failures of one tool usually mean a path, "
235
+ "permission or command-shape problem; fix the cause "
236
+ "instead of letting the agent retry into the context.",
237
+ ))
238
+ break
239
+
240
+ terminal = [s for s in session_view if s["terminal_errors"] > 0]
241
+ for s in terminal[:3]:
242
+ bad.append(_pattern(
243
+ "Turns Ending In Errors",
244
+ "medium",
245
+ f"Session {s['label']}: {s['terminal_errors']} turn(s) ended with "
246
+ "an error or abort status on disk.",
247
+ "Check what the agent was attempting at those turns; repeated "
248
+ "terminal errors often mean the task needs splitting or a "
249
+ "permission the session lacks.",
250
+ ))
251
+
252
+ unknown_tokens = [s for s in session_view if s["token_source"] == "cursor_tally_only"]
253
+ if unknown_tokens:
254
+ bad.append(_pattern(
255
+ "Token Footprint Unknown",
256
+ "low",
257
+ f"{len(unknown_tokens)} of {len(session_view)} session(s) have no "
258
+ "resolved token figures (no state.vscdb read, no transcript "
259
+ "estimate) - their usage is unknown, not zero.",
260
+ "Check that IDE chats exist (state.vscdb) or CLI transcripts are "
261
+ "present under <cursor_home>/projects; measure.py cursor-doctor "
262
+ "names both data planes.",
263
+ ))
264
+
265
+ marathon = [s for s in session_view if s["turns"] > 100]
266
+ for s in marathon[:3]:
267
+ bad.append(_pattern(
268
+ "Marathon Sessions",
269
+ "low",
270
+ f"Session {s['label']} ran {s['turns']} turns.",
271
+ "Very long sessions accumulate stale context; a fresh chat with "
272
+ "a short brief is cheaper than dragging the whole history.",
273
+ ))
274
+
275
+ vscdb = [s for s in session_view if s["token_source"] == "cursor_state_vscdb"]
276
+ if vscdb:
277
+ good.append(_pattern(
278
+ "Real Token Figures Flowing",
279
+ "info",
280
+ f"{len(vscdb)} of {len(session_view)} session(s) have host-measured "
281
+ "token figures (state.vscdb), so their coaching numbers are "
282
+ "measured rather than estimated.",
283
+ "Nothing to change; this is the provenance every other session "
284
+ "should reach.",
285
+ ))
286
+
287
+ clean = [
288
+ s for s in session_view
289
+ if s["tool_calls"] >= 20 and not s["failures_by_tool"] and s["terminal_errors"] == 0
290
+ ]
291
+ if clean:
292
+ good.append(_pattern(
293
+ "Clean Recorded Tool Record",
294
+ "info",
295
+ f"{len(clean)} session(s) with 20+ tool calls and no failures "
296
+ "recorded by the wired hooks (hook coverage, not a guarantee).",
297
+ "Nothing to change.",
298
+ ))
299
+
300
+ short = [s for s in session_view if 0 < s["turns"] <= 20]
301
+ if short:
302
+ good.append(_pattern(
303
+ "Short Focused Sessions",
304
+ "info",
305
+ f"{len(short)} session(s) stayed at or under 20 turns.",
306
+ "Short, single-purpose chats keep context lean; keep splitting "
307
+ "work this way.",
308
+ ))
309
+
310
+ return good, bad
311
+
312
+
313
+ def generate_cursor_coach_data(
314
+ cursor_home: Any = None, *, days: int = 30, focus: Any = None
315
+ ) -> dict:
316
+ """Coach-shaped data for the Cursor runtime. Never raises; never writes."""
317
+ try:
318
+ return _generate(cursor_home, days=days, focus=focus)
319
+ except Exception as exc: # pragma: no cover - coach must never break a CLI run
320
+ logger.debug("[cursor_coach] data generation failed: %s", exc)
321
+ return {
322
+ "runtime": "cursor",
323
+ "generated_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
324
+ "focus_area": focus,
325
+ "snapshot": {
326
+ "sessions_analyzed": 0,
327
+ "window_days": days,
328
+ "total_turns": 0,
329
+ "total_tool_calls": 0,
330
+ "total_compactions": 0,
331
+ "token_provenance": {},
332
+ "quality": {"scored_sessions": 0, "average_score": None,
333
+ "signals_note": "data generation failed; see logs"},
334
+ "cost": {"status": "cursor_no_cost_data", "detail": _NO_COST_DETAIL},
335
+ },
336
+ "patterns_good": [],
337
+ "patterns_bad": [],
338
+ "history": {"trended_sessions": 0, "tokens_resolved_sessions": 0,
339
+ "average_quality_score": None, "note": "data generation failed; see logs"},
340
+ "questions": [],
341
+ "health_score": None,
342
+ "coverage": {"skipped": [], "notes": ["data generation failed; see logs"]},
343
+ }
344
+
345
+
346
+ def _generate(cursor_home: Any = None, *, days: int = 30, focus: Any = None) -> dict:
347
+ home = Path(cursor_home) if cursor_home is not None else _default_cursor_home()
348
+ tallies, skipped = collect_cursor_sessions(home)
349
+
350
+ cutoff = time.time() - days * 86400
351
+ in_window: list[dict] = []
352
+ for tally in tallies:
353
+ updated = _safe_float(tally.get("updated_at"))
354
+ if updated is not None and updated < cutoff:
355
+ continue # outside the window; missing timestamps stay included
356
+ in_window.append(tally)
357
+
358
+ # Resolve token provenance before scoring. Raw tally JSON never carries
359
+ # bubble_tokens/transcript_tokens, so without this every session scores
360
+ # cursor_tally_only and output_input_ratio / the "real figures" pattern
361
+ # are unreachable on real installs. Same sources and ordering as
362
+ # _collect_cursor_sessions, bounded to the analysis window.
363
+ import cursor_state as _cst
364
+
365
+ composer_ids = [
366
+ str(t.get("conversation_id") or t.get("session_id") or "") for t in in_window
367
+ ]
368
+ try:
369
+ bubble = _cst.read_state_vscdb_tokens(composer_ids, db_path=_cst.state_vscdb_path_for_home(home))
370
+ except Exception:
371
+ bubble = {}
372
+ resolved_tallies: list[dict] = []
373
+ for tally in in_window:
374
+ enriched = dict(tally)
375
+ cid = str(tally.get("conversation_id") or tally.get("session_id") or "")
376
+ enriched["bubble_tokens"] = bubble.get(cid)
377
+ try:
378
+ enriched["transcript_tokens"] = _cst.transcript_estimate(
379
+ tally.get("transcript_path"), home
380
+ )
381
+ except Exception:
382
+ enriched["transcript_tokens"] = None
383
+ resolved_tallies.append(enriched)
384
+ in_window = resolved_tallies
385
+
386
+ import cursor_quality
387
+
388
+ session_view: list[dict] = []
389
+ qualities: list[dict] = []
390
+ for rank, tally in enumerate(in_window):
391
+ # Transcript parsing is the expensive part; bound it to recent sessions.
392
+ quality = cursor_quality.compute_cursor_quality(
393
+ tally,
394
+ cursor_home=home,
395
+ transcript_path=None if rank >= _MAX_TRANSCRIPT_SESSIONS else tally.get("transcript_path"),
396
+ )
397
+ conversation_id = str(tally.get("conversation_id") or tally.get("session_id") or "unknown")
398
+ compactions = tally.get("compactions") if isinstance(tally.get("compactions"), list) else []
399
+ latest_fill = None
400
+ for rec in reversed(compactions):
401
+ if not isinstance(rec, dict):
402
+ continue
403
+ tokens, window = _safe_int(rec.get("context_tokens")), _safe_int(rec.get("context_window_size"))
404
+ if tokens > 0 and window > 0:
405
+ latest_fill = min(1.0, tokens / window)
406
+ break
407
+ pct = _safe_float(rec.get("context_usage_percent"))
408
+ if pct and pct > 0:
409
+ latest_fill = min(1.0, pct / 100.0)
410
+ break
411
+ failures = tally.get("failures") if isinstance(tally.get("failures"), dict) else {}
412
+ failures_by_tool = {str(k): _safe_int(v) for k, v in failures.items()}
413
+ view = {
414
+ "label": conversation_id[:12],
415
+ "turns": _safe_int(tally.get("turns")),
416
+ "tool_calls": _safe_int(tally.get("tool_calls")),
417
+ "compactions": len(compactions),
418
+ "latest_compaction_fill": latest_fill,
419
+ "failures_by_tool": failures_by_tool,
420
+ "terminal_errors": (quality or {}).get("evidence", {}).get("terminal_errors", 0),
421
+ "token_source": (quality or {}).get("token_source", "cursor_tally_only"),
422
+ "quality": quality,
423
+ }
424
+ session_view.append(view)
425
+ if quality is not None:
426
+ qualities.append(quality)
427
+
428
+ patterns_good, patterns_bad = _detect_patterns(session_view)
429
+
430
+ provenance: dict[str, int] = {}
431
+ for view in session_view:
432
+ provenance[view["token_source"]] = provenance.get(view["token_source"], 0) + 1
433
+
434
+ scores = [q["score"] for q in qualities]
435
+ health_score = round(sum(scores) / len(scores)) if scores else None
436
+
437
+ questions = [
438
+ "What's your goal today - a new build that should stay token-efficient, "
439
+ "a chat that fills its context too fast, or a general health check?",
440
+ "Do your longer Cursor chats slow down or lose track before they "
441
+ "compact?",
442
+ "Are your project rules in .cursor/rules or AGENTS.md, and how long "
443
+ "are they?",
444
+ ]
445
+
446
+ return {
447
+ "runtime": "cursor",
448
+ "generated_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
449
+ "focus_area": focus,
450
+ "snapshot": {
451
+ "sessions_analyzed": len(session_view),
452
+ "window_days": days,
453
+ "total_turns": sum(s["turns"] for s in session_view),
454
+ "total_tool_calls": sum(s["tool_calls"] for s in session_view),
455
+ "total_compactions": sum(s["compactions"] for s in session_view),
456
+ "token_provenance": provenance,
457
+ "quality": {
458
+ "scored_sessions": len(qualities),
459
+ "average_score": round(sum(scores) / len(scores), 1) if scores else None,
460
+ "signals_note": (
461
+ "per-signal provenance on every score; unavailable signals "
462
+ "are omitted and the composite renormalizes"
463
+ ),
464
+ },
465
+ "cost": {"status": "cursor_no_cost_data", "detail": _NO_COST_DETAIL},
466
+ },
467
+ "patterns_good": patterns_good,
468
+ "patterns_bad": patterns_bad,
469
+ "history": _collect_history(home),
470
+ "questions": questions,
471
+ "health_score": health_score,
472
+ "coverage": {
473
+ "skipped": skipped,
474
+ "notes": [
475
+ "Cursor disk transcripts carry no tool results (bundle-proven "
476
+ "writer 2026.11.05): failure figures are what the wired hooks "
477
+ "recorded, never proof of clean runs.",
478
+ "preCompact fill numbers are the host's occupancy at "
479
+ "compaction time (historical), not a live reading.",
480
+ "Channels reporting unknown/shadow in cursor-doctor have no "
481
+ "delivery evidence on this install; nothing here claims they "
482
+ "ran.",
483
+ ],
484
+ },
485
+ }
@@ -3,13 +3,15 @@
3
3
 
4
4
  Per-surface health report with fix-it hints, plus ``--probe`` which replays
5
5
  the documented payload for each wired event through the exact installed
6
- command string (POSIX ``/bin/sh -c``) so a live Cursor is not required to prove
7
- the hooks can fire.
6
+ command: the persisted string is shape-parsed and executed as argv (no shell)
7
+ on POSIX and Windows, so a live Cursor is not required to prove the installed
8
+ commands can fire. The probe does NOT prove Cursor itself fires the hooks;
9
+ that is what the observed-events ledger reports.
8
10
 
9
11
  Checks:
10
12
  P0 Cursor binary presence (CLI ``agent`` / ``cursor`` launcher)
11
13
  P0 ~/.cursor exists; hooks.json present + writable
12
- P1 Token Optimizer hook entries installed (six events) + parseable
14
+ P1 Token Optimizer hook entries installed (all wired events) + parseable
13
15
  P1 installed payload integrity (bridge, atomic-writer, compress)
14
16
  P1 observed-events ledger (which events fired; rewrite_honoured vs ignored)
15
17
  P2 state.vscdb (IDE token plane) / transcript dir (CLI plane)
@@ -41,8 +43,12 @@ from cursor_install import _py_path_is_trusted # noqa: E402
41
43
  DAEMON_PORT = 24846
42
44
  _NO_WINDOW = getattr(subprocess, "CREATE_NO_WINDOW", 0)
43
45
 
44
- # The six events the installer wires (order = probe order = docs order).
45
- _WIRED_EVENTS = ("sessionStart", "preToolUse", "postToolUse", "preCompact", "stop", "sessionEnd")
46
+ # The events the installer wires (order = probe order = docs order).
47
+ _WIRED_EVENTS = (
48
+ "sessionStart", "preToolUse", "postToolUse", "preCompact", "stop",
49
+ "sessionEnd", "afterAgentResponse", "postToolUseFailure",
50
+ "afterShellExecution", "subagentStart", "subagentStop",
51
+ )
46
52
 
47
53
 
48
54
  def _check(status: str, name: str, detail: str, hint: str = "") -> dict:
@@ -157,7 +163,7 @@ def _hook_config_checks() -> list:
157
163
  if missing and wired:
158
164
  checks.append(
159
165
  _check("warn", "hook event coverage", f"Missing events: {', '.join(missing)}.",
160
- "Re-run install to restore the full six-event set.")
166
+ f"Re-run install to restore the full {len(_WIRED_EVENTS)}-event set.")
161
167
  )
162
168
  return checks
163
169
 
@@ -294,9 +300,42 @@ def _observed_checks() -> list:
294
300
  if honoured or ignored:
295
301
  detail += f"; Shell rewrite: {honoured} honoured, {ignored} ignored"
296
302
  checks.append(_check("ok", "observed events", detail))
303
+ checks.append(_read_channel_check(entries))
297
304
  return checks
298
305
 
299
306
 
307
+ def _read_channel_check(entries: list) -> dict:
308
+ """U2: report the Read channel state from config + the observed ledger.
309
+
310
+ States: unknown / shadow / armed-unverified, computed by
311
+ cursor_read_cache.channel_state. Shadow silence neither arms nor
312
+ confirms, and NO ledger pattern promotes to verified: absence of a
313
+ reread is negative evidence, not delivery proof. armed-verified needs
314
+ positive controlled native evidence no current source provides.
315
+ """
316
+ try:
317
+ import cursor_read_cache
318
+
319
+ info = cursor_read_cache.channel_state(entries)
320
+ except Exception as exc:
321
+ return _check("warn", "read channel", f"state unavailable ({type(exc).__name__})")
322
+ state = info["state"]
323
+ detail = (f"{state} (mode={info['mode']}; Claude import config "
324
+ f"{'present' if info['claude_import_config_present'] else 'absent'})")
325
+ if state == "shadow":
326
+ return _check("ok", "read channel", detail,
327
+ _hint("Shadow records what would be injected. To arm: set "
328
+ "{\"mode\": \"soft_block\"} in "
329
+ "<cursor-home>/token-optimizer/read-cache.json."))
330
+ if state == "armed-unverified":
331
+ return _check("warn", "read channel", detail,
332
+ _hint("Denies are emitted but delivery is unproven; silence is "
333
+ "consistent with cancels, failures and dropped hooks."))
334
+ if state == "unknown":
335
+ return _check("ok", "read channel", detail)
336
+ return _check("ok", "read channel", detail)
337
+
338
+
300
339
  def _data_checks() -> list:
301
340
  checks = []
302
341
  try:
@@ -404,6 +443,44 @@ def _probe_payloads() -> dict:
404
443
  "reason": "probe",
405
444
  "cursor_version": cv or "3.18.9",
406
445
  },
446
+ "afterAgentResponse": {
447
+ "hook_event_name": "afterAgentResponse",
448
+ "conversation_id": "to-probe-conv",
449
+ "generation_id": "to-probe-gen",
450
+ "model": "to-probe-model",
451
+ "text": "probe",
452
+ # Synthetic: third-party-observed fields, flagged in the ledger.
453
+ "input_tokens": 100,
454
+ "output_tokens": 20,
455
+ "cursor_version": cv or "3.18.9",
456
+ },
457
+ "postToolUseFailure": {
458
+ "hook_event_name": "postToolUseFailure",
459
+ "tool_name": "Shell",
460
+ "tool_input": {"command": "false"},
461
+ "error": "exit 1 (synthetic probe)",
462
+ "conversation_id": "to-probe-conv",
463
+ "cursor_version": cv or "3.18.9",
464
+ },
465
+ "afterShellExecution": {
466
+ "hook_event_name": "afterShellExecution",
467
+ "command": "echo token-optimizer-probe",
468
+ "output": "token-optimizer-probe",
469
+ "conversation_id": "to-probe-conv",
470
+ "cursor_version": cv or "3.18.9",
471
+ },
472
+ "subagentStart": {
473
+ "hook_event_name": "subagentStart",
474
+ "conversation_id": "to-probe-conv",
475
+ "tool_use_id": "to-probe-tu",
476
+ "cursor_version": cv or "3.18.9",
477
+ },
478
+ "subagentStop": {
479
+ "hook_event_name": "subagentStop",
480
+ "conversation_id": "to-probe-conv",
481
+ "tool_use_id": "to-probe-tu",
482
+ "cursor_version": cv or "3.18.9",
483
+ },
407
484
  }
408
485
 
409
486
 
@@ -454,9 +531,12 @@ def _run_probe_command(command: str, payload: dict, probe_home: Path) -> dict:
454
531
  ``probe_home`` redirects the bridge's data writes (tallies, observed-events)
455
532
  to a throwaway dir so replaying the documented payloads proves the hooks can
456
533
  fire without contaminating real session data with synthetic probe rows.
534
+
535
+ Windows: the installer writes a direct ``"<python>" "<bridge>" <event>``
536
+ command (no POSIX env prefix), which ``_parse_hook_command`` already
537
+ accepts; ``subprocess.run(argv)`` executes it natively, so the probe is
538
+ not POSIX-only.
457
539
  """
458
- if sys.platform == "win32":
459
- return {"event": None, "status": "skip", "detail": "probe is POSIX-only"}
460
540
  argv = _parse_hook_command(command)
461
541
  if argv is None:
462
542
  return {"event": None, "status": "fail",
@@ -572,7 +652,7 @@ def main(argv=None) -> int:
572
652
  _print_probe(results)
573
653
  ran = [r for r in results if r.get("status") == "ok"]
574
654
  failed = [r for r in results if r.get("status") == "fail"]
575
- # Skips are informational (not installed / Windows), not failures.
655
+ # Skips are informational (event not installed), not failures.
576
656
  return 1 if failed else 0
577
657
 
578
658
  checks = run_checks()