@alexgreensh/token-optimizer 5.13.69 → 5.13.71

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 (148) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/PRIVACY.md +4 -0
  4. package/hooks/hooks.json +11 -1
  5. package/hooks/module_runner.py +4 -1
  6. package/hooks/posttooluse_runner.py +44 -48
  7. package/hooks/sessionstart_runner.py +24 -5
  8. package/hooks/stop_runner.py +6 -6
  9. package/package.json +1 -1
  10. package/skills/token-optimizer/assets/dashboard.html +729 -767
  11. package/skills/token-optimizer/assets/savings_story.js +765 -0
  12. package/skills/token-optimizer/pricing/prices.json +1 -0
  13. package/skills/token-optimizer/references/cli-reference.md +1 -1
  14. package/skills/token-optimizer/references/implementation-playbook.md +3 -0
  15. package/skills/token-optimizer/scripts/_measure/__init__.py +3 -1
  16. package/skills/token-optimizer/scripts/_measure/archive_health.py +14 -0
  17. package/skills/token-optimizer/scripts/_measure/archive_void_codex.py +163 -0
  18. package/skills/token-optimizer/scripts/_measure/archive_void_evidence.py +165 -0
  19. package/skills/token-optimizer/scripts/_measure/audit.py +27 -135
  20. package/skills/token-optimizer/scripts/_measure/baseline_provenance.py +339 -0
  21. package/skills/token-optimizer/scripts/_measure/cache_policy.py +261 -581
  22. package/skills/token-optimizer/scripts/_measure/checkpoint_direction.py +97 -0
  23. package/skills/token-optimizer/scripts/_measure/checkpoint_retention.py +20 -0
  24. package/skills/token-optimizer/scripts/_measure/cli.py +12 -8
  25. package/skills/token-optimizer/scripts/_measure/codex_quality.py +246 -0
  26. package/skills/token-optimizer/scripts/_measure/compaction_survival.py +158 -0
  27. package/skills/token-optimizer/scripts/_measure/compression_fixture_void.py +147 -0
  28. package/skills/token-optimizer/scripts/_measure/compression_scan_checkpoint.py +72 -0
  29. package/skills/token-optimizer/scripts/_measure/context_reset_marker.py +66 -0
  30. package/skills/token-optimizer/scripts/_measure/continuity.py +64 -118
  31. package/skills/token-optimizer/scripts/_measure/cost_per_message_trend.py +40 -0
  32. package/skills/token-optimizer/scripts/_measure/counted_cap.py +30 -0
  33. package/skills/token-optimizer/scripts/_measure/counted_orphans.py +190 -0
  34. package/skills/token-optimizer/scripts/_measure/counted_position.py +20 -0
  35. package/skills/token-optimizer/scripts/_measure/counted_pricing_v5.py +267 -0
  36. package/skills/token-optimizer/scripts/_measure/counted_subagents.py +371 -0
  37. package/skills/token-optimizer/scripts/_measure/coverage_report.py +295 -0
  38. package/skills/token-optimizer/scripts/_measure/daemon.py +53 -74
  39. package/skills/token-optimizer/scripts/_measure/dashboard.py +90 -151
  40. package/skills/token-optimizer/scripts/_measure/dashboard_heal_claim.py +36 -0
  41. package/skills/token-optimizer/scripts/_measure/evidence_parallel.py +95 -0
  42. package/skills/token-optimizer/scripts/_measure/feature_health.py +256 -0
  43. package/skills/token-optimizer/scripts/_measure/file_refetch.py +250 -0
  44. package/skills/token-optimizer/scripts/_measure/first_call_context.py +216 -0
  45. package/skills/token-optimizer/scripts/_measure/first_read_outcomes.py +261 -0
  46. package/skills/token-optimizer/scripts/_measure/first_read_revive.py +137 -0
  47. package/skills/token-optimizer/scripts/_measure/fixture_context.py +65 -0
  48. package/skills/token-optimizer/scripts/_measure/headline.py +100 -0
  49. package/skills/token-optimizer/scripts/_measure/holdout_fallback.py +96 -0
  50. package/skills/token-optimizer/scripts/_measure/holdout_report.py +129 -0
  51. package/skills/token-optimizer/scripts/_measure/keepwarm_economics.py +201 -0
  52. package/skills/token-optimizer/scripts/_measure/keepwarm_linux.py +121 -0
  53. package/skills/token-optimizer/scripts/_measure/keepwarm_safety.py +260 -0
  54. package/skills/token-optimizer/scripts/_measure/lean_resume_receivers.py +260 -0
  55. package/skills/token-optimizer/scripts/_measure/lean_resume_threshold.py +76 -0
  56. package/skills/token-optimizer/scripts/_measure/lease_candidate_cleanup.py +82 -0
  57. package/skills/token-optimizer/scripts/_measure/lifecycle.py +54 -162
  58. package/skills/token-optimizer/scripts/_measure/mcp_archive_tripwire.py +120 -0
  59. package/skills/token-optimizer/scripts/_measure/mod_action_booking.py +178 -0
  60. package/skills/token-optimizer/scripts/_measure/mod_compaction_booking.py +276 -0
  61. package/skills/token-optimizer/scripts/_measure/mod_fresh_booking.py +105 -0
  62. package/skills/token-optimizer/scripts/_measure/output_reread.py +629 -0
  63. package/skills/token-optimizer/scripts/_measure/own_price_card.py +268 -0
  64. package/skills/token-optimizer/scripts/_measure/periphery_exposure.py +85 -0
  65. package/skills/token-optimizer/scripts/_measure/pricing.py +152 -87
  66. package/skills/token-optimizer/scripts/_measure/quality_archive.py +159 -215
  67. package/skills/token-optimizer/scripts/_measure/quality_checkpoint.py +174 -0
  68. package/skills/token-optimizer/scripts/_measure/quality_continuity.py +43 -0
  69. package/skills/token-optimizer/scripts/_measure/rework_metrics.py +194 -0
  70. package/skills/token-optimizer/scripts/_measure/routing_period.py +48 -0
  71. package/skills/token-optimizer/scripts/_measure/savings.py +439 -864
  72. package/skills/token-optimizer/scripts/_measure/savings_headline.py +130 -0
  73. package/skills/token-optimizer/scripts/_measure/savings_story.py +187 -0
  74. package/skills/token-optimizer/scripts/_measure/session_best.py +24 -0
  75. package/skills/token-optimizer/scripts/_measure/session_effect.py +557 -0
  76. package/skills/token-optimizer/scripts/_measure/session_flush_lock.py +75 -0
  77. package/skills/token-optimizer/scripts/_measure/session_store_spool.py +220 -0
  78. package/skills/token-optimizer/scripts/_measure/sessions.py +103 -196
  79. package/skills/token-optimizer/scripts/_measure/setup_attachment_counter.py +196 -0
  80. package/skills/token-optimizer/scripts/_measure/setup_budget_monitor.py +180 -0
  81. package/skills/token-optimizer/scripts/_measure/setup_connector_ledger.py +126 -0
  82. package/skills/token-optimizer/scripts/_measure/setup_step.py +220 -0
  83. package/skills/token-optimizer/scripts/_measure/status_bar_lock.py +117 -0
  84. package/skills/token-optimizer/scripts/_measure/structural_archives.py +79 -0
  85. package/skills/token-optimizer/scripts/_measure/structural_dedupe.py +91 -0
  86. package/skills/token-optimizer/scripts/_measure/structural_ledger.py +418 -0
  87. package/skills/token-optimizer/scripts/_measure/structural_listing.py +163 -0
  88. package/skills/token-optimizer/scripts/_measure/structural_report.py +339 -0
  89. package/skills/token-optimizer/scripts/_measure/structural_seed.py +164 -0
  90. package/skills/token-optimizer/scripts/_measure/structural_value.py +248 -0
  91. package/skills/token-optimizer/scripts/_measure/structure_funnel.py +97 -0
  92. package/skills/token-optimizer/scripts/_measure/timestamp_cache.py +11 -0
  93. package/skills/token-optimizer/scripts/_measure/token_type_split.py +29 -0
  94. package/skills/token-optimizer/scripts/_measure/transcript_backfill.py +419 -0
  95. package/skills/token-optimizer/scripts/_measure/transcript_product.py +228 -0
  96. package/skills/token-optimizer/scripts/_measure/transcript_stream.py +279 -0
  97. package/skills/token-optimizer/scripts/_measure/trends.py +44 -185
  98. package/skills/token-optimizer/scripts/_measure/ttl_period.py +6 -0
  99. package/skills/token-optimizer/scripts/_measure/upgrade_drain_control.py +287 -0
  100. package/skills/token-optimizer/scripts/activity_tracker.py +4 -33
  101. package/skills/token-optimizer/scripts/antigravity_install.py +2 -0
  102. package/skills/token-optimizer/scripts/archive_result.py +15 -19
  103. package/skills/token-optimizer/scripts/archive_verify.py +165 -0
  104. package/skills/token-optimizer/scripts/bash_compress.py +14 -43
  105. package/skills/token-optimizer/scripts/bash_compress_hook.py +132 -2
  106. package/skills/token-optimizer/scripts/checkpoint_state.py +2 -2
  107. package/skills/token-optimizer/scripts/cloud_kit.py +3 -6
  108. package/skills/token-optimizer/scripts/codemap.py +274 -0
  109. package/skills/token-optimizer/scripts/codemap_hint.py +153 -0
  110. package/skills/token-optimizer/scripts/codemap_index.py +656 -0
  111. package/skills/token-optimizer/scripts/codemap_ledger.py +309 -0
  112. package/skills/token-optimizer/scripts/codemap_reread.py +161 -0
  113. package/skills/token-optimizer/scripts/codex_doctor.py +9 -1
  114. package/skills/token-optimizer/scripts/codex_log_index.py +34 -15
  115. package/skills/token-optimizer/scripts/codex_session.py +16 -216
  116. package/skills/token-optimizer/scripts/compression_backfill.py +4 -35
  117. package/skills/token-optimizer/scripts/context_intel.py +5 -3
  118. package/skills/token-optimizer/scripts/copilot_install.py +2 -0
  119. package/skills/token-optimizer/scripts/coverage_funnel.py +261 -0
  120. package/skills/token-optimizer/scripts/cursor_install.py +12 -0
  121. package/skills/token-optimizer/scripts/cursor_quality.py +16 -64
  122. package/skills/token-optimizer/scripts/dashboard_assets.py +21 -0
  123. package/skills/token-optimizer/scripts/deterministic_candidates.py +2 -10
  124. package/skills/token-optimizer/scripts/devin_source.py +8 -3
  125. package/skills/token-optimizer/scripts/devin_verify.py +7 -1
  126. package/skills/token-optimizer/scripts/grok_install.py +2 -0
  127. package/skills/token-optimizer/scripts/heal_report.py +7 -6
  128. package/skills/token-optimizer/scripts/hermes_doctor.py +9 -1
  129. package/skills/token-optimizer/scripts/hermes_install.py +7 -1
  130. package/skills/token-optimizer/scripts/hermes_session.py +14 -136
  131. package/skills/token-optimizer/scripts/hint_paths.py +21 -0
  132. package/skills/token-optimizer/scripts/holdout.py +136 -0
  133. package/skills/token-optimizer/scripts/hook_runtime.py +1 -0
  134. package/skills/token-optimizer/scripts/hook_skip_log.py +89 -0
  135. package/skills/token-optimizer/scripts/large_transcripts.py +31 -0
  136. package/skills/token-optimizer/scripts/lean_resume_carry.py +518 -0
  137. package/skills/token-optimizer/scripts/measure.py +34 -76
  138. package/skills/token-optimizer/scripts/post_run_classify.py +349 -0
  139. package/skills/token-optimizer/scripts/preserved_reinject.py +54 -0
  140. package/skills/token-optimizer/scripts/read_cache.py +99 -100
  141. package/skills/token-optimizer/scripts/reset_epoch.py +3 -3
  142. package/skills/token-optimizer/scripts/session_store.py +49 -99
  143. package/skills/token-optimizer/scripts/session_store_guard.py +75 -0
  144. package/skills/token-optimizer/scripts/settings_backup.py +379 -0
  145. package/skills/token-optimizer/scripts/shipped_hook_templates.py +1 -0
  146. package/skills/token-optimizer/scripts/statusline.js +144 -30
  147. package/skills/token-optimizer/scripts/structural.py +25 -0
  148. package/skills/token-optimizer/scripts/structure_map.py +4 -26
@@ -0,0 +1,379 @@
1
+ """The secret-free backup behind the settings.json self-heal.
2
+
3
+ When settings.json is wiped, Token Optimizer can put back what was lost. The
4
+ backup it restores from is a copy of settings.json with every secret taken out,
5
+ so a second copy of the file never holds a credential:
6
+
7
+ * Whole keys that carry credentials by design are not copied: ``env``,
8
+ ``apiKeyHelper``, ``awsAuthRefresh``, ``awsCredentialExport``,
9
+ ``otelHeadersHelper``, and any top-level key whose name looks like a secret
10
+ (token, secret, key, password, credential, auth) except a short safe list.
11
+ * ``mcpServers`` / ``_disabledMcpServers`` keep their structure (name, type,
12
+ command, args, url) but lose each server's ``env`` and ``headers`` and any
13
+ argument or URL the credential detector flags.
14
+ * Every other string in the tree that ``credential_patterns`` flags is dropped.
15
+ A dropped value is simply absent: no placeholder is stored, so a restore can
16
+ never write back a stand-in that looks real.
17
+
18
+ A restore only ever adds keys that are missing, and names what it could not
19
+ restore. ``TOKEN_OPTIMIZER_SETTINGS_HEAL=0`` turns the backup and the restore off.
20
+
21
+ Lives beside measure.py; standard library only, Python 3.9 grammar.
22
+ """
23
+ from __future__ import annotations
24
+
25
+ import json
26
+ import os
27
+ import re
28
+ import sys
29
+ from datetime import datetime, timedelta
30
+ from pathlib import Path
31
+
32
+ KILL_SWITCH_ENV = "TOKEN_OPTIMIZER_SETTINGS_HEAL"
33
+ _OFF = ("0", "false", "off", "no")
34
+ _BACKUP_GLOB = "settings.json*"
35
+
36
+ # Credential carriers by design: never copied, whatever they hold.
37
+ DROP_KEYS = frozenset({"env", "apiKeyHelper", "awsAuthRefresh", "awsCredentialExport", "otelHeadersHelper"})
38
+ # Names that match the secret pattern below but are not secrets.
39
+ SAFE_KEYS = frozenset({"hooks", "keybindings", "authors", "author"})
40
+ _SECRET_KEY = re.compile(r"token|secret|key|password|credential|auth", re.IGNORECASE)
41
+ # Per-server MCP maps that carry credentials.
42
+ _MCP_DROP = frozenset({"env", "headers", "headersHelper", "apiKeyHelper"})
43
+ _MCP_KEYS = ("mcpServers", "_disabledMcpServers")
44
+ _DROP = object()
45
+
46
+
47
+ def heal_disabled():
48
+ """True when the user turned the backup and restore off."""
49
+ return os.environ.get(KILL_SWITCH_ENV, "").strip().lower() in _OFF
50
+
51
+
52
+ # --- the scrub -----------------------------------------------------------------
53
+
54
+ def _flagged(text):
55
+ """True when ``text`` holds something credential_patterns recognises. Uses
56
+ the shipped detectors only; with a broken custom-pattern file it falls back
57
+ to the built-in set rather than skipping the check."""
58
+ if not isinstance(text, str) or not text:
59
+ return False
60
+ import credential_patterns as cp
61
+ try:
62
+ # redact_credentials skips its regexes on text with no credential prefix;
63
+ # scan_for_credentials has no such shortcut, so gate it the same way.
64
+ maybe = getattr(cp, "_text_may_contain_credentials", lambda _t: True)(text)
65
+ return cp.redact_credentials(text) != text or (maybe and bool(cp.scan_for_credentials(text)))
66
+ except cp.RedactionConfigError:
67
+ return any(pat.search(text) for _, pat in cp.CREDENTIAL_PATTERNS)
68
+
69
+
70
+ def _secret_name(name):
71
+ return isinstance(name, str) and name not in SAFE_KEYS and bool(_SECRET_KEY.search(name))
72
+
73
+
74
+ class _Stats:
75
+ def __init__(self):
76
+ self.withheld = [] # top-level keys left out whole
77
+ self.partial = [] # top-level keys that lost some inner values
78
+ self.values = 0 # inner values dropped
79
+
80
+
81
+ def _tree(value, stats):
82
+ """Copy of ``value`` without flagged strings (and secret-named string fields)."""
83
+ if isinstance(value, str):
84
+ if _flagged(value):
85
+ stats.values += 1
86
+ return _DROP
87
+ return value
88
+ if isinstance(value, dict):
89
+ out = {}
90
+ for k, v in value.items():
91
+ if _flagged(k) or (_secret_name(k) and isinstance(v, str)):
92
+ stats.values += 1
93
+ continue
94
+ kept = _tree(v, stats)
95
+ if kept is not _DROP:
96
+ out[k] = kept
97
+ return out
98
+ if isinstance(value, list):
99
+ return [kept for kept in (_tree(v, stats) for v in value) if kept is not _DROP]
100
+ return value
101
+
102
+
103
+ def _args(args, stats):
104
+ """MCP args without credentials. A dropped value also takes the flag that
105
+ introduced it, and a secret-named flag takes its value, so no dangling
106
+ ``--token`` is left behind."""
107
+ out, skip = [], False
108
+ for a in args:
109
+ if skip:
110
+ skip = False
111
+ if not (isinstance(a, str) and a.startswith("-")):
112
+ stats.values += 1
113
+ continue
114
+ if isinstance(a, str) and a.startswith("-") and "=" not in a and _secret_name(a.lstrip("-")):
115
+ stats.values += 1
116
+ skip = True
117
+ continue
118
+ kept = _tree(a, stats)
119
+ if kept is _DROP:
120
+ if out and isinstance(out[-1], str) and out[-1].startswith("-") and "=" not in out[-1]:
121
+ out.pop()
122
+ continue
123
+ out.append(kept)
124
+ return out
125
+
126
+
127
+ def _mcp(value, stats):
128
+ if not isinstance(value, dict):
129
+ return _tree(value, stats)
130
+ out = {}
131
+ for name, cfg in value.items():
132
+ if not isinstance(cfg, dict):
133
+ kept = _tree(cfg, stats)
134
+ if kept is not _DROP:
135
+ out[name] = kept
136
+ continue
137
+ server = {}
138
+ for k, v in cfg.items():
139
+ if k in _MCP_DROP:
140
+ stats.values += 1
141
+ elif k == "args" and isinstance(v, list):
142
+ server[k] = _args(v, stats)
143
+ else:
144
+ kept = _tree(v, stats) if not (_secret_name(k) and isinstance(v, str)) else _DROP
145
+ if kept is _DROP:
146
+ stats.values += 1
147
+ else:
148
+ server[k] = kept
149
+ out[name] = server
150
+ return out
151
+
152
+
153
+ def _hooks(value, stats):
154
+ """Hooks without flagged commands; an entry whose command was dropped goes
155
+ too (a hook with no command restores as noise)."""
156
+ clean = _tree(value, stats)
157
+ if not isinstance(clean, dict):
158
+ return clean
159
+ out = {}
160
+ for event, groups in clean.items():
161
+ kept_groups = []
162
+ for group in groups if isinstance(groups, list) else []:
163
+ entries = group.get("hooks") if isinstance(group, dict) else None
164
+ if not isinstance(entries, list):
165
+ kept_groups.append(group)
166
+ continue
167
+ good = [e for e in entries if not (isinstance(e, dict) and e.get("type") == "command"
168
+ and not isinstance(e.get("command"), str))]
169
+ if good:
170
+ kept_groups.append(dict(group, hooks=good))
171
+ if kept_groups:
172
+ out[event] = kept_groups
173
+ return out
174
+
175
+
176
+ def scrub(data):
177
+ """(clean copy of a settings dict without secrets, stats). Never mutates ``data``."""
178
+ stats = _Stats()
179
+ clean = {}
180
+ if not isinstance(data, dict):
181
+ return clean, stats
182
+ for key, value in data.items():
183
+ if key in DROP_KEYS or _secret_name(key) or _flagged(key):
184
+ stats.withheld.append(str(key))
185
+ continue
186
+ before = stats.values
187
+ if key in _MCP_KEYS:
188
+ kept = _mcp(value, stats)
189
+ elif key == "hooks":
190
+ kept = _hooks(value, stats)
191
+ else:
192
+ kept = _tree(value, stats)
193
+ if key == "statusLine" and not (isinstance(kept, dict) and isinstance(kept.get("command"), str)):
194
+ kept = _DROP
195
+ if kept is _DROP:
196
+ stats.withheld.append(str(key))
197
+ continue
198
+ if stats.values > before:
199
+ stats.partial.append(str(key))
200
+ clean[key] = kept
201
+ return clean, stats
202
+
203
+
204
+ # --- snapshot ------------------------------------------------------------------
205
+
206
+ def _dump(value):
207
+ return json.dumps(value, indent=2, ensure_ascii=False) + "\n"
208
+
209
+
210
+ def _meta(clean, stats, timestamp=None):
211
+ return {"key_count": len(clean), "key_set": sorted(clean),
212
+ "withheld_keys": sorted(stats.withheld), "scrubbed_in": sorted(stats.partial),
213
+ "timestamp": timestamp or datetime.now().isoformat()}
214
+
215
+
216
+ def read_highwater(facade):
217
+ """The snapshot, scrubbed again on the way in so a copy an older version
218
+ wrote can never feed a restore. None when there is no file."""
219
+ raw = facade._settings_read_highwater()
220
+ return None if raw is None else scrub(raw)[0]
221
+
222
+
223
+ def read_meta(facade):
224
+ try:
225
+ meta = json.loads((Path(facade._settings_heal_dir()) / "highwater.meta.json").read_text(encoding="utf-8"))
226
+ return meta if isinstance(meta, dict) else {}
227
+ except (OSError, ValueError):
228
+ return {}
229
+
230
+
231
+ def update_highwater(facade, data):
232
+ """Snapshot the secret-free form of ``data``. Returns it, or None if not written.
233
+
234
+ Replaced when it holds more keys, or the same keys (or more) with fresher
235
+ values: hook commands change on upgrade, and restoring a stale path would
236
+ restore a broken hook. A sighting that lost a key never shrinks it."""
237
+ clean, stats = scrub(data)
238
+ if not clean:
239
+ return None
240
+ heal_dir = facade._settings_heal_ensure_dir()
241
+ if heal_dir is None:
242
+ return None
243
+ existing = read_highwater(facade)
244
+ if existing is not None:
245
+ grows = len(clean) > len(existing)
246
+ refreshes = set(clean) >= set(existing) and clean != existing
247
+ if not (grows or refreshes):
248
+ return None
249
+ if not facade._settings_write_file_secure(heal_dir / "highwater.json", _dump(clean)):
250
+ return None
251
+ facade._settings_write_file_secure(heal_dir / "highwater.meta.json", _dump(_meta(clean, stats)))
252
+ return clean
253
+
254
+
255
+ def backup_scrubbed(facade, dest_dir):
256
+ """Pre-restore backup of the live file, secret-free, mode 0600. Returns its
257
+ path, or None (the heal then aborts)."""
258
+ try:
259
+ path = Path(facade.SETTINGS_PATH)
260
+ if not path.is_file():
261
+ return None
262
+ live = json.loads(path.read_text(encoding="utf-8"))
263
+ dest = Path(dest_dir) / "settings.json"
264
+ i = 1
265
+ while dest.exists():
266
+ dest = Path(dest_dir) / ("settings.json-%d" % i)
267
+ i += 1
268
+ return dest if facade._settings_write_file_secure(dest, _dump(scrub(live)[0])) else None
269
+ except (OSError, ValueError):
270
+ return None
271
+
272
+
273
+ # --- restore notice --------------------------------------------------------------
274
+
275
+ def restore_notice(restored_keys, meta=None):
276
+ """The one line shown after a restore, naming what could not be restored."""
277
+ keys = sorted(restored_keys)
278
+ shown = ", ".join(keys[:6]) + (" +%d more" % (len(keys) - 6) if len(keys) > 6 else "")
279
+ line = "Token Optimizer restored %s after settings.json was reset" % (
280
+ "its backup (%s)" % shown if keys else "nothing")
281
+ meta = meta or {}
282
+ withheld = [k for k in meta.get("withheld_keys") or [] if k not in keys]
283
+ if withheld:
284
+ line += ". %s %s not restored: Token Optimizer never stores secrets" % (
285
+ ", ".join(withheld), "was" if len(withheld) == 1 else "were")
286
+ inner = [k for k in meta.get("scrubbed_in") or [] if k in keys]
287
+ if inner:
288
+ line += ". Secret values inside %s were left out" % ", ".join(inner)
289
+ return line
290
+
291
+
292
+ def announce_restore(notice):
293
+ """One short stderr line (the heal log entry carries the same text)."""
294
+ try:
295
+ print(" %s. Turn this off with %s=0." % (notice, KILL_SWITCH_ENV), file=sys.stderr)
296
+ except Exception:
297
+ pass
298
+
299
+
300
+ def last_restore_line(facade, max_age_days=14):
301
+ """The most recent restore as one line, or None when none within ``max_age_days``."""
302
+ try:
303
+ log = Path(facade._settings_heal_dir()) / "heal_log.jsonl"
304
+ if not log.is_file():
305
+ return None
306
+ for raw in reversed(log.read_text(encoding="utf-8").strip().split("\n")):
307
+ if not raw.strip():
308
+ continue
309
+ entry = json.loads(raw)
310
+ if entry.get("action") != "restore":
311
+ continue
312
+ when = datetime.fromisoformat(str(entry.get("timestamp")))
313
+ if max_age_days is not None and datetime.now() - when > timedelta(days=max_age_days):
314
+ return None
315
+ line = entry.get("notice") or restore_notice(entry.get("restored_keys") or [])
316
+ return "%s (%s)" % (line, when.strftime("%Y-%m-%d %H:%M"))
317
+ except Exception:
318
+ pass
319
+ return None
320
+
321
+
322
+ # --- migration -------------------------------------------------------------------
323
+
324
+ def _scrub_file(facade, path):
325
+ """Rewrite one settings copy without secrets, atomically, mode 0600. Returns
326
+ (items dropped, stats), or None when left alone (unreadable / not settings)."""
327
+ try:
328
+ data = json.loads(path.read_text(encoding="utf-8"))
329
+ except (OSError, ValueError):
330
+ return None
331
+ if not isinstance(data, dict):
332
+ return None
333
+ clean, stats = scrub(data)
334
+ if clean == data:
335
+ try:
336
+ os.chmod(str(path), 0o600)
337
+ except OSError:
338
+ pass
339
+ return 0, stats
340
+ if not facade._settings_write_file_secure(path, _dump(clean)):
341
+ return None
342
+ return len(stats.withheld) + stats.values, stats
343
+
344
+
345
+ def migrate_to_secret_free(facade):
346
+ """Scrub every settings copy under settings_heal: highwater.json (+ its meta)
347
+ and backups/settings.json*. Files outside settings_heal are never touched.
348
+ Returns {file: items dropped} for files that changed; idempotent."""
349
+ heal_dir = Path(facade._settings_heal_dir())
350
+ changed = {}
351
+ if not heal_dir.is_dir():
352
+ return changed
353
+ targets = [heal_dir / "highwater.json"]
354
+ backups = heal_dir / "backups"
355
+ if backups.is_dir():
356
+ targets += sorted(p for p in backups.glob(_BACKUP_GLOB) if p.is_file())
357
+ high_stats = None
358
+ for path in targets:
359
+ if not path.is_file():
360
+ continue
361
+ done = _scrub_file(facade, path)
362
+ if done is None:
363
+ continue
364
+ if path.name == "highwater.json":
365
+ high_stats = done[1]
366
+ if done[0]:
367
+ changed[str(path.relative_to(heal_dir))] = done[0]
368
+ meta = heal_dir / "highwater.meta.json"
369
+ if "highwater.json" in changed and high_stats is not None:
370
+ try:
371
+ clean = json.loads((heal_dir / "highwater.json").read_text(encoding="utf-8"))
372
+ old = json.loads(meta.read_text(encoding="utf-8")) if meta.is_file() else {}
373
+ facade._settings_write_file_secure(meta, _dump(_meta(clean, high_stats, old.get("timestamp"))))
374
+ except (OSError, ValueError, AttributeError):
375
+ pass
376
+ if changed:
377
+ facade._settings_heal_log("migrate_secret_free", files=sorted(changed),
378
+ items_dropped=sum(changed.values()))
379
+ return changed
@@ -223,6 +223,7 @@ SHIPPED_HOOK_CONTEXTS = frozenset((
223
223
  ('StopFailure', '', 'command', 'for b in bash /bin/bash /usr/bin/bash /usr/local/bin/bash /opt/homebrew/bin/bash; do command -v "$b" >/dev/null 2>&1 || continue; D="${CLAUDE_PLUGIN_ROOT}"; case "$D" in *\\\\*) D="$(printf \'%s\' "$D" | tr \'\\\\\' \'/\')";; esac; [ -r "$D/hooks/python-launcher.sh" ] || D="$(ls -d "${D%/*}"/*/ 2>/dev/null | grep -E "/[0-9]+[.][0-9]+[.][0-9]+/$" | sort -V | tail -n1)"; D="${D%/}"; [ -r "$D/hooks/python-launcher.sh" ] || exit 0; exec "$b" "$D/hooks/python-launcher.sh" "$D/hooks/run.py" skills/token-optimizer/scripts/measure.py compact-capture --trigger stop-failure --quiet; done; exit 0'),
224
224
  ('StopFailure', '', 'command', 'for b in bash /bin/bash /usr/bin/bash /usr/local/bin/bash /opt/homebrew/bin/bash; do command -v "$b" >/dev/null 2>&1 || continue; L="${CLAUDE_PLUGIN_ROOT}/hooks/python-launcher.sh"; [ -r "$L" ] || exit 0; exec "$b" "$L" "${CLAUDE_PLUGIN_ROOT}/hooks/run.py" skills/token-optimizer/scripts/measure.py compact-capture --trigger stop-failure --quiet; done; exit 0'),
225
225
  ('StopFailure', '', 'command', 'python3 "${CLAUDE_PLUGIN_ROOT}/hooks/run.py" skills/token-optimizer/scripts/measure.py compact-capture --trigger stop-failure --quiet'),
226
+ ('SubagentStart', '', 'command', 'for b in bash /bin/bash /usr/bin/bash /usr/local/bin/bash /opt/homebrew/bin/bash; do command -v "$b" >/dev/null 2>&1 || continue; D="${CLAUDE_PLUGIN_ROOT}"; [ -r "$D/hooks/python-launcher.sh" ] || D="$(ls -d "${D%[/\\\\]*}"/*/ 2>/dev/null | grep -E "/[0-9]+[.][0-9]+[.][0-9]+/$" | sort -V | tail -n1)"; D="${D%/}"; [ -r "$D/hooks/python-launcher.sh" ] || exit 0; exec "$b" "$D/hooks/python-launcher.sh" "$D/hooks/run.py" skills/token-optimizer/scripts/codemap_hint.py; done; exit 0'),
226
227
  ('UserPromptSubmit', '', 'command', "python3 '${CLAUDE_PLUGIN_ROOT}/skills/token-optimizer/scripts/measure.py' quality-cache --warn --quiet"),
227
228
  ('UserPromptSubmit', '', 'command', "test -f '${CLAUDE_PLUGIN_ROOT}/skills/token-optimizer/scripts/measure.py' && python3 '${CLAUDE_PLUGIN_ROOT}/skills/token-optimizer/scripts/measure.py' quality-cache --warn --quiet || true"),
228
229
  ('UserPromptSubmit', '', 'command', '"${CLAUDE_PLUGIN_ROOT}/hooks/run.py" skills/token-optimizer/scripts/measure.py quality-cache --warn --quiet'),
@@ -1,18 +1,22 @@
1
1
  #!/usr/bin/env node
2
2
  // Token Optimizer - Claude Code Status Line (two-row layout)
3
3
  //
4
- // Row 1: model | effort | project | context bar used% | ContextQ:grade(score)
5
- // Row 2: Eff:grade(score) | warnings | Compacts:N(observing) | duration | Agents
4
+ // Row 1: model | effort | project | context bar used% | Quality grade(score)
5
+ // Row 2: savings headline | warnings | duration | Agents | limits
6
6
  //
7
7
  // Install: python3 measure.py setup-quality-bar
8
8
  // The quality score is updated by a UserPromptSubmit hook every ~2 minutes.
9
9
  // Reads from the most recent per-session quality-cache-*.json for accuracy.
10
10
  // Effort level comes from the stdin payload (data.effort.level) when Claude
11
11
  // Code provides it, falling back to settings.json effortLevel on older versions.
12
+ // The savings segment is read from the status-bar JSON cache that
13
+ // `measure.py status-bar` writes under SNAPSHOT_DIR/status-bar/; this script
14
+ // never spawns Python (it runs on every render).
12
15
 
13
16
  const fs = require('fs');
14
17
  const path = require('path');
15
18
  const os = require('os');
19
+ const crypto = require('crypto');
16
20
  const { execFileSync } = require('child_process');
17
21
 
18
22
  // --- Self-disabling guard ---
@@ -124,6 +128,105 @@ function _claudeHome() {
124
128
  }
125
129
  const CLAUDE_HOME = _claudeHome();
126
130
 
131
+ // ---- OSC 8 hyperlink support ----
132
+ // Emit \x1b]8;;URL\x07TEXT\x1b]8;;\x07 only where the terminal is known to
133
+ // render it; everywhere else the segment stays plain text (the approved
134
+ // artboard's fallback). TOKEN_OPTIMIZER_HYPERLINKS=0/1 forces either way.
135
+ // tmux/screen are treated as unsupported: passthrough needs allow-passthrough
136
+ // AND a capable outer terminal, neither of which is detectable here.
137
+ function _supportsOsc8() {
138
+ try {
139
+ const env = process.env;
140
+ const override = String(env.TOKEN_OPTIMIZER_HYPERLINKS || '').trim().toLowerCase();
141
+ if (override === '0' || override === 'false' || override === 'off') return false;
142
+ if (override === '1' || override === 'true' || override === 'on') return true;
143
+ if (env.TMUX || env.STY) return false;
144
+ const tp = String(env.TERM_PROGRAM || '').toLowerCase();
145
+ if (['iterm.app', 'wezterm', 'kitty', 'ghostty', 'vscode', 'visual studio code',
146
+ 'hyper', 'tabby', 'warpterminal', 'alacritty', 'rio', 'contour',
147
+ 'mintty', 'cursor', 'windsurf'].includes(tp)) return true;
148
+ if (tp === 'apple_terminal') return false;
149
+ if (env.WT_SESSION || env.KONSOLE_VERSION || env.ALACRITTY_WINDOW_ID ||
150
+ env.ALACRITTY_LOG || env.KITTY_WINDOW_ID || env.GHOSTTY_RESOURCES_DIR) return true;
151
+ if (/foot|wezterm|kitty|alacritty|ghostty|contour|rio/.test(String(env.TERM || '').toLowerCase())) return true;
152
+ const vte = parseInt(env.VTE_VERSION || '0', 10);
153
+ if (vte >= 5000) return true;
154
+ return false;
155
+ } catch (e) {
156
+ return false;
157
+ }
158
+ }
159
+
160
+ // ---- Status-bar cache (savings headline) ----
161
+ // measure.py resolves SNAPSHOT_DIR as TOKEN_OPTIMIZER_SNAPSHOT_DIR, else
162
+ // <plugin-data>/data, else <runtime>/_backups/token-optimizer. The status line
163
+ // has no CLAUDE_PLUGIN_DATA, so mirror the quality-cache fan-out: check every
164
+ // candidate status-bar dir and keep the freshest cache file for this session.
165
+ function _statusBarDirs() {
166
+ const dirs = [];
167
+ const snap = String(process.env.TOKEN_OPTIMIZER_SNAPSHOT_DIR || '').trim();
168
+ if (snap) dirs.push(path.join(snap, 'status-bar'));
169
+ for (const v of [process.env.CLAUDE_PLUGIN_DATA, process.env.TOKEN_OPTIMIZER_PLUGIN_DATA]) {
170
+ const p = String(v || '').trim();
171
+ if (p) dirs.push(path.join(p, 'data', 'status-bar'));
172
+ }
173
+ try {
174
+ const dataRoot = path.join(CLAUDE_HOME, 'plugins', 'data');
175
+ for (const d of fs.readdirSync(dataRoot)) {
176
+ if (d.includes('token-optimizer')) {
177
+ dirs.push(path.join(dataRoot, d, 'data', 'status-bar'));
178
+ }
179
+ }
180
+ } catch (e) {}
181
+ dirs.push(path.join(CLAUDE_HOME, '_backups', 'token-optimizer', 'status-bar'));
182
+ return dirs;
183
+ }
184
+
185
+ // Python twin of sanitize_session_id + _status_bar_key: strip unsafe chars,
186
+ // "unknown" under 6, and long ids are shortened with a sha256 suffix.
187
+ function _statusBarSessionKey(sessionId) {
188
+ let sid = sessionId === null || sessionId === undefined ? '' : String(sessionId);
189
+ sid = sid.replace(/[^a-zA-Z0-9_-]/g, '');
190
+ if (sid.length < 6) sid = 'unknown';
191
+ if (sid.length <= 100) return sid;
192
+ const hash = crypto.createHash('sha256').update(sid, 'utf8').digest('hex').slice(0, 16);
193
+ return sid.slice(0, 64) + '-' + hash;
194
+ }
195
+
196
+ // The freshest status-bar cache's savings_headline.display, or null.
197
+ // Freshness is decided on computed_at across all candidate dirs BEFORE
198
+ // reading display, so a newer "below threshold" cache correctly hides an
199
+ // older number that no longer applies.
200
+ function _statusBarHeadlineDisplay(sessionId) {
201
+ try {
202
+ const key = _statusBarSessionKey(sessionId);
203
+ if (!key || key === 'unknown') return null;
204
+ let best = null, bestTs = -1;
205
+ for (const dir of _statusBarDirs()) {
206
+ try {
207
+ const file = path.join(dir, key + '.json');
208
+ const raw = fs.readFileSync(file, 'utf8');
209
+ const data = JSON.parse(raw);
210
+ if (!data || typeof data !== 'object') continue;
211
+ const ts = Number(data.computed_at);
212
+ const tsOrMtime = Number.isFinite(ts) ? ts : fs.statSync(file).mtimeMs / 1000;
213
+ if (tsOrMtime <= bestTs) continue;
214
+ bestTs = tsOrMtime;
215
+ best = data;
216
+ } catch (e) {}
217
+ }
218
+ const headline = best && best.savings && best.savings.savings_headline;
219
+ const display = headline && headline.display;
220
+ if (display && typeof display === 'object' &&
221
+ typeof display.short === 'string' && display.short) {
222
+ return display;
223
+ }
224
+ return null;
225
+ } catch (e) {
226
+ return null;
227
+ }
228
+ }
229
+
127
230
  // Host parse (Claude Code 2.1.296 Dd/FOo): scientific notation and thousand
128
231
  // separators first, then a decimal prefix. NaN or <= 0 is invalid and IGNORED
129
232
  // (the next source applies). Mirrors measure.py _host_parse_int; shared vectors
@@ -463,7 +566,7 @@ process.stdin.on('end', () => {
463
566
  // Keep the score's value-color (green/yellow/orange/red) regardless of
464
567
  // staleness; the `~` prefix is the only stale indicator so the number
465
568
  // stays readable. (Dimming the whole score made it barely visible.)
466
- const tag = `ContextQ:${stale ? '~' : ''}${grade}(${score})`;
569
+ const tag = q.measured === false ? `Quality ~${score}` : `Quality ${stale ? '~' : ''}${grade} ${score}`;
467
570
  if (score >= 85) {
468
571
  qScore = `${SEP}\x1b[32m${tag}${RESET}`;
469
572
  } else if (score >= 75) {
@@ -475,7 +578,7 @@ process.stdin.on('end', () => {
475
578
  }
476
579
  }
477
580
  } else {
478
- qScore = `${SEP}${DIM}ContextQ:--${RESET}`;
581
+ qScore = `${SEP}${DIM}Quality --${RESET}`;
479
582
  }
480
583
 
481
584
  const dirname = path.basename(dir);
@@ -494,7 +597,22 @@ process.stdin.on('end', () => {
494
597
  ].filter(Boolean);
495
598
 
496
599
  // ---- ROW 2: Session details ----
600
+ // The savings headline leads the row so packRows keeps it on the first
601
+ // physical line when the terminal is narrow. It comes from the status-bar
602
+ // cache (never a Python spawn) and is omitted entirely when the shared
603
+ // headline's display is null.
497
604
  const row2Parts = [];
605
+ const savingsDisplay = _statusBarHeadlineDisplay(sessionId);
606
+ let savingsSeg = null;
607
+ if (savingsDisplay) {
608
+ const label = `${savingsDisplay.short} ↗`;
609
+ const url = typeof savingsDisplay.url === 'string' && savingsDisplay.url
610
+ ? savingsDisplay.url : null;
611
+ savingsSeg = (url && _supportsOsc8())
612
+ ? `\x1b[32m\x1b]8;;${url}\x07${label}\x1b]8;;\x07${RESET}`
613
+ : `\x1b[32m${label}${RESET}`;
614
+ row2Parts.push(savingsSeg);
615
+ }
498
616
 
499
617
  // U3: near-zero-cost "resumable checkpoint" existence signal.
500
618
  // When the SessionStart pointer fired (a relevance-cleared checkpoint
@@ -510,24 +628,12 @@ process.stdin.on('end', () => {
510
628
  const flag = JSON.parse(fs.readFileSync(flagPath, 'utf8'));
511
629
  const ts = typeof flag.ts === 'number' ? flag.ts : NaN;
512
630
  if (isFinite(ts) && (Date.now() - ts) < (30 * 60 * 1000)) {
513
- row2Parts.push(`\x1b[36m⤸resumable${RESET}`);
631
+ row2Parts.push(`\x1b[36m⤸ resumable${RESET}`);
514
632
  }
515
633
  }
516
634
  }
517
635
  } catch (e) {}
518
636
 
519
- // SessionEfficiency
520
- if (q) {
521
- const se = q.session_efficiency;
522
- if (se != null) {
523
- const seScore = Math.round(se);
524
- const seGrade = q.session_efficiency_grade || gradeFor(seScore);
525
- row2Parts.push(`${DIM}Eff:${seGrade}(${seScore})${RESET}`);
526
- }
527
- } else {
528
- row2Parts.push(`${DIM}Eff:--${RESET}`);
529
- }
530
-
531
637
  // Biggest drag: the actual signal pulling the score down — context fill,
532
638
  // compactions, or the dominant waste cause — computed upstream by weighted
533
639
  // deficit, not guessed from waste keys here.
@@ -555,16 +661,11 @@ process.stdin.on('end', () => {
555
661
  }
556
662
  }
557
663
 
558
- // Recovery thresholds remain shadow-only until calibrated.
664
+ // Compactions only when there were any: "Compacts:0" announced nothing.
559
665
  if (q) {
560
666
  const c = q.compactions;
561
- if (c != null) {
562
- if (c > 0) {
563
- // Recovery evidence is shadow-only, even for older cached flags.
564
- row2Parts.push(`${DIM}Compacts:${c}(observing)${RESET}`);
565
- } else {
566
- row2Parts.push(`\x1b[32mCompacts:0${RESET}`);
567
- }
667
+ if (c != null && c > 0) {
668
+ row2Parts.push(`${DIM}compacted ${c}×${RESET}`);
568
669
  }
569
670
  }
570
671
 
@@ -580,7 +681,12 @@ process.stdin.on('end', () => {
580
681
  }
581
682
 
582
683
  // Active agents
583
- const stripAnsi = s => String(s).replace(/\x1b\[[0-9;]*[a-zA-Z]/g, '').replace(/[\x00-\x1f]/g, '');
684
+ // stripAnsi must drop OSC sequences (\x1b]…\x07 / \x1b]…\x1b\\) as well as
685
+ // CSI: the savings segment is an OSC 8 hyperlink whose raw bytes would
686
+ // otherwise count toward the packed-row width.
687
+ const stripAnsi = s => String(s)
688
+ .replace(/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/g, '')
689
+ .replace(/\x1b\[[0-9;]*[a-zA-Z]/g, '').replace(/[\x00-\x1f]/g, '');
584
690
  if (cacheMatchesSession && q.active_agents && q.active_agents.length > 0) {
585
691
  const running = q.active_agents.filter(a => a.status === 'running');
586
692
  if (running.length > 0) {
@@ -616,11 +722,13 @@ process.stdin.on('end', () => {
616
722
  pct >= 90 ? '\x1b[5;31m' : pct >= 75 ? '\x1b[38;5;208m' : pct >= 50 ? '\x1b[33m' : '\x1b[32m';
617
723
  if (fiveHour) {
618
724
  const p = Math.ceil(fiveHour.used_percentage);
619
- row2Parts.push(`${limitColor(p)}5h:${p}%${fmtReset(fiveHour.resets_at)}${RESET}`);
725
+ row2Parts.push(`${limitColor(p)}5 hours ${p}%${fmtReset(fiveHour.resets_at)}${RESET}`);
620
726
  }
621
727
  if (sevenDay) {
622
728
  const p = Math.ceil(sevenDay.used_percentage);
623
- row2Parts.push(`${DIM}7d:${p}%${RESET}`);
729
+ // Same pressure colours as the 5-hour window: a weekly limit near the
730
+ // cap is the most important number on the line, not a dim footnote.
731
+ row2Parts.push(`${limitColor(p)}week ${p}%${RESET}`);
624
732
  }
625
733
 
626
734
  // Responsive layout: when Claude Code exports COLUMNS (v2.1.153+), greedily pack
@@ -645,12 +753,18 @@ process.stdin.on('end', () => {
645
753
  // fields (row 1), never wrapped, whatever COLUMNS says.
646
754
  const _slim = (process.env.TOKEN_OPTIMIZER_STATUS_BAR_SIZE || '').trim().toLowerCase() === 'slim';
647
755
  if (_slim) {
648
- process.stdout.write(row1Segs.join(SEP));
756
+ // Slim prints row 1 only, so the savings pill is appended there or it
757
+ // would never be seen.
758
+ process.stdout.write(savingsSeg ? row1Segs.concat([savingsSeg]).join(SEP) : row1Segs.join(SEP));
649
759
  } else if (_width) {
650
760
  const rows = [...packRows(row1Segs, _width), ...packRows(row2Parts, _width)];
651
761
  process.stdout.write(rows.join('\n'));
652
762
  } else {
653
- process.stdout.write(`${row1Segs.join(SEP)}\n${row2Parts.join(SEP)}`);
763
+ // Row 2 can be legitimately empty (no savings display, no quality cache,
764
+ // no limits): emit one line rather than a dangling blank second row.
765
+ const row1Text = row1Segs.join(SEP);
766
+ const row2Text = row2Parts.join(SEP);
767
+ process.stdout.write(row2Text ? `${row1Text}\n${row2Text}` : row1Text);
654
768
  }
655
769
  } catch (e) {
656
770
  // Silent fail - never break the status line