@alexgreensh/token-optimizer 5.13.69 → 5.13.70
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +2 -2
- package/.claude-plugin/plugin.json +1 -1
- package/PRIVACY.md +4 -0
- package/hooks/hooks.json +11 -1
- package/hooks/module_runner.py +4 -1
- package/hooks/posttooluse_runner.py +44 -48
- package/hooks/sessionstart_runner.py +24 -5
- package/hooks/stop_runner.py +6 -6
- package/package.json +1 -1
- package/skills/token-optimizer/assets/dashboard.html +399 -509
- package/skills/token-optimizer/assets/savings_story.js +661 -0
- package/skills/token-optimizer/pricing/prices.json +1 -0
- package/skills/token-optimizer/references/implementation-playbook.md +3 -0
- package/skills/token-optimizer/scripts/_measure/__init__.py +3 -1
- package/skills/token-optimizer/scripts/_measure/archive_health.py +14 -0
- package/skills/token-optimizer/scripts/_measure/archive_void_codex.py +163 -0
- package/skills/token-optimizer/scripts/_measure/archive_void_evidence.py +165 -0
- package/skills/token-optimizer/scripts/_measure/audit.py +27 -135
- package/skills/token-optimizer/scripts/_measure/baseline_provenance.py +339 -0
- package/skills/token-optimizer/scripts/_measure/cache_policy.py +261 -581
- package/skills/token-optimizer/scripts/_measure/checkpoint_direction.py +97 -0
- package/skills/token-optimizer/scripts/_measure/checkpoint_retention.py +20 -0
- package/skills/token-optimizer/scripts/_measure/cli.py +12 -8
- package/skills/token-optimizer/scripts/_measure/codex_quality.py +246 -0
- package/skills/token-optimizer/scripts/_measure/compaction_survival.py +158 -0
- package/skills/token-optimizer/scripts/_measure/compression_fixture_void.py +147 -0
- package/skills/token-optimizer/scripts/_measure/compression_scan_checkpoint.py +72 -0
- package/skills/token-optimizer/scripts/_measure/context_reset_marker.py +64 -0
- package/skills/token-optimizer/scripts/_measure/continuity.py +64 -118
- package/skills/token-optimizer/scripts/_measure/cost_per_message_trend.py +40 -0
- package/skills/token-optimizer/scripts/_measure/counted_cap.py +28 -0
- package/skills/token-optimizer/scripts/_measure/counted_orphans.py +190 -0
- package/skills/token-optimizer/scripts/_measure/counted_position.py +20 -0
- package/skills/token-optimizer/scripts/_measure/counted_pricing_v5.py +267 -0
- package/skills/token-optimizer/scripts/_measure/counted_subagents.py +371 -0
- package/skills/token-optimizer/scripts/_measure/coverage_report.py +285 -0
- package/skills/token-optimizer/scripts/_measure/daemon.py +53 -74
- package/skills/token-optimizer/scripts/_measure/dashboard.py +87 -151
- package/skills/token-optimizer/scripts/_measure/dashboard_heal_claim.py +36 -0
- package/skills/token-optimizer/scripts/_measure/evidence_parallel.py +95 -0
- package/skills/token-optimizer/scripts/_measure/feature_health.py +256 -0
- package/skills/token-optimizer/scripts/_measure/file_refetch.py +250 -0
- package/skills/token-optimizer/scripts/_measure/first_call_context.py +216 -0
- package/skills/token-optimizer/scripts/_measure/first_read_outcomes.py +261 -0
- package/skills/token-optimizer/scripts/_measure/first_read_revive.py +137 -0
- package/skills/token-optimizer/scripts/_measure/fixture_context.py +65 -0
- package/skills/token-optimizer/scripts/_measure/headline.py +100 -0
- package/skills/token-optimizer/scripts/_measure/holdout_fallback.py +96 -0
- package/skills/token-optimizer/scripts/_measure/holdout_report.py +125 -0
- package/skills/token-optimizer/scripts/_measure/keepwarm_economics.py +201 -0
- package/skills/token-optimizer/scripts/_measure/keepwarm_fork.py +140 -0
- package/skills/token-optimizer/scripts/_measure/keepwarm_guard.py +35 -0
- package/skills/token-optimizer/scripts/_measure/keepwarm_guard_server.py +85 -0
- package/skills/token-optimizer/scripts/_measure/keepwarm_linux.py +121 -0
- package/skills/token-optimizer/scripts/_measure/keepwarm_prefix.py +143 -0
- package/skills/token-optimizer/scripts/_measure/keepwarm_response_filter.py +84 -0
- package/skills/token-optimizer/scripts/_measure/keepwarm_safety.py +256 -0
- package/skills/token-optimizer/scripts/_measure/lean_resume_receivers.py +260 -0
- package/skills/token-optimizer/scripts/_measure/lean_resume_threshold.py +76 -0
- package/skills/token-optimizer/scripts/_measure/lease_candidate_cleanup.py +82 -0
- package/skills/token-optimizer/scripts/_measure/lifecycle.py +54 -162
- package/skills/token-optimizer/scripts/_measure/mcp_archive_tripwire.py +120 -0
- package/skills/token-optimizer/scripts/_measure/mod_action_booking.py +178 -0
- package/skills/token-optimizer/scripts/_measure/mod_compaction_booking.py +276 -0
- package/skills/token-optimizer/scripts/_measure/mod_fresh_booking.py +105 -0
- package/skills/token-optimizer/scripts/_measure/output_reread.py +629 -0
- package/skills/token-optimizer/scripts/_measure/own_price_card.py +268 -0
- package/skills/token-optimizer/scripts/_measure/periphery_exposure.py +85 -0
- package/skills/token-optimizer/scripts/_measure/pricing.py +152 -87
- package/skills/token-optimizer/scripts/_measure/quality_archive.py +159 -215
- package/skills/token-optimizer/scripts/_measure/quality_checkpoint.py +173 -0
- package/skills/token-optimizer/scripts/_measure/quality_continuity.py +43 -0
- package/skills/token-optimizer/scripts/_measure/rework_metrics.py +194 -0
- package/skills/token-optimizer/scripts/_measure/routing_period.py +48 -0
- package/skills/token-optimizer/scripts/_measure/savings.py +431 -863
- package/skills/token-optimizer/scripts/_measure/savings_story.py +187 -0
- package/skills/token-optimizer/scripts/_measure/session_best.py +24 -0
- package/skills/token-optimizer/scripts/_measure/session_effect.py +557 -0
- package/skills/token-optimizer/scripts/_measure/session_flush_lock.py +75 -0
- package/skills/token-optimizer/scripts/_measure/session_store_spool.py +220 -0
- package/skills/token-optimizer/scripts/_measure/sessions.py +96 -196
- package/skills/token-optimizer/scripts/_measure/setup_attachment_counter.py +196 -0
- package/skills/token-optimizer/scripts/_measure/setup_budget_monitor.py +180 -0
- package/skills/token-optimizer/scripts/_measure/setup_connector_ledger.py +126 -0
- package/skills/token-optimizer/scripts/_measure/setup_step.py +220 -0
- package/skills/token-optimizer/scripts/_measure/status_bar_lock.py +117 -0
- package/skills/token-optimizer/scripts/_measure/structural_archives.py +79 -0
- package/skills/token-optimizer/scripts/_measure/structural_dedupe.py +91 -0
- package/skills/token-optimizer/scripts/_measure/structural_ledger.py +418 -0
- package/skills/token-optimizer/scripts/_measure/structural_listing.py +163 -0
- package/skills/token-optimizer/scripts/_measure/structural_report.py +339 -0
- package/skills/token-optimizer/scripts/_measure/structural_seed.py +164 -0
- package/skills/token-optimizer/scripts/_measure/structural_value.py +248 -0
- package/skills/token-optimizer/scripts/_measure/structure_funnel.py +97 -0
- package/skills/token-optimizer/scripts/_measure/timestamp_cache.py +11 -0
- package/skills/token-optimizer/scripts/_measure/token_type_split.py +29 -0
- package/skills/token-optimizer/scripts/_measure/transcript_backfill.py +419 -0
- package/skills/token-optimizer/scripts/_measure/transcript_product.py +228 -0
- package/skills/token-optimizer/scripts/_measure/transcript_stream.py +279 -0
- package/skills/token-optimizer/scripts/_measure/trends.py +44 -185
- package/skills/token-optimizer/scripts/_measure/ttl_period.py +6 -0
- package/skills/token-optimizer/scripts/_measure/upgrade_drain_control.py +287 -0
- package/skills/token-optimizer/scripts/activity_tracker.py +4 -33
- package/skills/token-optimizer/scripts/antigravity_install.py +2 -0
- package/skills/token-optimizer/scripts/archive_result.py +15 -19
- package/skills/token-optimizer/scripts/archive_verify.py +165 -0
- package/skills/token-optimizer/scripts/bash_compress.py +14 -43
- package/skills/token-optimizer/scripts/bash_compress_hook.py +132 -2
- package/skills/token-optimizer/scripts/checkpoint_state.py +2 -2
- package/skills/token-optimizer/scripts/cloud_kit.py +3 -6
- package/skills/token-optimizer/scripts/codemap.py +274 -0
- package/skills/token-optimizer/scripts/codemap_hint.py +153 -0
- package/skills/token-optimizer/scripts/codemap_index.py +656 -0
- package/skills/token-optimizer/scripts/codemap_ledger.py +309 -0
- package/skills/token-optimizer/scripts/codemap_reread.py +161 -0
- package/skills/token-optimizer/scripts/codex_doctor.py +9 -1
- package/skills/token-optimizer/scripts/codex_log_index.py +34 -15
- package/skills/token-optimizer/scripts/codex_session.py +16 -216
- package/skills/token-optimizer/scripts/compression_backfill.py +4 -35
- package/skills/token-optimizer/scripts/context_intel.py +5 -3
- package/skills/token-optimizer/scripts/copilot_install.py +2 -0
- package/skills/token-optimizer/scripts/coverage_funnel.py +261 -0
- package/skills/token-optimizer/scripts/cursor_install.py +12 -0
- package/skills/token-optimizer/scripts/cursor_quality.py +16 -64
- package/skills/token-optimizer/scripts/dashboard_assets.py +21 -0
- package/skills/token-optimizer/scripts/deterministic_candidates.py +2 -10
- package/skills/token-optimizer/scripts/devin_source.py +8 -3
- package/skills/token-optimizer/scripts/devin_verify.py +7 -1
- package/skills/token-optimizer/scripts/grok_install.py +2 -0
- package/skills/token-optimizer/scripts/heal_report.py +7 -6
- package/skills/token-optimizer/scripts/hermes_doctor.py +9 -1
- package/skills/token-optimizer/scripts/hermes_install.py +7 -1
- package/skills/token-optimizer/scripts/hermes_session.py +14 -136
- package/skills/token-optimizer/scripts/hint_paths.py +21 -0
- package/skills/token-optimizer/scripts/holdout.py +136 -0
- package/skills/token-optimizer/scripts/hook_runtime.py +1 -0
- package/skills/token-optimizer/scripts/hook_skip_log.py +89 -0
- package/skills/token-optimizer/scripts/large_transcripts.py +31 -0
- package/skills/token-optimizer/scripts/lean_resume_carry.py +518 -0
- package/skills/token-optimizer/scripts/measure.py +34 -76
- package/skills/token-optimizer/scripts/post_run_classify.py +349 -0
- package/skills/token-optimizer/scripts/preserved_reinject.py +54 -0
- package/skills/token-optimizer/scripts/read_cache.py +99 -100
- package/skills/token-optimizer/scripts/reset_epoch.py +3 -3
- package/skills/token-optimizer/scripts/session_store.py +49 -99
- package/skills/token-optimizer/scripts/session_store_guard.py +75 -0
- package/skills/token-optimizer/scripts/settings_backup.py +379 -0
- package/skills/token-optimizer/scripts/shipped_hook_templates.py +1 -0
- package/skills/token-optimizer/scripts/statusline.js +1 -1
- package/skills/token-optimizer/scripts/structural.py +25 -0
- package/skills/token-optimizer/scripts/structure_map.py +4 -26
|
@@ -0,0 +1,371 @@
|
|
|
1
|
+
"""Score a removal made inside a sub-agent against that sub-agent's own turns.
|
|
2
|
+
|
|
3
|
+
Claude Code writes each sub-agent (Task/Agent tool) to its own transcript,
|
|
4
|
+
``<session>/subagents/agent-<id>.jsonl``, and its hooks log to the parent
|
|
5
|
+
session's id. The counted pass used to walk only the parent transcript, so a
|
|
6
|
+
compression that happened inside a sub-agent was credited with the parent's
|
|
7
|
+
later turns: turns that never held that content. Pricing version 6 moves each
|
|
8
|
+
such removal onto the turns of the transcript that actually held it, up to that
|
|
9
|
+
sub-agent's end or its own compaction, priced per turn at the exact card of the
|
|
10
|
+
model that ran each turn (sub-agents often run a different model).
|
|
11
|
+
|
|
12
|
+
Locating an event (never by time alone):
|
|
13
|
+
* ``tool_archive_reexpand``: the archived result's tool_use_id is in the
|
|
14
|
+
event detail; the transcript holding that tool result is the location.
|
|
15
|
+
* ``tool_archive``: the detail states the tool and the original size; the
|
|
16
|
+
location is the tool result of that tool whose archive pointer states the
|
|
17
|
+
same size, nearest in time.
|
|
18
|
+
* compression rows with a command: the Bash tool result whose command,
|
|
19
|
+
redacted and cut the way the hook stores it, equals the stored command.
|
|
20
|
+
* anything else, no candidate, or candidates in two transcripts at about the
|
|
21
|
+
same time: the event stays on the parent (the previous behaviour) and is
|
|
22
|
+
counted as unlocated or ambiguous.
|
|
23
|
+
|
|
24
|
+
The facade is passed in (helpers and constants), so this module holds no
|
|
25
|
+
import-time state and imports nothing from measure.
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
import hashlib
|
|
29
|
+
from . import transcript_stream
|
|
30
|
+
import json
|
|
31
|
+
import re
|
|
32
|
+
import sqlite3
|
|
33
|
+
from datetime import datetime
|
|
34
|
+
from pathlib import Path
|
|
35
|
+
|
|
36
|
+
# Candidate tool results further than this from the logged event are not it.
|
|
37
|
+
MATCH_SECONDS = 120
|
|
38
|
+
# Candidates in two different transcripts this close together are ambiguous.
|
|
39
|
+
TIE_SECONDS = 2
|
|
40
|
+
SCOPE_PARENT = "parent"
|
|
41
|
+
SCOPE_SUBAGENT = "subagent"
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def collect_stats():
|
|
45
|
+
return dict.fromkeys(("located_subagent", "located_parent", "unlocated", "ambiguous"), 0)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def add_stats(total, session):
|
|
49
|
+
for key, count in session.items():
|
|
50
|
+
total[key] += count
|
|
51
|
+
|
|
52
|
+
_TOOL_USE_ID_RX = re.compile(r"\b(toolu_[A-Za-z0-9_\-]+)")
|
|
53
|
+
_ARCHIVE_DETAIL_RX = re.compile(r"replaced (\S+) \(([\d,]+) chars")
|
|
54
|
+
_POINTER_SIZE_RX = re.compile(r"\[Full result archived \((\d{1,3}(?:,\d{3})*|\d+) chars")
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def walk(facade, path, collect_markers=None, sidechain=False):
|
|
58
|
+
"""One pass over a transcript for the counted-cumulative engine.
|
|
59
|
+
|
|
60
|
+
Returns (turns, compacts, markers):
|
|
61
|
+
turns = [(utc-naive datetime, raw model id, full prompt tokens,
|
|
62
|
+
(cache write tokens, 1h part, 5m part, cache read tokens) or None)]
|
|
63
|
+
-- API calls, deduped on requestId/message.id (Claude Code
|
|
64
|
+
writes one assistant line per content block, all sharing the
|
|
65
|
+
same usage);
|
|
66
|
+
compacts= [utc-naive datetime] of real compact_boundary system lines;
|
|
67
|
+
markers = [(utc-naive datetime-or-None, tokens-or-None)] for
|
|
68
|
+
"Full result archived" injections (collect_markers only).
|
|
69
|
+
A parent transcript (sidechain=False) skips sidechain records; a sub-agent
|
|
70
|
+
transcript (sidechain=True) is made only of them, so they are its turns.
|
|
71
|
+
Never raises; returns ([], [], []) on unreadable files.
|
|
72
|
+
"""
|
|
73
|
+
turns, compacts, markers = [], [], []
|
|
74
|
+
seen = {}
|
|
75
|
+
last_ts = None
|
|
76
|
+
try:
|
|
77
|
+
with transcript_stream.open_transcript(path) as f:
|
|
78
|
+
for line in f:
|
|
79
|
+
if collect_markers and "Full result archived" in line:
|
|
80
|
+
m = facade._COUNTED_MARKER_RX.search(line)
|
|
81
|
+
tok = None
|
|
82
|
+
if m and m.group(1):
|
|
83
|
+
tok = max(1, int(m.group(1).replace(",", "")) // 4)
|
|
84
|
+
markers.append((last_ts, tok))
|
|
85
|
+
if '"assistant"' not in line and "compact_boundary" not in line:
|
|
86
|
+
continue
|
|
87
|
+
try:
|
|
88
|
+
d = facade.json.loads(line)
|
|
89
|
+
except (facade.json.JSONDecodeError, ValueError):
|
|
90
|
+
continue
|
|
91
|
+
if not isinstance(d, dict):
|
|
92
|
+
continue
|
|
93
|
+
t = d.get("type")
|
|
94
|
+
ts = d.get("timestamp")
|
|
95
|
+
dt = None
|
|
96
|
+
if ts:
|
|
97
|
+
try:
|
|
98
|
+
dt = facade.datetime.strptime(str(ts)[:19], "%Y-%m-%dT%H:%M:%S")
|
|
99
|
+
except (ValueError, TypeError):
|
|
100
|
+
dt = None
|
|
101
|
+
if dt is not None:
|
|
102
|
+
last_ts = dt
|
|
103
|
+
if t == "system" and d.get("subtype") == "compact_boundary":
|
|
104
|
+
if dt is not None:
|
|
105
|
+
compacts.append(dt)
|
|
106
|
+
continue
|
|
107
|
+
if t != "assistant" or (d.get("isSidechain") and not sidechain):
|
|
108
|
+
continue
|
|
109
|
+
msg = d.get("message") or {}
|
|
110
|
+
if not isinstance(msg, dict) or not msg.get("usage"):
|
|
111
|
+
continue
|
|
112
|
+
rid = facade._usage_request_key(d, msg)
|
|
113
|
+
if dt is None:
|
|
114
|
+
continue
|
|
115
|
+
# Raw model id: re-reads are priced by generation card
|
|
116
|
+
# (Opus 5.5 and Fable 5.1 read cache far cheaper than their family).
|
|
117
|
+
raw_model = msg.get("model")
|
|
118
|
+
usage = msg["usage"] if isinstance(msg["usage"], dict) else {}
|
|
119
|
+
prompt_parts = {k: usage[k] for k in (
|
|
120
|
+
"input_tokens", "cache_read_input_tokens", "cache_creation_input_tokens") if k in usage}
|
|
121
|
+
nested = usage.get("cache_creation")
|
|
122
|
+
nested = nested if isinstance(nested, dict) else {}
|
|
123
|
+
for key in ("ephemeral_1h_input_tokens", "ephemeral_5m_input_tokens"):
|
|
124
|
+
if key in nested or key in usage:
|
|
125
|
+
prompt_parts[key] = nested.get(key) or usage.get(key, 0)
|
|
126
|
+
if rid is not None and rid in seen:
|
|
127
|
+
index, previous_parts = seen[rid]
|
|
128
|
+
for key, value in previous_parts.items():
|
|
129
|
+
current = prompt_parts.get(key)
|
|
130
|
+
if isinstance(value, int) and (not isinstance(current, int) or value > current):
|
|
131
|
+
prompt_parts[key] = value
|
|
132
|
+
prompt_tokens = None
|
|
133
|
+
cache_class = None
|
|
134
|
+
if ("input_tokens" in prompt_parts
|
|
135
|
+
and all(isinstance(v, int) and v >= 0 for v in prompt_parts.values())):
|
|
136
|
+
# Flat and TTL fields describe overlapping cache writes.
|
|
137
|
+
# Partial chunks can fill either form; never add both.
|
|
138
|
+
creation = max(prompt_parts.get("cache_creation_input_tokens", 0),
|
|
139
|
+
prompt_parts.get("ephemeral_1h_input_tokens", 0)
|
|
140
|
+
+ prompt_parts.get("ephemeral_5m_input_tokens", 0))
|
|
141
|
+
prompt_tokens = facade._context_token_count(dict(prompt_parts, cache_creation_input_tokens=creation))
|
|
142
|
+
cache_class = (creation, prompt_parts.get("ephemeral_1h_input_tokens", 0),
|
|
143
|
+
prompt_parts.get("ephemeral_5m_input_tokens", 0),
|
|
144
|
+
prompt_parts.get("cache_read_input_tokens", 0))
|
|
145
|
+
if rid is not None and rid in seen:
|
|
146
|
+
previous = turns[index]
|
|
147
|
+
turns[index] = (previous[0], previous[1] or raw_model, prompt_tokens, cache_class)
|
|
148
|
+
seen[rid] = (index, prompt_parts)
|
|
149
|
+
continue
|
|
150
|
+
if rid is not None:
|
|
151
|
+
seen[rid] = (len(turns), prompt_parts)
|
|
152
|
+
turns.append((dt, raw_model if isinstance(raw_model, str)
|
|
153
|
+
and not raw_model.startswith("<") else None, prompt_tokens, cache_class))
|
|
154
|
+
except (OSError, PermissionError):
|
|
155
|
+
return [], [], []
|
|
156
|
+
turns.sort(key=lambda x: x[0])
|
|
157
|
+
compacts.sort()
|
|
158
|
+
return turns, compacts, markers
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def subagent_files(path):
|
|
162
|
+
"""Sub-agent transcripts of a parent session transcript, sorted. Never raises."""
|
|
163
|
+
try:
|
|
164
|
+
folder = Path(path).with_suffix("") / "subagents"
|
|
165
|
+
return sorted(folder.glob("*.jsonl")) if folder.is_dir() else []
|
|
166
|
+
except (OSError, TypeError, ValueError):
|
|
167
|
+
return []
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def _texts(content):
|
|
171
|
+
if isinstance(content, str):
|
|
172
|
+
return [content]
|
|
173
|
+
out = []
|
|
174
|
+
if isinstance(content, list):
|
|
175
|
+
for block in content:
|
|
176
|
+
if isinstance(block, dict) and block.get("type") == "text" and isinstance(block.get("text"), str):
|
|
177
|
+
out.append(block["text"])
|
|
178
|
+
return out
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def index_results(path, sidechain):
|
|
182
|
+
"""Tool results in one transcript: [(utc-naive dt, tool_use_id, tool name,
|
|
183
|
+
command or None, pointer original chars or None)]. Never raises."""
|
|
184
|
+
uses, results = {}, []
|
|
185
|
+
try:
|
|
186
|
+
with transcript_stream.open_transcript(path) as stream:
|
|
187
|
+
for line in stream:
|
|
188
|
+
if '"tool_use"' not in line and '"tool_result"' not in line:
|
|
189
|
+
continue
|
|
190
|
+
try:
|
|
191
|
+
record = json.loads(line)
|
|
192
|
+
except ValueError:
|
|
193
|
+
continue
|
|
194
|
+
if not isinstance(record, dict) or (record.get("isSidechain") and not sidechain):
|
|
195
|
+
continue
|
|
196
|
+
message = record.get("message")
|
|
197
|
+
content = message.get("content") if isinstance(message, dict) else None
|
|
198
|
+
if not isinstance(content, list):
|
|
199
|
+
continue
|
|
200
|
+
for block in content:
|
|
201
|
+
if not isinstance(block, dict):
|
|
202
|
+
continue
|
|
203
|
+
if block.get("type") == "tool_use" and block.get("id"):
|
|
204
|
+
command = (block.get("input") or {}).get("command") if isinstance(block.get("input"), dict) else None
|
|
205
|
+
uses[block["id"]] = (block.get("name"), command if isinstance(command, str) else None)
|
|
206
|
+
continue
|
|
207
|
+
if block.get("type") != "tool_result":
|
|
208
|
+
continue
|
|
209
|
+
try:
|
|
210
|
+
dt = datetime.strptime(str(record.get("timestamp"))[:19], "%Y-%m-%dT%H:%M:%S")
|
|
211
|
+
except (ValueError, TypeError):
|
|
212
|
+
continue
|
|
213
|
+
text = "\n".join(_texts(block.get("content")))
|
|
214
|
+
size = _POINTER_SIZE_RX.search(text[-2000:]) if "Full result archived" in text else None
|
|
215
|
+
name, command = uses.get(block.get("tool_use_id"), (None, None))
|
|
216
|
+
results.append((dt, block.get("tool_use_id"), name, command,
|
|
217
|
+
int(size.group(1).replace(",", "")) if size else None))
|
|
218
|
+
except (OSError, PermissionError):
|
|
219
|
+
return []
|
|
220
|
+
return results
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def _stored_command(command):
|
|
224
|
+
"""The command as the hook stores it: redacted, then cut to 100 chars."""
|
|
225
|
+
try:
|
|
226
|
+
from credential_patterns import redact_credentials
|
|
227
|
+
return redact_credentials(command)[:100]
|
|
228
|
+
except Exception:
|
|
229
|
+
return command[:100]
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def event_info(conn, keys):
|
|
233
|
+
"""{event_key: (kind, a, b)} from the ledger rows behind counted keys."""
|
|
234
|
+
out = {}
|
|
235
|
+
se = [int(k[3:]) for k in keys if k.startswith("se:") and k[3:].isdigit()]
|
|
236
|
+
ce = [int(k[3:]) for k in keys if k.startswith("ce:") and k[3:].isdigit()]
|
|
237
|
+
for chunk in range(0, len(se), 500):
|
|
238
|
+
part = se[chunk:chunk + 500]
|
|
239
|
+
for rid, kind, detail in conn.execute(
|
|
240
|
+
"SELECT id, event_type, detail FROM savings_events WHERE id IN (%s)"
|
|
241
|
+
% ",".join("?" * len(part)), part):
|
|
242
|
+
out["se:%d" % rid] = (kind, detail or "", None)
|
|
243
|
+
for chunk in range(0, len(ce), 500):
|
|
244
|
+
part = ce[chunk:chunk + 500]
|
|
245
|
+
for rid, feature, pattern, detail in conn.execute(
|
|
246
|
+
"SELECT id, feature, command_pattern, detail FROM compression_events WHERE id IN (%s)"
|
|
247
|
+
% ",".join("?" * len(part)), part):
|
|
248
|
+
marker = "missing-scope" if feature == "first_read_skeleton" and str(detail or "").endswith("; subagent") else None
|
|
249
|
+
out["ce:%d" % rid] = (feature, pattern or "", marker)
|
|
250
|
+
try:
|
|
251
|
+
for rid, tool_hash in conn.execute(
|
|
252
|
+
"SELECT event_id,tool_id_hash FROM first_read_confirmation_scopes WHERE event_id IN (%s)"
|
|
253
|
+
% ",".join("?" * len(part)), part):
|
|
254
|
+
key = "ce:%d" % rid
|
|
255
|
+
if key in out:
|
|
256
|
+
out[key] = (out[key][0], out[key][1], tool_hash)
|
|
257
|
+
except sqlite3.OperationalError:
|
|
258
|
+
pass
|
|
259
|
+
return out
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
class SessionScope:
|
|
263
|
+
"""Where each counted event of one session happened, and its turns there.
|
|
264
|
+
|
|
265
|
+
Built once per session walk. With no sub-agent transcript on disk every
|
|
266
|
+
event stays on the parent and nothing beyond a directory check is read.
|
|
267
|
+
"""
|
|
268
|
+
|
|
269
|
+
def __init__(self, facade, conn, path, events):
|
|
270
|
+
"""events: [(event_key, local-naive timestamp)]."""
|
|
271
|
+
self.facade = facade
|
|
272
|
+
self.files = subagent_files(path)
|
|
273
|
+
self.location = {}
|
|
274
|
+
self.required_subagents = set()
|
|
275
|
+
self.fail_closed = False
|
|
276
|
+
self.stats = collect_stats()
|
|
277
|
+
self._walks = {}
|
|
278
|
+
if not events:
|
|
279
|
+
return
|
|
280
|
+
try:
|
|
281
|
+
info = event_info(conn, [key for key, _ts in events])
|
|
282
|
+
except Exception:
|
|
283
|
+
self.fail_closed = True
|
|
284
|
+
return
|
|
285
|
+
self.required_subagents = {key for key, data in info.items() if data[0] == "first_read_skeleton" and data[2]}
|
|
286
|
+
if not self.files:
|
|
287
|
+
self.stats["unlocated"] += len(self.required_subagents)
|
|
288
|
+
return
|
|
289
|
+
results = [(dt, -1, tid, name, cmd, size) for dt, tid, name, cmd, size in index_results(path, False)]
|
|
290
|
+
for index, sub in enumerate(self.files):
|
|
291
|
+
results += [(dt, index, tid, name, cmd, size) for dt, tid, name, cmd, size in index_results(sub, True)]
|
|
292
|
+
by_id = {r[2]: r for r in results if r[2]}
|
|
293
|
+
used = set()
|
|
294
|
+
stored_commands = {}
|
|
295
|
+
for key, ts in sorted(events, key=lambda e: str(e[1])):
|
|
296
|
+
ev_dt = facade._counted_event_utc(ts)
|
|
297
|
+
kind = info.get(key)
|
|
298
|
+
if ev_dt is None or kind is None:
|
|
299
|
+
self.stats["unlocated"] += 1
|
|
300
|
+
continue
|
|
301
|
+
name, detail, _ = kind
|
|
302
|
+
if key in self.required_subagents:
|
|
303
|
+
hits = [r for r in results if r[2] and hashlib.sha256(str(r[2]).encode("utf-8", "replace")).hexdigest() == kind[2]]
|
|
304
|
+
scopes = {r[1] for r in hits}
|
|
305
|
+
if len(scopes) == 1 and next(iter(scopes)) >= 0:
|
|
306
|
+
self._place(key, hits[:1], ev_dt, used, exact_id=True)
|
|
307
|
+
else:
|
|
308
|
+
self.stats["ambiguous" if len(scopes) > 1 else "unlocated"] += 1
|
|
309
|
+
continue
|
|
310
|
+
if name == "tool_archive_reexpand":
|
|
311
|
+
match = _TOOL_USE_ID_RX.search(detail)
|
|
312
|
+
hit = by_id.get(match.group(1)) if match else None
|
|
313
|
+
self._place(key, [hit] if hit else [], ev_dt, used, exact_id=True)
|
|
314
|
+
continue
|
|
315
|
+
if name == "tool_archive":
|
|
316
|
+
match = _ARCHIVE_DETAIL_RX.search(detail)
|
|
317
|
+
if not match:
|
|
318
|
+
self.stats["unlocated"] += 1
|
|
319
|
+
continue
|
|
320
|
+
tool, chars = match.group(1), int(match.group(2).replace(",", ""))
|
|
321
|
+
cands = [r for r in results if r[3] == tool and r[5] == chars]
|
|
322
|
+
elif key.startswith("ce:") and detail:
|
|
323
|
+
cands = []
|
|
324
|
+
for r in results:
|
|
325
|
+
if r[3] != "Bash" or not r[4]:
|
|
326
|
+
continue
|
|
327
|
+
if r[4] not in stored_commands:
|
|
328
|
+
stored_commands[r[4]] = _stored_command(r[4])
|
|
329
|
+
if stored_commands[r[4]] == detail:
|
|
330
|
+
cands.append(r)
|
|
331
|
+
else:
|
|
332
|
+
self.stats["unlocated"] += 1
|
|
333
|
+
continue
|
|
334
|
+
self._place(key, cands, ev_dt, used)
|
|
335
|
+
|
|
336
|
+
def _place(self, key, cands, ev_dt, used, exact_id=False):
|
|
337
|
+
if exact_id:
|
|
338
|
+
near = [(0.0, r) for r in cands]
|
|
339
|
+
else:
|
|
340
|
+
near = sorted(((abs((r[0] - ev_dt).total_seconds()), r) for r in cands
|
|
341
|
+
if (r[1], r[2]) not in used
|
|
342
|
+
and abs((r[0] - ev_dt).total_seconds()) <= MATCH_SECONDS),
|
|
343
|
+
key=lambda item: item[0])
|
|
344
|
+
if not near:
|
|
345
|
+
self.stats["unlocated"] += 1
|
|
346
|
+
return
|
|
347
|
+
gap, best = near[0]
|
|
348
|
+
rivals = {r[1] for g, r in near if g <= gap + TIE_SECONDS}
|
|
349
|
+
if len(rivals) > 1:
|
|
350
|
+
self.stats["ambiguous"] += 1
|
|
351
|
+
return
|
|
352
|
+
if not exact_id:
|
|
353
|
+
used.add((best[1], best[2]))
|
|
354
|
+
if best[1] < 0:
|
|
355
|
+
self.stats["located_parent"] += 1
|
|
356
|
+
return
|
|
357
|
+
self.location[key] = best[1]
|
|
358
|
+
self.stats["located_subagent"] += 1
|
|
359
|
+
|
|
360
|
+
def turns_for(self, key, parent_turns, parent_compacts):
|
|
361
|
+
"""(turns, compacts, scope) to score this event against."""
|
|
362
|
+
index = self.location.get(key)
|
|
363
|
+
if index is None:
|
|
364
|
+
if self.fail_closed or key in self.required_subagents:
|
|
365
|
+
return [], [], SCOPE_SUBAGENT
|
|
366
|
+
return parent_turns, parent_compacts, SCOPE_PARENT
|
|
367
|
+
if index not in self._walks:
|
|
368
|
+
turns, compacts, _ = walk(self.facade, self.files[index], sidechain=True)
|
|
369
|
+
self._walks[index] = (turns, compacts)
|
|
370
|
+
turns, compacts = self._walks[index]
|
|
371
|
+
return turns, compacts, SCOPE_SUBAGENT
|
|
@@ -0,0 +1,285 @@
|
|
|
1
|
+
"""Bash coverage funnel: summary for the dashboard and the read-only replay.
|
|
2
|
+
|
|
3
|
+
``collect`` reads the counter rows the PostToolUse hook writes (coverage_funnel)
|
|
4
|
+
and returns the share of command-output tokens that ended in each gate.
|
|
5
|
+
``replay`` re-runs the same gates over the user's own transcripts, strictly
|
|
6
|
+
read-only, and feeds the same ``summarize``. Neither stores, prints or returns
|
|
7
|
+
command text or output text: only gate names, fixed-vocabulary reasons,
|
|
8
|
+
compressor pattern names and token counts leave this module.
|
|
9
|
+
|
|
10
|
+
Shares are fractions of command-output tokens and sum to 1 across the five
|
|
11
|
+
gates by construction (every result lands in exactly one).
|
|
12
|
+
"""
|
|
13
|
+
import json
|
|
14
|
+
import sqlite3
|
|
15
|
+
import sys
|
|
16
|
+
import time
|
|
17
|
+
from collections import Counter
|
|
18
|
+
from datetime import datetime, timedelta
|
|
19
|
+
from pathlib import Path
|
|
20
|
+
|
|
21
|
+
WINDOW_DAYS = 30
|
|
22
|
+
DEFAULT_MAX_RESULTS = 20000
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _gates():
|
|
26
|
+
import coverage_funnel
|
|
27
|
+
return coverage_funnel.GATES, coverage_funnel.GATE_LABELS
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def summarize(rows, window_days=None):
|
|
31
|
+
"""rows: iterable of (gate, reason, pattern, tokens, removed_tokens)."""
|
|
32
|
+
gates, labels = _gates()
|
|
33
|
+
acc = {g: {"results": 0, "tokens": 0, "removed": 0} for g in gates}
|
|
34
|
+
rejects, patterns, shorts = Counter(), Counter(), Counter()
|
|
35
|
+
for gate, reason, pattern, tokens, removed in rows:
|
|
36
|
+
if gate not in acc:
|
|
37
|
+
continue
|
|
38
|
+
tokens, removed = int(tokens or 0), int(removed or 0)
|
|
39
|
+
a = acc[gate]
|
|
40
|
+
a["results"] += 1
|
|
41
|
+
a["tokens"] += tokens
|
|
42
|
+
a["removed"] += removed
|
|
43
|
+
if gate == "not_read_only":
|
|
44
|
+
rejects[reason or "unknown"] += tokens
|
|
45
|
+
elif gate == "compressed":
|
|
46
|
+
patterns[pattern or "unlabelled"] += removed
|
|
47
|
+
elif gate == "error_or_short":
|
|
48
|
+
shorts[reason or "unknown"] += tokens
|
|
49
|
+
total = sum(a["tokens"] for a in acc.values())
|
|
50
|
+
results = sum(a["results"] for a in acc.values())
|
|
51
|
+
out_gates = []
|
|
52
|
+
for g in gates:
|
|
53
|
+
a = acc[g]
|
|
54
|
+
out_gates.append({"gate": g, "label": labels[g], "results": a["results"],
|
|
55
|
+
"tokens": a["tokens"], "removed_tokens": a["removed"],
|
|
56
|
+
"share": (a["tokens"] / total) if total else 0.0})
|
|
57
|
+
top = rejects.most_common(1)
|
|
58
|
+
return {
|
|
59
|
+
"available": True, "empty": results == 0, "window_days": window_days,
|
|
60
|
+
"results": results, "tokens": total,
|
|
61
|
+
"gates": out_gates,
|
|
62
|
+
"acted_share": (acc["compressed"]["tokens"] / total) if total else 0.0,
|
|
63
|
+
"removed_tokens": acc["compressed"]["removed"],
|
|
64
|
+
"not_eligible_share": (acc["not_read_only"]["tokens"] / total) if total else 0.0,
|
|
65
|
+
"top_reject": ({"reason": top[0][0], "tokens": top[0][1],
|
|
66
|
+
"share": top[0][1] / total} if top and total else None),
|
|
67
|
+
"rejects": [{"reason": r, "tokens": t, "share": (t / total) if total else 0.0}
|
|
68
|
+
for r, t in rejects.most_common(8)],
|
|
69
|
+
"short_reasons": [{"reason": r, "tokens": t} for r, t in shorts.most_common()],
|
|
70
|
+
"patterns": [{"pattern": p, "removed_tokens": t} for p, t in patterns.most_common(8)],
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def unavailable(why):
|
|
75
|
+
return {"available": False, "why": why}
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def collect(db_path, days=WINDOW_DAYS, now=None):
|
|
79
|
+
"""Summary of the last ``days`` days from the counter table. Read-only.
|
|
80
|
+
|
|
81
|
+
A missing database or table is "unavailable" (unknown), never a row of zeros.
|
|
82
|
+
A table with no rows in the window is ``empty`` (nothing counted yet).
|
|
83
|
+
"""
|
|
84
|
+
path = Path(db_path)
|
|
85
|
+
if not path.is_file():
|
|
86
|
+
return unavailable("no ledger")
|
|
87
|
+
cutoff = ((now or datetime.now()) - timedelta(days=days)).isoformat()
|
|
88
|
+
try:
|
|
89
|
+
with sqlite3.connect(path.resolve().as_uri() + "?mode=ro", uri=True, timeout=1.0) as conn:
|
|
90
|
+
have = conn.execute("SELECT 1 FROM sqlite_master WHERE type='table' AND name='bash_coverage'").fetchone()
|
|
91
|
+
if not have:
|
|
92
|
+
return unavailable("no counter table yet")
|
|
93
|
+
rows = conn.execute(
|
|
94
|
+
"SELECT gate, reason, pattern, tokens, removed_tokens FROM bash_coverage WHERE timestamp >= ?",
|
|
95
|
+
(cutoff,)).fetchall()
|
|
96
|
+
except (sqlite3.Error, OSError, ValueError):
|
|
97
|
+
return unavailable("ledger unreadable")
|
|
98
|
+
return summarize(rows, days)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _fmt_tokens(n):
|
|
102
|
+
n = int(n)
|
|
103
|
+
if n >= 1_000_000:
|
|
104
|
+
return f"{n / 1_000_000:.1f}M"
|
|
105
|
+
if n >= 10_000:
|
|
106
|
+
return f"{n / 1000:.0f}K"
|
|
107
|
+
return f"{n:,}"
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def headline(summary):
|
|
111
|
+
"""One honest sentence: what TO saw, what it acted on, what was not eligible."""
|
|
112
|
+
if not summary or not summary.get("available"):
|
|
113
|
+
return "Command-output coverage is unknown: the counter ledger could not be read."
|
|
114
|
+
if summary.get("empty"):
|
|
115
|
+
return "No command output has been counted yet."
|
|
116
|
+
line = (f"TO saw {_fmt_tokens(summary['tokens'])} tokens of command output, "
|
|
117
|
+
f"acted on {summary['acted_share'] * 100:.1f}%. "
|
|
118
|
+
f"Not eligible: {summary['not_eligible_share'] * 100:.1f}%")
|
|
119
|
+
top = summary.get("top_reject")
|
|
120
|
+
if top:
|
|
121
|
+
line += f" (top reason: {top['reason']}, {top['share'] * 100:.1f}%)"
|
|
122
|
+
return line + "."
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def format_table(summary, source_note=""):
|
|
126
|
+
if not summary.get("available"):
|
|
127
|
+
return headline(summary)
|
|
128
|
+
out = [headline(summary), ""]
|
|
129
|
+
if source_note:
|
|
130
|
+
out += [source_note, ""]
|
|
131
|
+
out.append(f"{'gate':50s} {'results':>8s} {'tokens':>10s} {'share':>7s} {'removed':>9s}")
|
|
132
|
+
for g in summary["gates"]:
|
|
133
|
+
out.append(f"{g['label'][:50]:50s} {g['results']:8d} {g['tokens']:10d} "
|
|
134
|
+
f"{g['share'] * 100:6.1f}% {g['removed_tokens']:9d}")
|
|
135
|
+
if summary["rejects"]:
|
|
136
|
+
out += ["", "Not eligible, by reason (share of all command-output tokens):"]
|
|
137
|
+
out += [f" {r['reason']:40s} {r['share'] * 100:5.1f}%" for r in summary["rejects"]]
|
|
138
|
+
if summary["short_reasons"]:
|
|
139
|
+
out += ["", "Left raw by design:"]
|
|
140
|
+
out += [f" {r['reason']:40s} {r['tokens']:>9d} tokens" for r in summary["short_reasons"]]
|
|
141
|
+
if summary["patterns"]:
|
|
142
|
+
out += ["", "Compressed, by compressor (tokens removed):"]
|
|
143
|
+
out += [f" {r['pattern']:40s} {r['removed_tokens']:>9d}" for r in summary["patterns"]]
|
|
144
|
+
if summary.get("file_refetch"):
|
|
145
|
+
from . import file_refetch
|
|
146
|
+
out += [""] + file_refetch.format_lines(summary["file_refetch"])
|
|
147
|
+
return "\n".join(out)
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def _transcripts(projects_dir, days, now=None):
|
|
151
|
+
"""Transcript files modified within ``days``, newest first, or None if the folder is missing."""
|
|
152
|
+
root = Path(projects_dir)
|
|
153
|
+
if not root.is_dir():
|
|
154
|
+
return None
|
|
155
|
+
cutoff = ((now or datetime.now()) - timedelta(days=days)).timestamp()
|
|
156
|
+
files = []
|
|
157
|
+
for p in root.rglob("*.jsonl"):
|
|
158
|
+
try:
|
|
159
|
+
mtime = p.stat().st_mtime
|
|
160
|
+
except OSError:
|
|
161
|
+
continue
|
|
162
|
+
if mtime >= cutoff:
|
|
163
|
+
files.append((mtime, p))
|
|
164
|
+
files.sort(reverse=True)
|
|
165
|
+
return [p for _, p in files]
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def replay(projects_dir, days=WINDOW_DAYS, max_results=DEFAULT_MAX_RESULTS, now=None, deadline=None):
|
|
169
|
+
"""Replay the hook's gates over transcripts under ``projects_dir``. Read-only.
|
|
170
|
+
|
|
171
|
+
Newest files first, files older than ``days`` skipped by modification time.
|
|
172
|
+
Stops at ``max_results`` Bash results (reported in ``truncated``). Nothing is
|
|
173
|
+
written; no command or output text is kept past the gate decision. The same
|
|
174
|
+
walk feeds the file-content re-fetch metric (see file_refetch).
|
|
175
|
+
"""
|
|
176
|
+
here = str(Path(__file__).resolve().parent.parent)
|
|
177
|
+
if here not in sys.path:
|
|
178
|
+
sys.path.insert(0, here)
|
|
179
|
+
from coverage_funnel import classify_result
|
|
180
|
+
from . import file_refetch
|
|
181
|
+
files = _transcripts(projects_dir, days, now)
|
|
182
|
+
if files is None:
|
|
183
|
+
return unavailable("no transcripts folder")
|
|
184
|
+
rows, truncated, unreadable = [], False, 0
|
|
185
|
+
refetch = file_refetch.new_counts()
|
|
186
|
+
for path in files:
|
|
187
|
+
if truncated or (deadline and time.monotonic() > deadline):
|
|
188
|
+
truncated = True
|
|
189
|
+
break
|
|
190
|
+
try:
|
|
191
|
+
sequence = file_refetch.calls(path)
|
|
192
|
+
except OSError:
|
|
193
|
+
unreadable += 1
|
|
194
|
+
continue
|
|
195
|
+
file_refetch.scan(sequence, refetch)
|
|
196
|
+
for entry in sequence:
|
|
197
|
+
cmd = entry["input"].get("command") if entry["name"] == "Bash" else None
|
|
198
|
+
if not entry["has_result"] or not isinstance(cmd, str):
|
|
199
|
+
continue
|
|
200
|
+
r = classify_result(cmd, entry["text"], entry["is_error"])
|
|
201
|
+
rows.append((r["gate"], r["reason"], r["pattern"], r["tokens"], r["removed"]))
|
|
202
|
+
if len(rows) >= max_results:
|
|
203
|
+
truncated = True
|
|
204
|
+
break
|
|
205
|
+
result = summarize(rows, days)
|
|
206
|
+
result.update(files=len(files), unreadable=unreadable, truncated=truncated,
|
|
207
|
+
file_refetch=file_refetch.summarize(refetch))
|
|
208
|
+
return result
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def refetch_only(projects_dir, days=WINDOW_DAYS, now=None):
|
|
212
|
+
"""Just the file-content re-fetch metric over the same transcripts. Read-only."""
|
|
213
|
+
from . import file_refetch
|
|
214
|
+
files = _transcripts(projects_dir, days, now)
|
|
215
|
+
if files is None:
|
|
216
|
+
return unavailable("no transcripts folder")
|
|
217
|
+
acc, unreadable = file_refetch.new_counts(), 0
|
|
218
|
+
for path in files:
|
|
219
|
+
try:
|
|
220
|
+
file_refetch.scan(file_refetch.calls(path), acc)
|
|
221
|
+
except OSError:
|
|
222
|
+
unreadable += 1
|
|
223
|
+
out = file_refetch.summarize(acc)
|
|
224
|
+
out.update(available=True, files=len(files), unreadable=unreadable, window_days=days)
|
|
225
|
+
return out
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def _parse_args(args, projects_dir):
|
|
229
|
+
days, max_results, as_json = WINDOW_DAYS, DEFAULT_MAX_RESULTS, False
|
|
230
|
+
i = 0
|
|
231
|
+
while i < len(args):
|
|
232
|
+
a = args[i]
|
|
233
|
+
if a == "--json":
|
|
234
|
+
as_json = True
|
|
235
|
+
elif a in ("--days", "--max", "--projects-dir") and i + 1 < len(args):
|
|
236
|
+
try:
|
|
237
|
+
if a == "--days":
|
|
238
|
+
days = max(1, int(args[i + 1]))
|
|
239
|
+
elif a == "--max":
|
|
240
|
+
max_results = max(1, int(args[i + 1]))
|
|
241
|
+
else:
|
|
242
|
+
projects_dir = Path(args[i + 1]).expanduser()
|
|
243
|
+
except ValueError:
|
|
244
|
+
print(f"[Error] Invalid {a} value: {args[i + 1]}")
|
|
245
|
+
return None
|
|
246
|
+
i += 1
|
|
247
|
+
i += 1
|
|
248
|
+
return days, max_results, as_json, projects_dir
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
def replay_cli(args, projects_dir, now=None):
|
|
252
|
+
"""`measure.py coverage-replay [--days N] [--max N] [--projects-dir PATH] [--json]`."""
|
|
253
|
+
parsed = _parse_args(args, projects_dir)
|
|
254
|
+
if parsed is None:
|
|
255
|
+
return 1
|
|
256
|
+
days, max_results, as_json, projects_dir = parsed
|
|
257
|
+
summary = replay(projects_dir, days=days, max_results=max_results, now=now)
|
|
258
|
+
if as_json:
|
|
259
|
+
print(json.dumps(summary, indent=2))
|
|
260
|
+
return 0 if summary.get("available") else 1
|
|
261
|
+
note = ""
|
|
262
|
+
if summary.get("available"):
|
|
263
|
+
note = (f"Replayed {summary['results']:,} Bash results from {summary['files']:,} transcripts "
|
|
264
|
+
f"in the last {days} days (read-only; nothing stored)."
|
|
265
|
+
+ (" Stopped at the --max limit; newest transcripts first." if summary["truncated"] else ""))
|
|
266
|
+
print(format_table(summary, note))
|
|
267
|
+
return 0 if summary.get("available") else 1
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
def refetch_cli(args, projects_dir, now=None):
|
|
271
|
+
"""`measure.py file-refetch [--days N] [--projects-dir PATH] [--json]`: re-fetch metric only."""
|
|
272
|
+
parsed = _parse_args(args, projects_dir)
|
|
273
|
+
if parsed is None:
|
|
274
|
+
return 1
|
|
275
|
+
days, _max, as_json, projects_dir = parsed
|
|
276
|
+
out = refetch_only(projects_dir, days=days, now=now)
|
|
277
|
+
if as_json:
|
|
278
|
+
print(json.dumps(out, indent=2))
|
|
279
|
+
elif not out.get("available"):
|
|
280
|
+
print(headline(out))
|
|
281
|
+
else:
|
|
282
|
+
from . import file_refetch
|
|
283
|
+
print("\n".join([f"Read {out['files']:,} transcripts from the last {days} days (read-only; nothing stored)."]
|
|
284
|
+
+ file_refetch.format_lines(out)))
|
|
285
|
+
return 0 if out.get("available") else 1
|