@alexgreensh/token-optimizer 5.13.56 → 5.13.59

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (30) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/hooks/hooks.json +16 -16
  4. package/hooks/python-launcher.sh +10 -0
  5. package/hooks/stop_runner.py +27 -4
  6. package/hooks/windows-launcher.py +57 -3
  7. package/package.json +1 -1
  8. package/skills/fleet-auditor/scripts/shared.py +29 -1
  9. package/skills/token-optimizer/pricing/prices.json +13 -1
  10. package/skills/token-optimizer/scripts/codex_compact_prompt.py +93 -9
  11. package/skills/token-optimizer/scripts/codex_doctor.py +134 -16
  12. package/skills/token-optimizer/scripts/codex_install.py +436 -26
  13. package/skills/token-optimizer/scripts/codex_session.py +38 -8
  14. package/skills/token-optimizer/scripts/copilot_doctor.py +129 -6
  15. package/skills/token-optimizer/scripts/copilot_hook_bridge.py +62 -14
  16. package/skills/token-optimizer/scripts/copilot_install.py +56 -4
  17. package/skills/token-optimizer/scripts/detectors/cache_instability.py +18 -4
  18. package/skills/token-optimizer/scripts/deterministic_candidates.py +55 -15
  19. package/skills/token-optimizer/scripts/devin_source.py +1 -1
  20. package/skills/token-optimizer/scripts/hermes_doctor.py +177 -1
  21. package/skills/token-optimizer/scripts/hermes_hook_bridge.py +190 -0
  22. package/skills/token-optimizer/scripts/hermes_install.py +43 -0
  23. package/skills/token-optimizer/scripts/hermes_session.py +133 -0
  24. package/skills/token-optimizer/scripts/hermes_state.py +58 -0
  25. package/skills/token-optimizer/scripts/hermes_tool_hooks.py +291 -0
  26. package/skills/token-optimizer/scripts/measure.py +1442 -325
  27. package/skills/token-optimizer/scripts/plugin_env.py +18 -0
  28. package/skills/token-optimizer/scripts/recovery_output.py +15 -2
  29. package/skills/token-optimizer/scripts/refetch_fingerprint.py +36 -1
  30. package/skills/token-optimizer/scripts/runtime_env.py +5 -1
@@ -90,10 +90,11 @@ import tempfile
90
90
  import textwrap
91
91
  import time
92
92
  import types
93
+ import unicodedata
93
94
  import platform
94
95
  import posixpath
95
96
  import shutil
96
- from collections import deque
97
+ from collections import Counter, deque
97
98
  from contextlib import contextmanager, nullcontext
98
99
  from datetime import datetime, timedelta, timezone
99
100
  from pathlib import Path, PureWindowsPath
@@ -148,6 +149,13 @@ def _redirect_bytecode_out_of_repo():
148
149
  # main-guard line must appear only once in this file, see below.)
149
150
  if __name__ in ("__main__",):
150
151
  _redirect_bytecode_out_of_repo()
152
+ # A leading `--runtime NAME` must reach the environment BEFORE plugin_env
153
+ # (imported just below) fixes its data directories from the active
154
+ # runtime at import. Applied later, the flag changed hints but every
155
+ # archive, checkpoint and trends path still pointed at the default
156
+ # runtime (`measure.py --runtime hermes expand <id>` found nothing).
157
+ from runtime_env import consume_runtime_flag as _consume_runtime_flag_early
158
+ sys.argv[:] = _consume_runtime_flag_early(sys.argv, os.environ)
151
159
 
152
160
  from hook_io import read_stdin_hook_input as _read_stdin_hook_input_shared
153
161
  from hook_runtime import (
@@ -2102,6 +2110,178 @@ def _safe_int(value):
2102
2110
  return 0
2103
2111
 
2104
2112
 
2113
+ def _context_usage(usage):
2114
+ """Select live executor usage, leaving aggregate usage for billing.
2115
+
2116
+ Advisor/server-tool responses can sum several executor reads in the
2117
+ top-level usage. Only the final message iteration describes occupancy.
2118
+ An unusable final executor falls back to the aggregate, never an older
2119
+ executor (which may describe a different context). Ignore advisor tails.
2120
+ """
2121
+ if isinstance(usage, dict) and isinstance(usage.get("iterations"), list):
2122
+ for iteration in reversed(usage["iterations"]):
2123
+ if isinstance(iteration, dict) and iteration.get("type") == "message":
2124
+ if (_valid_context_usage(iteration)
2125
+ and _context_token_count(iteration) > 0):
2126
+ return iteration
2127
+ break
2128
+ return usage
2129
+
2130
+
2131
+ def _valid_context_usage(usage):
2132
+ """Reject corrupt present executor buckets before lossy int coercion.
2133
+
2134
+ Missing buckets are optional. TTL splits matter only when the flat
2135
+ cache-write count is absent or zero, matching _context_token_count.
2136
+ """
2137
+ values = [usage[key] for key in ("input_tokens", "cache_read_input_tokens",
2138
+ "cache_creation_input_tokens") if key in usage]
2139
+ if not _safe_int(usage.get("cache_creation_input_tokens")):
2140
+ nested = usage.get("cache_creation", {})
2141
+ if not isinstance(nested, dict):
2142
+ return False
2143
+ for key in ("ephemeral_1h_input_tokens", "ephemeral_5m_input_tokens"):
2144
+ if key in nested:
2145
+ values.append(nested[key])
2146
+ if not nested.get(key) and key in usage:
2147
+ values.append(usage[key])
2148
+ try:
2149
+ return all(math.isfinite(float(value)) and float(value) >= 0
2150
+ for value in values)
2151
+ except (TypeError, ValueError, OverflowError):
2152
+ return False
2153
+
2154
+
2155
+ def _resume_usage(usage):
2156
+ """The first executor tests whether the cache survived the pause.
2157
+
2158
+ Later executors may read cache written earlier in this same response;
2159
+ that is not evidence that a keep-warm ping avoided the initial rewrite.
2160
+ Unusable first-executor data keeps the aggregate comparison, not a later
2161
+ executor that could hide a paid rewrite.
2162
+ """
2163
+ if isinstance(usage, dict) and isinstance(usage.get("iterations"), list):
2164
+ for iteration in usage["iterations"]:
2165
+ if isinstance(iteration, dict) and iteration.get("type") == "message":
2166
+ if (_valid_context_usage(iteration)
2167
+ and _context_token_count(iteration) > 0):
2168
+ return iteration
2169
+ break
2170
+ return usage
2171
+
2172
+
2173
+ _USAGE_BUCKET_KEYS = ("inp", "out", "cr", "cc", "cc_1h", "cc_5m")
2174
+
2175
+
2176
+ def _usage_buckets(usage):
2177
+ """Billing buckets of one usage dict (or iteration), never raising."""
2178
+ if not isinstance(usage, dict):
2179
+ return dict.fromkeys(_USAGE_BUCKET_KEYS, 0)
2180
+ nested = usage.get("cache_creation", {})
2181
+ if not isinstance(nested, dict):
2182
+ nested = {}
2183
+ cc_1h = _safe_int(nested.get("ephemeral_1h_input_tokens", 0)
2184
+ or usage.get("ephemeral_1h_input_tokens", 0))
2185
+ cc_5m = _safe_int(nested.get("ephemeral_5m_input_tokens", 0)
2186
+ or usage.get("ephemeral_5m_input_tokens", 0))
2187
+ return {
2188
+ "inp": max(0, _safe_int(usage.get("input_tokens", 0))),
2189
+ "out": max(0, _safe_int(usage.get("output_tokens", 0))),
2190
+ "cr": max(0, _safe_int(usage.get("cache_read_input_tokens", 0))),
2191
+ "cc": max(0, _safe_int(usage.get("cache_creation_input_tokens", 0))
2192
+ or (cc_1h + cc_5m)),
2193
+ "cc_1h": max(0, cc_1h),
2194
+ "cc_5m": max(0, cc_5m),
2195
+ }
2196
+
2197
+
2198
+ def _billed_usage_parts(usage, model, tier=None):
2199
+ """Split one response's usage into [(price_model, buckets), ...].
2200
+
2201
+ The first part is the executor (priced at the response model). Advisor
2202
+ iterations (type "advisor_message") run on the advisor's own model, so
2203
+ each becomes its own part priced at that model when the rate card knows
2204
+ it, else at the executor model. Tokens are never dropped: when the
2205
+ top-level usage already covers the advisor tokens they are moved out of
2206
+ the executor part, otherwise (the documented shape, top-level is the
2207
+ executor sum only) they are added on top.
2208
+ """
2209
+ agg = _usage_buckets(usage)
2210
+ iterations = usage.get("iterations") if isinstance(usage, dict) else None
2211
+ if not isinstance(iterations, list):
2212
+ return [(model, agg)]
2213
+ executor_sum = dict.fromkeys(_USAGE_BUCKET_KEYS, 0)
2214
+ advisor_sum = dict.fromkeys(_USAGE_BUCKET_KEYS, 0)
2215
+ advisors = []
2216
+ for iteration in iterations:
2217
+ if not isinstance(iteration, dict):
2218
+ continue
2219
+ kind = iteration.get("type")
2220
+ if kind == "message":
2221
+ for k, v in _usage_buckets(iteration).items():
2222
+ executor_sum[k] += v
2223
+ elif kind == "advisor_message":
2224
+ buckets = _usage_buckets(iteration)
2225
+ if not any(buckets.values()):
2226
+ continue
2227
+ adv_model = iteration.get("model")
2228
+ if not (isinstance(adv_model, str) and adv_model
2229
+ and _is_priced_model(adv_model, tier)):
2230
+ adv_model = model
2231
+ advisors.append((adv_model, buckets))
2232
+ for k, v in buckets.items():
2233
+ advisor_sum[k] += v
2234
+ if not advisors:
2235
+ return [(model, agg)]
2236
+ executor = dict(agg)
2237
+ if all(agg[k] >= executor_sum[k] + advisor_sum[k] for k in _USAGE_BUCKET_KEYS):
2238
+ executor = {k: agg[k] - advisor_sum[k] for k in _USAGE_BUCKET_KEYS}
2239
+ return [(model, executor)] + advisors
2240
+
2241
+
2242
+ def _price_usage_parts(parts, tier=None, per_request=False, ttl_split=True):
2243
+ """USD for _billed_usage_parts output; cache writes priced by TTL split."""
2244
+ total = 0.0
2245
+ for part_model, b in parts:
2246
+ if ttl_split and (b["cc_1h"] or b["cc_5m"]):
2247
+ total += _get_model_cost(part_model, b["inp"], b["out"], b["cr"], b["cc"],
2248
+ tier=tier, cache_create_1h=b["cc_1h"],
2249
+ cache_create_5m=b["cc_5m"], per_request=per_request)
2250
+ else:
2251
+ total += _get_model_cost(part_model, b["inp"], b["out"], b["cr"], b["cc"],
2252
+ tier=tier, per_request=per_request)
2253
+ return total
2254
+
2255
+
2256
+ def _turn_prefix_cached(turn):
2257
+ """Cached prefix a turn leaves behind: final executor when known (#287)."""
2258
+ if "ctx_cache" in turn:
2259
+ return max(0, _safe_int(turn.get("ctx_cache")))
2260
+ return _safe_int(turn.get("cache_read")) + _safe_int(turn.get("cache_creation"))
2261
+
2262
+
2263
+ def _turn_resume_write(turn):
2264
+ """Cache written when a turn starts: first executor when known (#287)."""
2265
+ if "resume_cache_creation" in turn:
2266
+ return max(0, _safe_int(turn.get("resume_cache_creation")))
2267
+ return _safe_int(turn.get("cache_creation"))
2268
+
2269
+
2270
+ def _context_token_count(usage):
2271
+ """Input footprint, including flat or TTL-split cache writes."""
2272
+ if not isinstance(usage, dict):
2273
+ return 0
2274
+ creation = _safe_int(usage.get("cache_creation_input_tokens"))
2275
+ if not creation:
2276
+ nested = usage.get("cache_creation")
2277
+ if not isinstance(nested, dict):
2278
+ nested = {}
2279
+ creation = sum(_safe_int(nested.get(key) or usage.get(key)) for key in (
2280
+ "ephemeral_1h_input_tokens", "ephemeral_5m_input_tokens"))
2281
+ return (_safe_int(usage.get("input_tokens"))
2282
+ + _safe_int(usage.get("cache_read_input_tokens")) + creation)
2283
+
2284
+
2105
2285
  def estimate_tokens_from_file(filepath):
2106
2286
  """Estimate tokens by reading file content (character count / 4)."""
2107
2287
  try:
@@ -2354,12 +2534,9 @@ def get_session_baselines(limit=10):
2354
2534
  if "message" in data and isinstance(data["message"], dict):
2355
2535
  msg = data["message"]
2356
2536
  if "usage" in msg:
2357
- u = msg["usage"]
2358
- first_usage = (
2359
- u.get("input_tokens", 0)
2360
- + u.get("cache_creation_input_tokens", 0)
2361
- + u.get("cache_read_input_tokens", 0)
2362
- )
2537
+ # Context size, not the advisor-summed bill (#287).
2538
+ first_usage = _context_token_count(
2539
+ _context_usage(msg["usage"]))
2363
2540
  break
2364
2541
  except (json.JSONDecodeError, KeyError, TypeError):
2365
2542
  continue
@@ -3566,6 +3743,7 @@ def _measure_codex_components():
3566
3743
  "count": len(plugin_skills),
3567
3744
  "tokens": sum(int(item.get("tokens", 0)) for item in plugin_skills),
3568
3745
  "names": [item["name"] for item in plugin_skills],
3746
+ "per_plugin": dict(Counter(item.get("plugin") or "other" for item in plugin_skills)),
3569
3747
  "plugins": _collect_codex_plugin_inventory(cfg),
3570
3748
  "disabled_plugins": [p["name"] for p in _collect_codex_plugin_inventory(cfg) if not p.get("enabled", True)],
3571
3749
  "duplicate_skills": {},
@@ -4118,6 +4296,31 @@ def _resolve_compact_window(model, env=None, settings=None):
4118
4296
  if not isinstance(settings, dict):
4119
4297
  settings = {}
4120
4298
 
4299
+ if detect_runtime() == "codex":
4300
+ # Codex: the Claude table and Claude's autocompact settings do not
4301
+ # apply. A GPT id fell through to the Claude 1M default, so a 475K
4302
+ # model reported a 967K compaction point (issue #276). Use Codex's
4303
+ # own catalog window, then the runtime's detected window.
4304
+ window = None
4305
+ try:
4306
+ import codex_models
4307
+ window = codex_models.effective_window(model) if model else None
4308
+ except Exception:
4309
+ window = None
4310
+ if not window:
4311
+ try:
4312
+ window = detect_context_window()[0]
4313
+ except Exception:
4314
+ window = None
4315
+ if window:
4316
+ return {
4317
+ "tokens": int(window),
4318
+ "source": f"Codex model window ({model or 'configured model'})",
4319
+ "user_override": False,
4320
+ "model_window": int(window),
4321
+ "default_tokens": int(window),
4322
+ }
4323
+
4121
4324
  model_window = _context_window_for_model_str(model)
4122
4325
  if not model_window:
4123
4326
  try:
@@ -5749,8 +5952,13 @@ def print_snapshot_summary(snapshot):
5749
5952
  name = plugin.get("name")
5750
5953
  if name:
5751
5954
  plugins.append(str(name))
5752
- plugin_label = ", ".join(plugins) if plugins else "plugins"
5753
- print(f" {'+ Plugin skills':<33s} {ps.get('tokens', 0):>6,} tokens [{ps.get('count', 0)} from {plugin_label}{suffix}]")
5955
+ per_plugin = ps.get("per_plugin") or {}
5956
+ if per_plugin:
5957
+ plugin_label = ", ".join(f"{n} {name}" for name, n in sorted(per_plugin.items()))
5958
+ print(f" {'+ Plugin skills':<33s} {ps.get('tokens', 0):>6,} tokens [{ps.get('count', 0)}: {plugin_label}{suffix}]")
5959
+ else:
5960
+ plugin_label = ", ".join(plugins) if plugins else "plugins"
5961
+ print(f" {'+ Plugin skills':<33s} {ps.get('tokens', 0):>6,} tokens [{ps.get('count', 0)} from {plugin_label}{suffix}]")
5754
5962
  dupes = ps.get("duplicate_skills", {})
5755
5963
  if dupes:
5756
5964
  dupe_count = sum(len(v) - 1 for v in dupes.values())
@@ -7135,9 +7343,16 @@ def _collect_copilot_hook_status_for_dashboard():
7135
7343
  return {
7136
7344
  "copilot_hooks": {
7137
7345
  "installed": _ok("TO hook config"),
7138
- "partial": by_name.get("TO hook config", {}).get("status") == "warn",
7346
+ # Installed stays tied to the hook config; a dead legacy `stop` entry
7347
+ # or a bridge that cannot find measure.py (session-end refresh paused), or a
7348
+ # damaged hook payload (missing bridge modules) is installed-but-partial,
7349
+ # not healthy.
7350
+ "partial": any(
7351
+ by_name.get(n, {}).get("status") == "warn"
7352
+ for n in ("TO hook config", "TO session-end hook", "session-end refresh")
7353
+ ) or by_name.get("hook payload", {}).get("status") in ("warn", "fail"),
7139
7354
  "label": "Copilot CLI Hooks",
7140
- "description": "Wires Token Optimizer into ~/.copilot/hooks/: sessionStart continuity restore, preToolUse bash compression (capability-gated), postToolUse crash-recovery tally + nudges, stop-time rollup.",
7355
+ "description": "Wires Token Optimizer into ~/.copilot/hooks/: sessionStart continuity restore, preToolUse bash compression (capability-gated), postToolUse crash-recovery tally + nudges, session-end rollup.",
7141
7356
  "install_cmd": install_cmd,
7142
7357
  "uninstall_cmd": f"{_runtime_cli('copilot')} copilot-uninstall",
7143
7358
  },
@@ -7462,11 +7677,40 @@ def _collect_codex_skill_inventory(cfg: dict, *, project: Path) -> dict[str, lis
7462
7677
  return f"{parts[1]}@{parts[0]}"
7463
7678
  return None
7464
7679
 
7680
+ # The cache keeps old versions after an upgrade, but Codex loads one
7681
+ # version per plugin. Counting every cached copy inflated the plugin
7682
+ # skill total several times over (issue #276).
7683
+ def _version_key(name: str):
7684
+ nums = re.findall(r"\d+", name)
7685
+ return tuple(int(n) for n in nums) if nums else (-1,)
7686
+
7687
+ newest_version: dict[tuple[str, str], str] = {}
7688
+ for path, source in candidates:
7689
+ if source != "plugin":
7690
+ continue
7691
+ try:
7692
+ rel = path.relative_to(plugin_cache)
7693
+ except ValueError:
7694
+ continue
7695
+ if len(rel.parts) >= 6 and rel.parts[-3] == "skills":
7696
+ key = (rel.parts[0], rel.parts[1])
7697
+ current = newest_version.get(key)
7698
+ if current is None or _version_key(rel.parts[2]) > _version_key(current):
7699
+ newest_version[key] = rel.parts[2]
7700
+
7465
7701
  active = []
7466
7702
  disabled = []
7467
7703
  seen: set[str] = set()
7468
7704
  mp_cmd = _shell_script_path()
7469
7705
  for path, source in candidates:
7706
+ if source == "plugin":
7707
+ try:
7708
+ rel = path.relative_to(plugin_cache)
7709
+ except ValueError:
7710
+ rel = None
7711
+ if (rel is not None and len(rel.parts) >= 6 and rel.parts[-3] == "skills"
7712
+ and newest_version.get((rel.parts[0], rel.parts[1])) != rel.parts[2]):
7713
+ continue
7470
7714
  resolved = str(path.expanduser().resolve(strict=False))
7471
7715
  if resolved in seen:
7472
7716
  continue
@@ -7483,6 +7727,8 @@ def _collect_codex_skill_inventory(cfg: dict, *, project: Path) -> dict[str, lis
7483
7727
  "enable_cmd": f"{_runtime_cli('codex')} codex-skill enable --path {shlex.quote(resolved)}",
7484
7728
  }
7485
7729
  _pkey = _plugin_key_for(resolved)
7730
+ if _pkey is not None:
7731
+ item["plugin"] = _pkey
7486
7732
  if resolved in disabled_paths or (_pkey is not None and _pkey in disabled_plugin_keys):
7487
7733
  disabled.append(item)
7488
7734
  else:
@@ -8672,6 +8918,118 @@ def _session_refresh_due(min_interval_seconds=120):
8672
8918
  return True
8673
8919
 
8674
8920
 
8921
+ HOOK_STATUS_FILE = RUNTIME_DIR / "token-optimizer" / "hook-status.json"
8922
+
8923
+
8924
+ def _pid_is_running(pid):
8925
+ """True when process ``pid`` exists, on every OS. Never raises.
8926
+
8927
+ ``os.kill(pid, 0)`` is a liveness probe only on POSIX. On Windows signal 0
8928
+ is CTRL_C_EVENT: Python calls GenerateConsoleCtrlEvent, which fails for
8929
+ any pid when the caller has no console (hooks run detached, so a live lock
8930
+ owner read as dead) and, with a console, interrupts the whole console
8931
+ group. Windows asks the process table instead. When the answer is unknown
8932
+ the process counts as running, so a lock is never stolen from a live owner.
8933
+ """
8934
+ try:
8935
+ pid = int(pid)
8936
+ except (TypeError, ValueError):
8937
+ return False
8938
+ if pid <= 0:
8939
+ return False
8940
+ if os.name == "nt":
8941
+ return _win_pid_is_running(pid)
8942
+ try:
8943
+ os.kill(pid, 0)
8944
+ except ProcessLookupError:
8945
+ return False
8946
+ except PermissionError:
8947
+ return True # exists, owned by someone else
8948
+ except OSError:
8949
+ return False
8950
+ return True
8951
+
8952
+
8953
+ def _win_pid_is_running(pid):
8954
+ try:
8955
+ import ctypes
8956
+ from ctypes import wintypes
8957
+
8958
+ kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
8959
+ kernel32.OpenProcess.restype = wintypes.HANDLE
8960
+ kernel32.OpenProcess.argtypes = (wintypes.DWORD, wintypes.BOOL, wintypes.DWORD)
8961
+ handle = kernel32.OpenProcess(0x1000, False, pid) # PROCESS_QUERY_LIMITED_INFORMATION
8962
+ if not handle:
8963
+ # 5 = access denied: the process exists but is not ours.
8964
+ # 87 = invalid parameter: no such process.
8965
+ return ctypes.get_last_error() != 87
8966
+ try:
8967
+ code = wintypes.DWORD()
8968
+ if not kernel32.GetExitCodeProcess(handle, ctypes.byref(code)):
8969
+ return True
8970
+ return code.value == 259 # STILL_ACTIVE
8971
+ finally:
8972
+ kernel32.CloseHandle(handle)
8973
+ except Exception:
8974
+ return True
8975
+
8976
+
8977
+ def _record_hook_status(key, result):
8978
+ """Remember the last outcome of a background hook job, for the doctor.
8979
+
8980
+ The Stop hook's output goes to NUL and its runner always exits 0, so
8981
+ without this a user cannot tell "ran", "skipped on purpose" and "broke"
8982
+ apart (issue #276). Best effort: never raises.
8983
+ """
8984
+ try:
8985
+ try:
8986
+ data = json.loads(HOOK_STATUS_FILE.read_text(encoding="utf-8"))
8987
+ if not isinstance(data, dict):
8988
+ data = {}
8989
+ except (OSError, ValueError):
8990
+ data = {}
8991
+ data[key] = {"at": datetime.now(timezone.utc).isoformat(timespec="seconds"), "result": result}
8992
+ HOOK_STATUS_FILE.parent.mkdir(parents=True, exist_ok=True)
8993
+ tmp = HOOK_STATUS_FILE.with_name(HOOK_STATUS_FILE.name + f".{os.getpid()}.tmp")
8994
+ tmp.write_text(json.dumps(data, indent=2), encoding="utf-8")
8995
+ os.replace(tmp, HOOK_STATUS_FILE)
8996
+ except Exception:
8997
+ pass
8998
+
8999
+
9000
+ def _flush_capture_checkpoint(args):
9001
+ """The checkpoint step of the deferred Stop/SessionEnd flush worker.
9002
+
9003
+ The worker has no stdin, so the Stop runner hands it the session identity
9004
+ the host gave the hook as ``--session-id`` / ``--transcript-path``. On Codex
9005
+ with no identity from the host or the environment, no checkpoint is
9006
+ written: an anonymous "unknown" file can outrank real ones on restore
9007
+ (issue #278). Returns the checkpoint path or None.
9008
+ """
9009
+ flush_trigger = "end"
9010
+ sid = None
9011
+ transcript = None
9012
+ for i, a in enumerate(args):
9013
+ if a == "--trigger" and i + 1 < len(args):
9014
+ flush_trigger = args[i + 1]
9015
+ elif a == "--session-id" and i + 1 < len(args):
9016
+ sid = args[i + 1]
9017
+ elif a == "--transcript-path" and i + 1 < len(args):
9018
+ transcript = args[i + 1]
9019
+ if (_use_codex_session_adapter() and not sid and not transcript
9020
+ and _find_current_session_jsonl() is None):
9021
+ _record_hook_status(
9022
+ "stop_capture",
9023
+ "skipped: the Stop hook payload and environment carried no session id")
9024
+ return None
9025
+ path = compact_capture(trigger=flush_trigger, backfill_tools=True,
9026
+ session_id=sid, transcript_path=transcript)
9027
+ _record_hook_status(
9028
+ "stop_capture",
9029
+ "ok: checkpoint written" if path else "no checkpoint written (session transcript not found)")
9030
+ return path
9031
+
9032
+
8675
9033
  def _run_session_end_flush_worker(args, budget_seconds=20):
8676
9034
  """Run heavyweight Stop-hook work outside Codex's visible hook budget.
8677
9035
 
@@ -8680,11 +9038,17 @@ def _run_session_end_flush_worker(args, budget_seconds=20):
8680
9038
  the hook timeout."""
8681
9039
  lock_dir = _acquire_session_end_flush_lock()
8682
9040
  if lock_dir is None:
9041
+ _record_hook_status("stop_flush", "skipped: another refresh was already running")
8683
9042
  return
8684
9043
  _lean = _remote_lean_profile()
8685
9044
  old_budget = _install_hook_budget(budget_seconds)
9045
+ _flush_result = "error: stopped early"
8686
9046
  try:
8687
- if _session_refresh_due():
9047
+ if not _session_refresh_due():
9048
+ _flush_result = "skipped: last refresh and checkpoint were under 2 minutes ago"
9049
+ else:
9050
+ _flush_result = "ran"
9051
+ if _flush_result.startswith("ran"):
8688
9052
  try:
8689
9053
  # First-ever collection: DEEP backfill of all history still on disk
8690
9054
  # (not just the rolling 90-day window), so a long-time user's baseline
@@ -8750,11 +9114,7 @@ def _run_session_end_flush_worker(args, budget_seconds=20):
8750
9114
  except Exception:
8751
9115
  pass
8752
9116
  try:
8753
- flush_trigger = "end"
8754
- for i, a in enumerate(args):
8755
- if a == "--trigger" and i + 1 < len(args):
8756
- flush_trigger = args[i + 1]
8757
- compact_capture(trigger=flush_trigger, backfill_tools=True)
9117
+ _flush_capture_checkpoint(args)
8758
9118
  except Exception:
8759
9119
  pass
8760
9120
  # Data-retention enforcement (enterprise compliance)
@@ -8780,7 +9140,10 @@ def _run_session_end_flush_worker(args, budget_seconds=20):
8780
9140
  except Exception:
8781
9141
  pass
8782
9142
  except _HookTimeout:
8783
- pass
9143
+ _flush_result = "timed out: refresh hit its time budget and resumes next turn"
9144
+ except Exception as exc:
9145
+ _flush_result = f"error: {type(exc).__name__}"
9146
+ raise
8784
9147
  else:
8785
9148
  # Flush work completed without a timeout. M-5: release the flush lock
8786
9149
  # BEFORE running post-flush extensions, so a slow/hung extension does
@@ -8808,6 +9171,7 @@ def _run_session_end_flush_worker(args, budget_seconds=20):
8808
9171
  if lock_dir is not None:
8809
9172
  _release_session_end_flush_lock(lock_dir)
8810
9173
  _clear_hook_budget(old_budget)
9174
+ _record_hook_status("stop_flush", _flush_result)
8811
9175
 
8812
9176
 
8813
9177
  def _run_post_flush_extensions(time_left_fn=None, version="unknown"):
@@ -10048,7 +10412,8 @@ def generate_auto_recommendations(components, trends=None, days=30):
10048
10412
  haiku_pct = model_mix.get("haiku", 0) / total_tokens * 100
10049
10413
  if opus_pct > 50 and haiku_pct < 15:
10050
10414
  # Root cause: hardcoded model in settings.json → split into Quick Win
10051
- if default_model and "opus" in str(default_model).lower():
10415
+ if (default_model and "opus" in str(default_model).lower()
10416
+ and not _model_routing_handled_elsewhere()):
10052
10417
  quick.append(
10053
10418
  f"**Remove hardcoded model from settings.json (`\"model\": \"{default_model}\"`)**: "
10054
10419
  f"This forces ALL operations to use {default_model}, overriding any CLAUDE.md routing. "
@@ -10333,7 +10698,8 @@ def _deterministic_candidates_data(days=30, budget_s=_DETCAND_COACH_BUDGET_S,
10333
10698
  if _sidechain_path_reason(jf) is None]
10334
10699
  return deterministic_candidates.run(
10335
10700
  runtime, files, price, days=days, budget_s=budget_s, max_sessions=max_sessions,
10336
- cache_dir=SNAPSHOT_DIR, tier=tier, use_cache=use_cache, progress=progress)
10701
+ cache_dir=SNAPSHOT_DIR, tier=tier, use_cache=use_cache, progress=progress,
10702
+ split_usage=lambda model, usage: _billed_usage_parts(usage, model, tier=tier))
10337
10703
  except Exception as exc: # never break coach --json
10338
10704
  return {"status": "error", "runtime": runtime, "partial": True, "candidates": [],
10339
10705
  "basis": deterministic_candidates.BASIS,
@@ -11726,21 +12092,14 @@ def _extract_costly_prompts(jsonl_path, tier=None, top_n=5):
11726
12092
  if is_sidechain:
11727
12093
  continue
11728
12094
  content = msg.get("content") if isinstance(msg, dict) else msg
11729
- text = ""
11730
- if isinstance(content, str):
11731
- text = content
11732
- elif isinstance(content, list):
12095
+ if isinstance(content, list):
11733
12096
  # Skip if all items are tool_result
11734
12097
  types = [i.get("type") for i in content if isinstance(i, dict)]
11735
12098
  if types and all(t == "tool_result" for t in types):
11736
12099
  continue
11737
- for block in content:
11738
- if isinstance(block, dict) and block.get("type") == "text":
11739
- text = block.get("text", "")
11740
- break
11741
- elif isinstance(block, str):
11742
- text = block
11743
- break
12100
+ # Same filter as checkpoints: harness text (meta records,
12101
+ # compact summaries, command caveats) is not a prompt.
12102
+ text = _task_user_text(record)
11744
12103
  if text and len(text) > 5:
11745
12104
  pending_prompt = {
11746
12105
  "text": text[:300],
@@ -11758,8 +12117,9 @@ def _extract_costly_prompts(jsonl_path, tier=None, top_n=5):
11758
12117
  cr = _safe_int(usage.get("cache_read_input_tokens", 0))
11759
12118
  cc = _safe_int(usage.get("cache_creation_input_tokens", 0))
11760
12119
  model = _record_model(msg)
11761
- cost = _get_model_cost(model, inp, out, cr, cc, tier=tier,
11762
- per_request=True)
12120
+ cost = _price_usage_parts(
12121
+ _billed_usage_parts(usage, model, tier=tier),
12122
+ tier=tier, per_request=True, ttl_split=False)
11763
12123
  pending_prompt["tokens_in"] = inp + cr + cc
11764
12124
  pending_prompt["tokens_out"] = out
11765
12125
  pending_prompt["fresh_input"] = inp
@@ -12099,22 +12459,10 @@ def _parse_session_jsonl(filepath, window_start=None, window_end=None):
12099
12459
 
12100
12460
  rec_type = record.get("type")
12101
12461
 
12102
- # Extract topic from first user message
12462
+ # Topic and checkpoint task share a human-task-only view. Keep
12463
+ # raw user text for message scoring and slash-skill accounting.
12103
12464
  if rec_type == "user" and topic is None:
12104
- msg = record.get("message", {})
12105
- content = msg.get("content") if isinstance(msg, dict) else msg
12106
- if isinstance(content, str):
12107
- topic = _extract_topic(content)
12108
- elif isinstance(content, list):
12109
- for block in content:
12110
- if isinstance(block, dict) and block.get("type") == "text":
12111
- topic = _extract_topic(block.get("text", ""))
12112
- if topic:
12113
- break
12114
- elif isinstance(block, str):
12115
- topic = _extract_topic(block)
12116
- if topic:
12117
- break
12465
+ topic = _extract_topic(_task_user_text(record))
12118
12466
 
12119
12467
  if rec_type in ("user", "assistant"):
12120
12468
  _conversation_records += 1
@@ -12157,6 +12505,8 @@ def _parse_session_jsonl(filepath, window_start=None, window_end=None):
12157
12505
  isinstance(b, dict) and b.get("type") == "tool_result" for b in _c
12158
12506
  ):
12159
12507
  pass # tool output, not a human turn
12508
+ elif record.get("isMeta") or record.get("isCompactSummary"):
12509
+ pass # harness-written, not a human turn
12160
12510
  else:
12161
12511
  message_count += 1
12162
12512
 
@@ -12256,26 +12606,31 @@ def _parse_session_jsonl(filepath, window_start=None, window_end=None):
12256
12606
  # each other — use the map's own size as a monotonic
12257
12607
  # per-session counter.
12258
12608
  key = req_id if req_id else f"__noreq__{len(request_usage_map)}"
12259
- prev = request_usage_map.get(key)
12260
- if prev is None:
12261
- request_usage_map[key] = {
12262
- "inp": inp_tok, "out": out_tok, "cr": cr, "cc": cc,
12263
- "cc_1h": cc_1h, "cc_5m": cc_5m, "model": model,
12264
- "ts": ts_str,
12265
- }
12266
- else:
12267
- # Streaming: keep MAX of each token category.
12268
- # Model + timestamp: prefer later (non-empty) values.
12269
- prev["inp"] = max(prev["inp"], inp_tok)
12270
- prev["out"] = max(prev["out"], out_tok)
12271
- prev["cr"] = max(prev["cr"], cr)
12272
- prev["cc"] = max(prev["cc"], cc)
12273
- prev["cc_1h"] = max(prev["cc_1h"], cc_1h)
12274
- prev["cc_5m"] = max(prev["cc_5m"], cc_5m)
12275
- if model and model != "unknown":
12276
- prev["model"] = model
12277
- if ts_str:
12278
- prev["ts"] = ts_str
12609
+ # Advisor iterations bill at the advisor's own model:
12610
+ # each is a separate entry under "<request>#advisor<n>"
12611
+ # so streamed copies still dedup by MAX per entry.
12612
+ parts = _billed_usage_parts(usage, model)
12613
+ for part_index, (part_model, b) in enumerate(parts):
12614
+ part_key = key if part_index == 0 else f"{key}#advisor{part_index}"
12615
+ prev = request_usage_map.get(part_key)
12616
+ if prev is None:
12617
+ request_usage_map[part_key] = {
12618
+ "inp": b["inp"], "out": b["out"], "cr": b["cr"],
12619
+ "cc": b["cc"], "cc_1h": b["cc_1h"],
12620
+ "cc_5m": b["cc_5m"], "model": part_model,
12621
+ "ts": ts_str,
12622
+ }
12623
+ if part_index:
12624
+ request_usage_map[part_key]["advisor"] = True
12625
+ else:
12626
+ # Streaming: keep MAX of each token category.
12627
+ # Model + timestamp: prefer later (non-empty) values.
12628
+ for field in _USAGE_BUCKET_KEYS:
12629
+ prev[field] = max(prev[field], b[field])
12630
+ if part_model and part_model != "unknown":
12631
+ prev["model"] = part_model
12632
+ if ts_str:
12633
+ prev["ts"] = ts_str
12279
12634
 
12280
12635
  except (PermissionError, OSError):
12281
12636
  return None
@@ -12302,9 +12657,11 @@ def _parse_session_jsonl(filepath, window_start=None, window_end=None):
12302
12657
  total_cache_create += u["cc"]
12303
12658
  total_cache_create_1h += u["cc_1h"]
12304
12659
  total_cache_create_5m += u["cc_5m"]
12305
- api_calls += 1
12306
12660
  ts_s = u.get("ts")
12307
- if ts_s and isinstance(ts_s, str):
12661
+ if not u.get("advisor"):
12662
+ # An advisor part belongs to its request: not another API call.
12663
+ api_calls += 1
12664
+ if ts_s and isinstance(ts_s, str) and not u.get("advisor"):
12308
12665
  try:
12309
12666
  api_call_timestamps.append(datetime.fromisoformat(ts_s.replace("Z", "+00:00")))
12310
12667
  except (ValueError, TypeError):
@@ -12500,14 +12857,8 @@ def parse_session_turns(filepath):
12500
12857
  prev_call_ts = call_ts
12501
12858
  except (ValueError, TypeError):
12502
12859
  pass
12503
- # Price cache-create by TTL tier when the per-turn split is available.
12504
- if cc_1h or cc_5m:
12505
- cost = _get_model_cost(model, inp_tok, out_tok, cr, cc, tier=tier,
12506
- cache_create_1h=cc_1h, cache_create_5m=cc_5m,
12507
- per_request=True)
12508
- else:
12509
- cost = _get_model_cost(model, inp_tok, out_tok, cr, cc, tier=tier,
12510
- per_request=True)
12860
+ cost = _price_usage_parts(_billed_usage_parts(usage, model, tier=tier),
12861
+ tier=tier, per_request=True)
12511
12862
 
12512
12863
  turns.append({
12513
12864
  "turn_index": turn_index,
@@ -12524,6 +12875,22 @@ def parse_session_turns(filepath):
12524
12875
  "tools_used": tools,
12525
12876
  "cost_usd": round(cost, 6),
12526
12877
  })
12878
+ ctx_usage = _context_usage(usage)
12879
+ if ctx_usage is not usage:
12880
+ # Cached prefix the next turn can reuse: the final executor
12881
+ # only, matching the live keep-warm arm (#287).
12882
+ turns[-1]["ctx_cache"] = (
12883
+ _context_token_count(ctx_usage)
12884
+ - _safe_int(ctx_usage.get("input_tokens")))
12885
+ resume_usage = _resume_usage(usage)
12886
+ if resume_usage is not usage:
12887
+ # Billing stays aggregate; pause warmth uses the first
12888
+ # executor, before any cache writes inside this response.
12889
+ resume_read = _safe_int(resume_usage.get("cache_read_input_tokens"))
12890
+ turns[-1]["resume_cache_read"] = resume_read
12891
+ turns[-1]["resume_cache_creation"] = (
12892
+ _context_token_count(resume_usage) - resume_read
12893
+ - _safe_int(resume_usage.get("input_tokens")))
12527
12894
  turn_index += 1
12528
12895
 
12529
12896
  except (PermissionError, OSError):
@@ -13318,6 +13685,32 @@ def _origin_insert_parts(conn, table):
13318
13685
  return "", "", ()
13319
13686
 
13320
13687
 
13688
+ def _claude_projects_like_patterns() -> tuple:
13689
+ """Prefix LIKE patterns (ESCAPE '!') for transcripts under the resolved
13690
+ Claude config's projects/ dir, or () when that is the default ~/.claude
13691
+ (the literal pattern already covers it) or unresolvable.
13692
+
13693
+ Anchored at the start of the path, so a "copilot:"/"hermes:" dedup key or
13694
+ a path that merely contains the folder name further down never matches.
13695
+ Forward slashes only: callers match it against _PLATFORM_PATH_SQL, which
13696
+ folds the backslashes of rows written on Windows to forward slashes.
13697
+ """
13698
+ try:
13699
+ projects = Path(CLAUDE_DIR) / "projects"
13700
+ if projects == Path(HOME) / ".claude" / "projects":
13701
+ return ()
13702
+ form = str(projects).replace("\\", "/")
13703
+ esc = form.replace("!", "!!").replace("%", "!%").replace("_", "!_")
13704
+ return (esc + "/%",)
13705
+ except Exception:
13706
+ return ()
13707
+
13708
+
13709
+ # session_log.jsonl_path with Windows backslashes folded to forward slashes,
13710
+ # so one path pattern matches rows written on every OS (the platform backfill).
13711
+ _PLATFORM_PATH_SQL = "REPLACE(jsonl_path, '\\', '/')"
13712
+
13713
+
13321
13714
  def _init_trends_db():
13322
13715
  """Initialize the trends SQLite DB. Returns a connection.
13323
13716
 
@@ -13487,52 +13880,47 @@ def _init_trends_db():
13487
13880
  # running collector.
13488
13881
  _platform_patterns = ("%/.claude/projects/%", "%/.codex/sessions/%", "%/.codex/archived_sessions/%",
13489
13882
  "hermes:%", "copilot:%", "cursor:%", "antigravity:%")
13883
+ # A relocated Claude config (CLAUDE_CONFIG_DIR) keeps its transcripts under
13884
+ # <config>/projects/, which the literal ~/.claude pattern above misses.
13885
+ _claude_cfg_patterns = _claude_projects_like_patterns()
13886
+ # Paths are matched with backslashes folded to '/', so a row written on
13887
+ # Windows (C:\Users\me\.claude\projects\...) is tagged like a POSIX one.
13888
+ _p = _PLATFORM_PATH_SQL
13889
+ _cfg_where = " OR ".join([f"{_p} LIKE ? ESCAPE '!'"] * len(_claude_cfg_patterns))
13490
13890
  try:
13491
13891
  _needs_platform = conn.execute(
13492
13892
  "SELECT 1 FROM session_log WHERE platform IS NULL AND ("
13493
- + " OR ".join(["jsonl_path LIKE ?"] * len(_platform_patterns)) + ") LIMIT 1",
13494
- _platform_patterns,
13893
+ + " OR ".join([f"{_p} LIKE ?"] * len(_platform_patterns))
13894
+ + (" OR " + _cfg_where if _cfg_where else "") + ") LIMIT 1",
13895
+ _platform_patterns + _claude_cfg_patterns,
13495
13896
  ).fetchone()
13496
13897
  except sqlite3.Error:
13497
13898
  _needs_platform = True
13498
13899
  try:
13499
13900
  if not _needs_platform:
13500
13901
  raise _SkipMigration
13501
- conn.execute(
13502
- "UPDATE session_log SET platform = 'claude' "
13503
- "WHERE platform IS NULL "
13504
- "AND jsonl_path LIKE '%/.claude/projects/%'"
13505
- )
13506
- conn.execute(
13507
- "UPDATE session_log SET platform = 'codex' "
13508
- "WHERE platform IS NULL "
13509
- "AND jsonl_path LIKE '%/.codex/sessions/%'"
13510
- )
13511
- conn.execute(
13512
- "UPDATE session_log SET platform = 'codex' "
13513
- "WHERE platform IS NULL "
13514
- "AND jsonl_path LIKE '%/.codex/archived_sessions/%'"
13515
- )
13516
- conn.execute(
13517
- "UPDATE session_log SET platform = 'hermes' "
13518
- "WHERE platform IS NULL "
13519
- "AND jsonl_path LIKE 'hermes:%'"
13520
- )
13521
- conn.execute(
13522
- "UPDATE session_log SET platform = 'copilot' "
13523
- "WHERE platform IS NULL "
13524
- "AND jsonl_path LIKE 'copilot:%'"
13525
- )
13526
- conn.execute(
13527
- "UPDATE session_log SET platform = 'cursor' "
13528
- "WHERE platform IS NULL "
13529
- "AND jsonl_path LIKE 'cursor:%'"
13530
- )
13531
- conn.execute(
13532
- "UPDATE session_log SET platform = 'antigravity' "
13533
- "WHERE platform IS NULL "
13534
- "AND jsonl_path LIKE 'antigravity:%'"
13535
- )
13902
+ for _platform, _pattern in (("claude", "%/.claude/projects/%"),
13903
+ ("codex", "%/.codex/sessions/%"),
13904
+ ("codex", "%/.codex/archived_sessions/%"),
13905
+ ("hermes", "hermes:%"),
13906
+ ("copilot", "copilot:%"),
13907
+ ("cursor", "cursor:%"),
13908
+ ("antigravity", "antigravity:%")):
13909
+ conn.execute(
13910
+ f"UPDATE session_log SET platform = ? WHERE platform IS NULL AND {_p} LIKE ?",
13911
+ (_platform, _pattern),
13912
+ )
13913
+ # Last, so every other runtime's definitive pattern has claimed its rows
13914
+ # first; the Codex path patterns are excluded again so a config dir
13915
+ # that happens to sit inside a Codex home can never tag a Codex file.
13916
+ if _cfg_where:
13917
+ conn.execute(
13918
+ "UPDATE session_log SET platform = 'claude' "
13919
+ "WHERE platform IS NULL AND (" + _cfg_where + ") "
13920
+ f"AND {_p} NOT LIKE '%/.codex/sessions/%' "
13921
+ f"AND {_p} NOT LIKE '%/.codex/archived_sessions/%'",
13922
+ _claude_cfg_patterns,
13923
+ )
13536
13924
  conn.commit()
13537
13925
  except _SkipMigration:
13538
13926
  pass
@@ -15474,21 +15862,10 @@ def _keepwarm_prefix_proxy(usage):
15474
15862
  cache_creation may be the flat int field OR a nested object (sum its ephemeral
15475
15863
  splits). Falls back to 0 on malformed input.
15476
15864
  """
15865
+ usage = _context_usage(usage)
15477
15866
  if not isinstance(usage, dict):
15478
15867
  return 0
15479
- cr = int(usage.get("cache_read_input_tokens", 0) or 0)
15480
- cc = usage.get("cache_creation_input_tokens", 0)
15481
- if cc is None:
15482
- cc = 0
15483
- cc = int(cc or 0)
15484
- if cc == 0:
15485
- nested = usage.get("cache_creation", {})
15486
- if isinstance(nested, dict):
15487
- cc = int(
15488
- (nested.get("ephemeral_1h_input_tokens", 0) or 0)
15489
- + (nested.get("ephemeral_5m_input_tokens", 0) or 0)
15490
- )
15491
- return cr + cc
15868
+ return _context_token_count(usage) - _safe_int(usage.get("input_tokens"))
15492
15869
 
15493
15870
 
15494
15871
  def _keepwarm_iso_to_epoch(ts):
@@ -16318,6 +16695,10 @@ def _keepwarm_resolve_claude_bin():
16318
16695
  Path("/usr/local/bin/claude"),
16319
16696
  home / ".local" / "bin" / "claude",
16320
16697
  ]
16698
+ # Claude Code's local installer lives under its config dir, so a relocated
16699
+ # CLAUDE_CONFIG_DIR moves it off ~/.claude/local.
16700
+ if CLAUDE_DIR / "local" / "claude" not in candidates:
16701
+ candidates.insert(1, CLAUDE_DIR / "local" / "claude")
16321
16702
  for cand in candidates:
16322
16703
  try:
16323
16704
  if cand.is_file() and os.access(str(cand), os.X_OK):
@@ -16341,13 +16722,7 @@ def _keepwarm_scheduler_install_lock(soft_fail=False):
16341
16722
  max_age = 10 * 60
16342
16723
 
16343
16724
  def _pid_alive(pid):
16344
- if pid <= 0:
16345
- return False
16346
- try:
16347
- os.kill(pid, 0)
16348
- return True
16349
- except OSError:
16350
- return False
16725
+ return _pid_is_running(pid)
16351
16726
 
16352
16727
  def _try_reclaim_stale():
16353
16728
  try:
@@ -17250,15 +17625,7 @@ def _keepwarm_acquire_ping_lock(session_id, now=None):
17250
17625
  owner_pid = None
17251
17626
  alive = False
17252
17627
  if owner_pid and owner_pid > 0:
17253
- try:
17254
- os.kill(owner_pid, 0)
17255
- alive = True
17256
- except ProcessLookupError:
17257
- alive = False
17258
- except PermissionError:
17259
- alive = True # exists but not ours -> treat as live
17260
- except OSError:
17261
- alive = False
17628
+ alive = _pid_is_running(owner_pid)
17262
17629
  if not alive and age > _KEEPWARM_STALE_LOCK_SECONDS:
17263
17630
  try:
17264
17631
  os.unlink(str(lock_path))
@@ -17732,15 +18099,7 @@ def _keepwarm_tick_singleton():
17732
18099
  owner = None
17733
18100
  alive = False
17734
18101
  if owner and owner > 0:
17735
- try:
17736
- os.kill(owner, 0)
17737
- alive = True
17738
- except ProcessLookupError:
17739
- alive = False
17740
- except PermissionError:
17741
- alive = True
17742
- except OSError:
17743
- alive = False
18102
+ alive = _pid_is_running(owner)
17744
18103
  if not alive and (now - st.st_mtime) > _KEEPWARM_STALE_LOCK_SECONDS:
17745
18104
  try:
17746
18105
  os.unlink(str(lock_path))
@@ -18119,9 +18478,10 @@ def _keepwarm_reconstruct_session_events(turns, now):
18119
18478
  gap = cur_epoch - prev_epoch
18120
18479
  if gap <= boundary:
18121
18480
  continue
18122
- prev_cached = (int(prev_turn.get("cache_read", 0) or 0)
18123
- + int(prev_turn.get("cache_creation", 0) or 0))
18124
- cc = int(cur_turn.get("cache_creation", 0) or 0)
18481
+ # Executor occupancy, not the advisor-summed aggregate (#287), so
18482
+ # replay agrees with the live arm path.
18483
+ prev_cached = _turn_prefix_cached(prev_turn)
18484
+ cc = _turn_resume_write(cur_turn)
18125
18485
  if prev_cached <= 0:
18126
18486
  continue
18127
18487
  rewrote = cc >= _CACHE_REWRITE_PREFIX_FRACTION * prev_cached
@@ -18138,8 +18498,7 @@ def _keepwarm_reconstruct_session_events(turns, now):
18138
18498
  })
18139
18499
 
18140
18500
  last_epoch, last_turn = parsed[-1]
18141
- last_cached = (int(last_turn.get("cache_read", 0) or 0)
18142
- + int(last_turn.get("cache_creation", 0) or 0))
18501
+ last_cached = _turn_prefix_cached(last_turn)
18143
18502
  tail = None
18144
18503
  # Only a tail that idled past the boundary AND had a cacheable prefix is a
18145
18504
  # ping candidate (matches the live arm eligibility floor downstream).
@@ -18856,8 +19215,8 @@ def keepwarm_resume_is_warm(turn, prefix_proxy):
18856
19215
  prefix = 0
18857
19216
  if prefix <= 0 or not isinstance(turn, dict):
18858
19217
  return None
18859
- cr = int(turn.get("cache_read", 0) or 0)
18860
- cc = int(turn.get("cache_creation", 0) or 0)
19218
+ cr = int(turn.get("resume_cache_read", turn.get("cache_read", 0)) or 0)
19219
+ cc = int(turn.get("resume_cache_creation", turn.get("cache_creation", 0)) or 0)
18861
19220
  warm = (cr >= _KEEPWARM_WARM_READ_FRACTION * prefix
18862
19221
  and cc < _KEEPWARM_WARM_WRITE_FRACTION * prefix)
18863
19222
  return bool(warm)
@@ -20856,7 +21215,9 @@ def subagent_cache_payoff(days=30, now=None, since_ts=None,
20856
21215
  reqs = []
20857
21216
  for u in (parsed.get("request_usage") or {}).values():
20858
21217
  ts_s = u.get("ts")
20859
- if not ts_s or not isinstance(ts_s, str):
21218
+ if u.get("advisor") or not ts_s or not isinstance(ts_s, str):
21219
+ # Advisor parts run on the advisor's own cache, not this
21220
+ # subagent's prefix.
20860
21221
  continue
20861
21222
  try:
20862
21223
  ts = datetime.fromisoformat(ts_s.replace("Z", "+00:00")).timestamp()
@@ -22367,13 +22728,15 @@ def _detect_explicit_ttl(turns, tier_data, profile, dominant_model=None, detail_
22367
22728
  first_write_tokens = cc
22368
22729
  if prev is not None:
22369
22730
  gap = turn.get("gap_since_prev_seconds")
22370
- prev_cached = int(prev.get("cache_read", 0) or 0) + int(prev.get("cache_creation", 0) or 0)
22731
+ # Threshold basis is executor occupancy (#287); the dollars below
22732
+ # stay on the billed aggregate `cc`.
22733
+ prev_cached = _turn_prefix_cached(prev)
22371
22734
  if (
22372
22735
  gap is not None
22373
22736
  and boundary is not None
22374
22737
  and gap > boundary
22375
22738
  and prev_cached > 0
22376
- and cc >= _CACHE_REWRITE_PREFIX_FRACTION * prev_cached
22739
+ and _turn_resume_write(turn) >= _CACHE_REWRITE_PREFIX_FRACTION * prev_cached
22377
22740
  ):
22378
22741
  if cc_1h or cc_5m:
22379
22742
  split_1h = min(cc_1h, cc)
@@ -23974,6 +24337,68 @@ def _migrate_streaming_dedup(conn, quiet=False):
23974
24337
  print(f" [Token Optimizer] migration failed: {e}", file=sys.stderr)
23975
24338
 
23976
24339
 
24340
+ def _hermes_refresh_session_totals(conn, dedup_key, parsed):
24341
+ """Refresh an existing Hermes row's per-session numbers from a newer snapshot.
24342
+
24343
+ Returns True when the row was updated. The rule is monotonic: Hermes's
24344
+ state.db message and token counters only grow during a session, so the new
24345
+ snapshot wins only when it is >= the stored row on every counter and > on
24346
+ at least one. Quality and skills columns keep their own rules (they need a
24347
+ rollup's live reading) and are not touched here.
24348
+ """
24349
+ stored = conn.execute(
24350
+ "SELECT message_count, input_tokens, output_tokens, api_calls "
24351
+ "FROM session_log WHERE jsonl_path = ?",
24352
+ (dedup_key,),
24353
+ ).fetchone()
24354
+ if stored is None:
24355
+ return False
24356
+ new = (
24357
+ int(parsed.get("message_count") or 0),
24358
+ int(parsed.get("total_input_tokens") or 0),
24359
+ int(parsed.get("total_output_tokens") or 0),
24360
+ int(parsed.get("api_calls") or 0),
24361
+ )
24362
+ old = tuple(int(v or 0) for v in stored)
24363
+ if any(n < o for n, o in zip(new, old)) or new == old:
24364
+ return False
24365
+ conn.execute(
24366
+ """UPDATE session_log
24367
+ SET duration_minutes = ?, input_tokens = ?, output_tokens = ?,
24368
+ message_count = ?, api_calls = ?, cache_hit_rate = ?,
24369
+ cache_create_1h_tokens = ?, cache_create_5m_tokens = ?,
24370
+ avg_call_gap_seconds = ?, max_call_gap_seconds = ?,
24371
+ p95_call_gap_seconds = ?, subagents_json = ?, tool_calls_json = ?,
24372
+ model_usage_json = ?, all_model_usage_json = ?,
24373
+ model_usage_breakdown_json = ?, version = ?, topic = ?,
24374
+ collected_at = ?
24375
+ WHERE jsonl_path = ?""",
24376
+ (
24377
+ parsed["duration_minutes"],
24378
+ parsed["total_input_tokens"],
24379
+ parsed["total_output_tokens"],
24380
+ parsed["message_count"],
24381
+ parsed.get("api_calls", 0),
24382
+ parsed["cache_hit_rate"],
24383
+ parsed.get("total_cache_create_1h", 0),
24384
+ parsed.get("total_cache_create_5m", 0),
24385
+ parsed.get("avg_call_gap_seconds"),
24386
+ parsed.get("max_call_gap_seconds"),
24387
+ parsed.get("p95_call_gap_seconds"),
24388
+ json.dumps(parsed.get("subagents_used", {})),
24389
+ json.dumps(parsed.get("tool_calls", {})),
24390
+ json.dumps(parsed.get("model_usage", {})),
24391
+ json.dumps(parsed.get("model_usage", {})),
24392
+ json.dumps(parsed.get("model_usage_breakdown", {})),
24393
+ parsed.get("version"),
24394
+ parsed.get("topic"),
24395
+ datetime.now().isoformat(),
24396
+ dedup_key,
24397
+ ),
24398
+ )
24399
+ return True
24400
+
24401
+
23977
24402
  def _collect_hermes_sessions(days=90, quiet=False, rebuild=False):
23978
24403
  """Collect Hermes sessions from state.db into the trends DB.
23979
24404
 
@@ -24016,6 +24441,11 @@ def _collect_hermes_sessions(days=90, quiet=False, rebuild=False):
24016
24441
  parsed = hermes_session.normalize_session(row, context_tokens=live_context_tokens)
24017
24442
  if not parsed:
24018
24443
  continue
24444
+ # Skill loads the plugin counted from Hermes's on_skill_lifecycle
24445
+ # hook (state.db does not record them).
24446
+ rollup_skills = globals().get("_HERMES_ROLLUP_SKILLS", {}).get(session_id)
24447
+ if rollup_skills:
24448
+ parsed["skills_used"] = dict(rollup_skills)
24019
24449
 
24020
24450
  slug = parsed.get("slug") or ""
24021
24451
  dedup_key = f"hermes:{slug}" if slug else None
@@ -24023,6 +24453,17 @@ def _collect_hermes_sessions(days=90, quiet=False, rebuild=False):
24023
24453
  continue
24024
24454
 
24025
24455
  if _is_file_collected(conn, dedup_key):
24456
+ # A collect that ran while the session was still live stored
24457
+ # its totals at that point. Hermes's state.db counters only
24458
+ # grow, so refresh the per-session numbers whenever this
24459
+ # snapshot is at least as far along on every counter and ahead
24460
+ # on one. A snapshot behind on any counter is stale (e.g. a
24461
+ # dashboard collect that read state.db before a finished
24462
+ # rollup wrote) and never overwrites the newer row. Totals are
24463
+ # replaced, never added, and the aggregates are rebuilt from
24464
+ # session_log, so a refresh cannot double count.
24465
+ if _hermes_refresh_session_totals(conn, dedup_key, parsed):
24466
+ updated_count += 1
24026
24467
  # A rollup carries the session's live occupancy, which an
24027
24468
  # earlier mid-session collect could not see. Refresh the stored
24028
24469
  # grade in place so the first write does not freeze a
@@ -24040,6 +24481,12 @@ def _collect_hermes_sessions(days=90, quiet=False, rebuild=False):
24040
24481
  ),
24041
24482
  )
24042
24483
  updated_count += 1
24484
+ if rollup_skills:
24485
+ conn.execute(
24486
+ "UPDATE session_log SET skills_json = ? WHERE jsonl_path = ?",
24487
+ (json.dumps(parsed["skills_used"]), dedup_key),
24488
+ )
24489
+ updated_count += 1
24043
24490
  continue
24044
24491
 
24045
24492
  started_at = row.get("started_at")
@@ -24113,6 +24560,44 @@ def _collect_hermes_sessions(days=90, quiet=False, rebuild=False):
24113
24560
  return new_count
24114
24561
 
24115
24562
 
24563
+ _HERMES_SKILLS_MAX = 200
24564
+
24565
+
24566
+ def _parse_hermes_rollup_skills(args):
24567
+ """Parse ``--session`` + ``--skills-json`` out of hermes-rollup CLI args.
24568
+
24569
+ Returns ``{session_id: {skill_name: loads}}`` or ``{}``. The JSON comes
24570
+ from the plugin's in-memory count; anything malformed is dropped, names
24571
+ are capped at 128 characters and counts must be positive integers.
24572
+ """
24573
+ session = ""
24574
+ raw = ""
24575
+ i = 0
24576
+ while i < len(args):
24577
+ if args[i] == "--session" and i + 1 < len(args):
24578
+ session = args[i + 1]
24579
+ i += 2
24580
+ elif args[i] == "--skills-json" and i + 1 < len(args):
24581
+ raw = args[i + 1]
24582
+ i += 2
24583
+ else:
24584
+ i += 1
24585
+ if not session or not raw or len(raw) > 65_536:
24586
+ return {}
24587
+ try:
24588
+ data = json.loads(raw)
24589
+ except ValueError:
24590
+ return {}
24591
+ if not isinstance(data, dict):
24592
+ return {}
24593
+ skills = {}
24594
+ for name, count in list(data.items())[:_HERMES_SKILLS_MAX]:
24595
+ if (isinstance(name, str) and name.strip() and isinstance(count, int)
24596
+ and not isinstance(count, bool) and count > 0):
24597
+ skills[name.strip()[:128]] = min(count, 1_000_000)
24598
+ return {session: skills} if skills else {}
24599
+
24600
+
24116
24601
  def _parse_hermes_rollup_context(args):
24117
24602
  """Parse ``--session``/``--context-tokens`` out of hermes-rollup CLI args.
24118
24603
 
@@ -24144,6 +24629,186 @@ def _parse_hermes_rollup_context(args):
24144
24629
  return {session: context_tokens} if session and context_tokens is not None else {}
24145
24630
 
24146
24631
 
24632
+ # Private scratch dir for the short-lived transcript a Hermes checkpoint is
24633
+ # built from. Files are removed right after use; stragglers from a killed run
24634
+ # are swept after a day.
24635
+ _HERMES_TRANSCRIPT_STALE_SECONDS = 24 * 3600
24636
+
24637
+
24638
+ def _hermes_transcript_dir():
24639
+ return CHECKPOINT_DIR.parent / "hermes-transcripts"
24640
+
24641
+
24642
+ def _sweep_hermes_transcripts(directory, now=None):
24643
+ now = time.time() if now is None else now
24644
+ try:
24645
+ for p in directory.glob("*.jsonl"):
24646
+ try:
24647
+ if not p.is_symlink() and now - p.stat().st_mtime > _HERMES_TRANSCRIPT_STALE_SECONDS:
24648
+ p.unlink()
24649
+ except OSError:
24650
+ continue
24651
+ except OSError:
24652
+ pass
24653
+
24654
+
24655
+ def hermes_checkpoint(session_id, trigger="stop", fill_pct=None, cwd=None):
24656
+ """Write a session checkpoint for a Hermes session.
24657
+
24658
+ Hermes keeps its transcript in state.db, not a JSONL file. Read the
24659
+ session's messages read-only, translate them into the record shape the
24660
+ shared checkpoint engine reads, and hand that to ``compact_capture``. The
24661
+ translated file lives in Token Optimizer's own private directory for the
24662
+ duration of the call only.
24663
+
24664
+ Returns the checkpoint path, or None (no session id, no messages, or the
24665
+ engine declined). Never falls back to guessing another transcript: a
24666
+ Claude Code session on the same machine must never become a Hermes
24667
+ checkpoint.
24668
+ """
24669
+ sid = str(session_id or "").strip()
24670
+ if not sid:
24671
+ return None
24672
+ try:
24673
+ import hermes_state as _hs # noqa: PLC0415
24674
+ import hermes_session as _hsess # noqa: PLC0415
24675
+ except Exception:
24676
+ return None
24677
+ records = _hsess.messages_to_transcript_records(_hs.session_messages(sid, limit=500))
24678
+ if not records:
24679
+ return None
24680
+ if not cwd:
24681
+ # The session's own working directory, so the checkpoint's git line
24682
+ # describes the user's project, not wherever this process started.
24683
+ row_cwd = (_hs.get_session(sid, live=True) or {}).get("cwd")
24684
+ try:
24685
+ if isinstance(row_cwd, str) and row_cwd and Path(row_cwd).is_dir():
24686
+ cwd = row_cwd
24687
+ except (OSError, ValueError):
24688
+ cwd = None
24689
+ directory = _hermes_transcript_dir()
24690
+ try:
24691
+ directory.mkdir(parents=True, exist_ok=True)
24692
+ try:
24693
+ os.chmod(str(directory), 0o700)
24694
+ except OSError:
24695
+ pass
24696
+ except OSError:
24697
+ return None
24698
+ _sweep_hermes_transcripts(directory)
24699
+ fd, tmp_name = tempfile.mkstemp(prefix=".hermes-", suffix=".jsonl", dir=str(directory))
24700
+ tmp_path = Path(tmp_name)
24701
+ try:
24702
+ with os.fdopen(fd, "w", encoding="utf-8") as fh:
24703
+ for record in records:
24704
+ fh.write(json.dumps(record, ensure_ascii=False) + "\n")
24705
+ return compact_capture(
24706
+ session_id=sid,
24707
+ trigger=trigger,
24708
+ cwd=cwd,
24709
+ fill_pct=fill_pct,
24710
+ _trusted_transcript=tmp_path,
24711
+ )
24712
+ finally:
24713
+ try:
24714
+ tmp_path.unlink()
24715
+ except OSError:
24716
+ pass
24717
+
24718
+
24719
+ def _hermes_checkpoint_cli(args):
24720
+ """``hermes-checkpoint --session <id> [--trigger T] [--fill-pct N] [--cwd DIR] [--quiet]``."""
24721
+ sid = ""
24722
+ trigger = "stop"
24723
+ fill_pct = None
24724
+ cwd = None
24725
+ i = 0
24726
+ while i < len(args):
24727
+ a = args[i]
24728
+ if a == "--session" and i + 1 < len(args):
24729
+ sid = args[i + 1]
24730
+ i += 2
24731
+ elif a == "--trigger" and i + 1 < len(args):
24732
+ trigger = args[i + 1]
24733
+ i += 2
24734
+ elif a == "--fill-pct" and i + 1 < len(args):
24735
+ try:
24736
+ fill_pct = float(args[i + 1])
24737
+ except ValueError:
24738
+ fill_pct = None
24739
+ i += 2
24740
+ elif a == "--cwd" and i + 1 < len(args):
24741
+ cwd = args[i + 1] or None
24742
+ i += 2
24743
+ else:
24744
+ i += 1
24745
+ quiet = "--quiet" in args or "-q" in args
24746
+ if cwd is not None:
24747
+ try:
24748
+ if not Path(cwd).is_dir():
24749
+ cwd = None
24750
+ except (OSError, ValueError):
24751
+ cwd = None
24752
+ result = hermes_checkpoint(sid, trigger=trigger, fill_pct=fill_pct, cwd=cwd)
24753
+ if result and not quiet:
24754
+ print(f"[Token Optimizer] Checkpoint saved: {result}")
24755
+ return result
24756
+
24757
+
24758
+ def hermes_turn_context(payload):
24759
+ """Per-turn model context for a Hermes session, in one process.
24760
+
24761
+ Same engines Claude Code's SessionStart / UserPromptSubmit hooks run:
24762
+ - first turn: the new-session checkpoint pointer (compact_restore)
24763
+ - every turn: the topic-matched prior-session hint (_continuity_prompt_hint)
24764
+ - when the plugin passes a live fill reading: the lean-output nudge
24765
+ (_verbosity_nudge_text). Hermes has no session-efficiency signal, so
24766
+ only the strong tier (75-89% fill) can apply; the plugin paces it.
24767
+
24768
+ ``payload`` keys: session_id, prompt, first_turn, fill_pct, score.
24769
+ Returns {"parts": [...], "verbosity": bool}. Never raises.
24770
+ """
24771
+ out = {"parts": [], "verbosity": False}
24772
+ if not isinstance(payload, dict):
24773
+ return out
24774
+ sid = str(payload.get("session_id") or "").strip()
24775
+ if not sid:
24776
+ return out
24777
+ if payload.get("first_turn"):
24778
+ from contextlib import redirect_stdout as _redirect_stdout # noqa: PLC0415
24779
+
24780
+ buf = io.StringIO()
24781
+ try:
24782
+ with _redirect_stdout(buf):
24783
+ compact_restore(session_id=sid, new_session_only=True)
24784
+ except Exception:
24785
+ pass
24786
+ pointer = buf.getvalue().strip()
24787
+ if pointer:
24788
+ out["parts"].append(pointer)
24789
+ prompt = str(payload.get("prompt") or "").strip()
24790
+ if prompt:
24791
+ try:
24792
+ hint = (_continuity_prompt_hint(prompt_text=prompt[:4000], session_id=sid) or "").strip()
24793
+ except Exception:
24794
+ hint = ""
24795
+ if hint:
24796
+ out["parts"].append(hint)
24797
+ fill = payload.get("fill_pct")
24798
+ if isinstance(fill, (int, float)) and not isinstance(fill, bool):
24799
+ score = payload.get("score")
24800
+ score = float(score) if isinstance(score, (int, float)) and not isinstance(score, bool) else 100.0
24801
+ # No efficiency signal on Hermes: 100 keeps the gentle tier off.
24802
+ window = payload.get("context_window")
24803
+ cached = ({"model_context_window": int(window)}
24804
+ if isinstance(window, int) and not isinstance(window, bool) and window > 0 else {})
24805
+ nudge = _verbosity_nudge_text(float(fill), score, 100, cached)
24806
+ if nudge:
24807
+ out["parts"].append(nudge)
24808
+ out["verbosity"] = True
24809
+ return out
24810
+
24811
+
24147
24812
  def _resolve_copilot_home_wsl_aware(mnt_root=None):
24148
24813
  """Resolve the Copilot home with a WSL-root /mnt/ exception.
24149
24814
 
@@ -28962,6 +29627,10 @@ def _resolve_runtime_bin(process_name):
28962
29627
  Path("/usr/local/bin") / process_name,
28963
29628
  home / ".bun" / "bin" / process_name,
28964
29629
  ]
29630
+ # Claude Code's local installer lives under its config dir, so a relocated
29631
+ # CLAUDE_CONFIG_DIR moves it off ~/.claude/local.
29632
+ if process_name == "claude" and CLAUDE_DIR / "local" / process_name not in candidates:
29633
+ candidates.insert(2, CLAUDE_DIR / "local" / process_name)
28965
29634
  for cand in candidates:
28966
29635
  try:
28967
29636
  if cand.is_file() and os.access(str(cand), os.X_OK):
@@ -30730,7 +31399,7 @@ def _maybe_self_heal_sessionend_fossils_on_hook():
30730
31399
  _clear_hook_budget(deadline)
30731
31400
 
30732
31401
 
30733
- def setup_hook(dry_run=False, uninstall=False):
31402
+ def setup_hook(dry_run=False, uninstall=False, user_initiated=False):
30734
31403
  """Install or uninstall the SessionEnd hook for automatic usage collection.
30735
31404
 
30736
31405
  ``uninstall=True`` removes ONLY Token Optimizer's own SessionEnd hook
@@ -30786,7 +31455,7 @@ def setup_hook(dry_run=False, uninstall=False):
30786
31455
  import shutil
30787
31456
  shutil.copy2(str(SETTINGS_PATH), str(backup_path))
30788
31457
  try:
30789
- if not _write_settings_atomic(settings):
31458
+ if not _write_settings_atomic(settings, user_initiated=user_initiated):
30790
31459
  print("[Error] settings.json write was refused; no SessionEnd hooks were removed.", file=sys.stderr)
30791
31460
  return
30792
31461
  print(f"[Token Optimizer] Removed {removed} Token Optimizer SessionEnd hook(s) from settings.json.")
@@ -30878,7 +31547,7 @@ def setup_hook(dry_run=False, uninstall=False):
30878
31547
 
30879
31548
  # Write atomically
30880
31549
  try:
30881
- if not _write_settings_atomic(settings):
31550
+ if not _write_settings_atomic(settings, user_initiated=user_initiated):
30882
31551
  print("[Error] settings.json write was refused; SessionEnd hook was not installed.", file=sys.stderr)
30883
31552
  return
30884
31553
  action = "upgraded" if upgrading else "installed"
@@ -33145,13 +33814,7 @@ def _daemon_install_lock(soft_fail=False):
33145
33814
  MAX_LOCK_AGE = 10 * 60 # 10 minutes
33146
33815
 
33147
33816
  def _pid_alive(pid):
33148
- if pid <= 0:
33149
- return False
33150
- try:
33151
- os.kill(pid, 0)
33152
- return True
33153
- except OSError:
33154
- return False
33817
+ return _pid_is_running(pid)
33155
33818
 
33156
33819
  def _try_reclaim_stale():
33157
33820
  """Return True if we successfully reaped a stale lock, False otherwise."""
@@ -33946,6 +34609,11 @@ def _generate_windows_launcher_cmd(daemon_script_path, log_dir):
33946
34609
 
33947
34610
  return (
33948
34611
  "@echo off\r\n"
34612
+ # cmd.exe reads a batch file in the console (OEM) code page, but this
34613
+ # file is written as UTF-8: a profile path like C:\Users\Jos\u00e9 was
34614
+ # garbled and the daemon never started. Switch to UTF-8 first; this
34615
+ # line and everything above it is plain ASCII.
34616
+ "chcp 65001\r\n"
33949
34617
  "REM Token Optimizer dashboard daemon launcher (v5.3.2+).\r\n"
33950
34618
  "REM Auto-generated. Resolves Python at runtime so interpreter upgrades\r\n"
33951
34619
  "REM do not break the scheduled task.\r\n"
@@ -33959,7 +34627,7 @@ def _generate_windows_launcher_cmd(daemon_script_path, log_dir):
33959
34627
  f'set "STDOUT_LOG={log_dir}\\stdout.log"\r\n'
33960
34628
  f'set "STDERR_LOG={log_dir}\\stderr.log"\r\n'
33961
34629
  'if not exist "%DAEMON_SCRIPT%" (\r\n'
33962
- ' echo [%DATE% %TIME%] daemon script missing: %DAEMON_SCRIPT% >> "%STDERR_LOG%"\r\n'
34630
+ ' echo [%DATE% %TIME%] daemon script missing: "%DAEMON_SCRIPT%" >> "%STDERR_LOG%"\r\n'
33963
34631
  " exit /b 1\r\n"
33964
34632
  ")\r\n"
33965
34633
  'set "PYW_EXE="\r\n'
@@ -34958,6 +35626,15 @@ def _retained_paths() -> list[tuple[str, Path]]:
34958
35626
  pass
34959
35627
  # Always include the resolved snapshot dir even under a sandbox override.
34960
35628
  paths.append(("session data (this install)", SNAPSHOT_DIR))
35629
+ # Compaction checkpoints (conversation-context captures) live under the
35630
+ # per-session state base, which on a script install is NOT inside
35631
+ # SNAPSHOT_DIR (#106 named them as undisclosed). Disclose them too.
35632
+ try:
35633
+ listed = {p for _, p in paths}
35634
+ if CHECKPOINT_DIR not in listed:
35635
+ paths.append(("checkpoints (this install)", CHECKPOINT_DIR))
35636
+ except NameError:
35637
+ pass
34961
35638
  return paths
34962
35639
 
34963
35640
 
@@ -35034,6 +35711,9 @@ def _remove_our_settings_entries(settings: dict) -> list[str]:
35034
35711
  ``quality-cache`` (our cache hook).
35035
35712
  - ``SessionEnd`` hook entries that are ours (reuses
35036
35713
  _remove_token_optimizer_session_end_hooks).
35714
+ - ``compactInstructions`` when it is the block setup-smart-compact
35715
+ generated (removed) or holds our appended section (only that section
35716
+ is removed; the user's own text stays).
35037
35717
 
35038
35718
  Foreign statusLines, foreign hooks, and every other settings key are left
35039
35719
  byte-identical. Returns a list of human-readable descriptions of what was
@@ -35101,6 +35781,10 @@ def _remove_our_settings_entries(settings: dict) -> list[str]:
35101
35781
  n_session_end = _remove_token_optimizer_session_end_hooks(settings)
35102
35782
  if n_session_end:
35103
35783
  removed.append(f"{n_session_end} SessionEnd hook(s)")
35784
+ # compactInstructions written by setup-smart-compact (#106: it outlived
35785
+ # cleanup). Only our generated block / appended section is removed.
35786
+ if _remove_our_compact_instructions(settings):
35787
+ removed.append("compactInstructions (token-optimizer)")
35104
35788
  return removed
35105
35789
 
35106
35790
 
@@ -35149,6 +35833,24 @@ def cleanup(dry_run=False, this_install_only=False):
35149
35833
  # the preview stays side-effect-free.
35150
35834
  if not dry_run:
35151
35835
  _unlink_if_exists(PLIST_PATH)
35836
+ # Same reasoning for the other platforms' per-identity daemon files:
35837
+ # each platform's uninstaller sweeps only its own launcher, so a HOME
35838
+ # synced or migrated from another OS kept dashboard-launcher.cmd /
35839
+ # .schtasks-daemon.xml (Windows) or the Linux launcher after cleanup
35840
+ # (#106). They are plain files once the scheduler job is gone.
35841
+ if not _daemon_snapshot_sandboxed():
35842
+ for _snap in _daemon_identity_snapshot_dirs(this_install_only):
35843
+ _gone, _ = _sweep_identity_daemon_files(
35844
+ _snap, ("daemon_script", "daemon_token", "daemon_host",
35845
+ "windows_launcher", "linux_launcher"))
35846
+ try:
35847
+ for _xml in _snap.glob("*schtasks-daemon*.xml"):
35848
+ if _unlink_if_exists(_xml):
35849
+ _gone.append(str(_xml))
35850
+ except OSError:
35851
+ pass
35852
+ for _path in _gone:
35853
+ print(f" Deleted: {_path}")
35152
35854
  print()
35153
35855
 
35154
35856
  # 2. settings.json
@@ -35198,7 +35900,14 @@ def cleanup(dry_run=False, this_install_only=False):
35198
35900
  # silent no-op. Reporting "Removed" for a write that never
35199
35901
  # landed leaves the user with the dangling statusLine this
35200
35902
  # command exists to clear, so surface it instead.
35201
- if _write_settings_atomic(fresh, allow_removing_keys={"statusLine"}):
35903
+ # user_initiated: cleanup is an explicit user command. Under
35904
+ # the hook cohort throttle any Token Optimizer settings
35905
+ # write in the previous ~10s (a SessionStart heal, a setup
35906
+ # command) made this write lose the lease, and the whole
35907
+ # removal was skipped (#106 leftovers).
35908
+ if _write_settings_atomic(
35909
+ fresh, allow_removing_keys={"statusLine", "compactInstructions"},
35910
+ user_initiated=True):
35202
35911
  for entry in our_entries:
35203
35912
  print(f" Removed: {entry}")
35204
35913
  print(f" Backup: {backed}")
@@ -36445,7 +37154,8 @@ def _external_memory_present() -> bool:
36445
37154
  without touching the filesystem.
36446
37155
  2. A neutral coordination marker file, whose mere existence means an
36447
37156
  external durable-memory tool is active:
36448
- ``${TO_EXTERNAL_MEMORY_MARKER:-~/.claude/durable-memory.json}``.
37157
+ ``${TO_EXTERNAL_MEMORY_MARKER:-<claude home>/durable-memory.json}``, where the
37158
+ Claude home honors CLAUDE_CONFIG_DIR (CLAUDE_DIR / claude_home()).
36449
37159
 
36450
37160
  The external tool writes the marker once (set-and-forget), so detection is
36451
37161
  automatic with no per-session configuration. Cached in a module global so
@@ -36469,7 +37179,7 @@ def _external_memory_present() -> bool:
36469
37179
  marker = (
36470
37180
  Path(marker_env).expanduser()
36471
37181
  if marker_env
36472
- else Path.home() / ".claude" / "durable-memory.json"
37182
+ else CLAUDE_DIR / "durable-memory.json"
36473
37183
  )
36474
37184
  try:
36475
37185
  if marker.exists():
@@ -36548,6 +37258,100 @@ def _extract_user_text(record):
36548
37258
  return ""
36549
37259
 
36550
37260
 
37261
+ _HARNESS_TASK_PREFIXES = (
37262
+ "<local-command-caveat>", "<local-command-stdout>",
37263
+ "<local-command-stderr>", "<task-notification>",
37264
+ "[SYSTEM NOTIFICATION", "[Request interrupted by user",
37265
+ "Your response above was cut off mid-stream",
37266
+ )
37267
+ # Built-in commands that only change the session or UI. Run bare, they are not
37268
+ # a task. With arguments, or when an installed skill owns the name, they are.
37269
+ _LOCAL_SLASH_COMMANDS = frozenset((
37270
+ "add-dir", "agents", "bug", "config", "context", "continue", "cost",
37271
+ "doctor", "exit", "export", "fast", "feedback", "help", "hooks", "ide",
37272
+ "init", "login", "logout", "mcp", "memory", "model", "output-style",
37273
+ "permissions", "privacy-settings", "quit", "release-notes", "resume",
37274
+ "rewind", "settings", "stats", "status", "statusline", "terminal-setup",
37275
+ "theme", "upgrade", "usage", "vim",
37276
+ ))
37277
+ _COMMAND_TASK_TAG_RE = re.compile(r"\s*<command-(name|message|args)>")
37278
+
37279
+
37280
+ def _command_task_text(text):
37281
+ """Unwrap a complete command once, with bounded, non-backtracking scans."""
37282
+ fields = {}
37283
+ pos = 0
37284
+ while pos < len(text):
37285
+ if not text[pos:].strip():
37286
+ break
37287
+ tag = _COMMAND_TASK_TAG_RE.match(text, pos)
37288
+ if tag is None or tag.group(1) in fields:
37289
+ return ""
37290
+ name = tag.group(1)
37291
+ close = "</command-" + name + ">"
37292
+ end = text.find(close, tag.end())
37293
+ if end < 0:
37294
+ return ""
37295
+ fields[name] = text[tag.end():end]
37296
+ pos = end + len(close)
37297
+ command = _SLASH_COMMAND_RE.fullmatch(
37298
+ "<command-name>" + fields.get("name", "") + "</command-name>")
37299
+ if command is None:
37300
+ return ""
37301
+ name = command.group(1)
37302
+ if name.lower() in ("compact", "clear"):
37303
+ return ""
37304
+ # Some versions omit an empty <command-args>: treat a missing tag as empty.
37305
+ args = fields.get("args", "").strip()
37306
+ if (not args and name.lower() in _LOCAL_SLASH_COMMANDS
37307
+ and not _resolve_installed_skill(name)):
37308
+ return ""
37309
+ return "/" + name + (" " + args if args else "")
37310
+
37311
+
37312
+ def _task_user_text(record):
37313
+ """Task text for continuity only, excluding harness/meta/tool transport.
37314
+
37315
+ A slash-command wrapper is transport, but its name and arguments can be
37316
+ a real task. Preserve those without changing raw scoring/skill-use input.
37317
+ """
37318
+ if record.get("isMeta") or record.get("isCompactSummary"):
37319
+ return ""
37320
+ message = record.get("message", {})
37321
+ content = message.get("content") if isinstance(message, dict) else message
37322
+ if isinstance(content, str):
37323
+ parts = [content]
37324
+ elif isinstance(content, list):
37325
+ parts = [
37326
+ block if isinstance(block, str) else block.get("text", "")
37327
+ for block in content
37328
+ if isinstance(block, str) or (
37329
+ isinstance(block, dict) and block.get("type") == "text")
37330
+ ]
37331
+ else:
37332
+ return ""
37333
+ texts = []
37334
+ for part in parts:
37335
+ if not isinstance(part, str):
37336
+ continue
37337
+ text = part.strip()
37338
+ # A <system-reminder> block can lead a real prompt: drop the block,
37339
+ # keep what follows. An unclosed block is all harness.
37340
+ while text.startswith("<system-reminder>"):
37341
+ end = text.find("</system-reminder>")
37342
+ text = "" if end < 0 else text[end + len("</system-reminder>"):].strip()
37343
+ if not text or text.startswith(_HARNESS_TASK_PREFIXES):
37344
+ continue
37345
+ if text.startswith(("<command-name>", "<command-message>", "<command-args>")):
37346
+ # Only a complete wrapper is an invocation. Do not turn malformed
37347
+ # harness markup into a recovered task, or strip tags from prose.
37348
+ text = _command_task_text(text)
37349
+ if not text:
37350
+ continue
37351
+ texts.append(text)
37352
+ return "\n".join(texts)
37353
+
37354
+
36551
37355
  def _read_stdin_hook_input(max_bytes=65536):
36552
37356
  """Thin wrapper: measure.py callers default to 64KB (PreToolUse payloads)."""
36553
37357
  return _read_stdin_hook_input_shared(max_bytes)
@@ -36710,9 +37514,7 @@ def _parse_jsonl_for_quality(filepath):
36710
37514
  # raise and abort the whole parse (losing all quality data).
36711
37515
  usage = msg.get("usage")
36712
37516
  if isinstance(usage, dict):
36713
- tok = (_safe_int(usage.get("input_tokens"))
36714
- + _safe_int(usage.get("cache_creation_input_tokens"))
36715
- + _safe_int(usage.get("cache_read_input_tokens")))
37517
+ tok = _context_token_count(_context_usage(usage))
36716
37518
  if tok > 0:
36717
37519
  context_tokens = tok
36718
37520
  model_str = msg.get("model")
@@ -39738,6 +40540,78 @@ def _log_reexpand_debit(session_id, tool_use_id, response_text):
39738
40540
  pass
39739
40541
 
39740
40542
 
40543
+ def _find_archive_entry(archive_roots, tool_use_id, session_id=None, strict=False):
40544
+ """First ``<root>/<session>/<tool_use_id>.json`` that exists, or None.
40545
+
40546
+ *tool_use_id* must already have passed expand's ``[a-zA-Z0-9_-]+`` check, so
40547
+ the filename can never leave its session dir. *strict* (the cross-runtime
40548
+ fallback) additionally requires a regular, non-symlink file whose resolved
40549
+ path stays inside its archive root.
40550
+ """
40551
+ for archive_root in archive_roots:
40552
+ if session_id:
40553
+ sid = sanitize_session_id(session_id)
40554
+ if sid == "unknown":
40555
+ continue
40556
+ session_dirs = [archive_root / sid]
40557
+ elif archive_root.is_dir() and not archive_root.is_symlink():
40558
+ try:
40559
+ session_dirs = [d for d in archive_root.iterdir()
40560
+ if d.is_dir() and not d.is_symlink()]
40561
+ except OSError:
40562
+ continue
40563
+ else:
40564
+ continue
40565
+ for sd in session_dirs:
40566
+ entry_path = sd / f"{tool_use_id}.json"
40567
+ try:
40568
+ if not entry_path.exists():
40569
+ continue
40570
+ if strict:
40571
+ if (archive_root.is_symlink() or sd.is_symlink()
40572
+ or entry_path.is_symlink() or not entry_path.is_file()):
40573
+ continue
40574
+ entry_path.resolve(strict=True).relative_to(archive_root.resolve(strict=True))
40575
+ except (OSError, ValueError):
40576
+ continue
40577
+ return entry_path
40578
+ return None
40579
+
40580
+
40581
+ # Every runtime whose archive an unpinned expand may fall back to, in lookup order.
40582
+ _EXPAND_FALLBACK_RUNTIMES = ("claude", "codex", "hermes", "copilot", "cursor",
40583
+ "opencode", "antigravity", "grok", "devin")
40584
+
40585
+
40586
+ def _expand_may_cross_runtimes():
40587
+ """True for a bare expand: no --runtime / TOKEN_OPTIMIZER_RUNTIME pin and
40588
+ no sandbox snapshot override."""
40589
+ return not (os.environ.get("TOKEN_OPTIMIZER_RUNTIME", "").strip()
40590
+ or os.environ.get("TOKEN_OPTIMIZER_SNAPSHOT_DIR", "").strip())
40591
+
40592
+
40593
+ def _cross_runtime_archive_roots(exclude):
40594
+ """tool-archive dirs under every other runtime's home. Never raises."""
40595
+ roots = []
40596
+ seen = set(exclude)
40597
+ try:
40598
+ from runtime_env import runtime_home_for
40599
+ from plugin_env import snapshot_roots_for_home
40600
+ except Exception:
40601
+ return roots
40602
+ for runtime in _EXPAND_FALLBACK_RUNTIMES:
40603
+ try:
40604
+ home = runtime_home_for(runtime)
40605
+ for snapshot_root in snapshot_roots_for_home(home):
40606
+ root = snapshot_root / "tool-archive"
40607
+ if root not in seen:
40608
+ seen.add(root)
40609
+ roots.append(root)
40610
+ except Exception:
40611
+ continue
40612
+ return roots
40613
+
40614
+
39741
40615
  def expand_archived(tool_use_id=None, session_id=None, list_all=False):
39742
40616
  """Retrieve an archived tool result, or list all archived results.
39743
40617
 
@@ -39810,48 +40684,43 @@ def expand_archived(tool_use_id=None, session_id=None, list_all=False):
39810
40684
  print("[Error] Invalid tool_use_id format.", file=sys.stderr)
39811
40685
  sys.exit(1)
39812
40686
 
39813
- if not any(root.is_dir() for root in archive_roots):
40687
+ entry_path = _find_archive_entry(archive_roots, tool_use_id, session_id)
40688
+ if entry_path is None and _expand_may_cross_runtimes():
40689
+ # Not in this runtime's archive. A pointer printed by Claude Code is
40690
+ # never pinned, so a shell that detects another runtime (or a scan
40691
+ # that failed open to Claude Code when the archive was written under
40692
+ # another runtime) would otherwise miss an entry that exists. Only an
40693
+ # unpinned expand falls back; an explicit --runtime stays strict.
40694
+ fallback_roots = _cross_runtime_archive_roots(archive_roots)
40695
+ entry_path = _find_archive_entry(fallback_roots, tool_use_id, session_id, strict=True)
40696
+ if entry_path is None and not any(root.is_dir() for root in archive_roots):
40697
+ archive_roots = archive_roots + [r for r in fallback_roots if r.is_dir()]
40698
+
40699
+ if entry_path is None and not any(root.is_dir() for root in archive_roots):
39814
40700
  print("[Error] No archive directory found. No results have been archived yet.", file=sys.stderr)
39815
40701
  sys.exit(1)
39816
40702
 
39817
- # Determine search scope
39818
- if session_id:
39819
- sid = sanitize_session_id(session_id)
39820
- search_dirs = [
39821
- archive_root / sid for archive_root in archive_roots
39822
- if sid != "unknown"
39823
- ]
39824
- else:
39825
- search_dirs = []
39826
- for archive_root in archive_roots:
39827
- if archive_root.is_dir() and not archive_root.is_symlink():
39828
- search_dirs.extend(
39829
- d for d in archive_root.iterdir()
39830
- if d.is_dir() and not d.is_symlink()
39831
- )
39832
-
39833
- for sd in search_dirs:
39834
- entry_path = sd / f"{tool_use_id}.json"
39835
- if entry_path.exists():
39836
- try:
39837
- data = json.loads(entry_path.read_text(encoding="utf-8"))
39838
- response = data.get("response", "")
39839
- if response:
39840
- # B6 integrity: re-popping an archived result means it did NOT
39841
- # stay collapsed, so reverse its tool_archive credit. Log the
39842
- # re-popped tokens as a debit (netted in _get_savings_summary),
39843
- # deduped per item so a second expand never double-debits.
39844
- _log_reexpand_debit(sd.name, tool_use_id, response)
39845
- # No added newline: expand returns the stored text as stored.
39846
- sys.stdout.write(response)
39847
- sys.stdout.flush()
39848
- return
39849
- else:
39850
- print(f"[Error] Archived entry found but response is empty: {entry_path}", file=sys.stderr)
39851
- sys.exit(1)
39852
- except (json.JSONDecodeError, OSError) as e:
39853
- print(f"[Error] Failed to read archived result: {e}", file=sys.stderr)
40703
+ if entry_path is not None:
40704
+ sd = entry_path.parent
40705
+ try:
40706
+ data = json.loads(entry_path.read_text(encoding="utf-8"))
40707
+ response = data.get("response", "")
40708
+ if response:
40709
+ # B6 integrity: re-popping an archived result means it did NOT
40710
+ # stay collapsed, so reverse its tool_archive credit. Log the
40711
+ # re-popped tokens as a debit (netted in _get_savings_summary),
40712
+ # deduped per item so a second expand never double-debits.
40713
+ _log_reexpand_debit(sd.name, tool_use_id, response)
40714
+ # No added newline: expand returns the stored text as stored.
40715
+ sys.stdout.write(response)
40716
+ sys.stdout.flush()
40717
+ return
40718
+ else:
40719
+ print(f"[Error] Archived entry found but response is empty: {entry_path}", file=sys.stderr)
39854
40720
  sys.exit(1)
40721
+ except (json.JSONDecodeError, OSError) as e:
40722
+ print(f"[Error] Failed to read archived result: {e}", file=sys.stderr)
40723
+ sys.exit(1)
39855
40724
 
39856
40725
  print(f"[Error] Tool result not found: {tool_use_id}", file=sys.stderr)
39857
40726
  if not session_id:
@@ -40083,11 +40952,9 @@ def _purge_all_data(confirm=False, force=False):
40083
40952
  try:
40084
40953
  raw = pid_file.read_text(encoding="utf-8").strip()
40085
40954
  candidate_pid = int(raw)
40086
- try:
40087
- os.kill(candidate_pid, 0)
40955
+ if _pid_is_running(candidate_pid):
40088
40956
  running_pid = candidate_pid
40089
- except OSError:
40090
- pass # process not alive; PID file is stale
40957
+ # else: process not alive; PID file is stale
40091
40958
  except (OSError, ValueError):
40092
40959
  pass
40093
40960
 
@@ -40103,9 +40970,14 @@ def _purge_all_data(confirm=False, force=False):
40103
40970
  # Verify PID identity before SIGTERM to avoid killing a recycled PID
40104
40971
  is_ours = False
40105
40972
  try:
40106
- result = _sp.run(["ps", "-p", str(running_pid), "-o", "comm="],
40107
- capture_output=True, text=True, timeout=3)
40108
- proc_name = result.stdout.strip().lower()
40973
+ if os.name == "nt":
40974
+ # No `ps` on Windows: the daemon was never stopped there, and
40975
+ # the purge then hit the files it still held open.
40976
+ proc_name = ((_windows_process_names() or {}).get(running_pid) or (0, ""))[1]
40977
+ else:
40978
+ result = _sp.run(["ps", "-p", str(running_pid), "-o", "comm="],
40979
+ capture_output=True, text=True, timeout=3)
40980
+ proc_name = result.stdout.strip().lower()
40109
40981
  is_ours = "python" in proc_name or "measure" in proc_name
40110
40982
  except Exception:
40111
40983
  is_ours = False
@@ -40295,9 +41167,8 @@ def _security_report(as_json=False):
40295
41167
  pid_file = DAEMON_LOG_DIR / "daemon.pid"
40296
41168
  if pid_file.exists():
40297
41169
  try:
40298
- daemon_pid = int(pid_file.read_text().strip())
40299
- os.kill(daemon_pid, 0)
40300
- daemon_running = True
41170
+ daemon_pid = int(pid_file.read_text(encoding="utf-8").strip())
41171
+ daemon_running = _pid_is_running(daemon_pid)
40301
41172
  except (ValueError, OSError):
40302
41173
  pass
40303
41174
 
@@ -40543,7 +41414,7 @@ def _extract_session_state(filepath, tail_lines=500):
40543
41414
 
40544
41415
  # User messages
40545
41416
  if rec_type == "user":
40546
- text = _ingest_redact(_extract_user_text(record))
41417
+ text = _ingest_redact(_task_user_text(record))
40547
41418
  if text.strip():
40548
41419
  last_user_msg = text.strip()
40549
41420
  # Check for questions
@@ -40766,13 +41637,22 @@ def _redaction_skip_notice(session_id):
40766
41637
  return None
40767
41638
 
40768
41639
 
40769
- def compact_capture(transcript_path=None, session_id=None, trigger="auto", cwd=None, fill_pct=None, quality_score=None, backfill_tools=False):
41640
+ class _SkipTranscriptQuality(Exception):
41641
+ """Internal: leave the transcript-derived quality block out of a checkpoint."""
41642
+
41643
+
41644
+ def compact_capture(transcript_path=None, session_id=None, trigger="auto", cwd=None, fill_pct=None, quality_score=None, backfill_tools=False, _trusted_transcript=None):
40770
41645
  """Capture structured session state before compaction or session end.
40771
41646
 
40772
41647
  Writes a markdown checkpoint to CHECKPOINT_DIR.
40773
41648
  Called by PreCompact, Stop, and SessionEnd hooks via CLI.
40774
41649
  Progressive checkpoints pass fill_pct and trigger="progressive-{band}".
40775
41650
 
41651
+ ``_trusted_transcript`` is for internal callers only: a transcript Token
41652
+ Optimizer built itself in its own private directory (the Hermes adapter
41653
+ translates Hermes's state.db messages into one). It skips the confinement
41654
+ meant for hook-supplied paths. Never pass hook input through it.
41655
+
40776
41656
  Returns the checkpoint file path, or None on failure.
40777
41657
  """
40778
41658
  # Validate trigger before it flows into the checkpoint filename.
@@ -40794,7 +41674,9 @@ def compact_capture(transcript_path=None, session_id=None, trigger="auto", cwd=N
40794
41674
  ts = now.strftime("%Y-%m-%dT%H:%M:%S%z")
40795
41675
  ts_file = now.strftime("%Y%m%d-%H%M%S")
40796
41676
 
40797
- if transcript_path:
41677
+ if _trusted_transcript is not None:
41678
+ filepath = Path(_trusted_transcript)
41679
+ elif transcript_path:
40798
41680
  # A supplied path that fails confinement is a forged hook input — do
40799
41681
  # not checkpoint from it, and do not fall through to inference (which
40800
41682
  # would let a bad pointer silently capture a different session).
@@ -40812,6 +41694,20 @@ def compact_capture(transcript_path=None, session_id=None, trigger="auto", cwd=N
40812
41694
  trigger_suffix = f"-{trigger}" if trigger and trigger != "auto" else ""
40813
41695
 
40814
41696
  if not filepath or not filepath.exists():
41697
+ if _use_codex_session_adapter(transcript_path or None):
41698
+ # Codex with no readable transcript: a "No transcript data
41699
+ # available" placeholder (named "unknown" when the host sent no
41700
+ # session id) holds nothing to restore, can outrank real
41701
+ # checkpoints, and hides that capture failed (issue #278). Say
41702
+ # why instead, for the doctor; never the id or path themselves.
41703
+ _record_hook_status(
41704
+ "stop_capture" if trigger in ("stop", "end") else "checkpoint_capture",
41705
+ "skipped: " + (
41706
+ "the transcript path the host sent is outside the Codex sessions folder or unreadable"
41707
+ if transcript_path else
41708
+ "no Codex transcript matches the session id the host sent" if session_id else
41709
+ "the hook payload and environment carried no session id"))
41710
+ return None
40815
41711
  # Write minimal checkpoint with safe permissions
40816
41712
  sid = sanitize_session_id(session_id)
40817
41713
  checkpoint_path = CHECKPOINT_DIR / f"{sid}-{ts_file}{trigger_suffix}.md"
@@ -40868,6 +41764,11 @@ def compact_capture(transcript_path=None, session_id=None, trigger="auto", cwd=N
40868
41764
  sid = sanitize_session_id(session_id) if session_id else sanitize_session_id(filepath.stem)
40869
41765
  quality_summary = None
40870
41766
  try:
41767
+ if _trusted_transcript is not None:
41768
+ # A translated transcript carries no usage data, so scoring it
41769
+ # would print a fake perfect grade. The caller passes the real
41770
+ # fill instead; the quality block is simply left out.
41771
+ raise _SkipTranscriptQuality()
40871
41772
  # Prefer the per-session quality cache over re-parsing the whole transcript.
40872
41773
  # _parse_jsonl_for_quality is O(file): a ~200MB session costs ~8s, and this
40873
41774
  # runs on the synchronous Stop hook, so an unbounded reparse shows up as
@@ -40911,7 +41812,12 @@ def compact_capture(transcript_path=None, session_id=None, trigger="auto", cwd=N
40911
41812
  pass
40912
41813
  fill_info = f" | Fill: {fill_pct:.0f}%" if fill_pct is not None else ""
40913
41814
  quality_info = f" | Quality: {quality_score:.1f}" if quality_score is not None else ""
40914
- git_branch, git_sha = _capture_git_state(cwd)
41815
+ if _trusted_transcript is not None and not cwd:
41816
+ # No known working directory: this process's own cwd is not the
41817
+ # session's project, so its git state would be someone else's.
41818
+ git_branch, git_sha = None, None
41819
+ else:
41820
+ git_branch, git_sha = _capture_git_state(cwd)
40915
41821
  git_line = ""
40916
41822
  if git_branch or git_sha:
40917
41823
  git_line = f" | Git: {git_branch or '?'}@{git_sha or '?'}"
@@ -42507,27 +43413,42 @@ _RESUME_TOPIC_STOPWORDS = frozenset({
42507
43413
 
42508
43414
 
42509
43415
  # --- Non-English topic tokenizer — single source of truth on the Python side ---
42510
- # Two branches: an ASCII/accented-Latin run, OR a whole non-ASCII run (CJK etc.) as one
42511
- # token, so a token never mixes ASCII and non-ASCII ("measure.py를" -> "measure.py" + "를").
43416
+ # Two branches: an ASCII/accented-Latin run, OR a whole non-ASCII run as one token, so a token
43417
+ # never mixes ASCII and non-ASCII ("measure.py를" -> "measure.py" + "를").
42512
43418
  # The Latin-1/Extended-A ranges deliberately skip U+00D7 (×) and U+00F7 (÷): they sit inside
42513
43419
  # the block but are math symbols, not letters. U+0100–U+024F is Latin Extended-A/B, all letters.
42514
43420
  _TOPIC_TOKEN_RE = re.compile(r"[a-zA-Z0-9_.:À-ÖØ-öø-ÿĀ-ɏ/-]+|[^\x00-\x7F]+")
42515
- # Script-aware length floor. CJK scripts (Hangul/Han/Kana, all >= U+3000) carry a full topic
42516
- # word in two characters — 결제 (payment), 모듈 (module) — so they are kept at len>=2. ASCII and
42517
- # accented Latin keep the len>3 English stopword heuristic (a 2-char Latin token like "ré" is
42518
- # stopword-like, not content). This is why the floor cannot be a single constant.
42519
- _CJK_MIN = 0x3000
43421
+ # Script-aware length floor, defined by fixed code-point ranges so Python, OpenClaw and
43422
+ # OpenCode classify every character the same way on any Unicode version.
43423
+ # * Any char at or above U+3000 (Han, Kana, Hangul, fullwidth forms): a 2-char word such as
43424
+ # 결제 (payment) or 모듈 (module) is a full topic, so keep len>=2.
43425
+ # * Other non-Latin letters (Cyrillic, Greek, Arabic, Hebrew, Indic...): keep len>=3, which
43426
+ # keeps "кот" but drops 2-letter function words such as "на", "في", "של".
43427
+ # * Latin (ASCII, accented, extended, letterlike): the len>3 English stopword heuristic.
43428
+ # Combining marks (accents, niqqud, harakat) never count toward the length.
43429
+ _TOPIC_WIDE_MIN = 0x3000
43430
+ _TOPIC_LATIN_RANGES = (
43431
+ (0x0000, 0x036F), (0x1D00, 0x1DFF), (0x1E00, 0x1EFF), (0x2000, 0x214F),
43432
+ (0x2C60, 0x2C7F), (0xA720, 0xA7FF), (0xAB30, 0xAB6F),
43433
+ )
43434
+ _TOPIC_MARK_RANGES = (
43435
+ (0x0300, 0x036F), (0x0483, 0x0489), (0x0591, 0x05C7), (0x0610, 0x061A), (0x064B, 0x065F),
43436
+ (0x0670, 0x0670), (0x06D6, 0x06ED), (0x1AB0, 0x1AFF), (0x1DC0, 0x1DFF), (0x200B, 0x200F),
43437
+ (0x20D0, 0x20FF), (0xFE00, 0xFE0F), (0xFE20, 0xFE2F),
43438
+ )
42520
43439
 
42521
43440
 
42522
- def _has_cjk(w):
42523
- """True when a token contains any CJK / non-Latin-script char (ord >= U+3000)."""
42524
- return any(ord(ch) >= _CJK_MIN for ch in w)
43441
+ def _in_ranges(cp, ranges):
43442
+ return any(lo <= cp <= hi for lo, hi in ranges)
42525
43443
 
42526
43444
 
42527
43445
  def _topic_token_kept(w):
42528
- if _has_cjk(w):
42529
- return len(w) >= 2
42530
- return len(w) > 3
43446
+ cps = [ord(ch) for ch in w if not _in_ranges(ord(ch), _TOPIC_MARK_RANGES)]
43447
+ if any(cp >= _TOPIC_WIDE_MIN for cp in cps):
43448
+ return len(cps) >= 2
43449
+ if any(not _in_ranges(cp, _TOPIC_LATIN_RANGES) for cp in cps):
43450
+ return len(cps) >= 3
43451
+ return len(cps) > 3
42531
43452
 
42532
43453
 
42533
43454
  def _topic_tokens(text, stopwords=frozenset()):
@@ -43642,9 +44563,7 @@ def _transcript_last_turn(sid_safe):
43642
44563
  u = msg.get("usage") or {}
43643
44564
  if not isinstance(u, dict):
43644
44565
  continue
43645
- ctx = (_safe_int(u.get("input_tokens"))
43646
- + _safe_int(u.get("cache_read_input_tokens"))
43647
- + _safe_int(u.get("cache_creation_input_tokens")))
44566
+ ctx = _context_token_count(_context_usage(u))
43648
44567
  if ctx <= 0:
43649
44568
  continue
43650
44569
  model = _normalize_model_name(msg.get("model"))
@@ -43803,7 +44722,65 @@ def checkpoint_trigger(milestone=None, session_id=None, transcript_path=None, qu
43803
44722
  return cp_path
43804
44723
 
43805
44724
 
43806
- def generate_compact_instructions(as_json=False, install=False, dry_run=False):
44725
+ _COMPACT_INSTR_HEAD = "When summarizing this session, pay special attention to:"
44726
+ _COMPACT_INSTR_TAIL = (
44727
+ "Always include the specific next step with enough detail to continue without asking."
44728
+ )
44729
+ _COMPACT_INSTR_BULLETS = frozenset({
44730
+ "- Architectural decisions and their reasoning",
44731
+ "- Skill invocations and their outcomes",
44732
+ "- External service interactions and their results",
44733
+ "- Modified file paths with line ranges",
44734
+ "- Error-fix sequences (what was tried, what failed, what worked)",
44735
+ "- Open questions and unresolved TODOs",
44736
+ "- Agent/team state (task assignments, completion status)",
44737
+ })
44738
+ # Separator used when our instructions are appended to the user's own text.
44739
+ _COMPACT_INSTR_MARKER = "\n\n# Token Optimizer additions:\n"
44740
+
44741
+
44742
+ def _compact_instructions_generated(text):
44743
+ """True when ``text`` is exactly a block generate_compact_instructions writes."""
44744
+ if not isinstance(text, str):
44745
+ return False
44746
+ lines = text.strip().split("\n")
44747
+ if len(lines) < 2 or lines[0] != _COMPACT_INSTR_HEAD or lines[-1] != _COMPACT_INSTR_TAIL:
44748
+ return False
44749
+ return all(line in _COMPACT_INSTR_BULLETS for line in lines[1:-1])
44750
+
44751
+
44752
+ def _split_compact_instructions(text):
44753
+ """Split a ``compactInstructions`` value into (user_part, ours_present).
44754
+
44755
+ Ours is either the whole value (a block we generated) or a section we
44756
+ appended after the user's own text behind ``_COMPACT_INSTR_MARKER``.
44757
+ Anything else is the user's and is returned untouched.
44758
+ """
44759
+ if not isinstance(text, str):
44760
+ return text, False
44761
+ if _COMPACT_INSTR_MARKER in text:
44762
+ return text.split(_COMPACT_INSTR_MARKER, 1)[0].rstrip(), True
44763
+ if _compact_instructions_generated(text):
44764
+ return "", True
44765
+ return text, False
44766
+
44767
+
44768
+ def _remove_our_compact_instructions(settings):
44769
+ """Drop our compactInstructions (keeping any user-written part). True if changed."""
44770
+ if not isinstance(settings, dict) or "compactInstructions" not in settings:
44771
+ return False
44772
+ user_part, ours = _split_compact_instructions(settings.get("compactInstructions"))
44773
+ if not ours:
44774
+ return False
44775
+ if user_part:
44776
+ settings["compactInstructions"] = user_part
44777
+ else:
44778
+ del settings["compactInstructions"]
44779
+ return True
44780
+
44781
+
44782
+ def generate_compact_instructions(as_json=False, install=False, dry_run=False,
44783
+ user_initiated=False):
43807
44784
  """Generate project-specific Compact Instructions.
43808
44785
 
43809
44786
  Analyzes CLAUDE.md, recent session patterns, and common loss patterns
@@ -43814,7 +44791,7 @@ def generate_compact_instructions(as_json=False, install=False, dry_run=False):
43814
44791
  """
43815
44792
  components = measure_components()
43816
44793
  instructions_parts = [
43817
- "When summarizing this session, pay special attention to:",
44794
+ _COMPACT_INSTR_HEAD,
43818
44795
  ]
43819
44796
 
43820
44797
  # Analyze CLAUDE.md content for project priorities
@@ -43837,7 +44814,7 @@ def generate_compact_instructions(as_json=False, install=False, dry_run=False):
43837
44814
  "- Modified file paths with line ranges",
43838
44815
  "- Error-fix sequences (what was tried, what failed, what worked)",
43839
44816
  "- Open questions and unresolved TODOs",
43840
- "Always include the specific next step with enough detail to continue without asking.",
44817
+ _COMPACT_INSTR_TAIL,
43841
44818
  ])
43842
44819
 
43843
44820
  # Check for agent usage in recent sessions
@@ -43869,14 +44846,20 @@ def generate_compact_instructions(as_json=False, install=False, dry_run=False):
43869
44846
  )
43870
44847
  return instructions_text
43871
44848
  existing = settings.get("compactInstructions", "")
44849
+ user_part, ours_present = _split_compact_instructions(existing)
43872
44850
 
43873
- if existing and "Token Optimizer" in existing:
44851
+ if existing and ours_present:
44852
+ # Refresh only our part. A value that also holds the user's own
44853
+ # text keeps it: replacing the whole value used to erase it.
43874
44854
  if dry_run:
43875
44855
  print(f"\n [Dry run] Would update existing compact instructions in {settings_path}")
43876
44856
  print(f"\n Compact instructions preview:\n {instructions_text}\n")
43877
44857
  return instructions_text
43878
- settings["compactInstructions"] = instructions_text
43879
- if not _write_settings_atomic(settings):
44858
+ settings["compactInstructions"] = (
44859
+ user_part + _COMPACT_INSTR_MARKER + instructions_text
44860
+ if user_part else instructions_text
44861
+ )
44862
+ if not _write_settings_atomic(settings, user_initiated=user_initiated):
43880
44863
  print("[Error] settings.json write was refused; compact instructions were not updated.", file=sys.stderr)
43881
44864
  return instructions_text
43882
44865
  print(f"[Token Optimizer] Compact Instructions updated in {settings_path}")
@@ -43884,7 +44867,7 @@ def generate_compact_instructions(as_json=False, install=False, dry_run=False):
43884
44867
 
43885
44868
  if existing:
43886
44869
  # User has their own instructions, append ours
43887
- combined = existing.rstrip() + "\n\n# Token Optimizer additions:\n" + instructions_text
44870
+ combined = existing.rstrip() + _COMPACT_INSTR_MARKER + instructions_text
43888
44871
  if dry_run:
43889
44872
  print(f"\n [Dry run] Would append to existing compact instructions in {settings_path}")
43890
44873
  print(f"\n Appended:\n {instructions_text}\n")
@@ -43897,7 +44880,7 @@ def generate_compact_instructions(as_json=False, install=False, dry_run=False):
43897
44880
  return instructions_text
43898
44881
  settings["compactInstructions"] = instructions_text
43899
44882
 
43900
- if not _write_settings_atomic(settings):
44883
+ if not _write_settings_atomic(settings, user_initiated=user_initiated):
43901
44884
  print("[Error] settings.json write was refused; compact instructions were not installed.", file=sys.stderr)
43902
44885
  return instructions_text
43903
44886
  print(f"[Token Optimizer] Compact Instructions installed to {settings_path}")
@@ -44596,16 +45579,30 @@ def _smart_compact_hook_commands():
44596
45579
  resolved to), the hook exits 0 silently instead of erroring on every event.
44597
45580
  Mirrors the launcher guard in hooks.json.
44598
45581
  """
44599
- mp = _get_measure_py_path()
44600
- guard = f"[ -r '{mp}' ] || exit 0; "
45582
+ py, mp = _settings_hook_python_and_script(_get_measure_py_path())
45583
+ guard = f"[ -r {mp} ] || exit 0; "
44601
45584
  return {
44602
- "PreCompact": f"{guard}python3 '{mp}' compact-capture --trigger auto",
44603
- "SessionStart": f"{guard}python3 '{mp}' compact-restore",
44604
- "Stop": f"{guard}python3 '{mp}' compact-capture --trigger stop",
44605
- "SessionEnd": f"{guard}python3 '{mp}' compact-capture --trigger end",
45585
+ "PreCompact": f"{guard}{py} {mp} compact-capture --trigger auto",
45586
+ "SessionStart": f"{guard}{py} {mp} compact-restore",
45587
+ "Stop": f"{guard}{py} {mp} compact-capture --trigger stop",
45588
+ "SessionEnd": f"{guard}{py} {mp} compact-capture --trigger end",
44606
45589
  }
44607
45590
 
44608
45591
 
45592
+ def _settings_hook_python_and_script(mp):
45593
+ """(interpreter, script) shell tokens for a settings.json hook command.
45594
+
45595
+ Claude Code runs these through Git Bash on Windows, where bare ``python3``
45596
+ is often missing or the Microsoft Store stub (exit 9009 on every event),
45597
+ so Windows names the running interpreter with forward slashes, quoted for
45598
+ bash (an apostrophe in the path is safe). POSIX keeps ``python3 '<mp>'``.
45599
+ """
45600
+ if sys.platform == "win32":
45601
+ return (shlex.quote(str(sys.executable).replace("\\", "/")),
45602
+ shlex.quote(str(mp).replace("\\", "/")))
45603
+ return "python3", f"'{mp}'"
45604
+
45605
+
44609
45606
  def _is_smart_compact_installed(settings=None):
44610
45607
  """Check which smart compact hooks are installed.
44611
45608
 
@@ -44658,7 +45655,8 @@ def _is_smart_compact_installed(settings=None):
44658
45655
  return status
44659
45656
 
44660
45657
 
44661
- def setup_smart_compact(dry_run=False, uninstall=False, status_only=False):
45658
+ def setup_smart_compact(dry_run=False, uninstall=False, status_only=False,
45659
+ user_initiated=False):
44662
45660
  """Install, uninstall, or check status of smart compaction hooks.
44663
45661
 
44664
45662
  Appends to existing hooks (never overwrites). Safe to run multiple times.
@@ -44723,10 +45721,16 @@ def setup_smart_compact(dry_run=False, uninstall=False, status_only=False):
44723
45721
  return
44724
45722
 
44725
45723
  settings["hooks"] = hooks
44726
- if not _write_settings_atomic(settings):
45724
+ # setup-smart-compact also installed compactInstructions; take ours
45725
+ # back out (a user-written part stays).
45726
+ ci_removed = _remove_our_compact_instructions(settings)
45727
+ if not _write_settings_atomic(settings, allow_removing_keys={"compactInstructions"},
45728
+ user_initiated=user_initiated):
44727
45729
  print("[Error] settings.json write was refused; smart compact hooks were not removed.", file=sys.stderr)
44728
45730
  return
44729
45731
  print(f"[Token Optimizer] Removed smart compact hooks. {removed} hook(s) removed.")
45732
+ if ci_removed:
45733
+ print("[Token Optimizer] Removed Token Optimizer compact instructions.")
44730
45734
  return
44731
45735
 
44732
45736
  # Install
@@ -44817,7 +45821,7 @@ def setup_smart_compact(dry_run=False, uninstall=False, status_only=False):
44817
45821
  return
44818
45822
 
44819
45823
  settings["hooks"] = hooks
44820
- if not _write_settings_atomic(settings):
45824
+ if not _write_settings_atomic(settings, user_initiated=user_initiated):
44821
45825
  print("[Error] settings.json write was refused; smart compact hooks were not installed.", file=sys.stderr)
44822
45826
  return
44823
45827
 
@@ -44828,7 +45832,7 @@ def setup_smart_compact(dry_run=False, uninstall=False, status_only=False):
44828
45832
 
44829
45833
  # Also install compact instructions (tells Claude WHAT to preserve)
44830
45834
  print()
44831
- generate_compact_instructions(install=True)
45835
+ generate_compact_instructions(install=True, user_initiated=user_initiated)
44832
45836
 
44833
45837
  print("\n What happens now:")
44834
45838
  print(" Compact Instructions: Guides Claude on what to preserve during compaction")
@@ -45662,6 +46666,9 @@ def _verbosity_nudge_min_fill() -> int:
45662
46666
 
45663
46667
  _VERBOSITY_NUDGE_MIN_FILL = _verbosity_nudge_min_fill()
45664
46668
  _VERBOSITY_NUDGE_EFFICIENCY_THRESHOLD = 75
46669
+ # Lean-output nudge pacing: at most this many per session, this far apart.
46670
+ _VERBOSITY_MAX_NUDGES = 3
46671
+ _VERBOSITY_COOLDOWN_SEC = 300
45665
46672
  _NUDGE_SESSION_CAP = 3
45666
46673
  # Fresh-session nudge: when a session is BOTH long (high fill) and degraded
45667
46674
  # (quality < threshold), suggest starting a fresh session -- cold-resume-lean
@@ -46419,7 +47426,9 @@ def quality_cache(throttle_seconds=120, warn_threshold=70, quiet=False, session_
46419
47426
  result["session_start_ts"] = _extract_session_start_ts(filepath)
46420
47427
  result["active_agents"] = _extract_active_agents(filepath)
46421
47428
 
46422
- # Cache hit rate for statusline (v5.4.27)
47429
+ # Cache hit rate for statusline (v5.4.27). A billing ratio, so it reads
47430
+ # the top-level (advisor-summed) usage on purpose, unlike context fill,
47431
+ # which uses _context_usage (#287).
46423
47432
  try:
46424
47433
  total_input_all = 0
46425
47434
  total_cache_read = 0
@@ -47627,6 +48636,28 @@ def _resolve_feature_env(env_var):
47627
48636
  return _settings_env_value(env_var)
47628
48637
 
47629
48638
 
48639
+ def _model_routing_handled_elsewhere():
48640
+ """True when subagent models are already routed outside settings.json.
48641
+
48642
+ A model-routing plugin sets the model per Agent call, so a pinned main
48643
+ model is a choice, not a leak, and "remove the model key" saves nothing
48644
+ (issue #275). Matches any enabled plugin with "router" in its name, plus
48645
+ an explicit opt-out for routing done some other way.
48646
+ """
48647
+ if os.environ.get("TOKEN_OPTIMIZER_SKIP_MODEL_PIN_HINT", "").strip().lower() in ("1", "true", "yes"):
48648
+ return True
48649
+ try:
48650
+ plugins = _resolve_settings_value("enabledPlugins", {}) or {}
48651
+ except Exception:
48652
+ return False
48653
+ if not isinstance(plugins, dict):
48654
+ return False
48655
+ return any(
48656
+ enabled and "router" in str(name).split("@", 1)[0].lower()
48657
+ for name, enabled in plugins.items()
48658
+ )
48659
+
48660
+
47630
48661
  def _resolve_settings_value(key, default=None):
47631
48662
  """Return a top-level settings.json key (e.g. includeGitInstructions, model)
47632
48663
  resolving project local/shared over global local/shared, first match wins.
@@ -47886,7 +48917,8 @@ def _get_v5_savings_recommendation():
47886
48917
  }
47887
48918
 
47888
48919
 
47889
- def setup_quality_bar(dry_run=False, uninstall=False, status_only=False, force=False, quiet=False):
48920
+ def setup_quality_bar(dry_run=False, uninstall=False, status_only=False, force=False, quiet=False,
48921
+ user_initiated=False):
47890
48922
  """Install, uninstall, or check quality bar (status line + cache hook).
47891
48923
 
47892
48924
  Installs:
@@ -47905,6 +48937,12 @@ def setup_quality_bar(dry_run=False, uninstall=False, status_only=False, force=F
47905
48937
  every turn. The advisory is only shown on an explicit,
47906
48938
  interactive `setup-quality-bar` run.
47907
48939
 
48940
+ user_initiated=True is passed only by the `setup-quality-bar` CLI command
48941
+ (the same for setup-hook / setup-smart-compact / compact-instructions):
48942
+ an explicit command takes the settings lease past the hook-herd
48943
+ reservation, so commands typed back to back are not refused. The
48944
+ automatic heal callers keep the default and the non-blocking lease.
48945
+
47908
48946
  Side-effects on config.json:
47909
48947
  install -> clears "quality_bar_disabled" (explicit opt-in)
47910
48948
  --uninstall -> sets "quality_bar_disabled" (sticky opt-out)
@@ -48005,7 +49043,8 @@ def setup_quality_bar(dry_run=False, uninstall=False, status_only=False, force=F
48005
49043
  settings["hooks"] = hooks
48006
49044
  # Deliberate top-level removal: declare it so the choke-point guard
48007
49045
  # allows this one and only this one.
48008
- if not _write_settings_atomic(settings, allow_removing_keys={"statusLine"}):
49046
+ if not _write_settings_atomic(settings, allow_removing_keys={"statusLine"},
49047
+ user_initiated=user_initiated):
48009
49048
  print("[Error] settings.json write was refused; Quality Bar was not removed.", file=sys.stderr)
48010
49049
  return
48011
49050
  _set_quality_bar_disabled(True)
@@ -48031,7 +49070,8 @@ def setup_quality_bar(dry_run=False, uninstall=False, status_only=False, force=F
48031
49070
  skipped.append("cache hook")
48032
49071
  else:
48033
49072
  hooks = settings.setdefault("hooks", {})
48034
- hook_cmd = f"python3 '{mp}' quality-cache --quiet"
49073
+ _py, _mp = _settings_hook_python_and_script(mp)
49074
+ hook_cmd = f"{_py} {_mp} quality-cache --quiet"
48035
49075
  hook_entry = {"type": "command", "command": hook_cmd}
48036
49076
  hook_group = {"hooks": [hook_entry]}
48037
49077
  hooks.setdefault("UserPromptSubmit", []).append(hook_group)
@@ -48049,13 +49089,16 @@ def setup_quality_bar(dry_run=False, uninstall=False, status_only=False, force=F
48049
49089
  # is a clobber rather than an intentional choice).
48050
49090
  try:
48051
49091
  _rt_seg = RUNTIME_DIR.relative_to(HOME).as_posix()
49092
+ _rt_base = f"os.homedir(), '{_rt_seg}'"
48052
49093
  except ValueError:
48053
- _rt_seg = ".claude"
49094
+ # Runtime dir outside HOME (e.g. CLAUDE_CONFIG_DIR on a
49095
+ # relocated volume): print its absolute path, never ~/.claude.
49096
+ _rt_base = json.dumps(RUNTIME_DIR.as_posix())
48054
49097
  warnings.append(
48055
49098
  "You already have a custom status line configured.\n"
48056
49099
  " To integrate quality scoring, add this to your status line script:\n\n"
48057
49100
  " // Read context quality score\n"
48058
- f" const qFile = path.join(os.homedir(), '{_rt_seg}', 'token-optimizer', 'quality-cache.json');\n"
49101
+ f" const qFile = path.join({_rt_base}, 'token-optimizer', 'quality-cache.json');\n"
48059
49102
  " let qScore = '';\n"
48060
49103
  " if (fs.existsSync(qFile)) {\n"
48061
49104
  " try {\n"
@@ -48072,7 +49115,10 @@ def setup_quality_bar(dry_run=False, uninstall=False, status_only=False, force=F
48072
49115
  else:
48073
49116
  settings["statusLine"] = {
48074
49117
  "type": "command",
48075
- "command": f"node '{sl_path}'"
49118
+ # A plain '...' wrap broke on an apostrophe in the path
49119
+ # (C:\Users\O'Brien). Keep the familiar form otherwise.
49120
+ "command": (f"node '{sl_path}'" if "'" not in str(sl_path)
49121
+ else f"node {shlex.quote(str(sl_path))}"),
48076
49122
  }
48077
49123
  installed.append("status line")
48078
49124
 
@@ -48100,7 +49146,7 @@ def setup_quality_bar(dry_run=False, uninstall=False, status_only=False, force=F
48100
49146
  return
48101
49147
 
48102
49148
  if installed:
48103
- if not _write_settings_atomic(settings):
49149
+ if not _write_settings_atomic(settings, user_initiated=user_initiated):
48104
49150
  if not quiet:
48105
49151
  print("[Error] settings.json write was refused; Quality Bar was not installed.", file=sys.stderr)
48106
49152
  return
@@ -53800,7 +54846,11 @@ def _advice_session_data(path):
53800
54846
  turns per-request context size (input + cache_read + cache_creation)
53801
54847
  of each main-thread assistant usage row, in order; streamed
53802
54848
  chunks sharing a requestId collapse to the largest row.
53803
- cache_reads cache_read_input_tokens per turn (same indexing).
54849
+ cache_reads cache_read_input_tokens per turn (same indexing). This is
54850
+ the billed aggregate, while `turns` is executor occupancy
54851
+ (#287). On advisor sessions avoided reads (derived from
54852
+ `turns`) are measured against the larger billed total, so
54853
+ avoided_share_pct can only understate the saving.
53804
54854
  boundaries indexes in `turns` that directly follow a compact_boundary.
53805
54855
  model newest model id on a main-thread row, or None.
53806
54856
  post_compact_ctx context size of the first request after each recorded
@@ -53855,9 +54905,10 @@ def _advice_session_data(path):
53855
54905
  u = msg.get("usage")
53856
54906
  if not isinstance(u, dict):
53857
54907
  continue
54908
+ # Cache-read traffic is billed aggregate usage; occupancy is
54909
+ # only the final executor iteration of an advisor response.
53858
54910
  cr = _safe_int(u.get("cache_read_input_tokens"))
53859
- ctx = (_safe_int(u.get("input_tokens")) + cr
53860
- + _safe_int(u.get("cache_creation_input_tokens")))
54911
+ ctx = _context_token_count(_context_usage(u))
53861
54912
  if ctx <= 0:
53862
54913
  continue
53863
54914
  m = msg.get("model")
@@ -56997,11 +58048,9 @@ def run_verbosity_steer(transcript_path=None, quiet=True, session_id=None):
56997
58048
  _now = _vs_time.time()
56998
58049
  _nudge_count = cached.get("nudge_count", 0) or 0
56999
58050
  _last_nudge = cached.get("last_nudge_time", 0) or 0
57000
- _COOLDOWN_SEC = 300
57001
- _MAX_NUDGES = 3
57002
- if _nudge_count >= _MAX_NUDGES:
58051
+ if _nudge_count >= _VERBOSITY_MAX_NUDGES:
57003
58052
  return ""
57004
- if _now - _last_nudge < _COOLDOWN_SEC:
58053
+ if _now - _last_nudge < _VERBOSITY_COOLDOWN_SEC:
57005
58054
  return ""
57006
58055
 
57007
58056
  # At 90%+ fill, don't add more tokens
@@ -57013,44 +58062,8 @@ def run_verbosity_steer(transcript_path=None, quiet=True, session_id=None):
57013
58062
  )
57014
58063
  return ""
57015
58064
 
57016
- # Determine nudge tier.
57017
- #
57018
- # The spartan/ADHD phrasing is used verbatim because it produced the
57019
- # largest reduction in verbose output across multiple models while
57020
- # maintaining answer quality. Notes on what the data showed:
57021
- # - Word ceilings were REMOVED. An earlier draft capped answers at
57022
- # 80/120 words. A cap makes a model either truncate a genuinely
57023
- # complex answer or ignore the nudge, and a nudge that gets ignored
57024
- # is the original failure this rewrite exists to fix.
57025
- # - The real waste is elaboration, not preamble. The padding-focused
57026
- # wording targeted preamble and restatement and cut half as much,
57027
- # because verbose answers mostly repeat themselves rather than
57028
- # restate the question.
57029
- # - Quality held. On the hardest fixture (prompt-caching explainer,
57030
- # 1159 -> 759 words) the spartan answer kept every concept and
57031
- # covered TTL MORE; what it dropped was the same point made six
57032
- # times instead of three.
57033
- # - Reasoning and deliverables are fenced off explicitly, because the
57034
- # nudge fires mid-task where "spartan" could otherwise be read as
57035
- # "write less code".
57036
- # - Opus is roughly half as responsive as Sonnet here. Do not quote
57037
- # the Sonnet figure as the product number.
57038
- if fill_pct >= 75:
57039
- nudge = (
57040
- f"[Token Optimizer] Context {_format_context_fill(fill_pct, cached)}, resource health {score:.0f}/100. "
57041
- "Answer in a focused and spartan way, as if the user has ADHD. Cut everything "
57042
- "that is not the answer itself. Think as long as you need, and size code, "
57043
- "diffs and file contents to the task."
57044
- )
57045
- elif (fill_pct >= _VERBOSITY_NUDGE_MIN_FILL
57046
- and session_efficiency < _VERBOSITY_NUDGE_EFFICIENCY_THRESHOLD):
57047
- nudge = (
57048
- f"[Token Optimizer] Context {_format_context_fill(fill_pct, cached)}, "
57049
- f"session efficiency {session_efficiency:.0f}/100. "
57050
- "Answer in a focused and spartan way, as if the user has ADHD. "
57051
- "Think as long as you need, and size code, diffs and file contents to the task."
57052
- )
57053
- else:
58065
+ nudge = _verbosity_nudge_text(fill_pct, score, session_efficiency, cached)
58066
+ if not nudge:
57054
58067
  return ""
57055
58068
 
57056
58069
  payload = json.dumps({
@@ -57127,6 +58140,62 @@ def run_verbosity_steer(transcript_path=None, quiet=True, session_id=None):
57127
58140
  return ""
57128
58141
 
57129
58142
 
58143
+ def _verbosity_nudge_text(fill_pct, score, session_efficiency, cached):
58144
+ """The lean-output nudge for a fill level, or "" when none applies.
58145
+
58146
+ Shared by Claude Code / Codex (run_verbosity_steer) and Hermes
58147
+ (hermes-turn-context), so every runtime gets the same tiers and wording.
58148
+ ``cached`` is the quality-cache dict (or a small stand-in with
58149
+ ``model_context_window``) that ``_format_context_fill`` reads.
58150
+
58151
+ Tiers:
58152
+ 90%+ fill -> "" (adding tokens makes it worse)
58153
+ 75-89% fill -> strong nudge
58154
+ _VERBOSITY_NUDGE_MIN_FILL-74% and session efficiency below
58155
+ _VERBOSITY_NUDGE_EFFICIENCY_THRESHOLD -> gentle nudge
58156
+ """
58157
+ if fill_pct >= 90:
58158
+ return ""
58159
+ # Determine nudge tier.
58160
+ #
58161
+ # The spartan/ADHD phrasing is used verbatim because it produced the
58162
+ # largest reduction in verbose output across multiple models while
58163
+ # maintaining answer quality. Notes on what the data showed:
58164
+ # - Word ceilings were REMOVED. An earlier draft capped answers at
58165
+ # 80/120 words. A cap makes a model either truncate a genuinely
58166
+ # complex answer or ignore the nudge, and a nudge that gets ignored
58167
+ # is the original failure this rewrite exists to fix.
58168
+ # - The real waste is elaboration, not preamble. The padding-focused
58169
+ # wording targeted preamble and restatement and cut half as much,
58170
+ # because verbose answers mostly repeat themselves rather than
58171
+ # restate the question.
58172
+ # - Quality held. On the hardest fixture (prompt-caching explainer,
58173
+ # 1159 -> 759 words) the spartan answer kept every concept and
58174
+ # covered TTL MORE; what it dropped was the same point made six
58175
+ # times instead of three.
58176
+ # - Reasoning and deliverables are fenced off explicitly, because the
58177
+ # nudge fires mid-task where "spartan" could otherwise be read as
58178
+ # "write less code".
58179
+ # - Opus is roughly half as responsive as Sonnet here. Do not quote
58180
+ # the Sonnet figure as the product number.
58181
+ if fill_pct >= 75:
58182
+ return (
58183
+ f"[Token Optimizer] Context {_format_context_fill(fill_pct, cached)}, resource health {score:.0f}/100. "
58184
+ "Answer in a focused and spartan way, as if the user has ADHD. Cut everything "
58185
+ "that is not the answer itself. Think as long as you need, and size code, "
58186
+ "diffs and file contents to the task."
58187
+ )
58188
+ if (fill_pct >= _VERBOSITY_NUDGE_MIN_FILL
58189
+ and session_efficiency < _VERBOSITY_NUDGE_EFFICIENCY_THRESHOLD):
58190
+ return (
58191
+ f"[Token Optimizer] Context {_format_context_fill(fill_pct, cached)}, "
58192
+ f"session efficiency {session_efficiency:.0f}/100. "
58193
+ "Answer in a focused and spartan way, as if the user has ADHD. "
58194
+ "Think as long as you need, and size code, diffs and file contents to the task."
58195
+ )
58196
+ return ""
58197
+
58198
+
57130
58199
  if __name__ == "__main__":
57131
58200
  # On a non-UTF-8 host locale, re-exec under Python UTF-8 mode FIRST so every
57132
58201
  # subprocess(text=True) decode (ps/git session detection), default open(), and
@@ -57153,6 +58222,19 @@ if __name__ == "__main__":
57153
58222
  i += 1
57154
58223
  args = _filtered_args
57155
58224
 
58225
+ # Windows Codex: hooks saved by older versions start with a quote, which
58226
+ # cmd.exe mangles, so they fail before reaching this script and cannot
58227
+ # fix themselves (issue #276). Any Token Optimizer run on that machine
58228
+ # repairs them in place. One small JSON read; never raises.
58229
+ if sys.platform == "win32" and detect_runtime() == "codex":
58230
+ try:
58231
+ import codex_install as _ci
58232
+ _healed = _ci.heal_quoted_launcher_commands()
58233
+ if _healed:
58234
+ print(f"[Token Optimizer] Repaired {_healed} Codex hook command(s) that Windows could not run. Restart Codex to load them.", file=sys.stderr)
58235
+ except Exception:
58236
+ pass
58237
+
57156
58238
  # --- Foreign-runtime guardrail (cross-platform universality) -
57157
58239
  # OpenCode loads ~/.claude/skills by default, Copilot and Hermes can be
57158
58240
  # invoked from their own sessions, so any of them can reach this skill even
@@ -57314,7 +58396,7 @@ if __name__ == "__main__":
57314
58396
  sys.exit(0)
57315
58397
  elif args[0] == "copilot-rollup":
57316
58398
  # Ingest recent Copilot sessions (CLI + VS Code planes) into trends.db.
57317
- # Fired by the stop hook via copilot_hook_bridge.handle_stop(); extra
58399
+ # Fired by the sessionEnd hook via copilot_hook_bridge.handle_session_end(); extra
57318
58400
  # flags are silently consumed (INSERT OR IGNORE keeps this idempotent).
57319
58401
  # Wall-clock backstop: this dispatch is spawned fire-and-forget by the
57320
58402
  # Stop hook bridge (start_new_session=True, DEVNULL, no PID tracking),
@@ -57444,7 +58526,8 @@ if __name__ == "__main__":
57444
58526
  # plugin's on_session_end hook via hermes_hook_bridge.run_rollup().
57445
58527
  # --session <id> and --platform / --reason are accepted and silently
57446
58528
  # consumed so the bridge's exact call signature never causes an error;
57447
- # a full recent collect is always run (INSERT OR IGNORE is idempotent).
58529
+ # a full recent collect is always run (idempotent: rows are keyed per
58530
+ # session and only refreshed when state.db has moved further along).
57448
58531
  # Wall-clock backstop: same rationale as copilot-rollup above -- the
57449
58532
  # Hermes bridge spawns this fire-and-forget with start_new_session=True
57450
58533
  # and no PID tracking, so the parent hook deadline never propagates.
@@ -57452,6 +58535,7 @@ if __name__ == "__main__":
57452
58535
  # session re-collects idempotently), a frozen orphan is not.
57453
58536
  quiet = "--quiet" in args or "-q" in args
57454
58537
  _HERMES_ROLLUP_CONTEXT = _parse_hermes_rollup_context(args[1:])
58538
+ _HERMES_ROLLUP_SKILLS = _parse_hermes_rollup_skills(args[1:])
57455
58539
  _tok_hook_deadline = _install_hook_budget(60)
57456
58540
  try:
57457
58541
  _collect_hermes_sessions(days=90, quiet=quiet)
@@ -57462,6 +58546,36 @@ if __name__ == "__main__":
57462
58546
  finally:
57463
58547
  _clear_hook_budget(_tok_hook_deadline)
57464
58548
  sys.exit(0)
58549
+ elif args[0] == "hermes-checkpoint":
58550
+ # Session checkpoint for a Hermes session, built from Hermes's own
58551
+ # state.db messages (read-only). Spawned detached by the Hermes plugin
58552
+ # at fill bands, before compaction, before subagent fan-out, after edit
58553
+ # batches, at turn end and at session end. Same 60s backstop as
58554
+ # hermes-rollup: a skipped checkpoint is invisible, a frozen orphan is not.
58555
+ _tok_hook_deadline = _install_hook_budget(60)
58556
+ try:
58557
+ _hermes_checkpoint_cli(args[1:])
58558
+ except _HookTimeout:
58559
+ pass
58560
+ except Exception:
58561
+ pass
58562
+ finally:
58563
+ _clear_hook_budget(_tok_hook_deadline)
58564
+ sys.exit(0)
58565
+ elif args[0] == "hermes-turn-context":
58566
+ # One child process per Hermes turn for continuity + lean-output (see
58567
+ # hermes_turn_context). Reads a JSON payload on stdin, prints one JSON
58568
+ # object. Same 8s budget as the Claude Code prompt hooks.
58569
+ _tok_hook_deadline = _install_hook_budget(8)
58570
+ try:
58571
+ print(json.dumps(hermes_turn_context(_read_stdin_hook_input())))
58572
+ except _HookTimeout:
58573
+ pass
58574
+ except Exception:
58575
+ pass
58576
+ finally:
58577
+ _clear_hook_budget(_tok_hook_deadline)
58578
+ sys.exit(0)
57465
58579
  elif args[0] == "hermes-summary":
57466
58580
  # Print a brief usage summary for the most recent Hermes sessions.
57467
58581
  # Called by hermes_hook_bridge.run_summary() on /token-optimizer command.
@@ -57857,7 +58971,7 @@ if __name__ == "__main__":
57857
58971
  elif args[0] == "setup-hook":
57858
58972
  dry = "--dry-run" in args
57859
58973
  uninstall = "--uninstall" in args
57860
- setup_hook(dry_run=dry, uninstall=uninstall)
58974
+ setup_hook(dry_run=dry, uninstall=uninstall, user_initiated=True)
57861
58975
  elif args[0] == "setup-all-hooks":
57862
58976
  dry = "--dry-run" in args
57863
58977
  verbose = "--verbose" in args or "-v" in args
@@ -58601,7 +59715,8 @@ if __name__ == "__main__":
58601
59715
  output_json = "--json" in args
58602
59716
  install = "--install" in args
58603
59717
  dry = "--dry-run" in args
58604
- generate_compact_instructions(as_json=output_json, install=install, dry_run=dry)
59718
+ generate_compact_instructions(as_json=output_json, install=install, dry_run=dry,
59719
+ user_initiated=True)
58605
59720
  elif args[0] == "dynamic-compact-instructions":
58606
59721
  hook_input = _read_stdin_hook_input()
58607
59722
  sid = hook_input.get("session_id") or os.environ.get("CLAUDE_SESSION_ID", "")
@@ -58610,7 +59725,8 @@ if __name__ == "__main__":
58610
59725
  dry = "--dry-run" in args
58611
59726
  uninstall = "--uninstall" in args
58612
59727
  status = "--status" in args
58613
- setup_smart_compact(dry_run=dry, uninstall=uninstall, status_only=status)
59728
+ setup_smart_compact(dry_run=dry, uninstall=uninstall, status_only=status,
59729
+ user_initiated=True)
58614
59730
  elif args[0] == "daemon-revive":
58615
59731
  # Detached child spawned by _daemon_midsession_pulse. Revives a dead
58616
59732
  # dashboard daemon OFF the hot path: force=True bypasses the 24h
@@ -59182,7 +60298,8 @@ if __name__ == "__main__":
59182
60298
  dry = "--dry-run" in args
59183
60299
  uninstall = "--uninstall" in args
59184
60300
  status = "--status" in args
59185
- setup_quality_bar(dry_run=dry, uninstall=uninstall, status_only=status)
60301
+ setup_quality_bar(dry_run=dry, uninstall=uninstall, status_only=status,
60302
+ user_initiated=True)
59186
60303
  elif args[0] == "setup-vscode-extension":
59187
60304
  # Manage the VS Code status-bar extension auto-install.
59188
60305
  # --uninstall : sticky opt-out (+ remove the extension if a CLI is present)