@alexgreensh/token-optimizer 5.13.75 → 5.13.76
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/hooks/module_runner.py +1 -1
- package/hooks/posttooluse_runner.py +7 -9
- package/hooks/run.py +5 -1
- package/hooks/stop_runner.py +15 -56
- package/hooks/userpromptsubmit_runner.py +29 -4
- package/package.json +1 -1
- package/skills/token-optimizer/assets/dashboard.html +30 -14
- package/skills/token-optimizer/assets/savings_story.js +103 -27
- package/skills/token-optimizer/references/agent-prompts.md +2 -0
- package/skills/token-optimizer/references/implementation-playbook.md +1 -0
- package/skills/token-optimizer/scripts/_measure/__init__.py +1 -1
- package/skills/token-optimizer/scripts/_measure/apply_safe.py +512 -0
- package/skills/token-optimizer/scripts/_measure/audit.py +9 -20
- package/skills/token-optimizer/scripts/_measure/autocompact_advice.py +455 -0
- package/skills/token-optimizer/scripts/_measure/cache_policy.py +82 -127
- package/skills/token-optimizer/scripts/_measure/cli.py +10 -24
- package/skills/token-optimizer/scripts/_measure/cold_guard.py +777 -0
- package/skills/token-optimizer/scripts/_measure/continuity.py +45 -4
- package/skills/token-optimizer/scripts/_measure/counted_closes.py +398 -0
- package/skills/token-optimizer/scripts/_measure/counted_headline.py +112 -0
- package/skills/token-optimizer/scripts/_measure/dashboard.py +14 -6
- package/skills/token-optimizer/scripts/_measure/feature_health.py +6 -0
- package/skills/token-optimizer/scripts/_measure/keepwarm_auto.py +452 -0
- package/skills/token-optimizer/scripts/_measure/keepwarm_economics.py +8 -4
- package/skills/token-optimizer/scripts/_measure/keepwarm_safety.py +548 -24
- package/skills/token-optimizer/scripts/_measure/limit_units.py +463 -0
- package/skills/token-optimizer/scripts/_measure/local_adapt.py +192 -0
- package/skills/token-optimizer/scripts/_measure/mod_action_booking.py +71 -14
- package/skills/token-optimizer/scripts/_measure/next_actions.py +420 -0
- package/skills/token-optimizer/scripts/_measure/poc_commands.py +44 -0
- package/skills/token-optimizer/scripts/_measure/prefix_cost.py +215 -0
- package/skills/token-optimizer/scripts/_measure/pt_resume_cues.py +46 -0
- package/skills/token-optimizer/scripts/_measure/quality_archive.py +7 -10
- package/skills/token-optimizer/scripts/_measure/savings.py +75 -81
- package/skills/token-optimizer/scripts/_measure/savings_headline.py +17 -21
- package/skills/token-optimizer/scripts/_measure/savings_story.py +8 -1
- package/skills/token-optimizer/scripts/_measure/session_store_spool.py +119 -78
- package/skills/token-optimizer/scripts/_measure/status_bar_refresh.py +38 -3
- package/skills/token-optimizer/scripts/_measure/structural_ledger.py +1 -1
- package/skills/token-optimizer/scripts/_measure/subscription_audits.py +725 -0
- package/skills/token-optimizer/scripts/_measure/transcript_backfill.py +1 -1
- package/skills/token-optimizer/scripts/_measure/transcript_stream.py +8 -2
- package/skills/token-optimizer/scripts/antigravity_install.py +3 -0
- package/skills/token-optimizer/scripts/archive_result.py +16 -28
- package/skills/token-optimizer/scripts/archive_verify.py +1 -1
- package/skills/token-optimizer/scripts/bash_compress.py +156 -176
- package/skills/token-optimizer/scripts/bash_compress_hook.py +218 -174
- package/skills/token-optimizer/scripts/bash_search_results.py +189 -9
- package/skills/token-optimizer/scripts/bash_whitelist.py +6 -1
- package/skills/token-optimizer/scripts/benchmark.py +11 -13
- package/skills/token-optimizer/scripts/big_noncode_read.py +998 -0
- package/skills/token-optimizer/scripts/build_output_compress.py +103 -8
- package/skills/token-optimizer/scripts/builtin_tool_compress.py +716 -0
- package/skills/token-optimizer/scripts/cloud_kit.py +1 -1
- package/skills/token-optimizer/scripts/codex_doctor.py +1 -1
- package/skills/token-optimizer/scripts/command_compress_extra.py +955 -0
- package/skills/token-optimizer/scripts/compact_markers.py +129 -0
- package/skills/token-optimizer/scripts/copilot_install.py +3 -0
- package/skills/token-optimizer/scripts/cursor_install.py +7 -0
- package/skills/token-optimizer/scripts/devin_source.py +5 -5
- package/skills/token-optimizer/scripts/emit_safety_gate.py +518 -0
- package/skills/token-optimizer/scripts/fixtures/b2_more_commands.json +142 -0
- package/skills/token-optimizer/scripts/fixtures/b5_more_savings.json +26 -0
- package/skills/token-optimizer/scripts/fixtures/builtin_tools.json +103 -0
- package/skills/token-optimizer/scripts/fixtures/c7_review_ratchet.json +52 -0
- package/skills/token-optimizer/scripts/fixtures/large_output_policy.json +55 -0
- package/skills/token-optimizer/scripts/go_cargo_test_compress.py +493 -0
- package/skills/token-optimizer/scripts/grok_install.py +3 -0
- package/skills/token-optimizer/scripts/hermes_doctor.py +4 -1
- package/skills/token-optimizer/scripts/hermes_install.py +10 -1
- package/skills/token-optimizer/scripts/hook_fastpath.py +94 -0
- package/skills/token-optimizer/scripts/hook_runtime.py +6 -2
- package/skills/token-optimizer/scripts/large_output_policy.py +431 -0
- package/skills/token-optimizer/scripts/measure.py +10 -12
- package/skills/token-optimizer/scripts/pipe_file_compress.py +900 -0
- package/skills/token-optimizer/scripts/pipeline_analyzer.py +15 -1
- package/skills/token-optimizer/scripts/post_run_classify.py +2 -2
- package/skills/token-optimizer/scripts/preserved_reinject.py +20 -3
- package/skills/token-optimizer/scripts/process_identity.py +66 -0
- package/skills/token-optimizer/scripts/read_cache.py +51 -60
- package/skills/token-optimizer/scripts/statusline.js +21 -3
- package/skills/token-optimizer/scripts/visibility_rule.py +536 -0
|
@@ -0,0 +1,512 @@
|
|
|
1
|
+
"""Lane B: apply safe savings."""
|
|
2
|
+
import hashlib
|
|
3
|
+
import hmac
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
import argparse
|
|
7
|
+
import sys
|
|
8
|
+
import tempfile
|
|
9
|
+
import uuid
|
|
10
|
+
from datetime import datetime, timedelta
|
|
11
|
+
|
|
12
|
+
from . import autocompact_advice, limit_units, prefix_cost, structural_ledger, transcript_product
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _old_enough(path):
|
|
16
|
+
try:
|
|
17
|
+
return path.lstat().st_mtime <= (datetime.now() - timedelta(days=30)).timestamp()
|
|
18
|
+
except OSError:
|
|
19
|
+
return False
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _price_prefix(facade, activity, tokens):
|
|
23
|
+
total = 0.0
|
|
24
|
+
for model, count in activity['requests_by_model'].items():
|
|
25
|
+
card = limit_units._resolve_card(facade, model)
|
|
26
|
+
if not card or card.get('cache_read') is None or card.get('input') is None:
|
|
27
|
+
return None
|
|
28
|
+
write = card.get('cache_write_1h', card['input'] * 2)
|
|
29
|
+
total += tokens * (count * card['cache_read'] + activity['writes_events_by_model'].get(model, 0) * write) / 1000000
|
|
30
|
+
return total if activity['requests_by_model'] else None
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _live_usage(facade, cutoff):
|
|
34
|
+
"""Check current transcripts too, so an outdated database cannot hide a use."""
|
|
35
|
+
used, tools = set(), set()
|
|
36
|
+
files = facade._find_all_jsonl_files(days=30)
|
|
37
|
+
if not files:
|
|
38
|
+
return None
|
|
39
|
+
for path, _, _ in files:
|
|
40
|
+
for transcript in [path, *facade._find_subagent_jsonl_files(path)]:
|
|
41
|
+
parsed = facade._parse_session_jsonl(transcript)
|
|
42
|
+
if not isinstance(parsed, dict) or not isinstance(parsed.get('daily_metrics'), dict):
|
|
43
|
+
return None
|
|
44
|
+
for field, target in (('skills_used', used), ('tool_calls', tools)):
|
|
45
|
+
lifetime = parsed.get(field) or {}
|
|
46
|
+
if not isinstance(lifetime, dict):
|
|
47
|
+
return None
|
|
48
|
+
target.update(name for name, count in lifetime.items() if count)
|
|
49
|
+
for day, metrics in parsed['daily_metrics'].items():
|
|
50
|
+
if day < cutoff:
|
|
51
|
+
continue
|
|
52
|
+
if not isinstance(metrics, dict) or not isinstance(metrics.get('skills'), dict) or not isinstance(metrics.get('tool_calls'), dict):
|
|
53
|
+
return None
|
|
54
|
+
used.update(name for name, count in metrics['skills'].items() if count)
|
|
55
|
+
tools.update(name for name, count in metrics['tool_calls'].items() if count)
|
|
56
|
+
return used, tools
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def build_plan(facade):
|
|
60
|
+
"""Build an advisory plan using only locally recorded evidence."""
|
|
61
|
+
now = datetime.now()
|
|
62
|
+
items = []
|
|
63
|
+
components = facade.measure_components()
|
|
64
|
+
management = facade._collect_management_data(components=components)
|
|
65
|
+
conn = facade._open_trends_db_readonly(timeout=1.0)
|
|
66
|
+
try:
|
|
67
|
+
activity = prefix_cost._ledger_activity(facade, conn, 30)
|
|
68
|
+
cutoff = (now - timedelta(days=30)).date().isoformat()
|
|
69
|
+
used = {row[0] for row in conn.execute('SELECT DISTINCT skill FROM skill_daily WHERE date >= ? AND invocations > 0', (cutoff,))}
|
|
70
|
+
metrics = conn.execute('SELECT daily_metrics_json FROM session_log WHERE COALESCE(last_activity_day,date) >= ?', (cutoff,)).fetchall()
|
|
71
|
+
tools = set()
|
|
72
|
+
tools_known = bool(metrics)
|
|
73
|
+
for (raw,) in metrics:
|
|
74
|
+
try:
|
|
75
|
+
days = json.loads(raw)
|
|
76
|
+
if not isinstance(days, dict):
|
|
77
|
+
raise ValueError('missing metrics')
|
|
78
|
+
for day, values in days.items():
|
|
79
|
+
if day >= cutoff:
|
|
80
|
+
if not isinstance(values, dict) or not isinstance(values.get('tool_calls'), dict):
|
|
81
|
+
raise ValueError('missing tool calls')
|
|
82
|
+
tools.update(name for name, count in values['tool_calls'].items() if count)
|
|
83
|
+
except (ValueError, TypeError, AttributeError):
|
|
84
|
+
tools_known = False
|
|
85
|
+
finally:
|
|
86
|
+
conn.close()
|
|
87
|
+
|
|
88
|
+
live = _live_usage(facade, cutoff)
|
|
89
|
+
if live is None:
|
|
90
|
+
used = set((components.get('skills') or {}).get('names') or ())
|
|
91
|
+
tools_known = False
|
|
92
|
+
else:
|
|
93
|
+
used.update(live[0])
|
|
94
|
+
tools.update(live[1])
|
|
95
|
+
|
|
96
|
+
skill_info = components.get('skills') or {}
|
|
97
|
+
observations = transcript_product.from_facade(facade, days=30)
|
|
98
|
+
listing_eligible = not observations.get('incomplete') and (observations.get('listing') or {}).get('at_cap') is False
|
|
99
|
+
aliases = skill_info.get('name_to_dir') or {}
|
|
100
|
+
used_dirs = set()
|
|
101
|
+
for name in used:
|
|
102
|
+
if isinstance(name, str):
|
|
103
|
+
for part in (name, *name.split(':')):
|
|
104
|
+
used_dirs.add(part)
|
|
105
|
+
used_dirs.add(aliases.get(part, part))
|
|
106
|
+
plugin_names = {name.split(':', 1)[-1] for name in (components.get('plugin_skills') or {}).get('names', [])}
|
|
107
|
+
details = components.get('skills_detail') or {}
|
|
108
|
+
inventory = []
|
|
109
|
+
for name in (skill_info.get('names') or []) if listing_eligible else ():
|
|
110
|
+
if not isinstance(name, str) or not name or '/' in name or '\\' in name or name in ('.', '..'):
|
|
111
|
+
continue
|
|
112
|
+
path = facade.CLAUDE_DIR / 'skills' / name
|
|
113
|
+
if not path.is_dir() or not _old_enough(path) or name in used_dirs:
|
|
114
|
+
continue
|
|
115
|
+
tokens = int((details.get(name) or {}).get('frontmatter_tokens') or 0)
|
|
116
|
+
if tokens <= 0:
|
|
117
|
+
continue
|
|
118
|
+
duplicate = name in plugin_names and (path.is_symlink() or not [p for p in path.iterdir() if p.name != 'SKILL.md' and not p.name.startswith('.')])
|
|
119
|
+
inventory.append({'name': name, 'kind': 'skill', 'tokens': tokens, 'uses': 0, 'duplicate': duplicate})
|
|
120
|
+
settings_old = _old_enough(facade.SETTINGS_PATH)
|
|
121
|
+
if tools_known and settings_old:
|
|
122
|
+
connector_rows = {transcript_product._normalize(item['server']): item for item in observations.get('unused_connectors', []) if item.get('server')}
|
|
123
|
+
for server in (management.get('mcp_servers') or {}).get('active', []):
|
|
124
|
+
name = server.get('name')
|
|
125
|
+
normalized = lambda text: ''.join(ch.lower() for ch in text if ch.isalnum())
|
|
126
|
+
called = any(tool.startswith('mcp__') and normalized(tool.split('__', 2)[1]) == normalized(name) for tool in tools if isinstance(tool, str) and isinstance(name, str))
|
|
127
|
+
observed = connector_rows.get(transcript_product._normalize(name)) if isinstance(name, str) else None
|
|
128
|
+
tokens = int((observed or {}).get('estimated_tokens_per_call') or 0)
|
|
129
|
+
if name and tokens > 0 and not called and not observations.get('incomplete'):
|
|
130
|
+
inventory.append({'name': name, 'kind': 'mcp_server', 'tokens': tokens, 'uses': 0})
|
|
131
|
+
conn = facade._open_trends_db_readonly(timeout=1.0)
|
|
132
|
+
try:
|
|
133
|
+
report = prefix_cost.prefix_cost_report(facade, conn, days=30, inventory=inventory)
|
|
134
|
+
finally:
|
|
135
|
+
conn.close()
|
|
136
|
+
source_rows = {(row['kind'], row['name']): row for row in report['all_components']}
|
|
137
|
+
for row in inventory if activity['total_requests'] > 0 else ():
|
|
138
|
+
name, tokens = row['name'], row['tokens']
|
|
139
|
+
evidence = source_rows.get((row['kind'], name))
|
|
140
|
+
if not evidence or not evidence['unused_here']:
|
|
141
|
+
continue
|
|
142
|
+
tokens = evidence['tokens']
|
|
143
|
+
kind = ('duplicate_skill' if row.get('duplicate') else 'unused_skill') if row['kind'] == 'skill' else 'unused_mcp'
|
|
144
|
+
net = _price_prefix(facade, activity, tokens)
|
|
145
|
+
if net is not None and net <= 0:
|
|
146
|
+
continue
|
|
147
|
+
items.append({'id': kind + ':' + name, 'kind': kind, 'label': ('Archive skill ' if kind != 'unused_mcp' else 'Disable unused server ') + name,
|
|
148
|
+
'tokens_per_request': tokens, 'net_usd_month': net, 'own_cost_usd_month': 0.0,
|
|
149
|
+
'basis': '0 uses in 30 days; {} tokens on {} requests'.format(tokens, activity['total_requests']),
|
|
150
|
+
'undo': 'measure.py apply-safe --undo <receipt_id>', 'default_selected': True})
|
|
151
|
+
items.sort(key=lambda item: (('duplicate_skill', 'unused_skill', 'unused_mcp').index(item['kind']), item['id']))
|
|
152
|
+
advice = autocompact_advice.recommend(facade)
|
|
153
|
+
compact = autocompact_advice.plan_item(facade, advice) if advice and not advice.get('blocked') else None
|
|
154
|
+
if compact:
|
|
155
|
+
items.append(compact)
|
|
156
|
+
for module in ('cold_guard', 'keepwarm_auto'):
|
|
157
|
+
try:
|
|
158
|
+
from importlib import import_module
|
|
159
|
+
planner = getattr(import_module('.' + module, __package__), 'plan_item', None)
|
|
160
|
+
item = planner(facade) if callable(planner) else None
|
|
161
|
+
if isinstance(item, dict) and (item.get('net_usd_month') is None or float(item['net_usd_month']) > 0):
|
|
162
|
+
items.append(item)
|
|
163
|
+
except Exception:
|
|
164
|
+
pass
|
|
165
|
+
return {'schema': 1, 'generated_at': now.isoformat(), 'window_days': 30, 'items': items, **({'advice': advice['text']} if advice and advice.get('blocked') else {}),
|
|
166
|
+
'total_net_usd_month': sum(float(i['net_usd_month']) for i in items if i.get('net_usd_month') is not None),
|
|
167
|
+
'token': plan_token(items)}
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def plan_token(items):
|
|
171
|
+
"""Bind approval to the actions, settings and displayed dollar precision."""
|
|
172
|
+
fields = ('id', 'kind', 'tokens_per_request', 'model', 'per_model', 'current', 'target')
|
|
173
|
+
selected = []
|
|
174
|
+
for item in items:
|
|
175
|
+
entry = {key: item.get(key) for key in fields}
|
|
176
|
+
for key in ('net_usd_month', 'own_cost_usd_month'):
|
|
177
|
+
amount = item.get(key)
|
|
178
|
+
entry[key] = round(float(amount), 2) if amount is not None else None
|
|
179
|
+
selected.append(entry)
|
|
180
|
+
payload = json.dumps(sorted(selected, key=lambda item: item['id']), sort_keys=True, separators=(',', ':'), allow_nan=False)
|
|
181
|
+
return hashlib.sha256(payload.encode()).hexdigest()
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def validate_token(facade, selected_ids, token):
|
|
185
|
+
"""Rebuild the plan and reject absent, changed, or duplicated selections."""
|
|
186
|
+
if not isinstance(token, str) or not isinstance(selected_ids, (list, tuple)) or not selected_ids or len(set(selected_ids)) != len(selected_ids):
|
|
187
|
+
return False
|
|
188
|
+
try:
|
|
189
|
+
items = build_plan(facade)['items']
|
|
190
|
+
selected = [item for item in items if item['id'] in selected_ids]
|
|
191
|
+
return len(selected) == len(selected_ids) and hmac.compare_digest(token, plan_token(selected))
|
|
192
|
+
except (ValueError, TypeError, KeyError, NameError, AttributeError):
|
|
193
|
+
return False
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def _append_receipt(facade, receipt):
|
|
197
|
+
path = facade.SNAPSHOT_DIR / 'apply_safe_receipts.jsonl'
|
|
198
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
199
|
+
flags = os.O_WRONLY | os.O_CREAT | os.O_APPEND | getattr(os, 'O_NOFOLLOW', 0)
|
|
200
|
+
flags |= getattr(os, 'O_BINARY', 0)
|
|
201
|
+
fd = os.open(path, flags, 0o600)
|
|
202
|
+
try:
|
|
203
|
+
if hasattr(os, 'fchmod'):
|
|
204
|
+
os.fchmod(fd, 0o600)
|
|
205
|
+
data = (json.dumps(receipt, sort_keys=True) + '\n').encode()
|
|
206
|
+
if os.write(fd, data) != len(data):
|
|
207
|
+
raise OSError('incomplete receipt')
|
|
208
|
+
os.fsync(fd)
|
|
209
|
+
finally:
|
|
210
|
+
os.close(fd)
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def _archive_paths(facade, name):
|
|
214
|
+
parent = facade.CLAUDE_DIR / '_backups'
|
|
215
|
+
try:
|
|
216
|
+
return {str(p / name) for p in parent.iterdir() if p.is_dir() and p.name.startswith(facade.SKILL_ARCHIVE_DIR_PREFIXES) and ((p / name).exists() or (p / name).is_symlink())}
|
|
217
|
+
except OSError:
|
|
218
|
+
return set()
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def _intent(facade, item):
|
|
222
|
+
ident, kind = item['id'], item['kind']
|
|
223
|
+
name = ident.split(':', 1)[1] if ':' in ident else ''
|
|
224
|
+
row = {'id': ident, 'kind': kind, 'ok': True}
|
|
225
|
+
if kind in ('duplicate_skill', 'unused_skill'):
|
|
226
|
+
row.update(undo_action='restore', archives_before=sorted(_archive_paths(facade, name)))
|
|
227
|
+
elif kind == 'unused_mcp':
|
|
228
|
+
row['undo_action'] = 'enable'
|
|
229
|
+
elif kind in ('cold_guard', 'keepwarm_auto'):
|
|
230
|
+
from importlib import import_module
|
|
231
|
+
module = import_module('.' + kind, __package__)
|
|
232
|
+
before = module._configured_mode(facade) if kind == 'cold_guard' else facade._read_config_flag('keepwarm_auto', False)
|
|
233
|
+
after = 'ask' if kind == 'cold_guard' else True
|
|
234
|
+
row.update(undo_action='lane', lane_result={'before': before, 'after': after})
|
|
235
|
+
return row
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def apply(facade, plan, selected_ids, token):
|
|
239
|
+
"""Apply an approved fresh plan, recording each result without double credit."""
|
|
240
|
+
if facade._is_foreign_runtime():
|
|
241
|
+
return {'ok': False, 'error': 'This runtime cannot modify these settings.'}
|
|
242
|
+
if not validate_token(facade, selected_ids, token):
|
|
243
|
+
return {'ok': False, 'error': 'Your setup changed since the plan was shown. Run it again.'}
|
|
244
|
+
fresh = build_plan(facade)
|
|
245
|
+
by_id = {item['id']: item for item in fresh['items']}
|
|
246
|
+
try:
|
|
247
|
+
selected = [by_id[ident] for ident in selected_ids]
|
|
248
|
+
if not hmac.compare_digest(token, plan_token(selected)):
|
|
249
|
+
raise ValueError('stale')
|
|
250
|
+
except (KeyError, ValueError, TypeError):
|
|
251
|
+
return {'ok': False, 'error': 'Your setup changed since the plan was shown. Run it again.'}
|
|
252
|
+
receipt_id = uuid.uuid4().hex
|
|
253
|
+
backup = facade._backup_settings_file(facade.SNAPSHOT_DIR / 'apply-safe-backups')
|
|
254
|
+
if not backup:
|
|
255
|
+
return {'ok': False, 'error': 'Settings backup failed. Nothing was changed.'}
|
|
256
|
+
receipt = {'receipt_id': receipt_id, 'ts': datetime.now().isoformat(), 'items': [], 'backup_path': str(backup)}
|
|
257
|
+
try:
|
|
258
|
+
_append_receipt(facade, dict(receipt, status='pending', selected_ids=selected_ids))
|
|
259
|
+
except OSError:
|
|
260
|
+
return {'ok': False, 'error': 'Receipt could not be written. Nothing was changed.'}
|
|
261
|
+
duplicates = [item for item in selected if item['kind'] == 'duplicate_skill']
|
|
262
|
+
duplicate_results = set()
|
|
263
|
+
prior_trims = {trim['id'] for trim in structural_ledger.load_trims(facade.SNAPSHOT_DIR)}
|
|
264
|
+
before_archives = {item['id']: _archive_paths(facade, item['id'].split(':', 1)[1]) for item in duplicates}
|
|
265
|
+
if duplicates:
|
|
266
|
+
try:
|
|
267
|
+
for item in duplicates:
|
|
268
|
+
_append_receipt(facade, {'receipt_id': receipt_id, 'status': 'intent', 'item': _intent(facade, item)})
|
|
269
|
+
result = facade.plugin_cleanup(dry_run=False, quiet=True,
|
|
270
|
+
selected_items={item['id'].split(':', 1)[1] for item in duplicates}, plan_token=token, selected_ids=selected_ids)
|
|
271
|
+
duplicate_results = {line.removeprefix('archived duplicate local skill: ') for line in result if line.startswith('archived duplicate local skill: ')}
|
|
272
|
+
except Exception:
|
|
273
|
+
pass
|
|
274
|
+
for item in selected:
|
|
275
|
+
ident, kind = item['id'], item['kind']
|
|
276
|
+
name = ident.split(':', 1)[1] if ':' in ident else ''
|
|
277
|
+
row = {'id': ident, 'kind': kind, 'undo_action': None, 'before': None, 'after': None, 'ok': False}
|
|
278
|
+
previous_archives = before_archives.get(ident, _archive_paths(facade, name)) if kind in ('duplicate_skill', 'unused_skill') else set()
|
|
279
|
+
try:
|
|
280
|
+
if kind not in ('duplicate_skill', 'autocompact_window'):
|
|
281
|
+
_append_receipt(facade, {'receipt_id': receipt_id, 'status': 'intent', 'item': _intent(facade, item)})
|
|
282
|
+
if kind == 'duplicate_skill':
|
|
283
|
+
row.update(ok=name in duplicate_results, undo_action='restore', before=name, after=name)
|
|
284
|
+
elif kind == 'unused_skill':
|
|
285
|
+
row.update(undo_action='restore', before=name, after=name)
|
|
286
|
+
row['ok'] = bool(facade._manage_skill('archive', name))
|
|
287
|
+
elif kind == 'unused_mcp':
|
|
288
|
+
row.update(ok=bool(facade._manage_mcp('disable', name)), undo_action='enable', before=name, after=name)
|
|
289
|
+
if row['ok']:
|
|
290
|
+
row['applied'] = True
|
|
291
|
+
trim = structural_ledger.make_trim('mcp_tools', name, 'global', item['tokens_per_request'], 0,
|
|
292
|
+
structural_ledger.now_iso(), 'apply_safe', evidence=str(backup))
|
|
293
|
+
if not structural_ledger.record_trim(facade.SNAPSHOT_DIR, trim):
|
|
294
|
+
raise RuntimeError('trim not recorded')
|
|
295
|
+
row['trim_id'] = trim['id']
|
|
296
|
+
elif kind == 'autocompact_window':
|
|
297
|
+
def record_window(setting):
|
|
298
|
+
intent = {'id': ident, 'kind': kind, 'ok': True,
|
|
299
|
+
'undo_action': 'restore_window', 'setting': setting}
|
|
300
|
+
_append_receipt(facade, {'receipt_id': receipt_id, 'status': 'intent', 'item': intent})
|
|
301
|
+
result = autocompact_advice.apply_item(facade, item, before_write=record_window)
|
|
302
|
+
row.update(ok=bool(result.get('ok')), undo_action='restore_window', before=result.get('before'), after=result.get('after'), setting=result, main_model=item.get('model'), previous_window=item.get('current'), applied_at=datetime.now().isoformat())
|
|
303
|
+
elif kind in ('cold_guard', 'keepwarm_auto'):
|
|
304
|
+
from importlib import import_module
|
|
305
|
+
module = import_module('.' + kind, __package__)
|
|
306
|
+
result = module.apply_item(facade, item)
|
|
307
|
+
row.update(ok=bool(result.get('ok')), undo_action='lane', before=result.get('before'), after=result.get('after'), lane_result=result)
|
|
308
|
+
except Exception as exc:
|
|
309
|
+
row['ok'] = False
|
|
310
|
+
row['error'] = type(exc).__name__
|
|
311
|
+
if kind in ('duplicate_skill', 'unused_skill'):
|
|
312
|
+
added = _archive_paths(facade, name) - previous_archives
|
|
313
|
+
source = facade.CLAUDE_DIR / 'skills' / name
|
|
314
|
+
if len(added) == 1 and not source.exists() and not source.is_symlink():
|
|
315
|
+
row.update(applied=True, archive=added.pop())
|
|
316
|
+
new_trims = [trim for trim in structural_ledger.load_trims(facade.SNAPSHOT_DIR)
|
|
317
|
+
if trim['id'] not in prior_trims and trim.get('component') == 'skills' and trim.get('item') == name]
|
|
318
|
+
if len(new_trims) != 1:
|
|
319
|
+
row.update(ok=False, error='structural-trim-not-verified')
|
|
320
|
+
elif row['ok']:
|
|
321
|
+
row.update(ok=False, error='archive-not-verified')
|
|
322
|
+
receipt['items'].append(row)
|
|
323
|
+
try:
|
|
324
|
+
_append_receipt(facade, {'receipt_id': receipt_id, 'status': 'item', 'item': row})
|
|
325
|
+
except OSError:
|
|
326
|
+
row['receipt_error'] = True
|
|
327
|
+
break
|
|
328
|
+
try:
|
|
329
|
+
receipt['settings_after_sha256'] = hashlib.sha256(facade.SETTINGS_PATH.read_bytes()).hexdigest()
|
|
330
|
+
_append_receipt(facade, dict(receipt, status='complete'))
|
|
331
|
+
except OSError:
|
|
332
|
+
return {'ok': False, 'error': 'Changes were made but the receipt could not be completed.', 'receipt': receipt}
|
|
333
|
+
return {'ok': all(row['ok'] for row in receipt['items']) and len(receipt['items']) == len(selected), 'receipt': receipt}
|
|
334
|
+
|
|
335
|
+
|
|
336
|
+
def _receipts(facade):
|
|
337
|
+
try:
|
|
338
|
+
lines = (facade.SNAPSHOT_DIR / 'apply_safe_receipts.jsonl').read_text(encoding='utf-8').splitlines()
|
|
339
|
+
except OSError:
|
|
340
|
+
return []
|
|
341
|
+
rows = []
|
|
342
|
+
for line in lines:
|
|
343
|
+
try:
|
|
344
|
+
row = json.loads(line)
|
|
345
|
+
if isinstance(row, dict):
|
|
346
|
+
rows.append(row)
|
|
347
|
+
except ValueError:
|
|
348
|
+
continue
|
|
349
|
+
return rows
|
|
350
|
+
|
|
351
|
+
|
|
352
|
+
def _restore_settings_format(facade, backup):
|
|
353
|
+
"""Restore original bytes only when no other setting differs."""
|
|
354
|
+
original = backup.read_bytes()
|
|
355
|
+
original_data = json.loads(original)
|
|
356
|
+
with facade._settings_lock(user_initiated=True) as acquired:
|
|
357
|
+
if not acquired:
|
|
358
|
+
return False
|
|
359
|
+
path = facade.SETTINGS_PATH.resolve(strict=True)
|
|
360
|
+
current = path.read_bytes()
|
|
361
|
+
if json.loads(current) != original_data:
|
|
362
|
+
return True
|
|
363
|
+
mode = path.stat().st_mode & 0o777
|
|
364
|
+
fd, temp = tempfile.mkstemp(prefix='.apply-safe-', dir=path.parent)
|
|
365
|
+
try:
|
|
366
|
+
with os.fdopen(fd, 'wb') as out:
|
|
367
|
+
if hasattr(os, 'fchmod'):
|
|
368
|
+
os.fchmod(out.fileno(), mode)
|
|
369
|
+
out.write(original)
|
|
370
|
+
out.flush()
|
|
371
|
+
os.fsync(out.fileno())
|
|
372
|
+
if facade.SETTINGS_PATH.resolve(strict=True) != path or path.read_bytes() != current:
|
|
373
|
+
return False
|
|
374
|
+
os.replace(temp, path)
|
|
375
|
+
return True
|
|
376
|
+
finally:
|
|
377
|
+
if os.path.exists(temp):
|
|
378
|
+
os.unlink(temp)
|
|
379
|
+
|
|
380
|
+
|
|
381
|
+
def undo(facade, receipt_id):
|
|
382
|
+
if facade._is_foreign_runtime():
|
|
383
|
+
return {'ok': False, 'error': 'This runtime cannot modify these settings.'}
|
|
384
|
+
rows = _receipts(facade)
|
|
385
|
+
previous_undo = [row for row in rows if row.get('undo_of') == receipt_id]
|
|
386
|
+
if any(row.get('ok') for row in previous_undo):
|
|
387
|
+
return {'ok': False, 'error': 'This receipt was already undone.'}
|
|
388
|
+
already_restored = {item['id'] for row in previous_undo for item in row.get('items', []) if item.get('ok')}
|
|
389
|
+
receipt = next((row for row in reversed(rows) if row.get('receipt_id') == receipt_id and row.get('status') == 'complete'), None)
|
|
390
|
+
if not receipt:
|
|
391
|
+
pending = next((row for row in reversed(rows) if row.get('receipt_id') == receipt_id and row.get('status') == 'pending'), None)
|
|
392
|
+
if not pending:
|
|
393
|
+
return {'ok': False, 'error': 'Receipt not found.'}
|
|
394
|
+
entries = [row for row in rows if row.get('receipt_id') == receipt_id and row.get('status') in ('intent', 'item')]
|
|
395
|
+
by_id = {}
|
|
396
|
+
for entry in entries:
|
|
397
|
+
item = entry.get('item') or {}
|
|
398
|
+
if item.get('id'):
|
|
399
|
+
by_id[item['id']] = dict(item)
|
|
400
|
+
for item in by_id.values():
|
|
401
|
+
if 'archives_before' in item:
|
|
402
|
+
name = item['id'].split(':', 1)[1]
|
|
403
|
+
added = _archive_paths(facade, name) - set(item.pop('archives_before'))
|
|
404
|
+
if len(added) == 1:
|
|
405
|
+
item['archive'] = added.pop()
|
|
406
|
+
else:
|
|
407
|
+
item['ok'] = False
|
|
408
|
+
receipt = dict(pending, items=list(by_id.values()))
|
|
409
|
+
backup = facade.Path(receipt['backup_path'])
|
|
410
|
+
try:
|
|
411
|
+
backup.resolve().relative_to((facade.SNAPSHOT_DIR / 'apply-safe-backups').resolve())
|
|
412
|
+
original = json.loads(backup.read_text(encoding='utf-8'))
|
|
413
|
+
except (OSError, ValueError, TypeError):
|
|
414
|
+
return {'ok': False, 'error': 'Settings backup is unavailable.'}
|
|
415
|
+
results = []
|
|
416
|
+
for item in reversed(receipt['items']):
|
|
417
|
+
if not (item.get('ok') or item.get('applied')) or item['id'] in already_restored:
|
|
418
|
+
continue
|
|
419
|
+
ident, action = item['id'], item.get('undo_action')
|
|
420
|
+
name = ident.split(':', 1)[1] if ':' in ident else ''
|
|
421
|
+
ok = False
|
|
422
|
+
try:
|
|
423
|
+
if action == 'restore':
|
|
424
|
+
parent = facade.CLAUDE_DIR / '_backups'
|
|
425
|
+
candidates = sorted((p / name for p in parent.iterdir() if p.is_dir() and p.name.startswith(facade.SKILL_ARCHIVE_DIR_PREFIXES) and (p / name).exists()), reverse=True)
|
|
426
|
+
if candidates and str(candidates[0]) == item.get('archive'):
|
|
427
|
+
ok = bool(facade._manage_skill('restore', name))
|
|
428
|
+
elif action == 'enable':
|
|
429
|
+
current, valid = facade._read_settings_for_write()
|
|
430
|
+
old_config = (original.get('mcpServers') or {}).get(name)
|
|
431
|
+
disabled = (current.get('_disabledMcpServers') or {}).get(name)
|
|
432
|
+
if valid and old_config is not None and disabled == old_config and name not in (current.get('mcpServers') or {}):
|
|
433
|
+
ok = bool(facade._manage_mcp('enable', name))
|
|
434
|
+
elif action == 'restore_window':
|
|
435
|
+
ok = autocompact_advice.undo_item(facade, item.get('setting') or {})
|
|
436
|
+
elif action == 'lane':
|
|
437
|
+
from importlib import import_module
|
|
438
|
+
module = import_module('.' + item['kind'], __package__)
|
|
439
|
+
ok = bool(module.undo_item(facade, item.get('lane_result') or {}))
|
|
440
|
+
if ok and item.get('trim_id'):
|
|
441
|
+
structural_ledger.close_trim(facade.SNAPSHOT_DIR, item['trim_id'], structural_ledger.now_iso(), 'apply-safe undo')
|
|
442
|
+
except Exception:
|
|
443
|
+
ok = False
|
|
444
|
+
results.append({'id': ident, 'ok': ok})
|
|
445
|
+
try:
|
|
446
|
+
format_ok = _restore_settings_format(facade, backup) if all(row['ok'] for row in results) else False
|
|
447
|
+
result = {'receipt_id': uuid.uuid4().hex, 'undo_of': receipt_id, 'ts': datetime.now().isoformat(),
|
|
448
|
+
'items': results, 'ok': all(row['ok'] for row in results) and format_ok}
|
|
449
|
+
_append_receipt(facade, result)
|
|
450
|
+
return result
|
|
451
|
+
except (OSError, ValueError, TypeError):
|
|
452
|
+
return {'ok': False, 'error': 'Undo could not be fully recorded.', 'items': results}
|
|
453
|
+
|
|
454
|
+
|
|
455
|
+
def main(facade, args):
|
|
456
|
+
parser = argparse.ArgumentParser(prog='measure.py apply-safe')
|
|
457
|
+
parser.add_argument('--json', action='store_true')
|
|
458
|
+
parser.add_argument('--yes', action='store_true')
|
|
459
|
+
parser.add_argument('--token')
|
|
460
|
+
parser.add_argument('--only')
|
|
461
|
+
parser.add_argument('--undo')
|
|
462
|
+
parser.add_argument('--list', action='store_true')
|
|
463
|
+
options = parser.parse_args(args)
|
|
464
|
+
if options.list:
|
|
465
|
+
print(json.dumps(_receipts(facade), indent=2))
|
|
466
|
+
return 0
|
|
467
|
+
if options.undo:
|
|
468
|
+
result = undo(facade, options.undo)
|
|
469
|
+
print(json.dumps(result, indent=2))
|
|
470
|
+
return 0 if result.get('ok') else 1
|
|
471
|
+
try:
|
|
472
|
+
plan = build_plan(facade)
|
|
473
|
+
except Exception:
|
|
474
|
+
print('Could not build a safe plan from the available history.')
|
|
475
|
+
return 1
|
|
476
|
+
if options.only:
|
|
477
|
+
requested = options.only.split(',')
|
|
478
|
+
available = {item['id'] for item in plan['items']}
|
|
479
|
+
if len(requested) != len(set(requested)) or not set(requested) <= available:
|
|
480
|
+
print('One or more requested items are not in the current plan.')
|
|
481
|
+
return 1
|
|
482
|
+
plan['items'] = [item for item in plan['items'] if item['id'] in requested]
|
|
483
|
+
plan['total_net_usd_month'] = sum(float(item['net_usd_month']) for item in plan['items'] if item.get('net_usd_month') is not None)
|
|
484
|
+
plan['token'] = plan_token(plan['items'])
|
|
485
|
+
if options.json:
|
|
486
|
+
print(json.dumps(plan, indent=2))
|
|
487
|
+
else:
|
|
488
|
+
for item in plan['items']:
|
|
489
|
+
value = item.get('net_usd_month')
|
|
490
|
+
print('{}: {} ({})'.format(item['id'], item['label'], 'unpriced' if value is None else '${:.2f}/month'.format(value)))
|
|
491
|
+
if item.get('basis'):
|
|
492
|
+
print(' ' + str(item['basis']))
|
|
493
|
+
if plan.get('advice'):
|
|
494
|
+
print(plan['advice'])
|
|
495
|
+
print('Plan token: ' + plan['token'])
|
|
496
|
+
selected = [item['id'] for item in plan['items'] if item.get('default_selected', True)]
|
|
497
|
+
if not selected or (options.json and not options.yes):
|
|
498
|
+
return 0
|
|
499
|
+
if options.yes:
|
|
500
|
+
if not options.token:
|
|
501
|
+
print('--yes requires --token from the displayed plan.')
|
|
502
|
+
return 2
|
|
503
|
+
token = options.token
|
|
504
|
+
else:
|
|
505
|
+
if not sys.stdin.isatty():
|
|
506
|
+
return 0
|
|
507
|
+
if input('Apply these {} changes? [y/N] '.format(len(selected))).strip().lower() != 'y':
|
|
508
|
+
return 0
|
|
509
|
+
token = plan_token([item for item in plan['items'] if item['id'] in selected])
|
|
510
|
+
result = apply(facade, plan, selected, token)
|
|
511
|
+
print(json.dumps(result, indent=2))
|
|
512
|
+
return 0 if result.get('ok') else 1
|
|
@@ -4128,6 +4128,9 @@ def _generate_codex_auto_recommendations(components, trends=None, days=None):
|
|
|
4128
4128
|
"Session continuity is valuable inside a task, but stale tool outputs and old plans hurt quality. Use a new thread or compact/checkpoint when the objective changes."
|
|
4129
4129
|
)
|
|
4130
4130
|
|
|
4131
|
+
from . import subscription_audits as _sub_audits
|
|
4132
|
+
_sub_audits.append_codex_recommendations(components, trends, quick, medium, deep, habits, _measure_facade)
|
|
4133
|
+
|
|
4131
4134
|
sections = []
|
|
4132
4135
|
if quick:
|
|
4133
4136
|
sections.append("## Quick Wins\n\n" + "\n\n".join(f"- [ ] {item}" for item in quick))
|
|
@@ -4703,19 +4706,9 @@ def generate_auto_recommendations(components, trends=None, days=None):
|
|
|
4703
4706
|
f"This prevents cloud MCPs from loading in CLI sessions while keeping them on claude.ai."
|
|
4704
4707
|
)
|
|
4705
4708
|
|
|
4706
|
-
# --- Rule 16
|
|
4707
|
-
|
|
4708
|
-
|
|
4709
|
-
if effort_level and str(effort_level).lower() == "high":
|
|
4710
|
-
habits.append(
|
|
4711
|
-
"**`effortLevel` is set to \"high\" (FYI)**: "
|
|
4712
|
-
"Your settings.json has `effortLevel: \"high\"`. This maximizes response quality "
|
|
4713
|
-
"and thinking depth. If you chose this deliberately, no action needed, "
|
|
4714
|
-
"the optimizer respects your model and effort choices.\n"
|
|
4715
|
-
" For awareness: \"high\" uses ~15-25% more output tokens per response than \"medium\". "
|
|
4716
|
-
"You can check token usage with `/cost`. Claude's adaptive thinking still adjusts "
|
|
4717
|
-
"within the effort level based on task complexity."
|
|
4718
|
-
)
|
|
4709
|
+
# --- Rule 16+: Subscription-limit advisory audits (effort, monorepo CLAUDE.md, outputStyle) ---
|
|
4710
|
+
from . import subscription_audits as _sub_audits
|
|
4711
|
+
_sub_audits.append_claude_recommendations(components, trends, quick, medium, deep, habits, _measure_facade)
|
|
4719
4712
|
|
|
4720
4713
|
# --- Rule 13: Compact habits (always include) ---
|
|
4721
4714
|
try:
|
|
@@ -5206,13 +5199,9 @@ def generate_coach_data(focus=None, components=None, trends=None, include_determ
|
|
|
5206
5199
|
})
|
|
5207
5200
|
score -= 3
|
|
5208
5201
|
|
|
5209
|
-
#
|
|
5210
|
-
|
|
5211
|
-
|
|
5212
|
-
patterns_good.append({
|
|
5213
|
-
"name": "Effort Level Set",
|
|
5214
|
-
"detail": "effortLevel: \"high\" — deliberate quality choice. Uses ~15-25% more output tokens than \"medium\".",
|
|
5215
|
-
})
|
|
5202
|
+
# Subscription-limit advisory audits (effort, monorepo CLAUDE.md, Codex MCP, outputStyle)
|
|
5203
|
+
from . import subscription_audits as _sub_audits
|
|
5204
|
+
_sub_audits.append_coach_findings(components, trends, is_claude, is_codex, patterns_good, patterns_bad, questions, _measure_facade)
|
|
5216
5205
|
|
|
5217
5206
|
# Check settings env vars for optimization opportunities. Resolve across
|
|
5218
5207
|
# process env + all settings files so a project-level opt-out is honoured.
|