@alexgreensh/token-optimizer 0.0.0-stage → 5.13.50
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 +76 -0
- package/.claude-plugin/plugin.json +21 -0
- package/LICENSE +130 -0
- package/LICENSE-SMALL-BUSINESS.md +62 -0
- package/PRIVACY.md +200 -0
- package/README.md +13 -2
- package/hooks/codex-hooks.json +4 -0
- package/hooks/hooks.json +182 -0
- package/hooks/module_runner.py +149 -0
- package/hooks/posttooluse_runner.py +1110 -0
- package/hooks/python-launcher.sh +816 -0
- package/hooks/run.py +776 -0
- package/hooks/sessionstart_runner.py +629 -0
- package/hooks/stop_runner.py +408 -0
- package/hooks/userpromptsubmit_runner.py +722 -0
- package/hooks/windows-launcher.py +163 -0
- package/install-cloud.sh +23 -0
- package/package.json +29 -4
- package/skills/fleet-auditor/SKILL.md +150 -0
- package/skills/fleet-auditor/references/fleet-systems.md +167 -0
- package/skills/fleet-auditor/references/report-template.md +50 -0
- package/skills/fleet-auditor/references/waste-patterns.md +126 -0
- package/skills/fleet-auditor/scripts/fleet.py +3612 -0
- package/skills/fleet-auditor/scripts/shared.py +277 -0
- package/skills/resume-checkpoint/SKILL.md +52 -0
- package/skills/resume-checkpoint/scripts/pull_checkpoint.py +188 -0
- package/skills/token-coach/SKILL.md +129 -0
- package/skills/token-coach/assets/coach-dashboard-tab.html +45 -0
- package/skills/token-coach/examples/coaching-session-agentic.md +62 -0
- package/skills/token-coach/examples/coaching-session-heavy-setup.md +46 -0
- package/skills/token-coach/examples/coaching-session-new-project.md +38 -0
- package/skills/token-coach/references/agentic-systems.md +147 -0
- package/skills/token-coach/references/coach-patterns.md +120 -0
- package/skills/token-coach/references/coaching-scripts.md +146 -0
- package/skills/token-coach/references/deterministic-stages.md +102 -0
- package/skills/token-coach/references/keepwarm-consent.md +48 -0
- package/skills/token-coach/references/quick-reference.md +155 -0
- package/skills/token-dashboard/SKILL.md +72 -0
- package/skills/token-optimizer/SKILL.md +150 -0
- package/skills/token-optimizer/assets/dashboard.html +7251 -0
- package/skills/token-optimizer/examples/claude-md-optimized.md +40 -0
- package/skills/token-optimizer/examples/hooks-starter.json +179 -0
- package/skills/token-optimizer/examples/permissions-deny-template.json +24 -0
- package/skills/token-optimizer/pricing/prices.json +695 -0
- package/skills/token-optimizer/references/agent-prompts.md +687 -0
- package/skills/token-optimizer/references/cli-reference.md +92 -0
- package/skills/token-optimizer/references/codex-workflow.md +188 -0
- package/skills/token-optimizer/references/cursor-workflow.md +74 -0
- package/skills/token-optimizer/references/error-recovery.md +37 -0
- package/skills/token-optimizer/references/implementation-playbook.md +416 -0
- package/skills/token-optimizer/references/keepwarm-consent.md +48 -0
- package/skills/token-optimizer/references/opencode-workflow.md +72 -0
- package/skills/token-optimizer/references/optimization-checklist.md +714 -0
- package/skills/token-optimizer/references/phase0-setup.md +142 -0
- package/skills/token-optimizer/references/presentation-workflow.md +72 -0
- package/skills/token-optimizer/references/session-continuity.md +19 -0
- package/skills/token-optimizer/references/token-flow-architecture.md +629 -0
- package/skills/token-optimizer/scripts/activity_tracker.py +143 -0
- package/skills/token-optimizer/scripts/antigravity_doctor.py +548 -0
- package/skills/token-optimizer/scripts/antigravity_hook_bridge.py +511 -0
- package/skills/token-optimizer/scripts/antigravity_install.py +376 -0
- package/skills/token-optimizer/scripts/antigravity_proto.py +413 -0
- package/skills/token-optimizer/scripts/antigravity_session.py +346 -0
- package/skills/token-optimizer/scripts/antigravity_state.py +486 -0
- package/skills/token-optimizer/scripts/archive_result.py +1725 -0
- package/skills/token-optimizer/scripts/bash_compress.py +2490 -0
- package/skills/token-optimizer/scripts/bash_compress_hook.py +766 -0
- package/skills/token-optimizer/scripts/bash_hook.py +61 -0
- package/skills/token-optimizer/scripts/bash_whitelist.py +243 -0
- package/skills/token-optimizer/scripts/benchmark.py +1765 -0
- package/skills/token-optimizer/scripts/build_output_compress.py +776 -0
- package/skills/token-optimizer/scripts/cloud_kit.py +991 -0
- package/skills/token-optimizer/scripts/codex_command_compress.py +434 -0
- package/skills/token-optimizer/scripts/codex_compact_prompt.py +273 -0
- package/skills/token-optimizer/scripts/codex_doctor.py +454 -0
- package/skills/token-optimizer/scripts/codex_hook_bridge.py +311 -0
- package/skills/token-optimizer/scripts/codex_install.py +810 -0
- package/skills/token-optimizer/scripts/codex_io.py +119 -0
- package/skills/token-optimizer/scripts/codex_log_index.py +219 -0
- package/skills/token-optimizer/scripts/codex_models.py +34 -0
- package/skills/token-optimizer/scripts/codex_session.py +1186 -0
- package/skills/token-optimizer/scripts/codex_state.py +707 -0
- package/skills/token-optimizer/scripts/codex_statusline.py +303 -0
- package/skills/token-optimizer/scripts/command_filters.py +386 -0
- package/skills/token-optimizer/scripts/compression_backfill.py +600 -0
- package/skills/token-optimizer/scripts/compression_log.py +230 -0
- package/skills/token-optimizer/scripts/context_intel.py +331 -0
- package/skills/token-optimizer/scripts/context_pressure.py +115 -0
- package/skills/token-optimizer/scripts/copilot_doctor.py +406 -0
- package/skills/token-optimizer/scripts/copilot_hook_bridge.py +709 -0
- package/skills/token-optimizer/scripts/copilot_install.py +277 -0
- package/skills/token-optimizer/scripts/copilot_session.py +496 -0
- package/skills/token-optimizer/scripts/copilot_state.py +569 -0
- package/skills/token-optimizer/scripts/copilot_vscode.py +832 -0
- package/skills/token-optimizer/scripts/cowork_doctor.py +270 -0
- package/skills/token-optimizer/scripts/cowork_install.py +380 -0
- package/skills/token-optimizer/scripts/credential_patterns.py +1514 -0
- package/skills/token-optimizer/scripts/cursor_doctor.py +602 -0
- package/skills/token-optimizer/scripts/cursor_hook_bridge.py +843 -0
- package/skills/token-optimizer/scripts/cursor_install.py +423 -0
- package/skills/token-optimizer/scripts/cursor_session.py +303 -0
- package/skills/token-optimizer/scripts/cursor_state.py +348 -0
- package/skills/token-optimizer/scripts/delta_diff.py +110 -0
- package/skills/token-optimizer/scripts/detectors/__init__.py +2 -0
- package/skills/token-optimizer/scripts/detectors/bad_decomposition.py +78 -0
- package/skills/token-optimizer/scripts/detectors/cache_instability.py +504 -0
- package/skills/token-optimizer/scripts/detectors/looping.py +88 -0
- package/skills/token-optimizer/scripts/detectors/output_waste.py +143 -0
- package/skills/token-optimizer/scripts/detectors/overpowered.py +116 -0
- package/skills/token-optimizer/scripts/detectors/pdf_ingestion.py +52 -0
- package/skills/token-optimizer/scripts/detectors/registry.py +65 -0
- package/skills/token-optimizer/scripts/detectors/respond_to_bash.py +76 -0
- package/skills/token-optimizer/scripts/detectors/retry_churn.py +83 -0
- package/skills/token-optimizer/scripts/detectors/tool_cascade.py +62 -0
- package/skills/token-optimizer/scripts/detectors/wasteful_thinking.py +75 -0
- package/skills/token-optimizer/scripts/detectors/weak_model.py +55 -0
- package/skills/token-optimizer/scripts/detectors/websearch_routing.py +72 -0
- package/skills/token-optimizer/scripts/deterministic_candidates.py +1458 -0
- package/skills/token-optimizer/scripts/devin_compress.py +790 -0
- package/skills/token-optimizer/scripts/devin_doctor.py +403 -0
- package/skills/token-optimizer/scripts/devin_hooks.py +453 -0
- package/skills/token-optimizer/scripts/devin_install.py +1086 -0
- package/skills/token-optimizer/scripts/devin_source.py +119 -0
- package/skills/token-optimizer/scripts/devin_state.py +330 -0
- package/skills/token-optimizer/scripts/devin_verify.py +67 -0
- package/skills/token-optimizer/scripts/grok_doctor.py +560 -0
- package/skills/token-optimizer/scripts/grok_hook_bridge.py +699 -0
- package/skills/token-optimizer/scripts/grok_install.py +397 -0
- package/skills/token-optimizer/scripts/grok_session.py +317 -0
- package/skills/token-optimizer/scripts/grok_state.py +299 -0
- package/skills/token-optimizer/scripts/hermes_doctor.py +479 -0
- package/skills/token-optimizer/scripts/hermes_hook_bridge.py +285 -0
- package/skills/token-optimizer/scripts/hermes_install.py +668 -0
- package/skills/token-optimizer/scripts/hermes_session.py +691 -0
- package/skills/token-optimizer/scripts/hermes_state.py +448 -0
- package/skills/token-optimizer/scripts/hook_io.py +120 -0
- package/skills/token-optimizer/scripts/hook_runtime.py +713 -0
- package/skills/token-optimizer/scripts/injection.py +156 -0
- package/skills/token-optimizer/scripts/install_reconcile.py +952 -0
- package/skills/token-optimizer/scripts/measure.py +58739 -0
- package/skills/token-optimizer/scripts/outline.py +53 -0
- package/skills/token-optimizer/scripts/pipeline_analyzer.py +723 -0
- package/skills/token-optimizer/scripts/plugin_env.py +562 -0
- package/skills/token-optimizer/scripts/py_trust.py +80 -0
- package/skills/token-optimizer/scripts/quality_cache_gate.py +320 -0
- package/skills/token-optimizer/scripts/read_cache.py +2489 -0
- package/skills/token-optimizer/scripts/recovery_output.py +110 -0
- package/skills/token-optimizer/scripts/refetch_fingerprint.py +236 -0
- package/skills/token-optimizer/scripts/refetch_guard.py +244 -0
- package/skills/token-optimizer/scripts/routing_advisor.py +389 -0
- package/skills/token-optimizer/scripts/runtime_env.py +1893 -0
- package/skills/token-optimizer/scripts/session_store.py +979 -0
- package/skills/token-optimizer/scripts/spawn_utils.py +122 -0
- package/skills/token-optimizer/scripts/statusline.js +660 -0
- package/skills/token-optimizer/scripts/structure_map.py +2880 -0
- package/skills/token-optimizer/scripts/structure_map_ts.py +676 -0
- package/skills/token-optimizer/scripts/structure_replay.py +1556 -0
- package/skills/token-optimizer/scripts/thrash_guard.py +604 -0
- package/skills/token-optimizer/scripts/token_estimate.py +80 -0
- package/skills/token-optimizer/scripts/tool_search_diagnostic.py +61 -0
- package/skills/token-optimizer/scripts/utf8_io.py +219 -0
|
@@ -0,0 +1,1556 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""
|
|
3
|
+
Offline proof runner for structure-aware compression.
|
|
4
|
+
|
|
5
|
+
This script replays local Claude session JSONL transcripts and optional
|
|
6
|
+
read-cache decision logs, then simulates a conservative Python-only
|
|
7
|
+
structure-map replacement for redundant whole-file rereads.
|
|
8
|
+
|
|
9
|
+
Goals:
|
|
10
|
+
- stdlib only
|
|
11
|
+
- no remote telemetry
|
|
12
|
+
- separate transcript and decision-log summaries to avoid double counting
|
|
13
|
+
- conservative eligibility checks to avoid overstating savings
|
|
14
|
+
- compact proof metrics for before/after reporting
|
|
15
|
+
|
|
16
|
+
Usage examples:
|
|
17
|
+
python3 structure_replay.py
|
|
18
|
+
python3 structure_replay.py ~/.claude/projects/.../session.jsonl
|
|
19
|
+
python3 structure_replay.py --json ~/.claude/projects .../read-cache/decisions
|
|
20
|
+
python3 structure_replay.py --torture
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
from __future__ import annotations
|
|
24
|
+
|
|
25
|
+
import argparse
|
|
26
|
+
import glob
|
|
27
|
+
import hashlib
|
|
28
|
+
import os
|
|
29
|
+
import json
|
|
30
|
+
import re
|
|
31
|
+
import sys
|
|
32
|
+
import tempfile
|
|
33
|
+
from collections import Counter, defaultdict
|
|
34
|
+
from dataclasses import dataclass, field
|
|
35
|
+
from datetime import datetime, timezone
|
|
36
|
+
from pathlib import Path
|
|
37
|
+
from typing import Any, Dict, Iterator, List, Optional, Sequence, Tuple
|
|
38
|
+
|
|
39
|
+
from runtime_env import claude_home
|
|
40
|
+
from structure_map import (
|
|
41
|
+
StructureMapResult,
|
|
42
|
+
estimate_tokens,
|
|
43
|
+
is_python_file,
|
|
44
|
+
is_structure_supported_file,
|
|
45
|
+
summarize_code_source,
|
|
46
|
+
)
|
|
47
|
+
|
|
48
|
+
DEFAULT_MIN_FILE_TOKENS = 1000
|
|
49
|
+
DEFAULT_MAX_BYTES = 400 * 1024
|
|
50
|
+
DEFAULT_MAX_LINES = 5000
|
|
51
|
+
DEFAULT_STRUCTURE_CAPS = {
|
|
52
|
+
"signatures": 500,
|
|
53
|
+
"top_level": 700,
|
|
54
|
+
"skeleton": 1200,
|
|
55
|
+
}
|
|
56
|
+
DEFAULT_REMINDER_OVERHEAD_TOKENS = 20
|
|
57
|
+
DEFAULT_REASON_ONLY_OVERHEAD_TOKENS = 10
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
@dataclass
|
|
61
|
+
class ReplayEvent:
|
|
62
|
+
source_path: Path
|
|
63
|
+
source_kind: str # "transcript" or "decision_log"
|
|
64
|
+
session_id: str
|
|
65
|
+
timestamp: str
|
|
66
|
+
order: int
|
|
67
|
+
event_kind: str # "read", "edit", "write", "decision"
|
|
68
|
+
raw_file_path: str
|
|
69
|
+
normalized_file_path: str
|
|
70
|
+
tool_use_id: str = ""
|
|
71
|
+
cwd: str = ""
|
|
72
|
+
offset: int = 0
|
|
73
|
+
limit: int = 0
|
|
74
|
+
pages: str = ""
|
|
75
|
+
decision: str = ""
|
|
76
|
+
reason: str = ""
|
|
77
|
+
tokens_est_hint: Optional[int] = None
|
|
78
|
+
replacement_tokens_est: Optional[int] = None
|
|
79
|
+
net_saved_tokens_est: Optional[int] = None
|
|
80
|
+
repeat_replacement_count: int = 0
|
|
81
|
+
actual_substitution: bool = False
|
|
82
|
+
read_result_text: str = ""
|
|
83
|
+
read_result_tokens_est: Optional[int] = None
|
|
84
|
+
read_result_total_lines: Optional[int] = None
|
|
85
|
+
read_result_start_line: Optional[int] = None
|
|
86
|
+
read_result_num_lines: Optional[int] = None
|
|
87
|
+
is_error: bool = False
|
|
88
|
+
event_id: str = ""
|
|
89
|
+
|
|
90
|
+
@property
|
|
91
|
+
def is_whole_file(self) -> bool:
|
|
92
|
+
return self.event_kind == "read" and self.offset == 0 and self.limit == 0 and not self.pages
|
|
93
|
+
|
|
94
|
+
@property
|
|
95
|
+
def read_signature(self) -> Tuple[int, int, str]:
|
|
96
|
+
return (self.offset, self.limit, self.pages or "")
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
@dataclass
|
|
100
|
+
class FileSnapshot:
|
|
101
|
+
path: Path
|
|
102
|
+
exists: bool
|
|
103
|
+
provenance: str = "disk"
|
|
104
|
+
stat_key: str = ""
|
|
105
|
+
size_bytes: int = 0
|
|
106
|
+
line_count: int = 0
|
|
107
|
+
mtime_ns: int = 0
|
|
108
|
+
sha256: str = ""
|
|
109
|
+
tokens_est: int = 0
|
|
110
|
+
text: str = ""
|
|
111
|
+
generated_like: bool = False
|
|
112
|
+
parse_error: str = ""
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
@dataclass
|
|
116
|
+
class ReplayFileStats:
|
|
117
|
+
source_path: str
|
|
118
|
+
normalized_file_path: str
|
|
119
|
+
session_id: str
|
|
120
|
+
total_reads: int = 0
|
|
121
|
+
whole_file_reads: int = 0
|
|
122
|
+
redundant_candidates: int = 0
|
|
123
|
+
eligible_replacements: int = 0
|
|
124
|
+
repeat_replacements: int = 0
|
|
125
|
+
verified_replacements: int = 0
|
|
126
|
+
skipped: Counter = field(default_factory=Counter)
|
|
127
|
+
baseline_tokens: int = 0
|
|
128
|
+
structure_tokens: int = 0
|
|
129
|
+
reminder_tokens: int = 0
|
|
130
|
+
reason_only_tokens: int = 0
|
|
131
|
+
net_saved_tokens: int = 0
|
|
132
|
+
directional_baseline_tokens: int = 0
|
|
133
|
+
directional_saved_tokens: int = 0
|
|
134
|
+
historical_result_backed: int = 0
|
|
135
|
+
current_disk_fallbacks: int = 0
|
|
136
|
+
replacement_followups: int = 0
|
|
137
|
+
replacement_different_range_followups: int = 0
|
|
138
|
+
error_replacement_attempts: int = 0
|
|
139
|
+
replacement_fingerprints: set = field(default_factory=set)
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
@dataclass
|
|
143
|
+
class ReplaySummary:
|
|
144
|
+
source_kind: str
|
|
145
|
+
source_count: int = 0
|
|
146
|
+
sessions: int = 0
|
|
147
|
+
total_events: int = 0
|
|
148
|
+
read_events: int = 0
|
|
149
|
+
edit_events: int = 0
|
|
150
|
+
candidate_events: int = 0
|
|
151
|
+
eligible_replacements: int = 0
|
|
152
|
+
repeat_replacements: int = 0
|
|
153
|
+
verified_replacements: int = 0
|
|
154
|
+
baseline_tokens: int = 0
|
|
155
|
+
structure_tokens: int = 0
|
|
156
|
+
reminder_tokens: int = 0
|
|
157
|
+
reason_only_tokens: int = 0
|
|
158
|
+
net_saved_tokens: int = 0
|
|
159
|
+
directional_baseline_tokens: int = 0
|
|
160
|
+
directional_saved_tokens: int = 0
|
|
161
|
+
historical_result_backed: int = 0
|
|
162
|
+
current_disk_fallbacks: int = 0
|
|
163
|
+
skipped: Counter = field(default_factory=Counter)
|
|
164
|
+
files: Dict[str, ReplayFileStats] = field(default_factory=dict)
|
|
165
|
+
sessions_seen: set = field(default_factory=set)
|
|
166
|
+
|
|
167
|
+
def add_file_stats(self, stats: ReplayFileStats) -> None:
|
|
168
|
+
self.files[stats.normalized_file_path] = stats
|
|
169
|
+
self.eligible_replacements += stats.eligible_replacements
|
|
170
|
+
self.repeat_replacements += stats.repeat_replacements
|
|
171
|
+
self.verified_replacements += stats.verified_replacements
|
|
172
|
+
self.baseline_tokens += stats.baseline_tokens
|
|
173
|
+
self.structure_tokens += stats.structure_tokens
|
|
174
|
+
self.reminder_tokens += stats.reminder_tokens
|
|
175
|
+
self.reason_only_tokens += stats.reason_only_tokens
|
|
176
|
+
self.net_saved_tokens += stats.net_saved_tokens
|
|
177
|
+
self.directional_baseline_tokens += stats.directional_baseline_tokens
|
|
178
|
+
self.directional_saved_tokens += stats.directional_saved_tokens
|
|
179
|
+
self.historical_result_backed += stats.historical_result_backed
|
|
180
|
+
self.current_disk_fallbacks += stats.current_disk_fallbacks
|
|
181
|
+
self.skipped.update(stats.skipped)
|
|
182
|
+
self.sessions_seen.add(stats.session_id)
|
|
183
|
+
|
|
184
|
+
@property
|
|
185
|
+
def capture_rate(self) -> float:
|
|
186
|
+
if self.candidate_events == 0:
|
|
187
|
+
return 0.0
|
|
188
|
+
return self.eligible_replacements / self.candidate_events
|
|
189
|
+
|
|
190
|
+
@property
|
|
191
|
+
def repeat_share(self) -> float:
|
|
192
|
+
if self.eligible_replacements == 0:
|
|
193
|
+
return 0.0
|
|
194
|
+
return self.repeat_replacements / self.eligible_replacements
|
|
195
|
+
|
|
196
|
+
@property
|
|
197
|
+
def savings_rate(self) -> float:
|
|
198
|
+
if self.baseline_tokens == 0:
|
|
199
|
+
return 0.0
|
|
200
|
+
return self.net_saved_tokens / self.baseline_tokens
|
|
201
|
+
|
|
202
|
+
@property
|
|
203
|
+
def directional_savings_rate(self) -> float:
|
|
204
|
+
if self.directional_baseline_tokens == 0:
|
|
205
|
+
return 0.0
|
|
206
|
+
return self.directional_saved_tokens / self.directional_baseline_tokens
|
|
207
|
+
|
|
208
|
+
@property
|
|
209
|
+
def replacement_events(self) -> int:
|
|
210
|
+
return self.eligible_replacements + self.repeat_replacements
|
|
211
|
+
|
|
212
|
+
@property
|
|
213
|
+
def followup_rate(self) -> float:
|
|
214
|
+
replacement_events = self.replacement_events
|
|
215
|
+
if replacement_events == 0:
|
|
216
|
+
return 0.0
|
|
217
|
+
total_followups = sum(stats.replacement_followups for stats in self.files.values())
|
|
218
|
+
return total_followups / replacement_events
|
|
219
|
+
|
|
220
|
+
@property
|
|
221
|
+
def false_block_proxy_rate(self) -> float:
|
|
222
|
+
replacement_events = self.replacement_events
|
|
223
|
+
if replacement_events == 0:
|
|
224
|
+
return 0.0
|
|
225
|
+
total_followups = sum(
|
|
226
|
+
stats.replacement_different_range_followups for stats in self.files.values()
|
|
227
|
+
)
|
|
228
|
+
return total_followups / replacement_events
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def _safe_int(value: Any, default: int = 0) -> int:
|
|
232
|
+
if value is None:
|
|
233
|
+
return default
|
|
234
|
+
try:
|
|
235
|
+
return int(float(value))
|
|
236
|
+
except (TypeError, ValueError, OverflowError):
|
|
237
|
+
return default
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def _normalize_session_id(value: Any, fallback: str = "unknown") -> str:
|
|
241
|
+
if value is None:
|
|
242
|
+
return fallback
|
|
243
|
+
text = str(value).strip()
|
|
244
|
+
return text or fallback
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def _normalize_path_text(value: Any) -> str:
|
|
248
|
+
if value is None:
|
|
249
|
+
return ""
|
|
250
|
+
text = str(value).strip()
|
|
251
|
+
if not text:
|
|
252
|
+
return ""
|
|
253
|
+
return str(Path(text).expanduser())
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def _normalize_file_path(value: Any) -> str:
|
|
257
|
+
return _normalize_path_text(value)
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def _normalize_timestamp(value: Any) -> str:
|
|
261
|
+
if value is None:
|
|
262
|
+
return ""
|
|
263
|
+
if isinstance(value, (int, float)):
|
|
264
|
+
try:
|
|
265
|
+
return datetime.fromtimestamp(float(value), tz=timezone.utc).isoformat()
|
|
266
|
+
except (OverflowError, ValueError):
|
|
267
|
+
return str(value)
|
|
268
|
+
return str(value)
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
def _iter_jsonl_records(path: Path) -> Iterator[Tuple[int, dict]]:
|
|
272
|
+
try:
|
|
273
|
+
with path.open("r", encoding="utf-8") as fh:
|
|
274
|
+
for index, line in enumerate(fh, 1):
|
|
275
|
+
line = line.strip()
|
|
276
|
+
if not line:
|
|
277
|
+
continue
|
|
278
|
+
try:
|
|
279
|
+
obj = json.loads(line)
|
|
280
|
+
except json.JSONDecodeError:
|
|
281
|
+
continue
|
|
282
|
+
if isinstance(obj, dict):
|
|
283
|
+
yield index, obj
|
|
284
|
+
except OSError:
|
|
285
|
+
return
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
def _walk_values(value: Any) -> Iterator[dict]:
|
|
289
|
+
if isinstance(value, dict):
|
|
290
|
+
yield value
|
|
291
|
+
for nested in value.values():
|
|
292
|
+
yield from _walk_values(nested)
|
|
293
|
+
elif isinstance(value, list):
|
|
294
|
+
for item in value:
|
|
295
|
+
yield from _walk_values(item)
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
def _looks_like_tool_use(obj: dict) -> bool:
|
|
299
|
+
name = obj.get("name")
|
|
300
|
+
input_obj = obj.get("input")
|
|
301
|
+
return isinstance(name, str) and isinstance(input_obj, dict)
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
def _tool_name(obj: dict) -> str:
|
|
305
|
+
return str(obj.get("name") or "").strip()
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
def _extract_file_path(input_obj: dict) -> str:
|
|
309
|
+
for key in ("file_path", "path", "file", "filename"):
|
|
310
|
+
value = input_obj.get(key)
|
|
311
|
+
if value:
|
|
312
|
+
return _normalize_file_path(value)
|
|
313
|
+
return ""
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
def _extract_read_fields(input_obj: dict) -> Tuple[int, int, str]:
|
|
317
|
+
offset = _safe_int(input_obj.get("offset"), 0)
|
|
318
|
+
limit = _safe_int(input_obj.get("limit"), 0)
|
|
319
|
+
pages = ""
|
|
320
|
+
if "pages" in input_obj and input_obj.get("pages") is not None:
|
|
321
|
+
pages = str(input_obj.get("pages")).strip()
|
|
322
|
+
elif "page" in input_obj and input_obj.get("page") is not None:
|
|
323
|
+
pages = str(input_obj.get("page")).strip()
|
|
324
|
+
return offset, limit, pages
|
|
325
|
+
|
|
326
|
+
|
|
327
|
+
def _extract_event_id(record: dict, line_no: int, source_path: Path) -> str:
|
|
328
|
+
for key in ("uuid", "toolUseID", "tool_use_id", "id", "event_id", "requestId"):
|
|
329
|
+
value = record.get(key)
|
|
330
|
+
if value:
|
|
331
|
+
return str(value)
|
|
332
|
+
return f"{source_path.name}:{line_no}"
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
def _extract_read_result_payload(
|
|
336
|
+
block: dict,
|
|
337
|
+
tool_use_result: Any,
|
|
338
|
+
) -> Tuple[str, Optional[int], Optional[int], Optional[int], Optional[int]]:
|
|
339
|
+
text = ""
|
|
340
|
+
tokens_est: Optional[int] = None
|
|
341
|
+
start_line: Optional[int] = None
|
|
342
|
+
num_lines: Optional[int] = None
|
|
343
|
+
total_lines: Optional[int] = None
|
|
344
|
+
|
|
345
|
+
if isinstance(tool_use_result, dict):
|
|
346
|
+
file_payload = tool_use_result.get("file")
|
|
347
|
+
if isinstance(file_payload, dict):
|
|
348
|
+
content = file_payload.get("content")
|
|
349
|
+
if isinstance(content, str):
|
|
350
|
+
text = content
|
|
351
|
+
tokens_est = estimate_tokens(content)
|
|
352
|
+
start_line = _safe_int(file_payload.get("startLine"), 0) or None
|
|
353
|
+
num_lines = _safe_int(file_payload.get("numLines"), 0) or None
|
|
354
|
+
total_lines = _safe_int(file_payload.get("totalLines"), 0) or None
|
|
355
|
+
elif isinstance(tool_use_result.get("content"), str):
|
|
356
|
+
text = str(tool_use_result.get("content"))
|
|
357
|
+
tokens_est = estimate_tokens(text)
|
|
358
|
+
|
|
359
|
+
if not text:
|
|
360
|
+
content = block.get("content")
|
|
361
|
+
if isinstance(content, str):
|
|
362
|
+
text = content
|
|
363
|
+
tokens_est = estimate_tokens(text)
|
|
364
|
+
elif isinstance(content, list):
|
|
365
|
+
text_parts = []
|
|
366
|
+
for item in content:
|
|
367
|
+
if isinstance(item, dict) and item.get("type") == "text" and isinstance(item.get("text"), str):
|
|
368
|
+
text_parts.append(item["text"])
|
|
369
|
+
if text_parts:
|
|
370
|
+
text = "\n".join(text_parts)
|
|
371
|
+
tokens_est = estimate_tokens(text)
|
|
372
|
+
|
|
373
|
+
return text, tokens_est, start_line, num_lines, total_lines
|
|
374
|
+
|
|
375
|
+
|
|
376
|
+
def _classify_jsonl(path: Path) -> str:
|
|
377
|
+
for _, record in _iter_jsonl_records(path):
|
|
378
|
+
if "decision" in record and ("file" in record or "file_path" in record):
|
|
379
|
+
return "decision_log"
|
|
380
|
+
if "message" in record or "type" in record or "toolUseResult" in record:
|
|
381
|
+
return "transcript"
|
|
382
|
+
break
|
|
383
|
+
return "transcript"
|
|
384
|
+
|
|
385
|
+
|
|
386
|
+
def _extract_transcript_events(path: Path) -> List[ReplayEvent]:
|
|
387
|
+
events: List[ReplayEvent] = []
|
|
388
|
+
tool_events_by_id: Dict[str, ReplayEvent] = {}
|
|
389
|
+
seen_tool_ids: set[str] = set()
|
|
390
|
+
for line_no, record in _iter_jsonl_records(path):
|
|
391
|
+
session_id = _normalize_session_id(
|
|
392
|
+
record.get("sessionId") or record.get("session_id") or record.get("session") or path.stem
|
|
393
|
+
)
|
|
394
|
+
timestamp = _normalize_timestamp(record.get("timestamp"))
|
|
395
|
+
event_id_prefix = _extract_event_id(record, line_no, path)
|
|
396
|
+
cwd = _normalize_path_text(record.get("cwd"))
|
|
397
|
+
msg = record.get("message", {})
|
|
398
|
+
content = msg.get("content", []) if isinstance(msg, dict) else []
|
|
399
|
+
|
|
400
|
+
if isinstance(content, list):
|
|
401
|
+
for block in content:
|
|
402
|
+
if not isinstance(block, dict) or block.get("type") != "tool_use":
|
|
403
|
+
continue
|
|
404
|
+
tool_name = str(block.get("name") or "").strip().lower()
|
|
405
|
+
input_obj = block.get("input", {})
|
|
406
|
+
if not isinstance(input_obj, dict):
|
|
407
|
+
continue
|
|
408
|
+
raw_file_path = _extract_file_path(input_obj)
|
|
409
|
+
if not raw_file_path:
|
|
410
|
+
continue
|
|
411
|
+
tool_use_id = str(block.get("id") or "")
|
|
412
|
+
dedupe_key = f"{session_id}:{tool_use_id}"
|
|
413
|
+
if tool_use_id and dedupe_key in seen_tool_ids:
|
|
414
|
+
continue
|
|
415
|
+
if tool_use_id:
|
|
416
|
+
seen_tool_ids.add(dedupe_key)
|
|
417
|
+
|
|
418
|
+
normalized_file_path = str(Path(raw_file_path).expanduser())
|
|
419
|
+
event_kind = "read" if tool_name == "read" else "edit" if tool_name in {
|
|
420
|
+
"edit",
|
|
421
|
+
"write",
|
|
422
|
+
"multiedit",
|
|
423
|
+
"notebookedit",
|
|
424
|
+
} else ""
|
|
425
|
+
if not event_kind:
|
|
426
|
+
continue
|
|
427
|
+
offset, limit, pages = _extract_read_fields(input_obj) if event_kind == "read" else (0, 0, "")
|
|
428
|
+
event = ReplayEvent(
|
|
429
|
+
source_path=path,
|
|
430
|
+
source_kind="transcript",
|
|
431
|
+
session_id=session_id,
|
|
432
|
+
timestamp=timestamp,
|
|
433
|
+
order=len(events),
|
|
434
|
+
event_kind=event_kind,
|
|
435
|
+
raw_file_path=raw_file_path,
|
|
436
|
+
normalized_file_path=normalized_file_path,
|
|
437
|
+
tool_use_id=tool_use_id,
|
|
438
|
+
cwd=cwd,
|
|
439
|
+
offset=offset,
|
|
440
|
+
limit=limit,
|
|
441
|
+
pages=pages,
|
|
442
|
+
event_id=f"{event_id_prefix}:{tool_name}:{len(events)}",
|
|
443
|
+
)
|
|
444
|
+
events.append(event)
|
|
445
|
+
if tool_use_id:
|
|
446
|
+
tool_events_by_id[tool_use_id] = event
|
|
447
|
+
|
|
448
|
+
for block in content:
|
|
449
|
+
if not isinstance(block, dict) or block.get("type") != "tool_result":
|
|
450
|
+
continue
|
|
451
|
+
tool_use_id = str(block.get("tool_use_id") or "")
|
|
452
|
+
if not tool_use_id or tool_use_id not in tool_events_by_id:
|
|
453
|
+
continue
|
|
454
|
+
event = tool_events_by_id[tool_use_id]
|
|
455
|
+
event.is_error = bool(block.get("is_error"))
|
|
456
|
+
if event.event_kind != "read" or event.is_error:
|
|
457
|
+
continue
|
|
458
|
+
text, tokens_est, start_line, num_lines, total_lines = _extract_read_result_payload(
|
|
459
|
+
block,
|
|
460
|
+
record.get("toolUseResult"),
|
|
461
|
+
)
|
|
462
|
+
if text:
|
|
463
|
+
event.read_result_text = text
|
|
464
|
+
event.read_result_tokens_est = tokens_est
|
|
465
|
+
event.read_result_start_line = start_line
|
|
466
|
+
event.read_result_num_lines = num_lines
|
|
467
|
+
event.read_result_total_lines = total_lines
|
|
468
|
+
return events
|
|
469
|
+
|
|
470
|
+
|
|
471
|
+
def _extract_decision_log_events(path: Path) -> List[ReplayEvent]:
|
|
472
|
+
events: List[ReplayEvent] = []
|
|
473
|
+
for line_no, record in _iter_jsonl_records(path):
|
|
474
|
+
session_id = _normalize_session_id(record.get("session") or record.get("session_id") or path.stem)
|
|
475
|
+
timestamp = _normalize_timestamp(record.get("ts") or record.get("timestamp"))
|
|
476
|
+
raw_file_path = _extract_file_path(record)
|
|
477
|
+
if not raw_file_path:
|
|
478
|
+
continue
|
|
479
|
+
normalized_file_path = str(Path(raw_file_path).expanduser())
|
|
480
|
+
decision = str(record.get("decision") or "").strip().lower()
|
|
481
|
+
reason = str(record.get("reason") or "").strip()
|
|
482
|
+
tokens_est_hint = record.get("file_tokens_est")
|
|
483
|
+
if tokens_est_hint is not None:
|
|
484
|
+
tokens_est_hint = _safe_int(tokens_est_hint, 0)
|
|
485
|
+
events.append(
|
|
486
|
+
ReplayEvent(
|
|
487
|
+
source_path=path,
|
|
488
|
+
source_kind="decision_log",
|
|
489
|
+
session_id=session_id,
|
|
490
|
+
timestamp=timestamp,
|
|
491
|
+
order=len(events),
|
|
492
|
+
event_kind="decision",
|
|
493
|
+
raw_file_path=raw_file_path,
|
|
494
|
+
normalized_file_path=normalized_file_path,
|
|
495
|
+
decision=decision,
|
|
496
|
+
reason=reason,
|
|
497
|
+
tokens_est_hint=tokens_est_hint if isinstance(tokens_est_hint, int) else None,
|
|
498
|
+
replacement_tokens_est=_safe_int(record.get("replacement_tokens_est"), 0),
|
|
499
|
+
net_saved_tokens_est=_safe_int(record.get("net_saved_tokens_est"), 0),
|
|
500
|
+
repeat_replacement_count=_safe_int(record.get("repeat_replacement_count"), 0),
|
|
501
|
+
actual_substitution=bool(record.get("actual_substitution")),
|
|
502
|
+
event_id=f"{path.name}:{line_no}",
|
|
503
|
+
)
|
|
504
|
+
)
|
|
505
|
+
return events
|
|
506
|
+
|
|
507
|
+
|
|
508
|
+
def _read_text(path: Path) -> str:
|
|
509
|
+
return path.read_text(encoding="utf-8", errors="ignore")
|
|
510
|
+
|
|
511
|
+
|
|
512
|
+
def _looks_generated(path: Path, text: str) -> bool:
|
|
513
|
+
name = path.name.lower()
|
|
514
|
+
if re.search(r"(?:^|[._-])(generated|autogen|autogenerated|gen)(?:[._-]|$)", name):
|
|
515
|
+
return True
|
|
516
|
+
for line in text.splitlines()[:40]:
|
|
517
|
+
stripped = line.strip().lower()
|
|
518
|
+
if not stripped:
|
|
519
|
+
continue
|
|
520
|
+
if stripped.startswith(("#", "//", "/*", "*", '"""', "'''")) and any(
|
|
521
|
+
phrase in stripped for phrase in ("generated by", "auto-generated", "autogenerated", "do not edit")
|
|
522
|
+
):
|
|
523
|
+
return True
|
|
524
|
+
return False
|
|
525
|
+
|
|
526
|
+
|
|
527
|
+
def _current_file_snapshot(path_text: str, cache: Dict[str, FileSnapshot]) -> FileSnapshot:
|
|
528
|
+
cached = cache.get(path_text)
|
|
529
|
+
path = Path(path_text)
|
|
530
|
+
try:
|
|
531
|
+
stat = path.stat()
|
|
532
|
+
except OSError:
|
|
533
|
+
snapshot = FileSnapshot(path=path, exists=False, provenance="disk")
|
|
534
|
+
cache[path_text] = snapshot
|
|
535
|
+
return snapshot
|
|
536
|
+
|
|
537
|
+
stat_key = f"{stat.st_mtime_ns}:{stat.st_size}"
|
|
538
|
+
if cached and cached.exists and cached.stat_key == stat_key:
|
|
539
|
+
return cached
|
|
540
|
+
|
|
541
|
+
try:
|
|
542
|
+
text = _read_text(path)
|
|
543
|
+
except OSError as exc:
|
|
544
|
+
snapshot = FileSnapshot(
|
|
545
|
+
path=path,
|
|
546
|
+
exists=True,
|
|
547
|
+
provenance="disk",
|
|
548
|
+
stat_key=stat_key,
|
|
549
|
+
size_bytes=stat.st_size,
|
|
550
|
+
line_count=0,
|
|
551
|
+
mtime_ns=stat.st_mtime_ns,
|
|
552
|
+
sha256="",
|
|
553
|
+
tokens_est=max(1, stat.st_size // 4),
|
|
554
|
+
text="",
|
|
555
|
+
generated_like=False,
|
|
556
|
+
parse_error=str(exc),
|
|
557
|
+
)
|
|
558
|
+
cache[path_text] = snapshot
|
|
559
|
+
return snapshot
|
|
560
|
+
|
|
561
|
+
line_count = text.count("\n") + (0 if not text else 1)
|
|
562
|
+
tokens_est = max(1, len(text) // 4)
|
|
563
|
+
snapshot = FileSnapshot(
|
|
564
|
+
path=path,
|
|
565
|
+
exists=True,
|
|
566
|
+
provenance="disk",
|
|
567
|
+
stat_key=stat_key,
|
|
568
|
+
size_bytes=stat.st_size,
|
|
569
|
+
line_count=line_count,
|
|
570
|
+
mtime_ns=stat.st_mtime_ns,
|
|
571
|
+
sha256=hashlib.sha256(text.encode("utf-8", errors="ignore")).hexdigest(),
|
|
572
|
+
tokens_est=tokens_est,
|
|
573
|
+
text=text,
|
|
574
|
+
generated_like=_looks_generated(path, text),
|
|
575
|
+
)
|
|
576
|
+
cache[path_text] = snapshot
|
|
577
|
+
return snapshot
|
|
578
|
+
|
|
579
|
+
|
|
580
|
+
def _snapshot_from_text(
|
|
581
|
+
path_text: str,
|
|
582
|
+
text: str,
|
|
583
|
+
*,
|
|
584
|
+
start_line: Optional[int] = None,
|
|
585
|
+
num_lines: Optional[int] = None,
|
|
586
|
+
total_lines: Optional[int] = None,
|
|
587
|
+
) -> FileSnapshot:
|
|
588
|
+
path = Path(path_text)
|
|
589
|
+
content = text or ""
|
|
590
|
+
derived_line_count = content.count("\n") + (0 if not content else 1)
|
|
591
|
+
line_count = total_lines or derived_line_count
|
|
592
|
+
is_full_coverage = (
|
|
593
|
+
start_line in (None, 0, 1)
|
|
594
|
+
and (
|
|
595
|
+
total_lines is None
|
|
596
|
+
or num_lines is None
|
|
597
|
+
or num_lines >= total_lines
|
|
598
|
+
)
|
|
599
|
+
)
|
|
600
|
+
return FileSnapshot(
|
|
601
|
+
path=path,
|
|
602
|
+
exists=True,
|
|
603
|
+
provenance="historical_full" if is_full_coverage else "historical_partial",
|
|
604
|
+
stat_key=f"historical:{hashlib.sha256(content.encode('utf-8', errors='ignore')).hexdigest()}",
|
|
605
|
+
size_bytes=len(content.encode("utf-8", errors="ignore")),
|
|
606
|
+
line_count=line_count,
|
|
607
|
+
mtime_ns=0,
|
|
608
|
+
sha256=hashlib.sha256(content.encode("utf-8", errors="ignore")).hexdigest(),
|
|
609
|
+
tokens_est=estimate_tokens(content),
|
|
610
|
+
text=content,
|
|
611
|
+
generated_like=False,
|
|
612
|
+
parse_error="",
|
|
613
|
+
)
|
|
614
|
+
|
|
615
|
+
|
|
616
|
+
def _is_supported_candidate(
|
|
617
|
+
event: ReplayEvent,
|
|
618
|
+
snapshot: FileSnapshot,
|
|
619
|
+
min_file_tokens: int,
|
|
620
|
+
max_bytes: int,
|
|
621
|
+
max_lines: int,
|
|
622
|
+
language_scope: str,
|
|
623
|
+
) -> Tuple[bool, str]:
|
|
624
|
+
if event.event_kind != "read":
|
|
625
|
+
return False, "not_read"
|
|
626
|
+
if not event.is_whole_file:
|
|
627
|
+
return False, "partial_read"
|
|
628
|
+
if language_scope == "python-only":
|
|
629
|
+
if not is_python_file(event.normalized_file_path):
|
|
630
|
+
return False, "unsupported_language"
|
|
631
|
+
elif not is_structure_supported_file(event.normalized_file_path):
|
|
632
|
+
return False, "unsupported_language"
|
|
633
|
+
if not snapshot.exists:
|
|
634
|
+
return False, "file_missing"
|
|
635
|
+
if snapshot.generated_like:
|
|
636
|
+
return False, "generated_like"
|
|
637
|
+
if snapshot.size_bytes > max_bytes:
|
|
638
|
+
return False, "over_byte_cap"
|
|
639
|
+
if snapshot.line_count > max_lines:
|
|
640
|
+
return False, "over_line_cap"
|
|
641
|
+
if snapshot.tokens_est < min_file_tokens:
|
|
642
|
+
return False, "below_min_tokens"
|
|
643
|
+
if snapshot.parse_error:
|
|
644
|
+
return False, "file_unreadable"
|
|
645
|
+
return True, "eligible"
|
|
646
|
+
|
|
647
|
+
|
|
648
|
+
def _summarize_snapshot(
|
|
649
|
+
snapshot: FileSnapshot,
|
|
650
|
+
*,
|
|
651
|
+
file_tokens_est: Optional[int] = None,
|
|
652
|
+
) -> StructureMapResult:
|
|
653
|
+
return summarize_code_source(
|
|
654
|
+
snapshot.text,
|
|
655
|
+
file_path=str(snapshot.path),
|
|
656
|
+
offset=0,
|
|
657
|
+
limit=0,
|
|
658
|
+
file_tokens_est=file_tokens_est or snapshot.tokens_est,
|
|
659
|
+
file_size_bytes=snapshot.size_bytes,
|
|
660
|
+
)
|
|
661
|
+
|
|
662
|
+
|
|
663
|
+
def _build_replacement_fingerprint(snapshot: FileSnapshot, summary: StructureMapResult, offset: int, limit: int) -> str:
|
|
664
|
+
digest_input = "|".join(
|
|
665
|
+
[
|
|
666
|
+
str(snapshot.path),
|
|
667
|
+
str(snapshot.mtime_ns),
|
|
668
|
+
str(snapshot.size_bytes),
|
|
669
|
+
snapshot.sha256,
|
|
670
|
+
summary.replacement_type,
|
|
671
|
+
summary.fingerprint,
|
|
672
|
+
str(offset),
|
|
673
|
+
str(limit),
|
|
674
|
+
]
|
|
675
|
+
)
|
|
676
|
+
return hashlib.sha256(digest_input.encode("utf-8")).hexdigest()
|
|
677
|
+
|
|
678
|
+
|
|
679
|
+
def _simulate_transcript_group(
|
|
680
|
+
source_path: Path,
|
|
681
|
+
events: List[ReplayEvent],
|
|
682
|
+
min_file_tokens: int,
|
|
683
|
+
max_bytes: int,
|
|
684
|
+
max_lines: int,
|
|
685
|
+
caps: Dict[str, int],
|
|
686
|
+
reminder_overhead_tokens: int,
|
|
687
|
+
reason_only_overhead_tokens: int,
|
|
688
|
+
language_scope: str,
|
|
689
|
+
) -> ReplaySummary:
|
|
690
|
+
summary = ReplaySummary(source_kind="transcript")
|
|
691
|
+
summary.source_count = len({event.source_path for event in events}) or 1
|
|
692
|
+
summary.total_events = len(events)
|
|
693
|
+
summary.sessions = len({event.session_id for event in events})
|
|
694
|
+
summary.read_events = sum(1 for event in events if event.event_kind == "read")
|
|
695
|
+
summary.edit_events = sum(1 for event in events if event.event_kind == "edit")
|
|
696
|
+
|
|
697
|
+
snapshots: Dict[str, FileSnapshot] = {}
|
|
698
|
+
by_session: Dict[str, List[Tuple[int, ReplayEvent]]] = defaultdict(list)
|
|
699
|
+
for index, event in enumerate(events):
|
|
700
|
+
by_session[event.session_id].append((index, event))
|
|
701
|
+
|
|
702
|
+
for session_id, indexed_events in by_session.items():
|
|
703
|
+
per_file_state: Dict[str, Dict[str, Any]] = defaultdict(
|
|
704
|
+
lambda: {
|
|
705
|
+
"dirty": False,
|
|
706
|
+
"last_signature": None,
|
|
707
|
+
"last_read_index": None,
|
|
708
|
+
"seen_fingerprints": set(),
|
|
709
|
+
"last_success_snapshot": None,
|
|
710
|
+
"history": [],
|
|
711
|
+
}
|
|
712
|
+
)
|
|
713
|
+
|
|
714
|
+
for position, (index, event) in enumerate(indexed_events):
|
|
715
|
+
file_key = event.normalized_file_path
|
|
716
|
+
if event.event_kind == "edit":
|
|
717
|
+
per_file_state[file_key]["dirty"] = True
|
|
718
|
+
per_file_state[file_key]["history"].append((index, "edit", event.read_signature))
|
|
719
|
+
continue
|
|
720
|
+
|
|
721
|
+
if event.event_kind != "read":
|
|
722
|
+
continue
|
|
723
|
+
|
|
724
|
+
disk_snapshot = _current_file_snapshot(file_key, snapshots)
|
|
725
|
+
snapshot = (
|
|
726
|
+
_snapshot_from_text(
|
|
727
|
+
file_key,
|
|
728
|
+
event.read_result_text,
|
|
729
|
+
start_line=event.read_result_start_line,
|
|
730
|
+
num_lines=event.read_result_num_lines,
|
|
731
|
+
total_lines=event.read_result_total_lines,
|
|
732
|
+
)
|
|
733
|
+
if event.read_result_text
|
|
734
|
+
else disk_snapshot
|
|
735
|
+
)
|
|
736
|
+
file_stats = summary.files.get(file_key)
|
|
737
|
+
if file_stats is None:
|
|
738
|
+
file_stats = ReplayFileStats(
|
|
739
|
+
source_path=str(event.source_path),
|
|
740
|
+
normalized_file_path=file_key,
|
|
741
|
+
session_id=session_id,
|
|
742
|
+
)
|
|
743
|
+
summary.files[file_key] = file_stats
|
|
744
|
+
|
|
745
|
+
file_stats.total_reads += 1
|
|
746
|
+
if event.is_whole_file:
|
|
747
|
+
file_stats.whole_file_reads += 1
|
|
748
|
+
|
|
749
|
+
state = per_file_state[file_key]
|
|
750
|
+
evidence_snapshot = state["last_success_snapshot"] or snapshot
|
|
751
|
+
is_redundant = (
|
|
752
|
+
not state["dirty"]
|
|
753
|
+
and state["last_signature"] == event.read_signature
|
|
754
|
+
and state["last_read_index"] is not None
|
|
755
|
+
)
|
|
756
|
+
candidate_snapshot = evidence_snapshot if is_redundant else snapshot
|
|
757
|
+
candidate, reason = _is_supported_candidate(
|
|
758
|
+
event,
|
|
759
|
+
candidate_snapshot,
|
|
760
|
+
min_file_tokens,
|
|
761
|
+
max_bytes,
|
|
762
|
+
max_lines,
|
|
763
|
+
language_scope,
|
|
764
|
+
)
|
|
765
|
+
if not candidate:
|
|
766
|
+
file_stats.skipped[reason] += 1
|
|
767
|
+
continue
|
|
768
|
+
|
|
769
|
+
if not is_redundant:
|
|
770
|
+
state["dirty"] = False
|
|
771
|
+
state["last_signature"] = event.read_signature
|
|
772
|
+
state["last_read_index"] = index
|
|
773
|
+
if not event.is_error and snapshot.exists and snapshot.provenance != "historical_partial":
|
|
774
|
+
state["last_success_snapshot"] = snapshot
|
|
775
|
+
elif state["last_success_snapshot"] is None and snapshot.exists and snapshot.provenance == "disk":
|
|
776
|
+
state["last_success_snapshot"] = snapshot
|
|
777
|
+
state["history"].append((index, "first", event.read_signature))
|
|
778
|
+
continue
|
|
779
|
+
|
|
780
|
+
baseline_tokens = event.read_result_tokens_est or evidence_snapshot.tokens_est
|
|
781
|
+
file_stats.redundant_candidates += 1
|
|
782
|
+
summary.candidate_events += 1
|
|
783
|
+
|
|
784
|
+
summary_result = _summarize_snapshot(evidence_snapshot, file_tokens_est=baseline_tokens)
|
|
785
|
+
if not summary_result.eligible or summary_result.replacement_type not in caps:
|
|
786
|
+
file_stats.skipped["structure_digest_fallback"] += 1
|
|
787
|
+
state["history"].append((index, "digest", event.read_signature, summary_result.reason))
|
|
788
|
+
continue
|
|
789
|
+
|
|
790
|
+
if evidence_snapshot.provenance == "historical_full":
|
|
791
|
+
file_stats.historical_result_backed += 1
|
|
792
|
+
else:
|
|
793
|
+
file_stats.current_disk_fallbacks += 1
|
|
794
|
+
|
|
795
|
+
fingerprint = _build_replacement_fingerprint(
|
|
796
|
+
evidence_snapshot,
|
|
797
|
+
summary_result,
|
|
798
|
+
event.offset,
|
|
799
|
+
event.limit,
|
|
800
|
+
)
|
|
801
|
+
duplicate = fingerprint in state["seen_fingerprints"]
|
|
802
|
+
state["seen_fingerprints"].add(fingerprint)
|
|
803
|
+
|
|
804
|
+
replacement_cost = summary_result.replacement_tokens_est
|
|
805
|
+
if duplicate:
|
|
806
|
+
file_stats.repeat_replacements += 1
|
|
807
|
+
replacement_cost = reminder_overhead_tokens if file_stats.repeat_replacements == 1 else reason_only_overhead_tokens
|
|
808
|
+
if file_stats.repeat_replacements == 1:
|
|
809
|
+
file_stats.reminder_tokens += replacement_cost
|
|
810
|
+
else:
|
|
811
|
+
file_stats.reason_only_tokens += replacement_cost
|
|
812
|
+
else:
|
|
813
|
+
file_stats.eligible_replacements += 1
|
|
814
|
+
file_stats.structure_tokens += summary_result.replacement_tokens_est
|
|
815
|
+
file_stats.replacement_fingerprints.add(fingerprint)
|
|
816
|
+
|
|
817
|
+
if event.is_error:
|
|
818
|
+
file_stats.error_replacement_attempts += 1
|
|
819
|
+
|
|
820
|
+
actual_historical_read = (
|
|
821
|
+
not event.is_error
|
|
822
|
+
and bool(event.read_result_text)
|
|
823
|
+
and snapshot.provenance == "historical_full"
|
|
824
|
+
)
|
|
825
|
+
saved_tokens = max(0, baseline_tokens - replacement_cost)
|
|
826
|
+
if actual_historical_read:
|
|
827
|
+
file_stats.verified_replacements += 1
|
|
828
|
+
file_stats.baseline_tokens += baseline_tokens
|
|
829
|
+
file_stats.net_saved_tokens += saved_tokens
|
|
830
|
+
else:
|
|
831
|
+
file_stats.directional_baseline_tokens += baseline_tokens
|
|
832
|
+
file_stats.directional_saved_tokens += saved_tokens
|
|
833
|
+
|
|
834
|
+
# Track simple follow-up proxies.
|
|
835
|
+
later_events = indexed_events[position + 1 :]
|
|
836
|
+
for _, later_event in later_events:
|
|
837
|
+
if later_event.normalized_file_path != file_key:
|
|
838
|
+
continue
|
|
839
|
+
if later_event.event_kind == "edit":
|
|
840
|
+
break
|
|
841
|
+
if later_event.event_kind == "read":
|
|
842
|
+
if later_event.is_error:
|
|
843
|
+
continue
|
|
844
|
+
file_stats.replacement_followups += 1
|
|
845
|
+
if later_event.read_signature != event.read_signature:
|
|
846
|
+
file_stats.replacement_different_range_followups += 1
|
|
847
|
+
break
|
|
848
|
+
|
|
849
|
+
state["dirty"] = False
|
|
850
|
+
state["last_signature"] = event.read_signature
|
|
851
|
+
state["last_read_index"] = index
|
|
852
|
+
if not event.is_error and snapshot.exists and snapshot.provenance != "historical_partial":
|
|
853
|
+
state["last_success_snapshot"] = snapshot
|
|
854
|
+
state["history"].append((index, summary_result.replacement_type, event.read_signature))
|
|
855
|
+
|
|
856
|
+
for stats in summary.files.values():
|
|
857
|
+
summary.add_file_stats(stats)
|
|
858
|
+
return summary
|
|
859
|
+
|
|
860
|
+
|
|
861
|
+
def _simulate_decision_log_group(
|
|
862
|
+
source_path: Path,
|
|
863
|
+
events: List[ReplayEvent],
|
|
864
|
+
min_file_tokens: int,
|
|
865
|
+
max_bytes: int,
|
|
866
|
+
max_lines: int,
|
|
867
|
+
caps: Dict[str, int],
|
|
868
|
+
language_scope: str,
|
|
869
|
+
) -> ReplaySummary:
|
|
870
|
+
summary = ReplaySummary(source_kind="decision_log")
|
|
871
|
+
summary.source_count = len({event.source_path for event in events}) or 1
|
|
872
|
+
summary.total_events = len(events)
|
|
873
|
+
summary.sessions = len({event.session_id for event in events})
|
|
874
|
+
summary.read_events = len(events)
|
|
875
|
+
|
|
876
|
+
snapshots: Dict[str, FileSnapshot] = {}
|
|
877
|
+
by_file: Dict[str, List[ReplayEvent]] = defaultdict(list)
|
|
878
|
+
for event in events:
|
|
879
|
+
by_file[event.normalized_file_path].append(event)
|
|
880
|
+
|
|
881
|
+
for file_key, file_events in by_file.items():
|
|
882
|
+
file_stats = ReplayFileStats(
|
|
883
|
+
source_path=str(file_events[0].source_path if file_events else source_path),
|
|
884
|
+
normalized_file_path=file_key,
|
|
885
|
+
session_id=file_events[0].session_id if file_events else "unknown",
|
|
886
|
+
)
|
|
887
|
+
snapshot = _current_file_snapshot(file_key, snapshots)
|
|
888
|
+
|
|
889
|
+
for event in file_events:
|
|
890
|
+
if event.decision not in {"warn", "block"} and not re.search(r"redundant_read", event.reason, re.IGNORECASE):
|
|
891
|
+
continue
|
|
892
|
+
if not event.actual_substitution:
|
|
893
|
+
file_stats.skipped["not_actual_substitution"] += 1
|
|
894
|
+
continue
|
|
895
|
+
candidate, reason = _is_supported_candidate(
|
|
896
|
+
ReplayEvent(
|
|
897
|
+
source_path=source_path,
|
|
898
|
+
source_kind="decision_log",
|
|
899
|
+
session_id=event.session_id,
|
|
900
|
+
timestamp=event.timestamp,
|
|
901
|
+
order=event.order,
|
|
902
|
+
event_kind="read",
|
|
903
|
+
raw_file_path=event.raw_file_path,
|
|
904
|
+
normalized_file_path=event.normalized_file_path,
|
|
905
|
+
),
|
|
906
|
+
snapshot,
|
|
907
|
+
min_file_tokens,
|
|
908
|
+
max_bytes,
|
|
909
|
+
max_lines,
|
|
910
|
+
language_scope,
|
|
911
|
+
)
|
|
912
|
+
if not candidate:
|
|
913
|
+
file_stats.skipped[reason] += 1
|
|
914
|
+
continue
|
|
915
|
+
|
|
916
|
+
summary_result = _summarize_snapshot(snapshot, file_tokens_est=event.tokens_est_hint or snapshot.tokens_est)
|
|
917
|
+
if not summary_result.eligible or summary_result.replacement_type not in caps:
|
|
918
|
+
file_stats.skipped["structure_digest_fallback"] += 1
|
|
919
|
+
continue
|
|
920
|
+
file_stats.total_reads += 1
|
|
921
|
+
file_stats.whole_file_reads += 1
|
|
922
|
+
file_stats.redundant_candidates += 1
|
|
923
|
+
summary.candidate_events += 1
|
|
924
|
+
file_stats.eligible_replacements += 1
|
|
925
|
+
file_stats.verified_replacements += 1
|
|
926
|
+
baseline_tokens = event.tokens_est_hint or snapshot.tokens_est
|
|
927
|
+
structure_tokens = event.replacement_tokens_est or summary_result.replacement_tokens_est
|
|
928
|
+
net_saved_tokens = event.net_saved_tokens_est or max(0, baseline_tokens - structure_tokens)
|
|
929
|
+
file_stats.baseline_tokens += baseline_tokens
|
|
930
|
+
file_stats.structure_tokens += structure_tokens
|
|
931
|
+
file_stats.net_saved_tokens += net_saved_tokens
|
|
932
|
+
file_stats.current_disk_fallbacks += 1
|
|
933
|
+
if event.repeat_replacement_count > 1:
|
|
934
|
+
file_stats.repeat_replacements += 1
|
|
935
|
+
summary.add_file_stats(file_stats)
|
|
936
|
+
|
|
937
|
+
return summary
|
|
938
|
+
|
|
939
|
+
|
|
940
|
+
def _gather_input_paths(raw_paths: Sequence[str]) -> List[Path]:
|
|
941
|
+
expanded: List[Path] = []
|
|
942
|
+
if not raw_paths:
|
|
943
|
+
defaults = [
|
|
944
|
+
claude_home() / "projects",
|
|
945
|
+
claude_home() / "_backups" / "token-optimizer" / "read-cache" / "decisions",
|
|
946
|
+
]
|
|
947
|
+
for root in defaults:
|
|
948
|
+
if root.exists():
|
|
949
|
+
expanded.append(root)
|
|
950
|
+
return expanded
|
|
951
|
+
|
|
952
|
+
# Determine the safe root for glob expansion.
|
|
953
|
+
# TOKEN_OPTIMIZER_SAFE_ROOT overrides the default (claude_home()) for tests only.
|
|
954
|
+
_default_root = claude_home().resolve()
|
|
955
|
+
_safe_root_env = os.environ.get("TOKEN_OPTIMIZER_SAFE_ROOT", "").strip()
|
|
956
|
+
if _safe_root_env:
|
|
957
|
+
_candidate = Path(_safe_root_env).resolve()
|
|
958
|
+
try:
|
|
959
|
+
safe_root = _candidate if _candidate.is_relative_to(_default_root) else _default_root
|
|
960
|
+
except (OSError, ValueError):
|
|
961
|
+
safe_root = _default_root
|
|
962
|
+
else:
|
|
963
|
+
safe_root = _default_root
|
|
964
|
+
|
|
965
|
+
for raw in raw_paths:
|
|
966
|
+
if any(ch in raw for ch in "*?[]"):
|
|
967
|
+
for match in sorted(glob.glob(raw)):
|
|
968
|
+
try:
|
|
969
|
+
# Reject any expansion that escapes the safe root.
|
|
970
|
+
# Prevents crafted globs from traversing into ~/.ssh/, /etc/, etc.
|
|
971
|
+
if not Path(match).resolve().is_relative_to(safe_root):
|
|
972
|
+
continue
|
|
973
|
+
except (OSError, ValueError):
|
|
974
|
+
continue
|
|
975
|
+
expanded.append(Path(match))
|
|
976
|
+
continue
|
|
977
|
+
path = Path(raw).expanduser()
|
|
978
|
+
expanded.append(path)
|
|
979
|
+
return expanded
|
|
980
|
+
|
|
981
|
+
|
|
982
|
+
def _iter_jsonl_files(paths: Sequence[Path]) -> Iterator[Path]:
|
|
983
|
+
seen = set()
|
|
984
|
+
for path in paths:
|
|
985
|
+
if not path.exists():
|
|
986
|
+
continue
|
|
987
|
+
if path.is_file() and path.suffix.lower() == ".jsonl":
|
|
988
|
+
resolved = str(path.resolve())
|
|
989
|
+
if resolved not in seen:
|
|
990
|
+
seen.add(resolved)
|
|
991
|
+
yield path
|
|
992
|
+
elif path.is_dir():
|
|
993
|
+
for child in sorted(path.rglob("*.jsonl")):
|
|
994
|
+
resolved = str(child.resolve())
|
|
995
|
+
if resolved not in seen:
|
|
996
|
+
seen.add(resolved)
|
|
997
|
+
yield child
|
|
998
|
+
|
|
999
|
+
|
|
1000
|
+
def _split_sources(paths: Sequence[Path]) -> Tuple[List[Path], List[Path]]:
|
|
1001
|
+
transcript_files: List[Path] = []
|
|
1002
|
+
decision_files: List[Path] = []
|
|
1003
|
+
for path in _iter_jsonl_files(paths):
|
|
1004
|
+
kind = _classify_jsonl(path)
|
|
1005
|
+
if kind == "decision_log":
|
|
1006
|
+
decision_files.append(path)
|
|
1007
|
+
else:
|
|
1008
|
+
transcript_files.append(path)
|
|
1009
|
+
return transcript_files, decision_files
|
|
1010
|
+
|
|
1011
|
+
|
|
1012
|
+
def _load_replay_events(paths: Sequence[Path]) -> Tuple[List[ReplayEvent], List[ReplayEvent]]:
|
|
1013
|
+
transcript_events: List[ReplayEvent] = []
|
|
1014
|
+
decision_events: List[ReplayEvent] = []
|
|
1015
|
+
for path in _iter_jsonl_files(paths):
|
|
1016
|
+
kind = _classify_jsonl(path)
|
|
1017
|
+
if kind == "decision_log":
|
|
1018
|
+
decision_events.extend(_extract_decision_log_events(path))
|
|
1019
|
+
else:
|
|
1020
|
+
transcript_events.extend(_extract_transcript_events(path))
|
|
1021
|
+
return transcript_events, decision_events
|
|
1022
|
+
|
|
1023
|
+
|
|
1024
|
+
def _filter_transcript_events(
|
|
1025
|
+
events: Sequence[ReplayEvent],
|
|
1026
|
+
*,
|
|
1027
|
+
cwd_contains: Sequence[str],
|
|
1028
|
+
exclude_cwd_contains: Sequence[str],
|
|
1029
|
+
) -> List[ReplayEvent]:
|
|
1030
|
+
if not cwd_contains and not exclude_cwd_contains:
|
|
1031
|
+
return list(events)
|
|
1032
|
+
|
|
1033
|
+
filtered: List[ReplayEvent] = []
|
|
1034
|
+
for event in events:
|
|
1035
|
+
cwd = event.cwd or ""
|
|
1036
|
+
if cwd_contains and not any(fragment in cwd for fragment in cwd_contains):
|
|
1037
|
+
continue
|
|
1038
|
+
if exclude_cwd_contains and any(fragment in cwd for fragment in exclude_cwd_contains):
|
|
1039
|
+
continue
|
|
1040
|
+
filtered.append(event)
|
|
1041
|
+
return filtered
|
|
1042
|
+
|
|
1043
|
+
|
|
1044
|
+
def _format_tokens(tokens: int) -> str:
|
|
1045
|
+
return f"{tokens:,}"
|
|
1046
|
+
|
|
1047
|
+
|
|
1048
|
+
def _percent(value: float) -> str:
|
|
1049
|
+
return f"{value * 100:.1f}%"
|
|
1050
|
+
|
|
1051
|
+
|
|
1052
|
+
def _print_summary(summary: ReplaySummary, label: str) -> None:
|
|
1053
|
+
print(f"\n[{label}]")
|
|
1054
|
+
print(f" source files: {summary.source_count}")
|
|
1055
|
+
print(f" sessions: {summary.sessions}")
|
|
1056
|
+
print(f" events: {summary.total_events} total | {summary.read_events} reads | {summary.edit_events} edits")
|
|
1057
|
+
print(f" redundant candidates: {summary.candidate_events}")
|
|
1058
|
+
print(f" eligible replacements: {summary.eligible_replacements}")
|
|
1059
|
+
print(f" repeat replacements: {summary.repeat_replacements}")
|
|
1060
|
+
print(f" verified replacements: {summary.verified_replacements}")
|
|
1061
|
+
print(f" capture rate: {_percent(summary.capture_rate)}")
|
|
1062
|
+
print(f" repeat share: {_percent(summary.repeat_share)}")
|
|
1063
|
+
print(f" baseline tokens: {_format_tokens(summary.baseline_tokens)}")
|
|
1064
|
+
print(f" structure tokens: {_format_tokens(summary.structure_tokens)}")
|
|
1065
|
+
if summary.reminder_tokens or summary.reason_only_tokens:
|
|
1066
|
+
print(f" reminder / reason-only tokens: {_format_tokens(summary.reminder_tokens + summary.reason_only_tokens)}")
|
|
1067
|
+
print(f" net saved tokens (historical-only): {_format_tokens(summary.net_saved_tokens)}")
|
|
1068
|
+
print(f" savings rate (historical-only): {_percent(summary.savings_rate)}")
|
|
1069
|
+
if summary.directional_baseline_tokens or summary.directional_saved_tokens:
|
|
1070
|
+
print(
|
|
1071
|
+
f" directional opportunity: {_format_tokens(summary.directional_saved_tokens)} "
|
|
1072
|
+
f"on {_format_tokens(summary.directional_baseline_tokens)} baseline"
|
|
1073
|
+
)
|
|
1074
|
+
print(f" directional savings rate: {_percent(summary.directional_savings_rate)}")
|
|
1075
|
+
print(
|
|
1076
|
+
f" evidence: historical results={summary.historical_result_backed} | "
|
|
1077
|
+
f"disk fallback={summary.current_disk_fallbacks}"
|
|
1078
|
+
)
|
|
1079
|
+
print(f" follow-up same-file rate: {_percent(summary.followup_rate)}")
|
|
1080
|
+
print(f" false-block proxy: {_percent(summary.false_block_proxy_rate)}")
|
|
1081
|
+
|
|
1082
|
+
if summary.skipped:
|
|
1083
|
+
print(" skips:")
|
|
1084
|
+
for reason, count in summary.skipped.most_common(10):
|
|
1085
|
+
print(f" {reason}: {count}")
|
|
1086
|
+
|
|
1087
|
+
if summary.files:
|
|
1088
|
+
top_files = sorted(summary.files.values(), key=lambda s: (s.net_saved_tokens, s.eligible_replacements), reverse=True)[:8]
|
|
1089
|
+
print(" top files:")
|
|
1090
|
+
for stats in top_files:
|
|
1091
|
+
if stats.net_saved_tokens <= 0 and stats.eligible_replacements <= 0:
|
|
1092
|
+
continue
|
|
1093
|
+
print(
|
|
1094
|
+
f" {stats.normalized_file_path} | saved={_format_tokens(stats.net_saved_tokens)} "
|
|
1095
|
+
f"| eligible={stats.eligible_replacements} | repeats={stats.repeat_replacements}"
|
|
1096
|
+
)
|
|
1097
|
+
|
|
1098
|
+
|
|
1099
|
+
def _json_ready_counter(counter: Counter) -> Dict[str, int]:
|
|
1100
|
+
return {str(key): int(value) for key, value in counter.items()}
|
|
1101
|
+
|
|
1102
|
+
|
|
1103
|
+
def _summary_to_dict(summary: ReplaySummary) -> Dict[str, Any]:
|
|
1104
|
+
return {
|
|
1105
|
+
"source_kind": summary.source_kind,
|
|
1106
|
+
"source_count": summary.source_count,
|
|
1107
|
+
"sessions": summary.sessions,
|
|
1108
|
+
"total_events": summary.total_events,
|
|
1109
|
+
"read_events": summary.read_events,
|
|
1110
|
+
"edit_events": summary.edit_events,
|
|
1111
|
+
"candidate_events": summary.candidate_events,
|
|
1112
|
+
"eligible_replacements": summary.eligible_replacements,
|
|
1113
|
+
"repeat_replacements": summary.repeat_replacements,
|
|
1114
|
+
"verified_replacements": summary.verified_replacements,
|
|
1115
|
+
"capture_rate": summary.capture_rate,
|
|
1116
|
+
"repeat_share": summary.repeat_share,
|
|
1117
|
+
"baseline_tokens": summary.baseline_tokens,
|
|
1118
|
+
"structure_tokens": summary.structure_tokens,
|
|
1119
|
+
"reminder_tokens": summary.reminder_tokens,
|
|
1120
|
+
"reason_only_tokens": summary.reason_only_tokens,
|
|
1121
|
+
"net_saved_tokens": summary.net_saved_tokens,
|
|
1122
|
+
"directional_baseline_tokens": summary.directional_baseline_tokens,
|
|
1123
|
+
"directional_saved_tokens": summary.directional_saved_tokens,
|
|
1124
|
+
"historical_result_backed": summary.historical_result_backed,
|
|
1125
|
+
"current_disk_fallbacks": summary.current_disk_fallbacks,
|
|
1126
|
+
"savings_rate": summary.savings_rate,
|
|
1127
|
+
"directional_savings_rate": summary.directional_savings_rate,
|
|
1128
|
+
"followup_rate": summary.followup_rate,
|
|
1129
|
+
"false_block_proxy_rate": summary.false_block_proxy_rate,
|
|
1130
|
+
"skipped": _json_ready_counter(summary.skipped),
|
|
1131
|
+
"files": {
|
|
1132
|
+
path: {
|
|
1133
|
+
"source_path": stats.source_path,
|
|
1134
|
+
"session_id": stats.session_id,
|
|
1135
|
+
"total_reads": stats.total_reads,
|
|
1136
|
+
"whole_file_reads": stats.whole_file_reads,
|
|
1137
|
+
"redundant_candidates": stats.redundant_candidates,
|
|
1138
|
+
"eligible_replacements": stats.eligible_replacements,
|
|
1139
|
+
"repeat_replacements": stats.repeat_replacements,
|
|
1140
|
+
"verified_replacements": stats.verified_replacements,
|
|
1141
|
+
"baseline_tokens": stats.baseline_tokens,
|
|
1142
|
+
"structure_tokens": stats.structure_tokens,
|
|
1143
|
+
"reminder_tokens": stats.reminder_tokens,
|
|
1144
|
+
"reason_only_tokens": stats.reason_only_tokens,
|
|
1145
|
+
"net_saved_tokens": stats.net_saved_tokens,
|
|
1146
|
+
"directional_baseline_tokens": stats.directional_baseline_tokens,
|
|
1147
|
+
"directional_saved_tokens": stats.directional_saved_tokens,
|
|
1148
|
+
"historical_result_backed": stats.historical_result_backed,
|
|
1149
|
+
"current_disk_fallbacks": stats.current_disk_fallbacks,
|
|
1150
|
+
"skipped": _json_ready_counter(stats.skipped),
|
|
1151
|
+
"replacement_followups": stats.replacement_followups,
|
|
1152
|
+
"replacement_different_range_followups": stats.replacement_different_range_followups,
|
|
1153
|
+
"error_replacement_attempts": stats.error_replacement_attempts,
|
|
1154
|
+
}
|
|
1155
|
+
for path, stats in summary.files.items()
|
|
1156
|
+
},
|
|
1157
|
+
}
|
|
1158
|
+
|
|
1159
|
+
|
|
1160
|
+
def _create_transcript_fixture(tmpdir: Path) -> Path:
|
|
1161
|
+
py_file = tmpdir / "fixture.py"
|
|
1162
|
+
filler = "\n".join(f"# filler line {i} with extra payload to clear token threshold" for i in range(360))
|
|
1163
|
+
py_file.write_text(
|
|
1164
|
+
f"import os\n\n"
|
|
1165
|
+
f"class Greeter:\n"
|
|
1166
|
+
f" def hello(self, name):\n"
|
|
1167
|
+
f" return f'hello {{name}}'\n\n"
|
|
1168
|
+
f"def top_level(x, y):\n"
|
|
1169
|
+
f" return x + y\n\n"
|
|
1170
|
+
f"{filler}\n",
|
|
1171
|
+
encoding="utf-8",
|
|
1172
|
+
)
|
|
1173
|
+
transcript = tmpdir / "fixture.jsonl"
|
|
1174
|
+
session_id = "fixture-session"
|
|
1175
|
+
records = [
|
|
1176
|
+
{
|
|
1177
|
+
"type": "assistant",
|
|
1178
|
+
"sessionId": session_id,
|
|
1179
|
+
"timestamp": "2026-04-01T10:00:00Z",
|
|
1180
|
+
"uuid": "1",
|
|
1181
|
+
"message": {
|
|
1182
|
+
"content": [
|
|
1183
|
+
{"type": "tool_use", "name": "Read", "id": "toolu_py_1", "input": {"file_path": str(py_file)}}
|
|
1184
|
+
]
|
|
1185
|
+
},
|
|
1186
|
+
},
|
|
1187
|
+
{
|
|
1188
|
+
"type": "user",
|
|
1189
|
+
"sessionId": session_id,
|
|
1190
|
+
"timestamp": "2026-04-01T10:00:00Z",
|
|
1191
|
+
"uuid": "1b",
|
|
1192
|
+
"message": {
|
|
1193
|
+
"role": "user",
|
|
1194
|
+
"content": [{"type": "tool_result", "tool_use_id": "toolu_py_1", "content": py_file.read_text(encoding="utf-8")}],
|
|
1195
|
+
},
|
|
1196
|
+
"toolUseResult": {
|
|
1197
|
+
"type": "text",
|
|
1198
|
+
"file": {
|
|
1199
|
+
"filePath": str(py_file),
|
|
1200
|
+
"content": py_file.read_text(encoding="utf-8"),
|
|
1201
|
+
"numLines": len(py_file.read_text(encoding="utf-8").splitlines()),
|
|
1202
|
+
"startLine": 1,
|
|
1203
|
+
"totalLines": len(py_file.read_text(encoding="utf-8").splitlines()),
|
|
1204
|
+
}
|
|
1205
|
+
},
|
|
1206
|
+
},
|
|
1207
|
+
{
|
|
1208
|
+
"type": "assistant",
|
|
1209
|
+
"sessionId": session_id,
|
|
1210
|
+
"timestamp": "2026-04-01T10:00:01Z",
|
|
1211
|
+
"uuid": "2",
|
|
1212
|
+
"message": {
|
|
1213
|
+
"content": [
|
|
1214
|
+
{"type": "tool_use", "name": "Read", "id": "toolu_py_2", "input": {"file_path": str(py_file)}}
|
|
1215
|
+
]
|
|
1216
|
+
},
|
|
1217
|
+
},
|
|
1218
|
+
{
|
|
1219
|
+
"type": "user",
|
|
1220
|
+
"sessionId": session_id,
|
|
1221
|
+
"timestamp": "2026-04-01T10:00:01Z",
|
|
1222
|
+
"uuid": "2b",
|
|
1223
|
+
"message": {
|
|
1224
|
+
"role": "user",
|
|
1225
|
+
"content": [{"type": "tool_result", "tool_use_id": "toolu_py_2", "content": py_file.read_text(encoding="utf-8")}],
|
|
1226
|
+
},
|
|
1227
|
+
"toolUseResult": {
|
|
1228
|
+
"type": "text",
|
|
1229
|
+
"file": {
|
|
1230
|
+
"filePath": str(py_file),
|
|
1231
|
+
"content": py_file.read_text(encoding="utf-8"),
|
|
1232
|
+
"numLines": len(py_file.read_text(encoding="utf-8").splitlines()),
|
|
1233
|
+
"startLine": 1,
|
|
1234
|
+
"totalLines": len(py_file.read_text(encoding="utf-8").splitlines()),
|
|
1235
|
+
}
|
|
1236
|
+
},
|
|
1237
|
+
},
|
|
1238
|
+
{
|
|
1239
|
+
"type": "assistant",
|
|
1240
|
+
"sessionId": session_id,
|
|
1241
|
+
"timestamp": "2026-04-01T10:00:02Z",
|
|
1242
|
+
"uuid": "3",
|
|
1243
|
+
"message": {
|
|
1244
|
+
"content": [
|
|
1245
|
+
{"type": "tool_use", "name": "Edit", "input": {"file_path": str(py_file)}}
|
|
1246
|
+
]
|
|
1247
|
+
},
|
|
1248
|
+
},
|
|
1249
|
+
{
|
|
1250
|
+
"type": "assistant",
|
|
1251
|
+
"sessionId": session_id,
|
|
1252
|
+
"timestamp": "2026-04-01T10:00:03Z",
|
|
1253
|
+
"uuid": "4",
|
|
1254
|
+
"message": {
|
|
1255
|
+
"content": [
|
|
1256
|
+
{"type": "tool_use", "name": "Read", "input": {"file_path": str(py_file)}}
|
|
1257
|
+
]
|
|
1258
|
+
},
|
|
1259
|
+
},
|
|
1260
|
+
]
|
|
1261
|
+
with transcript.open("w", encoding="utf-8") as fh:
|
|
1262
|
+
for record in records:
|
|
1263
|
+
fh.write(json.dumps(record) + "\n")
|
|
1264
|
+
return transcript
|
|
1265
|
+
|
|
1266
|
+
|
|
1267
|
+
def _create_ts_transcript_fixture(tmpdir: Path) -> Path:
|
|
1268
|
+
ts_file = tmpdir / "fixture.tsx"
|
|
1269
|
+
filler = "\n".join(f"// filler line {i} to keep this file safely above the token threshold" for i in range(260))
|
|
1270
|
+
ts_file.write_text(
|
|
1271
|
+
"import React from 'react';\n"
|
|
1272
|
+
"import { z } from 'zod';\n\n"
|
|
1273
|
+
"export interface WidgetProps {\n"
|
|
1274
|
+
" title: string;\n"
|
|
1275
|
+
" count?: number;\n"
|
|
1276
|
+
"}\n\n"
|
|
1277
|
+
"export type WidgetMode = 'compact' | 'full';\n\n"
|
|
1278
|
+
"export class WidgetService {\n"
|
|
1279
|
+
" constructor(private readonly mode: WidgetMode) {}\n"
|
|
1280
|
+
" getTitle(input: WidgetProps) {\n"
|
|
1281
|
+
" return `${input.title}:${this.mode}`;\n"
|
|
1282
|
+
" }\n"
|
|
1283
|
+
"}\n\n"
|
|
1284
|
+
"export const Widget = ({ title, count = 0 }: WidgetProps) => {\n"
|
|
1285
|
+
" return <div>{title}:{count}</div>;\n"
|
|
1286
|
+
"};\n\n"
|
|
1287
|
+
"export default Widget;\n\n"
|
|
1288
|
+
f"{filler}\n",
|
|
1289
|
+
encoding="utf-8",
|
|
1290
|
+
)
|
|
1291
|
+
transcript = tmpdir / "fixture-ts.jsonl"
|
|
1292
|
+
session_id = "fixture-ts-session"
|
|
1293
|
+
records = [
|
|
1294
|
+
{
|
|
1295
|
+
"type": "assistant",
|
|
1296
|
+
"sessionId": session_id,
|
|
1297
|
+
"timestamp": "2026-04-01T11:00:00Z",
|
|
1298
|
+
"uuid": "ts-1",
|
|
1299
|
+
"message": {
|
|
1300
|
+
"role": "assistant",
|
|
1301
|
+
"content": [
|
|
1302
|
+
{"type": "tool_use", "name": "Read", "id": "toolu_ts_1", "input": {"file_path": str(ts_file)}}
|
|
1303
|
+
],
|
|
1304
|
+
},
|
|
1305
|
+
},
|
|
1306
|
+
{
|
|
1307
|
+
"type": "user",
|
|
1308
|
+
"sessionId": session_id,
|
|
1309
|
+
"timestamp": "2026-04-01T11:00:01Z",
|
|
1310
|
+
"uuid": "ts-2",
|
|
1311
|
+
"message": {
|
|
1312
|
+
"role": "user",
|
|
1313
|
+
"content": [{"type": "tool_result", "tool_use_id": "toolu_ts_1", "content": ts_file.read_text(encoding="utf-8")}],
|
|
1314
|
+
},
|
|
1315
|
+
"toolUseResult": {
|
|
1316
|
+
"type": "text",
|
|
1317
|
+
"file": {
|
|
1318
|
+
"filePath": str(ts_file),
|
|
1319
|
+
"content": ts_file.read_text(encoding="utf-8"),
|
|
1320
|
+
"numLines": len(ts_file.read_text(encoding="utf-8").splitlines()),
|
|
1321
|
+
"startLine": 1,
|
|
1322
|
+
"totalLines": len(ts_file.read_text(encoding="utf-8").splitlines()),
|
|
1323
|
+
}
|
|
1324
|
+
},
|
|
1325
|
+
},
|
|
1326
|
+
{
|
|
1327
|
+
"type": "assistant",
|
|
1328
|
+
"sessionId": session_id,
|
|
1329
|
+
"timestamp": "2026-04-01T11:00:02Z",
|
|
1330
|
+
"uuid": "ts-3",
|
|
1331
|
+
"message": {
|
|
1332
|
+
"role": "assistant",
|
|
1333
|
+
"content": [
|
|
1334
|
+
{"type": "tool_use", "name": "Read", "id": "toolu_ts_2", "input": {"file_path": str(ts_file)}}
|
|
1335
|
+
],
|
|
1336
|
+
},
|
|
1337
|
+
},
|
|
1338
|
+
{
|
|
1339
|
+
"type": "user",
|
|
1340
|
+
"sessionId": session_id,
|
|
1341
|
+
"timestamp": "2026-04-01T11:00:03Z",
|
|
1342
|
+
"uuid": "ts-4",
|
|
1343
|
+
"message": {
|
|
1344
|
+
"role": "user",
|
|
1345
|
+
"content": [{"type": "tool_result", "tool_use_id": "toolu_ts_2", "content": ts_file.read_text(encoding="utf-8")}],
|
|
1346
|
+
},
|
|
1347
|
+
"toolUseResult": {
|
|
1348
|
+
"type": "text",
|
|
1349
|
+
"file": {
|
|
1350
|
+
"filePath": str(ts_file),
|
|
1351
|
+
"content": ts_file.read_text(encoding="utf-8"),
|
|
1352
|
+
"numLines": len(ts_file.read_text(encoding="utf-8").splitlines()),
|
|
1353
|
+
"startLine": 1,
|
|
1354
|
+
"totalLines": len(ts_file.read_text(encoding="utf-8").splitlines()),
|
|
1355
|
+
}
|
|
1356
|
+
},
|
|
1357
|
+
},
|
|
1358
|
+
]
|
|
1359
|
+
with transcript.open("w", encoding="utf-8") as fh:
|
|
1360
|
+
for record in records:
|
|
1361
|
+
fh.write(json.dumps(record) + "\n")
|
|
1362
|
+
return transcript
|
|
1363
|
+
|
|
1364
|
+
|
|
1365
|
+
def _run_torture() -> int:
|
|
1366
|
+
failures: List[str] = []
|
|
1367
|
+
with tempfile.TemporaryDirectory() as tmp:
|
|
1368
|
+
tmpdir = Path(tmp)
|
|
1369
|
+
transcript = _create_transcript_fixture(tmpdir)
|
|
1370
|
+
events = _extract_transcript_events(transcript)
|
|
1371
|
+
summary = _simulate_transcript_group(
|
|
1372
|
+
transcript,
|
|
1373
|
+
events,
|
|
1374
|
+
1,
|
|
1375
|
+
DEFAULT_MAX_BYTES,
|
|
1376
|
+
DEFAULT_MAX_LINES,
|
|
1377
|
+
DEFAULT_STRUCTURE_CAPS,
|
|
1378
|
+
DEFAULT_REMINDER_OVERHEAD_TOKENS,
|
|
1379
|
+
DEFAULT_REASON_ONLY_OVERHEAD_TOKENS,
|
|
1380
|
+
"all-supported",
|
|
1381
|
+
)
|
|
1382
|
+
if summary.candidate_events != 1:
|
|
1383
|
+
failures.append(f"expected 1 redundant candidate, got {summary.candidate_events}")
|
|
1384
|
+
if summary.eligible_replacements != 1:
|
|
1385
|
+
failures.append(f"expected 1 eligible replacement, got {summary.eligible_replacements}")
|
|
1386
|
+
if summary.repeat_replacements != 0:
|
|
1387
|
+
failures.append(f"expected 0 repeat replacements, got {summary.repeat_replacements}")
|
|
1388
|
+
if summary.net_saved_tokens <= 0:
|
|
1389
|
+
failures.append("expected positive net savings on synthetic fixture")
|
|
1390
|
+
|
|
1391
|
+
ts_transcript = _create_ts_transcript_fixture(tmpdir)
|
|
1392
|
+
ts_events = _extract_transcript_events(ts_transcript)
|
|
1393
|
+
ts_summary = _simulate_transcript_group(
|
|
1394
|
+
ts_transcript,
|
|
1395
|
+
ts_events,
|
|
1396
|
+
DEFAULT_MIN_FILE_TOKENS,
|
|
1397
|
+
DEFAULT_MAX_BYTES,
|
|
1398
|
+
DEFAULT_MAX_LINES,
|
|
1399
|
+
DEFAULT_STRUCTURE_CAPS,
|
|
1400
|
+
DEFAULT_REMINDER_OVERHEAD_TOKENS,
|
|
1401
|
+
DEFAULT_REASON_ONLY_OVERHEAD_TOKENS,
|
|
1402
|
+
"all-supported",
|
|
1403
|
+
)
|
|
1404
|
+
if ts_summary.candidate_events != 1:
|
|
1405
|
+
failures.append(f"expected 1 TS redundant candidate, got {ts_summary.candidate_events}")
|
|
1406
|
+
if ts_summary.eligible_replacements != 1:
|
|
1407
|
+
failures.append(f"expected 1 TS eligible replacement, got {ts_summary.eligible_replacements}")
|
|
1408
|
+
if ts_summary.net_saved_tokens <= 0:
|
|
1409
|
+
failures.append("expected positive TS net savings on synthetic fixture")
|
|
1410
|
+
|
|
1411
|
+
generated = tmpdir / "generated.py"
|
|
1412
|
+
generated.write_text("# generated by foo\nx = 1\n", encoding="utf-8")
|
|
1413
|
+
snap = _current_file_snapshot(str(generated), {})
|
|
1414
|
+
ok, reason = _is_supported_candidate(
|
|
1415
|
+
ReplayEvent(
|
|
1416
|
+
source_path=transcript,
|
|
1417
|
+
source_kind="transcript",
|
|
1418
|
+
session_id="fixture-session",
|
|
1419
|
+
timestamp="2026-04-01T10:00:00Z",
|
|
1420
|
+
order=0,
|
|
1421
|
+
event_kind="read",
|
|
1422
|
+
raw_file_path=str(generated),
|
|
1423
|
+
normalized_file_path=str(generated),
|
|
1424
|
+
),
|
|
1425
|
+
snap,
|
|
1426
|
+
DEFAULT_MIN_FILE_TOKENS,
|
|
1427
|
+
DEFAULT_MAX_BYTES,
|
|
1428
|
+
DEFAULT_MAX_LINES,
|
|
1429
|
+
"all-supported",
|
|
1430
|
+
)
|
|
1431
|
+
if ok:
|
|
1432
|
+
failures.append("generated-looking file should not be eligible")
|
|
1433
|
+
|
|
1434
|
+
if failures:
|
|
1435
|
+
print("[torture] FAIL")
|
|
1436
|
+
for failure in failures:
|
|
1437
|
+
print(f" - {failure}")
|
|
1438
|
+
return 1
|
|
1439
|
+
|
|
1440
|
+
print("[torture] PASS")
|
|
1441
|
+
return 0
|
|
1442
|
+
|
|
1443
|
+
|
|
1444
|
+
def build_arg_parser() -> argparse.ArgumentParser:
|
|
1445
|
+
parser = argparse.ArgumentParser(description="Replay local session artifacts for structure-aware compression proof.")
|
|
1446
|
+
parser.add_argument("paths", nargs="*", help="JSONL transcript files, decision logs, directories, or globs.")
|
|
1447
|
+
parser.add_argument("--json", action="store_true", help="Emit machine-readable JSON instead of text.")
|
|
1448
|
+
parser.add_argument("--torture", action="store_true", help="Run the built-in offline torture fixture and exit.")
|
|
1449
|
+
parser.add_argument("--min-file-tokens", type=int, default=DEFAULT_MIN_FILE_TOKENS, help="Minimum estimated file tokens before a code file is eligible.")
|
|
1450
|
+
parser.add_argument("--max-bytes", type=int, default=DEFAULT_MAX_BYTES, help="Maximum file size in bytes for structure summarization.")
|
|
1451
|
+
parser.add_argument("--max-lines", type=int, default=DEFAULT_MAX_LINES, help="Maximum line count for structure summarization.")
|
|
1452
|
+
parser.add_argument("--reminder-overhead-tokens", type=int, default=DEFAULT_REMINDER_OVERHEAD_TOKENS, help="Estimated tokens for the second identical reread reminder.")
|
|
1453
|
+
parser.add_argument("--reason-only-overhead-tokens", type=int, default=DEFAULT_REASON_ONLY_OVERHEAD_TOKENS, help="Estimated tokens for third+ identical reread reasons.")
|
|
1454
|
+
parser.add_argument("--signatures-cap", type=int, default=DEFAULT_STRUCTURE_CAPS["signatures"], help="Maximum characters for signatures view.")
|
|
1455
|
+
parser.add_argument("--top-level-cap", type=int, default=DEFAULT_STRUCTURE_CAPS["top_level"], help="Maximum characters for top-level view.")
|
|
1456
|
+
parser.add_argument("--skeleton-cap", type=int, default=DEFAULT_STRUCTURE_CAPS["skeleton"], help="Maximum characters for skeleton view.")
|
|
1457
|
+
parser.add_argument("--language-scope", choices=["all-supported", "python-only"], default="all-supported", help="Replay either all supported code languages or the original Python-only slice.")
|
|
1458
|
+
parser.add_argument("--cwd-contains", action="append", default=[], help="Only include transcript events whose cwd contains this substring. Repeatable.")
|
|
1459
|
+
parser.add_argument("--exclude-cwd-contains", action="append", default=[], help="Exclude transcript events whose cwd contains this substring. Repeatable.")
|
|
1460
|
+
return parser
|
|
1461
|
+
|
|
1462
|
+
|
|
1463
|
+
def main(argv: Optional[Sequence[str]] = None) -> int:
|
|
1464
|
+
parser = build_arg_parser()
|
|
1465
|
+
args = parser.parse_args(argv)
|
|
1466
|
+
|
|
1467
|
+
if args.torture:
|
|
1468
|
+
return _run_torture()
|
|
1469
|
+
|
|
1470
|
+
raw_paths = list(args.paths)
|
|
1471
|
+
path_objs = _gather_input_paths(raw_paths)
|
|
1472
|
+
if not path_objs:
|
|
1473
|
+
print("No input paths found.", file=sys.stderr)
|
|
1474
|
+
return 1
|
|
1475
|
+
|
|
1476
|
+
transcript_events, decision_events = _load_replay_events(path_objs)
|
|
1477
|
+
transcript_events = _filter_transcript_events(
|
|
1478
|
+
transcript_events,
|
|
1479
|
+
cwd_contains=args.cwd_contains,
|
|
1480
|
+
exclude_cwd_contains=args.exclude_cwd_contains,
|
|
1481
|
+
)
|
|
1482
|
+
caps = {
|
|
1483
|
+
"signatures": max(1, args.signatures_cap),
|
|
1484
|
+
"top_level": max(1, args.top_level_cap),
|
|
1485
|
+
"skeleton": max(1, args.skeleton_cap),
|
|
1486
|
+
}
|
|
1487
|
+
|
|
1488
|
+
transcript_summary = None
|
|
1489
|
+
if transcript_events:
|
|
1490
|
+
transcript_summary = _simulate_transcript_group(
|
|
1491
|
+
source_path=path_objs[0],
|
|
1492
|
+
events=transcript_events,
|
|
1493
|
+
min_file_tokens=max(1, args.min_file_tokens),
|
|
1494
|
+
max_bytes=max(1, args.max_bytes),
|
|
1495
|
+
max_lines=max(1, args.max_lines),
|
|
1496
|
+
caps=caps,
|
|
1497
|
+
reminder_overhead_tokens=max(0, args.reminder_overhead_tokens),
|
|
1498
|
+
reason_only_overhead_tokens=max(0, args.reason_only_overhead_tokens),
|
|
1499
|
+
language_scope=args.language_scope,
|
|
1500
|
+
)
|
|
1501
|
+
transcript_summary.source_count = len({event.source_path for event in transcript_events}) or 1
|
|
1502
|
+
|
|
1503
|
+
decision_summary = None
|
|
1504
|
+
if decision_events:
|
|
1505
|
+
decision_summary = _simulate_decision_log_group(
|
|
1506
|
+
source_path=path_objs[0],
|
|
1507
|
+
events=decision_events,
|
|
1508
|
+
min_file_tokens=max(1, args.min_file_tokens),
|
|
1509
|
+
max_bytes=max(1, args.max_bytes),
|
|
1510
|
+
max_lines=max(1, args.max_lines),
|
|
1511
|
+
caps=caps,
|
|
1512
|
+
language_scope=args.language_scope,
|
|
1513
|
+
)
|
|
1514
|
+
decision_summary.source_count = len({event.source_path for event in decision_events}) or 1
|
|
1515
|
+
|
|
1516
|
+
if args.json:
|
|
1517
|
+
payload = {
|
|
1518
|
+
"inputs": [str(path) for path in path_objs],
|
|
1519
|
+
"filters": {
|
|
1520
|
+
"language_scope": args.language_scope,
|
|
1521
|
+
"cwd_contains": list(args.cwd_contains),
|
|
1522
|
+
"exclude_cwd_contains": list(args.exclude_cwd_contains),
|
|
1523
|
+
},
|
|
1524
|
+
"transcript": _summary_to_dict(transcript_summary) if transcript_summary else None,
|
|
1525
|
+
"decision_log": _summary_to_dict(decision_summary) if decision_summary else None,
|
|
1526
|
+
}
|
|
1527
|
+
print(json.dumps(payload, indent=2, sort_keys=True))
|
|
1528
|
+
return 0
|
|
1529
|
+
|
|
1530
|
+
print("Structure-aware replay proof")
|
|
1531
|
+
print("============================")
|
|
1532
|
+
print(f"inputs: {len(path_objs)}")
|
|
1533
|
+
print(f"language scope: {args.language_scope}")
|
|
1534
|
+
if args.cwd_contains or args.exclude_cwd_contains:
|
|
1535
|
+
print(f"cwd filters: include={list(args.cwd_contains)} exclude={list(args.exclude_cwd_contains)}")
|
|
1536
|
+
print(f"transcript events: {len(transcript_events)}")
|
|
1537
|
+
print(f"decision-log events: {len(decision_events)}")
|
|
1538
|
+
if transcript_summary:
|
|
1539
|
+
_print_summary(transcript_summary, "transcript replay")
|
|
1540
|
+
else:
|
|
1541
|
+
print("\n[transcript replay]")
|
|
1542
|
+
print(" no transcript data found")
|
|
1543
|
+
if decision_summary:
|
|
1544
|
+
_print_summary(decision_summary, "decision-log replay")
|
|
1545
|
+
elif decision_events:
|
|
1546
|
+
print("\n[decision-log replay]")
|
|
1547
|
+
print(" no usable decision entries found")
|
|
1548
|
+
print("\nNotes:")
|
|
1549
|
+
print(" - Transcript and decision-log totals are reported separately to avoid double counting.")
|
|
1550
|
+
print(" - Transcript replay prefers historical Read tool results when available and falls back to current local file state otherwise.")
|
|
1551
|
+
print(" - Quality impact is proxy-only here; this tool is a savings proof runner, not a runtime hook.")
|
|
1552
|
+
return 0
|
|
1553
|
+
|
|
1554
|
+
|
|
1555
|
+
if __name__ == "__main__":
|
|
1556
|
+
raise SystemExit(main())
|