@alexgreensh/token-optimizer 5.13.69 → 5.13.70
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/PRIVACY.md +4 -0
- package/hooks/hooks.json +11 -1
- package/hooks/module_runner.py +4 -1
- package/hooks/posttooluse_runner.py +44 -48
- package/hooks/sessionstart_runner.py +24 -5
- package/hooks/stop_runner.py +6 -6
- package/package.json +1 -1
- package/skills/token-optimizer/assets/dashboard.html +399 -509
- package/skills/token-optimizer/assets/savings_story.js +661 -0
- package/skills/token-optimizer/pricing/prices.json +1 -0
- package/skills/token-optimizer/references/implementation-playbook.md +3 -0
- package/skills/token-optimizer/scripts/_measure/__init__.py +3 -1
- package/skills/token-optimizer/scripts/_measure/archive_health.py +14 -0
- package/skills/token-optimizer/scripts/_measure/archive_void_codex.py +163 -0
- package/skills/token-optimizer/scripts/_measure/archive_void_evidence.py +165 -0
- package/skills/token-optimizer/scripts/_measure/audit.py +27 -135
- package/skills/token-optimizer/scripts/_measure/baseline_provenance.py +339 -0
- package/skills/token-optimizer/scripts/_measure/cache_policy.py +261 -581
- package/skills/token-optimizer/scripts/_measure/checkpoint_direction.py +97 -0
- package/skills/token-optimizer/scripts/_measure/checkpoint_retention.py +20 -0
- package/skills/token-optimizer/scripts/_measure/cli.py +12 -8
- package/skills/token-optimizer/scripts/_measure/codex_quality.py +246 -0
- package/skills/token-optimizer/scripts/_measure/compaction_survival.py +158 -0
- package/skills/token-optimizer/scripts/_measure/compression_fixture_void.py +147 -0
- package/skills/token-optimizer/scripts/_measure/compression_scan_checkpoint.py +72 -0
- package/skills/token-optimizer/scripts/_measure/context_reset_marker.py +64 -0
- package/skills/token-optimizer/scripts/_measure/continuity.py +64 -118
- package/skills/token-optimizer/scripts/_measure/cost_per_message_trend.py +40 -0
- package/skills/token-optimizer/scripts/_measure/counted_cap.py +28 -0
- package/skills/token-optimizer/scripts/_measure/counted_orphans.py +190 -0
- package/skills/token-optimizer/scripts/_measure/counted_position.py +20 -0
- package/skills/token-optimizer/scripts/_measure/counted_pricing_v5.py +267 -0
- package/skills/token-optimizer/scripts/_measure/counted_subagents.py +371 -0
- package/skills/token-optimizer/scripts/_measure/coverage_report.py +285 -0
- package/skills/token-optimizer/scripts/_measure/daemon.py +53 -74
- package/skills/token-optimizer/scripts/_measure/dashboard.py +87 -151
- package/skills/token-optimizer/scripts/_measure/dashboard_heal_claim.py +36 -0
- package/skills/token-optimizer/scripts/_measure/evidence_parallel.py +95 -0
- package/skills/token-optimizer/scripts/_measure/feature_health.py +256 -0
- package/skills/token-optimizer/scripts/_measure/file_refetch.py +250 -0
- package/skills/token-optimizer/scripts/_measure/first_call_context.py +216 -0
- package/skills/token-optimizer/scripts/_measure/first_read_outcomes.py +261 -0
- package/skills/token-optimizer/scripts/_measure/first_read_revive.py +137 -0
- package/skills/token-optimizer/scripts/_measure/fixture_context.py +65 -0
- package/skills/token-optimizer/scripts/_measure/headline.py +100 -0
- package/skills/token-optimizer/scripts/_measure/holdout_fallback.py +96 -0
- package/skills/token-optimizer/scripts/_measure/holdout_report.py +125 -0
- package/skills/token-optimizer/scripts/_measure/keepwarm_economics.py +201 -0
- package/skills/token-optimizer/scripts/_measure/keepwarm_fork.py +140 -0
- package/skills/token-optimizer/scripts/_measure/keepwarm_guard.py +35 -0
- package/skills/token-optimizer/scripts/_measure/keepwarm_guard_server.py +85 -0
- package/skills/token-optimizer/scripts/_measure/keepwarm_linux.py +121 -0
- package/skills/token-optimizer/scripts/_measure/keepwarm_prefix.py +143 -0
- package/skills/token-optimizer/scripts/_measure/keepwarm_response_filter.py +84 -0
- package/skills/token-optimizer/scripts/_measure/keepwarm_safety.py +256 -0
- package/skills/token-optimizer/scripts/_measure/lean_resume_receivers.py +260 -0
- package/skills/token-optimizer/scripts/_measure/lean_resume_threshold.py +76 -0
- package/skills/token-optimizer/scripts/_measure/lease_candidate_cleanup.py +82 -0
- package/skills/token-optimizer/scripts/_measure/lifecycle.py +54 -162
- package/skills/token-optimizer/scripts/_measure/mcp_archive_tripwire.py +120 -0
- package/skills/token-optimizer/scripts/_measure/mod_action_booking.py +178 -0
- package/skills/token-optimizer/scripts/_measure/mod_compaction_booking.py +276 -0
- package/skills/token-optimizer/scripts/_measure/mod_fresh_booking.py +105 -0
- package/skills/token-optimizer/scripts/_measure/output_reread.py +629 -0
- package/skills/token-optimizer/scripts/_measure/own_price_card.py +268 -0
- package/skills/token-optimizer/scripts/_measure/periphery_exposure.py +85 -0
- package/skills/token-optimizer/scripts/_measure/pricing.py +152 -87
- package/skills/token-optimizer/scripts/_measure/quality_archive.py +159 -215
- package/skills/token-optimizer/scripts/_measure/quality_checkpoint.py +173 -0
- package/skills/token-optimizer/scripts/_measure/quality_continuity.py +43 -0
- package/skills/token-optimizer/scripts/_measure/rework_metrics.py +194 -0
- package/skills/token-optimizer/scripts/_measure/routing_period.py +48 -0
- package/skills/token-optimizer/scripts/_measure/savings.py +431 -863
- package/skills/token-optimizer/scripts/_measure/savings_story.py +187 -0
- package/skills/token-optimizer/scripts/_measure/session_best.py +24 -0
- package/skills/token-optimizer/scripts/_measure/session_effect.py +557 -0
- package/skills/token-optimizer/scripts/_measure/session_flush_lock.py +75 -0
- package/skills/token-optimizer/scripts/_measure/session_store_spool.py +220 -0
- package/skills/token-optimizer/scripts/_measure/sessions.py +96 -196
- package/skills/token-optimizer/scripts/_measure/setup_attachment_counter.py +196 -0
- package/skills/token-optimizer/scripts/_measure/setup_budget_monitor.py +180 -0
- package/skills/token-optimizer/scripts/_measure/setup_connector_ledger.py +126 -0
- package/skills/token-optimizer/scripts/_measure/setup_step.py +220 -0
- package/skills/token-optimizer/scripts/_measure/status_bar_lock.py +117 -0
- package/skills/token-optimizer/scripts/_measure/structural_archives.py +79 -0
- package/skills/token-optimizer/scripts/_measure/structural_dedupe.py +91 -0
- package/skills/token-optimizer/scripts/_measure/structural_ledger.py +418 -0
- package/skills/token-optimizer/scripts/_measure/structural_listing.py +163 -0
- package/skills/token-optimizer/scripts/_measure/structural_report.py +339 -0
- package/skills/token-optimizer/scripts/_measure/structural_seed.py +164 -0
- package/skills/token-optimizer/scripts/_measure/structural_value.py +248 -0
- package/skills/token-optimizer/scripts/_measure/structure_funnel.py +97 -0
- package/skills/token-optimizer/scripts/_measure/timestamp_cache.py +11 -0
- package/skills/token-optimizer/scripts/_measure/token_type_split.py +29 -0
- package/skills/token-optimizer/scripts/_measure/transcript_backfill.py +419 -0
- package/skills/token-optimizer/scripts/_measure/transcript_product.py +228 -0
- package/skills/token-optimizer/scripts/_measure/transcript_stream.py +279 -0
- package/skills/token-optimizer/scripts/_measure/trends.py +44 -185
- package/skills/token-optimizer/scripts/_measure/ttl_period.py +6 -0
- package/skills/token-optimizer/scripts/_measure/upgrade_drain_control.py +287 -0
- package/skills/token-optimizer/scripts/activity_tracker.py +4 -33
- package/skills/token-optimizer/scripts/antigravity_install.py +2 -0
- package/skills/token-optimizer/scripts/archive_result.py +15 -19
- package/skills/token-optimizer/scripts/archive_verify.py +165 -0
- package/skills/token-optimizer/scripts/bash_compress.py +14 -43
- package/skills/token-optimizer/scripts/bash_compress_hook.py +132 -2
- package/skills/token-optimizer/scripts/checkpoint_state.py +2 -2
- package/skills/token-optimizer/scripts/cloud_kit.py +3 -6
- package/skills/token-optimizer/scripts/codemap.py +274 -0
- package/skills/token-optimizer/scripts/codemap_hint.py +153 -0
- package/skills/token-optimizer/scripts/codemap_index.py +656 -0
- package/skills/token-optimizer/scripts/codemap_ledger.py +309 -0
- package/skills/token-optimizer/scripts/codemap_reread.py +161 -0
- package/skills/token-optimizer/scripts/codex_doctor.py +9 -1
- package/skills/token-optimizer/scripts/codex_log_index.py +34 -15
- package/skills/token-optimizer/scripts/codex_session.py +16 -216
- package/skills/token-optimizer/scripts/compression_backfill.py +4 -35
- package/skills/token-optimizer/scripts/context_intel.py +5 -3
- package/skills/token-optimizer/scripts/copilot_install.py +2 -0
- package/skills/token-optimizer/scripts/coverage_funnel.py +261 -0
- package/skills/token-optimizer/scripts/cursor_install.py +12 -0
- package/skills/token-optimizer/scripts/cursor_quality.py +16 -64
- package/skills/token-optimizer/scripts/dashboard_assets.py +21 -0
- package/skills/token-optimizer/scripts/deterministic_candidates.py +2 -10
- package/skills/token-optimizer/scripts/devin_source.py +8 -3
- package/skills/token-optimizer/scripts/devin_verify.py +7 -1
- package/skills/token-optimizer/scripts/grok_install.py +2 -0
- package/skills/token-optimizer/scripts/heal_report.py +7 -6
- package/skills/token-optimizer/scripts/hermes_doctor.py +9 -1
- package/skills/token-optimizer/scripts/hermes_install.py +7 -1
- package/skills/token-optimizer/scripts/hermes_session.py +14 -136
- package/skills/token-optimizer/scripts/hint_paths.py +21 -0
- package/skills/token-optimizer/scripts/holdout.py +136 -0
- package/skills/token-optimizer/scripts/hook_runtime.py +1 -0
- package/skills/token-optimizer/scripts/hook_skip_log.py +89 -0
- package/skills/token-optimizer/scripts/large_transcripts.py +31 -0
- package/skills/token-optimizer/scripts/lean_resume_carry.py +518 -0
- package/skills/token-optimizer/scripts/measure.py +34 -76
- package/skills/token-optimizer/scripts/post_run_classify.py +349 -0
- package/skills/token-optimizer/scripts/preserved_reinject.py +54 -0
- package/skills/token-optimizer/scripts/read_cache.py +99 -100
- package/skills/token-optimizer/scripts/reset_epoch.py +3 -3
- package/skills/token-optimizer/scripts/session_store.py +49 -99
- package/skills/token-optimizer/scripts/session_store_guard.py +75 -0
- package/skills/token-optimizer/scripts/settings_backup.py +379 -0
- package/skills/token-optimizer/scripts/shipped_hook_templates.py +1 -0
- package/skills/token-optimizer/scripts/statusline.js +1 -1
- package/skills/token-optimizer/scripts/structural.py +25 -0
- package/skills/token-optimizer/scripts/structure_map.py +4 -26
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"""Definition-only implementations; mutable state belongs to measure."""
|
|
2
2
|
from __future__ import annotations
|
|
3
|
-
from . import _compat
|
|
3
|
+
from . import _compat, transcript_stream, quality_continuity, quality_checkpoint, lease_candidate_cleanup
|
|
4
4
|
|
|
5
5
|
|
|
6
6
|
def _int_env(key: str, default: int) -> int:
|
|
@@ -464,7 +464,7 @@ def _rec_track_tool_result(rec, block, idx, ts):
|
|
|
464
464
|
open_b["post_calls"].append(call)
|
|
465
465
|
|
|
466
466
|
|
|
467
|
-
def _parse_jsonl_for_quality(filepath):
|
|
467
|
+
def _parse_jsonl_for_quality(filepath, checkpoint=None):
|
|
468
468
|
"""Parse a JSONL session file and extract quality-relevant data.
|
|
469
469
|
|
|
470
470
|
Returns a dict with chronological lists of reads, writes, tool results,
|
|
@@ -473,7 +473,14 @@ def _parse_jsonl_for_quality(filepath):
|
|
|
473
473
|
"""
|
|
474
474
|
_measure_facade = _compat.facade()
|
|
475
475
|
if _measure_facade._use_codex_session_adapter(filepath):
|
|
476
|
-
|
|
476
|
+
try:
|
|
477
|
+
with open(filepath, "rb"):
|
|
478
|
+
pass
|
|
479
|
+
except OSError:
|
|
480
|
+
return quality_checkpoint.ParseFailure("unreadable")
|
|
481
|
+
parsed = (_measure_facade.codex_session.parse_jsonl_for_quality(filepath, checkpoint)
|
|
482
|
+
if checkpoint else _measure_facade.codex_session.parse_jsonl_for_quality(filepath))
|
|
483
|
+
return parsed if parsed is not None else quality_checkpoint.ParseFailure("no_messages")
|
|
477
484
|
|
|
478
485
|
reads = [] # (index, path, timestamp)
|
|
479
486
|
writes = [] # (index, path, timestamp)
|
|
@@ -516,16 +523,25 @@ def _parse_jsonl_for_quality(filepath):
|
|
|
516
523
|
_rec_cwd = ""
|
|
517
524
|
|
|
518
525
|
idx = 0
|
|
526
|
+
saved_checkpoint = None
|
|
527
|
+
parsed_offset = 0
|
|
528
|
+
window_offset = 0
|
|
519
529
|
try:
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
530
|
+
with open(filepath, "rb") as f:
|
|
531
|
+
if checkpoint:
|
|
532
|
+
resumed = quality_checkpoint.restore(f, checkpoint)
|
|
533
|
+
if resumed is not None:
|
|
534
|
+
_rec = resumed
|
|
535
|
+
idx = checkpoint["idx"]
|
|
536
|
+
compactions = checkpoint["compactions"]
|
|
537
|
+
tool_calls = checkpoint["tool_calls"]
|
|
538
|
+
current_model = checkpoint["model"]
|
|
539
|
+
_rec_first_ts = checkpoint["first_ts"]
|
|
540
|
+
_rec_last_ts = checkpoint["last_ts"]
|
|
541
|
+
_rec_cwd = checkpoint["cwd"]
|
|
542
|
+
parsed_offset = checkpoint["offset"]
|
|
543
|
+
window_offset = parsed_offset
|
|
544
|
+
for line_offset, line in quality_checkpoint.lines(f, transcript_stream.LINE_BYTES):
|
|
529
545
|
try:
|
|
530
546
|
record = _measure_facade.json.loads(line)
|
|
531
547
|
except _measure_facade.json.JSONDecodeError:
|
|
@@ -548,22 +564,13 @@ def _parse_jsonl_for_quality(filepath):
|
|
|
548
564
|
if isinstance(_cwd_val, str) and _cwd_val:
|
|
549
565
|
_rec_cwd = _cwd_val
|
|
550
566
|
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
or "compactMetadata" in record
|
|
559
|
-
)
|
|
560
|
-
is_plan_exit = False
|
|
561
|
-
if rec_type == "assistant":
|
|
562
|
-
for block in record.get("message", {}).get("content", []):
|
|
563
|
-
if isinstance(block, dict) and block.get("type") == "tool_use" and block.get("name") == "ExitPlanMode":
|
|
564
|
-
is_plan_exit = True
|
|
565
|
-
break
|
|
566
|
-
if is_compact or is_plan_exit:
|
|
567
|
+
is_compact = rec_type == "system" and (record.get("subtype") == "compact_boundary" or "compactMetadata" in record)
|
|
568
|
+
if is_compact and not _is_sidechain:
|
|
569
|
+
window_offset = line_offset
|
|
570
|
+
saved_checkpoint = quality_checkpoint.save(
|
|
571
|
+
f, line_offset, _rec, idx=idx, compactions=compactions,
|
|
572
|
+
tool_calls=tool_calls, model=current_model, first_ts=_rec_first_ts,
|
|
573
|
+
last_ts=_rec_last_ts, cwd=_rec_cwd)
|
|
567
574
|
if not _is_sidechain:
|
|
568
575
|
safe_pause = False
|
|
569
576
|
if is_compact:
|
|
@@ -616,7 +623,7 @@ def _parse_jsonl_for_quality(filepath):
|
|
|
616
623
|
# right after a compaction with no further turn, leaving the old
|
|
617
624
|
# value would over-report fill. None falls through to the
|
|
618
625
|
# char-length estimate of whatever follows the boundary.
|
|
619
|
-
context_tokens = None
|
|
626
|
+
context_tokens = _md.get("postTokens") if isinstance(_md.get("postTokens"), (int, float)) else None
|
|
620
627
|
idx += 1
|
|
621
628
|
continue
|
|
622
629
|
|
|
@@ -757,9 +764,10 @@ def _parse_jsonl_for_quality(filepath):
|
|
|
757
764
|
agent_dispatches[-1] = (last[0], last[1], len(result_text))
|
|
758
765
|
|
|
759
766
|
idx += 1
|
|
760
|
-
|
|
767
|
+
if f.tell() - window_offset > _measure_facade.codex_session.MAX_PARSE_FILE_BYTES:
|
|
768
|
+
return quality_checkpoint.ParseFailure("too_large")
|
|
761
769
|
except (PermissionError, OSError):
|
|
762
|
-
return
|
|
770
|
+
return quality_checkpoint.ParseFailure("unreadable")
|
|
763
771
|
|
|
764
772
|
# Close the last open boundary at EOF: its post window is whatever the
|
|
765
773
|
# session produced before ending (possibly still filling -> "observing").
|
|
@@ -767,10 +775,10 @@ def _parse_jsonl_for_quality(filepath):
|
|
|
767
775
|
_measure_facade._finalize_compaction_boundary(_rec["open"], _rec["notices"])
|
|
768
776
|
_rec["boundaries"].append(_rec["open"])
|
|
769
777
|
|
|
770
|
-
if not messages:
|
|
771
|
-
return None
|
|
772
|
-
|
|
773
778
|
return {
|
|
779
|
+
"parse_reason": None if messages else "no_messages",
|
|
780
|
+
"_quality_checkpoint": saved_checkpoint,
|
|
781
|
+
"_parsed_from_offset": parsed_offset,
|
|
774
782
|
"reads": reads,
|
|
775
783
|
"writes": writes,
|
|
776
784
|
"tool_results": tool_results,
|
|
@@ -1149,8 +1157,6 @@ def compute_quality_score(quality_data, session_id=None):
|
|
|
1149
1157
|
"""
|
|
1150
1158
|
_measure_facade = _compat.facade()
|
|
1151
1159
|
total_messages = len(quality_data["messages"])
|
|
1152
|
-
if total_messages == 0:
|
|
1153
|
-
return {"score": 0, "signals": {}, "breakdown": {}}
|
|
1154
1160
|
|
|
1155
1161
|
# 0. Context fill degradation
|
|
1156
1162
|
# Priority: live fill from statusline (real-time) > JSONL context_tokens (previous turn) > char-length estimate
|
|
@@ -1369,11 +1375,7 @@ def compute_quality_score(quality_data, session_id=None):
|
|
|
1369
1375
|
dup_data = _measure_facade.detect_duplicates(quality_data)
|
|
1370
1376
|
dup_score = max(0, min(100, 100 - dup_data["duplicates"] * 10))
|
|
1371
1377
|
|
|
1372
|
-
#
|
|
1373
|
-
# quality weight. Measured post-boundary recovery signals are reported
|
|
1374
|
-
# separately in the recovery panel (see _assess_compaction_recovery);
|
|
1375
|
-
# the count-only "~65/88/95% lost" model was unsupported by the paired
|
|
1376
|
-
# event study and is removed (COMPACTION-QUALITY.md).
|
|
1378
|
+
# Continuity is applied after recovery evidence has been evaluated.
|
|
1377
1379
|
compactions = quality_data["compactions"]
|
|
1378
1380
|
|
|
1379
1381
|
# 5. Decision density: rolling window over last N messages.
|
|
@@ -1435,21 +1437,17 @@ def compute_quality_score(quality_data, session_id=None):
|
|
|
1435
1437
|
)
|
|
1436
1438
|
|
|
1437
1439
|
# Absolute waste tokens signal for ResourceHealth (0-100, higher = less waste)
|
|
1438
|
-
waste_fraction = total_waste / max(
|
|
1440
|
+
waste_fraction = total_waste / max(model_context_window, 1) if model_context_window > 0 else 0
|
|
1439
1441
|
waste_score = max(0, min(100, 100 - waste_fraction * 1000))
|
|
1440
1442
|
signals["absolute_waste_tokens"] = round(waste_score, 1)
|
|
1441
1443
|
|
|
1442
|
-
#
|
|
1444
|
+
# Base resource health and separate diagnostic session efficiency.
|
|
1443
1445
|
resource_health = sum(
|
|
1444
1446
|
signals[k] * _measure_facade._RESOURCE_HEALTH_WEIGHTS[k]
|
|
1445
1447
|
for k in _measure_facade._RESOURCE_HEALTH_WEIGHTS
|
|
1446
1448
|
)
|
|
1447
1449
|
|
|
1448
|
-
#
|
|
1449
|
-
# resource_health, so attribute its deficit by weighted contribution —
|
|
1450
|
-
# weight * (100 - signal) — not by which waste key happens to exist. This
|
|
1451
|
-
# is what the "biggest drag" wording everywhere must reflect: a 70% fill
|
|
1452
|
-
# drags harder than one stale read even when no waste was recorded.
|
|
1450
|
+
# Attribute the base deficit to the weighted fill and waste signals.
|
|
1453
1451
|
_drag_deficit = {
|
|
1454
1452
|
k: _measure_facade._RESOURCE_HEALTH_WEIGHTS[k] * max(0.0, 100.0 - signals[k])
|
|
1455
1453
|
for k in _measure_facade._RESOURCE_HEALTH_WEIGHTS
|
|
@@ -1566,7 +1564,7 @@ def compute_quality_score(quality_data, session_id=None):
|
|
|
1566
1564
|
},
|
|
1567
1565
|
"compactions": {
|
|
1568
1566
|
"count": compactions,
|
|
1569
|
-
"weighted":
|
|
1567
|
+
"weighted": True,
|
|
1570
1568
|
"detail": f"{compactions} compaction(s)" if compactions > 0 else "No compactions",
|
|
1571
1569
|
},
|
|
1572
1570
|
"compaction_recovery": {
|
|
@@ -1638,13 +1636,32 @@ def compute_quality_score(quality_data, session_id=None):
|
|
|
1638
1636
|
"message": "System prompt erosion accelerating, middle content at highest risk",
|
|
1639
1637
|
}
|
|
1640
1638
|
|
|
1639
|
+
multiplier, effective = quality_continuity.continuity(compactions, recovery["evidence"])
|
|
1640
|
+
base_score = resource_health
|
|
1641
|
+
resource_health *= multiplier
|
|
1642
|
+
compaction_drag = base_score * (1 - multiplier)
|
|
1643
|
+
if compaction_drag >= 3 and (not top_drag or compaction_drag > top_drag["points"] * multiplier):
|
|
1644
|
+
top_drag = {"key": "compactions", "label": "compaction continuity prior", "points": round(compaction_drag, 1)}
|
|
1645
|
+
if quality_data.get("unmeasured"):
|
|
1646
|
+
try:
|
|
1647
|
+
previous = float(quality_data.get("last_measured_score", 100))
|
|
1648
|
+
if not _measure_facade.math.isfinite(previous):
|
|
1649
|
+
previous = 100
|
|
1650
|
+
except (TypeError, ValueError):
|
|
1651
|
+
previous = 100
|
|
1652
|
+
resource_health = min(max(0, previous), 100 * multiplier)
|
|
1641
1653
|
rh_rounded = round(resource_health, 1)
|
|
1642
1654
|
se_rounded = round(session_efficiency, 1)
|
|
1643
|
-
rh_grade = _measure_facade.score_to_grade(round(resource_health))
|
|
1655
|
+
rh_grade = _measure_facade.score_to_grade(round(resource_health)) if not quality_data.get("unmeasured") else "?"
|
|
1644
1656
|
se_grade = _measure_facade.score_to_grade(round(session_efficiency))
|
|
1645
1657
|
|
|
1646
1658
|
return {
|
|
1647
1659
|
"score": rh_rounded,
|
|
1660
|
+
"measured": not quality_data.get("unmeasured", False),
|
|
1661
|
+
"continuity": multiplier,
|
|
1662
|
+
"base_score": round(base_score, 1),
|
|
1663
|
+
"effective_compactions": effective,
|
|
1664
|
+
"base_source": "assumed-empty" if total_messages == 0 and quality_data.get("context_tokens") is None and fill_source != "host-live" else fill_source,
|
|
1648
1665
|
"grade": rh_grade,
|
|
1649
1666
|
"score_version": _measure_facade._QUALITY_SCORE_VERSION,
|
|
1650
1667
|
"resource_health": rh_rounded,
|
|
@@ -1870,27 +1887,36 @@ def quality_analyzer(session_id=None, as_json=None):
|
|
|
1870
1887
|
print("[Token Optimizer] No session logs found. Run a Claude Code session first.")
|
|
1871
1888
|
return None
|
|
1872
1889
|
|
|
1873
|
-
|
|
1874
|
-
|
|
1875
|
-
|
|
1876
|
-
|
|
1877
|
-
|
|
1878
|
-
|
|
1879
|
-
|
|
1880
|
-
|
|
1881
|
-
|
|
1882
|
-
|
|
1883
|
-
|
|
1884
|
-
|
|
1890
|
+
try:
|
|
1891
|
+
result = _measure_facade._read_quality_cache(_measure_facade._quality_cache_path_for(filepath)) or {}
|
|
1892
|
+
except (OSError, ValueError, TypeError):
|
|
1893
|
+
result = {}
|
|
1894
|
+
if result.get("score_version") != _measure_facade._QUALITY_SCORE_VERSION or result.get("session_file") != _measure_facade.Path(filepath).name:
|
|
1895
|
+
quality_data = _measure_facade._parse_jsonl_for_quality(filepath)
|
|
1896
|
+
if not quality_data:
|
|
1897
|
+
if as_json:
|
|
1898
|
+
print(_measure_facade.json.dumps({"error": "Session log is unmeasurable.", "reason": getattr(quality_data, "reason", "unreadable")}))
|
|
1899
|
+
else:
|
|
1900
|
+
print("[Token Optimizer] Session log is unmeasurable.")
|
|
1901
|
+
return None
|
|
1902
|
+
result = _measure_facade.compute_quality_score(quality_data)
|
|
1903
|
+
result["session_file"] = _measure_facade.Path(filepath).name
|
|
1904
|
+
result["total_messages"] = len(quality_data["messages"])
|
|
1905
|
+
result["decisions_found"] = len(quality_data["decisions"])
|
|
1906
|
+
if quality_data.get("estimated"):
|
|
1907
|
+
result["estimated"] = True
|
|
1908
|
+
result.pop("_quality_checkpoint", None)
|
|
1885
1909
|
result["runtime"] = _measure_facade.detect_runtime()
|
|
1886
1910
|
result["runtime_label"] = _measure_facade.runtime_name_for_humans()
|
|
1887
|
-
if quality_data.get("estimated"):
|
|
1888
|
-
result["estimated"] = True
|
|
1889
1911
|
|
|
1890
1912
|
if as_json:
|
|
1891
1913
|
print(_measure_facade.json.dumps(result, indent=2))
|
|
1892
1914
|
return result
|
|
1893
1915
|
|
|
1916
|
+
if result.get("measured") is False:
|
|
1917
|
+
print(f"\n Context Quality: ~{result['score']} (unmeasured)\n")
|
|
1918
|
+
return result
|
|
1919
|
+
|
|
1894
1920
|
# Pretty print
|
|
1895
1921
|
score = result["score"]
|
|
1896
1922
|
bd = result["breakdown"]
|
|
@@ -2837,8 +2863,7 @@ def _log_reexpand_debit(session_id, tool_use_id, response_text, tool_name=None,
|
|
|
2837
2863
|
``content_ranges`` carries the (start, end) char offsets of ``response_text``
|
|
2838
2864
|
that were actually returned — a bounded ``expand --lines/--chars/--match``
|
|
2839
2865
|
debits only those tokens, while a full expand (``None``) asks for the whole
|
|
2840
|
-
response.
|
|
2841
|
-
is logged only for characters no earlier re-expansion of that item already
|
|
2866
|
+
response. A debit is logged only for characters no earlier expansion already
|
|
2842
2867
|
covered, so overlapping windows and full-then-bounded reads cannot reverse
|
|
2843
2868
|
more than the item once. Legacy rows without a `` chars `` spec count as full
|
|
2844
2869
|
coverage. The detail records the range set actually debited. Never raises.
|
|
@@ -2863,6 +2888,8 @@ def _log_reexpand_debit(session_id, tool_use_id, response_text, tool_name=None,
|
|
|
2863
2888
|
if not wanted:
|
|
2864
2889
|
return
|
|
2865
2890
|
sid = _measure_facade.sanitize_session_id(session_id) if session_id else None
|
|
2891
|
+
from . import mcp_archive_tripwire
|
|
2892
|
+
if '__' in (tool_name or ''): mcp_archive_tripwire.record_expand(_measure_facade.TRENDS_DB, sid, tool_use_id)
|
|
2866
2893
|
covered = []
|
|
2867
2894
|
if _measure_facade.TRENDS_DB.exists():
|
|
2868
2895
|
conn = _measure_facade._init_trends_db()
|
|
@@ -2878,8 +2905,7 @@ def _log_reexpand_debit(session_id, tool_use_id, response_text, tool_name=None,
|
|
|
2878
2905
|
conn.close()
|
|
2879
2906
|
for (prior_detail,) in rows:
|
|
2880
2907
|
prior = _measure_facade._reexpand_detail_ranges(prior_detail, total_chars)
|
|
2881
|
-
# A legacy row
|
|
2882
|
-
# row covers exactly the ranges it returned.
|
|
2908
|
+
# A legacy row covers everything; bounded rows cover their ranges.
|
|
2883
2909
|
if prior is None:
|
|
2884
2910
|
covered = [(0, total_chars)]
|
|
2885
2911
|
break
|
|
@@ -3238,15 +3264,14 @@ def expand_archived(tool_use_id=None, session_id=None, list_all=None, window_fla
|
|
|
3238
3264
|
print(f"[Error] {exc}", file=_measure_facade.sys.stderr)
|
|
3239
3265
|
_measure_facade.sys.exit(1)
|
|
3240
3266
|
if spec is None:
|
|
3241
|
-
# B6 integrity: re-popping an archived result means it did
|
|
3242
|
-
# NOT stay collapsed, so reverse its tool_archive credit.
|
|
3243
|
-
# Log the re-popped tokens as a debit (netted in
|
|
3244
|
-
# _get_savings_summary), deduped per identical range set.
|
|
3245
3267
|
_measure_facade._log_reexpand_debit(sd.name, tool_use_id, response,
|
|
3246
3268
|
data.get("tool_name") or "")
|
|
3247
3269
|
# No added newline: expand returns the stored text as stored.
|
|
3248
3270
|
_measure_facade.sys.stdout.write(response)
|
|
3249
3271
|
_measure_facade.sys.stdout.flush()
|
|
3272
|
+
if data.get("tool_name") == "Bash" and data.get("truncated") is False:
|
|
3273
|
+
from . import savings_story
|
|
3274
|
+
savings_story.record_full_bash_fetch(_measure_facade, sd.name, tool_use_id, response)
|
|
3250
3275
|
return
|
|
3251
3276
|
out, ranges = _measure_facade._expand_bounded(data, response, tool_use_id,
|
|
3252
3277
|
sd.name, spec)
|
|
@@ -3912,7 +3937,7 @@ def maybe_sweep_stale_leases(directory=None):
|
|
|
3912
3937
|
if not _measure_facade._qlease_sweep_due():
|
|
3913
3938
|
return 0
|
|
3914
3939
|
target = _measure_facade.Path(directory) if directory is not None else _measure_facade.QUALITY_CACHE_DIR
|
|
3915
|
-
removed = _measure_facade._sweep_stale_leases(target)
|
|
3940
|
+
removed = _measure_facade._sweep_stale_leases(target) + lease_candidate_cleanup.sweep(_measure_facade.SNAPSHOT_DIR)
|
|
3916
3941
|
# Stamp AFTER a successful run so a mid-sweep crash retries next session.
|
|
3917
3942
|
try:
|
|
3918
3943
|
_measure_facade._QLEASE_SWEEP_MARKER.parent.mkdir(parents=True, exist_ok=True)
|
|
@@ -4690,37 +4715,19 @@ def _recent_compact_boundary(path, within_s=None, now=None):
|
|
|
4690
4715
|
|
|
4691
4716
|
|
|
4692
4717
|
def _settled_compactions(parsed, prev_result, post_compact, now=None):
|
|
4693
|
-
"""
|
|
4694
|
-
|
|
4695
|
-
Claude Code appends the compact_boundary row to the transcript after the
|
|
4696
|
-
PostCompact hooks run, so the PostCompact refresh parses a transcript that
|
|
4697
|
-
does not show the compaction yet. That refresh therefore counts one more
|
|
4698
|
-
than before when the parse has not caught up, once per compaction (a
|
|
4699
|
-
second PostCompact within a minute is the same one). A later parse that
|
|
4700
|
-
sees the boundary agrees with that count rather than adding to it. The
|
|
4701
|
-
caller passes post_compact=False when the boundary is already in the
|
|
4702
|
-
transcript. Two real compactions inside one minute read as one until the
|
|
4703
|
-
next parse sees both boundaries, which then corrects the count.
|
|
4704
|
-
"""
|
|
4718
|
+
"""Allow a short pending hook bump, then trust the transcript again."""
|
|
4705
4719
|
_measure_facade = _compat.facade()
|
|
4706
4720
|
try:
|
|
4707
4721
|
prev = max(0, int((prev_result or {}).get("compactions", 0) or 0))
|
|
4708
|
-
except (TypeError, ValueError, OverflowError):
|
|
4709
|
-
prev = 0
|
|
4710
|
-
try:
|
|
4711
4722
|
parsed = max(0, int(parsed or 0))
|
|
4723
|
+
last = float((prev_result or {}).get("_compact_bumped_at") or 0)
|
|
4712
4724
|
except (TypeError, ValueError, OverflowError):
|
|
4713
|
-
|
|
4714
|
-
|
|
4715
|
-
|
|
4716
|
-
|
|
4717
|
-
|
|
4718
|
-
|
|
4719
|
-
except (TypeError, ValueError, OverflowError):
|
|
4720
|
-
last = 0.0
|
|
4721
|
-
if now - last > _measure_facade._COMPACT_BUMP_WINDOW_S:
|
|
4722
|
-
count = prev + 1
|
|
4723
|
-
return count
|
|
4725
|
+
return 0
|
|
4726
|
+
now = _measure_facade.time.time() if now is None else now
|
|
4727
|
+
pending = prev > parsed and 0 <= now - last < _measure_facade._COMPACT_BUMP_WINDOW_S
|
|
4728
|
+
if pending:
|
|
4729
|
+
return prev
|
|
4730
|
+
return parsed + 1 if post_compact else parsed
|
|
4724
4731
|
|
|
4725
4732
|
|
|
4726
4733
|
def _quality_scores_comparable(prev_result, result):
|
|
@@ -5563,64 +5570,38 @@ def quality_cache(throttle_seconds=None, warn_threshold=None, quiet=None, sessio
|
|
|
5563
5570
|
|
|
5564
5571
|
try:
|
|
5565
5572
|
# Run quality analysis
|
|
5566
|
-
|
|
5573
|
+
try:
|
|
5574
|
+
prev_result = _measure_facade._read_quality_cache(cache_path) or {} if cache_path.exists() else {}
|
|
5575
|
+
except Exception:
|
|
5576
|
+
prev_result = {}
|
|
5577
|
+
checkpoint = prev_result.get("_quality_checkpoint")
|
|
5578
|
+
quality_data = (_measure_facade._parse_jsonl_for_quality(filepath, checkpoint)
|
|
5579
|
+
if checkpoint else _measure_facade._parse_jsonl_for_quality(filepath))
|
|
5580
|
+
parsed_compactions = 0
|
|
5567
5581
|
if not quality_data:
|
|
5568
|
-
# New/empty session - write a clean score to cache so stale score doesn't persist.
|
|
5569
|
-
# A transcript the parser gives up on (very large) is not a new session: keep the
|
|
5570
|
-
# compaction count it already had, so "never decreases" holds there too.
|
|
5571
5582
|
try:
|
|
5572
|
-
|
|
5573
|
-
|
|
5574
|
-
_prev_empty = {}
|
|
5575
|
-
result = {
|
|
5576
|
-
"score": 100,
|
|
5577
|
-
"grade": "S",
|
|
5578
|
-
"score_version": _measure_facade._QUALITY_SCORE_VERSION,
|
|
5579
|
-
"signals": {},
|
|
5580
|
-
"breakdown": {},
|
|
5581
|
-
"total_messages": 0,
|
|
5582
|
-
"decisions_found": 0,
|
|
5583
|
-
"compactions": _measure_facade._settled_compactions(
|
|
5584
|
-
0, _prev_empty or {}, post_compact and not _measure_facade._recent_compact_boundary(filepath)),
|
|
5585
|
-
"recovery_status": None,
|
|
5586
|
-
"recovery_score": None,
|
|
5587
|
-
"recovery_evidence": [],
|
|
5588
|
-
"turns": 0,
|
|
5589
|
-
"timestamp": _measure_facade.datetime.now(_measure_facade.timezone.utc).isoformat(),
|
|
5590
|
-
"session_file": _measure_facade.Path(filepath).name,
|
|
5591
|
-
"model_context_window": _measure_facade.detect_context_window()[0],
|
|
5592
|
-
}
|
|
5593
|
-
# Same bump bookkeeping as the full path: one count per compaction.
|
|
5594
|
-
if (_prev_empty or {}).get("_compact_bumped_at"):
|
|
5595
|
-
result["_compact_bumped_at"] = _prev_empty["_compact_bumped_at"]
|
|
5596
|
-
# Keep the nudge and warning state too: dropping it re-arms nudges
|
|
5597
|
-
# that already fired once the transcript parses again.
|
|
5598
|
-
for carry_key in _measure_facade._CARRY_KEYS:
|
|
5599
|
-
if carry_key in (_prev_empty or {}):
|
|
5600
|
-
result[carry_key] = _prev_empty[carry_key]
|
|
5601
|
-
# A legacy/v1 nudge baseline must not seed v2 comparisons.
|
|
5602
|
-
if (_prev_empty or {}).get("score_version") != _measure_facade._QUALITY_SCORE_VERSION:
|
|
5603
|
-
result.pop("_nudge_previous_score", None)
|
|
5604
|
-
try:
|
|
5605
|
-
_prev_n = int((_prev_empty or {}).get("compactions", 0) or 0)
|
|
5583
|
+
count = max(0, int(prev_result.get("compactions", 0) or 0))
|
|
5584
|
+
bumped_at = float(prev_result.get("_compact_bumped_at", 0) or 0)
|
|
5606
5585
|
except (TypeError, ValueError, OverflowError):
|
|
5607
|
-
|
|
5608
|
-
if post_compact and
|
|
5609
|
-
|
|
5610
|
-
|
|
5611
|
-
|
|
5612
|
-
|
|
5613
|
-
|
|
5614
|
-
|
|
5615
|
-
|
|
5616
|
-
|
|
5617
|
-
|
|
5618
|
-
|
|
5619
|
-
|
|
5620
|
-
|
|
5621
|
-
|
|
5586
|
+
count, bumped_at = 0, 0
|
|
5587
|
+
if post_compact and _measure_facade.time.time() - bumped_at > _measure_facade._COMPACT_BUMP_WINDOW_S:
|
|
5588
|
+
count += 1
|
|
5589
|
+
quality_data = {"messages": [], "decisions": [], "reads": [], "writes": [],
|
|
5590
|
+
"tool_results": [], "tool_result_meta": [], "system_reminders": [],
|
|
5591
|
+
"agent_dispatches": [], "total_entries": 0, "tool_calls": 0,
|
|
5592
|
+
"compactions": count, "unmeasured": True,
|
|
5593
|
+
"last_measured_score": prev_result.get("last_measured_score", prev_result.get("score", 100)),
|
|
5594
|
+
"parse_reason": getattr(quality_data, "reason", "unreadable")}
|
|
5595
|
+
else:
|
|
5596
|
+
parsed_compactions = quality_data["compactions"]
|
|
5597
|
+
quality_data["compactions"] = _measure_facade._settled_compactions(
|
|
5598
|
+
quality_data["compactions"], prev_result,
|
|
5599
|
+
post_compact and not _measure_facade._recent_compact_boundary(filepath))
|
|
5622
5600
|
_session_id = _measure_facade.Path(cache_path).stem.replace("quality-cache-", "", 1) if cache_path else None
|
|
5623
5601
|
result = _measure_facade.compute_quality_score(quality_data, session_id=_session_id)
|
|
5602
|
+
result["_quality_checkpoint"] = quality_data.get("_quality_checkpoint")
|
|
5603
|
+
result["parse_reason"] = quality_data.get("parse_reason")
|
|
5604
|
+
result["last_measured_score"] = (result["score"] if result["measured"] else quality_data["last_measured_score"])
|
|
5624
5605
|
for carry_key in _measure_facade._CARRY_KEYS:
|
|
5625
5606
|
if carry_key in prev_result and carry_key not in result:
|
|
5626
5607
|
result[carry_key] = prev_result[carry_key]
|
|
@@ -5635,14 +5616,11 @@ def quality_cache(throttle_seconds=None, warn_threshold=None, quiet=None, sessio
|
|
|
5635
5616
|
# accurate. Routing the statusline through the same dedup would add
|
|
5636
5617
|
# latency to every prompt for a number the user glances at.
|
|
5637
5618
|
result["decisions_found"] = len(quality_data["decisions"])
|
|
5638
|
-
result["compactions"] = _measure_facade._settled_compactions(
|
|
5639
|
-
quality_data["compactions"], prev_result,
|
|
5640
|
-
post_compact and not _measure_facade._recent_compact_boundary(filepath))
|
|
5641
5619
|
try:
|
|
5642
5620
|
_prev_compactions = int(prev_result.get("compactions", 0) or 0)
|
|
5643
5621
|
except (TypeError, ValueError, OverflowError):
|
|
5644
5622
|
_prev_compactions = 0
|
|
5645
|
-
if post_compact and result["compactions"] > max(int(
|
|
5623
|
+
if post_compact and result["compactions"] > max(int(parsed_compactions or 0), _prev_compactions):
|
|
5646
5624
|
result["_compact_bumped_at"] = _measure_facade.time.time()
|
|
5647
5625
|
elif prev_result.get("_compact_bumped_at"):
|
|
5648
5626
|
result["_compact_bumped_at"] = prev_result["_compact_bumped_at"]
|
|
@@ -5666,50 +5644,16 @@ def quality_cache(throttle_seconds=None, warn_threshold=None, quiet=None, sessio
|
|
|
5666
5644
|
)
|
|
5667
5645
|
result["context_window_contradicted"] = bool(cfd.get("window_contradicted"))
|
|
5668
5646
|
|
|
5669
|
-
|
|
5670
|
-
# Fill_pct fluctuates between measurements (context adds/removes, compaction).
|
|
5671
|
-
# Allow recovery but dampen: drops are immediate, recovery moves 30% toward
|
|
5672
|
-
# the new value per measurement to prevent wild upward swings.
|
|
5673
|
-
# Only within the same score_version: a v1 score mixed in the count-only
|
|
5674
|
-
# compaction penalty, so importing its deficit (or its nudge baseline)
|
|
5675
|
-
# would silently compare apples to oranges (COMPACTION-QUALITY.md).
|
|
5676
|
-
if _measure_facade._quality_scores_comparable(prev_result, result):
|
|
5677
|
-
prev_rh = prev_result.get("resource_health")
|
|
5678
|
-
current_rh = result.get("resource_health")
|
|
5679
|
-
if prev_rh is not None and current_rh is not None:
|
|
5680
|
-
if current_rh >= prev_rh:
|
|
5681
|
-
result["resource_health"] = round(prev_rh + (current_rh - prev_rh) * 0.3, 1)
|
|
5682
|
-
result["score"] = result["resource_health"]
|
|
5683
|
-
result["grade"] = _measure_facade.score_to_grade(round(result["resource_health"]))
|
|
5684
|
-
result["resource_health_grade"] = result["grade"]
|
|
5685
|
-
else:
|
|
5686
|
-
# Version boundary or legacy unversioned cache: reseed the nudge
|
|
5687
|
-
# baseline instead of comparing across score schemes.
|
|
5647
|
+
if not _measure_facade._quality_scores_comparable(prev_result, result):
|
|
5688
5648
|
result.pop("_nudge_previous_score", None)
|
|
5689
5649
|
|
|
5690
|
-
#
|
|
5691
|
-
|
|
5692
|
-
result["
|
|
5693
|
-
|
|
5694
|
-
|
|
5695
|
-
|
|
5696
|
-
|
|
5697
|
-
try:
|
|
5698
|
-
total_input_all = 0
|
|
5699
|
-
total_cache_read = 0
|
|
5700
|
-
with open(filepath, "r", encoding="utf-8", errors="replace") as f:
|
|
5701
|
-
for line in f:
|
|
5702
|
-
try:
|
|
5703
|
-
rec = _measure_facade.json.loads(line)
|
|
5704
|
-
usage = rec.get("message", {}).get("usage", {}) if rec.get("type") == "assistant" else {}
|
|
5705
|
-
if usage:
|
|
5706
|
-
total_input_all += usage.get("input_tokens", 0) + usage.get("cache_read_input_tokens", 0) + usage.get("cache_creation_input_tokens", 0)
|
|
5707
|
-
total_cache_read += usage.get("cache_read_input_tokens", 0)
|
|
5708
|
-
except (_measure_facade.json.JSONDecodeError, AttributeError):
|
|
5709
|
-
continue
|
|
5710
|
-
result["cache_hit_rate"] = round(total_cache_read / total_input_all, 3) if total_input_all > 0 else 0
|
|
5711
|
-
except (OSError, ZeroDivisionError):
|
|
5712
|
-
result["cache_hit_rate"] = 0
|
|
5650
|
+
# Reuse cumulative telemetry and scan only appended records.
|
|
5651
|
+
telemetry = quality_checkpoint.status_telemetry(filepath, prev_result.get("_status_telemetry"))
|
|
5652
|
+
result["_status_telemetry"] = telemetry
|
|
5653
|
+
result["session_start_ts"] = telemetry.get("started")
|
|
5654
|
+
result["active_agents"] = telemetry.get("agents", [])
|
|
5655
|
+
total_input = telemetry.get("total_input", 0)
|
|
5656
|
+
result["cache_hit_rate"] = round(telemetry.get("cache_read", 0) / total_input, 3) if total_input else 0
|
|
5713
5657
|
|
|
5714
5658
|
if not _measure_facade._write_quality_cache(cache_path, result):
|
|
5715
5659
|
return None
|
|
@@ -5744,9 +5688,9 @@ def quality_cache(throttle_seconds=None, warn_threshold=None, quiet=None, sessio
|
|
|
5744
5688
|
# Fresh-session nudge takes precedence: when a session is long AND degraded,
|
|
5745
5689
|
# "start fresh (context is preserved)" is the stronger remedy than /compact, and
|
|
5746
5690
|
# firing both would be noise. Only fall back to the /compact nudge if it didn't fire.
|
|
5747
|
-
fresh_msg = _measure_facade._maybe_fresh_session_nudge(result, cache_path, quality_data)
|
|
5691
|
+
fresh_msg = _measure_facade._maybe_fresh_session_nudge(result, cache_path, quality_data) if result["measured"] else None
|
|
5748
5692
|
remedy_fired = bool(fresh_msg)
|
|
5749
|
-
if not fresh_msg:
|
|
5693
|
+
if not fresh_msg and result["measured"]:
|
|
5750
5694
|
nudge_msg = _measure_facade._maybe_nudge(result, cache_path, quality_data)
|
|
5751
5695
|
if nudge_msg:
|
|
5752
5696
|
system_messages.append(nudge_msg)
|
|
@@ -5757,8 +5701,8 @@ def quality_cache(throttle_seconds=None, warn_threshold=None, quiet=None, sessio
|
|
|
5757
5701
|
# Context-size advisory: eligibility, not an instruction -- at most
|
|
5758
5702
|
# once per session, suppressed while a stronger remedy already fired
|
|
5759
5703
|
# (suppression does not consume the once-per-session slot).
|
|
5760
|
-
advisory_msg = _measure_facade._maybe_context_size_advisory(
|
|
5761
|
-
result, cache_path, quality_data, suppressed=remedy_fired)
|
|
5704
|
+
advisory_msg = (_measure_facade._maybe_context_size_advisory(
|
|
5705
|
+
result, cache_path, quality_data, suppressed=remedy_fired) if result["measured"] else None)
|
|
5762
5706
|
if advisory_msg:
|
|
5763
5707
|
system_messages.append(advisory_msg)
|
|
5764
5708
|
# Persist nudge/loop/fresh state (the once-per-session _fresh_nudge_fired flag
|
|
@@ -5804,7 +5748,7 @@ def quality_cache(throttle_seconds=None, warn_threshold=None, quiet=None, sessio
|
|
|
5804
5748
|
# actually installs: `quality-cache --warn --quiet`). Gated by
|
|
5805
5749
|
# _maybe_quality_warn so it no longer re-prints on every prompt while a
|
|
5806
5750
|
# session sits in one quality band; see that function for the rationale.
|
|
5807
|
-
if warn and _measure_facade._maybe_quality_warn(result, warn_threshold):
|
|
5751
|
+
if warn and result["measured"] and _measure_facade._maybe_quality_warn(result, warn_threshold):
|
|
5808
5752
|
_emit_warn = True
|
|
5809
5753
|
try:
|
|
5810
5754
|
from context_pressure import should_inject, get_pressure_level, log_suppression
|
|
@@ -5878,8 +5822,8 @@ def quality_cache(throttle_seconds=None, warn_threshold=None, quiet=None, sessio
|
|
|
5878
5822
|
original_text=" " * (measured_tokens_recovered * 4),
|
|
5879
5823
|
compressed_text=f"nudge_followthrough:fill={nudge_fill}->{current_fill}",
|
|
5880
5824
|
session_id=ft_sid,
|
|
5881
|
-
detail=f"
|
|
5882
|
-
verified=True,
|
|
5825
|
+
detail=f"estimated_recovery: fill {nudge_fill}%->{current_fill}% = {measured_tokens_recovered} tokens on {context_size} context",
|
|
5826
|
+
verified=True, tier="estimated",
|
|
5883
5827
|
)
|
|
5884
5828
|
except Exception:
|
|
5885
5829
|
pass
|
|
@@ -6692,14 +6636,10 @@ def _format_window_note(cached):
|
|
|
6692
6636
|
|
|
6693
6637
|
|
|
6694
6638
|
def _verbosity_measured_savings(baseline_avg, post_nudge_outputs):
|
|
6695
|
-
"""
|
|
6696
|
-
|
|
6697
|
-
|
|
6698
|
-
|
|
6699
|
-
saving. ``baseline_avg`` is the session's pre-nudge average output tokens
|
|
6700
|
-
(recorded in the nudge event detail). ``post_nudge_outputs`` is the list of
|
|
6701
|
-
output_tokens for the turns AFTER the nudge. Returns 0 when there is no
|
|
6702
|
-
post-nudge data yet (no counterfactual to measure against).
|
|
6639
|
+
"""Estimated positive output reduction against the session's prior mean.
|
|
6640
|
+
|
|
6641
|
+
This before/after comparison has no control and is not a causal measure.
|
|
6642
|
+
Signed changes are retained separately in the calibration event detail.
|
|
6703
6643
|
"""
|
|
6704
6644
|
_measure_facade = _compat.facade()
|
|
6705
6645
|
try:
|
|
@@ -6767,7 +6707,11 @@ def _transcript_request_outputs(filepath):
|
|
|
6767
6707
|
|
|
6768
6708
|
|
|
6769
6709
|
def _calibrate_prior_verbosity_nudges(session_id, filepath):
|
|
6770
|
-
"""Book the
|
|
6710
|
+
"""Book the before/after output change of a prior verbosity nudge (R5, D1).
|
|
6711
|
+
|
|
6712
|
+
The booked row is an uncontrolled comparison and stays out of the realized
|
|
6713
|
+
total; the estimated tier credits only the net-of-control figure
|
|
6714
|
+
(``output_reread.summary_pool``). The signed change is kept in the detail.
|
|
6771
6715
|
|
|
6772
6716
|
The nudge event itself books 0 -- there is no counterfactual at fire time.
|
|
6773
6717
|
This pass runs on a later UserPromptSubmit turn: it finds the most recent
|
|
@@ -6854,7 +6798,7 @@ def _calibrate_prior_verbosity_nudges(session_id, filepath):
|
|
|
6854
6798
|
measured,
|
|
6855
6799
|
session_id=sid,
|
|
6856
6800
|
detail=(f"calibrates_ts={src_ts} post_turns={len(post_outputs)} "
|
|
6857
|
-
f"pre_avg_out={pre_avg}"),
|
|
6801
|
+
f"pre_avg_out={pre_avg} signed_delta={int(pre_avg * len(post_outputs) - sum(post_outputs))}"),
|
|
6858
6802
|
)
|
|
6859
6803
|
return measured
|
|
6860
6804
|
except Exception:
|