@alexgreensh/token-optimizer 5.13.68 → 5.13.69

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/hooks/module_runner.py +1 -1
  4. package/package.json +1 -1
  5. package/skills/fleet-auditor/references/fleet-systems.md +38 -0
  6. package/skills/fleet-auditor/scripts/fleet.py +63 -92
  7. package/skills/fleet-auditor/scripts/fleet_base.py +106 -0
  8. package/skills/fleet-auditor/scripts/fleet_cursor_adapter.py +376 -0
  9. package/skills/token-coach/SKILL.md +21 -23
  10. package/skills/token-dashboard/SKILL.md +5 -4
  11. package/skills/token-optimizer/SKILL.md +1 -1
  12. package/skills/token-optimizer/assets/dashboard.html +101 -50
  13. package/skills/token-optimizer/references/cli-reference.md +1 -1
  14. package/skills/token-optimizer/references/cursor-workflow.md +1 -1
  15. package/skills/token-optimizer/references/phase0-setup.md +1 -1
  16. package/skills/token-optimizer/references/presentation-workflow.md +1 -1
  17. package/skills/token-optimizer/scripts/_measure/__init__.py +1 -1
  18. package/skills/token-optimizer/scripts/_measure/cli.py +86 -0
  19. package/skills/token-optimizer/scripts/_measure/daemon.py +13 -25
  20. package/skills/token-optimizer/scripts/_measure/dashboard.py +63 -37
  21. package/skills/token-optimizer/scripts/_measure/dashboard_history.py +79 -0
  22. package/skills/token-optimizer/scripts/_measure/lifecycle.py +6 -7
  23. package/skills/token-optimizer/scripts/_measure/savings.py +20 -70
  24. package/skills/token-optimizer/scripts/_measure/sessions.py +58 -20
  25. package/skills/token-optimizer/scripts/_measure/weekly_activity.py +69 -0
  26. package/skills/token-optimizer/scripts/antigravity_install.py +4 -0
  27. package/skills/token-optimizer/scripts/bash_compress.py +8 -40
  28. package/skills/token-optimizer/scripts/bash_compress_hook.py +6 -0
  29. package/skills/token-optimizer/scripts/bash_search_results.py +43 -0
  30. package/skills/token-optimizer/scripts/cloud_kit.py +1 -1
  31. package/skills/token-optimizer/scripts/codex_doctor.py +1 -1
  32. package/skills/token-optimizer/scripts/copilot_install.py +4 -0
  33. package/skills/token-optimizer/scripts/credential_patterns.py +4 -19
  34. package/skills/token-optimizer/scripts/credential_url_patterns.py +42 -0
  35. package/skills/token-optimizer/scripts/cursor_audit.py +723 -0
  36. package/skills/token-optimizer/scripts/cursor_bridge_checkpoint.py +213 -0
  37. package/skills/token-optimizer/scripts/cursor_bridge_payload.py +170 -0
  38. package/skills/token-optimizer/scripts/cursor_bridge_rewrite.py +106 -0
  39. package/skills/token-optimizer/scripts/cursor_bridge_rollup.py +115 -0
  40. package/skills/token-optimizer/scripts/cursor_coach.py +485 -0
  41. package/skills/token-optimizer/scripts/cursor_doctor.py +89 -9
  42. package/skills/token-optimizer/scripts/cursor_hook_bridge.py +393 -276
  43. package/skills/token-optimizer/scripts/cursor_install.py +106 -19
  44. package/skills/token-optimizer/scripts/cursor_quality.py +505 -0
  45. package/skills/token-optimizer/scripts/cursor_read_cache.py +597 -0
  46. package/skills/token-optimizer/scripts/cursor_session.py +26 -5
  47. package/skills/token-optimizer/scripts/cursor_state.py +8 -0
  48. package/skills/token-optimizer/scripts/cursor_statusline.py +372 -0
  49. package/skills/token-optimizer/scripts/cursor_thrash.py +78 -0
  50. package/skills/token-optimizer/scripts/cursor_transcript.py +223 -0
  51. package/skills/token-optimizer/scripts/devin_source.py +12 -2
  52. package/skills/token-optimizer/scripts/devin_verify.py +7 -6
  53. package/skills/token-optimizer/scripts/grok_install.py +4 -0
  54. package/skills/token-optimizer/scripts/hermes_doctor.py +4 -1
  55. package/skills/token-optimizer/scripts/hermes_install.py +4 -1
  56. package/skills/token-optimizer/scripts/measure.py +2 -2
  57. package/skills/token-optimizer/scripts/thrash_guard.py +10 -5
@@ -0,0 +1,597 @@
1
+ """Cursor read-path parity (U2): shadow-first redundant-read interception.
2
+
3
+ Reuses the Claude path's ``structure_map`` eligibility and structure maps,
4
+ and ``read_cache``'s message builders and contextignore eligibility, and owns
5
+ only the Cursor-specific parts: payload shape (the bridge's decoded
6
+ ``fields``), the per-session fingerprint store under the Cursor home, the
7
+ mode gate, and the deny + ``user_message`` emit contract.
8
+
9
+ Modes (same names as Claude, one deliberate difference): ``shadow``
10
+ (default: record what would be injected, emit nothing), ``soft_block``
11
+ (deny + injected map - BOUNDED here: after 3 denies for the same
12
+ session+file it degrades to ``warn`` so work always proceeds; Claude's
13
+ ``soft_block`` denies without a bound), ``warn`` (allow + note), ``block``
14
+ (deny, reason only - never degrades). Arming is NEVER automatic:
15
+ ``soft_block``/``block`` take effect only when the install's
16
+ ``<cursor_home>/token-optimizer/read-cache.json`` names the mode. The
17
+ doctor reports the channel state (``unknown``/``shadow``/
18
+ ``armed-unverified``) from the observed ledger; shadow-mode silence
19
+ neither arms nor confirms anything, and no ledger pattern verifies -
20
+ ``armed-verified`` needs positive controlled native evidence no current
21
+ source provides.
22
+
23
+ Fingerprints are scoped to the conversation and promoted only after a
24
+ matching successful Read hook. Changed files are always allowed. KTD9
25
+ coexistence: when Claude Token Optimizer hooks
26
+ are configured (the 4 Claude settings files, read-only) and no explicit
27
+ mode is set, the Read channel defers to record-only - the imported Claude
28
+ hook may own the channel; Cursor's import toggle itself has no verified
29
+ file surface, so ownership is reported as config-presence-based, never
30
+ assumed demonstrated.
31
+
32
+ Fail open everywhere: unknown tool shapes, oversized payloads, decode or
33
+ store failures emit nothing.
34
+ """
35
+
36
+ from __future__ import annotations
37
+
38
+ import json
39
+ import hashlib
40
+ import fnmatch
41
+ import uuid
42
+ import os
43
+ import tempfile
44
+ import time
45
+ from contextlib import contextmanager
46
+ from pathlib import Path
47
+
48
+ _MAX_STORE_ENTRIES = 200
49
+ _MAX_STORE_BYTES = 512 * 1024
50
+ _MAX_FILE_BYTES = 1024 * 1024 # never intercept reads of very large files
51
+ _MODES = ("shadow", "soft_block", "warn", "block")
52
+ _SOFT_BLOCK_MAX_DENIES = 3 # denials per session+file before degrading to warn
53
+ _DEFAULT_MODE = "shadow"
54
+
55
+ # Claude settings files scanned (read-only) for KTD9 coexistence, matching
56
+ # the audit's four-file contract; nothing else under ~/.claude is read.
57
+ _CLAUDE_SETTINGS_REL = (
58
+ ("user", ".claude/settings.json"),
59
+ ("user-local", ".claude/settings.local.json"),
60
+ )
61
+
62
+
63
+ def _home():
64
+ from runtime_env import cursor_home
65
+
66
+ return cursor_home()
67
+
68
+
69
+ def _to_dir() -> Path:
70
+ return _home() / "token-optimizer"
71
+
72
+
73
+ def _config_path() -> Path:
74
+ return _to_dir() / "read-cache.json"
75
+
76
+
77
+ def _load_config() -> dict:
78
+ try:
79
+ data = json.loads(_config_path().read_text(encoding="utf-8"))
80
+ return data if isinstance(data, dict) else {}
81
+ except (OSError, ValueError):
82
+ return {}
83
+
84
+
85
+ def configured_mode() -> str:
86
+ """The install's configured mode; invalid/missing values mean shadow."""
87
+ return _mode_from(_load_config())
88
+
89
+
90
+ def _mode_from(config: dict) -> str:
91
+ mode = config.get("mode")
92
+ return mode if mode in _MODES else _DEFAULT_MODE
93
+
94
+
95
+ def _claude_to_hooks_present(workspace_roots) -> bool:
96
+ """Config-presence check only (KTD9): a Claude TO hook command in any of
97
+ the user settings files or the workspace's project settings files."""
98
+ candidates = []
99
+ home = os.path.expanduser("~")
100
+ for _, rel in _CLAUDE_SETTINGS_REL:
101
+ candidates.append(Path(home) / rel)
102
+ for root in (workspace_roots or [])[:4]:
103
+ if isinstance(root, str) and root:
104
+ candidates.append(Path(root) / ".claude" / "settings.json")
105
+ candidates.append(Path(root) / ".claude" / "settings.local.json")
106
+ needles = ("read_cache", "read-cache")
107
+ for path in candidates[:8]:
108
+ try:
109
+ if not path.is_file() or path.is_symlink():
110
+ continue
111
+ if path.stat().st_size > 256 * 1024:
112
+ continue
113
+ text = path.read_text(encoding="utf-8", errors="replace")
114
+ except OSError:
115
+ continue
116
+ if ("token-optimizer" in text or "measure.py" in text) and any(
117
+ n in text for n in needles
118
+ ):
119
+ return True
120
+ return False
121
+
122
+
123
+ def channel_owner(fields, config: dict | None = None) -> str:
124
+ """Who emits on the Read channel: 'claude-import' (config presence, IDE
125
+ toggle unverified) when Claude TO read hooks exist and no explicit mode
126
+ overrides, else 'cursor'."""
127
+ if config is None:
128
+ config = _load_config()
129
+ explicit = config.get("mode") in ("soft_block", "block", "warn")
130
+ if not explicit and _claude_to_hooks_present(fields.get("workspace_roots")):
131
+ return "claude-import"
132
+ return "cursor"
133
+
134
+
135
+ # ---------------------------------------------------------------------------
136
+ # Per-session fingerprint store
137
+ # ---------------------------------------------------------------------------
138
+
139
+
140
+ def _store_path(sid: str) -> Path:
141
+ safe = sid if sid and len(sid) <= 64 and all(c in "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_" for c in sid) else "~" + hashlib.sha256(sid.encode("utf-8", "surrogatepass")).hexdigest()
142
+ return _to_dir() / "read-fingerprints" / f"{safe}.json"
143
+
144
+
145
+ def _file_key(file_path: str) -> str:
146
+ if len(file_path) <= 1024:
147
+ return file_path
148
+ return "sha256:" + hashlib.sha256(file_path.encode("utf-8", "surrogatepass")).hexdigest()
149
+
150
+
151
+ def clear_session_reads(sid):
152
+ """Advance the compaction epoch; if that fails, discard the store."""
153
+ if not sid or sid == "unknown":
154
+ return
155
+ path = _store_path(sid).with_suffix(".epoch")
156
+ tmp = None
157
+ try:
158
+ path.parent.mkdir(parents=True, exist_ok=True)
159
+ fd, tmp = tempfile.mkstemp(prefix=".epoch-", dir=str(path.parent))
160
+ with os.fdopen(fd, "w", encoding="utf-8") as fh:
161
+ fh.write(uuid.uuid4().hex)
162
+ for attempt in range(3):
163
+ try:
164
+ os.replace(tmp, path)
165
+ return
166
+ except OSError:
167
+ if attempt < 2:
168
+ time.sleep(0.01)
169
+ except OSError:
170
+ pass
171
+ finally:
172
+ if tmp is not None:
173
+ try:
174
+ os.unlink(tmp)
175
+ except OSError:
176
+ pass
177
+ with _store_lock(sid) as acquired:
178
+ if not acquired:
179
+ raise OSError("cannot invalidate read fingerprints")
180
+ _store_path(sid).unlink(missing_ok=True)
181
+
182
+
183
+ def _epoch(sid):
184
+ path = _store_path(sid).with_suffix(".epoch")
185
+ if path.is_symlink():
186
+ raise ValueError("invalid epoch")
187
+ try:
188
+ return path.read_text(encoding="utf-8")
189
+ except FileNotFoundError:
190
+ return ""
191
+
192
+
193
+ def _load_store(sid: str) -> dict:
194
+ try:
195
+ path = _store_path(sid)
196
+ if path.is_symlink() or path.stat().st_size > _MAX_STORE_BYTES:
197
+ return {}
198
+ data = json.loads(path.read_text(encoding="utf-8"))
199
+ epoch = _epoch(sid)
200
+ return data if isinstance(data, dict) and data.get("epoch", "") == epoch else {"epoch": epoch}
201
+ except FileNotFoundError:
202
+ return {"epoch": _epoch(sid)}
203
+ except (OSError, ValueError):
204
+ raise
205
+
206
+
207
+ @contextmanager
208
+ def _store_lock(sid):
209
+ from hook_runtime import lease_lock
210
+ directory = _store_path(sid).parent
211
+ directory.mkdir(parents=True, exist_ok=True)
212
+ with lease_lock(directory / ("." + _store_path(sid).stem + ".lock"),
213
+ acquire_timeout=0.075, cohort_throttle=False,
214
+ reclaim_released=True) as acquired:
215
+ yield acquired
216
+
217
+
218
+ def _save_store(sid: str, store: dict) -> None:
219
+ tmp = None
220
+ try:
221
+ path = _store_path(sid)
222
+ path.parent.mkdir(parents=True, exist_ok=True)
223
+ try:
224
+ os.chmod(path.parent, 0o700)
225
+ except OSError:
226
+ pass
227
+ store.setdefault("epoch", _epoch(sid))
228
+ entries = store.setdefault("files", {})
229
+ while entries:
230
+ encoded = json.dumps(store).encode("utf-8")
231
+ if len(entries) <= _MAX_STORE_ENTRIES and len(encoded) <= _MAX_STORE_BYTES:
232
+ break
233
+ oldest = min(entries, key=lambda key: entries[key].get("ts", 0))
234
+ del entries[oldest]
235
+ encoded = json.dumps(store).encode("utf-8")
236
+ if len(encoded) > _MAX_STORE_BYTES:
237
+ return
238
+ fd, tmp = tempfile.mkstemp(prefix=".fingerprint-", suffix=".tmp", dir=str(path.parent))
239
+ with os.fdopen(fd, "wb") as fh:
240
+ fh.write(encoded)
241
+ os.replace(tmp, path)
242
+ tmp = None
243
+ except OSError:
244
+ pass
245
+ finally:
246
+ if tmp is not None:
247
+ try:
248
+ os.unlink(tmp)
249
+ except OSError:
250
+ pass
251
+
252
+
253
+ # ---------------------------------------------------------------------------
254
+ # Evaluation
255
+ # ---------------------------------------------------------------------------
256
+
257
+
258
+ def _redact_for_storage(text: str) -> str | None:
259
+ """Redact file text before it reaches the persisted fingerprint store.
260
+
261
+ Fail CLOSED: a redactor failure degrades the entry to hash-only (the
262
+ cached content is omitted) rather than persisting raw file content
263
+ (G1). Change detection is unaffected - the sha1 is over the raw bytes.
264
+ """
265
+ try:
266
+ from credential_patterns import redact_credentials
267
+
268
+ redacted = redact_credentials(text)
269
+ return redacted if isinstance(redacted, str) else None
270
+ except Exception:
271
+ return None
272
+
273
+
274
+ def _read_fingerprint(path: Path) -> tuple[str, int, str | None] | None:
275
+ """One read of the target: (sha1, size, redacted-text-if-delta-cacheable).
276
+
277
+ The text is retained only within delta_diff's content-cache cap.
278
+ Symlinks, unreadable and oversized
279
+ files return None (fail open).
280
+ """
281
+ try:
282
+ if path.is_symlink():
283
+ return None
284
+ st = path.stat()
285
+ if not path.is_file() or st.st_size > _MAX_FILE_BYTES:
286
+ return None
287
+ raw = path.read_bytes()
288
+ except OSError:
289
+ return None
290
+ text = None
291
+ try:
292
+ from delta_diff import MAX_CONTENT_CACHE_BYTES
293
+
294
+ if len(raw) <= MAX_CONTENT_CACHE_BYTES:
295
+ text = _redact_for_storage(raw.decode("utf-8", errors="replace"))
296
+ except ImportError:
297
+ pass
298
+ return hashlib.sha1(raw).hexdigest(), st.st_size, text
299
+
300
+
301
+ def _structure_message(file_path: str) -> str | None:
302
+ """Bounded, redacted structure-map message via the Claude builders."""
303
+ try:
304
+ import read_cache
305
+ from structure_map import summarize_code_file
306
+
307
+ summary = summarize_code_file(file_path)
308
+ if summary is None or not getattr(summary, "eligible", False) or not getattr(summary, "replacement_text", ""):
309
+ return None
310
+ text = summary.replacement_text
311
+ if len(text) > 2000:
312
+ text = text[:2000] + "\n[truncated: structure map exceeds budget]"
313
+ summary.replacement_text = text
314
+ saved = max(1, len(text) // 4)
315
+ msg = read_cache._build_structure_message(file_path, summary, saved)
316
+ from credential_patterns import redact_credentials
317
+
318
+ return redact_credentials(msg) or None
319
+ except Exception:
320
+ return None
321
+
322
+
323
+ def _reason_message(file_path: str) -> str:
324
+ try:
325
+ import read_cache
326
+
327
+ return read_cache._build_reason_only_message(file_path)
328
+ except Exception:
329
+ name = Path(file_path).name
330
+ return f"[Token Optimizer] {name} is unchanged (already read this session)."
331
+
332
+
333
+ def _eligible(file_path: str) -> bool:
334
+ try:
335
+ from structure_map import NON_CODE_SUFFIXES, is_structure_supported_file
336
+
337
+ if Path(file_path).suffix.lower() in NON_CODE_SUFFIXES or not is_structure_supported_file(file_path):
338
+ return False
339
+ except Exception:
340
+ return False
341
+ return True
342
+
343
+
344
+
345
+ def _resolve_read_path(fields, file_path):
346
+ roots = fields.get("workspace_roots") or []
347
+ root = fields.get("cwd") or (roots[0] if roots else None)
348
+ path = Path(file_path).expanduser()
349
+ if not path.is_absolute():
350
+ if not root or not Path(root).is_absolute():
351
+ return None
352
+ path = Path(root) / path
353
+ if path.is_symlink():
354
+ return None
355
+ return os.path.normcase(str(path.resolve()))
356
+
357
+
358
+ def _contextignored(path, fields):
359
+ roots = fields.get("workspace_roots") or []
360
+ root = roots[0] if roots else fields.get("cwd")
361
+ root = str(Path(root).resolve()) if root else None
362
+ from runtime_env import runtime_home
363
+ candidates = ([Path(root) / ".contextignore"] if root else []) + [runtime_home() / ".contextignore"]
364
+ for ignore in candidates:
365
+ if not ignore.is_file() or ignore.is_symlink():
366
+ continue
367
+ if ignore.stat().st_size > 256 * 1024:
368
+ return True
369
+ lines = ignore.read_text(encoding="utf-8").splitlines()
370
+ if len(lines) > 1000:
371
+ return True
372
+ for line in lines:
373
+ pattern = line.strip()
374
+ if pattern and not pattern.startswith("#"):
375
+ relative = os.path.relpath(path, root) if root else path
376
+ values = (path, relative, Path(path).name)
377
+ if any(fnmatch.fnmatch(value, pattern) for value in values):
378
+ return True
379
+ if pattern.endswith("/") and (relative.replace(os.sep, "/") + "/").startswith(pattern):
380
+ return True
381
+ return False
382
+
383
+
384
+ def evaluate(fields) -> dict | None:
385
+ """Evaluate a Cursor preToolUse Read payload.
386
+
387
+ Returns {"emit": <bridge emit object>, "observed": <ledger kwargs>} or
388
+ None (emit nothing). Never raises.
389
+ """
390
+ try:
391
+ return _evaluate(fields)
392
+ except Exception:
393
+ return None
394
+
395
+
396
+ def _evaluate(fields) -> dict | None:
397
+ if fields.get("tool_name") != "Read":
398
+ return None
399
+ args = fields.get("tool_args")
400
+ if not isinstance(args, dict):
401
+ return None
402
+ file_path = args.get("file_path")
403
+ if not isinstance(file_path, str) or not file_path.strip():
404
+ return None
405
+ # Partial reads are never intercepted.
406
+ for key in ("offset", "limit"):
407
+ value = args.get(key)
408
+ if isinstance(value, (int, float)) and not isinstance(value, bool) and value:
409
+ return None
410
+ file_path = _resolve_read_path(fields, file_path)
411
+ if not file_path or not _eligible(file_path) or _contextignored(file_path, fields):
412
+ return None
413
+
414
+ sid = fields.get("cache_conversation_id") or fields.get("conversation_id")
415
+ agent = fields.get("agent_id")
416
+ if not sid or sid == "unknown" or not isinstance(agent, str) or not agent.strip():
417
+ return None
418
+ path = Path(file_path)
419
+ fp = _read_fingerprint(path)
420
+ if fp is None:
421
+ return None
422
+ digest, size, current = fp
423
+
424
+ config = _load_config()
425
+ mode = _mode_from(config)
426
+ owner = channel_owner(fields, config)
427
+ if owner != "cursor":
428
+ mode = "shadow" # KTD9 defer: record-only while the import may own it
429
+
430
+ with _store_lock(sid) as acquired:
431
+ if not acquired:
432
+ return None
433
+ return _evaluate_locked(fields, sid, file_path, digest, size, current, mode, owner)
434
+
435
+
436
+ def _evaluate_locked(fields, sid, file_path, digest, size, current, mode, owner):
437
+ store = _load_store(sid)
438
+ files = store.setdefault("files", {})
439
+ key = hashlib.sha256(fields["agent_id"].encode("utf-8", "surrogatepass")).hexdigest() + ":" + _file_key(file_path)
440
+ entry = files.get(key)
441
+ base = {"mode": mode, "owner": owner, "path": Path(file_path).name}
442
+
443
+ if entry is None or not entry.get("hash"):
444
+ # A pre-hook cannot prove the model received a first read either.
445
+ new_entry = {"hash": digest, "size": size, "ts": time.time()}
446
+ if current is not None:
447
+ new_entry["content"] = current
448
+ new_entry["tool_use_id"] = fields.get("tool_use_id") or ""
449
+ files[key] = {"ts": new_entry["ts"], "pending": new_entry}
450
+ _save_store(sid, store)
451
+ return {"emit": None, "observed": {**base, "decision": "first_read"}}
452
+
453
+ if entry.get("hash") != digest:
454
+ # Stage only: a postToolUse success confirms that the new bytes arrived.
455
+ entry["pending"] = {"hash": digest, "size": size, "ts": time.time(),
456
+ "tool_use_id": fields.get("tool_use_id") or "",
457
+ **({"content": current} if current is not None else {})}
458
+ _save_store(sid, store)
459
+ return {"emit": None, "observed": {**base, "decision": "changed_reread"}}
460
+
461
+ # Unchanged redundant read. Shadow/warn do no store write: the ts
462
+ # refresh would be a per-Read-hook disk write for pruning metadata only.
463
+ msg = _structure_message(file_path)
464
+ if not msg:
465
+ return _decide("warn" if mode in ("soft_block", "block") else mode,
466
+ _reason_message(file_path), base, "redundant")
467
+ return _soft_block_decide(mode, msg, base, "redundant", store, sid, key, entry)
468
+
469
+
470
+ def confirm_read(fields):
471
+ """Promote a staged changed fingerprint only after a successful Read hook."""
472
+ try:
473
+ sid = fields.get("cache_conversation_id") or fields.get("conversation_id")
474
+ agent = fields.get("agent_id")
475
+ path = fields.get("tool_args", {}).get("file_path")
476
+ if not sid or sid == "unknown" or not isinstance(agent, str) or not agent.strip() or not isinstance(path, str):
477
+ return
478
+ path = _resolve_read_path(fields, path)
479
+ if not path:
480
+ return
481
+ key = hashlib.sha256(agent.encode("utf-8", "surrogatepass")).hexdigest() + ":" + _file_key(path)
482
+ with _store_lock(sid) as acquired:
483
+ if not acquired:
484
+ return
485
+ store = _load_store(sid)
486
+ entry = store.get("files", {}).get(key)
487
+ pending = entry.get("pending") if isinstance(entry, dict) else None
488
+ if not isinstance(pending, dict):
489
+ return
490
+ expected_id = pending.get("tool_use_id")
491
+ if not expected_id or expected_id != fields.get("tool_use_id"):
492
+ return
493
+ fp = _read_fingerprint(Path(path))
494
+ if fp is None or fp[0] != pending.get("hash"):
495
+ return
496
+ pending.pop("tool_use_id", None)
497
+ store["files"][key] = pending
498
+ _save_store(sid, store)
499
+ except Exception:
500
+ return
501
+
502
+
503
+ def _soft_block_decide(mode, msg, base, kind, store, sid, file_path, entry):
504
+ """_decide with a bounded soft_block: deny loops degrade to warn (G0).
505
+
506
+ The model gets _SOFT_BLOCK_MAX_DENIES real denials (each carrying the
507
+ injected map), then soft_block degrades to warn so work can always
508
+ proceed. Explicit block mode never degrades. The counter costs one store
509
+ write per DENIED read only; other modes keep the write-free hot path.
510
+ """
511
+ if mode != "soft_block":
512
+ return _decide(mode, msg, base, kind)
513
+ denies = int(entry.get("denies", 0) or 0) + 1
514
+ entry["denies"] = denies
515
+ store.setdefault("files", {})[file_path] = entry
516
+ _save_store(sid, store)
517
+ if denies > _SOFT_BLOCK_MAX_DENIES:
518
+ return _decide("warn", msg, base, kind)
519
+ return _decide(mode, msg, base, kind)
520
+
521
+
522
+ def _decide(mode: str, message: str, base: dict, kind: str) -> dict:
523
+ """Map (mode, message) onto the emit contract; shadow emits nothing."""
524
+ if mode == "shadow":
525
+ return {"emit": None, "observed": {**base, "decision": f"shadow_{kind}"}}
526
+ if mode == "warn":
527
+ return {
528
+ "emit": {"user_message": message},
529
+ "observed": {**base, "decision": f"warn_{kind}"},
530
+ }
531
+ if mode == "block":
532
+ note = _reason_message_from(message)
533
+ return {
534
+ "emit": {"permission": "deny", "user_message": note},
535
+ "observed": {**base, "decision": "deny_reason"},
536
+ }
537
+ # soft_block
538
+ decision = "deny_inject" if kind == "redundant" else f"deny_{kind}"
539
+ return {
540
+ "emit": {"permission": "deny", "user_message": message},
541
+ "observed": {**base, "decision": decision},
542
+ }
543
+
544
+
545
+ def _reason_message_from(message: str) -> str:
546
+ first = message.split("\n", 1)[0]
547
+ return first if first else "[Token Optimizer] redundant read blocked."
548
+
549
+
550
+ # ---------------------------------------------------------------------------
551
+ # Doctor channel evidence
552
+ # ---------------------------------------------------------------------------
553
+
554
+
555
+ def channel_state(ledger_events) -> dict:
556
+ """Compute the Read-channel state for cursor-doctor.
557
+
558
+ ``ledger_events`` is the observed-events ledger (list of dicts, oldest
559
+ first). State ladder: no config + no events -> ``unknown``; shadow mode
560
+ or no deny events -> ``shadow``; deny events -> ``armed-unverified``.
561
+
562
+ There is NO ledger path to ``armed-verified``: a denied file absent
563
+ from later postToolUse events is negative evidence, consistent with
564
+ cancels, failures, dropped hooks and tool routing - never proof of
565
+ delivery or adaptation. Verification requires positive controlled
566
+ native evidence (a real Cursor session demonstrably receiving the deny
567
+ + user_message and adapting), which no current source establishes.
568
+ """
569
+ mode = configured_mode()
570
+ owner_claude = False
571
+ try:
572
+ owner_claude = _claude_to_hooks_present([])
573
+ except Exception:
574
+ pass
575
+ events = [e for e in (ledger_events or []) if isinstance(e, dict)]
576
+ denies = any(
577
+ e.get("event") == "readCache"
578
+ and str(e.get("decision") or "").startswith("deny")
579
+ for e in events
580
+ )
581
+ if not events and mode == _DEFAULT_MODE:
582
+ state = "unknown"
583
+ elif mode == "shadow" or not denies:
584
+ state = "shadow"
585
+ else:
586
+ state = "armed-unverified"
587
+ return {
588
+ "channel": "read",
589
+ "state": state,
590
+ "mode": mode,
591
+ "claude_import_config_present": owner_claude,
592
+ "note": ("Cursor's Claude-hook import toggle has no verified file "
593
+ "surface, so KTD9 ownership from config presence is "
594
+ "inconclusive (record-only defer avoids damage, parity is "
595
+ "not closed by it). armed-verified needs positive "
596
+ "controlled native evidence; absence never verifies."),
597
+ }
@@ -95,8 +95,22 @@ def _parse_ts(value: Any) -> Optional[str]:
95
95
  return None
96
96
 
97
97
 
98
- def _quality(input_tokens, output_tokens, message_count, model, ctx_window):
99
- """Quality score from Cursor's session-level fields (mirrors copilot_session)."""
98
+ def _quality(input_tokens, output_tokens, message_count, model, ctx_window, raw=None):
99
+ """Quality score from Cursor's session-level fields (mirrors copilot_session).
100
+
101
+ Slice D: delegates to cursor_quality.quality_for_session (multi-signal,
102
+ per-signal provenance, historical-only preCompact fill) whenever the raw
103
+ tally is available; the Hermes 3-signal scorer remains the fallback.
104
+ """
105
+ if isinstance(raw, dict):
106
+ try:
107
+ import cursor_quality
108
+
109
+ q = cursor_quality.quality_for_session(raw)
110
+ if q is not None:
111
+ return q
112
+ except Exception as exc: # pragma: no cover - defensive fallback
113
+ logger.debug("[cursor_session] cursor_quality scorer unavailable: %s", exc)
100
114
  try:
101
115
  from hermes_session import compute_quality_score
102
116
 
@@ -173,12 +187,19 @@ def _base_canonical(slug: str, token_source: str) -> dict:
173
187
  }
174
188
 
175
189
 
176
- def resolve_token_source(bubble_tokens, transcript_tokens):
190
+ def resolve_token_source(bubble_tokens, transcript_tokens, hook_measured=None):
177
191
  """R16 ordered token resolution.
178
192
 
179
193
  Returns ``(input_tokens, output_tokens, token_source, estimated)``.
180
194
  Bubble tokens win only when at least one of input/output is non-zero;
181
- otherwise the transcript estimate; otherwise a zero-token tally-only row.
195
+ then the transcript estimate; otherwise a zero-token tally-only row.
196
+
197
+ ``hook_measured`` is accepted for signature stability but QUARANTINED:
198
+ afterAgentResponse usage numbers are stored in the tally's
199
+ ``hook_measured_tokens`` bucket for offline correlation only. Whether
200
+ they are per-response or cumulative is unproven, so they must never be
201
+ summed into resolved session tokens; claiming them as trusted fill
202
+ (``estimated = False``) would be a premature candidate claim.
182
203
  """
183
204
  if isinstance(bubble_tokens, dict) and (
184
205
  _safe_int(bubble_tokens.get("input_tokens")) > 0
@@ -268,7 +289,7 @@ def normalize_session(raw: dict) -> Optional[dict]:
268
289
  elif roots_list and isinstance(roots_list[0], str):
269
290
  root = roots_list[0]
270
291
 
271
- quality = _quality(total_input, total_output, message_count, model, ctx_window)
292
+ quality = _quality(total_input, total_output, message_count, model, ctx_window, raw=raw)
272
293
 
273
294
  session = _base_canonical(conversation_id, token_source)
274
295
  session.update(
@@ -199,6 +199,14 @@ def state_vscdb_path() -> Path:
199
199
  return base / "User" / "globalStorage" / "state.vscdb"
200
200
 
201
201
 
202
+ def state_vscdb_path_for_home(home: Path) -> Path:
203
+ """Use an explicitly selected Cursor home, otherwise the IDE default."""
204
+ home = Path(home).expanduser()
205
+ if not os.environ.get("TOKEN_OPTIMIZER_CURSOR_HOME") and home == _safe_home() / ".cursor":
206
+ return state_vscdb_path()
207
+ return home / "User" / "globalStorage" / "state.vscdb"
208
+
209
+
202
210
  def _ro_connect_vscdb(path: Path):
203
211
  """Open state.vscdb read-only. ``mode=ro`` only — not ``immutable=1``."""
204
212
  # Build the file: URI via Path.as_uri() rather than string interpolation