@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
@@ -1,7 +1,6 @@
1
1
  """Definition-only implementations; mutable state belongs to measure."""
2
2
  from __future__ import annotations
3
- from . import _compat
4
-
3
+ from . import _compat, dashboard_history
5
4
 
6
5
  def _daemon_is_running():
7
6
  """Return True iff the dashboard daemon identity probe passes.
@@ -26,7 +25,6 @@ def _daemon_is_running():
26
25
  continue
27
26
  return False
28
27
 
29
-
30
28
  def _launch_opener(argv):
31
29
  """Run a browser opener detached from our terminal (#199).
32
30
 
@@ -57,7 +55,6 @@ def _launch_opener(argv):
57
55
  if rc != 0:
58
56
  raise _measure_facade.subprocess.CalledProcessError(rc, argv)
59
57
 
60
-
61
58
  def _open_in_browser(filepath):
62
59
  """Open a file in the default browser. Cross-platform.
63
60
 
@@ -82,7 +79,6 @@ def _open_in_browser(filepath):
82
79
  print("\n Could not auto-open browser. Open manually:")
83
80
  print(f" {url}")
84
81
 
85
-
86
82
  def _open_dashboard(fallback_filepath):
87
83
  """Open the dashboard, preferring the bookmarkable URL.
88
84
 
@@ -117,7 +113,6 @@ def _open_dashboard(fallback_filepath):
117
113
  # Daemon down: open the file directly
118
114
  _measure_facade._open_in_browser(fallback_filepath)
119
115
 
120
-
121
116
  def _serve_dashboard(filepath, port=None, host=None):
122
117
  """Serve the dashboard over HTTP for headless/remote access."""
123
118
  _measure_facade = _compat.facade()
@@ -128,7 +123,7 @@ def _serve_dashboard(filepath, port=None, host=None):
128
123
  filepath = _measure_facade.Path(filepath).resolve()
129
124
  serve_dir = str(filepath.parent)
130
125
  filename = filepath.name
131
-
126
+ _measure_facade._get_or_create_daemon_token()
132
127
  # Find an available port if the default is taken
133
128
  for attempt_port in range(port, port + 20):
134
129
  try:
@@ -283,7 +278,6 @@ def _serve_dashboard(filepath, port=None, host=None):
283
278
  self.send_error(413, "Request body too large")
284
279
  return
285
280
 
286
- # Read JSON body
287
281
  body = {}
288
282
  if content_len > 0:
289
283
  try:
@@ -291,6 +285,22 @@ def _serve_dashboard(filepath, port=None, host=None):
291
285
  except (_measure_facade.json.JSONDecodeError, ValueError):
292
286
  pass
293
287
 
288
+ if not isinstance(body, dict): body = {}
289
+ if path == "/api/regenerate":
290
+ choice = body.get("days", dashboard_history.load(_measure_facade.RUNTIME_DIR))
291
+ if not dashboard_history.valid(choice):
292
+ self._json_response(400, {"ok": False, "msg": "invalid history window"})
293
+ return
294
+ try:
295
+ days = dashboard_history.resolve_days(choice, _measure_facade.TRENDS_DB)
296
+ out = _measure_facade.generate_standalone_dashboard(days=days, quiet=True, force=True)
297
+ if out and "days" in body:
298
+ dashboard_history.save(_measure_facade.RUNTIME_DIR, choice)
299
+ self._json_response(200 if out else 500, {"ok": bool(out)})
300
+ except Exception:
301
+ self._json_response(500, {"ok": False, "msg": "regeneration failed"})
302
+ return
303
+
294
304
  if path == "/api/session-turns":
295
305
  raw_path = body.get("jsonl_path", "")
296
306
  if not raw_path:
@@ -436,7 +446,6 @@ def _serve_dashboard(filepath, port=None, host=None):
436
446
  except KeyboardInterrupt:
437
447
  print("\n Server stopped.")
438
448
 
439
-
440
449
  def _sanitize_dashboard_paths(data):
441
450
  """Redact home-directory prefixes from paths embedded in dashboard HTML.
442
451
 
@@ -469,7 +478,6 @@ def _sanitize_dashboard_paths(data):
469
478
 
470
479
  return data
471
480
 
472
-
473
481
  def _codex_state_summary():
474
482
  """Collect Codex runtime-state metrics for display, or None unless Codex.
475
483
 
@@ -541,7 +549,6 @@ def _codex_state_summary():
541
549
  pass
542
550
  return summary
543
551
 
544
-
545
552
  def codex_state_report(as_json=None):
546
553
  """Print the Codex runtime-state summary (subagents, memory, goals, signals)."""
547
554
  _measure_facade = _compat.facade()
@@ -612,7 +619,6 @@ def codex_state_report(as_json=None):
612
619
  f"avg compression to {comp['avg_ratio'] * 100:.0f}% of pre-compaction context")
613
620
  print()
614
621
 
615
-
616
622
  def generate_dashboard(coord_path):
617
623
  """Generate an interactive HTML dashboard from audit results."""
618
624
  _measure_facade = _compat.facade()
@@ -684,7 +690,7 @@ def generate_dashboard(coord_path):
684
690
  # Collect trends and health data
685
691
  print(" Collecting usage trends...")
686
692
  try:
687
- trends = _measure_facade._collect_trends_data(days=30)
693
+ trends = _measure_facade._collect_trends_data(days=dashboard_history.selected_days(_measure_facade.RUNTIME_DIR, _measure_facade.TRENDS_DB))
688
694
  except Exception:
689
695
  trends = None
690
696
  print(" Checking session health...")
@@ -848,13 +854,11 @@ def generate_dashboard(coord_path):
848
854
  _measure_facade._open_dashboard(fallback_filepath=out_path)
849
855
  return str(out_path)
850
856
 
851
-
852
857
  def _shell_script_path():
853
858
  """This script's resolved path, quoted to paste into Bash, PowerShell and cmd.exe."""
854
859
  _measure_facade = _compat.facade()
855
860
  return _measure_facade.shell_path(_measure_facade.Path(_measure_facade.__file__).resolve())
856
861
 
857
-
858
862
  def _measure_cli(*args):
859
863
  """The command that runs this script, for hints a user will paste into a shell.
860
864
 
@@ -869,7 +873,6 @@ def _measure_cli(*args):
869
873
  parts.extend(args)
870
874
  return " ".join(parts)
871
875
 
872
-
873
876
  def _runtime_cli(runtime, *args):
874
877
  """`_measure_cli` pinned to a runtime for hints.
875
878
 
@@ -885,7 +888,6 @@ def _runtime_cli(runtime, *args):
885
888
  parts.extend(args)
886
889
  return " ".join(parts)
887
890
 
888
-
889
891
  def _hint(text):
890
892
  """Make a printed hint pasteable from any directory.
891
893
 
@@ -897,13 +899,11 @@ def _hint(text):
897
899
  text = _measure_facade._ENV_PREFIXED_BARE_HINT.sub(lambda m: ((_measure_facade := _compat.facade()), _measure_facade._runtime_cli(m.group(1)))[1], text)
898
900
  return text.replace("python3 measure.py", _measure_facade._measure_cli())
899
901
 
900
-
901
902
  def _subagent_cache_cmd(action=None):
902
903
  """The `subagent-cache [action]` command users are told to run (advice, enable, undo)."""
903
904
  _measure_facade = _compat.facade()
904
905
  return _measure_facade._measure_cli("subagent-cache", *([action] if action else []))
905
906
 
906
-
907
907
  def _display_path(absolute_path):
908
908
  """Replace the user's home directory with ~ for display purposes.
909
909
 
@@ -918,7 +918,6 @@ def _display_path(absolute_path):
918
918
  return "~" + s[len(home):]
919
919
  return s
920
920
 
921
-
922
921
  def _collect_hook_status_for_dashboard():
923
922
  """Collect hook installation status for dashboard toggle panel."""
924
923
  _measure_facade = _compat.facade()
@@ -963,7 +962,6 @@ def _collect_hook_status_for_dashboard():
963
962
  },
964
963
  }
965
964
 
966
-
967
965
  def _collect_codex_hook_status_for_dashboard():
968
966
  """Collect Codex project hook status for dashboard toggle panel."""
969
967
  _measure_facade = _compat.facade()
@@ -1039,7 +1037,6 @@ def _collect_codex_hook_status_for_dashboard():
1039
1037
  },
1040
1038
  }
1041
1039
 
1042
-
1043
1040
  def _collect_copilot_hook_status_for_dashboard():
1044
1041
  """Hook status for the dashboard toggle panel under the Copilot runtime.
1045
1042
 
@@ -1105,7 +1102,6 @@ def _collect_copilot_hook_status_for_dashboard():
1105
1102
  },
1106
1103
  }
1107
1104
 
1108
-
1109
1105
  def _collect_cursor_hook_status_for_dashboard():
1110
1106
  """Hook status for the dashboard toggle panel under the Cursor runtime.
1111
1107
 
@@ -1160,7 +1156,6 @@ def _collect_cursor_hook_status_for_dashboard():
1160
1156
  },
1161
1157
  }
1162
1158
 
1163
-
1164
1159
  def _collect_grok_hook_status_for_dashboard():
1165
1160
  """Hook status for the dashboard toggle panel under the Grok Build runtime.
1166
1161
 
@@ -1211,7 +1206,6 @@ def _collect_grok_hook_status_for_dashboard():
1211
1206
  },
1212
1207
  }
1213
1208
 
1214
-
1215
1209
  def _collect_hermes_hook_status_for_dashboard():
1216
1210
  """Collect Hermes plugin hook status for dashboard toggle panel.
1217
1211
 
@@ -1266,7 +1260,6 @@ def _collect_hermes_hook_status_for_dashboard():
1266
1260
  },
1267
1261
  }
1268
1262
 
1269
-
1270
1263
  def _collect_antigravity_hook_status_for_dashboard():
1271
1264
  """Antigravity plugin hook status for the dashboard toggle panel.
1272
1265
 
@@ -1325,7 +1318,6 @@ def _collect_antigravity_hook_status_for_dashboard():
1325
1318
  },
1326
1319
  }
1327
1320
 
1328
-
1329
1321
  def _parse_skill_frontmatter(path: Path) -> dict:
1330
1322
  _measure_facade = _compat.facade()
1331
1323
  try:
@@ -1355,7 +1347,6 @@ def _parse_skill_frontmatter(path: Path) -> dict:
1355
1347
  meta["body_tokens"] = _measure_facade._estimate_tokens(text)
1356
1348
  return meta
1357
1349
 
1358
-
1359
1350
  def _collect_codex_skill_inventory(cfg: dict, *, project: Path) -> dict[str, list[dict]]:
1360
1351
  _measure_facade = _compat.facade()
1361
1352
  disabled_paths = set()
@@ -1469,7 +1460,6 @@ def _collect_codex_skill_inventory(cfg: dict, *, project: Path) -> dict[str, lis
1469
1460
  disabled.sort(key=lambda item: ((_measure_facade := _compat.facade()), (item["source"], item["name"]))[1])
1470
1461
  return {"active": active, "disabled": disabled}
1471
1462
 
1472
-
1473
1463
  def _collect_codex_mcp_inventory(cfg: dict) -> list[dict]:
1474
1464
  _measure_facade = _compat.facade()
1475
1465
  servers = cfg.get("mcp_servers")
@@ -1494,7 +1484,6 @@ def _collect_codex_mcp_inventory(cfg: dict) -> list[dict]:
1494
1484
  })
1495
1485
  return sorted(items, key=lambda item: ((_measure_facade := _compat.facade()), item["name"])[1])
1496
1486
 
1497
-
1498
1487
  def _collect_codex_plugin_inventory(cfg: dict) -> list[dict]:
1499
1488
  _measure_facade = _compat.facade()
1500
1489
  plugins = cfg.get("plugins")
@@ -1508,12 +1497,10 @@ def _collect_codex_plugin_inventory(cfg: dict) -> list[dict]:
1508
1497
  items.append({"name": name, "enabled": enabled})
1509
1498
  return sorted(items, key=lambda item: ((_measure_facade := _compat.facade()), item["name"])[1])
1510
1499
 
1511
-
1512
1500
  def _codex_config_path() -> Path:
1513
1501
  _measure_facade = _compat.facade()
1514
1502
  return _measure_facade.runtime_home() / "config.toml"
1515
1503
 
1516
-
1517
1504
  def _safe_codex_config_path() -> Path:
1518
1505
  _measure_facade = _compat.facade()
1519
1506
  home = _measure_facade.runtime_home().resolve(strict=False)
@@ -1530,7 +1517,6 @@ def _safe_codex_config_path() -> Path:
1530
1517
  parent.mkdir(mode=0o700)
1531
1518
  return path
1532
1519
 
1533
-
1534
1520
  def _codex_config_lock():
1535
1521
  """Bounded portable lease for config.toml writes.
1536
1522
 
@@ -1547,7 +1533,6 @@ def _codex_config_lock():
1547
1533
  ) as acquired:
1548
1534
  yield acquired
1549
1535
 
1550
-
1551
1536
  def _skill_mgmt_lock():
1552
1537
  """Bounded portable lease serializing skill archive/restore mutations.
1553
1538
 
@@ -2278,6 +2263,8 @@ def generate_standalone_dashboard(days=None, quiet=None, force=None):
2278
2263
  # version-mismatch regen path so a freshly-updated plugin always
2279
2264
  # wins over a recently-written stale file.
2280
2265
  _measure_facade = _compat.facade()
2266
+ if days is None:
2267
+ days = dashboard_history.resolve_days(dashboard_history.load(_measure_facade.RUNTIME_DIR), _measure_facade.TRENDS_DB)
2281
2268
  if quiet and not force and _measure_facade.DASHBOARD_PATH.exists():
2282
2269
  try:
2283
2270
  age = _measure_facade.time.time() - _measure_facade.DASHBOARD_PATH.stat().st_mtime
@@ -2659,8 +2646,32 @@ def _dispatch_dashboard(args):
2659
2646
  print(f"[Error] Invalid --port value: {args[i + 1]}")
2660
2647
  _measure_facade.sys.exit(1)
2661
2648
  serve = True
2649
+
2650
+ def _note_hook_bounded():
2651
+ """One stderr line when this run is bounded as a hook.
2652
+
2653
+ A piped-stdin invocation (an agent's shell tool, a runner script) is
2654
+ indistinguishable from a real hook, so the 20s budget can kill a heavy
2655
+ rebuild and the run exits 1 with no explanation -- the "dashboard
2656
+ quietly skips itself" report. Real hook launchers pass --quiet, so
2657
+ gating on it keeps hook logs clean while every non-quiet bounded run
2658
+ says why and names the --user escape hatch. stderr only: stdout stays
2659
+ clean for the `Dashboard:` line consumers parse.
2660
+ """
2661
+ if "--quiet" in args or "-q" in args:
2662
+ return
2663
+ print(
2664
+ "[Token Optimizer] dashboard: stdin is not a terminal, so this run "
2665
+ "is treated as a hook and the rebuild is capped at a "
2666
+ f"{_measure_facade._dashboard_hook_budget_seconds():g}s budget; it "
2667
+ "may be killed before it finishes or opens. Pass --user to force "
2668
+ "an interactive run.",
2669
+ file=_measure_facade.sys.stderr,
2670
+ )
2671
+
2662
2672
  if not cp:
2663
- days = 30
2673
+ choice = dashboard_history.load(_measure_facade.RUNTIME_DIR)
2674
+ explicit = False
2664
2675
  quiet = "--quiet" in args or "-q" in args
2665
2676
  # --force bypasses the 60s write throttle. The detached version-bump
2666
2677
  # self-heal passes it so a stale file just written by a killed regen
@@ -2669,12 +2680,20 @@ def _dispatch_dashboard(args):
2669
2680
  for i, a in enumerate(args):
2670
2681
  if a == "--days" and i + 1 < len(args):
2671
2682
  try:
2672
- days = int(args[i + 1])
2683
+ choice = 'all' if args[i + 1] == 'all' else int(args[i + 1])
2684
+ if not dashboard_history.valid(choice):
2685
+ raise ValueError()
2686
+ explicit = True
2673
2687
  except ValueError:
2674
- pass
2688
+ print("[Error] --days must be a positive integer or all")
2689
+ _measure_facade.sys.exit(1)
2690
+ days = dashboard_history.resolve_days(choice, _measure_facade.TRENDS_DB)
2691
+ force = force or explicit
2675
2692
  deadline = (
2676
2693
  None if (serve or not _measure_facade._running_under_hook()) else _measure_facade._install_hook_budget(_measure_facade._dashboard_hook_budget_seconds())
2677
2694
  )
2695
+ if deadline is not None:
2696
+ _note_hook_bounded()
2678
2697
  timed_out = False
2679
2698
  try:
2680
2699
  lock = (_measure_facade._dashboard_selfheal_build_lock()
@@ -2698,6 +2717,11 @@ def _dispatch_dashboard(args):
2698
2717
  # applies, so a forced heal never clobbers a newer dashboard).
2699
2718
  if timed_out:
2700
2719
  _measure_facade._spawn_detached_dashboard_selfheal(days=days, force=force)
2720
+ if out and explicit and not _measure_facade.os.environ.get("TOKEN_OPTIMIZER_DASHBOARD_SELFHEAL"):
2721
+ try:
2722
+ dashboard_history.save(_measure_facade.RUNTIME_DIR, choice)
2723
+ except OSError:
2724
+ pass
2701
2725
  if out and serve:
2702
2726
  _measure_facade._serve_dashboard(out, port=serve_port, host=serve_host)
2703
2727
  elif out and not quiet:
@@ -2706,6 +2730,8 @@ def _dispatch_dashboard(args):
2706
2730
  deadline = (
2707
2731
  None if (serve or not _measure_facade._running_under_hook()) else _measure_facade._install_hook_budget(_measure_facade._dashboard_hook_budget_seconds())
2708
2732
  )
2733
+ if deadline is not None:
2734
+ _note_hook_bounded()
2709
2735
  timed_out = False
2710
2736
  try:
2711
2737
  out = _measure_facade.generate_dashboard(cp)
@@ -0,0 +1,79 @@
1
+ """Persist the dashboard's embedded history window across rebuilds."""
2
+ import json
3
+ import os
4
+ import sqlite3
5
+ import tempfile
6
+ from datetime import date
7
+ from pathlib import Path
8
+
9
+ DEFAULT_DAYS = 30
10
+
11
+
12
+ def valid(value):
13
+ return value == 'all' or (type(value) is int and 1 <= value <= 365000)
14
+
15
+
16
+ def load(runtime_dir):
17
+ try:
18
+ path = Path(runtime_dir) / 'token-optimizer' / 'dashboard-history.json'
19
+ if path.is_symlink() or path.stat().st_size > 1024:
20
+ return DEFAULT_DAYS
21
+ value = json.loads(path.read_text(encoding='utf-8')).get('days')
22
+ return value if valid(value) else DEFAULT_DAYS
23
+ except (OSError, ValueError, AttributeError):
24
+ return DEFAULT_DAYS
25
+
26
+
27
+ def save(runtime_dir, value):
28
+ if not valid(value):
29
+ raise ValueError('invalid dashboard history window')
30
+ path = Path(runtime_dir) / 'token-optimizer' / 'dashboard-history.json'
31
+ path.parent.mkdir(parents=True, exist_ok=True)
32
+ fd, name = tempfile.mkstemp(prefix='.history-', dir=str(path.parent))
33
+ try:
34
+ with os.fdopen(fd, 'w', encoding='utf-8') as handle:
35
+ json.dump({'days': value}, handle)
36
+ os.replace(name, path)
37
+ finally:
38
+ if os.path.exists(name):
39
+ os.unlink(name)
40
+
41
+
42
+ def resolve_days(value, db_path, today=None):
43
+ if value != 'all':
44
+ return value if valid(value) else DEFAULT_DAYS
45
+ today = today or date.today()
46
+ earliest = None
47
+ try:
48
+ # URI mode=ro prevents an absent DB from being created as a side effect.
49
+ uri = Path(db_path).resolve().as_uri() + '?mode=ro'
50
+ with sqlite3.connect(uri, uri=True) as conn:
51
+ columns = {row[1] for row in conn.execute('PRAGMA table_info(session_log)')}
52
+ for column in ('date', 'first_activity_day'):
53
+ if column in columns:
54
+ value = conn.execute('SELECT MIN(' + column + ') FROM session_log').fetchone()[0]
55
+ if value:
56
+ day = date.fromisoformat(value[:10])
57
+ earliest = day if earliest is None else min(earliest, day)
58
+ # Older databases may not yet have activity bounds. Inspect their
59
+ # daily maps so an older day is not hidden by the session date.
60
+ for column in ('daily_usage_json', 'parent_daily_usage_json', 'daily_calls_json'):
61
+ if column not in columns:
62
+ continue
63
+ condition = ' WHERE first_activity_day IS NULL' if 'first_activity_day' in columns else ''
64
+ for (raw,) in conn.execute('SELECT ' + column + ' FROM session_log' + condition):
65
+ try:
66
+ for key in json.loads(raw or '{}'):
67
+ day = date.fromisoformat(key)
68
+ earliest = day if earliest is None else min(earliest, day)
69
+ except (ValueError, TypeError):
70
+ continue
71
+ except (OSError, sqlite3.Error, ValueError, TypeError):
72
+ pass
73
+ # A missing or old DB falls back to a broad window for JSONL discovery.
74
+ earliest = earliest or date(1900, 1, 1)
75
+ return max(DEFAULT_DAYS, (today - earliest).days + 1)
76
+
77
+
78
+ def selected_days(runtime_dir, db_path):
79
+ return resolve_days(load(runtime_dir), db_path)
@@ -1,7 +1,6 @@
1
1
  """Definition-only implementations; mutable state belongs to measure."""
2
2
  from __future__ import annotations
3
- from . import _compat
4
-
3
+ from . import _compat, dashboard_history
5
4
 
6
5
  def _settings_lock(user_initiated=None):
7
6
  """Bounded portable lease for settings.json writes.
@@ -25,7 +24,6 @@ def _settings_lock(user_initiated=None):
25
24
  ) as acquired:
26
25
  yield acquired
27
26
 
28
-
29
27
  def _acquire_session_end_flush_lock(max_age_seconds=None):
30
28
  """Return a lock directory path, or None if another worker is active."""
31
29
  _measure_facade = _compat.facade()
@@ -50,7 +48,6 @@ def _acquire_session_end_flush_lock(max_age_seconds=None):
50
48
  except OSError:
51
49
  return None
52
50
 
53
-
54
51
  def _release_session_end_flush_lock(lock_dir):
55
52
  _measure_facade = _compat.facade()
56
53
  if not lock_dir:
@@ -259,7 +256,7 @@ def _run_session_end_flush_worker(args, budget_seconds=None):
259
256
  # No browser in a cloud VM: the 4 MB dashboard rebuild is skipped
260
257
  # there (an explicit /token-dashboard still builds it on demand).
261
258
  if not _lean and not (_measure_facade._dashboard_hook_backoff_active() or _measure_facade._dashboard_selfheal_inflight()):
262
- _measure_facade.generate_standalone_dashboard(days=30, quiet=True)
259
+ _measure_facade.generate_standalone_dashboard(quiet=True)
263
260
  except _measure_facade._HookTimeout:
264
261
  # Gap 4: the bounded SessionEnd regen was killed by the 20s budget
265
262
  # (a large history's 4 MB build does not fit), so it may have left
@@ -268,7 +265,7 @@ def _run_session_end_flush_worker(args, budget_seconds=None):
268
265
  # file catches up off the hot path instead of waiting for the user
269
266
  # to re-open. Re-raised so the outer handler still runs cleanup.
270
267
  try:
271
- _measure_facade._spawn_detached_dashboard_selfheal(days=30)
268
+ _measure_facade._spawn_detached_dashboard_selfheal()
272
269
  except Exception:
273
270
  pass
274
271
  raise
@@ -667,6 +664,8 @@ def _spawn_detached_dashboard_selfheal(days=None, force=None, *, hook_timeout=No
667
664
  # Detach so the child outlives the killed hook: POSIX new session, or
668
665
  # (on Windows) DETACHED_PROCESS. start_new_session is POSIX-only.
669
666
  popen_kw = {} if _measure_facade.os.name == "nt" else {"start_new_session": True}
667
+ if days is None:
668
+ days = dashboard_history.selected_days(_measure_facade.RUNTIME_DIR, _measure_facade.TRENDS_DB)
670
669
  argv = [_measure_facade.sys.executable, _measure_facade.os.path.abspath(_measure_facade.__file__),
671
670
  "dashboard", "--quiet", "--days", str(int(days))]
672
671
  if force:
@@ -5092,7 +5091,7 @@ def run_ensure_health():
5092
5091
  # already uses; _dashboard_heal_spawn_due() fails OPEN so a lock
5093
5092
  # glitch never skips the heal.
5094
5093
  try:
5095
- _measure_facade._spawn_detached_dashboard_selfheal(days=30, force=True, hook_timeout=False)
5094
+ _measure_facade._spawn_detached_dashboard_selfheal(force=True, hook_timeout=False)
5096
5095
  print(f" [Token Optimizer] Refreshing dashboard to v{_measure_facade.TOKEN_OPTIMIZER_VERSION} (background)", file=_measure_facade.sys.stderr)
5097
5096
  except Exception as _e:
5098
5097
  print(f" [Token Optimizer] dashboard refresh failed: {_e}", file=_measure_facade.sys.stderr)