@alexgreensh/token-optimizer 5.13.74 → 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.
Files changed (84) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/hooks/module_runner.py +1 -1
  4. package/hooks/posttooluse_runner.py +7 -9
  5. package/hooks/run.py +5 -1
  6. package/hooks/stop_runner.py +15 -56
  7. package/hooks/userpromptsubmit_runner.py +29 -4
  8. package/package.json +1 -1
  9. package/skills/token-optimizer/assets/dashboard.html +30 -14
  10. package/skills/token-optimizer/assets/savings_story.js +103 -27
  11. package/skills/token-optimizer/references/agent-prompts.md +2 -0
  12. package/skills/token-optimizer/references/implementation-playbook.md +1 -0
  13. package/skills/token-optimizer/scripts/_measure/__init__.py +1 -1
  14. package/skills/token-optimizer/scripts/_measure/apply_safe.py +512 -0
  15. package/skills/token-optimizer/scripts/_measure/audit.py +9 -20
  16. package/skills/token-optimizer/scripts/_measure/autocompact_advice.py +455 -0
  17. package/skills/token-optimizer/scripts/_measure/cache_policy.py +82 -127
  18. package/skills/token-optimizer/scripts/_measure/cli.py +10 -24
  19. package/skills/token-optimizer/scripts/_measure/cold_guard.py +777 -0
  20. package/skills/token-optimizer/scripts/_measure/continuity.py +45 -4
  21. package/skills/token-optimizer/scripts/_measure/counted_closes.py +398 -0
  22. package/skills/token-optimizer/scripts/_measure/counted_headline.py +112 -0
  23. package/skills/token-optimizer/scripts/_measure/dashboard.py +14 -6
  24. package/skills/token-optimizer/scripts/_measure/feature_health.py +6 -0
  25. package/skills/token-optimizer/scripts/_measure/keepwarm_auto.py +452 -0
  26. package/skills/token-optimizer/scripts/_measure/keepwarm_economics.py +8 -4
  27. package/skills/token-optimizer/scripts/_measure/keepwarm_safety.py +548 -24
  28. package/skills/token-optimizer/scripts/_measure/limit_units.py +463 -0
  29. package/skills/token-optimizer/scripts/_measure/local_adapt.py +192 -0
  30. package/skills/token-optimizer/scripts/_measure/mod_action_booking.py +71 -14
  31. package/skills/token-optimizer/scripts/_measure/next_actions.py +420 -0
  32. package/skills/token-optimizer/scripts/_measure/poc_commands.py +44 -0
  33. package/skills/token-optimizer/scripts/_measure/prefix_cost.py +215 -0
  34. package/skills/token-optimizer/scripts/_measure/pt_resume_cues.py +46 -0
  35. package/skills/token-optimizer/scripts/_measure/quality_archive.py +7 -10
  36. package/skills/token-optimizer/scripts/_measure/savings.py +80 -82
  37. package/skills/token-optimizer/scripts/_measure/savings_headline.py +17 -21
  38. package/skills/token-optimizer/scripts/_measure/savings_story.py +8 -1
  39. package/skills/token-optimizer/scripts/_measure/session_store_spool.py +119 -78
  40. package/skills/token-optimizer/scripts/_measure/status_bar_refresh.py +38 -3
  41. package/skills/token-optimizer/scripts/_measure/structural_ledger.py +1 -1
  42. package/skills/token-optimizer/scripts/_measure/subscription_audits.py +725 -0
  43. package/skills/token-optimizer/scripts/_measure/transcript_backfill.py +1 -1
  44. package/skills/token-optimizer/scripts/_measure/transcript_stream.py +8 -2
  45. package/skills/token-optimizer/scripts/antigravity_install.py +3 -0
  46. package/skills/token-optimizer/scripts/archive_result.py +16 -28
  47. package/skills/token-optimizer/scripts/archive_verify.py +1 -1
  48. package/skills/token-optimizer/scripts/bash_compress.py +156 -176
  49. package/skills/token-optimizer/scripts/bash_compress_hook.py +218 -174
  50. package/skills/token-optimizer/scripts/bash_search_results.py +189 -9
  51. package/skills/token-optimizer/scripts/bash_whitelist.py +6 -1
  52. package/skills/token-optimizer/scripts/benchmark.py +11 -13
  53. package/skills/token-optimizer/scripts/big_noncode_read.py +998 -0
  54. package/skills/token-optimizer/scripts/build_output_compress.py +103 -8
  55. package/skills/token-optimizer/scripts/builtin_tool_compress.py +716 -0
  56. package/skills/token-optimizer/scripts/cloud_kit.py +1 -1
  57. package/skills/token-optimizer/scripts/codex_doctor.py +1 -1
  58. package/skills/token-optimizer/scripts/command_compress_extra.py +955 -0
  59. package/skills/token-optimizer/scripts/compact_markers.py +129 -0
  60. package/skills/token-optimizer/scripts/copilot_install.py +3 -0
  61. package/skills/token-optimizer/scripts/cursor_install.py +7 -0
  62. package/skills/token-optimizer/scripts/devin_source.py +5 -5
  63. package/skills/token-optimizer/scripts/emit_safety_gate.py +518 -0
  64. package/skills/token-optimizer/scripts/fixtures/b2_more_commands.json +142 -0
  65. package/skills/token-optimizer/scripts/fixtures/b5_more_savings.json +26 -0
  66. package/skills/token-optimizer/scripts/fixtures/builtin_tools.json +103 -0
  67. package/skills/token-optimizer/scripts/fixtures/c7_review_ratchet.json +52 -0
  68. package/skills/token-optimizer/scripts/fixtures/large_output_policy.json +55 -0
  69. package/skills/token-optimizer/scripts/go_cargo_test_compress.py +493 -0
  70. package/skills/token-optimizer/scripts/grok_install.py +3 -0
  71. package/skills/token-optimizer/scripts/hermes_doctor.py +4 -1
  72. package/skills/token-optimizer/scripts/hermes_install.py +10 -1
  73. package/skills/token-optimizer/scripts/hook_fastpath.py +94 -0
  74. package/skills/token-optimizer/scripts/hook_runtime.py +6 -2
  75. package/skills/token-optimizer/scripts/large_output_policy.py +431 -0
  76. package/skills/token-optimizer/scripts/measure.py +10 -12
  77. package/skills/token-optimizer/scripts/pipe_file_compress.py +900 -0
  78. package/skills/token-optimizer/scripts/pipeline_analyzer.py +15 -1
  79. package/skills/token-optimizer/scripts/post_run_classify.py +2 -2
  80. package/skills/token-optimizer/scripts/preserved_reinject.py +20 -3
  81. package/skills/token-optimizer/scripts/process_identity.py +66 -0
  82. package/skills/token-optimizer/scripts/read_cache.py +51 -60
  83. package/skills/token-optimizer/scripts/statusline.js +21 -3
  84. package/skills/token-optimizer/scripts/visibility_rule.py +536 -0
@@ -0,0 +1,455 @@
1
+ """Lane B: compact-window advice."""
2
+ from collections import Counter
3
+ from datetime import datetime, timedelta, timezone
4
+ import math
5
+ import os
6
+ import statistics
7
+ import json
8
+ import hashlib
9
+ import re
10
+ import sys
11
+ import time
12
+
13
+ from . import limit_units, transcript_stream
14
+
15
+ LABEL = 'Earlier auto-compact'
16
+
17
+
18
+ def estimate_compaction(facade, event, prior, later, cohort_turns):
19
+ """Estimate saved reads less a pessimistic compaction and rebuild cost."""
20
+ before, after = event.get('before'), event.get('after')
21
+ window, previous = event.get('window'), event.get('previous_window')
22
+ if (event.get('manual_overlap') or not all(type(n) is int and n > 0 for n in (before, after, window, previous))
23
+ or after >= before or before >= previous or abs(before - window) > window * .1):
24
+ return None
25
+ if not prior or not later or cohort_turns is None or cohort_turns <= 0:
26
+ return None
27
+ turns = later[:min(10, int(cohort_turns))]
28
+ try:
29
+ card = limit_units._resolve_card(facade, prior['model'], per_request=True, full_input=before)
30
+ next_card = limit_units._resolve_card(facade, turns[0]['model'], per_request=True, full_input=after)
31
+ if not card or not next_card:
32
+ return None
33
+ lifetime = 3600 if int(prior.get('cache_creation_1h') or 0) else 300
34
+ gap = (event['stamp'] - prior['stamp']).total_seconds()
35
+ if gap < 0:
36
+ return None
37
+ prior_write = card.get('cache_write', card['input'] * 1.25)
38
+ request_rate = card['cache_read'] if gap <= lifetime else prior_write
39
+ next_write = (next_card.get('cache_write_1h', next_card['input'] * 2)
40
+ if int(turns[0].get('cache_creation_1h') or 0)
41
+ else next_card.get('cache_write', next_card['input'] * 1.25))
42
+ request_cost = before * request_rate / 1000000
43
+ output_cost = after * card['output'] / 1000000
44
+ rebuild_cost = after * next_write / 1000000
45
+ net = -request_cost - output_cost - rebuild_cost
46
+ units = -(request_cost + output_cost) * 1000000 / card['input'] - rebuild_cost * 1000000 / next_card['input']
47
+ tokens = 0
48
+ for turn in turns:
49
+ actual = min(before - after, max(0, int(turn.get('cache_read') or 0)))
50
+ turn_card = limit_units._resolve_card(facade, turn['model'], per_request=True, full_input=int(turn.get('context') or before))
51
+ if not turn_card or not turn_card.get('input') or turn_card.get('cache_read') is None:
52
+ return None
53
+ value = actual * turn_card['cache_read'] / 1000000
54
+ tokens += actual
55
+ net += value
56
+ units += value * 1000000 / turn_card['input']
57
+ return {'tokens_saved': tokens, 'cost_saved_usd': net, 'net_limit_units': units,
58
+ 'own_cost_usd': request_cost + output_cost + rebuild_cost, 'turns': len(turns)}
59
+ except (TypeError, ValueError, KeyError, ZeroDivisionError, AttributeError):
60
+ return None
61
+
62
+
63
+ def print_savings_line(summary, cents, period, money):
64
+ pool = summary.get('autocompact_window_estimated') or {}
65
+ if pool.get('events'):
66
+ print(' + est. {}: ~${}{} [estimated]'.format(LABEL, money(cents.get('autocompact_window_estimated', 0)), period))
67
+
68
+
69
+ def _recent_sessions(facade, include_paths=False, days=30):
70
+ """Read deduplicated per-request usage and compaction boundaries, off hook paths."""
71
+ cutoff = (datetime.now(timezone.utc) - timedelta(days=days)).replace(tzinfo=None)
72
+ conn = facade._open_trends_db_readonly(timeout=1.0)
73
+ try:
74
+ paths = conn.execute('SELECT DISTINCT jsonl_path FROM session_log WHERE COALESCE(last_activity_day,date) >= ? AND COALESCE(is_sidechain,0)=0', (cutoff.date().isoformat(),)).fetchall()
75
+ finally:
76
+ conn.close()
77
+ sessions = []
78
+ seen = set()
79
+ for (path,) in paths:
80
+ if not path:
81
+ continue
82
+ turns = []
83
+ for turn in facade.parse_session_turns(path):
84
+ try:
85
+ stamp = datetime.fromisoformat(turn['timestamp'].replace('Z', '+00:00'))
86
+ stamp = stamp.astimezone(timezone.utc).replace(tzinfo=None) if stamp.tzinfo else stamp
87
+ except (KeyError, ValueError, AttributeError):
88
+ continue
89
+ if stamp < cutoff:
90
+ continue
91
+ request_id = turn.get('request_id')
92
+ if request_id and request_id in seen:
93
+ continue
94
+ if request_id:
95
+ seen.add(request_id)
96
+ turns.append(dict(turn, stamp=stamp, context=sum(max(0, int(turn.get(k) or 0)) for k in ('input_tokens', 'cache_read', 'cache_creation'))))
97
+ if turns:
98
+ _, boundaries, _ = facade._counted_walk_transcript(path)
99
+ boundaries = [boundary for boundary in boundaries if boundary >= cutoff]
100
+ sessions.append((turns, boundaries, path) if include_paths else (turns, boundaries))
101
+ return sessions
102
+
103
+
104
+ def _utc_naive(value):
105
+ stamp = datetime.fromisoformat(str(value).replace('Z', '+00:00'))
106
+ return stamp.astimezone(timezone.utc).replace(tzinfo=None) if stamp.tzinfo else stamp
107
+
108
+
109
+ def _automatic_boundaries(path):
110
+ found = []
111
+ with transcript_stream.open_transcript(path) as stream:
112
+ for line in stream:
113
+ if 'compact_boundary' not in line:
114
+ continue
115
+ try:
116
+ row = json.loads(line)
117
+ meta = row.get('compactMetadata') or {}
118
+ if (row.get('type') != 'system' or row.get('subtype') != 'compact_boundary'
119
+ or row.get('isSidechain') or meta.get('trigger') != 'auto'):
120
+ continue
121
+ found.append({'stamp': _utc_naive(row['timestamp']), 'before': int(meta['preTokens']),
122
+ 'after': int(meta['postTokens']) if meta.get('postTokens') is not None else None,
123
+ 'boundary_id': str(row.get('uuid') or '')})
124
+ except (ValueError, TypeError, AttributeError, KeyError):
125
+ continue
126
+ return found
127
+
128
+
129
+ def _applications(facade):
130
+ from . import apply_safe
131
+ rows = apply_safe._receipts(facade)
132
+ settings, _ = facade._read_settings_json()
133
+ if (os.environ.get('CLAUDE_CODE_AUTO_COMPACT_WINDOW') is not None or
134
+ os.environ.get('CLAUDE_AUTOCOMPACT_PCT_OVERRIDE') is not None or
135
+ (settings.get('env') or {}).get('CLAUDE_AUTOCOMPACT_PCT_OVERRIDE') is not None):
136
+ return []
137
+ applications = []
138
+ for receipt in rows:
139
+ if receipt.get('status') != 'complete':
140
+ continue
141
+ for item in receipt.get('items', []):
142
+ if item.get('kind') != 'autocompact_window' or not item.get('ok'):
143
+ continue
144
+ try:
145
+ start = datetime.fromisoformat(item.get('applied_at') or receipt['ts']).astimezone(timezone.utc).replace(tzinfo=None)
146
+ window, previous = int(item['after']), int(item['previous_window'])
147
+ setting = item.get('setting') or {}
148
+ setting_model = setting.get('model')
149
+ model = item.get('main_model')
150
+ current = ((settings.get('modelSettings') or {}).get(setting_model) or {}).get('autoCompactWindow') if setting_model else settings.get('autoCompactWindow')
151
+ undos = [r for r in rows if r.get('undo_of') == receipt.get('receipt_id') and
152
+ any(i.get('id') == item['id'] and i.get('ok') for i in r.get('items', []))]
153
+ end = min((datetime.fromisoformat(r['ts']).astimezone(timezone.utc).replace(tzinfo=None) for r in undos), default=None)
154
+ if end is None and current != window:
155
+ continue
156
+ applications.append({'start': start, 'end': end, 'window': window, 'previous_window': previous,
157
+ 'receipt_id': receipt['receipt_id'], 'model': model})
158
+ except (ValueError, TypeError, KeyError, AttributeError):
159
+ continue
160
+ return applications
161
+
162
+
163
+ def _manual_overlap(conn, sid, session_uuid, boundary_id):
164
+ """Do not stack an estimate with an existing manual compaction receipt."""
165
+ rows = conn.execute("SELECT detail FROM compression_events WHERE (session_id=? OR session_uuid=?) "
166
+ "AND feature IN ('mod_clean','mod_clean_first') UNION ALL "
167
+ "SELECT detail FROM savings_events WHERE (session_id=? OR session_uuid=?) "
168
+ "AND event_type='mod_compaction_cost'", (sid, session_uuid, sid, session_uuid)).fetchall()
169
+ for (detail,) in rows:
170
+ match = re.search(r'compaction_id=([A-Za-z0-9._-]+)', detail or '')
171
+ if not match or not boundary_id or match.group(1) == boundary_id:
172
+ return True
173
+ return False
174
+
175
+
176
+ def refresh_bookings(facade):
177
+ """Book observed automatic boundaries on an explicit report or dashboard path."""
178
+ applications = _applications(facade)
179
+ if not applications:
180
+ return 0
181
+ days = max(30, (datetime.now(timezone.utc).replace(tzinfo=None) - min(a['start'] for a in applications)).days + 1)
182
+ sessions = _recent_sessions(facade, include_paths=True, days=days)
183
+ conn = facade._init_trends_db()
184
+ booked = 0
185
+ try:
186
+ conn.execute('CREATE TABLE IF NOT EXISTS autocompact_receipts '
187
+ '(session_uuid TEXT NOT NULL, boundary_id TEXT NOT NULL, event_id INTEGER NOT NULL, '
188
+ 'PRIMARY KEY(session_uuid,boundary_id))')
189
+ conn.commit()
190
+ for turns, all_boundaries, path in sessions:
191
+ sid = facade.Path(path).stem
192
+ session_uuid, unjoinable = facade._extract_session_uuid(sid)
193
+ if not session_uuid or unjoinable:
194
+ continue
195
+ try:
196
+ boundaries = _automatic_boundaries(path)
197
+ except OSError:
198
+ continue
199
+ for event in boundaries:
200
+ active = [a for a in applications if a['start'] <= event['stamp'] and (a['end'] is None or event['stamp'] < a['end'])]
201
+ if not active:
202
+ continue
203
+ application = max(active, key=lambda item: item['start'])
204
+ earlier = [t for t in turns if t['stamp'] <= event['stamp']]
205
+ later = [t for t in turns if t['stamp'] > event['stamp']]
206
+ following_boundary = next((b for b in all_boundaries if b > event['stamp']), None)
207
+ if following_boundary:
208
+ later = [t for t in later if t['stamp'] < following_boundary]
209
+ if not earlier or not later or (application['model'] and earlier[-1].get('model') != application['model']):
210
+ continue
211
+ if event['after'] is None:
212
+ event['after'] = int(later[0].get('context') or 0)
213
+ position = len(earlier)
214
+ cohort = [max(0, len(other) - position) for other, _, other_path in sessions if other_path != path and len(other) >= position]
215
+ if len(cohort) < 5:
216
+ continue
217
+ boundary_id = event['boundary_id'] or hashlib.sha256((sid + event['stamp'].isoformat() + str(event['before'])).encode()).hexdigest()
218
+ if _manual_overlap(conn, sid, session_uuid, event['boundary_id']):
219
+ existing = conn.execute('SELECT event_id FROM autocompact_receipts WHERE session_uuid=? AND boundary_id=?', (session_uuid, boundary_id)).fetchone()
220
+ if existing:
221
+ cur = conn.execute("UPDATE savings_events SET tokens_saved=0,cost_saved_usd=0,detail=? WHERE id=? AND event_type='autocompact_window_estimated' AND (tokens_saved<>0 OR cost_saved_usd<>0)",
222
+ (json.dumps({'basis': 'voided: manual compaction receipt', 'net_limit_units': 0}), existing[0]))
223
+ if cur.rowcount:
224
+ row = conn.execute('SELECT tokens_saved,cost_saved_usd FROM savings_events WHERE id=?', (existing[0],)).fetchone()
225
+ if row != (0, 0.0):
226
+ conn.rollback()
227
+ raise ValueError('reversal not verified')
228
+ conn.commit()
229
+ continue
230
+ event.update(window=application['window'], previous_window=application['previous_window'])
231
+ estimate = estimate_compaction(facade, event, earlier[-1], later, statistics.median(cohort))
232
+ if estimate is None:
233
+ continue
234
+ conn.execute('BEGIN IMMEDIATE')
235
+ try:
236
+ old = conn.execute('SELECT event_id FROM autocompact_receipts WHERE session_uuid=? AND boundary_id=?', (session_uuid, boundary_id)).fetchone()
237
+ detail = json.dumps({'basis': 'pessimistic estimate', 'compaction_id': boundary_id,
238
+ 'net_limit_units': estimate['net_limit_units'], 'own_cost_usd': estimate['own_cost_usd'],
239
+ 'continuation_turns': estimate['turns'], 'receipt_id': application['receipt_id']}, sort_keys=True)
240
+ if old:
241
+ cur = conn.execute("UPDATE savings_events SET tokens_saved=?,cost_saved_usd=?,detail=? WHERE id=? AND event_type='autocompact_window_estimated' AND (tokens_saved<>? OR cost_saved_usd<>? OR detail<>?)",
242
+ (estimate['tokens_saved'], estimate['cost_saved_usd'], detail, old[0], estimate['tokens_saved'], estimate['cost_saved_usd'], detail))
243
+ if cur.rowcount:
244
+ row = conn.execute('SELECT tokens_saved,cost_saved_usd,detail FROM savings_events WHERE id=?', (old[0],)).fetchone()
245
+ if row != (estimate['tokens_saved'], estimate['cost_saved_usd'], detail):
246
+ raise ValueError('re-estimate not verified')
247
+ conn.commit()
248
+ else:
249
+ conn.rollback()
250
+ continue
251
+ local_stamp = event['stamp'].replace(tzinfo=timezone.utc).astimezone().replace(tzinfo=None).isoformat()
252
+ cur = conn.execute('INSERT INTO savings_events(timestamp,event_type,tokens_saved,cost_saved_usd,session_id,session_uuid,detail,model,unjoinable) VALUES(?,?,?,?,?,?,?,?,?)',
253
+ (local_stamp, 'autocompact_window_estimated', estimate['tokens_saved'], estimate['cost_saved_usd'], sid, session_uuid, detail, earlier[-1].get('model'), 0))
254
+ if cur.rowcount != 1:
255
+ raise ValueError('event not written')
256
+ event_id = cur.lastrowid
257
+ cur = conn.execute('INSERT INTO autocompact_receipts VALUES(?,?,?)', (session_uuid, boundary_id, event_id))
258
+ if cur.rowcount != 1 or conn.execute('SELECT event_id FROM autocompact_receipts WHERE session_uuid=? AND boundary_id=?', (session_uuid, boundary_id)).fetchone() != (event_id,):
259
+ raise ValueError('receipt not written')
260
+ conn.commit()
261
+ booked += 1
262
+ except Exception:
263
+ conn.rollback()
264
+ raise
265
+ finally:
266
+ conn.close()
267
+ return booked
268
+
269
+
270
+ _last_refresh = 0.0
271
+
272
+
273
+ def refresh_if_allowed(facade, explicit=False):
274
+ """Never walk transcripts from hooks; refresh only reports and dashboard processes."""
275
+ global _last_refresh
276
+ program = os.path.basename(sys.argv[0]).lower()
277
+ dashboard = program == 'dashboard-server.py'
278
+ if not explicit and not dashboard:
279
+ return
280
+ if time.monotonic() - _last_refresh < 60:
281
+ return
282
+ _last_refresh = time.monotonic()
283
+ try:
284
+ refresh_bookings(facade)
285
+ except Exception:
286
+ return
287
+
288
+
289
+ def _median_compaction_cost(facade):
290
+ cutoff = (datetime.now() - timedelta(days=30)).isoformat()
291
+ conn = facade._open_trends_db_readonly(timeout=1.0)
292
+ try:
293
+ costs = [abs(float(row[0])) for row in conn.execute(
294
+ "SELECT cost_saved_usd FROM savings_events WHERE event_type='mod_compaction_cost' AND timestamp >= ? AND cost_saved_usd < 0", (cutoff,))]
295
+ finally:
296
+ conn.close()
297
+ return statistics.median(costs) if costs else None
298
+
299
+
300
+ def recommend(facade):
301
+ """Recommend only when observed history and exact pricing support a net gain."""
302
+ if getattr(facade, '_is_foreign_runtime', lambda: False)():
303
+ return None
304
+ if os.environ.get('CLAUDE_CODE_AUTO_COMPACT_WINDOW') is not None:
305
+ return {'blocked': 'env', 'text': 'The environment override controls the compact window.'}
306
+ if os.environ.get('CLAUDE_AUTOCOMPACT_PCT_OVERRIDE') is not None:
307
+ return {'blocked': 'env', 'text': 'The existing percentage override changes the effective compact window.'}
308
+ try:
309
+ sessions = _recent_sessions(facade)
310
+ models = Counter(t.get('model') for turns, _ in sessions for t in turns if t.get('model'))
311
+ if not models:
312
+ return None
313
+ model = models.most_common(1)[0][0]
314
+ if facade._context_window_for_model_str(model) != 1000000:
315
+ return None
316
+ sessions = [([turn for turn in turns if turn.get('model') == model], boundaries)
317
+ for turns, boundaries in sessions]
318
+ sessions = [(turns, boundaries) for turns, boundaries in sessions if turns]
319
+ settings, _ = facade._read_settings_json()
320
+ if (settings.get('env') or {}).get('CLAUDE_AUTOCOMPACT_PCT_OVERRIDE') is not None:
321
+ return {'blocked': 'env', 'text': 'The existing percentage override changes the effective compact window.'}
322
+ current, _ = facade.effective_compact_window(model, env=os.environ, settings=settings)
323
+ if current <= 500000:
324
+ return None
325
+ peaks = [max(t['context'] for t in turns) for turns, _ in sessions]
326
+ if sum(peak >= 300000 for peak in peaks) < 20:
327
+ return None
328
+ p75 = sorted(peaks)[max(0, math.ceil(len(peaks) * .75) - 1)]
329
+ target = 400000 if p75 < 300000 else 500000 if p75 > 450000 else 450000
330
+ gross = 0.0
331
+ crossings = 0
332
+ happened = 0
333
+ for turns, boundaries in sessions:
334
+ previous = 0
335
+ boundary_index = 0
336
+ for turn in turns:
337
+ while boundary_index < len(boundaries) and boundaries[boundary_index] <= turn['stamp']:
338
+ previous = 0
339
+ boundary_index += 1
340
+ context = turn['context']
341
+ if previous < target <= context:
342
+ crossings += 1
343
+ previous = context
344
+ if context > target:
345
+ card = limit_units._resolve_card(facade, turn.get('model'), per_request=True, full_input=context)
346
+ if not card or card.get('cache_read') is None:
347
+ return None
348
+ gross += (context - target) * card['cache_read'] / 1000000
349
+ for boundary in boundaries:
350
+ before = [t for t in turns if t['stamp'] <= boundary]
351
+ if before:
352
+ happened += 1
353
+ extra = max(0, crossings - happened)
354
+ card = limit_units._resolve_card(facade, model, per_request=True, full_input=target)
355
+ cost = _median_compaction_cost(facade) if extra else 0
356
+ write_rate = card.get('cache_write_1h', card.get('input') * 2 if card.get('input') is not None else None) if card else None
357
+ if write_rate is None or cost is None:
358
+ return None
359
+ own_cost = extra * (cost + target * .15 * write_rate / 1000000)
360
+ net = gross - own_cost
361
+ if net <= 0:
362
+ return None
363
+ per_model = 'autoCompactWindow' in ((settings.get('modelSettings') or {}).get(model) or {})
364
+ return {'model': model, 'target': target, 'current': current, 'gross_usd_month': gross,
365
+ 'own_cost_usd_month': own_cost, 'net_usd_month': net, 'per_model': per_model,
366
+ 'text': 'Compacting earlier keeps less history in context. Token Optimizer saves a checkpoint before each compaction.'}
367
+ except Exception:
368
+ return None
369
+
370
+
371
+ def plan_item(facade, advice=None):
372
+ if advice is None:
373
+ advice = recommend(facade)
374
+ if not advice or advice.get('blocked'):
375
+ return None
376
+ return dict(advice, id='autocompact_window', kind='autocompact_window',
377
+ label='Compact earlier' + (' for ' + advice['model'] if advice['per_model'] else ''),
378
+ tokens_per_request=0, basis=advice['text'], default_selected=True,
379
+ undo='measure.py apply-safe --undo <receipt_id>')
380
+
381
+
382
+ def apply_item(facade, item, before_write=None):
383
+ """Write the approved window at the setting that currently takes precedence."""
384
+ if getattr(facade, '_is_foreign_runtime', lambda: False)():
385
+ return {'ok': False}
386
+ target, model = item.get('target'), item.get('model')
387
+ if target not in (400000, 450000, 500000) or not isinstance(model, str) or not model:
388
+ return {'ok': False}
389
+ with facade._settings_lock(user_initiated=True) as acquired:
390
+ if not acquired:
391
+ return {'ok': False}
392
+ identity = getattr(facade, '_settings_file_identity', lambda: None)()
393
+ settings, ok = facade._read_settings_for_write()
394
+ if not ok or not isinstance(settings, dict):
395
+ return {'ok': False}
396
+ models = settings.get('modelSettings')
397
+ model_settings = models.get(model) if isinstance(models, dict) else None
398
+ per_model = isinstance(model_settings, dict) and 'autoCompactWindow' in model_settings
399
+ container = model_settings if per_model else settings
400
+ previous = container.get('autoCompactWindow')
401
+ existed = 'autoCompactWindow' in container
402
+ receipt = {'ok': True, 'before': previous, 'before_exists': existed, 'after': target,
403
+ 'model': model if per_model else None}
404
+ if before_write is not None:
405
+ before_write(receipt)
406
+ container['autoCompactWindow'] = target
407
+ if not facade._write_settings_atomic_locked(settings, expect_identity=identity):
408
+ return {'ok': False}
409
+ return receipt
410
+
411
+
412
+ def undo_item(facade, receipt):
413
+ """Restore only this setting, refusing to overwrite a later edit."""
414
+ if getattr(facade, '_is_foreign_runtime', lambda: False)():
415
+ return False
416
+ with facade._settings_lock(user_initiated=True) as acquired:
417
+ if not acquired:
418
+ return False
419
+ identity = getattr(facade, '_settings_file_identity', lambda: None)()
420
+ settings, ok = facade._read_settings_for_write()
421
+ if not ok or not isinstance(settings, dict):
422
+ return False
423
+ model = receipt.get('model')
424
+ if model is not None:
425
+ models = settings.get('modelSettings')
426
+ container = models.get(model) if isinstance(models, dict) else None
427
+ else:
428
+ container = settings
429
+ if not isinstance(container, dict) or container.get('autoCompactWindow') != receipt.get('after'):
430
+ return False
431
+ if receipt.get('before_exists'):
432
+ container['autoCompactWindow'] = receipt['before']
433
+ else:
434
+ container.pop('autoCompactWindow', None)
435
+ allow = {'autoCompactWindow'} if model is None and not receipt.get('before_exists') else None
436
+ return bool(facade._write_settings_atomic_locked(settings, allow_removing_keys=allow, expect_identity=identity))
437
+
438
+
439
+ def main(facade, args):
440
+ """Show advice without changing settings."""
441
+ if any(arg != '--json' for arg in args):
442
+ print('Usage: measure.py autocompact-advice [--json]')
443
+ return 2
444
+ advice = recommend(facade)
445
+ if '--json' in args:
446
+ print(json.dumps(advice))
447
+ elif advice is None:
448
+ print('No compact-window recommendation is available.')
449
+ elif advice.get('blocked'):
450
+ print(advice['text'])
451
+ else:
452
+ location = 'model-specific setting' if advice['per_model'] else 'top-level setting'
453
+ print('Recommended window: {:,} ({}, estimated net ${:.2f}/month).'.format(advice['target'], location, advice['net_usd_month']))
454
+ print(advice['text'])
455
+ return 0