@alexgreensh/token-optimizer 5.13.81 → 5.13.82
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +2 -2
- package/.claude-plugin/plugin.json +1 -1
- package/hooks/module_runner.py +1 -1
- package/package.json +1 -1
- package/skills/token-optimizer/assets/savings_story.js +6 -4
- package/skills/token-optimizer/scripts/_measure/__init__.py +1 -1
- package/skills/token-optimizer/scripts/_measure/continuity.py +30 -3
- package/skills/token-optimizer/scripts/_measure/cost_per_message_trend.py +32 -15
- package/skills/token-optimizer/scripts/_measure/daemon.py +25 -2
- package/skills/token-optimizer/scripts/_measure/dashboard.py +2 -1
- package/skills/token-optimizer/scripts/_measure/feature_health.py +14 -5
- package/skills/token-optimizer/scripts/_measure/install_baseline.py +2 -1
- package/skills/token-optimizer/scripts/_measure/like_for_like.py +329 -0
- package/skills/token-optimizer/scripts/_measure/limit_units.py +39 -0
- package/skills/token-optimizer/scripts/_measure/model_families.py +133 -0
- package/skills/token-optimizer/scripts/_measure/own_price_card.py +38 -14
- package/skills/token-optimizer/scripts/_measure/pilot_report.py +197 -48
- package/skills/token-optimizer/scripts/_measure/pricing.py +7 -2
- package/skills/token-optimizer/scripts/_measure/quality_archive.py +41 -19
- package/skills/token-optimizer/scripts/_measure/quality_continuity.py +2 -0
- package/skills/token-optimizer/scripts/_measure/savings.py +155 -80
- package/skills/token-optimizer/scripts/_measure/sessions.py +7 -2
- package/skills/token-optimizer/scripts/_measure/trends.py +20 -2
- package/skills/token-optimizer/scripts/_measure/weekly_activity.py +37 -4
- package/skills/token-optimizer/scripts/antigravity_doctor.py +42 -6
- package/skills/token-optimizer/scripts/antigravity_install.py +18 -9
- package/skills/token-optimizer/scripts/cloud_kit.py +1 -1
- package/skills/token-optimizer/scripts/codex_doctor.py +1 -1
- package/skills/token-optimizer/scripts/cursor_coach.py +5 -4
- package/skills/token-optimizer/scripts/cursor_install.py +1 -0
- package/skills/token-optimizer/scripts/delta_serve.py +174 -0
- package/skills/token-optimizer/scripts/devin_source.py +1 -1
- package/skills/token-optimizer/scripts/hermes_doctor.py +2 -1
- package/skills/token-optimizer/scripts/hermes_install.py +2 -1
- package/skills/token-optimizer/scripts/measure.py +14 -21
- package/skills/token-optimizer/scripts/read_cache.py +19 -76
- package/skills/token-optimizer/scripts/reset_epoch.py +5 -3
- package/skills/token-optimizer/scripts/session_activity.py +1 -1
- package/skills/token-optimizer/scripts/session_store.py +5 -6
|
@@ -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.
|
|
16
|
+
"version": "5.13.82",
|
|
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.
|
|
58
|
+
"version": "5.13.82",
|
|
59
59
|
"author": {
|
|
60
60
|
"name": "Alex Greenshpun",
|
|
61
61
|
"url": "https://linkedin.com/in/alexgreensh"
|
package/hooks/module_runner.py
CHANGED
|
@@ -134,7 +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 = ('__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', 'selfheal_guard.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', 'pt_resume_cues.py', 'subscription_audits.py', 'limit_units.py', 'local_adapt.py', 'prefix_cost.py', 'poc_commands.py', 'counted_closes.py', 'counted_headline.py', 'apply_safe.py', 'autocompact_advice.py', 'cold_guard.py', 'keepwarm_auto.py', 'keepwarm_rearm.py', 'next_actions.py', 'ttl_file_memo.py', 'project_md_walk.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', 'like_for_like.py', 'model_families.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', 'selfheal_guard.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', 'pt_resume_cues.py', 'subscription_audits.py', 'limit_units.py', 'local_adapt.py', 'prefix_cost.py', 'poc_commands.py', 'counted_closes.py', 'counted_headline.py', 'apply_safe.py', 'autocompact_advice.py', 'cold_guard.py', 'keepwarm_auto.py', 'keepwarm_rearm.py', 'next_actions.py', 'ttl_file_memo.py', 'project_md_walk.py')
|
|
138
138
|
|
|
139
139
|
|
|
140
140
|
def _runtime_sources(measure_src):
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@alexgreensh/token-optimizer",
|
|
3
|
-
"version": "5.13.
|
|
3
|
+
"version": "5.13.82",
|
|
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)",
|
|
@@ -471,11 +471,13 @@ function savingsTransformationHtml(data) {
|
|
|
471
471
|
var wp = ba.session_weight_pool || {}, fr = wp.flat_rates || null;
|
|
472
472
|
var fixed = fr && has(fr.input) && has(fr.output) && has(fr.cache_read) && has(fr.cache_write);
|
|
473
473
|
var own = fixed && wp.price_basis === 'own_prices';
|
|
474
|
+
var reference = wp.price_basis === 'current_model_reference';
|
|
474
475
|
var rate = function(v) { return '$' + Number(num(v).toFixed(2)); };
|
|
475
|
-
var method = '<ul><li>' + (prov.versus_label ? esc(prov.versus_label) : 'Without Token Optimizer') + (own ? ', at your current prices' : fixed ? ', at the fixed price card' : '') + ': ' + savingsCents(ba.counterfactual_monthly_usd) + ' a month</li>' +
|
|
476
|
-
'<li>' + (own ? 'This period, at your current prices' : fixed ? 'This period, at the same fixed price card' : 'What you actually spent') + ': ' + savingsCents(ba.actual_monthly_usd) + ' a month</li>' +
|
|
476
|
+
var method = '<ul><li>' + (prov.versus_label ? esc(prov.versus_label) : 'Without Token Optimizer') + (reference ? ', at the same current model-family price card' : own ? ', at your current prices' : fixed ? ', at the fixed price card' : '') + ': ' + savingsCents(ba.counterfactual_monthly_usd) + ' a month</li>' +
|
|
477
|
+
'<li>' + (reference ? 'This period, at the same current model-family price card' : own ? 'This period, at your current prices' : fixed ? 'This period, at the same fixed price card' : 'What you actually spent') + ': ' + savingsCents(ba.actual_monthly_usd) + ' a month</li>' +
|
|
477
478
|
'<li>Difference: ' + savingsCents(ba.monthly_savings_usd) + ' a month</li></ul>' +
|
|
478
|
-
(
|
|
479
|
+
(reference ? '<p>Both sides are priced at today\'s reference card for the model family that ran each token, so a newer generation inside the same family cannot count as a saving or a loss. Routing between families still counts because it changes what the same work costs.</p>'
|
|
480
|
+
: own ? '<p>Both sides are priced at your own current prices (per million tokens: ' + rate(fr.input) + ' input, ' + rate(fr.output) + ' output, ' + rate(fr.cache_read) + ' cache read, ' + rate(fr.cache_write) + ' cache write, averaged over the models you ran this period), so a price change between the two periods cannot count as a saving.</p>'
|
|
479
481
|
: fixed ? '<p>Both sides are priced at one fixed card (per million tokens: $' + num(fr.input) + ' input, $' + num(fr.output) + ' output, $' + num(fr.cache_read) + ' cache read, $' + num(fr.cache_write) + ' cache write), so a price change between the two periods cannot count as a saving. These are dollars at that card, not your bill.' +
|
|
480
482
|
(num(wp.engine_priced_actual_usd) > 0 ? ' At the prices of the models you actually used, this period comes to ' + savingsCents(wp.engine_priced_actual_usd) + ' at API rates.' : '') + '</p>' : '') +
|
|
481
483
|
(prov.note ? '<p>' + esc(prov.note) + '</p>' : '') +
|
|
@@ -671,7 +673,7 @@ function savingsCostTrendHtml(raw) {
|
|
|
671
673
|
var points = trend.map(function(p, i) { return (i * 500 / (trend.length - 1)).toFixed(1) + ',' + (90 - Number(p.index) / maxIndex * 80).toFixed(1); }).join(' ');
|
|
672
674
|
var ticks = trend.map(function(p, i) { if (i !== trend.length - 1 && i % Math.ceil(trend.length / 6)) return ''; var d = new Date(p.month + '-01T00:00:00'), x = 20 + i * 460 / (trend.length - 1); return '<text x="' + x.toFixed(1) + '" y="115" text-anchor="middle" fill="currentColor" font-size="11">' + esc(d.toLocaleDateString('en-US', {month:'short'})) + '</text>'; }).join('');
|
|
673
675
|
return '<div class="card wide st-card"><h2 class="st-h">Cost per message down ' + down + '% since ' + esc(since) + '</h2>' +
|
|
674
|
-
'<p class="st-lead">Indexed to the first month, at
|
|
676
|
+
'<p class="st-lead">Indexed to the first month, at the same current model-family reference prices as the transformation card. This trend is per message and is not attributed to Token Optimizer.</p>' +
|
|
675
677
|
'<p>Start ' + Math.round(start) + ' · Latest ' + Math.round(latest) + '</p>' +
|
|
676
678
|
'<svg viewBox="0 0 500 120" role="img" aria-label="Monthly cost per message index" style="width:100%;height:140px">' +
|
|
677
679
|
'<polyline fill="none" stroke="currentColor" stroke-width="3" points="' + points + '"></polyline>' + ticks + '</svg></div>';
|
|
@@ -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) + ('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')
|
|
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', 'like_for_like.py', 'model_families.py', 'own_price_card.py', 'transcript_stream.py', 'checkpoint_direction.py', 'checkpoint_retention.py')
|
|
14
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', 'selfheal_guard.py', 'config_cache.py', 'setup_observation_cache.py', 'status_bar_refresh.py', 'routing_default.py', 'pilot_report.py',)
|
|
15
15
|
RUNTIME_SOURCES += ('nudge_followthrough.py', 'runway_all_in.py',)
|
|
16
16
|
RUNTIME_SOURCES += ('session_activity.py', 'routing_savings.py', 'pt_resume_cues.py', 'subscription_audits.py', 'limit_units.py', 'local_adapt.py', 'prefix_cost.py', 'poc_commands.py', 'counted_closes.py', 'counted_headline.py', 'apply_safe.py', 'autocompact_advice.py', 'cold_guard.py', 'keepwarm_auto.py', 'keepwarm_rearm.py', 'next_actions.py', 'ttl_file_memo.py', 'project_md_walk.py',)
|
|
@@ -814,6 +814,10 @@ def compact_capture(transcript_path=None, session_id=None, trigger=None, cwd=Non
|
|
|
814
814
|
)
|
|
815
815
|
if not _measure_facade._write_checkpoint_atomic(checkpoint_path, content):
|
|
816
816
|
return None
|
|
817
|
+
_measure_facade._append_checkpoint_event(
|
|
818
|
+
session_id=sid, trigger=trigger or "auto",
|
|
819
|
+
checkpoint_path=checkpoint_path, fill_pct=fill_pct,
|
|
820
|
+
quality_score=quality_score, placeholder=True)
|
|
817
821
|
return str(checkpoint_path)
|
|
818
822
|
|
|
819
823
|
try:
|
|
@@ -862,6 +866,12 @@ def compact_capture(transcript_path=None, session_id=None, trigger=None, cwd=Non
|
|
|
862
866
|
# Generate checkpoint markdown
|
|
863
867
|
sid = _measure_facade.sanitize_session_id(session_id) if session_id else _measure_facade.sanitize_session_id(filepath.stem)
|
|
864
868
|
quality_summary = None
|
|
869
|
+
# An unmeasured session (grade '?') still carries the scorer's fallback
|
|
870
|
+
# score (last_measured_score, default 100). That number is honest in the
|
|
871
|
+
# checkpoint sidecar (restore metadata), but the telemetry event must not
|
|
872
|
+
# present it as a measurement: checkpoint-stats readers would see a
|
|
873
|
+
# phantom 100 for a session that was never measured (#360 class).
|
|
874
|
+
quality_measured = True
|
|
865
875
|
try:
|
|
866
876
|
if _trusted_transcript is not None:
|
|
867
877
|
# A translated transcript carries no usage data, so scoring it
|
|
@@ -894,6 +904,10 @@ def compact_capture(transcript_path=None, session_id=None, trigger=None, cwd=Non
|
|
|
894
904
|
if fill_pct is None:
|
|
895
905
|
cfd = quality_summary.get("breakdown", {}).get("context_fill_degradation", {})
|
|
896
906
|
fill_pct = cfd.get("fill_pct")
|
|
907
|
+
# compute_quality_score returns measured=False for unmeasured
|
|
908
|
+
# sessions; a cache blob old enough to lack the key is treated as
|
|
909
|
+
# measured (we cannot prove otherwise).
|
|
910
|
+
quality_measured = quality_summary.get("measured") is not False
|
|
897
911
|
except Exception:
|
|
898
912
|
quality_summary = None
|
|
899
913
|
if quality_summary:
|
|
@@ -1012,6 +1026,16 @@ def compact_capture(transcript_path=None, session_id=None, trigger=None, cwd=Non
|
|
|
1012
1026
|
_measure_facade._cleanup_quality_cache()
|
|
1013
1027
|
_measure_facade._rotate_checkpoint_events()
|
|
1014
1028
|
|
|
1029
|
+
# Every successful checkpoint write is recorded here, at the single choke
|
|
1030
|
+
# point all capture paths (PreCompact/Stop/SessionEnd/progressive/quality/
|
|
1031
|
+
# milestone) funnel through. Recording only in the progressive/quality
|
|
1032
|
+
# callers left real Stop checkpoints invisible to checkpoint-stats (#358).
|
|
1033
|
+
_measure_facade._append_checkpoint_event(
|
|
1034
|
+
session_id=sid, trigger=trigger or "auto",
|
|
1035
|
+
checkpoint_path=checkpoint_path, fill_pct=fill_pct,
|
|
1036
|
+
quality_score=quality_score if quality_measured else None,
|
|
1037
|
+
quality_unmeasured=not quality_measured)
|
|
1038
|
+
|
|
1015
1039
|
return str(checkpoint_path)
|
|
1016
1040
|
|
|
1017
1041
|
|
|
@@ -1969,11 +1993,14 @@ def compact_restore(session_id=None, cwd=None, is_compact=None, new_session_only
|
|
|
1969
1993
|
_print_intel_digest(sid_safe)
|
|
1970
1994
|
# Only the estimated avoided working set is a credit. The injected
|
|
1971
1995
|
# checkpoint itself adds context and is never a savings floor.
|
|
1996
|
+
# The event is logged even at zero credit so a successful restore
|
|
1997
|
+
# stays auditable when the working set was empty (#358).
|
|
1972
1998
|
try:
|
|
1973
1999
|
est_tokens_recovered = _measure_facade._checkpoint_restore_recovery_tokens(sid_safe, 0)
|
|
1974
|
-
|
|
1975
|
-
|
|
1976
|
-
|
|
2000
|
+
_measure_facade._log_savings_event("checkpoint_restore", est_tokens_recovered,
|
|
2001
|
+
session_id=sid_safe,
|
|
2002
|
+
detail=f"restored from {trigger_label}" if est_tokens_recovered > 0
|
|
2003
|
+
else f"restored from {trigger_label} (no working-set credit)")
|
|
1977
2004
|
except (OSError, KeyError):
|
|
1978
2005
|
pass
|
|
1979
2006
|
return
|
|
@@ -1,36 +1,53 @@
|
|
|
1
|
-
"""An unattributed cost-per-message trend on
|
|
2
|
-
|
|
3
|
-
|
|
1
|
+
"""An unattributed cost-per-message trend on the same like-for-like price basis
|
|
2
|
+
as the transformation card: today's reference card for the model family that did
|
|
3
|
+
the work. Generation price movement therefore does not move the index through
|
|
4
|
+
price, while family routing still changes what a message costs."""
|
|
4
5
|
import json
|
|
5
6
|
import math
|
|
6
7
|
from collections import defaultdict
|
|
7
8
|
|
|
9
|
+
from . import like_for_like
|
|
10
|
+
from . import _compat
|
|
11
|
+
|
|
8
12
|
|
|
9
13
|
def index_rows(rows):
|
|
10
|
-
|
|
14
|
+
monthly_cost = defaultdict(float)
|
|
15
|
+
monthly_messages = defaultdict(int)
|
|
16
|
+
try:
|
|
17
|
+
facade = _compat.facade()
|
|
18
|
+
except KeyError:
|
|
19
|
+
# Unit tests import this module directly; production always resolves the
|
|
20
|
+
# already-loaded measure facade. Importing here keeps the module pure for
|
|
21
|
+
# callers while avoiding a circular import during measure startup.
|
|
22
|
+
import measure as facade
|
|
23
|
+
|
|
11
24
|
for day, messages, raw in rows:
|
|
12
25
|
try:
|
|
13
26
|
messages = int(messages or 0)
|
|
14
27
|
models = json.loads(raw) if isinstance(raw, str) and raw else (raw or {})
|
|
15
28
|
if not day or messages < 0 or not isinstance(models, dict):
|
|
16
29
|
continue
|
|
17
|
-
|
|
18
|
-
for parts in models.
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
if not
|
|
30
|
+
classes = {}
|
|
31
|
+
for model, parts in models.items():
|
|
32
|
+
key = like_for_like.model_key(facade, model)
|
|
33
|
+
if key and isinstance(parts, dict):
|
|
34
|
+
like_for_like.add_parts(classes.setdefault(key, like_for_like.empty_classes()), parts)
|
|
35
|
+
valued = like_for_like.value_model_classes(facade, classes)
|
|
36
|
+
if not valued or valued["coverage"] < 0.80 or not math.isfinite(valued["usd"]):
|
|
24
37
|
continue
|
|
25
|
-
|
|
26
|
-
|
|
38
|
+
month = str(day)[:7]
|
|
39
|
+
monthly_cost[month] += valued["usd"]
|
|
40
|
+
monthly_messages[month] += messages
|
|
27
41
|
except (TypeError, ValueError, OverflowError):
|
|
28
42
|
continue
|
|
29
|
-
values = [(month,
|
|
43
|
+
values = [(month, monthly_cost[month] / monthly_messages[month])
|
|
44
|
+
for month in sorted(monthly_messages)
|
|
45
|
+
if monthly_messages[month] and monthly_cost[month] > 0]
|
|
30
46
|
if not values:
|
|
31
47
|
return []
|
|
32
48
|
base = values[0][1]
|
|
33
|
-
return [{'month': month, 'index': round(value / base * 100, 1)
|
|
49
|
+
return [{'month': month, 'index': round(value / base * 100, 1),
|
|
50
|
+
'price_basis': 'current_model_reference'} for month, value in values]
|
|
34
51
|
|
|
35
52
|
|
|
36
53
|
def query(conn):
|
|
@@ -2060,11 +2060,34 @@ def _read_plugin_version(default=None):
|
|
|
2060
2060
|
Falls back to the default when the manifest is absent, which is the case for
|
|
2061
2061
|
a skill-only install with no plugin directory. Never raises: a version
|
|
2062
2062
|
string is cosmetic and must not prevent the tool from running.
|
|
2063
|
+
|
|
2064
|
+
The Codex marketplace artifact ships only ``.codex-plugin/plugin.json``
|
|
2065
|
+
(scripts/sync-codex-marketplace-plugin.sh stages skills/, hooks/ and
|
|
2066
|
+
.codex-plugin/), so a Codex install has no .claude-plugin manifest anywhere
|
|
2067
|
+
in this probe and the version fell back to "0.0.0" (#357). Probe both
|
|
2068
|
+
manifests at the plugin root, preferring the active runtime's own.
|
|
2063
2069
|
"""
|
|
2064
2070
|
_measure_facade = _compat.facade()
|
|
2065
2071
|
here = _measure_facade.Path(_measure_facade.__file__).resolve()
|
|
2066
|
-
|
|
2067
|
-
|
|
2072
|
+
try:
|
|
2073
|
+
runtime = (_measure_facade.os.environ.get("TOKEN_OPTIMIZER_RUNTIME") or "").strip().lower()
|
|
2074
|
+
except Exception:
|
|
2075
|
+
runtime = ""
|
|
2076
|
+
manifest_dirs = (".codex-plugin", ".claude-plugin") if runtime == "codex" else (".claude-plugin", ".codex-plugin")
|
|
2077
|
+
# In every shipped layout (repo checkout, Codex marketplace mirror, Cowork
|
|
2078
|
+
# committed tree, installed plugin) this script sits at
|
|
2079
|
+
# <plugin root>/skills/token-optimizer/scripts/measure.py and the manifest
|
|
2080
|
+
# lives at <plugin root>/<manifest dir>/plugin.json. Derive the plugin root
|
|
2081
|
+
# from that fixed relative location instead of walking every ancestor: an
|
|
2082
|
+
# unbounded walk stats real home directories (pytest tmp on Windows lives
|
|
2083
|
+
# under the user profile, so tests/_home_guard.py flags it) and can select
|
|
2084
|
+
# an unrelated parent project's manifest. Anything that does not match the
|
|
2085
|
+
# shipped layout is a skill-only install and falls back to the default.
|
|
2086
|
+
if here.parts[-4:] != ("skills", "token-optimizer", "scripts", "measure.py"):
|
|
2087
|
+
return default
|
|
2088
|
+
plugin_root = here.parents[3]
|
|
2089
|
+
for manifest_dir in manifest_dirs:
|
|
2090
|
+
candidate = plugin_root / manifest_dir / "plugin.json"
|
|
2068
2091
|
try:
|
|
2069
2092
|
if candidate.is_file():
|
|
2070
2093
|
value = _measure_facade.json.loads(candidate.read_text(encoding="utf-8")).get("version")
|
|
@@ -3285,7 +3285,8 @@ def _collect_trends_from_jsonl(days=None):
|
|
|
3285
3285
|
"subagents_json": _measure_facade.json.dumps(parsed.get("subagents_used") or {}),
|
|
3286
3286
|
"tool_calls_json": _measure_facade.json.dumps(parsed.get("tool_calls") or {}),
|
|
3287
3287
|
"slug": parsed.get("slug"), "topic": parsed.get("topic"),
|
|
3288
|
-
"quality_score": quality["score"]
|
|
3288
|
+
"quality_score": quality["score"] if quality.get("measured") else None,
|
|
3289
|
+
"quality_grade": quality["grade"],
|
|
3289
3290
|
"is_sidechain": int(bool(parsed.get("is_sidechain"))), "transcript_mtime": mtime,
|
|
3290
3291
|
}
|
|
3291
3292
|
conn.execute("INSERT INTO session_log (" + ",".join(values) + ") VALUES ("
|
|
@@ -173,8 +173,9 @@ def _active_days(conn, tables, start, end):
|
|
|
173
173
|
return days
|
|
174
174
|
|
|
175
175
|
|
|
176
|
-
def _status(recent, expected, earlier, zero_recent):
|
|
177
|
-
|
|
176
|
+
def _status(recent, expected, earlier, zero_recent, zero_effect_events=None):
|
|
177
|
+
zero_effect_events = recent if zero_effect_events is None else zero_effect_events
|
|
178
|
+
if zero_effect_events >= ZERO_EFFECT_MIN and zero_recent >= ZERO_EFFECT_SHARE * zero_effect_events:
|
|
178
179
|
return "no_effect"
|
|
179
180
|
if expected is None:
|
|
180
181
|
return "new" if recent else ("never" if not earlier else "idle")
|
|
@@ -226,8 +227,9 @@ def _collect(db_path, now, recent_days):
|
|
|
226
227
|
continue
|
|
227
228
|
where, params = _where(column, names, prefix)
|
|
228
229
|
try:
|
|
229
|
-
recent, zero_recent = conn.execute(
|
|
230
|
-
f"SELECT COUNT(*), COALESCE(SUM({_SAVED_EXPR[table]} <= 0), 0)
|
|
230
|
+
recent, zero_recent, credited_recent = conn.execute(
|
|
231
|
+
f"SELECT COUNT(*), COALESCE(SUM({_SAVED_EXPR[table]} <= 0), 0), "
|
|
232
|
+
f"COALESCE(SUM({_SAVED_EXPR[table]} > 0), 0) FROM {table} "
|
|
231
233
|
f"WHERE {where} AND timestamp >= ?", params + [recent_start]).fetchone()
|
|
232
234
|
earlier, first_earlier = conn.execute(
|
|
233
235
|
f"SELECT COUNT(*), MIN(timestamp) FROM {table} WHERE {where} "
|
|
@@ -247,7 +249,14 @@ def _collect(db_path, now, recent_days):
|
|
|
247
249
|
earlier_active = len(_active_days(conn, tables, str(first_earlier)[:10], recent_start))
|
|
248
250
|
if earlier_active:
|
|
249
251
|
expected = round(earlier / earlier_active * recent_active, 1)
|
|
250
|
-
|
|
252
|
+
zero_effect_events = recent
|
|
253
|
+
zero_effect_zeroes = zero_recent
|
|
254
|
+
if key == "checkpoint_restore":
|
|
255
|
+
# Zero-credit restores audit a successful serve. Only rows that
|
|
256
|
+
# claimed credit belong in the zero-effect rate at all.
|
|
257
|
+
zero_effect_events = credited_recent
|
|
258
|
+
zero_effect_zeroes = 0
|
|
259
|
+
status = _status(recent, expected, earlier, zero_effect_zeroes, zero_effect_events)
|
|
251
260
|
row.update(events=recent, earlier_events=earlier, expected=expected,
|
|
252
261
|
last_event=str(last)[:10] if last else None, status=status,
|
|
253
262
|
warning=status in ("quiet", "no_effect"))
|
|
@@ -143,7 +143,8 @@ def workload_anchor(f, conn, tier):
|
|
|
143
143
|
start, end = window.get('start'), window.get('end')
|
|
144
144
|
if not start or not end:
|
|
145
145
|
return None
|
|
146
|
-
metrics = f._price_parent_window(conn, 'AND date >= ? AND date <= ?', (start, end), tier
|
|
146
|
+
metrics = f._price_parent_window(conn, 'AND date >= ? AND date <= ?', (start, end), tier,
|
|
147
|
+
include_sidechains=True)
|
|
147
148
|
return {'metrics': metrics, 'label': 'baseline (%s to %s)' % (start, end)} if metrics else None
|
|
148
149
|
except (OSError, ValueError, TypeError):
|
|
149
150
|
return None
|