@alexgreensh/token-optimizer 5.13.71 → 5.13.72
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/hooks/module_runner.py +1 -1
- package/hooks/sessionstart_runner.py +6 -0
- package/package.json +1 -1
- package/skills/token-optimizer/scripts/_measure/__init__.py +1 -1
- package/skills/token-optimizer/scripts/_measure/config_cache.py +63 -0
- package/skills/token-optimizer/scripts/_measure/dashboard.py +32 -64
- package/skills/token-optimizer/scripts/_measure/lifecycle.py +6 -7
- package/skills/token-optimizer/scripts/_measure/savings.py +2 -2
- package/skills/token-optimizer/scripts/_measure/setup_observation_cache.py +99 -0
- package/skills/token-optimizer/scripts/_measure/setup_step.py +4 -5
- package/skills/token-optimizer/scripts/_measure/status_bar_refresh.py +218 -0
- package/skills/token-optimizer/scripts/_measure/structural_report.py +25 -6
- package/skills/token-optimizer/scripts/_measure/structural_value.py +16 -10
- package/skills/token-optimizer/scripts/cloud_kit.py +1 -2
- package/skills/token-optimizer/scripts/codemap.py +33 -5
- package/skills/token-optimizer/scripts/codemap_hint.py +152 -11
- package/skills/token-optimizer/scripts/codemap_index.py +100 -11
- package/skills/token-optimizer/scripts/codemap_ledger.py +29 -0
- package/skills/token-optimizer/scripts/codex_doctor.py +1 -1
- package/skills/token-optimizer/scripts/hermes_doctor.py +1 -1
- package/skills/token-optimizer/scripts/hermes_install.py +1 -1
- package/skills/token-optimizer/scripts/statusline.js +17 -4
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
"""Share window savings and keep session-specific figures separate."""
|
|
2
|
+
import time
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
def atomic_write(facade, path, data):
|
|
6
|
+
tmp = path.with_name('.' + path.name + '.' + facade.os.urandom(16).hex() + '.tmp')
|
|
7
|
+
try:
|
|
8
|
+
tmp.write_text(facade.json.dumps(data), encoding='utf-8')
|
|
9
|
+
for attempt in range(3):
|
|
10
|
+
try:
|
|
11
|
+
facade.os.replace(tmp, path)
|
|
12
|
+
return
|
|
13
|
+
except PermissionError:
|
|
14
|
+
if attempt == 2:
|
|
15
|
+
raise
|
|
16
|
+
time.sleep(.02 * (attempt + 1))
|
|
17
|
+
finally:
|
|
18
|
+
try:
|
|
19
|
+
tmp.unlink(missing_ok=True)
|
|
20
|
+
except OSError:
|
|
21
|
+
pass
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def retry_delay(failures):
|
|
25
|
+
return min(600, 60 * 2 ** min(max(0, int(failures) - 1), 6))
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def write_cache(facade, session_id, savings, reason):
|
|
29
|
+
# One failure is routine (a hook writing): the retry note needs two in a row.
|
|
30
|
+
directory = facade._status_bar_dir()
|
|
31
|
+
directory.mkdir(parents=True, exist_ok=True)
|
|
32
|
+
prior = facade._status_bar_read_cache(session_id)
|
|
33
|
+
failed = savings is None
|
|
34
|
+
stale = bool(failed and prior and prior.get('savings') is not None)
|
|
35
|
+
failures = min(10, int((prior or {}).get('failures', 0)) + 1) if failed else 0
|
|
36
|
+
if stale:
|
|
37
|
+
savings = prior['savings']
|
|
38
|
+
friendly = 'no savings recorded yet' if reason == 'no savings recorded yet' else 'still counting savings'
|
|
39
|
+
data = {
|
|
40
|
+
'schema': facade._STATUS_BAR_SCHEMA, 'computed_at': prior['computed_at'] if stale else facade.time.time(),
|
|
41
|
+
'savings': savings, 'reason': friendly if savings is None else None, 'stale': stale,
|
|
42
|
+
'last_attempt': facade.time.time() if failed else 0, 'failures': failures, 'refresh_failed': failed and failures >= 2 and reason != 'no savings recorded yet',
|
|
43
|
+
}
|
|
44
|
+
try:
|
|
45
|
+
atomic_write(facade, facade._status_bar_cache_path(session_id), data)
|
|
46
|
+
except PermissionError:
|
|
47
|
+
atomic_write(facade, directory / ('global-pending-' + facade.os.urandom(16).hex() + '.json'), data)
|
|
48
|
+
else:
|
|
49
|
+
try:
|
|
50
|
+
drop_older_pending(facade, directory, data['computed_at'])
|
|
51
|
+
except OSError:
|
|
52
|
+
pass
|
|
53
|
+
cutoff = facade.time.time() - facade._STATUS_BAR_CACHE_RETENTION_S
|
|
54
|
+
try:
|
|
55
|
+
for path in directory.iterdir():
|
|
56
|
+
try:
|
|
57
|
+
orphan = path.name.endswith(('.tmp', '.stale', '.release')) and path.stat().st_mtime < facade.time.time() - 86400
|
|
58
|
+
if orphan or (path.name.endswith(('.json', '.session')) and path.stat().st_mtime < cutoff):
|
|
59
|
+
path.unlink()
|
|
60
|
+
except OSError:
|
|
61
|
+
pass
|
|
62
|
+
except OSError:
|
|
63
|
+
pass
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def drop_older_pending(facade, directory, computed_at):
|
|
67
|
+
"""Once global.json holds a result, pending files no newer than it are dead
|
|
68
|
+
weight that every poll would still parse; remove them."""
|
|
69
|
+
for path in directory.glob('global-pending-*.json'):
|
|
70
|
+
try:
|
|
71
|
+
data = facade.json.loads(path.read_text(encoding='utf-8'))
|
|
72
|
+
stamp = data.get('computed_at') if isinstance(data, dict) else None
|
|
73
|
+
if not isinstance(stamp, (int, float)) or stamp <= computed_at:
|
|
74
|
+
path.unlink()
|
|
75
|
+
except (OSError, ValueError):
|
|
76
|
+
try:
|
|
77
|
+
path.unlink()
|
|
78
|
+
except OSError:
|
|
79
|
+
pass
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def read_cache(facade, session_id):
|
|
83
|
+
path = facade._status_bar_cache_path(session_id)
|
|
84
|
+
valid = []
|
|
85
|
+
try:
|
|
86
|
+
paths = [path, *path.parent.glob('global-pending-*.json')]
|
|
87
|
+
for candidate in paths:
|
|
88
|
+
try:
|
|
89
|
+
data = facade.json.loads(candidate.read_text(encoding='utf-8'))
|
|
90
|
+
if isinstance(data, dict) and isinstance(data.get('computed_at'), (int, float)):
|
|
91
|
+
valid.append(data)
|
|
92
|
+
except (OSError, ValueError):
|
|
93
|
+
pass
|
|
94
|
+
if valid:
|
|
95
|
+
return max(valid, key=lambda item: (item['computed_at'], item.get('last_attempt', 0) if isinstance(item.get('last_attempt', 0), (int, float)) else 0))
|
|
96
|
+
except OSError:
|
|
97
|
+
pass
|
|
98
|
+
return seed_legacy(facade, session_id)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def seed_legacy(facade, session_id):
|
|
102
|
+
directory = facade._status_bar_dir()
|
|
103
|
+
try:
|
|
104
|
+
candidates = []
|
|
105
|
+
for path in directory.glob('*.json'):
|
|
106
|
+
if path.name == 'global.json' or path.name.startswith('compactions-'):
|
|
107
|
+
continue
|
|
108
|
+
try:
|
|
109
|
+
data = facade.json.loads(path.read_text(encoding='utf-8'))
|
|
110
|
+
if isinstance(data, dict) and isinstance(data.get('savings'), dict) and isinstance(data.get('computed_at'), (int, float)):
|
|
111
|
+
candidates.append(data)
|
|
112
|
+
except (OSError, ValueError):
|
|
113
|
+
continue
|
|
114
|
+
if not candidates:
|
|
115
|
+
return None
|
|
116
|
+
data = max(candidates, key=lambda item: item['computed_at'])
|
|
117
|
+
data.update(stale=True, last_attempt=0, failures=0, refresh_failed=False)
|
|
118
|
+
try:
|
|
119
|
+
atomic_write(facade, facade._status_bar_cache_path(session_id), data)
|
|
120
|
+
except OSError:
|
|
121
|
+
pass
|
|
122
|
+
return data
|
|
123
|
+
except OSError:
|
|
124
|
+
return None
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
_SESSION_REUSE_S = 300
|
|
128
|
+
_SESSION_RETRY_S = 30
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def _session_path(facade, session_id):
|
|
132
|
+
return facade._status_bar_dir() / ('session-' + facade._status_bar_key(session_id) + '.session')
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def _save_session(facade, session_id, values):
|
|
136
|
+
try:
|
|
137
|
+
path = _session_path(facade, session_id)
|
|
138
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
139
|
+
atomic_write(facade, path, values)
|
|
140
|
+
except OSError:
|
|
141
|
+
pass
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def for_session(facade, session_id, savings):
|
|
145
|
+
if savings is None:
|
|
146
|
+
return None
|
|
147
|
+
path = _session_path(facade, session_id)
|
|
148
|
+
try:
|
|
149
|
+
if facade.time.time() - path.stat().st_mtime < _SESSION_REUSE_S:
|
|
150
|
+
values = facade.json.loads(path.read_text(encoding='utf-8'))
|
|
151
|
+
return {**savings, 'session_tokens': values['session_tokens'], 'session_usd': values['session_usd']}
|
|
152
|
+
except (OSError, ValueError, TypeError, KeyError):
|
|
153
|
+
pass
|
|
154
|
+
try:
|
|
155
|
+
conn = facade._open_trends_db_readonly()
|
|
156
|
+
try:
|
|
157
|
+
bucket = facade._realized_savings_buckets(conn, '', session_uuid=session_id).get('', {})
|
|
158
|
+
finally:
|
|
159
|
+
conn.close()
|
|
160
|
+
values = {'session_tokens': int(bucket.get('tokens', 0)), 'session_usd': float(bucket.get('usd', 0.0))}
|
|
161
|
+
_save_session(facade, session_id, values)
|
|
162
|
+
except Exception:
|
|
163
|
+
try:
|
|
164
|
+
values = facade.json.loads(path.read_text(encoding='utf-8'))
|
|
165
|
+
values = {'session_tokens': values['session_tokens'], 'session_usd': values['session_usd']}
|
|
166
|
+
except (OSError, ValueError, TypeError, KeyError):
|
|
167
|
+
values = {'session_tokens': None, 'session_usd': None}
|
|
168
|
+
# Keep what we have and wait _SESSION_RETRY_S before querying again, so
|
|
169
|
+
# a busy database does not cost every poll its full timeout.
|
|
170
|
+
_save_session(facade, session_id, values)
|
|
171
|
+
try:
|
|
172
|
+
stamp = facade.time.time() - _SESSION_REUSE_S + _SESSION_RETRY_S
|
|
173
|
+
facade.os.utime(path, (stamp, stamp))
|
|
174
|
+
except OSError:
|
|
175
|
+
pass
|
|
176
|
+
return {**savings, **values}
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def failed_payload(facade, session_id, out):
|
|
180
|
+
savings = out.get('savings')
|
|
181
|
+
if savings is None:
|
|
182
|
+
try:
|
|
183
|
+
cached = facade._status_bar_read_cache(session_id)
|
|
184
|
+
savings = for_session(facade, session_id, cached.get('savings')) if cached else None
|
|
185
|
+
except Exception:
|
|
186
|
+
pass
|
|
187
|
+
out.update(savings=savings, savings_state='stale' if savings is not None else 'loading',
|
|
188
|
+
savings_reason=None if savings is not None else 'still counting savings',
|
|
189
|
+
savings_refresh_failed=True)
|
|
190
|
+
return out
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def sync(facade, session_id, out):
|
|
194
|
+
try:
|
|
195
|
+
from . import config_cache
|
|
196
|
+
with config_cache.pricing_snapshot(facade), config_cache.skip_cache_scan():
|
|
197
|
+
savings, reason = facade._status_bar_savings_or_reason(session_id)
|
|
198
|
+
except Exception as exc:
|
|
199
|
+
savings, reason = None, str(exc)
|
|
200
|
+
if savings is None:
|
|
201
|
+
facade._log_spawn_failure("status-bar savings refresh failed: " + str(reason))
|
|
202
|
+
try:
|
|
203
|
+
facade._status_bar_write_cache(session_id, savings, reason)
|
|
204
|
+
except OSError:
|
|
205
|
+
pass
|
|
206
|
+
cached = None
|
|
207
|
+
if savings is None:
|
|
208
|
+
cached = facade._status_bar_read_cache(session_id)
|
|
209
|
+
if cached and cached.get("savings") is not None:
|
|
210
|
+
out.update(savings=for_session(facade, session_id, cached["savings"]), savings_state="stale", savings_reason=None,
|
|
211
|
+
savings_age_s=round(max(0.0, facade.time.time() - cached["computed_at"]), 1), savings_refresh_failed=bool(cached.get('refresh_failed')))
|
|
212
|
+
return out
|
|
213
|
+
if savings is not None:
|
|
214
|
+
_save_session(facade, session_id, {k: savings[k] for k in ('session_tokens', 'session_usd')})
|
|
215
|
+
out.update(savings=savings, savings_state="fresh" if savings is not None else ("unavailable" if reason == "no savings recorded yet" else "loading"),
|
|
216
|
+
savings_reason=None if savings is not None else ("no savings recorded yet" if reason == "no savings recorded yet" else "still counting savings"),
|
|
217
|
+
savings_age_s=0.0, savings_refresh_failed=bool(savings is None and cached and cached.get('refresh_failed')))
|
|
218
|
+
return out
|
|
@@ -17,10 +17,12 @@ from . import _compat, structural_ledger as ledger, structural_listing as listin
|
|
|
17
17
|
NO_TRIMS = "no trims recorded yet"
|
|
18
18
|
|
|
19
19
|
|
|
20
|
-
def _local_sessions(conn, home):
|
|
20
|
+
def _local_sessions(conn, home, canonical=None):
|
|
21
21
|
out = []
|
|
22
|
-
|
|
23
|
-
|
|
22
|
+
if canonical is None:
|
|
23
|
+
cloud = value.cloud_sessions(conn)
|
|
24
|
+
canonical = dedupe.canonical_sessions(conn, lambda uuid, path: value.proven_foreign(uuid, path, cloud))
|
|
25
|
+
winners, _ = canonical
|
|
24
26
|
for row in winners:
|
|
25
27
|
if value.scope_matches("global", row["project"], home) and not row["foreign"]:
|
|
26
28
|
out.append((value._session_start(row["metrics"], row["first_day"] or row["date"]), row["path"]))
|
|
@@ -80,7 +82,9 @@ def compute(days=30, now=None, f=None, home=None, trims=None, projection_days=30
|
|
|
80
82
|
return {**zero, "status": "no_data", "message": "no usage data yet"}
|
|
81
83
|
home = str(home or f.HOME)
|
|
82
84
|
try:
|
|
83
|
-
|
|
85
|
+
cloud = value.cloud_sessions(conn)
|
|
86
|
+
canonical = dedupe.canonical_sessions(conn, lambda uuid, path: value.proven_foreign(uuid, path, cloud))
|
|
87
|
+
listing.apply_listing_check(trims, _local_sessions(conn, home, canonical), f.CHARS_PER_TOKEN, f.SNAPSHOT_DIR)
|
|
84
88
|
for t in trims:
|
|
85
89
|
if t.get("listing_check") == "pending" and t["tier"] == "measured":
|
|
86
90
|
t["tier"] = "estimated" # not yet verified against what was sent
|
|
@@ -101,9 +105,10 @@ def compute(days=30, now=None, f=None, home=None, trims=None, projection_days=30
|
|
|
101
105
|
connector = setup_connector_ledger.measured_values(conn, trims, estimate_tokens, card, window_start, window_end)
|
|
102
106
|
if not trims and not budget["calls"] and not connector["calls"]:
|
|
103
107
|
return {**zero, "budget_observed": budget, "connector_observed": connector}
|
|
104
|
-
|
|
108
|
+
sessions = value.load_sessions(conn, canonical)
|
|
109
|
+
real = value.value_trims(conn, trims, start, end, card, home, sessions=sessions)
|
|
105
110
|
pstart, pend = value.window(projection_days, now)
|
|
106
|
-
proj = value.value_trims(conn, trims, pstart, pend, card, home, projected=True)
|
|
111
|
+
proj = value.value_trims(conn, trims, pstart, pend, card, home, projected=True, sessions=sessions)
|
|
107
112
|
cover = value.call_coverage(conn, start)
|
|
108
113
|
finally:
|
|
109
114
|
conn.close()
|
|
@@ -159,9 +164,23 @@ def compute(days=30, now=None, f=None, home=None, trims=None, projection_days=30
|
|
|
159
164
|
**cover,
|
|
160
165
|
}
|
|
161
166
|
except Exception as exc: # never break the savings summary
|
|
167
|
+
_log_error(f, exc)
|
|
162
168
|
return {**zero, "status": "error", "message": type(exc).__name__}
|
|
163
169
|
|
|
164
170
|
|
|
171
|
+
def _log_error(f, exc):
|
|
172
|
+
"""A failed report reads as zero structural savings; leave a durable line
|
|
173
|
+
so a tripped guard (e.g. the zero-write pricing check) is discoverable."""
|
|
174
|
+
try:
|
|
175
|
+
f.DAEMON_LOG_DIR.mkdir(parents=True, exist_ok=True)
|
|
176
|
+
path = f.DAEMON_LOG_DIR / "structural-report.log"
|
|
177
|
+
f._cap_append_log(path)
|
|
178
|
+
with open(path, "a", encoding="utf-8") as out:
|
|
179
|
+
out.write("%s structural report failed: %s: %s\n" % (f.time.strftime("%Y-%m-%dT%H:%M:%S"), type(exc).__name__, str(exc)[:300]))
|
|
180
|
+
except Exception:
|
|
181
|
+
pass
|
|
182
|
+
|
|
183
|
+
|
|
165
184
|
def price_synthetic(s, days, now=None, f=None, home=None, scope="global"):
|
|
166
185
|
"""Forward value of S prefix tokens over the window, on the same per-request
|
|
167
186
|
pricing as realized trims. Used by the opportunity figure."""
|
|
@@ -97,13 +97,15 @@ def _session_start(metrics_json, first_day):
|
|
|
97
97
|
return None
|
|
98
98
|
|
|
99
99
|
|
|
100
|
-
def load_sessions(conn):
|
|
100
|
+
def load_sessions(conn, canonical=None):
|
|
101
101
|
"""owner_hash -> (project, start_epoch, foreign), one canonical row per real
|
|
102
102
|
session: copies of a session (uuid, else first request) resolve to the most
|
|
103
103
|
complete one, so scope comes from a single row (see structural_dedupe)."""
|
|
104
104
|
out = {}
|
|
105
|
-
|
|
106
|
-
|
|
105
|
+
if canonical is None:
|
|
106
|
+
cloud = cloud_sessions(conn)
|
|
107
|
+
canonical = dedupe.canonical_sessions(conn, lambda uuid, path: proven_foreign(uuid, path, cloud))
|
|
108
|
+
_, canon = canonical
|
|
107
109
|
for path, win in canon.items():
|
|
108
110
|
value = (win["project"] or "", _session_start(win["metrics"], win["first_day"] or win["date"]),
|
|
109
111
|
win["foreign"])
|
|
@@ -128,7 +130,7 @@ def _price(card, s, cr, cc, cc_1h, cc_5m):
|
|
|
128
130
|
return s, 0, s * float(card.get("cache_read", 0) or 0) / 1e6, 0.0, 0.0
|
|
129
131
|
|
|
130
132
|
|
|
131
|
-
def value_trims(conn, trims, start_day, end_day, card_fn, home, projected=False):
|
|
133
|
+
def value_trims(conn, trims, start_day, end_day, card_fn, home, projected=False, sessions=None):
|
|
132
134
|
"""Per-trim and per-day value over [start_day, end_day] (local days).
|
|
133
135
|
|
|
134
136
|
projected=True values each still-open trim as if it held for the whole
|
|
@@ -136,7 +138,7 @@ def value_trims(conn, trims, start_day, end_day, card_fn, home, projected=False)
|
|
|
136
138
|
inside the trim's life. Returns {"trims": {id: {...}}, "days": {...},
|
|
137
139
|
"requests": n, "unmatched_requests": n, "unpriced_tokens": n}.
|
|
138
140
|
"""
|
|
139
|
-
sessions = load_sessions(conn)
|
|
141
|
+
sessions = load_sessions(conn) if sessions is None else sessions
|
|
140
142
|
rows = load_requests(conn, start_day, end_day)
|
|
141
143
|
per = {t["id"]: {"read_tokens": 0, "write_tokens": 0, "usd": 0.0, "read_usd": 0.0,
|
|
142
144
|
"write_1h_usd": 0.0, "write_5m_usd": 0.0, "requests": 0,
|
|
@@ -154,6 +156,7 @@ def value_trims(conn, trims, start_day, end_day, card_fn, home, projected=False)
|
|
|
154
156
|
for t in live
|
|
155
157
|
}
|
|
156
158
|
scope_cache = {}
|
|
159
|
+
price_cache = {}
|
|
157
160
|
for owner, day, model, calls, cr, cc, cc_1h, cc_5m, inp in rows:
|
|
158
161
|
sess = sessions.get(owner)
|
|
159
162
|
if sess is None:
|
|
@@ -161,6 +164,7 @@ def value_trims(conn, trims, start_day, end_day, card_fn, home, projected=False)
|
|
|
161
164
|
continue
|
|
162
165
|
project, start, foreign = sess
|
|
163
166
|
card = card_fn(model, (cr or 0) + (cc or 0) + (inp or 0))
|
|
167
|
+
cache_read = float(card.get("cache_read", 0) or 0) if card is not None else None
|
|
164
168
|
n = dedupe.request_weight(calls)
|
|
165
169
|
if not n:
|
|
166
170
|
continue # duplicate share of a request another session copy already owns
|
|
@@ -183,21 +187,23 @@ def value_trims(conn, trims, start_day, end_day, card_fn, home, projected=False)
|
|
|
183
187
|
if card is None:
|
|
184
188
|
acc["unpriced_tokens"] += t["tokens"] * n
|
|
185
189
|
continue
|
|
186
|
-
|
|
190
|
+
price_key = (t["tokens"], cache_read)
|
|
191
|
+
if price_key not in price_cache:
|
|
192
|
+
price_cache[price_key] = _price(card, t["tokens"], cr or 0, cc or 0, cc_1h or 0, cc_5m or 0)
|
|
193
|
+
if any(price_cache[price_key][i] for i in (1, 3, 4)):
|
|
194
|
+
raise RuntimeError("structural pricing assumes no cache-write savings")
|
|
195
|
+
r, w, ur, u1, u5 = price_cache[price_key]
|
|
187
196
|
if not (r or w):
|
|
188
197
|
continue
|
|
189
198
|
usd = ur + u1 + u5
|
|
190
199
|
acc["read_tokens"] += r * n
|
|
191
|
-
acc["write_tokens"] += w * n
|
|
192
200
|
acc["usd"] += usd * n
|
|
193
|
-
acc["read_usd"] += ur * n
|
|
194
|
-
acc["write_1h_usd"] += u1 * n
|
|
195
|
-
acc["write_5m_usd"] += u5 * n
|
|
196
201
|
acc["requests"] += n
|
|
197
202
|
d = days.setdefault(day, {"tokens": 0, "usd": 0.0})
|
|
198
203
|
d["tokens"] += (r + w) * n
|
|
199
204
|
d["usd"] += usd * n
|
|
200
205
|
for acc in per.values():
|
|
206
|
+
acc["read_usd"] = acc["usd"]
|
|
201
207
|
for k in ("usd", "read_usd", "write_1h_usd", "write_5m_usd"):
|
|
202
208
|
acc[k] = round(acc[k], 4)
|
|
203
209
|
for d in days.values():
|
|
@@ -486,10 +486,9 @@ _REQUIRED = ("hooks/hooks.json", "hooks/python-launcher.sh", "hooks/run.py",
|
|
|
486
486
|
"skills/token-optimizer/scripts/_measure/" + name for name in (
|
|
487
487
|
'__init__.py', '_compat.py', 'runtime.py', 'pricing.py', 'audit.py',
|
|
488
488
|
'dashboard.py', 'lifecycle.py', 'sessions.py', 'trends.py', 'cache_policy.py',
|
|
489
|
-
'daemon.py', 'quality_archive.py', 'continuity.py', 'savings.py', 'cli.py', 'dashboard_history.py', 'weekly_activity.py', 'headline.py', 'counted_position.py', 'counted_pricing_v5.py', 'transcript_backfill.py', 'counted_subagents.py', 'lean_resume_threshold.py', 'output_reread.py', 'session_effect.py', 'structural_ledger.py', 'structural_archives.py', 'structural_listing.py', 'structural_report.py', 'structural_seed.py', 'structural_value.py', 'rework_metrics.py', 'session_best.py', 'savings_story.py', 'savings_headline.py', 'counted_orphans.py', 'counted_cap.py', 'archive_void_evidence.py', 'cost_per_message_trend.py', 'lean_resume_receivers.py', 'routing_period.py', 'fixture_context.py', 'transcript_product.py', 'periphery_exposure.py', 'structure_funnel.py', 'setup_attachment_counter.py', 'first_read_outcomes.py', 'setup_budget_monitor.py', 'setup_connector_ledger.py', 'first_call_context.py', 'timestamp_cache.py', 'token_type_split.py', 'evidence_parallel.py', 'ttl_period.py', 'first_read_revive.py', 'mcp_archive_tripwire.py', 'compaction_survival.py', 'archive_void_codex.py', 'compression_fixture_void.py', 'feature_health.py', 'archive_health.py', 'coverage_report.py', 'file_refetch.py', 'holdout_report.py', 'structural_dedupe.py', 'setup_step.py', 'baseline_provenance.py', 'own_price_card.py', 'transcript_stream.py', 'checkpoint_direction.py', 'checkpoint_retention.py', 'keepwarm_safety.py', 'keepwarm_economics.py', 'keepwarm_linux.py', 'mod_action_booking.py', 'mod_compaction_booking.py', 'mod_fresh_booking.py', 'quality_continuity.py', 'quality_checkpoint.py', 'codex_quality.py', 'lease_candidate_cleanup.py', 'session_store_spool.py', 'upgrade_drain_control.py', 'compression_scan_checkpoint.py', 'status_bar_lock.py', 'session_flush_lock.py', 'context_reset_marker.py', 'holdout_fallback.py', 'dashboard_heal_claim.py')
|
|
489
|
+
'daemon.py', 'quality_archive.py', 'continuity.py', 'savings.py', 'cli.py', 'dashboard_history.py', 'weekly_activity.py', 'headline.py', 'counted_position.py', 'counted_pricing_v5.py', 'transcript_backfill.py', 'counted_subagents.py', 'lean_resume_threshold.py', 'output_reread.py', 'session_effect.py', 'structural_ledger.py', 'structural_archives.py', 'structural_listing.py', 'structural_report.py', 'structural_seed.py', 'structural_value.py', 'rework_metrics.py', 'session_best.py', 'savings_story.py', 'savings_headline.py', 'counted_orphans.py', 'counted_cap.py', 'archive_void_evidence.py', 'cost_per_message_trend.py', 'lean_resume_receivers.py', 'routing_period.py', 'fixture_context.py', 'transcript_product.py', 'periphery_exposure.py', 'structure_funnel.py', 'setup_attachment_counter.py', 'first_read_outcomes.py', 'setup_budget_monitor.py', 'setup_connector_ledger.py', 'first_call_context.py', 'timestamp_cache.py', 'token_type_split.py', 'evidence_parallel.py', 'ttl_period.py', 'first_read_revive.py', 'mcp_archive_tripwire.py', 'compaction_survival.py', 'archive_void_codex.py', 'compression_fixture_void.py', 'feature_health.py', 'archive_health.py', 'coverage_report.py', 'file_refetch.py', 'holdout_report.py', 'structural_dedupe.py', 'setup_step.py', 'baseline_provenance.py', 'own_price_card.py', 'transcript_stream.py', 'checkpoint_direction.py', 'checkpoint_retention.py', 'keepwarm_safety.py', 'keepwarm_economics.py', 'keepwarm_linux.py', 'mod_action_booking.py', 'mod_compaction_booking.py', 'mod_fresh_booking.py', 'quality_continuity.py', 'quality_checkpoint.py', 'codex_quality.py', 'lease_candidate_cleanup.py', 'session_store_spool.py', 'upgrade_drain_control.py', 'compression_scan_checkpoint.py', 'status_bar_lock.py', 'session_flush_lock.py', 'context_reset_marker.py', 'holdout_fallback.py', 'dashboard_heal_claim.py', 'config_cache.py', 'setup_observation_cache.py', 'status_bar_refresh.py')
|
|
490
490
|
)
|
|
491
491
|
|
|
492
|
-
|
|
493
492
|
# Written into the cache dir on install. Uninstall only removes the shared
|
|
494
493
|
# names (pycache, .stage-*, the runner, install.log) where it finds this, and
|
|
495
494
|
# prune/uninstall only remove version dirs that hold our package: the cache
|
|
@@ -98,6 +98,16 @@ def cmd_show(idx, symbol: str, within: str, max_lines: int, out: _Out) -> List[s
|
|
|
98
98
|
rows.sort(key=lambda r: (r[2] == "variable", r[1] != symbol))
|
|
99
99
|
name, qual, kind, path, line, end, sig = rows[0]
|
|
100
100
|
abs_path = idx.root / path
|
|
101
|
+
if idx.readonly:
|
|
102
|
+
row = idx.file_row(path)
|
|
103
|
+
try:
|
|
104
|
+
st = abs_path.stat()
|
|
105
|
+
if not row or (st.st_mtime_ns, st.st_size) != (row[1], row[2]):
|
|
106
|
+
out.add(f"{path} changed since indexed, use Read.")
|
|
107
|
+
return []
|
|
108
|
+
except OSError:
|
|
109
|
+
out.add(f"{path} changed since indexed, use Read.")
|
|
110
|
+
return []
|
|
101
111
|
try:
|
|
102
112
|
src = abs_path.read_text(encoding="utf-8", errors="replace").splitlines()
|
|
103
113
|
except OSError:
|
|
@@ -219,9 +229,11 @@ def run(argv: Sequence[str]) -> Tuple[int, str]:
|
|
|
219
229
|
c = idx.counts()
|
|
220
230
|
return 0, "" if args.quiet else f"codemap index: {c['files']} files, complete={idx.complete}"
|
|
221
231
|
if args.command == "stats":
|
|
232
|
+
import codemap_ledger as led
|
|
222
233
|
c = idx.counts()
|
|
234
|
+
failures = led.failure_count()
|
|
223
235
|
return 0, (f"root {idx.root}\nfiles {c['files']} defs {c['defs']} imports {c['imports']} "
|
|
224
|
-
f"call-edges {c['refs']} complete={idx.complete} db={idx.db_path.stat().st_size // 1024}KB")
|
|
236
|
+
f"call-edges {c['refs']} complete={idx.complete} failures={failures} db={idx.db_path.stat().st_size // 1024}KB")
|
|
225
237
|
out = _Out()
|
|
226
238
|
max_lines = max(5, min(int(args.max_lines or MAX_SHOW_LINES), 400))
|
|
227
239
|
symbol = args.arg.strip()
|
|
@@ -235,10 +247,15 @@ def run(argv: Sequence[str]) -> Tuple[int, str]:
|
|
|
235
247
|
covered = cmd_outline(idx, symbol, out)
|
|
236
248
|
else:
|
|
237
249
|
covered = cmd_deps(idx, symbol, out)
|
|
250
|
+
if idx.readonly and idx.stale:
|
|
251
|
+
out.lines.append("(read-only index may be stale; source files changed or the sweep was incomplete)")
|
|
252
|
+
if idx.capped:
|
|
253
|
+
out.lines.append(f"(index covers the first {ci.MAX_FILES:,} files)")
|
|
238
254
|
if not idx.complete:
|
|
239
255
|
out.lines.append(f"(index still building: {idx.counts()['files']} files so far; rerun or Grep for anything missing)")
|
|
240
256
|
text = out.text(" (narrow with --in <path> or Class.method)")
|
|
241
|
-
|
|
257
|
+
if not idx.stale:
|
|
258
|
+
_log(idx, args.command, text, covered)
|
|
242
259
|
return 0, text
|
|
243
260
|
finally:
|
|
244
261
|
idx.close()
|
|
@@ -261,9 +278,20 @@ def main(argv: Optional[Sequence[str]] = None) -> int:
|
|
|
261
278
|
except SystemExit as exc: # argparse usage errors
|
|
262
279
|
return int(exc.code or 0)
|
|
263
280
|
except Exception as exc:
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
281
|
+
cause = exc
|
|
282
|
+
while cause.__cause__ is not None:
|
|
283
|
+
cause = cause.__cause__
|
|
284
|
+
code = getattr(cause, "sqlite_errorname", None) or str(getattr(cause, "sqlite_errorcode", "unknown"))
|
|
285
|
+
message = str(exc)
|
|
286
|
+
if not message.startswith("query failed at "):
|
|
287
|
+
message = f"query failed at lookup ({type(cause).__name__}; code {code})"
|
|
288
|
+
try:
|
|
289
|
+
import codemap_ledger as led
|
|
290
|
+
stage = "open/sync" if "open/sync" in message else "lookup"
|
|
291
|
+
led.log_failure(stage, code)
|
|
292
|
+
except Exception:
|
|
293
|
+
pass
|
|
294
|
+
print(FALLBACK.format(why=message[:160]))
|
|
267
295
|
return 0
|
|
268
296
|
if text:
|
|
269
297
|
print(text)
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env python3
|
|
2
2
|
"""Discovery hint for the code map (SessionStart and SubagentStart).
|
|
3
3
|
|
|
4
|
-
Tells the agent, in
|
|
4
|
+
Tells the agent, in approximately 75 to 81 estimated tokens depending on installation paths, to use the code map before grepping or
|
|
5
5
|
reading whole files for structural questions, and warms the index in a
|
|
6
6
|
detached background process so the first lookup is fast. Silent (no output,
|
|
7
7
|
no spawn) when the feature is off, when the cwd is the home directory or the
|
|
@@ -27,6 +27,9 @@ sys.path.insert(0, str(Path(__file__).resolve().parent))
|
|
|
27
27
|
PROBE_MAX_ENTRIES = 400
|
|
28
28
|
PROBE_MAX_S = 0.25
|
|
29
29
|
LOCK_FRESH_S = 300.0
|
|
30
|
+
OLD_INDEX_AGE_S = 7 * 86400
|
|
31
|
+
OLD_INDEX_CLEANUP_LIMIT = 10
|
|
32
|
+
OLD_INDEX_CLEANUP_INTERVAL_S = 86400
|
|
30
33
|
# Subagents that never explore code: no hint for them.
|
|
31
34
|
SKIP_AGENT_TYPES = frozenset({"statusline-setup", "claude-code-guide", "web-fetch"})
|
|
32
35
|
|
|
@@ -71,11 +74,12 @@ def warm_index(root: Path) -> bool:
|
|
|
71
74
|
import sqlite3
|
|
72
75
|
conn = sqlite3.connect(str(db), timeout=1.0)
|
|
73
76
|
try:
|
|
74
|
-
row = conn.execute("SELECT v FROM meta WHERE k='complete'"
|
|
77
|
+
row = conn.execute("SELECT v FROM meta WHERE k='complete' AND "
|
|
78
|
+
"(SELECT v FROM meta WHERE k='schema')=?", (ci.SCHEMA_VERSION,)).fetchone()
|
|
75
79
|
finally:
|
|
76
80
|
conn.close()
|
|
77
81
|
if row and row[0] == "1":
|
|
78
|
-
return
|
|
82
|
+
return True # an existing complete index needs no warm-up
|
|
79
83
|
if lock.exists() and time.time() - lock.stat().st_mtime < LOCK_FRESH_S:
|
|
80
84
|
return False
|
|
81
85
|
lock.parent.mkdir(parents=True, exist_ok=True)
|
|
@@ -96,24 +100,161 @@ def warm_index(root: Path) -> bool:
|
|
|
96
100
|
def hint_text(root: Path) -> str:
|
|
97
101
|
script = shlex.quote(str(Path(__file__).resolve().parent / "codemap.py"))
|
|
98
102
|
py = shlex.quote(sys.executable or "python3")
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
103
|
+
import codemap_index as ci
|
|
104
|
+
import sqlite3
|
|
105
|
+
conn = sqlite3.connect(ci.index_path(root).resolve().as_uri() + "?mode=ro", uri=True)
|
|
106
|
+
try:
|
|
107
|
+
row = conn.execute("SELECT path FROM files ORDER BY path LIMIT 1").fetchone()
|
|
108
|
+
finally:
|
|
109
|
+
conn.close()
|
|
110
|
+
if not row:
|
|
111
|
+
return ""
|
|
112
|
+
return f"[Token Optimizer] Code map: inspect a file with `{py} {script} outline {shlex.quote(row[0])}`."
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _clean_old_indexes(directory: Path) -> None:
|
|
116
|
+
"""Remove a few inactive legacy indexes, without following symlinks."""
|
|
117
|
+
import re
|
|
118
|
+
import sqlite3
|
|
119
|
+
import stat
|
|
120
|
+
|
|
121
|
+
# Directory-relative operations keep every unlink inside the opened folder.
|
|
122
|
+
if not hasattr(os, "O_NOFOLLOW") or os.unlink not in os.supports_dir_fd:
|
|
123
|
+
return
|
|
124
|
+
try:
|
|
125
|
+
fd = os.open(directory, os.O_RDONLY | os.O_NOFOLLOW | getattr(os, "O_DIRECTORY", 0))
|
|
126
|
+
except OSError:
|
|
127
|
+
return
|
|
128
|
+
try:
|
|
129
|
+
cutoff = time.time() - OLD_INDEX_AGE_S
|
|
130
|
+
removed = 0
|
|
131
|
+
with os.scandir(fd) as entries:
|
|
132
|
+
for entry in entries:
|
|
133
|
+
if removed >= OLD_INDEX_CLEANUP_LIMIT:
|
|
134
|
+
break
|
|
135
|
+
if not re.fullmatch(r"[0-9a-f]{16}\.db", entry.name):
|
|
136
|
+
continue
|
|
137
|
+
try:
|
|
138
|
+
old = os.stat(entry.name, dir_fd=fd, follow_symlinks=False)
|
|
139
|
+
if not stat.S_ISREG(old.st_mode) or old.st_mtime > cutoff:
|
|
140
|
+
continue
|
|
141
|
+
sidecars = []
|
|
142
|
+
for suffix in ("-wal", "-shm"):
|
|
143
|
+
name = entry.name + suffix
|
|
144
|
+
try:
|
|
145
|
+
info = os.stat(name, dir_fd=fd, follow_symlinks=False)
|
|
146
|
+
except FileNotFoundError:
|
|
147
|
+
continue
|
|
148
|
+
if not stat.S_ISREG(info.st_mode) or info.st_mtime > cutoff:
|
|
149
|
+
break
|
|
150
|
+
sidecars.append(name)
|
|
151
|
+
else:
|
|
152
|
+
# Inspect the database through a no-follow descriptor; an
|
|
153
|
+
# immutable read cannot create or modify SQLite sidecars.
|
|
154
|
+
source_fd = os.open(entry.name, os.O_RDONLY | os.O_NOFOLLOW, dir_fd=fd)
|
|
155
|
+
try:
|
|
156
|
+
current = os.fstat(source_fd)
|
|
157
|
+
if (current.st_ino, current.st_dev, current.st_mtime_ns, current.st_size) != (
|
|
158
|
+
old.st_ino, old.st_dev, old.st_mtime_ns, old.st_size):
|
|
159
|
+
continue
|
|
160
|
+
conn = sqlite3.connect(f"file:/dev/fd/{source_fd}?mode=ro&immutable=1", uri=True)
|
|
161
|
+
try:
|
|
162
|
+
version = conn.execute("SELECT v FROM meta WHERE k='schema'").fetchone()
|
|
163
|
+
finally:
|
|
164
|
+
conn.close()
|
|
165
|
+
if not version or version[0] != "2":
|
|
166
|
+
continue
|
|
167
|
+
finally:
|
|
168
|
+
os.close(source_fd)
|
|
169
|
+
os.unlink(entry.name, dir_fd=fd)
|
|
170
|
+
removed += 1
|
|
171
|
+
for name in sidecars:
|
|
172
|
+
try:
|
|
173
|
+
os.unlink(name, dir_fd=fd)
|
|
174
|
+
except OSError:
|
|
175
|
+
pass
|
|
176
|
+
except (OSError, sqlite3.Error):
|
|
177
|
+
continue
|
|
178
|
+
except OSError:
|
|
179
|
+
pass
|
|
180
|
+
finally:
|
|
181
|
+
os.close(fd)
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def cleanup_old_indexes_daily() -> None:
|
|
185
|
+
"""Run the legacy cleanup at most once a day when the engine is enabled."""
|
|
186
|
+
try:
|
|
187
|
+
import codemap_index as ci
|
|
188
|
+
import fcntl
|
|
189
|
+
import stat
|
|
190
|
+
if not ci.codemap_enabled() or not hasattr(os, "O_NOFOLLOW"):
|
|
191
|
+
return
|
|
192
|
+
directory = ci.index_dir()
|
|
193
|
+
fd = os.open(directory, os.O_RDONLY | os.O_NOFOLLOW | getattr(os, "O_DIRECTORY", 0))
|
|
194
|
+
try:
|
|
195
|
+
name = ".legacy-cleanup-timestamp"
|
|
196
|
+
try:
|
|
197
|
+
marker = os.open(name, os.O_RDWR | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW | os.O_NONBLOCK,
|
|
198
|
+
0o600, dir_fd=fd)
|
|
199
|
+
first = True
|
|
200
|
+
except FileExistsError:
|
|
201
|
+
marker = os.open(name, os.O_RDWR | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=fd)
|
|
202
|
+
first = False
|
|
203
|
+
try:
|
|
204
|
+
if not stat.S_ISREG(os.fstat(marker).st_mode):
|
|
205
|
+
return
|
|
206
|
+
fcntl.flock(marker, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
207
|
+
if not first and time.time() - os.fstat(marker).st_mtime < OLD_INDEX_CLEANUP_INTERVAL_S:
|
|
208
|
+
return
|
|
209
|
+
os.utime(marker, None)
|
|
210
|
+
_clean_old_indexes(directory)
|
|
211
|
+
finally:
|
|
212
|
+
os.close(marker)
|
|
213
|
+
finally:
|
|
214
|
+
os.close(fd)
|
|
215
|
+
except (ImportError, OSError):
|
|
216
|
+
pass
|
|
105
217
|
|
|
106
218
|
|
|
107
219
|
def session_text(hook_input: dict) -> str:
|
|
108
220
|
"""Plain hint text for SessionStart ('' when off or not a code project)."""
|
|
109
221
|
try:
|
|
110
222
|
import codemap_index as ci
|
|
111
|
-
if not ci.
|
|
223
|
+
if not ci.codemap_hint_enabled():
|
|
112
224
|
return ""
|
|
113
225
|
root = _project_root(str(hook_input.get("cwd") or ""))
|
|
114
226
|
if root is None:
|
|
115
227
|
return ""
|
|
116
|
-
warm_index(root)
|
|
228
|
+
if not warm_index(root):
|
|
229
|
+
return ""
|
|
230
|
+
import sqlite3
|
|
231
|
+
db = ci.index_path(root)
|
|
232
|
+
conn = sqlite3.connect(db.resolve().as_uri() + "?mode=ro", uri=True, timeout=1.0)
|
|
233
|
+
try:
|
|
234
|
+
row = conn.execute("SELECT v FROM meta WHERE k='complete'").fetchone()
|
|
235
|
+
finally:
|
|
236
|
+
conn.close()
|
|
237
|
+
if not row or row[0] != "1":
|
|
238
|
+
return ""
|
|
239
|
+
sid = str(hook_input.get("session_id") or "")
|
|
240
|
+
if not sid:
|
|
241
|
+
return ""
|
|
242
|
+
agent_id = str(hook_input.get("agent_id") or "")
|
|
243
|
+
if agent_id:
|
|
244
|
+
sid += ":" + agent_id
|
|
245
|
+
import hashlib
|
|
246
|
+
for old in db.parent.glob("hint-*"):
|
|
247
|
+
try:
|
|
248
|
+
if time.time() - old.stat().st_mtime > 7 * 86400:
|
|
249
|
+
old.unlink()
|
|
250
|
+
except OSError:
|
|
251
|
+
pass
|
|
252
|
+
marker = db.parent / ("hint-" + hashlib.sha256(sid.encode()).hexdigest())
|
|
253
|
+
try:
|
|
254
|
+
with marker.open("x", encoding="utf-8"):
|
|
255
|
+
pass
|
|
256
|
+
except FileExistsError:
|
|
257
|
+
return ""
|
|
117
258
|
return hint_text(root)
|
|
118
259
|
except Exception:
|
|
119
260
|
return ""
|