@alexgreensh/token-optimizer 5.13.50 → 5.13.52

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.
@@ -72,6 +72,7 @@ import errno
72
72
  import hashlib
73
73
  import heapq
74
74
  import hmac
75
+ import io
75
76
  import json
76
77
  import math
77
78
  import os
@@ -4946,10 +4947,12 @@ def doctor(as_json=False):
4946
4947
  # 4. SessionEnd hook (plugin hooks.json auto-installs these, so check for plugin too)
4947
4948
  total += 1
4948
4949
  settings, _ = _read_settings_json()
4949
- if _is_hook_installed(settings):
4950
+ # The label names where the hook really comes from: _is_hook_installed alone
4951
+ # also counts the plugin's hooks.json, which is not settings.json.
4952
+ if _is_hook_installed(settings, settings_only=True):
4950
4953
  checks.append(("OK", "SessionEnd hook", "active (settings.json)"))
4951
4954
  score += 1
4952
- elif _is_plugin_installed():
4955
+ elif _is_plugin_installed() or _is_hook_installed(settings):
4953
4956
  checks.append(("OK", "SessionEnd hook", "active (plugin hooks.json)"))
4954
4957
  score += 1
4955
4958
  else:
@@ -4980,8 +4983,24 @@ def doctor(as_json=False):
4980
4983
  # 6. Quality bar
4981
4984
  total += 1
4982
4985
  qb = _is_quality_bar_installed(settings)
4983
- if qb["statusline"] and qb["hook"]:
4984
- checks.append(("OK", "Quality bar", "status line + hook active"))
4986
+ # Which statusline.js the status line really runs: a missing file shows a
4987
+ # blank status line, and another checkout runs other code than this one.
4988
+ _qb_sl_path = None
4989
+ try:
4990
+ _found = _statusline_js_in_command(((settings or {}).get("statusLine") or {}).get("command") or "")
4991
+ _qb_sl_path = _found[2] if _found else None
4992
+ except Exception:
4993
+ _qb_sl_path = None
4994
+ _qb_ours = _get_statusline_path()
4995
+ if qb["statusline"] and _qb_sl_path and not Path(_qb_sl_path).expanduser().is_file():
4996
+ checks.append(("!!", "Quality bar", _hint(
4997
+ f"status line runs a missing file: {_qb_sl_path} "
4998
+ "(fix: start a new session, it re-points it; or python3 measure.py setup-quality-bar --force)")))
4999
+ elif qb["statusline"] and qb["hook"]:
5000
+ _qb_note = ""
5001
+ if _qb_sl_path and os.path.normcase(os.path.abspath(_qb_sl_path)) != os.path.normcase(os.path.abspath(_qb_ours)):
5002
+ _qb_note = f" (runs another Token Optimizer copy: {_qb_sl_path})"
5003
+ checks.append(("OK", "Quality bar", "status line + hook active" + _qb_note))
4985
5004
  score += 1
4986
5005
  else:
4987
5006
  missing = []
@@ -25819,6 +25838,646 @@ def _read_path_upkeep(conn, days):
25819
25838
  pass
25820
25839
 
25821
25840
 
25841
+ def _session_price_buckets(mb, pricing_tier):
25842
+ """(priced_tokens, unpriced_tokens) for a per-model breakdown."""
25843
+ priced = unpriced = 0
25844
+ for model_name, parts in (mb or {}).items():
25845
+ if not isinstance(parts, dict):
25846
+ continue
25847
+ model_tokens = (
25848
+ int(parts.get("fresh_input") or 0)
25849
+ + int(parts.get("cache_read") or 0)
25850
+ + int(parts.get("cache_create") or 0)
25851
+ + int(parts.get("output") or 0)
25852
+ )
25853
+ if _is_priced_model(model_name, tier=pricing_tier):
25854
+ priced += model_tokens
25855
+ else:
25856
+ unpriced += model_tokens
25857
+ return priced, unpriced
25858
+
25859
+
25860
+ def _price_session_row(sr, pricing_tier):
25861
+ """Price one session_log row: THE per-session cost for the dashboard and
25862
+ for `session-cost`, so the two can never disagree.
25863
+
25864
+ *sr* needs date, input_tokens, output_tokens, cache_hit_rate,
25865
+ cache_create_1h_tokens, cache_create_5m_tokens, model_usage_json,
25866
+ model_usage_breakdown_json and daily_usage_json. Every model is priced at
25867
+ its own generation card (_get_model_cost -> _claude_price_key).
25868
+
25869
+ Returns a dict:
25870
+ main_cost parent-thread cost (stored per-model breakdown; a dominant-model
25871
+ estimate for rows that carry none)
25872
+ total_cost the whole session. With per-day usage (parent + subagents,
25873
+ requests merged by requestId so a shared one bills once) it is
25874
+ the sum of the days; without it, main_cost.
25875
+ slices [[date, cost, priced, unpriced, input, output], ...] every
25876
+ billed day, uncut by any window
25877
+ has_daily whether total_cost includes the subagents
25878
+ priced_tokens / unpriced_tokens, dom_model, model_usage, breakdown,
25879
+ daily_usage
25880
+ """
25881
+ inp_total = sr["input_tokens"] or 0
25882
+ out_total = sr["output_tokens"] or 0
25883
+ chr_val = sr["cache_hit_rate"] or 0
25884
+ cache_read_est = _safe_int(inp_total * chr_val)
25885
+ cache_create_1h = sr["cache_create_1h_tokens"] or 0
25886
+ cache_create_5m = sr["cache_create_5m_tokens"] or 0
25887
+ cache_create_total = cache_create_1h + cache_create_5m
25888
+ uncached_est = max(0, inp_total - cache_read_est - cache_create_total)
25889
+
25890
+ mu = _safe_json_dict(sr["model_usage_json"])
25891
+ dom_model = max(mu, key=mu.get) if mu else "unknown"
25892
+ mb = _safe_json_dict(sr["model_usage_breakdown_json"])
25893
+ du = _safe_json_dict(sr["daily_usage_json"])
25894
+
25895
+ if mb:
25896
+ session_priced_tokens, session_unpriced_tokens = _session_price_buckets(mb, pricing_tier)
25897
+ else:
25898
+ model_tokens = inp_total + out_total
25899
+ if _is_priced_model(dom_model, tier=pricing_tier):
25900
+ session_priced_tokens, session_unpriced_tokens = model_tokens, 0
25901
+ else:
25902
+ session_priced_tokens, session_unpriced_tokens = 0, model_tokens
25903
+ # Main-thread cost from the stored session breakdown. Used as-is for rows
25904
+ # without per-day data (non-JSONL adapters, transcript gone).
25905
+ split = bool(cache_create_1h or cache_create_5m)
25906
+ session_cost = _cost_from_model_breakdown(mb, tier=pricing_tier,
25907
+ cache_create_1h=cache_create_1h if split else None,
25908
+ cache_create_5m=cache_create_5m if split else None)
25909
+ if session_cost == 0.0:
25910
+ # Use the stored 1h/5m split when available; fall back to 5m-only rate otherwise.
25911
+ if split:
25912
+ session_cost = _get_model_cost(dom_model, uncached_est, out_total, cache_read_est, cache_create_total,
25913
+ tier=pricing_tier, cache_create_1h=cache_create_1h, cache_create_5m=cache_create_5m)
25914
+ else:
25915
+ session_cost = _get_model_cost(dom_model, uncached_est, out_total, cache_read_est, cache_create_total, tier=pricing_tier)
25916
+ if session_cost == 0.0 and session_priced_tokens == 0 and session_unpriced_tokens == 0 and (inp_total or out_total):
25917
+ session_unpriced_tokens = inp_total + out_total
25918
+
25919
+ # Per-day slices (#200). With per-day data, each calendar day is billed for
25920
+ # the requests that ran on it, subagents included. Without it, the whole
25921
+ # session lands on its stored date.
25922
+ slices = [] # (date, cost, priced, unpriced, input_tokens, output_tokens)
25923
+ if du:
25924
+ by_day = {}
25925
+ undated_day = _undated_bill_day(du, sr["date"])
25926
+ for day, day_mb in du.items():
25927
+ if not isinstance(day_mb, dict):
25928
+ continue
25929
+ day = undated_day if day == UNDATED_USAGE_KEY else day
25930
+ _merge_daily_usage(by_day.setdefault(day, {}), {"_": day_mb})
25931
+ for day in sorted(by_day):
25932
+ day_mb = by_day[day].get("_", {})
25933
+ day_cost = _cost_from_model_breakdown(day_mb, tier=pricing_tier)
25934
+ day_priced, day_unpriced = _session_price_buckets(day_mb, pricing_tier)
25935
+ day_in = sum(
25936
+ int(p.get("fresh_input") or 0) + int(p.get("cache_read") or 0) + int(p.get("cache_create") or 0)
25937
+ for p in day_mb.values() if isinstance(p, dict))
25938
+ day_out = sum(int(p.get("output") or 0) for p in day_mb.values() if isinstance(p, dict))
25939
+ slices.append([day, day_cost, day_priced, day_unpriced, day_in, day_out])
25940
+ total_cost = sum(sl[1] for sl in slices)
25941
+ else:
25942
+ total_cost = session_cost
25943
+ slices = [[sr["date"], session_cost, session_priced_tokens, session_unpriced_tokens, inp_total, out_total]]
25944
+ return {
25945
+ "main_cost": session_cost,
25946
+ "total_cost": total_cost,
25947
+ "slices": slices,
25948
+ "has_daily": bool(du),
25949
+ "priced_tokens": sum(sl[2] for sl in slices),
25950
+ "unpriced_tokens": sum(sl[3] for sl in slices),
25951
+ "dom_model": dom_model,
25952
+ "model_usage": mu,
25953
+ "breakdown": mb,
25954
+ "daily_usage": du,
25955
+ }
25956
+
25957
+
25958
+ # ---------------------------------------------------------------------------
25959
+ # session-cost: "what did the Garden session yesterday cost?" answered from
25960
+ # trends.db, priced by _price_session_row (the dashboard's own number). Strictly
25961
+ # read-only: the DB is opened mode=ro (WAL readers never block a writer) and,
25962
+ # only if that open fails, immutable=1. Nothing here creates, migrates or
25963
+ # writes a file.
25964
+ # ---------------------------------------------------------------------------
25965
+
25966
+ # Filler words a plain question carries ("what did the ... session cost").
25967
+ # Dropped before matching so passing the user's own words still works.
25968
+ _SESSION_COST_STOPWORDS = frozenset("""
25969
+ a an and are at be by cost costs costed did do does for from how i in is it
25970
+ its me much my of on or price priced pricing session sessions spend spent
25971
+ that the this to was were what which with
25972
+ """.split())
25973
+ _SESSION_COST_ID_RX = re.compile(r"^[0-9a-f]{8}[0-9a-f-]*$", re.IGNORECASE)
25974
+ _SESSION_COST_DATE_RX = re.compile(r"^\d{4}-\d{2}-\d{2}$")
25975
+ _SESSION_COST_COLS = (
25976
+ "id, jsonl_path, date, project, duration_minutes, input_tokens, output_tokens, "
25977
+ "message_count, api_calls, cache_hit_rate, cache_create_1h_tokens, "
25978
+ "cache_create_5m_tokens, model_usage_json, model_usage_breakdown_json, "
25979
+ "daily_usage_json, slug, topic, session_uuid, is_sidechain, subagents_json, "
25980
+ "collected_at, origin, platform"
25981
+ )
25982
+ SESSION_COST_BASIS = (
25983
+ "API-equivalent list price ({tier}). On a subscription plan this is what the "
25984
+ "work would have cost at API rates, not a bill."
25985
+ )
25986
+
25987
+
25988
+ def _session_cost_norm(text):
25989
+ """Case- and form-insensitive text for matching (Hebrew/any script safe)."""
25990
+ import unicodedata # noqa: PLC0415 - only this command needs it
25991
+ return unicodedata.normalize("NFKC", str(text or "")).casefold()
25992
+
25993
+
25994
+ def _session_cost_resolve_date(word, today=None):
25995
+ """'today' / 'yesterday' / YYYY-MM-DD -> YYYY-MM-DD, else None."""
25996
+ today = today or datetime.now().date()
25997
+ w = _session_cost_norm(word).strip()
25998
+ if w == "today":
25999
+ return today.strftime("%Y-%m-%d")
26000
+ if w == "yesterday":
26001
+ return (today - timedelta(days=1)).strftime("%Y-%m-%d")
26002
+ if _SESSION_COST_DATE_RX.match(w):
26003
+ try:
26004
+ return datetime.strptime(w, "%Y-%m-%d").strftime("%Y-%m-%d")
26005
+ except ValueError:
26006
+ return None
26007
+ return None
26008
+
26009
+
26010
+ def _session_cost_parse_args(argv):
26011
+ """Parse session-cost arguments. Returns (opts, error-or-None)."""
26012
+ opts = {"words": [], "id": None, "date": None, "days": None, "limit": 5, "json": False}
26013
+ i = 0
26014
+ while i < len(argv):
26015
+ a = argv[i]
26016
+ if a == "--json":
26017
+ opts["json"] = True
26018
+ elif a in ("--id", "--date", "--days", "--limit"):
26019
+ if i + 1 >= len(argv):
26020
+ return opts, f"{a} needs a value"
26021
+ val = argv[i + 1]
26022
+ i += 1
26023
+ if a == "--id":
26024
+ opts["id"] = val.strip().lower()
26025
+ elif a == "--date":
26026
+ d = _session_cost_resolve_date(val)
26027
+ if d is None:
26028
+ return opts, f"--date takes YYYY-MM-DD, today or yesterday (got {val!r})"
26029
+ opts["date"] = d
26030
+ else:
26031
+ try:
26032
+ n = int(val)
26033
+ except ValueError:
26034
+ return opts, f"{a} takes a whole number (got {val!r})"
26035
+ if n < 1:
26036
+ return opts, f"{a} must be at least 1"
26037
+ opts["days" if a == "--days" else "limit"] = n
26038
+ elif a.startswith("--"):
26039
+ return opts, f"unknown option {a}"
26040
+ else:
26041
+ opts["words"].append(a)
26042
+ i += 1
26043
+ # Plain words may carry the date or the id themselves.
26044
+ words = []
26045
+ for raw in opts["words"]:
26046
+ for w in re.split(r"[\s,?!.;:]+", raw):
26047
+ w = w.strip("\"'()[]{}<>")
26048
+ if not w:
26049
+ continue
26050
+ d = _session_cost_resolve_date(w)
26051
+ if d is not None:
26052
+ opts["date"] = opts["date"] or d
26053
+ continue
26054
+ if _SESSION_COST_ID_RX.match(w) and not opts["id"]:
26055
+ opts["id"] = w.lower()
26056
+ continue
26057
+ n = _session_cost_norm(w)
26058
+ if n not in _SESSION_COST_STOPWORDS:
26059
+ words.append(n)
26060
+ opts["words"] = words
26061
+ return opts, None
26062
+
26063
+
26064
+ def _session_cost_open_db(db_path):
26065
+ """Open trends.db without writing a byte or blocking a writer.
26066
+
26067
+ trends.db runs in WAL mode. With no writer attached (no -wal, or an empty
26068
+ one) every row is in the main file, so immutable=1 reads it with no locks
26069
+ and creates nothing; a plain mode=ro open would create -wal/-shm files.
26070
+ With a live writer (-wal holding data and its -shm present), mode=ro
26071
+ joins the shared read protocol: it sees every committed row and a WAL
26072
+ reader never blocks a writer. If that fails (an exclusive lock, or a WAL
26073
+ with no -shm to share), immutable=1 still answers from the main file,
26074
+ which may miss the newest rows. Returns (conn, mode) or (None, error)."""
26075
+ db_path = Path(db_path).resolve()
26076
+ uri_base = db_path.as_uri()
26077
+ try:
26078
+ wal = Path(str(db_path) + "-wal")
26079
+ live = wal.exists() and wal.stat().st_size > 0
26080
+ shm_ok = Path(str(db_path) + "-shm").exists()
26081
+ except OSError:
26082
+ live, shm_ok = True, False
26083
+ if not live:
26084
+ attempts = (("quiescent", "?mode=ro&immutable=1"),)
26085
+ elif shm_ok:
26086
+ attempts = (("shared-read", "?mode=ro"), ("snapshot", "?mode=ro&immutable=1"))
26087
+ else:
26088
+ attempts = (("snapshot", "?mode=ro&immutable=1"),)
26089
+ last_err = None
26090
+ for mode, query in attempts:
26091
+ conn = None
26092
+ try:
26093
+ conn = sqlite3.connect(uri_base + query, uri=True, timeout=1.5)
26094
+ conn.execute("PRAGMA query_only=1")
26095
+ conn.execute("SELECT 1 FROM session_log LIMIT 1").fetchall()
26096
+ conn.row_factory = sqlite3.Row
26097
+ return conn, mode
26098
+ except sqlite3.Error as exc:
26099
+ last_err = exc
26100
+ if conn is not None:
26101
+ try:
26102
+ conn.close()
26103
+ except sqlite3.Error:
26104
+ pass
26105
+ return None, str(last_err)
26106
+
26107
+
26108
+ def _session_cost_haystack(row):
26109
+ """Every text field a plain-words question can match: topic, slug, project
26110
+ (raw and cleaned) and the transcript's folder name."""
26111
+ project = row["project"] or ""
26112
+ parts = [row["topic"], row["slug"], project, _clean_project_name(project)]
26113
+ jp = row["jsonl_path"]
26114
+ if jp:
26115
+ parts.append(Path(jp).parent.name)
26116
+ return _session_cost_norm(" ".join(str(p) for p in parts if p))
26117
+
26118
+
26119
+ def _session_cost_word_hits(words, row):
26120
+ """How many of *words* match this row. A word of three characters or fewer
26121
+ must be a whole token ('tr' never matches 'trends'); longer words match
26122
+ anywhere (Hebrew prefixes attach to the word they modify)."""
26123
+ hay = _session_cost_haystack(row)
26124
+ tokens = set(re.findall(r"\w+", hay))
26125
+ hits = 0
26126
+ for w in words:
26127
+ if (w in tokens) if len(w) <= 3 else (w in hay):
26128
+ hits += 1
26129
+ return hits
26130
+
26131
+
26132
+ def _session_cost_row_id(row):
26133
+ uuid = row["session_uuid"]
26134
+ if uuid:
26135
+ return str(uuid)
26136
+ jp = row["jsonl_path"] or ""
26137
+ return Path(jp).stem if jp else f"row-{row['id']}"
26138
+
26139
+
26140
+ def _session_cost_components(priced, row, tier):
26141
+ """Per-model tokens and dollars from the same buckets the total came from
26142
+ (per-day usage when stored, else the parent breakdown, else the
26143
+ dominant-model estimate). Returns (models, tokens, cost_parts)."""
26144
+ buckets = {}
26145
+ if priced["has_daily"]:
26146
+ for day_mb in priced["daily_usage"].values():
26147
+ if isinstance(day_mb, dict):
26148
+ _merge_daily_usage(buckets, {"_": day_mb})
26149
+ buckets = buckets.get("_", {})
26150
+ elif priced["breakdown"]:
26151
+ buckets = {m: p for m, p in priced["breakdown"].items() if isinstance(p, dict)}
26152
+ else:
26153
+ inp = int(row["input_tokens"] or 0)
26154
+ cr = _safe_int(inp * (row["cache_hit_rate"] or 0))
26155
+ cc1 = int(row["cache_create_1h_tokens"] or 0)
26156
+ cc5 = int(row["cache_create_5m_tokens"] or 0)
26157
+ buckets = {priced["dom_model"]: {
26158
+ "fresh_input": max(0, inp - cr - cc1 - cc5), "cache_read": cr,
26159
+ "cache_create": cc1 + cc5, "cache_create_1h": cc1, "cache_create_5m": cc5,
26160
+ "output": int(row["output_tokens"] or 0)}}
26161
+ tokens = {"input": 0, "output": 0, "cache_read": 0, "cache_write": 0}
26162
+ parts = {"input": 0.0, "output": 0.0, "cache_read": 0.0, "cache_write": 0.0}
26163
+ models = []
26164
+ for model, p in buckets.items():
26165
+ fi = int(p.get("fresh_input") or 0)
26166
+ out = int(p.get("output") or 0)
26167
+ cr = int(p.get("cache_read") or 0)
26168
+ cc = int(p.get("cache_create") or 0)
26169
+ has_split = "cache_create_1h" in p or "cache_create_5m" in p
26170
+ c1 = int(p.get("cache_create_1h") or 0) if has_split else None
26171
+ c5 = int(p.get("cache_create_5m") or 0) if has_split else None
26172
+ c_in = _get_model_cost(model, fi, 0, 0, 0, tier=tier)
26173
+ c_out = _get_model_cost(model, 0, out, 0, 0, tier=tier)
26174
+ c_cr = _get_model_cost(model, 0, 0, cr, 0, tier=tier)
26175
+ c_cw = _get_model_cost(model, 0, 0, 0, cc, tier=tier, cache_create_1h=c1, cache_create_5m=c5)
26176
+ for k, v in (("input", fi), ("output", out), ("cache_read", cr), ("cache_write", cc)):
26177
+ tokens[k] += v
26178
+ for k, v in (("input", c_in), ("output", c_out), ("cache_read", c_cr), ("cache_write", c_cw)):
26179
+ parts[k] += v
26180
+ models.append({"model": model, "priced": _is_priced_model(model, tier=tier),
26181
+ "tokens": fi + out + cr + cc,
26182
+ "cost_usd": round(c_in + c_out + c_cr + c_cw, 4)})
26183
+ models.sort(key=lambda m: (-m["cost_usd"], -m["tokens"]))
26184
+ return models, tokens, parts
26185
+
26186
+
26187
+ def _session_cost_entry(row, tier, date_filter=None, current_id=None):
26188
+ """One matched session, priced, as a JSON-ready dict."""
26189
+ priced = _price_session_row(row, tier)
26190
+ total = float(priced["total_cost"])
26191
+ models, tokens, parts = _session_cost_components(priced, row, tier)
26192
+ subagents = _safe_json_dict(row["subagents_json"])
26193
+ sub_count = sum(int(v or 0) for v in subagents.values() if isinstance(v, (int, float)))
26194
+ main = min(float(priced["main_cost"]), total) if priced["has_daily"] else total
26195
+ sub_cost = max(0.0, total - main) if priced["has_daily"] else 0.0
26196
+ # Components come from the same buckets as the total; any gap is the
26197
+ # per-request long-context card on a row with no per-day data.
26198
+ adjustment = total - sum(parts.values())
26199
+ days = sorted({sl[0] for sl in priced["slices"] if sl[0]})
26200
+ sid = _session_cost_row_id(row)
26201
+ partial = False
26202
+ partial_reason = None
26203
+ if current_id and sid.startswith(current_id):
26204
+ partial, partial_reason = True, "this is the current session; it is collected again when it ends"
26205
+ else:
26206
+ try:
26207
+ jp = row["jsonl_path"]
26208
+ collected = row["collected_at"]
26209
+ if jp and collected and os.path.exists(jp):
26210
+ if datetime.fromtimestamp(os.stat(jp).st_mtime) > datetime.fromisoformat(str(collected)) + timedelta(seconds=60):
26211
+ partial, partial_reason = True, "the transcript grew after it was collected"
26212
+ except (OSError, ValueError, TypeError):
26213
+ pass
26214
+ entry = {
26215
+ "session_id": sid,
26216
+ "date": row["date"],
26217
+ "days": days or [row["date"]],
26218
+ "topic": _strip_ansi(row["topic"] or "") or None,
26219
+ "slug": _strip_ansi(row["slug"] or "") or None,
26220
+ "project": _strip_ansi(_clean_project_name(row["project"])),
26221
+ "kind": "delegated" if row["is_sidechain"] else "session",
26222
+ "origin": row["origin"],
26223
+ "duration_minutes": round(float(row["duration_minutes"] or 0), 1),
26224
+ "api_calls": int(row["api_calls"] or 0),
26225
+ "models": models,
26226
+ "tokens": tokens,
26227
+ "cost_usd": {
26228
+ "input": round(parts["input"], 4),
26229
+ "output": round(parts["output"], 4),
26230
+ "cache_read": round(parts["cache_read"], 4),
26231
+ "cache_write": round(parts["cache_write"], 4),
26232
+ "total": round(total, 4),
26233
+ "main_thread": round(main, 4),
26234
+ "subagents": round(sub_cost, 4),
26235
+ },
26236
+ "subagents": {"count": sub_count, "types": subagents,
26237
+ "included": bool(priced["has_daily"]) or not sub_count},
26238
+ "unpriced_tokens": int(priced["unpriced_tokens"]),
26239
+ "collected_at": row["collected_at"],
26240
+ "partial": partial,
26241
+ "partial_reason": partial_reason,
26242
+ }
26243
+ if abs(adjustment) >= 0.0001:
26244
+ entry["cost_usd"]["long_context_adjustment"] = round(adjustment, 4)
26245
+ if date_filter and len(entry["days"]) > 1:
26246
+ entry["cost_usd"]["on_date"] = round(
26247
+ sum(sl[1] for sl in priced["slices"] if sl[0] == date_filter), 4)
26248
+ return entry
26249
+
26250
+
26251
+ def _session_cost_uncollected(id_prefix):
26252
+ """Transcripts on disk for an id that trends.db has no row for (read-only glob)."""
26253
+ if not id_prefix or detect_runtime() != "claude":
26254
+ return []
26255
+ try:
26256
+ base = CLAUDE_DIR / "projects"
26257
+ if not base.is_dir():
26258
+ return []
26259
+ safe = re.sub(r"[^0-9a-fA-F-]", "", id_prefix)
26260
+ return [str(p) for p in base.glob(f"*/{safe}*.jsonl")][:3] if safe else []
26261
+ except OSError:
26262
+ return []
26263
+
26264
+
26265
+ def session_cost_query(argv):
26266
+ """Build the session-cost answer as a dict (see session_cost_main)."""
26267
+ opts, err = _session_cost_parse_args(argv)
26268
+ tier = _load_pricing_tier()
26269
+ out = {
26270
+ "db": str(TRENDS_DB),
26271
+ "basis": SESSION_COST_BASIS.format(tier=_pricing_tier_label(tier)),
26272
+ "query": {"words": opts["words"], "id": opts["id"], "date": opts["date"],
26273
+ "days": opts["days"]},
26274
+ "sessions": [],
26275
+ "match_count": 0,
26276
+ "total_cost_usd": 0.0,
26277
+ "closest": [],
26278
+ "note": None,
26279
+ }
26280
+ if err:
26281
+ out["error"] = err
26282
+ return out
26283
+ if not TRENDS_DB.exists():
26284
+ out["error"] = ("No Token Optimizer history yet (no trends database at this "
26285
+ "path). Sessions are collected when they end.")
26286
+ return out
26287
+ conn, mode = _session_cost_open_db(TRENDS_DB)
26288
+ if conn is None:
26289
+ out["error"] = f"Could not read the trends database read-only: {mode}"
26290
+ return out
26291
+ out["read_mode"] = mode
26292
+ current_id = (os.environ.get("CLAUDE_CODE_SESSION_ID") or "").strip().lower() or None
26293
+ try:
26294
+ cols = {r[1] for r in conn.execute("PRAGMA table_info(session_log)").fetchall()}
26295
+ select = ", ".join(c if c in cols else f"NULL AS {c}"
26296
+ for c in (x.strip() for x in _SESSION_COST_COLS.split(",")))
26297
+ params = []
26298
+ where = []
26299
+ if opts["date"]:
26300
+ where.append("date >= ?") # date is a session's LAST day
26301
+ params.append(opts["date"])
26302
+ elif not opts["id"]:
26303
+ days = opts["days"] or 30
26304
+ cutoff = (datetime.now().date() - timedelta(days=days - 1)).strftime("%Y-%m-%d")
26305
+ out["query"]["days"] = days
26306
+ where.append("date >= ?")
26307
+ params.append(cutoff)
26308
+ sql = f"SELECT {select} FROM session_log"
26309
+ if where:
26310
+ sql += " WHERE " + " AND ".join(where)
26311
+ rows = conn.execute(sql + " ORDER BY date DESC, id DESC", params).fetchall()
26312
+ except sqlite3.Error as exc:
26313
+ conn.close()
26314
+ out["error"] = f"Could not read the trends database: {exc}"
26315
+ return out
26316
+ conn.close()
26317
+
26318
+ # One session counts once: copies of a session (worktree, mirror) keep the
26319
+ # most complete row, the same rule as _dedupe_session_rows.
26320
+ best = {}
26321
+ for r in rows:
26322
+ key = _session_cost_row_id(r)
26323
+ rank = _session_rank(r["message_count"], r["input_tokens"], r["output_tokens"])
26324
+ if key not in best or rank > best[key][0]:
26325
+ best[key] = (rank, r)
26326
+ rows = [v[1] for v in best.values()]
26327
+ rows.sort(key=lambda r: (str(r["date"] or ""), int(r["id"] or 0)), reverse=True)
26328
+
26329
+ def _days_of(r):
26330
+ du = _safe_json_dict(r["daily_usage_json"])
26331
+ ds = {d for d in du if d != UNDATED_USAGE_KEY}
26332
+ ds.add(r["date"])
26333
+ return ds
26334
+
26335
+ def _id_ok(r):
26336
+ if not opts["id"]:
26337
+ return True
26338
+ sid = _session_cost_row_id(r).lower()
26339
+ stem = Path(r["jsonl_path"] or "").stem.lower()
26340
+ return sid.startswith(opts["id"]) or stem.startswith(opts["id"])
26341
+
26342
+ def _date_ok(r):
26343
+ return not opts["date"] or opts["date"] in _days_of(r)
26344
+
26345
+ words = opts["words"]
26346
+ scoped = [r for r in rows if _id_ok(r) and _date_ok(r)]
26347
+ matched = [r for r in scoped if not words or _session_cost_word_hits(words, r) == len(words)]
26348
+
26349
+ entries = [_session_cost_entry(r, tier, opts["date"], current_id) for r in matched]
26350
+ out["match_count"] = len(entries)
26351
+ out["total_cost_usd"] = round(sum(e["cost_usd"]["total"] for e in entries), 4)
26352
+ out["sessions"] = entries[:opts["limit"]]
26353
+ out["shown"] = len(out["sessions"])
26354
+ if entries:
26355
+ return out
26356
+
26357
+ # Nothing matched: say so and offer the closest few. Sessions matching
26358
+ # some of the words come first, then the newest in the date scope.
26359
+ pool = scoped if (opts["date"] or opts["id"]) and scoped else rows
26360
+ if words:
26361
+ # Stable sort: within a hit count the newest-first order stays.
26362
+ pool = sorted(pool, key=lambda r: -_session_cost_word_hits(words, r))
26363
+ out["closest"] = [_session_cost_entry(r, tier, opts["date"], current_id) for r in pool[:3]]
26364
+ if opts["id"]:
26365
+ on_disk = _session_cost_uncollected(opts["id"])
26366
+ if on_disk:
26367
+ out["note"] = ("That session has a transcript but is not collected yet. "
26368
+ "Collection runs when a session ends; run `measure.py collect` "
26369
+ "to collect now, then ask again.")
26370
+ out["uncollected_transcripts"] = on_disk
26371
+ return out
26372
+ out["note"] = ("No collected session matches. Collection runs when a session ends, "
26373
+ "so a session still open (or ended in the last minute) may not be "
26374
+ "here yet.")
26375
+ return out
26376
+
26377
+
26378
+ def _fmt_session_cost_tokens(n):
26379
+ n = int(n or 0)
26380
+ if n >= 1_000_000:
26381
+ return f"{n / 1_000_000:.1f}M"
26382
+ if n >= 1_000:
26383
+ return f"{n / 1_000:.0f}K"
26384
+ return str(n)
26385
+
26386
+
26387
+ def _fmt_session_cost_duration(minutes):
26388
+ m = int(round(float(minutes or 0)))
26389
+ return f"{m // 60}h {m % 60:02d}m" if m >= 60 else f"{m}m"
26390
+
26391
+
26392
+ def _usd(v):
26393
+ """Dollars as people read them: cents from $1 up, four places below."""
26394
+ v = float(v or 0)
26395
+ return f"${v:,.2f}" if abs(v) >= 1 else f"${v:.4f}"
26396
+
26397
+
26398
+ def _print_session_cost_entry(n, e, date_filter=None):
26399
+ title = e["topic"] or e["slug"] or "(untitled session)"
26400
+ days = e["days"]
26401
+ when = days[0] if len(days) == 1 else f"{days[0]} to {days[-1]}"
26402
+ kind = " [delegated session]" if e["kind"] == "delegated" else ""
26403
+ print(f"{n}. {title}{kind}")
26404
+ print(f" {when} · project {e['project']} · id {e['session_id']}")
26405
+ sub = e["subagents"]
26406
+ sub_txt = f" · {sub['count']} subagent run{'s' if sub['count'] != 1 else ''}" if sub["count"] else ""
26407
+ print(f" {_fmt_session_cost_duration(e['duration_minutes'])} · {e['api_calls']} calls{sub_txt}")
26408
+ models = " · ".join(
26409
+ f"{m['model']} {_usd(m['cost_usd'])}" + ("" if m["priced"] else " (no price card)")
26410
+ for m in e["models"]) or "none recorded"
26411
+ print(f" Models: {models}")
26412
+ t = e["tokens"]
26413
+ print(f" Tokens: {_fmt_session_cost_tokens(t['input'])} input · "
26414
+ f"{_fmt_session_cost_tokens(t['output'])} output · "
26415
+ f"{_fmt_session_cost_tokens(t['cache_read'])} cache read · "
26416
+ f"{_fmt_session_cost_tokens(t['cache_write'])} cache write")
26417
+ c = e["cost_usd"]
26418
+ print(f" Cost: input {_usd(c['input'])} · output {_usd(c['output'])} · "
26419
+ f"cache read {_usd(c['cache_read'])} · cache write {_usd(c['cache_write'])}"
26420
+ + (f" · long-context {_usd(c['long_context_adjustment'])}" if "long_context_adjustment" in c else ""))
26421
+ split = ""
26422
+ if (sub["count"] or c["subagents"] > 0) and sub["included"]:
26423
+ split = f" (main thread {_usd(c['main_thread'])} + subagents {_usd(c['subagents'])})"
26424
+ elif sub["count"]:
26425
+ split = " (main thread only; subagents are added on the next collection)"
26426
+ print(f" Total: {_usd(c['total'])}{split}")
26427
+ if "on_date" in c:
26428
+ print(f" Of which on {date_filter}: {_usd(c['on_date'])}")
26429
+ if e["partial"]:
26430
+ print(f" Partial: {e['partial_reason']} (figures as of {e['collected_at']}).")
26431
+
26432
+
26433
+ def session_cost_main(argv):
26434
+ """`measure.py session-cost [words...] [--id UUID] [--date D] [--days N]
26435
+ [--limit N] [--json]`: what a session cost, from the user's own words."""
26436
+ res = session_cost_query(argv)
26437
+ if "--json" in argv:
26438
+ print(json.dumps(res, indent=2, ensure_ascii=False, default=str))
26439
+ return 1 if res.get("error") else 0
26440
+ if res.get("error"):
26441
+ print(f"[Token Optimizer] {res['error']}")
26442
+ return 1
26443
+ q = res["query"]
26444
+ scope = []
26445
+ if q["words"]:
26446
+ scope.append("“" + " ".join(q["words"]) + "”")
26447
+ if q["id"]:
26448
+ scope.append(f"id {q['id']}")
26449
+ if q["date"]:
26450
+ scope.append(f"on {q['date']}")
26451
+ elif q.get("days"):
26452
+ scope.append(f"in the last {q['days']} days")
26453
+ scope_txt = " ".join(scope) or "all sessions"
26454
+ if res["match_count"]:
26455
+ n = res["match_count"]
26456
+ print(f"Session cost: {n} session{'s' if n != 1 else ''} {scope_txt}"
26457
+ + (f", {_usd(res['total_cost_usd'])} in total" if n > 1 else ""))
26458
+ if res["shown"] < n:
26459
+ print(f"(showing the newest {res['shown']}; --limit N shows more)")
26460
+ print()
26461
+ for i, e in enumerate(res["sessions"], 1):
26462
+ _print_session_cost_entry(i, e, q["date"])
26463
+ print()
26464
+ else:
26465
+ print(f"Session cost: no session matches {scope_txt}.")
26466
+ if res.get("note"):
26467
+ print(res["note"])
26468
+ if res["closest"]:
26469
+ print()
26470
+ print("Closest sessions:")
26471
+ print()
26472
+ for i, e in enumerate(res["closest"], 1):
26473
+ _print_session_cost_entry(i, e, q["date"])
26474
+ print()
26475
+ print(f"Basis: {res['basis']}")
26476
+ if res.get("read_mode") == "snapshot":
26477
+ print("Read from a lock-free snapshot; the very latest writes may be missing.")
26478
+ return 0
26479
+
26480
+
25822
26481
  def _collect_trends_from_db(days=30):
25823
26482
  """Query SQLite trends DB for aggregated usage data.
25824
26483
 
@@ -26016,24 +26675,6 @@ def _query_trends_db(conn, days):
26016
26675
  (cutoff,),
26017
26676
  ).fetchall()
26018
26677
 
26019
- def _price_buckets(mb):
26020
- """(priced_tokens, unpriced_tokens) for a per-model breakdown."""
26021
- priced = unpriced = 0
26022
- for model_name, parts in (mb or {}).items():
26023
- if not isinstance(parts, dict):
26024
- continue
26025
- model_tokens = (
26026
- int(parts.get("fresh_input") or 0)
26027
- + int(parts.get("cache_read") or 0)
26028
- + int(parts.get("cache_create") or 0)
26029
- + int(parts.get("output") or 0)
26030
- )
26031
- if _is_priced_model(model_name, tier=pricing_tier):
26032
- priced += model_tokens
26033
- else:
26034
- unpriced += model_tokens
26035
- return priced, unpriced
26036
-
26037
26678
  def _day_entry(date):
26038
26679
  if date not in daily:
26039
26680
  daily[date] = {
@@ -26056,85 +26697,20 @@ def _query_trends_db(conn, days):
26056
26697
  except (json.JSONDecodeError, TypeError):
26057
26698
  subagents = {}
26058
26699
 
26059
- # Estimate cost from stored data
26700
+ # One pricing path for every per-session dollar figure (the dashboard
26701
+ # here, `session-cost` for plain-language questions): _price_session_row.
26060
26702
  inp_total = sr["input_tokens"] or 0
26061
26703
  out_total = sr["output_tokens"] or 0
26062
26704
  chr_val = sr["cache_hit_rate"] or 0
26063
- cache_read_est = _safe_int(inp_total * chr_val)
26064
26705
  cache_create_1h = sr["cache_create_1h_tokens"] or 0
26065
26706
  cache_create_5m = sr["cache_create_5m_tokens"] or 0
26066
- cache_create_total = cache_create_1h + cache_create_5m
26067
- uncached_est = max(0, inp_total - cache_read_est - cache_create_total)
26068
-
26069
- # Determine dominant model from model_usage_json
26070
- try:
26071
- mu_raw = sr["model_usage_json"]
26072
- mu = json.loads(mu_raw) if mu_raw else {}
26073
- except (json.JSONDecodeError, TypeError, KeyError):
26074
- mu = {}
26075
- dom_model = max(mu, key=mu.get) if mu else "unknown"
26076
- try:
26077
- mb_raw = sr["model_usage_breakdown_json"]
26078
- mb = json.loads(mb_raw) if mb_raw else {}
26079
- except (json.JSONDecodeError, TypeError, KeyError):
26080
- mb = {}
26081
- try:
26082
- du_raw = sr["daily_usage_json"]
26083
- du = json.loads(du_raw) if du_raw else {}
26084
- except (json.JSONDecodeError, TypeError, KeyError):
26085
- du = {}
26086
- if not isinstance(du, dict):
26087
- du = {}
26088
-
26089
- if isinstance(mb, dict) and mb:
26090
- session_priced_tokens, session_unpriced_tokens = _price_buckets(mb)
26091
- else:
26092
- model_tokens = inp_total + out_total
26093
- if _is_priced_model(dom_model, tier=pricing_tier):
26094
- session_priced_tokens, session_unpriced_tokens = model_tokens, 0
26095
- else:
26096
- session_priced_tokens, session_unpriced_tokens = 0, model_tokens
26097
- # Main-thread cost from the stored session breakdown. Used as-is for rows
26098
- # without per-day data (non-JSONL adapters, transcript gone).
26099
- session_cost = _cost_from_model_breakdown(mb, tier=pricing_tier,
26100
- cache_create_1h=cache_create_1h if cache_create_1h or cache_create_5m else None,
26101
- cache_create_5m=cache_create_5m if cache_create_1h or cache_create_5m else None)
26102
- if session_cost == 0.0:
26103
- # Use the stored 1h/5m split when available; fall back to 5m-only rate otherwise.
26104
- if cache_create_1h or cache_create_5m:
26105
- session_cost = _get_model_cost(dom_model, uncached_est, out_total, cache_read_est, cache_create_total,
26106
- tier=pricing_tier, cache_create_1h=cache_create_1h, cache_create_5m=cache_create_5m)
26107
- else:
26108
- session_cost = _get_model_cost(dom_model, uncached_est, out_total, cache_read_est, cache_create_total, tier=pricing_tier)
26109
- if session_cost == 0.0 and session_priced_tokens == 0 and session_unpriced_tokens == 0 and (inp_total or out_total):
26110
- session_unpriced_tokens = inp_total + out_total
26111
-
26112
- # Per-day slices (#200). With per-day data, each calendar day is billed for
26113
- # the requests that ran on it, subagents included; a day before the window
26114
- # is dropped. Without it, the whole session lands on its stored date.
26115
- slices = [] # (date, cost, priced, unpriced, input_tokens, output_tokens)
26116
- if du:
26117
- by_day = {}
26118
- undated_day = _undated_bill_day(du, sr["date"])
26119
- for day, day_mb in du.items():
26120
- if not isinstance(day_mb, dict):
26121
- continue
26122
- day = undated_day if day == UNDATED_USAGE_KEY else day
26123
- _merge_daily_usage(by_day.setdefault(day, {}), {"_": day_mb})
26124
- for day in sorted(by_day):
26125
- day_mb = by_day[day].get("_", {})
26126
- day_cost = _cost_from_model_breakdown(day_mb, tier=pricing_tier)
26127
- day_priced, day_unpriced = _price_buckets(day_mb)
26128
- day_in = sum(
26129
- int(p.get("fresh_input") or 0) + int(p.get("cache_read") or 0) + int(p.get("cache_create") or 0)
26130
- for p in day_mb.values() if isinstance(p, dict))
26131
- day_out = sum(int(p.get("output") or 0) for p in day_mb.values() if isinstance(p, dict))
26132
- slices.append([day, day_cost, day_priced, day_unpriced, day_in, day_out])
26133
- session_total_cost = sum(sl[1] for sl in slices)
26134
- slices = [sl for sl in slices if sl[0] >= cutoff]
26135
- else:
26136
- session_total_cost = session_cost
26137
- slices = [[sr["date"], session_cost, session_priced_tokens, session_unpriced_tokens, inp_total, out_total]]
26707
+ priced_row = _price_session_row(sr, pricing_tier)
26708
+ mu = priced_row["model_usage"]
26709
+ dom_model = priced_row["dom_model"]
26710
+ du = priced_row["daily_usage"]
26711
+ session_total_cost = priced_row["total_cost"]
26712
+ # A day before the window is dropped.
26713
+ slices = [sl for sl in priced_row["slices"] if sl[0] >= cutoff]
26138
26714
 
26139
26715
  window_unpriced = 0
26140
26716
  jsonl_path = sr["jsonl_path"]
@@ -29048,12 +29624,13 @@ def _is_compaction_runner(cmd, event):
29048
29624
  return bool(re.search(r"(?:^|[\s\"'/\\])" + name + r"\.py(?:$|[\s\"';])", cmd))
29049
29625
 
29050
29626
 
29051
- def _is_hook_installed(settings=None):
29627
+ def _is_hook_installed(settings=None, settings_only=False):
29052
29628
  """Check if the SessionEnd measure.py collect hook is installed.
29053
29629
 
29054
29630
  Returns True if any SessionEnd hook command contains 'measure.py collect'.
29055
29631
  Recognizes both old (collect-only) and new (collect + dashboard) hook commands.
29056
- Also checks plugin cache hooks (auto-installed via marketplace plugin).
29632
+ Also checks plugin cache hooks (auto-installed via marketplace plugin), unless
29633
+ ``settings_only`` asks only whether settings.json carries it (doctor's label).
29057
29634
  """
29058
29635
  # Check user settings.json
29059
29636
  if settings is None:
@@ -29078,6 +29655,9 @@ def _is_hook_installed(settings=None):
29078
29655
  ):
29079
29656
  return True
29080
29657
 
29658
+ if settings_only:
29659
+ return False
29660
+
29081
29661
  # Check plugin cache hooks (marketplace plugin auto-install)
29082
29662
  plugin_cache = CLAUDE_DIR / "plugins" / "cache"
29083
29663
  if plugin_cache.exists():
@@ -31926,6 +32506,14 @@ def _hook_command_identity(cmd):
31926
32506
  if not cmd:
31927
32507
  return ""
31928
32508
 
32509
+ # The plugin's version resolver (D="$(ls -d ... | sort -V | tail -n1)") is
32510
+ # plumbing, not identity: drop that one flat $(...) so a resolver command
32511
+ # keeps the identity of its handler instead of collapsing to "run.py" for
32512
+ # every hook (which would make setup_all_hooks/dedup treat all of an event's
32513
+ # hooks as one).
32514
+ if 'D="$(ls -d ' in cmd:
32515
+ cmd = re.sub(r'D="\$\(ls -d [^()]*\)"', 'D=""', cmd)
32516
+
31929
32517
  # Subshell fallback: commands with $(...) or backticks confuse shlex —
31930
32518
  # shell noise (2>/dev/null, |, sort, -V) leaks into identity tokens.
31931
32519
  # Extract .py name via regex and find subcommand/flags after the closing ).
@@ -34709,8 +35297,11 @@ def _ensure_dashboard_daemon(force=False):
34709
35297
  landing-verification.) Never raises.
34710
35298
  """
34711
35299
  # An explicit snapshot override is an isolation boundary, including when a
34712
- # detached daemon-revive child calls this with force=True.
34713
- if _scheduler_install_refused():
35300
+ # detached daemon-revive child calls this with force=True. Frozen flag
35301
+ # only up here: this is the SessionStart hot path, and the full guard's
35302
+ # job check runs `schtasks /Query` on Windows. It runs below, once the
35303
+ # cheap gates and the health probe say a repair is actually due.
35304
+ if _daemon_snapshot_sandboxed():
34714
35305
  return "noop-sandbox"
34715
35306
  # Claude Code cloud VM: no browser to open the URL in, and no systemd user
34716
35307
  # bus to install a unit on (the install path fails in containers).
@@ -34746,6 +35337,11 @@ def _ensure_dashboard_daemon(force=False):
34746
35337
  if installed and alive:
34747
35338
  return "noop-healthy"
34748
35339
 
35340
+ # A repair is due. Refuse it (before stamping the throttle) when the
35341
+ # account's job belongs to another install: writing ours would re-point it.
35342
+ if _scheduler_install_refused():
35343
+ return "noop-sandbox"
35344
+
34749
35345
  # We need the costly path (install or restart). Throttle the ATTEMPT so a
34750
35346
  # persistently-failing install doesn't shell out every prompt. The cheap
34751
35347
  # probe above still runs every time, so a daemon that comes back healthy is
@@ -35222,7 +35818,9 @@ def _heal_windows_task_action(stop_first=False, throttle=False):
35222
35818
  """
35223
35819
  # Per-account scheduler job: never touched from a redirected HOME
35224
35820
  # (a test sandbox or scratch run would re-point the user's live job).
35225
- if _scheduler_install_refused():
35821
+ # Frozen flag here; the job check (a `schtasks /Query`) waits until the
35822
+ # cheap gates below say a heal is actually due.
35823
+ if _daemon_snapshot_sandboxed():
35226
35824
  return False
35227
35825
  try:
35228
35826
  if os.name != "nt":
@@ -35249,6 +35847,10 @@ def _heal_windows_task_action(stop_first=False, throttle=False):
35249
35847
  return False # nothing better to migrate TO (a DEAD action is
35250
35848
  # always worth re-registering: the .cmd fallback beats a daemon
35251
35849
  # that can never start again)
35850
+ # A heal is due. Refuse it when the registered task belongs to
35851
+ # another install (re-registering would re-point it at this one).
35852
+ if _scheduler_install_refused():
35853
+ return False
35252
35854
  if throttle:
35253
35855
  # A heal that keeps failing (policy-blocked /Create,
35254
35856
  # foreign process on the port) must not bounce the daemon every
@@ -35471,12 +36073,17 @@ def _restart_dashboard_daemon(system):
35471
36073
  would SIGTERM session A's freshly-bound correct daemon, causing a restart
35472
36074
  flap. Checking the served version first makes the whole restart idempotent.
35473
36075
  """
35474
- if _scheduler_install_refused():
36076
+ if _daemon_snapshot_sandboxed():
35475
36077
  return "noop-sandbox"
35476
36078
  try:
35477
- # Already current (a sibling session fixed it)? Do not reap/restart.
36079
+ # Already current (a sibling session fixed it)? Do not reap/restart,
36080
+ # and do not pay for the job check below (`schtasks /Query` on
36081
+ # Windows): nothing is about to be written.
35478
36082
  if _daemon_served_version() == TOKEN_OPTIMIZER_VERSION:
35479
36083
  return "restarted"
36084
+ # About to reap and restart: refuse when the job is another install's.
36085
+ if _scheduler_install_refused():
36086
+ return "noop-sandbox"
35480
36087
 
35481
36088
  # Reap our own orphaned port-holder first (never a foreign process).
35482
36089
  try:
@@ -35806,6 +36413,12 @@ _PROGRESSIVE_BANDS = [20, 35, 50, 65, 80]
35806
36413
  _PROGRESSIVE_ENABLED = os.environ.get("TOKEN_OPTIMIZER_PROGRESSIVE_CHECKPOINTS", "1") not in ("0", "false", "no", "off")
35807
36414
  _QUALITY_CHECKPOINT_THRESHOLDS = [80, 70, 50, 40]
35808
36415
  _CHECKPOINT_COOLDOWN_SECONDS = _int_env("TOKEN_OPTIMIZER_CHECKPOINT_COOLDOWN_SECONDS", 90)
36416
+ # A post-compact restore treats the session's newest PreCompact ("auto") checkpoint
36417
+ # as the moment of the compaction it is restoring for, when it is this recent.
36418
+ # Compaction (PreCompact capture -> summary request -> SessionStart(compact)) runs
36419
+ # in minutes; an older one belongs to an earlier compaction whose own PreCompact
36420
+ # capture is all this one has to go on (e.g. #253: the capture was cut off).
36421
+ _COMPACT_RESTORE_ANCHOR_MAX_AGE_S = 1800
35809
36422
  _EDIT_BATCH_WRITE_THRESHOLD = _int_env("TOKEN_OPTIMIZER_EDIT_BATCH_WRITE_THRESHOLD", 4)
35810
36423
  _EDIT_BATCH_FILE_THRESHOLD = _int_env("TOKEN_OPTIMIZER_EDIT_BATCH_FILE_THRESHOLD", 3)
35811
36424
  _CHECKPOINT_TELEMETRY_ENABLED = os.environ.get("TOKEN_OPTIMIZER_CHECKPOINT_TELEMETRY", "0").lower() in ("1", "true", "yes", "on")
@@ -36655,7 +37268,8 @@ def compute_quality_score(quality_data, session_id=None):
36655
37268
  elif _worst_key == "context_fill_degradation":
36656
37269
  top_drag = {
36657
37270
  "key": "context_fill",
36658
- "label": f"{round(fill_pct * 100)}% context fill",
37271
+ "label": (f"{round(model_fill * 100)}% context fill ({round(fill_pct * 100)}% of the way to auto-compact)"
37272
+ if compact_window_reduced else f"{round(fill_pct * 100)}% context fill"),
36659
37273
  "points": round(_worst_pts, 1),
36660
37274
  }
36661
37275
  elif _worst_key == "compaction_depth":
@@ -36706,8 +37320,8 @@ def compute_quality_score(quality_data, session_id=None):
36706
37320
  _cfd_detail = f"{round(fill_pct * 100)}% fill, {band_name.lower()} ({curve_name})"
36707
37321
  if compact_window_reduced:
36708
37322
  _cfd_detail = (
36709
- f"{round(fill_pct * 100)}% of compact window "
36710
- f"({round(model_fill * 100)}% of model window), "
37323
+ f"{round(model_fill * 100)}% of model window "
37324
+ f"({round(fill_pct * 100)}% of the way to auto-compact), "
36711
37325
  f"{band_name.lower()} ({curve_name})"
36712
37326
  )
36713
37327
 
@@ -39721,6 +40335,61 @@ def _security_report(as_json=False):
39721
40335
  # PreCompact state capture, SessionStart restoration, Compact Instructions generation.
39722
40336
  # All logic in Python for cross-platform compatibility.
39723
40337
 
40338
+ def _iter_tail_lines(filepath, tail_lines, chunk_size=1 << 20):
40339
+ """Return the tail lines of a JSONL transcript covering its last records.
40340
+
40341
+ Equivalent to what ``for line in open(filepath)`` yields, restricted to a
40342
+ suffix window large enough that the caller's ``deque(maxlen=tail_lines)``
40343
+ sees the same records as a whole-file pass: the window extends backwards
40344
+ from EOF until it holds tail_lines lines that pass the caller's own
40345
+ filters (size cap + json.loads), or the file start is reached. A large
40346
+ transcript then costs a small window read instead of reading and parsing
40347
+ every byte. The window grows geometrically, so even a transcript whose
40348
+ tail needs most of the file costs about one extra pass, not a rescan per
40349
+ chunk.
40350
+
40351
+ Two equivalence details:
40352
+
40353
+ - Lines come from ``StringIO(text, newline=None)``, which iterates with
40354
+ the same universal-newline semantics as text-mode file iteration, so
40355
+ the caller's ``len(line)`` cap and ``json.loads`` see identical
40356
+ strings.
40357
+ - A window starting mid-file can cut inside a line (and inside a
40358
+ multi-byte UTF-8 sequence, where ``errors="replace"`` would diverge
40359
+ from a whole-file decode), so its first line is dropped and the window
40360
+ must hold tail_lines valid records without it. At byte 0 the window is
40361
+ the whole file and nothing is dropped.
40362
+ """
40363
+ with open(filepath, "rb") as f:
40364
+ f.seek(0, os.SEEK_END)
40365
+ pos = f.tell()
40366
+ buf = b""
40367
+ grow = chunk_size
40368
+ while True:
40369
+ start = max(0, pos - grow)
40370
+ f.seek(start)
40371
+ buf = f.read(pos - start) + buf
40372
+ pos = start
40373
+ grow *= 2
40374
+ lines = io.StringIO(
40375
+ buf.decode("utf-8", errors="replace"), newline=None
40376
+ ).readlines()
40377
+ candidates = lines if pos == 0 else lines[1:]
40378
+ valid = 0
40379
+ for line in reversed(candidates):
40380
+ if len(line) > codex_session.MAX_JSONL_LINE_CHARS:
40381
+ continue
40382
+ try:
40383
+ json.loads(line)
40384
+ except json.JSONDecodeError:
40385
+ continue
40386
+ valid += 1
40387
+ if valid >= tail_lines:
40388
+ break
40389
+ if pos == 0 or valid >= tail_lines:
40390
+ return candidates
40391
+
40392
+
39724
40393
  def _extract_session_state(filepath, tail_lines=500):
39725
40394
  """Extract structured session state from a JSONL transcript.
39726
40395
 
@@ -39768,14 +40437,13 @@ def _extract_session_state(filepath, tail_lines=500):
39768
40437
  except OSError:
39769
40438
  return None
39770
40439
  try:
39771
- with open(filepath, "r", encoding="utf-8", errors="replace") as f:
39772
- for line in f:
39773
- if len(line) > codex_session.MAX_JSONL_LINE_CHARS:
39774
- continue
39775
- try:
39776
- records.append(json.loads(line))
39777
- except json.JSONDecodeError:
39778
- continue
40440
+ for line in _iter_tail_lines(filepath, tail_lines):
40441
+ if len(line) > codex_session.MAX_JSONL_LINE_CHARS:
40442
+ continue
40443
+ try:
40444
+ records.append(json.loads(line))
40445
+ except json.JSONDecodeError:
40446
+ continue
39779
40447
  except (PermissionError, OSError):
39780
40448
  return None
39781
40449
 
@@ -39915,10 +40583,16 @@ def _capture_git_state(cwd=None):
39915
40583
  kw = {"capture_output": True, "text": True, "timeout": 2}
39916
40584
  if cwd:
39917
40585
  kw["cwd"] = cwd
39918
- br = subprocess.run(["git", "rev-parse", "--abbrev-ref", "HEAD"], **kw, creationflags=_NO_WINDOW)
39919
- sha = subprocess.run(["git", "rev-parse", "--short", "HEAD"], **kw, creationflags=_NO_WINDOW)
39920
- if br.returncode == 0 and sha.returncode == 0:
39921
- return br.stdout.strip() or None, sha.stdout.strip() or None
40586
+ # One spawn, not two: rev-parse mode flags apply in argument order,
40587
+ # so the HEAD before --abbrev-ref resolves to the full sha and the
40588
+ # HEAD after it to the branch. The sha is only a display label; [:7]
40589
+ # matches git's default --short abbreviation for any repo below its
40590
+ # auto-lengthen threshold.
40591
+ r = subprocess.run(["git", "rev-parse", "HEAD", "--abbrev-ref", "HEAD"], **kw, creationflags=_NO_WINDOW)
40592
+ if r.returncode == 0:
40593
+ out = r.stdout.splitlines()
40594
+ if len(out) >= 2:
40595
+ return out[1].strip() or None, out[0].strip()[:7] or None
39922
40596
  except Exception:
39923
40597
  pass
39924
40598
  return None, None
@@ -39968,7 +40642,13 @@ def _confine_transcript_path(transcript_path):
39968
40642
  resolved = raw.resolve()
39969
40643
  except OSError:
39970
40644
  return None
39971
- if _use_codex_session_adapter():
40645
+ # Path-aware, like the parser that reads it: the Codex marketplace plugin
40646
+ # runs these hooks with CLAUDE_PLUGIN_ROOT set and no Codex marker, so
40647
+ # detect_runtime() says "claude" there while transcript_path is a Codex
40648
+ # rollout under ~/.codex/sessions. Judging by runtime alone refused it and
40649
+ # every Codex plugin Stop exited 0 with no checkpoint (#253 class). Still
40650
+ # confined: only the Codex session roots, and only for a path inside them.
40651
+ if _use_codex_session_adapter(resolved):
39972
40652
  try:
39973
40653
  roots = [r.resolve() for r in codex_session.session_roots()]
39974
40654
  except Exception:
@@ -40180,7 +40860,7 @@ def compact_capture(transcript_path=None, session_id=None, trigger="auto", cwd=N
40180
40860
  lines.append("## Context Quality")
40181
40861
  lines.append(
40182
40862
  f"- Score: {quality_summary.get('grade', '?')} ({quality_summary.get('score', '?')}/100)"
40183
- f" | Fill: {cfd.get('fill_pct', '?')}%"
40863
+ f" | Fill: {_format_context_fill(cfd.get('fill_pct'), cfd)}"
40184
40864
  f" | Model: {cfd.get('model') or quality_summary.get('model') or 'unknown'}"
40185
40865
  )
40186
40866
  if cfd.get("quality_curve"):
@@ -41015,6 +41695,18 @@ def compact_restore(session_id=None, cwd=None, is_compact=False, new_session_onl
41015
41695
  rank = _checkpoint_restore_rank(trigger)
41016
41696
  session_checkpoints.append((rank, cp))
41017
41697
 
41698
+ # Only what was saved before this compaction can restore what it replaced.
41699
+ # SessionStart(compact) and PostCompact refresh the quality cache, which can
41700
+ # capture a progressive band from the post-compact transcript: its "task" is
41701
+ # the compaction summary, and it would outrank the PreCompact capture taken
41702
+ # just before (progressive beats auto). Anything newer than this
41703
+ # compaction's PreCompact checkpoint is dropped from the choice.
41704
+ precompact = [cp["created"] for _, cp in session_checkpoints if cp.get("trigger", "auto") == "auto"]
41705
+ if precompact:
41706
+ anchor = max(precompact)
41707
+ if (now - anchor).total_seconds() <= _COMPACT_RESTORE_ANCHOR_MAX_AGE_S:
41708
+ session_checkpoints = [(r, cp) for r, cp in session_checkpoints if cp["created"] <= anchor]
41709
+
41018
41710
  if session_checkpoints:
41019
41711
  # Sort by rank (lowest = best progressive), then by recency for ties
41020
41712
  session_checkpoints.sort(key=lambda x: (x[0], -x[1]["created"].timestamp()))
@@ -42324,7 +43016,7 @@ def _continuity_prompt_hint(prompt_text="", session_id=None, cwd=None, max_age_m
42324
43016
  if quality:
42325
43017
  lines.append(
42326
43018
  f"- Prior context quality: {quality.get('grade', '?')} "
42327
- f"({quality.get('score', '?')}/100), fill {quality.get('breakdown', {}).get('context_fill_degradation', {}).get('fill_pct', '?')}%"
43019
+ f"({quality.get('score', '?')}/100), fill {_format_context_fill(quality.get('breakdown', {}).get('context_fill_degradation', {}).get('fill_pct'), quality.get('breakdown', {}).get('context_fill_degradation', {}))}"
42328
43020
  )
42329
43021
  # Per-item relevance filter: a checkpoint that passed the
42330
43022
  # same-project gate may still carry session-wide Key Decisions / Files that
@@ -43003,7 +43695,7 @@ def checkpoint_trigger(milestone=None, session_id=None, transcript_path=None, qu
43003
43695
  transcript_path=str(filepath),
43004
43696
  session_id=session_id,
43005
43697
  trigger=trigger,
43006
- fill_pct=result.get("fill_pct"),
43698
+ fill_pct=_model_window_fill(result),
43007
43699
  quality_score=result.get("score"),
43008
43700
  )
43009
43701
  if not cp_path:
@@ -45177,8 +45869,11 @@ def _maybe_fresh_session_nudge(result, cache_path, quality_data, quiet=False):
45177
45869
  saved_str = f"~{saved // 1000}K" if saved >= 1000 else f"~{saved}"
45178
45870
  usd = _fresh_session_savings_usd(saved, session_id)
45179
45871
  cost_str = f" (~${usd:.2f})" if usd >= 0.01 else ""
45872
+ # Share of the model window: what the user's meter shows (see _format_context_fill).
45873
+ shown = _model_window_fill(result)
45874
+ shown = shown if isinstance(shown, (int, float)) else fill_pct
45180
45875
  return (
45181
- f"[Token Optimizer] {int(fill_pct)}% full, quality {score}. "
45876
+ f"[Token Optimizer] {int(shown)}% full, quality {score}. "
45182
45877
  f"Fresh session reclaims {saved_str}{cost_str}. "
45183
45878
  f"Checkpoint saved, say \"continue this\"."
45184
45879
  )
@@ -46044,6 +46739,84 @@ def _migrate_statusline_to_stable_path():
46044
46739
  return False
46045
46740
 
46046
46741
 
46742
+ _STATUSLINE_JS_IN_CMD_RE = re.compile(r"""(['"])([^'"]*statusline\.js)\1|([^\s'"]*statusline\.js)""")
46743
+
46744
+
46745
+ def _statusline_js_in_command(cmd):
46746
+ """(start, end, path) of the statusline.js path inside a statusLine
46747
+ command (quoted or bare), or None."""
46748
+ m = _STATUSLINE_JS_IN_CMD_RE.search(cmd or "")
46749
+ if not m:
46750
+ return None
46751
+ if m.group(2) is not None:
46752
+ return m.start(2), m.end(2), m.group(2)
46753
+ return m.start(3), m.end(3), m.group(3)
46754
+
46755
+
46756
+ def _path_is_under(path, base):
46757
+ try:
46758
+ Path(path).expanduser().resolve(strict=False).relative_to(Path(base).resolve(strict=False))
46759
+ return True
46760
+ except (ValueError, OSError, RuntimeError):
46761
+ return False
46762
+
46763
+
46764
+ def _heal_dangling_statusline():
46765
+ """Re-point OUR statusLine when it runs a statusline.js that is gone or
46766
+ that sits in Codex's plugin cache.
46767
+
46768
+ Before 5.13.51 a Codex-loaded plugin hook was detected as Claude Code, and
46769
+ its settings heal pointed Claude Code's statusLine at the Codex plugin
46770
+ cache (deleted on Codex's next plugin update, so the status line went
46771
+ blank). The stale-path heal only rewrites ``/plugins/cache/`` roots and
46772
+ only on plugin-cache installs, so a script install, a missing file outside
46773
+ a cache, or a still-present Codex copy kept the bad command.
46774
+
46775
+ Acts only in Claude Code (never a hosted VM's lean profile), only on a
46776
+ statusLine that is ours (``statusline.js`` + ``token-optimizer`` in the
46777
+ command), and only when the referenced file is missing or under
46778
+ ``<codex home>/plugins/``. An existing statusline.js from another Token
46779
+ Optimizer checkout (a dev clone) is the user's choice and is left alone.
46780
+ Only the path inside the command changes; every other key is preserved.
46781
+ Returns True if it rewrote the command.
46782
+ """
46783
+ try:
46784
+ if detect_runtime() != "claude" or _remote_lean_profile():
46785
+ return False
46786
+ settings, _ok = _read_settings_for_write()
46787
+ if not _ok or not settings:
46788
+ return False
46789
+ sl = settings.get("statusLine")
46790
+ if not isinstance(sl, dict):
46791
+ return False
46792
+ cmd = sl.get("command") or ""
46793
+ if not isinstance(cmd, str) or "statusline.js" not in cmd or "token-optimizer" not in cmd:
46794
+ return False
46795
+ found = _statusline_js_in_command(cmd)
46796
+ if not found:
46797
+ return False
46798
+ start, end, old_path = found
46799
+ ours = _get_statusline_path()
46800
+ if not ours or not Path(ours).is_file():
46801
+ return False
46802
+ if os.path.normcase(os.path.abspath(old_path)) == os.path.normcase(os.path.abspath(ours)):
46803
+ return False
46804
+ from runtime_env import codex_home as _codex_home
46805
+ in_codex = _path_is_under(old_path, _codex_home() / "plugins")
46806
+ if Path(old_path).expanduser().is_file() and not in_codex:
46807
+ return False
46808
+ new_cmd = cmd[:start] + ours + cmd[end:]
46809
+ if cmd[start - 1:start] not in ("'", '"') and any(c.isspace() for c in ours):
46810
+ new_cmd = cmd[:start] + "'" + ours + "'" + cmd[end:]
46811
+ new_settings = dict(settings)
46812
+ new_sl = dict(sl)
46813
+ new_sl["command"] = new_cmd
46814
+ new_settings["statusLine"] = new_sl
46815
+ return bool(_write_settings_atomic(new_settings))
46816
+ except Exception:
46817
+ return False
46818
+
46819
+
46047
46820
  def _heal_keepwarm_plist_path():
46048
46821
  """Rewrite an installed keep-warm launchd plist whose measure.py path went
46049
46822
  stale onto the update-surviving marketplace clone path, then reload the agent.
@@ -46065,7 +46838,11 @@ def _heal_keepwarm_plist_path():
46065
46838
  """
46066
46839
  # Per-account scheduler job: never touched from a redirected HOME
46067
46840
  # (a test sandbox or scratch run would re-point the user's live job).
46068
- if _scheduler_install_refused():
46841
+ # Frozen flag only up here: this runs in ensure-health on EVERY
46842
+ # SessionStart, and the full guard's job check is a `schtasks /Query` on
46843
+ # Windows, where this macOS heal never has a plist to fix. The full guard
46844
+ # runs below, once a stale plist exists and needs a rewrite.
46845
+ if _daemon_snapshot_sandboxed():
46069
46846
  return False
46070
46847
  if not _is_running_from_plugin_cache():
46071
46848
  return False
@@ -46092,6 +46869,10 @@ def _heal_keepwarm_plist_path():
46092
46869
  if isinstance(a, str) and a.endswith("measure.py")), None)
46093
46870
  if idx is None or args[idx] == stable:
46094
46871
  return False
46872
+ # A rewrite is due. Refuse it when the account's job belongs to another
46873
+ # install (rewriting and reloading would re-point it at this one).
46874
+ if _scheduler_install_refused():
46875
+ return False
46095
46876
  new_args = list(args)
46096
46877
  new_args[idx] = stable
46097
46878
  new_data = dict(data)
@@ -55415,6 +56196,12 @@ def run_ensure_health():
55415
56196
  print(" [Token Optimizer] Migrated statusLine to stable path", file=sys.stderr)
55416
56197
  except Exception as _e:
55417
56198
  print(f" [Token Optimizer] statusLine path migration failed: {_e}", file=sys.stderr)
56199
+ try:
56200
+ if _heal_dangling_statusline():
56201
+ print(" [Token Optimizer] Re-pointed a statusLine that ran a missing "
56202
+ "or Codex-cache statusline.js", file=sys.stderr)
56203
+ except Exception as _e:
56204
+ print(f" [Token Optimizer] statusLine heal failed: {_e}", file=sys.stderr)
55418
56205
  # Same class for the keep-warm launchd agent: an existing plist pinned to a
55419
56206
  # version-cache measure.py path dies on plugin update and freezes the
55420
56207
  # dashboard's savings. Lift it onto the clone path (macOS-only in practice).
@@ -55636,7 +56423,11 @@ def run_ensure_health():
55636
56423
  try:
55637
56424
  already_shown = _read_config_flag("autoupdate_nudge_shown", False)
55638
56425
  qb_disabled = _read_config_flag("quality_bar_disabled", False)
56426
+ # Claude Code steps only: Codex loads the same plugin build from its
56427
+ # own plugin cache, and its users were told to open Claude Code's
56428
+ # /plugin menu.
55639
56429
  if (not _lean
56430
+ and detect_runtime() == "claude"
55640
56431
  and _is_running_from_plugin_cache()
55641
56432
  and not already_shown
55642
56433
  and not qb_disabled):
@@ -55746,6 +56537,43 @@ def _format_reduced_window_note(cached, model_window, model_size):
55746
56537
  return f" (of {_format_window_size(compact)} compact window, {share}{model_size} model window{origin})"
55747
56538
 
55748
56539
 
56540
+ def _format_context_fill(fill_pct, cached):
56541
+ """The fill phrase every model-facing message uses, e.g. "38% of 1M window".
56542
+
56543
+ Leads with the share of the MODEL window: the number the user's own context
56544
+ meter shows. With a reduced compact window the compact share follows as
56545
+ distance to auto-compact. Models quote the first number they read; leading
56546
+ with the compact share made sessions report "76% full" and offer handovers
56547
+ at 38% real fill.
56548
+ """
56549
+ cached = cached or {}
56550
+ try:
56551
+ model_window = int(cached.get("model_context_window") or 0)
56552
+ compact = int(cached.get("compact_window") or 0)
56553
+ except (TypeError, ValueError, OverflowError):
56554
+ model_window = compact = 0
56555
+ model_fill = cached.get("model_fill_pct")
56556
+ if (cached.get("compact_window_reduced") and 0 < compact < model_window
56557
+ and isinstance(fill_pct, (int, float))):
56558
+ if not isinstance(model_fill, (int, float)):
56559
+ model_fill = fill_pct * compact / model_window
56560
+ source = _safe_note_text(cached.get("compact_window_source"), extra="=.[]'", limit=64)
56561
+ origin = f", source: {source}" if source else ""
56562
+ return (f"{model_fill:.0f}% of {_format_window_size(model_window)} window "
56563
+ f"(auto-compact at {_format_window_size(compact)}, {fill_pct:.0f}% of the way there{origin})")
56564
+ if not isinstance(fill_pct, (int, float)):
56565
+ return "?%"
56566
+ return f"{fill_pct:.0f}%{_format_window_note(cached)}"
56567
+
56568
+
56569
+ def _model_window_fill(result):
56570
+ """Share of the model window for display; fill_pct when no reduction applies."""
56571
+ result = result or {}
56572
+ if result.get("compact_window_reduced") and isinstance(result.get("model_fill_pct"), (int, float)):
56573
+ return result["model_fill_pct"]
56574
+ return result.get("fill_pct")
56575
+
56576
+
55749
56577
  def _format_window_note(cached):
55750
56578
  """Render the denominator and its origin, e.g. " (1M window, source: default 1M)".
55751
56579
 
@@ -56078,7 +56906,7 @@ def run_verbosity_steer(transcript_path=None, quiet=True, session_id=None):
56078
56906
  if fill_pct >= 90:
56079
56907
  if not quiet:
56080
56908
  sys.stderr.write(
56081
- f"[Token Optimizer] Context at {fill_pct:.0f}%{window_note} — consider /compact or /clear. "
56909
+ f"[Token Optimizer] Context at {_format_context_fill(fill_pct, cached)} — consider /compact or /clear. "
56082
56910
  f"Verbosity nudge suppressed to avoid adding tokens.\n"
56083
56911
  )
56084
56912
  return ""
@@ -56107,7 +56935,7 @@ def run_verbosity_steer(transcript_path=None, quiet=True, session_id=None):
56107
56935
  # the Sonnet figure as the product number.
56108
56936
  if fill_pct >= 75:
56109
56937
  nudge = (
56110
- f"[Token Optimizer] Context {fill_pct:.0f}%{window_note}, resource health {score:.0f}/100. "
56938
+ f"[Token Optimizer] Context {_format_context_fill(fill_pct, cached)}, resource health {score:.0f}/100. "
56111
56939
  "Answer in a focused and spartan way, as if the user has ADHD. Cut everything "
56112
56940
  "that is not the answer itself. Think as long as you need, and size code, "
56113
56941
  "diffs and file contents to the task."
@@ -56115,7 +56943,7 @@ def run_verbosity_steer(transcript_path=None, quiet=True, session_id=None):
56115
56943
  elif (fill_pct >= _VERBOSITY_NUDGE_MIN_FILL
56116
56944
  and session_efficiency < _VERBOSITY_NUDGE_EFFICIENCY_THRESHOLD):
56117
56945
  nudge = (
56118
- f"[Token Optimizer] Context {fill_pct:.0f}%{window_note}, "
56946
+ f"[Token Optimizer] Context {_format_context_fill(fill_pct, cached)}, "
56119
56947
  f"session efficiency {session_efficiency:.0f}/100. "
56120
56948
  "Answer in a focused and spartan way, as if the user has ADHD. "
56121
56949
  "Think as long as you need, and size code, diffs and file contents to the task."
@@ -58536,6 +59364,9 @@ if __name__ == "__main__":
58536
59364
  # PostToolUse hook handler: archive large tool results
58537
59365
  quiet = "--quiet" in args or "-q" in args
58538
59366
  archive_result(quiet=quiet)
59367
+ elif args[0] == "session-cost":
59368
+ # "What did the Garden session yesterday cost?" Read-only; see session_cost_main.
59369
+ sys.exit(session_cost_main(args[1:]))
58539
59370
  elif args[0] == "expand":
58540
59371
  # Retrieve archived tool result
58541
59372
  list_all = "--list" in args
@@ -58672,7 +59503,7 @@ if __name__ == "__main__":
58672
59503
  print(" python3 measure.py setup-hook --dry-run # Show what would be installed")
58673
59504
  print(" python3 measure.py setup-hook --uninstall # Remove Token Optimizer's SessionEnd hook")
58674
59505
  print(" python3 measure.py compact-capture # Capture session state checkpoint")
58675
- print(" python3 measure.py compact-capture --budget-seconds N # Allow up to N s (default 8, max 60)")
59506
+ print(" python3 measure.py compact-capture --budget-seconds N # Allow up to N s (default 14, max 60)")
58676
59507
  print(" python3 measure.py checkpoint-trigger --milestone pre-fanout # Milestone checkpoint with guards")
58677
59508
  print(" python3 measure.py compact-restore # Restore context from checkpoint")
58678
59509
  print(" python3 measure.py continue-last --topic TEXT # Show Codex continuity hint for a topic")
@@ -58717,6 +59548,8 @@ if __name__ == "__main__":
58717
59548
  print(" python3 measure.py attention-optimize --apply # Apply reordering (backup + write)")
58718
59549
  print(" python3 measure.py archive-result # PostToolUse hook: archive large tool results")
58719
59550
  print(" python3 measure.py archive-result --quiet # Silent mode (suppress stderr)")
59551
+ print(" python3 measure.py session-cost garden --date yesterday # What a session cost, in your words (read-only)")
59552
+ print(" python3 measure.py session-cost --id UUID --json # One session by id, machine-readable")
58720
59553
  print(" python3 measure.py expand TOOL_USE_ID # Retrieve archived tool result")
58721
59554
  print(" python3 measure.py expand TOOL_USE_ID --session SID # Retrieve from specific session")
58722
59555
  print(" python3 measure.py expand --list # List all archived results")