@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,287 @@
|
|
|
1
|
+
"""Coordinate upgrade-drain processes without expiring a live worker."""
|
|
2
|
+
import os
|
|
3
|
+
import itertools
|
|
4
|
+
import re
|
|
5
|
+
import sqlite3
|
|
6
|
+
import tempfile
|
|
7
|
+
import time
|
|
8
|
+
from contextlib import contextmanager
|
|
9
|
+
|
|
10
|
+
from hook_provenance import _exclusive
|
|
11
|
+
from .lease_candidate_cleanup import owner_is_gone
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _marker(facade):
|
|
15
|
+
return facade.SNAPSHOT_DIR / facade._UPGRADE_DRAIN_LOCK_NAME
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _write_marker(marker, pid, exclusive=False):
|
|
19
|
+
fd, name = tempfile.mkstemp(prefix="." + marker.name + "." + str(os.getpid()) + ".", dir=str(marker.parent))
|
|
20
|
+
try:
|
|
21
|
+
with os.fdopen(fd, "w") as handle:
|
|
22
|
+
handle.write(str(pid))
|
|
23
|
+
handle.flush()
|
|
24
|
+
os.fsync(handle.fileno())
|
|
25
|
+
if exclusive:
|
|
26
|
+
os.link(name, marker)
|
|
27
|
+
else:
|
|
28
|
+
os.replace(name, marker)
|
|
29
|
+
finally:
|
|
30
|
+
try:
|
|
31
|
+
os.unlink(name)
|
|
32
|
+
except FileNotFoundError:
|
|
33
|
+
pass
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _clean_temporaries(facade, marker):
|
|
37
|
+
prefix = "." + marker.name + "."
|
|
38
|
+
deadline = time.monotonic() + 0.025
|
|
39
|
+
try:
|
|
40
|
+
with os.scandir(marker.parent) as entries:
|
|
41
|
+
for entry in entries:
|
|
42
|
+
if time.monotonic() >= deadline:
|
|
43
|
+
break
|
|
44
|
+
if not entry.name.startswith(prefix):
|
|
45
|
+
continue
|
|
46
|
+
parts = entry.name[len(prefix):].split(".")
|
|
47
|
+
if (len(parts) != 2 or not parts[0].isdigit() or len(parts[1]) != 8
|
|
48
|
+
or any(c not in "abcdefghijklmnopqrstuvwxyz0123456789_" for c in parts[1])):
|
|
49
|
+
continue
|
|
50
|
+
try:
|
|
51
|
+
if (entry.is_file(follow_symlinks=False) and entry.stat(follow_symlinks=False).st_mtime < time.time() - 86400
|
|
52
|
+
and owner_is_gone(int(parts[0]))):
|
|
53
|
+
os.unlink(entry.path)
|
|
54
|
+
except OSError:
|
|
55
|
+
continue
|
|
56
|
+
except OSError:
|
|
57
|
+
pass
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def claim(facade):
|
|
61
|
+
marker = _marker(facade)
|
|
62
|
+
try:
|
|
63
|
+
marker.parent.mkdir(parents=True, exist_ok=True)
|
|
64
|
+
with _exclusive(marker.with_name(marker.name + ".claim"), timeout=0.05) as held:
|
|
65
|
+
if not held:
|
|
66
|
+
return False
|
|
67
|
+
_clean_temporaries(facade, marker)
|
|
68
|
+
if marker.exists():
|
|
69
|
+
age = time.time() - marker.stat().st_mtime
|
|
70
|
+
try:
|
|
71
|
+
pid = int(marker.read_text(encoding="utf-8"))
|
|
72
|
+
except (ValueError, OSError):
|
|
73
|
+
pid = 0
|
|
74
|
+
if age < 1 or (pid > 0 and not owner_is_gone(pid)):
|
|
75
|
+
return False
|
|
76
|
+
marker.unlink()
|
|
77
|
+
_write_marker(marker, os.getpid(), exclusive=True)
|
|
78
|
+
return True
|
|
79
|
+
except OSError:
|
|
80
|
+
return False
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def publish_child(facade, child_pid):
|
|
84
|
+
marker = _marker(facade)
|
|
85
|
+
try:
|
|
86
|
+
with _exclusive(marker.with_name(marker.name + ".claim"), timeout=0.05) as held:
|
|
87
|
+
if held and marker.read_text(encoding="utf-8") == str(os.getpid()):
|
|
88
|
+
_write_marker(marker, child_pid)
|
|
89
|
+
except OSError:
|
|
90
|
+
pass
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def release(facade):
|
|
94
|
+
marker = _marker(facade)
|
|
95
|
+
try:
|
|
96
|
+
with _exclusive(marker.with_name(marker.name + ".claim"), timeout=0.05) as held:
|
|
97
|
+
if held and marker.read_text(encoding="utf-8") == str(os.getpid()):
|
|
98
|
+
marker.unlink()
|
|
99
|
+
except OSError:
|
|
100
|
+
pass
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
@contextmanager
|
|
104
|
+
def running(facade):
|
|
105
|
+
marker = _marker(facade)
|
|
106
|
+
try:
|
|
107
|
+
marker.parent.mkdir(parents=True, exist_ok=True)
|
|
108
|
+
except OSError:
|
|
109
|
+
yield False
|
|
110
|
+
return
|
|
111
|
+
with _exclusive(marker.with_name(marker.name + ".running"), timeout=0) as held:
|
|
112
|
+
yield held
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def retry_ready(raw, key, now):
|
|
116
|
+
parts = (raw or "").split(":")
|
|
117
|
+
if len(parts) < 2 or parts[0] != key:
|
|
118
|
+
return True, 0
|
|
119
|
+
try:
|
|
120
|
+
attempts = max(0, int(parts[1]))
|
|
121
|
+
last = float(parts[2]) if len(parts) > 2 else 0
|
|
122
|
+
except ValueError:
|
|
123
|
+
return True, 0
|
|
124
|
+
age = now - last
|
|
125
|
+
delay = min(300, 2 ** min(attempts, 9))
|
|
126
|
+
return not (0 <= age < delay), attempts
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def transcript_progress(conn):
|
|
130
|
+
conn.execute("CREATE TABLE IF NOT EXISTS transcript_backfill_progress "
|
|
131
|
+
"(session_uuid TEXT PRIMARY KEY, size INTEGER NOT NULL, mtime_ns INTEGER NOT NULL)")
|
|
132
|
+
return {sid: [size, mtime] for sid, size, mtime in conn.execute(
|
|
133
|
+
"SELECT session_uuid, size, mtime_ns FROM transcript_backfill_progress")}
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def commit_transcript(conn, session_uuid, stamp):
|
|
137
|
+
conn.execute("INSERT INTO transcript_backfill_progress (session_uuid, size, mtime_ns) VALUES (?, ?, ?) "
|
|
138
|
+
"ON CONFLICT(session_uuid) DO UPDATE SET size=excluded.size, mtime_ns=excluded.mtime_ns",
|
|
139
|
+
(session_uuid, stamp[0], stamp[1]))
|
|
140
|
+
conn.commit()
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def commit_marker_cursor(conn, key, cursor):
|
|
144
|
+
conn.execute("INSERT INTO token_optimizer_meta (key, value) VALUES (?, ?) "
|
|
145
|
+
"ON CONFLICT(key) DO UPDATE SET value=excluded.value WHERE token_optimizer_meta.value < excluded.value",
|
|
146
|
+
(key, cursor))
|
|
147
|
+
conn.commit()
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def commit_drain_session(conn):
|
|
151
|
+
if os.environ.get("TOKEN_OPTIMIZER_UPGRADE_DRAIN", "").strip() == "1":
|
|
152
|
+
conn.commit()
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def backfill_pending(stats):
|
|
156
|
+
return bool(stats.get("pending") or any(
|
|
157
|
+
(value.get("pending") if isinstance(value, dict) else value)
|
|
158
|
+
for key, value in stats.items() if key.endswith("error") or isinstance(value, dict)))
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
_SESSION_WRITE = re.compile(r'^\s*(?:INSERT(?:\s+OR\s+\w+)?\s+INTO|UPDATE(?:\s+OR\s+\w+)?|DELETE\s+FROM)\s+["`\[]?session_log(?=[\s(\]`";]|$)', re.I)
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
class _RawConnection:
|
|
165
|
+
def __init__(self, conn):
|
|
166
|
+
self.conn = conn
|
|
167
|
+
|
|
168
|
+
def execute(self, sql, parameters=()):
|
|
169
|
+
return sqlite3.Connection.execute(self.conn, sql, parameters)
|
|
170
|
+
|
|
171
|
+
def executemany(self, sql, parameters):
|
|
172
|
+
return sqlite3.Connection.executemany(self.conn, sql, parameters)
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
class SessionLogConnection(sqlite3.Connection):
|
|
176
|
+
"""Apply the bounded retry to direct session_log writes from every adapter."""
|
|
177
|
+
def execute(self, sql, parameters=()):
|
|
178
|
+
if _SESSION_WRITE.match(sql):
|
|
179
|
+
result = session_write(self, sql, parameters)
|
|
180
|
+
if result is None:
|
|
181
|
+
raise sqlite3.OperationalError("session_log write deferred: database is locked")
|
|
182
|
+
return result
|
|
183
|
+
return super().execute(sql, parameters)
|
|
184
|
+
|
|
185
|
+
def executemany(self, sql, parameters):
|
|
186
|
+
if _SESSION_WRITE.match(sql):
|
|
187
|
+
result = session_write(self, sql, parameters, many=True)
|
|
188
|
+
if result is None:
|
|
189
|
+
raise sqlite3.OperationalError("session_log write deferred: database is locked")
|
|
190
|
+
return result
|
|
191
|
+
return super().executemany(sql, parameters)
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def session_write(conn, sql, parameters, budget_seconds=0.3, many=False):
|
|
195
|
+
"""Retry a session-row mutation briefly; None leaves it for the next pass."""
|
|
196
|
+
raw = _RawConnection(conn) if isinstance(conn, SessionLogConnection) else conn
|
|
197
|
+
previous = raw.execute("PRAGMA busy_timeout").fetchone()[0]
|
|
198
|
+
deadline = time.monotonic() + budget_seconds
|
|
199
|
+
raw.execute("PRAGMA busy_timeout=50")
|
|
200
|
+
source = iter(parameters) if many else None
|
|
201
|
+
try:
|
|
202
|
+
for attempt in range(6):
|
|
203
|
+
try:
|
|
204
|
+
if not many:
|
|
205
|
+
return raw.execute(sql, parameters)
|
|
206
|
+
batch, source = itertools.tee(source)
|
|
207
|
+
if conn.isolation_level is not None and not conn.in_transaction:
|
|
208
|
+
raw.execute("BEGIN")
|
|
209
|
+
raw.execute("SAVEPOINT to_session_write")
|
|
210
|
+
try:
|
|
211
|
+
result = raw.executemany(sql, batch)
|
|
212
|
+
except BaseException:
|
|
213
|
+
raw.execute("ROLLBACK TO to_session_write")
|
|
214
|
+
raw.execute("RELEASE to_session_write")
|
|
215
|
+
raise
|
|
216
|
+
raw.execute("RELEASE to_session_write")
|
|
217
|
+
return result
|
|
218
|
+
except sqlite3.OperationalError as exc:
|
|
219
|
+
if "locked" not in str(exc).lower() and "busy" not in str(exc).lower():
|
|
220
|
+
raise
|
|
221
|
+
remaining = deadline - time.monotonic()
|
|
222
|
+
if remaining <= 0:
|
|
223
|
+
return None
|
|
224
|
+
time.sleep(min(remaining, 0.01 * (2 ** attempt)))
|
|
225
|
+
return None
|
|
226
|
+
finally:
|
|
227
|
+
raw.execute("PRAGMA busy_timeout=" + str(int(previous)))
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
class DailyUpdates:
|
|
231
|
+
"""Commit each completed session in a drain; keep hook passes batched."""
|
|
232
|
+
def __init__(self, conn, facade):
|
|
233
|
+
self.conn = conn
|
|
234
|
+
self.facade = facade
|
|
235
|
+
self.pending = []
|
|
236
|
+
self.count = 0
|
|
237
|
+
self.immediate = facade._collect_drain_mode() == "full"
|
|
238
|
+
|
|
239
|
+
def append(self, row):
|
|
240
|
+
self.pending.append(row)
|
|
241
|
+
if self.immediate and self.facade._retry_db_operation(self.conn, self.flush) is None:
|
|
242
|
+
raise self.facade.sqlite3.OperationalError("daily backfill remained locked")
|
|
243
|
+
|
|
244
|
+
def flush(self):
|
|
245
|
+
count = len(self.pending)
|
|
246
|
+
result = session_write(self.conn,
|
|
247
|
+
"UPDATE session_log SET daily_usage_json=?, session_uuid=COALESCE(session_uuid, ?), "
|
|
248
|
+
"first_activity_day=?, last_activity_day=?, date=?, parent_daily_usage_json=?, "
|
|
249
|
+
"daily_calls_json=?, daily_metrics_json=? WHERE jsonl_path=? AND daily_usage_json IS NULL", self.pending, many=True)
|
|
250
|
+
if result is None:
|
|
251
|
+
raise sqlite3.OperationalError("database is locked")
|
|
252
|
+
self.conn.commit()
|
|
253
|
+
self.pending.clear()
|
|
254
|
+
self.count += count
|
|
255
|
+
return count
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
def counted_backfill_all(facade, conn, quiet):
|
|
259
|
+
stats = facade._update_counted_cumulative(conn, max_sessions=10**9, deadline_seconds=None, quiet=quiet)
|
|
260
|
+
marker_total = {"files_scanned": 0, "rows_written": 0, "done": False}
|
|
261
|
+
|
|
262
|
+
def cursor():
|
|
263
|
+
try:
|
|
264
|
+
row = conn.execute("SELECT value FROM token_optimizer_meta WHERE key=?",
|
|
265
|
+
(facade._COUNTED_META_MARKER_CURSOR,)).fetchone()
|
|
266
|
+
return row[0] if row else ""
|
|
267
|
+
except facade.sqlite3.Error:
|
|
268
|
+
return None
|
|
269
|
+
|
|
270
|
+
seen = {cursor()}
|
|
271
|
+
for _ in range(1000):
|
|
272
|
+
marker = facade._counted_marker_backfill(conn, max_files=500, deadline_seconds=None, quiet=quiet)
|
|
273
|
+
marker_total["files_scanned"] += int(marker.get("files_scanned", 0) or 0)
|
|
274
|
+
marker_total["rows_written"] += int(marker.get("rows_written", 0) or 0)
|
|
275
|
+
marker_total["done"] = bool(marker.get("done"))
|
|
276
|
+
if marker_total["done"] or not marker.get("files_scanned"):
|
|
277
|
+
break
|
|
278
|
+
current = cursor()
|
|
279
|
+
if current in seen:
|
|
280
|
+
break
|
|
281
|
+
seen.add(current)
|
|
282
|
+
stats.update({"marker_files_scanned": marker_total["files_scanned"],
|
|
283
|
+
"marker_rows_written": marker_total["rows_written"],
|
|
284
|
+
"marker_backfill_done": marker_total["done"],
|
|
285
|
+
"rows_removed_no_transcript": facade._purge_counted_without_transcripts(conn)})
|
|
286
|
+
stats["pricing_coverage"] = facade._counted_rollup_rows(facade._counted_stored_rows(conn).values(), conn)
|
|
287
|
+
return stats
|
|
@@ -106,38 +106,9 @@ def log_tool_use(store, tool_name: str, command: str = "", has_error: bool = Fal
|
|
|
106
106
|
Current detected mode string, or None on failure
|
|
107
107
|
"""
|
|
108
108
|
try:
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
"INSERT INTO activity_log (tool_name, tool_bucket, has_error, timestamp) "
|
|
114
|
-
"VALUES (?, ?, ?, ?)",
|
|
115
|
-
(tool_name[:64], bucket, 1 if has_error else 0, time.time()),
|
|
116
|
-
)
|
|
117
|
-
|
|
118
|
-
rows = conn.execute(
|
|
119
|
-
"SELECT tool_bucket, has_error FROM activity_log "
|
|
120
|
-
"ORDER BY id DESC LIMIT ?",
|
|
121
|
-
(_WINDOW_SIZE,),
|
|
122
|
-
).fetchall()
|
|
123
|
-
|
|
124
|
-
row_count = conn.execute("SELECT COUNT(*) FROM activity_log").fetchone()[0]
|
|
125
|
-
if row_count > _PRUNE_THRESHOLD:
|
|
126
|
-
conn.execute(
|
|
127
|
-
"DELETE FROM activity_log WHERE id NOT IN "
|
|
128
|
-
"(SELECT id FROM activity_log ORDER BY id DESC LIMIT ?)",
|
|
129
|
-
(_PRUNE_KEEP,),
|
|
130
|
-
)
|
|
131
|
-
|
|
132
|
-
recent_buckets = [r[0] for r in rows]
|
|
133
|
-
has_recent_errors = any(r[1] for r in rows)
|
|
134
|
-
mode = detect_mode(recent_buckets, has_recent_errors)
|
|
135
|
-
|
|
136
|
-
conn.execute(
|
|
137
|
-
"INSERT OR REPLACE INTO session_meta (key, value) VALUES (?, ?)",
|
|
138
|
-
("current_mode", mode),
|
|
139
|
-
)
|
|
140
|
-
conn.commit()
|
|
141
|
-
return mode
|
|
109
|
+
from _measure import session_store_spool
|
|
110
|
+
session_store_spool.enqueue(store, {"kind": "activity", "tool_name": tool_name[:64],
|
|
111
|
+
"bucket": classify_tool(tool_name, command), "has_error": int(bool(has_error)), "timestamp": time.time()})
|
|
112
|
+
return store.get_meta("current_mode") if store._conn is not None else None
|
|
142
113
|
except Exception:
|
|
143
114
|
return None
|
|
@@ -57,6 +57,8 @@ _PAYLOAD_MODULES = (
|
|
|
57
57
|
"plugin_env.py",
|
|
58
58
|
"bash_hook.py",
|
|
59
59
|
"bash_compress.py",
|
|
60
|
+
"post_run_classify.py",
|
|
61
|
+
"preserved_reinject.py",
|
|
60
62
|
"bash_search_results.py",
|
|
61
63
|
# Dependency-free whitelist gate shared by bash_hook + bash_compress.
|
|
62
64
|
"bash_whitelist.py",
|
|
@@ -1472,11 +1472,10 @@ def archive_result(quiet: bool = False) -> None:
|
|
|
1472
1472
|
print("[Tool Archive] Missing tool_use_id or session_id, skipping.", file=sys.stderr)
|
|
1473
1473
|
return
|
|
1474
1474
|
|
|
1475
|
-
|
|
1476
|
-
|
|
1477
|
-
|
|
1478
|
-
|
|
1479
|
-
# validation, and makes path traversal impossible by construction.
|
|
1475
|
+
if '__' in tool_name and not _is_archive_exempt(tool_name):
|
|
1476
|
+
from _measure.mcp_archive_tripwire import decide
|
|
1477
|
+
if decide(TRENDS_DB, tool_name, active=os.environ.get('TOKEN_OPTIMIZER_MCP_ARCHIVE_TRIPWIRE') == 'active'):
|
|
1478
|
+
return
|
|
1480
1479
|
raw_tool_use_id = tool_use_id
|
|
1481
1480
|
tool_use_id = _safe_archive_key(tool_use_id)
|
|
1482
1481
|
if tool_use_id != raw_tool_use_id and not quiet:
|
|
@@ -1671,10 +1670,7 @@ def archive_result(quiet: bool = False) -> None:
|
|
|
1671
1670
|
if store is not None:
|
|
1672
1671
|
store.close()
|
|
1673
1672
|
|
|
1674
|
-
# Allowlisted tools
|
|
1675
|
-
# fetchers: skip the replacement so the full verbatim result reaches
|
|
1676
|
-
# context. It's still archived to disk above, so `expand <id>` works —
|
|
1677
|
-
# same treatment as _AGENT_RESULT_TOOL_NAMES (archive, don't replace).
|
|
1673
|
+
# Allowlisted tools serve their full result.
|
|
1678
1674
|
if "__" in tool_name and _is_archive_exempt(tool_name):
|
|
1679
1675
|
if not quiet:
|
|
1680
1676
|
print(f"[Tool Archive] {tool_name} is allowlisted; serving full result (archived for expand).", file=sys.stderr)
|
|
@@ -1691,7 +1687,8 @@ def archive_result(quiet: bool = False) -> None:
|
|
|
1691
1687
|
|
|
1692
1688
|
if "__" in tool_name:
|
|
1693
1689
|
output_type = _detect_output_type(safe_response)
|
|
1694
|
-
|
|
1690
|
+
from _measure.mcp_archive_tripwire import structured_preview
|
|
1691
|
+
preview = structured_preview(safe_response, breaks_cluster=_breaks_cluster)
|
|
1695
1692
|
suffix = f" ({output_type})" if output_type != "text" else ""
|
|
1696
1693
|
if original_char_count > _ARCHIVE_MAX_SIZE:
|
|
1697
1694
|
replacement = preview + (
|
|
@@ -1706,15 +1703,12 @@ def archive_result(quiet: bool = False) -> None:
|
|
|
1706
1703
|
original_tokens = int(original_char_count / CODE_CHARS_PER_TOKEN)
|
|
1707
1704
|
replacement_tokens = int(len(replacement) / CODE_CHARS_PER_TOKEN)
|
|
1708
1705
|
tokens_saved = max(0, original_tokens - replacement_tokens)
|
|
1709
|
-
|
|
1710
|
-
|
|
1711
|
-
|
|
1712
|
-
|
|
1713
|
-
|
|
1714
|
-
|
|
1715
|
-
f"({original_char_count:,} chars -> {len(replacement):,} chars)"
|
|
1716
|
-
),
|
|
1717
|
-
)
|
|
1706
|
+
detail = f"replaced {tool_name} ({original_char_count:,} chars -> {len(replacement):,} chars)"
|
|
1707
|
+
_log_savings_event("tool_archive", tokens_saved, session_id=session_id, detail=detail)
|
|
1708
|
+
import archive_verify # read back earlier replacements from the transcript, then queue this one
|
|
1709
|
+
archive_verify.verify(TRENDS_DB, session_id)
|
|
1710
|
+
if tokens_saved > 0: archive_verify.record(TRENDS_DB, session_id, raw_tool_use_id, tool_name,
|
|
1711
|
+
original_char_count, len(replacement), hook_input.get("transcript_path"), detail)
|
|
1718
1712
|
output = json.dumps({
|
|
1719
1713
|
"hookSpecificOutput": {
|
|
1720
1714
|
"hookEventName": "PostToolUse",
|
|
@@ -1722,6 +1716,8 @@ def archive_result(quiet: bool = False) -> None:
|
|
|
1722
1716
|
}
|
|
1723
1717
|
})
|
|
1724
1718
|
print(output)
|
|
1719
|
+
from _measure.mcp_archive_tripwire import record
|
|
1720
|
+
record(TRENDS_DB, tool_name, sanitize_sid(session_id), tool_use_id, tokens_saved)
|
|
1725
1721
|
|
|
1726
1722
|
|
|
1727
1723
|
if __name__ == "__main__":
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
"""Check at the source that an archived tool result was really replaced.
|
|
2
|
+
|
|
3
|
+
The archive hook returns a trimmed replacement and logs "replaced" right
|
|
4
|
+
away. Whether the host honoured the replacement only shows later, in the
|
|
5
|
+
session transcript: the tool_result there is either the pointer or the full
|
|
6
|
+
output. Some host versions ignored the replacement for months while the
|
|
7
|
+
ledger kept claiming the saving, and nothing warned.
|
|
8
|
+
|
|
9
|
+
``record`` notes each replacement as pending. ``verify`` runs on a later hook
|
|
10
|
+
call in the same session, reads back the tool_result for pending calls from
|
|
11
|
+
the transcript tail, and stores a verdict: ``pointer`` (the saving is real) or
|
|
12
|
+
``full`` (it is not; the counted view leaves that ledger row out). ``health``
|
|
13
|
+
raises a warning when the newest MIN_STREAK verdicts are all ``full``.
|
|
14
|
+
|
|
15
|
+
Hook hot path: stdlib only, bounded reads, never raises.
|
|
16
|
+
"""
|
|
17
|
+
import json
|
|
18
|
+
import os
|
|
19
|
+
import sqlite3
|
|
20
|
+
from datetime import datetime
|
|
21
|
+
from pathlib import Path
|
|
22
|
+
|
|
23
|
+
TABLE = "archive_verifications"
|
|
24
|
+
MIN_STREAK = 3
|
|
25
|
+
TAIL_BYTES = 16 * 1024 * 1024
|
|
26
|
+
MARKER = "Full result archived"
|
|
27
|
+
_SCHEMA = ("CREATE TABLE IF NOT EXISTS " + TABLE + " (tool_use_id TEXT, session_id TEXT, event_id INTEGER, "
|
|
28
|
+
"tool_name TEXT, original_chars INTEGER, pointer_chars INTEGER, transcript_path TEXT, "
|
|
29
|
+
"logged_at TEXT, verdict TEXT, checked_at TEXT, PRIMARY KEY(session_id, tool_use_id))")
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _connect(trends_db, timeout=0.5):
|
|
33
|
+
conn = sqlite3.connect(str(trends_db), timeout=timeout)
|
|
34
|
+
conn.execute("PRAGMA busy_timeout=%d" % int(timeout * 1000))
|
|
35
|
+
conn.execute(_SCHEMA)
|
|
36
|
+
return conn
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def record(trends_db, session_id, tool_use_id, tool_name, original_chars, pointer_chars, transcript_path, detail):
|
|
40
|
+
"""Note a logged replacement as pending verification. Never raises."""
|
|
41
|
+
if not (session_id and tool_use_id and transcript_path):
|
|
42
|
+
return
|
|
43
|
+
conn = None
|
|
44
|
+
try:
|
|
45
|
+
conn = _connect(trends_db)
|
|
46
|
+
row = conn.execute("SELECT max(id) FROM savings_events WHERE event_type='tool_archive' AND session_id=? AND detail=?",
|
|
47
|
+
(session_id, detail)).fetchone()
|
|
48
|
+
conn.execute("INSERT OR IGNORE INTO " + TABLE + " (tool_use_id, session_id, event_id, tool_name, original_chars, "
|
|
49
|
+
"pointer_chars, transcript_path, logged_at) VALUES (?,?,?,?,?,?,?,?)",
|
|
50
|
+
(tool_use_id, session_id, row[0] if row else None, tool_name, int(original_chars),
|
|
51
|
+
int(pointer_chars), str(transcript_path), datetime.now().isoformat()))
|
|
52
|
+
conn.commit()
|
|
53
|
+
except Exception:
|
|
54
|
+
pass
|
|
55
|
+
finally:
|
|
56
|
+
if conn is not None:
|
|
57
|
+
conn.close()
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _tail_results(path, wanted):
|
|
61
|
+
"""{tool_use_id: result text length, has pointer marker} from the transcript tail."""
|
|
62
|
+
found = {}
|
|
63
|
+
with open(path, "rb") as stream:
|
|
64
|
+
size = os.fstat(stream.fileno()).st_size
|
|
65
|
+
if size > TAIL_BYTES:
|
|
66
|
+
stream.seek(size - TAIL_BYTES)
|
|
67
|
+
stream.readline()
|
|
68
|
+
for line in stream:
|
|
69
|
+
if b'"tool_result"' not in line or not any(t.encode() in line for t in wanted):
|
|
70
|
+
continue
|
|
71
|
+
try:
|
|
72
|
+
record = json.loads(line)
|
|
73
|
+
except ValueError:
|
|
74
|
+
continue
|
|
75
|
+
content = (record.get("message") or {}).get("content") if isinstance(record, dict) else None
|
|
76
|
+
for block in content if isinstance(content, list) else []:
|
|
77
|
+
if not isinstance(block, dict) or block.get("type") != "tool_result" or block.get("tool_use_id") not in wanted:
|
|
78
|
+
continue
|
|
79
|
+
value = block.get("content")
|
|
80
|
+
if isinstance(value, list):
|
|
81
|
+
value = "\n".join(b.get("text", "") for b in value if isinstance(b, dict) and b.get("type") == "text")
|
|
82
|
+
if isinstance(value, str):
|
|
83
|
+
found[block["tool_use_id"]] = (len(value), MARKER in value)
|
|
84
|
+
return found
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def verdict_for(length, has_marker, original_chars, pointer_chars):
|
|
88
|
+
if has_marker or abs(length - pointer_chars) <= max(100, pointer_chars * 0.1):
|
|
89
|
+
return "pointer"
|
|
90
|
+
if length >= 0.9 * original_chars:
|
|
91
|
+
return "full"
|
|
92
|
+
return None
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def verify(trends_db, session_id, limit=50):
|
|
96
|
+
"""Judge pending replacements of this session from its transcript. Never raises."""
|
|
97
|
+
if not session_id:
|
|
98
|
+
return 0
|
|
99
|
+
conn = None
|
|
100
|
+
judged = 0
|
|
101
|
+
try:
|
|
102
|
+
conn = _connect(trends_db)
|
|
103
|
+
rows = conn.execute("SELECT tool_use_id, original_chars, pointer_chars, transcript_path FROM " + TABLE +
|
|
104
|
+
" WHERE session_id=? AND verdict IS NULL ORDER BY logged_at LIMIT ?", (session_id, limit)).fetchall()
|
|
105
|
+
if not rows:
|
|
106
|
+
return 0
|
|
107
|
+
found = _tail_results(rows[0][3], {r[0] for r in rows})
|
|
108
|
+
now = datetime.now().isoformat()
|
|
109
|
+
for tool_use_id, original, pointer, _path in rows:
|
|
110
|
+
if tool_use_id not in found:
|
|
111
|
+
continue
|
|
112
|
+
verdict = verdict_for(found[tool_use_id][0], found[tool_use_id][1], original, pointer)
|
|
113
|
+
if verdict:
|
|
114
|
+
conn.execute("UPDATE " + TABLE + " SET verdict=?, checked_at=? WHERE session_id=? AND tool_use_id=?",
|
|
115
|
+
(verdict, now, session_id, tool_use_id))
|
|
116
|
+
judged += 1
|
|
117
|
+
conn.commit()
|
|
118
|
+
except Exception:
|
|
119
|
+
pass
|
|
120
|
+
finally:
|
|
121
|
+
if conn is not None:
|
|
122
|
+
conn.close()
|
|
123
|
+
return judged
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def health(conn, min_streak=MIN_STREAK):
|
|
127
|
+
"""{'status': ok|warning|unknown, ...} from the newest verdicts."""
|
|
128
|
+
try:
|
|
129
|
+
if not conn.execute("SELECT 1 FROM sqlite_master WHERE type='table' AND name=?", (TABLE,)).fetchone():
|
|
130
|
+
return {"status": "unknown", "verified": 0, "full": 0, "full_streak": 0}
|
|
131
|
+
rows = conn.execute("SELECT verdict, checked_at FROM " + TABLE + " WHERE verdict IS NOT NULL "
|
|
132
|
+
"ORDER BY checked_at DESC, rowid DESC LIMIT 200").fetchall()
|
|
133
|
+
except sqlite3.Error:
|
|
134
|
+
return {"status": "unknown", "verified": 0, "full": 0, "full_streak": 0}
|
|
135
|
+
streak = 0
|
|
136
|
+
for verdict, _at in rows:
|
|
137
|
+
if verdict != "full":
|
|
138
|
+
break
|
|
139
|
+
streak += 1
|
|
140
|
+
full = sum(1 for v, _ in rows if v == "full")
|
|
141
|
+
status = "unknown" if not rows else ("warning" if streak >= min_streak else "ok")
|
|
142
|
+
out = {"status": status, "verified": len(rows), "full": full, "full_streak": streak,
|
|
143
|
+
"last_checked": rows[0][1] if rows else None}
|
|
144
|
+
if status == "warning":
|
|
145
|
+
out["message"] = ("The last %d archived tool results stayed in full in the transcript: the host is not "
|
|
146
|
+
"applying archive replacements, and those savings are not counted." % streak)
|
|
147
|
+
return out
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def view_filter(alias):
|
|
151
|
+
"""SQL clause leaving out archive rows whose transcript kept the full result."""
|
|
152
|
+
return ("NOT EXISTS (SELECT 1 FROM main." + TABLE + " w WHERE w.event_id=" + alias
|
|
153
|
+
+ ".id AND w.verdict='full')")
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def replacement_check(trends_db):
|
|
157
|
+
"""Health of archive replacements for the dashboard and audit. Never raises."""
|
|
158
|
+
try:
|
|
159
|
+
conn = sqlite3.connect(Path(trends_db).resolve().as_uri() + "?mode=ro", uri=True, timeout=1.0)
|
|
160
|
+
try:
|
|
161
|
+
return health(conn)
|
|
162
|
+
finally:
|
|
163
|
+
conn.close()
|
|
164
|
+
except Exception:
|
|
165
|
+
return {"status": "unknown", "verified": 0, "full": 0, "full_streak": 0}
|
|
@@ -2153,6 +2153,10 @@ def compress(command_str, raw_output, returncode=0, stderr=""):
|
|
|
2153
2153
|
patterns on stderr even with exit 0, return raw output verbatim. Never
|
|
2154
2154
|
compress failure output — the user needs the full signal to debug.
|
|
2155
2155
|
"""
|
|
2156
|
+
from post_run_classify import unsafe_compound_output, echo_boundary_preserved
|
|
2157
|
+
if unsafe_compound_output(command_str):
|
|
2158
|
+
return raw_output
|
|
2159
|
+
|
|
2156
2160
|
if _looks_like_failure(returncode, stderr):
|
|
2157
2161
|
return raw_output # fail-open tee: full output, unchanged
|
|
2158
2162
|
|
|
@@ -2162,15 +2166,8 @@ def compress(command_str, raw_output, returncode=0, stderr=""):
|
|
|
2162
2166
|
# Strip ANSI codes (always safe)
|
|
2163
2167
|
cleaned = _strip_ansi(raw_output)
|
|
2164
2168
|
|
|
2165
|
-
#
|
|
2166
|
-
#
|
|
2167
|
-
# (UUID/URL/hash/id) that the user is likely grepping FOR must survive the
|
|
2168
|
-
# summarizer, or the model re-runs a narrower query and spends back the
|
|
2169
|
-
# tokens we just saved. Both feed the shared re-injection path below (capped
|
|
2170
|
-
# at _MAX_REINJECTED_LINES, so a needle-dense log still compresses).
|
|
2171
|
-
# The git log / find summarizers keep every hash and path themselves, so
|
|
2172
|
-
# re-injecting "rare token" lines would only paste raw "commit <hash>" lines
|
|
2173
|
-
# back; they keep only the credential/error scan.
|
|
2169
|
+
# Preserve credentials, errors, and distinctive tokens before summarizing.
|
|
2170
|
+
# Git log and find keep their own hashes and paths.
|
|
2174
2171
|
_summarizer_pattern = False
|
|
2175
2172
|
try:
|
|
2176
2173
|
_summarizer_pattern = _detect_pattern(command_str) in ("git_log", "find")
|
|
@@ -2179,7 +2176,9 @@ def compress(command_str, raw_output, returncode=0, stderr=""):
|
|
|
2179
2176
|
preserved_lines = _find_preserved_lines(cleaned)
|
|
2180
2177
|
if not _summarizer_pattern:
|
|
2181
2178
|
preserved_lines = preserved_lines | _find_distinctive_lines(cleaned)
|
|
2182
|
-
|
|
2179
|
+
from preserved_reinject import find_priority_lines, reinject
|
|
2180
|
+
priority_lines = find_priority_lines(cleaned, _ERROR_STDERR_PATTERNS + _FOREIGN_ERROR_PATTERNS)
|
|
2181
|
+
preserved_lines = preserved_lines | priority_lines
|
|
2183
2182
|
# Detect pattern
|
|
2184
2183
|
pattern = _detect_pattern(command_str)
|
|
2185
2184
|
if pattern is None:
|
|
@@ -2209,40 +2208,12 @@ def compress(command_str, raw_output, returncode=0, stderr=""):
|
|
|
2209
2208
|
except Exception:
|
|
2210
2209
|
return cleaned # fail open
|
|
2211
2210
|
|
|
2212
|
-
#
|
|
2213
|
-
# Uses exact-line membership (not substring) so a short preserved
|
|
2214
|
-
# line that happens to be contained inside a longer compressed line
|
|
2215
|
-
# is still emitted on its own rather than silently folded into the
|
|
2216
|
-
# larger line.
|
|
2217
|
-
#
|
|
2218
|
-
# Cap at _MAX_REINJECTED_LINES: when a credential pattern appears on
|
|
2219
|
-
# most lines (e.g. grep for API keys), re-injecting all of them
|
|
2220
|
-
# defeats compression. The first N are re-injected; the full original
|
|
2221
|
-
# is already archived via progressive disclosure for retrieval.
|
|
2211
|
+
# Cap credential reinjection; the full original remains archived.
|
|
2222
2212
|
if preserved_lines:
|
|
2223
|
-
|
|
2224
|
-
|
|
2225
|
-
|
|
2226
|
-
|
|
2227
|
-
injected = 0
|
|
2228
|
-
for line_idx in preserved_lines:
|
|
2229
|
-
if injected >= _MAX_REINJECTED_LINES:
|
|
2230
|
-
break
|
|
2231
|
-
if line_idx < len(original_lines):
|
|
2232
|
-
preserved_line = original_lines[line_idx]
|
|
2233
|
-
if _summarizer_pattern and preserved_line.strip() in compressed:
|
|
2234
|
-
continue # already carried by a summary line
|
|
2235
|
-
if preserved_line not in compressed_line_set:
|
|
2236
|
-
appended.append(preserved_line)
|
|
2237
|
-
compressed_line_set.add(preserved_line)
|
|
2238
|
-
injected += 1
|
|
2239
|
-
if appended:
|
|
2240
|
-
if injected < len(preserved_lines):
|
|
2241
|
-
appended.append(
|
|
2242
|
-
f"... {len(preserved_lines) - injected} more credential-bearing lines "
|
|
2243
|
-
f"archived in full original (retrieve via expand key) ..."
|
|
2244
|
-
)
|
|
2245
|
-
compressed = compressed + "\n" + "\n".join(appended)
|
|
2213
|
+
compressed = reinject(compressed, cleaned, preserved_lines, priority_lines, _summarizer_pattern)
|
|
2214
|
+
|
|
2215
|
+
if not echo_boundary_preserved(command_str, cleaned, compressed):
|
|
2216
|
+
return raw_output
|
|
2246
2217
|
|
|
2247
2218
|
try:
|
|
2248
2219
|
from token_estimate import estimate_tokens as _est
|