@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.
- package/.claude-plugin/marketplace.json +2 -2
- package/.claude-plugin/plugin.json +1 -1
- package/PRIVACY.md +4 -0
- package/hooks/hooks.json +11 -1
- package/hooks/module_runner.py +4 -1
- package/hooks/posttooluse_runner.py +44 -48
- package/hooks/sessionstart_runner.py +24 -5
- package/hooks/stop_runner.py +6 -6
- package/package.json +1 -1
- package/skills/fleet-auditor/references/fleet-systems.md +38 -0
- package/skills/fleet-auditor/scripts/fleet.py +63 -92
- package/skills/fleet-auditor/scripts/fleet_base.py +106 -0
- package/skills/fleet-auditor/scripts/fleet_cursor_adapter.py +376 -0
- package/skills/token-coach/SKILL.md +21 -23
- package/skills/token-dashboard/SKILL.md +5 -4
- package/skills/token-optimizer/SKILL.md +1 -1
- package/skills/token-optimizer/assets/dashboard.html +492 -551
- package/skills/token-optimizer/assets/savings_story.js +661 -0
- package/skills/token-optimizer/pricing/prices.json +1 -0
- package/skills/token-optimizer/references/cli-reference.md +1 -1
- package/skills/token-optimizer/references/cursor-workflow.md +1 -1
- package/skills/token-optimizer/references/implementation-playbook.md +3 -0
- package/skills/token-optimizer/references/phase0-setup.md +1 -1
- package/skills/token-optimizer/references/presentation-workflow.md +1 -1
- package/skills/token-optimizer/scripts/_measure/__init__.py +3 -1
- package/skills/token-optimizer/scripts/_measure/archive_health.py +14 -0
- package/skills/token-optimizer/scripts/_measure/archive_void_codex.py +163 -0
- package/skills/token-optimizer/scripts/_measure/archive_void_evidence.py +165 -0
- package/skills/token-optimizer/scripts/_measure/audit.py +27 -135
- package/skills/token-optimizer/scripts/_measure/baseline_provenance.py +339 -0
- package/skills/token-optimizer/scripts/_measure/cache_policy.py +261 -581
- package/skills/token-optimizer/scripts/_measure/checkpoint_direction.py +97 -0
- package/skills/token-optimizer/scripts/_measure/checkpoint_retention.py +20 -0
- package/skills/token-optimizer/scripts/_measure/cli.py +98 -8
- package/skills/token-optimizer/scripts/_measure/codex_quality.py +246 -0
- package/skills/token-optimizer/scripts/_measure/compaction_survival.py +158 -0
- package/skills/token-optimizer/scripts/_measure/compression_fixture_void.py +147 -0
- package/skills/token-optimizer/scripts/_measure/compression_scan_checkpoint.py +72 -0
- package/skills/token-optimizer/scripts/_measure/context_reset_marker.py +64 -0
- package/skills/token-optimizer/scripts/_measure/continuity.py +64 -118
- package/skills/token-optimizer/scripts/_measure/cost_per_message_trend.py +40 -0
- package/skills/token-optimizer/scripts/_measure/counted_cap.py +28 -0
- package/skills/token-optimizer/scripts/_measure/counted_orphans.py +190 -0
- package/skills/token-optimizer/scripts/_measure/counted_position.py +20 -0
- package/skills/token-optimizer/scripts/_measure/counted_pricing_v5.py +267 -0
- package/skills/token-optimizer/scripts/_measure/counted_subagents.py +371 -0
- package/skills/token-optimizer/scripts/_measure/coverage_report.py +285 -0
- package/skills/token-optimizer/scripts/_measure/daemon.py +61 -94
- package/skills/token-optimizer/scripts/_measure/dashboard.py +149 -187
- package/skills/token-optimizer/scripts/_measure/dashboard_heal_claim.py +36 -0
- package/skills/token-optimizer/scripts/_measure/dashboard_history.py +79 -0
- package/skills/token-optimizer/scripts/_measure/evidence_parallel.py +95 -0
- package/skills/token-optimizer/scripts/_measure/feature_health.py +256 -0
- package/skills/token-optimizer/scripts/_measure/file_refetch.py +250 -0
- package/skills/token-optimizer/scripts/_measure/first_call_context.py +216 -0
- package/skills/token-optimizer/scripts/_measure/first_read_outcomes.py +261 -0
- package/skills/token-optimizer/scripts/_measure/first_read_revive.py +137 -0
- package/skills/token-optimizer/scripts/_measure/fixture_context.py +65 -0
- package/skills/token-optimizer/scripts/_measure/headline.py +100 -0
- package/skills/token-optimizer/scripts/_measure/holdout_fallback.py +96 -0
- package/skills/token-optimizer/scripts/_measure/holdout_report.py +125 -0
- package/skills/token-optimizer/scripts/_measure/keepwarm_economics.py +201 -0
- package/skills/token-optimizer/scripts/_measure/keepwarm_fork.py +140 -0
- package/skills/token-optimizer/scripts/_measure/keepwarm_guard.py +35 -0
- package/skills/token-optimizer/scripts/_measure/keepwarm_guard_server.py +85 -0
- package/skills/token-optimizer/scripts/_measure/keepwarm_linux.py +121 -0
- package/skills/token-optimizer/scripts/_measure/keepwarm_prefix.py +143 -0
- package/skills/token-optimizer/scripts/_measure/keepwarm_response_filter.py +84 -0
- package/skills/token-optimizer/scripts/_measure/keepwarm_safety.py +256 -0
- package/skills/token-optimizer/scripts/_measure/lean_resume_receivers.py +260 -0
- package/skills/token-optimizer/scripts/_measure/lean_resume_threshold.py +76 -0
- package/skills/token-optimizer/scripts/_measure/lease_candidate_cleanup.py +82 -0
- package/skills/token-optimizer/scripts/_measure/lifecycle.py +59 -168
- package/skills/token-optimizer/scripts/_measure/mcp_archive_tripwire.py +120 -0
- package/skills/token-optimizer/scripts/_measure/mod_action_booking.py +178 -0
- package/skills/token-optimizer/scripts/_measure/mod_compaction_booking.py +276 -0
- package/skills/token-optimizer/scripts/_measure/mod_fresh_booking.py +105 -0
- package/skills/token-optimizer/scripts/_measure/output_reread.py +629 -0
- package/skills/token-optimizer/scripts/_measure/own_price_card.py +268 -0
- package/skills/token-optimizer/scripts/_measure/periphery_exposure.py +85 -0
- package/skills/token-optimizer/scripts/_measure/pricing.py +152 -87
- package/skills/token-optimizer/scripts/_measure/quality_archive.py +159 -215
- package/skills/token-optimizer/scripts/_measure/quality_checkpoint.py +173 -0
- package/skills/token-optimizer/scripts/_measure/quality_continuity.py +43 -0
- package/skills/token-optimizer/scripts/_measure/rework_metrics.py +194 -0
- package/skills/token-optimizer/scripts/_measure/routing_period.py +48 -0
- package/skills/token-optimizer/scripts/_measure/savings.py +451 -933
- package/skills/token-optimizer/scripts/_measure/savings_story.py +187 -0
- package/skills/token-optimizer/scripts/_measure/session_best.py +24 -0
- package/skills/token-optimizer/scripts/_measure/session_effect.py +557 -0
- package/skills/token-optimizer/scripts/_measure/session_flush_lock.py +75 -0
- package/skills/token-optimizer/scripts/_measure/session_store_spool.py +220 -0
- package/skills/token-optimizer/scripts/_measure/sessions.py +154 -216
- package/skills/token-optimizer/scripts/_measure/setup_attachment_counter.py +196 -0
- package/skills/token-optimizer/scripts/_measure/setup_budget_monitor.py +180 -0
- package/skills/token-optimizer/scripts/_measure/setup_connector_ledger.py +126 -0
- package/skills/token-optimizer/scripts/_measure/setup_step.py +220 -0
- package/skills/token-optimizer/scripts/_measure/status_bar_lock.py +117 -0
- package/skills/token-optimizer/scripts/_measure/structural_archives.py +79 -0
- package/skills/token-optimizer/scripts/_measure/structural_dedupe.py +91 -0
- package/skills/token-optimizer/scripts/_measure/structural_ledger.py +418 -0
- package/skills/token-optimizer/scripts/_measure/structural_listing.py +163 -0
- package/skills/token-optimizer/scripts/_measure/structural_report.py +339 -0
- package/skills/token-optimizer/scripts/_measure/structural_seed.py +164 -0
- package/skills/token-optimizer/scripts/_measure/structural_value.py +248 -0
- package/skills/token-optimizer/scripts/_measure/structure_funnel.py +97 -0
- package/skills/token-optimizer/scripts/_measure/timestamp_cache.py +11 -0
- package/skills/token-optimizer/scripts/_measure/token_type_split.py +29 -0
- package/skills/token-optimizer/scripts/_measure/transcript_backfill.py +419 -0
- package/skills/token-optimizer/scripts/_measure/transcript_product.py +228 -0
- package/skills/token-optimizer/scripts/_measure/transcript_stream.py +279 -0
- package/skills/token-optimizer/scripts/_measure/trends.py +44 -185
- package/skills/token-optimizer/scripts/_measure/ttl_period.py +6 -0
- package/skills/token-optimizer/scripts/_measure/upgrade_drain_control.py +287 -0
- package/skills/token-optimizer/scripts/_measure/weekly_activity.py +69 -0
- package/skills/token-optimizer/scripts/activity_tracker.py +4 -33
- package/skills/token-optimizer/scripts/antigravity_install.py +6 -0
- package/skills/token-optimizer/scripts/archive_result.py +15 -19
- package/skills/token-optimizer/scripts/archive_verify.py +165 -0
- package/skills/token-optimizer/scripts/bash_compress.py +22 -83
- package/skills/token-optimizer/scripts/bash_compress_hook.py +137 -1
- package/skills/token-optimizer/scripts/bash_search_results.py +43 -0
- package/skills/token-optimizer/scripts/checkpoint_state.py +2 -2
- package/skills/token-optimizer/scripts/cloud_kit.py +3 -6
- package/skills/token-optimizer/scripts/codemap.py +274 -0
- package/skills/token-optimizer/scripts/codemap_hint.py +153 -0
- package/skills/token-optimizer/scripts/codemap_index.py +656 -0
- package/skills/token-optimizer/scripts/codemap_ledger.py +309 -0
- package/skills/token-optimizer/scripts/codemap_reread.py +161 -0
- package/skills/token-optimizer/scripts/codex_doctor.py +9 -1
- package/skills/token-optimizer/scripts/codex_log_index.py +34 -15
- package/skills/token-optimizer/scripts/codex_session.py +16 -216
- package/skills/token-optimizer/scripts/compression_backfill.py +4 -35
- package/skills/token-optimizer/scripts/context_intel.py +5 -3
- package/skills/token-optimizer/scripts/copilot_install.py +6 -0
- package/skills/token-optimizer/scripts/coverage_funnel.py +261 -0
- package/skills/token-optimizer/scripts/credential_patterns.py +4 -19
- package/skills/token-optimizer/scripts/credential_url_patterns.py +42 -0
- package/skills/token-optimizer/scripts/cursor_audit.py +723 -0
- package/skills/token-optimizer/scripts/cursor_bridge_checkpoint.py +213 -0
- package/skills/token-optimizer/scripts/cursor_bridge_payload.py +170 -0
- package/skills/token-optimizer/scripts/cursor_bridge_rewrite.py +106 -0
- package/skills/token-optimizer/scripts/cursor_bridge_rollup.py +115 -0
- package/skills/token-optimizer/scripts/cursor_coach.py +485 -0
- package/skills/token-optimizer/scripts/cursor_doctor.py +89 -9
- package/skills/token-optimizer/scripts/cursor_hook_bridge.py +393 -276
- package/skills/token-optimizer/scripts/cursor_install.py +118 -19
- package/skills/token-optimizer/scripts/cursor_quality.py +457 -0
- package/skills/token-optimizer/scripts/cursor_read_cache.py +597 -0
- package/skills/token-optimizer/scripts/cursor_session.py +26 -5
- package/skills/token-optimizer/scripts/cursor_state.py +8 -0
- package/skills/token-optimizer/scripts/cursor_statusline.py +372 -0
- package/skills/token-optimizer/scripts/cursor_thrash.py +78 -0
- package/skills/token-optimizer/scripts/cursor_transcript.py +223 -0
- package/skills/token-optimizer/scripts/dashboard_assets.py +21 -0
- package/skills/token-optimizer/scripts/deterministic_candidates.py +2 -10
- package/skills/token-optimizer/scripts/devin_source.py +19 -4
- package/skills/token-optimizer/scripts/devin_verify.py +13 -6
- package/skills/token-optimizer/scripts/grok_install.py +6 -0
- package/skills/token-optimizer/scripts/heal_report.py +7 -6
- package/skills/token-optimizer/scripts/hermes_doctor.py +12 -1
- package/skills/token-optimizer/scripts/hermes_install.py +10 -1
- package/skills/token-optimizer/scripts/hermes_session.py +14 -136
- package/skills/token-optimizer/scripts/hint_paths.py +21 -0
- package/skills/token-optimizer/scripts/holdout.py +136 -0
- package/skills/token-optimizer/scripts/hook_runtime.py +1 -0
- package/skills/token-optimizer/scripts/hook_skip_log.py +89 -0
- package/skills/token-optimizer/scripts/large_transcripts.py +31 -0
- package/skills/token-optimizer/scripts/lean_resume_carry.py +518 -0
- package/skills/token-optimizer/scripts/measure.py +36 -78
- package/skills/token-optimizer/scripts/post_run_classify.py +349 -0
- package/skills/token-optimizer/scripts/preserved_reinject.py +54 -0
- package/skills/token-optimizer/scripts/read_cache.py +99 -100
- package/skills/token-optimizer/scripts/reset_epoch.py +3 -3
- package/skills/token-optimizer/scripts/session_store.py +49 -99
- package/skills/token-optimizer/scripts/session_store_guard.py +75 -0
- package/skills/token-optimizer/scripts/settings_backup.py +379 -0
- package/skills/token-optimizer/scripts/shipped_hook_templates.py +1 -0
- package/skills/token-optimizer/scripts/statusline.js +1 -1
- package/skills/token-optimizer/scripts/structural.py +25 -0
- package/skills/token-optimizer/scripts/structure_map.py +4 -26
- package/skills/token-optimizer/scripts/thrash_guard.py +10 -5
|
@@ -0,0 +1,372 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Token Optimizer — Cursor CLI ``statusLine`` command (opt-in).
|
|
3
|
+
|
|
4
|
+
Cursor CLI (changelog v2026.08.11) supports a custom ``statusLine`` command in
|
|
5
|
+
the CLI config, shaped ``{ "statusLine": { "type": "command", "command": ... } }``.
|
|
6
|
+
The command receives ONE JSON object on stdin and its stdout renders as the
|
|
7
|
+
footer; each printed line renders as its own row.
|
|
8
|
+
|
|
9
|
+
Evidence state (2026-11-09), kept honest per R13:
|
|
10
|
+
|
|
11
|
+
- Cursor's official CLI configuration reference does NOT document the
|
|
12
|
+
statusLine payload schema. The only payload evidence is a user report
|
|
13
|
+
against CLI 2026.07.20 (forum.cursor.com/t/166364): stdin carries
|
|
14
|
+
``context_window.total_input_tokens``, ``context_window.context_window_size``
|
|
15
|
+
and ``autorun``. Every payload read below is therefore schema-defensive: an
|
|
16
|
+
absent or renamed field renders as "?" or is omitted — never a fabricated
|
|
17
|
+
value.
|
|
18
|
+
- Live-fill gate (architecture judge, 2026-11-09): a "context X% full" number
|
|
19
|
+
may only come from a proven host occupancy snapshot. The statusLine payload's
|
|
20
|
+
``context_window`` fields are forum-observed but NOT yet proven to be current
|
|
21
|
+
occupancy (vs. a cumulative/usage counter) on current builds, so payload fill
|
|
22
|
+
is gated behind ``PAYLOAD_FILL_PROVEN = False`` below. The integration owner
|
|
23
|
+
flips it to True only when the extracted CLI bundle contract proves
|
|
24
|
+
``context_window.total_input_tokens`` is present-window occupancy. Until
|
|
25
|
+
then the only fill source is the tally's last ``preCompact`` snapshot, which
|
|
26
|
+
IS documented occupancy. A lifetime token sum is never a fill numerator.
|
|
27
|
+
- Cursor staff (kevinn, same thread) confirmed the custom command REPLACES the
|
|
28
|
+
native two-row footer (there is no append/prepend mode) and that multiline
|
|
29
|
+
stdout renders as separate rows. Line 1 below therefore reconstructs the
|
|
30
|
+
model/context information the native footer would have shown.
|
|
31
|
+
- The payload's ``autorun`` boolean cannot distinguish Allowlist from
|
|
32
|
+
Auto-review approval modes (staff-confirmed), so this script NEVER renders
|
|
33
|
+
approval-mode state.
|
|
34
|
+
|
|
35
|
+
Wiring is strictly opt-in (R12/KTD7): the installer offers this command only on
|
|
36
|
+
explicit request because it replaces the native footer. This script itself is
|
|
37
|
+
read-only — it writes nothing, keeps the ~40ms hook-path budget (stdlib only,
|
|
38
|
+
no heavy imports), and always exits 0. Any failure prints nothing rather than
|
|
39
|
+
garbage into the footer.
|
|
40
|
+
|
|
41
|
+
Line 1 (native-footer reconstruction): ``<model> · ctx <pct>% (<used>/<window>)``
|
|
42
|
+
when a proven live fill exists, otherwise ``ctx ?`` — current occupancy is
|
|
43
|
+
unknown on Cursor today.
|
|
44
|
+
Line 2 (Token Optimizer): the LAST COMPACTION's recorded occupancy, labeled as
|
|
45
|
+
history ("last compact 95% 3m ago", aged from the entry's own ``ts`` — never
|
|
46
|
+
the tally's updated_at, which later hook events bump without measuring
|
|
47
|
+
occupancy), plus compaction and tool-call counts from the session tally under
|
|
48
|
+
``<cursor_home>/token-optimizer/sessions/``.
|
|
49
|
+
|
|
50
|
+
No fill-derived grade is shown on the tally path: the pre-compaction peak is
|
|
51
|
+
history (context dropped right after), so scoring current quality from it
|
|
52
|
+
would present stale data as current. A grade returns only if the gated live
|
|
53
|
+
payload fill is ever proven (see PAYLOAD_FILL_PROVEN). The dashboard's
|
|
54
|
+
multi-signal quality score lives in cursor_session/hermes_session.
|
|
55
|
+
"""
|
|
56
|
+
|
|
57
|
+
from __future__ import annotations
|
|
58
|
+
|
|
59
|
+
import json
|
|
60
|
+
import re
|
|
61
|
+
import sys
|
|
62
|
+
import time
|
|
63
|
+
from pathlib import Path
|
|
64
|
+
from typing import Any, Optional
|
|
65
|
+
|
|
66
|
+
# Bounds: a statusline runs on the CLI's refresh cadence, so every read is
|
|
67
|
+
# capped. A pathological payload or tally must never stall the footer.
|
|
68
|
+
_MAX_STDIN_BYTES = 1024 * 1024
|
|
69
|
+
_MAX_TALLY_BYTES = 4 * 1024 * 1024
|
|
70
|
+
_MAX_TALLY_CANDIDATES = 8
|
|
71
|
+
_MAX_MODEL_LEN = 40
|
|
72
|
+
_SESSION_ID_RE = re.compile(r"[^A-Za-z0-9_-]")
|
|
73
|
+
|
|
74
|
+
# Live-fill gate (see module docstring): False until the installed CLI bundle's
|
|
75
|
+
# statusLine contract proves context_window.total_input_tokens is present-window
|
|
76
|
+
# occupancy. Flipping this without that evidence is a contract violation.
|
|
77
|
+
PAYLOAD_FILL_PROVEN = False
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
# ---------------------------------------------------------------------------
|
|
81
|
+
# Payload extraction (schema-defensive; see module docstring for evidence)
|
|
82
|
+
# ---------------------------------------------------------------------------
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _read_stdin_payload() -> dict:
|
|
86
|
+
"""Read and parse the single JSON object Cursor pipes on stdin; {} on any failure."""
|
|
87
|
+
try:
|
|
88
|
+
raw = sys.stdin.buffer.read(_MAX_STDIN_BYTES + 1)
|
|
89
|
+
except (OSError, ValueError):
|
|
90
|
+
return {}
|
|
91
|
+
if not raw or len(raw) > _MAX_STDIN_BYTES:
|
|
92
|
+
return {}
|
|
93
|
+
try:
|
|
94
|
+
data = json.loads(raw.decode("utf-8", errors="replace"))
|
|
95
|
+
except (json.JSONDecodeError, ValueError):
|
|
96
|
+
return {}
|
|
97
|
+
return data if isinstance(data, dict) else {}
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _payload_model(payload: dict) -> Optional[str]:
|
|
101
|
+
"""Model name from tolerant key shapes; None when the payload carries none."""
|
|
102
|
+
for key in ("model", "model_id"):
|
|
103
|
+
value = payload.get(key)
|
|
104
|
+
if isinstance(value, str) and value.strip():
|
|
105
|
+
return value.strip()[:_MAX_MODEL_LEN]
|
|
106
|
+
if isinstance(value, dict):
|
|
107
|
+
for sub in ("display_name", "name", "id"):
|
|
108
|
+
name = value.get(sub)
|
|
109
|
+
if isinstance(name, str) and name.strip():
|
|
110
|
+
return name.strip()[:_MAX_MODEL_LEN]
|
|
111
|
+
return None
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _payload_context(payload: dict) -> tuple[Optional[int], Optional[int]]:
|
|
115
|
+
"""(used_tokens, window_tokens) from the payload, or (None, None).
|
|
116
|
+
|
|
117
|
+
The forum-observed shape is ``context_window.{total_input_tokens,
|
|
118
|
+
context_window_size}``; top-level ``context_tokens``/``context_window_size``
|
|
119
|
+
(the preCompact hook's documented keys) are tolerated as well. Non-positive
|
|
120
|
+
or non-numeric values are treated as absent.
|
|
121
|
+
"""
|
|
122
|
+
candidates = []
|
|
123
|
+
cw = payload.get("context_window")
|
|
124
|
+
if isinstance(cw, dict):
|
|
125
|
+
candidates.append((cw.get("total_input_tokens"), cw.get("context_window_size")))
|
|
126
|
+
candidates.append((payload.get("context_tokens"), payload.get("context_window_size")))
|
|
127
|
+
for used_raw, window_raw in candidates:
|
|
128
|
+
try:
|
|
129
|
+
used = int(float(used_raw)) if used_raw is not None else 0
|
|
130
|
+
window = int(float(window_raw)) if window_raw is not None else 0
|
|
131
|
+
except (TypeError, ValueError, OverflowError):
|
|
132
|
+
continue
|
|
133
|
+
if used > 0 and window > 0:
|
|
134
|
+
return used, window
|
|
135
|
+
return None, None
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def _payload_conversation_id(payload: dict) -> str:
|
|
139
|
+
for key in ("conversation_id", "session_id"):
|
|
140
|
+
value = payload.get(key)
|
|
141
|
+
if isinstance(value, str) and value.strip():
|
|
142
|
+
return value.strip()
|
|
143
|
+
return ""
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
# ---------------------------------------------------------------------------
|
|
147
|
+
# Session tally (read-only; written by cursor_hook_bridge.py)
|
|
148
|
+
# ---------------------------------------------------------------------------
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def _sanitize_session_id(sid: str) -> str:
|
|
152
|
+
"""Mirror cursor_hook_bridge._sanitize_session_id (path-traversal guard)."""
|
|
153
|
+
if not sid:
|
|
154
|
+
return "unknown"
|
|
155
|
+
cleaned = _SESSION_ID_RE.sub("", sid)[:64]
|
|
156
|
+
return cleaned if len(cleaned) >= 6 else "unknown"
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def _cursor_home() -> Path:
|
|
160
|
+
try:
|
|
161
|
+
from runtime_env import cursor_home
|
|
162
|
+
|
|
163
|
+
return cursor_home()
|
|
164
|
+
except Exception: # broken/partial install: read the default location
|
|
165
|
+
return Path.home() / ".cursor"
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def _read_tally(path: Path) -> Optional[dict]:
|
|
169
|
+
try:
|
|
170
|
+
if path.stat().st_size > _MAX_TALLY_BYTES:
|
|
171
|
+
return None
|
|
172
|
+
data = json.loads(path.read_text(encoding="utf-8", errors="replace"))
|
|
173
|
+
return data if isinstance(data, dict) else None
|
|
174
|
+
except (OSError, json.JSONDecodeError, ValueError):
|
|
175
|
+
return None
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def _safe_float(value: Any) -> Optional[float]:
|
|
179
|
+
try:
|
|
180
|
+
return float(value)
|
|
181
|
+
except (TypeError, ValueError, OverflowError):
|
|
182
|
+
return None
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def _find_tally(sessions_dir: Path, sid: str) -> Optional[dict]:
|
|
186
|
+
"""Tally for this conversation, else the most recently updated tally.
|
|
187
|
+
|
|
188
|
+
A sanitized id of "unknown" never selects the literal unknown.json bucket —
|
|
189
|
+
that file mixes every id-less session, so the latest-real-tally fallback is
|
|
190
|
+
the honest choice.
|
|
191
|
+
"""
|
|
192
|
+
if not sessions_dir.is_dir():
|
|
193
|
+
return None
|
|
194
|
+
clean = _sanitize_session_id(sid)
|
|
195
|
+
if clean != "unknown":
|
|
196
|
+
direct = _read_tally(sessions_dir / f"{clean}.json")
|
|
197
|
+
if direct is not None:
|
|
198
|
+
return direct
|
|
199
|
+
try:
|
|
200
|
+
candidates = sorted(
|
|
201
|
+
(p for p in sessions_dir.iterdir() if p.is_file() and p.suffix == ".json"),
|
|
202
|
+
key=lambda p: p.stat().st_mtime,
|
|
203
|
+
reverse=True,
|
|
204
|
+
)[:_MAX_TALLY_CANDIDATES]
|
|
205
|
+
except OSError:
|
|
206
|
+
return None
|
|
207
|
+
best: Optional[dict] = None
|
|
208
|
+
best_updated = -1.0
|
|
209
|
+
for path in candidates:
|
|
210
|
+
tally = _read_tally(path)
|
|
211
|
+
if tally is None:
|
|
212
|
+
continue
|
|
213
|
+
updated = _safe_float(tally.get("updated_at")) or 0.0
|
|
214
|
+
if updated > best_updated:
|
|
215
|
+
best, best_updated = tally, updated
|
|
216
|
+
return best
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def _last_compaction(tally: dict) -> tuple[Optional[float], Optional[float]]:
|
|
220
|
+
"""(fill_percent, measured_ts) of the newest usable preCompact entry.
|
|
221
|
+
|
|
222
|
+
This is a HISTORICAL measurement: the occupancy the host reported just
|
|
223
|
+
BEFORE that compaction ran (the peak that triggered it), recorded with the
|
|
224
|
+
entry's own ``ts``. It is never the current fill — after the compaction the
|
|
225
|
+
real occupancy dropped, and later hook events bump only the tally's
|
|
226
|
+
updated_at, not this number. The bridge records context_usage_percent as
|
|
227
|
+
its own field, so an entry may carry a percent without token counts; token
|
|
228
|
+
counts are preferred when present.
|
|
229
|
+
"""
|
|
230
|
+
compactions = tally.get("compactions")
|
|
231
|
+
if not isinstance(compactions, list):
|
|
232
|
+
return None, None
|
|
233
|
+
for entry in reversed(compactions):
|
|
234
|
+
if not isinstance(entry, dict):
|
|
235
|
+
continue
|
|
236
|
+
ts = _safe_float(entry.get("ts"))
|
|
237
|
+
used = _safe_float(entry.get("context_tokens"))
|
|
238
|
+
window = _safe_float(entry.get("context_window_size"))
|
|
239
|
+
if used and window and used > 0 and window > 0:
|
|
240
|
+
return min(100.0, 100.0 * used / window), ts
|
|
241
|
+
pct = _safe_float(entry.get("context_usage_percent"))
|
|
242
|
+
if pct and pct > 0:
|
|
243
|
+
return min(100.0, pct), ts
|
|
244
|
+
return None, None
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def _fmt_age(ts: Optional[float]) -> str:
|
|
248
|
+
"""'3m ago' style age of a measurement timestamp; '' when unknown/implausible."""
|
|
249
|
+
if not ts or ts <= 0:
|
|
250
|
+
return ""
|
|
251
|
+
age = time.time() - ts
|
|
252
|
+
if age < 0 or age > 30 * 86400:
|
|
253
|
+
return ""
|
|
254
|
+
if age < 90:
|
|
255
|
+
return "just now"
|
|
256
|
+
if age < 3600:
|
|
257
|
+
return f"{int(age // 60)}m ago"
|
|
258
|
+
if age < 86400:
|
|
259
|
+
return f"{int(age // 3600)}h ago"
|
|
260
|
+
return f"{int(age // 86400)}d ago"
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
# ---------------------------------------------------------------------------
|
|
264
|
+
# Fill-derived grade (mirrors cursor_session._quality's documented fallback)
|
|
265
|
+
# ---------------------------------------------------------------------------
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
def _fill_grade(fill_frac: float) -> tuple[int, str]:
|
|
269
|
+
fill = min(1.0, max(0.0, fill_frac))
|
|
270
|
+
score = max(0, round(100.0 - fill * 50.0))
|
|
271
|
+
grade = "A" if score >= 90 else ("B" if score >= 75 else ("C" if score >= 60 else "D"))
|
|
272
|
+
return score, grade
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
def _fmt_tokens(n: int) -> str:
|
|
276
|
+
return f"{n / 1000:.0f}k" if n >= 1000 else str(n)
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
# ---------------------------------------------------------------------------
|
|
280
|
+
# Line assembly
|
|
281
|
+
# ---------------------------------------------------------------------------
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
def build_lines(payload: dict, tally: Optional[dict]) -> list[str]:
|
|
285
|
+
"""Assemble the footer rows. Empty list => print nothing.
|
|
286
|
+
|
|
287
|
+
Never renders approval-mode state: the payload's ``autorun`` boolean cannot
|
|
288
|
+
distinguish Allowlist from Auto-review (staff-confirmed), so it is read by
|
|
289
|
+
no code path here on purpose.
|
|
290
|
+
"""
|
|
291
|
+
used, window = _payload_context(payload) if PAYLOAD_FILL_PROVEN else (None, None)
|
|
292
|
+
live_fill = used is not None and bool(window)
|
|
293
|
+
|
|
294
|
+
# Line 1: native-footer reconstruction (model + context fill).
|
|
295
|
+
segments = []
|
|
296
|
+
model = _payload_model(payload)
|
|
297
|
+
if model is None and tally is not None:
|
|
298
|
+
models = tally.get("models")
|
|
299
|
+
if isinstance(models, dict) and len(models) == 1:
|
|
300
|
+
# The tally records per-model turn COUNTS with no recency, so after
|
|
301
|
+
# a mid-session model switch max-by-count could name a model the
|
|
302
|
+
# session has moved away from. Only a single recorded model is a
|
|
303
|
+
# safe display; anything richer needs a last_model tally field
|
|
304
|
+
# (requested from the bridge owner in the wiring spec).
|
|
305
|
+
model = str(next(iter(models)))[:_MAX_MODEL_LEN]
|
|
306
|
+
if model:
|
|
307
|
+
segments.append(model)
|
|
308
|
+
if live_fill:
|
|
309
|
+
pct = min(100, round(100 * used / window))
|
|
310
|
+
segments.append(f"ctx {pct}% ({_fmt_tokens(used)}/{_fmt_tokens(window)})")
|
|
311
|
+
else:
|
|
312
|
+
# Current occupancy is UNKNOWN on Cursor today: the only recorded
|
|
313
|
+
# occupancy is the pre-compaction peak (historical), shown on line 2.
|
|
314
|
+
segments.append("ctx ?")
|
|
315
|
+
line1 = " · ".join(segments) if segments else ""
|
|
316
|
+
|
|
317
|
+
# Line 2: Token Optimizer session facts from the tally.
|
|
318
|
+
if tally is None:
|
|
319
|
+
line2 = "TO · no session data"
|
|
320
|
+
else:
|
|
321
|
+
parts = []
|
|
322
|
+
if live_fill:
|
|
323
|
+
score, grade = _fill_grade(used / window)
|
|
324
|
+
parts.append(f"TO {grade} {score}")
|
|
325
|
+
parts.append("fill live")
|
|
326
|
+
else:
|
|
327
|
+
# No grade: a fill-derived score from the historical pre-compaction
|
|
328
|
+
# peak would present stale data as current quality.
|
|
329
|
+
last_pct, last_ts = _last_compaction(tally)
|
|
330
|
+
if last_pct is not None:
|
|
331
|
+
note = f"last compact {round(last_pct)}%"
|
|
332
|
+
age = _fmt_age(last_ts)
|
|
333
|
+
if age:
|
|
334
|
+
note += f" {age}"
|
|
335
|
+
parts.append("TO · " + note)
|
|
336
|
+
else:
|
|
337
|
+
parts.append("TO · ctx unknown")
|
|
338
|
+
compactions = tally.get("compactions")
|
|
339
|
+
if isinstance(compactions, list):
|
|
340
|
+
parts.append(f"comp {len(compactions)}")
|
|
341
|
+
tool_calls = tally.get("tool_calls")
|
|
342
|
+
if isinstance(tool_calls, (int, float)) and tool_calls > 0:
|
|
343
|
+
parts.append(f"tools {int(tool_calls)}")
|
|
344
|
+
line2 = " · ".join(parts)
|
|
345
|
+
|
|
346
|
+
return [line for line in (line1, line2) if line]
|
|
347
|
+
|
|
348
|
+
|
|
349
|
+
def main() -> int:
|
|
350
|
+
try:
|
|
351
|
+
payload = _read_stdin_payload()
|
|
352
|
+
home = _cursor_home()
|
|
353
|
+
tally = _find_tally(home / "token-optimizer" / "sessions",
|
|
354
|
+
_payload_conversation_id(payload))
|
|
355
|
+
lines = build_lines(payload, tally)
|
|
356
|
+
if lines:
|
|
357
|
+
stream = sys.stdout
|
|
358
|
+
encoding = (getattr(stream, "encoding", "") or "").lower().replace("-", "")
|
|
359
|
+
if encoding and encoding not in ("utf8", "cp65001"):
|
|
360
|
+
try:
|
|
361
|
+
stream.reconfigure(encoding="utf-8", errors="replace")
|
|
362
|
+
except (AttributeError, OSError, ValueError):
|
|
363
|
+
lines = [line.encode("ascii", "replace").decode("ascii") for line in lines]
|
|
364
|
+
stream.write("\n".join(lines) + "\n")
|
|
365
|
+
sys.stdout.flush()
|
|
366
|
+
except Exception: # never break the footer; fail silent per docstring
|
|
367
|
+
pass
|
|
368
|
+
return 0
|
|
369
|
+
|
|
370
|
+
|
|
371
|
+
if __name__ == "__main__":
|
|
372
|
+
sys.exit(main())
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
"""Thin thrash-guard adapter for the Cursor runtime (U5).
|
|
2
|
+
|
|
3
|
+
Reuses ``thrash_guard.check`` unchanged - the streak, burn and inline-script
|
|
4
|
+
logic, thresholds, cooldowns and redaction stay byte-identical with the
|
|
5
|
+
Claude path. This module only bridges two Claude-era assumptions:
|
|
6
|
+
|
|
7
|
+
1. ``thrash_guard.check`` keys its streak store on ``CLAUDE_SESSION_ID``;
|
|
8
|
+
the Cursor conversation_id (already sanitized by the bridge) is supplied
|
|
9
|
+
through that variable for the duration of the call.
|
|
10
|
+
2. ``session_store.SNAPSHOT_DIR`` resolves at import time; pointing
|
|
11
|
+
``TOKEN_OPTIMIZER_SNAPSHOT_DIR`` at ``<cursor_home>/token-optimizer``
|
|
12
|
+
keeps Cursor streak state under the Cursor home instead of any Claude
|
|
13
|
+
plugin-data dir (the Claude ledger must never see Cursor activity).
|
|
14
|
+
Hook invocations are one-shot processes, so the env shims cannot leak
|
|
15
|
+
across runtimes; they are restored anyway for the in-process tests.
|
|
16
|
+
|
|
17
|
+
Fail-open by contract: any error returns None and the hook emits nothing.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
import os
|
|
23
|
+
|
|
24
|
+
_SNAPSHOT_ENV = "TOKEN_OPTIMIZER_SNAPSHOT_DIR"
|
|
25
|
+
_SESSION_ENV = "CLAUDE_SESSION_ID"
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _set_env(name, value):
|
|
29
|
+
old = os.environ.get(name)
|
|
30
|
+
os.environ[name] = value
|
|
31
|
+
return old
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _restore_env(name, old):
|
|
35
|
+
if old is None:
|
|
36
|
+
os.environ.pop(name, None)
|
|
37
|
+
else:
|
|
38
|
+
os.environ[name] = old
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def shell_thrash_nudge(fields, now=None):
|
|
42
|
+
"""Return a thrash nudge line for a Cursor Shell postToolUse, else None.
|
|
43
|
+
|
|
44
|
+
``fields`` is the bridge's decoded payload (tool_args.command,
|
|
45
|
+
tool_output, conversation_id). Cursor's postToolUse carries no separate
|
|
46
|
+
exit code or stderr stream, so failure detection falls back to
|
|
47
|
+
thrash_guard's output heuristics - identical to a Claude run whose
|
|
48
|
+
caller does not know the exit status.
|
|
49
|
+
"""
|
|
50
|
+
try:
|
|
51
|
+
tool_args = fields.get("tool_args")
|
|
52
|
+
command = tool_args.get("command") if isinstance(tool_args, dict) else None
|
|
53
|
+
output = fields.get("tool_output") or ""
|
|
54
|
+
sid = fields.get("conversation_id") or ""
|
|
55
|
+
if not command or not isinstance(command, str) or not output or not sid:
|
|
56
|
+
return None
|
|
57
|
+
|
|
58
|
+
from runtime_env import cursor_home
|
|
59
|
+
|
|
60
|
+
old_session = _set_env(_SESSION_ENV, sid)
|
|
61
|
+
old_snapshot = _set_env(
|
|
62
|
+
_SNAPSHOT_ENV, str(cursor_home() / "token-optimizer" / "snapshot")
|
|
63
|
+
)
|
|
64
|
+
try:
|
|
65
|
+
from thrash_guard import check as _thrash_check
|
|
66
|
+
|
|
67
|
+
import session_store
|
|
68
|
+
old_dir = session_store.SNAPSHOT_DIR
|
|
69
|
+
session_store.SNAPSHOT_DIR = cursor_home() / "token-optimizer" / "snapshot"
|
|
70
|
+
try:
|
|
71
|
+
return _thrash_check(command, output, combined_output=True, now=now)
|
|
72
|
+
finally:
|
|
73
|
+
session_store.SNAPSHOT_DIR = old_dir
|
|
74
|
+
finally:
|
|
75
|
+
_restore_env(_SESSION_ENV, old_session)
|
|
76
|
+
_restore_env(_SNAPSHOT_ENV, old_snapshot)
|
|
77
|
+
except Exception:
|
|
78
|
+
return None
|
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
"""U1: Cursor on-disk transcript adapter.
|
|
2
|
+
|
|
3
|
+
Reads Cursor's on-disk transcript JSONL and translates it into
|
|
4
|
+
Claude-Code-shaped transcript records, the Hermes precedent exactly
|
|
5
|
+
(``hermes_session.messages_to_transcript_records`` output shape), so the
|
|
6
|
+
existing ``compact_capture(_trusted_transcript=...)`` pipeline consumes it
|
|
7
|
+
with no new dict-shaped contract.
|
|
8
|
+
|
|
9
|
+
Source schema (bundle-proven, Cursor CLI 2026.11.05 TranscriptStore,
|
|
10
|
+
7923.index.js): one JSON object per line, ``{"role": <role>, "message":
|
|
11
|
+
{"content": [...]}}`` with ``{type:"text",text}`` and ``{type:"tool_use",
|
|
12
|
+
name,input}`` content entries; terminal lines ``{"type":"turn_ended",
|
|
13
|
+
status, ...}``. Disk transcripts carry NO tool-result text - the writer
|
|
14
|
+
reduces tool-result content to ``{toolName}`` and drops it (U/R at
|
|
15
|
+
9679-11290). Callers needing failure detail must use the observed ledger /
|
|
16
|
+
hook payloads instead; this adapter never fabricates results.
|
|
17
|
+
|
|
18
|
+
The translated file is credential-redacted and written 0o600 under
|
|
19
|
+
``<cursor_home>/token-optimizer/transcripts/`` before any downstream
|
|
20
|
+
consumer reads it. Reads are byte-capped and confined under
|
|
21
|
+
``<cursor_home>/projects`` (a crafted path is refused, never followed).
|
|
22
|
+
Unknown or malformed lines are skipped with a count, never fatal.
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
from __future__ import annotations
|
|
26
|
+
|
|
27
|
+
import json
|
|
28
|
+
import os
|
|
29
|
+
from pathlib import Path
|
|
30
|
+
from typing import Any, Optional
|
|
31
|
+
|
|
32
|
+
_MAX_TRANSCRIPT_BYTES = 8 * 1024 * 1024
|
|
33
|
+
_MAX_MESSAGES = 4000
|
|
34
|
+
_WRITER_SCHEMA = "cursor-transcriptstore-jsonl@2026.11.05"
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _confined_transcript_path(transcript_path: Any, home: Path) -> Optional[Path]:
|
|
38
|
+
"""Resolve a transcript path confined under <home>/projects, else None."""
|
|
39
|
+
if not transcript_path:
|
|
40
|
+
return None
|
|
41
|
+
try:
|
|
42
|
+
path = Path(str(transcript_path))
|
|
43
|
+
root = (home / "projects").resolve(strict=False)
|
|
44
|
+
resolved = path.resolve(strict=False)
|
|
45
|
+
if not resolved.is_relative_to(root):
|
|
46
|
+
return None
|
|
47
|
+
except (OSError, ValueError):
|
|
48
|
+
return None
|
|
49
|
+
return path if path.is_file() else None
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def read_cursor_messages(transcript_path: Any, home: Path) -> tuple[list[dict], int]:
|
|
53
|
+
"""Read a Cursor transcript into normalized messages.
|
|
54
|
+
|
|
55
|
+
Returns (messages, skipped_lines). Each message: {"role": str,
|
|
56
|
+
"content": str, "tool_calls": [{"name": str, "input": dict}],
|
|
57
|
+
"turn_ended": bool}. Malformed JSON lines and unknown shapes are
|
|
58
|
+
skipped and counted. Bounded bytes and message count. Never raises.
|
|
59
|
+
"""
|
|
60
|
+
path = _confined_transcript_path(transcript_path, home)
|
|
61
|
+
if path is None:
|
|
62
|
+
return [], 0
|
|
63
|
+
try:
|
|
64
|
+
with path.open("rb") as fh:
|
|
65
|
+
raw = fh.read(_MAX_TRANSCRIPT_BYTES + 1)
|
|
66
|
+
raw = raw[:_MAX_TRANSCRIPT_BYTES]
|
|
67
|
+
except OSError:
|
|
68
|
+
return [], 0
|
|
69
|
+
messages: list[dict] = []
|
|
70
|
+
skipped = 0
|
|
71
|
+
for line in raw.decode("utf-8", errors="replace").splitlines():
|
|
72
|
+
line = line.strip()
|
|
73
|
+
if not line:
|
|
74
|
+
continue
|
|
75
|
+
try:
|
|
76
|
+
rec = json.loads(line)
|
|
77
|
+
except ValueError:
|
|
78
|
+
skipped += 1
|
|
79
|
+
continue
|
|
80
|
+
if not isinstance(rec, dict):
|
|
81
|
+
skipped += 1
|
|
82
|
+
continue
|
|
83
|
+
if rec.get("type") == "turn_ended":
|
|
84
|
+
# The ONE piece of terminal evidence on disk: preserve status and
|
|
85
|
+
# error verbatim. Absence of tool results elsewhere must never be
|
|
86
|
+
# read as "tools ran clean"; a turn_ended error is the only
|
|
87
|
+
# disk-backed failure signal this format carries.
|
|
88
|
+
if messages:
|
|
89
|
+
messages[-1]["turn_ended"] = True
|
|
90
|
+
status = rec.get("status")
|
|
91
|
+
if isinstance(status, str) and status:
|
|
92
|
+
messages[-1]["turn_ended_status"] = status
|
|
93
|
+
error = rec.get("error")
|
|
94
|
+
if isinstance(error, str) and error:
|
|
95
|
+
messages[-1]["turn_ended_error"] = error
|
|
96
|
+
continue
|
|
97
|
+
if rec.get("type") == "conversation_meta":
|
|
98
|
+
continue # known schema line (overview/metadata), not a message
|
|
99
|
+
role = rec.get("role")
|
|
100
|
+
body = rec.get("message")
|
|
101
|
+
if not isinstance(role, str) or not isinstance(body, dict):
|
|
102
|
+
skipped += 1 # unknown shapes and malformed records
|
|
103
|
+
continue
|
|
104
|
+
content = body.get("content")
|
|
105
|
+
text_parts: list[str] = []
|
|
106
|
+
tool_calls: list[dict] = []
|
|
107
|
+
if isinstance(content, str):
|
|
108
|
+
text_parts.append(content)
|
|
109
|
+
elif isinstance(content, list):
|
|
110
|
+
for block in content:
|
|
111
|
+
if not isinstance(block, dict):
|
|
112
|
+
continue
|
|
113
|
+
btype = block.get("type")
|
|
114
|
+
if btype == "text":
|
|
115
|
+
text = block.get("text")
|
|
116
|
+
if isinstance(text, str) and text.strip():
|
|
117
|
+
text_parts.append(text)
|
|
118
|
+
elif btype == "tool_use":
|
|
119
|
+
name = block.get("name")
|
|
120
|
+
if isinstance(name, str) and name:
|
|
121
|
+
tool_calls.append({
|
|
122
|
+
"name": name,
|
|
123
|
+
"input": block.get("input") if isinstance(block.get("input"), dict) else {},
|
|
124
|
+
})
|
|
125
|
+
if not text_parts and not tool_calls:
|
|
126
|
+
continue
|
|
127
|
+
messages.append({
|
|
128
|
+
"role": role,
|
|
129
|
+
"content": "\n\n".join(text_parts),
|
|
130
|
+
"tool_calls": tool_calls,
|
|
131
|
+
"turn_ended": False,
|
|
132
|
+
})
|
|
133
|
+
if len(messages) >= _MAX_MESSAGES:
|
|
134
|
+
break
|
|
135
|
+
return messages, skipped
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def messages_to_cc_records(messages: list[dict]) -> list[dict]:
|
|
139
|
+
"""Translate normalized Cursor messages into CC-shaped transcript records.
|
|
140
|
+
|
|
141
|
+
Same output contract as hermes_session.messages_to_transcript_records:
|
|
142
|
+
user rows carry text content, assistant rows carry text + tool_use
|
|
143
|
+
blocks; rows with neither are dropped. Cursor disk transcripts have no
|
|
144
|
+
tool-result rows to skip (the writer never persists them): a translated
|
|
145
|
+
assistant record with tool_use blocks says NOTHING about whether those
|
|
146
|
+
calls succeeded - absence of results is not evidence of health, and no
|
|
147
|
+
consumer may present it as error-free execution.
|
|
148
|
+
"""
|
|
149
|
+
records: list[dict] = []
|
|
150
|
+
for msg in messages or []:
|
|
151
|
+
if not isinstance(msg, dict):
|
|
152
|
+
continue
|
|
153
|
+
role = msg.get("role")
|
|
154
|
+
text = msg.get("content") or ""
|
|
155
|
+
if not isinstance(text, str):
|
|
156
|
+
text = ""
|
|
157
|
+
if role == "user":
|
|
158
|
+
if text.strip():
|
|
159
|
+
records.append({"type": "user", "message": {"role": "user", "content": text}})
|
|
160
|
+
elif role == "assistant":
|
|
161
|
+
blocks: list[dict] = []
|
|
162
|
+
if text.strip():
|
|
163
|
+
blocks.append({"type": "text", "text": text})
|
|
164
|
+
for call in msg.get("tool_calls") or []:
|
|
165
|
+
if not isinstance(call, dict):
|
|
166
|
+
continue
|
|
167
|
+
name = call.get("name")
|
|
168
|
+
if isinstance(name, str) and name:
|
|
169
|
+
blocks.append({"type": "tool_use", "name": name, "input": call.get("input") or {}})
|
|
170
|
+
# Carry the disk's only terminal failure evidence INTO the CC
|
|
171
|
+
# records as a bracketed provenance-tagged text block, so
|
|
172
|
+
# compact_capture's error-context extraction can see a
|
|
173
|
+
# turn_ended error. A success line adds nothing (absence of
|
|
174
|
+
# error is the disk's healthy signal, stated, not fabricated).
|
|
175
|
+
status = msg.get("turn_ended_status")
|
|
176
|
+
if msg.get("turn_ended") and isinstance(status, str) and status != "success":
|
|
177
|
+
note = f"[cursor turn_ended status={status}"
|
|
178
|
+
err = msg.get("turn_ended_error")
|
|
179
|
+
if isinstance(err, str) and err.strip():
|
|
180
|
+
note += f": {err.strip()[:200]}"
|
|
181
|
+
blocks.append({"type": "text", "text": note + "]"})
|
|
182
|
+
if blocks:
|
|
183
|
+
records.append({"type": "assistant", "message": {"role": "assistant", "content": blocks}})
|
|
184
|
+
return records
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def translate_transcript(transcript_path: Any, home: Path, conversation_id: str) -> Optional[Path]:
|
|
188
|
+
"""Translate a Cursor transcript to a redacted CC-shaped JSONL file.
|
|
189
|
+
|
|
190
|
+
Writes ``<home>/token-optimizer/transcripts/<conversation_id>.jsonl``
|
|
191
|
+
with mode 0o600 (never following a pre-existing symlink at the target)
|
|
192
|
+
and returns its path, or None when there is nothing to translate.
|
|
193
|
+
Credential redaction runs on every serialized record line BEFORE the
|
|
194
|
+
file exists on disk. Never raises.
|
|
195
|
+
"""
|
|
196
|
+
try:
|
|
197
|
+
safe_id = "".join(c for c in str(conversation_id) if c.isalnum() or c in "_-")[:64]
|
|
198
|
+
if len(safe_id) < 6:
|
|
199
|
+
return None
|
|
200
|
+
messages, _skipped = read_cursor_messages(transcript_path, home)
|
|
201
|
+
if not messages:
|
|
202
|
+
return None
|
|
203
|
+
records = messages_to_cc_records(messages)
|
|
204
|
+
if not records:
|
|
205
|
+
return None
|
|
206
|
+
|
|
207
|
+
from archive_result import _redact_credentials
|
|
208
|
+
|
|
209
|
+
lines = [_redact_credentials(json.dumps(r, ensure_ascii=False)) for r in records]
|
|
210
|
+
out_dir = Path(home) / "token-optimizer" / "transcripts"
|
|
211
|
+
out_dir.mkdir(parents=True, exist_ok=True, mode=0o700)
|
|
212
|
+
out_path = out_dir / f"{safe_id}.jsonl"
|
|
213
|
+
if out_path.is_symlink():
|
|
214
|
+
return None
|
|
215
|
+
fd = os.open(str(out_path), os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
|
216
|
+
try:
|
|
217
|
+
with os.fdopen(fd, "w", encoding="utf-8") as fh:
|
|
218
|
+
fh.write("\n".join(lines) + "\n")
|
|
219
|
+
except BaseException:
|
|
220
|
+
raise
|
|
221
|
+
return out_path
|
|
222
|
+
except Exception:
|
|
223
|
+
return None
|