@alexgreensh/token-optimizer 5.13.67 → 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 (75) 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/_vendor/README.md +8 -2
  19. package/skills/token-optimizer/scripts/_measure/_vendor/__init__.py +46 -6
  20. package/skills/token-optimizer/scripts/_measure/_vendor/tomli/__init__.py +34 -3
  21. package/skills/token-optimizer/scripts/_measure/audit.py +5 -21
  22. package/skills/token-optimizer/scripts/_measure/cli.py +86 -0
  23. package/skills/token-optimizer/scripts/_measure/daemon.py +34 -76
  24. package/skills/token-optimizer/scripts/_measure/dashboard.py +63 -37
  25. package/skills/token-optimizer/scripts/_measure/dashboard_history.py +79 -0
  26. package/skills/token-optimizer/scripts/_measure/lifecycle.py +88 -528
  27. package/skills/token-optimizer/scripts/_measure/savings.py +20 -70
  28. package/skills/token-optimizer/scripts/_measure/sessions.py +58 -20
  29. package/skills/token-optimizer/scripts/_measure/weekly_activity.py +69 -0
  30. package/skills/token-optimizer/scripts/{_measure/_vendor/tomli/_parser.py → _tomli.py} +156 -10
  31. package/skills/token-optimizer/scripts/antigravity_install.py +7 -0
  32. package/skills/token-optimizer/scripts/bash_compress.py +8 -40
  33. package/skills/token-optimizer/scripts/bash_compress_hook.py +6 -0
  34. package/skills/token-optimizer/scripts/bash_search_results.py +43 -0
  35. package/skills/token-optimizer/scripts/cloud_kit.py +22 -22
  36. package/skills/token-optimizer/scripts/codex_doctor.py +34 -8
  37. package/skills/token-optimizer/scripts/codex_hook_provenance.py +268 -0
  38. package/skills/token-optimizer/scripts/codex_install.py +33 -69
  39. package/skills/token-optimizer/scripts/command_filters.py +39 -309
  40. package/skills/token-optimizer/scripts/copilot_install.py +9 -0
  41. package/skills/token-optimizer/scripts/credential_patterns.py +4 -19
  42. package/skills/token-optimizer/scripts/credential_url_patterns.py +42 -0
  43. package/skills/token-optimizer/scripts/cursor_audit.py +723 -0
  44. package/skills/token-optimizer/scripts/cursor_bridge_checkpoint.py +213 -0
  45. package/skills/token-optimizer/scripts/cursor_bridge_payload.py +170 -0
  46. package/skills/token-optimizer/scripts/cursor_bridge_rewrite.py +106 -0
  47. package/skills/token-optimizer/scripts/cursor_bridge_rollup.py +115 -0
  48. package/skills/token-optimizer/scripts/cursor_coach.py +485 -0
  49. package/skills/token-optimizer/scripts/cursor_doctor.py +89 -9
  50. package/skills/token-optimizer/scripts/cursor_hook_bridge.py +393 -276
  51. package/skills/token-optimizer/scripts/cursor_install.py +111 -19
  52. package/skills/token-optimizer/scripts/cursor_quality.py +505 -0
  53. package/skills/token-optimizer/scripts/cursor_read_cache.py +597 -0
  54. package/skills/token-optimizer/scripts/cursor_session.py +26 -5
  55. package/skills/token-optimizer/scripts/cursor_state.py +8 -0
  56. package/skills/token-optimizer/scripts/cursor_statusline.py +372 -0
  57. package/skills/token-optimizer/scripts/cursor_thrash.py +78 -0
  58. package/skills/token-optimizer/scripts/cursor_transcript.py +223 -0
  59. package/skills/token-optimizer/scripts/devin_install.py +6 -12
  60. package/skills/token-optimizer/scripts/devin_source.py +17 -6
  61. package/skills/token-optimizer/scripts/devin_verify.py +17 -0
  62. package/skills/token-optimizer/scripts/grok_install.py +9 -0
  63. package/skills/token-optimizer/scripts/heal_report.py +92 -0
  64. package/skills/token-optimizer/scripts/hermes_doctor.py +4 -1
  65. package/skills/token-optimizer/scripts/hermes_install.py +4 -1
  66. package/skills/token-optimizer/scripts/hook_heal.py +138 -0
  67. package/skills/token-optimizer/scripts/hook_provenance.py +878 -0
  68. package/skills/token-optimizer/scripts/measure.py +2 -2
  69. package/skills/token-optimizer/scripts/owned_hooks.py +420 -0
  70. package/skills/token-optimizer/scripts/shipped_codex_hook_templates.json +5815 -0
  71. package/skills/token-optimizer/scripts/shipped_hook_templates.py +252 -0
  72. package/skills/token-optimizer/scripts/shipped_starter_hooks.py +55 -0
  73. package/skills/token-optimizer/scripts/thrash_guard.py +10 -5
  74. package/skills/token-optimizer/scripts/_measure/_vendor/tomli/_re.py +0 -112
  75. package/skills/token-optimizer/scripts/_measure/_vendor/tomli/_types.py +0 -10
@@ -102,145 +102,39 @@ try:
102
102
  except ImportError: # pragma: no cover - broken install
103
103
  lease_lock = None # type: ignore[assignment]
104
104
 
105
- _MAX_STDIN_BYTES = 4 * 1024 * 1024 # refuse absurd payloads (amplification)
106
- _RESTORE_MAX_BYTES = 16_384 # restore-context files above this are ignored
105
+
106
+ # Bridge helper modules (same installed payload; split under the 1,000-line
107
+ # file-size ratchet). Optional like every sibling import above: a partial
108
+ # install missing them degrades the bridge to a no-op via the main() guard
109
+ # rather than raising into Cursor.
110
+ try:
111
+ import cursor_bridge_checkpoint
112
+ import cursor_bridge_payload
113
+ import cursor_bridge_rewrite
114
+ import cursor_bridge_rollup
115
+ from cursor_bridge_checkpoint import _RESTORE_MAX_BYTES
116
+ from cursor_bridge_payload import _parse_tool_input, _sanitize_session_id, decode_payload
117
+ except ImportError: # pragma: no cover - broken/partial install
118
+ cursor_bridge_checkpoint = None # type: ignore[assignment]
119
+ cursor_bridge_payload = None # type: ignore[assignment]
120
+ cursor_bridge_rewrite = None # type: ignore[assignment]
121
+ cursor_bridge_rollup = None # type: ignore[assignment]
122
+ decode_payload = None # type: ignore[assignment]
123
+ _parse_tool_input = None # type: ignore[assignment]
124
+ _sanitize_session_id = None # type: ignore[assignment]
125
+ _RESTORE_MAX_BYTES = 16_384 # degraded-mode ceiling only; the enforced value lives in cursor_bridge_checkpoint
126
+
107
127
  _ACTIVE_WORKSPACE_SECS = 600 # skip restore when a sibling tally is live
108
- _STOP_ROLLUP_SECS = 120 # R12: at most one stop rollup per machine per 120s
109
- _STALE_LOCK_SECS = 7 * 24 * 3600 # sessionStart lock sweep threshold
110
128
  _NUDGE_TOOL_CALLS = (30, 80) # context-growth nudge thresholds (turn proxy)
111
129
 
112
130
  # Snapshot at import: the installed payload is static for the process lifetime.
113
131
  _COMPRESS_PATH = _SCRIPT_DIR / "bash_compress.py"
114
132
  _COMPRESS_AVAILABLE = _COMPRESS_PATH.exists()
115
133
 
116
- _SESSION_ID_RE = re.compile(r"[^A-Za-z0-9_-]")
117
-
118
-
119
- def _sanitize_session_id(sid):
120
- """Strip everything but [A-Za-z0-9_-] so a payload id can never traverse.
121
-
122
- Mirrors measure.sanitize_session_id / copilot_hook_bridge: a conversation_id
123
- like "../../../etc/passwd" would otherwise let _atomic_write_json / the lock
124
- path escape the data dir.
125
- """
126
- if not sid:
127
- return "unknown"
128
- cleaned = _SESSION_ID_RE.sub("", sid)[:64]
129
- return cleaned if len(cleaned) >= 6 else "unknown"
130
-
131
134
 
132
135
  def _read_stdin_payload():
133
- """Read and decode the Cursor hook payload from stdin. None on any failure."""
134
- try:
135
- raw = sys.stdin.read(_MAX_STDIN_BYTES + 1)
136
- except (OSError, UnicodeDecodeError):
137
- return None
138
- if not raw or len(raw) > _MAX_STDIN_BYTES:
139
- return None
140
- try:
141
- payload = json.loads(raw)
142
- except (json.JSONDecodeError, ValueError):
143
- return None
144
- if not isinstance(payload, dict):
145
- return None
146
- return payload
147
-
148
-
149
- def _parse_tool_input(raw):
150
- """tool_input as a dict, or as a JSON-encoded string -> dict; {} otherwise."""
151
- if isinstance(raw, dict):
152
- return raw
153
- if isinstance(raw, str) and raw:
154
- try:
155
- parsed = json.loads(raw)
156
- if isinstance(parsed, dict):
157
- return parsed
158
- except (json.JSONDecodeError, ValueError):
159
- pass
160
- return {}
161
-
162
-
163
- def decode_payload(payload):
164
- """Normalize a Cursor hook payload into a flat, safe dict.
165
-
166
- ``conversation_id`` wins over ``session_id`` (sessionStart carries only
167
- session_id; the tool events carry conversation_id). ``workspace_roots`` is
168
- the list Cursor exports; ``cwd`` is capped at 1024 chars because it is
169
- rewritten into the tally on every tool call and into restore-context.
170
- Missing fields default to empty values so callers never KeyError.
171
- """
172
- out = {
173
- "tool_name": "",
174
- "tool_args": {},
175
- "conversation_id": "",
176
- "hook_event_name": "",
177
- "cwd": "",
178
- "cursor_version": "",
179
- "workspace_roots": [],
180
- "transcript_path": None,
181
- "model": None,
182
- "timestamp": None,
183
- # preCompact numbers (0/0.0 when absent or the payload is not a dict)
184
- "context_tokens": 0,
185
- "context_window_size": 0,
186
- "context_usage_percent": 0.0,
187
- "trigger": "",
188
- }
189
- if not isinstance(payload, dict):
190
- return out
191
-
192
- tool_name = payload.get("tool_name", payload.get("toolName", ""))
193
- if isinstance(tool_name, str):
194
- out["tool_name"] = tool_name.strip()
195
- out["tool_args"] = _parse_tool_input(
196
- payload.get("tool_input", payload.get("toolInput", {}))
197
- )
198
-
199
- sid = payload.get("conversation_id", payload.get("session_id", ""))
200
- if isinstance(sid, str):
201
- out["conversation_id"] = _sanitize_session_id(sid)
202
-
203
- event = payload.get("hook_event_name", "")
204
- if isinstance(event, str):
205
- out["hook_event_name"] = event.strip()
206
-
207
- cwd = payload.get("cwd", "")
208
- if isinstance(cwd, str):
209
- out["cwd"] = cwd[:1024]
210
-
211
- version = payload.get("cursor_version", "")
212
- if isinstance(version, str):
213
- out["cursor_version"] = version[:64]
214
-
215
- roots = payload.get("workspace_roots")
216
- if isinstance(roots, list):
217
- out["workspace_roots"] = [
218
- str(r)[:1024] for r in roots if isinstance(r, str)
219
- ][:8]
220
-
221
- tp = payload.get("transcript_path")
222
- if isinstance(tp, str):
223
- out["transcript_path"] = tp[:1024]
224
-
225
- model = payload.get("model")
226
- if isinstance(model, str):
227
- out["model"] = model[:128]
228
-
229
- out["timestamp"] = payload.get("timestamp")
230
-
231
- for key in ("context_tokens", "context_window_size"):
232
- try:
233
- out[key] = int(payload.get(key) or 0)
234
- except (TypeError, ValueError):
235
- out[key] = 0
236
- try:
237
- out["context_usage_percent"] = float(payload.get("context_usage_percent") or 0.0)
238
- except (TypeError, ValueError):
239
- out["context_usage_percent"] = 0.0
240
- trigger = payload.get("trigger")
241
- if isinstance(trigger, str):
242
- out["trigger"] = trigger
243
- return out
136
+ # seam wrapper: tests monkeypatch this name on the bridge
137
+ return cursor_bridge_payload._read_stdin_payload()
244
138
 
245
139
 
246
140
  # ---------------------------------------------------------------------------
@@ -255,6 +149,10 @@ def _to_dir():
255
149
  try:
256
150
  d = cursor_home() / "token-optimizer"
257
151
  d.mkdir(parents=True, exist_ok=True)
152
+ try:
153
+ os.chmod(d, 0o700) # session tallies/ledger hold file contents (G1)
154
+ except OSError:
155
+ pass
258
156
  return d
259
157
  except OSError:
260
158
  return None
@@ -274,11 +172,18 @@ def _sessions_dir():
274
172
 
275
173
 
276
174
  def _atomic_write_json(path, obj):
277
- """Atomic JSON write via codex_io; concurrent writers never corrupt."""
175
+ """Atomic JSON write via codex_io; concurrent writers never corrupt.
176
+
177
+ replace_symlink=True: codex_io FOLLOWS a symlinked destination by default
178
+ (dotfile-manager contract), which would redirect a tally/pending-rewrite
179
+ write through an attacker-planted link into a victim file (G1-F2, proven
180
+ with byte-level victim replacement). Our data-dir files must always
181
+ replace the link itself.
182
+ """
278
183
  if _atomic_write_json_impl is None:
279
184
  return False
280
185
  try:
281
- _atomic_write_json_impl(path, obj)
186
+ _atomic_write_json_impl(path, obj, replace_symlink=True)
282
187
  return True
283
188
  except OSError:
284
189
  return False
@@ -301,7 +206,19 @@ def _record_observed(event, **extra):
301
206
  }
302
207
  entry.update({k: v for k, v in extra.items() if v is not None})
303
208
  try:
304
- with (to_dir / "observed-events.jsonl").open("a", encoding="utf-8") as fh:
209
+ ledger = to_dir / "observed-events.jsonl"
210
+ # O_NOFOLLOW where the platform has it: a symlinked ledger must never
211
+ # redirect the append into a victim file (G1). 0o600 on create.
212
+ flags = os.O_WRONLY | os.O_CREAT | os.O_APPEND
213
+ if hasattr(os, "O_NOFOLLOW"):
214
+ flags |= os.O_NOFOLLOW
215
+ fd = os.open(str(ledger), flags, 0o600)
216
+ try:
217
+ if hasattr(os, "fchmod"):
218
+ os.fchmod(fd, 0o600) # tighten a pre-existing 0o644 ledger
219
+ except OSError:
220
+ pass
221
+ with os.fdopen(fd, "a", encoding="utf-8") as fh:
305
222
  fh.write(json.dumps(entry, default=str) + "\n")
306
223
  except OSError:
307
224
  # Log once per process: on a persistently unwritable data dir this fires
@@ -329,6 +246,10 @@ def _tally_path(fields):
329
246
  def _load_tally(path):
330
247
  if path is None or not path.exists():
331
248
  return None
249
+ if path.is_symlink():
250
+ # A planted link reads attacker-chosen bytes into the tally RMW; treat
251
+ # it as absent (the next write replaces the link itself).
252
+ return None
332
253
  try:
333
254
  data = json.loads(path.read_text(encoding="utf-8"))
334
255
  return data if isinstance(data, dict) else None
@@ -343,6 +264,15 @@ def _session_lock(to_dir, sid):
343
264
  Fail-open on contention: a contender skips after 75ms rather than blocking
344
265
  a Cursor hot path. The tally is a soft counter, so a skipped update is
345
266
  tolerable. A missing ``hook_runtime`` (broken install) proceeds unlocked.
267
+
268
+ Every Cursor hook event is its own process, so the default cohort
269
+ throttle (reuse_wall = lease expiry) would suppress every distinct-PID
270
+ acquirer for ~10s after a clean release and silently drop tally updates
271
+ (G2 P1, executed repro: 2 of 3 sequential events lost). Distinct
272
+ mutation writers opt out via ``cohort_throttle=False``;
273
+ ``reclaim_released=True`` lets a cleanly FINISHED event's successor in
274
+ without ever stealing a LIVE lease (release marker is written only on
275
+ clean finish).
346
276
  """
347
277
  if to_dir is None or sid in (None, "", "unknown"):
348
278
  yield False
@@ -357,13 +287,15 @@ def _session_lock(to_dir, sid):
357
287
  yield True
358
288
  return
359
289
  lock_path = lock_dir / f"{sid}.lock"
360
- with lease_lock(lock_path, acquire_timeout=0.075) as acquired:
290
+ with lease_lock(lock_path, acquire_timeout=0.075,
291
+ cohort_throttle=False, reclaim_released=True) as acquired:
361
292
  yield acquired
362
293
 
363
294
 
364
295
  def _update_tally(fields, *, terminal=False, end_reason=None,
365
296
  increment_turns=False, count_tool=False, compaction=None,
366
- bump_nudge=False):
297
+ bump_nudge=False, hook_tokens=None, failure=False,
298
+ subagent=False, compact_checkpoint=None, restore_pending=None):
367
299
  """Read-modify-write the session tally; returns ``(tally, nudge_emitted)``.
368
300
 
369
301
  Non-terminal activity reopens an idle/sessionEnd-finalised tally (final set
@@ -426,6 +358,29 @@ def _update_tally(fields, *, terminal=False, end_reason=None,
426
358
  comps.append(compaction)
427
359
  tally["compactions"] = comps[-200:]
428
360
 
361
+ if compact_checkpoint is not None:
362
+ tally["compact_checkpoint"] = compact_checkpoint
363
+ if restore_pending is not None:
364
+ tally["restore_pending"] = bool(restore_pending)
365
+
366
+ if hook_tokens is not None:
367
+ hm = tally.setdefault("hook_measured_tokens", {
368
+ "input": 0, "output": 0, "cache_read": 0, "cache_write": 0,
369
+ "responses": 0, "source": "cursor_hook_measured",
370
+ })
371
+ for k in ("input", "output", "cache_read", "cache_write"):
372
+ hm[k] = int(hm.get(k, 0) or 0) + int(hook_tokens.get(k) or 0)
373
+ hm["responses"] = int(hm.get("responses", 0) or 0) + 1
374
+ hm["source"] = "cursor_hook_measured"
375
+
376
+ if failure:
377
+ fails = tally.setdefault("failures", {})
378
+ fname = fields.get("tool_name") or "tool"
379
+ fails[fname] = int(fails.get(fname, 0) or 0) + 1
380
+
381
+ if subagent:
382
+ tally["subagents"] = int(tally.get("subagents", 0) or 0) + 1
383
+
429
384
  # Context-growth nudge (R10), folded into THIS locked RMW: computing it
430
385
  # in the caller needed a second lock (and a gap a concurrent stop/
431
386
  # preCompact could exploit to clobber either the tool_calls increment
@@ -444,6 +399,31 @@ def _update_tally(fields, *, terminal=False, end_reason=None,
444
399
  return tally, nudge_emitted
445
400
 
446
401
 
402
+ def _claim_restore(fields):
403
+ """Atomically claim a pending compact restore; checkpoint path or None.
404
+
405
+ The restore_pending pop happens inside ONE locked RMW, so concurrent
406
+ postToolUse processes (each its own PID) can never both observe True:
407
+ only the claimer emits the restore (G2 P2). Fail-open: a skipped claim
408
+ just defers the restore to the next event.
409
+ """
410
+ to_dir = _to_dir()
411
+ path = _tally_path(fields) if to_dir is not None else None
412
+ if path is None:
413
+ return None
414
+ sid = fields.get("conversation_id") or "unknown"
415
+ with _session_lock(to_dir, sid) as acquired:
416
+ if not acquired:
417
+ return None
418
+ tally = _load_tally(path)
419
+ if not tally or not tally.get("restore_pending"):
420
+ return None
421
+ tally["restore_pending"] = False
422
+ tally["updated_at"] = time.time()
423
+ _atomic_write_json(path, tally)
424
+ return tally.get("compact_checkpoint")
425
+
426
+
447
427
  # ---------------------------------------------------------------------------
448
428
  # Restore context (per workspace)
449
429
  # ---------------------------------------------------------------------------
@@ -457,56 +437,9 @@ def _workspace_root(fields):
457
437
 
458
438
 
459
439
  def _restore_for_workspace(fields):
460
- """Return the restore-context for THIS workspace, or None.
461
-
462
- Cursor IDE runs many concurrent chats across repos, so a single global
463
- restore file would seed every new chat with whichever conversation rolled
464
- up last. Files are keyed by ``sha1(workspace_root)`` and injected only for
465
- the matching root. Injection is skipped while a non-final sibling tally in
466
- that workspace has activity in the last 10 minutes.
467
- """
468
- root = _workspace_root(fields)
469
- to_dir = _to_dir()
470
- if to_dir is None or not root:
471
- return None
472
-
473
- sdir = _sessions_dir()
474
- now = time.time()
475
- own_id = fields.get("conversation_id") or ""
476
- if sdir is not None:
477
- try:
478
- for p in sdir.glob("*.json"):
479
- t = _load_tally(p)
480
- if not t or t.get("final"):
481
- continue
482
- # Exclude the session being started: its own freshly-written
483
- # tally is active by definition and must not suppress restore.
484
- if own_id and str(t.get("conversation_id") or "") == own_id:
485
- continue
486
- troot = None
487
- wroots = t.get("workspace_roots")
488
- if isinstance(wroots, list) and wroots and isinstance(wroots[0], str):
489
- troot = wroots[0]
490
- else:
491
- troot = t.get("cwd")
492
- if str(troot) == str(root):
493
- try:
494
- if now - float(t.get("updated_at") or 0) < _ACTIVE_WORKSPACE_SECS:
495
- return None
496
- except (TypeError, ValueError):
497
- pass
498
- except OSError:
499
- pass
500
-
501
- digest = hashlib.sha1(root.encode("utf-8", "replace")).hexdigest()
502
- path = to_dir / "restore-context" / f"{digest}.md"
503
- try:
504
- if path.exists() and path.stat().st_size <= _RESTORE_MAX_BYTES:
505
- text = path.read_text(encoding="utf-8").strip()
506
- return text or None
507
- except OSError:
508
- return None
509
- return None
440
+ return cursor_bridge_checkpoint.restore_for_workspace(
441
+ fields, _workspace_root(fields), _to_dir(), _sessions_dir(), _load_tally,
442
+ _ACTIVE_WORKSPACE_SECS)
510
443
 
511
444
 
512
445
  # ---------------------------------------------------------------------------
@@ -515,6 +448,12 @@ def _restore_for_workspace(fields):
515
448
 
516
449
 
517
450
  def _compression_enabled():
451
+ # Native Windows stays record-only: the rewrite quotes with shlex
452
+ # (POSIX single quotes), which cmd.exe does not honor, and which host
453
+ # shell Cursor's Windows Shell tool actually uses is unverified - an
454
+ # unsafe rewrite is worse than no rewrite (G4). POSIX shells keep it.
455
+ if os.name == "nt":
456
+ return False
518
457
  return (
519
458
  _bash_hook is not None
520
459
  and _COMPRESS_AVAILABLE
@@ -542,21 +481,6 @@ _NUDGE_TEXT = (
542
481
  # ---------------------------------------------------------------------------
543
482
 
544
483
 
545
- def _measure_env(interactive=False):
546
- env = dict(os.environ)
547
- env["TOKEN_OPTIMIZER_RUNTIME"] = "cursor"
548
- env["PYTHONUTF8"] = "1"
549
- env["PYTHONIOENCODING"] = "utf-8"
550
- if interactive:
551
- env["TOKEN_OPTIMIZER_INTERACTIVE"] = "1"
552
- return env
553
-
554
-
555
- # The installer does NOT copy measure.py into the plugin dir (version-drift
556
- # risk); it writes a one-line "measure-path" locator next to this bridge naming
557
- # the canonical measure.py in the checkout. Resolution order: a sibling
558
- # measure.py (dev/test checkout), then the locator. Mirrors
559
- # hermes_hook_bridge._locate_measure_py.
560
484
  _MEASURE_LOCATOR = _SCRIPT_DIR / "measure-path"
561
485
 
562
486
 
@@ -582,40 +506,13 @@ def _locate_measure_py():
582
506
 
583
507
 
584
508
  def _spawn_rollup():
585
- # cursor-doctor --probe replays the installed command to prove it fires;
586
- # it must not trigger a real detached rollup/dashboard as a side effect.
587
- if os.environ.get("TOKEN_OPTIMIZER_PROBE") == "1":
588
- return
589
- measure = _locate_measure_py()
590
- if measure is None:
591
- return
592
- try:
593
- spawn_detached(
594
- [sys.executable, str(measure), "cursor-rollup", "--quiet"],
595
- env=_measure_env(),
596
- stdout=subprocess.DEVNULL,
597
- stderr=subprocess.DEVNULL,
598
- )
599
- except (OSError, subprocess.SubprocessError):
600
- logger.warning("[cursor_hook_bridge] detached rollup spawn failed", exc_info=True)
509
+ # seam wrapper: bridge globals resolved at call time (tests monkeypatch them)
510
+ return cursor_bridge_rollup._spawn_rollup(_locate_measure_py, spawn_detached)
601
511
 
602
512
 
603
513
  def _spawn_dashboard():
604
- # Same probe guard as _spawn_rollup(): replay must not spawn detached work.
605
- if os.environ.get("TOKEN_OPTIMIZER_PROBE") == "1":
606
- return
607
- measure = _locate_measure_py()
608
- if measure is None:
609
- return
610
- try:
611
- spawn_detached(
612
- [sys.executable, str(measure), "dashboard", "--quiet"],
613
- env=_measure_env(interactive=True),
614
- stdout=subprocess.DEVNULL,
615
- stderr=subprocess.DEVNULL,
616
- )
617
- except (OSError, subprocess.SubprocessError):
618
- logger.warning("[cursor_hook_bridge] detached dashboard spawn failed", exc_info=True)
514
+ # seam wrapper: bridge globals resolved at call time (tests monkeypatch them)
515
+ return cursor_bridge_rollup._spawn_dashboard(_locate_measure_py, spawn_detached)
619
516
 
620
517
 
621
518
  def _stop_rollup_due():
@@ -647,42 +544,13 @@ def _stop_rollup_due():
647
544
 
648
545
 
649
546
  def _stop_rollup_due_locked(state, now):
650
- last = None
651
- try:
652
- if state.exists():
653
- data = json.loads(state.read_text(encoding="utf-8"))
654
- if isinstance(data, dict):
655
- last = float(data.get("last", 0) or 0)
656
- except (OSError, json.JSONDecodeError, ValueError, TypeError):
657
- last = None
658
- if last is not None and now - last < _STOP_ROLLUP_SECS:
659
- return False
660
- # Fail closed: if the throttle-state write fails (disk full, read-only data
661
- # dir), do NOT spawn — otherwise every stop would spawn a rollup+dashboard
662
- # storm precisely under the degraded conditions the throttle is meant to
663
- # contain. _atomic_write_json returns True only on a successful write.
664
- return _atomic_write_json(state, {"last": now})
547
+ # seam wrapper: _atomic_write_json resolved from bridge globals at call time
548
+ return cursor_bridge_rollup._stop_rollup_due_locked(state, now, _atomic_write_json)
665
549
 
666
550
 
667
551
  def _sweep_stale_locks():
668
- """Remove stale lock/candidate artifacts (7d) on sessionStart. Never fatal."""
669
- to_dir = _to_dir()
670
- if to_dir is None:
671
- return
672
- lock_dir = to_dir / ".locks"
673
- if not lock_dir.is_dir():
674
- return
675
- now = time.time()
676
- try:
677
- for pattern in ("*.lock", ".*.lock.candidate-*"):
678
- for p in lock_dir.glob(pattern):
679
- try:
680
- if now - p.stat().st_mtime > _STALE_LOCK_SECS:
681
- p.unlink()
682
- except OSError:
683
- continue
684
- except OSError:
685
- pass
552
+ # seam wrapper: _to_dir resolved from bridge globals at call time
553
+ return cursor_bridge_rollup._sweep_stale_locks(_to_dir())
686
554
 
687
555
 
688
556
  # ---------------------------------------------------------------------------
@@ -708,12 +576,45 @@ def handle_session_start(payload):
708
576
 
709
577
 
710
578
  def handle_pre_tool_use(payload):
711
- """Shell bash-compression via updated_input, gated and fail-closed."""
579
+ """Shell bash-compression via updated_input, gated and fail-closed.
580
+
581
+ Read interception (U2) runs through cursor_read_cache: shadow by
582
+ default, deny + user_message only under an explicit per-install mode,
583
+ fail-open on every uncertainty.
584
+ """
712
585
  fields = decode_payload(payload)
586
+ if fields["tool_name"] == "Read":
587
+ try:
588
+ import cursor_read_cache
589
+
590
+ decision = cursor_read_cache.evaluate(fields)
591
+ except Exception:
592
+ decision = None
593
+ if decision is not None:
594
+ emit = decision.get("emit")
595
+ if emit:
596
+ _emit(emit)
597
+ observed = decision.get("observed")
598
+ if isinstance(observed, dict):
599
+ _record_observed("readCache",
600
+ conversation_id=fields["conversation_id"] or None,
601
+ **observed)
602
+ else:
603
+ # Not an interceptable read (ineligible, first read elsewhere,
604
+ # fail-open): keep the plain observed record.
605
+ _record_observed("preToolUse",
606
+ conversation_id=fields["conversation_id"] or None,
607
+ tool_name=fields["tool_name"] or None,
608
+ rewrite=None)
609
+ return
713
610
  rewrite = None
714
611
  if fields["tool_name"] == "Shell" and _compression_enabled():
715
612
  command = fields["tool_args"].get("command")
716
- if isinstance(command, str) and command:
613
+ # G0: cap BEFORE the whitelist/shlex path - shlex.split is quadratic
614
+ # on hostile lengths (measured: 300KB=2s, 1MB=23.7s) and the stdin
615
+ # cap permits multi-MB commands. Oversized commands pass through
616
+ # uncompressed; compression is a savings feature, never a gate.
617
+ if isinstance(command, str) and 0 < len(command) <= _MAX_REWRITE_COMMAND_BYTES:
717
618
  # The rewrite is emitted with permission "allow", so it is limited
718
619
  # to commands that cannot write, delete or run other programs.
719
620
  if _bash_hook._is_auto_approvable(command):
@@ -733,8 +634,10 @@ def handle_pre_tool_use(payload):
733
634
  updated = dict(fields["tool_args"])
734
635
  updated["command"] = rewritten
735
636
  _emit({"permission": "allow", "updated_input": updated})
637
+ _stage_pending_rewrite(fields, rewritten)
736
638
  rewrite = "attempted"
737
639
  _record_observed("preToolUse",
640
+ conversation_id=fields["conversation_id"] or None,
738
641
  tool_name=fields["tool_name"] or None,
739
642
  rewrite=rewrite)
740
643
 
@@ -742,31 +645,113 @@ def handle_pre_tool_use(payload):
742
645
  def handle_post_tool_use(payload):
743
646
  """Update the tally and, for Shell, record whether the rewrite was honoured.
744
647
 
745
- Cursor's postToolUse tool_input carries the command as actually executed:
746
- ``command`` containing ``bash_compress.py`` proves the rewrite was honoured;
747
- a whitelisted command that arrived bare proves it was ignored.
648
+ G0: honoured/ignored is PAIRED, never inferred from substrings. preToolUse
649
+ stages the exact rewritten command under this tool_use_id; postToolUse
650
+ compares the executed command against it byte-for-byte. No staged attempt
651
+ means unknown - neither honoured nor ignored is provable (a bare
652
+ whitelisted command or an executed 'ls bash_compress.py' both say
653
+ nothing), and the old substring heuristic lied in both directions.
748
654
  """
749
655
  fields = decode_payload(payload)
750
656
  rewrite = None
751
657
  if fields["tool_name"] == "Shell" and _compression_enabled():
752
- command = fields["tool_args"].get("command")
753
- if isinstance(command, str) and command:
754
- if not _bash_hook._has_dangerous_chars(command) and _bash_hook._is_whitelisted(command):
755
- rewrite = "honoured" if "bash_compress.py" in command else "ignored"
658
+ rewrite = _classify_rewrite(fields)
659
+ read_path = None
660
+ if fields["tool_name"] == "Read":
661
+ try:
662
+ import cursor_read_cache
663
+ cursor_read_cache.confirm_read(fields)
664
+ except Exception:
665
+ pass
666
+ rp = fields["tool_args"].get("file_path")
667
+ if isinstance(rp, str) and rp:
668
+ read_path = Path(rp).name
756
669
  _record_observed("postToolUse",
670
+ conversation_id=fields["conversation_id"] or None,
757
671
  tool_name=fields["tool_name"] or None,
672
+ path=read_path,
758
673
  rewrite=rewrite)
759
674
 
760
675
  tally, nudge_emitted = _update_tally(fields, count_tool=True, bump_nudge=True)
761
676
  if tally is None:
762
677
  return
763
- if nudge_emitted:
764
- _emit({"additional_context": _NUDGE_TEXT})
678
+ nudges = [_NUDGE_TEXT] if nudge_emitted else []
679
+ # U3: post-compaction restore - exactly one bounded inject, then clear.
680
+ # Consecutive compactions without a tool call coalesce to this one.
681
+ # The claim pops restore_pending inside ONE locked RMW: with distinct
682
+ # hook processes no longer suppressed, a check-then-clear across two
683
+ # locks would let concurrent postToolUse events both emit (G2 P2).
684
+ cp = _claim_restore(fields)
685
+ if isinstance(cp, str) and cp:
686
+ restore_text = _read_checkpoint_bounded(cp)
687
+ if restore_text:
688
+ nudges.append(restore_text)
689
+ _record_observed("compactRestore",
690
+ conversation_id=fields["conversation_id"] or None,
691
+ emitted=True)
692
+ # U5 thrash guard: same streak/burn/inline-script logic as Claude,
693
+ # nudge-only, fail-open (cursor_thrash owns the env bridging).
694
+ if fields["tool_name"] == "Shell":
695
+ try:
696
+ import cursor_thrash
697
+ thrash = cursor_thrash.shell_thrash_nudge(fields)
698
+ except Exception:
699
+ thrash = None
700
+ if thrash:
701
+ nudges.append(thrash)
702
+ _record_observed("thrashNudge", nudge="thrash")
703
+ if nudges:
704
+ _emit({"additional_context": "\n".join(nudges)})
705
+
706
+
707
+ _MAX_REWRITE_COMMAND_BYTES = 8_192 # shlex is quadratic past this (G0)
708
+
709
+
710
+ def _pending_rewrite_path(fields):
711
+ # seam wrapper: _to_dir resolved from bridge globals at call time
712
+ return cursor_bridge_rewrite._pending_rewrite_path(fields, _to_dir())
713
+
714
+
715
+ def _stage_pending_rewrite(fields, rewritten):
716
+ # seam wrapper: _to_dir + _atomic_write_json resolved from bridge globals at call time
717
+ return cursor_bridge_rewrite._stage_pending_rewrite(
718
+ fields, rewritten, to_dir=_to_dir(), atomic_write=_atomic_write_json)
719
+
720
+
721
+ def _classify_rewrite(fields):
722
+ # seam wrapper: _to_dir resolved from bridge globals at call time
723
+ return cursor_bridge_rewrite._classify_rewrite(fields, to_dir=_to_dir())
724
+
725
+
726
+ def _capture_compact_checkpoint(fields):
727
+ # seam wrapper: cursor_home + _locate_measure_py resolved from bridge
728
+ # globals at call time (tests monkeypatch both)
729
+ home = cursor_home() if cursor_home is not None else None
730
+ return cursor_bridge_checkpoint._capture_compact_checkpoint(
731
+ fields, home, _locate_measure_py)
732
+
733
+
734
+ def _read_checkpoint_bounded(path_str):
735
+ # seam wrapper: cursor_home resolved from bridge globals at call time
736
+ home = cursor_home() if cursor_home is not None else None
737
+ return cursor_bridge_checkpoint._read_checkpoint_bounded(path_str, home)
765
738
 
766
739
 
767
740
  def handle_pre_compact(payload):
768
- """Record Cursor's real context numbers and compaction trigger."""
741
+ """Record Cursor's real context numbers and compaction trigger.
742
+
743
+ U3: when the payload names a transcript, capture a redacted checkpoint
744
+ through the U1 adapter + compact_capture and mark restore-pending; the
745
+ next postToolUse emits exactly one bounded restore. The preCompact
746
+ ``user_message`` note is emitted and ledgered as ``emitted`` - delivery
747
+ into Cursor's UI is claimed only with positive native evidence.
748
+ """
769
749
  fields = decode_payload(payload)
750
+ try:
751
+ import cursor_read_cache
752
+ cursor_read_cache.clear_session_reads(fields.get("cache_conversation_id") or fields["conversation_id"])
753
+ except Exception:
754
+ pass
770
755
  _record_observed("preCompact", conversation_id=fields["conversation_id"] or None)
771
756
  _update_tally(
772
757
  fields,
@@ -778,6 +763,18 @@ def handle_pre_compact(payload):
778
763
  "ts": time.time(),
779
764
  },
780
765
  )
766
+ try:
767
+ checkpoint = _capture_compact_checkpoint(fields)
768
+ except Exception:
769
+ checkpoint = None # fail-open: never raise into Cursor
770
+ if checkpoint:
771
+ _update_tally(fields, compact_checkpoint=checkpoint, restore_pending=True)
772
+ _record_observed("compactCapture",
773
+ conversation_id=fields["conversation_id"] or None,
774
+ checkpoint=os.path.basename(checkpoint))
775
+ _emit({"user_message":
776
+ "Token Optimizer: checkpoint captured before compaction; "
777
+ "it will be offered back after the context rebuild."})
781
778
 
782
779
 
783
780
  def handle_stop(payload):
@@ -801,6 +798,119 @@ def handle_session_end(payload):
801
798
  _spawn_dashboard()
802
799
 
803
800
 
801
+ _RESPONSE_TOKEN_KEYS = (
802
+ "input_tokens",
803
+ "output_tokens",
804
+ "cache_read_tokens",
805
+ "cache_write_tokens",
806
+ )
807
+
808
+
809
+ def _opt_nonneg_int(value):
810
+ """Plausible token count or None: rejects bools, negatives, non-numerics,
811
+ and non-integral floats (1.5 silently truncating to 1 would misstate the
812
+ observed count; G5)."""
813
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
814
+ return None
815
+ if isinstance(value, float) and not value.is_integer():
816
+ return None
817
+ try:
818
+ ivalue = int(value)
819
+ except (TypeError, ValueError):
820
+ return None
821
+ return ivalue if ivalue >= 0 else None
822
+
823
+
824
+ def handle_after_agent_response(payload):
825
+ """Record the event; ingest real per-response tokens when plausible (KTD3).
826
+
827
+ The token fields are third-party-observed and undocumented by Cursor, so
828
+ they are a candidate source only: present + plausible values accumulate
829
+ into the tally flagged ``cursor_hook_measured``; anything else leaves the
830
+ existing source ordering untouched. Record-only: never emits.
831
+ """
832
+ fields = decode_payload(payload)
833
+ raw = payload if isinstance(payload, dict) else {}
834
+ present = [k for k in _RESPONSE_TOKEN_KEYS if k in raw]
835
+ state = "absent"
836
+ tokens = None
837
+ if present:
838
+ vals = {k: _opt_nonneg_int(raw.get(k)) for k in present}
839
+ if all(v is not None for v in vals.values()):
840
+ state = "measured"
841
+ tokens = {
842
+ "input": vals.get("input_tokens") or 0,
843
+ "output": vals.get("output_tokens") or 0,
844
+ "cache_read": vals.get("cache_read_tokens") or 0,
845
+ "cache_write": vals.get("cache_write_tokens") or 0,
846
+ }
847
+ else:
848
+ state = "rejected"
849
+ _record_observed("afterAgentResponse",
850
+ conversation_id=fields["conversation_id"] or None,
851
+ generation_id=fields["generation_id"] or None,
852
+ tokens=state)
853
+ if tokens is not None:
854
+ _update_tally(fields, hook_tokens=tokens)
855
+
856
+
857
+ def _redact_for_ledger(text):
858
+ """Redact before the observed-events ledger; fail CLOSED (drop the field).
859
+
860
+ Redaction runs on the full string BEFORE any truncation - a mid-shape
861
+ cut could slice a credential past its pattern's anchors (G1).
862
+ """
863
+ try:
864
+ from credential_patterns import redact_credentials
865
+
866
+ redacted = redact_credentials(text)
867
+ return redacted if isinstance(redacted, str) else None
868
+ except Exception:
869
+ return None
870
+
871
+
872
+ def handle_post_tool_use_failure(payload):
873
+ """Count tool failures by tool name; feeds the R9 burn signal. Record-only."""
874
+ fields = decode_payload(payload)
875
+ error = payload.get("error") if isinstance(payload, dict) else None
876
+ redacted_error = _redact_for_ledger(str(error)) if error is not None else None
877
+ _record_observed("postToolUseFailure",
878
+ conversation_id=fields["conversation_id"] or None,
879
+ tool_name=fields["tool_name"] or None,
880
+ tool_use_id=fields["tool_use_id"] or None,
881
+ error=redacted_error[:256] if redacted_error is not None else None)
882
+ if fields["conversation_id"]:
883
+ _update_tally(fields, failure=True)
884
+
885
+
886
+ def handle_after_shell_execution(payload):
887
+ """Record shell completion; postToolUse owns rewrite classification."""
888
+ fields = decode_payload(payload)
889
+ output = payload.get("output") if isinstance(payload, dict) else None
890
+ _record_observed("afterShellExecution",
891
+ conversation_id=fields["conversation_id"] or None,
892
+ tool_use_id=fields["tool_use_id"] or None,
893
+ output_len=len(output) if isinstance(output, str) else None)
894
+
895
+
896
+ def handle_subagent_start(payload):
897
+ """Record subagent fan-out; counted once per start for fleet rows."""
898
+ fields = decode_payload(payload)
899
+ _record_observed("subagentStart",
900
+ conversation_id=fields["conversation_id"] or None,
901
+ tool_use_id=fields["tool_use_id"] or None)
902
+ if fields["conversation_id"]:
903
+ _update_tally(fields, subagent=True)
904
+
905
+
906
+ def handle_subagent_stop(payload):
907
+ """Record subagent completion. Record-only; the start already counted."""
908
+ fields = decode_payload(payload)
909
+ _record_observed("subagentStop",
910
+ conversation_id=fields["conversation_id"] or None,
911
+ tool_use_id=fields["tool_use_id"] or None)
912
+
913
+
804
914
  _HANDLERS = {
805
915
  "sessionStart": handle_session_start,
806
916
  "preToolUse": handle_pre_tool_use,
@@ -808,10 +918,17 @@ _HANDLERS = {
808
918
  "preCompact": handle_pre_compact,
809
919
  "stop": handle_stop,
810
920
  "sessionEnd": handle_session_end,
921
+ "afterAgentResponse": handle_after_agent_response,
922
+ "postToolUseFailure": handle_post_tool_use_failure,
923
+ "afterShellExecution": handle_after_shell_execution,
924
+ "subagentStart": handle_subagent_start,
925
+ "subagentStop": handle_subagent_stop,
811
926
  }
812
927
 
813
928
 
814
929
  def main(argv=None):
930
+ if decode_payload is None: # broken install: bridge helper modules missing; fail open
931
+ return 0
815
932
  try:
816
933
  from utf8_io import enforce_utf8_io
817
934
  enforce_utf8_io()