@alexgreensh/token-optimizer 5.13.69 → 5.13.71

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (148) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/PRIVACY.md +4 -0
  4. package/hooks/hooks.json +11 -1
  5. package/hooks/module_runner.py +4 -1
  6. package/hooks/posttooluse_runner.py +44 -48
  7. package/hooks/sessionstart_runner.py +24 -5
  8. package/hooks/stop_runner.py +6 -6
  9. package/package.json +1 -1
  10. package/skills/token-optimizer/assets/dashboard.html +729 -767
  11. package/skills/token-optimizer/assets/savings_story.js +765 -0
  12. package/skills/token-optimizer/pricing/prices.json +1 -0
  13. package/skills/token-optimizer/references/cli-reference.md +1 -1
  14. package/skills/token-optimizer/references/implementation-playbook.md +3 -0
  15. package/skills/token-optimizer/scripts/_measure/__init__.py +3 -1
  16. package/skills/token-optimizer/scripts/_measure/archive_health.py +14 -0
  17. package/skills/token-optimizer/scripts/_measure/archive_void_codex.py +163 -0
  18. package/skills/token-optimizer/scripts/_measure/archive_void_evidence.py +165 -0
  19. package/skills/token-optimizer/scripts/_measure/audit.py +27 -135
  20. package/skills/token-optimizer/scripts/_measure/baseline_provenance.py +339 -0
  21. package/skills/token-optimizer/scripts/_measure/cache_policy.py +261 -581
  22. package/skills/token-optimizer/scripts/_measure/checkpoint_direction.py +97 -0
  23. package/skills/token-optimizer/scripts/_measure/checkpoint_retention.py +20 -0
  24. package/skills/token-optimizer/scripts/_measure/cli.py +12 -8
  25. package/skills/token-optimizer/scripts/_measure/codex_quality.py +246 -0
  26. package/skills/token-optimizer/scripts/_measure/compaction_survival.py +158 -0
  27. package/skills/token-optimizer/scripts/_measure/compression_fixture_void.py +147 -0
  28. package/skills/token-optimizer/scripts/_measure/compression_scan_checkpoint.py +72 -0
  29. package/skills/token-optimizer/scripts/_measure/context_reset_marker.py +66 -0
  30. package/skills/token-optimizer/scripts/_measure/continuity.py +64 -118
  31. package/skills/token-optimizer/scripts/_measure/cost_per_message_trend.py +40 -0
  32. package/skills/token-optimizer/scripts/_measure/counted_cap.py +30 -0
  33. package/skills/token-optimizer/scripts/_measure/counted_orphans.py +190 -0
  34. package/skills/token-optimizer/scripts/_measure/counted_position.py +20 -0
  35. package/skills/token-optimizer/scripts/_measure/counted_pricing_v5.py +267 -0
  36. package/skills/token-optimizer/scripts/_measure/counted_subagents.py +371 -0
  37. package/skills/token-optimizer/scripts/_measure/coverage_report.py +295 -0
  38. package/skills/token-optimizer/scripts/_measure/daemon.py +53 -74
  39. package/skills/token-optimizer/scripts/_measure/dashboard.py +90 -151
  40. package/skills/token-optimizer/scripts/_measure/dashboard_heal_claim.py +36 -0
  41. package/skills/token-optimizer/scripts/_measure/evidence_parallel.py +95 -0
  42. package/skills/token-optimizer/scripts/_measure/feature_health.py +256 -0
  43. package/skills/token-optimizer/scripts/_measure/file_refetch.py +250 -0
  44. package/skills/token-optimizer/scripts/_measure/first_call_context.py +216 -0
  45. package/skills/token-optimizer/scripts/_measure/first_read_outcomes.py +261 -0
  46. package/skills/token-optimizer/scripts/_measure/first_read_revive.py +137 -0
  47. package/skills/token-optimizer/scripts/_measure/fixture_context.py +65 -0
  48. package/skills/token-optimizer/scripts/_measure/headline.py +100 -0
  49. package/skills/token-optimizer/scripts/_measure/holdout_fallback.py +96 -0
  50. package/skills/token-optimizer/scripts/_measure/holdout_report.py +129 -0
  51. package/skills/token-optimizer/scripts/_measure/keepwarm_economics.py +201 -0
  52. package/skills/token-optimizer/scripts/_measure/keepwarm_linux.py +121 -0
  53. package/skills/token-optimizer/scripts/_measure/keepwarm_safety.py +260 -0
  54. package/skills/token-optimizer/scripts/_measure/lean_resume_receivers.py +260 -0
  55. package/skills/token-optimizer/scripts/_measure/lean_resume_threshold.py +76 -0
  56. package/skills/token-optimizer/scripts/_measure/lease_candidate_cleanup.py +82 -0
  57. package/skills/token-optimizer/scripts/_measure/lifecycle.py +54 -162
  58. package/skills/token-optimizer/scripts/_measure/mcp_archive_tripwire.py +120 -0
  59. package/skills/token-optimizer/scripts/_measure/mod_action_booking.py +178 -0
  60. package/skills/token-optimizer/scripts/_measure/mod_compaction_booking.py +276 -0
  61. package/skills/token-optimizer/scripts/_measure/mod_fresh_booking.py +105 -0
  62. package/skills/token-optimizer/scripts/_measure/output_reread.py +629 -0
  63. package/skills/token-optimizer/scripts/_measure/own_price_card.py +268 -0
  64. package/skills/token-optimizer/scripts/_measure/periphery_exposure.py +85 -0
  65. package/skills/token-optimizer/scripts/_measure/pricing.py +152 -87
  66. package/skills/token-optimizer/scripts/_measure/quality_archive.py +159 -215
  67. package/skills/token-optimizer/scripts/_measure/quality_checkpoint.py +174 -0
  68. package/skills/token-optimizer/scripts/_measure/quality_continuity.py +43 -0
  69. package/skills/token-optimizer/scripts/_measure/rework_metrics.py +194 -0
  70. package/skills/token-optimizer/scripts/_measure/routing_period.py +48 -0
  71. package/skills/token-optimizer/scripts/_measure/savings.py +439 -864
  72. package/skills/token-optimizer/scripts/_measure/savings_headline.py +130 -0
  73. package/skills/token-optimizer/scripts/_measure/savings_story.py +187 -0
  74. package/skills/token-optimizer/scripts/_measure/session_best.py +24 -0
  75. package/skills/token-optimizer/scripts/_measure/session_effect.py +557 -0
  76. package/skills/token-optimizer/scripts/_measure/session_flush_lock.py +75 -0
  77. package/skills/token-optimizer/scripts/_measure/session_store_spool.py +220 -0
  78. package/skills/token-optimizer/scripts/_measure/sessions.py +103 -196
  79. package/skills/token-optimizer/scripts/_measure/setup_attachment_counter.py +196 -0
  80. package/skills/token-optimizer/scripts/_measure/setup_budget_monitor.py +180 -0
  81. package/skills/token-optimizer/scripts/_measure/setup_connector_ledger.py +126 -0
  82. package/skills/token-optimizer/scripts/_measure/setup_step.py +220 -0
  83. package/skills/token-optimizer/scripts/_measure/status_bar_lock.py +117 -0
  84. package/skills/token-optimizer/scripts/_measure/structural_archives.py +79 -0
  85. package/skills/token-optimizer/scripts/_measure/structural_dedupe.py +91 -0
  86. package/skills/token-optimizer/scripts/_measure/structural_ledger.py +418 -0
  87. package/skills/token-optimizer/scripts/_measure/structural_listing.py +163 -0
  88. package/skills/token-optimizer/scripts/_measure/structural_report.py +339 -0
  89. package/skills/token-optimizer/scripts/_measure/structural_seed.py +164 -0
  90. package/skills/token-optimizer/scripts/_measure/structural_value.py +248 -0
  91. package/skills/token-optimizer/scripts/_measure/structure_funnel.py +97 -0
  92. package/skills/token-optimizer/scripts/_measure/timestamp_cache.py +11 -0
  93. package/skills/token-optimizer/scripts/_measure/token_type_split.py +29 -0
  94. package/skills/token-optimizer/scripts/_measure/transcript_backfill.py +419 -0
  95. package/skills/token-optimizer/scripts/_measure/transcript_product.py +228 -0
  96. package/skills/token-optimizer/scripts/_measure/transcript_stream.py +279 -0
  97. package/skills/token-optimizer/scripts/_measure/trends.py +44 -185
  98. package/skills/token-optimizer/scripts/_measure/ttl_period.py +6 -0
  99. package/skills/token-optimizer/scripts/_measure/upgrade_drain_control.py +287 -0
  100. package/skills/token-optimizer/scripts/activity_tracker.py +4 -33
  101. package/skills/token-optimizer/scripts/antigravity_install.py +2 -0
  102. package/skills/token-optimizer/scripts/archive_result.py +15 -19
  103. package/skills/token-optimizer/scripts/archive_verify.py +165 -0
  104. package/skills/token-optimizer/scripts/bash_compress.py +14 -43
  105. package/skills/token-optimizer/scripts/bash_compress_hook.py +132 -2
  106. package/skills/token-optimizer/scripts/checkpoint_state.py +2 -2
  107. package/skills/token-optimizer/scripts/cloud_kit.py +3 -6
  108. package/skills/token-optimizer/scripts/codemap.py +274 -0
  109. package/skills/token-optimizer/scripts/codemap_hint.py +153 -0
  110. package/skills/token-optimizer/scripts/codemap_index.py +656 -0
  111. package/skills/token-optimizer/scripts/codemap_ledger.py +309 -0
  112. package/skills/token-optimizer/scripts/codemap_reread.py +161 -0
  113. package/skills/token-optimizer/scripts/codex_doctor.py +9 -1
  114. package/skills/token-optimizer/scripts/codex_log_index.py +34 -15
  115. package/skills/token-optimizer/scripts/codex_session.py +16 -216
  116. package/skills/token-optimizer/scripts/compression_backfill.py +4 -35
  117. package/skills/token-optimizer/scripts/context_intel.py +5 -3
  118. package/skills/token-optimizer/scripts/copilot_install.py +2 -0
  119. package/skills/token-optimizer/scripts/coverage_funnel.py +261 -0
  120. package/skills/token-optimizer/scripts/cursor_install.py +12 -0
  121. package/skills/token-optimizer/scripts/cursor_quality.py +16 -64
  122. package/skills/token-optimizer/scripts/dashboard_assets.py +21 -0
  123. package/skills/token-optimizer/scripts/deterministic_candidates.py +2 -10
  124. package/skills/token-optimizer/scripts/devin_source.py +8 -3
  125. package/skills/token-optimizer/scripts/devin_verify.py +7 -1
  126. package/skills/token-optimizer/scripts/grok_install.py +2 -0
  127. package/skills/token-optimizer/scripts/heal_report.py +7 -6
  128. package/skills/token-optimizer/scripts/hermes_doctor.py +9 -1
  129. package/skills/token-optimizer/scripts/hermes_install.py +7 -1
  130. package/skills/token-optimizer/scripts/hermes_session.py +14 -136
  131. package/skills/token-optimizer/scripts/hint_paths.py +21 -0
  132. package/skills/token-optimizer/scripts/holdout.py +136 -0
  133. package/skills/token-optimizer/scripts/hook_runtime.py +1 -0
  134. package/skills/token-optimizer/scripts/hook_skip_log.py +89 -0
  135. package/skills/token-optimizer/scripts/large_transcripts.py +31 -0
  136. package/skills/token-optimizer/scripts/lean_resume_carry.py +518 -0
  137. package/skills/token-optimizer/scripts/measure.py +34 -76
  138. package/skills/token-optimizer/scripts/post_run_classify.py +349 -0
  139. package/skills/token-optimizer/scripts/preserved_reinject.py +54 -0
  140. package/skills/token-optimizer/scripts/read_cache.py +99 -100
  141. package/skills/token-optimizer/scripts/reset_epoch.py +3 -3
  142. package/skills/token-optimizer/scripts/session_store.py +49 -99
  143. package/skills/token-optimizer/scripts/session_store_guard.py +75 -0
  144. package/skills/token-optimizer/scripts/settings_backup.py +379 -0
  145. package/skills/token-optimizer/scripts/shipped_hook_templates.py +1 -0
  146. package/skills/token-optimizer/scripts/statusline.js +144 -30
  147. package/skills/token-optimizer/scripts/structural.py +25 -0
  148. package/skills/token-optimizer/scripts/structure_map.py +4 -26
@@ -129,33 +129,19 @@ def _safe_int(value: Any) -> int:
129
129
 
130
130
 
131
131
  def _iter_json_records(filepath: str | Path, *, skip_large_file: bool = True):
132
- """Yield parsed JSONL records without letting pathological logs dominate.
133
-
134
- Codex can occasionally leave multi-GB session files or individual records
135
- with enormous embedded tool output. Dashboard and hook refresh paths need
136
- bounded work more than perfect telemetry from those outlier transcripts.
137
- """
132
+ """Stream small logs; large logs advance a resumable telemetry index."""
138
133
  path = Path(filepath)
139
134
  try:
140
135
  with path.open("rb") as handle:
141
136
  size = path.stat().st_size
142
137
  if skip_large_file and size > MAX_PARSE_FILE_BYTES:
143
- # Keep identity, but never attribute the omitted interval to
144
- # the model from the first turn. Only recent usage is sampled.
145
- head = handle.readline(65536)
138
+ import codex_log_index
139
+ values, _ = codex_log_index.records(path)
146
140
  try:
147
- meta = json.loads(head)
148
- if isinstance(meta, dict) and meta.get('type') == 'session_meta':
149
- yield meta
150
- except (ValueError, UnicodeError):
151
- pass
152
- offset = max(handle.tell(), size - LARGE_FILE_TAIL_BYTES)
153
- handle.seek(max(0, offset - 1))
154
- if offset and handle.read(1) != b'\n':
155
- while True:
156
- fragment = handle.readline(65536)
157
- if not fragment or fragment.endswith(b'\n'):
158
- break
141
+ yield from values
142
+ finally:
143
+ values.close()
144
+ return
159
145
  while True:
160
146
  line = handle.readline(MAX_JSONL_LINE_CHARS + 1)
161
147
  if not line:
@@ -435,7 +421,8 @@ def parse_session_jsonl(filepath: str | Path) -> dict[str, Any] | None:
435
421
  return result
436
422
  except (OSError, ValueError, sqlite3.Error):
437
423
  # Contention must not stall a hook. A tail fallback remains labelled.
438
- return _parse_session_records(_iter_json_records(filepath), incomplete=True, sampled=True)
424
+ from _measure.transcript_stream import sampled_records
425
+ return _parse_session_records(sampled_records(filepath), incomplete=True, sampled=True)
439
426
  return _parse_session_records(_iter_json_records(filepath))
440
427
 
441
428
 
@@ -739,200 +726,13 @@ def parse_session_turns(filepath: str | Path) -> list[dict[str, Any]]:
739
726
  return turns
740
727
 
741
728
 
742
- def parse_jsonl_for_quality(filepath: str | Path) -> dict[str, Any] | None:
743
- reads: list[tuple[int, str, str]] = []
744
- writes: list[tuple[int, str, str]] = []
745
- tool_results: list[tuple[int, str, int, bool]] = []
746
- system_reminders: list[tuple[int, str, int]] = []
747
- messages: list[tuple[int, str, int, bool]] = []
748
- compactions = 0
749
- agent_dispatches: list[tuple[int, int, int]] = []
750
- decisions: list[tuple[int, str]] = []
751
- compaction_ratios: list[dict[str, Any]] = []
752
- compaction_events: list[dict[str, Any]] = []
753
- last_usage: dict[str, int] | None = None
754
- current_model = _UNKNOWN_MODEL
755
- topics: dict[str, str | None] = {}
756
- idx = 0
757
- prev_was_compacted = False
758
- last_turn_context: int | None = None
759
- safe_pause = False
760
-
761
- for record in _iter_json_records(filepath):
762
- payload = _payload(record)
763
- payload_type = payload.get("type")
764
- ts = str(record.get("timestamp") or "")
765
- if payload_type in {"task_complete", "turn_complete"}:
766
- safe_pause = True
767
- elif payload_type in {"task_started", "turn_started", "function_call", "custom_tool_call",
768
- "function_call_output", "custom_tool_call_output", "exec_command_end",
769
- "patch_apply_end", "agent_message"}:
770
- safe_pause = False
771
-
772
- model = _extract_model(payload)
773
- if model:
774
- current_model = model
775
-
776
- # Per compaction: the `compacted` rollout record (which carries
777
- # replacement_history) is authoritative — count it and capture the ratio.
778
- # Its paired `context_compacted` event_msg fires immediately after, so
779
- # count that ONLY when standalone (older Codex with no `compacted`
780
- # record), detected by the previous record not being a `compacted`. This
781
- # keeps the count==len(ratios) invariant even for back-to-back compactions.
782
- is_compacted_record = record.get("type") == "compacted"
783
- if is_compacted_record or payload_type == "context_compacted":
784
- safe_pause = False
785
- if is_compacted_record:
786
- compactions += 1
787
- # Minimal recovery event for the quality panel: Codex has no
788
- # matched pre/post tool-call windows, so window_data=False
789
- # keeps every boundary honestly "unmeasurable" rather than
790
- # implying healthy recovery.
791
- compaction_events.append({
792
- "boundary_id": f"codex-{compactions}",
793
- "ordinal": compactions,
794
- "line": idx,
795
- "ts": ts,
796
- "trigger": "auto",
797
- "pre_tokens": last_turn_context,
798
- "post_tokens": None,
799
- "host_version": None,
800
- "model": current_model if current_model != _UNKNOWN_MODEL else None,
801
- "pre_seg_calls": 0,
802
- "post_seg_calls": 0,
803
- "matched_calls": 0,
804
- "eligible": False,
805
- "window_data": False,
806
- "restore_transcript": False,
807
- "capture_notice": False,
808
- })
809
- rh = payload.get("replacement_history")
810
- # Codex total_token_usage is cumulative (monotonic), so it does
811
- # not drop at compaction. The meaningful "before" is the context
812
- # occupancy of the last turn (per-turn input+cache); the "after"
813
- # is the size of the replacement history that becomes the new
814
- # context. ratio < 1 means compaction shrank the context; ratio is
815
- # None for a degenerate empty/missing replacement_history.
816
- after_tokens = _replacement_content_tokens(rh) if isinstance(rh, list) else None
817
- ratio = round(after_tokens / last_turn_context, 3) if after_tokens and last_turn_context else None
818
- compaction_ratios.append({
819
- "before_context_tokens": last_turn_context,
820
- "after_context_tokens": after_tokens,
821
- "replacement_msgs": len(rh) if isinstance(rh, list) else None,
822
- "ratio": ratio,
823
- })
824
- elif not prev_was_compacted:
825
- compactions += 1
826
- compaction_events.append({
827
- "boundary_id": f"codex-{compactions}",
828
- "ordinal": compactions,
829
- "line": idx,
830
- "ts": ts,
831
- "trigger": "auto",
832
- "pre_tokens": last_turn_context,
833
- "post_tokens": None,
834
- "host_version": None,
835
- "model": current_model if current_model != _UNKNOWN_MODEL else None,
836
- "pre_seg_calls": 0,
837
- "post_seg_calls": 0,
838
- "matched_calls": 0,
839
- "eligible": False,
840
- "window_data": False,
841
- "restore_transcript": False,
842
- "capture_notice": False,
843
- })
844
- prev_was_compacted = is_compacted_record
845
- reads = []
846
- writes = []
847
- tool_results = []
848
- system_reminders = []
849
- messages = []
850
- agent_dispatches = []
851
- decisions = []
852
- idx += 1
853
- continue
854
- prev_was_compacted = False
855
-
856
- if payload_type == "token_count":
857
- usage = _token_usage(payload, cumulative=True)
858
- if usage:
859
- last_usage = usage
860
- turn = _token_usage(payload, cumulative=False)
861
- if turn:
862
- # input already includes cached input; cumulative session
863
- # usage is not the occupancy of this response's context.
864
- last_turn_context = turn["input_tokens"] + turn["output_tokens"]
865
-
866
- elif payload_type == "collab_agent_spawn_end":
867
- prompt = str(payload.get("prompt") or "")
868
- agent_dispatches.append((idx, len(prompt), 0))
869
-
870
- elif payload_type in {"user_message", "message", "agent_message"}:
871
- text = _extract_text(payload)
872
- role = "assistant" if payload_type == "agent_message" else str(payload.get("role") or "user")
873
- safe_pause = role == "user" and bool(_task_user_text(text))
874
- if role == "user" and not topics.get(payload_type):
875
- task = _task_user_text(text)
876
- if task:
877
- topics[payload_type] = _extract_topic(task)
878
- substantive = len(text.split()) > (20 if role == "assistant" else 10)
879
- messages.append((idx, role, len(text), substantive))
880
- if re.search(r"\b(chose|decided|because|switched|going with)\b", text, re.IGNORECASE):
881
- decisions.append((idx, text[:200].strip()))
882
-
883
- elif payload_type in {"function_call", "custom_tool_call"}:
884
- name = str(payload.get("name") or "")
885
- args = _parse_arguments(payload)
886
- if name == "exec_command":
887
- cmd = str(args.get("cmd") or "")
888
- if READ_CMD_RE.search(cmd):
889
- for path in _extract_shell_paths(cmd):
890
- reads.append((idx, path, ts))
891
- elif name == "apply_patch":
892
- patch = str(args.get("patch") or "")
893
- for path in PATCH_FILE_RE.findall(patch):
894
- writes.append((idx, path.strip(), ts))
895
- elif name == "spawn_agent":
896
- prompt = str(args.get("message") or args.get("prompt") or "")
897
- agent_dispatches.append((idx, len(prompt), 0))
898
-
899
- elif payload_type in {"function_call_output", "custom_tool_call_output"}:
900
- text = str(payload.get("output") or "")
901
- call_id = str(payload.get("call_id") or idx)
902
- tool_results.append((idx, call_id, len(text), False))
903
- if agent_dispatches and agent_dispatches[-1][2] == 0:
904
- last = agent_dispatches[-1]
905
- agent_dispatches[-1] = (last[0], last[1], len(text))
906
- elif payload_type in {"exec_command_end", "patch_apply_end"}:
907
- text = _event_output_text(payload)
908
- if text:
909
- call_id = str(payload.get("call_id") or idx)
910
- tool_results.append((idx, call_id, len(text), False))
911
-
912
- idx += 1
913
-
914
- if not messages:
915
- return None
916
-
917
- return {
918
- "reads": reads,
919
- "writes": writes,
920
- "tool_results": tool_results,
921
- "system_reminders": system_reminders,
922
- "messages": messages,
923
- "safe_pause": safe_pause,
924
- "compactions": compactions,
925
- "agent_dispatches": agent_dispatches,
926
- "decisions": decisions,
927
- "compaction_ratios": compaction_ratios,
928
- "compaction_events": compaction_events,
929
- "total_entries": idx,
930
- "estimated": True,
931
- "context_tokens": last_turn_context or None,
932
- "model_context_window": last_usage["model_context_window"] if last_usage else None,
933
- "model": current_model if current_model != _UNKNOWN_MODEL else _DEFAULT_MODEL,
934
- "topic": _pick_topic(topics),
935
- }
729
+ def parse_jsonl_for_quality(filepath: str | Path, checkpoint=None) -> dict[str, Any] | None:
730
+ from _measure.codex_quality import parse_jsonl_for_quality as parse
731
+ from _measure.quality_checkpoint import ParseFailure
732
+ try:
733
+ return parse(filepath, checkpoint)
734
+ except OSError:
735
+ return ParseFailure("unreadable")
936
736
 
937
737
 
938
738
  def iter_tool_outputs(
@@ -1,26 +1,5 @@
1
1
  #!/usr/bin/env python3
2
- """Token Optimizer - first-read shadow BACKFILL analyzer.
3
-
4
- Replays existing Claude Code (and Codex) transcripts to answer the R9 promotion
5
- question from REAL history instead of waiting weeks for live shadow data:
6
-
7
- For large structure-supported whole-file reads, what would a skeleton have
8
- saved, and how often did the model edit that same file SOON after reading it
9
- (the "it needed the full file" signal)?
10
-
11
- A transcript already contains both halves: the Read tool_result holds the file
12
- content as it entered context, and later Edit/Write/MultiEdit tool_use blocks
13
- name the file. So `turns_until_edit` -- impossible to know live at read time --
14
- is directly observable in history.
15
-
16
- Output: a per-cohort report (language x size-band) of read count, edit-within-N
17
- rate, and average would-be skeleton ratio. With --write-cohorts it persists the
18
- cohorts that pass the gate (edit-rate < threshold AND enough samples) to a gate
19
- file the active first-read path consults. With --write-events it writes
20
- opportunity-tier rows so the dashboard coverage panel reflects history.
21
-
22
- This is an offline analysis tool, NOT a hot-path hook: it may import freely.
23
- """
2
+ """Offline first-read shadow backfill. Edits are not a promotion signal."""
24
3
 
25
4
  from __future__ import annotations
26
5
 
@@ -309,11 +288,6 @@ def build_report(cohorts, totals, edit_window):
309
288
  n_sessions = len(c["sessions"])
310
289
  edit_rate = (c["edited_within"] / reads) if reads else 0.0
311
290
  avg_ratio = (c["ratio_sum"] / reads) if reads else 0.0
312
- passes = (
313
- reads >= PROMOTION_MIN_SAMPLES
314
- and n_sessions >= PROMOTION_MIN_SESSIONS
315
- and edit_rate < PROMOTION_EDIT_RATE
316
- )
317
291
  rows.append({
318
292
  "language": lang,
319
293
  "size_band": band,
@@ -324,14 +298,12 @@ def build_report(cohorts, totals, edit_window):
324
298
  "edit_rate_pct": round(100 * edit_rate, 1),
325
299
  "avg_would_be_ratio_pct": round(100 * avg_ratio, 1),
326
300
  "would_be_tokens": c["would_be_tokens"],
327
- "promotion_ready": passes,
301
+ "promotion_ready": False,
328
302
  })
329
303
  report = {
330
304
  "edit_window_turns": edit_window,
331
305
  "metric": "first-read-only per session",
332
- "promotion_gate": {"edit_rate_pct": 100 * PROMOTION_EDIT_RATE,
333
- "min_samples": PROMOTION_MIN_SAMPLES,
334
- "min_sessions": PROMOTION_MIN_SESSIONS},
306
+ "promotion_gate": {"mode": "shadow", "edit_rate_is_harm": False},
335
307
  "totals": totals,
336
308
  "cohorts": rows,
337
309
  }
@@ -350,11 +322,8 @@ def print_report(report):
350
322
  print(f" Eligible (large, structure-supported, >={int(MIN_RATIO*100)}% win): {t['eligible']:,}")
351
323
  print(f" Skipped — small: {t['skipped_small']:,} too big: {t['skipped_big']:,} "
352
324
  f"unsupported: {t['skipped_unsupported']:,} low-win/ineligible: {t['skipped_ineligible']:,}")
353
- g = report["promotion_gate"]
354
325
  print(f"\n Metric: {report['metric']}")
355
- print(f" Promotion gate: edit-rate < {g['edit_rate_pct']:.0f}% within "
356
- f"{report['edit_window_turns']} turns AND >= {g['min_samples']} first-reads "
357
- f"across >= {g['min_sessions']} sessions\n")
326
+ print(" Edit rates are descriptive only and do not establish promotion safety.\n")
358
327
  if not report["cohorts"]:
359
328
  print(" No eligible cohorts found.")
360
329
  return
@@ -206,9 +206,7 @@ def _extract_decisions(text: str, store: SessionStore) -> None:
206
206
 
207
207
  Uses split-then-filter to avoid catastrophic regex backtracking on
208
208
  large outputs without sentence-ending punctuation (build logs, JSON).
209
- Uses SessionStore's auto-commit get_meta/set_meta (no explicit transaction)
210
- to avoid conflicting with the implicit transaction from log_tool_use on
211
- the same shared connection.
209
+ SessionStore merges redacted decisions atomically through its durable queue.
212
210
  """
213
211
  if len(text) < 50:
214
212
  return
@@ -245,6 +243,10 @@ def _extract_decisions(text: str, store: SessionStore) -> None:
245
243
  return
246
244
 
247
245
  try:
246
+ if isinstance(store, SessionStore):
247
+ from _measure import session_store_spool
248
+ session_store_spool.enqueue(store, {"kind": "decisions", "decisions": new_decisions})
249
+ return
248
250
  existing_raw = store.get_meta("session_decisions")
249
251
  existing = json.loads(existing_raw) if existing_raw else []
250
252
 
@@ -48,6 +48,8 @@ _PAYLOAD_MODULES = (
48
48
  "copilot_vscode.py",
49
49
  "bash_hook.py",
50
50
  "bash_compress.py",
51
+ "post_run_classify.py",
52
+ "preserved_reinject.py",
51
53
  "bash_search_results.py",
52
54
  # Dependency-free whitelist gate shared by bash_hook + bash_compress.
53
55
  "bash_whitelist.py",
@@ -0,0 +1,261 @@
1
+ #!/usr/bin/env python3
2
+ """Token Optimizer - Bash coverage funnel (counters only, no behaviour change).
3
+
4
+ Every Bash result that reaches the PostToolUse hook ends in exactly one of five
5
+ gates. This module owns the gate vocabulary, a pure classifier that replays the
6
+ hook's own gate order on a (command, output) pair, and a tiny fail-open row
7
+ writer for the hook. It never changes what the model sees.
8
+
9
+ Gates (the order the hook applies them):
10
+ error_or_short empty/under 100 chars, failed command, or error words in
11
+ the output. These stay raw by design.
12
+ already_compressed carries Token Optimizer's own marker (PreToolUse got there).
13
+ not_read_only the command is not a read-only pipeline, so no compressor
14
+ was consulted. ``reason`` holds the reject category.
15
+ under_10pct a compressor ran and found under 10% to remove.
16
+ compressed the output was replaced by a smaller one.
17
+
18
+ Privacy: a row holds the gate, a fixed-vocabulary reason, the compressor pattern
19
+ name, and two token counts. No command text and no output text is stored.
20
+ The classifier is stdlib-only and imports the heavy modules lazily so the hook
21
+ path pays nothing for the replay code.
22
+ """
23
+ from __future__ import annotations
24
+
25
+ import os
26
+ import random
27
+ import re
28
+ import sqlite3
29
+ from datetime import datetime, timedelta
30
+ from pathlib import Path
31
+
32
+ GATES = ("not_read_only", "under_10pct", "already_compressed", "compressed", "error_or_short")
33
+
34
+ GATE_LABELS = {
35
+ "not_read_only": "Command shape not eligible",
36
+ "under_10pct": "Compressor found under 10% to remove",
37
+ "already_compressed": "Already compressed",
38
+ "compressed": "Compressed",
39
+ "error_or_short": "Error words, failed command, or under 100 chars",
40
+ }
41
+
42
+ # Fine-grained reasons for error_or_short, so the five-way split stays honest.
43
+ SHORT_REASONS = ("short", "failed_command", "error_words")
44
+
45
+ _MIN_CHARS = 100
46
+ _MIN_REMOVED_SHARE = 0.10
47
+ _DB_TIMEOUT_SECONDS = 0.05
48
+ _DB_BUSY_TIMEOUT_MS = 50
49
+ _RETENTION_DAYS = 120
50
+ _PRUNE_ODDS = 200
51
+
52
+ _SCHEMA = """
53
+ CREATE TABLE IF NOT EXISTS bash_coverage (
54
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
55
+ timestamp TEXT NOT NULL,
56
+ session_uuid TEXT,
57
+ gate TEXT NOT NULL,
58
+ reason TEXT,
59
+ pattern TEXT,
60
+ tokens INTEGER DEFAULT 0,
61
+ removed_tokens INTEGER DEFAULT 0
62
+ );
63
+ CREATE INDEX IF NOT EXISTS idx_bash_coverage_ts ON bash_coverage(timestamp);
64
+ """
65
+
66
+ _UUID_PAT = re.compile(
67
+ r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$", re.IGNORECASE)
68
+ _REASON_SAFE = re.compile(r"[^a-z0-9_-]+")
69
+ _STAGE_PREFIX = re.compile(r"^stage-\d+:")
70
+
71
+
72
+ def reject_category(reason) -> str:
73
+ """Reduce pipeline_analyzer's reject reason to a command-free category.
74
+
75
+ ``glued-operator-in-token:;`` -> ``glued-operator-in-token``;
76
+ ``stage-1:not-whitelisted:cd`` -> ``not-whitelisted``. Anything after the
77
+ first colon can carry a token of the user's command, so it is dropped.
78
+ """
79
+ text = _STAGE_PREFIX.sub("", str(reason or "").strip()).split(":", 1)[0].strip().lower()
80
+ text = _REASON_SAFE.sub("-", text).strip("-")
81
+ return text[:48] or "unknown"
82
+
83
+
84
+ _SAMPLE_CHARS = 16384
85
+
86
+
87
+ def tokens_of(text: str) -> int:
88
+ """Token estimate that stays cheap on the hook path.
89
+
90
+ The shared estimator is instant on ASCII but walks non-ASCII text one
91
+ character at a time (about 1 ms per 1,000 characters), which would put a
92
+ large Hebrew or CJK output over the hook budget for a counter. Past
93
+ ``_SAMPLE_CHARS`` such text is estimated from its head and scaled. The hook
94
+ and the replay both use this, so their figures agree.
95
+ """
96
+ if not text:
97
+ return 0
98
+ try:
99
+ from token_estimate import estimate_tokens
100
+ if len(text) <= _SAMPLE_CHARS or text.isascii():
101
+ return int(estimate_tokens(text))
102
+ return int(estimate_tokens(text[:_SAMPLE_CHARS]) * len(text) / _SAMPLE_CHARS)
103
+ except Exception:
104
+ return len(text.encode("utf-8", errors="replace")) // 4
105
+
106
+
107
+ _tokens = tokens_of
108
+
109
+
110
+ def _already_compressed(output: str) -> bool:
111
+ return "[Full result archived" in output or "[bash_compress]" in output
112
+
113
+
114
+ def classify_result(command: str, output: str, is_error: bool = False) -> dict:
115
+ """Replay the hook's gate order on one finished Bash result. Read-only.
116
+
117
+ Returns ``{"gate", "reason", "pattern", "tokens", "removed"}``. Nothing is
118
+ archived, logged, or emitted. ``is_error`` stands in for a non-zero exit
119
+ code, which transcripts record only as a flag.
120
+ """
121
+ output = output if isinstance(output, str) else ""
122
+ command = command if isinstance(command, str) else ""
123
+ tokens = _tokens(output)
124
+ row = {"gate": "error_or_short", "reason": "short", "pattern": "",
125
+ "tokens": tokens, "removed": 0}
126
+ if len(output) < _MIN_CHARS:
127
+ return row
128
+ if _already_compressed(output):
129
+ row.update(gate="already_compressed", reason="marker")
130
+ return row
131
+ try:
132
+ from post_run_classify import unsafe_compound_output
133
+ if unsafe_compound_output(command):
134
+ row.update(gate="not_read_only", reason="mixed_output")
135
+ return row
136
+ except Exception:
137
+ pass # the hook fails open on this check too
138
+ compress_command = command
139
+ try:
140
+ from pipeline_analyzer import is_read_only_pipeline
141
+ is_ro, why = is_read_only_pipeline(command)
142
+ except Exception:
143
+ is_ro, why = False, "analyzer-error"
144
+ if not is_ro:
145
+ # Same step as the hook: a harmless prefix (`cd /p;`, `export X=1 &&`)
146
+ # does not hide the command from its pattern-specific compressor.
147
+ try:
148
+ from post_run_classify import eligible_effective, mode as _prc_mode
149
+ if _prc_mode() == "on":
150
+ effective = eligible_effective(command)
151
+ if effective is not None:
152
+ is_ro, compress_command = True, effective
153
+ except Exception:
154
+ pass
155
+ from bash_compress import _strip_ansi
156
+ cleaned = _strip_ansi(output)
157
+ if not is_ro:
158
+ built = _build_removed(command, cleaned)
159
+ if built is not None:
160
+ row.update(gate="compressed", reason="build_output", pattern="build_output",
161
+ removed=built)
162
+ return row
163
+ row.update(gate="not_read_only", reason=reject_category(why))
164
+ return row
165
+ from bash_compress import _looks_like_failure, _detect_pattern, compress
166
+ if _looks_like_failure(1 if is_error else 0, ""):
167
+ row.update(reason="failed_command")
168
+ return row
169
+ from bash_compress_hook import _stdout_has_error_patterns
170
+ if _stdout_has_error_patterns(cleaned):
171
+ row.update(reason="error_words")
172
+ return row
173
+ pattern = _safe_pattern(_detect_pattern, command)
174
+ row["pattern"] = pattern
175
+ try:
176
+ packed = compress(compress_command, cleaned, returncode=0, stderr="")
177
+ packed = packed if isinstance(packed, str) else (
178
+ packed[0] if isinstance(packed, (tuple, list)) and packed else str(packed))
179
+ except Exception:
180
+ row.update(gate="under_10pct", reason="compressor_error")
181
+ return row
182
+ before, after = _tokens(cleaned), _tokens(packed)
183
+ if packed and packed != cleaned and before and (1.0 - after / before) >= _MIN_REMOVED_SHARE:
184
+ row.update(gate="compressed", reason="read_only", removed=max(0, before - after))
185
+ return row
186
+ row.update(gate="under_10pct", reason="read_only")
187
+ return row
188
+
189
+
190
+ def _safe_pattern(detect, command) -> str:
191
+ try:
192
+ return str(detect(command) or "")[:40]
193
+ except Exception:
194
+ return ""
195
+
196
+
197
+ def _build_removed(command: str, cleaned: str):
198
+ """Tokens the build/test compressor would remove, or None. No side effects."""
199
+ if len(cleaned.splitlines()) < 25:
200
+ return None
201
+ try:
202
+ from build_output_compress import classify, classify_by_shape, compress as build_compress
203
+ if not (classify(command) or classify_by_shape(cleaned, command)):
204
+ return None
205
+ packed = build_compress(command, cleaned)
206
+ if not packed or packed == cleaned:
207
+ return None
208
+ before, after = _tokens(cleaned), _tokens(packed)
209
+ if before and (1.0 - after / before) >= _MIN_REMOVED_SHARE:
210
+ return max(0, before - after)
211
+ except Exception:
212
+ return None
213
+ return None
214
+
215
+
216
+ def _snapshot_dir() -> Path:
217
+ from plugin_env import resolve_snapshot_dir
218
+ return resolve_snapshot_dir()
219
+
220
+
221
+ def _session_uuid(session_id):
222
+ return session_id if session_id and _UUID_PAT.match(session_id) else None
223
+
224
+
225
+ def record(gate: str, reason: str = "", pattern: str = "", tokens: int = 0,
226
+ removed: int = 0, session_id: str | None = None,
227
+ snapshot_dir: Path | None = None) -> None:
228
+ """Write one counter row. Fail-open: never raises, never blocks the hook."""
229
+ if gate not in GATES:
230
+ return
231
+ conn = None
232
+ try:
233
+ directory = Path(snapshot_dir) if snapshot_dir is not None else _snapshot_dir()
234
+ directory.mkdir(parents=True, exist_ok=True, mode=0o700)
235
+ db = directory / "trends.db"
236
+ conn = sqlite3.connect(str(db), timeout=_DB_TIMEOUT_SECONDS)
237
+ conn.execute(f"PRAGMA busy_timeout={_DB_BUSY_TIMEOUT_MS}")
238
+ conn.execute("PRAGMA synchronous=NORMAL")
239
+ conn.executescript(_SCHEMA)
240
+ conn.execute(
241
+ "INSERT INTO bash_coverage (timestamp, session_uuid, gate, reason, pattern, tokens, removed_tokens) "
242
+ "VALUES (?, ?, ?, ?, ?, ?, ?)",
243
+ (datetime.now().isoformat(), _session_uuid(session_id), gate,
244
+ reject_category(reason) if reason else "", _REASON_SAFE.sub("_", pattern.lower())[:40],
245
+ max(0, int(tokens)), max(0, int(removed))))
246
+ if random.randrange(_PRUNE_ODDS) == 0:
247
+ cutoff = (datetime.now() - timedelta(days=_RETENTION_DAYS)).isoformat()
248
+ conn.execute("DELETE FROM bash_coverage WHERE timestamp < ?", (cutoff,))
249
+ conn.commit()
250
+ try:
251
+ os.chmod(str(db), 0o600)
252
+ except OSError:
253
+ pass
254
+ except Exception:
255
+ pass
256
+ finally:
257
+ if conn is not None:
258
+ try:
259
+ conn.close()
260
+ except Exception:
261
+ pass
@@ -54,6 +54,8 @@ _PAYLOAD_MODULES = (
54
54
  "cursor_quality.py",
55
55
  "bash_hook.py",
56
56
  "bash_compress.py",
57
+ "post_run_classify.py",
58
+ "preserved_reinject.py",
57
59
  "bash_search_results.py",
58
60
  # Dependency-free whitelist gate shared by bash_hook + bash_compress.
59
61
  "bash_whitelist.py",
@@ -102,12 +104,22 @@ _PAYLOAD_MODULES = (
102
104
  "cursor_thrash.py",
103
105
  "thrash_guard.py",
104
106
  "session_store.py",
107
+ "session_store_guard.py",
108
+ "hint_paths.py", # session_store imports it at module load
105
109
  "delta_diff.py",
106
110
  "archive_result.py",
107
111
  "recovery_output.py",
108
112
  "refetch_fingerprint.py",
109
113
  "reset_epoch.py",
110
114
  "token_estimate.py",
115
+ # session_store queues contended writes through the spool and publishes
116
+ # reset markers; both live in the _measure package.
117
+ "_measure/__init__.py",
118
+ "_measure/session_store_spool.py",
119
+ "_measure/lease_candidate_cleanup.py",
120
+ "_measure/context_reset_marker.py",
121
+ "hook_provenance.py",
122
+ "shipped_hook_templates.py", # hook_provenance imports it at module load
111
123
  "cursor_transcript.py",
112
124
  )
113
125