@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
@@ -0,0 +1,505 @@
1
+ #!/usr/bin/env python3
2
+ """Cursor session quality scoring with per-signal provenance (Slice D / U6).
3
+
4
+ Moves the Cursor quality score off the bare three-signal fallback toward the
5
+ full seven-signal model - one proven data source at a time, and never past
6
+ what Cursor actually carries.
7
+
8
+ Data-source reality (bundle-proven against Cursor CLI 2026.11.05, and the
9
+ recorded hook contract this repo observes):
10
+
11
+ - preCompact ``context_tokens`` / ``context_window_size`` /
12
+ ``context_usage_percent`` are the host's occupancy AT COMPACTION TIME.
13
+ They are HISTORICAL evidence: after the compaction the real occupancy is
14
+ whatever the host rebuilt, which no hook observes. They are reported as
15
+ fill metadata (labeled ``cursor_precompact_historical``,
16
+ ``fill_is_current`` False) and feed ``compaction_depth`` - a signal about
17
+ the compaction event, itself historical. ``context_fill`` is NEVER graded
18
+ from them: a past peak must not poison the current composite, so the
19
+ signal is omitted and the composite renormalizes.
20
+ - A lifetime token sum is never a fill numerator. With no current host
21
+ occupancy source the fill signal stays omitted.
22
+ - Disk transcripts carry NO tool results (the writer reduces tool-result
23
+ content to ``{toolName}`` and drops it). ``bloated_results`` therefore has
24
+ no source and stays omitted; absence of failure records reflects hook
25
+ coverage, never proof of clean runs.
26
+ - Terminal ``turn_ended`` status/error lines are the disk's ONLY failure
27
+ evidence. This module reads ``cursor_transcript.read_cursor_messages``
28
+ directly for the full status/error detail (the CC-record translation
29
+ carries only a reduced terminal provenance).
30
+ - ``hook_measured_tokens`` (afterAgentResponse usage) are quarantined:
31
+ per-response vs cumulative semantics are unproven, so they never enter
32
+ tokens, fill, or this score.
33
+ - Cursor exposes no local billing data. Nothing here computes dollars.
34
+
35
+ Composite: the base signals (context fill, message count, output/input
36
+ ratio) reuse the EXACT banding tables and relative weights of
37
+ ``hermes_session.compute_quality_score`` (0.40 / 0.35 / 0.25, renormalized
38
+ over active signals) and the same measure.py grade scale. When deeper
39
+ Cursor signals are active they take a 0.40 family share (compaction depth
40
+ 0.15, agent efficiency 0.15, decision density 0.10) and the base family
41
+ keeps its Hermes proportions scaled by 0.6 - the resource/efficiency split
42
+ ported from the Claude composite. A session with only base signals active
43
+ gets a byte-identical score to the shared Hermes scorer; extra evidence
44
+ extends the score, it never forks the scale.
45
+
46
+ Consumers: ``compute_cursor_quality(tally, ...)`` for one session tally;
47
+ ``quality_for_session`` is the seam ``cursor_session.normalize_session`` (and
48
+ the status surfaces) call so there is exactly one Cursor scorer.
49
+ """
50
+
51
+ from __future__ import annotations
52
+
53
+ import logging
54
+ import os
55
+ from pathlib import Path
56
+ from typing import Any, Optional
57
+
58
+ logger = logging.getLogger(__name__)
59
+
60
+
61
+ # Base-signal relative weights, identical to hermes_session.compute_quality_score.
62
+ _BASE_WEIGHTS = {
63
+ "context_fill": 0.40,
64
+ "message_count": 0.35,
65
+ "output_input_ratio": 0.25,
66
+ }
67
+ # Deeper Cursor signals; when any is active the base family scales by 0.6 and
68
+ # these take their 0.4 family share (Claude resource/efficiency split, ported).
69
+ _EXTRA_WEIGHTS = {
70
+ "compaction_depth": 0.15,
71
+ "agent_efficiency": 0.15,
72
+ "decision_density": 0.10,
73
+ }
74
+ _BASE_FAMILY_SCALE_WITH_EXTRAS = 0.6
75
+
76
+ # Signals unavailable from current persisted Cursor data, with the evidence.
77
+ # If a future Cursor version persists a real source, the signal can activate.
78
+ _NEVER_AVAILABLE = {
79
+ "stale_reads": (
80
+ "read-cache events are not aggregated into this scorer, and current "
81
+ "persisted Cursor data carries no reread evidence to measure"
82
+ ),
83
+ "bloated_results": (
84
+ "Cursor disk transcripts never persist tool outputs (bundle-proven "
85
+ "writer 2026.11.05) and hook tool_output is consumed live only"
86
+ ),
87
+ "duplicates": (
88
+ "Cursor's transcript writer strips system-reminder content; there is "
89
+ "no reminder channel to measure"
90
+ ),
91
+ }
92
+
93
+ # Rolling-window + floor for decision density, ported from the Claude scorer
94
+ # (measure.py _QUALITY_ROLLING_WINDOW / _DENSITY_MIN_MESSAGES defaults).
95
+ _DENSITY_WINDOW = 20
96
+ _DENSITY_MIN_MESSAGES = 6
97
+
98
+ _NO_TOOL_RESULTS_CAVEAT = (
99
+ "Cursor disk transcripts carry no tool results (bundle-proven writer "
100
+ "2026.11.05); recorded failures reflect wired-hook coverage, never proof "
101
+ "of clean runs."
102
+ )
103
+ _HISTORICAL_FILL_CAVEAT = (
104
+ "preCompact context numbers are the host's occupancy at compaction time "
105
+ "(historical), reported as metadata only and never graded; current "
106
+ "occupancy is unknown until a fresh host snapshot exists."
107
+ )
108
+
109
+ # Terminal statuses on a disk turn_ended line that count as failure evidence.
110
+ _TERMINAL_ERROR_STATUSES = ("error", "aborted", "abandoned", "failed")
111
+
112
+
113
+ # ---------------------------------------------------------------------------
114
+ # Banding tables - exact mirrors of hermes_session.compute_quality_score
115
+ # ---------------------------------------------------------------------------
116
+
117
+
118
+ def _message_score(count: int) -> int:
119
+ if count <= 20:
120
+ return 100
121
+ if count <= 40:
122
+ return 80
123
+ if count <= 60:
124
+ return 55
125
+ if count <= 100:
126
+ return 30
127
+ return 10
128
+
129
+
130
+ def _oi_score(ratio: float) -> int:
131
+ if ratio >= 0.05:
132
+ return 100
133
+ if ratio >= 0.02:
134
+ return 70
135
+ if ratio >= 0.01:
136
+ return 40
137
+ return 15
138
+
139
+
140
+ def _compaction_depth_score(count: int, latest_fill_ratio: Optional[float]) -> int:
141
+ """Frequency + heat of compactions. A single shallow compaction is fine."""
142
+ score = 100 - 15 * max(0, count - 1)
143
+ if latest_fill_ratio is not None:
144
+ if latest_fill_ratio >= 0.85:
145
+ score -= 20
146
+ elif latest_fill_ratio >= 0.70:
147
+ score -= 10
148
+ return max(10, score)
149
+
150
+
151
+ def _agent_efficiency_score(failures: int, tool_calls: int, terminal_errors: int) -> int:
152
+ rate = failures / tool_calls if tool_calls > 0 else 0.0
153
+ if rate <= 0.0:
154
+ score = 100
155
+ elif rate < 0.02:
156
+ score = 90
157
+ elif rate < 0.05:
158
+ score = 75
159
+ elif rate < 0.10:
160
+ score = 55
161
+ elif rate < 0.20:
162
+ score = 30
163
+ else:
164
+ score = 10
165
+ # Terminal turn_ended errors are the disk's strongest failure evidence.
166
+ return max(0, score - 10 * min(terminal_errors, 3))
167
+
168
+
169
+ def _decision_density_score(messages: list[dict]) -> Optional[float]:
170
+ """Substantive-message ratio over the rolling window (Claude port).
171
+
172
+ Substantive mirrors the Claude parse: user text > 10 words; assistant
173
+ text > 20 words or any tool_use (tool invocations ARE decisions).
174
+ """
175
+ window = messages[-_DENSITY_WINDOW:]
176
+ if len(window) < _DENSITY_MIN_MESSAGES:
177
+ return None
178
+ substantive = 0
179
+ for msg in window:
180
+ role = msg.get("role")
181
+ words = len((msg.get("content") or "").split())
182
+ if role == "user" and words > 10:
183
+ substantive += 1
184
+ elif role == "assistant" and (msg.get("tool_calls") or words > 20):
185
+ substantive += 1
186
+ return min(100.0, (substantive / len(window)) * 200)
187
+
188
+
189
+ # ---------------------------------------------------------------------------
190
+ # Grade scale - measure.py's via hermes_session's helper, with the same
191
+ # inline fallback the shared scorer uses when measure.py is not importable.
192
+ # ---------------------------------------------------------------------------
193
+
194
+
195
+ def _grade_and_band(score: int) -> tuple[str, str]:
196
+ try:
197
+ import hermes_session
198
+
199
+ helpers = hermes_session._get_measure_helpers() # noqa: SLF001
200
+ if helpers:
201
+ # measure.py's facade functions resolve sys.modules['measure'] at
202
+ # CALL time; in harnesses that swap that module out the call can
203
+ # still fail, so the fallback lives around the call, not the lookup.
204
+ return helpers[0](score), helpers[1](score)
205
+ except Exception: # pragma: no cover - defensive
206
+ pass
207
+ if score >= 90:
208
+ grade = "S"
209
+ elif score >= 80:
210
+ grade = "A"
211
+ elif score >= 70:
212
+ grade = "B"
213
+ elif score >= 55:
214
+ grade = "C"
215
+ elif score >= 40:
216
+ grade = "D"
217
+ else:
218
+ grade = "F"
219
+ if score >= 80:
220
+ band = "Good"
221
+ elif score >= 60:
222
+ band = "Fair"
223
+ elif score >= 40:
224
+ band = "Needs Work"
225
+ else:
226
+ band = "Poor"
227
+ return grade, band
228
+
229
+
230
+ # ---------------------------------------------------------------------------
231
+ # Inputs
232
+ # ---------------------------------------------------------------------------
233
+
234
+
235
+ def _default_cursor_home() -> Path:
236
+ # Delegate to runtime_env.cursor_home() so TOKEN_OPTIMIZER_CURSOR_HOME gets
237
+ # the same validation the hook bridge applies (absolute, existing,
238
+ # non-symlink, confined under $HOME / the WSL /mnt opt-in). A bare
239
+ # Path(override) here let scoring read a different home than the bridge
240
+ # writes to.
241
+ try:
242
+ from runtime_env import cursor_home
243
+
244
+ return cursor_home()
245
+ except Exception:
246
+ return Path.home() / ".cursor"
247
+
248
+
249
+ def _safe_int(value: Any, default: int = 0) -> int:
250
+ try:
251
+ return int(float(value)) if value is not None else default
252
+ except (TypeError, ValueError, OverflowError):
253
+ return default
254
+
255
+
256
+ def _latest_compaction_snapshot(compactions: Any) -> Optional[dict]:
257
+ """The most recent preCompact record carrying real host numbers, or None."""
258
+ if not isinstance(compactions, list):
259
+ return None
260
+ for rec in reversed(compactions):
261
+ if not isinstance(rec, dict):
262
+ continue
263
+ tokens = _safe_int(rec.get("context_tokens"))
264
+ window = _safe_int(rec.get("context_window_size"))
265
+ pct = rec.get("context_usage_percent")
266
+ if tokens > 0 and window > 0:
267
+ return {"fill_ratio": min(1.0, tokens / window), "measured_at": rec.get("ts")}
268
+ try:
269
+ pct_val = float(pct)
270
+ except (TypeError, ValueError):
271
+ continue
272
+ if pct_val > 0:
273
+ return {"fill_ratio": min(1.0, pct_val / 100.0), "measured_at": rec.get("ts")}
274
+ return None
275
+
276
+
277
+ def _read_transcript_messages(tally: dict, cursor_home: Path, transcript_path: Any) -> list[dict]:
278
+ path = transcript_path if transcript_path else tally.get("transcript_path")
279
+ if not path:
280
+ return []
281
+ try:
282
+ import cursor_transcript
283
+
284
+ messages, _skipped = cursor_transcript.read_cursor_messages(path, Path(cursor_home))
285
+ return messages
286
+ except Exception as exc: # pragma: no cover - defensive; readers never raise
287
+ logger.debug("[cursor_quality] transcript read failed: %s", exc)
288
+ return []
289
+
290
+
291
+ # ---------------------------------------------------------------------------
292
+ # Public API
293
+ # ---------------------------------------------------------------------------
294
+
295
+
296
+ def compute_cursor_quality(
297
+ tally: Any,
298
+ *,
299
+ cursor_home: Any = None,
300
+ transcript_path: Any = None,
301
+ ) -> Optional[dict]:
302
+ """Score one Cursor session tally with per-signal provenance.
303
+
304
+ ``tally`` is the cursor_hook_bridge session tally, optionally carrying
305
+ the collector-injected ``bubble_tokens`` / ``transcript_tokens`` keys
306
+ (the same convention ``cursor_session.normalize_session`` consumes).
307
+ Returns None for a tally without a session identity. Never raises.
308
+ """
309
+ try:
310
+ if not isinstance(tally, dict):
311
+ return None
312
+ conversation_id = str(tally.get("conversation_id") or tally.get("session_id") or "")
313
+ if not conversation_id:
314
+ return None
315
+
316
+ home = Path(cursor_home) if cursor_home is not None else _default_cursor_home()
317
+
318
+ import cursor_session
319
+
320
+ bubble_tokens = tally.get("bubble_tokens")
321
+ transcript_tokens = tally.get("transcript_tokens")
322
+ total_input, total_output, token_source, estimated = cursor_session.resolve_token_source(
323
+ bubble_tokens, transcript_tokens
324
+ )
325
+
326
+ # context_window_used is a positive fact only for a single known
327
+ # model (bubble_tokens.model, or a one-model tally). Picking the
328
+ # dominant model from a multi-model tally would mislabel recency,
329
+ # and an unknown model must not inherit a default window as "fact".
330
+ models = tally.get("models") if isinstance(tally.get("models"), dict) else {}
331
+ model = None
332
+ if isinstance(bubble_tokens, dict) and bubble_tokens.get("model"):
333
+ model = str(bubble_tokens["model"])
334
+ elif len(models) == 1:
335
+ model = str(next(iter(models)))
336
+ ctx_window = (
337
+ cursor_session.context_window_for_model(model) if model else None
338
+ )
339
+
340
+ turns = _safe_int(tally.get("turns"))
341
+ tool_calls = _safe_int(tally.get("tool_calls"))
342
+ compactions = tally.get("compactions") if isinstance(tally.get("compactions"), list) else []
343
+ failures = tally.get("failures") if isinstance(tally.get("failures"), dict) else {}
344
+ failure_count = sum(_safe_int(v) for v in failures.values())
345
+
346
+ messages = _read_transcript_messages(tally, home, transcript_path)
347
+ terminal_errors = sum(
348
+ 1
349
+ for m in messages
350
+ if str(m.get("turn_ended_status") or "").lower() in _TERMINAL_ERROR_STATUSES
351
+ )
352
+
353
+ snapshot = _latest_compaction_snapshot(compactions)
354
+
355
+ signals_active: list[str] = []
356
+ signals_omitted: list[str] = []
357
+ omitted_reasons: dict[str, str] = {}
358
+ signal_scores: dict[str, Optional[float]] = {}
359
+ signal_provenance: dict[str, str] = {}
360
+
361
+ def _omit(name: str, reason: str) -> None:
362
+ signals_omitted.append(name)
363
+ omitted_reasons[name] = reason
364
+ signal_scores[name] = None
365
+
366
+ # --- base signals ---------------------------------------------------
367
+ # Historical preCompact occupancy is metadata, never a grade: it is
368
+ # host fill at compaction time, not current fill. context_fill stays
369
+ # omitted until a current occupancy source exists; the composite
370
+ # renormalizes over the remaining signals.
371
+ fill_ratio = None
372
+ if snapshot is not None:
373
+ fill_ratio = snapshot["fill_ratio"]
374
+ _omit(
375
+ "context_fill",
376
+ "no current host occupancy source; preCompact context numbers "
377
+ "are historical (fill at compaction time), reported as metadata "
378
+ "only and never graded; a lifetime token sum is never a fill",
379
+ )
380
+
381
+ signals_active.append("message_count")
382
+ signal_scores["message_count"] = _message_score(turns)
383
+ signal_provenance["message_count"] = "cursor_tally_turns"
384
+
385
+ if token_source == "cursor_state_vscdb" and total_input > 0:
386
+ signals_active.append("output_input_ratio")
387
+ signal_scores["output_input_ratio"] = _oi_score(total_output / total_input)
388
+ signal_provenance["output_input_ratio"] = "cursor_state_vscdb"
389
+ else:
390
+ _omit(
391
+ "output_input_ratio",
392
+ "no verified input/output token pair (state.vscdb absent; "
393
+ "estimates carry no output side)",
394
+ )
395
+
396
+ # --- deeper Cursor signals -----------------------------------------
397
+ if compactions:
398
+ signals_active.append("compaction_depth")
399
+ signal_scores["compaction_depth"] = _compaction_depth_score(
400
+ len(compactions), fill_ratio
401
+ )
402
+ signal_provenance["compaction_depth"] = "cursor_precompact_events"
403
+ else:
404
+ _omit(
405
+ "compaction_depth",
406
+ "no preCompact events observed (none fired, or the hook is not "
407
+ "wired on this install)",
408
+ )
409
+
410
+ if tool_calls > 0:
411
+ signals_active.append("agent_efficiency")
412
+ signal_scores["agent_efficiency"] = _agent_efficiency_score(
413
+ failure_count, tool_calls, terminal_errors
414
+ )
415
+ signal_provenance["agent_efficiency"] = (
416
+ "cursor_tally_failures+cursor_transcript_turn_ended"
417
+ )
418
+ else:
419
+ _omit("agent_efficiency", "no tool calls recorded")
420
+
421
+ density = _decision_density_score(messages)
422
+ if density is not None:
423
+ signals_active.append("decision_density")
424
+ signal_scores["decision_density"] = round(density, 1)
425
+ signal_provenance["decision_density"] = "cursor_transcript_disk"
426
+ else:
427
+ _omit(
428
+ "decision_density",
429
+ "no usable disk transcript under <cursor_home>/projects "
430
+ f"(need >= {_DENSITY_MIN_MESSAGES} messages)",
431
+ )
432
+
433
+ for name, reason in _NEVER_AVAILABLE.items():
434
+ _omit(name, reason)
435
+
436
+ # --- composite ------------------------------------------------------
437
+ extras_active = [n for n in _EXTRA_WEIGHTS if n in signals_active]
438
+ base_scale = _BASE_FAMILY_SCALE_WITH_EXTRAS if extras_active else 1.0
439
+ weights: dict[str, float] = {}
440
+ for name in signals_active:
441
+ if name in _BASE_WEIGHTS:
442
+ weights[name] = _BASE_WEIGHTS[name] * base_scale
443
+ else:
444
+ weights[name] = _EXTRA_WEIGHTS[name]
445
+ total_weight = sum(weights.values())
446
+ if total_weight <= 0:
447
+ return None
448
+ weights = {k: v / total_weight for k, v in weights.items()}
449
+ raw = sum(signal_scores[name] * weights[name] for name in signals_active)
450
+ score = int(round(min(100, max(0, raw))))
451
+ grade, band = _grade_and_band(score)
452
+
453
+ caveats = [_NO_TOOL_RESULTS_CAVEAT]
454
+ if snapshot is not None:
455
+ caveats.append(_HISTORICAL_FILL_CAVEAT)
456
+ if token_source != "cursor_state_vscdb":
457
+ caveats.append(
458
+ "token figures are estimated or unknown for this session; "
459
+ "Cursor exposes no billing data and no dollars are computed"
460
+ )
461
+
462
+ return {
463
+ "score": score,
464
+ "grade": grade,
465
+ "band": band,
466
+ "runtime": "cursor",
467
+ "quality_pending": False,
468
+ "signals_active": signals_active,
469
+ "signals_omitted": signals_omitted,
470
+ "omitted_reasons": omitted_reasons,
471
+ "signal_scores": signal_scores,
472
+ "signal_weights": {k: round(v, 4) for k, v in weights.items()},
473
+ "signal_provenance": signal_provenance,
474
+ "caveats": caveats,
475
+ "fill_ratio": round(fill_ratio, 4) if fill_ratio is not None else None,
476
+ "fill_is_current": False if snapshot is not None else None,
477
+ "fill_measured_at": snapshot["measured_at"] if snapshot is not None else None,
478
+ "context_window_used": ctx_window,
479
+ "context_source": (
480
+ "cursor_precompact_historical" if snapshot is not None else "unavailable"
481
+ ),
482
+ "token_source": token_source,
483
+ "estimated": estimated,
484
+ "evidence": {
485
+ "turns": turns,
486
+ "tool_calls": tool_calls,
487
+ "tool_failures": failure_count,
488
+ "terminal_errors": terminal_errors,
489
+ "compactions": len(compactions),
490
+ "transcript_messages": len(messages),
491
+ },
492
+ }
493
+ except Exception as exc: # pragma: no cover - scoring must never break a session
494
+ logger.debug("[cursor_quality] scoring failed: %s", exc)
495
+ return None
496
+
497
+
498
+ def quality_for_session(raw: Any, *, cursor_home: Any = None) -> Optional[dict]:
499
+ """Integration seam for cursor_session.normalize_session / status surfaces.
500
+
501
+ Single call site for the Cursor score so no surface computes its own.
502
+ ``raw`` is the tally (+ collector-injected token keys), exactly as
503
+ ``normalize_session`` receives it.
504
+ """
505
+ return compute_cursor_quality(raw, cursor_home=cursor_home)