@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,216 @@
|
|
|
1
|
+
"""Privacy-safe first-call context observations from parent transcripts."""
|
|
2
|
+
import json
|
|
3
|
+
import re
|
|
4
|
+
import sqlite3
|
|
5
|
+
import statistics
|
|
6
|
+
import threading
|
|
7
|
+
import time
|
|
8
|
+
from collections import defaultdict, OrderedDict
|
|
9
|
+
from functools import lru_cache
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@lru_cache(maxsize=1)
|
|
14
|
+
def _optimizer_commands():
|
|
15
|
+
"""Use registered hook commands as identity evidence, not runner names."""
|
|
16
|
+
try:
|
|
17
|
+
root = json.loads((Path(__file__).resolve().parents[4] / "hooks" / "hooks.json").read_text(encoding="utf-8"))
|
|
18
|
+
except (OSError, ValueError, IndexError):
|
|
19
|
+
return frozenset()
|
|
20
|
+
commands, pending = set(), [root]
|
|
21
|
+
while pending:
|
|
22
|
+
item = pending.pop()
|
|
23
|
+
if isinstance(item, dict):
|
|
24
|
+
if isinstance(item.get("command"), str):
|
|
25
|
+
commands.add(item["command"])
|
|
26
|
+
pending.extend(item.values())
|
|
27
|
+
elif isinstance(item, list):
|
|
28
|
+
pending.extend(item)
|
|
29
|
+
return frozenset(commands)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _text(value):
|
|
33
|
+
if isinstance(value, str):
|
|
34
|
+
return value
|
|
35
|
+
if isinstance(value, list):
|
|
36
|
+
return "\n".join(_text(item) for item in value)
|
|
37
|
+
if isinstance(value, dict):
|
|
38
|
+
return _text(value.get("text", value.get("content", "")))
|
|
39
|
+
return ""
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def observe(rows, estimate):
|
|
43
|
+
"""Return estimates and measured API input for the first parent call only."""
|
|
44
|
+
parts = defaultdict(int)
|
|
45
|
+
first_user = False
|
|
46
|
+
hook_outputs = []
|
|
47
|
+
for row in rows:
|
|
48
|
+
if row.get("isSidechain"):
|
|
49
|
+
continue
|
|
50
|
+
kind = row.get("type")
|
|
51
|
+
if kind == "assistant":
|
|
52
|
+
message = row.get("message") or {}
|
|
53
|
+
usage = message.get("usage") or {}
|
|
54
|
+
if not isinstance(usage, dict) or not usage:
|
|
55
|
+
continue
|
|
56
|
+
try:
|
|
57
|
+
total = sum(int(usage.get(key) or 0) for key in
|
|
58
|
+
("input_tokens", "cache_read_input_tokens", "cache_creation_input_tokens"))
|
|
59
|
+
except (TypeError, ValueError):
|
|
60
|
+
return None
|
|
61
|
+
timestamp = row.get("timestamp")
|
|
62
|
+
if total <= 0 or not isinstance(timestamp, str) or len(timestamp) < 7:
|
|
63
|
+
return None
|
|
64
|
+
return {"month": timestamp[:7], "total": total, "components": dict(parts)}
|
|
65
|
+
if kind == "user" and not first_user and not row.get("isMeta"):
|
|
66
|
+
message = row.get("message") or {}
|
|
67
|
+
if isinstance(message, dict) and message.get("role") == "user":
|
|
68
|
+
parts["first_user"] += estimate(_text(message.get("content")))
|
|
69
|
+
first_user = True
|
|
70
|
+
if kind != "attachment":
|
|
71
|
+
continue
|
|
72
|
+
a = row.get("attachment") or {}
|
|
73
|
+
if not isinstance(a, dict):
|
|
74
|
+
continue
|
|
75
|
+
typ = a.get("type")
|
|
76
|
+
if typ == "hook_success":
|
|
77
|
+
command = str(a.get("command") or "")
|
|
78
|
+
if command in _optimizer_commands() or any(name in command.lower() for name in ("token-optimizer", "token_optimizer")):
|
|
79
|
+
try:
|
|
80
|
+
output = json.loads(a.get("stdout") or "{}")
|
|
81
|
+
context = (output.get("hookSpecificOutput") or {}).get("additionalContext")
|
|
82
|
+
if isinstance(context, str) and context:
|
|
83
|
+
hook_outputs.append((a.get("hookEvent"), context))
|
|
84
|
+
except (ValueError, TypeError, AttributeError):
|
|
85
|
+
pass
|
|
86
|
+
mapping = {"skill_listing": ("skills", "content"),
|
|
87
|
+
"deferred_tools_delta": ("mcp_tools", "addedLines"),
|
|
88
|
+
"mcp_instructions_delta": ("mcp_instructions", "addedBlocks"),
|
|
89
|
+
"agent_listing_delta": ("agents", "addedLines")}
|
|
90
|
+
if typ in mapping:
|
|
91
|
+
name, field = mapping[typ]
|
|
92
|
+
parts[name] += estimate(_text(a.get(field)))
|
|
93
|
+
if typ == "deferred_tools_delta":
|
|
94
|
+
parts[name] += sum(estimate(_text(item.get("definition"))) for item in a.get("surfacedDefinitions") or [] if isinstance(item, dict))
|
|
95
|
+
elif typ == "instructions":
|
|
96
|
+
for item in a.get("files") or []:
|
|
97
|
+
if isinstance(item, dict):
|
|
98
|
+
path = str(item.get("path") or "").replace("\\", "/").lower()
|
|
99
|
+
kind = str(item.get("type") or "").lower()
|
|
100
|
+
if path.endswith("/claude.md") or path == "claude.md":
|
|
101
|
+
name = "claude_md"
|
|
102
|
+
elif "/memory/" in path or path.endswith("/memory.md") or kind == "memory":
|
|
103
|
+
name = "memory_files"
|
|
104
|
+
else:
|
|
105
|
+
name = "other_instructions"
|
|
106
|
+
parts[name] += estimate(_text(item.get("content")))
|
|
107
|
+
elif typ == "hook_additional_context":
|
|
108
|
+
event = a.get("hookEvent")
|
|
109
|
+
if event in ("SessionStart", "UserPromptSubmit"):
|
|
110
|
+
content = _text(a.get("content"))
|
|
111
|
+
for item in hook_outputs[:]:
|
|
112
|
+
if item[0] == event and item[1] in content:
|
|
113
|
+
parts[event + "_token_optimizer"] += estimate(item[1])
|
|
114
|
+
content = content.replace(item[1], "", 1)
|
|
115
|
+
hook_outputs.remove(item)
|
|
116
|
+
parts[event + "_other_or_unknown"] += estimate(content)
|
|
117
|
+
return None
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def _quantile(values, fraction):
|
|
121
|
+
values = sorted(values)
|
|
122
|
+
index = (len(values) - 1) * fraction
|
|
123
|
+
lo = int(index)
|
|
124
|
+
hi = min(lo + 1, len(values) - 1)
|
|
125
|
+
return round(values[lo] + (values[hi] - values[lo]) * (index - lo))
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def summarize(observations):
|
|
129
|
+
groups = defaultdict(list)
|
|
130
|
+
for row in observations:
|
|
131
|
+
if row:
|
|
132
|
+
groups[row["month"]].append(row)
|
|
133
|
+
result = []
|
|
134
|
+
for month, rows in sorted(groups.items()):
|
|
135
|
+
totals = [row["total"] for row in rows]
|
|
136
|
+
names = set().union(*(row["components"] for row in rows))
|
|
137
|
+
components = {}
|
|
138
|
+
for name in sorted(names):
|
|
139
|
+
found = [row["components"][name] for row in rows if name in row["components"]]
|
|
140
|
+
components[name] = {"median": round(statistics.median(found)), "observed": len(found)}
|
|
141
|
+
result.append({"month": month, "n": len(rows), "median": round(statistics.median(totals)),
|
|
142
|
+
"p25": _quantile(totals, .25), "p75": _quantile(totals, .75),
|
|
143
|
+
"components": components})
|
|
144
|
+
return result
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
_RELEVANT_TYPE = re.compile(r'"type"\s*:\s*"(?:assistant|user|attachment)"')
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def transcript(path):
|
|
151
|
+
with open(path, encoding="utf-8", errors="replace") as stream:
|
|
152
|
+
for line in stream:
|
|
153
|
+
if '\\u' not in line and not _RELEVANT_TYPE.search(line):
|
|
154
|
+
continue
|
|
155
|
+
try:
|
|
156
|
+
row = json.loads(line)
|
|
157
|
+
except ValueError:
|
|
158
|
+
continue
|
|
159
|
+
if isinstance(row, dict):
|
|
160
|
+
yield row
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
_cache = OrderedDict()
|
|
164
|
+
_cache_lock = threading.Lock()
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def collect(db_path, data_dir):
|
|
168
|
+
"""Share a scan for one minute after it finishes, even if it ran slowly."""
|
|
169
|
+
key = (str(db_path), str(data_dir))
|
|
170
|
+
with _cache_lock:
|
|
171
|
+
entry = _cache.get(key)
|
|
172
|
+
if entry and time.monotonic() - entry[0] < 60:
|
|
173
|
+
_cache.move_to_end(key)
|
|
174
|
+
return entry[1]
|
|
175
|
+
value = _collect_uncached(*key)
|
|
176
|
+
_cache[key] = (time.monotonic(), value)
|
|
177
|
+
_cache.move_to_end(key)
|
|
178
|
+
while len(_cache) > 4:
|
|
179
|
+
_cache.popitem(last=False)
|
|
180
|
+
return value
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def _collect_uncached(db_path, data_dir):
|
|
184
|
+
from . import structural_ledger
|
|
185
|
+
db_path = Path(db_path)
|
|
186
|
+
if not db_path.is_file():
|
|
187
|
+
return {"months": [], "trim_dates": [], "missing": 0}
|
|
188
|
+
observations, missing, seen = [], 0, set()
|
|
189
|
+
try:
|
|
190
|
+
with sqlite3.connect(db_path.resolve().as_uri() + "?mode=ro", uri=True) as conn:
|
|
191
|
+
paths = conn.execute("SELECT DISTINCT jsonl_path FROM session_log WHERE jsonl_path IS NOT NULL AND COALESCE(is_sidechain,0)=0").fetchall()
|
|
192
|
+
files = []
|
|
193
|
+
for (name,) in paths:
|
|
194
|
+
path = Path(name)
|
|
195
|
+
if path in seen:
|
|
196
|
+
continue
|
|
197
|
+
seen.add(path)
|
|
198
|
+
try:
|
|
199
|
+
files.append((str(path), path.stat()))
|
|
200
|
+
except (OSError, ValueError, TypeError):
|
|
201
|
+
missing += 1
|
|
202
|
+
from . import evidence_parallel
|
|
203
|
+
if len(files) >= 256 and evidence_parallel.safe_entrypoint():
|
|
204
|
+
batches = evidence_parallel.batches(files, None, 8 * 1024 * 1024, evidence_parallel.first_call)
|
|
205
|
+
else:
|
|
206
|
+
batches = ([((path, stat), evidence_parallel.first_call(path))] for path, stat in files)
|
|
207
|
+
for batch in batches:
|
|
208
|
+
for _, (item, failed) in batch:
|
|
209
|
+
missing += int(failed)
|
|
210
|
+
if item:
|
|
211
|
+
observations.append(item)
|
|
212
|
+
dates = sorted({str(t.get("ts"))[:10] for t in structural_ledger.load_trims(data_dir)
|
|
213
|
+
if t.get("ts") and int(t.get("tokens") or 0) > 0})
|
|
214
|
+
return {"months": summarize(observations), "trim_dates": dates, "missing": missing}
|
|
215
|
+
except (sqlite3.Error, OSError, ValueError, TypeError):
|
|
216
|
+
return {"months": [], "trim_dates": [], "missing": missing}
|
|
@@ -0,0 +1,261 @@
|
|
|
1
|
+
"""Conservative transcript-only first-read outcome diagnostics.
|
|
2
|
+
|
|
3
|
+
An observation is usable only when its Read result and, for a map, hook output
|
|
4
|
+
are visible and its follow-up window is complete. These signals are proxies,
|
|
5
|
+
not proof of causality; absence of an explicit cancellation is not proof that
|
|
6
|
+
the task was completed. Project/task labels used for matching stay in memory.
|
|
7
|
+
"""
|
|
8
|
+
import hashlib
|
|
9
|
+
import argparse
|
|
10
|
+
import json
|
|
11
|
+
import math
|
|
12
|
+
import re
|
|
13
|
+
from collections import defaultdict
|
|
14
|
+
|
|
15
|
+
_TEST = re.compile(r"(?:^|[;&|]\s*)(?:python\S*\s+-m\s+pytest|pytest|npm\s+(?:run\s+)?test|cargo\s+test|go\s+test)\b")
|
|
16
|
+
_CANCEL = re.compile(r"^\s*(?:cancel (?:this|the task)|stop (?:this|the task)|abandon (?:this|the task))\s*[.!]?\s*$", re.I)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _hash(value):
|
|
20
|
+
return hashlib.sha256(str(value).encode("utf-8", "replace")).hexdigest()
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _blocks(row):
|
|
24
|
+
message = row.get("message") or {}
|
|
25
|
+
content = message.get("content") if isinstance(message, dict) else None
|
|
26
|
+
return content if isinstance(content, list) else []
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def inspect(rows, exposure, window=10):
|
|
30
|
+
"""Inspect a single exposure without returning source text or paths."""
|
|
31
|
+
if window < 1:
|
|
32
|
+
raise ValueError("window must be positive")
|
|
33
|
+
token = exposure.get("tool_use_id")
|
|
34
|
+
arm = exposure.get("arm")
|
|
35
|
+
out = {"confirmed": False, "complete": False, "failed_test": False, "revert": False,
|
|
36
|
+
"repeated_region": False, "abandoned": False, "harm": False}
|
|
37
|
+
if not token or arm not in ("map", "no_map", "legacy_skeleton"):
|
|
38
|
+
return out
|
|
39
|
+
started = read_ok = delivered = False
|
|
40
|
+
turns, seen_messages, seen_tools = 0, set(), set()
|
|
41
|
+
tests, finished_tests, pending_edits, prior_edit = set(), set(), {}, {}
|
|
42
|
+
unsupported_edit = False
|
|
43
|
+
for row in rows:
|
|
44
|
+
typ = row.get("type")
|
|
45
|
+
blocks = _blocks(row)
|
|
46
|
+
exposure_turn = False
|
|
47
|
+
if not started:
|
|
48
|
+
started = any(isinstance(b, dict) and b.get("type") == "tool_use" and b.get("name") == "Read"
|
|
49
|
+
and b.get("id") and _hash(b["id"]) == token for b in blocks)
|
|
50
|
+
if not started:
|
|
51
|
+
continue
|
|
52
|
+
exposure_turn = True
|
|
53
|
+
elif typ == "assistant":
|
|
54
|
+
msg = row.get("message") or {}
|
|
55
|
+
mid = msg.get("id") or row.get("uuid")
|
|
56
|
+
if mid is None or mid not in seen_messages:
|
|
57
|
+
turns += 1
|
|
58
|
+
if mid is not None:
|
|
59
|
+
seen_messages.add(mid)
|
|
60
|
+
if turns > window:
|
|
61
|
+
break
|
|
62
|
+
if typ == "attachment":
|
|
63
|
+
a = row.get("attachment") or {}
|
|
64
|
+
if a.get("toolUseID") and _hash(a["toolUseID"]) == token:
|
|
65
|
+
content = str(a.get("content") or "") + str(a.get("stdout") or "")
|
|
66
|
+
if arm == "legacy_skeleton":
|
|
67
|
+
delivered |= "large-file first read served as" in content
|
|
68
|
+
else:
|
|
69
|
+
delivered |= "[Token Optimizer] Periphery skeletons" in content
|
|
70
|
+
if typ == "user":
|
|
71
|
+
content = (row.get("message") or {}).get("content")
|
|
72
|
+
if isinstance(content, str) and _CANCEL.fullmatch(content):
|
|
73
|
+
out["abandoned"] = True
|
|
74
|
+
for block in blocks:
|
|
75
|
+
if not isinstance(block, dict):
|
|
76
|
+
continue
|
|
77
|
+
if block.get("type") == "tool_result":
|
|
78
|
+
tid = block.get("tool_use_id")
|
|
79
|
+
if tid and _hash(tid) == token:
|
|
80
|
+
if arm == "legacy_skeleton":
|
|
81
|
+
read_ok |= "large-file first read served as" in str(block.get("content") or "")
|
|
82
|
+
else:
|
|
83
|
+
read_ok |= block.get("is_error") is False
|
|
84
|
+
tool_result = row.get("toolUseResult") or {}
|
|
85
|
+
exit_code = tool_result.get("exitCode") if isinstance(tool_result, dict) else None
|
|
86
|
+
if tid in tests and (isinstance(block.get("is_error"), bool) or isinstance(exit_code, int)):
|
|
87
|
+
finished_tests.add(tid)
|
|
88
|
+
if block.get("is_error") is True or (isinstance(exit_code, int) and exit_code != 0):
|
|
89
|
+
out["failed_test"] = True
|
|
90
|
+
if tid in pending_edits and isinstance(block.get("is_error"), bool):
|
|
91
|
+
path, old_id, new_id = pending_edits.pop(tid)
|
|
92
|
+
if block["is_error"] is False:
|
|
93
|
+
previous = prior_edit.get(path)
|
|
94
|
+
if previous and old_id == previous[1]:
|
|
95
|
+
out["repeated_region"] = True
|
|
96
|
+
if new_id == previous[0]:
|
|
97
|
+
out["revert"] = True
|
|
98
|
+
prior_edit[path] = (old_id, new_id)
|
|
99
|
+
if exposure_turn or block.get("type") != "tool_use" or not block.get("id"):
|
|
100
|
+
continue
|
|
101
|
+
tid = block["id"]
|
|
102
|
+
if tid in seen_tools:
|
|
103
|
+
continue
|
|
104
|
+
seen_tools.add(tid)
|
|
105
|
+
name, args = block.get("name"), block.get("input") or {}
|
|
106
|
+
if not isinstance(args, dict):
|
|
107
|
+
continue
|
|
108
|
+
if name == "Bash" and isinstance(args.get("command"), str) and _TEST.search(args["command"]):
|
|
109
|
+
tests.add(tid)
|
|
110
|
+
if name in ("Write", "MultiEdit") or (name == "Edit" and args.get("replace_all")):
|
|
111
|
+
unsupported_edit = True
|
|
112
|
+
continue
|
|
113
|
+
if name != "Edit":
|
|
114
|
+
continue
|
|
115
|
+
if not args.get("file_path"):
|
|
116
|
+
unsupported_edit = True
|
|
117
|
+
continue
|
|
118
|
+
old, new = args.get("old_string"), args.get("new_string")
|
|
119
|
+
if not isinstance(old, str) or not old or not isinstance(new, str):
|
|
120
|
+
unsupported_edit = True
|
|
121
|
+
continue
|
|
122
|
+
pending_edits[tid] = (_hash(args["file_path"]), _hash(old), _hash(new))
|
|
123
|
+
out["confirmed"] = read_ok and (arm == "no_map" or delivered)
|
|
124
|
+
out["complete"] = ((turns >= window or out["abandoned"]) and tests <= finished_tests
|
|
125
|
+
and not pending_edits and not unsupported_edit)
|
|
126
|
+
out["harm"] = any(out[k] for k in ("failed_test", "revert", "repeated_region", "abandoned"))
|
|
127
|
+
return out
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _wilson(k, n):
|
|
131
|
+
if not n:
|
|
132
|
+
return None
|
|
133
|
+
z = 1.959963984540054
|
|
134
|
+
p = k / n
|
|
135
|
+
denominator = 1 + z * z / n
|
|
136
|
+
center = (p + z * z / (2 * n)) / denominator
|
|
137
|
+
radius = z * math.sqrt((p * (1 - p) + z * z / (4 * n)) / n) / denominator
|
|
138
|
+
return [max(0.0, center - radius), min(1.0, center + radius)]
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def compare(observations, treatment="map"):
|
|
142
|
+
"""Match independent sessions within exact cohort, project and task labels."""
|
|
143
|
+
if treatment not in ("map", "legacy_skeleton"):
|
|
144
|
+
raise ValueError("unknown treatment")
|
|
145
|
+
groups = defaultdict(lambda: {"map": [], "no_map": []})
|
|
146
|
+
seen_sessions = set()
|
|
147
|
+
for row in observations:
|
|
148
|
+
if not row.get("confirmed") or not row.get("complete") or row.get("arm") not in (treatment, "no_map"):
|
|
149
|
+
continue
|
|
150
|
+
if not all(row.get(k) for k in ("cohort", "project", "task_type", "session_id", "tool_use_id")):
|
|
151
|
+
continue
|
|
152
|
+
session_key = (row["arm"], row["session_id"])
|
|
153
|
+
if session_key in seen_sessions:
|
|
154
|
+
continue
|
|
155
|
+
seen_sessions.add(session_key)
|
|
156
|
+
group_arm = "map" if row["arm"] == treatment else "no_map"
|
|
157
|
+
groups[(row["cohort"], row["project"], row["task_type"])][group_arm].append(
|
|
158
|
+
(row["session_id"], bool(row.get("harm"))))
|
|
159
|
+
pairs = defaultdict(list)
|
|
160
|
+
used_sessions = set()
|
|
161
|
+
for (cohort, _, _), arms in groups.items():
|
|
162
|
+
available = list(arms["no_map"])
|
|
163
|
+
for session, harm in arms["map"]:
|
|
164
|
+
if session in used_sessions:
|
|
165
|
+
continue
|
|
166
|
+
match = next((i for i, (other, _) in enumerate(available)
|
|
167
|
+
if other != session and other not in used_sessions), None)
|
|
168
|
+
if match is not None:
|
|
169
|
+
other, control_harm = available.pop(match)
|
|
170
|
+
used_sessions.update((session, other))
|
|
171
|
+
pairs[cohort].append((harm, control_harm))
|
|
172
|
+
result = {}
|
|
173
|
+
for cohort, values in pairs.items():
|
|
174
|
+
if not values:
|
|
175
|
+
continue
|
|
176
|
+
n = len(values)
|
|
177
|
+
on = sum(a for a, _ in values)
|
|
178
|
+
off = sum(b for _, b in values)
|
|
179
|
+
difference = (on - off) / n
|
|
180
|
+
radius = math.sqrt(2 * math.log(40) / n)
|
|
181
|
+
result[cohort] = {"treatment": treatment, "pairs": n, "map_harm": on, "control_harm": off,
|
|
182
|
+
"map_rate": on / n, "control_rate": off / n,
|
|
183
|
+
"map_interval_95": _wilson(on, n), "control_interval_95": _wilson(off, n),
|
|
184
|
+
"difference": difference,
|
|
185
|
+
"difference_interval_95": [max(-1.0, difference - radius), min(1.0, difference + radius)]}
|
|
186
|
+
return result
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def analyse_sessions(sessions, exposures, window=10):
|
|
190
|
+
"""Replay explicit transcript records against privacy-preserving exposure IDs.
|
|
191
|
+
|
|
192
|
+
Each session supplies session_id, project, task_type and transcript rows.
|
|
193
|
+
Project and task_type are matching labels only and are never returned.
|
|
194
|
+
"""
|
|
195
|
+
by_session = defaultdict(list)
|
|
196
|
+
variants = defaultdict(set)
|
|
197
|
+
exposures = list(exposures)
|
|
198
|
+
for e in exposures:
|
|
199
|
+
variants[(e.get("session_id"), e.get("tool_use_id"))].add(
|
|
200
|
+
(e.get("arm"), e.get("language"), e.get("band")))
|
|
201
|
+
seen = set()
|
|
202
|
+
for e in exposures:
|
|
203
|
+
key = (e.get("session_id"), e.get("tool_use_id"), e.get("arm"))
|
|
204
|
+
if not all(key) or key in seen or len(variants[key[:2]]) != 1:
|
|
205
|
+
continue
|
|
206
|
+
seen.add(key)
|
|
207
|
+
by_session[key[0]].append(e)
|
|
208
|
+
observations = []
|
|
209
|
+
seen_sessions = set()
|
|
210
|
+
for s in sessions:
|
|
211
|
+
sid = _hash(s.get("session_id")) if s.get("session_id") else ""
|
|
212
|
+
if not sid or sid in seen_sessions:
|
|
213
|
+
continue
|
|
214
|
+
seen_sessions.add(sid)
|
|
215
|
+
for exposure in by_session.get(sid, []):
|
|
216
|
+
language, band = exposure.get("language"), exposure.get("band")
|
|
217
|
+
if not language or not band:
|
|
218
|
+
continue
|
|
219
|
+
outcome = inspect(s.get("rows") or [], exposure, window=window)
|
|
220
|
+
outcome.update(session_id=sid, tool_use_id=exposure["tool_use_id"], arm=exposure["arm"],
|
|
221
|
+
cohort=f"{language}|{band}", project=s.get("project"), task_type=s.get("task_type"))
|
|
222
|
+
observations.append(outcome)
|
|
223
|
+
return {"unique_observations": len(observations),
|
|
224
|
+
"unconfirmed": sum(not x["confirmed"] for x in observations),
|
|
225
|
+
"censored": sum(x["confirmed"] and not x["complete"] for x in observations),
|
|
226
|
+
"cohorts": compare(observations), "target_outline_cohorts": compare(observations, treatment="legacy_skeleton")}
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def _read_jsonl(path):
|
|
230
|
+
rows = []
|
|
231
|
+
with open(path, encoding="utf-8", errors="replace") as fh:
|
|
232
|
+
for line in fh:
|
|
233
|
+
try:
|
|
234
|
+
row = json.loads(line)
|
|
235
|
+
except ValueError:
|
|
236
|
+
continue
|
|
237
|
+
if isinstance(row, dict):
|
|
238
|
+
rows.append(row)
|
|
239
|
+
return rows
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
def main(argv=None):
|
|
243
|
+
parser = argparse.ArgumentParser(description=__doc__)
|
|
244
|
+
parser.add_argument("manifest", help="JSON array: transcript_path, session_id, project, task_type")
|
|
245
|
+
parser.add_argument("exposures", help="periphery_exposures.jsonl")
|
|
246
|
+
parser.add_argument("--window", type=int, default=10)
|
|
247
|
+
args = parser.parse_args(argv)
|
|
248
|
+
if not 1 <= args.window <= 100:
|
|
249
|
+
parser.error("window must be between 1 and 100")
|
|
250
|
+
with open(args.manifest, encoding="utf-8") as fh:
|
|
251
|
+
entries = json.load(fh)
|
|
252
|
+
sessions = []
|
|
253
|
+
for entry in entries:
|
|
254
|
+
sessions.append({"session_id": entry["session_id"], "project": entry["project"],
|
|
255
|
+
"task_type": entry["task_type"], "rows": _read_jsonl(entry["transcript_path"])})
|
|
256
|
+
print(json.dumps(analyse_sessions(sessions, _read_jsonl(args.exposures), args.window), sort_keys=True))
|
|
257
|
+
return 0
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
if __name__ == "__main__":
|
|
261
|
+
raise SystemExit(main())
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
"""First-read replacement only after a new, explicit cohort re-promotion."""
|
|
2
|
+
import json
|
|
3
|
+
import math
|
|
4
|
+
import os
|
|
5
|
+
from datetime import datetime
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def enabled(sidecar_path, language, band):
|
|
10
|
+
"""Old promotions and malformed sidecars never activate target replacement."""
|
|
11
|
+
try:
|
|
12
|
+
data = json.loads(Path(sidecar_path).read_text(encoding="utf-8"))
|
|
13
|
+
promoted = data["promoted_at"]
|
|
14
|
+
demoted = data["demoted"]
|
|
15
|
+
key = language + "|" + band
|
|
16
|
+
stamp = promoted[key]
|
|
17
|
+
marker = promoted.get("target_skeleton_v1|" + key)
|
|
18
|
+
return (isinstance(demoted, list) and [language, band] not in demoted
|
|
19
|
+
and isinstance(stamp, (int, float)) and not isinstance(stamp, bool)
|
|
20
|
+
and math.isfinite(stamp) and stamp > 0
|
|
21
|
+
and isinstance(marker, (int, float)) and not isinstance(marker, bool)
|
|
22
|
+
and marker == stamp)
|
|
23
|
+
except (OSError, ValueError, TypeError, OverflowError, KeyError, AttributeError):
|
|
24
|
+
return False
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def serve(file_path, stat, language, band, session_id, content, result, orig_tokens, estimate, emit,
|
|
28
|
+
snapshot_dir=None, tool_use_id="", allow_context=None, strict=False, parent_session_id=""):
|
|
29
|
+
"""Archive first, emit a real denial, then log its estimated net removal."""
|
|
30
|
+
try:
|
|
31
|
+
from archive_result import archive_entry_exists, archive_original, build_archive_pointer, derive_archive_key
|
|
32
|
+
source = Path(file_path)
|
|
33
|
+
content = source.read_text(encoding="utf-8", errors="replace")
|
|
34
|
+
current = source.stat()
|
|
35
|
+
if current.st_mtime_ns != stat.st_mtime_ns or current.st_size != stat.st_size:
|
|
36
|
+
return False
|
|
37
|
+
orig_tokens = min(orig_tokens, int(estimate(content)))
|
|
38
|
+
key = derive_archive_key(session_id, file_path, stat.st_mtime_ns)
|
|
39
|
+
if archive_original(content, session_id, key, "Read", quiet=True, file_path=file_path, language=language) is None:
|
|
40
|
+
return False
|
|
41
|
+
if not archive_entry_exists(session_id, key):
|
|
42
|
+
return False
|
|
43
|
+
body = build_archive_pointer(result.replacement_text, len(content), key)
|
|
44
|
+
reason = "large-file first read served as a code outline; use expand or a ranged Read for the full file."
|
|
45
|
+
context = "[Token Optimizer] First-read code outline.\n" + body
|
|
46
|
+
if allow_context is not None and not allow_context(context, strict):
|
|
47
|
+
return False
|
|
48
|
+
replacement_tokens = int(estimate(reason) + estimate(context))
|
|
49
|
+
if replacement_tokens <= 0 or replacement_tokens >= orig_tokens:
|
|
50
|
+
return False
|
|
51
|
+
emit("deny", reason, context)
|
|
52
|
+
except Exception:
|
|
53
|
+
return False
|
|
54
|
+
if snapshot_dir is not None and tool_use_id:
|
|
55
|
+
try:
|
|
56
|
+
from .periphery_exposure import record_target_outline
|
|
57
|
+
rows = record_target_outline(snapshot_dir, session_id, tool_use_id, file_path, language, band)
|
|
58
|
+
if rows:
|
|
59
|
+
from .first_read_outcomes import _hash
|
|
60
|
+
rows[0].update(timestamp_local=datetime.now().isoformat(), original_tokens=orig_tokens,
|
|
61
|
+
compressed_tokens=replacement_tokens, parent_session_id=_hash(parent_session_id or session_id))
|
|
62
|
+
path = Path(snapshot_dir) / "diagnostics" / "first_read_pending.jsonl"
|
|
63
|
+
fd = os.open(str(path), os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0o600)
|
|
64
|
+
with os.fdopen(fd, "a", encoding="utf-8") as stream:
|
|
65
|
+
stream.write(json.dumps(rows[0], separators=(",", ":")) + "\n")
|
|
66
|
+
except Exception:
|
|
67
|
+
pass
|
|
68
|
+
return True
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def reconcile(conn, snapshot_dir):
|
|
72
|
+
"""Append measured rows only after the transcript confirms the denial."""
|
|
73
|
+
from .first_read_outcomes import _hash, inspect
|
|
74
|
+
from .setup_attachment_counter import read_transcript
|
|
75
|
+
from .counted_subagents import subagent_files
|
|
76
|
+
path = Path(snapshot_dir) / "diagnostics" / "first_read_pending.jsonl"
|
|
77
|
+
if not path.is_file():
|
|
78
|
+
return 0
|
|
79
|
+
try:
|
|
80
|
+
pending = []
|
|
81
|
+
with path.open(encoding="utf-8") as stream:
|
|
82
|
+
for line in stream:
|
|
83
|
+
try:
|
|
84
|
+
row = json.loads(line)
|
|
85
|
+
if isinstance(row, dict):
|
|
86
|
+
pending.append(row)
|
|
87
|
+
except ValueError:
|
|
88
|
+
continue
|
|
89
|
+
conn.execute("CREATE TABLE IF NOT EXISTS first_read_confirmations (exposure_id TEXT PRIMARY KEY, event_id INTEGER NOT NULL)")
|
|
90
|
+
conn.execute("CREATE TABLE IF NOT EXISTS first_read_confirmation_scopes (event_id INTEGER PRIMARY KEY, tool_id_hash TEXT NOT NULL)")
|
|
91
|
+
done = {row[0] for row in conn.execute("SELECT exposure_id FROM first_read_confirmations")}
|
|
92
|
+
sessions = {}
|
|
93
|
+
for uuid, transcript in conn.execute("SELECT DISTINCT session_uuid,jsonl_path FROM session_log WHERE session_uuid IS NOT NULL AND jsonl_path IS NOT NULL"):
|
|
94
|
+
sessions.setdefault(_hash(uuid), []).append((uuid, transcript))
|
|
95
|
+
written = 0
|
|
96
|
+
for row in pending:
|
|
97
|
+
ident = row.get("exposure_id")
|
|
98
|
+
matches = sessions.get(row.get("parent_session_id") or row.get("session_id"), [])
|
|
99
|
+
if not ident or ident in done or len(matches) != 1:
|
|
100
|
+
continue
|
|
101
|
+
uuid, transcript = matches[0]
|
|
102
|
+
try:
|
|
103
|
+
subagent = row.get("session_id") != _hash(uuid)
|
|
104
|
+
if subagent:
|
|
105
|
+
candidates = [p for p in subagent_files(transcript) if p.stem.startswith("agent-") and _hash(p.stem[6:]) == row.get("session_id")]
|
|
106
|
+
if len(candidates) != 1:
|
|
107
|
+
continue
|
|
108
|
+
transcript = candidates[0]
|
|
109
|
+
original, compressed = int(row["original_tokens"]), int(row["compressed_tokens"])
|
|
110
|
+
timestamp = row["timestamp_local"]
|
|
111
|
+
datetime.fromisoformat(timestamp)
|
|
112
|
+
if original <= compressed or compressed <= 0 or not inspect(read_transcript(transcript), row)["confirmed"]:
|
|
113
|
+
continue
|
|
114
|
+
conn.execute("SAVEPOINT first_read_confirmation")
|
|
115
|
+
cursor = conn.execute("INSERT INTO compression_events(timestamp,session_id,session_uuid,feature,command_pattern,original_tokens,compressed_tokens,compression_ratio,quality_preserved,verified,detail,model,tier) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)",
|
|
116
|
+
(timestamp, uuid, uuid, "first_read_skeleton", str(row["language"]) + "|" + str(row["band"]), original, compressed, 1 - compressed / original, 0, 1, "repromoted target outline; quality not verified" + ("; subagent" if subagent else ""), "unknown", "measured"))
|
|
117
|
+
if cursor.rowcount != 1:
|
|
118
|
+
raise RuntimeError("event was not inserted")
|
|
119
|
+
receipt = conn.execute("INSERT INTO first_read_confirmations(exposure_id,event_id) VALUES(?,?)", (ident, cursor.lastrowid))
|
|
120
|
+
if subagent:
|
|
121
|
+
conn.execute("INSERT INTO first_read_confirmation_scopes(event_id,tool_id_hash) VALUES(?,?)", (cursor.lastrowid, row["tool_use_id"]))
|
|
122
|
+
stored = conn.execute("SELECT original_tokens,compressed_tokens,tier FROM compression_events WHERE id=?", (cursor.lastrowid,)).fetchone()
|
|
123
|
+
if receipt.rowcount != 1 or stored != (original, compressed, "measured"):
|
|
124
|
+
raise RuntimeError("event readback failed")
|
|
125
|
+
conn.execute("RELEASE first_read_confirmation")
|
|
126
|
+
done.add(ident)
|
|
127
|
+
written += 1
|
|
128
|
+
except (OSError, ValueError, TypeError, KeyError):
|
|
129
|
+
continue
|
|
130
|
+
return written
|
|
131
|
+
except Exception:
|
|
132
|
+
try:
|
|
133
|
+
conn.execute("ROLLBACK TO first_read_confirmation")
|
|
134
|
+
conn.execute("RELEASE first_read_confirmation")
|
|
135
|
+
except Exception:
|
|
136
|
+
pass
|
|
137
|
+
return 0
|