@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,34 +1,17 @@
|
|
|
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, checkpoint_direction, checkpoint_retention, upgrade_drain_control
|
|
4
4
|
|
|
5
5
|
|
|
6
6
|
def _iter_tail_lines(filepath, tail_lines, chunk_size=None):
|
|
7
|
-
"""
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
sees the same records as a whole-file pass: the window extends backwards
|
|
12
|
-
from EOF until it holds tail_lines lines that pass the caller's own
|
|
13
|
-
filters (size cap + json.loads), or the file start is reached. A large
|
|
14
|
-
transcript then costs a small window read instead of reading and parsing
|
|
15
|
-
every byte. The window grows geometrically, so even a transcript whose
|
|
16
|
-
tail needs most of the file costs about one extra pass, not a rescan per
|
|
17
|
-
chunk.
|
|
18
|
-
|
|
19
|
-
Two equivalence details:
|
|
20
|
-
|
|
21
|
-
- Lines come from ``StringIO(text, newline=None)``, which iterates with
|
|
22
|
-
the same universal-newline semantics as text-mode file iteration, so
|
|
23
|
-
the caller's ``len(line)`` cap and ``json.loads`` see identical
|
|
24
|
-
strings.
|
|
25
|
-
- A window starting mid-file can cut inside a line (and inside a
|
|
26
|
-
multi-byte UTF-8 sequence, where ``errors="replace"`` would diverge
|
|
27
|
-
from a whole-file decode), so its first line is dropped and the window
|
|
28
|
-
must hold tail_lines valid records without it. At byte 0 the window is
|
|
29
|
-
the whole file and nothing is dropped.
|
|
7
|
+
"""Read a suffix window for small logs, or the indexed tail for large logs.
|
|
8
|
+
|
|
9
|
+
Small-log windows retain universal-newline semantics and discard a leading
|
|
10
|
+
partial line. Indexed tails never grow a raw buffer to the source-file size.
|
|
30
11
|
"""
|
|
31
12
|
_measure_facade = _compat.facade()
|
|
13
|
+
if _measure_facade.Path(filepath).stat().st_size > transcript_stream.LARGE_BYTES:
|
|
14
|
+
return transcript_stream.tail_lines(filepath, tail_lines)
|
|
32
15
|
with open(filepath, "rb") as f:
|
|
33
16
|
f.seek(0, _measure_facade.os.SEEK_END)
|
|
34
17
|
pos = f.tell()
|
|
@@ -93,15 +76,7 @@ def _tool_call_target(name, inp):
|
|
|
93
76
|
|
|
94
77
|
|
|
95
78
|
def _first_task_user_message(filepath):
|
|
96
|
-
"""
|
|
97
|
-
transcript head.
|
|
98
|
-
|
|
99
|
-
The tail window used for state extraction loses the objective on long
|
|
100
|
-
sessions, and the objective is definitionally the first user message — so
|
|
101
|
-
it gets its own bounded head pass (<=400 lines / <=8MB, early exit). The
|
|
102
|
-
caller redacts the returned text like every other ingested string.
|
|
103
|
-
Returns (None, None) when absent or unreadable. Never raises.
|
|
104
|
-
"""
|
|
79
|
+
"""Return the first user task and its source ID."""
|
|
105
80
|
_measure_facade = _compat.facade()
|
|
106
81
|
try:
|
|
107
82
|
total = 0
|
|
@@ -116,7 +91,7 @@ def _first_task_user_message(filepath):
|
|
|
116
91
|
rec = _measure_facade.json.loads(line)
|
|
117
92
|
except _measure_facade.json.JSONDecodeError:
|
|
118
93
|
continue
|
|
119
|
-
if not isinstance(rec, dict) or rec.get("type") != "user":
|
|
94
|
+
if not isinstance(rec, dict) or rec.get("type") != "user" or rec.get("isSidechain"):
|
|
120
95
|
continue
|
|
121
96
|
text = _measure_facade._task_user_text(rec).strip()
|
|
122
97
|
if text:
|
|
@@ -178,11 +153,6 @@ def _extract_session_state(filepath, tail_lines=None):
|
|
|
178
153
|
|
|
179
154
|
# Use deque to only keep the tail in memory (avoids loading entire file)
|
|
180
155
|
records = _measure_facade.deque(maxlen=tail_lines)
|
|
181
|
-
try:
|
|
182
|
-
if _measure_facade.os.stat(filepath).st_size > _measure_facade.codex_session.MAX_PARSE_FILE_BYTES:
|
|
183
|
-
return None
|
|
184
|
-
except OSError:
|
|
185
|
-
return None
|
|
186
156
|
try:
|
|
187
157
|
for line in _measure_facade._iter_tail_lines(filepath, tail_lines):
|
|
188
158
|
if len(line) > _measure_facade.codex_session.MAX_JSONL_LINE_CHARS:
|
|
@@ -204,7 +174,7 @@ def _extract_session_state(filepath, tail_lines=None):
|
|
|
204
174
|
file_count = 0
|
|
205
175
|
|
|
206
176
|
for record in tail:
|
|
207
|
-
if not isinstance(record, dict):
|
|
177
|
+
if not isinstance(record, dict) or record.get("isSidechain"):
|
|
208
178
|
continue
|
|
209
179
|
rec_type = record.get("type")
|
|
210
180
|
|
|
@@ -339,16 +309,11 @@ def _extract_session_state(filepath, tail_lines=None):
|
|
|
339
309
|
error_context.append((recent_errors[-1][:200], assistant_text[:200].strip()))
|
|
340
310
|
recent_errors = []
|
|
341
311
|
|
|
342
|
-
# Objective head-scan: the FIRST user message, which the tail window can
|
|
343
|
-
# lose on long sessions. Redacted like every other ingested string.
|
|
344
312
|
_obj_text, _obj_id = _measure_facade._first_task_user_message(filepath)
|
|
345
|
-
objective = None
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
"source": {"kind": "user_message",
|
|
350
|
-
"id": str(_obj_id) if _obj_id else None},
|
|
351
|
-
}
|
|
313
|
+
objective = {"text": _ingest_redact(_obj_text), "source": {"kind": "user_message", "id": _obj_id}} if _obj_text else None
|
|
314
|
+
_, direction, constraints = checkpoint_direction.scan(
|
|
315
|
+
filepath, _measure_facade._task_user_text, _ingest_redact,
|
|
316
|
+
_measure_facade.checkpoint_state, _measure_facade.codex_session.MAX_JSONL_LINE_CHARS)
|
|
352
317
|
|
|
353
318
|
task_state = _measure_facade.checkpoint_state.build_task_state(
|
|
354
319
|
user_texts=user_texts,
|
|
@@ -360,6 +325,9 @@ def _extract_session_state(filepath, tail_lines=None):
|
|
|
360
325
|
objective=objective,
|
|
361
326
|
)
|
|
362
327
|
|
|
328
|
+
task_state["current_direction"] = direction
|
|
329
|
+
task_state["user_constraints"] = constraints
|
|
330
|
+
|
|
363
331
|
return {
|
|
364
332
|
"active_files": active_files[-_measure_facade._CHECKPOINT_MAX_FILES:],
|
|
365
333
|
"recent_reads": recent_reads[-_measure_facade._CHECKPOINT_MAX_FILES:],
|
|
@@ -616,12 +584,14 @@ def _checkpoint_sections(state, quality_summary=None, archive_entries=None):
|
|
|
616
584
|
ts_task = {}
|
|
617
585
|
sections = []
|
|
618
586
|
|
|
619
|
-
|
|
587
|
+
direction = ts_task.get("current_direction") or []
|
|
588
|
+
if direction:
|
|
589
|
+
sections.append(_measure_facade._checkpoint_section(
|
|
590
|
+
"Current direction", ["## Current direction"] + ["- " + item["text"] for item in direction], "hard", None))
|
|
620
591
|
obj = ts_task.get("objective") or {}
|
|
621
592
|
if isinstance(obj, dict) and obj.get("text"):
|
|
622
593
|
sections.append(_measure_facade._checkpoint_section(
|
|
623
|
-
"
|
|
624
|
-
_measure_facade.checkpoint_state.OBJECTIVE_MAX_CHARS + len("## Objective\n")))
|
|
594
|
+
"Session began", ["## Session began", "Session began with: " + str(obj["text"])[:200]], "optional", None, 999))
|
|
625
595
|
constraints = ts_task.get("user_constraints") or []
|
|
626
596
|
con_lines = ["## User Constraints"] + [
|
|
627
597
|
f"- {c.get('text', '')}" for c in constraints
|
|
@@ -643,7 +613,7 @@ def _checkpoint_sections(state, quality_summary=None, archive_entries=None):
|
|
|
643
613
|
"hard", 700))
|
|
644
614
|
|
|
645
615
|
# --- keep: structured state, shrunk only under real pressure ---
|
|
646
|
-
if state["current_step"]["last_user"]:
|
|
616
|
+
if state["current_step"]["last_user"] and not direction:
|
|
647
617
|
sections.append(_measure_facade._checkpoint_section(
|
|
648
618
|
"Active Task",
|
|
649
619
|
["## Active Task", state["current_step"]["last_user"]],
|
|
@@ -797,7 +767,7 @@ def compact_capture(transcript_path=None, session_id=None, trigger=None, cwd=Non
|
|
|
797
767
|
# stale. The offset suffix keeps it unambiguous; selection/age still use mtime.
|
|
798
768
|
now = _measure_facade.datetime.now().astimezone()
|
|
799
769
|
ts = now.strftime("%Y-%m-%dT%H:%M:%S%z")
|
|
800
|
-
ts_file = now.strftime("%Y%m%d-%H%M%S")
|
|
770
|
+
ts_file = now.strftime("%Y%m%d-%H%M%S") + "-u" + _measure_facade.os.urandom(8).hex()
|
|
801
771
|
|
|
802
772
|
if _trusted_transcript is not None:
|
|
803
773
|
filepath = _measure_facade.Path(_trusted_transcript)
|
|
@@ -846,8 +816,6 @@ def compact_capture(transcript_path=None, session_id=None, trigger=None, cwd=Non
|
|
|
846
816
|
return None
|
|
847
817
|
return str(checkpoint_path)
|
|
848
818
|
|
|
849
|
-
# Parse session state. The extractor redacts as it reads; a configured-but-
|
|
850
|
-
# broken custom pattern file makes it raise, and then nothing is written.
|
|
851
819
|
try:
|
|
852
820
|
from credential_patterns import RedactionConfigError as _ExtractCfgErr
|
|
853
821
|
except Exception:
|
|
@@ -858,6 +826,12 @@ def compact_capture(transcript_path=None, session_id=None, trigger=None, cwd=Non
|
|
|
858
826
|
return None
|
|
859
827
|
if not state:
|
|
860
828
|
return None
|
|
829
|
+
_sid = _measure_facade.sanitize_session_id(session_id or filepath.stem)
|
|
830
|
+
_cached = checkpoint_direction.previous_state(_measure_facade.CHECKPOINT_DIR, _sid)
|
|
831
|
+
_task = state.get("task_state") or {}
|
|
832
|
+
_task["user_constraints"] = checkpoint_direction.merge_constraints(_task.get("user_constraints"), _cached.get("user_constraints"))
|
|
833
|
+
if not _task.get("current_direction"):
|
|
834
|
+
_task["current_direction"] = _cached.get("current_direction") or []
|
|
861
835
|
|
|
862
836
|
# Redact credentials from the whole checkpoint state (SEC-004). One
|
|
863
837
|
# recursive pass over every string — including dict keys, tuples, and any
|
|
@@ -1005,12 +979,6 @@ def compact_capture(transcript_path=None, session_id=None, trigger=None, cwd=Non
|
|
|
1005
979
|
return None
|
|
1006
980
|
|
|
1007
981
|
# JSON sidecar: structured companion for precise recovery. The MD is for
|
|
1008
|
-
# Claude to read cold; the JSON lets Claude re-hydrate exact fields on
|
|
1009
|
-
# demand. version 2 adds the versioned task_state (objective, constraints,
|
|
1010
|
-
# requirements, verified facts vs assumptions, checks, dead ends, next
|
|
1011
|
-
# action, done condition, archive pointers) — every field source-backed or
|
|
1012
|
-
# explicitly listed in unknown_fields. All v1 keys are unchanged so older
|
|
1013
|
-
# readers keep working.
|
|
1014
982
|
try:
|
|
1015
983
|
sidecar = {
|
|
1016
984
|
"version": 2,
|
|
@@ -1859,24 +1827,24 @@ def compact_restore(session_id=None, cwd=None, is_compact=None, new_session_only
|
|
|
1859
1827
|
# CHECKPOINT_RELEVANCE_THRESHOLD. A home-dir / generic cwd yields no
|
|
1860
1828
|
# opening context -> no score -> no pointer. The cross-session label,
|
|
1861
1829
|
# the "NOT your own prior work" framing, the filename-format warning path,
|
|
1862
|
-
# the
|
|
1830
|
+
# the 24-hour age gate, and own-session exclusion are preserved.
|
|
1863
1831
|
try:
|
|
1864
1832
|
cur = _measure_facade.Path(cwd) if cwd else _measure_facade.Path.cwd()
|
|
1865
1833
|
except Exception:
|
|
1866
1834
|
cur = None
|
|
1867
|
-
# Filter candidates once: own-session excluded,
|
|
1835
|
+
# Filter candidates once: own-session excluded, 24-hour age gate applied.
|
|
1868
1836
|
# The age gate and own-session exclusion are evaluated here (before
|
|
1869
1837
|
# selection) so a stale or own-session checkpoint can never be the
|
|
1870
1838
|
# relevance winner either.
|
|
1871
1839
|
candidates = []
|
|
1872
1840
|
for cp in checkpoints:
|
|
1873
|
-
if sid_safe and sid_safe
|
|
1841
|
+
if sid_safe and sid_safe == _measure_facade._checkpoint_session(cp["filename"]):
|
|
1874
1842
|
continue
|
|
1875
1843
|
try:
|
|
1876
1844
|
age_seconds = (_measure_facade.datetime.now() - cp["created"]).total_seconds()
|
|
1877
1845
|
except Exception:
|
|
1878
1846
|
continue
|
|
1879
|
-
if age_seconds >
|
|
1847
|
+
if age_seconds > 86400:
|
|
1880
1848
|
continue
|
|
1881
1849
|
candidates.append(cp)
|
|
1882
1850
|
if not candidates:
|
|
@@ -1968,24 +1936,11 @@ def compact_restore(session_id=None, cwd=None, is_compact=None, new_session_only
|
|
|
1968
1936
|
return
|
|
1969
1937
|
|
|
1970
1938
|
if is_compact and sid_safe:
|
|
1971
|
-
#
|
|
1972
|
-
# Progressive checkpoints (captured at 50/65/80% fill) are preferred because
|
|
1973
|
-
# they contain richer context than emergency checkpoints at ~98%.
|
|
1974
|
-
# All checkpoint types use the retention-days window here: this path is
|
|
1975
|
-
# both session-matched (sid_safe in filename) and post-compaction, so the
|
|
1976
|
-
# most recent stop/end checkpoint from THIS session is the best continuity
|
|
1977
|
-
# source after a compact regardless of wall-clock age. The old 5-min TTL
|
|
1978
|
-
# gated out stop/end (the common triggers) and produced 0 restores.
|
|
1979
|
-
# Selection is module-level (_order_checkpoints_for_restore) so the
|
|
1980
|
-
# cold-resume-lean path shares the same "latest valid checkpoint"
|
|
1981
|
-
# preference order.
|
|
1939
|
+
# Exact-session restore can use an older save retained for an active session.
|
|
1982
1940
|
now = _measure_facade.datetime.now()
|
|
1983
|
-
retention_cutoff = now - _measure_facade.timedelta(days=_measure_facade._CHECKPOINT_RETENTION_DAYS)
|
|
1984
1941
|
session_checkpoints = []
|
|
1985
1942
|
for cp in checkpoints:
|
|
1986
|
-
if sid_safe
|
|
1987
|
-
continue
|
|
1988
|
-
if cp["created"] < retention_cutoff:
|
|
1943
|
+
if sid_safe != _measure_facade._checkpoint_session(cp["filename"]):
|
|
1989
1944
|
continue
|
|
1990
1945
|
session_checkpoints.append(cp)
|
|
1991
1946
|
|
|
@@ -2012,21 +1967,10 @@ def compact_restore(session_id=None, cwd=None, is_compact=None, new_session_only
|
|
|
2012
1967
|
merged = _measure_facade._merge_earlier_checkpoint_context(best_cp, ordered[1:4])
|
|
2013
1968
|
_print_checkpoint_body(best_cp["path"], label, merged_body=merged)
|
|
2014
1969
|
_print_intel_digest(sid_safe)
|
|
2015
|
-
#
|
|
2016
|
-
#
|
|
2017
|
-
# checkpoint-file-size estimate so we never regress. The re-read
|
|
2018
|
-
# never happens, so nothing is metered -- _get_savings_summary
|
|
2019
|
-
# files checkpoint_restore in the estimated tier.
|
|
1970
|
+
# Only the estimated avoided working set is a credit. The injected
|
|
1971
|
+
# checkpoint itself adds context and is never a savings floor.
|
|
2020
1972
|
try:
|
|
2021
|
-
|
|
2022
|
-
# Calibrated floor (U-F: ~3.3 chars/tok), consistent with the TS
|
|
2023
|
-
# ports and the rest of the estimator surface, not the legacy 4.0.
|
|
2024
|
-
try:
|
|
2025
|
-
from token_estimate import estimate_tokens_from_bytes
|
|
2026
|
-
floor_tokens = estimate_tokens_from_bytes(cp_size)
|
|
2027
|
-
except ImportError:
|
|
2028
|
-
floor_tokens = int(cp_size / _measure_facade.CHARS_PER_TOKEN)
|
|
2029
|
-
est_tokens_recovered = _measure_facade._checkpoint_restore_recovery_tokens(sid_safe, floor_tokens)
|
|
1973
|
+
est_tokens_recovered = _measure_facade._checkpoint_restore_recovery_tokens(sid_safe, 0)
|
|
2030
1974
|
if est_tokens_recovered > 0:
|
|
2031
1975
|
_measure_facade._log_savings_event("checkpoint_restore", est_tokens_recovered,
|
|
2032
1976
|
session_id=sid_safe, detail=f"restored from {trigger_label}")
|
|
@@ -2034,12 +1978,7 @@ def compact_restore(session_id=None, cwd=None, is_compact=None, new_session_only
|
|
|
2034
1978
|
pass
|
|
2035
1979
|
return
|
|
2036
1980
|
|
|
2037
|
-
# No matching checkpoint
|
|
2038
|
-
# different session's body into post-compaction context; only surface a
|
|
2039
|
-
# short pointer so the user can opt in if it is actually relevant.
|
|
2040
|
-
latest = checkpoints[0]
|
|
2041
|
-
if latest["created"] >= retention_cutoff:
|
|
2042
|
-
print(f"[Token Optimizer] No matching checkpoint. Recent: {latest['path']}. Load if relevant.")
|
|
1981
|
+
# No matching checkpoint: do not suggest a sibling during compaction.
|
|
2043
1982
|
return
|
|
2044
1983
|
|
|
2045
1984
|
|
|
@@ -2880,7 +2819,7 @@ def _continuity_resume_block(text, checkpoints, sid_safe, cwd):
|
|
|
2880
2819
|
block = _measure_facade.build_lean_resume_context(cp_sid, prompt_text=text, cwd=cwd,
|
|
2881
2820
|
footer_mode=_named_footer)
|
|
2882
2821
|
if block:
|
|
2883
|
-
_measure_facade._log_resume_lean_savings(cp_sid, block)
|
|
2822
|
+
_measure_facade._log_resume_lean_savings(cp_sid, block, receiver_session_id=sid_safe)
|
|
2884
2823
|
return block
|
|
2885
2824
|
# No checkpoint matches the named id. If the id was the WHOLE ask (no separate
|
|
2886
2825
|
# resume verb) never substitute a different session -- return "". But when
|
|
@@ -2892,7 +2831,7 @@ def _continuity_resume_block(text, checkpoints, sid_safe, cwd):
|
|
|
2892
2831
|
|
|
2893
2832
|
same_project = []
|
|
2894
2833
|
for cp in checkpoints[:50]:
|
|
2895
|
-
if sid_safe and sid_safe
|
|
2834
|
+
if sid_safe and sid_safe == _measure_facade._checkpoint_session(cp.get("filename", "")):
|
|
2896
2835
|
continue # same-session recovery is SessionStart/compact's job
|
|
2897
2836
|
sidecar = _measure_facade._read_checkpoint_sidecar(cp["path"])
|
|
2898
2837
|
if not _measure_facade._checkpoint_in_project(sidecar, cwd):
|
|
@@ -2929,7 +2868,7 @@ def _continuity_resume_block(text, checkpoints, sid_safe, cwd):
|
|
|
2929
2868
|
if block:
|
|
2930
2869
|
# Count the cold-resume cost this lean reconstruction avoided (idempotent
|
|
2931
2870
|
# per target session). Token-free; never blocks the injection.
|
|
2932
|
-
_measure_facade._log_resume_lean_savings(sid, block)
|
|
2871
|
+
_measure_facade._log_resume_lean_savings(sid, block, receiver_session_id=sid_safe)
|
|
2933
2872
|
return block
|
|
2934
2873
|
|
|
2935
2874
|
|
|
@@ -3091,7 +3030,7 @@ def _continuity_prompt_hint(prompt_text=None, session_id=None, cwd=None, max_age
|
|
|
3091
3030
|
# but among similar-relevance sessions the more active one wins.
|
|
3092
3031
|
activity_weight = 1.0 + 0.5 * min(density, 20) / 20.0
|
|
3093
3032
|
for checkpoint in _cps[:_per_session_scan]:
|
|
3094
|
-
if sid_safe and sid_safe
|
|
3033
|
+
if sid_safe and sid_safe == _measure_facade._checkpoint_session(checkpoint.get("filename", "")):
|
|
3095
3034
|
continue
|
|
3096
3035
|
score, sidecar = _measure_facade._checkpoint_topic_score(text, checkpoint, cwd=cwd)
|
|
3097
3036
|
# Collect from the teaser floor (default 0.3); the full-block gate
|
|
@@ -3332,7 +3271,7 @@ def _best_checkpoint_for_session(session_id, within_retention=None):
|
|
|
3332
3271
|
cutoff = _measure_facade.datetime.now() - _measure_facade.timedelta(days=_measure_facade._CHECKPOINT_RETENTION_DAYS)
|
|
3333
3272
|
cands = []
|
|
3334
3273
|
for cp in _measure_facade.list_checkpoints():
|
|
3335
|
-
if sid_safe
|
|
3274
|
+
if sid_safe != _measure_facade._checkpoint_session(cp.get("filename", "")):
|
|
3336
3275
|
continue
|
|
3337
3276
|
if within_retention and cp["created"] < cutoff:
|
|
3338
3277
|
continue
|
|
@@ -3757,7 +3696,7 @@ def _transcript_last_turn(sid_safe):
|
|
|
3757
3696
|
return None
|
|
3758
3697
|
|
|
3759
3698
|
|
|
3760
|
-
def _log_resume_lean_savings(target_session_id, lean_block):
|
|
3699
|
+
def _log_resume_lean_savings(target_session_id, lean_block, receiver_session_id=None):
|
|
3761
3700
|
"""Credit the cold-resume cost avoided by reconstructing a session lean
|
|
3762
3701
|
instead of `claude --resume`-ing it.
|
|
3763
3702
|
|
|
@@ -3812,9 +3751,20 @@ def _log_resume_lean_savings(target_session_id, lean_block):
|
|
|
3812
3751
|
rates = tier_data["claude_models"].get(
|
|
3813
3752
|
model_norm, tier_data["claude_models"].get("sonnet", {}))
|
|
3814
3753
|
per_mtok = float(rates.get(rate_key) or rates.get("input", 3.0))
|
|
3754
|
+
try: # the session's exact model card, not its family card
|
|
3755
|
+
conn = _measure_facade._open_trends_db_readonly(timeout=1.0)
|
|
3756
|
+
try:
|
|
3757
|
+
per_mtok = _measure_facade._counted_pricing_v5.resume_lean_log_rate(
|
|
3758
|
+
conn, sid_safe, model_norm, rate_key,
|
|
3759
|
+
lambda m: ((_measure_facade := _compat.facade()), _measure_facade._counted_exact_card(m, tier_data))[1]) or per_mtok
|
|
3760
|
+
finally:
|
|
3761
|
+
conn.close()
|
|
3762
|
+
except Exception:
|
|
3763
|
+
pass
|
|
3815
3764
|
_measure_facade._log_savings_event("resume_lean", saved, session_id=sid_safe,
|
|
3816
3765
|
detail=f"lean resume vs --resume reload of last-turn context "
|
|
3817
|
-
f"({basis}, ${per_mtok}/MTok)"
|
|
3766
|
+
f"({basis}, ${per_mtok}/MTok)"
|
|
3767
|
+
+ (f" receiver={_measure_facade.sanitize_session_id(receiver_session_id)}" if receiver_session_id else ""),
|
|
3818
3768
|
model=model_norm, cost_per_mtok=per_mtok)
|
|
3819
3769
|
except Exception:
|
|
3820
3770
|
pass
|
|
@@ -4421,9 +4371,9 @@ def list_checkpoints(max_age_minutes=None):
|
|
|
4421
4371
|
|
|
4422
4372
|
# Parse trigger type from filename suffix.
|
|
4423
4373
|
trigger = "auto"
|
|
4424
|
-
match = _measure_facade.re.search(r'-\d{8}-\d{6}-(.+)\.md$', safe_cp.name)
|
|
4374
|
+
match = _measure_facade.re.search(r'-\d{8}-\d{6}-(?:u[0-9a-f]{16}(?:-(.+))?|(.+))\.md$', safe_cp.name)
|
|
4425
4375
|
if match:
|
|
4426
|
-
trigger = match.group(1)
|
|
4376
|
+
trigger = match.group(1) or match.group(2) or "auto"
|
|
4427
4377
|
|
|
4428
4378
|
checkpoints.append({
|
|
4429
4379
|
"path": safe_cp,
|
|
@@ -4452,9 +4402,8 @@ def _checkpoints_to_prune(checkpoints, now=None, days=None, total_max=None, per_
|
|
|
4452
4402
|
- older than the retention window: removed;
|
|
4453
4403
|
- per session: the newest `per_session`, plus the newest of each trigger
|
|
4454
4404
|
(restore prefers earlier, richer saves over late stop saves), are kept;
|
|
4455
|
-
- over the disk ceiling: extra saves go oldest first
|
|
4456
|
-
|
|
4457
|
-
A session's newest checkpoint is removed only by age or the ceiling, never
|
|
4405
|
+
- over the disk ceiling: extra saves go oldest first; newest saves survive.
|
|
4406
|
+
A session's newest checkpoint is removed only by age, never
|
|
4458
4407
|
by another session's activity. A file a writer has not seen yet is never in
|
|
4459
4408
|
its list, so it cannot be removed by that writer.
|
|
4460
4409
|
"""
|
|
@@ -4489,8 +4438,6 @@ def _checkpoints_to_prune(checkpoints, now=None, days=None, total_max=None, per_
|
|
|
4489
4438
|
drop_extra = extra[::-1][:over]
|
|
4490
4439
|
prune.extend(drop_extra)
|
|
4491
4440
|
over -= len(drop_extra)
|
|
4492
|
-
if over > 0:
|
|
4493
|
-
prune.extend(newest[::-1][:over])
|
|
4494
4441
|
return prune
|
|
4495
4442
|
|
|
4496
4443
|
|
|
@@ -4509,12 +4456,11 @@ def _cleanup_checkpoints():
|
|
|
4509
4456
|
if not checkpoints:
|
|
4510
4457
|
return
|
|
4511
4458
|
|
|
4512
|
-
for cp in _measure_facade._checkpoints_to_prune(checkpoints):
|
|
4459
|
+
for cp in checkpoint_retention.exclude_latest(_measure_facade._checkpoints_to_prune(checkpoints), checkpoints, _measure_facade._checkpoint_session, _measure_facade._checkpoint_has_restorable_body):
|
|
4513
4460
|
try:
|
|
4514
4461
|
cp["path"].unlink()
|
|
4515
4462
|
except OSError:
|
|
4516
4463
|
continue
|
|
4517
|
-
# Also delete the sibling JSON sidecar if present.
|
|
4518
4464
|
try:
|
|
4519
4465
|
cp["path"].with_suffix(".json").unlink()
|
|
4520
4466
|
except OSError:
|
|
@@ -4587,7 +4533,7 @@ def _prune_trends_db():
|
|
|
4587
4533
|
return
|
|
4588
4534
|
cutoff_iso = (_measure_facade.datetime.now() - _measure_facade.timedelta(days=_measure_facade._TRENDS_RETENTION_DAYS)).isoformat()
|
|
4589
4535
|
cutoff_date = cutoff_iso[:10] # session_log.date is YYYY-MM-DD
|
|
4590
|
-
conn = _measure_facade.sqlite3.connect(str(trends_path), timeout=5)
|
|
4536
|
+
conn = _measure_facade.sqlite3.connect(str(trends_path), timeout=5, factory=upgrade_drain_control.SessionLogConnection)
|
|
4591
4537
|
try:
|
|
4592
4538
|
conn.execute("PRAGMA journal_mode=WAL")
|
|
4593
4539
|
conn.execute("PRAGMA busy_timeout=5000")
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
"""An unattributed cost-per-message trend on one constant price basis: Opus
|
|
2
|
+
list prices for every model, so model mix changes do not move the index
|
|
3
|
+
through price; the renderer labels it "at constant Opus prices"."""
|
|
4
|
+
import json
|
|
5
|
+
import math
|
|
6
|
+
from collections import defaultdict
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def index_rows(rows):
|
|
10
|
+
monthly = defaultdict(lambda: [0.0, 0])
|
|
11
|
+
for day, messages, raw in rows:
|
|
12
|
+
try:
|
|
13
|
+
messages = int(messages or 0)
|
|
14
|
+
models = json.loads(raw) if isinstance(raw, str) and raw else (raw or {})
|
|
15
|
+
if not day or messages < 0 or not isinstance(models, dict):
|
|
16
|
+
continue
|
|
17
|
+
cost = 0.0
|
|
18
|
+
for parts in models.values():
|
|
19
|
+
if not isinstance(parts, dict):
|
|
20
|
+
continue
|
|
21
|
+
cost += (float(parts.get('fresh_input') or 0) * 5 + float(parts.get('output') or 0) * 25
|
|
22
|
+
+ float(parts.get('cache_read') or 0) * .5 + float(parts.get('cache_create') or 0) * 6.25)
|
|
23
|
+
if not math.isfinite(cost) or cost < 0:
|
|
24
|
+
continue
|
|
25
|
+
monthly[str(day)[:7]][0] += cost
|
|
26
|
+
monthly[str(day)[:7]][1] += messages
|
|
27
|
+
except (TypeError, ValueError, OverflowError):
|
|
28
|
+
continue
|
|
29
|
+
values = [(month, cost / messages) for month, (cost, messages) in sorted(monthly.items()) if messages and cost > 0]
|
|
30
|
+
if not values:
|
|
31
|
+
return []
|
|
32
|
+
base = values[0][1]
|
|
33
|
+
return [{'month': month, 'index': round(value / base * 100, 1)} for month, value in values]
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def query(conn):
|
|
37
|
+
from session_activity import ensure_activity_view
|
|
38
|
+
ensure_activity_view(conn)
|
|
39
|
+
rows = conn.execute("SELECT date, message_count, model_usage_breakdown_json FROM session_activity WHERE COALESCE(is_sidechain,0)=0 ORDER BY date").fetchall()
|
|
40
|
+
return index_rows(rows)
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
"""Exclude cap estimates contradicted by their own recorded evidence."""
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
def contradicted(alias):
|
|
5
|
+
detail = alias + '.detail'
|
|
6
|
+
chars = "CAST(REPLACE(substr({d}, instr({d}, '(')+1, instr({d}, ' chars >=')-instr({d}, '(')-1), ',', '') AS INTEGER)".format(d=detail)
|
|
7
|
+
cap = "CAST(REPLACE(substr({d}, instr({d}, 'cap=')+4, instr({d}, ' tok,')-instr({d}, 'cap=')-4), ',', '') AS INTEGER)".format(d=detail)
|
|
8
|
+
tool = "substr({d}, 12, instr(substr({d}, 12), ' result at cap')-1)".format(d=detail)
|
|
9
|
+
return ("({a}.event_type = 'mcp_cap' AND ((instr({d}, ' chars >=') > 0 AND instr({d}, 'cap=') > 0 "
|
|
10
|
+
"AND {chars} > 0 AND {cap} > 0 AND {chars} <= 4 * {cap}) OR "
|
|
11
|
+
"(COALESCE({a}.session_id, '') != '' AND {tool} != '' AND EXISTS "
|
|
12
|
+
"(SELECT 1 FROM main.savings_events ar WHERE ar.event_type = 'tool_archive' "
|
|
13
|
+
"AND ar.session_id = {a}.session_id AND substr(ar.detail, 1, length('replaced ' || {tool} || ' (')) = 'replaced ' || {tool} || ' (' "
|
|
14
|
+
"AND abs((julianday(ar.timestamp)-julianday({a}.timestamp))*86400) <= 3))))").format(
|
|
15
|
+
a=alias, d=detail, chars=chars, cap=cap, tool=tool)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def reexpand_type(alias=''):
|
|
19
|
+
"""Separate Bash archive debits from MCP debits using recorded lineage."""
|
|
20
|
+
prefix = alias + '.' if alias else ''
|
|
21
|
+
detail = prefix + 'detail'
|
|
22
|
+
kind = prefix + 'event_type'
|
|
23
|
+
return ("CASE WHEN {kind}='tool_archive_reexpand' AND "
|
|
24
|
+
"(instr(coalesce({detail},''), ' (Bash)') > 0 OR "
|
|
25
|
+
"(length(substr(coalesce({detail},''),1,16))=16 AND "
|
|
26
|
+
"substr({detail},1,16) NOT GLOB '*[^0-9a-f]*' AND "
|
|
27
|
+
"(length({detail})=16 OR (substr({detail},17,1)=' ' AND instr({detail}, ' (')=0)))) "
|
|
28
|
+
"THEN 'bash_archive_reexpand' ELSE {kind} END").format(kind=kind, detail=detail)
|