@alexgreensh/token-optimizer 5.13.79 → 5.13.80

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.
@@ -13,7 +13,7 @@
13
13
  "name": "token-optimizer",
14
14
  "source": "./",
15
15
  "description": "Audit, fix, and monitor Claude Code context window usage. Find the ghost tokens.",
16
- "version": "5.13.79",
16
+ "version": "5.13.80",
17
17
  "author": {
18
18
  "name": "Alex Greenshpun",
19
19
  "url": "https://linkedin.com/in/alexgreensh"
@@ -55,7 +55,7 @@
55
55
  "name": "token-optimizer-cowork",
56
56
  "source": "./cowork/token-optimizer",
57
57
  "description": "Token Optimizer for Claude Cowork \u2014 full skills + Cowork-native hooks (beta). Install THIS in Cowork; the standard token-optimizer entry is for desktop Claude Code.",
58
- "version": "5.13.79",
58
+ "version": "5.13.80",
59
59
  "author": {
60
60
  "name": "Alex Greenshpun",
61
61
  "url": "https://linkedin.com/in/alexgreensh"
@@ -7,7 +7,7 @@
7
7
  },
8
8
  "homepage": "https://github.com/alexgreensh/token-optimizer",
9
9
  "repository": "https://github.com/alexgreensh/token-optimizer",
10
- "version": "5.13.79",
10
+ "version": "5.13.80",
11
11
  "license": "PolyForm-Noncommercial-1.0.0",
12
12
  "keywords": [
13
13
  "token",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@alexgreensh/token-optimizer",
3
- "version": "5.13.79",
3
+ "version": "5.13.80",
4
4
  "description": "Token Optimizer for Claude Code cloud sessions: the real plugin, installed by your cloud environment's setup script.",
5
5
  "license": "PolyForm-Noncommercial-1.0.0",
6
6
  "author": "Alex Greenshpun (https://linkedin.com/in/alexgreensh)",
@@ -159,35 +159,73 @@ def classify(rows, emitted, new_rows=None):
159
159
  return 'pending', None, []
160
160
 
161
161
 
162
- def _project_index(directory):
163
- """Read each transcript once before the database write transaction."""
164
- transcripts, failures = {}, []
162
+ def _start(path):
163
+ """First timestamp of an append-only transcript, without reading the rest."""
164
+ with Path(path).open(encoding='utf-8', errors='replace') as stream:
165
+ for line in stream:
166
+ try:
167
+ row = json.loads(line)
168
+ except ValueError:
169
+ continue
170
+ if isinstance(row, dict) and not row.get('isSidechain'):
171
+ stamp = _epoch(row.get('timestamp'))
172
+ if stamp is not None:
173
+ return stamp
174
+ return None
175
+
176
+
177
+ def _project_index(directory, since):
178
+ """Start times of transcripts written after `since`.
179
+
180
+ Only these can follow a nudged session. Reading every transcript in full
181
+ held a whole project history in memory: 17 GB of logs grew past 11 GB.
182
+ """
183
+ starts, failures = {}, []
165
184
  for path in Path(directory).glob('*.jsonl'):
166
185
  if path.is_symlink():
167
186
  continue
168
187
  try:
169
- rows = list(_rows(path))
170
- stamps = [_epoch(row.get('timestamp')) for row in rows]
171
- stamps = [stamp for stamp in stamps if stamp is not None]
172
- if stamps:
173
- transcripts[path] = (min(stamps), max(stamps), rows)
188
+ if path.stat().st_mtime < since:
189
+ continue
190
+ start = _start(path)
191
+ if start is not None:
192
+ starts[path] = start
174
193
  except Exception as exc:
175
194
  failures.append(exc)
176
- return transcripts, failures
195
+ return starts, failures
177
196
 
178
197
 
179
- def _next_session(path, stamp, index):
198
+ def _nudged_rows(path, stamp):
199
+ """Rows from the nudge on, plus the newest row, and the session's last timestamp."""
200
+ kept, end, newest = [], None, None
201
+ for row in _rows(Path(path)):
202
+ ts = _epoch(row.get('timestamp'))
203
+ if ts is None:
204
+ continue
205
+ if end is None or ts > end:
206
+ end, newest = ts, row
207
+ if ts >= stamp:
208
+ kept.append(row)
209
+ if newest is not None and (_epoch(newest.get('timestamp')) or 0) < stamp:
210
+ kept.append(newest)
211
+ return kept, end
212
+
213
+
214
+ def _successor_rows(path):
215
+ """The opening rows of the next session, up to the requests classify prices."""
216
+ rows = []
217
+ for row in _rows(Path(path)):
218
+ rows.append(row)
219
+ if row.get('type') == 'assistant' and len(_requests(rows)) >= 50:
220
+ break
221
+ return rows
222
+
223
+
224
+ def _next_session(path, stamp, end, starts):
180
225
  current = Path(path)
181
- entry = index.get(current)
182
- if not entry:
183
- return None
184
- end = entry[1]
185
- choices = [(start, str(candidate), rows) for candidate, (start, _, rows) in index.items()
226
+ choices = [(start, str(candidate)) for candidate, start in starts.items()
186
227
  if candidate != current and start > end and start > stamp]
187
- if not choices:
188
- return None, None
189
- _, candidate, rows = min(choices)
190
- return candidate, rows
228
+ return str(min(choices)[1]) if choices else None
191
229
 
192
230
 
193
231
  def _session_ended(facade, sid, last_ts):
@@ -216,31 +254,51 @@ def resolve(facade, conn=None):
216
254
  return
217
255
  _schema(conn)
218
256
  conn.commit()
219
- events = conn.execute('SELECT id,session_uuid,ts,context_tokens,transcript_path,savings_event_id FROM nudge_events').fetchall()
220
- projects = {Path(path).parent for _, _, _, _, path, _ in events if path}
257
+ events = conn.execute("SELECT id,session_uuid,ts,context_tokens,transcript_path,savings_event_id FROM nudge_events WHERE status='pending' AND savings_event_id IS NULL").fetchall()
258
+ events = [event for event in events if event[4] and _epoch(event[2]) is not None]
259
+ first_stamp = {}
260
+ for _, _, ts, _, path, _ in events:
261
+ first_stamp[path] = min(first_stamp.get(path, float('inf')), _epoch(ts))
262
+ nudged = {}
263
+ for path, stamp in first_stamp.items():
264
+ try:
265
+ rows, end = _nudged_rows(path, stamp)
266
+ if end is not None:
267
+ nudged[path] = rows, end
268
+ except Exception as exc:
269
+ _diagnostic(facade, exc)
221
270
  indexes = {}
222
- for project in projects:
271
+ for project in {Path(path).parent for path in first_stamp}:
272
+ ends = [end for path, (_, end) in nudged.items() if Path(path).parent == project]
223
273
  try:
224
- transcripts, failures = _project_index(project)
274
+ # A successor is written after the nudged session ends; allow clock skew.
275
+ starts, failures = _project_index(project, min(ends, default=float('inf')) - 300)
225
276
  except Exception as exc:
226
- transcripts, failures = {}, [exc]
277
+ starts, failures = {}, [exc]
227
278
  for failure in failures:
228
279
  _diagnostic(facade, failure)
229
- indexes[project] = transcripts
280
+ indexes[project] = starts
281
+ successors = {}
230
282
  prepared = {}
231
283
  claimed_sessions = set()
232
284
  events.sort(key=lambda event: (_epoch(event[2]) or 0, event[0]), reverse=True)
233
285
  for ident, sid, ts, before, path, event_id in events:
234
- if not path:
235
- continue
236
- entry = indexes[Path(path).parent].get(Path(path))
237
- if not entry:
286
+ if path not in nudged:
238
287
  continue
239
- rows = entry[2]
288
+ rows, end = nudged[path]
240
289
  status, action, requests = classify(rows, ts)
241
290
  if status == 'pending':
242
- next_path, next_rows = _next_session(path, _epoch(ts), indexes[Path(path).parent])
243
- if next_rows and _session_ended(facade, sid, entry[1]):
291
+ next_path = _next_session(path, _epoch(ts), end, indexes[Path(path).parent])
292
+ next_rows = None
293
+ if next_path and _session_ended(facade, sid, end):
294
+ if next_path not in successors:
295
+ try:
296
+ successors[next_path] = _successor_rows(next_path)
297
+ except Exception as exc:
298
+ _diagnostic(facade, exc)
299
+ successors[next_path] = None
300
+ next_rows = successors[next_path]
301
+ if next_rows:
244
302
  status, action, requests = classify(rows, ts, next_rows)
245
303
  if status == 'followed':
246
304
  if next_path in claimed_sessions:
@@ -57,7 +57,8 @@ def backoff_active(snapshot_dir, now=None):
57
57
  age = (time.time() if now is None else now) - marker.stat().st_mtime
58
58
  except OSError:
59
59
  return False
60
- return 0 <= age < backoff_seconds()
60
+ # File clocks can run a moment ahead of time.time() (seen on Windows).
61
+ return -60 <= age < backoff_seconds()
61
62
 
62
63
 
63
64
  def clear_backoff(snapshot_dir):