@alexgreensh/token-optimizer 5.13.68 → 5.13.70
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +2 -2
- package/.claude-plugin/plugin.json +1 -1
- package/PRIVACY.md +4 -0
- package/hooks/hooks.json +11 -1
- package/hooks/module_runner.py +4 -1
- package/hooks/posttooluse_runner.py +44 -48
- package/hooks/sessionstart_runner.py +24 -5
- package/hooks/stop_runner.py +6 -6
- package/package.json +1 -1
- package/skills/fleet-auditor/references/fleet-systems.md +38 -0
- package/skills/fleet-auditor/scripts/fleet.py +63 -92
- package/skills/fleet-auditor/scripts/fleet_base.py +106 -0
- package/skills/fleet-auditor/scripts/fleet_cursor_adapter.py +376 -0
- package/skills/token-coach/SKILL.md +21 -23
- package/skills/token-dashboard/SKILL.md +5 -4
- package/skills/token-optimizer/SKILL.md +1 -1
- package/skills/token-optimizer/assets/dashboard.html +492 -551
- package/skills/token-optimizer/assets/savings_story.js +661 -0
- package/skills/token-optimizer/pricing/prices.json +1 -0
- package/skills/token-optimizer/references/cli-reference.md +1 -1
- package/skills/token-optimizer/references/cursor-workflow.md +1 -1
- package/skills/token-optimizer/references/implementation-playbook.md +3 -0
- package/skills/token-optimizer/references/phase0-setup.md +1 -1
- package/skills/token-optimizer/references/presentation-workflow.md +1 -1
- package/skills/token-optimizer/scripts/_measure/__init__.py +3 -1
- package/skills/token-optimizer/scripts/_measure/archive_health.py +14 -0
- package/skills/token-optimizer/scripts/_measure/archive_void_codex.py +163 -0
- package/skills/token-optimizer/scripts/_measure/archive_void_evidence.py +165 -0
- package/skills/token-optimizer/scripts/_measure/audit.py +27 -135
- package/skills/token-optimizer/scripts/_measure/baseline_provenance.py +339 -0
- package/skills/token-optimizer/scripts/_measure/cache_policy.py +261 -581
- package/skills/token-optimizer/scripts/_measure/checkpoint_direction.py +97 -0
- package/skills/token-optimizer/scripts/_measure/checkpoint_retention.py +20 -0
- package/skills/token-optimizer/scripts/_measure/cli.py +98 -8
- package/skills/token-optimizer/scripts/_measure/codex_quality.py +246 -0
- package/skills/token-optimizer/scripts/_measure/compaction_survival.py +158 -0
- package/skills/token-optimizer/scripts/_measure/compression_fixture_void.py +147 -0
- package/skills/token-optimizer/scripts/_measure/compression_scan_checkpoint.py +72 -0
- package/skills/token-optimizer/scripts/_measure/context_reset_marker.py +64 -0
- package/skills/token-optimizer/scripts/_measure/continuity.py +64 -118
- package/skills/token-optimizer/scripts/_measure/cost_per_message_trend.py +40 -0
- package/skills/token-optimizer/scripts/_measure/counted_cap.py +28 -0
- package/skills/token-optimizer/scripts/_measure/counted_orphans.py +190 -0
- package/skills/token-optimizer/scripts/_measure/counted_position.py +20 -0
- package/skills/token-optimizer/scripts/_measure/counted_pricing_v5.py +267 -0
- package/skills/token-optimizer/scripts/_measure/counted_subagents.py +371 -0
- package/skills/token-optimizer/scripts/_measure/coverage_report.py +285 -0
- package/skills/token-optimizer/scripts/_measure/daemon.py +61 -94
- package/skills/token-optimizer/scripts/_measure/dashboard.py +149 -187
- package/skills/token-optimizer/scripts/_measure/dashboard_heal_claim.py +36 -0
- package/skills/token-optimizer/scripts/_measure/dashboard_history.py +79 -0
- package/skills/token-optimizer/scripts/_measure/evidence_parallel.py +95 -0
- package/skills/token-optimizer/scripts/_measure/feature_health.py +256 -0
- package/skills/token-optimizer/scripts/_measure/file_refetch.py +250 -0
- package/skills/token-optimizer/scripts/_measure/first_call_context.py +216 -0
- package/skills/token-optimizer/scripts/_measure/first_read_outcomes.py +261 -0
- package/skills/token-optimizer/scripts/_measure/first_read_revive.py +137 -0
- package/skills/token-optimizer/scripts/_measure/fixture_context.py +65 -0
- package/skills/token-optimizer/scripts/_measure/headline.py +100 -0
- package/skills/token-optimizer/scripts/_measure/holdout_fallback.py +96 -0
- package/skills/token-optimizer/scripts/_measure/holdout_report.py +125 -0
- package/skills/token-optimizer/scripts/_measure/keepwarm_economics.py +201 -0
- package/skills/token-optimizer/scripts/_measure/keepwarm_fork.py +140 -0
- package/skills/token-optimizer/scripts/_measure/keepwarm_guard.py +35 -0
- package/skills/token-optimizer/scripts/_measure/keepwarm_guard_server.py +85 -0
- package/skills/token-optimizer/scripts/_measure/keepwarm_linux.py +121 -0
- package/skills/token-optimizer/scripts/_measure/keepwarm_prefix.py +143 -0
- package/skills/token-optimizer/scripts/_measure/keepwarm_response_filter.py +84 -0
- package/skills/token-optimizer/scripts/_measure/keepwarm_safety.py +256 -0
- package/skills/token-optimizer/scripts/_measure/lean_resume_receivers.py +260 -0
- package/skills/token-optimizer/scripts/_measure/lean_resume_threshold.py +76 -0
- package/skills/token-optimizer/scripts/_measure/lease_candidate_cleanup.py +82 -0
- package/skills/token-optimizer/scripts/_measure/lifecycle.py +59 -168
- package/skills/token-optimizer/scripts/_measure/mcp_archive_tripwire.py +120 -0
- package/skills/token-optimizer/scripts/_measure/mod_action_booking.py +178 -0
- package/skills/token-optimizer/scripts/_measure/mod_compaction_booking.py +276 -0
- package/skills/token-optimizer/scripts/_measure/mod_fresh_booking.py +105 -0
- package/skills/token-optimizer/scripts/_measure/output_reread.py +629 -0
- package/skills/token-optimizer/scripts/_measure/own_price_card.py +268 -0
- package/skills/token-optimizer/scripts/_measure/periphery_exposure.py +85 -0
- package/skills/token-optimizer/scripts/_measure/pricing.py +152 -87
- package/skills/token-optimizer/scripts/_measure/quality_archive.py +159 -215
- package/skills/token-optimizer/scripts/_measure/quality_checkpoint.py +173 -0
- package/skills/token-optimizer/scripts/_measure/quality_continuity.py +43 -0
- package/skills/token-optimizer/scripts/_measure/rework_metrics.py +194 -0
- package/skills/token-optimizer/scripts/_measure/routing_period.py +48 -0
- package/skills/token-optimizer/scripts/_measure/savings.py +451 -933
- package/skills/token-optimizer/scripts/_measure/savings_story.py +187 -0
- package/skills/token-optimizer/scripts/_measure/session_best.py +24 -0
- package/skills/token-optimizer/scripts/_measure/session_effect.py +557 -0
- package/skills/token-optimizer/scripts/_measure/session_flush_lock.py +75 -0
- package/skills/token-optimizer/scripts/_measure/session_store_spool.py +220 -0
- package/skills/token-optimizer/scripts/_measure/sessions.py +154 -216
- package/skills/token-optimizer/scripts/_measure/setup_attachment_counter.py +196 -0
- package/skills/token-optimizer/scripts/_measure/setup_budget_monitor.py +180 -0
- package/skills/token-optimizer/scripts/_measure/setup_connector_ledger.py +126 -0
- package/skills/token-optimizer/scripts/_measure/setup_step.py +220 -0
- package/skills/token-optimizer/scripts/_measure/status_bar_lock.py +117 -0
- package/skills/token-optimizer/scripts/_measure/structural_archives.py +79 -0
- package/skills/token-optimizer/scripts/_measure/structural_dedupe.py +91 -0
- package/skills/token-optimizer/scripts/_measure/structural_ledger.py +418 -0
- package/skills/token-optimizer/scripts/_measure/structural_listing.py +163 -0
- package/skills/token-optimizer/scripts/_measure/structural_report.py +339 -0
- package/skills/token-optimizer/scripts/_measure/structural_seed.py +164 -0
- package/skills/token-optimizer/scripts/_measure/structural_value.py +248 -0
- package/skills/token-optimizer/scripts/_measure/structure_funnel.py +97 -0
- package/skills/token-optimizer/scripts/_measure/timestamp_cache.py +11 -0
- package/skills/token-optimizer/scripts/_measure/token_type_split.py +29 -0
- package/skills/token-optimizer/scripts/_measure/transcript_backfill.py +419 -0
- package/skills/token-optimizer/scripts/_measure/transcript_product.py +228 -0
- package/skills/token-optimizer/scripts/_measure/transcript_stream.py +279 -0
- package/skills/token-optimizer/scripts/_measure/trends.py +44 -185
- package/skills/token-optimizer/scripts/_measure/ttl_period.py +6 -0
- package/skills/token-optimizer/scripts/_measure/upgrade_drain_control.py +287 -0
- package/skills/token-optimizer/scripts/_measure/weekly_activity.py +69 -0
- package/skills/token-optimizer/scripts/activity_tracker.py +4 -33
- package/skills/token-optimizer/scripts/antigravity_install.py +6 -0
- package/skills/token-optimizer/scripts/archive_result.py +15 -19
- package/skills/token-optimizer/scripts/archive_verify.py +165 -0
- package/skills/token-optimizer/scripts/bash_compress.py +22 -83
- package/skills/token-optimizer/scripts/bash_compress_hook.py +137 -1
- package/skills/token-optimizer/scripts/bash_search_results.py +43 -0
- package/skills/token-optimizer/scripts/checkpoint_state.py +2 -2
- package/skills/token-optimizer/scripts/cloud_kit.py +3 -6
- package/skills/token-optimizer/scripts/codemap.py +274 -0
- package/skills/token-optimizer/scripts/codemap_hint.py +153 -0
- package/skills/token-optimizer/scripts/codemap_index.py +656 -0
- package/skills/token-optimizer/scripts/codemap_ledger.py +309 -0
- package/skills/token-optimizer/scripts/codemap_reread.py +161 -0
- package/skills/token-optimizer/scripts/codex_doctor.py +9 -1
- package/skills/token-optimizer/scripts/codex_log_index.py +34 -15
- package/skills/token-optimizer/scripts/codex_session.py +16 -216
- package/skills/token-optimizer/scripts/compression_backfill.py +4 -35
- package/skills/token-optimizer/scripts/context_intel.py +5 -3
- package/skills/token-optimizer/scripts/copilot_install.py +6 -0
- package/skills/token-optimizer/scripts/coverage_funnel.py +261 -0
- package/skills/token-optimizer/scripts/credential_patterns.py +4 -19
- package/skills/token-optimizer/scripts/credential_url_patterns.py +42 -0
- package/skills/token-optimizer/scripts/cursor_audit.py +723 -0
- package/skills/token-optimizer/scripts/cursor_bridge_checkpoint.py +213 -0
- package/skills/token-optimizer/scripts/cursor_bridge_payload.py +170 -0
- package/skills/token-optimizer/scripts/cursor_bridge_rewrite.py +106 -0
- package/skills/token-optimizer/scripts/cursor_bridge_rollup.py +115 -0
- package/skills/token-optimizer/scripts/cursor_coach.py +485 -0
- package/skills/token-optimizer/scripts/cursor_doctor.py +89 -9
- package/skills/token-optimizer/scripts/cursor_hook_bridge.py +393 -276
- package/skills/token-optimizer/scripts/cursor_install.py +118 -19
- package/skills/token-optimizer/scripts/cursor_quality.py +457 -0
- package/skills/token-optimizer/scripts/cursor_read_cache.py +597 -0
- package/skills/token-optimizer/scripts/cursor_session.py +26 -5
- package/skills/token-optimizer/scripts/cursor_state.py +8 -0
- package/skills/token-optimizer/scripts/cursor_statusline.py +372 -0
- package/skills/token-optimizer/scripts/cursor_thrash.py +78 -0
- package/skills/token-optimizer/scripts/cursor_transcript.py +223 -0
- package/skills/token-optimizer/scripts/dashboard_assets.py +21 -0
- package/skills/token-optimizer/scripts/deterministic_candidates.py +2 -10
- package/skills/token-optimizer/scripts/devin_source.py +19 -4
- package/skills/token-optimizer/scripts/devin_verify.py +13 -6
- package/skills/token-optimizer/scripts/grok_install.py +6 -0
- package/skills/token-optimizer/scripts/heal_report.py +7 -6
- package/skills/token-optimizer/scripts/hermes_doctor.py +12 -1
- package/skills/token-optimizer/scripts/hermes_install.py +10 -1
- package/skills/token-optimizer/scripts/hermes_session.py +14 -136
- package/skills/token-optimizer/scripts/hint_paths.py +21 -0
- package/skills/token-optimizer/scripts/holdout.py +136 -0
- package/skills/token-optimizer/scripts/hook_runtime.py +1 -0
- package/skills/token-optimizer/scripts/hook_skip_log.py +89 -0
- package/skills/token-optimizer/scripts/large_transcripts.py +31 -0
- package/skills/token-optimizer/scripts/lean_resume_carry.py +518 -0
- package/skills/token-optimizer/scripts/measure.py +36 -78
- package/skills/token-optimizer/scripts/post_run_classify.py +349 -0
- package/skills/token-optimizer/scripts/preserved_reinject.py +54 -0
- package/skills/token-optimizer/scripts/read_cache.py +99 -100
- package/skills/token-optimizer/scripts/reset_epoch.py +3 -3
- package/skills/token-optimizer/scripts/session_store.py +49 -99
- package/skills/token-optimizer/scripts/session_store_guard.py +75 -0
- package/skills/token-optimizer/scripts/settings_backup.py +379 -0
- package/skills/token-optimizer/scripts/shipped_hook_templates.py +1 -0
- package/skills/token-optimizer/scripts/statusline.js +1 -1
- package/skills/token-optimizer/scripts/structural.py +25 -0
- package/skills/token-optimizer/scripts/structure_map.py +4 -26
- package/skills/token-optimizer/scripts/thrash_guard.py +10 -5
|
@@ -0,0 +1,309 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Measurement ledger for code map lookups and re-read outlines.
|
|
3
|
+
|
|
4
|
+
Every lookup is logged with the files its answer covers and the tokens a full
|
|
5
|
+
Read of each would have cost. A Read of a covered file inside the follow-up
|
|
6
|
+
window means the lookup did NOT replace that read. When the window closes the
|
|
7
|
+
lookup is resolved: covered files that were never read count as avoided reads,
|
|
8
|
+
minus the tokens the answers themselves cost. The net is booked to
|
|
9
|
+
``savings_events`` as ``codemap_lookup``, an ESTIMATED-tier event type (the
|
|
10
|
+
avoided read is a counterfactual; the dashboard keeps it out of the measured
|
|
11
|
+
total).
|
|
12
|
+
|
|
13
|
+
Re-read outlines are different: the full re-read was actually denied and the
|
|
14
|
+
outline served instead, so ``codemap_outline`` is a measured removal, like
|
|
15
|
+
``structure_map``.
|
|
16
|
+
|
|
17
|
+
Rows carry the session id so a later matched comparison (sessions with vs
|
|
18
|
+
without lookups, same project and task mix) can be run from ``codemap_events``.
|
|
19
|
+
Everything here is best-effort and silent: a ledger failure never affects the
|
|
20
|
+
agent's tools.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
from __future__ import annotations
|
|
24
|
+
|
|
25
|
+
import json
|
|
26
|
+
import os
|
|
27
|
+
import sqlite3
|
|
28
|
+
import time
|
|
29
|
+
from datetime import datetime
|
|
30
|
+
from pathlib import Path
|
|
31
|
+
from typing import Dict, List, Optional, Sequence, Tuple
|
|
32
|
+
|
|
33
|
+
FOLLOWUP_WINDOW_S = 600.0
|
|
34
|
+
READ_TOKENS_CAP = 10_000 # credit per avoided file; long files are usually read in ranges
|
|
35
|
+
PENDING_MAX_PATHS = 400
|
|
36
|
+
_PENDING_NAME = "pending.json"
|
|
37
|
+
|
|
38
|
+
_SCHEMA = """
|
|
39
|
+
CREATE TABLE IF NOT EXISTS codemap_events (
|
|
40
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
41
|
+
timestamp TEXT NOT NULL,
|
|
42
|
+
ts_epoch REAL NOT NULL,
|
|
43
|
+
session_id TEXT,
|
|
44
|
+
kind TEXT NOT NULL,
|
|
45
|
+
command TEXT,
|
|
46
|
+
root_hash TEXT,
|
|
47
|
+
answer_tokens INTEGER DEFAULT 0,
|
|
48
|
+
covered TEXT,
|
|
49
|
+
status TEXT,
|
|
50
|
+
reads_after INTEGER DEFAULT 0,
|
|
51
|
+
avoided_tokens INTEGER DEFAULT 0,
|
|
52
|
+
resolved_ts REAL
|
|
53
|
+
);
|
|
54
|
+
CREATE TABLE IF NOT EXISTS codemap_reads (
|
|
55
|
+
event_id INTEGER, path TEXT, ts_epoch REAL
|
|
56
|
+
);
|
|
57
|
+
CREATE INDEX IF NOT EXISTS codemap_events_status ON codemap_events(status, ts_epoch);
|
|
58
|
+
"""
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _snapshot_dir() -> Path:
|
|
62
|
+
from plugin_env import resolve_snapshot_dir
|
|
63
|
+
return resolve_snapshot_dir()
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _trends_db() -> Path:
|
|
67
|
+
return _snapshot_dir() / "trends.db"
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _pending_path() -> Path:
|
|
71
|
+
return _snapshot_dir() / "codemap" / _PENDING_NAME
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def session_id_from_env() -> str:
|
|
75
|
+
for var in ("CLAUDE_CODE_SESSION_ID", "CLAUDE_SESSION_ID", "CODEX_SESSION_ID"):
|
|
76
|
+
val = os.environ.get(var, "").strip()
|
|
77
|
+
if val:
|
|
78
|
+
return val[:80]
|
|
79
|
+
return "unknown"
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _connect() -> sqlite3.Connection:
|
|
83
|
+
db = _trends_db()
|
|
84
|
+
db.parent.mkdir(parents=True, exist_ok=True)
|
|
85
|
+
conn = sqlite3.connect(str(db), timeout=3.0)
|
|
86
|
+
conn.execute("PRAGMA busy_timeout=3000")
|
|
87
|
+
conn.executescript(_SCHEMA)
|
|
88
|
+
return conn
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _read_pending() -> Dict:
|
|
92
|
+
try:
|
|
93
|
+
raw = _pending_path().read_text(encoding="utf-8")
|
|
94
|
+
data = json.loads(raw)
|
|
95
|
+
return data if isinstance(data, dict) else {}
|
|
96
|
+
except (OSError, ValueError):
|
|
97
|
+
return {}
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _write_pending(data: Dict) -> None:
|
|
101
|
+
p = _pending_path()
|
|
102
|
+
try:
|
|
103
|
+
p.parent.mkdir(parents=True, exist_ok=True)
|
|
104
|
+
tmp = p.with_suffix(".tmp")
|
|
105
|
+
tmp.write_text(json.dumps(data, separators=(",", ":")), encoding="utf-8")
|
|
106
|
+
os.replace(tmp, p)
|
|
107
|
+
except OSError:
|
|
108
|
+
pass
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def log_lookup(
|
|
112
|
+
command: str,
|
|
113
|
+
answer_tokens: int,
|
|
114
|
+
covered: Sequence[Tuple[str, int]],
|
|
115
|
+
*,
|
|
116
|
+
root_hash: str = "",
|
|
117
|
+
session_id: Optional[str] = None,
|
|
118
|
+
now: Optional[float] = None,
|
|
119
|
+
) -> Optional[int]:
|
|
120
|
+
"""Record one lookup. ``covered`` is [(abs_path, full_read_tokens)]."""
|
|
121
|
+
now = time.time() if now is None else now
|
|
122
|
+
sid = session_id or session_id_from_env()
|
|
123
|
+
cov = [(str(p), int(min(max(0, t), READ_TOKENS_CAP))) for p, t in covered][:5]
|
|
124
|
+
try:
|
|
125
|
+
conn = _connect()
|
|
126
|
+
try:
|
|
127
|
+
cur = conn.execute(
|
|
128
|
+
"INSERT INTO codemap_events (timestamp, ts_epoch, session_id, kind, command, root_hash, "
|
|
129
|
+
"answer_tokens, covered, status) VALUES (?,?,?,?,?,?,?,?,?)",
|
|
130
|
+
(datetime.fromtimestamp(now).isoformat(), now, sid, "lookup", command[:40], root_hash,
|
|
131
|
+
int(answer_tokens), json.dumps(cov), "pending"),
|
|
132
|
+
)
|
|
133
|
+
conn.commit()
|
|
134
|
+
event_id = cur.lastrowid
|
|
135
|
+
finally:
|
|
136
|
+
conn.close()
|
|
137
|
+
except Exception:
|
|
138
|
+
return None
|
|
139
|
+
if event_id and cov:
|
|
140
|
+
data = _read_pending()
|
|
141
|
+
paths = data.get("paths") if isinstance(data.get("paths"), dict) else {}
|
|
142
|
+
for path, _tok in cov:
|
|
143
|
+
ids = paths.setdefault(path, [])
|
|
144
|
+
if event_id not in ids:
|
|
145
|
+
ids.append(event_id)
|
|
146
|
+
if len(paths) > PENDING_MAX_PATHS:
|
|
147
|
+
for k in list(paths)[: len(paths) - PENDING_MAX_PATHS]:
|
|
148
|
+
paths.pop(k, None)
|
|
149
|
+
data["paths"] = paths
|
|
150
|
+
data["until"] = max(float(data.get("until") or 0), now + FOLLOWUP_WINDOW_S)
|
|
151
|
+
_write_pending(data)
|
|
152
|
+
return event_id
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def note_read(file_path: str, *, now: Optional[float] = None) -> bool:
|
|
156
|
+
"""Called on every Read: records a Read of a file a pending lookup covered.
|
|
157
|
+
|
|
158
|
+
Fast path is one failed stat/read of a tiny sidecar, so the Read hook pays
|
|
159
|
+
almost nothing when no lookup is pending.
|
|
160
|
+
"""
|
|
161
|
+
now = time.time() if now is None else now
|
|
162
|
+
data = _read_pending()
|
|
163
|
+
if not data:
|
|
164
|
+
return False
|
|
165
|
+
paths = data.get("paths") or {}
|
|
166
|
+
ids = paths.get(str(file_path))
|
|
167
|
+
if float(data.get("until") or 0) < now:
|
|
168
|
+
try:
|
|
169
|
+
_pending_path().unlink()
|
|
170
|
+
except OSError:
|
|
171
|
+
pass
|
|
172
|
+
return False
|
|
173
|
+
if not ids:
|
|
174
|
+
return False
|
|
175
|
+
try:
|
|
176
|
+
conn = _connect()
|
|
177
|
+
try:
|
|
178
|
+
for eid in ids:
|
|
179
|
+
conn.execute("INSERT INTO codemap_reads VALUES (?,?,?)", (int(eid), str(file_path), now))
|
|
180
|
+
conn.execute("UPDATE codemap_events SET reads_after=reads_after+1 WHERE id=?", (int(eid),))
|
|
181
|
+
conn.commit()
|
|
182
|
+
finally:
|
|
183
|
+
conn.close()
|
|
184
|
+
except Exception:
|
|
185
|
+
return False
|
|
186
|
+
return True
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def resolve_pending(*, now: Optional[float] = None, window_s: float = FOLLOWUP_WINDOW_S) -> Dict[str, int]:
|
|
190
|
+
"""Resolve lookups whose follow-up window closed and book the net estimate."""
|
|
191
|
+
now = time.time() if now is None else now
|
|
192
|
+
out = {"resolved": 0, "avoided_tokens": 0, "answer_tokens": 0, "booked": 0}
|
|
193
|
+
try:
|
|
194
|
+
conn = _connect()
|
|
195
|
+
except Exception:
|
|
196
|
+
return out
|
|
197
|
+
try:
|
|
198
|
+
rows = conn.execute(
|
|
199
|
+
"SELECT id, session_id, answer_tokens, covered FROM codemap_events "
|
|
200
|
+
"WHERE kind='lookup' AND status='pending' AND ts_epoch < ? LIMIT 500",
|
|
201
|
+
(now - window_s,)).fetchall()
|
|
202
|
+
by_session: Dict[str, List[int]] = {}
|
|
203
|
+
for eid, sid, ans, cov_raw in rows:
|
|
204
|
+
try:
|
|
205
|
+
cov = json.loads(cov_raw or "[]")
|
|
206
|
+
except ValueError:
|
|
207
|
+
cov = []
|
|
208
|
+
read = {r[0] for r in conn.execute("SELECT path FROM codemap_reads WHERE event_id=?", (eid,))}
|
|
209
|
+
avoided = sum(int(t) for p, t in cov if p not in read)
|
|
210
|
+
conn.execute(
|
|
211
|
+
"UPDATE codemap_events SET status='resolved', avoided_tokens=?, resolved_ts=? WHERE id=?",
|
|
212
|
+
(avoided, now, eid))
|
|
213
|
+
agg = by_session.setdefault(sid or "unknown", [0, 0])
|
|
214
|
+
agg[0] += avoided
|
|
215
|
+
agg[1] += int(ans or 0)
|
|
216
|
+
out["resolved"] += 1
|
|
217
|
+
out["avoided_tokens"] += avoided
|
|
218
|
+
out["answer_tokens"] += int(ans or 0)
|
|
219
|
+
conn.commit()
|
|
220
|
+
except Exception:
|
|
221
|
+
return out
|
|
222
|
+
finally:
|
|
223
|
+
conn.close()
|
|
224
|
+
# Net per session: lookups that did not help still cost their answers.
|
|
225
|
+
for sid, (avoided, answers) in by_session.items():
|
|
226
|
+
net = avoided - answers
|
|
227
|
+
if net > 0 and _book_savings("codemap_lookup", net, sid, f"lookups resolved; avoided={avoided} answers={answers}"):
|
|
228
|
+
out["booked"] += net
|
|
229
|
+
if rows:
|
|
230
|
+
try:
|
|
231
|
+
if _read_pending() and float(_read_pending().get("until") or 0) < now:
|
|
232
|
+
_pending_path().unlink()
|
|
233
|
+
except OSError:
|
|
234
|
+
pass
|
|
235
|
+
return out
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def log_outline_served(file_path: str, file_tokens: int, outline_tokens: int, session_id: str) -> int:
|
|
239
|
+
"""A full re-read was replaced by an outline: a measured removal."""
|
|
240
|
+
net = max(0, int(file_tokens) - int(outline_tokens))
|
|
241
|
+
now = time.time()
|
|
242
|
+
try:
|
|
243
|
+
conn = _connect()
|
|
244
|
+
try:
|
|
245
|
+
conn.execute(
|
|
246
|
+
"INSERT INTO codemap_events (timestamp, ts_epoch, session_id, kind, command, answer_tokens, "
|
|
247
|
+
"covered, status, avoided_tokens) VALUES (?,?,?,?,?,?,?,?,?)",
|
|
248
|
+
(datetime.fromtimestamp(now).isoformat(), now, session_id, "reread_outline", "outline",
|
|
249
|
+
int(outline_tokens), json.dumps([[str(file_path), int(file_tokens)]]), "served", net))
|
|
250
|
+
conn.commit()
|
|
251
|
+
finally:
|
|
252
|
+
conn.close()
|
|
253
|
+
except Exception:
|
|
254
|
+
pass
|
|
255
|
+
if net > 0:
|
|
256
|
+
_book_savings("codemap_outline", net, session_id, f"{Path(file_path).name}:codemap_outline")
|
|
257
|
+
return net
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def _book_savings(event_type: str, tokens: int, session_id: str, detail: str) -> bool:
|
|
261
|
+
"""Write through read_cache's savings writer (pricing, uuid join, origin)."""
|
|
262
|
+
try:
|
|
263
|
+
import read_cache
|
|
264
|
+
# read_cache binds its data paths at import; point them at the current
|
|
265
|
+
# resolver so a long-lived importer never writes a stale trends.db.
|
|
266
|
+
read_cache.SNAPSHOT_DIR = _snapshot_dir()
|
|
267
|
+
read_cache.TRENDS_DB = _trends_db()
|
|
268
|
+
before = _count_rows(event_type)
|
|
269
|
+
read_cache._log_savings_event(event_type, int(tokens), session_id, detail)
|
|
270
|
+
return _count_rows(event_type) > before
|
|
271
|
+
except Exception:
|
|
272
|
+
return False
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
def _count_rows(event_type: str) -> int:
|
|
276
|
+
try:
|
|
277
|
+
conn = sqlite3.connect(str(_trends_db()), timeout=3.0)
|
|
278
|
+
try:
|
|
279
|
+
return int(conn.execute("SELECT COUNT(*) FROM savings_events WHERE event_type=?",
|
|
280
|
+
(event_type,)).fetchone()[0])
|
|
281
|
+
finally:
|
|
282
|
+
conn.close()
|
|
283
|
+
except Exception:
|
|
284
|
+
return -1
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
def summary(days: int = 30) -> Dict[str, int]:
|
|
288
|
+
"""Totals for reports: lookups, resolved, avoided, answer cost, outlines."""
|
|
289
|
+
since = time.time() - days * 86400
|
|
290
|
+
try:
|
|
291
|
+
conn = _connect()
|
|
292
|
+
try:
|
|
293
|
+
row = conn.execute(
|
|
294
|
+
"SELECT COUNT(*), SUM(status='resolved'), COALESCE(SUM(avoided_tokens),0), "
|
|
295
|
+
"COALESCE(SUM(answer_tokens),0), COALESCE(SUM(reads_after>0),0) "
|
|
296
|
+
"FROM codemap_events WHERE kind='lookup' AND ts_epoch>=?", (since,)).fetchone()
|
|
297
|
+
orow = conn.execute(
|
|
298
|
+
"SELECT COUNT(*), COALESCE(SUM(avoided_tokens),0) FROM codemap_events "
|
|
299
|
+
"WHERE kind='reread_outline' AND ts_epoch>=?", (since,)).fetchone()
|
|
300
|
+
finally:
|
|
301
|
+
conn.close()
|
|
302
|
+
except Exception:
|
|
303
|
+
return {}
|
|
304
|
+
return {
|
|
305
|
+
"lookups": int(row[0] or 0), "resolved": int(row[1] or 0),
|
|
306
|
+
"avoided_tokens": int(row[2] or 0), "answer_tokens": int(row[3] or 0),
|
|
307
|
+
"lookups_followed_by_read": int(row[4] or 0),
|
|
308
|
+
"outlines": int(orow[0] or 0), "outline_tokens_saved": int(orow[1] or 0),
|
|
309
|
+
}
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Safe re-read outline, called from read_cache's PreToolUse Read path.
|
|
3
|
+
|
|
4
|
+
The existing structure-map path already replaces an unchanged re-read with a
|
|
5
|
+
skeleton when its own summary is confident. This module covers the re-reads it
|
|
6
|
+
declines (summary over its cap, low confidence, generated-looking, digest-only), using the code
|
|
7
|
+
map's outline instead, under stricter rules:
|
|
8
|
+
|
|
9
|
+
* the earlier Read covered the WHOLE file (offset 0, no limit) and so does this one;
|
|
10
|
+
* the file is unchanged (read_cache already matched mtime and size) and there
|
|
11
|
+
has been no compaction since (read_cache clears its ledger on compaction);
|
|
12
|
+
* the user's read-cache mode is soft_block (shadow/warn stay hands-off);
|
|
13
|
+
* at most ONE outline per file version: Reading it again serves the full file;
|
|
14
|
+
* the outline must cost at most a third of the file.
|
|
15
|
+
|
|
16
|
+
Any error returns None and the Read proceeds untouched (fail open).
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
import os
|
|
22
|
+
from pathlib import Path
|
|
23
|
+
from typing import Any, Dict, Optional
|
|
24
|
+
|
|
25
|
+
DECLINED_REASONS = frozenset({
|
|
26
|
+
"structure_over_cap", "low_confidence", "fallback_digest",
|
|
27
|
+
"low_signal_structure", "hook_context_cap", "generated_like",
|
|
28
|
+
})
|
|
29
|
+
MIN_FILE_TOKENS = 1500
|
|
30
|
+
MAX_OUTLINE_RATIO = 0.33
|
|
31
|
+
# Persisted through the read-cache store's replacement columns, which read_cache
|
|
32
|
+
# resets whenever the file changes.
|
|
33
|
+
SERVED_TYPE = "codemap_outline"
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def note_read(file_path: str) -> None:
|
|
37
|
+
"""Measurement hook for every Read (cheap when no lookup is pending)."""
|
|
38
|
+
try:
|
|
39
|
+
import codemap_ledger
|
|
40
|
+
codemap_ledger.note_read(str(file_path))
|
|
41
|
+
except Exception:
|
|
42
|
+
pass
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _full_read_seen(entry: Dict[str, Any]) -> bool:
|
|
46
|
+
for rng in entry.get("ranges_seen") or []:
|
|
47
|
+
try:
|
|
48
|
+
if int(rng[0]) == 0 and int(rng[1]) == 0:
|
|
49
|
+
return True
|
|
50
|
+
except (TypeError, ValueError, IndexError):
|
|
51
|
+
continue
|
|
52
|
+
return False
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _span(line: int, end: int) -> str:
|
|
56
|
+
return f"{line}-{end}" if end and end > line else f"{line}"
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def build_outline(file_path: str, max_chars: int) -> Optional[str]:
|
|
60
|
+
"""Outline lines for one file from the code map (indexes just that file)."""
|
|
61
|
+
import codemap_index as ci
|
|
62
|
+
p = Path(file_path).resolve()
|
|
63
|
+
root = ci.find_project_root(p)
|
|
64
|
+
idx = ci.CodeIndex.open(root)
|
|
65
|
+
try:
|
|
66
|
+
if not idx.refresh_file(p):
|
|
67
|
+
return None
|
|
68
|
+
rel = idx.rel(p)
|
|
69
|
+
row = idx.file_row(rel) if rel else None
|
|
70
|
+
if row is None or not row[6]:
|
|
71
|
+
return None
|
|
72
|
+
rows = [r for r in idx.outline(rel) if r[2] != "variable"]
|
|
73
|
+
full = [f"{' ' * q.count('.')}{_span(ln, e)} {sig}" for _n, q, _k, ln, e, sig in rows]
|
|
74
|
+
if sum(len(x) + 1 for x in full) <= max_chars:
|
|
75
|
+
return "\n".join(full) or None
|
|
76
|
+
# Compact form: top-level definitions with signatures, methods by name@line.
|
|
77
|
+
methods: Dict[str, list] = {}
|
|
78
|
+
for n, q, k, ln, _e, _sig in rows:
|
|
79
|
+
if k == "method" and "." in q:
|
|
80
|
+
methods.setdefault(q.rsplit(".", 1)[0], []).append(f"{n}@{ln}")
|
|
81
|
+
compact = []
|
|
82
|
+
for n, q, k, ln, e, sig in rows:
|
|
83
|
+
if "." in q:
|
|
84
|
+
continue
|
|
85
|
+
text = f"{_span(ln, e)} {sig}"
|
|
86
|
+
if q in methods:
|
|
87
|
+
ms = methods[q]
|
|
88
|
+
text += f" [{len(ms)} methods: " + ", ".join(ms[:6]) + (", ..." if len(ms) > 6 else "") + "]"
|
|
89
|
+
compact.append(text)
|
|
90
|
+
out, size = [], 0
|
|
91
|
+
for text in compact:
|
|
92
|
+
if size + len(text) + 1 > max_chars:
|
|
93
|
+
if len(text) > 120 and size + 125 <= max_chars:
|
|
94
|
+
out.append(text[:110] + " ...]")
|
|
95
|
+
out.append(" ...")
|
|
96
|
+
break
|
|
97
|
+
out.append(text)
|
|
98
|
+
size += len(text) + 1
|
|
99
|
+
return "\n".join(out) or None
|
|
100
|
+
finally:
|
|
101
|
+
idx.close()
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def try_outline(
|
|
105
|
+
file_path: str,
|
|
106
|
+
entry: Dict[str, Any],
|
|
107
|
+
*,
|
|
108
|
+
offset: int,
|
|
109
|
+
limit: int,
|
|
110
|
+
tokens_est: int,
|
|
111
|
+
reason_code: str,
|
|
112
|
+
mode: str,
|
|
113
|
+
mtime_ns: int,
|
|
114
|
+
max_context_chars: int,
|
|
115
|
+
) -> Optional[Dict[str, Any]]:
|
|
116
|
+
"""Return {'reason', 'context', 'outline_tokens'} to deny with, or None to allow."""
|
|
117
|
+
try:
|
|
118
|
+
import codemap_index as ci
|
|
119
|
+
if mode != "soft_block" or offset or limit:
|
|
120
|
+
return None
|
|
121
|
+
if reason_code not in DECLINED_REASONS or tokens_est < MIN_FILE_TOKENS:
|
|
122
|
+
return None
|
|
123
|
+
suffix = Path(file_path).suffix.lower()
|
|
124
|
+
if suffix not in ci.SUPPORTED_SUFFIXES or not _full_read_seen(entry):
|
|
125
|
+
return None
|
|
126
|
+
marker = f"codemap:{int(mtime_ns)}"
|
|
127
|
+
if entry.get("last_replacement_fingerprint") == marker:
|
|
128
|
+
return None # outline already served for this version: give the full file
|
|
129
|
+
if not ci.reread_outline_enabled():
|
|
130
|
+
return None
|
|
131
|
+
name = os.path.basename(file_path)
|
|
132
|
+
header = (
|
|
133
|
+
f"[Token Optimizer] {name} is unchanged since your full Read earlier in this session "
|
|
134
|
+
"(no compaction since), so its outline is shown instead of a second full copy. "
|
|
135
|
+
"Read with offset/limit for exact lines, Edit it directly, or Read it again for the full file."
|
|
136
|
+
)
|
|
137
|
+
body = build_outline(file_path, max(200, max_context_chars - len(header) - 40))
|
|
138
|
+
if not body:
|
|
139
|
+
return None
|
|
140
|
+
context = f"{header}\n{body}"
|
|
141
|
+
from token_estimate import estimate_tokens
|
|
142
|
+
outline_tokens = int(estimate_tokens(context))
|
|
143
|
+
if outline_tokens > tokens_est * MAX_OUTLINE_RATIO or len(context) > max_context_chars:
|
|
144
|
+
return None
|
|
145
|
+
entry["last_replacement_fingerprint"] = marker
|
|
146
|
+
entry["last_replacement_type"] = SERVED_TYPE
|
|
147
|
+
return {
|
|
148
|
+
"reason": f"{name} is unchanged and already in context; using its code map outline.",
|
|
149
|
+
"context": context,
|
|
150
|
+
"outline_tokens": outline_tokens,
|
|
151
|
+
}
|
|
152
|
+
except Exception:
|
|
153
|
+
return None
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def record_served(file_path: str, tokens_est: int, outline_tokens: int, session_id: str) -> None:
|
|
157
|
+
try:
|
|
158
|
+
import codemap_ledger
|
|
159
|
+
codemap_ledger.log_outline_served(file_path, tokens_est, outline_tokens, session_id)
|
|
160
|
+
except Exception:
|
|
161
|
+
pass
|
|
@@ -41,7 +41,10 @@ REQUIRED_FILES = (
|
|
|
41
41
|
"skills/token-optimizer/scripts/bash_compress.py",
|
|
42
42
|
"skills/token-optimizer/scripts/context_intel.py",
|
|
43
43
|
"skills/token-optimizer/scripts/archive_result.py",
|
|
44
|
+
"skills/token-optimizer/scripts/archive_verify.py",
|
|
44
45
|
"skills/token-optimizer/scripts/measure.py",
|
|
46
|
+
"skills/token-optimizer/scripts/session_store.py",
|
|
47
|
+
"skills/token-optimizer/scripts/session_store_guard.py",
|
|
45
48
|
"skills/token-optimizer/scripts/outline.py",
|
|
46
49
|
"skills/token-optimizer/scripts/runtime_env.py",
|
|
47
50
|
)
|
|
@@ -54,6 +57,8 @@ SKILL_INSTALL_FILES = (
|
|
|
54
57
|
"scripts/codex_statusline.py",
|
|
55
58
|
"scripts/codex_install.py",
|
|
56
59
|
"scripts/measure.py",
|
|
60
|
+
"scripts/session_store.py",
|
|
61
|
+
"scripts/session_store_guard.py",
|
|
57
62
|
"scripts/runtime_env.py",
|
|
58
63
|
)
|
|
59
64
|
|
|
@@ -64,8 +69,11 @@ _MEASURE_PACKAGE_FILES = (
|
|
|
64
69
|
"_measure/pricing.py", "_measure/audit.py", "_measure/dashboard.py",
|
|
65
70
|
"_measure/lifecycle.py", "_measure/sessions.py", "_measure/trends.py",
|
|
66
71
|
"_measure/cache_policy.py", "_measure/daemon.py", "_measure/quality_archive.py",
|
|
67
|
-
"_measure/continuity.py", "_measure/savings.py", "_measure/cli.py",
|
|
72
|
+
"_measure/continuity.py", "_measure/savings.py", "_measure/cli.py", "_measure/dashboard_history.py", "_measure/weekly_activity.py", "_measure/headline.py", "_measure/counted_position.py", "_measure/counted_pricing_v5.py", "_measure/transcript_backfill.py", "_measure/counted_subagents.py", "_measure/lean_resume_threshold.py", "_measure/output_reread.py", "_measure/session_effect.py", "_measure/structural_ledger.py", "_measure/structural_archives.py", "_measure/structural_listing.py", "_measure/structural_report.py", "_measure/structural_seed.py", "_measure/structural_value.py", "_measure/rework_metrics.py", "_measure/session_best.py", "_measure/savings_story.py", "_measure/counted_orphans.py", "_measure/counted_cap.py", "_measure/archive_void_evidence.py", "_measure/cost_per_message_trend.py", "_measure/lean_resume_receivers.py", "_measure/routing_period.py", "_measure/fixture_context.py", "_measure/transcript_product.py", "_measure/periphery_exposure.py", "_measure/structure_funnel.py", "_measure/setup_attachment_counter.py", "_measure/first_read_outcomes.py", "_measure/setup_budget_monitor.py", "_measure/setup_connector_ledger.py", "_measure/first_call_context.py", "_measure/timestamp_cache.py", "_measure/token_type_split.py", "_measure/evidence_parallel.py", "_measure/ttl_period.py", "_measure/first_read_revive.py", "_measure/mcp_archive_tripwire.py", "_measure/compaction_survival.py", "_measure/archive_void_codex.py", "_measure/compression_fixture_void.py", "_measure/feature_health.py", "_measure/archive_health.py", "_measure/coverage_report.py", "_measure/file_refetch.py", "_measure/holdout_report.py", "_measure/structural_dedupe.py", "_measure/setup_step.py", "_measure/baseline_provenance.py", "_measure/own_price_card.py",
|
|
68
73
|
)
|
|
74
|
+
_MEASURE_PACKAGE_FILES += ('_measure/transcript_stream.py', '_measure/checkpoint_direction.py', '_measure/checkpoint_retention.py')
|
|
75
|
+
_MEASURE_PACKAGE_FILES += ('_measure/keepwarm_safety.py', '_measure/keepwarm_economics.py', '_measure/keepwarm_linux.py', '_measure/keepwarm_prefix.py', '_measure/keepwarm_response_filter.py', '_measure/keepwarm_guard.py', '_measure/keepwarm_guard_server.py', '_measure/keepwarm_fork.py', '_measure/mod_action_booking.py', '_measure/mod_compaction_booking.py', '_measure/mod_fresh_booking.py',)
|
|
76
|
+
_MEASURE_PACKAGE_FILES += ('_measure/quality_continuity.py', '_measure/quality_checkpoint.py', '_measure/codex_quality.py', '_measure/lease_candidate_cleanup.py', '_measure/session_store_spool.py', '_measure/upgrade_drain_control.py', '_measure/compression_scan_checkpoint.py', '_measure/status_bar_lock.py', '_measure/session_flush_lock.py', '_measure/context_reset_marker.py', '_measure/holdout_fallback.py', '_measure/dashboard_heal_claim.py',)
|
|
69
77
|
|
|
70
78
|
|
|
71
79
|
def _repo_root() -> Path:
|
|
@@ -12,8 +12,9 @@ from pathlib import Path
|
|
|
12
12
|
from plugin_env import resolve_snapshot_dir
|
|
13
13
|
|
|
14
14
|
PASS_BYTES = 64 * 1024 * 1024
|
|
15
|
+
PASS_SECONDS = 1.0
|
|
15
16
|
LINE_BYTES = 16 * 1024 * 1024
|
|
16
|
-
SCHEMA_VERSION =
|
|
17
|
+
SCHEMA_VERSION = 3
|
|
17
18
|
|
|
18
19
|
_SCHEMA = '''
|
|
19
20
|
CREATE TABLE IF NOT EXISTS files(path TEXT PRIMARY KEY, identity TEXT, offset INTEGER,
|
|
@@ -34,6 +35,8 @@ def _open_db(db_path):
|
|
|
34
35
|
conn.execute('ALTER TABLE files ADD COLUMN mtime INTEGER')
|
|
35
36
|
except sqlite3.OperationalError:
|
|
36
37
|
pass # concurrent migration: column already added
|
|
38
|
+
if 'anchor' not in {row[1] for row in conn.execute('PRAGMA table_info(files)')}:
|
|
39
|
+
conn.execute('ALTER TABLE files ADD COLUMN anchor TEXT')
|
|
37
40
|
except Exception:
|
|
38
41
|
# On Windows an abandoned handle pins the file and defeats the
|
|
39
42
|
# unlink-and-rebuild below, so a failed open must not leak it.
|
|
@@ -82,16 +85,23 @@ def pending(filepath):
|
|
|
82
85
|
try:
|
|
83
86
|
conn = _connect()
|
|
84
87
|
try:
|
|
85
|
-
row = conn.execute('SELECT offset,revision,mtime FROM files WHERE path=?', (str(path),)).fetchone()
|
|
88
|
+
row = conn.execute('SELECT offset,revision,mtime,skipped FROM files WHERE path=?', (str(path),)).fetchone()
|
|
86
89
|
stat = path.stat()
|
|
87
90
|
return (row is None or row[0] != stat.st_size or
|
|
88
|
-
row[1] != SCHEMA_VERSION or row[2] != stat.st_mtime_ns)
|
|
91
|
+
row[1] != SCHEMA_VERSION or row[2] != stat.st_mtime_ns or row[3] > 0)
|
|
89
92
|
finally:
|
|
90
93
|
conn.close()
|
|
91
94
|
except (OSError, sqlite3.Error):
|
|
92
95
|
return True
|
|
93
96
|
|
|
94
97
|
|
|
98
|
+
def _archive_chars(output):
|
|
99
|
+
if isinstance(output, str):
|
|
100
|
+
return [len(output), len(output)]
|
|
101
|
+
text = sum(len(v.get('text') or '') for v in output if isinstance(v, dict)) if isinstance(output, list) else 0
|
|
102
|
+
return [text, len(json.dumps(output))]
|
|
103
|
+
|
|
104
|
+
|
|
95
105
|
def _slim(record):
|
|
96
106
|
from codex_session import _extract_text, _event_output_text
|
|
97
107
|
payload = record.get('payload')
|
|
@@ -105,9 +115,11 @@ def _slim(record):
|
|
|
105
115
|
text = _extract_text(payload)
|
|
106
116
|
payload = {'type': kind, 'role': payload.get('role'), 'message': text[:1000],
|
|
107
117
|
'content': text[:1000], '_optimizer_chars': len(text)}
|
|
108
|
-
elif kind in ('function_call_output', 'custom_tool_call_output', 'exec_command_end', 'patch_apply_end'):
|
|
118
|
+
elif kind in ('function_call_output', 'custom_tool_call_output', 'mcp_tool_call_output', 'exec_command_end', 'patch_apply_end'):
|
|
119
|
+
output = payload.get('output')
|
|
109
120
|
chars = len(str(payload.get('output') or '')) if kind.endswith('call_output') else len(_event_output_text(payload))
|
|
110
|
-
payload = {'type': kind, '_optimizer_output_chars': chars, 'duration': payload.get('duration')
|
|
121
|
+
payload = {'type': kind, '_optimizer_output_chars': chars, 'duration': payload.get('duration'),
|
|
122
|
+
'_optimizer_archive_chars': _archive_chars(output)}
|
|
111
123
|
elif kind in ('function_call', 'custom_tool_call'):
|
|
112
124
|
payload = {'type': kind, 'name': payload.get('name'),
|
|
113
125
|
'arguments': payload.get('arguments') if payload.get('name') == 'spawn_agent' else None}
|
|
@@ -142,29 +154,35 @@ def records(filepath):
|
|
|
142
154
|
stat = path.stat()
|
|
143
155
|
identity = f'{SCHEMA_VERSION}:{stat.st_dev}:{stat.st_ino}:' + hashlib.sha256(handle.readline(65536)).hexdigest()
|
|
144
156
|
# Decide whether to re-index BEFORE acquiring the write lock.
|
|
145
|
-
row = conn.execute('SELECT identity,offset,skipped,mtime FROM files WHERE path=?', (key,)).fetchone()
|
|
146
|
-
#
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
157
|
+
row = conn.execute('SELECT identity,offset,skipped,mtime,anchor,size FROM files WHERE path=?', (key,)).fetchone()
|
|
158
|
+
# Validate the old boundary before resuming an append.
|
|
159
|
+
from _measure.transcript_stream import _anchor
|
|
160
|
+
restart = (not row or row[0] != identity or row[1] > stat.st_size
|
|
161
|
+
or row[4] != _anchor(handle, row[1])
|
|
162
|
+
or (row[5] == stat.st_size and row[3] != stat.st_mtime_ns))
|
|
163
|
+
if restart:
|
|
150
164
|
offset, skipped = 0, 0
|
|
151
165
|
else:
|
|
152
166
|
offset, skipped = row[1], row[2]
|
|
153
167
|
handle.seek(offset)
|
|
154
168
|
end = min(stat.st_size, offset + PASS_BYTES)
|
|
155
169
|
parsed = []
|
|
156
|
-
|
|
170
|
+
parse_deadline = time.monotonic() + PASS_SECONDS
|
|
171
|
+
while handle.tell() < end and time.monotonic() < parse_deadline:
|
|
157
172
|
start = handle.tell()
|
|
158
173
|
line = handle.readline(LINE_BYTES + 1)
|
|
159
174
|
if not line:
|
|
160
175
|
break
|
|
161
176
|
if len(line) > LINE_BYTES:
|
|
162
|
-
while line and not line.endswith(b'\n'):
|
|
177
|
+
while line and not line.endswith(b'\n') and time.monotonic() < parse_deadline:
|
|
163
178
|
line = handle.readline(65536)
|
|
164
179
|
if not line or not line.endswith(b'\n'):
|
|
165
180
|
handle.seek(start)
|
|
166
181
|
break
|
|
167
182
|
skipped += 1
|
|
183
|
+
elif not line.endswith(b'\n'):
|
|
184
|
+
handle.seek(start)
|
|
185
|
+
break
|
|
168
186
|
else:
|
|
169
187
|
try:
|
|
170
188
|
record = json.loads(line)
|
|
@@ -183,6 +201,7 @@ def records(filepath):
|
|
|
183
201
|
else:
|
|
184
202
|
skipped += 1
|
|
185
203
|
offset = handle.tell()
|
|
204
|
+
anchor = _anchor(handle, offset)
|
|
186
205
|
# Now acquire the write lock for a tight batch commit only. A losing
|
|
187
206
|
# thread can still outlast busy_timeout under heavy contention (or hit
|
|
188
207
|
# the no-retry lock-upgrade deadlock path), so retry the transaction
|
|
@@ -191,11 +210,11 @@ def records(filepath):
|
|
|
191
210
|
while True:
|
|
192
211
|
try:
|
|
193
212
|
conn.execute('BEGIN IMMEDIATE')
|
|
194
|
-
if
|
|
213
|
+
if restart:
|
|
195
214
|
conn.execute('DELETE FROM records WHERE path=?', (key,))
|
|
196
215
|
conn.executemany('INSERT OR REPLACE INTO records(path, offset, data) VALUES (?,?,?)', parsed)
|
|
197
|
-
conn.execute('INSERT OR REPLACE INTO files(path, identity, offset, size, skipped, revision, mtime) VALUES (
|
|
198
|
-
(key, identity, offset, stat.st_size, skipped, SCHEMA_VERSION, stat.st_mtime_ns))
|
|
216
|
+
conn.execute('INSERT OR REPLACE INTO files(path, identity, offset, size, skipped, revision, mtime, anchor) VALUES (?,?,?,?,?,?,?,?)',
|
|
217
|
+
(key, identity, offset, stat.st_size, skipped, SCHEMA_VERSION, stat.st_mtime_ns, anchor))
|
|
199
218
|
conn.commit()
|
|
200
219
|
break
|
|
201
220
|
except sqlite3.OperationalError:
|