@alexgreensh/token-optimizer 5.13.68 → 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/fleet-auditor/references/fleet-systems.md +38 -0
- package/skills/fleet-auditor/scripts/fleet.py +63 -92
- package/skills/fleet-auditor/scripts/fleet_base.py +106 -0
- package/skills/fleet-auditor/scripts/fleet_cursor_adapter.py +376 -0
- package/skills/token-coach/SKILL.md +21 -23
- package/skills/token-dashboard/SKILL.md +5 -4
- package/skills/token-optimizer/SKILL.md +1 -1
- package/skills/token-optimizer/assets/dashboard.html +492 -551
- package/skills/token-optimizer/assets/savings_story.js +661 -0
- package/skills/token-optimizer/pricing/prices.json +1 -0
- package/skills/token-optimizer/references/cli-reference.md +1 -1
- package/skills/token-optimizer/references/cursor-workflow.md +1 -1
- package/skills/token-optimizer/references/implementation-playbook.md +3 -0
- package/skills/token-optimizer/references/phase0-setup.md +1 -1
- package/skills/token-optimizer/references/presentation-workflow.md +1 -1
- 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 +98 -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 +61 -94
- package/skills/token-optimizer/scripts/_measure/dashboard.py +149 -187
- package/skills/token-optimizer/scripts/_measure/dashboard_heal_claim.py +36 -0
- package/skills/token-optimizer/scripts/_measure/dashboard_history.py +79 -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 +59 -168
- 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 +451 -933
- 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 +154 -216
- 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/_measure/weekly_activity.py +69 -0
- package/skills/token-optimizer/scripts/activity_tracker.py +4 -33
- package/skills/token-optimizer/scripts/antigravity_install.py +6 -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 +22 -83
- package/skills/token-optimizer/scripts/bash_compress_hook.py +137 -1
- package/skills/token-optimizer/scripts/bash_search_results.py +43 -0
- 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 +6 -0
- package/skills/token-optimizer/scripts/coverage_funnel.py +261 -0
- package/skills/token-optimizer/scripts/credential_patterns.py +4 -19
- package/skills/token-optimizer/scripts/credential_url_patterns.py +42 -0
- package/skills/token-optimizer/scripts/cursor_audit.py +723 -0
- package/skills/token-optimizer/scripts/cursor_bridge_checkpoint.py +213 -0
- package/skills/token-optimizer/scripts/cursor_bridge_payload.py +170 -0
- package/skills/token-optimizer/scripts/cursor_bridge_rewrite.py +106 -0
- package/skills/token-optimizer/scripts/cursor_bridge_rollup.py +115 -0
- package/skills/token-optimizer/scripts/cursor_coach.py +485 -0
- package/skills/token-optimizer/scripts/cursor_doctor.py +89 -9
- package/skills/token-optimizer/scripts/cursor_hook_bridge.py +393 -276
- package/skills/token-optimizer/scripts/cursor_install.py +118 -19
- package/skills/token-optimizer/scripts/cursor_quality.py +457 -0
- package/skills/token-optimizer/scripts/cursor_read_cache.py +597 -0
- package/skills/token-optimizer/scripts/cursor_session.py +26 -5
- package/skills/token-optimizer/scripts/cursor_state.py +8 -0
- package/skills/token-optimizer/scripts/cursor_statusline.py +372 -0
- package/skills/token-optimizer/scripts/cursor_thrash.py +78 -0
- package/skills/token-optimizer/scripts/cursor_transcript.py +223 -0
- 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 +19 -4
- package/skills/token-optimizer/scripts/devin_verify.py +13 -6
- package/skills/token-optimizer/scripts/grok_install.py +6 -0
- package/skills/token-optimizer/scripts/heal_report.py +7 -6
- package/skills/token-optimizer/scripts/hermes_doctor.py +12 -1
- package/skills/token-optimizer/scripts/hermes_install.py +10 -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 +36 -78
- 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
- package/skills/token-optimizer/scripts/thrash_guard.py +10 -5
|
@@ -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
|
-
"""
|
|
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
|
-
|
|
144
|
-
|
|
145
|
-
head = handle.readline(65536)
|
|
138
|
+
import codex_log_index
|
|
139
|
+
values, _ = codex_log_index.records(path)
|
|
146
140
|
try:
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
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
|
-
|
|
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
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
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
|
-
"""
|
|
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":
|
|
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": {"
|
|
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(
|
|
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
|
-
|
|
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,9 @@ _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",
|
|
53
|
+
"bash_search_results.py",
|
|
51
54
|
# Dependency-free whitelist gate shared by bash_hook + bash_compress.
|
|
52
55
|
"bash_whitelist.py",
|
|
53
56
|
# command_filters + _tomli: user [filters.*] TOML config consulted by
|
|
@@ -75,6 +78,9 @@ _PAYLOAD_MODULES = (
|
|
|
75
78
|
# credential_patterns: bash_compress's credential-preservation patterns and
|
|
76
79
|
# copilot_session's topic redaction (both fall back to less without it).
|
|
77
80
|
"credential_patterns.py",
|
|
81
|
+
# credential_patterns imports this at module import time (URL family split
|
|
82
|
+
# under the 1,000-line ratchet); missing = import failure in the payload.
|
|
83
|
+
"credential_url_patterns.py",
|
|
78
84
|
)
|
|
79
85
|
|
|
80
86
|
|
|
@@ -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
|