@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
@@ -262,6 +262,17 @@ def main():
262
262
  elif _measure_facade.args[0] == "cursor-uninstall":
263
263
  import cursor_install as _measure_import_24; _measure_facade.cursor_install = _measure_import_24; del _measure_import_24
264
264
  _measure_facade.sys.exit(_measure_facade.cursor_install.main(["uninstall"] + _measure_facade.args[1:]))
265
+ elif _measure_facade.args[0] == "cursor-home":
266
+ # Print the resolved Cursor home directory (honors
267
+ # TOKEN_OPTIMIZER_CURSOR_HOME via runtime_env.cursor_home() → the
268
+ # safe-home guard plus the WSL-root /mnt opt-in). Used by install.sh
269
+ # to show the TRUE hook destination in its banner instead of a
270
+ # hardcoded ~/.cursor path (WSL-root installs wrote to /root/.cursor
271
+ # which the Windows Cursor never reads).
272
+ from runtime_env import cursor_home as _measure_import_ch; _measure_facade._clh = _measure_import_ch; del _measure_import_ch # noqa: PLC0415
273
+
274
+ print(str(_measure_facade._clh()))
275
+ _measure_facade.sys.exit(0)
265
276
  elif _measure_facade.args[0] == "cursor-rollup":
266
277
  # The bridge always pins TOKEN_OPTIMIZER_RUNTIME=cursor. A bare manual
267
278
  # run must refuse (not silently collect under the default runtime).
@@ -325,6 +336,62 @@ def main():
325
336
  _measure_facade.sys.exit(0)
326
337
  _measure_facade._cursor_summary()
327
338
  _measure_facade.sys.exit(0)
339
+ elif _measure_facade.args[0] == "cursor-coach":
340
+ # Native coach data for the Cursor runtime (Slice D): tallies,
341
+ # per-signal quality, and rollup trends - never a ~/.claude scan.
342
+ if _measure_facade.detect_runtime() != "cursor":
343
+ print(
344
+ "[Token Optimizer] cursor-coach reads only the Cursor runtime; "
345
+ "set TOKEN_OPTIMIZER_RUNTIME=cursor.",
346
+ file=_measure_facade.sys.stderr,
347
+ )
348
+ _measure_facade.sys.exit(0)
349
+ import cursor_coach as _measure_import_cc
350
+ _measure_facade.cursor_coach = _measure_import_cc
351
+ del _measure_import_cc
352
+ # Forward --days/--focus like `coach` does; the generator accepts both
353
+ # (window_days / focus_area in the snapshot).
354
+ _measure_facade._cc_days = 30
355
+ _measure_facade._cc_focus = None
356
+ _measure_facade._i = 1
357
+ while _measure_facade._i < len(_measure_facade.args):
358
+ _measure_facade._a = _measure_facade.args[_measure_facade._i]
359
+ if _measure_facade._a == "--days" and _measure_facade._i + 1 < len(_measure_facade.args):
360
+ try:
361
+ _measure_facade._cc_days = int(_measure_facade.args[_measure_facade._i + 1])
362
+ except ValueError:
363
+ pass
364
+ _measure_facade._i += 2
365
+ elif _measure_facade._a == "--focus" and _measure_facade._i + 1 < len(_measure_facade.args):
366
+ _measure_facade._cc_focus = _measure_facade.args[_measure_facade._i + 1]
367
+ _measure_facade._i += 2
368
+ else:
369
+ _measure_facade._i += 1
370
+ _measure_facade._cc_data = _measure_facade.cursor_coach.generate_cursor_coach_data(
371
+ days=_measure_facade._cc_days, focus=_measure_facade._cc_focus
372
+ )
373
+ if "--json" in _measure_facade.args:
374
+ print(_measure_facade.json.dumps(_measure_facade._cc_data, indent=2))
375
+ else:
376
+ _measure_facade._csnap = _measure_facade._cc_data["snapshot"]
377
+ print("Token Optimizer - Cursor coach data")
378
+ _measure_facade._chs = _measure_facade._cc_data["health_score"]
379
+ print(f" Health score: {_measure_facade._chs if _measure_facade._chs is not None else 'no scored sessions'}")
380
+ print(f" Sessions analyzed: {_measure_facade._csnap['sessions_analyzed']} "
381
+ f"({_measure_facade._csnap['total_turns']} turns, "
382
+ f"{_measure_facade._csnap['total_tool_calls']} tool calls, "
383
+ f"{_measure_facade._csnap['total_compactions']} compactions)")
384
+ print(f" Cost: {_measure_facade._csnap['cost']['detail']}")
385
+ if _measure_facade._cc_data["patterns_bad"]:
386
+ print(" Issues detected:")
387
+ for _measure_facade._p in _measure_facade._cc_data["patterns_bad"]:
388
+ _measure_facade._sev = {"high": "!!!", "medium": "!!", "low": "!"}.get(_measure_facade._p["severity"], "!")
389
+ print(f" [{_measure_facade._sev}] {_measure_facade._p['name']}: {_measure_facade._p['detail']}")
390
+ if _measure_facade._cc_data["patterns_good"]:
391
+ print(" Good practices:")
392
+ for _measure_facade._p in _measure_facade._cc_data["patterns_good"]:
393
+ print(f" [OK] {_measure_facade._p['name']}: {_measure_facade._p['detail']}")
394
+ _measure_facade.sys.exit(0)
328
395
  elif _measure_facade.args[0] == "grok-summary":
329
396
  _measure_facade._grok_summary()
330
397
  _measure_facade.sys.exit(0)
@@ -2483,6 +2550,23 @@ def main():
2483
2550
  stale_days=_measure_facade.stale_d, project_dir=_measure_facade.proj_dir)
2484
2551
  if _measure_facade.output_json and _measure_facade.result:
2485
2552
  print(_measure_facade.json.dumps(_measure_facade.result, indent=2, default=str))
2553
+ elif _measure_facade.args[0] == "cursor-audit":
2554
+ # Read-only audit of Cursor rules + hooks; deliberately NOT gated on
2555
+ # detect_runtime() == "cursor": beyond the Cursor runtime itself it
2556
+ # reads only 4 Claude settings files for hook-import coexistence
2557
+ # detection (never other ~/.claude state), so a Claude-runtime user
2558
+ # auditing their Cursor setup is legitimate.
2559
+ _measure_facade.output_json = "--json" in _measure_facade.args
2560
+ _measure_facade.proj_dir = None
2561
+ for _measure_facade.i, _measure_facade.a in enumerate(_measure_facade.args):
2562
+ if _measure_facade.a == "--project-dir" and _measure_facade.i + 1 < len(_measure_facade.args):
2563
+ _measure_facade.proj_dir = _measure_facade.args[_measure_facade.i + 1]
2564
+ import cursor_audit as _measure_import_ca
2565
+ _measure_facade.cursor_audit_mod = _measure_import_ca
2566
+ del _measure_import_ca
2567
+ _measure_facade.result = _measure_facade.cursor_audit_mod.cursor_audit(project_dir=_measure_facade.proj_dir, as_json=_measure_facade.output_json)
2568
+ if _measure_facade.output_json and _measure_facade.result:
2569
+ print(_measure_facade.json.dumps(_measure_facade.result, indent=2, default=str))
2486
2570
  elif _measure_facade.args[0] == "archive-result":
2487
2571
  # PostToolUse hook handler: archive large tool results
2488
2572
  _measure_facade.quiet = "--quiet" in _measure_facade.args or "-q" in _measure_facade.args
@@ -2600,7 +2684,9 @@ def main():
2600
2684
  print(" python3 measure.py cursor-doctor # Cursor adapter readiness check")
2601
2685
  print(" python3 measure.py cursor-install # Install Cursor hooks (merged into ~/.cursor/hooks.json)")
2602
2686
  print(" python3 measure.py cursor-summary # Token/quality Cursor session summary")
2687
+ print(" python3 measure.py cursor-coach # Cursor coach data (sessions, quality, patterns; --json --days N --focus X)")
2603
2688
  print(" python3 measure.py cursor-rollup # Ingest Cursor sessions into trends DB")
2689
+ print(" python3 measure.py cursor-audit # Audit Cursor rules (.cursor/rules, AGENTS.md) + hooks.json health")
2604
2690
  print(" python3 measure.py antigravity-doctor # Google Antigravity adapter readiness check")
2605
2691
  print(" python3 measure.py antigravity-install # Install Antigravity hooks (consent-gated)")
2606
2692
  print(" python3 measure.py antigravity-uninstall # Remove Antigravity hooks + trend rows")
@@ -2,7 +2,6 @@
2
2
  from __future__ import annotations
3
3
  from . import _compat
4
4
 
5
-
6
5
  def _parse_elapsed_time(elapsed_str):
7
6
  """Parse ps elapsed time format (dd-HH:MM:SS or HH:MM:SS or MM:SS) to seconds."""
8
7
  _measure_facade = _compat.facade()
@@ -24,7 +23,6 @@ def _parse_elapsed_time(elapsed_str):
24
23
 
25
24
  return days * 86400 + hours * 3600 + minutes * 60 + seconds
26
25
 
27
-
28
26
  def _format_elapsed(seconds):
29
27
  """Format seconds into a human-readable elapsed string."""
30
28
  _measure_facade = _compat.facade()
@@ -38,7 +36,6 @@ def _format_elapsed(seconds):
38
36
  h = hours % 24
39
37
  return f"{d}d {h}h"
40
38
 
41
-
42
39
  def _scan_project_jsonl_stats():
43
40
  """Return [(path, birth_time, mtime), ...] for every project JSONL, cached.
44
41
 
@@ -77,7 +74,6 @@ def _scan_project_jsonl_stats():
77
74
  _measure_facade._PROJECT_JSONL_STAT_CACHE_TS = _measure_facade.time.monotonic()
78
75
  return out
79
76
 
80
-
81
77
  def _find_session_version_for_pid(pid):
82
78
  """Try to find the Claude Code version for a running process by matching its session JSONL.
83
79
 
@@ -154,7 +150,6 @@ def _find_session_version_for_pid(pid):
154
150
  return best_match
155
151
  return None # No confident match; don't guess (causes false OUTDATED flags)
156
152
 
157
-
158
153
  def _command_matches_process(command, process_name):
159
154
  """True if a `ps` COMMAND field denotes a `process_name` CLI session.
160
155
 
@@ -198,7 +193,6 @@ def _command_matches_process(command, process_name):
198
193
  exe_base = exe_base[:-4]
199
194
  return exe_base == process_name
200
195
 
201
-
202
196
  def _posix_comm_name(comm):
203
197
  """Lower-case executable name from a ps COMM field ("-zsh" -> "zsh",
204
198
  "tmux: server" -> "tmux", "/bin/bash" -> "bash"). Never raises."""
@@ -209,7 +203,6 @@ def _posix_comm_name(comm):
209
203
  text = text.split(": ", 1)[0].rsplit("/", 1)[-1]
210
204
  return text.lstrip("-").strip().lower()
211
205
 
212
-
213
206
  def _posix_comm_is_claude(comm):
214
207
  """True when a COMM field names a claude CLI executable (basename `claude`,
215
208
  `.exe` stripped, or the versioned ccd-cli launcher). Matches desktop-hosted
@@ -224,7 +217,6 @@ def _posix_comm_is_claude(comm):
224
217
  base = base[:-4]
225
218
  return base == "claude" or bool(_measure_facade._CCD_CLI_LAUNCHER_RE.search(text))
226
219
 
227
-
228
220
  def _posix_is_claude_host(comm, args):
229
221
  """True when a process is the Claude desktop app (main, helper, disclaimer
230
222
  wrapper, Electron build) or another claude process: a claude below it is hosted."""
@@ -238,14 +230,12 @@ def _posix_is_claude_host(comm, args):
238
230
  return True
239
231
  return _measure_facade._command_matches_process(args or "", "claude")
240
232
 
241
-
242
233
  def _posix_option_args(argv):
243
234
  """Arguments that can be options: everything after argv[0] up to a bare --."""
244
235
  _measure_facade = _compat.facade()
245
236
  args = list(argv[1:])
246
237
  return args[:args.index("--")] if "--" in args else args
247
238
 
248
-
249
239
  def _posix_is_headless(options):
250
240
  """True for SDK/headless/IDE switches and for subcommand processes."""
251
241
  _measure_facade = _compat.facade()
@@ -259,7 +249,6 @@ def _posix_is_headless(options):
259
249
  return True
260
250
  return False
261
251
 
262
-
263
252
  def _posix_read_argv(pid):
264
253
  """Exact argv of a process, or None when the OS will not say.
265
254
 
@@ -1734,18 +1723,13 @@ def session_health():
1734
1723
  print("\nSession health check is not supported on this platform.")
1735
1724
  return
1736
1725
 
1737
- installed_version = health["installed_version"]
1738
- running_sessions = health["running_sessions"]
1739
- automated = health["automated"]
1740
- recommendations = health["recommendations"]
1726
+ installed_version, running_sessions, automated, recommendations = (
1727
+ health[k] for k in ("installed_version", "running_sessions", "automated", "recommendations"))
1741
1728
 
1742
1729
  print("\nSESSION HEALTH CHECK")
1743
1730
  print("=" * 55)
1744
1731
 
1745
- if installed_version:
1746
- print(f"\n Installed version: {installed_version}")
1747
- else:
1748
- print("\n Installed version: unknown (could not run 'claude --version')")
1732
+ print(f"\n Installed version: {installed_version or 'unknown (could not run ' + repr('claude --version') + ')'}")
1749
1733
 
1750
1734
  if not running_sessions:
1751
1735
  print("\n No running Claude Code CLI sessions found.")
@@ -1770,6 +1754,11 @@ def session_health():
1770
1754
  print("\nAUTOMATED PROCESSES")
1771
1755
  for proc in automated:
1772
1756
  print(f" {proc}")
1757
+ try: # hooks the malformed-hook healer left alone (heal_report.py)
1758
+ for _line in __import__("heal_report").health_lines(_measure_facade):
1759
+ print(_line)
1760
+ except Exception:
1761
+ pass # health must never fail on this optional section
1773
1762
 
1774
1763
  print()
1775
1764
 
@@ -2569,7 +2558,7 @@ REGEN_STEP_TIMEOUT = 45
2569
2558
  # thread waits for the child and clears _regen_inflight when it exits, bounded by
2570
2559
  # this timeout so a hung child can never wedge the guard True forever (the manual
2571
2560
  # regen path already caps each step at REGEN_STEP_TIMEOUT; this is one step + headroom).
2572
- REGEN_BG_TIMEOUT = REGEN_STEP_TIMEOUT + 45
2561
+ REGEN_BG_TIMEOUT = 300
2573
2562
  MEASURE_PY_RESOLVE_TTL = 300
2574
2563
  REGEN_LOG = os.path.join(os.path.dirname(DASHBOARD), "daemon-regen.log")
2575
2564
 
@@ -3134,6 +3123,15 @@ class Handler(http.server.SimpleHTTPRequestHandler):
3134
3123
  self._json_response(200 if payload.get("ok") else 500, payload)
3135
3124
  return
3136
3125
  if clean == "api/regenerate":
3126
+ try:
3127
+ length = int(self.headers.get("Content-Length", 0))
3128
+ if length < 0 or length > 4096: raise ValueError()
3129
+ body = json.loads(self.rfile.read(length).decode("utf-8")) if length else {{}}
3130
+ days = body.get("days")
3131
+ if days is not None and not (days == "all" or type(days) is int and 1 <= days <= 365000): raise ValueError()
3132
+ except (ValueError, TypeError, AttributeError, UnicodeDecodeError):
3133
+ self._json_response(400, {{"ok": False, "msg": "invalid history window"}})
3134
+ return
3137
3135
  # Synchronous, unlike the background freshness regen: the caller is a
3138
3136
  # human who pressed a button and needs a real success/failure answer,
3139
3137
  # not a fire-and-forget that looks identical whether it worked or not.
@@ -3167,23 +3165,13 @@ class Handler(http.server.SimpleHTTPRequestHandler):
3167
3165
  argv = [sys.executable, target, step, "--quiet"]
3168
3166
  if step == "dashboard":
3169
3167
  argv.append("--force")
3170
- # retry cap: retry ONLY the "dashboard" step -- the
3171
- # one with the observed intermittent hang (lock contention
3172
- # makes the normally-~9s build blow past a single
3173
- # REGEN_STEP_TIMEOUT shot) -- and do NOT double the cap on the
3174
- # retry. The earlier "2 attempts per step, doubled cap" put the
3175
- # worst case at REGEN_STEP_TIMEOUT*(1+2)*2 = 6x = 270s, WORSE
3176
- # than the ~240s wedge the original per-step cap fixed. Capping
3177
- # every attempt at a flat REGEN_STEP_TIMEOUT and retrying only
3178
- # the flaky step bounds the worst case at
3179
- # REGEN_STEP_TIMEOUT*(1 + 2) = 3x = 135s, well under 240s, while
3180
- # still surviving one transient dashboard hang. `collect` has no
3181
- # observed hang, so it stays single-shot.
3168
+ if days is not None: argv.extend(["--days", str(days)])
3169
+ # Full-history dashboards can exceed the normal collect timeout.
3182
3170
  _max_attempts = 2 if step == "dashboard" else 1
3183
3171
  r = None
3184
3172
  _timeout_exc = None
3185
3173
  for _attempt in range(_max_attempts):
3186
- _to = REGEN_STEP_TIMEOUT
3174
+ _to = 180 if step == "dashboard" else REGEN_STEP_TIMEOUT
3187
3175
  try:
3188
3176
  r = subprocess.run(
3189
3177
  argv,
@@ -5430,51 +5418,19 @@ def _backup_settings_file(dest_dir: Path) -> Path | None:
5430
5418
  return None
5431
5419
 
5432
5420
 
5433
- def _is_our_hook_entry(entry) -> bool:
5434
- """True when a settings.json hook entry is one WE installed.
5435
-
5436
- Ownership markers, all anchored on our own script names rather than a bare
5437
- "token-optimizer" substring (a user hook may legitimately mention us in a
5438
- path or a comment without being ours to delete):
5439
- * the command invokes one of our scripts (measure.py / read_cache.py /
5440
- statusline.js / archive_result.py / context_intel.py) AND references
5441
- token-optimizer, or
5442
- * it carries one of our distinctive subcommands (quality-cache,
5443
- compact-capture, compact-restore, ensure-health, clear-compacted,
5444
- session-end-flush, dynamic-compact-instructions).
5421
+ def _is_our_hook_entry(entry, event="", group=None) -> bool:
5422
+ """True when a settings.json hook entry is one Token Optimizer wrote (cleanup).
5445
5423
 
5446
- Conservative by construction: unrecognized shapes are NOT ours, so a hook
5447
- we cannot positively identify is left in place. The cost of a false
5448
- negative is a dangling entry the user can delete; the cost of a false
5449
- positive is silently deleting their automation.
5424
+ Proof only (owned_hooks.cleanup_owner): recorded in the provenance ledger,
5425
+ a shipped hooks.json entry for an install root, or byte-identical to a
5426
+ command setup_hook / setup_smart_compact / setup_quality_bar generated for
5427
+ an install's measure.py. A command that merely names our subcommands or
5428
+ scripts proves nothing and stays: a dangling entry the user can delete
5429
+ beats silently deleting their automation.
5450
5430
  """
5451
5431
  _measure_facade = _compat.facade()
5452
- if not isinstance(entry, dict):
5453
- return False
5454
- cmd = entry.get("command")
5455
- if not isinstance(cmd, str) or not cmd:
5456
- return False
5457
- low = cmd.lower()
5458
- our_subcommands = (
5459
- "quality-cache", "compact-capture", "compact-restore", "ensure-health",
5460
- "clear-compacted", "session-end-flush", "dynamic-compact-instructions",
5461
- )
5462
- if any(sub in low for sub in our_subcommands):
5463
- return True
5464
- our_scripts = (
5465
- "measure.py", "read_cache.py", "statusline.js", "archive_result.py",
5466
- "context_intel.py", "activity_tracker.py",
5467
- # the UserPromptSubmit dispatcher. Without it a hook that
5468
- # runs userpromptsubmit_runner.py (+ token-optimizer) is not recognised
5469
- # as ours, so ownership-gated repair/reconciliation skips it. Whitelisting
5470
- # the script name here is inert until the dispatcher ships (it is not yet
5471
- # in this branch) and never matches a foreign hook (the token-optimizer
5472
- # substring is still required alongside it).
5473
- "userpromptsubmit_runner.py",
5474
- )
5475
- if "token-optimizer" in low and any(s in low for s in our_scripts):
5476
- return True
5477
- return False
5432
+ import owned_hooks
5433
+ return owned_hooks.cleanup_owner(_measure_facade)(event, {"hooks": [entry]} if group is None else group, entry)
5478
5434
 
5479
5435
 
5480
5436
  def _remove_our_settings_entries(settings: dict) -> list[str]:
@@ -5522,6 +5478,8 @@ def _remove_our_settings_entries(settings: dict) -> list[str]:
5522
5478
  # filtered with the same ownership predicate.
5523
5479
  hooks = settings.get("hooks")
5524
5480
  if isinstance(hooks, dict):
5481
+ import owned_hooks
5482
+ owns = owned_hooks.cleanup_owner(_measure_facade) # proof only, as _is_our_hook_entry
5525
5483
  for event in list(hooks.keys()):
5526
5484
  groups = hooks.get(event)
5527
5485
  if not isinstance(groups, list):
@@ -5536,7 +5494,7 @@ def _remove_our_settings_entries(settings: dict) -> list[str]:
5536
5494
  if not isinstance(entries, list):
5537
5495
  new_groups.append(group)
5538
5496
  continue
5539
- kept = [h for h in entries if not _measure_facade._is_our_hook_entry(h)]
5497
+ kept = [h for h in entries if not owns(event, group, h)]
5540
5498
  n_ours = len(entries) - len(kept)
5541
5499
  if n_ours == 0:
5542
5500
  # Nothing of ours here -- leave the group exactly as-is,