@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
|
@@ -107,6 +107,16 @@ def codemap_enabled() -> bool:
|
|
|
107
107
|
return False
|
|
108
108
|
|
|
109
109
|
|
|
110
|
+
def codemap_hint_enabled() -> bool:
|
|
111
|
+
if not codemap_enabled():
|
|
112
|
+
return False
|
|
113
|
+
try:
|
|
114
|
+
from plugin_env import is_v5_flag_enabled
|
|
115
|
+
return is_v5_flag_enabled("v5_codemap_hint", "TOKEN_OPTIMIZER_CODEMAP_HINT", default=False)
|
|
116
|
+
except Exception:
|
|
117
|
+
return False
|
|
118
|
+
|
|
119
|
+
|
|
110
120
|
def reread_outline_enabled() -> bool:
|
|
111
121
|
if not codemap_enabled():
|
|
112
122
|
return False
|
|
@@ -148,7 +158,7 @@ def index_dir() -> Path:
|
|
|
148
158
|
|
|
149
159
|
def index_path(root: Path) -> Path:
|
|
150
160
|
digest = hashlib.sha256(str(root).encode("utf-8", "replace")).hexdigest()[:16]
|
|
151
|
-
return index_dir() / f"{digest}.db"
|
|
161
|
+
return index_dir() / f"{digest}-bounded-v1.db"
|
|
152
162
|
|
|
153
163
|
|
|
154
164
|
# --------------------------------------------------------------------------- #
|
|
@@ -365,6 +375,14 @@ def parse_file(path: Path, root: Path, source: Optional[str] = None) -> FileFact
|
|
|
365
375
|
# Store
|
|
366
376
|
# --------------------------------------------------------------------------- #
|
|
367
377
|
|
|
378
|
+
class IncompleteSweep(Exception):
|
|
379
|
+
"""The source sweep ran out of time."""
|
|
380
|
+
|
|
381
|
+
|
|
382
|
+
class CappedSweep(Exception):
|
|
383
|
+
"""The source sweep reached its file limit."""
|
|
384
|
+
|
|
385
|
+
|
|
368
386
|
def _iter_source_files(root: Path, deadline: float) -> Iterator[Path]:
|
|
369
387
|
count = 0
|
|
370
388
|
for dirpath, dirnames, filenames in os.walk(root, followlinks=False):
|
|
@@ -375,8 +393,10 @@ def _iter_source_files(root: Path, deadline: float) -> Iterator[Path]:
|
|
|
375
393
|
if fn.endswith((".min.js", ".bundle.js", ".d.ts")):
|
|
376
394
|
continue
|
|
377
395
|
count += 1
|
|
378
|
-
if
|
|
379
|
-
|
|
396
|
+
if time.monotonic() > deadline:
|
|
397
|
+
raise IncompleteSweep()
|
|
398
|
+
if count > MAX_FILES:
|
|
399
|
+
raise CappedSweep()
|
|
380
400
|
yield Path(dirpath) / fn
|
|
381
401
|
|
|
382
402
|
|
|
@@ -388,6 +408,9 @@ class CodeIndex:
|
|
|
388
408
|
self.conn = conn
|
|
389
409
|
self.db_path = db_path
|
|
390
410
|
self.complete = False
|
|
411
|
+
self.capped = False
|
|
412
|
+
self.readonly = False
|
|
413
|
+
self.stale = False
|
|
391
414
|
|
|
392
415
|
@classmethod
|
|
393
416
|
def open(cls, root: str | os.PathLike[str], db_path: Optional[Path] = None) -> "CodeIndex":
|
|
@@ -523,6 +546,7 @@ class CodeIndex:
|
|
|
523
546
|
seen = set()
|
|
524
547
|
stats = {"parsed": 0, "unchanged": 0, "removed": 0}
|
|
525
548
|
timed_out = False
|
|
549
|
+
self.capped = False
|
|
526
550
|
try:
|
|
527
551
|
for p in _iter_source_files(self.root, deadline):
|
|
528
552
|
rel = _rel(self.root, p)
|
|
@@ -548,11 +572,18 @@ class CodeIndex:
|
|
|
548
572
|
break
|
|
549
573
|
else:
|
|
550
574
|
timed_out = time.monotonic() > deadline
|
|
575
|
+
except IncompleteSweep:
|
|
576
|
+
timed_out = True
|
|
577
|
+
except CappedSweep:
|
|
578
|
+
self.capped = True
|
|
579
|
+
try:
|
|
551
580
|
if not timed_out:
|
|
552
581
|
for rel in set(known) - seen:
|
|
553
582
|
self._drop(rel)
|
|
554
583
|
stats["removed"] += 1
|
|
555
584
|
self.complete = not timed_out
|
|
585
|
+
self.conn.execute("INSERT OR REPLACE INTO meta VALUES('capped', ?)",
|
|
586
|
+
("1" if self.capped and not timed_out else "0",))
|
|
556
587
|
self.conn.execute("INSERT OR REPLACE INTO meta VALUES('complete', ?)",
|
|
557
588
|
("1" if self.complete else "0",))
|
|
558
589
|
self.conn.commit()
|
|
@@ -639,16 +670,74 @@ class CodeIndex:
|
|
|
639
670
|
def open_synced(start: str | os.PathLike[str], budget_s: Optional[float] = None) -> CodeIndex:
|
|
640
671
|
"""Open (building lazily) and sync the index for the project containing ``start``."""
|
|
641
672
|
root = find_project_root(start)
|
|
642
|
-
idx =
|
|
673
|
+
idx = None
|
|
643
674
|
try:
|
|
675
|
+
idx = CodeIndex.open(root)
|
|
644
676
|
idx.sync(budget_s)
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
677
|
+
return idx
|
|
678
|
+
except Exception as write_error:
|
|
679
|
+
if idx is not None:
|
|
680
|
+
idx.close()
|
|
681
|
+
db = index_path(root)
|
|
682
|
+
# Normal read-only mode can see WAL data when its sidecars are accessible.
|
|
683
|
+
# Immutable is a last resort for a snapshot whose WAL cannot be opened.
|
|
684
|
+
uri = db.resolve().as_uri() + "?mode=ro"
|
|
685
|
+
conn = None
|
|
686
|
+
immutable = False
|
|
687
|
+
try:
|
|
688
|
+
try:
|
|
689
|
+
conn = sqlite3.connect(uri, uri=True, timeout=3.0)
|
|
690
|
+
conn.execute("SELECT v FROM meta WHERE k='schema'").fetchone()
|
|
691
|
+
except sqlite3.Error:
|
|
692
|
+
try:
|
|
693
|
+
conn.close()
|
|
694
|
+
except (AttributeError, UnboundLocalError):
|
|
695
|
+
pass
|
|
696
|
+
conn = sqlite3.connect(uri + "&immutable=1", uri=True, timeout=3.0)
|
|
697
|
+
immutable = True
|
|
698
|
+
idx = CodeIndex(root, conn, db)
|
|
699
|
+
version = conn.execute("SELECT v FROM meta WHERE k='schema'").fetchone()
|
|
700
|
+
if not version or version[0] != SCHEMA_VERSION:
|
|
701
|
+
raise CodemapError("read-only index schema mismatch")
|
|
702
|
+
row = conn.execute("SELECT v FROM meta WHERE k='complete'").fetchone()
|
|
703
|
+
idx.complete = bool(row and row[0] == "1")
|
|
704
|
+
capped = conn.execute("SELECT v FROM meta WHERE k='capped'").fetchone()
|
|
705
|
+
idx.capped = bool(capped and capped[0] == "1")
|
|
706
|
+
idx.readonly = True
|
|
707
|
+
idx.stale = immutable
|
|
708
|
+
known = {r[0]: (r[1], r[2]) for r in conn.execute("SELECT path, mtime_ns, size FROM files")}
|
|
709
|
+
seen = set()
|
|
710
|
+
try:
|
|
711
|
+
for path in _iter_source_files(root, time.monotonic() + SWEEP_BUDGET_S):
|
|
712
|
+
rel = _rel(root, path)
|
|
713
|
+
if rel is None:
|
|
714
|
+
continue
|
|
715
|
+
seen.add(rel)
|
|
716
|
+
try:
|
|
717
|
+
st = path.stat()
|
|
718
|
+
if known.get(rel) != (st.st_mtime_ns, st.st_size):
|
|
719
|
+
idx.stale = True
|
|
720
|
+
except OSError:
|
|
721
|
+
idx.stale = True
|
|
722
|
+
except CappedSweep:
|
|
723
|
+
if not idx.capped:
|
|
724
|
+
idx.stale = True
|
|
725
|
+
except IncompleteSweep:
|
|
726
|
+
idx.stale = True
|
|
727
|
+
idx.stale = idx.stale or seen != set(known)
|
|
728
|
+
return idx
|
|
729
|
+
except Exception as read_error:
|
|
730
|
+
if idx is not None:
|
|
731
|
+
idx.close()
|
|
732
|
+
elif conn is not None:
|
|
733
|
+
conn.close()
|
|
734
|
+
if isinstance(read_error, CodemapError):
|
|
735
|
+
raise read_error
|
|
736
|
+
cause = read_error if isinstance(read_error, sqlite3.Error) else write_error
|
|
737
|
+
while cause.__cause__ is not None:
|
|
738
|
+
cause = cause.__cause__
|
|
739
|
+
code = getattr(cause, "sqlite_errorname", "unavailable")
|
|
740
|
+
raise CodemapError(f"query failed at open/sync (SQLite {code}; data dir {db.parent.name})") from read_error
|
|
652
741
|
|
|
653
742
|
|
|
654
743
|
def symbols_in(text: str) -> Sequence[str]:
|
|
@@ -36,6 +36,9 @@ PENDING_MAX_PATHS = 400
|
|
|
36
36
|
_PENDING_NAME = "pending.json"
|
|
37
37
|
|
|
38
38
|
_SCHEMA = """
|
|
39
|
+
CREATE TABLE IF NOT EXISTS codemap_failures (
|
|
40
|
+
id INTEGER PRIMARY KEY, ts_epoch REAL NOT NULL, stage TEXT, code TEXT
|
|
41
|
+
);
|
|
39
42
|
CREATE TABLE IF NOT EXISTS codemap_events (
|
|
40
43
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
41
44
|
timestamp TEXT NOT NULL,
|
|
@@ -85,9 +88,35 @@ def _connect() -> sqlite3.Connection:
|
|
|
85
88
|
conn = sqlite3.connect(str(db), timeout=3.0)
|
|
86
89
|
conn.execute("PRAGMA busy_timeout=3000")
|
|
87
90
|
conn.executescript(_SCHEMA)
|
|
91
|
+
columns = {row[1] for row in conn.execute("PRAGMA table_info(codemap_failures)")}
|
|
92
|
+
for column in ("stage", "code"):
|
|
93
|
+
if column not in columns:
|
|
94
|
+
conn.execute(f"ALTER TABLE codemap_failures ADD COLUMN {column} TEXT")
|
|
88
95
|
return conn
|
|
89
96
|
|
|
90
97
|
|
|
98
|
+
def log_failure(stage: str = "lookup", code: str = "unknown") -> None:
|
|
99
|
+
"""Count failed attempts independently of the savings ledger."""
|
|
100
|
+
conn = _connect()
|
|
101
|
+
try:
|
|
102
|
+
conn.execute("INSERT INTO codemap_failures (ts_epoch, stage, code) VALUES (?, ?, ?)",
|
|
103
|
+
(time.time(), stage[:32], code[:64]))
|
|
104
|
+
conn.commit()
|
|
105
|
+
finally:
|
|
106
|
+
conn.close()
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def failure_count() -> int:
|
|
110
|
+
try:
|
|
111
|
+
conn = _connect()
|
|
112
|
+
try:
|
|
113
|
+
return int(conn.execute("SELECT COUNT(*) FROM codemap_failures").fetchone()[0])
|
|
114
|
+
finally:
|
|
115
|
+
conn.close()
|
|
116
|
+
except Exception:
|
|
117
|
+
return 0
|
|
118
|
+
|
|
119
|
+
|
|
91
120
|
def _read_pending() -> Dict:
|
|
92
121
|
try:
|
|
93
122
|
raw = _pending_path().read_text(encoding="utf-8")
|
|
@@ -73,7 +73,7 @@ _MEASURE_PACKAGE_FILES = (
|
|
|
73
73
|
)
|
|
74
74
|
_MEASURE_PACKAGE_FILES += ('_measure/transcript_stream.py', '_measure/checkpoint_direction.py', '_measure/checkpoint_retention.py')
|
|
75
75
|
_MEASURE_PACKAGE_FILES += ('_measure/keepwarm_safety.py', '_measure/keepwarm_economics.py', '_measure/keepwarm_linux.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',)
|
|
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', '_measure/config_cache.py', '_measure/setup_observation_cache.py', '_measure/status_bar_refresh.py',)
|
|
77
77
|
|
|
78
78
|
|
|
79
79
|
def _repo_root() -> Path:
|
|
@@ -363,7 +363,7 @@ _MEASURE_PACKAGE_FILES = (
|
|
|
363
363
|
)
|
|
364
364
|
_MEASURE_PACKAGE_FILES += ('_measure/transcript_stream.py', '_measure/checkpoint_direction.py', '_measure/checkpoint_retention.py')
|
|
365
365
|
_MEASURE_PACKAGE_FILES += ('_measure/keepwarm_safety.py', '_measure/keepwarm_economics.py', '_measure/keepwarm_linux.py', '_measure/mod_action_booking.py', '_measure/mod_compaction_booking.py', '_measure/mod_fresh_booking.py',)
|
|
366
|
-
_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',)
|
|
366
|
+
_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', '_measure/config_cache.py', '_measure/setup_observation_cache.py', '_measure/status_bar_refresh.py',)
|
|
367
367
|
|
|
368
368
|
|
|
369
369
|
def _engine_checks() -> list[dict[str, str]]:
|
|
@@ -106,7 +106,7 @@ _MEASURE_PACKAGE_FILES = (
|
|
|
106
106
|
)
|
|
107
107
|
_MEASURE_PACKAGE_FILES += ('_measure/transcript_stream.py', '_measure/checkpoint_direction.py', '_measure/checkpoint_retention.py')
|
|
108
108
|
_MEASURE_PACKAGE_FILES += ('_measure/keepwarm_safety.py', '_measure/keepwarm_economics.py', '_measure/keepwarm_linux.py', '_measure/mod_action_booking.py', '_measure/mod_compaction_booking.py', '_measure/mod_fresh_booking.py',)
|
|
109
|
-
_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',)
|
|
109
|
+
_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', '_measure/config_cache.py', '_measure/setup_observation_cache.py', '_measure/status_bar_refresh.py',)
|
|
110
110
|
|
|
111
111
|
|
|
112
112
|
def _scripts_dir() -> Path:
|
|
@@ -193,18 +193,31 @@ function _statusBarSessionKey(sessionId) {
|
|
|
193
193
|
return sid.slice(0, 64) + '-' + hash;
|
|
194
194
|
}
|
|
195
195
|
|
|
196
|
+
// Cache files that can hold the headline in one status-bar dir. measure.py
|
|
197
|
+
// writes the shared 30-day figure to global.json (or global-pending-*.json when
|
|
198
|
+
// global.json is locked). The per-session <key>.json is the pre-upgrade layout,
|
|
199
|
+
// read only so the number shows before the first refresh after an upgrade.
|
|
200
|
+
function _statusBarCacheFiles(dir, key) {
|
|
201
|
+
const files = [path.join(dir, 'global.json')];
|
|
202
|
+
try {
|
|
203
|
+
for (const name of fs.readdirSync(dir)) {
|
|
204
|
+
if (name.startsWith('global-pending-') && name.endsWith('.json')) files.push(path.join(dir, name));
|
|
205
|
+
}
|
|
206
|
+
} catch (e) {}
|
|
207
|
+
if (key && key !== 'unknown' && key !== 'global') files.push(path.join(dir, key + '.json'));
|
|
208
|
+
return files;
|
|
209
|
+
}
|
|
210
|
+
|
|
196
211
|
// The freshest status-bar cache's savings_headline.display, or null.
|
|
197
|
-
// Freshness is decided on computed_at across all candidate
|
|
212
|
+
// Freshness is decided on computed_at across all candidate files BEFORE
|
|
198
213
|
// reading display, so a newer "below threshold" cache correctly hides an
|
|
199
214
|
// older number that no longer applies.
|
|
200
215
|
function _statusBarHeadlineDisplay(sessionId) {
|
|
201
216
|
try {
|
|
202
217
|
const key = _statusBarSessionKey(sessionId);
|
|
203
|
-
if (!key || key === 'unknown') return null;
|
|
204
218
|
let best = null, bestTs = -1;
|
|
205
219
|
for (const dir of _statusBarDirs()) {
|
|
206
|
-
try {
|
|
207
|
-
const file = path.join(dir, key + '.json');
|
|
220
|
+
for (const file of _statusBarCacheFiles(dir, key)) try {
|
|
208
221
|
const raw = fs.readFileSync(file, 'utf8');
|
|
209
222
|
const data = JSON.parse(raw);
|
|
210
223
|
if (!data || typeof data !== 'object') continue;
|