@alexgreensh/token-optimizer 5.13.68 → 5.13.70

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 (182) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/PRIVACY.md +4 -0
  4. package/hooks/hooks.json +11 -1
  5. package/hooks/module_runner.py +4 -1
  6. package/hooks/posttooluse_runner.py +44 -48
  7. package/hooks/sessionstart_runner.py +24 -5
  8. package/hooks/stop_runner.py +6 -6
  9. package/package.json +1 -1
  10. package/skills/fleet-auditor/references/fleet-systems.md +38 -0
  11. package/skills/fleet-auditor/scripts/fleet.py +63 -92
  12. package/skills/fleet-auditor/scripts/fleet_base.py +106 -0
  13. package/skills/fleet-auditor/scripts/fleet_cursor_adapter.py +376 -0
  14. package/skills/token-coach/SKILL.md +21 -23
  15. package/skills/token-dashboard/SKILL.md +5 -4
  16. package/skills/token-optimizer/SKILL.md +1 -1
  17. package/skills/token-optimizer/assets/dashboard.html +492 -551
  18. package/skills/token-optimizer/assets/savings_story.js +661 -0
  19. package/skills/token-optimizer/pricing/prices.json +1 -0
  20. package/skills/token-optimizer/references/cli-reference.md +1 -1
  21. package/skills/token-optimizer/references/cursor-workflow.md +1 -1
  22. package/skills/token-optimizer/references/implementation-playbook.md +3 -0
  23. package/skills/token-optimizer/references/phase0-setup.md +1 -1
  24. package/skills/token-optimizer/references/presentation-workflow.md +1 -1
  25. package/skills/token-optimizer/scripts/_measure/__init__.py +3 -1
  26. package/skills/token-optimizer/scripts/_measure/archive_health.py +14 -0
  27. package/skills/token-optimizer/scripts/_measure/archive_void_codex.py +163 -0
  28. package/skills/token-optimizer/scripts/_measure/archive_void_evidence.py +165 -0
  29. package/skills/token-optimizer/scripts/_measure/audit.py +27 -135
  30. package/skills/token-optimizer/scripts/_measure/baseline_provenance.py +339 -0
  31. package/skills/token-optimizer/scripts/_measure/cache_policy.py +261 -581
  32. package/skills/token-optimizer/scripts/_measure/checkpoint_direction.py +97 -0
  33. package/skills/token-optimizer/scripts/_measure/checkpoint_retention.py +20 -0
  34. package/skills/token-optimizer/scripts/_measure/cli.py +98 -8
  35. package/skills/token-optimizer/scripts/_measure/codex_quality.py +246 -0
  36. package/skills/token-optimizer/scripts/_measure/compaction_survival.py +158 -0
  37. package/skills/token-optimizer/scripts/_measure/compression_fixture_void.py +147 -0
  38. package/skills/token-optimizer/scripts/_measure/compression_scan_checkpoint.py +72 -0
  39. package/skills/token-optimizer/scripts/_measure/context_reset_marker.py +64 -0
  40. package/skills/token-optimizer/scripts/_measure/continuity.py +64 -118
  41. package/skills/token-optimizer/scripts/_measure/cost_per_message_trend.py +40 -0
  42. package/skills/token-optimizer/scripts/_measure/counted_cap.py +28 -0
  43. package/skills/token-optimizer/scripts/_measure/counted_orphans.py +190 -0
  44. package/skills/token-optimizer/scripts/_measure/counted_position.py +20 -0
  45. package/skills/token-optimizer/scripts/_measure/counted_pricing_v5.py +267 -0
  46. package/skills/token-optimizer/scripts/_measure/counted_subagents.py +371 -0
  47. package/skills/token-optimizer/scripts/_measure/coverage_report.py +285 -0
  48. package/skills/token-optimizer/scripts/_measure/daemon.py +61 -94
  49. package/skills/token-optimizer/scripts/_measure/dashboard.py +149 -187
  50. package/skills/token-optimizer/scripts/_measure/dashboard_heal_claim.py +36 -0
  51. package/skills/token-optimizer/scripts/_measure/dashboard_history.py +79 -0
  52. package/skills/token-optimizer/scripts/_measure/evidence_parallel.py +95 -0
  53. package/skills/token-optimizer/scripts/_measure/feature_health.py +256 -0
  54. package/skills/token-optimizer/scripts/_measure/file_refetch.py +250 -0
  55. package/skills/token-optimizer/scripts/_measure/first_call_context.py +216 -0
  56. package/skills/token-optimizer/scripts/_measure/first_read_outcomes.py +261 -0
  57. package/skills/token-optimizer/scripts/_measure/first_read_revive.py +137 -0
  58. package/skills/token-optimizer/scripts/_measure/fixture_context.py +65 -0
  59. package/skills/token-optimizer/scripts/_measure/headline.py +100 -0
  60. package/skills/token-optimizer/scripts/_measure/holdout_fallback.py +96 -0
  61. package/skills/token-optimizer/scripts/_measure/holdout_report.py +125 -0
  62. package/skills/token-optimizer/scripts/_measure/keepwarm_economics.py +201 -0
  63. package/skills/token-optimizer/scripts/_measure/keepwarm_fork.py +140 -0
  64. package/skills/token-optimizer/scripts/_measure/keepwarm_guard.py +35 -0
  65. package/skills/token-optimizer/scripts/_measure/keepwarm_guard_server.py +85 -0
  66. package/skills/token-optimizer/scripts/_measure/keepwarm_linux.py +121 -0
  67. package/skills/token-optimizer/scripts/_measure/keepwarm_prefix.py +143 -0
  68. package/skills/token-optimizer/scripts/_measure/keepwarm_response_filter.py +84 -0
  69. package/skills/token-optimizer/scripts/_measure/keepwarm_safety.py +256 -0
  70. package/skills/token-optimizer/scripts/_measure/lean_resume_receivers.py +260 -0
  71. package/skills/token-optimizer/scripts/_measure/lean_resume_threshold.py +76 -0
  72. package/skills/token-optimizer/scripts/_measure/lease_candidate_cleanup.py +82 -0
  73. package/skills/token-optimizer/scripts/_measure/lifecycle.py +59 -168
  74. package/skills/token-optimizer/scripts/_measure/mcp_archive_tripwire.py +120 -0
  75. package/skills/token-optimizer/scripts/_measure/mod_action_booking.py +178 -0
  76. package/skills/token-optimizer/scripts/_measure/mod_compaction_booking.py +276 -0
  77. package/skills/token-optimizer/scripts/_measure/mod_fresh_booking.py +105 -0
  78. package/skills/token-optimizer/scripts/_measure/output_reread.py +629 -0
  79. package/skills/token-optimizer/scripts/_measure/own_price_card.py +268 -0
  80. package/skills/token-optimizer/scripts/_measure/periphery_exposure.py +85 -0
  81. package/skills/token-optimizer/scripts/_measure/pricing.py +152 -87
  82. package/skills/token-optimizer/scripts/_measure/quality_archive.py +159 -215
  83. package/skills/token-optimizer/scripts/_measure/quality_checkpoint.py +173 -0
  84. package/skills/token-optimizer/scripts/_measure/quality_continuity.py +43 -0
  85. package/skills/token-optimizer/scripts/_measure/rework_metrics.py +194 -0
  86. package/skills/token-optimizer/scripts/_measure/routing_period.py +48 -0
  87. package/skills/token-optimizer/scripts/_measure/savings.py +451 -933
  88. package/skills/token-optimizer/scripts/_measure/savings_story.py +187 -0
  89. package/skills/token-optimizer/scripts/_measure/session_best.py +24 -0
  90. package/skills/token-optimizer/scripts/_measure/session_effect.py +557 -0
  91. package/skills/token-optimizer/scripts/_measure/session_flush_lock.py +75 -0
  92. package/skills/token-optimizer/scripts/_measure/session_store_spool.py +220 -0
  93. package/skills/token-optimizer/scripts/_measure/sessions.py +154 -216
  94. package/skills/token-optimizer/scripts/_measure/setup_attachment_counter.py +196 -0
  95. package/skills/token-optimizer/scripts/_measure/setup_budget_monitor.py +180 -0
  96. package/skills/token-optimizer/scripts/_measure/setup_connector_ledger.py +126 -0
  97. package/skills/token-optimizer/scripts/_measure/setup_step.py +220 -0
  98. package/skills/token-optimizer/scripts/_measure/status_bar_lock.py +117 -0
  99. package/skills/token-optimizer/scripts/_measure/structural_archives.py +79 -0
  100. package/skills/token-optimizer/scripts/_measure/structural_dedupe.py +91 -0
  101. package/skills/token-optimizer/scripts/_measure/structural_ledger.py +418 -0
  102. package/skills/token-optimizer/scripts/_measure/structural_listing.py +163 -0
  103. package/skills/token-optimizer/scripts/_measure/structural_report.py +339 -0
  104. package/skills/token-optimizer/scripts/_measure/structural_seed.py +164 -0
  105. package/skills/token-optimizer/scripts/_measure/structural_value.py +248 -0
  106. package/skills/token-optimizer/scripts/_measure/structure_funnel.py +97 -0
  107. package/skills/token-optimizer/scripts/_measure/timestamp_cache.py +11 -0
  108. package/skills/token-optimizer/scripts/_measure/token_type_split.py +29 -0
  109. package/skills/token-optimizer/scripts/_measure/transcript_backfill.py +419 -0
  110. package/skills/token-optimizer/scripts/_measure/transcript_product.py +228 -0
  111. package/skills/token-optimizer/scripts/_measure/transcript_stream.py +279 -0
  112. package/skills/token-optimizer/scripts/_measure/trends.py +44 -185
  113. package/skills/token-optimizer/scripts/_measure/ttl_period.py +6 -0
  114. package/skills/token-optimizer/scripts/_measure/upgrade_drain_control.py +287 -0
  115. package/skills/token-optimizer/scripts/_measure/weekly_activity.py +69 -0
  116. package/skills/token-optimizer/scripts/activity_tracker.py +4 -33
  117. package/skills/token-optimizer/scripts/antigravity_install.py +6 -0
  118. package/skills/token-optimizer/scripts/archive_result.py +15 -19
  119. package/skills/token-optimizer/scripts/archive_verify.py +165 -0
  120. package/skills/token-optimizer/scripts/bash_compress.py +22 -83
  121. package/skills/token-optimizer/scripts/bash_compress_hook.py +137 -1
  122. package/skills/token-optimizer/scripts/bash_search_results.py +43 -0
  123. package/skills/token-optimizer/scripts/checkpoint_state.py +2 -2
  124. package/skills/token-optimizer/scripts/cloud_kit.py +3 -6
  125. package/skills/token-optimizer/scripts/codemap.py +274 -0
  126. package/skills/token-optimizer/scripts/codemap_hint.py +153 -0
  127. package/skills/token-optimizer/scripts/codemap_index.py +656 -0
  128. package/skills/token-optimizer/scripts/codemap_ledger.py +309 -0
  129. package/skills/token-optimizer/scripts/codemap_reread.py +161 -0
  130. package/skills/token-optimizer/scripts/codex_doctor.py +9 -1
  131. package/skills/token-optimizer/scripts/codex_log_index.py +34 -15
  132. package/skills/token-optimizer/scripts/codex_session.py +16 -216
  133. package/skills/token-optimizer/scripts/compression_backfill.py +4 -35
  134. package/skills/token-optimizer/scripts/context_intel.py +5 -3
  135. package/skills/token-optimizer/scripts/copilot_install.py +6 -0
  136. package/skills/token-optimizer/scripts/coverage_funnel.py +261 -0
  137. package/skills/token-optimizer/scripts/credential_patterns.py +4 -19
  138. package/skills/token-optimizer/scripts/credential_url_patterns.py +42 -0
  139. package/skills/token-optimizer/scripts/cursor_audit.py +723 -0
  140. package/skills/token-optimizer/scripts/cursor_bridge_checkpoint.py +213 -0
  141. package/skills/token-optimizer/scripts/cursor_bridge_payload.py +170 -0
  142. package/skills/token-optimizer/scripts/cursor_bridge_rewrite.py +106 -0
  143. package/skills/token-optimizer/scripts/cursor_bridge_rollup.py +115 -0
  144. package/skills/token-optimizer/scripts/cursor_coach.py +485 -0
  145. package/skills/token-optimizer/scripts/cursor_doctor.py +89 -9
  146. package/skills/token-optimizer/scripts/cursor_hook_bridge.py +393 -276
  147. package/skills/token-optimizer/scripts/cursor_install.py +118 -19
  148. package/skills/token-optimizer/scripts/cursor_quality.py +457 -0
  149. package/skills/token-optimizer/scripts/cursor_read_cache.py +597 -0
  150. package/skills/token-optimizer/scripts/cursor_session.py +26 -5
  151. package/skills/token-optimizer/scripts/cursor_state.py +8 -0
  152. package/skills/token-optimizer/scripts/cursor_statusline.py +372 -0
  153. package/skills/token-optimizer/scripts/cursor_thrash.py +78 -0
  154. package/skills/token-optimizer/scripts/cursor_transcript.py +223 -0
  155. package/skills/token-optimizer/scripts/dashboard_assets.py +21 -0
  156. package/skills/token-optimizer/scripts/deterministic_candidates.py +2 -10
  157. package/skills/token-optimizer/scripts/devin_source.py +19 -4
  158. package/skills/token-optimizer/scripts/devin_verify.py +13 -6
  159. package/skills/token-optimizer/scripts/grok_install.py +6 -0
  160. package/skills/token-optimizer/scripts/heal_report.py +7 -6
  161. package/skills/token-optimizer/scripts/hermes_doctor.py +12 -1
  162. package/skills/token-optimizer/scripts/hermes_install.py +10 -1
  163. package/skills/token-optimizer/scripts/hermes_session.py +14 -136
  164. package/skills/token-optimizer/scripts/hint_paths.py +21 -0
  165. package/skills/token-optimizer/scripts/holdout.py +136 -0
  166. package/skills/token-optimizer/scripts/hook_runtime.py +1 -0
  167. package/skills/token-optimizer/scripts/hook_skip_log.py +89 -0
  168. package/skills/token-optimizer/scripts/large_transcripts.py +31 -0
  169. package/skills/token-optimizer/scripts/lean_resume_carry.py +518 -0
  170. package/skills/token-optimizer/scripts/measure.py +36 -78
  171. package/skills/token-optimizer/scripts/post_run_classify.py +349 -0
  172. package/skills/token-optimizer/scripts/preserved_reinject.py +54 -0
  173. package/skills/token-optimizer/scripts/read_cache.py +99 -100
  174. package/skills/token-optimizer/scripts/reset_epoch.py +3 -3
  175. package/skills/token-optimizer/scripts/session_store.py +49 -99
  176. package/skills/token-optimizer/scripts/session_store_guard.py +75 -0
  177. package/skills/token-optimizer/scripts/settings_backup.py +379 -0
  178. package/skills/token-optimizer/scripts/shipped_hook_templates.py +1 -0
  179. package/skills/token-optimizer/scripts/statusline.js +1 -1
  180. package/skills/token-optimizer/scripts/structural.py +25 -0
  181. package/skills/token-optimizer/scripts/structure_map.py +4 -26
  182. package/skills/token-optimizer/scripts/thrash_guard.py +10 -5
@@ -0,0 +1,213 @@
1
+ """Compact-checkpoint capture and bounded restore reads for the Cursor bridge.
2
+
3
+ Split out of cursor_hook_bridge.py under the repo's 1,000-line file-size
4
+ ratchet (scripts/check_file_size.py). The Cursor home is RESOLVED BY THE
5
+ BRIDGE's same-name wrappers and injected, so tests monkeypatching
6
+ cursor_hook_bridge.cursor_home keep working. Confinement and byte budgets are
7
+ unchanged: only resolved paths under <cursor_home>/token-optimizer are read,
8
+ leaf symlinks refused, and the restore payload stays within its byte budget.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import sys
14
+ import os
15
+ import hashlib
16
+ import time
17
+ from pathlib import Path
18
+
19
+ _RESTORE_MAX_BYTES = 16_384 # restore-context files above this are ignored
20
+ _COMPACT_RESTORE_MAX_BYTES = 8_000 # restore payload cap (bounded inject)
21
+
22
+
23
+ def _import_measure_via_locator(locate_measure_py):
24
+ """Resolve ``import measure`` for an installed bridge (no copied measure).
25
+
26
+ The payload deliberately ships no measure.py (a plugin-dir copy is never
27
+ refreshed, so it would drift from the checkout); the installer-written
28
+ one-line locator names the canonical measure.py. Appending its validated
29
+ parent dir lets the normal import machinery load measure + its _measure
30
+ package from that single source of truth, registering sys.modules
31
+ ['measure'] so the provider facade resolves. Trust boundary is unchanged:
32
+ _locate_measure_py already gates the fire-and-forget rollup/dashboard
33
+ spawns of the same file - a crafted locator could already execute code as
34
+ the user. Fail-open: any error returns None and the capture degrades to
35
+ numbers-only recording.
36
+ """
37
+ try:
38
+ try:
39
+ import measure
40
+ return measure
41
+ except ImportError:
42
+ pass
43
+ if locate_measure_py is None:
44
+ return None
45
+ located = locate_measure_py()
46
+ if located is None:
47
+ return None
48
+ parent = str(Path(located).parent)
49
+ if parent not in sys.path:
50
+ sys.path.append(parent) # append: payload modules keep precedence
51
+ import measure
52
+ return measure
53
+ except Exception:
54
+ return None
55
+
56
+
57
+ def _capture_compact_checkpoint(fields, home, locate_measure_py=None):
58
+ """U3: translate the Cursor disk transcript and capture a checkpoint.
59
+
60
+ Returns the checkpoint path (str) or None. Uses the U1 adapter's
61
+ bundle-proven schema translation and compact_capture's trusted internal
62
+ path; the translated temp file is always removed. Imported ``measure``
63
+ resolves CHECKPOINT_DIR under the Cursor runtime home (CURSOR_VERSION is
64
+ exported to every Cursor hook process), so checkpoint state never lands
65
+ in Claude's ledger. Fail-open: any error returns None and preCompact
66
+ degrades to today's numbers-only recording.
67
+ """
68
+ transcript_path = fields.get("transcript_path")
69
+ sid = fields.get("conversation_id") or ""
70
+ if not transcript_path or not sid:
71
+ return None
72
+ translated = None
73
+ try:
74
+ import cursor_transcript
75
+ from cursor_thrash import _restore_env, _set_env
76
+
77
+ if home is None:
78
+ return None
79
+ translated = cursor_transcript.translate_transcript(
80
+ transcript_path, home, sid
81
+ )
82
+ if translated is None:
83
+ return None
84
+ old_snapshot = _set_env(
85
+ "TOKEN_OPTIMIZER_SNAPSHOT_DIR",
86
+ str(home / "token-optimizer" / "snapshot"),
87
+ )
88
+ try:
89
+ measure = _import_measure_via_locator(locate_measure_py)
90
+ if measure is None:
91
+ return None
92
+
93
+ fill_pct = fields.get("context_usage_percent")
94
+ try:
95
+ fill_pct = float(fill_pct) if fill_pct is not None else None
96
+ except (TypeError, ValueError):
97
+ fill_pct = None
98
+ old_dir, old_log = measure.CHECKPOINT_DIR, measure.CHECKPOINT_EVENT_LOG
99
+ measure.CHECKPOINT_DIR = home / "token-optimizer" / "checkpoints"
100
+ measure.CHECKPOINT_EVENT_LOG = home / "token-optimizer" / "checkpoint-events.jsonl"
101
+ try:
102
+ checkpoint = measure.compact_capture(
103
+ session_id=sid,
104
+ trigger=fields.get("trigger") or "precompact",
105
+ cwd=fields.get("cwd") or None,
106
+ fill_pct=fill_pct,
107
+ _trusted_transcript=translated,
108
+ )
109
+ finally:
110
+ measure.CHECKPOINT_DIR, measure.CHECKPOINT_EVENT_LOG = old_dir, old_log
111
+ finally:
112
+ _restore_env("TOKEN_OPTIMIZER_SNAPSHOT_DIR", old_snapshot)
113
+ return str(checkpoint) if checkpoint else None
114
+ except Exception:
115
+ return None
116
+ finally:
117
+ if translated is not None:
118
+ try:
119
+ translated.unlink()
120
+ except OSError:
121
+ pass
122
+
123
+
124
+ def _read_checkpoint_bounded(path_str, home):
125
+ """Read a checkpoint for restore injection, byte-bounded. Never raises.
126
+
127
+ The tally is forgeable local state: only paths that resolve under our own
128
+ data dir (<cursor_home>/token-optimizer) may be read into model context.
129
+ resolve() collapses parent-directory symlink escapes; the leaf symlink
130
+ check above covers the file itself (G1).
131
+ """
132
+ try:
133
+ path = Path(path_str)
134
+ if not path.is_file() or path.is_symlink():
135
+ return None
136
+ if home is None:
137
+ return None
138
+ root = (home / "token-optimizer").resolve()
139
+ resolved = path.resolve()
140
+ if resolved != root and root not in resolved.parents:
141
+ return None
142
+ if resolved.stat().st_size > _RESTORE_MAX_BYTES:
143
+ return None
144
+ text = resolved.read_text(encoding="utf-8", errors="replace")
145
+ except (OSError, ValueError):
146
+ return None
147
+ body = text.strip()
148
+ if not body:
149
+ return None
150
+ prefix = (
151
+ "Token Optimizer checkpoint captured before compaction "
152
+ "(restore after context rebuild):\n\n"
153
+ )
154
+ marker = "\n\n[truncated: checkpoint exceeds restore budget]"
155
+ # The 8KB contract bounds the WHOLE emitted string (prefix + body +
156
+ # marker) in UTF-8 bytes; cut encoded bytes so multibyte checkpoints
157
+ # cannot inflate the inject (a character cut misses by up to ~4x).
158
+ body_budget = _COMPACT_RESTORE_MAX_BYTES - len(prefix.encode("utf-8"))
159
+ if len(body.encode("utf-8", "replace")) > body_budget:
160
+ cut = body.encode("utf-8", "replace")[
161
+ : body_budget - len(marker.encode("utf-8"))
162
+ ].decode("utf-8", errors="ignore")
163
+ body = cut + marker
164
+ return prefix + body
165
+
166
+
167
+ _RESTORE_MAX_AGE = 7 * 24 * 3600
168
+
169
+
170
+ def normalize_workspace(root):
171
+ return os.path.normcase(os.path.realpath(os.path.normpath(root)))
172
+
173
+
174
+ def restore_for_workspace(fields, root, to_dir, sessions_dir, load_tally, active_seconds):
175
+ """Inject recent workspace continuity unless a recent sibling is active."""
176
+ if to_dir is None or not root:
177
+ return None
178
+ root = normalize_workspace(root)
179
+ now = time.time()
180
+ own_id = fields.get("conversation_id") or ""
181
+ try:
182
+ if sessions_dir is not None:
183
+ for path in sessions_dir.glob("*.json"):
184
+ try:
185
+ if now - path.stat().st_mtime >= active_seconds:
186
+ continue
187
+ except OSError:
188
+ continue
189
+ tally = load_tally(path)
190
+ if not tally or tally.get("final") or (own_id and tally.get("conversation_id") == own_id):
191
+ continue
192
+ roots = tally.get("workspace_roots")
193
+ sibling_root = roots[0] if isinstance(roots, list) and roots else tally.get("cwd")
194
+ try:
195
+ if sibling_root and normalize_workspace(str(sibling_root)) == root and now - float(tally.get("updated_at") or 0) < active_seconds:
196
+ return None
197
+ except (TypeError, ValueError):
198
+ continue
199
+ digest = hashlib.sha1(root.encode("utf-8", "replace")).hexdigest()
200
+ path = to_dir / "restore-context" / (digest + ".md")
201
+ if (path.is_symlink() or path.parent.is_symlink()
202
+ or to_dir.resolve() not in path.resolve().parents
203
+ or path.stat().st_size > _RESTORE_MAX_BYTES):
204
+ return None
205
+ stamp, text = path.read_text(encoding="utf-8").split("\n", 1)
206
+ if not stamp.startswith("<!-- source-end: ") or not stamp.endswith(" -->"):
207
+ return None
208
+ ended = float(stamp[len("<!-- source-end: "):-4])
209
+ if not 0 <= now - ended <= _RESTORE_MAX_AGE:
210
+ return None
211
+ return text.strip() or None
212
+ except (OSError, ValueError, OverflowError):
213
+ return None
@@ -0,0 +1,170 @@
1
+ """stdin payload decoding for the Cursor hook bridge.
2
+
3
+ Split out of cursor_hook_bridge.py under the repo's 1,000-line file-size
4
+ ratchet (scripts/check_file_size.py). Pure parsing only: no I/O beyond the
5
+ payload text, no patched seams. cursor_hook_bridge re-imports these names, so
6
+ bridge.decode_payload and friends keep working.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ import re
13
+ import sys
14
+ from pathlib import Path
15
+
16
+ _MAX_STDIN_BYTES = 4 * 1024 * 1024 # refuse absurd payloads (amplification)
17
+ _SESSION_ID_RE = re.compile(r"[^A-Za-z0-9_-]")
18
+
19
+
20
+ def _sanitize_session_id(sid):
21
+ """Strip everything but [A-Za-z0-9_-] so a payload id can never traverse.
22
+
23
+ Mirrors measure.sanitize_session_id / copilot_hook_bridge: a conversation_id
24
+ like "../../../etc/passwd" would otherwise let _atomic_write_json / the lock
25
+ path escape the data dir.
26
+ """
27
+ if not sid:
28
+ return "unknown"
29
+ cleaned = _SESSION_ID_RE.sub("", sid)[:64]
30
+ return cleaned if len(cleaned) >= 6 else "unknown"
31
+
32
+
33
+ def _parse_tool_input(raw):
34
+ """tool_input as a dict, or as a JSON-encoded string -> dict; {} otherwise."""
35
+ if isinstance(raw, dict):
36
+ return raw
37
+ if isinstance(raw, str) and raw:
38
+ try:
39
+ parsed = json.loads(raw)
40
+ if isinstance(parsed, dict):
41
+ return parsed
42
+ except (json.JSONDecodeError, ValueError, RecursionError):
43
+ pass
44
+ return {}
45
+
46
+
47
+ def decode_payload(payload):
48
+ """Normalize a Cursor hook payload into a flat, safe dict.
49
+
50
+ ``conversation_id`` wins over ``session_id`` (sessionStart carries only
51
+ session_id; the tool events carry conversation_id). ``workspace_roots`` is
52
+ the list Cursor exports; ``cwd`` is capped at 1024 chars because it is
53
+ rewritten into the tally on every tool call and into restore-context.
54
+ Missing fields default to empty values so callers never KeyError.
55
+ """
56
+ out = {
57
+ "tool_name": "",
58
+ "tool_args": {},
59
+ "conversation_id": "",
60
+ "hook_event_name": "",
61
+ "cwd": "",
62
+ "cursor_version": "",
63
+ "workspace_roots": [],
64
+ "transcript_path": None,
65
+ "model": None,
66
+ "timestamp": None,
67
+ # preCompact numbers (0/0.0 when absent or the payload is not a dict)
68
+ "context_tokens": 0,
69
+ "context_window_size": 0,
70
+ "context_usage_percent": 0.0,
71
+ "trigger": "",
72
+ # U4 correlation/output fields (CLI bundle 2026.11.05 evidence)
73
+ "generation_id": "",
74
+ "agent_id": "",
75
+ "cache_conversation_id": "",
76
+ "tool_use_id": "",
77
+ "parent_tool_call_id": "",
78
+ "tool_output": "",
79
+ "duration": 0.0,
80
+ }
81
+ if not isinstance(payload, dict):
82
+ return out
83
+
84
+ tool_name = payload.get("tool_name", payload.get("toolName", ""))
85
+ if isinstance(tool_name, str):
86
+ out["tool_name"] = tool_name.strip()
87
+ out["tool_args"] = _parse_tool_input(
88
+ payload.get("tool_input", payload.get("toolInput", {}))
89
+ )
90
+
91
+ sid = payload.get("conversation_id", payload.get("session_id", ""))
92
+ if isinstance(sid, str):
93
+ out["conversation_id"] = _sanitize_session_id(sid)
94
+ out["cache_conversation_id"] = sid if len(sid) <= 1024 else ""
95
+
96
+ event = payload.get("hook_event_name", "")
97
+ if isinstance(event, str):
98
+ out["hook_event_name"] = event.strip()
99
+
100
+ cwd = payload.get("cwd", "")
101
+ if isinstance(cwd, str):
102
+ out["cwd"] = cwd[:1024]
103
+
104
+ version = payload.get("cursor_version", "")
105
+ if isinstance(version, str):
106
+ out["cursor_version"] = version[:64]
107
+
108
+ roots = payload.get("workspace_roots")
109
+ if isinstance(roots, list):
110
+ out["workspace_roots"] = [
111
+ str(r)[:1024] for r in roots if isinstance(r, str)
112
+ ][:8]
113
+
114
+ tp = payload.get("transcript_path")
115
+ if isinstance(tp, str):
116
+ out["transcript_path"] = tp[:1024]
117
+
118
+ agent = payload.get("agent_id") or payload.get("subagent_id")
119
+ if isinstance(agent, str) and agent.strip() and len(agent) <= 128:
120
+ out["agent_id"] = agent
121
+ for key in ("generation_id", "tool_use_id", "parent_tool_call_id"):
122
+ v = payload.get(key)
123
+ if isinstance(v, str):
124
+ out[key] = v[:128]
125
+ to = payload.get("tool_output")
126
+ if isinstance(to, str):
127
+ out["tool_output"] = to[:262144]
128
+ try:
129
+ out["duration"] = float(payload.get("duration") or 0.0)
130
+ except (TypeError, ValueError):
131
+ out["duration"] = 0.0
132
+
133
+ model = payload.get("model")
134
+ if isinstance(model, str):
135
+ out["model"] = model[:128]
136
+
137
+ out["timestamp"] = payload.get("timestamp")
138
+
139
+ for key in ("context_tokens", "context_window_size"):
140
+ try:
141
+ out[key] = int(payload.get(key) or 0)
142
+ except (TypeError, ValueError):
143
+ out[key] = 0
144
+ try:
145
+ out["context_usage_percent"] = float(payload.get("context_usage_percent") or 0.0)
146
+ except (TypeError, ValueError):
147
+ out["context_usage_percent"] = 0.0
148
+ trigger = payload.get("trigger")
149
+ if isinstance(trigger, str):
150
+ out["trigger"] = trigger
151
+ return out
152
+
153
+
154
+ def _read_stdin_payload():
155
+ """Read and decode the Cursor hook payload from stdin. None on any failure."""
156
+ try:
157
+ raw = sys.stdin.read(_MAX_STDIN_BYTES + 1)
158
+ except (OSError, UnicodeDecodeError):
159
+ return None
160
+ if not raw or len(raw) > _MAX_STDIN_BYTES:
161
+ return None
162
+ try:
163
+ payload = json.loads(raw)
164
+ except (json.JSONDecodeError, ValueError, RecursionError):
165
+ # RecursionError: a deeply nested payload ('[' * 2000 ...) must never
166
+ # escape the fail-open envelope and break always-exit-0 (G0).
167
+ return None
168
+ if not isinstance(payload, dict):
169
+ return None
170
+ return payload
@@ -0,0 +1,106 @@
1
+ """Pending command-rewrite staging and post-execution pairing (G0).
2
+
3
+ Split out of cursor_hook_bridge.py under the repo's 1,000-line file-size
4
+ ratchet (scripts/check_file_size.py). The data-dir resolver and the atomic
5
+ writer are INJECTED by the bridge's same-name wrappers at call time, so tests
6
+ monkeypatching cursor_hook_bridge._to_dir / ._atomic_write_json keep working.
7
+ Hash-only staging: rewritten command text never touches disk.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import json
13
+ import os
14
+ import time
15
+
16
+ from cursor_bridge_payload import _SESSION_ID_RE
17
+
18
+ _PENDING_REWRITE_MAX_AGE = 600 # seconds; staged rewrite evidence horizon
19
+
20
+
21
+ def _pending_rewrite_path(fields, to_dir):
22
+ sid = _SESSION_ID_RE.sub("", str(fields.get("conversation_id") or ""))[:64]
23
+ tuid = _SESSION_ID_RE.sub("", str(fields.get("tool_use_id") or ""))[:64]
24
+ if len(sid) < 6 or len(tuid) < 6:
25
+ return None
26
+ if to_dir is None:
27
+ return None
28
+ return to_dir / "pending-rewrites" / f"{sid}--{tuid}.json"
29
+
30
+
31
+ def _stage_pending_rewrite(fields, rewritten, *, to_dir, atomic_write):
32
+ """Stage THIS session+tool_use_id's rewrite for postToolUse pairing.
33
+
34
+ Hash-only: the rewritten command text never touches disk (a whitelisted
35
+ command can still embed a credential in its arguments). Equality is
36
+ proven by comparing digests at postToolUse. Best-effort and bounded:
37
+ the dir is pruned by age on each stage. Never raises.
38
+ """
39
+ try:
40
+ path = _pending_rewrite_path(fields, to_dir)
41
+ if path is None:
42
+ return
43
+ path.parent.mkdir(parents=True, exist_ok=True)
44
+ try:
45
+ os.chmod(path.parent, 0o700)
46
+ except OSError:
47
+ pass
48
+ now = time.time()
49
+ for old in path.parent.glob("*.json"):
50
+ try:
51
+ if now - old.stat().st_mtime > _PENDING_REWRITE_MAX_AGE:
52
+ old.unlink()
53
+ except OSError:
54
+ pass
55
+ import hashlib
56
+
57
+ atomic_write(path, {
58
+ "sha256": hashlib.sha256(rewritten.encode("utf-8")).hexdigest(),
59
+ "ts": now,
60
+ })
61
+ except Exception:
62
+ pass
63
+
64
+
65
+ def _classify_rewrite(fields, *, to_dir):
66
+ """Pair the executed Shell command with this tool_use_id's staged rewrite.
67
+
68
+ honoured: the executed command's digest matches the staged digest.
69
+ ignored: a rewrite was staged but a different command actually ran.
70
+ None: no staged attempt (unknown - never proof in either direction, G0).
71
+ The pop is claim-by-rename so two processes can never both classify one
72
+ staged rewrite.
73
+ """
74
+ try:
75
+ path = _pending_rewrite_path(fields, to_dir)
76
+ if path is None or not path.is_file() or path.is_symlink():
77
+ return None
78
+ claimed = path.with_name(path.name + f".claimed-{os.getpid()}")
79
+ try:
80
+ os.replace(path, claimed)
81
+ except OSError:
82
+ return None # another process claimed it first (or it vanished)
83
+ try:
84
+ staged = json.loads(claimed.read_text(encoding="utf-8"))
85
+ except (OSError, ValueError):
86
+ staged = None
87
+ try:
88
+ claimed.unlink()
89
+ except OSError:
90
+ pass
91
+ if not isinstance(staged, dict):
92
+ return None
93
+ expected = staged.get("sha256")
94
+ if not isinstance(expected, str):
95
+ return None
96
+ actual = fields["tool_args"].get("command")
97
+ if not isinstance(actual, str) or not actual:
98
+ # Missing/invalid executed-command data is UNKNOWN, never
99
+ # 'ignored' - we cannot say what Cursor actually ran.
100
+ return None
101
+ import hashlib
102
+
103
+ digest = hashlib.sha256(actual.encode("utf-8")).hexdigest()
104
+ return "honoured" if digest == expected else "ignored"
105
+ except Exception:
106
+ return None
@@ -0,0 +1,115 @@
1
+ """Rollup/dashboard spawning and stop-throttle state for the Cursor bridge.
2
+
3
+ Split out of cursor_hook_bridge.py under the repo's 1,000-line file-size
4
+ ratchet (scripts/check_file_size.py). The measure.py locator, the detaching
5
+ spawner, the data-dir resolver and the atomic writer are INJECTED by the
6
+ bridge's same-name wrappers at call time, so tests monkeypatching
7
+ cursor_hook_bridge._locate_measure_py / .spawn_detached / ._to_dir /
8
+ ._atomic_write_json keep working.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import json
14
+ import logging
15
+ import os
16
+ import subprocess
17
+ import sys
18
+ import time
19
+
20
+ logger = logging.getLogger(__name__)
21
+
22
+ _STOP_ROLLUP_SECS = 120 # R12: at most one stop rollup per machine per 120s
23
+ _STALE_LOCK_SECS = 7 * 24 * 3600 # sessionStart lock sweep threshold
24
+
25
+
26
+ def _measure_env(interactive=False):
27
+ env = dict(os.environ)
28
+ env["TOKEN_OPTIMIZER_RUNTIME"] = "cursor"
29
+ env["PYTHONUTF8"] = "1"
30
+ env["PYTHONIOENCODING"] = "utf-8"
31
+ if interactive:
32
+ env["TOKEN_OPTIMIZER_INTERACTIVE"] = "1"
33
+ return env
34
+
35
+
36
+ # The installer does NOT copy measure.py into the plugin dir (version-drift
37
+ # risk); it writes a one-line "measure-path" locator next to this bridge naming
38
+ # the canonical measure.py in the checkout. Resolution order: a sibling
39
+ # measure.py (dev/test checkout), then the locator. Mirrors
40
+ # hermes_hook_bridge._locate_measure_py.
41
+
42
+
43
+ def _spawn_rollup(locate_measure_py, spawn_detached):
44
+ # cursor-doctor --probe replays the installed command to prove it fires;
45
+ # it must not trigger a real detached rollup/dashboard as a side effect.
46
+ if os.environ.get("TOKEN_OPTIMIZER_PROBE") == "1":
47
+ return
48
+ measure = locate_measure_py()
49
+ if measure is None:
50
+ return
51
+ try:
52
+ spawn_detached(
53
+ [sys.executable, str(measure), "cursor-rollup", "--quiet"],
54
+ env=_measure_env(),
55
+ stdout=subprocess.DEVNULL,
56
+ stderr=subprocess.DEVNULL,
57
+ )
58
+ except (OSError, subprocess.SubprocessError):
59
+ logger.warning("[cursor_hook_bridge] detached rollup spawn failed", exc_info=True)
60
+
61
+
62
+ def _spawn_dashboard(locate_measure_py, spawn_detached):
63
+ # Same probe guard as _spawn_rollup(): replay must not spawn detached work.
64
+ if os.environ.get("TOKEN_OPTIMIZER_PROBE") == "1":
65
+ return
66
+ measure = locate_measure_py()
67
+ if measure is None:
68
+ return
69
+ try:
70
+ spawn_detached(
71
+ [sys.executable, str(measure), "dashboard", "--quiet"],
72
+ env=_measure_env(interactive=True),
73
+ stdout=subprocess.DEVNULL,
74
+ stderr=subprocess.DEVNULL,
75
+ )
76
+ except (OSError, subprocess.SubprocessError):
77
+ logger.warning("[cursor_hook_bridge] detached dashboard spawn failed", exc_info=True)
78
+
79
+
80
+ def _stop_rollup_due_locked(state, now, atomic_write):
81
+ last = None
82
+ try:
83
+ if state.exists():
84
+ data = json.loads(state.read_text(encoding="utf-8"))
85
+ if isinstance(data, dict):
86
+ last = float(data.get("last", 0) or 0)
87
+ except (OSError, json.JSONDecodeError, ValueError, TypeError):
88
+ last = None
89
+ if last is not None and now - last < _STOP_ROLLUP_SECS:
90
+ return False
91
+ # Fail closed: if the throttle-state write fails (disk full, read-only data
92
+ # dir), do NOT spawn — otherwise every stop would spawn a rollup+dashboard
93
+ # storm precisely under the degraded conditions the throttle is meant to
94
+ # contain. _atomic_write_json returns True only on a successful write.
95
+ return atomic_write(state, {"last": now})
96
+
97
+
98
+ def _sweep_stale_locks(to_dir):
99
+ """Remove stale lock/candidate artifacts (7d) on sessionStart. Never fatal."""
100
+ if to_dir is None:
101
+ return
102
+ lock_dir = to_dir / ".locks"
103
+ if not lock_dir.is_dir():
104
+ return
105
+ now = time.time()
106
+ try:
107
+ for pattern in ("*.lock", ".*.lock.candidate-*"):
108
+ for p in lock_dir.glob(pattern):
109
+ try:
110
+ if now - p.stat().st_mtime > _STALE_LOCK_SECS:
111
+ p.unlink()
112
+ except OSError:
113
+ continue
114
+ except OSError:
115
+ pass