@alexgreensh/token-optimizer 5.13.62 → 5.13.64
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/sessionstart_runner.py +25 -4
- package/package.json +1 -1
- package/skills/fleet-auditor/SKILL.md +1 -1
- package/skills/fleet-auditor/scripts/fleet.py +4 -1
- package/skills/fleet-auditor/scripts/shared.py +31 -14
- package/skills/token-coach/SKILL.md +49 -40
- package/skills/token-coach/references/deterministic-stages.md +1 -1
- package/skills/token-coach/references/keepwarm-consent.md +7 -7
- package/skills/token-dashboard/SKILL.md +30 -6
- package/skills/token-optimizer/SKILL.md +42 -44
- package/skills/token-optimizer/assets/dashboard.html +571 -106
- package/skills/token-optimizer/references/agent-prompts.md +4 -1
- package/skills/token-optimizer/references/codex-workflow.md +30 -12
- package/skills/token-optimizer/references/cursor-workflow.md +9 -7
- package/skills/token-optimizer/references/implementation-playbook.md +4 -4
- package/skills/token-optimizer/references/keepwarm-consent.md +7 -7
- package/skills/token-optimizer/references/opencode-workflow.md +4 -2
- package/skills/token-optimizer/references/optimization-checklist.md +9 -9
- package/skills/token-optimizer/references/phase0-setup.md +9 -9
- package/skills/token-optimizer/references/presentation-workflow.md +3 -3
- package/skills/token-optimizer/references/session-continuity.md +1 -1
- package/skills/token-optimizer/references/token-flow-architecture.md +2 -1
- package/skills/token-optimizer/scripts/adapter_hook_command.py +94 -0
- package/skills/token-optimizer/scripts/antigravity_doctor.py +12 -0
- package/skills/token-optimizer/scripts/antigravity_hook_bridge.py +4 -0
- package/skills/token-optimizer/scripts/antigravity_install.py +9 -18
- package/skills/token-optimizer/scripts/antigravity_session.py +31 -6
- package/skills/token-optimizer/scripts/archive_result.py +6 -1
- package/skills/token-optimizer/scripts/archive_window.py +274 -0
- package/skills/token-optimizer/scripts/checkpoint_state.py +385 -0
- package/skills/token-optimizer/scripts/codex_install.py +5 -3
- package/skills/token-optimizer/scripts/codex_session.py +149 -1
- package/skills/token-optimizer/scripts/cursor_doctor.py +12 -27
- package/skills/token-optimizer/scripts/cursor_install.py +11 -19
- package/skills/token-optimizer/scripts/devin_source.py +3 -3
- package/skills/token-optimizer/scripts/grok_doctor.py +12 -24
- package/skills/token-optimizer/scripts/grok_install.py +9 -16
- package/skills/token-optimizer/scripts/measure.py +7300 -1642
- package/skills/token-optimizer/scripts/read_cache.py +52 -27
- package/skills/token-optimizer/scripts/recovery_output.py +67 -18
- package/skills/token-optimizer/scripts/refetch_guard.py +9 -3
- package/skills/token-optimizer/scripts/session_activity.py +169 -0
- package/skills/token-optimizer/scripts/session_store.py +127 -9
- package/skills/token-optimizer/scripts/statusline.js +4 -6
|
@@ -24,6 +24,7 @@ Configuration:
|
|
|
24
24
|
|
|
25
25
|
from __future__ import annotations
|
|
26
26
|
|
|
27
|
+
import hashlib
|
|
27
28
|
import json
|
|
28
29
|
import re
|
|
29
30
|
import sqlite3
|
|
@@ -38,6 +39,11 @@ SNAPSHOT_DIR = resolve_snapshot_dir()
|
|
|
38
39
|
SESSION_STORE_DIR = SNAPSHOT_DIR / "session-store"
|
|
39
40
|
|
|
40
41
|
MAX_DB_SIZE_BYTES = 50 * 1024 * 1024 # 50MB cap
|
|
42
|
+
# tool_outputs.output_text is a search index copy, not the recovery source (the
|
|
43
|
+
# archive sidecar keeps the full redacted body). Bound it so a few multi-MB
|
|
44
|
+
# archives cannot fill the 50MB session DB and pause every later write.
|
|
45
|
+
MAX_TOOL_OUTPUT_INDEX_BYTES = 256 * 1024
|
|
46
|
+
_INDEX_TRUNCATED_MARKER = "\n[... index truncated ...]\n"
|
|
41
47
|
CLEANUP_AGE_HOURS = 48
|
|
42
48
|
|
|
43
49
|
# v2: added tool_outputs lineage columns + the FTS5 archive index, and
|
|
@@ -76,7 +82,9 @@ CREATE TABLE IF NOT EXISTS tool_outputs (
|
|
|
76
82
|
source_file_path TEXT,
|
|
77
83
|
language TEXT,
|
|
78
84
|
archived_from TEXT,
|
|
79
|
-
output_text TEXT
|
|
85
|
+
output_text TEXT,
|
|
86
|
+
truncated INTEGER,
|
|
87
|
+
index_truncated INTEGER
|
|
80
88
|
);
|
|
81
89
|
|
|
82
90
|
CREATE TABLE IF NOT EXISTS command_outputs (
|
|
@@ -162,6 +170,27 @@ def _sanitize_session_id(sid: str) -> str:
|
|
|
162
170
|
return sid
|
|
163
171
|
|
|
164
172
|
|
|
173
|
+
def _bound_tool_output_index(text: Optional[str]):
|
|
174
|
+
"""Bound ``output_text`` to a head+tail search index.
|
|
175
|
+
|
|
176
|
+
Returns ``(index_text, index_truncated)``. The full redacted body still lives
|
|
177
|
+
in the archive sidecar; this column only feeds FTS/LIKE search, so keeping a
|
|
178
|
+
bounded head and tail preserves findability without letting a few multi-MB
|
|
179
|
+
outputs fill the per-session database cap.
|
|
180
|
+
"""
|
|
181
|
+
if text is None:
|
|
182
|
+
return None, 0
|
|
183
|
+
raw = text.encode("utf-8", "replace")
|
|
184
|
+
if len(raw) <= MAX_TOOL_OUTPUT_INDEX_BYTES:
|
|
185
|
+
return text, 0
|
|
186
|
+
marker = _INDEX_TRUNCATED_MARKER.encode("utf-8")
|
|
187
|
+
head_budget = MAX_TOOL_OUTPUT_INDEX_BYTES // 2
|
|
188
|
+
tail_budget = MAX_TOOL_OUTPUT_INDEX_BYTES - head_budget - len(marker)
|
|
189
|
+
head = raw[:head_budget].decode("utf-8", "ignore")
|
|
190
|
+
tail = raw[len(raw) - tail_budget:].decode("utf-8", "ignore") if tail_budget > 0 else ""
|
|
191
|
+
return head + _INDEX_TRUNCATED_MARKER + tail, 1
|
|
192
|
+
|
|
193
|
+
|
|
165
194
|
class SessionStore:
|
|
166
195
|
"""Per-session SQLite store for tool output caching."""
|
|
167
196
|
|
|
@@ -276,10 +305,17 @@ class SessionStore:
|
|
|
276
305
|
cols = {r[1] for r in conn.execute("PRAGMA table_info(tool_outputs)").fetchall()}
|
|
277
306
|
except sqlite3.DatabaseError:
|
|
278
307
|
return
|
|
279
|
-
for col in (
|
|
308
|
+
for col, decl in (
|
|
309
|
+
("source_file_path", "TEXT"),
|
|
310
|
+
("language", "TEXT"),
|
|
311
|
+
("archived_from", "TEXT"),
|
|
312
|
+
("output_text", "TEXT"),
|
|
313
|
+
("truncated", "INTEGER"),
|
|
314
|
+
("index_truncated", "INTEGER"),
|
|
315
|
+
):
|
|
280
316
|
if col not in cols:
|
|
281
317
|
try:
|
|
282
|
-
conn.execute(f"ALTER TABLE tool_outputs ADD COLUMN {col}
|
|
318
|
+
conn.execute(f"ALTER TABLE tool_outputs ADD COLUMN {col} {decl}")
|
|
283
319
|
except sqlite3.OperationalError:
|
|
284
320
|
pass
|
|
285
321
|
|
|
@@ -575,6 +611,31 @@ class SessionStore:
|
|
|
575
611
|
conn.execute("DELETE FROM file_reads")
|
|
576
612
|
conn.commit()
|
|
577
613
|
|
|
614
|
+
def reset_context_state(self) -> None:
|
|
615
|
+
"""Forget everything that records what the model currently holds.
|
|
616
|
+
|
|
617
|
+
A /clear or a compaction empties the model's context while the session
|
|
618
|
+
id (and so this store) lives on. Every record that later lets a hook say
|
|
619
|
+
"you already have this" must go with it: the read ledger, the delta-read
|
|
620
|
+
baselines, the cross-turn command outputs, the repeat-command streaks, the
|
|
621
|
+
served-hint ledger and the first-read skeleton markers. Nothing here is a
|
|
622
|
+
recovery source: the tool-output archive, activity log, compaction
|
|
623
|
+
cursor and decision notes stay, because they describe the session, not
|
|
624
|
+
the context window. One transaction, so a lock failure leaves the old
|
|
625
|
+
state intact rather than half-cleared.
|
|
626
|
+
"""
|
|
627
|
+
conn = self._connect()
|
|
628
|
+
with conn:
|
|
629
|
+
conn.execute("DELETE FROM file_reads")
|
|
630
|
+
conn.execute("DELETE FROM cached_content")
|
|
631
|
+
conn.execute("DELETE FROM command_outputs")
|
|
632
|
+
conn.execute("DELETE FROM command_run_streaks")
|
|
633
|
+
conn.execute("DELETE FROM hint_serves")
|
|
634
|
+
conn.execute(
|
|
635
|
+
"DELETE FROM session_meta WHERE key GLOB 'shadow_fr:*' "
|
|
636
|
+
"OR key GLOB 'active_fr:*'"
|
|
637
|
+
)
|
|
638
|
+
|
|
578
639
|
# ----- cached_content -----
|
|
579
640
|
|
|
580
641
|
def get_cached_content(self, file_path: str) -> Optional[dict[str, Any]]:
|
|
@@ -623,23 +684,27 @@ class SessionStore:
|
|
|
623
684
|
language: Optional[str] = None,
|
|
624
685
|
archived_from: Optional[str] = None,
|
|
625
686
|
output_text: Optional[str] = None,
|
|
687
|
+
truncated: Optional[int] = None,
|
|
626
688
|
) -> None:
|
|
627
689
|
if self._is_over_size_cap():
|
|
628
690
|
return
|
|
691
|
+
index_text, index_truncated = _bound_tool_output_index(output_text)
|
|
629
692
|
conn = self._connect()
|
|
630
693
|
conn.execute(
|
|
631
694
|
"""INSERT OR IGNORE INTO tool_outputs
|
|
632
695
|
(tool_use_id, tool_name, tool_type, command_or_path,
|
|
633
696
|
output_hash, output_chars, output_tokens_est,
|
|
634
697
|
compressed_preview, timestamp,
|
|
635
|
-
source_file_path, language, archived_from, output_text
|
|
636
|
-
|
|
698
|
+
source_file_path, language, archived_from, output_text,
|
|
699
|
+
truncated, index_truncated)
|
|
700
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
637
701
|
""",
|
|
638
702
|
(
|
|
639
703
|
tool_use_id, tool_name, tool_type, command_or_path,
|
|
640
704
|
output_hash, output_chars, output_tokens_est,
|
|
641
705
|
compressed_preview, time.time(),
|
|
642
|
-
source_file_path, language, archived_from,
|
|
706
|
+
source_file_path, language, archived_from, index_text,
|
|
707
|
+
truncated, index_truncated,
|
|
643
708
|
),
|
|
644
709
|
)
|
|
645
710
|
# fix-1: the external-content FTS mirror is maintained by the AFTER
|
|
@@ -651,9 +716,10 @@ class SessionStore:
|
|
|
651
716
|
# ----- tool_outputs search (U6: FTS5 with LIKE fallback) -----
|
|
652
717
|
|
|
653
718
|
def search_tool_outputs(self, query: str, limit: int = 20) -> list[dict[str, Any]]:
|
|
654
|
-
"""Full-text search over archived tool outputs Returns rows
|
|
655
|
-
|
|
656
|
-
|
|
719
|
+
"""Full-text search over archived tool outputs Returns rows carrying
|
|
720
|
+
(tool_use_id, tool_name, command_or_path, source_file_path, language,
|
|
721
|
+
archived_from, output_hash, output_chars, timestamp, truncated,
|
|
722
|
+
index_truncated, snippet) ranked by relevance. Uses FTS5 ``bm25()`` when available; falls back to a
|
|
657
723
|
bounded ``LIKE '%term%'`` query over the lineage + output_text
|
|
658
724
|
columns when FTS5 is not compiled into SQLite. Never raises: an
|
|
659
725
|
empty/invalid query or a missing index returns an empty list.
|
|
@@ -667,6 +733,8 @@ class SessionStore:
|
|
|
667
733
|
rows = conn.execute(
|
|
668
734
|
"""SELECT t.tool_use_id, t.tool_name, t.command_or_path,
|
|
669
735
|
t.source_file_path, t.language, t.archived_from,
|
|
736
|
+
t.output_hash, t.output_chars, t.timestamp, t.truncated,
|
|
737
|
+
t.index_truncated,
|
|
670
738
|
snippet(tool_outputs_fts, 6, '>>', '<<', '...', 16) AS snippet
|
|
671
739
|
FROM tool_outputs_fts f
|
|
672
740
|
JOIN tool_outputs t ON t.rowid = f.rowid
|
|
@@ -693,6 +761,8 @@ class SessionStore:
|
|
|
693
761
|
rows = conn.execute(
|
|
694
762
|
r"""SELECT tool_use_id, tool_name, command_or_path,
|
|
695
763
|
source_file_path, language, archived_from,
|
|
764
|
+
output_hash, output_chars, timestamp, truncated,
|
|
765
|
+
index_truncated,
|
|
696
766
|
substr(COALESCE(output_text, compressed_preview, ''), 1, 200) AS snippet
|
|
697
767
|
FROM tool_outputs
|
|
698
768
|
WHERE tool_name LIKE ? ESCAPE '\' OR command_or_path LIKE ? ESCAPE '\'
|
|
@@ -810,6 +880,15 @@ class SessionStore:
|
|
|
810
880
|
)
|
|
811
881
|
conn.commit()
|
|
812
882
|
|
|
883
|
+
def record_file_edit(self, file_path: str) -> None:
|
|
884
|
+
"""Keep edit evidence without persisting credential-shaped path text."""
|
|
885
|
+
fingerprint = hashlib.sha256(file_path.encode("utf-8")).hexdigest()
|
|
886
|
+
self.set_meta("checkpoint_edit:" + fingerprint, "1")
|
|
887
|
+
|
|
888
|
+
def was_file_edited(self, file_path: str) -> bool:
|
|
889
|
+
fingerprint = hashlib.sha256(file_path.encode("utf-8")).hexdigest()
|
|
890
|
+
return self.get_meta("checkpoint_edit:" + fingerprint) == "1"
|
|
891
|
+
|
|
813
892
|
# ----- context_intel_events -----
|
|
814
893
|
|
|
815
894
|
def insert_intel_event(
|
|
@@ -960,6 +1039,45 @@ class SessionStore:
|
|
|
960
1039
|
return [dict(r) for r in rows]
|
|
961
1040
|
|
|
962
1041
|
|
|
1042
|
+
def _context_reset_marker(session_id: str, snapshot_dir: Optional[Path] = None) -> Optional[Path]:
|
|
1043
|
+
# An id the archive would not accept maps to no marker, so a malformed id
|
|
1044
|
+
# can never fork a stray directory.
|
|
1045
|
+
if not session_id or not re.match(r"^[a-zA-Z0-9_-]+\Z", session_id):
|
|
1046
|
+
return None
|
|
1047
|
+
base = snapshot_dir or resolve_snapshot_dir()
|
|
1048
|
+
return base / "tool-archive" / session_id / "context_reset_at"
|
|
1049
|
+
|
|
1050
|
+
|
|
1051
|
+
def mark_context_reset(session_id: str, snapshot_dir: Optional[Path] = None) -> None:
|
|
1052
|
+
"""Record that this session's context was emptied now (/clear or compaction).
|
|
1053
|
+
|
|
1054
|
+
The re-fetch guard reads this to stop treating archived MCP results from
|
|
1055
|
+
before the reset as data the model still holds. A plain timestamp file, not a
|
|
1056
|
+
database row, because the guard runs on every MCP call and stays free of
|
|
1057
|
+
SQLite. Best-effort: a failed write only means the guard keeps its old
|
|
1058
|
+
behaviour.
|
|
1059
|
+
"""
|
|
1060
|
+
try:
|
|
1061
|
+
marker = _context_reset_marker(session_id, snapshot_dir)
|
|
1062
|
+
if marker is None:
|
|
1063
|
+
return
|
|
1064
|
+
marker.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
|
|
1065
|
+
marker.write_text(repr(time.time()), encoding="utf-8")
|
|
1066
|
+
except OSError:
|
|
1067
|
+
pass
|
|
1068
|
+
|
|
1069
|
+
|
|
1070
|
+
def context_reset_at(session_id: str, snapshot_dir: Optional[Path] = None) -> float:
|
|
1071
|
+
"""Epoch seconds of the session's last context reset, or 0.0 if none."""
|
|
1072
|
+
try:
|
|
1073
|
+
marker = _context_reset_marker(session_id, snapshot_dir)
|
|
1074
|
+
if marker is None:
|
|
1075
|
+
return 0.0
|
|
1076
|
+
return float(marker.read_text(encoding="utf-8").strip())
|
|
1077
|
+
except (OSError, ValueError):
|
|
1078
|
+
return 0.0
|
|
1079
|
+
|
|
1080
|
+
|
|
963
1081
|
def cleanup_old_stores(max_age_hours: int = CLEANUP_AGE_HOURS) -> int:
|
|
964
1082
|
"""Delete session store DBs older than max_age_hours. Returns count deleted."""
|
|
965
1083
|
if not SESSION_STORE_DIR.exists():
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
// Token Optimizer - Claude Code Status Line (two-row layout)
|
|
3
3
|
//
|
|
4
4
|
// Row 1: model | effort | project | context bar used% | ContextQ:grade(score)
|
|
5
|
-
// Row 2: Eff:grade(score) | warnings | Compacts:N(
|
|
5
|
+
// Row 2: Eff:grade(score) | warnings | Compacts:N(observing) | duration | Agents
|
|
6
6
|
//
|
|
7
7
|
// Install: python3 measure.py setup-quality-bar
|
|
8
8
|
// The quality score is updated by a UserPromptSubmit hook every ~2 minutes.
|
|
@@ -555,15 +555,13 @@ process.stdin.on('end', () => {
|
|
|
555
555
|
}
|
|
556
556
|
}
|
|
557
557
|
|
|
558
|
-
//
|
|
558
|
+
// Recovery thresholds remain shadow-only until calibrated.
|
|
559
559
|
if (q) {
|
|
560
560
|
const c = q.compactions;
|
|
561
561
|
if (c != null) {
|
|
562
562
|
if (c > 0) {
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
const color = c <= 2 ? '\x1b[33m' : '\x1b[31m';
|
|
566
|
-
row2Parts.push(`${color}Compacts:${c}(${loss} lost)${RESET}`);
|
|
563
|
+
// Recovery evidence is shadow-only, even for older cached flags.
|
|
564
|
+
row2Parts.push(`${DIM}Compacts:${c}(observing)${RESET}`);
|
|
567
565
|
} else {
|
|
568
566
|
row2Parts.push(`\x1b[32mCompacts:0${RESET}`);
|
|
569
567
|
}
|