@alexgreensh/token-optimizer 5.13.50 → 5.13.51

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 Navina 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")
@@ -39721,6 +40334,61 @@ def _security_report(as_json=False):
39721
40334
  # PreCompact state capture, SessionStart restoration, Compact Instructions generation.
39722
40335
  # All logic in Python for cross-platform compatibility.
39723
40336
 
40337
+ def _iter_tail_lines(filepath, tail_lines, chunk_size=1 << 20):
40338
+ """Return the tail lines of a JSONL transcript covering its last records.
40339
+
40340
+ Equivalent to what ``for line in open(filepath)`` yields, restricted to a
40341
+ suffix window large enough that the caller's ``deque(maxlen=tail_lines)``
40342
+ sees the same records as a whole-file pass: the window extends backwards
40343
+ from EOF until it holds tail_lines lines that pass the caller's own
40344
+ filters (size cap + json.loads), or the file start is reached. A large
40345
+ transcript then costs a small window read instead of reading and parsing
40346
+ every byte. The window grows geometrically, so even a transcript whose
40347
+ tail needs most of the file costs about one extra pass, not a rescan per
40348
+ chunk.
40349
+
40350
+ Two equivalence details:
40351
+
40352
+ - Lines come from ``StringIO(text, newline=None)``, which iterates with
40353
+ the same universal-newline semantics as text-mode file iteration, so
40354
+ the caller's ``len(line)`` cap and ``json.loads`` see identical
40355
+ strings.
40356
+ - A window starting mid-file can cut inside a line (and inside a
40357
+ multi-byte UTF-8 sequence, where ``errors="replace"`` would diverge
40358
+ from a whole-file decode), so its first line is dropped and the window
40359
+ must hold tail_lines valid records without it. At byte 0 the window is
40360
+ the whole file and nothing is dropped.
40361
+ """
40362
+ with open(filepath, "rb") as f:
40363
+ f.seek(0, os.SEEK_END)
40364
+ pos = f.tell()
40365
+ buf = b""
40366
+ grow = chunk_size
40367
+ while True:
40368
+ start = max(0, pos - grow)
40369
+ f.seek(start)
40370
+ buf = f.read(pos - start) + buf
40371
+ pos = start
40372
+ grow *= 2
40373
+ lines = io.StringIO(
40374
+ buf.decode("utf-8", errors="replace"), newline=None
40375
+ ).readlines()
40376
+ candidates = lines if pos == 0 else lines[1:]
40377
+ valid = 0
40378
+ for line in reversed(candidates):
40379
+ if len(line) > codex_session.MAX_JSONL_LINE_CHARS:
40380
+ continue
40381
+ try:
40382
+ json.loads(line)
40383
+ except json.JSONDecodeError:
40384
+ continue
40385
+ valid += 1
40386
+ if valid >= tail_lines:
40387
+ break
40388
+ if pos == 0 or valid >= tail_lines:
40389
+ return candidates
40390
+
40391
+
39724
40392
  def _extract_session_state(filepath, tail_lines=500):
39725
40393
  """Extract structured session state from a JSONL transcript.
39726
40394
 
@@ -39768,14 +40436,13 @@ def _extract_session_state(filepath, tail_lines=500):
39768
40436
  except OSError:
39769
40437
  return None
39770
40438
  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
40439
+ for line in _iter_tail_lines(filepath, tail_lines):
40440
+ if len(line) > codex_session.MAX_JSONL_LINE_CHARS:
40441
+ continue
40442
+ try:
40443
+ records.append(json.loads(line))
40444
+ except json.JSONDecodeError:
40445
+ continue
39779
40446
  except (PermissionError, OSError):
39780
40447
  return None
39781
40448
 
@@ -39915,10 +40582,16 @@ def _capture_git_state(cwd=None):
39915
40582
  kw = {"capture_output": True, "text": True, "timeout": 2}
39916
40583
  if cwd:
39917
40584
  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
40585
+ # One spawn, not two: rev-parse mode flags apply in argument order,
40586
+ # so the HEAD before --abbrev-ref resolves to the full sha and the
40587
+ # HEAD after it to the branch. The sha is only a display label; [:7]
40588
+ # matches git's default --short abbreviation for any repo below its
40589
+ # auto-lengthen threshold.
40590
+ r = subprocess.run(["git", "rev-parse", "HEAD", "--abbrev-ref", "HEAD"], **kw, creationflags=_NO_WINDOW)
40591
+ if r.returncode == 0:
40592
+ out = r.stdout.splitlines()
40593
+ if len(out) >= 2:
40594
+ return out[1].strip() or None, out[0].strip()[:7] or None
39922
40595
  except Exception:
39923
40596
  pass
39924
40597
  return None, None
@@ -39968,7 +40641,13 @@ def _confine_transcript_path(transcript_path):
39968
40641
  resolved = raw.resolve()
39969
40642
  except OSError:
39970
40643
  return None
39971
- if _use_codex_session_adapter():
40644
+ # Path-aware, like the parser that reads it: the Codex marketplace plugin
40645
+ # runs these hooks with CLAUDE_PLUGIN_ROOT set and no Codex marker, so
40646
+ # detect_runtime() says "claude" there while transcript_path is a Codex
40647
+ # rollout under ~/.codex/sessions. Judging by runtime alone refused it and
40648
+ # every Codex plugin Stop exited 0 with no checkpoint (#253 class). Still
40649
+ # confined: only the Codex session roots, and only for a path inside them.
40650
+ if _use_codex_session_adapter(resolved):
39972
40651
  try:
39973
40652
  roots = [r.resolve() for r in codex_session.session_roots()]
39974
40653
  except Exception:
@@ -41015,6 +41694,18 @@ def compact_restore(session_id=None, cwd=None, is_compact=False, new_session_onl
41015
41694
  rank = _checkpoint_restore_rank(trigger)
41016
41695
  session_checkpoints.append((rank, cp))
41017
41696
 
41697
+ # Only what was saved before this compaction can restore what it replaced.
41698
+ # SessionStart(compact) and PostCompact refresh the quality cache, which can
41699
+ # capture a progressive band from the post-compact transcript: its "task" is
41700
+ # the compaction summary, and it would outrank the PreCompact capture taken
41701
+ # just before (progressive beats auto). Anything newer than this
41702
+ # compaction's PreCompact checkpoint is dropped from the choice.
41703
+ precompact = [cp["created"] for _, cp in session_checkpoints if cp.get("trigger", "auto") == "auto"]
41704
+ if precompact:
41705
+ anchor = max(precompact)
41706
+ if (now - anchor).total_seconds() <= _COMPACT_RESTORE_ANCHOR_MAX_AGE_S:
41707
+ session_checkpoints = [(r, cp) for r, cp in session_checkpoints if cp["created"] <= anchor]
41708
+
41018
41709
  if session_checkpoints:
41019
41710
  # Sort by rank (lowest = best progressive), then by recency for ties
41020
41711
  session_checkpoints.sort(key=lambda x: (x[0], -x[1]["created"].timestamp()))
@@ -46044,6 +46735,84 @@ def _migrate_statusline_to_stable_path():
46044
46735
  return False
46045
46736
 
46046
46737
 
46738
+ _STATUSLINE_JS_IN_CMD_RE = re.compile(r"""(['"])([^'"]*statusline\.js)\1|([^\s'"]*statusline\.js)""")
46739
+
46740
+
46741
+ def _statusline_js_in_command(cmd):
46742
+ """(start, end, path) of the statusline.js path inside a statusLine
46743
+ command (quoted or bare), or None."""
46744
+ m = _STATUSLINE_JS_IN_CMD_RE.search(cmd or "")
46745
+ if not m:
46746
+ return None
46747
+ if m.group(2) is not None:
46748
+ return m.start(2), m.end(2), m.group(2)
46749
+ return m.start(3), m.end(3), m.group(3)
46750
+
46751
+
46752
+ def _path_is_under(path, base):
46753
+ try:
46754
+ Path(path).expanduser().resolve(strict=False).relative_to(Path(base).resolve(strict=False))
46755
+ return True
46756
+ except (ValueError, OSError, RuntimeError):
46757
+ return False
46758
+
46759
+
46760
+ def _heal_dangling_statusline():
46761
+ """Re-point OUR statusLine when it runs a statusline.js that is gone or
46762
+ that sits in Codex's plugin cache.
46763
+
46764
+ Before 5.13.51 a Codex-loaded plugin hook was detected as Claude Code, and
46765
+ its settings heal pointed Claude Code's statusLine at the Codex plugin
46766
+ cache (deleted on Codex's next plugin update, so the status line went
46767
+ blank). The stale-path heal only rewrites ``/plugins/cache/`` roots and
46768
+ only on plugin-cache installs, so a script install, a missing file outside
46769
+ a cache, or a still-present Codex copy kept the bad command.
46770
+
46771
+ Acts only in Claude Code (never a hosted VM's lean profile), only on a
46772
+ statusLine that is ours (``statusline.js`` + ``token-optimizer`` in the
46773
+ command), and only when the referenced file is missing or under
46774
+ ``<codex home>/plugins/``. An existing statusline.js from another Token
46775
+ Optimizer checkout (a dev clone) is the user's choice and is left alone.
46776
+ Only the path inside the command changes; every other key is preserved.
46777
+ Returns True if it rewrote the command.
46778
+ """
46779
+ try:
46780
+ if detect_runtime() != "claude" or _remote_lean_profile():
46781
+ return False
46782
+ settings, _ok = _read_settings_for_write()
46783
+ if not _ok or not settings:
46784
+ return False
46785
+ sl = settings.get("statusLine")
46786
+ if not isinstance(sl, dict):
46787
+ return False
46788
+ cmd = sl.get("command") or ""
46789
+ if not isinstance(cmd, str) or "statusline.js" not in cmd or "token-optimizer" not in cmd:
46790
+ return False
46791
+ found = _statusline_js_in_command(cmd)
46792
+ if not found:
46793
+ return False
46794
+ start, end, old_path = found
46795
+ ours = _get_statusline_path()
46796
+ if not ours or not Path(ours).is_file():
46797
+ return False
46798
+ if os.path.normcase(os.path.abspath(old_path)) == os.path.normcase(os.path.abspath(ours)):
46799
+ return False
46800
+ from runtime_env import codex_home as _codex_home
46801
+ in_codex = _path_is_under(old_path, _codex_home() / "plugins")
46802
+ if Path(old_path).expanduser().is_file() and not in_codex:
46803
+ return False
46804
+ new_cmd = cmd[:start] + ours + cmd[end:]
46805
+ if cmd[start - 1:start] not in ("'", '"') and any(c.isspace() for c in ours):
46806
+ new_cmd = cmd[:start] + "'" + ours + "'" + cmd[end:]
46807
+ new_settings = dict(settings)
46808
+ new_sl = dict(sl)
46809
+ new_sl["command"] = new_cmd
46810
+ new_settings["statusLine"] = new_sl
46811
+ return bool(_write_settings_atomic(new_settings))
46812
+ except Exception:
46813
+ return False
46814
+
46815
+
46047
46816
  def _heal_keepwarm_plist_path():
46048
46817
  """Rewrite an installed keep-warm launchd plist whose measure.py path went
46049
46818
  stale onto the update-surviving marketplace clone path, then reload the agent.
@@ -46065,7 +46834,11 @@ def _heal_keepwarm_plist_path():
46065
46834
  """
46066
46835
  # Per-account scheduler job: never touched from a redirected HOME
46067
46836
  # (a test sandbox or scratch run would re-point the user's live job).
46068
- if _scheduler_install_refused():
46837
+ # Frozen flag only up here: this runs in ensure-health on EVERY
46838
+ # SessionStart, and the full guard's job check is a `schtasks /Query` on
46839
+ # Windows, where this macOS heal never has a plist to fix. The full guard
46840
+ # runs below, once a stale plist exists and needs a rewrite.
46841
+ if _daemon_snapshot_sandboxed():
46069
46842
  return False
46070
46843
  if not _is_running_from_plugin_cache():
46071
46844
  return False
@@ -46092,6 +46865,10 @@ def _heal_keepwarm_plist_path():
46092
46865
  if isinstance(a, str) and a.endswith("measure.py")), None)
46093
46866
  if idx is None or args[idx] == stable:
46094
46867
  return False
46868
+ # A rewrite is due. Refuse it when the account's job belongs to another
46869
+ # install (rewriting and reloading would re-point it at this one).
46870
+ if _scheduler_install_refused():
46871
+ return False
46095
46872
  new_args = list(args)
46096
46873
  new_args[idx] = stable
46097
46874
  new_data = dict(data)
@@ -55415,6 +56192,12 @@ def run_ensure_health():
55415
56192
  print(" [Token Optimizer] Migrated statusLine to stable path", file=sys.stderr)
55416
56193
  except Exception as _e:
55417
56194
  print(f" [Token Optimizer] statusLine path migration failed: {_e}", file=sys.stderr)
56195
+ try:
56196
+ if _heal_dangling_statusline():
56197
+ print(" [Token Optimizer] Re-pointed a statusLine that ran a missing "
56198
+ "or Codex-cache statusline.js", file=sys.stderr)
56199
+ except Exception as _e:
56200
+ print(f" [Token Optimizer] statusLine heal failed: {_e}", file=sys.stderr)
55418
56201
  # Same class for the keep-warm launchd agent: an existing plist pinned to a
55419
56202
  # version-cache measure.py path dies on plugin update and freezes the
55420
56203
  # dashboard's savings. Lift it onto the clone path (macOS-only in practice).
@@ -55636,7 +56419,11 @@ def run_ensure_health():
55636
56419
  try:
55637
56420
  already_shown = _read_config_flag("autoupdate_nudge_shown", False)
55638
56421
  qb_disabled = _read_config_flag("quality_bar_disabled", False)
56422
+ # Claude Code steps only: Codex loads the same plugin build from its
56423
+ # own plugin cache, and its users were told to open Claude Code's
56424
+ # /plugin menu.
55639
56425
  if (not _lean
56426
+ and detect_runtime() == "claude"
55640
56427
  and _is_running_from_plugin_cache()
55641
56428
  and not already_shown
55642
56429
  and not qb_disabled):
@@ -58536,6 +59323,9 @@ if __name__ == "__main__":
58536
59323
  # PostToolUse hook handler: archive large tool results
58537
59324
  quiet = "--quiet" in args or "-q" in args
58538
59325
  archive_result(quiet=quiet)
59326
+ elif args[0] == "session-cost":
59327
+ # "What did the Navina session yesterday cost?" Read-only; see session_cost_main.
59328
+ sys.exit(session_cost_main(args[1:]))
58539
59329
  elif args[0] == "expand":
58540
59330
  # Retrieve archived tool result
58541
59331
  list_all = "--list" in args
@@ -58672,7 +59462,7 @@ if __name__ == "__main__":
58672
59462
  print(" python3 measure.py setup-hook --dry-run # Show what would be installed")
58673
59463
  print(" python3 measure.py setup-hook --uninstall # Remove Token Optimizer's SessionEnd hook")
58674
59464
  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)")
59465
+ print(" python3 measure.py compact-capture --budget-seconds N # Allow up to N s (default 14, max 60)")
58676
59466
  print(" python3 measure.py checkpoint-trigger --milestone pre-fanout # Milestone checkpoint with guards")
58677
59467
  print(" python3 measure.py compact-restore # Restore context from checkpoint")
58678
59468
  print(" python3 measure.py continue-last --topic TEXT # Show Codex continuity hint for a topic")
@@ -58717,6 +59507,8 @@ if __name__ == "__main__":
58717
59507
  print(" python3 measure.py attention-optimize --apply # Apply reordering (backup + write)")
58718
59508
  print(" python3 measure.py archive-result # PostToolUse hook: archive large tool results")
58719
59509
  print(" python3 measure.py archive-result --quiet # Silent mode (suppress stderr)")
59510
+ print(" python3 measure.py session-cost navina --date yesterday # What a session cost, in your words (read-only)")
59511
+ print(" python3 measure.py session-cost --id UUID --json # One session by id, machine-readable")
58720
59512
  print(" python3 measure.py expand TOOL_USE_ID # Retrieve archived tool result")
58721
59513
  print(" python3 measure.py expand TOOL_USE_ID --session SID # Retrieve from specific session")
58722
59514
  print(" python3 measure.py expand --list # List all archived results")