@alexgreensh/token-optimizer 0.0.0-stage → 5.13.51

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.
Files changed (161) hide show
  1. package/.claude-plugin/marketplace.json +76 -0
  2. package/.claude-plugin/plugin.json +21 -0
  3. package/LICENSE +130 -0
  4. package/LICENSE-SMALL-BUSINESS.md +62 -0
  5. package/PRIVACY.md +200 -0
  6. package/README.md +13 -2
  7. package/hooks/codex-hooks.json +4 -0
  8. package/hooks/hooks.json +182 -0
  9. package/hooks/module_runner.py +448 -0
  10. package/hooks/posttooluse_runner.py +1110 -0
  11. package/hooks/python-launcher.sh +816 -0
  12. package/hooks/run.py +788 -0
  13. package/hooks/sessionstart_runner.py +629 -0
  14. package/hooks/stop_runner.py +408 -0
  15. package/hooks/userpromptsubmit_runner.py +722 -0
  16. package/hooks/windows-launcher.py +163 -0
  17. package/install-cloud.sh +23 -0
  18. package/package.json +29 -4
  19. package/skills/fleet-auditor/SKILL.md +149 -0
  20. package/skills/fleet-auditor/references/fleet-systems.md +167 -0
  21. package/skills/fleet-auditor/references/report-template.md +50 -0
  22. package/skills/fleet-auditor/references/waste-patterns.md +126 -0
  23. package/skills/fleet-auditor/scripts/fleet.py +3633 -0
  24. package/skills/fleet-auditor/scripts/shared.py +277 -0
  25. package/skills/resume-checkpoint/SKILL.md +52 -0
  26. package/skills/resume-checkpoint/scripts/pull_checkpoint.py +188 -0
  27. package/skills/token-coach/SKILL.md +141 -0
  28. package/skills/token-coach/assets/coach-dashboard-tab.html +45 -0
  29. package/skills/token-coach/examples/coaching-session-agentic.md +62 -0
  30. package/skills/token-coach/examples/coaching-session-heavy-setup.md +46 -0
  31. package/skills/token-coach/examples/coaching-session-new-project.md +38 -0
  32. package/skills/token-coach/references/agentic-systems.md +147 -0
  33. package/skills/token-coach/references/coach-patterns.md +120 -0
  34. package/skills/token-coach/references/coaching-scripts.md +146 -0
  35. package/skills/token-coach/references/deterministic-stages.md +102 -0
  36. package/skills/token-coach/references/keepwarm-consent.md +48 -0
  37. package/skills/token-coach/references/quick-reference.md +155 -0
  38. package/skills/token-dashboard/SKILL.md +93 -0
  39. package/skills/token-optimizer/SKILL.md +150 -0
  40. package/skills/token-optimizer/assets/dashboard.html +7251 -0
  41. package/skills/token-optimizer/examples/claude-md-optimized.md +40 -0
  42. package/skills/token-optimizer/examples/hooks-starter.json +179 -0
  43. package/skills/token-optimizer/examples/permissions-deny-template.json +24 -0
  44. package/skills/token-optimizer/pricing/prices.json +695 -0
  45. package/skills/token-optimizer/references/agent-prompts.md +687 -0
  46. package/skills/token-optimizer/references/cli-reference.md +92 -0
  47. package/skills/token-optimizer/references/codex-workflow.md +188 -0
  48. package/skills/token-optimizer/references/cursor-workflow.md +74 -0
  49. package/skills/token-optimizer/references/error-recovery.md +37 -0
  50. package/skills/token-optimizer/references/implementation-playbook.md +416 -0
  51. package/skills/token-optimizer/references/keepwarm-consent.md +48 -0
  52. package/skills/token-optimizer/references/opencode-workflow.md +72 -0
  53. package/skills/token-optimizer/references/optimization-checklist.md +714 -0
  54. package/skills/token-optimizer/references/phase0-setup.md +142 -0
  55. package/skills/token-optimizer/references/presentation-workflow.md +72 -0
  56. package/skills/token-optimizer/references/session-continuity.md +19 -0
  57. package/skills/token-optimizer/references/token-flow-architecture.md +629 -0
  58. package/skills/token-optimizer/scripts/activity_tracker.py +143 -0
  59. package/skills/token-optimizer/scripts/antigravity_doctor.py +548 -0
  60. package/skills/token-optimizer/scripts/antigravity_hook_bridge.py +511 -0
  61. package/skills/token-optimizer/scripts/antigravity_install.py +379 -0
  62. package/skills/token-optimizer/scripts/antigravity_proto.py +413 -0
  63. package/skills/token-optimizer/scripts/antigravity_session.py +346 -0
  64. package/skills/token-optimizer/scripts/antigravity_state.py +486 -0
  65. package/skills/token-optimizer/scripts/archive_result.py +1725 -0
  66. package/skills/token-optimizer/scripts/bash_compress.py +2490 -0
  67. package/skills/token-optimizer/scripts/bash_compress_hook.py +766 -0
  68. package/skills/token-optimizer/scripts/bash_hook.py +61 -0
  69. package/skills/token-optimizer/scripts/bash_whitelist.py +243 -0
  70. package/skills/token-optimizer/scripts/benchmark.py +1765 -0
  71. package/skills/token-optimizer/scripts/build_output_compress.py +776 -0
  72. package/skills/token-optimizer/scripts/cloud_kit.py +1011 -0
  73. package/skills/token-optimizer/scripts/codex_command_compress.py +434 -0
  74. package/skills/token-optimizer/scripts/codex_compact_prompt.py +273 -0
  75. package/skills/token-optimizer/scripts/codex_doctor.py +454 -0
  76. package/skills/token-optimizer/scripts/codex_hook_bridge.py +311 -0
  77. package/skills/token-optimizer/scripts/codex_install.py +810 -0
  78. package/skills/token-optimizer/scripts/codex_io.py +119 -0
  79. package/skills/token-optimizer/scripts/codex_log_index.py +219 -0
  80. package/skills/token-optimizer/scripts/codex_models.py +34 -0
  81. package/skills/token-optimizer/scripts/codex_session.py +1186 -0
  82. package/skills/token-optimizer/scripts/codex_state.py +707 -0
  83. package/skills/token-optimizer/scripts/codex_statusline.py +303 -0
  84. package/skills/token-optimizer/scripts/command_filters.py +386 -0
  85. package/skills/token-optimizer/scripts/compression_backfill.py +600 -0
  86. package/skills/token-optimizer/scripts/compression_log.py +230 -0
  87. package/skills/token-optimizer/scripts/context_intel.py +331 -0
  88. package/skills/token-optimizer/scripts/context_pressure.py +115 -0
  89. package/skills/token-optimizer/scripts/copilot_doctor.py +406 -0
  90. package/skills/token-optimizer/scripts/copilot_hook_bridge.py +709 -0
  91. package/skills/token-optimizer/scripts/copilot_install.py +288 -0
  92. package/skills/token-optimizer/scripts/copilot_session.py +496 -0
  93. package/skills/token-optimizer/scripts/copilot_state.py +569 -0
  94. package/skills/token-optimizer/scripts/copilot_vscode.py +832 -0
  95. package/skills/token-optimizer/scripts/cowork_doctor.py +270 -0
  96. package/skills/token-optimizer/scripts/cowork_install.py +380 -0
  97. package/skills/token-optimizer/scripts/credential_patterns.py +1514 -0
  98. package/skills/token-optimizer/scripts/cursor_doctor.py +602 -0
  99. package/skills/token-optimizer/scripts/cursor_hook_bridge.py +843 -0
  100. package/skills/token-optimizer/scripts/cursor_install.py +426 -0
  101. package/skills/token-optimizer/scripts/cursor_session.py +303 -0
  102. package/skills/token-optimizer/scripts/cursor_state.py +348 -0
  103. package/skills/token-optimizer/scripts/delta_diff.py +110 -0
  104. package/skills/token-optimizer/scripts/detectors/__init__.py +2 -0
  105. package/skills/token-optimizer/scripts/detectors/bad_decomposition.py +78 -0
  106. package/skills/token-optimizer/scripts/detectors/cache_instability.py +504 -0
  107. package/skills/token-optimizer/scripts/detectors/looping.py +88 -0
  108. package/skills/token-optimizer/scripts/detectors/output_waste.py +143 -0
  109. package/skills/token-optimizer/scripts/detectors/overpowered.py +116 -0
  110. package/skills/token-optimizer/scripts/detectors/pdf_ingestion.py +52 -0
  111. package/skills/token-optimizer/scripts/detectors/registry.py +65 -0
  112. package/skills/token-optimizer/scripts/detectors/respond_to_bash.py +76 -0
  113. package/skills/token-optimizer/scripts/detectors/retry_churn.py +83 -0
  114. package/skills/token-optimizer/scripts/detectors/tool_cascade.py +62 -0
  115. package/skills/token-optimizer/scripts/detectors/wasteful_thinking.py +75 -0
  116. package/skills/token-optimizer/scripts/detectors/weak_model.py +55 -0
  117. package/skills/token-optimizer/scripts/detectors/websearch_routing.py +72 -0
  118. package/skills/token-optimizer/scripts/deterministic_candidates.py +1458 -0
  119. package/skills/token-optimizer/scripts/devin_compress.py +790 -0
  120. package/skills/token-optimizer/scripts/devin_doctor.py +403 -0
  121. package/skills/token-optimizer/scripts/devin_hooks.py +453 -0
  122. package/skills/token-optimizer/scripts/devin_install.py +1086 -0
  123. package/skills/token-optimizer/scripts/devin_source.py +119 -0
  124. package/skills/token-optimizer/scripts/devin_state.py +330 -0
  125. package/skills/token-optimizer/scripts/devin_verify.py +67 -0
  126. package/skills/token-optimizer/scripts/grok_doctor.py +560 -0
  127. package/skills/token-optimizer/scripts/grok_hook_bridge.py +699 -0
  128. package/skills/token-optimizer/scripts/grok_install.py +400 -0
  129. package/skills/token-optimizer/scripts/grok_session.py +317 -0
  130. package/skills/token-optimizer/scripts/grok_state.py +299 -0
  131. package/skills/token-optimizer/scripts/hermes_doctor.py +479 -0
  132. package/skills/token-optimizer/scripts/hermes_hook_bridge.py +285 -0
  133. package/skills/token-optimizer/scripts/hermes_install.py +668 -0
  134. package/skills/token-optimizer/scripts/hermes_session.py +691 -0
  135. package/skills/token-optimizer/scripts/hermes_state.py +448 -0
  136. package/skills/token-optimizer/scripts/hook_io.py +120 -0
  137. package/skills/token-optimizer/scripts/hook_runtime.py +716 -0
  138. package/skills/token-optimizer/scripts/injection.py +156 -0
  139. package/skills/token-optimizer/scripts/install_reconcile.py +952 -0
  140. package/skills/token-optimizer/scripts/measure.py +59531 -0
  141. package/skills/token-optimizer/scripts/outline.py +53 -0
  142. package/skills/token-optimizer/scripts/pipeline_analyzer.py +723 -0
  143. package/skills/token-optimizer/scripts/plugin_env.py +562 -0
  144. package/skills/token-optimizer/scripts/py_trust.py +80 -0
  145. package/skills/token-optimizer/scripts/quality_cache_gate.py +320 -0
  146. package/skills/token-optimizer/scripts/read_cache.py +2489 -0
  147. package/skills/token-optimizer/scripts/recovery_output.py +110 -0
  148. package/skills/token-optimizer/scripts/refetch_fingerprint.py +236 -0
  149. package/skills/token-optimizer/scripts/refetch_guard.py +244 -0
  150. package/skills/token-optimizer/scripts/routing_advisor.py +389 -0
  151. package/skills/token-optimizer/scripts/runtime_env.py +1923 -0
  152. package/skills/token-optimizer/scripts/session_store.py +979 -0
  153. package/skills/token-optimizer/scripts/spawn_utils.py +122 -0
  154. package/skills/token-optimizer/scripts/statusline.js +660 -0
  155. package/skills/token-optimizer/scripts/structure_map.py +2880 -0
  156. package/skills/token-optimizer/scripts/structure_map_ts.py +676 -0
  157. package/skills/token-optimizer/scripts/structure_replay.py +1556 -0
  158. package/skills/token-optimizer/scripts/thrash_guard.py +604 -0
  159. package/skills/token-optimizer/scripts/token_estimate.py +80 -0
  160. package/skills/token-optimizer/scripts/tool_search_diagnostic.py +61 -0
  161. package/skills/token-optimizer/scripts/utf8_io.py +219 -0
@@ -0,0 +1,979 @@
1
+ #!/usr/bin/env python3
2
+ """Token Optimizer v5.5 - Session Knowledge Store.
3
+
4
+ Per-session SQLite database for tool output caching, file read tracking,
5
+ and command deduplication. Replaces the per-session JSON cache files
6
+ with a structured, ACID-safe store.
7
+
8
+ Exact-match lookups use indexed PRIMARY KEY columns. The archive
9
+ (``tool_outputs``) additionally carries an EXTERNAL-CONTENT FTS5 mirror
10
+ (``tool_outputs_fts``, ``content='tool_outputs'``) kept in sync by triggers,
11
+ so full-text search is a true mirror of the base table (dedup follows the base
12
+ PRIMARY KEY, legacy rows backfilled by a one-time ``rebuild``). A bounded
13
+ ``LIKE`` query is the fallback when SQLite is built without FTS5.
14
+
15
+ Configuration:
16
+ - WAL mode for concurrent read/write from separate hook processes
17
+ - busy_timeout=50ms: fail-fast under write contention (shadow mode
18
+ accepts dropped writes rather than stalling the hook process)
19
+ - synchronous=NORMAL (WAL-safe relaxation for performance)
20
+ - 50MB cap per session DB
21
+ - PreToolUse hooks: READ-ONLY queries only
22
+ - PostToolUse hooks: WRITE operations
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ import json
28
+ import re
29
+ import sqlite3
30
+ import time
31
+ import uuid
32
+ from pathlib import Path
33
+ from typing import Any, Optional
34
+
35
+ from plugin_env import resolve_snapshot_dir
36
+
37
+ SNAPSHOT_DIR = resolve_snapshot_dir()
38
+ SESSION_STORE_DIR = SNAPSHOT_DIR / "session-store"
39
+
40
+ MAX_DB_SIZE_BYTES = 50 * 1024 * 1024 # 50MB cap
41
+ CLEANUP_AGE_HOURS = 48
42
+
43
+ # v2: added tool_outputs lineage columns + the FTS5 archive index, and
44
+ # converted that index to an external-content mirror of tool_outputs. The bump
45
+ # gates the one-time FTS backfill/rebuild migration in _ensure_fts5_index.
46
+ _SCHEMA_VERSION = 2
47
+
48
+ _SCHEMA_SQL = """
49
+ CREATE TABLE IF NOT EXISTS file_reads (
50
+ file_path TEXT PRIMARY KEY,
51
+ mtime_ns INTEGER NOT NULL,
52
+ size_bytes INTEGER NOT NULL,
53
+ ranges_seen TEXT NOT NULL DEFAULT '[]',
54
+ tokens_est INTEGER NOT NULL DEFAULT 0,
55
+ read_count INTEGER NOT NULL DEFAULT 1,
56
+ content_hash TEXT,
57
+ last_access REAL NOT NULL,
58
+ last_replacement_fingerprint TEXT DEFAULT '',
59
+ last_replacement_type TEXT DEFAULT '',
60
+ repeat_replacement_count INTEGER DEFAULT 0,
61
+ last_structure_reason TEXT DEFAULT '',
62
+ last_structure_confidence REAL DEFAULT 0.0,
63
+ last_tool_use_id TEXT DEFAULT ''
64
+ );
65
+
66
+ CREATE TABLE IF NOT EXISTS tool_outputs (
67
+ tool_use_id TEXT PRIMARY KEY,
68
+ tool_name TEXT NOT NULL,
69
+ tool_type TEXT NOT NULL,
70
+ command_or_path TEXT,
71
+ output_hash TEXT NOT NULL,
72
+ output_chars INTEGER NOT NULL,
73
+ output_tokens_est INTEGER NOT NULL,
74
+ compressed_preview TEXT,
75
+ timestamp REAL NOT NULL,
76
+ source_file_path TEXT,
77
+ language TEXT,
78
+ archived_from TEXT,
79
+ output_text TEXT
80
+ );
81
+
82
+ CREATE TABLE IF NOT EXISTS command_outputs (
83
+ command_hash TEXT PRIMARY KEY,
84
+ command_text TEXT NOT NULL,
85
+ output_hash TEXT NOT NULL,
86
+ output_chars INTEGER NOT NULL,
87
+ compressed_output TEXT,
88
+ timestamp REAL NOT NULL
89
+ );
90
+
91
+ CREATE TABLE IF NOT EXISTS command_run_streaks (
92
+ command_hash TEXT PRIMARY KEY,
93
+ command_text TEXT NOT NULL,
94
+ output_hash TEXT NOT NULL,
95
+ streak INTEGER NOT NULL,
96
+ nudged_streak INTEGER,
97
+ last_ts REAL NOT NULL,
98
+ fail_streak INTEGER NOT NULL DEFAULT 0,
99
+ fail_nudged_streak INTEGER,
100
+ inline_run_count INTEGER NOT NULL DEFAULT 0,
101
+ inline_nudged_count INTEGER
102
+ );
103
+
104
+ CREATE TABLE IF NOT EXISTS cached_content (
105
+ file_path TEXT PRIMARY KEY,
106
+ content TEXT NOT NULL,
107
+ content_hash TEXT NOT NULL,
108
+ cached_at REAL NOT NULL
109
+ );
110
+
111
+ CREATE TABLE IF NOT EXISTS session_meta (
112
+ key TEXT PRIMARY KEY,
113
+ value TEXT NOT NULL
114
+ );
115
+
116
+ CREATE TABLE IF NOT EXISTS context_intel_events (
117
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
118
+ tool_name TEXT NOT NULL,
119
+ tool_use_id TEXT NOT NULL,
120
+ summary TEXT NOT NULL,
121
+ output_chars INTEGER NOT NULL,
122
+ timestamp REAL NOT NULL
123
+ );
124
+
125
+ CREATE TABLE IF NOT EXISTS activity_log (
126
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
127
+ tool_name TEXT NOT NULL,
128
+ tool_bucket TEXT NOT NULL,
129
+ has_error INTEGER NOT NULL DEFAULT 0,
130
+ timestamp REAL NOT NULL
131
+ );
132
+
133
+ CREATE TABLE IF NOT EXISTS hint_serves (
134
+ file_path TEXT PRIMARY KEY,
135
+ served_at REAL NOT NULL,
136
+ credited INTEGER NOT NULL DEFAULT 0
137
+ );
138
+
139
+ """
140
+
141
+
142
+ def _is_real_fts_absence(exc: sqlite3.OperationalError) -> bool:
143
+ """True only when the OperationalError means FTS5 is genuinely absent from
144
+ this SQLite build (so it is safe to cache _fts5_available=False for the
145
+ process). A transient ``database is locked`` / ``busy`` returns False and
146
+ must NOT be cached -- it is retried on a later connect."""
147
+ msg = str(exc).lower()
148
+ return (
149
+ "no such module" in msg
150
+ or "unknown tokenizer" in msg
151
+ or "no such tokenizer" in msg
152
+ or "no such fts5" in msg
153
+ )
154
+
155
+
156
+ def _sanitize_session_id(sid: str) -> str:
157
+ # Generate a unique fallback instead of a static "unknown" string.
158
+ # A static fallback would cause all invalid/missing session IDs to share
159
+ # one SQLite database, leaking data across unrelated sessions.
160
+ if not sid or not re.match(r"^[a-zA-Z0-9_-]+$", sid):
161
+ return f"fallback-{uuid.uuid4().hex[:12]}"
162
+ return sid
163
+
164
+
165
+ class SessionStore:
166
+ """Per-session SQLite store for tool output caching."""
167
+
168
+ def __init__(
169
+ self,
170
+ session_id: str,
171
+ snapshot_dir: Optional[Path] = None,
172
+ busy_timeout_ms: Optional[int] = None,
173
+ ):
174
+ self.session_id = _sanitize_session_id(session_id)
175
+ # Per-instance busy_timeout. Defaults to the 50ms fail-fast policy
176
+ # documented above (shadow mode prefers dropped writes over stalling a
177
+ # hook process). The compaction clear (read_cache.handle_clear_compacted)
178
+ # opts into a higher value so it waits out a sibling write lock on the
179
+ # same per-session db instead of dying at 50ms and silently no-op'ing
180
+ # (contention-safe follow-up).
181
+ self._busy_timeout_ms = (
182
+ 50 if busy_timeout_ms is None else max(0, int(busy_timeout_ms))
183
+ )
184
+ base = snapshot_dir or SNAPSHOT_DIR
185
+ self._store_dir = base / "session-store"
186
+ self.db_path = self._store_dir / f"{self.session_id}.db"
187
+ self._conn: Optional[sqlite3.Connection] = None
188
+
189
+ def _connect(self) -> sqlite3.Connection:
190
+ if self._conn is not None:
191
+ return self._conn
192
+ self._store_dir.mkdir(parents=True, exist_ok=True, mode=0o700)
193
+ # Align the connect timeout (seconds) with the PRAGMA busy_timeout (ms)
194
+ # so the schema init AND later writes honor the same lock-wait budget.
195
+ timeout_s = max(0.05, self._busy_timeout_ms / 1000.0)
196
+ self._conn = sqlite3.connect(str(self.db_path), timeout=timeout_s)
197
+ self._conn.execute("PRAGMA journal_mode=WAL")
198
+ self._conn.execute(f"PRAGMA busy_timeout={int(self._busy_timeout_ms)}")
199
+ self._conn.execute("PRAGMA synchronous=NORMAL")
200
+ # Defense-in-depth privacy (the parent dir is already 0700): the DB and
201
+ # its WAL/SHM sidecars hold cached tool output, so restrict them to the
202
+ # owner (0600). sqlite creates them honoring umask (commonly 0644), so
203
+ # tighten explicitly. Best-effort; never break a connect on chmod.
204
+ import os as _os
205
+ for _p in (
206
+ self.db_path,
207
+ self.db_path.with_suffix(".db-wal"),
208
+ self.db_path.with_suffix(".db-shm"),
209
+ ):
210
+ try:
211
+ _os.chmod(_p, 0o600)
212
+ except OSError:
213
+ pass
214
+ self._conn.row_factory = sqlite3.Row
215
+ self._init_schema()
216
+ return self._conn
217
+
218
+ def _init_schema(self) -> None:
219
+ conn = self._conn
220
+ if conn is None:
221
+ return
222
+ conn.executescript(_SCHEMA_SQL)
223
+ # Read the PRIOR schema version BEFORE stamping the current one, so the
224
+ # FTS migration can tell a pre-v2 DB (legacy standalone FTS or none)
225
+ # from an already-migrated one. None => brand-new / pre-versioning DB.
226
+ prior_version = self._read_schema_version(conn)
227
+ # U5: idempotent in-place migration for the lineage columns on
228
+ # pre-existing tool_outputs tables (PRAGMA-introspect then ALTER).
229
+ # Runs BEFORE the FTS setup so the external-content mirror + triggers
230
+ # can reference the lineage columns (output_text in particular).
231
+ self._ensure_tool_output_columns(conn)
232
+ # F1b: add last_tool_use_id to file_reads for double-fire idempotency.
233
+ self._ensure_file_reads_columns(conn)
234
+ # Burn nudge: add fail_streak / fail_nudged_streak to command_run_streaks.
235
+ self._ensure_command_streaks_columns(conn)
236
+ # Double-fire guard for cross-turn dedup: last_tool_use_id on command_outputs.
237
+ self._ensure_command_outputs_columns(conn)
238
+ # U6/fix-1: probe + setup the external-content FTS5 mirror (LIKE
239
+ # fallback). Backfills legacy rows once, gated on prior_version < 2.
240
+ self._ensure_fts5_index(conn, prior_version)
241
+ # Stamp the current schema version last (INSERT OR REPLACE so the bump
242
+ # actually lands on pre-existing DBs, not just brand-new ones).
243
+ conn.execute(
244
+ "INSERT OR REPLACE INTO session_meta (key, value) VALUES (?, ?)",
245
+ ("_schema_version", str(_SCHEMA_VERSION)),
246
+ )
247
+ conn.commit()
248
+
249
+ @staticmethod
250
+ def _read_schema_version(conn: sqlite3.Connection) -> Optional[int]:
251
+ """Return the stored ``_schema_version`` (int) or None when absent/
252
+ unreadable. Never raises."""
253
+ try:
254
+ row = conn.execute(
255
+ "SELECT value FROM session_meta WHERE key = '_schema_version'"
256
+ ).fetchone()
257
+ except sqlite3.DatabaseError:
258
+ return None
259
+ if not row:
260
+ return None
261
+ try:
262
+ return int(row[0])
263
+ except (TypeError, ValueError):
264
+ return None
265
+
266
+ def _ensure_tool_output_columns(self, conn: sqlite3.Connection) -> None:
267
+ """Add source_file_path/language/archived_from/output_text to
268
+ tool_outputs if absent.
269
+
270
+ Mirrors the compression_log tier-migration pattern: PRAGMA table_info
271
+ to introspect, then ALTER TABLE ADD COLUMN for each missing one. Safe
272
+ to call on every connect; idempotent (SQLite ADD COLUMN is a no-op
273
+ once the column exists). Never raises on a corrupt/missing table.
274
+ """
275
+ try:
276
+ cols = {r[1] for r in conn.execute("PRAGMA table_info(tool_outputs)").fetchall()}
277
+ except sqlite3.DatabaseError:
278
+ return
279
+ for col in ("source_file_path", "language", "archived_from", "output_text"):
280
+ if col not in cols:
281
+ try:
282
+ conn.execute(f"ALTER TABLE tool_outputs ADD COLUMN {col} TEXT")
283
+ except sqlite3.OperationalError:
284
+ pass
285
+
286
+ def _ensure_file_reads_columns(self, conn: sqlite3.Connection) -> None:
287
+ """Add last_tool_use_id to file_reads if absent (F1b idempotency guard).
288
+
289
+ Mirrors the tool_outputs migration pattern: PRAGMA-introspect then
290
+ ALTER TABLE ADD COLUMN. Idempotent and never raises on a corrupt table.
291
+ """
292
+ try:
293
+ cols = {r[1] for r in conn.execute("PRAGMA table_info(file_reads)").fetchall()}
294
+ except sqlite3.DatabaseError:
295
+ return
296
+ if "last_tool_use_id" not in cols:
297
+ try:
298
+ conn.execute("ALTER TABLE file_reads ADD COLUMN last_tool_use_id TEXT DEFAULT ''")
299
+ except sqlite3.OperationalError:
300
+ pass
301
+
302
+ def _ensure_command_outputs_columns(self, conn: sqlite3.Connection) -> None:
303
+ """Add last_tool_use_id to command_outputs if absent, so cross-turn
304
+ dedup can tell a second hook firing on the same call from a real re-run.
305
+ Same idempotent PRAGMA + ALTER TABLE pattern as the migrations beside it.
306
+ """
307
+ try:
308
+ cols = {r[1] for r in conn.execute("PRAGMA table_info(command_outputs)").fetchall()}
309
+ except sqlite3.DatabaseError:
310
+ return
311
+ if "last_tool_use_id" not in cols:
312
+ try:
313
+ conn.execute("ALTER TABLE command_outputs ADD COLUMN last_tool_use_id TEXT DEFAULT ''")
314
+ except sqlite3.OperationalError:
315
+ pass
316
+
317
+ def _ensure_command_streaks_columns(self, conn: sqlite3.Connection) -> None:
318
+ """Add fail_streak and fail_nudged_streak to command_run_streaks if
319
+ absent (burn nudge). Idempotent ALTER TABLE, same pattern as the
320
+ tool_outputs and file_reads migrations. Never raises.
321
+ """
322
+ try:
323
+ cols = {r[1] for r in conn.execute(
324
+ "PRAGMA table_info(command_run_streaks)"
325
+ ).fetchall()}
326
+ except sqlite3.DatabaseError:
327
+ return
328
+ for col, decl in (
329
+ ("fail_streak", "INTEGER NOT NULL DEFAULT 0"),
330
+ ("fail_nudged_streak", "INTEGER"),
331
+ ("inline_run_count", "INTEGER NOT NULL DEFAULT 0"),
332
+ ("inline_nudged_count", "INTEGER"),
333
+ ):
334
+ if col not in cols:
335
+ try:
336
+ conn.execute(
337
+ f"ALTER TABLE command_run_streaks ADD COLUMN {col} {decl}"
338
+ )
339
+ except sqlite3.OperationalError:
340
+ pass
341
+
342
+ # U6/fix-1: external-content FTS5 mirror over the archive.
343
+ _fts5_available: Optional[bool] = None
344
+
345
+ def _ensure_fts5_index(
346
+ self, conn: sqlite3.Connection, prior_version: Optional[int] = None
347
+ ) -> None:
348
+ """Probe FTS5 and set up an EXTERNAL-CONTENT mirror of ``tool_outputs``.
349
+
350
+ External content (``content='tool_outputs'``) makes the FTS index a
351
+ true mirror of the base table rather than a separate copy:
352
+
353
+ * Dedup follows the base PRIMARY KEY. The AFTER INSERT trigger fires
354
+ only when ``INSERT OR IGNORE`` actually writes a new row, so
355
+ re-inserting the same ``tool_use_id`` (e.g. read_cache's stable
356
+ ``fr_shadow_<sha>`` id on a re-read) never appends a duplicate FTS
357
+ row -- search returns each match exactly once.
358
+ * Search reads content from the base table, so every base row is
359
+ visible, including legacy rows written before FTS existed.
360
+ * A one-time ``'rebuild'`` (gated on a pre-v2 schema version)
361
+ backfills the entire existing archive into the index.
362
+
363
+ Availability is cached once per process, but ONLY a genuine absence
364
+ (``no such module`` / ``unknown tokenizer``) disables FTS. A transient
365
+ ``database is locked`` / ``busy`` is left uncached so a later connect
366
+ retries -- a lock must never permanently disable FTS for the process.
367
+ Never raises.
368
+ """
369
+ if SessionStore._fts5_available is False:
370
+ return
371
+ if SessionStore._fts5_available is None:
372
+ try:
373
+ conn.execute("CREATE VIRTUAL TABLE IF NOT EXISTS _fts5_probe USING fts5(x)")
374
+ conn.execute("DROP TABLE IF EXISTS _fts5_probe")
375
+ SessionStore._fts5_available = True
376
+ except sqlite3.OperationalError as exc:
377
+ if _is_real_fts_absence(exc):
378
+ SessionStore._fts5_available = False
379
+ # transient (locked/busy or unknown): leave None, retry later
380
+ return
381
+ # A pre-v2 DB either has no FTS or the legacy STANDALONE (non-mirror)
382
+ # tool_outputs_fts from the first U6 cut; both must be replaced by the
383
+ # external-content mirror and backfilled once. A brand-new DB
384
+ # (prior_version is None) also takes this path -- rebuild over an empty
385
+ # base is a no-op.
386
+ needs_backfill = prior_version is None or prior_version < 2
387
+ try:
388
+ if needs_backfill:
389
+ self._drop_fts_objects(conn)
390
+ self._create_fts_objects(conn)
391
+ if needs_backfill:
392
+ conn.execute(
393
+ "INSERT INTO tool_outputs_fts(tool_outputs_fts) VALUES('rebuild')"
394
+ )
395
+ except sqlite3.OperationalError as exc:
396
+ if _is_real_fts_absence(exc):
397
+ SessionStore._fts5_available = False
398
+ # transient: leave availability as-is; retried on the next connect
399
+
400
+ @staticmethod
401
+ def _drop_fts_objects(conn: sqlite3.Connection) -> None:
402
+ """Drop the FTS mirror + its sync triggers (idempotent)."""
403
+ for stmt in (
404
+ "DROP TRIGGER IF EXISTS tool_outputs_ai",
405
+ "DROP TRIGGER IF EXISTS tool_outputs_ad",
406
+ "DROP TRIGGER IF EXISTS tool_outputs_au",
407
+ "DROP TABLE IF EXISTS tool_outputs_fts",
408
+ ):
409
+ conn.execute(stmt)
410
+
411
+ @staticmethod
412
+ def _create_fts_objects(conn: sqlite3.Connection) -> None:
413
+ """Create the external-content FTS mirror + AFTER INSERT/DELETE/UPDATE
414
+ sync triggers (all IF NOT EXISTS, so safe on every connect)."""
415
+ conn.execute(
416
+ """CREATE VIRTUAL TABLE IF NOT EXISTS tool_outputs_fts USING fts5(
417
+ tool_use_id UNINDEXED,
418
+ tool_name,
419
+ command_or_path,
420
+ source_file_path,
421
+ language,
422
+ archived_from,
423
+ output_text,
424
+ content='tool_outputs',
425
+ content_rowid='rowid',
426
+ tokenize='porter unicode61'
427
+ )"""
428
+ )
429
+ # AFTER INSERT fires only on a real insert (INSERT OR IGNORE that is
430
+ # ignored fires nothing) -> automatic dedup, no separate guard needed.
431
+ conn.execute(
432
+ """CREATE TRIGGER IF NOT EXISTS tool_outputs_ai
433
+ AFTER INSERT ON tool_outputs BEGIN
434
+ INSERT INTO tool_outputs_fts(
435
+ rowid, tool_use_id, tool_name, command_or_path,
436
+ source_file_path, language, archived_from, output_text)
437
+ VALUES (
438
+ new.rowid, new.tool_use_id, new.tool_name, new.command_or_path,
439
+ new.source_file_path, new.language, new.archived_from, new.output_text);
440
+ END"""
441
+ )
442
+ conn.execute(
443
+ """CREATE TRIGGER IF NOT EXISTS tool_outputs_ad
444
+ AFTER DELETE ON tool_outputs BEGIN
445
+ INSERT INTO tool_outputs_fts(
446
+ tool_outputs_fts, rowid, tool_use_id, tool_name, command_or_path,
447
+ source_file_path, language, archived_from, output_text)
448
+ VALUES (
449
+ 'delete', old.rowid, old.tool_use_id, old.tool_name, old.command_or_path,
450
+ old.source_file_path, old.language, old.archived_from, old.output_text);
451
+ END"""
452
+ )
453
+ conn.execute(
454
+ """CREATE TRIGGER IF NOT EXISTS tool_outputs_au
455
+ AFTER UPDATE ON tool_outputs BEGIN
456
+ INSERT INTO tool_outputs_fts(
457
+ tool_outputs_fts, rowid, tool_use_id, tool_name, command_or_path,
458
+ source_file_path, language, archived_from, output_text)
459
+ VALUES (
460
+ 'delete', old.rowid, old.tool_use_id, old.tool_name, old.command_or_path,
461
+ old.source_file_path, old.language, old.archived_from, old.output_text);
462
+ INSERT INTO tool_outputs_fts(
463
+ rowid, tool_use_id, tool_name, command_or_path,
464
+ source_file_path, language, archived_from, output_text)
465
+ VALUES (
466
+ new.rowid, new.tool_use_id, new.tool_name, new.command_or_path,
467
+ new.source_file_path, new.language, new.archived_from, new.output_text);
468
+ END"""
469
+ )
470
+
471
+ def close(self) -> None:
472
+ if self._conn is not None:
473
+ try:
474
+ self._conn.close()
475
+ except Exception:
476
+ pass
477
+ self._conn = None
478
+
479
+ _cap_warned = False
480
+
481
+ def _is_over_size_cap(self) -> bool:
482
+ try:
483
+ over = self.db_path.stat().st_size > MAX_DB_SIZE_BYTES
484
+ except OSError:
485
+ return False
486
+ if over and not SessionStore._cap_warned:
487
+ SessionStore._cap_warned = True
488
+ import sys as _sys
489
+ print("[Session Store] 50MB cap reached, new writes paused for this session", file=_sys.stderr)
490
+ return over
491
+
492
+ # ----- file_reads -----
493
+
494
+ def get_file_entry(self, file_path: str) -> Optional[dict[str, Any]]:
495
+ conn = self._connect()
496
+ row = conn.execute(
497
+ "SELECT * FROM file_reads WHERE file_path = ?", (file_path,)
498
+ ).fetchone()
499
+ if row is None:
500
+ return None
501
+ entry = dict(row)
502
+ if entry.get("ranges_seen"):
503
+ try:
504
+ entry["ranges_seen"] = json.loads(entry["ranges_seen"])
505
+ except (json.JSONDecodeError, TypeError):
506
+ entry["ranges_seen"] = []
507
+ return entry
508
+
509
+ def upsert_file_entry(self, file_path: str, entry: dict[str, Any]) -> None:
510
+ conn = self._connect()
511
+ ranges_json = json.dumps(entry.get("ranges_seen", []))
512
+ conn.execute(
513
+ """INSERT INTO file_reads
514
+ (file_path, mtime_ns, size_bytes, ranges_seen, tokens_est,
515
+ read_count, content_hash, last_access,
516
+ last_replacement_fingerprint, last_replacement_type,
517
+ repeat_replacement_count, last_structure_reason,
518
+ last_structure_confidence, last_tool_use_id)
519
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
520
+ ON CONFLICT(file_path) DO UPDATE SET
521
+ mtime_ns=excluded.mtime_ns,
522
+ size_bytes=excluded.size_bytes,
523
+ ranges_seen=excluded.ranges_seen,
524
+ tokens_est=excluded.tokens_est,
525
+ read_count=excluded.read_count,
526
+ content_hash=excluded.content_hash,
527
+ last_access=excluded.last_access,
528
+ last_replacement_fingerprint=excluded.last_replacement_fingerprint,
529
+ last_replacement_type=excluded.last_replacement_type,
530
+ repeat_replacement_count=excluded.repeat_replacement_count,
531
+ last_structure_reason=excluded.last_structure_reason,
532
+ last_structure_confidence=excluded.last_structure_confidence,
533
+ last_tool_use_id=excluded.last_tool_use_id
534
+ """,
535
+ (
536
+ file_path,
537
+ int(entry.get("mtime_ns", 0)),
538
+ int(entry.get("size_bytes", 0)),
539
+ ranges_json,
540
+ int(entry.get("tokens_est", 0)),
541
+ int(entry.get("read_count", 1)),
542
+ entry.get("content_hash"),
543
+ float(entry.get("last_access", time.time())),
544
+ entry.get("last_replacement_fingerprint", ""),
545
+ entry.get("last_replacement_type", ""),
546
+ int(entry.get("repeat_replacement_count", 0)),
547
+ entry.get("last_structure_reason", ""),
548
+ float(entry.get("last_structure_confidence", 0.0)),
549
+ entry.get("last_tool_use_id", ""),
550
+ ),
551
+ )
552
+ conn.commit()
553
+
554
+ def delete_file_entry(self, file_path: str) -> None:
555
+ conn = self._connect()
556
+ conn.execute("DELETE FROM file_reads WHERE file_path = ?", (file_path,))
557
+ conn.commit()
558
+
559
+ def get_all_file_entries(self) -> dict[str, dict[str, Any]]:
560
+ conn = self._connect()
561
+ rows = conn.execute("SELECT * FROM file_reads").fetchall()
562
+ result: dict[str, dict[str, Any]] = {}
563
+ for row in rows:
564
+ entry = dict(row)
565
+ if entry.get("ranges_seen"):
566
+ try:
567
+ entry["ranges_seen"] = json.loads(entry["ranges_seen"])
568
+ except (json.JSONDecodeError, TypeError):
569
+ entry["ranges_seen"] = []
570
+ result[entry["file_path"]] = entry
571
+ return result
572
+
573
+ def clear_file_entries(self) -> None:
574
+ conn = self._connect()
575
+ conn.execute("DELETE FROM file_reads")
576
+ conn.commit()
577
+
578
+ # ----- cached_content -----
579
+
580
+ def get_cached_content(self, file_path: str) -> Optional[dict[str, Any]]:
581
+ conn = self._connect()
582
+ row = conn.execute(
583
+ "SELECT * FROM cached_content WHERE file_path = ?", (file_path,)
584
+ ).fetchone()
585
+ return dict(row) if row else None
586
+
587
+ def upsert_cached_content(
588
+ self, file_path: str, content: str, content_hash: str,
589
+ ) -> None:
590
+ if self._is_over_size_cap():
591
+ return
592
+ conn = self._connect()
593
+ conn.execute(
594
+ """INSERT INTO cached_content (file_path, content, content_hash, cached_at)
595
+ VALUES (?, ?, ?, ?)
596
+ ON CONFLICT(file_path) DO UPDATE SET
597
+ content=excluded.content,
598
+ content_hash=excluded.content_hash,
599
+ cached_at=excluded.cached_at
600
+ """,
601
+ (file_path, content, content_hash, time.time()),
602
+ )
603
+ conn.commit()
604
+
605
+ def delete_cached_content(self, file_path: str) -> None:
606
+ conn = self._connect()
607
+ conn.execute("DELETE FROM cached_content WHERE file_path = ?", (file_path,))
608
+ conn.commit()
609
+
610
+ # ----- tool_outputs -----
611
+
612
+ def insert_tool_output(
613
+ self,
614
+ tool_use_id: str,
615
+ tool_name: str,
616
+ tool_type: str,
617
+ command_or_path: str,
618
+ output_hash: str,
619
+ output_chars: int,
620
+ output_tokens_est: int,
621
+ compressed_preview: Optional[str] = None,
622
+ source_file_path: Optional[str] = None,
623
+ language: Optional[str] = None,
624
+ archived_from: Optional[str] = None,
625
+ output_text: Optional[str] = None,
626
+ ) -> None:
627
+ if self._is_over_size_cap():
628
+ return
629
+ conn = self._connect()
630
+ conn.execute(
631
+ """INSERT OR IGNORE INTO tool_outputs
632
+ (tool_use_id, tool_name, tool_type, command_or_path,
633
+ output_hash, output_chars, output_tokens_est,
634
+ compressed_preview, timestamp,
635
+ source_file_path, language, archived_from, output_text)
636
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
637
+ """,
638
+ (
639
+ tool_use_id, tool_name, tool_type, command_or_path,
640
+ output_hash, output_chars, output_tokens_est,
641
+ compressed_preview, time.time(),
642
+ source_file_path, language, archived_from, output_text,
643
+ ),
644
+ )
645
+ # fix-1: the external-content FTS mirror is maintained by the AFTER
646
+ # INSERT trigger, which fires only when the INSERT OR IGNORE above
647
+ # actually writes a new row. No manual FTS write here -- that was the
648
+ # source of duplicate FTS rows on re-insert of the same tool_use_id.
649
+ conn.commit()
650
+
651
+ # ----- tool_outputs search (U6: FTS5 with LIKE fallback) -----
652
+
653
+ def search_tool_outputs(self, query: str, limit: int = 20) -> list[dict[str, Any]]:
654
+ """Full-text search over archived tool outputs Returns rows of (tool_use_id, tool_name, command_or_path,
655
+ source_file_path, language, archived_from, snippet) ranked by
656
+ relevance. Uses FTS5 ``bm25()`` when available; falls back to a
657
+ bounded ``LIKE '%term%'`` query over the lineage + output_text
658
+ columns when FTS5 is not compiled into SQLite. Never raises: an
659
+ empty/invalid query or a missing index returns an empty list.
660
+ """
661
+ if not query or not query.strip():
662
+ return []
663
+ conn = self._connect()
664
+ safe_limit = max(1, min(int(limit or 20), 200))
665
+ if SessionStore._fts5_available:
666
+ try:
667
+ rows = conn.execute(
668
+ """SELECT t.tool_use_id, t.tool_name, t.command_or_path,
669
+ t.source_file_path, t.language, t.archived_from,
670
+ snippet(tool_outputs_fts, 6, '>>', '<<', '...', 16) AS snippet
671
+ FROM tool_outputs_fts f
672
+ JOIN tool_outputs t ON t.rowid = f.rowid
673
+ WHERE tool_outputs_fts MATCH ?
674
+ ORDER BY bm25(tool_outputs_fts)
675
+ LIMIT ?""",
676
+ (query, safe_limit),
677
+ ).fetchall()
678
+ # fix (LOW): the external-content mirror covers every base row,
679
+ # so a successful-but-EMPTY FTS result is authoritative -- there
680
+ # is no match. Return it directly; only fall through to LIKE on
681
+ # an actual OperationalError (e.g. an FTS MATCH syntax error).
682
+ return [dict(r) for r in rows]
683
+ except sqlite3.OperationalError:
684
+ pass # FTS query failed (e.g. MATCH syntax) -> try LIKE
685
+ # LIKE fallback: bounded substring search over lineage + output_text.
686
+ # fix-4: escape LIKE wildcards (% and _) in the user query and declare
687
+ # an ESCAPE char so a literal '%'/'_' matches itself, not any-run.
688
+ try:
689
+ escaped = (
690
+ query.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
691
+ )
692
+ pattern = f"%{escaped}%"
693
+ rows = conn.execute(
694
+ r"""SELECT tool_use_id, tool_name, command_or_path,
695
+ source_file_path, language, archived_from,
696
+ substr(COALESCE(output_text, compressed_preview, ''), 1, 200) AS snippet
697
+ FROM tool_outputs
698
+ WHERE tool_name LIKE ? ESCAPE '\' OR command_or_path LIKE ? ESCAPE '\'
699
+ OR source_file_path LIKE ? ESCAPE '\' OR language LIKE ? ESCAPE '\'
700
+ OR archived_from LIKE ? ESCAPE '\' OR output_text LIKE ? ESCAPE '\'
701
+ OR compressed_preview LIKE ? ESCAPE '\'
702
+ ORDER BY timestamp DESC
703
+ LIMIT ?""",
704
+ (pattern, pattern, pattern, pattern, pattern, pattern, pattern, safe_limit),
705
+ ).fetchall()
706
+ return [dict(r) for r in rows]
707
+ except sqlite3.OperationalError:
708
+ return []
709
+
710
+ # ----- command_outputs -----
711
+
712
+ def get_command_output(self, command_hash: str) -> Optional[dict[str, Any]]:
713
+ conn = self._connect()
714
+ row = conn.execute(
715
+ "SELECT * FROM command_outputs WHERE command_hash = ?", (command_hash,)
716
+ ).fetchone()
717
+ return dict(row) if row else None
718
+
719
+ def insert_command_output(
720
+ self,
721
+ command_hash: str,
722
+ command_text: str,
723
+ output_hash: str,
724
+ output_chars: int,
725
+ compressed_output: Optional[str] = None,
726
+ tool_use_id: str = "",
727
+ ) -> None:
728
+ if self._is_over_size_cap():
729
+ return
730
+ conn = self._connect()
731
+ conn.execute(
732
+ """INSERT OR REPLACE INTO command_outputs
733
+ (command_hash, command_text, output_hash, output_chars,
734
+ compressed_output, timestamp, last_tool_use_id)
735
+ VALUES (?, ?, ?, ?, ?, ?, ?)
736
+ """,
737
+ (
738
+ command_hash, command_text, output_hash, output_chars,
739
+ compressed_output, time.time(), tool_use_id or "",
740
+ ),
741
+ )
742
+ conn.commit()
743
+
744
+ # ----- command_run_streaks (thrash guard) -----
745
+
746
+ def get_command_streak(self, command_hash: str) -> Optional[dict[str, Any]]:
747
+ conn = self._connect()
748
+ row = conn.execute(
749
+ "SELECT * FROM command_run_streaks WHERE command_hash = ?", (command_hash,)
750
+ ).fetchone()
751
+ return dict(row) if row else None
752
+
753
+ def upsert_command_streak(
754
+ self,
755
+ command_hash: str,
756
+ command_text: str,
757
+ output_hash: str,
758
+ streak: int,
759
+ nudged_streak: Optional[int],
760
+ last_ts: float,
761
+ fail_streak: int = 0,
762
+ fail_nudged_streak: Optional[int] = None,
763
+ inline_run_count: int = 0,
764
+ inline_nudged_count: Optional[int] = None,
765
+ ) -> None:
766
+ if self._is_over_size_cap():
767
+ # Cap hit: delete the stale row so the thrash guard fails open to
768
+ # "no streak" (streak=1, no nudge) rather than re-reading a frozen
769
+ # row that breaks the cooldown invariant.
770
+ try:
771
+ conn = self._connect()
772
+ conn.execute(
773
+ "DELETE FROM command_run_streaks WHERE command_hash = ?",
774
+ (command_hash,),
775
+ )
776
+ conn.commit()
777
+ except Exception:
778
+ pass
779
+ return
780
+ conn = self._connect()
781
+ conn.execute(
782
+ """INSERT OR REPLACE INTO command_run_streaks
783
+ (command_hash, command_text, output_hash, streak,
784
+ nudged_streak, last_ts, fail_streak, fail_nudged_streak,
785
+ inline_run_count, inline_nudged_count)
786
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
787
+ """,
788
+ (
789
+ command_hash, command_text[:500], output_hash, streak,
790
+ nudged_streak, last_ts, fail_streak, fail_nudged_streak,
791
+ inline_run_count, inline_nudged_count,
792
+ ),
793
+ )
794
+ conn.commit()
795
+
796
+ # ----- session_meta -----
797
+
798
+ def get_meta(self, key: str) -> Optional[str]:
799
+ conn = self._connect()
800
+ row = conn.execute(
801
+ "SELECT value FROM session_meta WHERE key = ?", (key,)
802
+ ).fetchone()
803
+ return row["value"] if row else None
804
+
805
+ def set_meta(self, key: str, value: str) -> None:
806
+ conn = self._connect()
807
+ conn.execute(
808
+ "INSERT OR REPLACE INTO session_meta (key, value) VALUES (?, ?)",
809
+ (key, value),
810
+ )
811
+ conn.commit()
812
+
813
+ # ----- context_intel_events -----
814
+
815
+ def insert_intel_event(
816
+ self,
817
+ tool_name: str,
818
+ tool_use_id: str,
819
+ summary: str,
820
+ output_chars: int,
821
+ ) -> None:
822
+ if self._is_over_size_cap():
823
+ return
824
+ conn = self._connect()
825
+ conn.execute(
826
+ """INSERT INTO context_intel_events
827
+ (tool_name, tool_use_id, summary, output_chars, timestamp)
828
+ VALUES (?, ?, ?, ?, ?)""",
829
+ (tool_name, tool_use_id, summary, output_chars, time.time()),
830
+ )
831
+ conn.commit()
832
+
833
+ def get_intel_events(self, limit: int = 20) -> list[dict[str, Any]]:
834
+ conn = self._connect()
835
+ rows = conn.execute(
836
+ """SELECT tool_name, summary, output_chars, timestamp
837
+ FROM context_intel_events
838
+ ORDER BY timestamp DESC
839
+ LIMIT ?""",
840
+ (limit,),
841
+ ).fetchall()
842
+ return [dict(r) for r in rows]
843
+
844
+ # ----- queries for dynamic compact instructions -----
845
+
846
+ def get_recent_file_reads(
847
+ self, limit: int = 10, min_read_count: int = 2,
848
+ ) -> list[dict[str, Any]]:
849
+ conn = self._connect()
850
+ rows = conn.execute(
851
+ """SELECT file_path, read_count, last_access
852
+ FROM file_reads
853
+ WHERE read_count >= ?
854
+ ORDER BY last_access DESC
855
+ LIMIT ?""",
856
+ (min_read_count, limit),
857
+ ).fetchall()
858
+ return [dict(r) for r in rows]
859
+
860
+ def get_one_time_reads(self, limit: int = 10) -> list[dict[str, Any]]:
861
+ conn = self._connect()
862
+ rows = conn.execute(
863
+ """SELECT file_path, tokens_est
864
+ FROM file_reads
865
+ WHERE read_count = 1
866
+ ORDER BY last_access ASC
867
+ LIMIT ?""",
868
+ (limit,),
869
+ ).fetchall()
870
+ return [dict(r) for r in rows]
871
+
872
+ def get_active_read_tokens(
873
+ self, limit: int = 25, min_read_count: int = 2,
874
+ ) -> int:
875
+ """Sum tokens_est of the session's active (repeatedly-read) files.
876
+
877
+ This is the working set a checkpoint restore lets a resumed session skip
878
+ re-reading -- the grounded basis for the avoided-reconstruction credit,
879
+ in place of the compressed checkpoint's own byte size.
880
+ """
881
+ conn = self._connect()
882
+ rows = conn.execute(
883
+ """SELECT COALESCE(tokens_est, 0) AS t
884
+ FROM file_reads
885
+ WHERE read_count >= ?
886
+ ORDER BY last_access DESC
887
+ LIMIT ?""",
888
+ (min_read_count, limit),
889
+ ).fetchall()
890
+ return int(sum(int(r["t"] or 0) for r in rows))
891
+
892
+ # ----- hint_serves (U-G: per-hint avoided-search measurement) -----
893
+
894
+ def record_hint_serve(self, file_paths) -> None:
895
+ """Record that a proactive prior-session hint surfaced these files to
896
+ this session. A later read of one of them is observed evidence the hint
897
+ spared an exploratory search (credited once via claim_hint_follow)."""
898
+ paths = [str(p).strip() for p in (file_paths or []) if str(p or "").strip()]
899
+ if not paths:
900
+ return
901
+ # Defensive cap independent of the call site (which already slices to ~5):
902
+ # a hint never legitimately surfaces dozens of files, so bound the write.
903
+ paths = paths[:25]
904
+ conn = self._connect()
905
+ now = time.time()
906
+ conn.executemany(
907
+ """INSERT INTO hint_serves (file_path, served_at, credited)
908
+ VALUES (?, ?, 0)
909
+ ON CONFLICT(file_path) DO NOTHING""",
910
+ [(p, now) for p in paths],
911
+ )
912
+ conn.commit()
913
+
914
+ # Only credit a hint follow when the read happens within this window of the
915
+ # hint being served. Beyond it, a read of the same file is more likely a
916
+ # coincidence than the hint doing its job -- keeps the avoided-search credit
917
+ # causally honest (and conservative).
918
+ HINT_FOLLOW_MAX_AGE_SECONDS = 4 * 60 * 60
919
+
920
+ def claim_hint_follow(self, file_path: str, max_age_seconds: float = HINT_FOLLOW_MAX_AGE_SECONDS) -> bool:
921
+ """If file_path was hinted to this session recently and not yet credited,
922
+ mark it credited and return True (caller logs the avoided-search saving
923
+ once). Returns False otherwise. Idempotent: a path is credited at most
924
+ once, and only within max_age_seconds of the serve.
925
+
926
+ This runs on every Read hook, so the common case (no matching uncredited
927
+ hint) takes only a cheap indexed SELECT and never acquires a write lock.
928
+ """
929
+ if not file_path:
930
+ return False
931
+ conn = self._connect()
932
+ fresh_after = time.time() - max(0.0, max_age_seconds)
933
+ hit = conn.execute(
934
+ "SELECT 1 FROM hint_serves "
935
+ "WHERE file_path = ? AND credited = 0 AND served_at >= ? LIMIT 1",
936
+ (str(file_path), fresh_after),
937
+ ).fetchone()
938
+ if not hit:
939
+ return False
940
+ cur = conn.execute(
941
+ "UPDATE hint_serves SET credited = 1 "
942
+ "WHERE file_path = ? AND credited = 0 AND served_at >= ?",
943
+ (str(file_path), fresh_after),
944
+ )
945
+ conn.commit()
946
+ return cur.rowcount > 0
947
+
948
+ def get_high_value_outputs(
949
+ self, min_tokens: int = 500, limit: int = 5,
950
+ ) -> list[dict[str, Any]]:
951
+ conn = self._connect()
952
+ rows = conn.execute(
953
+ """SELECT tool_name, command_or_path, output_tokens_est
954
+ FROM tool_outputs
955
+ WHERE output_tokens_est >= ?
956
+ ORDER BY output_tokens_est DESC
957
+ LIMIT ?""",
958
+ (min_tokens, limit),
959
+ ).fetchall()
960
+ return [dict(r) for r in rows]
961
+
962
+
963
+ def cleanup_old_stores(max_age_hours: int = CLEANUP_AGE_HOURS) -> int:
964
+ """Delete session store DBs older than max_age_hours. Returns count deleted."""
965
+ if not SESSION_STORE_DIR.exists():
966
+ return 0
967
+ cutoff = time.time() - (max_age_hours * 3600)
968
+ deleted = 0
969
+ for db_file in SESSION_STORE_DIR.glob("*.db"):
970
+ try:
971
+ if db_file.stat().st_mtime < cutoff:
972
+ db_file.unlink()
973
+ for wal in (db_file.with_suffix(".db-wal"), db_file.with_suffix(".db-shm")):
974
+ if wal.exists():
975
+ wal.unlink()
976
+ deleted += 1
977
+ except OSError:
978
+ pass
979
+ return deleted