@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,723 @@
1
+ #!/usr/bin/env python3
2
+ """Cursor rules / memory audit (U9, Slice E) - standalone module.
3
+
4
+ History: these ten symbols first shipped inside the frozen _measure/audit.py
5
+ provider (81412770), the first post-freeze provider evolution, which broke
6
+ the lane5 frozen-provider proofs (the u5 tooling has no extension path).
7
+ Per independent review they now live here as a sibling module beside
8
+ cursor_coach.py; the frozen provider, the split manifest and the measure
9
+ facade are byte-restored to their historical state, and the frozen
10
+ attention-scoring machinery is REUSED by importing the provider read-only
11
+ (never duplicated, never modified).
12
+
13
+ Runtime dependency, stated plainly: the SUPPORTED usage is the measure CLI
14
+ (``measure.py cursor-audit``), where the measure facade is installed. The
15
+ frozen attention provider resolves that facade at call time, so rule-file
16
+ attention scoring requires it; direct module import without measure works
17
+ for everything else (hooks health, coexistence detection, file discovery)
18
+ and ``_claude_dir`` falls back to runtime_env there.
19
+
20
+ Scope honesty contract (same style as docs/cursor.md "Honest gaps"):
21
+ - Audits FILE surfaces only: .cursor/rules/**/*.mdc (native project rules),
22
+ stray .md files inside .cursor/rules (ignored by Cursor per the official
23
+ docs), legacy .cursorrules, AGENTS.md, and ~/.cursor/hooks.json health.
24
+ - Cursor's native IDE Memories, User Rules (Settings UI) and Team Rules
25
+ (dashboard) have no verified local file surface; they are reported as
26
+ not covered, never implied audited.
27
+ - Per-channel hook ownership (KTD9) is a demonstrated runtime function
28
+ decided by cursor-doctor; this audit reports config presence only and
29
+ never assigns ownership.
30
+ - Read-only: writes nothing anywhere, recurses into no directory symlinks,
31
+ caps the per-file read size, and never ships file content beyond a single
32
+ matched rule line (capped) into a finding. A rule file whose symlink
33
+ target escapes the project directory is flagged but NOT read. The Claude
34
+ settings files (user + project) are read, never written, solely to
35
+ detect hook-import coexistence (KTD9); no other ~/.claude state is read.
36
+ """
37
+ from __future__ import annotations
38
+
39
+ import json
40
+ import os
41
+ import re
42
+ import sys
43
+ from pathlib import Path
44
+
45
+ from _measure import audit as _frozen_audit # frozen attention machinery, read-only
46
+
47
+ CHARS_PER_TOKEN = 4.0 # mirrors the measure facade constant
48
+ _MR_RULE_RE = re.compile(r'\b(NEVER|ALWAYS|MUST|CRITICAL|NON-NEGOTIABLE)\b') # mirrors the measure facade regex
49
+
50
+
51
+ def _claude_dir():
52
+ """Claude home: the measure facade constant wins inside the measure
53
+ runtime (it is env-resolved once at import and test-monkeypatchable);
54
+ standalone falls back to runtime_env."""
55
+ facade = sys.modules.get("measure")
56
+ if facade is not None and hasattr(facade, "CLAUDE_DIR"):
57
+ return facade.CLAUDE_DIR
58
+ from runtime_env import claude_home # noqa: PLC0415
59
+ return claude_home()
60
+
61
+
62
+ def _cursor_rule_targets(project_dir):
63
+ """Discover Cursor rule/instruction files under a project directory.
64
+
65
+ Returns a list of {"path": Path, "kind": str} where kind is one of:
66
+ - "project_rule": .cursor/rules/**/*.mdc (the documented format)
67
+ - "ignored_md": .cursor/rules/**/*.md (Cursor ignores these --
68
+ no frontmatter surface; docs say use .mdc or
69
+ AGENTS.md instead)
70
+ - "legacy_cursorrules": <project>/.cursorrules (legacy single file)
71
+ - "agents_md": <project>/AGENTS.md (documented alternative)
72
+ Candidates reached through symlinks are checked against the resolved
73
+ project boundary before their contents are read.
74
+ """
75
+ root = Path(project_dir)
76
+ targets = []
77
+ rules_dir = root / ".cursor" / "rules"
78
+ try:
79
+ is_dir = rules_dir.is_dir()
80
+ except OSError:
81
+ is_dir = False
82
+ if is_dir:
83
+ try:
84
+ candidates = sorted(rules_dir.rglob("*"))
85
+ except OSError:
86
+ candidates = []
87
+ for f in candidates:
88
+ try:
89
+ if not f.is_file():
90
+ continue
91
+ except OSError:
92
+ continue
93
+ suffix = f.suffix.lower()
94
+ if suffix == ".mdc":
95
+ targets.append({"path": f, "kind": "project_rule"})
96
+ elif suffix == ".md":
97
+ targets.append({"path": f, "kind": "ignored_md"})
98
+ # other extensions: not rule files, skip silently
99
+ legacy = root / ".cursorrules"
100
+ try:
101
+ if legacy.is_file():
102
+ targets.append({"path": legacy, "kind": "legacy_cursorrules"})
103
+ except OSError:
104
+ pass
105
+ agents = root / "AGENTS.md"
106
+ try:
107
+ if agents.is_file():
108
+ targets.append({"path": agents, "kind": "agents_md"})
109
+ except OSError:
110
+ pass
111
+ return targets
112
+
113
+
114
+ def _cursor_parse_rule_frontmatter(text):
115
+ """Parse the leading ``---`` block of an .mdc rule file.
116
+
117
+ Returns (meta, body) where meta maps lowercased keys to raw string
118
+ values, or (None, text) when there is no complete frontmatter block.
119
+ Deliberately a line parser, not YAML: the documented rule frontmatter is
120
+ three scalar fields (description, globs, alwaysApply) and a YAML
121
+ dependency must never gate an audit. An unterminated block is treated as
122
+ no frontmatter (honest parse, no crash).
123
+ """
124
+ lines = text.splitlines()
125
+ if not lines or lines[0].strip() != "---":
126
+ return None, text
127
+ meta = {}
128
+ for i in range(1, len(lines)):
129
+ line = lines[i]
130
+ if line.strip() == "---":
131
+ return meta, "\n".join(lines[i + 1:])
132
+ if ":" in line:
133
+ key, _, value = line.partition(":")
134
+ meta[key.strip().lower()] = value.strip().strip('"').strip("'")
135
+ return None, text
136
+
137
+
138
+ def _cursor_rule_activation(meta):
139
+ """Classify how a rule activates from its frontmatter (docs table).
140
+
141
+ alwaysApply: true -> "always" (injected into every chat)
142
+ globs present -> "glob" (auto-attached on matching files)
143
+ description present -> "intelligent" (agent pulls it in)
144
+ nothing usable -> "manual" (@-mention only)
145
+ """
146
+ if not meta:
147
+ return "manual"
148
+ meta = {str(k).strip().lower(): v for k, v in meta.items()}
149
+ if str(meta.get("alwaysapply", "")).strip().lower() in ("true", "yes"):
150
+ return "always"
151
+ if str(meta.get("globs", "")).strip():
152
+ return "glob"
153
+ if str(meta.get("description", "")).strip():
154
+ return "intelligent"
155
+ return "manual"
156
+
157
+
158
+ def _cursor_rule_lines_findings(file_rules):
159
+ """Cross-file duplicate-rule check. file_rules: {path_str: [rule_line,...]}"""
160
+ rule_text_cap = 120
161
+ seen = {} # normalized rule -> list of (path, raw_line)
162
+ for path_str, lines in file_rules.items():
163
+ for raw in lines:
164
+ normalized = raw.strip().lower()
165
+ for prefix in ("- ", "* ", "> "):
166
+ if normalized.startswith(prefix):
167
+ normalized = normalized[len(prefix):]
168
+ break
169
+ seen.setdefault(normalized, []).append((path_str, raw.strip()))
170
+ findings = []
171
+ for normalized, locations in seen.items():
172
+ files = sorted({loc[0] for loc in locations})
173
+ if len(files) > 1:
174
+ sample = locations[0][1][:rule_text_cap]
175
+ findings.append({
176
+ "category": "duplicate_rule",
177
+ "severity": "low",
178
+ "detail": "Rule appears in {n} files: {files} -- \"{rule}\"".format(
179
+ n=len(files), files=", ".join(Path(f).name for f in files),
180
+ rule=sample),
181
+ "files": files,
182
+ "fix": "Keep the rule in one file; duplicated rules cost tokens in every chat that loads both.",
183
+ "savings": 0,
184
+ })
185
+ return findings
186
+
187
+
188
+ def _cursor_audit_rule_file(path, kind, project_root):
189
+ """Audit one rule file. Returns (record, findings); never raises.
190
+
191
+ record carries the per-file inventory the report renders; findings are
192
+ memory-review-shaped dicts (category/severity/detail/fix/savings).
193
+ """
194
+ rule_max_bytes = 1_000_000
195
+ # Advisory budget, not a host-documented limit: an alwaysApply rule is
196
+ # injected into every chat, so past this rough token estimate it deserves
197
+ # a trim or glob scoping. Same rough-estimate convention as the
198
+ # memory-review detectors (chars / CHARS_PER_TOKEN).
199
+ always_apply_token_budget = 1000
200
+ rule_text_cap = 120
201
+ # Below this many non-blank lines a file is short enough that nothing is
202
+ # really "buried in the middle"; the low-zone finding would be noise. The
203
+ # attention SCORE is still computed and reported for every file.
204
+ low_zone_min_nonblank_lines = 30
205
+ record = {
206
+ "path": str(path),
207
+ "name": path.name,
208
+ "kind": kind,
209
+ "symlink": False,
210
+ "bytes": None,
211
+ "lines": None,
212
+ "tokens": None,
213
+ "attention_score": None,
214
+ "low_zone_critical": [],
215
+ "activation": None,
216
+ }
217
+ findings = []
218
+
219
+ try:
220
+ record["symlink"] = path.is_symlink()
221
+ except OSError:
222
+ pass
223
+ try:
224
+ resolved = path.resolve()
225
+ root_resolved = Path(project_root).resolve()
226
+ if record["symlink"]:
227
+ record["resolved"] = str(resolved)
228
+ resolved.relative_to(root_resolved)
229
+ except (OSError, ValueError, RuntimeError):
230
+ findings.append({
231
+ "category": "symlink_escape",
232
+ "severity": "low",
233
+ "detail": f"'{path}' resolves outside the project directory or cannot be resolved; not audited (outside the project boundary)",
234
+ "fix": "Vendoring the rule into the project keeps it version-controlled with the repo and auditable.",
235
+ "savings": 0,
236
+ })
237
+ return record, findings
238
+
239
+ try:
240
+ size = path.stat().st_size
241
+ except OSError as exc:
242
+ findings.append({
243
+ "category": "unreadable",
244
+ "severity": "medium",
245
+ "detail": f"Could not stat '{path}' ({type(exc).__name__}); skipped",
246
+ "fix": "Check the file's permissions.",
247
+ "savings": 0,
248
+ })
249
+ return record, findings
250
+ record["bytes"] = size
251
+ if size > rule_max_bytes:
252
+ findings.append({
253
+ "category": "skipped_too_large",
254
+ "severity": "medium",
255
+ "detail": f"'{path.name}' is {size:,} bytes (over the {rule_max_bytes:,}-byte audit cap); skipped",
256
+ "fix": "A rule file this large is a context liability regardless of the audit; split it.",
257
+ "savings": 0,
258
+ })
259
+ return record, findings
260
+ try:
261
+ text = path.read_text(encoding="utf-8", errors="replace")
262
+ except OSError as exc:
263
+ findings.append({
264
+ "category": "unreadable",
265
+ "severity": "medium",
266
+ "detail": f"Could not read '{path}' ({type(exc).__name__}); skipped",
267
+ "fix": "Check the file's permissions.",
268
+ "savings": 0,
269
+ })
270
+ return record, findings
271
+
272
+ record["lines"] = len(text.splitlines())
273
+ record["tokens"] = int(len(text) / CHARS_PER_TOKEN)
274
+
275
+ meta, body = None, text
276
+ if kind == "project_rule":
277
+ meta, body = _cursor_parse_rule_frontmatter(text)
278
+ activation = _cursor_rule_activation(meta)
279
+ record["activation"] = activation
280
+ if meta is None:
281
+ findings.append({
282
+ "category": "mdc_missing_frontmatter",
283
+ "severity": "medium",
284
+ "detail": f"'{path.name}' has no frontmatter; Cursor can only apply it via manual @-mention",
285
+ "fix": "Add frontmatter with description, globs, or alwaysApply so the rule activates on its own.",
286
+ "savings": 0,
287
+ })
288
+ elif activation == "manual":
289
+ findings.append({
290
+ "category": "manual_only_rule",
291
+ "severity": "low",
292
+ "detail": f"'{path.name}' sets no description, globs, or alwaysApply; it only applies when @-mentioned",
293
+ "fix": "Add a description (agent picks it when relevant) or globs (auto-attached to matching files).",
294
+ "savings": 0,
295
+ })
296
+ if activation == "always" and record["tokens"] > always_apply_token_budget:
297
+ findings.append({
298
+ "category": "always_apply_oversized",
299
+ "severity": "medium",
300
+ "detail": f"'{path.name}' is alwaysApply and ~{record['tokens']:,} tokens; it is injected into every chat",
301
+ "fix": "Trim it, or scope it with globs so only matching work pays for it.",
302
+ "savings": record["tokens"] - always_apply_token_budget,
303
+ })
304
+
305
+ if kind == "ignored_md":
306
+ findings.append({
307
+ "category": "rules_md_ignored",
308
+ "severity": "medium",
309
+ "detail": f"'{path.name}' is a plain .md file inside .cursor/rules; Cursor's rules system ignores it (no frontmatter surface)",
310
+ "fix": "Rename to .mdc with frontmatter, or move the content to AGENTS.md.",
311
+ "savings": 0,
312
+ })
313
+ if kind == "legacy_cursorrules":
314
+ findings.append({
315
+ "category": "legacy_cursorrules",
316
+ "severity": "low",
317
+ "detail": "Legacy .cursorrules file; project rules now live in .cursor/rules/*.mdc (or AGENTS.md)",
318
+ "fix": "Migrate to .cursor/rules/*.mdc for scoped activation, or AGENTS.md for plain markdown.",
319
+ "savings": 0,
320
+ })
321
+
322
+ # Attention scoring: critical rules (NEVER/ALWAYS/MUST/...) that land in
323
+ # the low-attention middle of the file. Body only for .mdc (frontmatter is
324
+ # activation metadata, not model-attended content); whole file otherwise.
325
+ score_text = body if kind == "project_rule" else text
326
+ tmp_sections_source = score_text
327
+ # _parse_sections takes a path; reuse it on a synthetic section list when
328
+ # the body differs from the file. Simplest honest route: parse the body
329
+ # directly through the same section shape.
330
+ sections = []
331
+ if tmp_sections_source.strip():
332
+ header_re = re.compile(r'^(#{1,2})\s+(.+)', re.MULTILINE)
333
+ matches = list(header_re.finditer(tmp_sections_source))
334
+ if not matches:
335
+ lines = tmp_sections_source.splitlines()
336
+ sections = [{
337
+ "title": path.name, "level": 0, "content": tmp_sections_source,
338
+ "char_start": 0, "char_end": len(tmp_sections_source), "lines": lines,
339
+ }]
340
+ else:
341
+ if matches[0].start() > 0 and tmp_sections_source[:matches[0].start()].strip():
342
+ pre = tmp_sections_source[:matches[0].start()]
343
+ sections.append({"title": "(preamble)", "level": 0, "content": pre,
344
+ "char_start": 0, "char_end": matches[0].start(),
345
+ "lines": pre.splitlines()})
346
+ for i, m in enumerate(matches):
347
+ end = matches[i + 1].start() if i + 1 < len(matches) else len(tmp_sections_source)
348
+ content = tmp_sections_source[m.start():end]
349
+ sections.append({"title": m.group(2).strip(), "level": len(m.group(1)),
350
+ "content": content, "char_start": m.start(), "char_end": end,
351
+ "lines": content.splitlines()})
352
+ if sections:
353
+ analyzed, _total_chars, _total_tokens = _frozen_audit._analyze_attention_sections(sections)
354
+ record["attention_score"] = _frozen_audit._score_attention(analyzed)
355
+ low_rules = []
356
+ for a in analyzed:
357
+ if a["zone"] == "LOW":
358
+ for rule in a["critical_rules"]:
359
+ low_rules.append(rule[:rule_text_cap])
360
+ record["low_zone_critical"] = low_rules
361
+ nonblank = len([ln for ln in score_text.splitlines() if ln.strip()])
362
+ if low_rules and nonblank >= low_zone_min_nonblank_lines:
363
+ shown = "; ".join(f'"{r}"' for r in low_rules[:3])
364
+ more = f" (+{len(low_rules) - 3} more)" if len(low_rules) > 3 else ""
365
+ findings.append({
366
+ "category": "critical_rule_low_zone",
367
+ "severity": "low",
368
+ "detail": f"'{path.name}': {len(low_rules)} critical rule(s) sit in the low-attention middle: {shown}{more}",
369
+ "fix": "Move critical rules to the top or bottom of the file (attention-optimize FILE proposes the reorder).",
370
+ "savings": 0,
371
+ })
372
+
373
+ # Collect rule lines for the cross-file duplicate check (caller passes
374
+ # them to _cursor_rule_lines_findings).
375
+ record["_rule_lines"] = [
376
+ ln for ln in score_text.splitlines() if _MR_RULE_RE.search(ln)
377
+ ]
378
+ return record, findings
379
+
380
+
381
+ def _cursor_audit_rules(project_dir):
382
+ """Audit all discovered Cursor rule files under project_dir."""
383
+ targets = _cursor_rule_targets(project_dir)
384
+ records = []
385
+ findings = []
386
+ file_rules = {}
387
+ for t in targets:
388
+ record, file_findings = _cursor_audit_rule_file(t["path"], t["kind"], project_dir)
389
+ rule_lines = record.pop("_rule_lines", [])
390
+ if rule_lines:
391
+ file_rules[str(t["path"])] = rule_lines
392
+ records.append(record)
393
+ findings.extend(file_findings)
394
+ findings.extend(_cursor_rule_lines_findings(file_rules))
395
+ return records, findings
396
+
397
+
398
+ def _cursor_hook_commands_from_settings(settings):
399
+ """Extract hook command strings from a Claude Code settings blob."""
400
+ commands = []
401
+
402
+ def _walk(node):
403
+ if isinstance(node, dict):
404
+ cmd = node.get("command")
405
+ if isinstance(cmd, str):
406
+ commands.append(cmd)
407
+ for value in node.values():
408
+ _walk(value)
409
+ elif isinstance(node, list):
410
+ for item in node:
411
+ _walk(item)
412
+
413
+ hooks = settings.get("hooks") if isinstance(settings, dict) else None
414
+ if isinstance(hooks, (dict, list)):
415
+ _walk(hooks)
416
+ return commands
417
+
418
+
419
+ def _cursor_audit_hooks(cursor_home, project_dir=None):
420
+ from runtime_env import with_measure_cli as _hint # noqa: PLC0415
421
+ """Health-check ~/.cursor/hooks.json and note import coexistence.
422
+
423
+ Presence-level only: per-channel OWNERSHIP between imported Claude hooks
424
+ and the Cursor bridge is a demonstrated runtime function (KTD9) reported
425
+ by cursor-doctor; this audit never assigns it. Reads Claude settings
426
+ files (user and project) strictly read-only to detect import
427
+ coexistence; nothing else under ~/.claude is read.
428
+ """
429
+ # Events Token Optimizer's adapter knows about. Anything else in
430
+ # hooks.json is reported as unrecognized-by-this-version, never as
431
+ # invalid: Cursor ships new events faster than this set moves.
432
+ known_hook_events = frozenset({
433
+ "sessionStart", "sessionEnd", "stop",
434
+ "preToolUse", "postToolUse", "postToolUseFailure",
435
+ "preCompact", "beforeSubmitPrompt",
436
+ "afterAgentResponse", "afterShellExecution",
437
+ "subagentStart", "subagentStop",
438
+ })
439
+ hooks_path = Path(cursor_home) / "hooks.json"
440
+ result = {
441
+ "path": str(hooks_path),
442
+ "present": False,
443
+ "valid": None,
444
+ "events": [],
445
+ "to_bridge_events": [],
446
+ "third_party_entry_count": 0,
447
+ "claude_import_coexistence": None,
448
+ }
449
+ findings = []
450
+
451
+ try:
452
+ exists = hooks_path.is_file()
453
+ except OSError:
454
+ exists = False
455
+ if not exists:
456
+ result["present"] = False
457
+ findings.append({
458
+ "category": "hooks_json_missing",
459
+ "severity": "info",
460
+ "detail": f"No hooks.json at {hooks_path}; the Token Optimizer Cursor bridge is not wired here",
461
+ "fix": _hint("Run: python3 measure.py cursor-install (merged, never overwriting other entries)."),
462
+ "savings": 0,
463
+ })
464
+ # Coexistence is still worth reporting below.
465
+ else:
466
+ result["present"] = True
467
+ try:
468
+ raw = hooks_path.read_text(encoding="utf-8", errors="replace")
469
+ data = json.loads(raw)
470
+ result["valid"] = True
471
+ except (OSError, json.JSONDecodeError, ValueError) as exc:
472
+ result["valid"] = False
473
+ findings.append({
474
+ "category": "hooks_json_invalid",
475
+ "severity": "high",
476
+ "detail": f"hooks.json at {hooks_path} is unreadable or invalid JSON ({type(exc).__name__}); Cursor silently runs no hooks from it",
477
+ "fix": "Fix or regenerate the file; cursor-install merges into valid JSON without touching other entries.",
478
+ "savings": 0,
479
+ })
480
+ data = None
481
+
482
+ if result["valid"]:
483
+ if not isinstance(data, dict) or not isinstance(data.get("hooks"), dict):
484
+ findings.append({
485
+ "category": "hooks_json_shape",
486
+ "severity": "medium",
487
+ "detail": "hooks.json has no top-level \"hooks\" object; no hook events are wired",
488
+ "fix": "Expected shape: {\"hooks\": {\"<event>\": [{\"command\": ...}]}}.",
489
+ "savings": 0,
490
+ })
491
+ else:
492
+ hooks = data["hooks"]
493
+ for event in sorted(hooks):
494
+ entries = hooks[event]
495
+ result["events"].append(event)
496
+ if event not in known_hook_events:
497
+ findings.append({
498
+ "category": "hooks_unknown_event",
499
+ "severity": "low",
500
+ "detail": f"hooks.json wires '{event}', which this Token Optimizer version does not recognize (may be valid in newer Cursor releases)",
501
+ "fix": "No action needed if Cursor documents the event; otherwise remove the entry.",
502
+ "savings": 0,
503
+ })
504
+ if not isinstance(entries, list):
505
+ findings.append({
506
+ "category": "hooks_json_shape",
507
+ "severity": "medium",
508
+ "detail": f"hooks.json entry for '{event}' is not a list; Cursor will not run it",
509
+ "fix": "Each event maps to a list of {command, type, ...} objects.",
510
+ "savings": 0,
511
+ })
512
+ continue
513
+ for entry in entries:
514
+ if not isinstance(entry, dict) or not isinstance(entry.get("command"), str):
515
+ findings.append({
516
+ "category": "hooks_json_shape",
517
+ "severity": "medium",
518
+ "detail": f"hooks.json entry under '{event}' lacks a string 'command'; Cursor will not run it",
519
+ "fix": "Each entry needs a 'command' string.",
520
+ "savings": 0,
521
+ })
522
+ continue
523
+ if "cursor_hook_bridge" in entry["command"]:
524
+ result["to_bridge_events"].append(event)
525
+ else:
526
+ result["third_party_entry_count"] += 1
527
+ if not result["to_bridge_events"]:
528
+ findings.append({
529
+ "category": "bridge_not_wired",
530
+ "severity": "info",
531
+ "detail": "hooks.json exists but wires no Token Optimizer cursor_hook_bridge entries",
532
+ "fix": _hint("Run: python3 measure.py cursor-install (merged, never overwriting other entries)."),
533
+ "savings": 0,
534
+ })
535
+ if result["third_party_entry_count"]:
536
+ findings.append({
537
+ "category": "third_party_hooks",
538
+ "severity": "info",
539
+ "detail": (f"hooks.json also wires {result['third_party_entry_count']} non-Token-Optimizer "
540
+ "hook entr" + ("y" if result["third_party_entry_count"] == 1 else "ies") +
541
+ "; Cursor merges all hook sources (deny > ask > allow, messages concatenate)"),
542
+ "fix": "No action required. Per-channel ownership is demonstrated at runtime and reported by cursor-doctor; this audit does not assign it.",
543
+ "savings": 0,
544
+ })
545
+
546
+ # Claude-side TO hook presence: Cursor imports Claude Code hooks by
547
+ # default (KTD9), from BOTH the user settings (~/.claude/settings.json,
548
+ # settings.local.json) and the project settings (.claude/settings.json,
549
+ # .claude/settings.local.json). Detection is config presence only;
550
+ # ownership is never assigned here. Reads are read-only and
551
+ # failure-tolerant.
552
+ claude_settings_paths = [
553
+ Path(_claude_dir()) / "settings.json",
554
+ Path(_claude_dir()) / "settings.local.json",
555
+ ]
556
+ if project_dir is not None:
557
+ project_claude = Path(project_dir) / ".claude"
558
+ claude_settings_paths.append(project_claude / "settings.json")
559
+ claude_settings_paths.append(project_claude / "settings.local.json")
560
+ claude_hits = []
561
+ for settings_path in claude_settings_paths:
562
+ try:
563
+ if not settings_path.is_file():
564
+ continue
565
+ blob = json.loads(settings_path.read_text(encoding="utf-8", errors="replace"))
566
+ except (OSError, ValueError):
567
+ continue
568
+ for cmd in _cursor_hook_commands_from_settings(blob):
569
+ if "token-optimizer" in cmd or "measure.py" in cmd:
570
+ claude_hits.append(str(settings_path))
571
+ break
572
+ if claude_hits:
573
+ result["claude_import_coexistence"] = True
574
+ findings.append({
575
+ "category": "claude_import_coexistence",
576
+ "severity": "info",
577
+ "detail": ("Claude Code Token Optimizer hooks found in " + ", ".join(sorted(set(claude_hits))) +
578
+ "; Cursor imports Claude hooks by default"),
579
+ "fix": ("No action required. The bridge and the Claude side defer to each other per channel based on "
580
+ "demonstrated ownership; cursor-doctor reports the owner with evidence."),
581
+ "savings": 0,
582
+ })
583
+ else:
584
+ result["claude_import_coexistence"] = False
585
+
586
+ return result, findings
587
+
588
+
589
+ def _cursor_not_covered():
590
+ """What this audit deliberately does NOT claim to cover (honest gaps)."""
591
+ return [
592
+ "Cursor native IDE Memories (Settings > Memories, beta): managed by the IDE with no verified local file surface; "
593
+ "the IDE state DB schema for memories is unverified, so this audit performs no IDE DB reads and does not score them",
594
+ "User Rules (Cursor Settings UI): global, not file-backed; not audited",
595
+ "Team Rules (Cursor dashboard, Team/Enterprise plans): not file-backed; not audited",
596
+ "Cursor's third-party Claude-hook import toggle: an IDE setting with no verified file surface; not audited",
597
+ "Per-channel hook ownership between imported Claude hooks and the Cursor bridge: a demonstrated runtime function "
598
+ "(KTD9) reported by cursor-doctor; this audit reports config presence only",
599
+ ]
600
+
601
+
602
+ def cursor_audit(project_dir=None, cursor_home=None, as_json=None):
603
+ """Cursor rules + memory/setup audit. Read-only, never fatal.
604
+
605
+ Scores .cursor/rules/*.mdc, stray .md, legacy .cursorrules and AGENTS.md
606
+ against the same attention curve CLAUDE.md gets, health-checks
607
+ ~/.cursor/hooks.json, and lists what is honestly not covered.
608
+ """
609
+
610
+ if cursor_home is None:
611
+ try:
612
+ from runtime_env import cursor_home as _resolve_cursor_home # noqa: PLC0415
613
+ cursor_home = _resolve_cursor_home()
614
+ except Exception:
615
+ cursor_home = Path.home() / ".cursor"
616
+ cursor_home = Path(cursor_home)
617
+
618
+ if project_dir is None:
619
+ project_dir = Path.cwd()
620
+ else:
621
+ project_dir = Path(project_dir).expanduser()
622
+ try:
623
+ project_dir = project_dir.resolve()
624
+ except OSError:
625
+ pass
626
+
627
+ project_exists = False
628
+ try:
629
+ project_exists = project_dir.is_dir()
630
+ except OSError:
631
+ project_exists = False
632
+
633
+ rule_records = []
634
+ rule_findings = []
635
+ if project_exists:
636
+ rule_records, rule_findings = _cursor_audit_rules(project_dir)
637
+ else:
638
+ rule_findings.append({
639
+ "category": "project_dir_missing",
640
+ "severity": "medium",
641
+ "detail": f"Project directory not found: {project_dir}",
642
+ "fix": "Pass --project-dir PATH for the repository whose Cursor rules should be audited.",
643
+ "savings": 0,
644
+ })
645
+
646
+ hooks_result, hooks_findings = _cursor_audit_hooks(cursor_home, project_dir=project_dir if project_exists else None)
647
+
648
+ all_findings = rule_findings + hooks_findings
649
+ severity_counts = {"high": 0, "medium": 0, "low": 0, "info": 0}
650
+ for f in all_findings:
651
+ sev = f.get("severity", "info")
652
+ severity_counts[sev] = severity_counts.get(sev, 0) + 1
653
+
654
+ result = {
655
+ "schema_version": 1,
656
+ "runtime": "cursor",
657
+ "project_dir": str(project_dir),
658
+ "cursor_home": str(cursor_home),
659
+ "rule_files": rule_records,
660
+ "hooks": hooks_result,
661
+ "findings": all_findings,
662
+ "severity_counts": severity_counts,
663
+ "not_covered": _cursor_not_covered(),
664
+ "summary": {
665
+ "rule_files": len(rule_records),
666
+ "findings": len(all_findings),
667
+ "high": severity_counts.get("high", 0),
668
+ "medium": severity_counts.get("medium", 0),
669
+ "low": severity_counts.get("low", 0),
670
+ "info": severity_counts.get("info", 0),
671
+ },
672
+ }
673
+
674
+ if as_json:
675
+ return result
676
+
677
+ # CLI output (memory-review style)
678
+ print(f"\n{'=' * 55}")
679
+ print(" CURSOR RULES + MEMORY AUDIT")
680
+ print(f"{'=' * 55}")
681
+ print(f"\n Project: {project_dir}")
682
+ print(f" Cursor home: {cursor_home}")
683
+
684
+ print(f"\n Rule files found: {len(rule_records)}")
685
+ if rule_records:
686
+ for rec in rule_records:
687
+ score = f"{rec['attention_score']}/100" if rec["attention_score"] is not None else "n/a"
688
+ tokens = f"~{rec['tokens']:,} tok" if rec["tokens"] is not None else "?"
689
+ activation = f", {rec['activation']}" if rec.get("activation") else ""
690
+ print(f" [{rec['kind']}] {rec['name']} ({tokens}, attention {score}{activation})")
691
+ else:
692
+ print(" No Cursor rules configured for this project (.cursor/rules/*.mdc, AGENTS.md, .cursorrules).")
693
+
694
+ hooks_line = "absent"
695
+ if hooks_result["present"]:
696
+ if hooks_result["valid"]:
697
+ wired = ", ".join(sorted(set(hooks_result["to_bridge_events"]))) or "none"
698
+ hooks_line = f"valid; TO bridge events: {wired}"
699
+ else:
700
+ hooks_line = "INVALID"
701
+ print(f"\n hooks.json: {hooks_line}")
702
+
703
+ if all_findings:
704
+ sev_order = ["high", "medium", "low", "info"]
705
+ sev_labels = {"high": "CRITICAL", "medium": "WARNING", "low": "NOTICE", "info": "INFO"}
706
+ print(f"\n Found {len(all_findings)} issue(s):")
707
+ for sev in sev_order:
708
+ sev_findings = [f for f in all_findings if f.get("severity") == sev]
709
+ if not sev_findings:
710
+ continue
711
+ print(f"\n [{sev_labels[sev]}]")
712
+ for f in sev_findings:
713
+ print(f" {f['detail']}")
714
+ if f.get("fix"):
715
+ print(f" Fix: {f['fix']}")
716
+ else:
717
+ print("\n No issues found.")
718
+
719
+ print("\n Not covered by this audit:")
720
+ for line in result["not_covered"]:
721
+ print(f" - {line}")
722
+ print()
723
+ return result