@alexgreensh/token-optimizer 5.13.67 → 5.13.69

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 (75) 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/package.json +1 -1
  5. package/skills/fleet-auditor/references/fleet-systems.md +38 -0
  6. package/skills/fleet-auditor/scripts/fleet.py +63 -92
  7. package/skills/fleet-auditor/scripts/fleet_base.py +106 -0
  8. package/skills/fleet-auditor/scripts/fleet_cursor_adapter.py +376 -0
  9. package/skills/token-coach/SKILL.md +21 -23
  10. package/skills/token-dashboard/SKILL.md +5 -4
  11. package/skills/token-optimizer/SKILL.md +1 -1
  12. package/skills/token-optimizer/assets/dashboard.html +101 -50
  13. package/skills/token-optimizer/references/cli-reference.md +1 -1
  14. package/skills/token-optimizer/references/cursor-workflow.md +1 -1
  15. package/skills/token-optimizer/references/phase0-setup.md +1 -1
  16. package/skills/token-optimizer/references/presentation-workflow.md +1 -1
  17. package/skills/token-optimizer/scripts/_measure/__init__.py +1 -1
  18. package/skills/token-optimizer/scripts/_measure/_vendor/README.md +8 -2
  19. package/skills/token-optimizer/scripts/_measure/_vendor/__init__.py +46 -6
  20. package/skills/token-optimizer/scripts/_measure/_vendor/tomli/__init__.py +34 -3
  21. package/skills/token-optimizer/scripts/_measure/audit.py +5 -21
  22. package/skills/token-optimizer/scripts/_measure/cli.py +86 -0
  23. package/skills/token-optimizer/scripts/_measure/daemon.py +34 -76
  24. package/skills/token-optimizer/scripts/_measure/dashboard.py +63 -37
  25. package/skills/token-optimizer/scripts/_measure/dashboard_history.py +79 -0
  26. package/skills/token-optimizer/scripts/_measure/lifecycle.py +88 -528
  27. package/skills/token-optimizer/scripts/_measure/savings.py +20 -70
  28. package/skills/token-optimizer/scripts/_measure/sessions.py +58 -20
  29. package/skills/token-optimizer/scripts/_measure/weekly_activity.py +69 -0
  30. package/skills/token-optimizer/scripts/{_measure/_vendor/tomli/_parser.py → _tomli.py} +156 -10
  31. package/skills/token-optimizer/scripts/antigravity_install.py +7 -0
  32. package/skills/token-optimizer/scripts/bash_compress.py +8 -40
  33. package/skills/token-optimizer/scripts/bash_compress_hook.py +6 -0
  34. package/skills/token-optimizer/scripts/bash_search_results.py +43 -0
  35. package/skills/token-optimizer/scripts/cloud_kit.py +22 -22
  36. package/skills/token-optimizer/scripts/codex_doctor.py +34 -8
  37. package/skills/token-optimizer/scripts/codex_hook_provenance.py +268 -0
  38. package/skills/token-optimizer/scripts/codex_install.py +33 -69
  39. package/skills/token-optimizer/scripts/command_filters.py +39 -309
  40. package/skills/token-optimizer/scripts/copilot_install.py +9 -0
  41. package/skills/token-optimizer/scripts/credential_patterns.py +4 -19
  42. package/skills/token-optimizer/scripts/credential_url_patterns.py +42 -0
  43. package/skills/token-optimizer/scripts/cursor_audit.py +723 -0
  44. package/skills/token-optimizer/scripts/cursor_bridge_checkpoint.py +213 -0
  45. package/skills/token-optimizer/scripts/cursor_bridge_payload.py +170 -0
  46. package/skills/token-optimizer/scripts/cursor_bridge_rewrite.py +106 -0
  47. package/skills/token-optimizer/scripts/cursor_bridge_rollup.py +115 -0
  48. package/skills/token-optimizer/scripts/cursor_coach.py +485 -0
  49. package/skills/token-optimizer/scripts/cursor_doctor.py +89 -9
  50. package/skills/token-optimizer/scripts/cursor_hook_bridge.py +393 -276
  51. package/skills/token-optimizer/scripts/cursor_install.py +111 -19
  52. package/skills/token-optimizer/scripts/cursor_quality.py +505 -0
  53. package/skills/token-optimizer/scripts/cursor_read_cache.py +597 -0
  54. package/skills/token-optimizer/scripts/cursor_session.py +26 -5
  55. package/skills/token-optimizer/scripts/cursor_state.py +8 -0
  56. package/skills/token-optimizer/scripts/cursor_statusline.py +372 -0
  57. package/skills/token-optimizer/scripts/cursor_thrash.py +78 -0
  58. package/skills/token-optimizer/scripts/cursor_transcript.py +223 -0
  59. package/skills/token-optimizer/scripts/devin_install.py +6 -12
  60. package/skills/token-optimizer/scripts/devin_source.py +17 -6
  61. package/skills/token-optimizer/scripts/devin_verify.py +17 -0
  62. package/skills/token-optimizer/scripts/grok_install.py +9 -0
  63. package/skills/token-optimizer/scripts/heal_report.py +92 -0
  64. package/skills/token-optimizer/scripts/hermes_doctor.py +4 -1
  65. package/skills/token-optimizer/scripts/hermes_install.py +4 -1
  66. package/skills/token-optimizer/scripts/hook_heal.py +138 -0
  67. package/skills/token-optimizer/scripts/hook_provenance.py +878 -0
  68. package/skills/token-optimizer/scripts/measure.py +2 -2
  69. package/skills/token-optimizer/scripts/owned_hooks.py +420 -0
  70. package/skills/token-optimizer/scripts/shipped_codex_hook_templates.json +5815 -0
  71. package/skills/token-optimizer/scripts/shipped_hook_templates.py +252 -0
  72. package/skills/token-optimizer/scripts/shipped_starter_hooks.py +55 -0
  73. package/skills/token-optimizer/scripts/thrash_guard.py +10 -5
  74. package/skills/token-optimizer/scripts/_measure/_vendor/tomli/_re.py +0 -112
  75. package/skills/token-optimizer/scripts/_measure/_vendor/tomli/_types.py +0 -10
@@ -2406,7 +2406,7 @@ function isNoInstructionHost(data) {
2406
2406
  return !!data && (data.runtime === 'cursor' || data.runtime === 'antigravity');
2407
2407
  }
2408
2408
  function hostRefreshHtml(data) {
2409
- return tcliHtml('<span class="update-cmd">TOKEN_OPTIMIZER_RUNTIME=' + esc(data.runtime) + ' python3 measure.py dashboard</span>');
2409
+ return tcliHtml('<span class="update-cmd">TOKEN_OPTIMIZER_RUNTIME=' + esc(data.runtime) + ' python3 measure.py dashboard --user</span>');
2410
2410
  }
2411
2411
  function hermesComponentDetails(c) {
2412
2412
  function fileSub(x, missing) {
@@ -3653,7 +3653,9 @@ var DB = (function() {
3653
3653
  var collectNote = isCodex
3654
3654
  ? tcliHtml('Codex sessions can be collected manually for now: <span class="update-cmd">TOKEN_OPTIMIZER_RUNTIME=codex python3 measure.py collect</span>')
3655
3655
  : tcliHtml('Sessions are collected automatically via the SessionEnd hook. Run a few sessions first, or manually: <span class="update-cmd">python3 measure.py collect</span>');
3656
- html += '<div class="empty-state">No trends data yet. ' + collectNote + '</div>';
3656
+ html += '<div class="empty-state">No trends data yet. ' + collectNote +
3657
+ ' <button class="date-nav-btn" onclick="window.__TOKEN_LOAD_HISTORY(\'all\', document.getElementById(\'history-load-message\'))">Load full history</button>' +
3658
+ '<span id="history-load-message" role="status"></span></div>';
3657
3659
  el.innerHTML = html;
3658
3660
  return;
3659
3661
  }
@@ -3757,21 +3759,32 @@ var DB = (function() {
3757
3759
  // Daily breakdown with date navigation
3758
3760
  var daily = t.daily || [];
3759
3761
  if (daily.length > 0) {
3760
- // Date nav: show 7 days by default, with picker to jump to a date
3762
+ var selectedRange = '7';
3763
+ try { selectedRange = localStorage.getItem('to-daily-range') || '7'; } catch (e) {}
3764
+ if (['7', '14', '30', '90', '180', 'all'].indexOf(selectedRange) < 0) selectedRange = '7';
3761
3765
  html += '<div class="card wide" id="daily-breakdown-card">' +
3762
3766
  '<div class="card-header"><span>Daily Breakdown</span></div>' +
3763
3767
  '<div style="font-size:12px;color:var(--c-text-dim);padding:0 0 var(--s-2) 0;">Click any row to expand per-session details with cost, quality scores, and cache data. ' + (isCodex ? 'Codex cache write TTL is not exposed, so those fields are hidden.' : 'Claude cache TTL mix is shown when available.') + ' Click a session for per-turn token breakdown.</div>' +
3764
3768
  '<div class="date-nav">' +
3765
- '<button class="date-nav-btn active" data-range="7">7 days</button>' +
3769
+ '<button class="date-nav-btn" data-range="7">7 days</button>' +
3766
3770
  '<button class="date-nav-btn" data-range="14">14 days</button>' +
3767
3771
  '<button class="date-nav-btn" data-range="30">30 days</button>' +
3772
+ '<button class="date-nav-btn" data-range="90">90 days</button>' +
3773
+ '<button class="date-nav-btn" data-range="180">180 days</button>' +
3774
+ '<button class="date-nav-btn" data-range="all">All</button>' +
3775
+ '<button class="date-nav-btn" id="load-full-history">Load full history</button>' +
3776
+ '<span id="history-load-message" role="status"></span>' +
3768
3777
  '<span style="color:var(--c-text-dim);font-size:12px;margin:0 4px;">|</span>' +
3769
3778
  '<label style="font-size:12px;color:var(--c-text-dim);font-family:var(--font-mono);">Jump to:</label>' +
3770
3779
  '<input type="date" class="date-picker-input" id="daily-date-picker" value="' + esc(daily[0].date) + '">' +
3771
3780
  '</div>';
3772
3781
  html += '<div id="daily-table-container">';
3773
- html += buildDailyTable(daily, 7, null);
3782
+ html += buildDailyTable(daily, selectedRange, null);
3774
3783
  html += '</div></div>';
3784
+ } else {
3785
+ html += '<div class="empty-state">No daily sessions in this window. ' +
3786
+ '<button class="date-nav-btn" onclick="window.__TOKEN_LOAD_HISTORY(\'all\', document.getElementById(\'history-load-message\'))">Load full history</button>' +
3787
+ '<span id="history-load-message" role="status"></span></div>';
3775
3788
  }
3776
3789
 
3777
3790
  // Skills usage bar chart with clickable skill details
@@ -3858,27 +3871,34 @@ var DB = (function() {
3858
3871
 
3859
3872
  el.innerHTML = html;
3860
3873
 
3861
- // Bind date range buttons + picker
3874
+ // The table range is local to the browser; the embedded window is saved
3875
+ // by the generator and can be expanded explicitly through the local server.
3862
3876
  if (daily.length > 0) {
3863
3877
  var container = document.getElementById('daily-table-container');
3864
3878
  var rangeBtns = document.querySelectorAll('.date-nav-btn[data-range]');
3879
+ var historyMessage = document.getElementById('history-load-message');
3880
+ function setRange(range) {
3881
+ selectedRange = range;
3882
+ try { localStorage.setItem('to-daily-range', range); } catch (e) {}
3883
+ rangeBtns.forEach(function(b) { b.classList.toggle('active', b.getAttribute('data-range') === range); });
3884
+ container.innerHTML = buildDailyTable(daily, range, null);
3885
+ }
3886
+ setRange(selectedRange);
3865
3887
  rangeBtns.forEach(function(btn) {
3866
3888
  btn.addEventListener('click', function() {
3867
- rangeBtns.forEach(function(b) { b.classList.remove('active'); });
3868
- this.classList.add('active');
3869
- var range = parseInt(this.getAttribute('data-range'), 10);
3870
- container.innerHTML = buildDailyTable(daily, range, null);
3889
+ var range = this.getAttribute('data-range');
3890
+ setRange(range);
3891
+ if (range !== 'all' && Number(range) > Number(t.period_days || 0)) window.__TOKEN_LOAD_HISTORY(Number(range), historyMessage);
3871
3892
  });
3872
3893
  });
3894
+ document.getElementById('load-full-history').addEventListener('click', function() {
3895
+ setRange('all');
3896
+ window.__TOKEN_LOAD_HISTORY('all', historyMessage);
3897
+ });
3873
3898
  var picker = document.getElementById('daily-date-picker');
3874
- if (picker) {
3875
- picker.addEventListener('change', function() {
3876
- var activeBtn = document.querySelector('.date-nav-btn[data-range].active');
3877
- var range = activeBtn ? parseInt(activeBtn.getAttribute('data-range'), 10) || 7 : 7;
3878
- rangeBtns.forEach(function(b) { b.classList.remove('active'); });
3879
- container.innerHTML = buildDailyTable(daily, range, this.value);
3880
- });
3881
- }
3899
+ if (picker) picker.addEventListener('change', function() {
3900
+ container.innerHTML = buildDailyTable(daily, selectedRange, this.value);
3901
+ });
3882
3902
  }
3883
3903
 
3884
3904
  // Bind skill detail expand
@@ -3971,7 +3991,7 @@ var DB = (function() {
3971
3991
  names.forEach(function(name) {
3972
3992
  cmd += ' && mv "$HOME/.claude/skills/"' + shellQuote(name) + ' "$ARCHIVE_DIR/"';
3973
3993
  });
3974
- cmd += ' && echo "Archived ' + names.length + tcli(' skill(s). Regenerate dashboard: python3 measure.py dashboard"');
3994
+ cmd += ' && echo "Archived ' + names.length + tcli(' skill(s). Regenerate dashboard: python3 measure.py dashboard --user"');
3975
3995
 
3976
3996
  if (navigator.clipboard && navigator.clipboard.writeText) {
3977
3997
  navigator.clipboard.writeText(cmd).then(function() {
@@ -4001,20 +4021,18 @@ var DB = (function() {
4001
4021
  return 'avg ' + fmtGap(avgGap) + ' | max ' + fmtGap(maxGap);
4002
4022
  }
4003
4023
 
4004
- function buildDailyTable(daily, range, jumpToDate) {
4024
+ function selectDailyRange(daily, range, jumpToDate) {
4025
+ if (!daily.length) return [];
4026
+ var start = jumpToDate || daily[0].date;
4027
+ if (range === 'all') return daily.filter(function(d) { return d.date <= start; });
4028
+ var end = new Date(start + 'T00:00:00Z');
4029
+ end.setUTCDate(end.getUTCDate() - Number(range) + 1);
4030
+ var cutoff = end.toISOString().slice(0, 10);
4031
+ return daily.filter(function(d) { return d.date <= start && d.date >= cutoff; });
4032
+ }
4005
4033
 
4006
- // Filter daily data based on range or jump-to date
4007
- var filtered;
4008
- if (jumpToDate) {
4009
- // Show 7 days starting from the selected date
4010
- var startDate = jumpToDate;
4011
- var endDate = new Date(jumpToDate);
4012
- endDate.setDate(endDate.getDate() - range + 1);
4013
- var endStr = endDate.toISOString().slice(0, 10);
4014
- filtered = daily.filter(function(d) { return d.date <= startDate && d.date >= endStr; });
4015
- } else {
4016
- filtered = daily.slice(0, range);
4017
- }
4034
+ function buildDailyTable(daily, range, jumpToDate) {
4035
+ var filtered = selectDailyRange(daily, range, jumpToDate);
4018
4036
 
4019
4037
  if (filtered.length === 0) {
4020
4038
  return '<div class="empty-state">No sessions found for this period.</div>';
@@ -4216,11 +4234,14 @@ var DB = (function() {
4216
4234
  var savedUsd = Number(w.saved_usd);
4217
4235
  var spanWord = w.key === 'five_hour' ? '5h' : 'week';
4218
4236
  var hasUsd = isFinite(savedUsd) && (w.key === 'five_hour' ? savedUsd > 0 : savedUsd >= 15);
4219
- var usdCaption = w.key === 'seven_day'
4220
- ? 'in API-equivalent savings this week' : 'in API-equivalent savings this 5h';
4237
+ // Without a whole-week estimate the figure is only the event-by-event count, so say so.
4238
+ var usdCaption = w.full_value
4239
+ ? (w.key === 'seven_day' ? 'in API-equivalent savings this week' : 'in API-equivalent savings this 5h')
4240
+ : (w.key === 'seven_day' ? 'in counted savings this week (partial)' : 'in counted savings this 5h (partial)');
4221
4241
  var usdExplainer = w.full_value
4222
4242
  ? 'Estimated additional cost at API prices for the same work without Token Optimizer. Includes lighter context, fewer repeat reads and working habits, counted once. Your plan may cover some or all of that usage.'
4223
- : 'API-equivalent value of the savings recorded in this window, including the available estimates.';
4243
+ : 'Only the savings counted one event at a time, at API prices. This is a floor, not the whole saving. A whole-week estimate appears when your work measures consistently against your baseline; this window it did not.';
4244
+ if (w.full_value && w.full_value.coverage && w.full_value.coverage.priced_sessions < w.full_value.coverage.total_sessions && Number(w.full_value.saved_usd) >= savedUsd) usdExplainer += ' Based on ' + Number(w.full_value.coverage.priced_sessions) + ' of ' + Number(w.full_value.coverage.total_sessions) + ' sessions; missing sessions are not estimated.';
4224
4245
  if (w.full_value && w.full_value.start) {
4225
4246
  usdExplainer += ' Since ' + esc(new Date(w.full_value.start).toLocaleString([], {month:'short', day:'numeric', hour:'numeric', minute:'2-digit'})) + '.';
4226
4247
  }
@@ -4260,7 +4281,7 @@ var DB = (function() {
4260
4281
  rwCards += '<div style="padding:var(--s-3);border:1px solid var(--c-border);border-radius:8px;">' +
4261
4282
  '<div class="label">Weekly savings</div><div style="font-size:22px;color:var(--c-savings-alt,#10b981);">&asymp;' +
4262
4283
  rwMoney(standaloneWeek.saved_usd) + ' in API-equivalent savings this week</div>' +
4263
- '<p>Full workload estimate since ' + esc(new Date(standaloneWeek.start).toLocaleString()) +
4284
+ '<p>Full workload estimate' + (standaloneWeek.coverage && standaloneWeek.coverage.priced_sessions < standaloneWeek.coverage.total_sessions ? ' based on ' + Number(standaloneWeek.coverage.priced_sessions) + ' of ' + Number(standaloneWeek.coverage.total_sessions) + ' sessions, missing sessions are not estimated,' : '') + ' since ' + esc(new Date(standaloneWeek.start).toLocaleString()) +
4264
4285
  '. Your weekly limit reading is unavailable.</p></div>';
4265
4286
  }
4266
4287
  // USD-per-window headline: the dollar figure reuses the metered
@@ -4271,10 +4292,7 @@ var DB = (function() {
4271
4292
  (rw.windows || []).forEach(function (w) {
4272
4293
  var v = Number(w.saved_usd);
4273
4294
  if (!isFinite(v) || v <= 0) return;
4274
- // Honest label -- API-credit overage over the window's own real span, not
4275
- // a slice of a longer ledger. The weekly dollar is aligned to the
4276
- // subscription limit reset boundary (not a rolling 7-day lookback), so
4277
- // it does not drift down as heavy days age out.
4295
+ // The weekly figure follows the subscription reset boundary.
4278
4296
  var span = w.key === 'five_hour' ? 'past 5h' : 'since your limit reset';
4279
4297
  usdParts.push('<em style="font-style:normal;color:var(--c-accent-cyan);">' + rwMoney(v) + '</em> ' + span);
4280
4298
  });
@@ -4725,14 +4743,14 @@ var DB = (function() {
4725
4743
  // is the net<=0 branch — parity with OpenClaw/OpenCode.
4726
4744
  html += '<div class="card wide" style="padding:var(--s-5) var(--s-4);margin-bottom:var(--s-3);">' +
4727
4745
  '<div class="label" style="margin-bottom:var(--s-2);">At or above your baseline this period</div>' +
4728
- '<div class="lede">Your recent sessions cost about what your frozen baseline would have — est. <strong>' + money(ba.actual_monthly_usd) + '/mo</strong> now vs <strong>' + money(ba.counterfactual_monthly_usd) + '/mo</strong> the old way. There is no net saving to headline this period, so we are not showing one. The figure below is what Token Optimizer counted directly, action by action.</div>' +
4746
+ '<div class="lede">Your recent sessions cost about what your frozen baseline would have — est. <strong>' + money(ba.actual_monthly_usd) + '</strong> now vs <strong>' + money(ba.counterfactual_monthly_usd) + '</strong> the old way in the last ' + days + ' days. There is no net saving to headline this period, so we are not showing one. The figure below is what Token Optimizer counted directly, action by action.</div>' +
4729
4747
  '</div>';
4730
4748
  } else if (ba.reason === 'flat') {
4731
4749
  // Both work-unit methods sit within a few percent of spend: no
4732
4750
  // measurable whole-workload change, so no headline and no scary number.
4733
4751
  html += '<div class="card wide" style="padding:var(--s-5) var(--s-4);margin-bottom:var(--s-3);">' +
4734
4752
  '<div class="label" style="margin-bottom:var(--s-2);">No measurable change in cost per unit of work</div>' +
4735
- '<div class="plain-line">Your recent work costs about the same per request as before install (' + money(ba.actual_monthly_usd) + '/mo now vs ' + money(ba.counterfactual_monthly_usd) + '/mo the old way). The savings below are counted action by action.</div>' +
4753
+ '<div class="plain-line">Your recent work costs about the same per request as before install (' + money(ba.actual_monthly_usd) + ' now vs ' + money(ba.counterfactual_monthly_usd) + ' the old way over ' + days + ' days). The savings below are counted action by action.</div>' +
4736
4754
  '</div>';
4737
4755
  } else if (ba.reason === 'methods_disagree') {
4738
4756
  // The two independent work-unit methods (per-API-call and per-message)
@@ -4752,8 +4770,8 @@ var DB = (function() {
4752
4770
  };
4753
4771
  html += '<div class="card wide" style="padding:var(--s-5) var(--s-4);margin-bottom:var(--s-3);">' +
4754
4772
  '<div class="label" style="margin-bottom:var(--s-2);">Two estimates disagree this period</div>' +
4755
- '<div class="lede">The ' + mainUnit + ' estimate is <strong>' + signedMoney(mainUsd) + '/mo</strong> and the ' + crossUnit +
4756
- ' estimate is <strong>' + signedMoney(crossUsd) + '/mo</strong>. They are too far apart to headline either one. The figure below is what Token Optimizer counted directly, action by action.</div>' +
4773
+ '<div class="lede">The ' + mainUnit + ' estimate is <strong>' + signedMoney(mainUsd) + '</strong> and the ' + crossUnit +
4774
+ ' estimate is <strong>' + signedMoney(crossUsd) + '</strong> over ' + days + ' days. They are too far apart to headline either one. The figure below is what Token Optimizer counted directly, action by action.</div>' +
4757
4775
  '</div>';
4758
4776
  }
4759
4777
 
@@ -5801,8 +5819,8 @@ var DB = (function() {
5801
5819
  var isCodex = data.runtime === 'codex';
5802
5820
  var codexSetup = (data.manage && data.manage.codex) || {};
5803
5821
  var refreshCmd = isCodex
5804
- ? tcli('TOKEN_OPTIMIZER_RUNTIME=codex python3 measure.py dashboard')
5805
- : tcli('python3 measure.py dashboard');
5822
+ ? tcli('TOKEN_OPTIMIZER_RUNTIME=codex python3 measure.py dashboard --user')
5823
+ : tcli('python3 measure.py dashboard --user');
5806
5824
 
5807
5825
  var html = '<div class="section-header">' +
5808
5826
  '<div class="label">Configuration</div>' +
@@ -6064,7 +6082,7 @@ var DB = (function() {
6064
6082
  ? 'Your ' + esc(data.runtime_label || 'runtime') + ' skills and MCP servers, read from its own files. Token Optimizer feature toggles are below.'
6065
6083
  : window.__TOKEN_API_LIVE
6066
6084
  ? '<span style="color:var(--c-accent-cyan);font-weight:600;">Live mode</span> — toggles apply instantly to settings. <strong>Restart ' + (isCodex ? 'Codex' : isNoInstructionHost(data) ? esc(data.runtime_label || 'the runtime') : 'Claude') + '</strong> to activate changes.'
6067
- : tcliHtml('Open in serve mode for live toggles: <code style="background:var(--c-bg);padding:2px 5px;border-radius:4px;">python3 measure.py dashboard --serve</code>')) +
6085
+ : tcliHtml('Open in serve mode for live toggles: <code style="background:var(--c-bg);padding:2px 5px;border-radius:4px;">python3 measure.py dashboard --user --serve</code>')) +
6068
6086
  '</p>' +
6069
6087
  '</div>';
6070
6088
 
@@ -6442,7 +6460,7 @@ var DB = (function() {
6442
6460
  title: 'Toggling v5 features needs a terminal',
6443
6461
  body: 'The read-only dashboard server can\u2019t write config. Run this in a terminal:',
6444
6462
  cmd: cliCmd,
6445
- hint: tcli('Or re-open the dashboard with full API: python3 measure.py dashboard --serve')
6463
+ hint: tcli('Or re-open the dashboard with full API: python3 measure.py dashboard --user --serve')
6446
6464
  });
6447
6465
  return;
6448
6466
  }
@@ -7480,7 +7498,7 @@ document.addEventListener('DOMContentLoaded', function() {
7480
7498
 
7481
7499
  var data = window.__TOKEN_DATA__;
7482
7500
  if (!data) {
7483
- document.body.innerHTML = '<div style="max-width:820px;margin:80px auto;padding:32px;border:1px solid var(--c-border);border-radius:14px;background:var(--c-surface);color:var(--c-text-main);font-family:system-ui,sans-serif;line-height:1.6;"><h1 style="margin-top:0;">Token Optimizer</h1><p><strong>You opened the dashboard template.</strong> This file intentionally contains no local metrics. Generate the runtime dashboard first, then open the generated file.</p><p style="margin-bottom:8px;color:var(--c-text-dim);">From the Token Optimizer checkout:</p><code style="display:block;white-space:normal;background:var(--c-elev-3);padding:12px;border-radius:8px;color:var(--c-text-main);">TOKEN_OPTIMIZER_RUNTIME=codex python3 skills/token-optimizer/scripts/measure.py dashboard</code><p style="margin:18px 0 8px;color:var(--c-text-dim);">Generated Codex dashboard path:</p><code style="display:block;white-space:normal;background:var(--c-elev-3);padding:12px;border-radius:8px;color:var(--c-text-main);">~/.codex/_backups/token-optimizer/dashboard.html</code></div>';
7501
+ document.body.innerHTML = '<div style="max-width:820px;margin:80px auto;padding:32px;border:1px solid var(--c-border);border-radius:14px;background:var(--c-surface);color:var(--c-text-main);font-family:system-ui,sans-serif;line-height:1.6;"><h1 style="margin-top:0;">Token Optimizer</h1><p><strong>You opened the dashboard template.</strong> This file intentionally contains no local metrics. Generate the runtime dashboard first, then open the generated file.</p><p style="margin-bottom:8px;color:var(--c-text-dim);">From the Token Optimizer checkout:</p><code style="display:block;white-space:normal;background:var(--c-elev-3);padding:12px;border-radius:8px;color:var(--c-text-main);">TOKEN_OPTIMIZER_RUNTIME=codex python3 skills/token-optimizer/scripts/measure.py dashboard --user</code><p style="margin:18px 0 8px;color:var(--c-text-dim);">Generated Codex dashboard path:</p><code style="display:block;white-space:normal;background:var(--c-elev-3);padding:12px;border-radius:8px;color:var(--c-text-main);">~/.codex/_backups/token-optimizer/dashboard.html</code></div>';
7484
7502
  return;
7485
7503
  }
7486
7504
  var runtimeLabel = data.runtime_label || (data.runtime === 'codex' ? 'Codex' : 'Claude Code');
@@ -7498,7 +7516,15 @@ document.addEventListener('DOMContentLoaded', function() {
7498
7516
  brandMeta.textContent = brandParts.join(' \u00b7 ');
7499
7517
  }
7500
7518
 
7501
- function startApp() { DB.init(data); refreshSavingsLive(); }
7519
+ function startApp() {
7520
+ DB.init(data); refreshSavingsLive();
7521
+ try {
7522
+ if (sessionStorage.getItem('to-history-return')) {
7523
+ sessionStorage.removeItem('to-history-return');
7524
+ document.querySelector('.nav-item[data-view="trends"]').click();
7525
+ }
7526
+ } catch (e) {}
7527
+ }
7502
7528
 
7503
7529
  // Pull fresh savings from the daemon and live-patch the Savings/Overview tiles.
7504
7530
  // No-op unless the custom API is live (served over http, health probe passed) —
@@ -7575,6 +7601,31 @@ document.addEventListener('DOMContentLoaded', function() {
7575
7601
  });
7576
7602
  };
7577
7603
 
7604
+ window.__TOKEN_LOAD_HISTORY = function(choice, message) {
7605
+ if (choice === 'all') { try { localStorage.setItem('to-daily-range', 'all'); } catch (e) {} }
7606
+ if (!window.__TOKEN_API_LIVE) {
7607
+ message.textContent = 'Open the dashboard through the local server to load more history.';
7608
+ return;
7609
+ }
7610
+ message.textContent = 'Loading history…';
7611
+ function attempt(retried) {
7612
+ window.__TOKEN_API_POST('/api/regenerate', {days: choice}).then(function(r) { return r.json(); })
7613
+ .then(function(result) {
7614
+ if (!result.ok) throw new Error(result.msg || 'Regeneration failed');
7615
+ try { sessionStorage.setItem('to-history-return', '1'); } catch (e) {}
7616
+ location.reload();
7617
+ }).catch(function(err) {
7618
+ if (err.authError && !retried) {
7619
+ _fetchToken(window.__TOKEN_API_BASE || '').then(function() { attempt(true); })
7620
+ .catch(function(e) { message.textContent = 'Could not load history: ' + e.message; });
7621
+ } else message.textContent = 'Could not load history: ' + err.message;
7622
+ });
7623
+ }
7624
+ if (window.__TOKEN_API_TOKEN) attempt(false);
7625
+ else _fetchToken(window.__TOKEN_API_BASE || '').then(function() { attempt(false); })
7626
+ .catch(function(e) { message.textContent = 'Could not load history: ' + e.message; });
7627
+ };
7628
+
7578
7629
  // Manual regeneration. The background freshness regen is stale-while-revalidate:
7579
7630
  // it serves the current file and refreshes for NEXT time, so a reader who wants
7580
7631
  // current numbers now would have to reload twice and never knows that. This is
@@ -5,7 +5,7 @@
5
5
  - `measure.py report` -- Token overhead report with per-component breakdown
6
6
  - `measure.py snapshot [label]` -- Save a measurement snapshot
7
7
  - `measure.py compare` -- Compare before/after snapshots
8
- - `measure.py dashboard [--coord-path PATH]` -- Generate interactive HTML dashboard
8
+ - `measure.py dashboard [--user] [--coord-path PATH]` -- Generate interactive HTML dashboard (`--user` marks a person-initiated run so the 20s hook budget does not apply on piped stdin)
9
9
  - `measure.py setup-daemon [--uninstall]` -- Bookmarkable dashboard URL (macOS/Windows)
10
10
  - `measure.py trends [--days N] [--json]` -- Skill adoption, model mix, overhead over time
11
11
  - `measure.py health` -- Session hygiene: stale/zombie sessions, version checks
@@ -42,7 +42,7 @@ Resolve `$MEASURE_PY` and `$PY` first with the SKILL.md Step 0b snippet (this fi
42
42
  "$PY" "$MEASURE_PY" cursor-doctor --probe # replay each wired event through the installed command
43
43
  TOKEN_OPTIMIZER_RUNTIME=cursor "$PY" "$MEASURE_PY" cursor-summary
44
44
  TOKEN_OPTIMIZER_RUNTIME=cursor "$PY" "$MEASURE_PY" cursor-rollup
45
- "$PY" "$MEASURE_PY" cursor-uninstall # remove only Token Optimizer's entries + payload
45
+ "$PY" "$MEASURE_PY" cursor-uninstall # remove hooks, payload and derived caches; keep session history
46
46
  ```
47
47
 
48
48
  Install from a checkout with `bash install.sh --cursor` (merges into Cursor's
@@ -109,7 +109,7 @@ First-time install prompt:
109
109
 
110
110
  After you run `setup-daemon`, the dashboard is served at:
111
111
  URL: http://localhost:24842/token-optimizer
112
- Until then, open the file path `measure.py dashboard` prints on its ` Dashboard: ` line. The location is install-dependent, so read it from the output rather than assuming a literal path.
112
+ Until then, open the file path `measure.py dashboard --user` prints on its ` Dashboard: ` line. The location is install-dependent, so read it from the output rather than assuming a literal path.
113
113
 
114
114
  What installing the URL does:
115
115
  - Runs a tiny web server on your machine (~2MB memory)
@@ -39,7 +39,7 @@ What should we tackle first?
39
39
  ## Dashboard Generation
40
40
 
41
41
  ```bash
42
- "$PY" "$MEASURE_PY" dashboard --coord-path "$COORD_PATH"
42
+ "$PY" "$MEASURE_PY" dashboard --user --coord-path "$COORD_PATH"
43
43
  ```
44
44
 
45
45
  Tell the user: "Dashboard opened in your browser. Browse findings by category, check the optimizations you want, click Copy Prompt and paste back here. Or just tell me directly what to tackle."
@@ -10,7 +10,7 @@ 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)
13
+ RUNTIME_SOURCES = ('__init__.py', '_compat.py') + tuple(name + '.py' for name in DOMAIN_MODULES) + ('dashboard_history.py', 'weekly_activity.py')
14
14
  # Set True by hooks/userpromptsubmit_runner.py right before `import measure`,
15
15
  # which consumes it. That process never patches or enumerates the facade.
16
16
  HOOK_IMPORT = False
@@ -1,9 +1,15 @@
1
1
  # Vendored TOML reader
2
2
 
3
- `tomli/` is the unmodified pure-Python source from Tomli 2.2.1, licensed under MIT (see `tomli/LICENSE`). It supplies TOML 1.0 parsing on Python 3.9 and 3.10 without a pip dependency. Python 3.11+ continues to use its standard-library `tomllib`.
3
+ The parser source is the flat `../../../_tomli.py` module (Tomli 2.2.1, MIT,
4
+ Taneli Hukkinen; SPDX headers in the file, full text in `tomli/LICENSE`).
5
+ It is the single copy: Devin's closed payload ships `_tomli.py` because it
6
+ forbids `_measure` imports, and `_measure._vendor.tomli` re-exports it so
7
+ repo code keeps one lazy entry point. Python 3.11+ uses stdlib `tomllib`.
4
8
 
5
9
  Source: https://pypi.org/project/tomli/2.2.1/
6
10
  Archive: https://files.pythonhosted.org/packages/18/87/302344fed471e44a87289cf4967697d07e532f2421fdaf868a303cbae4ff/tomli-2.2.1.tar.gz
7
11
  Archive SHA256: `cd45e1dc79c835ce60f7404ec8119f2eb06d38b1deba146f07ced3bbc44505ff`
8
12
 
9
- The source files and `py.typed` are copied from `src/tomli/`; `LICENSE` is copied from the archive root. Keep these files unchanged when updating. The package stays below `_measure` so the existing installed-source refusal boundary covers it too. It is not an extraction provider or public API.
13
+ `tomli/__init__.py` is a compatibility shim over `_tomli`; `LICENSE` and
14
+ `py.typed` are kept from the upstream package. It is not an extraction
15
+ provider or public API.
@@ -1,18 +1,58 @@
1
1
  """Private, license-preserving runtime dependencies; no runtime installation."""
2
- import importlib.util as _util
2
+ import importlib.util
3
+ import os as _os
3
4
  import sys as _sys
4
5
 
5
6
 
6
7
  def _lazy(name):
7
- """Return module ``name`` with its code deferred to first attribute access."""
8
+ """Return module ``name`` deferred to first attribute access.
9
+
10
+ The module object is registered in sys.modules immediately, but its code
11
+ runs only on the first attribute miss. No lock is held across that exec:
12
+ the shim's own __getattr__ keeps resolving parser attributes lazily, and
13
+ a fork child detects the inherited in-flight exec by pid and binds the
14
+ parser module directly instead of re-entering dead import state.
15
+ """
8
16
  module = _sys.modules.get(name)
9
17
  if module is not None:
10
18
  return module
11
- spec = _util.find_spec(name)
12
- spec.loader = _util.LazyLoader(spec.loader)
13
- module = _util.module_from_spec(spec)
19
+ spec = importlib.util.find_spec(name)
20
+ module = importlib.util.module_from_spec(spec)
21
+ pid = _os.getpid()
22
+
23
+ def _getattr(attr):
24
+ if _os.getpid() == pid:
25
+ spec.loader.exec_module(module)
26
+ try:
27
+ return module.__dict__[attr]
28
+ except KeyError:
29
+ pass
30
+ # The shim installed its own lazy __getattr__ during exec; it
31
+ # resolves parser attributes on demand. Anything else missing is
32
+ # a genuine AttributeError from that resolver.
33
+ module_getattr = module.__dict__.get('__getattr__')
34
+ if module_getattr is not None and module_getattr is not _getattr:
35
+ return module_getattr(attr)
36
+ else:
37
+ # Fork child: the parent's first exec of ``name`` was in flight,
38
+ # so its import lock is inherited held by a thread that does not
39
+ # exist here and exec_module could never finish. Bind the parser
40
+ # module's public names directly; _tomli's own lock is free.
41
+ impl = importlib.import_module('_tomli')
42
+ for key in ('TOMLDecodeError', '__version__', 'load', 'loads', '__all__'):
43
+ try:
44
+ module.__dict__[key] = getattr(impl, key)
45
+ except AttributeError:
46
+ pass
47
+ module.__dict__.pop('__getattr__', None)
48
+ try:
49
+ return module.__dict__[attr]
50
+ except KeyError:
51
+ raise AttributeError(
52
+ "module {!r} has no attribute {!r}".format(name, attr)) from None
53
+
54
+ module.__dict__['__getattr__'] = _getattr
14
55
  _sys.modules[name] = module
15
- spec.loader.exec_module(module)
16
56
  return module
17
57
 
18
58
 
@@ -2,7 +2,38 @@
2
2
  # SPDX-FileCopyrightText: 2021 Taneli Hukkinen
3
3
  # Licensed to PSF under a Contributor Agreement.
4
4
 
5
- __all__ = ("loads", "load", "TOMLDecodeError")
6
- __version__ = "2.2.1" # DO NOT EDIT THIS LINE MANUALLY. LET bump2version UTILITY DO IT
5
+ # Compatibility shim: the canonical flat copy ships as the _tomli payload
6
+ # module so Devin's closed set can use it without _measure imports. This
7
+ # package exists only so `from _measure._vendor import tomli` keeps working;
8
+ # _vendor's lazy loader still defers the real parser to first TOML access.
9
+ import importlib as _importlib
10
+
11
+ _EXPORTS = ("TOMLDecodeError", "__version__", "load", "loads")
12
+
7
13
 
8
- from ._parser import TOMLDecodeError, load, loads
14
+ def __getattr__(attr):
15
+ if attr not in _EXPORTS:
16
+ raise AttributeError(
17
+ "module '_measure._vendor.tomli' has no attribute {!r}".format(attr))
18
+ mod = _importlib.import_module("_tomli")
19
+ try:
20
+ value = getattr(mod, attr)
21
+ except AttributeError:
22
+ # _tomli is still executing its own first import on this thread (an
23
+ # import-time callback re-entered the facade). Hand back a resolver
24
+ # that delegates once the parser module finishes; it is not cached,
25
+ # so the real attribute binds on the next access.
26
+ def value(*args, **kwargs):
27
+ target = getattr(_importlib.import_module("_tomli"), attr, None)
28
+ if target is None:
29
+ raise RuntimeError(
30
+ "_tomli is still executing its first import; "
31
+ "tomli.{}() cannot run re-entrantly".format(attr))
32
+ globals()[attr] = target
33
+ return target(*args, **kwargs)
34
+ return value
35
+ globals()[attr] = value
36
+ return value
37
+
38
+
39
+ __all__ = ("loads", "load", "TOMLDecodeError")
@@ -3110,28 +3110,12 @@ def doctor(as_json=None):
3110
3110
  checks.append(("OK", "Dashboard daemon", "status unknown (probe failed)"))
3111
3111
  score += 1
3112
3112
 
3113
- # Settings self-heal history (visible to anyone who runs doctor).
3113
+ # Settings self-heal history, plus one line per hook the malformed-hook
3114
+ # healer left alone because Token Optimizer cannot prove it wrote it.
3115
+ # Informational rows: they never change the score (heal_report.py).
3114
3116
  try:
3115
- _heal_log = _measure_facade._settings_heal_dir() / "heal_log.jsonl"
3116
- if _heal_log.is_file():
3117
- _heal_entries = [
3118
- _measure_facade.json.loads(l) for l in _heal_log.read_text(encoding="utf-8").strip().split("\n")
3119
- if l.strip()
3120
- ]
3121
- _restores = [e for e in _heal_entries if e.get("action") == "restore"]
3122
- if _restores:
3123
- _last = _restores[-1]
3124
- _keys = ", ".join(_last.get("restored_keys", [])[:5])
3125
- if len(_last.get("restored_keys", [])) > 5:
3126
- _keys += f" (+{len(_last['restored_keys']) - 5} more)"
3127
- checks.append((
3128
- "OK", "Settings self-heal",
3129
- f"{len(_restores)} restore(s), last: {_keys} at {_last.get('timestamp', '?')[:19]}",
3130
- ))
3131
- else:
3132
- checks.append(("OK", "Settings self-heal", "no restores needed"))
3133
- else:
3134
- checks.append(("OK", "Settings self-heal", "no heal history yet"))
3117
+ import heal_report
3118
+ checks.extend(heal_report.doctor_rows(_measure_facade))
3135
3119
  except Exception:
3136
3120
  pass # doctor must never fail on heal history
3137
3121