@alexgreensh/token-optimizer 5.13.70 → 5.13.72

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 (40) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/hooks/module_runner.py +3 -3
  4. package/hooks/sessionstart_runner.py +6 -0
  5. package/package.json +1 -1
  6. package/skills/token-optimizer/assets/dashboard.html +361 -289
  7. package/skills/token-optimizer/assets/savings_story.js +140 -36
  8. package/skills/token-optimizer/references/cli-reference.md +1 -1
  9. package/skills/token-optimizer/scripts/_measure/__init__.py +3 -3
  10. package/skills/token-optimizer/scripts/_measure/config_cache.py +63 -0
  11. package/skills/token-optimizer/scripts/_measure/context_reset_marker.py +3 -1
  12. package/skills/token-optimizer/scripts/_measure/counted_cap.py +4 -2
  13. package/skills/token-optimizer/scripts/_measure/coverage_report.py +11 -1
  14. package/skills/token-optimizer/scripts/_measure/dashboard.py +35 -64
  15. package/skills/token-optimizer/scripts/_measure/holdout_report.py +5 -1
  16. package/skills/token-optimizer/scripts/_measure/keepwarm_safety.py +4 -0
  17. package/skills/token-optimizer/scripts/_measure/lifecycle.py +6 -7
  18. package/skills/token-optimizer/scripts/_measure/quality_checkpoint.py +4 -3
  19. package/skills/token-optimizer/scripts/_measure/savings.py +11 -4
  20. package/skills/token-optimizer/scripts/_measure/savings_headline.py +130 -0
  21. package/skills/token-optimizer/scripts/_measure/sessions.py +7 -0
  22. package/skills/token-optimizer/scripts/_measure/setup_observation_cache.py +99 -0
  23. package/skills/token-optimizer/scripts/_measure/setup_step.py +4 -5
  24. package/skills/token-optimizer/scripts/_measure/status_bar_refresh.py +218 -0
  25. package/skills/token-optimizer/scripts/_measure/structural_report.py +25 -6
  26. package/skills/token-optimizer/scripts/_measure/structural_value.py +16 -10
  27. package/skills/token-optimizer/scripts/cloud_kit.py +1 -2
  28. package/skills/token-optimizer/scripts/codemap.py +33 -5
  29. package/skills/token-optimizer/scripts/codemap_hint.py +152 -11
  30. package/skills/token-optimizer/scripts/codemap_index.py +100 -11
  31. package/skills/token-optimizer/scripts/codemap_ledger.py +29 -0
  32. package/skills/token-optimizer/scripts/codex_doctor.py +3 -3
  33. package/skills/token-optimizer/scripts/hermes_doctor.py +3 -3
  34. package/skills/token-optimizer/scripts/hermes_install.py +3 -3
  35. package/skills/token-optimizer/scripts/statusline.js +157 -30
  36. package/skills/token-optimizer/scripts/_measure/keepwarm_fork.py +0 -140
  37. package/skills/token-optimizer/scripts/_measure/keepwarm_guard.py +0 -35
  38. package/skills/token-optimizer/scripts/_measure/keepwarm_guard_server.py +0 -85
  39. package/skills/token-optimizer/scripts/_measure/keepwarm_prefix.py +0 -143
  40. package/skills/token-optimizer/scripts/_measure/keepwarm_response_filter.py +0 -84
@@ -109,8 +109,9 @@ function savingsStoryBands(data) {
109
109
  mUsd: mUsd, eUsd: eUsd, totalUsd: totalUsd, totalTok: totalTok };
110
110
  }
111
111
 
112
- function savingsStoryHtml(data) {
112
+ function savingsStoryHtml(data, extras) {
113
113
  if (!savingsStoryOn(data)) return '';
114
+ extras = extras || {};
114
115
  var f = savingsStoryFmt(), num = f.num, has = f.has, usd = f.usd, tok = f.tok, pct = f.pct, count = f.count;
115
116
  var s = data.savings || {};
116
117
  var se = s.session_effect || {};
@@ -215,12 +216,46 @@ function savingsStoryHtml(data) {
215
216
  var soFarAll = aiP.remeasuring === true || aiP.routing_pending === true;
216
217
  var left = Math.max(num(cp.remeasuring_sessions), num(aiP.remeasuring_sessions), num(aiP.routing_pending_sessions), mr.evidence === 'pending' ? num(mr.pending_sessions) : 0);
217
218
  var soFar = function(on) { return on ? ', so far' : ''; };
219
+ // Hover cards on the three hero numbers: what the number is made of and
220
+ // what to do about it. Opens on hover and focus, toggles on tap.
221
+ function tipCard(id, title, lines) {
222
+ return '<span class="st-tipcard" role="tooltip" id="' + id + '">' +
223
+ '<span class="st-tipcard__t">' + esc(title) + '</span>' +
224
+ lines.map(function(l) {
225
+ return '<span class="st-tipcard__l' + (l.note ? ' st-tipcard__note' : '') + '">' + l.html + '</span>';
226
+ }).join('') + '</span>';
227
+ }
228
+ var tipTotalLines = [{ html: 'Measured and estimated savings ' + usd(totalUsd) }];
229
+ if (num(as.reread_usd) > 0) tipTotalLines.push({ html: 'Of which re-reads avoided ' + usd(as.reread_usd) });
230
+ if (routing30 > 0) tipTotalLines.push({ html: 'Model routing (estimate) ' + usd(routing30) });
231
+ tipTotalLines.push({ html: 'At API prices. On a subscription this shows up as limit headroom, not a bill.', note: true });
232
+ if (num(mr.potential_cost_usd) > 0) {
233
+ var tipTarget = /sonnet/i.test(String(mr.target_model || '')) ? 'Sonnet' : /haiku/i.test(String(mr.target_model || '')) ? 'Haiku' : 'a lighter model';
234
+ tipTotalLines.push({ html: 'Want more: route routine work to ' + tipTarget + ', about ' + usd(mr.potential_cost_usd) + ' more per ' + days + ' days.' });
235
+ }
236
+ var tipTokLines = [{ html: 'What it means: text ' + esc(data.runtime_label || 'Claude Code') + ' never had to read again, so each turn was lighter and your window lasted longer.', note: true }];
237
+ var tipTokParts = [];
238
+ if (num(th.reread_tokens) > 0) tipTokParts.push(tok(th.reread_tokens) + ' re-reads avoided');
239
+ var tipRemoved = has(th.context_removed_tokens) ? num(th.context_removed_tokens) + num(th.output_not_generated_tokens) : num(th.removed_tokens);
240
+ if (tipRemoved > 0) tipTokParts.push(tok(tipRemoved) + ' removed from context');
241
+ if (num(th.reload_avoided_tokens) > 0) tipTokParts.push(tok(th.reload_avoided_tokens) + ' not reloaded after compaction');
242
+ if (tipTokParts.length) tipTokLines.push({ html: 'Mostly from: ' + tipTokParts.join(', ') + '.' });
243
+ var tipSinceLines = [];
244
+ if (SIh && SIh.measured > 0) tipSinceLines.push({ html: 'Measured: ' + usd(SIh.measured) });
245
+ if (SIh && SIh.estimated > 0) tipSinceLines.push({ html: 'Estimated: ' + usd(SIh.estimated) });
246
+ if (SIh && SIh.routing > 0) tipSinceLines.push({ html: 'Model routing (estimate): ' + usd(SIh.routing) });
218
247
  out += '<div class="card st-hero">' +
219
248
  '<h2 class="st-h">What Token Optimizer saved</h2>' +
220
249
  '<div class="st-mega__row st-mega__row--hero">' +
221
- '<div class="st-mega__item"><span class="st-mega st-mega--usd">' + usd(bigTotal) + '</span><span class="st-mega__unit">saved in the last ' + days + ' days' + soFar(soFar30) + '</span></div>' +
222
- (SIh && SIh.all > 0 ? '<div class="st-mega__item"><span class="st-mega st-mega--usd">' + usd(SIh.all) + '</span><span class="st-mega__unit">saved since you installed' + soFar(soFarAll) + '</span></div>' : '') +
223
- (totalTok > 0 ? '<div class="st-mega__item"><span class="st-mega st-mega--tok">' + tok(totalTok) + '</span><span class="st-mega__unit">tokens kept out of context in ' + days + ' days' + soFar(cp.remeasuring === true) + '</span></div>' : '') +
250
+ '<div class="st-mega__item"><button type="button" class="st-mega st-mega--usd st-tip" aria-describedby="st-tip-total">' + usd(bigTotal) + '</button>' +
251
+ tipCard('st-tip-total', 'What makes up ' + usd(bigTotal), tipTotalLines) +
252
+ '<span class="st-mega__unit">saved in the last ' + days + ' days' + soFar(soFar30) + '</span></div>' +
253
+ (SIh && SIh.all > 0 ? '<div class="st-mega__item"><button type="button" class="st-mega st-mega--usd st-tip" aria-describedby="st-tip-since">' + usd(SIh.all) + '</button>' +
254
+ tipCard('st-tip-since', 'Since ' + esc(SIh.date || 'install'), tipSinceLines) +
255
+ '<span class="st-mega__unit">saved since you installed' + soFar(soFarAll) + '</span></div>' : '') +
256
+ (totalTok > 0 ? '<div class="st-mega__item"><button type="button" class="st-mega st-mega--tok st-tip" aria-describedby="st-tip-tokens">' + tok(totalTok) + '</button>' +
257
+ tipCard('st-tip-tokens', tok(totalTok) + ' tokens kept out of context', tipTokLines) +
258
+ '<span class="st-mega__unit">tokens kept out of context in ' + days + ' days' + soFar(cp.remeasuring === true) + '</span></div>' : '') +
224
259
  '</div>' +
225
260
  (soFar30 || soFarAll ? '<p class="st-lead st-progress">Updating your history after an upgrade' + (left > 0 ? ' (' + count(left) + ' session' + (left === 1 ? '' : 's') + ' left)' : '') + '. These totals are in progress and will change when it finishes.</p>' : '') +
226
261
  f.fold('How this is calculated', method + (SIh && SIh.all > 0 ? savingsSinceInstallBody(data, SIh) : '')) +
@@ -232,7 +267,7 @@ function savingsStoryHtml(data) {
232
267
  out += savingsLimitsHtml(data);
233
268
 
234
269
  // ---- 1c. Still on the table: opportunity, never part of a savings total ----
235
- out += savingsOnTableHtml(data);
270
+ out += savingsOnTableHtml(data, extras);
236
271
 
237
272
  // ---- 2. The re-read card ----
238
273
  var cards = [];
@@ -241,8 +276,9 @@ function savingsStoryHtml(data) {
241
276
  var carryN = rereads / removedOnce;
242
277
  cards.push('<div class="card st-card st-reread">' +
243
278
  '<h2 class="st-h">' + (as.reread_available !== false && has(as.reread_usd) && num(as.reread_usd) > 0 && bigTotal > 0 ? usd(as.reread_usd) + ' of your ' + usd(bigTotal) + ' came from re-reads avoided' : 'Removed once, saved on every later turn') + '</h2>' +
244
- '<div class="st-reread__body"><p class="st-mega__item st-mega__item--card"><span class="st-mega st-mega--tok st-mega--card">' + Math.round(carryN) + '&times;</span><span class="st-mega__unit">re-reads avoided per token removed</span></p>' +
245
- '<p class="st-lead"><strong>' + tok(removedOnce) + ' priced tokens removed</strong> became <strong>' + tok(rereads) + ' tokens not sent</strong> on later reads' + (has(cp.reread_usd) ? ', worth ' + usd(cp.reread_usd) + ' at API rates' : '') + '.</p></div>' +
279
+ '<div class="st-reread__body"><p class="st-mega__item st-mega__item--card"><span class="st-mega st-mega--tok st-mega--card">' + Math.round(carryN) + '&times;</span><span class="st-mega__unit">each token removed was not re-read ' + Math.round(carryN) + ' times</span></p>' +
280
+ '<p class="st-lead">Removing <strong>' + tok(removedOnce) + ' tokens</strong> once kept <strong>' + tok(rereads) + ' tokens</strong> from being re-sent on later turns' +
281
+ (has(cp.reread_usd) ? '. Worth ' + usd(cp.reread_usd) + ' at API prices.' : '.') + '</p></div>' +
246
282
  '</div>');
247
283
  }
248
284
  if (cards.length) out += '<div class="st-grid">' + cards.join('') + '</div>';
@@ -335,7 +371,7 @@ function savingsBaselineProgressHtml(ba) {
335
371
  } else {
336
372
  return '';
337
373
  }
338
- return '<div class="card st-card st-baseline-progress"><h2 class="st-h">Your transformation</h2><p class="st-lead">' + line + '</p></div>';
374
+ return '<div class="card st-card st-baseline-progress"><h2 class="st-h">What the same work used to cost</h2><p class="st-lead">' + line + '</p></div>';
339
375
  }
340
376
 
341
377
  // Transformation: what this month would cost without Token Optimizer, against
@@ -347,8 +383,15 @@ function savingsTransformationHtml(data) {
347
383
  var share = has(ba.transformation_pct) && num(ba.transformation_pct) > 0 ? Math.round(num(ba.transformation_pct) * 100) : 0;
348
384
  // Where the "before" came from. Older payloads carry no provenance and keep the fixed sentence.
349
385
  var prov = ba.baseline_provenance || {};
350
- // The lead states the baseline; what it understates is spelled out in the fold.
351
- var against = prov.lead ? esc(prov.lead) : 'compared with your own baseline from before you installed.';
386
+ // Friendly dates inside the provenance sentence: "(2026-03-17 to 2026-04-16)"
387
+ // becomes "(Mar 17 to Apr 16)".
388
+ var leadSrc = String(prov.lead || 'compared with your earliest tracked month.');
389
+ var friendlyLead = leadSrc.replace(/(\d{4}-\d{2}-\d{2})\s+to\s+(\d{4}-\d{2}-\d{2})/g, function(m, a, b) {
390
+ return f.day(a) + ' to ' + f.day(b);
391
+ });
392
+ var desc = friendlyLead.replace(/^compared with /i, '').replace(/\.$/, '').replace(/^your own baseline from /i, '');
393
+ var lead = 'This month&rsquo;s work would have cost ' + usd(ba.monthly_savings_usd) + ' more at what each request cost you ' +
394
+ (/^before /i.test(desc) ? '' : 'in ') + esc(desc) + (share > 0 ? '. That is ' + share + '% saved.' : '.');
352
395
  // A work-normalized figure prices both periods at one fixed rate card, so its
353
396
  // "now" side is not the user's spend: name the card and show the exact-card cost.
354
397
  var wp = ba.session_weight_pool || {}, fr = wp.flat_rates || null;
@@ -365,10 +408,9 @@ function savingsTransformationHtml(data) {
365
408
  (ba.before_mix_label ? '<p>' + (prov.mix_note ? 'Baseline model mix: ' + esc(ba.before_mix_label) + ', ' + esc(prov.mix_note) : 'Baseline mix before you installed: ' + esc(ba.before_mix_label)) + '. Now: ' + esc(ba.after_mix_label || 'your current mix') + '.</p>' : '') +
366
409
  (ba.breakdown_caveat ? '<p>' + esc(ba.breakdown_caveat) + '</p>' : '');
367
410
  return '<div class="card st-card st-transform">' +
368
- '<h2 class="st-h">Your transformation</h2>' +
411
+ '<h2 class="st-h">What the same work used to cost</h2>' +
369
412
  '<p class="st-mega__item st-mega__item--card"><span class="st-mega st-mega--usd st-mega--card">' + usd(ba.monthly_savings_usd) + '<span class="st-mega__per"> a month</span></span>' +
370
- '</p><p class="st-lead">' + (prov.claim ? esc(prov.claim) : 'Without Token Optimizer, working the way you work now would cost you this much more, ' + against) +
371
- (share > 0 ? ' That is ' + share + '% of what this work would have cost.' : '') + '</p>' +
413
+ '</p><p class="st-lead">' + lead + '</p>' +
372
414
  f.fold('How this is calculated', method) +
373
415
  '</div>';
374
416
  }
@@ -389,22 +431,20 @@ function savingsLimitWindows(rw, ratio, versus) {
389
431
  if (!rows.length) { rows = (Array.isArray(rw.last_known_windows) ? rw.last_known_windows : []).filter(ok); stored = rows.length > 0; }
390
432
  if (!rows.length) return '';
391
433
  // One row per window: name, a bar (solid = used now, striped = without
392
- // Token Optimizer) and the two numbers as stat blocks.
434
+ // Token Optimizer) and the two numbers as stat blocks. The "without" figure
435
+ // is shown plainly, never as an over-the-limit verdict.
393
436
  var html = '<div class="st-limits">' + rows.map(function(w) {
394
437
  var used = num(w.used_pct), rawWithout = used * ratio;
395
438
  var name = names[w.key] || ((w.label || 'window') + ' limit');
396
439
  name = name.charAt(0).toUpperCase() + name.slice(1);
397
- var over = ratio > 0 && rawWithout > 100;
398
- var without = ratio > 0 ? Math.min(100, Math.round(rawWithout)) : 0;
399
- var label = Math.round(used) + '% used now' + (ratio > 0 ? (over ? ', over the limit ' + vs : ', ' + without + '% ' + vs) : '');
440
+ var without = ratio > 0 ? Math.round(rawWithout) : 0;
441
+ var label = Math.round(used) + '% used now' + (ratio > 0 ? ', about ' + without + '% ' + vs : '');
400
442
  var stat = ratio > 0
401
- ? (over
402
- ? '<span class="st-limit__stat st-limit__stat--over">over the limit ' + vs + '</span>'
403
- : '<span class="st-limit__stat"><span class="st-limit__num">' + without + '%</span> ' + vs + '</span>')
443
+ ? '<span class="st-limit__stat"><span class="st-limit__num">' + without + '%</span> ' + vs + '</span>'
404
444
  : '';
405
445
  return '<div class="st-limit"><span class="st-limit__name">' + esc(name) + '</span>' +
406
446
  '<span class="st-limit__meter" role="img" aria-label="' + esc(label) + '">' +
407
- (ratio > 0 ? '<span class="st-limit__ghost" style="width:' + without + '%"></span>' : '') +
447
+ (ratio > 0 ? '<span class="st-limit__ghost" style="width:' + Math.min(100, without) + '%"></span>' : '') +
408
448
  '<span class="st-limit__fill" style="width:' + Math.round(used) + '%"></span></span>' +
409
449
  '<span class="st-limit__stat"><span class="st-limit__used">' + Math.round(used) + '%</span> used now</span>' + stat + '</div>';
410
450
  }).join('') + '</div>';
@@ -416,6 +456,9 @@ function savingsLimitWindows(rw, ratio, versus) {
416
456
  return html;
417
457
  }
418
458
 
459
+ // The weekly limit card: how much further your limit goes with Token Optimizer.
460
+ // The headline is the cost ratio minus one ("more work fits"), never the
461
+ // share-of-cost-avoided figure, which belongs to the transformation card.
419
462
  function savingsLimitsHtml(data) {
420
463
  var f = savingsStoryFmt(), num = f.num;
421
464
  var rw = (data && data.runway) || null;
@@ -423,24 +466,71 @@ function savingsLimitsHtml(data) {
423
466
  var ba = ((data && data.savings) || {}).before_after || {};
424
467
  var actual = num(ba.actual_monthly_usd), before = num(ba.counterfactual_monthly_usd);
425
468
  var ratio = ba.transformation_state === 'ok' && actual > 0 && before > actual ? before / actual : 0;
426
- var extra = ratio > 1 ? Math.round((1 - 1 / ratio) * 100) : 0;
427
- var versus = (ba.baseline_provenance || {}).versus || '';
428
- var windows = savingsLimitWindows(rw, ratio, versus);
429
- if (!extra && !windows) return '';
469
+ if (!(ratio > 1)) return '';
470
+ var pctGain = Math.round((ratio - 1) * 100);
471
+ // Weekly window first; the 5-hour window is the fallback when no weekly
472
+ // reading exists. Live meter readings beat the last stored one.
473
+ function okWin(w) {
474
+ return w && w.used_pct != null && isFinite(Number(w.used_pct)) && Number(w.used_pct) >= 0 && Number(w.used_pct) <= 100;
475
+ }
476
+ var live = (Array.isArray(rw.windows) ? rw.windows : []).filter(okWin);
477
+ var stored = live.length ? [] : (Array.isArray(rw.last_known_windows) ? rw.last_known_windows : []).filter(okWin);
478
+ var pool = live.length ? live : stored;
479
+ var win = pool.filter(function(w) { return w.key === 'seven_day'; })[0] || pool[0] || null;
480
+ var used = win ? num(win.used_pct) : 0;
481
+ var rawWithout = used * ratio;
482
+ var withSuffix = win && win.key === 'five_hour' ? 'used in this 5-hour window' : 'used this week';
483
+ var withoutTxt = rawWithout >= 100
484
+ ? 'about ' + Math.round(rawWithout) + '%: right at your limit'
485
+ : Math.round(rawWithout) + '%';
486
+ // The bar names the user's own baseline: before install when that history exists, else the earliest tracked month.
487
+ var unitName = (ba.session_weight_pool || {}).work_unit || 'request';
488
+ var preInstall = /before you installed/i.test(String((ba.baseline_provenance || {}).lead || ''));
489
+ var barLabel = preInstall ? 'At your cost per ' + unitName + ' before you installed' : 'At your earliest month\u2019s cost per ' + unitName;
490
+ var bars = win
491
+ ? '<div class="st-limitbar"><div class="st-limitbar__label"><span>' + esc(barLabel) + '</span>' +
492
+ '<span class="st-limitbar__val">' + esc(withoutTxt) + '</span></div>' +
493
+ '<div class="st-limitbar__track"><span class="st-limitbar__fill st-limitbar__fill--ghost" style="width:' + Math.min(100, Math.round(rawWithout)) + '%"></span></div></div>' +
494
+ '<div class="st-limitbar"><div class="st-limitbar__label"><span>With Token Optimizer</span>' +
495
+ '<span class="st-limitbar__val">' + Math.round(used) + '% ' + esc(withSuffix) + '</span></div>' +
496
+ '<div class="st-limitbar__track"><span class="st-limitbar__fill" style="width:' + Math.round(used) + '%"></span></div></div>'
497
+ : '<p class="st-sub">No weekly limit reading right now; the comparison comes from your usage history.</p>';
498
+ // One-line basis: what the "before" side is, with friendly dates.
499
+ var prov = ba.baseline_provenance || {};
500
+ var basisSrc = String(prov.lead || 'compared with your earliest tracked month.');
501
+ var basis = basisSrc.replace(/(\d{4}-\d{2}-\d{2})\s+to\s+(\d{4}-\d{2}-\d{2})/g, function(m, a, b) {
502
+ return f.day(a) + ' to ' + f.day(b);
503
+ }).replace(/^compared with /i, 'Compared with ').replace(/\.?$/, '.');
504
+ basis = basis.charAt(0).toUpperCase() + basis.slice(1);
505
+ // Method fold: the direct measurement first, then what the rest is made of.
430
506
  var direct = num(rw.extra_work_pct);
431
- var method = '<p>Your usage is a meter reading. The ' + (versus ? 'comparison ' + esc(versus) : 'without-Token-Optimizer comparison') + ' is an estimate using the same before-and-after basis as your transformation: counterfactual monthly cost divided by actual monthly cost, multiplied by the used percentage and capped at 100%. Providers do not publish the exact weighting of usage limits.</p>' +
432
- (ratio ? '<p>' + savingsCents(before) + ' divided by ' + savingsCents(actual) + ' = &times;' + ratio.toFixed(2) + '.</p>' : '') +
433
- (direct > 0 ? '<p>Separately, directly measured savings imply about ' + direct + '% more work per token.</p>' : '');
507
+ var provider = (data && data.runtime) === 'codex' ? 'OpenAI' : 'Anthropic';
508
+ var methodLines = [];
509
+ if (direct > 0) methodLines.push('Measured directly by Token Optimizer: about ' + (Math.round(direct * 10) / 10) + '% more work per token');
510
+ methodLines.push('The rest comes from your setup, habits and model choices since your earliest tracked month');
511
+ if (prov.claim) methodLines.push('Token Optimizer was already running in that month, so the full gap is larger than shown');
512
+ methodLines.push(provider + "'s own improvements in that time are not separated out");
513
+ var method = '<ul>' + methodLines.map(function(l) { return '<li>' + esc(l) + '</li>'; }).join('') + '</ul>';
434
514
  return '<div class="card st-card st-limits-card">' +
435
- '<div class="st-limits__top"><h2 class="st-h">Your limits go further</h2>' + windows + '</div>' +
436
- '<div class="st-limits__bottom">' + (extra ? '<p>&asymp;' + extra + '% more room in your limits</p>' : '') +
437
- f.fold('How this is calculated', method) + '</div></div>';
515
+ '<div class="st-limits__head">' +
516
+ '<h2 class="st-h">Your limits go further</h2>' +
517
+ '<p class="st-limits__mega"><span class="st-mega st-mega--usd st-mega--card">' + pctGain + '%</span></p>' +
518
+ '<p class="st-lead">more work fits in your weekly limit</p>' +
519
+ '</div>' +
520
+ '<div class="st-limits__body">' +
521
+ bars +
522
+ '<p class="st-sub">' + esc(basis) + '</p>' +
523
+ (win && !live.length ? '<p class="st-sub">Last reading from your meter history.</p>' : '') +
524
+ f.fold('How this is calculated', method) +
525
+ '</div></div>';
438
526
  }
439
527
 
440
528
  // Still on the table: computable opportunities per period, each with one
441
529
  // action. A part the data cannot size is left out. Never part of any
442
530
  // savings total.
443
- function savingsOnTableHtml(data) {
531
+ function savingsOnTableHtml(data, extras) {
532
+ extras = extras || {};
533
+ var fixes = extras.fixes || {};
444
534
  var f = savingsStoryFmt(), num = f.num, has = f.has, usd = f.usd, tok = f.tok, count = f.count;
445
535
  var s = (data && data.savings) || {};
446
536
  var days = Number(s.period_days) || 30;
@@ -451,27 +541,41 @@ function savingsOnTableHtml(data) {
451
541
  var target = String(mr.target_model || '');
452
542
  var name = /sonnet/i.test(target) ? 'Sonnet' : /haiku/i.test(target) ? 'Haiku' : 'a lighter model';
453
543
  var frac = has(mr.routable_fraction) ? Math.round(num(mr.routable_fraction) * 100) : null;
454
- rows.push({ label: 'Model routing', action: 'Send routine work to ' + name, usd: num(mr.potential_cost_usd) });
544
+ rows.push({ key: 'routing', label: 'Model routing', action: 'Send routine work to ' + name, usd: num(mr.potential_cost_usd), fix: fixes.routing || null });
455
545
  how.push('<li>Model routing: if ' + (frac != null ? 'about ' + frac + '% of' : 'part of') + ' your Opus work ran on ' + name + ', new input and output priced at API rates. An assumption about your own work.</li>');
456
546
  }
457
547
  // The skill-listing row appears only when the user's own history sizes it;
458
548
  // with no earlier listing to compare, it is left out (never "Measuring").
459
549
  if (lb && typeof lb === 'object' && lb.available && num(lb.cost_usd) > 0) {
460
550
  var bm = /^\d{4}-\d{2}$/.test(lb.baseline_month || '') ? new Date(lb.baseline_month + '-01T00:00:00').toLocaleDateString('en-US', { month: 'short', year: 'numeric' }) : '';
461
- rows.push({ label: 'Skill listing', action: 'Trim the skill list budget', usd: num(lb.cost_usd) });
551
+ rows.push({ key: 'skills', label: 'Skill listing', action: 'Trim the skill list budget', usd: num(lb.cost_usd), fix: fixes.skills || null });
462
552
  how.push('<li>Skill listing: your skill list grew from ' + count(lb.baseline_chars) + ' to ' + count(lb.current_chars) + ' characters per message' + (bm ? ' since ' + esc(bm) : '') +
463
553
  '. Trimming it back is worth the ' + tok(lb.growth_tokens) + '-token difference &times; ' + count(lb.calls) + ' calls on this computer in the last ' + count(lb.period_days || days) + ' days &times; each call&rsquo;s cache-read price.</li>');
464
554
  }
465
555
  if (!rows.length) return '';
466
556
  var total = rows.reduce(function(a, r) { return a + r.usd; }, 0);
557
+ function fixBtn(r) {
558
+ var fx = r.fix;
559
+ if (!fx || !fx.view) return '';
560
+ return '<button type="button" class="st-fix" data-goto-view="' + esc(fx.view) + '"' +
561
+ (fx.idx != null && fx.idx !== '' ? ' data-goto-idx="' + esc(String(fx.idx)) + '"' : '') + '>Go to fix</button>';
562
+ }
563
+ var changeWord = rows.length === 1 ? 'this change' : (rows.length === 2 ? 'these two changes' : 'these ' + rows.length + ' changes');
467
564
  return '<div class="card st-table">' +
468
565
  '<h2 class="st-h">Still on the table</h2>' +
469
566
  '<div class="st-table__body"><p class="st-mega__item st-mega__item--card">' +
470
- '<span class="st-mega st-mega--warm st-mega--card">' + usd(total) + '</span><span class="st-mega__unit">more every ' + days + ' days, yours to claim</span></p>' +
567
+ '<span class="st-mega st-mega--route st-mega--card">' + usd(total) + '</span><span class="st-mega__unit">more every ' + days + ' days if you make ' + changeWord + '</span></p>' +
471
568
  '<div class="st-table__rows"><ul class="st-rows st-rows--card">' + rows.map(function(r) {
472
- return '<li><span>' + esc(r.label) + '<span class="st-sub">' + esc(r.action) + '</span></span><span class="st-v">' + usd(r.usd) + '</span></li>';
569
+ return '<li><span>' + esc(r.label) + '<span class="st-sub">' + esc(r.action) + '</span></span>' +
570
+ '<span class="st-fixcell"><span class="st-v">' + usd(r.usd) + '</span>' + fixBtn(r) + '</span></li>';
473
571
  }).join('') + '</ul>' +
474
572
  f.fold('How each one is sized', '<ul>' + how.join('') + '</ul><p>Valued at API rates, per ' + days + ' days. None of this is in any savings total.</p>') +
573
+ (Array.isArray(extras.parts) && extras.parts.length
574
+ ? f.fold('More changes you could make',
575
+ '<p>More changes to your setup or habits, beyond Still on the table. None of this is in any total above.</p>' +
576
+ extras.parts.map(function(p) { return '<p>' + esc(p) + '</p>'; }).join('') +
577
+ (extras.optimizerHint ? '<p>Run <strong>/token-optimizer</strong> and follow its suggestions to claim it.</p>' : ''))
578
+ : '') +
475
579
  '</div></div></div>';
476
580
  }
477
581
 
@@ -86,7 +86,7 @@
86
86
 
87
87
  ### Efficiency Grading
88
88
  Grades: S (90-100), A (80-89), B (70-79), C (55-69), D (40-54), F (0-39).
89
- Shown in status line (`ContextQ:A(82)`), dashboard, coach, and CLI.
89
+ Shown in status line (`Quality A 82`), dashboard, coach, and CLI.
90
90
 
91
91
  ### .contextignore
92
92
  Create `.contextignore` in project root or `~/.claude/.contextignore` (global). Uses gitignore-style glob patterns. Hard-blocks regardless of read-cache mode.
@@ -10,9 +10,9 @@ DOMAIN_MODULES = (
10
10
  # HOOK_IMPORT. No module-level facade code and no UserPromptSubmit handler
11
11
  # uses them (perf attribution, 2026-11-06).
12
12
  DEFERRED_MODULES = ('audit', 'dashboard', 'sessions', 'savings', 'cli')
13
- RUNTIME_SOURCES = ('__init__.py', '_compat.py') + tuple(name + '.py' for name in DOMAIN_MODULES) + ('dashboard_history.py', 'weekly_activity.py', 'headline.py', 'counted_position.py', 'counted_pricing_v5.py', 'transcript_backfill.py', 'counted_subagents.py', 'lean_resume_threshold.py', 'output_reread.py', 'session_effect.py', 'structural_ledger.py', 'structural_archives.py', 'structural_listing.py', 'structural_report.py', 'structural_seed.py', 'structural_value.py', 'rework_metrics.py', 'session_best.py', 'savings_story.py', 'counted_orphans.py', 'counted_cap.py', 'archive_void_evidence.py', 'cost_per_message_trend.py', 'lean_resume_receivers.py', 'routing_period.py', 'fixture_context.py', 'transcript_product.py', 'periphery_exposure.py', 'structure_funnel.py', 'setup_attachment_counter.py', 'first_read_outcomes.py', 'setup_budget_monitor.py', 'setup_connector_ledger.py', 'first_call_context.py', 'timestamp_cache.py', 'token_type_split.py', 'evidence_parallel.py', 'ttl_period.py', 'first_read_revive.py', 'mcp_archive_tripwire.py', 'compaction_survival.py', 'archive_void_codex.py', 'compression_fixture_void.py', 'feature_health.py', 'archive_health.py', 'coverage_report.py', 'file_refetch.py', 'holdout_report.py', 'structural_dedupe.py', 'setup_step.py', 'baseline_provenance.py', 'own_price_card.py', 'transcript_stream.py', 'checkpoint_direction.py', 'checkpoint_retention.py')
14
- RUNTIME_SOURCES += ('keepwarm_safety.py', 'keepwarm_economics.py', 'keepwarm_linux.py', 'keepwarm_prefix.py', 'keepwarm_response_filter.py', 'keepwarm_guard.py', 'keepwarm_guard_server.py', 'keepwarm_fork.py', 'mod_action_booking.py', 'mod_compaction_booking.py', 'mod_fresh_booking.py',)
15
- RUNTIME_SOURCES += ('quality_continuity.py', 'quality_checkpoint.py', 'codex_quality.py', 'lease_candidate_cleanup.py', 'session_store_spool.py', 'upgrade_drain_control.py', 'compression_scan_checkpoint.py', 'status_bar_lock.py', 'session_flush_lock.py', 'context_reset_marker.py', 'holdout_fallback.py', 'dashboard_heal_claim.py',)
13
+ RUNTIME_SOURCES = ('__init__.py', '_compat.py') + tuple(name + '.py' for name in DOMAIN_MODULES) + ('dashboard_history.py', 'weekly_activity.py', 'headline.py', 'counted_position.py', 'counted_pricing_v5.py', 'transcript_backfill.py', 'counted_subagents.py', 'lean_resume_threshold.py', 'output_reread.py', 'session_effect.py', 'structural_ledger.py', 'structural_archives.py', 'structural_listing.py', 'structural_report.py', 'structural_seed.py', 'structural_value.py', 'rework_metrics.py', 'session_best.py', 'savings_story.py', 'savings_headline.py', 'counted_orphans.py', 'counted_cap.py', 'archive_void_evidence.py', 'cost_per_message_trend.py', 'lean_resume_receivers.py', 'routing_period.py', 'fixture_context.py', 'transcript_product.py', 'periphery_exposure.py', 'structure_funnel.py', 'setup_attachment_counter.py', 'first_read_outcomes.py', 'setup_budget_monitor.py', 'setup_connector_ledger.py', 'first_call_context.py', 'timestamp_cache.py', 'token_type_split.py', 'evidence_parallel.py', 'ttl_period.py', 'first_read_revive.py', 'mcp_archive_tripwire.py', 'compaction_survival.py', 'archive_void_codex.py', 'compression_fixture_void.py', 'feature_health.py', 'archive_health.py', 'coverage_report.py', 'file_refetch.py', 'holdout_report.py', 'structural_dedupe.py', 'setup_step.py', 'baseline_provenance.py', 'own_price_card.py', 'transcript_stream.py', 'checkpoint_direction.py', 'checkpoint_retention.py')
14
+ RUNTIME_SOURCES += ('keepwarm_safety.py', 'keepwarm_economics.py', 'keepwarm_linux.py', 'mod_action_booking.py', 'mod_compaction_booking.py', 'mod_fresh_booking.py',)
15
+ RUNTIME_SOURCES += ('quality_continuity.py', 'quality_checkpoint.py', 'codex_quality.py', 'lease_candidate_cleanup.py', 'session_store_spool.py', 'upgrade_drain_control.py', 'compression_scan_checkpoint.py', 'status_bar_lock.py', 'session_flush_lock.py', 'context_reset_marker.py', 'holdout_fallback.py', 'dashboard_heal_claim.py', 'config_cache.py', 'setup_observation_cache.py', 'status_bar_refresh.py',)
16
16
  # Set True by hooks/userpromptsubmit_runner.py right before `import measure`,
17
17
  # which consumes it. That process never patches or enumerates the facade.
18
18
  HOOK_IMPORT = False
@@ -0,0 +1,63 @@
1
+ """Cache parsed local configuration, while leaving project fallback live.
2
+
3
+ Also scopes what one status-bar refresh may skip (see skip_cache_scan)."""
4
+ import copy
5
+ import contextvars
6
+ import threading
7
+ from contextlib import contextmanager
8
+
9
+ _cache = {}
10
+ _lock = threading.Lock()
11
+ _tier = contextvars.ContextVar('status_bar_pricing_tier', default=None)
12
+ _skip_scan = contextvars.ContextVar('status_bar_skip_cache_scan', default=False)
13
+
14
+
15
+ def current_tier():
16
+ return _tier.get()
17
+
18
+
19
+ @contextmanager
20
+ def pricing_snapshot(facade):
21
+ token = _tier.set(facade._load_pricing_tier())
22
+ try:
23
+ yield
24
+ finally:
25
+ _tier.reset(token)
26
+
27
+
28
+ def cache_scan_skipped():
29
+ return _skip_scan.get()
30
+
31
+
32
+ @contextmanager
33
+ def skip_cache_scan():
34
+ """Inside a status-bar refresh, skip the 30-day cache-waste transcript scan.
35
+
36
+ Its only output is the cache_drop opportunity block, which the status-bar
37
+ payload and savings_headline never read; the dashboard and CLI still scan.
38
+ """
39
+ token = _skip_scan.set(True)
40
+ try:
41
+ yield
42
+ finally:
43
+ _skip_scan.reset(token)
44
+
45
+
46
+ def clear():
47
+ with _lock:
48
+ _cache.clear()
49
+
50
+
51
+ def read(path, json_module):
52
+ try:
53
+ stat = path.stat()
54
+ key = (str(path), stat.st_mtime_ns, stat.st_size)
55
+ with _lock:
56
+ if key not in _cache:
57
+ value = json_module.loads(path.read_text(encoding='utf-8'))
58
+ _cache.clear()
59
+ _cache[key] = value if isinstance(value, dict) else {}
60
+ return copy.deepcopy(_cache[key])
61
+ except (OSError, ValueError, TypeError):
62
+ clear()
63
+ return {}
@@ -34,11 +34,13 @@ def _clean(parent):
34
34
 
35
35
 
36
36
  def publish(marker, now):
37
+ # A reset (/clear, compaction) is rare, so waiting up to 2 s for a competing writer is cheap; 50 ms and 0.5 s
38
+ # dropped a reset whenever eight writers raced on a slow-fsync disk (Windows CI), losing the newest timestamp.
37
39
  marker.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
38
40
  root = marker.parent.parent.parent / "session-store"
39
41
  root.mkdir(parents=True, exist_ok=True, mode=0o700)
40
42
  stripe = hashlib.sha256(str(marker).encode("utf-8")).digest()[0] & 15
41
- with _exclusive(root / (".context-reset-guard-%x" % stripe), timeout=0.05) as held:
43
+ with _exclusive(root / (".context-reset-guard-%x" % stripe), timeout=2.0) as held:
42
44
  if not held:
43
45
  return False
44
46
  _clean(marker.parent)
@@ -6,12 +6,14 @@ def contradicted(alias):
6
6
  chars = "CAST(REPLACE(substr({d}, instr({d}, '(')+1, instr({d}, ' chars >=')-instr({d}, '(')-1), ',', '') AS INTEGER)".format(d=detail)
7
7
  cap = "CAST(REPLACE(substr({d}, instr({d}, 'cap=')+4, instr({d}, ' tok,')-instr({d}, 'cap=')-4), ',', '') AS INTEGER)".format(d=detail)
8
8
  tool = "substr({d}, 12, instr(substr({d}, 12), ' result at cap')-1)".format(d=detail)
9
- return ("({a}.event_type = 'mcp_cap' AND ((instr({d}, ' chars >=') > 0 AND instr({d}, 'cap=') > 0 "
9
+ # CASE, not AND: SQLite before ~3.50 ran the EXISTS scan for every row whatever its event type, so
10
+ # a ledger of N archive rows cost N*N (the 50k-row status-bar test never finished on Linux and Windows).
11
+ return ("(CASE WHEN {a}.event_type = 'mcp_cap' THEN ((instr({d}, ' chars >=') > 0 AND instr({d}, 'cap=') > 0 "
10
12
  "AND {chars} > 0 AND {cap} > 0 AND {chars} <= 4 * {cap}) OR "
11
13
  "(COALESCE({a}.session_id, '') != '' AND {tool} != '' AND EXISTS "
12
14
  "(SELECT 1 FROM main.savings_events ar WHERE ar.event_type = 'tool_archive' "
13
15
  "AND ar.session_id = {a}.session_id AND substr(ar.detail, 1, length('replaced ' || {tool} || ' (')) = 'replaced ' || {tool} || ' (' "
14
- "AND abs((julianday(ar.timestamp)-julianday({a}.timestamp))*86400) <= 3))))").format(
16
+ "AND abs((julianday(ar.timestamp)-julianday({a}.timestamp))*86400) <= 3))) ELSE 0 END)").format(
15
17
  a=alias, d=detail, chars=chars, cap=cap, tool=tool)
16
18
 
17
19
 
@@ -147,12 +147,22 @@ def format_table(summary, source_note=""):
147
147
  return "\n".join(out)
148
148
 
149
149
 
150
+ def _cutoff(now, days):
151
+ """Oldest modification time the window admits. A window reaching before the epoch (``--days 36500``)
152
+ admits every file: Windows rejects pre-epoch local timestamps (OSError) and an absurd ``days``
153
+ overflows the date arithmetic on every platform."""
154
+ try:
155
+ return max(0.0, ((now or datetime.now()) - timedelta(days=days)).timestamp())
156
+ except (OverflowError, OSError, ValueError):
157
+ return 0.0
158
+
159
+
150
160
  def _transcripts(projects_dir, days, now=None):
151
161
  """Transcript files modified within ``days``, newest first, or None if the folder is missing."""
152
162
  root = Path(projects_dir)
153
163
  if not root.is_dir():
154
164
  return None
155
- cutoff = ((now or datetime.now()) - timedelta(days=days)).timestamp()
165
+ cutoff = _cutoff(now, days)
156
166
  files = []
157
167
  for p in root.rglob("*.jsonl"):
158
168
  try: