@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
@@ -5223,7 +5223,7 @@ def _session_weight_pool_savings(cutoff, days=None, tier=None, activity_window=N
5223
5223
  "{then_n:,} in {month}, {growth:.1f}x, at about the same total spend) -- "
5224
5224
  "that extra capacity is real, but it is capacity gained, not dollars saved, "
5225
5225
  "so it is not in the headline. Model price/mix drift worth about "
5226
- "${drift:,.0f}/mo is also excluded: it would have happened without Token "
5226
+ "${drift:,.0f} this period is also excluded: it would have happened without Token "
5227
5227
  "Optimizer."
5228
5228
  + ("" if pinned else " The anchor month already had partial Token Optimizer "
5229
5229
  "coverage, so if anything this understates the full pre-tool gap.")
@@ -5249,6 +5249,7 @@ def _session_weight_pool_savings(cutoff, days=None, tier=None, activity_window=N
5249
5249
  "counterfactual_usd": counterfactual,
5250
5250
  "transformation_usd": transformation,
5251
5251
  "crosscheck": crosscheck,
5252
+ "coverage": now.get("coverage"),
5252
5253
  "engine_priced_transformation_usd": engine_transformation,
5253
5254
  "engine_priced_actual_usd": n_usd,
5254
5255
  "price_mix_drift_usd": price_mix_drift,
@@ -5265,61 +5266,9 @@ def _session_weight_pool_savings(cutoff, days=None, tier=None, activity_window=N
5265
5266
 
5266
5267
 
5267
5268
  def _price_parent_activity_window(conn, start, end, tier):
5268
- """Use real in-window activity with the standard parent/child pricing rules.
5269
-
5270
- Reading transcripts here also keeps a weekly report correct while bounded
5271
- background collection catches up. Missing files produce an unavailable
5272
- estimate instead of silently treating missing work as zero cost.
5273
- """
5274
- _measure_facade = _compat.facade()
5275
- paths = conn.execute(
5276
- "SELECT jsonl_path, date FROM session_log WHERE input_tokens IS NOT NULL "
5277
- "AND COALESCE(is_sidechain,0)=0").fetchall()
5278
- # Include new sessions before bounded collection reaches them.
5279
- known = {str(name) for name, _ in paths}
5280
- for path, _mtime, _ in _measure_facade._find_all_jsonl_files(None):
5281
- if str(path) not in known:
5282
- paths.append((str(path), ""))
5283
- known.add(str(path))
5284
- rows = []
5285
- request_ledger = {} # a request repeated in another transcript counts once (largest usage)
5286
- for name, recorded_date in paths:
5287
- path = _measure_facade.Path(name)
5288
- if not path.exists():
5289
- if recorded_date and str(recorded_date) < start.date().isoformat():
5290
- continue
5291
- return None
5292
- children = _measure_facade._find_subagent_jsonl_files(path)
5293
- parsed = _measure_facade._parse_session_jsonl(path, window_start=start, window_end=end)
5294
- if parsed and parsed.get("is_sidechain"):
5295
- continue
5296
- if parsed:
5297
- parsed = _measure_facade._parsed_net_of_ledger(parsed, request_ledger)
5298
- if not parsed:
5299
- parsed = {"total_input_tokens": 0, "total_output_tokens": 0,
5300
- "total_cache_create_1h": 0, "total_cache_create_5m": 0,
5301
- "cache_hit_rate": 0, "model_usage": {}, "api_calls": 0,
5302
- "message_count": 0}
5303
- inp, out = parsed["total_input_tokens"], parsed["total_output_tokens"]
5304
- cw1, cw5 = parsed["total_cache_create_1h"], parsed["total_cache_create_5m"]
5305
- child_cache_read = 0
5306
- for child in children:
5307
- cp = _measure_facade._parse_session_jsonl(child, window_start=start, window_end=end)
5308
- if cp:
5309
- cp = _measure_facade._parsed_net_of_ledger(cp, request_ledger)
5310
- inp += cp["total_input_tokens"]
5311
- out += cp["total_output_tokens"]
5312
- cw1 += cp["total_cache_create_1h"]
5313
- cw5 += cp["total_cache_create_5m"]
5314
- child_cache_read += cp["total_cache_read"]
5315
- if not parsed["api_calls"] and inp + out == 0:
5316
- continue
5317
- usage = _measure_facade.json.dumps(parsed["model_usage"])
5318
- hit = (parsed["cache_hit_rate"] if parsed["api_calls"] else
5319
- child_cache_read / inp if inp else 0)
5320
- rows.append((inp, out, cw5, cw1, hit, usage, usage,
5321
- parsed["api_calls"], parsed["message_count"]))
5322
- return _measure_facade._price_parent_rows(rows, tier)
5269
+ """Price in-window activity and disclose incomplete transcript coverage."""
5270
+ from . import weekly_activity
5271
+ return weekly_activity.price(_compat.facade(), conn, start, end, tier)
5323
5272
 
5324
5273
 
5325
5274
  def _weekly_full_savings(resets_at=None, now=None):
@@ -5348,7 +5297,7 @@ def _weekly_full_savings(resets_at=None, now=None):
5348
5297
  age = end.timestamp() - float(cached["computed_at"])
5349
5298
  if (0 <= age < 60 and cached["start"] == start.isoformat()
5350
5299
  and cached["anchor_stamp"] == anchor_stamp
5351
- and cached.get("activity_basis") == 1
5300
+ and cached.get("activity_basis") == 2
5352
5301
  and cached["version"] == _measure_facade.TOKEN_OPTIMIZER_VERSION):
5353
5302
  return _measure_facade._positive_full_value(cached["value"])
5354
5303
  except (OSError, ValueError, TypeError, KeyError):
@@ -5369,13 +5318,14 @@ def _weekly_full_savings(resets_at=None, now=None):
5369
5318
  "uncapped_usd": round(pool["transformation_usd"], 2),
5370
5319
  "actual_usd": round(pool["actual_usd"], 2),
5371
5320
  "counterfactual_usd": round(pool["counterfactual_usd"], 2),
5372
- "api_calls": pool["now_units"], "anchor_month": pool["anchor_month"]}
5321
+ "api_calls": pool["now_units"], "anchor_month": pool["anchor_month"],
5322
+ "coverage": pool.get("coverage")}
5373
5323
  if now is None:
5374
5324
  try:
5375
5325
  _measure_facade._write_baseline_state(cache_path, {
5376
5326
  "computed_at": end.timestamp(), "start": start.isoformat(),
5377
5327
  "anchor_stamp": anchor_path.stat().st_mtime_ns if anchor_path.exists() else None,
5378
- "activity_basis": 1,
5328
+ "activity_basis": 2,
5379
5329
  "version": _measure_facade.TOKEN_OPTIMIZER_VERSION, "value": value})
5380
5330
  except OSError:
5381
5331
  pass
@@ -7051,7 +7001,7 @@ def savings_report(days=None, as_json=None):
7051
7001
  if float(ba.get("monthly_savings_usd", 0.0) or 0.0) > 0:
7052
7002
  wp = ba.get("session_weight_pool") or None
7053
7003
  print()
7054
- print(f" YOUR TRANSFORMATION: ~${ba['monthly_savings_usd']:,.0f}/mo")
7004
+ print(f" YOUR TRANSFORMATION: ~${ba['monthly_savings_usd']:,.0f} over {days} days")
7055
7005
  # Spend cap disclosure: when the counterfactual exceeds actual spend,
7056
7006
  # the headline is capped and the user must see why, not wonder why the
7057
7007
  # number stopped moving.
@@ -7080,7 +7030,7 @@ def savings_report(days=None, as_json=None):
7080
7030
  f"the old way) [estimated]")
7081
7031
  drift = float(wp.get("price_mix_drift_usd", 0.0) or 0.0)
7082
7032
  if abs(drift) >= 1.0:
7083
- print(f" Not claimed: ~${abs(drift):,.0f}/mo of model price/mix drift "
7033
+ print(f" Not claimed: ~${abs(drift):,.0f} this period of model price/mix drift "
7084
7034
  f"({'cheaper' if drift >= 0 else 'costlier'} models would have moved "
7085
7035
  f"your bill without Token Optimizer).")
7086
7036
  cross = wp.get("crosscheck") or {}
@@ -7092,11 +7042,11 @@ def savings_report(days=None, as_json=None):
7092
7042
  if isinstance(gap, (int, float)) else "")
7093
7043
  if _measure_facade._crosscheck_verdict(wp):
7094
7044
  print(f" Cross-check on {cross_unit}: "
7095
- f"{_measure_facade._signed_usd(cross_usd)}/mo "
7045
+ f"{_measure_facade._signed_usd(cross_usd)} this period "
7096
7046
  f"(independent unit, agrees within ~10%{gap_txt}).")
7097
7047
  else:
7098
7048
  print(f" Cross-check on {cross_unit}: "
7099
- f"{_measure_facade._signed_usd(cross_usd)}/mo "
7049
+ f"{_measure_facade._signed_usd(cross_usd)} this period "
7100
7050
  f"(independent unit, does not agree{gap_txt}).")
7101
7051
  else:
7102
7052
  print(f" Had you worked the way you did before Token Optimizer "
@@ -7111,7 +7061,7 @@ def savings_report(days=None, as_json=None):
7111
7061
  for lev in ba_breakdown:
7112
7062
  amt = float(lev.get("monthly_usd", 0) or 0)
7113
7063
  sign = "-" if amt < 0 else " "
7114
- print(f" {sign}${abs(amt):>8,.0f}/mo {lev.get('label', lev.get('key', ''))}")
7064
+ print(f" {sign}${abs(amt):>8,.0f} this period {lev.get('label', lev.get('key', ''))}")
7115
7065
  caveat = ba.get("breakdown_caveat") or ""
7116
7066
  if caveat:
7117
7067
  # Wrap the caveat so the CLI surfaces the same disclosure as the dashboard.
@@ -7122,7 +7072,7 @@ def savings_report(days=None, as_json=None):
7122
7072
  # session-weight pool delegated work is excluded from the headline entirely.
7123
7073
  prem = float(ba.get("premium_delegation_cost_usd", 0.0) or 0.0)
7124
7074
  if prem > 0:
7125
- print(f" Costlier delegation: ${prem:,.0f}/mo of premium-model "
7075
+ print(f" Costlier delegation: ${prem:,.0f} this period of premium-model "
7126
7076
  f"subagent spend. "
7127
7077
  + ("Not in the headline above (delegated work is measured separately)."
7128
7078
  if wp else "Included in the sidechain net above."))
@@ -7132,16 +7082,16 @@ def savings_report(days=None, as_json=None):
7132
7082
  print()
7133
7083
  print(" YOUR TRANSFORMATION: none to headline this period")
7134
7084
  print(f" Each request now carries more context than at your baseline "
7135
- f"(est. ${ba.get('actual_monthly_usd', 0):,.0f}/mo now vs "
7136
- f"${ba.get('counterfactual_monthly_usd', 0):,.0f}/mo at the baseline's cost "
7085
+ f"(est. ${ba.get('actual_monthly_usd', 0):,.0f} now vs "
7086
+ f"${ba.get('counterfactual_monthly_usd', 0):,.0f} this period at the baseline's cost "
7137
7087
  f"per request), so there is no whole-workload saving to headline. "
7138
7088
  f"The measured savings below are real and counted.")
7139
7089
  elif ba.get("reason") == "flat":
7140
7090
  print()
7141
7091
  print(" YOUR TRANSFORMATION: no measurable change this period")
7142
7092
  print(f" Cost per unit of work is about the same as before install "
7143
- f"(est. ${ba.get('actual_monthly_usd', 0):,.0f}/mo now vs "
7144
- f"${ba.get('counterfactual_monthly_usd', 0):,.0f}/mo the old way). "
7093
+ f"(est. ${ba.get('actual_monthly_usd', 0):,.0f} now vs "
7094
+ f"${ba.get('counterfactual_monthly_usd', 0):,.0f} this period the old way). "
7145
7095
  f"The savings below are counted action by action.")
7146
7096
  elif ba.get("reason") == "methods_disagree":
7147
7097
  # The two independent work-unit methods could not be reconciled, so the
@@ -7157,7 +7107,7 @@ def savings_report(days=None, as_json=None):
7157
7107
  print()
7158
7108
  print(" YOUR TRANSFORMATION: not headlined this period")
7159
7109
  print(f" The {main_unit} and {cross_unit} methods disagree "
7160
- f"({_measure_facade._signed_usd(main_usd)}/mo vs {_measure_facade._signed_usd(cross_usd)}/mo), "
7110
+ f"({_measure_facade._signed_usd(main_usd)} vs {_measure_facade._signed_usd(cross_usd)} this period), "
7161
7111
  f"so neither is headlined. The measured savings below are real "
7162
7112
  f"and counted.")
7163
7113
 
@@ -2377,7 +2377,7 @@ def _grok_summary():
2377
2377
  print(f" Cost: ~${total_cost:,.2f} ({cost_known} session(s) with authoritative cost)")
2378
2378
  else:
2379
2379
  print(" Cost: no authoritative billing data recorded (costUsdTicks scrubbed)")
2380
- print(f" Tokens: {total_in:,} in / {total_out:,} out")
2380
+ print(f" Tokens: {total_in:,} in / {total_out:,} out" + (f" (includes {estimated} estimated sessions)" if estimated else ""))
2381
2381
  if top_models:
2382
2382
  print(" Models: " + ", ".join(f"{_measure_facade._strip_ansi(str(m))} ({v:,})" for m, v in top_models))
2383
2383
  if incomplete:
@@ -2593,7 +2593,7 @@ def _copilot_summary():
2593
2593
  print(f" Cost: ~${total_cost:,.2f} (premium requests)")
2594
2594
  else:
2595
2595
  print(" Cost: no billing data recorded by Copilot for these sessions")
2596
- print(f" Tokens: {total_in:,} in / {total_out:,} out")
2596
+ print(f" Tokens: {total_in:,} in / {total_out:,} out" + (f" (includes {estimated} estimated sessions)" if estimated else ""))
2597
2597
  if top_models:
2598
2598
  print(" Models: " + ", ".join(f"{_measure_facade._strip_ansi(str(m))} ({v:,})" for m, v in top_models))
2599
2599
  if incomplete:
@@ -2819,13 +2819,9 @@ def _write_cursor_restore_context(sessions, quiet=None):
2819
2819
  import tempfile # noqa: PLC0415
2820
2820
 
2821
2821
  from runtime_env import cursor_home as _ch # noqa: PLC0415
2822
-
2823
- # Group the most recent COMPLETE session per workspace root. The key
2824
- # must match what the sessionStart hook looks up: workspace_roots[0]
2825
- # (the repo root Cursor exports) first, then cwd as a fallback. Using
2826
- # cwd alone would key the file by a tool's working_directory (often a
2827
- # subdirectory) while sessionStart looks up the repo root — a silent
2828
- # never-match.
2822
+ from cursor_bridge_checkpoint import normalize_workspace # noqa: PLC0415
2823
+ from datetime import datetime # noqa: PLC0415
2824
+ # Match sessionStart's workspace root and source-session end time.
2829
2825
  by_ws: dict = {}
2830
2826
  for s in sessions:
2831
2827
  if s.get("incomplete"):
@@ -2837,19 +2833,21 @@ def _write_cursor_restore_context(sessions, quiet=None):
2837
2833
  root = str(s.get("cwd") or s.get("slug") or "")
2838
2834
  if not root:
2839
2835
  continue
2840
- by_ws.setdefault(root, []).append(s)
2841
-
2836
+ by_ws.setdefault(normalize_workspace(root), []).append(s)
2842
2837
  def _clean(value):
2843
2838
  _measure_facade = _compat.facade()
2844
2839
  text = str(value or "")
2845
2840
  text = "".join(ch for ch in text if ch == " " or ch.isprintable())
2846
2841
  return text[:200]
2847
-
2848
2842
  base = _ch() / "token-optimizer" / "restore-context"
2849
2843
  base.mkdir(parents=True, exist_ok=True)
2850
2844
  for root, group in by_ws.items():
2851
- latest = max(group, key=lambda s: ((_measure_facade := _compat.facade()), (s.get("first_ts") is not None, s.get("first_ts") or ""))[1])
2852
- lines = [f"[Token Optimizer] Continuity from your previous Cursor session in {_clean(root)}:"]
2845
+ latest = max(group, key=lambda s: (s.get("last_ts") is not None, s.get("last_ts") or ""))
2846
+ try:
2847
+ end_ts = datetime.fromisoformat(str(latest.get("last_ts") or "").replace("Z", "+00:00")).timestamp()
2848
+ except (ValueError, OverflowError):
2849
+ continue
2850
+ lines = [f"<!-- source-end: {end_ts} -->", f"[Token Optimizer] Continuity from your previous Cursor session in {_clean(root)}:"]
2853
2851
  if latest.get("model"):
2854
2852
  lines.append(
2855
2853
  f"- Model: {_clean(latest['model'])}; "
@@ -2884,8 +2882,34 @@ def _cursor_summary():
2884
2882
  import cursor_state as _cst # noqa: PLC0415
2885
2883
 
2886
2884
  home = _ch() if _ch is not None else _measure_facade.Path.home() / ".cursor"
2887
- tallies = [t for p in _cst.find_tallies(home) if (t := _cst.read_tally(p)) is not None]
2888
- normalized = [s for t in tallies if (s := _measure_facade.cursor_session.normalize_session(t))]
2885
+ tallies = []
2886
+ for p in _cst.find_tallies(home):
2887
+ t = _cst.read_tally(p)
2888
+ if t is not None:
2889
+ tallies.append(_cst.idle_finalise(t))
2890
+
2891
+ # Resolve the same token sources _collect_cursor_sessions uses: raw tally
2892
+ # JSON never carries bubble_tokens/transcript_tokens, so without this the
2893
+ # summary always reports 0 tokens and mislabels every session "estimated".
2894
+ composer_ids = [
2895
+ str(t.get("conversation_id") or t.get("session_id") or "") for t in tallies
2896
+ ]
2897
+ try:
2898
+ bubble_tokens = _cst.read_state_vscdb_tokens(composer_ids, db_path=_cst.state_vscdb_path_for_home(home))
2899
+ except Exception:
2900
+ bubble_tokens = {}
2901
+ normalized = []
2902
+ for t in tallies:
2903
+ t = dict(t)
2904
+ cid = str(t.get("conversation_id") or t.get("session_id") or "")
2905
+ t["bubble_tokens"] = bubble_tokens.get(cid)
2906
+ try:
2907
+ t["transcript_tokens"] = _cst.transcript_estimate(t.get("transcript_path"), home)
2908
+ except Exception:
2909
+ t["transcript_tokens"] = None
2910
+ s = _measure_facade.cursor_session.normalize_session(t)
2911
+ if s is not None:
2912
+ normalized.append(s)
2889
2913
 
2890
2914
  print("Token Optimizer — Cursor summary")
2891
2915
  if not normalized:
@@ -2899,7 +2923,12 @@ def _cursor_summary():
2899
2923
  total_in = sum(s.get("total_input_tokens", 0) for s in normalized)
2900
2924
  total_out = sum(s.get("total_output_tokens", 0) for s in normalized)
2901
2925
  incomplete = sum(1 for s in normalized if s.get("incomplete"))
2902
- estimated = sum(1 for s in normalized if s.get("estimated"))
2926
+ token_sources = {}
2927
+ for s in normalized:
2928
+ src = s.get("token_source") or "unknown"
2929
+ token_sources[src] = token_sources.get(src, 0) + 1
2930
+ estimated = token_sources.get("cursor_transcript_estimate", 0)
2931
+ unknown_tokens = token_sources.get("cursor_tally_only", 0)
2903
2932
  compactions = sum(s.get("compactions", 0) for s in normalized)
2904
2933
  surfaces = {}
2905
2934
  for s in normalized:
@@ -2907,7 +2936,11 @@ def _cursor_summary():
2907
2936
  surfaces[sur] = surfaces.get(sur, 0) + 1
2908
2937
 
2909
2938
  print(f" {len(normalized)} session(s)")
2910
- print(f" Tokens: {total_in:,} in / {total_out:,} out")
2939
+ print(f" Tokens: {total_in:,} in / {total_out:,} out" + (f" (includes {estimated} estimated sessions)" if estimated else ""))
2940
+ if token_sources:
2941
+ print(" Token sources: " + ", ".join(
2942
+ f"{k} ({v})" for k, v in sorted(token_sources.items())
2943
+ ))
2911
2944
  if compactions:
2912
2945
  print(f" Compactions captured: {compactions}")
2913
2946
  if surfaces:
@@ -2917,7 +2950,12 @@ def _cursor_summary():
2917
2950
  if estimated:
2918
2951
  print(
2919
2952
  f" {estimated} session(s) use estimated token counts "
2920
- "(state.vscdb tokenCount is best-effort; transcripts carry no usage)"
2953
+ "(transcript chars-over-four; state.vscdb tokenCount is best-effort)"
2954
+ )
2955
+ if unknown_tokens:
2956
+ print(
2957
+ f" {unknown_tokens} session(s) have no token figures "
2958
+ "(tally only) — unknown, not zero"
2921
2959
  )
2922
2960
  print()
2923
2961
  print(" Cost: Cursor stores no local billing data — no savings headline is")
@@ -2972,7 +3010,7 @@ def _collect_cursor_sessions(days=None, quiet=None, rebuild=None):
2972
3010
  str(t.get("conversation_id") or t.get("session_id") or "") for t in tallies
2973
3011
  ]
2974
3012
  try:
2975
- bubble_tokens = _cst.read_state_vscdb_tokens(composer_ids)
3013
+ bubble_tokens = _cst.read_state_vscdb_tokens(composer_ids, db_path=_cst.state_vscdb_path_for_home(home))
2976
3014
  except Exception:
2977
3015
  bubble_tokens = {}
2978
3016
 
@@ -0,0 +1,69 @@
1
+ """Price a weekly activity window while reporting missing transcript coverage."""
2
+
3
+
4
+ def price(facade, conn, start, end, tier):
5
+ paths = conn.execute(
6
+ "SELECT jsonl_path, date, last_activity_day, cost_usd FROM session_log "
7
+ "WHERE input_tokens IS NOT NULL AND COALESCE(is_sidechain,0)=0").fetchall()
8
+ known = {str(row[0]) for row in paths}
9
+ for path, _mtime, _ in facade._find_all_jsonl_files(None):
10
+ if str(path) not in known:
11
+ paths.append((str(path), '', None, None))
12
+ known.add(str(path))
13
+ rows, missing = [], 0
14
+ costs, missing_cost, cost_complete = 0.0, 0.0, True
15
+ request_ledger = {}
16
+ for name, recorded_date, last_day, recorded_cost in paths:
17
+ path = facade.Path(name)
18
+ if not path.exists():
19
+ if ((last_day or recorded_date) and str(last_day or recorded_date) < start.date().isoformat()) or (recorded_date and str(recorded_date) > end.date().isoformat()):
20
+ continue
21
+ missing += 1
22
+ if recorded_cost is None:
23
+ cost_complete = False
24
+ else:
25
+ missing_cost += max(0.0, float(recorded_cost))
26
+ continue
27
+ children = facade._find_subagent_jsonl_files(path)
28
+ parsed = facade._parse_session_jsonl(path, window_start=start, window_end=end)
29
+ if parsed and parsed.get('is_sidechain'):
30
+ continue
31
+ if parsed:
32
+ parsed = facade._parsed_net_of_ledger(parsed, request_ledger)
33
+ if not parsed:
34
+ parsed = {'total_input_tokens': 0, 'total_output_tokens': 0,
35
+ 'total_cache_create_1h': 0, 'total_cache_create_5m': 0,
36
+ 'cache_hit_rate': 0, 'model_usage': {}, 'api_calls': 0,
37
+ 'message_count': 0}
38
+ inp, out = parsed['total_input_tokens'], parsed['total_output_tokens']
39
+ cw1, cw5 = parsed['total_cache_create_1h'], parsed['total_cache_create_5m']
40
+ child_cache_read = 0
41
+ for child in children:
42
+ cp = facade._parse_session_jsonl(child, window_start=start, window_end=end)
43
+ if cp:
44
+ cp = facade._parsed_net_of_ledger(cp, request_ledger)
45
+ inp += cp['total_input_tokens']
46
+ out += cp['total_output_tokens']
47
+ cw1 += cp['total_cache_create_1h']
48
+ cw5 += cp['total_cache_create_5m']
49
+ child_cache_read += cp['total_cache_read']
50
+ if not parsed['api_calls'] and inp + out == 0:
51
+ continue
52
+ if recorded_cost is None:
53
+ cost_complete = False
54
+ else:
55
+ costs += max(0.0, float(recorded_cost))
56
+ usage = facade.json.dumps(parsed['model_usage'])
57
+ hit = parsed['cache_hit_rate'] if parsed['api_calls'] else child_cache_read / inp if inp else 0
58
+ rows.append((inp, out, cw5, cw1, hit, usage, usage,
59
+ parsed['api_calls'], parsed['message_count']))
60
+ total = len(rows) + missing
61
+ cost_share = missing_cost / (costs + missing_cost) if cost_complete and costs + missing_cost > 0 else None
62
+ # Beyond 5% missing, a partial workload is too incomplete to headline.
63
+ if not total or missing / total > 0.05 or (cost_share is not None and cost_share > 0.05):
64
+ return None
65
+ result = facade._price_parent_rows(rows, tier)
66
+ if result:
67
+ result['coverage'] = {'priced_sessions': len(rows), 'total_sessions': total,
68
+ 'missing_recorded_cost_share': cost_share}
69
+ return result
@@ -57,6 +57,7 @@ _PAYLOAD_MODULES = (
57
57
  "plugin_env.py",
58
58
  "bash_hook.py",
59
59
  "bash_compress.py",
60
+ "bash_search_results.py",
60
61
  # Dependency-free whitelist gate shared by bash_hook + bash_compress.
61
62
  "bash_whitelist.py",
62
63
  "command_filters.py",
@@ -68,6 +69,9 @@ _PAYLOAD_MODULES = (
68
69
  # credential_patterns: bash_compress's credential-preservation patterns
69
70
  # (the inline fallback misses e.g. ghp_/github_pat_ tokens, #171).
70
71
  "credential_patterns.py",
72
+ # credential_patterns imports this at module import time (URL family split
73
+ # under the 1,000-line ratchet); missing = import failure in the payload.
74
+ "credential_url_patterns.py",
71
75
  )
72
76
 
73
77
 
@@ -1942,45 +1942,8 @@ def _compress_search_results(output):
1942
1942
  if not files:
1943
1943
  return output # not file:line format, don't compress
1944
1944
 
1945
- _MAX_PER_FILE = 3
1946
- _MAX_FILES = 20
1947
- result: list[str] = []
1948
- file_count = 0
1949
- file_items = list(files.items())
1950
- for fname, file_lines in file_items:
1951
- if file_count >= _MAX_FILES:
1952
- break
1953
- if len(file_lines) <= _MAX_PER_FILE:
1954
- result.extend(file_lines)
1955
- else:
1956
- result.extend(file_lines[:_MAX_PER_FILE])
1957
- result.append(f" ... {len(file_lines) - _MAX_PER_FILE} more matches in {fname} ...")
1958
- file_count += 1
1959
-
1960
- # Keep EVERY matching filename (cheap) so "does file X match?" stays
1961
- # answerable; only per-line CONTENT past the top-N is dropped, never names.
1962
- if file_count < len(file_items):
1963
- result.append(f"... plus {len(file_items) - file_count} more files with matches "
1964
- f"(filenames + counts, content omitted):")
1965
- for fname, file_lines in file_items[file_count:]:
1966
- result.append(f" {fname}: {len(file_lines)} matches")
1967
-
1968
- if no_file:
1969
- result.append("")
1970
- # "Binary file X matches" lines name a matching file; keep ALL of them so
1971
- # the banner's "a file not listed has NO matches" stays true for binaries.
1972
- binary = [ln for ln in no_file if ln.startswith("Binary file ") and " matches" in ln]
1973
- other = [ln for ln in no_file if not (ln.startswith("Binary file ") and " matches" in ln)]
1974
- result.extend(binary)
1975
- result.extend(other[:10])
1976
- if len(other) > 10:
1977
- result.append(f"... {len(other) - 10} more non-file lines omitted ...")
1978
-
1979
- total_matches = sum(len(v) for v in files.values())
1980
- result.insert(0, f"[Search results: {total_matches} matches across {len(files)} files. "
1981
- f"ALL matching filenames listed; per-line content shown for the top "
1982
- f"{_MAX_FILES}. A file not listed here has NO matches.]")
1983
- return "\n".join(result)
1945
+ from bash_search_results import render_search_results
1946
+ return render_search_results(files, no_file)
1984
1947
 
1985
1948
 
1986
1949
  _PATTERN_HANDLERS = {
@@ -2385,7 +2348,7 @@ def main():
2385
2348
 
2386
2349
  # Progressive disclosure: archive the raw original BEFORE compression
2387
2350
  # so the model can retrieve it via `expand <key>` if needed. Fail-open:
2388
- # if archiving fails, compression proceeds without the pointer.
2351
+ # if archiving fails, serve the original instead of a lossy preview.
2389
2352
  _archive_key = None
2390
2353
  if compressed != raw_output and len(raw_output) > 500:
2391
2354
  try:
@@ -2414,6 +2377,11 @@ def main():
2414
2377
  except Exception:
2415
2378
  _archive_key = None
2416
2379
 
2380
+ # Search matches must remain recoverable even below the archive floor
2381
+ # or when the archive write fails. Other handlers keep their contracts.
2382
+ if _archive_key is None and _detect_pattern(command_str) == "search_results":
2383
+ compressed = raw_output
2384
+
2417
2385
  # Record savings to trends.db if compression was meaningful
2418
2386
  try:
2419
2387
  orig_bytes = len(raw_output.encode("utf-8", errors="replace"))
@@ -302,6 +302,7 @@ def _run(payload: dict) -> None:
302
302
  _find_preserved_lines,
303
303
  _ERROR_STDERR_PATTERNS,
304
304
  _enforce_baseline_invariant,
305
+ _detect_pattern,
305
306
  )
306
307
 
307
308
  # --- check for failure (exit code or stderr patterns) ---
@@ -378,6 +379,11 @@ def _run(payload: dict) -> None:
378
379
  except Exception:
379
380
  _archive_key = None
380
381
 
382
+ # Search matches must remain recoverable even below the archive floor
383
+ # or when the archive write fails. Other handlers keep their contracts.
384
+ if _archive_key is None and _detect_pattern(command) == "search_results":
385
+ compressed = stdout
386
+
381
387
  # --- enforce the baseline-size invariant ---
382
388
  # If our compressed preview + archive pointer would exceed what
383
389
  # Claude Code would show as a baseline stub, shrink to fit.
@@ -0,0 +1,43 @@
1
+ """Render parsed search matches with explicit per-file and file-count limits."""
2
+
3
+
4
+ def render_search_results(files, no_file):
5
+ _MAX_PER_FILE = 3
6
+ _MAX_FILES = 20
7
+ result: list[str] = []
8
+ file_count = 0
9
+ file_items = list(files.items())
10
+ for fname, file_lines in file_items:
11
+ if file_count >= _MAX_FILES:
12
+ break
13
+ if len(file_lines) <= _MAX_PER_FILE:
14
+ result.extend(file_lines)
15
+ else:
16
+ result.extend(file_lines[:_MAX_PER_FILE])
17
+ result.append(f" ... {len(file_lines) - _MAX_PER_FILE} more matches in {fname} (content omitted) ...")
18
+ file_count += 1
19
+
20
+ # Keep EVERY matching filename (cheap) so "does file X match?" stays
21
+ # answerable; only per-line CONTENT past the top-N is dropped, never names.
22
+ if file_count < len(file_items):
23
+ result.append(f"... plus {len(file_items) - file_count} more files with matches "
24
+ f"(filenames + counts, content omitted):")
25
+ for fname, file_lines in file_items[file_count:]:
26
+ result.append(f" {fname}: {len(file_lines)} matches")
27
+
28
+ if no_file:
29
+ result.append("")
30
+ # "Binary file X matches" lines name a matching file; keep ALL of them so
31
+ # the banner's "a file not listed has NO matches" stays true for binaries.
32
+ binary = [ln for ln in no_file if ln.startswith("Binary file ") and " matches" in ln]
33
+ other = [ln for ln in no_file if not (ln.startswith("Binary file ") and " matches" in ln)]
34
+ result.extend(binary)
35
+ result.extend(other[:10])
36
+ if len(other) > 10:
37
+ result.append(f"... {len(other) - 10} more non-file lines omitted ...")
38
+
39
+ total_matches = sum(len(v) for v in files.values())
40
+ result.insert(0, f"[Search results: {total_matches} matches across {len(files)} files. "
41
+ f"ALL matching filenames listed; up to {_MAX_PER_FILE} matches per file "
42
+ f"shown for the first {_MAX_FILES} files. Other match content omitted.]")
43
+ return "\n".join(result)
@@ -488,7 +488,7 @@ _REQUIRED = ("hooks/hooks.json", "hooks/python-launcher.sh", "hooks/run.py",
488
488
  "skills/token-optimizer/scripts/_measure/" + name for name in (
489
489
  '__init__.py', '_compat.py', 'runtime.py', 'pricing.py', 'audit.py',
490
490
  'dashboard.py', 'lifecycle.py', 'sessions.py', 'trends.py', 'cache_policy.py',
491
- 'daemon.py', 'quality_archive.py', 'continuity.py', 'savings.py', 'cli.py',
491
+ 'daemon.py', 'quality_archive.py', 'continuity.py', 'savings.py', 'cli.py', 'dashboard_history.py', 'weekly_activity.py',
492
492
  )
493
493
  )
494
494
 
@@ -64,7 +64,7 @@ _MEASURE_PACKAGE_FILES = (
64
64
  "_measure/pricing.py", "_measure/audit.py", "_measure/dashboard.py",
65
65
  "_measure/lifecycle.py", "_measure/sessions.py", "_measure/trends.py",
66
66
  "_measure/cache_policy.py", "_measure/daemon.py", "_measure/quality_archive.py",
67
- "_measure/continuity.py", "_measure/savings.py", "_measure/cli.py",
67
+ "_measure/continuity.py", "_measure/savings.py", "_measure/cli.py", "_measure/dashboard_history.py", "_measure/weekly_activity.py",
68
68
  )
69
69
 
70
70
 
@@ -48,6 +48,7 @@ _PAYLOAD_MODULES = (
48
48
  "copilot_vscode.py",
49
49
  "bash_hook.py",
50
50
  "bash_compress.py",
51
+ "bash_search_results.py",
51
52
  # Dependency-free whitelist gate shared by bash_hook + bash_compress.
52
53
  "bash_whitelist.py",
53
54
  # command_filters + _tomli: user [filters.*] TOML config consulted by
@@ -75,6 +76,9 @@ _PAYLOAD_MODULES = (
75
76
  # credential_patterns: bash_compress's credential-preservation patterns and
76
77
  # copilot_session's topic redaction (both fall back to less without it).
77
78
  "credential_patterns.py",
79
+ # credential_patterns imports this at module import time (URL family split
80
+ # under the 1,000-line ratchet); missing = import failure in the payload.
81
+ "credential_url_patterns.py",
78
82
  )
79
83
 
80
84
 
@@ -18,6 +18,8 @@ from datetime import datetime, timezone
18
18
  from pathlib import Path
19
19
  from typing import Dict, List, Optional, Tuple
20
20
 
21
+ from credential_url_patterns import URL_CREDENTIAL_PATTERNS
22
+
21
23
  # (label, compiled_regex) pairs. Label is used in redaction placeholders.
22
24
  CREDENTIAL_PATTERNS: List[Tuple[str, "re.Pattern[str]"]] = [
23
25
  ("AWS access key", re.compile(r"AKIA[0-9A-Z]{16}")),
@@ -81,25 +83,7 @@ CREDENTIAL_PATTERNS: List[Tuple[str, "re.Pattern[str]"]] = [
81
83
  # of the text so a truncated body is never left behind.
82
84
  ("PEM private key", re.compile(
83
85
  r"-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z ]*PRIVATE KEY-----|\Z)")),
84
- ("Database URI", re.compile(r"(?:postgres|postgresql|mysql|mongodb|mongodb\+srv|redis)://[^:\s/]+:[^@\s]+@", re.I)),
85
- ("HTTP basic auth URL", re.compile(r"https?://[^:\s/@]+:[^@\s]+@", re.I)),
86
- # Credentials passed as URL query/matrix parameters OR OAuth-implicit-flow
87
- # fragment params (e.g. ?token=..., ?api_key=..., ;password=..., #access_token=...).
88
- # The named `keep` group captures the "?name="/"#name=" prefix so redaction
89
- # preserves the parameter name and blanks only the value (see redact_credentials).
90
- # The value class stops at the next delimiter (& # ; whitespace quote < >) but
91
- # otherwise matches EVERYTHING — including brackets — so a secret that itself
92
- # contains a `[` (common in passwords) is redacted whole, not leaked past the
93
- # bracket. To still avoid re-wrapping an already-inserted "[CREDENTIAL REDACTED:
94
- # ...]" placeholder (when the value is itself another credential shape an earlier
95
- # pattern redacted, e.g. ?token=<Bearer ...>), a negative lookahead skips a value
96
- # that begins with the placeholder rather than excluding brackets from real values.
97
- ("URL auth param", re.compile(
98
- r"(?P<keep>[?&#;](?:authorization|access[_-]?token|refresh[_-]?token|client[_-]?secret"
99
- r"|session[_-]?token|id[_-]?token|api[_-]?key|sessionid|session|password|passwd|signature"
100
- r"|secret|bearer|token|auth|sig|pwd|key|jwt)=)(?!\[CREDENTIAL REDACTED:)[^&#;\s\"'<>]+",
101
- re.I,
102
- )),
86
+ *URL_CREDENTIAL_PATTERNS,
103
87
  # M-12: mysql -p<password> (inline password after -p with no space).
104
88
  # The -p flag is special: the password immediately follows with no = or space.
105
89
  # N-3: re.I so "MySQL -pSECRET" (capitalized client name, as MySQL ships
@@ -1128,6 +1112,7 @@ _PATTERN_ANCHORS = {
1128
1112
  "Bearer token": ("bearer",),
1129
1113
  "Database URI": ("://",),
1130
1114
  "HTTP basic auth URL": ("://",),
1115
+ "HTTP token userinfo URL": ("://",),
1131
1116
  "URL auth param": ("=",),
1132
1117
  "MySQL password flag": ("mysql",),
1133
1118
  "Database env password": ("password=", "pwd=", "passwd=",