@alexgreensh/token-optimizer 5.13.73 → 5.13.75

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 (38) 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 -8
  4. package/hooks/sessionstart_runner.py +25 -0
  5. package/package.json +1 -1
  6. package/skills/token-optimizer/assets/dashboard.html +20 -7
  7. package/skills/token-optimizer/assets/savings_story.js +10 -6
  8. package/skills/token-optimizer/references/cli-reference.md +9 -0
  9. package/skills/token-optimizer/scripts/_measure/__init__.py +3 -2
  10. package/skills/token-optimizer/scripts/_measure/baseline_provenance.py +3 -1
  11. package/skills/token-optimizer/scripts/_measure/cache_policy.py +2 -79
  12. package/skills/token-optimizer/scripts/_measure/cli.py +24 -0
  13. package/skills/token-optimizer/scripts/_measure/daemon.py +77 -15
  14. package/skills/token-optimizer/scripts/_measure/install_baseline.py +157 -0
  15. package/skills/token-optimizer/scripts/_measure/mod_action_booking.py +16 -3
  16. package/skills/token-optimizer/scripts/_measure/mod_action_diagnostics.py +24 -0
  17. package/skills/token-optimizer/scripts/_measure/mod_action_selftest.py +33 -0
  18. package/skills/token-optimizer/scripts/_measure/mod_compaction_booking.py +4 -4
  19. package/skills/token-optimizer/scripts/_measure/mod_fresh_booking.py +2 -2
  20. package/skills/token-optimizer/scripts/_measure/nudge_followthrough.py +334 -0
  21. package/skills/token-optimizer/scripts/_measure/own_price_card.py +3 -0
  22. package/skills/token-optimizer/scripts/_measure/pilot_report.py +349 -0
  23. package/skills/token-optimizer/scripts/_measure/pricing.py +15 -414
  24. package/skills/token-optimizer/scripts/_measure/quality_archive.py +5 -10
  25. package/skills/token-optimizer/scripts/_measure/routing_credit.py +60 -0
  26. package/skills/token-optimizer/scripts/_measure/routing_default.py +374 -0
  27. package/skills/token-optimizer/scripts/_measure/routing_savings.py +368 -0
  28. package/skills/token-optimizer/scripts/_measure/runway_all_in.py +42 -0
  29. package/skills/token-optimizer/scripts/_measure/savings.py +33 -247
  30. package/skills/token-optimizer/scripts/_measure/savings_story.py +8 -1
  31. package/skills/token-optimizer/scripts/_measure/session_activity.py +128 -0
  32. package/skills/token-optimizer/scripts/_measure/ttl_period.py +59 -0
  33. package/skills/token-optimizer/scripts/cloud_kit.py +1 -4
  34. package/skills/token-optimizer/scripts/codex_doctor.py +1 -10
  35. package/skills/token-optimizer/scripts/hermes_doctor.py +1 -10
  36. package/skills/token-optimizer/scripts/hermes_install.py +1 -10
  37. package/skills/token-optimizer/scripts/injection.py +5 -2
  38. package/skills/token-optimizer/scripts/measure.py +4 -4
@@ -13,7 +13,7 @@
13
13
  "name": "token-optimizer",
14
14
  "source": "./",
15
15
  "description": "Audit, fix, and monitor Claude Code context window usage. Find the ghost tokens.",
16
- "version": "5.13.73",
16
+ "version": "5.13.75",
17
17
  "author": {
18
18
  "name": "Alex Greenshpun",
19
19
  "url": "https://linkedin.com/in/alexgreensh"
@@ -55,7 +55,7 @@
55
55
  "name": "token-optimizer-cowork",
56
56
  "source": "./cowork/token-optimizer",
57
57
  "description": "Token Optimizer for Claude Cowork \u2014 full skills + Cowork-native hooks (beta). Install THIS in Cowork; the standard token-optimizer entry is for desktop Claude Code.",
58
- "version": "5.13.73",
58
+ "version": "5.13.75",
59
59
  "author": {
60
60
  "name": "Alex Greenshpun",
61
61
  "url": "https://linkedin.com/in/alexgreensh"
@@ -7,7 +7,7 @@
7
7
  },
8
8
  "homepage": "https://github.com/alexgreensh/token-optimizer",
9
9
  "repository": "https://github.com/alexgreensh/token-optimizer",
10
- "version": "5.13.73",
10
+ "version": "5.13.75",
11
11
  "license": "PolyForm-Noncommercial-1.0.0",
12
12
  "keywords": [
13
13
  "token",
@@ -134,14 +134,7 @@ _COLD_COMPILE_FAILED = ".token-optimizer-compile.failed"
134
134
  _COLD_COMPILE_TAG = "token-optimizer-bytecode-warmup"
135
135
 
136
136
  # This closed set matches _measure.RUNTIME_SOURCES. No recursive repo scan.
137
- _MEASURE_PACKAGE_SOURCES = (
138
- '__init__.py', '_compat.py', 'runtime.py', 'pricing.py', 'audit.py',
139
- 'dashboard.py', 'lifecycle.py', 'sessions.py', 'trends.py', 'cache_policy.py',
140
- 'daemon.py', 'quality_archive.py', 'continuity.py', 'savings.py', 'cli.py', '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',
141
- )
142
- _MEASURE_PACKAGE_SOURCES += ('transcript_stream.py', 'checkpoint_direction.py', 'checkpoint_retention.py')
143
- _MEASURE_PACKAGE_SOURCES += ('keepwarm_safety.py', 'keepwarm_economics.py', 'keepwarm_linux.py', 'mod_action_booking.py', 'mod_compaction_booking.py', 'mod_fresh_booking.py',)
144
- _MEASURE_PACKAGE_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',)
137
+ _MEASURE_PACKAGE_SOURCES = ('__init__.py', '_compat.py', 'runtime.py', 'pricing.py', 'audit.py', 'dashboard.py', 'lifecycle.py', 'sessions.py', 'trends.py', 'cache_policy.py', 'daemon.py', 'quality_archive.py', 'continuity.py', 'savings.py', 'cli.py', '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', 'keepwarm_safety.py', 'keepwarm_economics.py', 'keepwarm_linux.py', 'mod_action_booking.py', 'mod_action_diagnostics.py', 'mod_action_selftest.py', 'install_baseline.py', 'routing_credit.py', 'mod_compaction_booking.py', 'mod_fresh_booking.py', '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', 'routing_default.py', 'pilot_report.py', 'nudge_followthrough.py', 'runway_all_in.py', 'session_activity.py', 'routing_savings.py')
145
138
 
146
139
 
147
140
  def _runtime_sources(measure_src):
@@ -524,6 +524,30 @@ def _sub_codemap_hint(hook_input: dict) -> None:
524
524
  print(text)
525
525
 
526
526
 
527
+ def _sub_routing_default(hook_input: dict) -> None:
528
+ """Model-routing guidance on by default + first-run audit offer.
529
+
530
+ Delegates to ``_measure.routing_default.session_start``: injects the
531
+ byte-stable MODEL_ROUTING block into the global instruction file (once,
532
+ idempotent), stamps ``routing_injected_at``, honors the
533
+ TOKEN_OPTIMIZER_ROUTING=0 opt-out and ``routing_removed_at``, and shows a
534
+ one-time /token-optimizer setup-trim offer while the trim ledger is
535
+ empty. Cheap by contract: env checks, marker reads, one instruction-file
536
+ read, one ledger read -- no history or transcript scans. Takes no runner
537
+ budget share, like the codemap hint.
538
+
539
+ Notices print as ``{"systemMessage": ...}`` lines so the shared envelope
540
+ carries them user-facing (the same channel ensure-health uses); they are
541
+ never model context.
542
+ """
543
+ try:
544
+ from _measure import routing_default # noqa: PLC0415
545
+ for notice in routing_default.session_start():
546
+ print(json.dumps({"systemMessage": notice}))
547
+ except Exception:
548
+ pass
549
+
550
+
527
551
  def _quality_cache_self_heal() -> None:
528
552
  """Replicate the quality-cache dispatch's self-healing block: if the
529
553
  quality-cache hook is missing from settings.json and this is NOT a plugin
@@ -657,6 +681,7 @@ def main() -> int:
657
681
  hook_input, _wrapped)
658
682
  _capture("codemap cleanup", _sub_codemap_cleanup)
659
683
  _capture("codemap hint", _sub_codemap_hint, hook_input)
684
+ _capture("routing-default", _sub_routing_default, hook_input)
660
685
 
661
686
  # Emit the compact-restore payloads and ensure-health/quality-cache
662
687
  # systemMessage lines as ONE host-valid JSON object. systemMessage values
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@alexgreensh/token-optimizer",
3
- "version": "5.13.73",
3
+ "version": "5.13.75",
4
4
  "description": "Token Optimizer for Claude Code cloud sessions: the real plugin, installed by your cloud environment's setup script.",
5
5
  "license": "PolyForm-Noncommercial-1.0.0",
6
6
  "author": "Alex Greenshpun (https://linkedin.com/in/alexgreensh)",
@@ -1526,6 +1526,16 @@ input:checked + .slider:before {
1526
1526
  border: 1px solid var(--c-waste, #f87171);
1527
1527
  background: var(--c-waste-fill, rgba(248,113,113,0.1));
1528
1528
  }
1529
+ .flag-badge.active {
1530
+ color: var(--c-savings, #4ade80);
1531
+ border: 1px solid var(--c-savings, #4ade80);
1532
+ background: var(--c-savings-fill, rgba(74,222,128,0.1));
1533
+ }
1534
+ .flag-badge.orchestrated {
1535
+ color: var(--c-info, #60a5fa);
1536
+ border: 1px solid var(--c-info, #60a5fa);
1537
+ background: rgba(96,165,250,0.1);
1538
+ }
1529
1539
 
1530
1540
  /* ========== VERSION HERO ========== */
1531
1541
  .version-hero {
@@ -5254,11 +5264,11 @@ var DB = (function() {
5254
5264
  '<div style="font-weight:500;color:var(--c-waste-strong, #ef4444)">' + staleCount + ' stale session' + (staleCount !== 1 ? 's' : '') + ' detected</div>' +
5255
5265
  '<button class="copy-fix-btn" id="kill-stale-btn" data-label="' + killLabel + '" style="background:var(--c-waste-strong, #ef4444);border-color:var(--c-waste-strong, #ef4444)">' + killLabel + '</button></div>' +
5256
5266
  '<div style="font-size:13px;color:var(--c-text-dim);line-height:1.5">' +
5257
- 'These ' + esc(data.runtime_label || 'Claude Code') + ' sessions have been running 24+ hours. ' +
5267
+ 'These ' + esc(data.runtime_label || 'Claude Code') + ' sessions have been idle for 24+ hours. ' +
5258
5268
  'Some may be your active terminals (marked TERMINAL), others may be forgotten or headless. ' +
5259
5269
  'Check the status column before killing. Only kill sessions you are not actively using.<br><br>' +
5260
5270
  '<span style="font-family:var(--font-mono);font-size:12px;color:var(--c-text-main)">Option 1:</span> ' + (taggedInventory ? 'Click "Copy Preview Command" and paste it in any terminal. It only lists what would be ended; run Option 2 to end it.' : 'Click "Copy Kill Command" and paste in any terminal.') + '<br>' +
5261
- '<span style="font-family:var(--font-mono);font-size:12px;color:var(--c-text-main)">Option 2:</span> Run <code style="font-family:var(--font-mono);color:var(--c-accent-cyan)">' + cliCmd + ' kill-stale</code> to auto-terminate terminal sessions running &gt;12 hours (desktop-hosted and unverified sessions are never terminated).<br>' +
5271
+ '<span style="font-family:var(--font-mono);font-size:12px;color:var(--c-text-main)">Option 2:</span> Run <code style="font-family:var(--font-mono);color:var(--c-accent-cyan)">' + cliCmd + ' kill-stale</code> to auto-terminate terminal sessions idle &gt;12 hours (busy sessions, desktop-hosted and unverified sessions are never terminated).<br>' +
5262
5272
  '<span style="font-family:var(--font-mono);font-size:12px;color:var(--c-text-main)">Option 3:</span> Run <code style="font-family:var(--font-mono);color:var(--c-accent-cyan)">' + cliCmd + ' kill-stale --dry-run</code> to preview without killing.' +
5263
5273
  '</div></div>';
5264
5274
  }
@@ -5272,7 +5282,7 @@ var DB = (function() {
5272
5282
  }
5273
5283
 
5274
5284
  html += '<table class="session-table"><thead><tr>' +
5275
- '<th>PID</th><th>Started</th><th>Elapsed</th>' + (isCodex ? '' : '<th>Version</th>') + '<th>Status</th><th></th>' +
5285
+ '<th>PID</th><th>Started</th><th>Elapsed</th><th>Idle</th>' + (isCodex ? '' : '<th>Version</th>') + '<th>Status</th><th></th>' +
5276
5286
  '</tr></thead><tbody>';
5277
5287
  sessions.forEach(function(s) {
5278
5288
  var flagHtml = '';
@@ -5289,6 +5299,7 @@ var DB = (function() {
5289
5299
  '<td>' + s.pid + '</td>' +
5290
5300
  '<td>' + esc((s.started || '').slice(0, 20)) + '</td>' +
5291
5301
  '<td>' + esc(s.elapsed_human || '?') + '</td>' +
5302
+ '<td>' + esc(s.idle_human || '—') + '</td>' +
5292
5303
  (isCodex ? '' : '<td>' + esc(s.version || 'unknown') + '</td>') +
5293
5304
  '<td>' + flagHtml + (flags.indexOf('ORPHAN') !== -1 ? '<div style="font-size:11px;color:var(--c-text-dim);margin-top:2px">terminal gone; started ' + esc(s.elapsed_human || '?') + ' ago</div>' : '') + '</td>' +
5294
5305
  '<td>' + killBtn + '</td>' +
@@ -5299,8 +5310,10 @@ var DB = (function() {
5299
5310
  html += '<div style="font-size:11px;color:var(--c-text-dim);margin-top:var(--s-2);line-height:1.6;font-family:var(--font-mono)">' +
5300
5311
  '<span class="flag-badge terminal" style="font-size:10px">TERMINAL</span> = attached to a terminal tab (your active sessions) &nbsp; ' +
5301
5312
  '<span class="flag-badge" style="font-size:10px;background:rgba(125,140,163,0.2);color:var(--c-text-dim)">HEADLESS</span> = no terminal (automation/background) &nbsp; ' +
5302
- '<span class="flag-badge stale" style="font-size:10px">STALE</span> = running 24h+ &nbsp; ' +
5303
- '<span class="flag-badge zombie" style="font-size:10px">ZOMBIE</span> = running 48h+' +
5313
+ '<span class="flag-badge stale" style="font-size:10px">STALE</span> = idle 24h+ &nbsp; ' +
5314
+ '<span class="flag-badge zombie" style="font-size:10px">ZOMBIE</span> = idle 48h+ &nbsp; ' +
5315
+ '<span class="flag-badge active" style="font-size:10px">ACTIVE</span> = working now &nbsp; ' +
5316
+ '<span class="flag-badge orchestrated" style="font-size:10px">ORCHESTRATED</span> = tmux/outsourcerer-managed' +
5304
5317
  (isCodex ? '' : ' &nbsp; <span class="flag-badge desktop" style="font-size:10px">DESKTOP</span> = hosted by the Claude desktop app (never auto-terminated)' +
5305
5318
  ' &nbsp; <span class="flag-badge unverified" style="font-size:10px">UNVERIFIED</span> = process identity could not be read (never auto-terminated)' +
5306
5319
  ' &nbsp; <span class="flag-badge orphan" style="font-size:10px">ORPHAN</span> = terminal gone (only ended with <code>kill-stale --include-orphans</code>)') +
@@ -7376,8 +7389,8 @@ function getSampleData() {
7376
7389
  health: {
7377
7390
  installed_version: '2.1.63',
7378
7391
  running_sessions: [
7379
- { pid: 48201, started: 'Sat Mar 01 10:18:43 2026', elapsed_seconds: 180000, elapsed_human: '2d 8h', version: '2.1.60', command: 'claude', flags: ['OUTDATED', 'ZOMBIE'] },
7380
- { pid: 51932, started: 'Sun Mar 02 14:10:59 2026', elapsed_seconds: 95000, elapsed_human: '1d 2h', version: '2.1.63', command: 'claude', flags: ['STALE'] }
7392
+ { pid: 48201, started: 'Sat Mar 01 10:18:43 2026', elapsed_seconds: 180000, elapsed_human: '2d 8h', idle_seconds: 183600, idle_human: '2d 3h', version: '2.1.60', command: 'claude', flags: ['OUTDATED', 'ZOMBIE'] },
7393
+ { pid: 51932, started: 'Sun Mar 02 14:10:59 2026', elapsed_seconds: 95000, elapsed_human: '1d 2h', idle_seconds: 98000, idle_human: '1d 3h', version: '2.1.63', command: 'claude', flags: ['STALE', 'ORCHESTRATED'] }
7381
7394
  ],
7382
7395
  automated: [
7383
7396
  '-\t0\tcom.anthropic.claudefordesktop.ShipIt',
@@ -185,7 +185,7 @@ function savingsStoryHtml(data, extras) {
185
185
  }).join('') + '</ul>' : '');
186
186
  }
187
187
  }
188
- var method = '<p><strong>Last ' + days + ' days, ' + savingsCents(allCents / 100) + '</strong>: measured ' + savingsCents(cents(measured) / 100) +
188
+ var method = (mr.routing_enabled === false ? '<p>Routing off</p>' : '') + '<p><strong>Last ' + days + ' days, ' + savingsCents(allCents / 100) + '</strong>: measured ' + savingsCents(cents(measured) / 100) +
189
189
  ', estimated ' + savingsCents(cents(estimated) / 100) + (routing30 > 0 ? ', routing ' + savingsCents(routing30) : '') + '.</p>' +
190
190
  table('Measured, counted event by event', measured) +
191
191
  table('Estimated, sized by a documented method', estimated) +
@@ -247,12 +247,15 @@ function savingsStoryHtml(data, extras) {
247
247
  out += '<div class="card st-hero">' +
248
248
  '<h2 class="st-h">What Token Optimizer saved</h2>' +
249
249
  '<div class="st-mega__row st-mega__row--hero">' +
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>' +
250
+ (has(mr.routing_enabled) ? (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>' +
251
+ tipCard('st-tip-since', 'Since ' + esc(SIh.date || 'install'), tipSinceLines) +
252
+ '<span class="st-mega__unit">saved since you installed' + soFar(soFarAll) + '</span></div>' : '') + '<div class="st-mega__item"><button type="button" class="st-mega st-mega--usd st-tip" aria-describedby="st-tip-total">' + usd(bigTotal) + '</button>' +
253
+ tipCard('st-tip-total', 'What makes up ' + usd(bigTotal), tipTotalLines) +
254
+ '<span class="st-mega__unit">saved in the last ' + days + ' days' + soFar(soFar30) + '</span></div>' : '<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
255
  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>' +
256
+ '<span class="st-mega__unit">saved in the last ' + days + ' days' + soFar(soFar30) + '</span></div>' + (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
257
  tipCard('st-tip-since', 'Since ' + esc(SIh.date || 'install'), tipSinceLines) +
255
- '<span class="st-mega__unit">saved since you installed' + soFar(soFarAll) + '</span></div>' : '') +
258
+ '<span class="st-mega__unit">saved since you installed' + soFar(soFarAll) + '</span></div>' : '')) +
256
259
  (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
260
  tipCard('st-tip-tokens', tok(totalTok) + ' tokens kept out of context', tipTokLines) +
258
261
  '<span class="st-mega__unit">tokens kept out of context in ' + days + ' days' + soFar(cp.remeasuring === true) + '</span></div>' : '') +
@@ -317,7 +320,7 @@ function savingsSinceInstallBody(data, SI) {
317
320
  (SI.measured > 0 ? '<li>Measured: ' + savingsCents(SI.measured) + '. Context removed, cheaper cache writes and re-reads avoided, counted event by event.</li>' : '') +
318
321
  (SI.estimated > 0 ? '<li>Estimated: ' + savingsCents(SI.estimated) + '. Setup cleanup from archives, handovers and other documented estimates.</li>' : '') +
319
322
  (SI.routing > 0 ? '<li>Model routing, estimated: ' + savingsCents(SI.routing) + '. ' + esc_(basis.lead) + (period ? ' Most of it from ' + esc_(period) + '.' : '') + '</li>' : '') +
320
- '</ul>';
323
+ (mr.routing_enabled === false ? '<li>Routing off</li>' : '') + '</ul>';
321
324
  var alt = SI.routing > 0 && basis.kind === 'stated' && has(ai.routing_measured_baseline_opus_share) && has(ai.routing_measured_baseline_realized_cost_usd)
322
325
  ? '<p>Using the measured starting mix (' + (num(ai.routing_measured_baseline_opus_share) * 100).toFixed(2) + '% Opus), the routing estimate is ' + usd(ai.routing_measured_baseline_realized_cost_usd) + '.</p>' : '';
323
326
  return split +
@@ -507,6 +510,7 @@ function savingsLimitsHtml(data) {
507
510
  var provider = (data && data.runtime) === 'codex' ? 'OpenAI' : 'Anthropic';
508
511
  var methodLines = [];
509
512
  if (direct > 0) methodLines.push('Measured directly by Token Optimizer: about ' + (Math.round(direct * 10) / 10) + '% more work per token');
513
+ if (num(rw.estimated_work_pct) > 0) methodLines.push('This includes estimated savings, converted using your usage costs');
510
514
  methodLines.push('The rest comes from your setup, habits and model choices since your earliest tracked month');
511
515
  if (prov.claim) methodLines.push('Token Optimizer was already running in that month, so the full gap is larger than shown');
512
516
  methodLines.push(provider + "'s own improvements in that time are not separated out");
@@ -53,6 +53,7 @@
53
53
  ## Other
54
54
 
55
55
  - `measure.py savings` -- Cumulative dollar savings report
56
+ - `measure.py pilot-report [--json]` -- Weekly pilot report for Slack: capacity since install, all-in savings, routing state, setup trims, nudge follow-through
56
57
  - `measure.py expand [--list|<tool-use-id>|--search <query>]` -- Retrieve archived tool results, or search by keyword/lineage
57
58
  - `measure.py setup-hook [--uninstall]` -- SessionEnd tracking hook
58
59
  - `measure.py setup-quality-bar [--uninstall]` -- Terminal status line
@@ -90,3 +91,11 @@ Shown in status line (`Quality A 82`), dashboard, coach, and CLI.
90
91
 
91
92
  ### .contextignore
92
93
  Create `.contextignore` in project root or `~/.claude/.contextignore` (global). Uses gitignore-style glob patterns. Hard-blocks regardless of read-cache mode.
94
+
95
+ To reserve a Keep warm attempt through the CLI, send a JSON receipt on standard input:
96
+
97
+ ```bash
98
+ printf '%s' '{"action":"warm-prepare","action_id":"ATTEMPT_ID","session_id":"SESSION_ID","timestamp":UNIX_SECONDS,"transcript_path":"/path/to/SESSION_ID.jsonl","byte_size":FILE_SIZE,"transcript_mtime":FILE_MTIME}' | python3 <plugin>/skills/token-optimizer/scripts/measure.py mod-action
99
+ ```
100
+
101
+ Replace the placeholders with the current transcript's exact file size and modification time, a unique attempt ID, and the current Unix time. The response is JSON. This reserves the booking; the caller must perform the warm request and submit its usage as a `warm` receipt, or send `warm-cancel` if it does not run.
@@ -11,8 +11,9 @@ DOMAIN_MODULES = (
11
11
  # uses them (perf attribution, 2026-11-06).
12
12
  DEFERRED_MODULES = ('audit', 'dashboard', 'sessions', 'savings', 'cli')
13
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',)
14
+ RUNTIME_SOURCES += ('keepwarm_safety.py', 'keepwarm_economics.py', 'keepwarm_linux.py', 'mod_action_booking.py', 'mod_action_diagnostics.py', 'mod_action_selftest.py', 'install_baseline.py', 'routing_credit.py', 'mod_compaction_booking.py', 'mod_fresh_booking.py', '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', 'routing_default.py', 'pilot_report.py',)
15
+ RUNTIME_SOURCES += ('nudge_followthrough.py', 'runway_all_in.py',)
16
+ RUNTIME_SOURCES += ('session_activity.py', 'routing_savings.py',)
16
17
  # Set True by hooks/userpromptsubmit_runner.py right before `import measure`,
17
18
  # which consumes it. That process never patches or enumerates the facade.
18
19
  HOOK_IMPORT = False
@@ -198,13 +198,15 @@ def transformation(facade, baseline, weight_pool):
198
198
  if len(dates) == 2:
199
199
  start, end = dates
200
200
  cov = window_coverage(start, end, install_evidence(facade))
201
+ if window.get("coverage") == "post_install":
202
+ cov["coverage"] = "post_install"
201
203
  try:
202
204
  stated = baseline.get("opus_share_source") == "pretool_baseline"
203
205
  share = float(baseline.get("opus_share") or 0)
204
206
  except (TypeError, ValueError):
205
207
  stated, share = False, 0.0
206
208
  cov.update(anchor=anchor, pending_anchor=pending,
207
- mix_source="stated" if stated else ("measured" if share > 0 else "current_mix"))
209
+ mix_source="stated" if stated else ("measured" if baseline.get("model_shares") or share > 0 else "current_mix"))
208
210
  cov["lead"], cov["note"] = _transformation_copy(cov)
209
211
  if cov["coverage"] in ("post_install", "partial"):
210
212
  # The tool ran in the baseline month, so the comparison is with that
@@ -381,85 +381,8 @@ def _get_cache_ttl_waste(days=None, collect_sessions=None):
381
381
 
382
382
 
383
383
  def _cache_ttl_waste_cached(days=None, fresh=None):
384
- """`_get_cache_ttl_waste` with a 15-min sidecar cache (cache_health.json).
385
-
386
- Returns the cached payload when the sidecar is younger than the TTL AND its
387
- stored `days` AND `platform` (runtime) match the current call; otherwise
388
- recomputes and rewrites the sidecar. The runtime is part of the hit
389
- condition because a `cd` into a Codex project (or a runtime flip) changes the
390
- session source — a sidecar computed under a different runtime would otherwise
391
- be served as if it described the current one. `fresh=True` bypasses the read
392
- (cache-report --fresh). Freshness uses the mtime idiom (module-level
393
- (mtime, payload) memo) for consistency with _demoted_cohorts. Fail-open: any
394
- cache I/O error falls through to a fresh compute.
395
- """
396
- _measure_facade = _compat.facade()
397
- pass
398
- cache_path = _measure_facade.SNAPSHOT_DIR / "cache_health.json"
399
- current_runtime = _measure_facade.detect_runtime()
400
-
401
- def _is_hit(payload):
402
- _measure_facade = _compat.facade()
403
- try:
404
- return (
405
- int(payload.get("period_days", -1)) == int(days)
406
- and payload.get("platform") == current_runtime
407
- and payload.get("engine") == 2 # older sidecars predate the rebuild fix
408
- and (_measure_facade.time.time() - float(payload.get("_cached_ts", 0)))
409
- < _measure_facade._CACHE_HEALTH_CACHE_TTL_SECONDS
410
- )
411
- except (TypeError, ValueError):
412
- return False
413
-
414
- if not fresh:
415
- try:
416
- mtime = cache_path.stat().st_mtime
417
- # In-process memo: same file version -> no re-read, no re-parse.
418
- if _measure_facade._cache_health_memo is not None and _measure_facade._cache_health_memo[0] == mtime:
419
- payload = _measure_facade._cache_health_memo[1]
420
- if _is_hit(payload):
421
- return payload
422
- else:
423
- payload = _measure_facade.json.loads(cache_path.read_text(encoding="utf-8"))
424
- _measure_facade._cache_health_memo = (mtime, payload)
425
- if _is_hit(payload):
426
- return payload
427
- except (_measure_facade.json.JSONDecodeError, OSError, ValueError, TypeError):
428
- pass
429
- result = _measure_facade._get_cache_ttl_waste(days=days)
430
- try:
431
- record = dict(result)
432
- record["_cached_ts"] = _measure_facade.time.time()
433
- _measure_facade.SNAPSHOT_DIR.mkdir(parents=True, exist_ok=True)
434
- # mkstemp + replace: an interrupted write never leaves a half-written
435
- # sidecar, and the 0600 mode is set before any content is visible.
436
- fd, tmp_name = _measure_facade.tempfile.mkstemp(
437
- prefix=".cache_health.", suffix=".tmp", dir=str(_measure_facade.SNAPSHOT_DIR))
438
- try:
439
- if hasattr(_measure_facade.os, "fchmod"): # POSIX only; mkstemp is already 0600
440
- _measure_facade.os.fchmod(fd, 0o600)
441
- with _measure_facade.os.fdopen(fd, "w", encoding="utf-8") as fh:
442
- # W7: json.dump can raise ValueError (e.g. a non-serializable
443
- # value or nan/inf with allow_nan path quirks), not just OSError;
444
- # broaden the inner cleanup trigger to Exception so a serialize
445
- # failure still unlinks the temp file instead of leaking it.
446
- _measure_facade.json.dump(record, fh)
447
- _measure_facade.os.replace(tmp_name, str(cache_path))
448
- try:
449
- _measure_facade._cache_health_memo = (_measure_facade.os.stat(cache_path).st_mtime, record)
450
- except OSError:
451
- _measure_facade._cache_health_memo = None
452
- except Exception:
453
- try:
454
- _measure_facade.os.unlink(tmp_name)
455
- except OSError:
456
- pass
457
- raise
458
- except Exception:
459
- # W7: the whole memoization layer is best-effort; any failure (I/O or
460
- # serialize) just means this call returns the fresh result uncached.
461
- pass
462
- return result
384
+ from . import ttl_period
385
+ return ttl_period.cache_health(_compat.facade(), days, fresh)
463
386
 
464
387
 
465
388
  def _keepwarm_sidecar_path():
@@ -993,6 +993,20 @@ def main():
993
993
  else:
994
994
  _measure_facade.section, _measure_facade.gen_fn, _measure_facade.err = "COACH", _measure_facade.generate_coach_block, "No coaching data available yet."
995
995
 
996
+ # inject-routing --uninstall removes the MODEL_ROUTING blocks and
997
+ # stamps routing_removed_at so routing credit stops from that date.
998
+ # The flag test stays an assignment, not an if-test, so the frozen
999
+ # measure-split dispatch inventory sees no new branch.
1000
+ _measure_facade._routing_uninstall = ("--uninstall" in _measure_facade.args
1001
+ and _measure_facade.args[0] == "inject-routing")
1002
+ if _measure_facade._routing_uninstall:
1003
+ from . import routing_default as _measure_routing_default
1004
+ _measure_facade._rr = _measure_routing_default.uninstall_routing()
1005
+ for _measure_facade._p in _measure_facade._rr["files"]:
1006
+ print(f" Removed MODEL_ROUTING block from {_measure_facade._p}")
1007
+ print(" Routing guidance uninstalled.")
1008
+ return
1009
+
996
1010
  _measure_facade.block = _measure_facade.gen_fn()
997
1011
  if not _measure_facade.block:
998
1012
  print(f"[Error] {_measure_facade.err} Run some sessions first.")
@@ -1012,6 +1026,11 @@ def main():
1012
1026
  if _measure_facade.args[0] == "setup-coach-injection":
1013
1027
  print(" Block will auto-remove after 48h if not refreshed.")
1014
1028
  print(" Uninstall: measure.py setup-coach-injection --uninstall")
1029
+ if _measure_facade.args[0] == "inject-routing":
1030
+ # Stamp routing_injected_at once and clear any earlier
1031
+ # routing_removed_at so the credit window matches reality.
1032
+ from . import routing_default as _measure_routing_default
1033
+ _measure_routing_default.record_injection()
1015
1034
  elif _measure_facade.args[0] == "check-staleness":
1016
1035
  from injection import check_staleness as _measure_import_38; _measure_facade.check_staleness = _measure_import_38; del _measure_import_38; from injection import remove_managed_block as _measure_import_39; _measure_facade.remove_managed_block = _measure_import_39; del _measure_import_39
1017
1036
  _measure_facade.section = _measure_facade.args[1] if len(_measure_facade.args) > 1 else "COACH"
@@ -2371,6 +2390,9 @@ def main():
2371
2390
  _measure_facade.usage_trends(days=_measure_facade.days, as_json=_measure_facade.output_json)
2372
2391
  else:
2373
2392
  _measure_facade.savings_report(days=_measure_facade.days, as_json=_measure_facade.output_json)
2393
+ elif _measure_facade.args[0] == "pilot-report":
2394
+ from . import pilot_report as _measure_pilot_report
2395
+ _measure_facade.sys.exit(_measure_pilot_report.main(_measure_facade.args[1:], facade=_measure_facade))
2374
2396
  elif _measure_facade.args[0] == "pin-baseline":
2375
2397
  _measure_facade.status = "building"
2376
2398
  while _measure_facade.status == "building":
@@ -2721,6 +2743,8 @@ def main():
2721
2743
  print(" python3 measure.py savings # Savings report (last 30 days)")
2722
2744
  print(" python3 measure.py savings --days 7 # Savings report (last 7 days)")
2723
2745
  print(" python3 measure.py savings --json # Machine-readable savings output")
2746
+ print(" python3 measure.py pilot-report # Weekly pilot report for Slack")
2747
+ print(" python3 measure.py pilot-report --json # Machine-readable pilot report")
2724
2748
  print(" python3 measure.py structure-proof # Replay local sessions for structure-map proof")
2725
2749
  print(" python3 measure.py structure-proof --json")
2726
2750
  print(" python3 measure.py structure-proof --torture")
@@ -1445,6 +1445,8 @@ def _collect_health_data():
1445
1445
  installed_key = _measure_facade._semver_key(installed_version)
1446
1446
 
1447
1447
  # Flag sessions
1448
+ from . import session_activity as _session_activity
1449
+ _activity_now = _measure_facade.time.time()
1448
1450
  for s in running_sessions:
1449
1451
  if runtime == "codex":
1450
1452
  # Desktop app-server lifetime is not task age or evidence of an
@@ -1455,15 +1457,30 @@ def _collect_health_data():
1455
1457
  session_key = _measure_facade._semver_key(s.get("version"))
1456
1458
  if session_key is not None and installed_key is not None and session_key < installed_key:
1457
1459
  flags.append("OUTDATED")
1458
- if s["elapsed_seconds"] > 172800:
1460
+ # Claude Code's sessions/<pid>.json record proves real idle time;
1461
+ # process age alone flags busy orchestrators as ZOMBIE. Sessions with
1462
+ # no record (older Claude Code) keep the elapsed-based thresholds.
1463
+ act = _session_activity.activity(s["pid"], _activity_now, elapsed_seconds=s.get("elapsed_seconds"))
1464
+ s["activity"] = act
1465
+ idle = act.get("idle_seconds")
1466
+ s["idle_seconds"] = idle
1467
+ s["idle_human"] = _measure_facade._format_elapsed(idle) if idle is not None else None
1468
+ if act.get("source") == "none":
1469
+ if s["elapsed_seconds"] > 172800:
1470
+ flags.append("ZOMBIE")
1471
+ elif s["elapsed_seconds"] > 86400:
1472
+ flags.append("STALE")
1473
+ elif system == "Windows" and s["elapsed_seconds"] == 0:
1474
+ # Windows without a creation-time source (wmic gone, PowerShell locked
1475
+ # down) can't threshold STALE/ZOMBIE. Surface explicitly so the user
1476
+ # isn't fooled into thinking all sessions are fresh.
1477
+ flags.append("UNKNOWN_AGE")
1478
+ elif act.get("status") == "busy":
1479
+ flags.append("ACTIVE")
1480
+ elif idle is not None and idle >= 172800:
1459
1481
  flags.append("ZOMBIE")
1460
- elif s["elapsed_seconds"] > 86400:
1482
+ elif idle is not None and idle >= 86400:
1461
1483
  flags.append("STALE")
1462
- elif system == "Windows" and s["elapsed_seconds"] == 0:
1463
- # Windows without a creation-time source (wmic gone, PowerShell locked
1464
- # down) can't threshold STALE/ZOMBIE. Surface explicitly so the user
1465
- # isn't fooled into thinking all sessions are fresh.
1466
- flags.append("UNKNOWN_AGE")
1467
1484
  identity = s.get("identity")
1468
1485
  if identity == "embedded_session":
1469
1486
  flags.append("DESKTOP")
@@ -1475,6 +1492,8 @@ def _collect_health_data():
1475
1492
  flags.append("TERMINAL")
1476
1493
  else:
1477
1494
  flags.append("HEADLESS")
1495
+ if act.get("tmux"):
1496
+ flags.append("ORCHESTRATED")
1478
1497
  s["flags"] = flags
1479
1498
 
1480
1499
  automated = []
@@ -1854,8 +1873,11 @@ def _kill_stale_owns(session):
1854
1873
 
1855
1874
 
1856
1875
  def kill_stale_sessions(threshold_hours=None, dry_run=None, include_orphans=None):
1857
- """Kill Claude Code sessions that have been running longer than threshold_hours.
1876
+ """Kill Claude Code sessions that have been idle longer than threshold_hours.
1858
1877
 
1878
+ Selection uses the session record's idle time when Claude Code provides
1879
+ one (sessions/<pid>.json); process age is only the fallback for sessions
1880
+ with no record. A session whose record says "busy" is never selected.
1859
1881
  Targets abandoned terminal sessions only: a session is terminable when its
1860
1882
  collector positively identified it as a terminal CLI process. Orphans
1861
1883
  (orphan_cli: terminal gone, reparented to init, macOS/Linux) are listed but
@@ -1879,6 +1901,40 @@ def kill_stale_sessions(threshold_hours=None, dry_run=None, include_orphans=None
1879
1901
  # carry no owner (see the closing message below).
1880
1902
  running = [s for s in health["running_sessions"] if _measure_facade._kill_stale_owns(s)]
1881
1903
  threshold_seconds = threshold_hours * 3600
1904
+
1905
+ def _age_seconds(s):
1906
+ # Inactivity seconds for selection: the session record's idle time when
1907
+ # Claude Code provides one (attached as s["activity"]), else the
1908
+ # historical elapsed-since-start. None when neither signal exists.
1909
+ act = s.get("activity") or {}
1910
+ if act.get("source") not in (None, "none"):
1911
+ return act.get("idle_seconds")
1912
+ return s.get("elapsed_seconds")
1913
+
1914
+ def _past_threshold(s):
1915
+ age = _age_seconds(s)
1916
+ return age is not None and age > threshold_seconds
1917
+
1918
+ def _record_busy_now(s):
1919
+ # Re-read sessions/<pid>.json for EVERY candidate right before the
1920
+ # signal and fail closed: a record-backed session is killed only when
1921
+ # its identity is verified, it says "idle" explicitly and it has been
1922
+ # idle past the threshold. Age alone decides only when the record is
1923
+ # confirmed absent on both reads (older Claude Code writes none).
1924
+ from . import session_activity as _session_activity
1925
+ try:
1926
+ fresh = _session_activity.activity(s["pid"], elapsed_seconds=s.get("elapsed_seconds"))
1927
+ except Exception:
1928
+ return True
1929
+ first = s.get("activity") or {}
1930
+ if fresh.get("source") == "none":
1931
+ return not (fresh.get("reason") == "missing" and first.get("source") in (None, "none")
1932
+ and first.get("reason", "missing") == "missing")
1933
+ if not fresh.get("verified") or fresh.get("status") != "idle":
1934
+ return True
1935
+ idle = fresh.get("idle_seconds")
1936
+ return idle is None or idle <= threshold_seconds
1937
+
1882
1938
  my_pid = _measure_facade.os.getpid()
1883
1939
  my_ppid = _measure_facade.os.getppid()
1884
1940
  # Never terminate the session this command is running inside of: it is an
@@ -1903,9 +1959,10 @@ def kill_stale_sessions(threshold_hours=None, dry_run=None, include_orphans=None
1903
1959
  killable = ("terminal_cli", "orphan_cli") if include_orphans else ("terminal_cli",)
1904
1960
  protected = [s for s in running
1905
1961
  if s.get("identity", "unknown") not in ("terminal_cli", "orphan_cli")
1906
- and s["elapsed_seconds"] > threshold_seconds]
1962
+ and _past_threshold(s)]
1907
1963
  stale = [s for s in running
1908
- if s["elapsed_seconds"] > threshold_seconds
1964
+ if _past_threshold(s)
1965
+ and (s.get("activity") or {}).get("status") != "busy"
1909
1966
  and s["pid"] != my_pid
1910
1967
  and s["pid"] != my_ppid
1911
1968
  and s["pid"] not in my_ancestors
@@ -1913,7 +1970,7 @@ def kill_stale_sessions(threshold_hours=None, dry_run=None, include_orphans=None
1913
1970
  held_orphans = [] if include_orphans else [
1914
1971
  s for s in running
1915
1972
  if s.get("identity") == "orphan_cli"
1916
- and s["elapsed_seconds"] > threshold_seconds
1973
+ and _past_threshold(s)
1917
1974
  and s["pid"] not in (my_pid, my_ppid)
1918
1975
  and s["pid"] not in my_ancestors]
1919
1976
 
@@ -1924,7 +1981,7 @@ def kill_stale_sessions(threshold_hours=None, dry_run=None, include_orphans=None
1924
1981
 
1925
1982
  if held_orphans:
1926
1983
  n = len(held_orphans)
1927
- print(f"\n {n} orphaned session{'s' if n != 1 else ''} (terminal gone, running >{threshold_hours}h) "
1984
+ print(f"\n {n} orphaned session{'s' if n != 1 else ''} (terminal gone, idle >{threshold_hours}h) "
1928
1985
  f"{'were' if n != 1 else 'was'} left alone. Orphans are only ended on request:")
1929
1986
  print(f" {_measure_facade._measure_cli('kill-stale', '--include-orphans', '--hours', str(threshold_hours))} (add --dry-run to preview)")
1930
1987
 
@@ -1936,10 +1993,12 @@ def kill_stale_sessions(threshold_hours=None, dry_run=None, include_orphans=None
1936
1993
  print(f" {len(running)} active session{'s' if len(running) != 1 else ''}, all within threshold.")
1937
1994
  return
1938
1995
 
1939
- print(f"\n Found {len(stale)} stale session{'s' if len(stale) != 1 else ''} (running >{threshold_hours}h):\n")
1996
+ print(f"\n Found {len(stale)} stale session{'s' if len(stale) != 1 else ''} (idle >{threshold_hours}h):\n")
1940
1997
  for s in stale:
1941
1998
  flags = " ".join(s.get("flags", []))
1942
- print(f" PID {s['pid']:<7d} {s['elapsed_human']:>10s} v{s.get('version') or '?':<10s} {flags}")
1999
+ idle = s.get("idle_human")
2000
+ idle_col = f" idle {idle}" if idle else ""
2001
+ print(f" PID {s['pid']:<7d} {s['elapsed_human']:>10s}{idle_col} v{s.get('version') or '?':<10s} {flags}")
1943
2002
 
1944
2003
  if dry_run:
1945
2004
  print(f"\n Dry run. Would kill {len(stale)} process{'es' if len(stale) != 1 else ''}.")
@@ -1959,6 +2018,9 @@ def kill_stale_sessions(threshold_hours=None, dry_run=None, include_orphans=None
1959
2018
  if not _measure_facade._revalidate_terminal_cli(s, identity=s.get("identity", "unknown")):
1960
2019
  print(f" PID {s['pid']} skipped: identity changed or could not be re-verified.")
1961
2020
  continue
2021
+ if _record_busy_now(s):
2022
+ print(f" PID {s['pid']} skipped: the session is busy now.")
2023
+ continue
1962
2024
  try:
1963
2025
  _measure_facade.os.kill(s["pid"], signal.SIGTERM)
1964
2026
  killed += 1
@@ -1974,7 +2036,7 @@ def kill_stale_sessions(threshold_hours=None, dry_run=None, include_orphans=None
1974
2036
 
1975
2037
  print(f"\n Terminated {killed} stale session{'s' if killed != 1 else ''}.")
1976
2038
  if killed > 0:
1977
- print(f" These were Claude Code processes running >{threshold_hours}h.")
2039
+ print(f" These were Claude Code processes idle >{threshold_hours}h.")
1978
2040
  if _measure_facade.os.name == "nt":
1979
2041
  # No owner column in the Windows process inventory (a GetOwner call per
1980
2042
  # process is a new slow CIM round trip), so do not claim an account filter.