@alexgreensh/token-optimizer 5.13.70 → 5.13.72

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 (40) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/hooks/module_runner.py +3 -3
  4. package/hooks/sessionstart_runner.py +6 -0
  5. package/package.json +1 -1
  6. package/skills/token-optimizer/assets/dashboard.html +361 -289
  7. package/skills/token-optimizer/assets/savings_story.js +140 -36
  8. package/skills/token-optimizer/references/cli-reference.md +1 -1
  9. package/skills/token-optimizer/scripts/_measure/__init__.py +3 -3
  10. package/skills/token-optimizer/scripts/_measure/config_cache.py +63 -0
  11. package/skills/token-optimizer/scripts/_measure/context_reset_marker.py +3 -1
  12. package/skills/token-optimizer/scripts/_measure/counted_cap.py +4 -2
  13. package/skills/token-optimizer/scripts/_measure/coverage_report.py +11 -1
  14. package/skills/token-optimizer/scripts/_measure/dashboard.py +35 -64
  15. package/skills/token-optimizer/scripts/_measure/holdout_report.py +5 -1
  16. package/skills/token-optimizer/scripts/_measure/keepwarm_safety.py +4 -0
  17. package/skills/token-optimizer/scripts/_measure/lifecycle.py +6 -7
  18. package/skills/token-optimizer/scripts/_measure/quality_checkpoint.py +4 -3
  19. package/skills/token-optimizer/scripts/_measure/savings.py +11 -4
  20. package/skills/token-optimizer/scripts/_measure/savings_headline.py +130 -0
  21. package/skills/token-optimizer/scripts/_measure/sessions.py +7 -0
  22. package/skills/token-optimizer/scripts/_measure/setup_observation_cache.py +99 -0
  23. package/skills/token-optimizer/scripts/_measure/setup_step.py +4 -5
  24. package/skills/token-optimizer/scripts/_measure/status_bar_refresh.py +218 -0
  25. package/skills/token-optimizer/scripts/_measure/structural_report.py +25 -6
  26. package/skills/token-optimizer/scripts/_measure/structural_value.py +16 -10
  27. package/skills/token-optimizer/scripts/cloud_kit.py +1 -2
  28. package/skills/token-optimizer/scripts/codemap.py +33 -5
  29. package/skills/token-optimizer/scripts/codemap_hint.py +152 -11
  30. package/skills/token-optimizer/scripts/codemap_index.py +100 -11
  31. package/skills/token-optimizer/scripts/codemap_ledger.py +29 -0
  32. package/skills/token-optimizer/scripts/codex_doctor.py +3 -3
  33. package/skills/token-optimizer/scripts/hermes_doctor.py +3 -3
  34. package/skills/token-optimizer/scripts/hermes_install.py +3 -3
  35. package/skills/token-optimizer/scripts/statusline.js +157 -30
  36. package/skills/token-optimizer/scripts/_measure/keepwarm_fork.py +0 -140
  37. package/skills/token-optimizer/scripts/_measure/keepwarm_guard.py +0 -35
  38. package/skills/token-optimizer/scripts/_measure/keepwarm_guard_server.py +0 -85
  39. package/skills/token-optimizer/scripts/_measure/keepwarm_prefix.py +0 -143
  40. package/skills/token-optimizer/scripts/_measure/keepwarm_response_filter.py +0 -84
@@ -107,6 +107,16 @@ def codemap_enabled() -> bool:
107
107
  return False
108
108
 
109
109
 
110
+ def codemap_hint_enabled() -> bool:
111
+ if not codemap_enabled():
112
+ return False
113
+ try:
114
+ from plugin_env import is_v5_flag_enabled
115
+ return is_v5_flag_enabled("v5_codemap_hint", "TOKEN_OPTIMIZER_CODEMAP_HINT", default=False)
116
+ except Exception:
117
+ return False
118
+
119
+
110
120
  def reread_outline_enabled() -> bool:
111
121
  if not codemap_enabled():
112
122
  return False
@@ -148,7 +158,7 @@ def index_dir() -> Path:
148
158
 
149
159
  def index_path(root: Path) -> Path:
150
160
  digest = hashlib.sha256(str(root).encode("utf-8", "replace")).hexdigest()[:16]
151
- return index_dir() / f"{digest}.db"
161
+ return index_dir() / f"{digest}-bounded-v1.db"
152
162
 
153
163
 
154
164
  # --------------------------------------------------------------------------- #
@@ -365,6 +375,14 @@ def parse_file(path: Path, root: Path, source: Optional[str] = None) -> FileFact
365
375
  # Store
366
376
  # --------------------------------------------------------------------------- #
367
377
 
378
+ class IncompleteSweep(Exception):
379
+ """The source sweep ran out of time."""
380
+
381
+
382
+ class CappedSweep(Exception):
383
+ """The source sweep reached its file limit."""
384
+
385
+
368
386
  def _iter_source_files(root: Path, deadline: float) -> Iterator[Path]:
369
387
  count = 0
370
388
  for dirpath, dirnames, filenames in os.walk(root, followlinks=False):
@@ -375,8 +393,10 @@ def _iter_source_files(root: Path, deadline: float) -> Iterator[Path]:
375
393
  if fn.endswith((".min.js", ".bundle.js", ".d.ts")):
376
394
  continue
377
395
  count += 1
378
- if count > MAX_FILES or time.monotonic() > deadline:
379
- return
396
+ if time.monotonic() > deadline:
397
+ raise IncompleteSweep()
398
+ if count > MAX_FILES:
399
+ raise CappedSweep()
380
400
  yield Path(dirpath) / fn
381
401
 
382
402
 
@@ -388,6 +408,9 @@ class CodeIndex:
388
408
  self.conn = conn
389
409
  self.db_path = db_path
390
410
  self.complete = False
411
+ self.capped = False
412
+ self.readonly = False
413
+ self.stale = False
391
414
 
392
415
  @classmethod
393
416
  def open(cls, root: str | os.PathLike[str], db_path: Optional[Path] = None) -> "CodeIndex":
@@ -523,6 +546,7 @@ class CodeIndex:
523
546
  seen = set()
524
547
  stats = {"parsed": 0, "unchanged": 0, "removed": 0}
525
548
  timed_out = False
549
+ self.capped = False
526
550
  try:
527
551
  for p in _iter_source_files(self.root, deadline):
528
552
  rel = _rel(self.root, p)
@@ -548,11 +572,18 @@ class CodeIndex:
548
572
  break
549
573
  else:
550
574
  timed_out = time.monotonic() > deadline
575
+ except IncompleteSweep:
576
+ timed_out = True
577
+ except CappedSweep:
578
+ self.capped = True
579
+ try:
551
580
  if not timed_out:
552
581
  for rel in set(known) - seen:
553
582
  self._drop(rel)
554
583
  stats["removed"] += 1
555
584
  self.complete = not timed_out
585
+ self.conn.execute("INSERT OR REPLACE INTO meta VALUES('capped', ?)",
586
+ ("1" if self.capped and not timed_out else "0",))
556
587
  self.conn.execute("INSERT OR REPLACE INTO meta VALUES('complete', ?)",
557
588
  ("1" if self.complete else "0",))
558
589
  self.conn.commit()
@@ -639,16 +670,74 @@ class CodeIndex:
639
670
  def open_synced(start: str | os.PathLike[str], budget_s: Optional[float] = None) -> CodeIndex:
640
671
  """Open (building lazily) and sync the index for the project containing ``start``."""
641
672
  root = find_project_root(start)
642
- idx = CodeIndex.open(root)
673
+ idx = None
643
674
  try:
675
+ idx = CodeIndex.open(root)
644
676
  idx.sync(budget_s)
645
- except CodemapError:
646
- idx.close()
647
- raise
648
- except Exception as exc: # parsing bugs must never escape to the agent
649
- idx.close()
650
- raise CodemapError(f"index sync failed: {exc}") from exc
651
- return idx
677
+ return idx
678
+ except Exception as write_error:
679
+ if idx is not None:
680
+ idx.close()
681
+ db = index_path(root)
682
+ # Normal read-only mode can see WAL data when its sidecars are accessible.
683
+ # Immutable is a last resort for a snapshot whose WAL cannot be opened.
684
+ uri = db.resolve().as_uri() + "?mode=ro"
685
+ conn = None
686
+ immutable = False
687
+ try:
688
+ try:
689
+ conn = sqlite3.connect(uri, uri=True, timeout=3.0)
690
+ conn.execute("SELECT v FROM meta WHERE k='schema'").fetchone()
691
+ except sqlite3.Error:
692
+ try:
693
+ conn.close()
694
+ except (AttributeError, UnboundLocalError):
695
+ pass
696
+ conn = sqlite3.connect(uri + "&immutable=1", uri=True, timeout=3.0)
697
+ immutable = True
698
+ idx = CodeIndex(root, conn, db)
699
+ version = conn.execute("SELECT v FROM meta WHERE k='schema'").fetchone()
700
+ if not version or version[0] != SCHEMA_VERSION:
701
+ raise CodemapError("read-only index schema mismatch")
702
+ row = conn.execute("SELECT v FROM meta WHERE k='complete'").fetchone()
703
+ idx.complete = bool(row and row[0] == "1")
704
+ capped = conn.execute("SELECT v FROM meta WHERE k='capped'").fetchone()
705
+ idx.capped = bool(capped and capped[0] == "1")
706
+ idx.readonly = True
707
+ idx.stale = immutable
708
+ known = {r[0]: (r[1], r[2]) for r in conn.execute("SELECT path, mtime_ns, size FROM files")}
709
+ seen = set()
710
+ try:
711
+ for path in _iter_source_files(root, time.monotonic() + SWEEP_BUDGET_S):
712
+ rel = _rel(root, path)
713
+ if rel is None:
714
+ continue
715
+ seen.add(rel)
716
+ try:
717
+ st = path.stat()
718
+ if known.get(rel) != (st.st_mtime_ns, st.st_size):
719
+ idx.stale = True
720
+ except OSError:
721
+ idx.stale = True
722
+ except CappedSweep:
723
+ if not idx.capped:
724
+ idx.stale = True
725
+ except IncompleteSweep:
726
+ idx.stale = True
727
+ idx.stale = idx.stale or seen != set(known)
728
+ return idx
729
+ except Exception as read_error:
730
+ if idx is not None:
731
+ idx.close()
732
+ elif conn is not None:
733
+ conn.close()
734
+ if isinstance(read_error, CodemapError):
735
+ raise read_error
736
+ cause = read_error if isinstance(read_error, sqlite3.Error) else write_error
737
+ while cause.__cause__ is not None:
738
+ cause = cause.__cause__
739
+ code = getattr(cause, "sqlite_errorname", "unavailable")
740
+ raise CodemapError(f"query failed at open/sync (SQLite {code}; data dir {db.parent.name})") from read_error
652
741
 
653
742
 
654
743
  def symbols_in(text: str) -> Sequence[str]:
@@ -36,6 +36,9 @@ PENDING_MAX_PATHS = 400
36
36
  _PENDING_NAME = "pending.json"
37
37
 
38
38
  _SCHEMA = """
39
+ CREATE TABLE IF NOT EXISTS codemap_failures (
40
+ id INTEGER PRIMARY KEY, ts_epoch REAL NOT NULL, stage TEXT, code TEXT
41
+ );
39
42
  CREATE TABLE IF NOT EXISTS codemap_events (
40
43
  id INTEGER PRIMARY KEY AUTOINCREMENT,
41
44
  timestamp TEXT NOT NULL,
@@ -85,9 +88,35 @@ def _connect() -> sqlite3.Connection:
85
88
  conn = sqlite3.connect(str(db), timeout=3.0)
86
89
  conn.execute("PRAGMA busy_timeout=3000")
87
90
  conn.executescript(_SCHEMA)
91
+ columns = {row[1] for row in conn.execute("PRAGMA table_info(codemap_failures)")}
92
+ for column in ("stage", "code"):
93
+ if column not in columns:
94
+ conn.execute(f"ALTER TABLE codemap_failures ADD COLUMN {column} TEXT")
88
95
  return conn
89
96
 
90
97
 
98
+ def log_failure(stage: str = "lookup", code: str = "unknown") -> None:
99
+ """Count failed attempts independently of the savings ledger."""
100
+ conn = _connect()
101
+ try:
102
+ conn.execute("INSERT INTO codemap_failures (ts_epoch, stage, code) VALUES (?, ?, ?)",
103
+ (time.time(), stage[:32], code[:64]))
104
+ conn.commit()
105
+ finally:
106
+ conn.close()
107
+
108
+
109
+ def failure_count() -> int:
110
+ try:
111
+ conn = _connect()
112
+ try:
113
+ return int(conn.execute("SELECT COUNT(*) FROM codemap_failures").fetchone()[0])
114
+ finally:
115
+ conn.close()
116
+ except Exception:
117
+ return 0
118
+
119
+
91
120
  def _read_pending() -> Dict:
92
121
  try:
93
122
  raw = _pending_path().read_text(encoding="utf-8")
@@ -69,11 +69,11 @@ _MEASURE_PACKAGE_FILES = (
69
69
  "_measure/pricing.py", "_measure/audit.py", "_measure/dashboard.py",
70
70
  "_measure/lifecycle.py", "_measure/sessions.py", "_measure/trends.py",
71
71
  "_measure/cache_policy.py", "_measure/daemon.py", "_measure/quality_archive.py",
72
- "_measure/continuity.py", "_measure/savings.py", "_measure/cli.py", "_measure/dashboard_history.py", "_measure/weekly_activity.py", "_measure/headline.py", "_measure/counted_position.py", "_measure/counted_pricing_v5.py", "_measure/transcript_backfill.py", "_measure/counted_subagents.py", "_measure/lean_resume_threshold.py", "_measure/output_reread.py", "_measure/session_effect.py", "_measure/structural_ledger.py", "_measure/structural_archives.py", "_measure/structural_listing.py", "_measure/structural_report.py", "_measure/structural_seed.py", "_measure/structural_value.py", "_measure/rework_metrics.py", "_measure/session_best.py", "_measure/savings_story.py", "_measure/counted_orphans.py", "_measure/counted_cap.py", "_measure/archive_void_evidence.py", "_measure/cost_per_message_trend.py", "_measure/lean_resume_receivers.py", "_measure/routing_period.py", "_measure/fixture_context.py", "_measure/transcript_product.py", "_measure/periphery_exposure.py", "_measure/structure_funnel.py", "_measure/setup_attachment_counter.py", "_measure/first_read_outcomes.py", "_measure/setup_budget_monitor.py", "_measure/setup_connector_ledger.py", "_measure/first_call_context.py", "_measure/timestamp_cache.py", "_measure/token_type_split.py", "_measure/evidence_parallel.py", "_measure/ttl_period.py", "_measure/first_read_revive.py", "_measure/mcp_archive_tripwire.py", "_measure/compaction_survival.py", "_measure/archive_void_codex.py", "_measure/compression_fixture_void.py", "_measure/feature_health.py", "_measure/archive_health.py", "_measure/coverage_report.py", "_measure/file_refetch.py", "_measure/holdout_report.py", "_measure/structural_dedupe.py", "_measure/setup_step.py", "_measure/baseline_provenance.py", "_measure/own_price_card.py",
72
+ "_measure/continuity.py", "_measure/savings.py", "_measure/cli.py", "_measure/dashboard_history.py", "_measure/weekly_activity.py", "_measure/headline.py", "_measure/counted_position.py", "_measure/counted_pricing_v5.py", "_measure/transcript_backfill.py", "_measure/counted_subagents.py", "_measure/lean_resume_threshold.py", "_measure/output_reread.py", "_measure/session_effect.py", "_measure/structural_ledger.py", "_measure/structural_archives.py", "_measure/structural_listing.py", "_measure/structural_report.py", "_measure/structural_seed.py", "_measure/structural_value.py", "_measure/rework_metrics.py", "_measure/session_best.py", "_measure/savings_story.py", "_measure/savings_headline.py", "_measure/counted_orphans.py", "_measure/counted_cap.py", "_measure/archive_void_evidence.py", "_measure/cost_per_message_trend.py", "_measure/lean_resume_receivers.py", "_measure/routing_period.py", "_measure/fixture_context.py", "_measure/transcript_product.py", "_measure/periphery_exposure.py", "_measure/structure_funnel.py", "_measure/setup_attachment_counter.py", "_measure/first_read_outcomes.py", "_measure/setup_budget_monitor.py", "_measure/setup_connector_ledger.py", "_measure/first_call_context.py", "_measure/timestamp_cache.py", "_measure/token_type_split.py", "_measure/evidence_parallel.py", "_measure/ttl_period.py", "_measure/first_read_revive.py", "_measure/mcp_archive_tripwire.py", "_measure/compaction_survival.py", "_measure/archive_void_codex.py", "_measure/compression_fixture_void.py", "_measure/feature_health.py", "_measure/archive_health.py", "_measure/coverage_report.py", "_measure/file_refetch.py", "_measure/holdout_report.py", "_measure/structural_dedupe.py", "_measure/setup_step.py", "_measure/baseline_provenance.py", "_measure/own_price_card.py",
73
73
  )
74
74
  _MEASURE_PACKAGE_FILES += ('_measure/transcript_stream.py', '_measure/checkpoint_direction.py', '_measure/checkpoint_retention.py')
75
- _MEASURE_PACKAGE_FILES += ('_measure/keepwarm_safety.py', '_measure/keepwarm_economics.py', '_measure/keepwarm_linux.py', '_measure/keepwarm_prefix.py', '_measure/keepwarm_response_filter.py', '_measure/keepwarm_guard.py', '_measure/keepwarm_guard_server.py', '_measure/keepwarm_fork.py', '_measure/mod_action_booking.py', '_measure/mod_compaction_booking.py', '_measure/mod_fresh_booking.py',)
76
- _MEASURE_PACKAGE_FILES += ('_measure/quality_continuity.py', '_measure/quality_checkpoint.py', '_measure/codex_quality.py', '_measure/lease_candidate_cleanup.py', '_measure/session_store_spool.py', '_measure/upgrade_drain_control.py', '_measure/compression_scan_checkpoint.py', '_measure/status_bar_lock.py', '_measure/session_flush_lock.py', '_measure/context_reset_marker.py', '_measure/holdout_fallback.py', '_measure/dashboard_heal_claim.py',)
75
+ _MEASURE_PACKAGE_FILES += ('_measure/keepwarm_safety.py', '_measure/keepwarm_economics.py', '_measure/keepwarm_linux.py', '_measure/mod_action_booking.py', '_measure/mod_compaction_booking.py', '_measure/mod_fresh_booking.py',)
76
+ _MEASURE_PACKAGE_FILES += ('_measure/quality_continuity.py', '_measure/quality_checkpoint.py', '_measure/codex_quality.py', '_measure/lease_candidate_cleanup.py', '_measure/session_store_spool.py', '_measure/upgrade_drain_control.py', '_measure/compression_scan_checkpoint.py', '_measure/status_bar_lock.py', '_measure/session_flush_lock.py', '_measure/context_reset_marker.py', '_measure/holdout_fallback.py', '_measure/dashboard_heal_claim.py', '_measure/config_cache.py', '_measure/setup_observation_cache.py', '_measure/status_bar_refresh.py',)
77
77
 
78
78
 
79
79
  def _repo_root() -> Path:
@@ -359,11 +359,11 @@ _MEASURE_PACKAGE_FILES = (
359
359
  "_measure/pricing.py", "_measure/audit.py", "_measure/dashboard.py",
360
360
  "_measure/lifecycle.py", "_measure/sessions.py", "_measure/trends.py",
361
361
  "_measure/cache_policy.py", "_measure/daemon.py", "_measure/quality_archive.py",
362
- "_measure/continuity.py", "_measure/savings.py", "_measure/cli.py", "_measure/dashboard_history.py", "_measure/weekly_activity.py", "_measure/headline.py", "_measure/counted_position.py", "_measure/counted_pricing_v5.py", "_measure/transcript_backfill.py", "_measure/counted_subagents.py", "_measure/lean_resume_threshold.py", "_measure/output_reread.py", "_measure/session_effect.py", "_measure/structural_ledger.py", "_measure/structural_archives.py", "_measure/structural_listing.py", "_measure/structural_report.py", "_measure/structural_seed.py", "_measure/structural_value.py", "_measure/rework_metrics.py", "_measure/session_best.py", "_measure/savings_story.py", "_measure/counted_orphans.py", "_measure/counted_cap.py", "_measure/archive_void_evidence.py", "_measure/cost_per_message_trend.py", "_measure/lean_resume_receivers.py", "_measure/routing_period.py", "_measure/fixture_context.py", "_measure/transcript_product.py", "_measure/periphery_exposure.py", "_measure/structure_funnel.py", "_measure/setup_attachment_counter.py", "_measure/first_read_outcomes.py", "_measure/setup_budget_monitor.py", "_measure/setup_connector_ledger.py", "_measure/first_call_context.py", "_measure/timestamp_cache.py", "_measure/token_type_split.py", "_measure/evidence_parallel.py", "_measure/ttl_period.py", "_measure/first_read_revive.py", "_measure/mcp_archive_tripwire.py", "_measure/compaction_survival.py", "_measure/archive_void_codex.py", "_measure/compression_fixture_void.py", "_measure/feature_health.py", "_measure/archive_health.py", "_measure/coverage_report.py", "_measure/file_refetch.py", "_measure/holdout_report.py", "_measure/structural_dedupe.py", "_measure/setup_step.py", "_measure/baseline_provenance.py", "_measure/own_price_card.py",
362
+ "_measure/continuity.py", "_measure/savings.py", "_measure/cli.py", "_measure/dashboard_history.py", "_measure/weekly_activity.py", "_measure/headline.py", "_measure/counted_position.py", "_measure/counted_pricing_v5.py", "_measure/transcript_backfill.py", "_measure/counted_subagents.py", "_measure/lean_resume_threshold.py", "_measure/output_reread.py", "_measure/session_effect.py", "_measure/structural_ledger.py", "_measure/structural_archives.py", "_measure/structural_listing.py", "_measure/structural_report.py", "_measure/structural_seed.py", "_measure/structural_value.py", "_measure/rework_metrics.py", "_measure/session_best.py", "_measure/savings_story.py", "_measure/savings_headline.py", "_measure/counted_orphans.py", "_measure/counted_cap.py", "_measure/archive_void_evidence.py", "_measure/cost_per_message_trend.py", "_measure/lean_resume_receivers.py", "_measure/routing_period.py", "_measure/fixture_context.py", "_measure/transcript_product.py", "_measure/periphery_exposure.py", "_measure/structure_funnel.py", "_measure/setup_attachment_counter.py", "_measure/first_read_outcomes.py", "_measure/setup_budget_monitor.py", "_measure/setup_connector_ledger.py", "_measure/first_call_context.py", "_measure/timestamp_cache.py", "_measure/token_type_split.py", "_measure/evidence_parallel.py", "_measure/ttl_period.py", "_measure/first_read_revive.py", "_measure/mcp_archive_tripwire.py", "_measure/compaction_survival.py", "_measure/archive_void_codex.py", "_measure/compression_fixture_void.py", "_measure/feature_health.py", "_measure/archive_health.py", "_measure/coverage_report.py", "_measure/file_refetch.py", "_measure/holdout_report.py", "_measure/structural_dedupe.py", "_measure/setup_step.py", "_measure/baseline_provenance.py", "_measure/own_price_card.py",
363
363
  )
364
364
  _MEASURE_PACKAGE_FILES += ('_measure/transcript_stream.py', '_measure/checkpoint_direction.py', '_measure/checkpoint_retention.py')
365
- _MEASURE_PACKAGE_FILES += ('_measure/keepwarm_safety.py', '_measure/keepwarm_economics.py', '_measure/keepwarm_linux.py', '_measure/keepwarm_prefix.py', '_measure/keepwarm_response_filter.py', '_measure/keepwarm_guard.py', '_measure/keepwarm_guard_server.py', '_measure/keepwarm_fork.py', '_measure/mod_action_booking.py', '_measure/mod_compaction_booking.py', '_measure/mod_fresh_booking.py',)
366
- _MEASURE_PACKAGE_FILES += ('_measure/quality_continuity.py', '_measure/quality_checkpoint.py', '_measure/codex_quality.py', '_measure/lease_candidate_cleanup.py', '_measure/session_store_spool.py', '_measure/upgrade_drain_control.py', '_measure/compression_scan_checkpoint.py', '_measure/status_bar_lock.py', '_measure/session_flush_lock.py', '_measure/context_reset_marker.py', '_measure/holdout_fallback.py', '_measure/dashboard_heal_claim.py',)
365
+ _MEASURE_PACKAGE_FILES += ('_measure/keepwarm_safety.py', '_measure/keepwarm_economics.py', '_measure/keepwarm_linux.py', '_measure/mod_action_booking.py', '_measure/mod_compaction_booking.py', '_measure/mod_fresh_booking.py',)
366
+ _MEASURE_PACKAGE_FILES += ('_measure/quality_continuity.py', '_measure/quality_checkpoint.py', '_measure/codex_quality.py', '_measure/lease_candidate_cleanup.py', '_measure/session_store_spool.py', '_measure/upgrade_drain_control.py', '_measure/compression_scan_checkpoint.py', '_measure/status_bar_lock.py', '_measure/session_flush_lock.py', '_measure/context_reset_marker.py', '_measure/holdout_fallback.py', '_measure/dashboard_heal_claim.py', '_measure/config_cache.py', '_measure/setup_observation_cache.py', '_measure/status_bar_refresh.py',)
367
367
 
368
368
 
369
369
  def _engine_checks() -> list[dict[str, str]]:
@@ -102,11 +102,11 @@ _MEASURE_PACKAGE_FILES = (
102
102
  "_measure/pricing.py", "_measure/audit.py", "_measure/dashboard.py",
103
103
  "_measure/lifecycle.py", "_measure/sessions.py", "_measure/trends.py",
104
104
  "_measure/cache_policy.py", "_measure/daemon.py", "_measure/quality_archive.py",
105
- "_measure/continuity.py", "_measure/savings.py", "_measure/cli.py", "_measure/dashboard_history.py", "_measure/weekly_activity.py", "_measure/headline.py", "_measure/counted_position.py", "_measure/counted_pricing_v5.py", "_measure/transcript_backfill.py", "_measure/counted_subagents.py", "_measure/lean_resume_threshold.py", "_measure/output_reread.py", "_measure/session_effect.py", "_measure/structural_ledger.py", "_measure/structural_archives.py", "_measure/structural_listing.py", "_measure/structural_report.py", "_measure/structural_seed.py", "_measure/structural_value.py", "_measure/rework_metrics.py", "_measure/session_best.py", "_measure/savings_story.py", "_measure/counted_orphans.py", "_measure/counted_cap.py", "_measure/archive_void_evidence.py", "_measure/cost_per_message_trend.py", "_measure/lean_resume_receivers.py", "_measure/routing_period.py", "_measure/fixture_context.py", "_measure/transcript_product.py", "_measure/periphery_exposure.py", "_measure/structure_funnel.py", "_measure/setup_attachment_counter.py", "_measure/first_read_outcomes.py", "_measure/setup_budget_monitor.py", "_measure/setup_connector_ledger.py", "_measure/first_call_context.py", "_measure/timestamp_cache.py", "_measure/token_type_split.py", "_measure/evidence_parallel.py", "_measure/ttl_period.py", "_measure/first_read_revive.py", "_measure/mcp_archive_tripwire.py", "_measure/compaction_survival.py", "_measure/archive_void_codex.py", "_measure/compression_fixture_void.py", "_measure/feature_health.py", "_measure/archive_health.py", "_measure/coverage_report.py", "_measure/file_refetch.py", "_measure/holdout_report.py", "_measure/structural_dedupe.py", "_measure/setup_step.py", "_measure/baseline_provenance.py", "_measure/own_price_card.py",
105
+ "_measure/continuity.py", "_measure/savings.py", "_measure/cli.py", "_measure/dashboard_history.py", "_measure/weekly_activity.py", "_measure/headline.py", "_measure/counted_position.py", "_measure/counted_pricing_v5.py", "_measure/transcript_backfill.py", "_measure/counted_subagents.py", "_measure/lean_resume_threshold.py", "_measure/output_reread.py", "_measure/session_effect.py", "_measure/structural_ledger.py", "_measure/structural_archives.py", "_measure/structural_listing.py", "_measure/structural_report.py", "_measure/structural_seed.py", "_measure/structural_value.py", "_measure/rework_metrics.py", "_measure/session_best.py", "_measure/savings_story.py", "_measure/savings_headline.py", "_measure/counted_orphans.py", "_measure/counted_cap.py", "_measure/archive_void_evidence.py", "_measure/cost_per_message_trend.py", "_measure/lean_resume_receivers.py", "_measure/routing_period.py", "_measure/fixture_context.py", "_measure/transcript_product.py", "_measure/periphery_exposure.py", "_measure/structure_funnel.py", "_measure/setup_attachment_counter.py", "_measure/first_read_outcomes.py", "_measure/setup_budget_monitor.py", "_measure/setup_connector_ledger.py", "_measure/first_call_context.py", "_measure/timestamp_cache.py", "_measure/token_type_split.py", "_measure/evidence_parallel.py", "_measure/ttl_period.py", "_measure/first_read_revive.py", "_measure/mcp_archive_tripwire.py", "_measure/compaction_survival.py", "_measure/archive_void_codex.py", "_measure/compression_fixture_void.py", "_measure/feature_health.py", "_measure/archive_health.py", "_measure/coverage_report.py", "_measure/file_refetch.py", "_measure/holdout_report.py", "_measure/structural_dedupe.py", "_measure/setup_step.py", "_measure/baseline_provenance.py", "_measure/own_price_card.py",
106
106
  )
107
107
  _MEASURE_PACKAGE_FILES += ('_measure/transcript_stream.py', '_measure/checkpoint_direction.py', '_measure/checkpoint_retention.py')
108
- _MEASURE_PACKAGE_FILES += ('_measure/keepwarm_safety.py', '_measure/keepwarm_economics.py', '_measure/keepwarm_linux.py', '_measure/keepwarm_prefix.py', '_measure/keepwarm_response_filter.py', '_measure/keepwarm_guard.py', '_measure/keepwarm_guard_server.py', '_measure/keepwarm_fork.py', '_measure/mod_action_booking.py', '_measure/mod_compaction_booking.py', '_measure/mod_fresh_booking.py',)
109
- _MEASURE_PACKAGE_FILES += ('_measure/quality_continuity.py', '_measure/quality_checkpoint.py', '_measure/codex_quality.py', '_measure/lease_candidate_cleanup.py', '_measure/session_store_spool.py', '_measure/upgrade_drain_control.py', '_measure/compression_scan_checkpoint.py', '_measure/status_bar_lock.py', '_measure/session_flush_lock.py', '_measure/context_reset_marker.py', '_measure/holdout_fallback.py', '_measure/dashboard_heal_claim.py',)
108
+ _MEASURE_PACKAGE_FILES += ('_measure/keepwarm_safety.py', '_measure/keepwarm_economics.py', '_measure/keepwarm_linux.py', '_measure/mod_action_booking.py', '_measure/mod_compaction_booking.py', '_measure/mod_fresh_booking.py',)
109
+ _MEASURE_PACKAGE_FILES += ('_measure/quality_continuity.py', '_measure/quality_checkpoint.py', '_measure/codex_quality.py', '_measure/lease_candidate_cleanup.py', '_measure/session_store_spool.py', '_measure/upgrade_drain_control.py', '_measure/compression_scan_checkpoint.py', '_measure/status_bar_lock.py', '_measure/session_flush_lock.py', '_measure/context_reset_marker.py', '_measure/holdout_fallback.py', '_measure/dashboard_heal_claim.py', '_measure/config_cache.py', '_measure/setup_observation_cache.py', '_measure/status_bar_refresh.py',)
110
110
 
111
111
 
112
112
  def _scripts_dir() -> Path:
@@ -1,18 +1,22 @@
1
1
  #!/usr/bin/env node
2
2
  // Token Optimizer - Claude Code Status Line (two-row layout)
3
3
  //
4
- // Row 1: model | effort | project | context bar used% | ContextQ:grade(score)
5
- // Row 2: Eff:grade(score) | warnings | Compacts:N(observing) | duration | Agents
4
+ // Row 1: model | effort | project | context bar used% | Quality grade(score)
5
+ // Row 2: savings headline | warnings | duration | Agents | limits
6
6
  //
7
7
  // Install: python3 measure.py setup-quality-bar
8
8
  // The quality score is updated by a UserPromptSubmit hook every ~2 minutes.
9
9
  // Reads from the most recent per-session quality-cache-*.json for accuracy.
10
10
  // Effort level comes from the stdin payload (data.effort.level) when Claude
11
11
  // Code provides it, falling back to settings.json effortLevel on older versions.
12
+ // The savings segment is read from the status-bar JSON cache that
13
+ // `measure.py status-bar` writes under SNAPSHOT_DIR/status-bar/; this script
14
+ // never spawns Python (it runs on every render).
12
15
 
13
16
  const fs = require('fs');
14
17
  const path = require('path');
15
18
  const os = require('os');
19
+ const crypto = require('crypto');
16
20
  const { execFileSync } = require('child_process');
17
21
 
18
22
  // --- Self-disabling guard ---
@@ -124,6 +128,118 @@ function _claudeHome() {
124
128
  }
125
129
  const CLAUDE_HOME = _claudeHome();
126
130
 
131
+ // ---- OSC 8 hyperlink support ----
132
+ // Emit \x1b]8;;URL\x07TEXT\x1b]8;;\x07 only where the terminal is known to
133
+ // render it; everywhere else the segment stays plain text (the approved
134
+ // artboard's fallback). TOKEN_OPTIMIZER_HYPERLINKS=0/1 forces either way.
135
+ // tmux/screen are treated as unsupported: passthrough needs allow-passthrough
136
+ // AND a capable outer terminal, neither of which is detectable here.
137
+ function _supportsOsc8() {
138
+ try {
139
+ const env = process.env;
140
+ const override = String(env.TOKEN_OPTIMIZER_HYPERLINKS || '').trim().toLowerCase();
141
+ if (override === '0' || override === 'false' || override === 'off') return false;
142
+ if (override === '1' || override === 'true' || override === 'on') return true;
143
+ if (env.TMUX || env.STY) return false;
144
+ const tp = String(env.TERM_PROGRAM || '').toLowerCase();
145
+ if (['iterm.app', 'wezterm', 'kitty', 'ghostty', 'vscode', 'visual studio code',
146
+ 'hyper', 'tabby', 'warpterminal', 'alacritty', 'rio', 'contour',
147
+ 'mintty', 'cursor', 'windsurf'].includes(tp)) return true;
148
+ if (tp === 'apple_terminal') return false;
149
+ if (env.WT_SESSION || env.KONSOLE_VERSION || env.ALACRITTY_WINDOW_ID ||
150
+ env.ALACRITTY_LOG || env.KITTY_WINDOW_ID || env.GHOSTTY_RESOURCES_DIR) return true;
151
+ if (/foot|wezterm|kitty|alacritty|ghostty|contour|rio/.test(String(env.TERM || '').toLowerCase())) return true;
152
+ const vte = parseInt(env.VTE_VERSION || '0', 10);
153
+ if (vte >= 5000) return true;
154
+ return false;
155
+ } catch (e) {
156
+ return false;
157
+ }
158
+ }
159
+
160
+ // ---- Status-bar cache (savings headline) ----
161
+ // measure.py resolves SNAPSHOT_DIR as TOKEN_OPTIMIZER_SNAPSHOT_DIR, else
162
+ // <plugin-data>/data, else <runtime>/_backups/token-optimizer. The status line
163
+ // has no CLAUDE_PLUGIN_DATA, so mirror the quality-cache fan-out: check every
164
+ // candidate status-bar dir and keep the freshest cache file for this session.
165
+ function _statusBarDirs() {
166
+ const dirs = [];
167
+ const snap = String(process.env.TOKEN_OPTIMIZER_SNAPSHOT_DIR || '').trim();
168
+ if (snap) dirs.push(path.join(snap, 'status-bar'));
169
+ for (const v of [process.env.CLAUDE_PLUGIN_DATA, process.env.TOKEN_OPTIMIZER_PLUGIN_DATA]) {
170
+ const p = String(v || '').trim();
171
+ if (p) dirs.push(path.join(p, 'data', 'status-bar'));
172
+ }
173
+ try {
174
+ const dataRoot = path.join(CLAUDE_HOME, 'plugins', 'data');
175
+ for (const d of fs.readdirSync(dataRoot)) {
176
+ if (d.includes('token-optimizer')) {
177
+ dirs.push(path.join(dataRoot, d, 'data', 'status-bar'));
178
+ }
179
+ }
180
+ } catch (e) {}
181
+ dirs.push(path.join(CLAUDE_HOME, '_backups', 'token-optimizer', 'status-bar'));
182
+ return dirs;
183
+ }
184
+
185
+ // Python twin of sanitize_session_id + _status_bar_key: strip unsafe chars,
186
+ // "unknown" under 6, and long ids are shortened with a sha256 suffix.
187
+ function _statusBarSessionKey(sessionId) {
188
+ let sid = sessionId === null || sessionId === undefined ? '' : String(sessionId);
189
+ sid = sid.replace(/[^a-zA-Z0-9_-]/g, '');
190
+ if (sid.length < 6) sid = 'unknown';
191
+ if (sid.length <= 100) return sid;
192
+ const hash = crypto.createHash('sha256').update(sid, 'utf8').digest('hex').slice(0, 16);
193
+ return sid.slice(0, 64) + '-' + hash;
194
+ }
195
+
196
+ // Cache files that can hold the headline in one status-bar dir. measure.py
197
+ // writes the shared 30-day figure to global.json (or global-pending-*.json when
198
+ // global.json is locked). The per-session <key>.json is the pre-upgrade layout,
199
+ // read only so the number shows before the first refresh after an upgrade.
200
+ function _statusBarCacheFiles(dir, key) {
201
+ const files = [path.join(dir, 'global.json')];
202
+ try {
203
+ for (const name of fs.readdirSync(dir)) {
204
+ if (name.startsWith('global-pending-') && name.endsWith('.json')) files.push(path.join(dir, name));
205
+ }
206
+ } catch (e) {}
207
+ if (key && key !== 'unknown' && key !== 'global') files.push(path.join(dir, key + '.json'));
208
+ return files;
209
+ }
210
+
211
+ // The freshest status-bar cache's savings_headline.display, or null.
212
+ // Freshness is decided on computed_at across all candidate files BEFORE
213
+ // reading display, so a newer "below threshold" cache correctly hides an
214
+ // older number that no longer applies.
215
+ function _statusBarHeadlineDisplay(sessionId) {
216
+ try {
217
+ const key = _statusBarSessionKey(sessionId);
218
+ let best = null, bestTs = -1;
219
+ for (const dir of _statusBarDirs()) {
220
+ for (const file of _statusBarCacheFiles(dir, key)) try {
221
+ const raw = fs.readFileSync(file, 'utf8');
222
+ const data = JSON.parse(raw);
223
+ if (!data || typeof data !== 'object') continue;
224
+ const ts = Number(data.computed_at);
225
+ const tsOrMtime = Number.isFinite(ts) ? ts : fs.statSync(file).mtimeMs / 1000;
226
+ if (tsOrMtime <= bestTs) continue;
227
+ bestTs = tsOrMtime;
228
+ best = data;
229
+ } catch (e) {}
230
+ }
231
+ const headline = best && best.savings && best.savings.savings_headline;
232
+ const display = headline && headline.display;
233
+ if (display && typeof display === 'object' &&
234
+ typeof display.short === 'string' && display.short) {
235
+ return display;
236
+ }
237
+ return null;
238
+ } catch (e) {
239
+ return null;
240
+ }
241
+ }
242
+
127
243
  // Host parse (Claude Code 2.1.296 Dd/FOo): scientific notation and thousand
128
244
  // separators first, then a decimal prefix. NaN or <= 0 is invalid and IGNORED
129
245
  // (the next source applies). Mirrors measure.py _host_parse_int; shared vectors
@@ -463,7 +579,7 @@ process.stdin.on('end', () => {
463
579
  // Keep the score's value-color (green/yellow/orange/red) regardless of
464
580
  // staleness; the `~` prefix is the only stale indicator so the number
465
581
  // stays readable. (Dimming the whole score made it barely visible.)
466
- const tag = q.measured === false ? `ContextQ:~${score}` : `ContextQ:${stale ? '~' : ''}${grade}(${score})`;
582
+ const tag = q.measured === false ? `Quality ~${score}` : `Quality ${stale ? '~' : ''}${grade} ${score}`;
467
583
  if (score >= 85) {
468
584
  qScore = `${SEP}\x1b[32m${tag}${RESET}`;
469
585
  } else if (score >= 75) {
@@ -475,7 +591,7 @@ process.stdin.on('end', () => {
475
591
  }
476
592
  }
477
593
  } else {
478
- qScore = `${SEP}${DIM}ContextQ:--${RESET}`;
594
+ qScore = `${SEP}${DIM}Quality --${RESET}`;
479
595
  }
480
596
 
481
597
  const dirname = path.basename(dir);
@@ -494,7 +610,22 @@ process.stdin.on('end', () => {
494
610
  ].filter(Boolean);
495
611
 
496
612
  // ---- ROW 2: Session details ----
613
+ // The savings headline leads the row so packRows keeps it on the first
614
+ // physical line when the terminal is narrow. It comes from the status-bar
615
+ // cache (never a Python spawn) and is omitted entirely when the shared
616
+ // headline's display is null.
497
617
  const row2Parts = [];
618
+ const savingsDisplay = _statusBarHeadlineDisplay(sessionId);
619
+ let savingsSeg = null;
620
+ if (savingsDisplay) {
621
+ const label = `${savingsDisplay.short} ↗`;
622
+ const url = typeof savingsDisplay.url === 'string' && savingsDisplay.url
623
+ ? savingsDisplay.url : null;
624
+ savingsSeg = (url && _supportsOsc8())
625
+ ? `\x1b[32m\x1b]8;;${url}\x07${label}\x1b]8;;\x07${RESET}`
626
+ : `\x1b[32m${label}${RESET}`;
627
+ row2Parts.push(savingsSeg);
628
+ }
498
629
 
499
630
  // U3: near-zero-cost "resumable checkpoint" existence signal.
500
631
  // When the SessionStart pointer fired (a relevance-cleared checkpoint
@@ -510,24 +641,12 @@ process.stdin.on('end', () => {
510
641
  const flag = JSON.parse(fs.readFileSync(flagPath, 'utf8'));
511
642
  const ts = typeof flag.ts === 'number' ? flag.ts : NaN;
512
643
  if (isFinite(ts) && (Date.now() - ts) < (30 * 60 * 1000)) {
513
- row2Parts.push(`\x1b[36m⤸resumable${RESET}`);
644
+ row2Parts.push(`\x1b[36m⤸ resumable${RESET}`);
514
645
  }
515
646
  }
516
647
  }
517
648
  } catch (e) {}
518
649
 
519
- // SessionEfficiency
520
- if (q) {
521
- const se = q.session_efficiency;
522
- if (se != null) {
523
- const seScore = Math.round(se);
524
- const seGrade = q.session_efficiency_grade || gradeFor(seScore);
525
- row2Parts.push(`${DIM}Eff:${seGrade}(${seScore})${RESET}`);
526
- }
527
- } else {
528
- row2Parts.push(`${DIM}Eff:--${RESET}`);
529
- }
530
-
531
650
  // Biggest drag: the actual signal pulling the score down — context fill,
532
651
  // compactions, or the dominant waste cause — computed upstream by weighted
533
652
  // deficit, not guessed from waste keys here.
@@ -555,16 +674,11 @@ process.stdin.on('end', () => {
555
674
  }
556
675
  }
557
676
 
558
- // Recovery thresholds remain shadow-only until calibrated.
677
+ // Compactions only when there were any: "Compacts:0" announced nothing.
559
678
  if (q) {
560
679
  const c = q.compactions;
561
- if (c != null) {
562
- if (c > 0) {
563
- // Recovery evidence is shadow-only, even for older cached flags.
564
- row2Parts.push(`${DIM}Compacts:${c}(observing)${RESET}`);
565
- } else {
566
- row2Parts.push(`\x1b[32mCompacts:0${RESET}`);
567
- }
680
+ if (c != null && c > 0) {
681
+ row2Parts.push(`${DIM}compacted ${c}×${RESET}`);
568
682
  }
569
683
  }
570
684
 
@@ -580,7 +694,12 @@ process.stdin.on('end', () => {
580
694
  }
581
695
 
582
696
  // Active agents
583
- const stripAnsi = s => String(s).replace(/\x1b\[[0-9;]*[a-zA-Z]/g, '').replace(/[\x00-\x1f]/g, '');
697
+ // stripAnsi must drop OSC sequences (\x1b]…\x07 / \x1b]…\x1b\\) as well as
698
+ // CSI: the savings segment is an OSC 8 hyperlink whose raw bytes would
699
+ // otherwise count toward the packed-row width.
700
+ const stripAnsi = s => String(s)
701
+ .replace(/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/g, '')
702
+ .replace(/\x1b\[[0-9;]*[a-zA-Z]/g, '').replace(/[\x00-\x1f]/g, '');
584
703
  if (cacheMatchesSession && q.active_agents && q.active_agents.length > 0) {
585
704
  const running = q.active_agents.filter(a => a.status === 'running');
586
705
  if (running.length > 0) {
@@ -616,11 +735,13 @@ process.stdin.on('end', () => {
616
735
  pct >= 90 ? '\x1b[5;31m' : pct >= 75 ? '\x1b[38;5;208m' : pct >= 50 ? '\x1b[33m' : '\x1b[32m';
617
736
  if (fiveHour) {
618
737
  const p = Math.ceil(fiveHour.used_percentage);
619
- row2Parts.push(`${limitColor(p)}5h:${p}%${fmtReset(fiveHour.resets_at)}${RESET}`);
738
+ row2Parts.push(`${limitColor(p)}5 hours ${p}%${fmtReset(fiveHour.resets_at)}${RESET}`);
620
739
  }
621
740
  if (sevenDay) {
622
741
  const p = Math.ceil(sevenDay.used_percentage);
623
- row2Parts.push(`${DIM}7d:${p}%${RESET}`);
742
+ // Same pressure colours as the 5-hour window: a weekly limit near the
743
+ // cap is the most important number on the line, not a dim footnote.
744
+ row2Parts.push(`${limitColor(p)}week ${p}%${RESET}`);
624
745
  }
625
746
 
626
747
  // Responsive layout: when Claude Code exports COLUMNS (v2.1.153+), greedily pack
@@ -645,12 +766,18 @@ process.stdin.on('end', () => {
645
766
  // fields (row 1), never wrapped, whatever COLUMNS says.
646
767
  const _slim = (process.env.TOKEN_OPTIMIZER_STATUS_BAR_SIZE || '').trim().toLowerCase() === 'slim';
647
768
  if (_slim) {
648
- process.stdout.write(row1Segs.join(SEP));
769
+ // Slim prints row 1 only, so the savings pill is appended there or it
770
+ // would never be seen.
771
+ process.stdout.write(savingsSeg ? row1Segs.concat([savingsSeg]).join(SEP) : row1Segs.join(SEP));
649
772
  } else if (_width) {
650
773
  const rows = [...packRows(row1Segs, _width), ...packRows(row2Parts, _width)];
651
774
  process.stdout.write(rows.join('\n'));
652
775
  } else {
653
- process.stdout.write(`${row1Segs.join(SEP)}\n${row2Parts.join(SEP)}`);
776
+ // Row 2 can be legitimately empty (no savings display, no quality cache,
777
+ // no limits): emit one line rather than a dangling blank second row.
778
+ const row1Text = row1Segs.join(SEP);
779
+ const row2Text = row2Parts.join(SEP);
780
+ process.stdout.write(row2Text ? `${row1Text}\n${row2Text}` : row1Text);
654
781
  }
655
782
  } catch (e) {
656
783
  // Silent fail - never break the status line