@alexgreensh/token-optimizer 5.13.69 → 5.13.70
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.
- package/.claude-plugin/marketplace.json +2 -2
- package/.claude-plugin/plugin.json +1 -1
- package/PRIVACY.md +4 -0
- package/hooks/hooks.json +11 -1
- package/hooks/module_runner.py +4 -1
- package/hooks/posttooluse_runner.py +44 -48
- package/hooks/sessionstart_runner.py +24 -5
- package/hooks/stop_runner.py +6 -6
- package/package.json +1 -1
- package/skills/token-optimizer/assets/dashboard.html +399 -509
- package/skills/token-optimizer/assets/savings_story.js +661 -0
- package/skills/token-optimizer/pricing/prices.json +1 -0
- package/skills/token-optimizer/references/implementation-playbook.md +3 -0
- package/skills/token-optimizer/scripts/_measure/__init__.py +3 -1
- package/skills/token-optimizer/scripts/_measure/archive_health.py +14 -0
- package/skills/token-optimizer/scripts/_measure/archive_void_codex.py +163 -0
- package/skills/token-optimizer/scripts/_measure/archive_void_evidence.py +165 -0
- package/skills/token-optimizer/scripts/_measure/audit.py +27 -135
- package/skills/token-optimizer/scripts/_measure/baseline_provenance.py +339 -0
- package/skills/token-optimizer/scripts/_measure/cache_policy.py +261 -581
- package/skills/token-optimizer/scripts/_measure/checkpoint_direction.py +97 -0
- package/skills/token-optimizer/scripts/_measure/checkpoint_retention.py +20 -0
- package/skills/token-optimizer/scripts/_measure/cli.py +12 -8
- package/skills/token-optimizer/scripts/_measure/codex_quality.py +246 -0
- package/skills/token-optimizer/scripts/_measure/compaction_survival.py +158 -0
- package/skills/token-optimizer/scripts/_measure/compression_fixture_void.py +147 -0
- package/skills/token-optimizer/scripts/_measure/compression_scan_checkpoint.py +72 -0
- package/skills/token-optimizer/scripts/_measure/context_reset_marker.py +64 -0
- package/skills/token-optimizer/scripts/_measure/continuity.py +64 -118
- package/skills/token-optimizer/scripts/_measure/cost_per_message_trend.py +40 -0
- package/skills/token-optimizer/scripts/_measure/counted_cap.py +28 -0
- package/skills/token-optimizer/scripts/_measure/counted_orphans.py +190 -0
- package/skills/token-optimizer/scripts/_measure/counted_position.py +20 -0
- package/skills/token-optimizer/scripts/_measure/counted_pricing_v5.py +267 -0
- package/skills/token-optimizer/scripts/_measure/counted_subagents.py +371 -0
- package/skills/token-optimizer/scripts/_measure/coverage_report.py +285 -0
- package/skills/token-optimizer/scripts/_measure/daemon.py +53 -74
- package/skills/token-optimizer/scripts/_measure/dashboard.py +87 -151
- package/skills/token-optimizer/scripts/_measure/dashboard_heal_claim.py +36 -0
- package/skills/token-optimizer/scripts/_measure/evidence_parallel.py +95 -0
- package/skills/token-optimizer/scripts/_measure/feature_health.py +256 -0
- package/skills/token-optimizer/scripts/_measure/file_refetch.py +250 -0
- package/skills/token-optimizer/scripts/_measure/first_call_context.py +216 -0
- package/skills/token-optimizer/scripts/_measure/first_read_outcomes.py +261 -0
- package/skills/token-optimizer/scripts/_measure/first_read_revive.py +137 -0
- package/skills/token-optimizer/scripts/_measure/fixture_context.py +65 -0
- package/skills/token-optimizer/scripts/_measure/headline.py +100 -0
- package/skills/token-optimizer/scripts/_measure/holdout_fallback.py +96 -0
- package/skills/token-optimizer/scripts/_measure/holdout_report.py +125 -0
- package/skills/token-optimizer/scripts/_measure/keepwarm_economics.py +201 -0
- package/skills/token-optimizer/scripts/_measure/keepwarm_fork.py +140 -0
- package/skills/token-optimizer/scripts/_measure/keepwarm_guard.py +35 -0
- package/skills/token-optimizer/scripts/_measure/keepwarm_guard_server.py +85 -0
- package/skills/token-optimizer/scripts/_measure/keepwarm_linux.py +121 -0
- package/skills/token-optimizer/scripts/_measure/keepwarm_prefix.py +143 -0
- package/skills/token-optimizer/scripts/_measure/keepwarm_response_filter.py +84 -0
- package/skills/token-optimizer/scripts/_measure/keepwarm_safety.py +256 -0
- package/skills/token-optimizer/scripts/_measure/lean_resume_receivers.py +260 -0
- package/skills/token-optimizer/scripts/_measure/lean_resume_threshold.py +76 -0
- package/skills/token-optimizer/scripts/_measure/lease_candidate_cleanup.py +82 -0
- package/skills/token-optimizer/scripts/_measure/lifecycle.py +54 -162
- package/skills/token-optimizer/scripts/_measure/mcp_archive_tripwire.py +120 -0
- package/skills/token-optimizer/scripts/_measure/mod_action_booking.py +178 -0
- package/skills/token-optimizer/scripts/_measure/mod_compaction_booking.py +276 -0
- package/skills/token-optimizer/scripts/_measure/mod_fresh_booking.py +105 -0
- package/skills/token-optimizer/scripts/_measure/output_reread.py +629 -0
- package/skills/token-optimizer/scripts/_measure/own_price_card.py +268 -0
- package/skills/token-optimizer/scripts/_measure/periphery_exposure.py +85 -0
- package/skills/token-optimizer/scripts/_measure/pricing.py +152 -87
- package/skills/token-optimizer/scripts/_measure/quality_archive.py +159 -215
- package/skills/token-optimizer/scripts/_measure/quality_checkpoint.py +173 -0
- package/skills/token-optimizer/scripts/_measure/quality_continuity.py +43 -0
- package/skills/token-optimizer/scripts/_measure/rework_metrics.py +194 -0
- package/skills/token-optimizer/scripts/_measure/routing_period.py +48 -0
- package/skills/token-optimizer/scripts/_measure/savings.py +431 -863
- package/skills/token-optimizer/scripts/_measure/savings_story.py +187 -0
- package/skills/token-optimizer/scripts/_measure/session_best.py +24 -0
- package/skills/token-optimizer/scripts/_measure/session_effect.py +557 -0
- package/skills/token-optimizer/scripts/_measure/session_flush_lock.py +75 -0
- package/skills/token-optimizer/scripts/_measure/session_store_spool.py +220 -0
- package/skills/token-optimizer/scripts/_measure/sessions.py +96 -196
- package/skills/token-optimizer/scripts/_measure/setup_attachment_counter.py +196 -0
- package/skills/token-optimizer/scripts/_measure/setup_budget_monitor.py +180 -0
- package/skills/token-optimizer/scripts/_measure/setup_connector_ledger.py +126 -0
- package/skills/token-optimizer/scripts/_measure/setup_step.py +220 -0
- package/skills/token-optimizer/scripts/_measure/status_bar_lock.py +117 -0
- package/skills/token-optimizer/scripts/_measure/structural_archives.py +79 -0
- package/skills/token-optimizer/scripts/_measure/structural_dedupe.py +91 -0
- package/skills/token-optimizer/scripts/_measure/structural_ledger.py +418 -0
- package/skills/token-optimizer/scripts/_measure/structural_listing.py +163 -0
- package/skills/token-optimizer/scripts/_measure/structural_report.py +339 -0
- package/skills/token-optimizer/scripts/_measure/structural_seed.py +164 -0
- package/skills/token-optimizer/scripts/_measure/structural_value.py +248 -0
- package/skills/token-optimizer/scripts/_measure/structure_funnel.py +97 -0
- package/skills/token-optimizer/scripts/_measure/timestamp_cache.py +11 -0
- package/skills/token-optimizer/scripts/_measure/token_type_split.py +29 -0
- package/skills/token-optimizer/scripts/_measure/transcript_backfill.py +419 -0
- package/skills/token-optimizer/scripts/_measure/transcript_product.py +228 -0
- package/skills/token-optimizer/scripts/_measure/transcript_stream.py +279 -0
- package/skills/token-optimizer/scripts/_measure/trends.py +44 -185
- package/skills/token-optimizer/scripts/_measure/ttl_period.py +6 -0
- package/skills/token-optimizer/scripts/_measure/upgrade_drain_control.py +287 -0
- package/skills/token-optimizer/scripts/activity_tracker.py +4 -33
- package/skills/token-optimizer/scripts/antigravity_install.py +2 -0
- package/skills/token-optimizer/scripts/archive_result.py +15 -19
- package/skills/token-optimizer/scripts/archive_verify.py +165 -0
- package/skills/token-optimizer/scripts/bash_compress.py +14 -43
- package/skills/token-optimizer/scripts/bash_compress_hook.py +132 -2
- package/skills/token-optimizer/scripts/checkpoint_state.py +2 -2
- package/skills/token-optimizer/scripts/cloud_kit.py +3 -6
- package/skills/token-optimizer/scripts/codemap.py +274 -0
- package/skills/token-optimizer/scripts/codemap_hint.py +153 -0
- package/skills/token-optimizer/scripts/codemap_index.py +656 -0
- package/skills/token-optimizer/scripts/codemap_ledger.py +309 -0
- package/skills/token-optimizer/scripts/codemap_reread.py +161 -0
- package/skills/token-optimizer/scripts/codex_doctor.py +9 -1
- package/skills/token-optimizer/scripts/codex_log_index.py +34 -15
- package/skills/token-optimizer/scripts/codex_session.py +16 -216
- package/skills/token-optimizer/scripts/compression_backfill.py +4 -35
- package/skills/token-optimizer/scripts/context_intel.py +5 -3
- package/skills/token-optimizer/scripts/copilot_install.py +2 -0
- package/skills/token-optimizer/scripts/coverage_funnel.py +261 -0
- package/skills/token-optimizer/scripts/cursor_install.py +12 -0
- package/skills/token-optimizer/scripts/cursor_quality.py +16 -64
- package/skills/token-optimizer/scripts/dashboard_assets.py +21 -0
- package/skills/token-optimizer/scripts/deterministic_candidates.py +2 -10
- package/skills/token-optimizer/scripts/devin_source.py +8 -3
- package/skills/token-optimizer/scripts/devin_verify.py +7 -1
- package/skills/token-optimizer/scripts/grok_install.py +2 -0
- package/skills/token-optimizer/scripts/heal_report.py +7 -6
- package/skills/token-optimizer/scripts/hermes_doctor.py +9 -1
- package/skills/token-optimizer/scripts/hermes_install.py +7 -1
- package/skills/token-optimizer/scripts/hermes_session.py +14 -136
- package/skills/token-optimizer/scripts/hint_paths.py +21 -0
- package/skills/token-optimizer/scripts/holdout.py +136 -0
- package/skills/token-optimizer/scripts/hook_runtime.py +1 -0
- package/skills/token-optimizer/scripts/hook_skip_log.py +89 -0
- package/skills/token-optimizer/scripts/large_transcripts.py +31 -0
- package/skills/token-optimizer/scripts/lean_resume_carry.py +518 -0
- package/skills/token-optimizer/scripts/measure.py +34 -76
- package/skills/token-optimizer/scripts/post_run_classify.py +349 -0
- package/skills/token-optimizer/scripts/preserved_reinject.py +54 -0
- package/skills/token-optimizer/scripts/read_cache.py +99 -100
- package/skills/token-optimizer/scripts/reset_epoch.py +3 -3
- package/skills/token-optimizer/scripts/session_store.py +49 -99
- package/skills/token-optimizer/scripts/session_store_guard.py +75 -0
- package/skills/token-optimizer/scripts/settings_backup.py +379 -0
- package/skills/token-optimizer/scripts/shipped_hook_templates.py +1 -0
- package/skills/token-optimizer/scripts/statusline.js +1 -1
- package/skills/token-optimizer/scripts/structural.py +25 -0
- 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'),
|
|
@@ -463,7 +463,7 @@ process.stdin.on('end', () => {
|
|
|
463
463
|
// Keep the score's value-color (green/yellow/orange/red) regardless of
|
|
464
464
|
// staleness; the `~` prefix is the only stale indicator so the number
|
|
465
465
|
// stays readable. (Dimming the whole score made it barely visible.)
|
|
466
|
-
const tag = `ContextQ:${stale ? '~' : ''}${grade}(${score})`;
|
|
466
|
+
const tag = q.measured === false ? `ContextQ:~${score}` : `ContextQ:${stale ? '~' : ''}${grade}(${score})`;
|
|
467
467
|
if (score >= 85) {
|
|
468
468
|
qScore = `${SEP}\x1b[32m${tag}${RESET}`;
|
|
469
469
|
} else if (score >= 75) {
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Setup-trim ledger CLI (kept outside measure.py's frozen dispatch table).
|
|
3
|
+
|
|
4
|
+
python3 structural.py status [--days 30]
|
|
5
|
+
python3 structural.py tick [--force] snapshot now, open/close trims
|
|
6
|
+
python3 structural.py seed --backup-dir DIR [--skills-archive DIR]
|
|
7
|
+
[--commands-archive DIR] [--ts ISO] [--apply]
|
|
8
|
+
[--revert BATCH --apply] one-time past-audit import, dry run by default
|
|
9
|
+
python3 structural.py attest --tokens N --date ISO [--note TEXT] [--apply]
|
|
10
|
+
python3 structural.py whatif --tokens 5150,11550,15000 --date ISO
|
|
11
|
+
python3 structural.py close --id TRIM_ID [--reason TEXT]
|
|
12
|
+
"""
|
|
13
|
+
import os
|
|
14
|
+
import sys
|
|
15
|
+
|
|
16
|
+
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
|
17
|
+
|
|
18
|
+
import measure # noqa: E402 (binds the facade the helpers resolve through)
|
|
19
|
+
from _measure import structural_report # noqa: E402
|
|
20
|
+
|
|
21
|
+
if __name__ == "__main__":
|
|
22
|
+
if measure._is_foreign_runtime():
|
|
23
|
+
print("structural: Claude Code setups only", file=sys.stderr)
|
|
24
|
+
sys.exit(2)
|
|
25
|
+
sys.exit(structural_report.cli(sys.argv[1:]))
|
|
@@ -2745,33 +2745,11 @@ def build_periphery_skeleton(
|
|
|
2745
2745
|
*,
|
|
2746
2746
|
limit: int = PERIPHERY_MAX_FILES,
|
|
2747
2747
|
budget: int = PERIPHERY_BUDGET_CHARS,
|
|
2748
|
+
shown_paths: Optional[list] = None,
|
|
2748
2749
|
) -> str:
|
|
2749
|
-
"""Build
|
|
2750
|
-
|
|
2751
|
-
|
|
2752
|
-
and ``limit`` files. Returns ``""`` when nothing fits or no paths resolve.
|
|
2753
|
-
Never raises.
|
|
2754
|
-
"""
|
|
2755
|
-
parts: List[str] = []
|
|
2756
|
-
total = 0
|
|
2757
|
-
count = 0
|
|
2758
|
-
for raw in related_paths:
|
|
2759
|
-
if count >= limit or total >= budget:
|
|
2760
|
-
break
|
|
2761
|
-
p = Path(raw)
|
|
2762
|
-
try:
|
|
2763
|
-
result = summarize_code_file(p)
|
|
2764
|
-
except Exception:
|
|
2765
|
-
continue
|
|
2766
|
-
if not result.replacement_text:
|
|
2767
|
-
continue
|
|
2768
|
-
chunk = f"# periphery: {p.name} ({result.replacement_type})\n{result.replacement_text}"
|
|
2769
|
-
if total + len(chunk) > budget:
|
|
2770
|
-
break
|
|
2771
|
-
parts.append(chunk)
|
|
2772
|
-
total += len(chunk)
|
|
2773
|
-
count += 1
|
|
2774
|
-
return "\n\n".join(parts)
|
|
2750
|
+
"""Build bounded periphery maps and optionally record included paths."""
|
|
2751
|
+
from _measure.periphery_exposure import build
|
|
2752
|
+
return build(related_paths, limit, budget, summarize_code_file, shown_paths)
|
|
2775
2753
|
|
|
2776
2754
|
|
|
2777
2755
|
# ---------------------------------------------------------------------------
|