@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.
@@ -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.71",
16
+ "version": "5.13.72",
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.71",
58
+ "version": "5.13.72",
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.71",
10
+ "version": "5.13.72",
11
11
  "license": "PolyForm-Noncommercial-1.0.0",
12
12
  "keywords": [
13
13
  "token",
@@ -141,7 +141,7 @@ _MEASURE_PACKAGE_SOURCES = (
141
141
  )
142
142
  _MEASURE_PACKAGE_SOURCES += ('transcript_stream.py', 'checkpoint_direction.py', 'checkpoint_retention.py')
143
143
  _MEASURE_PACKAGE_SOURCES += ('keepwarm_safety.py', 'keepwarm_economics.py', 'keepwarm_linux.py', 'mod_action_booking.py', 'mod_compaction_booking.py', 'mod_fresh_booking.py',)
144
- _MEASURE_PACKAGE_SOURCES += ('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',)
144
+ _MEASURE_PACKAGE_SOURCES += ('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',)
145
145
 
146
146
 
147
147
  def _runtime_sources(measure_src):
@@ -507,6 +507,11 @@ def _sub_compact_restore_new_session(hook_input: dict, sink: list) -> None:
507
507
  sink.append(buf.getvalue())
508
508
 
509
509
 
510
+ def _sub_codemap_cleanup() -> None:
511
+ import codemap_hint # noqa: PLC0415
512
+ codemap_hint.cleanup_old_indexes_daily()
513
+
514
+
510
515
  def _sub_codemap_hint(hook_input: dict) -> None:
511
516
  """Code map discovery hint (codemap_hint.py): plain text, so it lands in
512
517
  additionalContext via the envelope. Silent when the feature is off
@@ -650,6 +655,7 @@ def main() -> int:
650
655
  _capture("read_cache --clear-compacted", _sub_clear_compacted, hook_input)
651
656
  _capture("compact-restore --new-session-only", _sub_compact_restore_new_session,
652
657
  hook_input, _wrapped)
658
+ _capture("codemap cleanup", _sub_codemap_cleanup)
653
659
  _capture("codemap hint", _sub_codemap_hint, hook_input)
654
660
 
655
661
  # Emit the compact-restore payloads and ensure-health/quality-cache
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@alexgreensh/token-optimizer",
3
- "version": "5.13.71",
3
+ "version": "5.13.72",
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)",
@@ -12,7 +12,7 @@ DOMAIN_MODULES = (
12
12
  DEFERRED_MODULES = ('audit', 'dashboard', 'sessions', 'savings', 'cli')
13
13
  RUNTIME_SOURCES = ('__init__.py', '_compat.py') + tuple(name + '.py' for name in DOMAIN_MODULES) + ('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')
14
14
  RUNTIME_SOURCES += ('keepwarm_safety.py', 'keepwarm_economics.py', 'keepwarm_linux.py', 'mod_action_booking.py', 'mod_compaction_booking.py', 'mod_fresh_booking.py',)
15
- RUNTIME_SOURCES += ('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',)
15
+ RUNTIME_SOURCES += ('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',)
16
16
  # Set True by hooks/userpromptsubmit_runner.py right before `import measure`,
17
17
  # which consumes it. That process never patches or enumerates the facade.
18
18
  HOOK_IMPORT = False
@@ -0,0 +1,63 @@
1
+ """Cache parsed local configuration, while leaving project fallback live.
2
+
3
+ Also scopes what one status-bar refresh may skip (see skip_cache_scan)."""
4
+ import copy
5
+ import contextvars
6
+ import threading
7
+ from contextlib import contextmanager
8
+
9
+ _cache = {}
10
+ _lock = threading.Lock()
11
+ _tier = contextvars.ContextVar('status_bar_pricing_tier', default=None)
12
+ _skip_scan = contextvars.ContextVar('status_bar_skip_cache_scan', default=False)
13
+
14
+
15
+ def current_tier():
16
+ return _tier.get()
17
+
18
+
19
+ @contextmanager
20
+ def pricing_snapshot(facade):
21
+ token = _tier.set(facade._load_pricing_tier())
22
+ try:
23
+ yield
24
+ finally:
25
+ _tier.reset(token)
26
+
27
+
28
+ def cache_scan_skipped():
29
+ return _skip_scan.get()
30
+
31
+
32
+ @contextmanager
33
+ def skip_cache_scan():
34
+ """Inside a status-bar refresh, skip the 30-day cache-waste transcript scan.
35
+
36
+ Its only output is the cache_drop opportunity block, which the status-bar
37
+ payload and savings_headline never read; the dashboard and CLI still scan.
38
+ """
39
+ token = _skip_scan.set(True)
40
+ try:
41
+ yield
42
+ finally:
43
+ _skip_scan.reset(token)
44
+
45
+
46
+ def clear():
47
+ with _lock:
48
+ _cache.clear()
49
+
50
+
51
+ def read(path, json_module):
52
+ try:
53
+ stat = path.stat()
54
+ key = (str(path), stat.st_mtime_ns, stat.st_size)
55
+ with _lock:
56
+ if key not in _cache:
57
+ value = json_module.loads(path.read_text(encoding='utf-8'))
58
+ _cache.clear()
59
+ _cache[key] = value if isinstance(value, dict) else {}
60
+ return copy.deepcopy(_cache[key])
61
+ except (OSError, ValueError, TypeError):
62
+ clear()
63
+ return {}
@@ -3548,12 +3548,12 @@ def _status_bar_key(session_id):
3548
3548
 
3549
3549
  def _status_bar_cache_path(session_id):
3550
3550
  _measure_facade = _compat.facade()
3551
- return _measure_facade._status_bar_dir() / f"{_measure_facade._status_bar_key(session_id)}.json"
3551
+ return _measure_facade._status_bar_dir() / "global.json"
3552
3552
 
3553
3553
 
3554
3554
  def _status_bar_lock_path(session_id):
3555
3555
  _measure_facade = _compat.facade()
3556
- return _measure_facade._status_bar_dir() / f"{_measure_facade._status_bar_key(session_id)}.refresh.lock"
3556
+ return _measure_facade._status_bar_dir() / "global.refresh.lock"
3557
3557
 
3558
3558
 
3559
3559
  def _realized_savings_buckets(conn, cutoff, session_uuid=None, by_day=None):
@@ -3730,50 +3730,13 @@ def _status_bar_savings_or_reason(session_id, _retried=None):
3730
3730
 
3731
3731
 
3732
3732
  def _status_bar_write_cache(session_id, savings, reason):
3733
- _measure_facade = _compat.facade()
3734
- d = _measure_facade._status_bar_dir()
3735
- d.mkdir(parents=True, exist_ok=True)
3736
- path = _measure_facade._status_bar_cache_path(session_id)
3737
- if savings is None:
3738
- # A failed refresh keeps the last good figures (they read as stale), never null them.
3739
- prior = _measure_facade._status_bar_read_cache(session_id)
3740
- if prior is not None and prior.get("savings") is not None:
3741
- return
3742
- tmp = path.with_name(f".{path.name}.{_measure_facade.os.getpid()}.tmp")
3743
- tmp.write_text(_measure_facade.json.dumps({
3744
- "schema": _measure_facade._STATUS_BAR_SCHEMA,
3745
- "computed_at": _measure_facade.time.time(),
3746
- "savings": savings,
3747
- "reason": reason,
3748
- }), encoding="utf-8")
3749
- _measure_facade.os.replace(tmp, path)
3750
- # Bound the directory: drop caches for sessions untouched for 30 days.
3751
- cutoff = _measure_facade.time.time() - _measure_facade._STATUS_BAR_CACHE_RETENTION_S
3752
- orphan_cutoff = _measure_facade.time.time() - 86400
3753
- try:
3754
- for f in d.iterdir():
3755
- try:
3756
- name = f.name
3757
- # Temp files and set-aside locks left by a crash go after a day.
3758
- orphan = name.endswith((".tmp", ".stale", ".release"))
3759
- if (orphan and f.stat().st_mtime < orphan_cutoff) or (
3760
- name.endswith(".json") and f.stat().st_mtime < cutoff):
3761
- f.unlink()
3762
- except OSError:
3763
- pass
3764
- except OSError:
3765
- pass
3733
+ from . import status_bar_refresh
3734
+ return status_bar_refresh.write_cache(_compat.facade(), session_id, savings, reason)
3766
3735
 
3767
3736
 
3768
3737
  def _status_bar_read_cache(session_id):
3769
- _measure_facade = _compat.facade()
3770
- try:
3771
- data = _measure_facade.json.loads(_measure_facade._status_bar_cache_path(session_id).read_text(encoding="utf-8"))
3772
- except (OSError, ValueError):
3773
- return None
3774
- if not isinstance(data, dict) or not isinstance(data.get("computed_at"), (int, float)):
3775
- return None
3776
- return data
3738
+ from . import status_bar_refresh
3739
+ return status_bar_refresh.read_cache(_compat.facade(), session_id)
3777
3740
 
3778
3741
 
3779
3742
  def _status_bar_start_refresh(session_id):
@@ -4153,6 +4116,7 @@ def status_bar_payload(session_id, transcript=None, sync=None):
4153
4116
  "savings": None,
4154
4117
  "savings_state": "unavailable",
4155
4118
  "savings_age_s": None,
4119
+ "savings_refresh_failed": False,
4156
4120
  "savings_reason": None,
4157
4121
  "refresh_started": False,
4158
4122
  "last_request_epoch": None,
@@ -4210,39 +4174,43 @@ def status_bar_payload(session_id, transcript=None, sync=None):
4210
4174
 
4211
4175
  try:
4212
4176
  if sync:
4213
- savings, reason = _measure_facade._status_bar_savings_or_reason(sid)
4214
- try:
4215
- _measure_facade._status_bar_write_cache(sid, savings, reason)
4216
- except OSError:
4217
- pass
4218
- out["savings"], out["savings_reason"] = savings, reason
4219
- out["savings_age_s"] = 0.0
4220
- out["savings_state"] = "fresh" if savings is not None else "unavailable"
4221
- return out
4222
- if not _measure_facade.Path(_measure_facade.TRENDS_DB).exists():
4177
+ from . import status_bar_refresh
4178
+ return status_bar_refresh.sync(_measure_facade, sid, out)
4179
+ cached = _measure_facade._status_bar_read_cache(sid)
4180
+ if cached is None and not _measure_facade.Path(_measure_facade.TRENDS_DB).exists():
4223
4181
  out["savings_reason"] = "no savings recorded yet"
4224
4182
  return out
4225
- cached = _measure_facade._status_bar_read_cache(sid)
4226
4183
  if cached is None:
4227
4184
  out["savings_state"] = "loading"
4228
4185
  out["savings_reason"] = "computing savings"
4229
4186
  out["refresh_started"] = _measure_facade._status_bar_start_refresh(sid)
4230
4187
  return out
4231
4188
  age = max(0.0, _measure_facade.time.time() - float(cached["computed_at"]))
4232
- out["savings"] = cached.get("savings")
4189
+ from . import status_bar_refresh
4190
+ out["savings"] = status_bar_refresh.for_session(_measure_facade, sid, cached.get("savings"))
4233
4191
  out["savings_reason"] = cached.get("reason") if out["savings"] is None else None
4234
4192
  out["savings_age_s"] = round(age, 1)
4235
- stale = age > _measure_facade._STATUS_BAR_CACHE_MAX_AGE_S
4193
+ out["savings_refresh_failed"] = bool(cached.get("refresh_failed", cached.get("stale")))
4194
+ db_exists = _measure_facade.Path(_measure_facade.TRENDS_DB).exists()
4195
+ # The cached "no savings" reason only means the database was missing at
4196
+ # that refresh; decide on the database as it is now, or it sticks forever.
4197
+ no_db_cached = cached.get("reason") == "no savings recorded yet"
4198
+ stale = bool(cached.get("stale")) or age > _measure_facade._STATUS_BAR_CACHE_MAX_AGE_S or not db_exists
4236
4199
  if out["savings"] is None:
4237
- out["savings_state"] = "unavailable"
4200
+ out["savings_state"] = "unavailable" if no_db_cached and not db_exists else "loading"
4201
+ if no_db_cached and db_exists:
4202
+ out["savings_reason"] = "computing savings"
4238
4203
  else:
4239
4204
  out["savings_state"] = "stale" if stale else "fresh"
4240
- if stale:
4205
+ if no_db_cached:
4206
+ start = db_exists
4207
+ else:
4208
+ start = stale and _measure_facade.time.time() - float(cached.get("last_attempt", 0)) >= status_bar_refresh.retry_delay(cached.get("failures", 0))
4209
+ if start:
4241
4210
  out["refresh_started"] = _measure_facade._status_bar_start_refresh(sid)
4242
4211
  except Exception:
4243
- out["savings"] = None
4244
- out["savings_state"] = "unavailable"
4245
- out["savings_reason"] = "savings unavailable"
4212
+ from . import status_bar_refresh
4213
+ out = status_bar_refresh.failed_payload(_measure_facade, sid, out)
4246
4214
  return out
4247
4215
 
4248
4216
 
@@ -4285,7 +4253,7 @@ def _status_bar_cli(args):
4285
4253
  # Killed by its budget: leave a reason for the band and free the lock.
4286
4254
  _measure_facade = _compat.facade()
4287
4255
  try:
4288
- _measure_facade._status_bar_write_cache(sid, None, "savings took too long to compute")
4256
+ _measure_facade._status_bar_write_cache(sid, None, "still counting savings")
4289
4257
  except OSError:
4290
4258
  pass
4291
4259
  _measure_facade._status_bar_release_lock(sid, token)
@@ -4295,8 +4263,8 @@ def _status_bar_cli(args):
4295
4263
  try:
4296
4264
  payload = _measure_facade.status_bar_payload(session, transcript=_opt("--transcript"), sync=sync)
4297
4265
  except Exception:
4298
- payload = {"schema": _measure_facade._STATUS_BAR_SCHEMA, "session_id": sid, "savings": None,
4299
- "savings_state": "unavailable", "savings_reason": "savings unavailable"}
4266
+ from . import status_bar_refresh
4267
+ payload = status_bar_refresh.failed_payload(_measure_facade, sid, {"schema": _measure_facade._STATUS_BAR_SCHEMA, "session_id": sid})
4300
4268
  finally:
4301
4269
  if token:
4302
4270
  _measure_facade._status_bar_release_lock(sid, token)
@@ -3461,13 +3461,10 @@ def _read_config_flag(key, default=None):
3461
3461
  cloud session whose home is fresh every time still sees the team's
3462
3462
  committed opt-outs. The user's own value always wins."""
3463
3463
  _measure_facade = _compat.facade()
3464
- try:
3465
- if _measure_facade.CONFIG_PATH.exists():
3466
- cfg = _measure_facade.json.loads(_measure_facade.CONFIG_PATH.read_text(encoding="utf-8"))
3467
- if isinstance(cfg, dict) and key in cfg:
3468
- return cfg[key]
3469
- except (_measure_facade.json.JSONDecodeError, OSError):
3470
- pass
3464
+ from . import config_cache
3465
+ cfg = {key: config_cache.current_tier()} if key == "pricing_tier" and config_cache.current_tier() is not None else config_cache.read(_measure_facade.CONFIG_PATH, _measure_facade.json)
3466
+ if key in cfg:
3467
+ return cfg[key]
3471
3468
  try:
3472
3469
  value = _measure_facade.project_config_value(key)
3473
3470
  if value is not None:
@@ -3534,6 +3531,8 @@ def _write_config_flag(key, value):
3534
3531
  _measure_facade.json.dump(cfg, f, indent=2)
3535
3532
  f.write("\n")
3536
3533
  _measure_facade.os.replace(tmp_path, str(_measure_facade.CONFIG_PATH))
3534
+ from . import config_cache
3535
+ config_cache.clear()
3537
3536
  tmp_path = None
3538
3537
  except OSError:
3539
3538
  pass
@@ -3321,11 +3321,11 @@ def _estimate_cache_drop_savings(days=None):
3321
3321
  OPPORTUNITY tier: rebuilds that already happened, avoidable by resuming
3322
3322
  inside the TTL. Never summed into the realized total.
3323
3323
  """
3324
- _measure_facade = _compat.facade()
3324
+ _measure_facade = _compat.facade(); from . import config_cache
3325
3325
  zero = {"drop_sessions": 0, "est_drops": 0, "prefix_tokens": 0, "rebuilt_tokens": 0,
3326
3326
  "ttl_seconds": None, "cost_saved_usd": 0.0, "evidence": "opportunity"}
3327
3327
  try:
3328
- health = _measure_facade._cache_ttl_waste_cached(days=days) or {}
3328
+ health = {} if config_cache.cache_scan_skipped() else (_measure_facade._cache_ttl_waste_cached(days=days) or {})
3329
3329
  rebuild = health.get("rebuild") or {}
3330
3330
  events = int(rebuild.get("events", 0) or 0)
3331
3331
  tokens = int(rebuild.get("tokens", 0) or 0)
@@ -0,0 +1,99 @@
1
+ """Persist first-call observations without storing transcript text or paths."""
2
+ import hashlib
3
+ import json
4
+ import os
5
+ import time
6
+ import uuid
7
+ from pathlib import Path
8
+
9
+ from . import first_call_context, setup_step
10
+
11
+
12
+ class Cache:
13
+ def __init__(self, data_dir):
14
+ self.path = Path(data_dir) / 'setup-observations-v1.json'
15
+ self.entries = {}
16
+ self.dirty = False
17
+ self.pending = 0
18
+ try:
19
+ self.version = _version()
20
+ except OSError:
21
+ self.version = None
22
+ try:
23
+ data = json.loads(self.path.read_text(encoding='utf-8'))
24
+ if self.version is not None and data.get('version') == self.version and isinstance(data.get('entries'), dict):
25
+ self.entries = data.get('entries', {})
26
+ except (OSError, ValueError, TypeError, AttributeError):
27
+ pass
28
+ try:
29
+ for tmp in self.path.parent.glob('.setup-observations-v1.json.*.tmp'):
30
+ if time.time() - tmp.stat().st_mtime > 86400:
31
+ tmp.unlink()
32
+ except OSError:
33
+ pass
34
+
35
+ def observe(self, path):
36
+ path = Path(path)
37
+ key = hashlib.sha256(os.fsencode(str(path))).hexdigest()
38
+ try:
39
+ stat = path.stat()
40
+ signature = [stat.st_size, stat.st_mtime_ns]
41
+ entry = self.entries.get(key)
42
+ if isinstance(entry, dict) and 'observation' in entry and entry.get('signature') == signature and _valid(entry['observation']):
43
+ return entry.get('observation')
44
+ observation = setup_step.observe_step(first_call_context.transcript(path), lambda v: round(len(v) / 4))
45
+ after = path.stat()
46
+ if signature == [after.st_size, after.st_mtime_ns] and time.time_ns() - after.st_mtime_ns >= 2_000_000_000:
47
+ self.entries[key] = {'signature': signature, 'observation': observation}
48
+ self.dirty = True
49
+ self.pending += 1
50
+ if self.pending >= 200:
51
+ self.save()
52
+ return observation
53
+ except (OSError, ValueError, TypeError):
54
+ if key in self.entries:
55
+ del self.entries[key]
56
+ self.dirty = True
57
+ return None
58
+
59
+ def save(self):
60
+ if not self.dirty or self.version is None:
61
+ return
62
+ tmp = self.path.with_name('.%s.%s.tmp' % (self.path.name, uuid.uuid4().hex))
63
+ try:
64
+ tmp.write_text(json.dumps({'version': self.version, 'entries': self.entries}), encoding='utf-8')
65
+ for attempt in range(3):
66
+ try:
67
+ os.replace(tmp, self.path)
68
+ break
69
+ except PermissionError:
70
+ if attempt == 2:
71
+ raise
72
+ time.sleep(.02 * (attempt + 1))
73
+ self.dirty = False
74
+ self.pending = 0
75
+ except OSError:
76
+ pass
77
+ finally:
78
+ try:
79
+ tmp.unlink(missing_ok=True)
80
+ except OSError:
81
+ pass
82
+
83
+
84
+ def _valid(observation):
85
+ if observation is None:
86
+ return True
87
+ return (isinstance(observation, dict) and isinstance(observation.get('month'), str)
88
+ and isinstance(observation.get('total'), int) and isinstance(observation.get('components'), dict)
89
+ and all(isinstance(k, str) and isinstance(v, int) for k, v in observation['components'].items())
90
+ and isinstance(observation.get('ts'), str)
91
+ and (observation.get('model') is None or isinstance(observation.get('model'), str)))
92
+
93
+
94
+ def _version():
95
+ files = [Path(first_call_context.__file__), Path(setup_step.__file__)]
96
+ stamps = [hashlib.sha256(p.read_bytes()).hexdigest() for p in files]
97
+ commands = sorted(first_call_context._optimizer_commands())
98
+ digest = hashlib.sha256(json.dumps(commands).encode('utf-8')).hexdigest()
99
+ return {'schema': 1, 'estimator': 'round(len/4)', 'commands': digest, 'code': stamps}
@@ -183,7 +183,7 @@ def measured_epochs(db_path, data_dir, claude_dir=None, card_fn=None):
183
183
 
184
184
  def collect(db_path, data_dir, claude_dir=None, card_fn=None, keep_carried=False):
185
185
  """Steps for every dated trim, from the user's own ledger and transcripts. Read-only."""
186
- from . import first_call_context, structural_ledger as ledger
186
+ from . import setup_observation_cache, structural_ledger as ledger
187
187
  path = Path(db_path) if db_path else None
188
188
  if path is None or not path.is_file():
189
189
  return {"available": False, "why": "no ledger"}
@@ -201,15 +201,14 @@ def collect(db_path, data_dir, claude_dir=None, card_fn=None, keep_carried=False
201
201
  with sqlite3.connect(path.resolve().as_uri() + "?mode=ro", uri=True, timeout=1.0) as conn:
202
202
  rows = conn.execute("SELECT DISTINCT jsonl_path, api_calls FROM session_log "
203
203
  "WHERE jsonl_path IS NOT NULL AND COALESCE(is_sidechain,0)=0").fetchall()
204
+ cache = setup_observation_cache.Cache(data_dir)
204
205
  for name, api_calls in rows:
205
- try:
206
- obs = observe_step(first_call_context.transcript(Path(name)), lambda v: round(len(v) / 4))
207
- except (OSError, ValueError, TypeError):
208
- continue
206
+ obs = cache.observe(name)
209
207
  epoch = ledger.to_epoch(obs.get("ts")) if obs else None
210
208
  if obs and epoch is not None:
211
209
  sessions.append({"ts_epoch": epoch, "total": obs["total"], "components": obs["components"],
212
210
  "api_calls": api_calls, "model": obs.get("model")})
211
+ cache.save()
213
212
  rate_fn = None
214
213
  if card_fn is not None:
215
214
  def rate_fn(model):