@alexgreensh/token-optimizer 5.13.68 → 5.13.70

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 (182) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/PRIVACY.md +4 -0
  4. package/hooks/hooks.json +11 -1
  5. package/hooks/module_runner.py +4 -1
  6. package/hooks/posttooluse_runner.py +44 -48
  7. package/hooks/sessionstart_runner.py +24 -5
  8. package/hooks/stop_runner.py +6 -6
  9. package/package.json +1 -1
  10. package/skills/fleet-auditor/references/fleet-systems.md +38 -0
  11. package/skills/fleet-auditor/scripts/fleet.py +63 -92
  12. package/skills/fleet-auditor/scripts/fleet_base.py +106 -0
  13. package/skills/fleet-auditor/scripts/fleet_cursor_adapter.py +376 -0
  14. package/skills/token-coach/SKILL.md +21 -23
  15. package/skills/token-dashboard/SKILL.md +5 -4
  16. package/skills/token-optimizer/SKILL.md +1 -1
  17. package/skills/token-optimizer/assets/dashboard.html +492 -551
  18. package/skills/token-optimizer/assets/savings_story.js +661 -0
  19. package/skills/token-optimizer/pricing/prices.json +1 -0
  20. package/skills/token-optimizer/references/cli-reference.md +1 -1
  21. package/skills/token-optimizer/references/cursor-workflow.md +1 -1
  22. package/skills/token-optimizer/references/implementation-playbook.md +3 -0
  23. package/skills/token-optimizer/references/phase0-setup.md +1 -1
  24. package/skills/token-optimizer/references/presentation-workflow.md +1 -1
  25. package/skills/token-optimizer/scripts/_measure/__init__.py +3 -1
  26. package/skills/token-optimizer/scripts/_measure/archive_health.py +14 -0
  27. package/skills/token-optimizer/scripts/_measure/archive_void_codex.py +163 -0
  28. package/skills/token-optimizer/scripts/_measure/archive_void_evidence.py +165 -0
  29. package/skills/token-optimizer/scripts/_measure/audit.py +27 -135
  30. package/skills/token-optimizer/scripts/_measure/baseline_provenance.py +339 -0
  31. package/skills/token-optimizer/scripts/_measure/cache_policy.py +261 -581
  32. package/skills/token-optimizer/scripts/_measure/checkpoint_direction.py +97 -0
  33. package/skills/token-optimizer/scripts/_measure/checkpoint_retention.py +20 -0
  34. package/skills/token-optimizer/scripts/_measure/cli.py +98 -8
  35. package/skills/token-optimizer/scripts/_measure/codex_quality.py +246 -0
  36. package/skills/token-optimizer/scripts/_measure/compaction_survival.py +158 -0
  37. package/skills/token-optimizer/scripts/_measure/compression_fixture_void.py +147 -0
  38. package/skills/token-optimizer/scripts/_measure/compression_scan_checkpoint.py +72 -0
  39. package/skills/token-optimizer/scripts/_measure/context_reset_marker.py +64 -0
  40. package/skills/token-optimizer/scripts/_measure/continuity.py +64 -118
  41. package/skills/token-optimizer/scripts/_measure/cost_per_message_trend.py +40 -0
  42. package/skills/token-optimizer/scripts/_measure/counted_cap.py +28 -0
  43. package/skills/token-optimizer/scripts/_measure/counted_orphans.py +190 -0
  44. package/skills/token-optimizer/scripts/_measure/counted_position.py +20 -0
  45. package/skills/token-optimizer/scripts/_measure/counted_pricing_v5.py +267 -0
  46. package/skills/token-optimizer/scripts/_measure/counted_subagents.py +371 -0
  47. package/skills/token-optimizer/scripts/_measure/coverage_report.py +285 -0
  48. package/skills/token-optimizer/scripts/_measure/daemon.py +61 -94
  49. package/skills/token-optimizer/scripts/_measure/dashboard.py +149 -187
  50. package/skills/token-optimizer/scripts/_measure/dashboard_heal_claim.py +36 -0
  51. package/skills/token-optimizer/scripts/_measure/dashboard_history.py +79 -0
  52. package/skills/token-optimizer/scripts/_measure/evidence_parallel.py +95 -0
  53. package/skills/token-optimizer/scripts/_measure/feature_health.py +256 -0
  54. package/skills/token-optimizer/scripts/_measure/file_refetch.py +250 -0
  55. package/skills/token-optimizer/scripts/_measure/first_call_context.py +216 -0
  56. package/skills/token-optimizer/scripts/_measure/first_read_outcomes.py +261 -0
  57. package/skills/token-optimizer/scripts/_measure/first_read_revive.py +137 -0
  58. package/skills/token-optimizer/scripts/_measure/fixture_context.py +65 -0
  59. package/skills/token-optimizer/scripts/_measure/headline.py +100 -0
  60. package/skills/token-optimizer/scripts/_measure/holdout_fallback.py +96 -0
  61. package/skills/token-optimizer/scripts/_measure/holdout_report.py +125 -0
  62. package/skills/token-optimizer/scripts/_measure/keepwarm_economics.py +201 -0
  63. package/skills/token-optimizer/scripts/_measure/keepwarm_fork.py +140 -0
  64. package/skills/token-optimizer/scripts/_measure/keepwarm_guard.py +35 -0
  65. package/skills/token-optimizer/scripts/_measure/keepwarm_guard_server.py +85 -0
  66. package/skills/token-optimizer/scripts/_measure/keepwarm_linux.py +121 -0
  67. package/skills/token-optimizer/scripts/_measure/keepwarm_prefix.py +143 -0
  68. package/skills/token-optimizer/scripts/_measure/keepwarm_response_filter.py +84 -0
  69. package/skills/token-optimizer/scripts/_measure/keepwarm_safety.py +256 -0
  70. package/skills/token-optimizer/scripts/_measure/lean_resume_receivers.py +260 -0
  71. package/skills/token-optimizer/scripts/_measure/lean_resume_threshold.py +76 -0
  72. package/skills/token-optimizer/scripts/_measure/lease_candidate_cleanup.py +82 -0
  73. package/skills/token-optimizer/scripts/_measure/lifecycle.py +59 -168
  74. package/skills/token-optimizer/scripts/_measure/mcp_archive_tripwire.py +120 -0
  75. package/skills/token-optimizer/scripts/_measure/mod_action_booking.py +178 -0
  76. package/skills/token-optimizer/scripts/_measure/mod_compaction_booking.py +276 -0
  77. package/skills/token-optimizer/scripts/_measure/mod_fresh_booking.py +105 -0
  78. package/skills/token-optimizer/scripts/_measure/output_reread.py +629 -0
  79. package/skills/token-optimizer/scripts/_measure/own_price_card.py +268 -0
  80. package/skills/token-optimizer/scripts/_measure/periphery_exposure.py +85 -0
  81. package/skills/token-optimizer/scripts/_measure/pricing.py +152 -87
  82. package/skills/token-optimizer/scripts/_measure/quality_archive.py +159 -215
  83. package/skills/token-optimizer/scripts/_measure/quality_checkpoint.py +173 -0
  84. package/skills/token-optimizer/scripts/_measure/quality_continuity.py +43 -0
  85. package/skills/token-optimizer/scripts/_measure/rework_metrics.py +194 -0
  86. package/skills/token-optimizer/scripts/_measure/routing_period.py +48 -0
  87. package/skills/token-optimizer/scripts/_measure/savings.py +451 -933
  88. package/skills/token-optimizer/scripts/_measure/savings_story.py +187 -0
  89. package/skills/token-optimizer/scripts/_measure/session_best.py +24 -0
  90. package/skills/token-optimizer/scripts/_measure/session_effect.py +557 -0
  91. package/skills/token-optimizer/scripts/_measure/session_flush_lock.py +75 -0
  92. package/skills/token-optimizer/scripts/_measure/session_store_spool.py +220 -0
  93. package/skills/token-optimizer/scripts/_measure/sessions.py +154 -216
  94. package/skills/token-optimizer/scripts/_measure/setup_attachment_counter.py +196 -0
  95. package/skills/token-optimizer/scripts/_measure/setup_budget_monitor.py +180 -0
  96. package/skills/token-optimizer/scripts/_measure/setup_connector_ledger.py +126 -0
  97. package/skills/token-optimizer/scripts/_measure/setup_step.py +220 -0
  98. package/skills/token-optimizer/scripts/_measure/status_bar_lock.py +117 -0
  99. package/skills/token-optimizer/scripts/_measure/structural_archives.py +79 -0
  100. package/skills/token-optimizer/scripts/_measure/structural_dedupe.py +91 -0
  101. package/skills/token-optimizer/scripts/_measure/structural_ledger.py +418 -0
  102. package/skills/token-optimizer/scripts/_measure/structural_listing.py +163 -0
  103. package/skills/token-optimizer/scripts/_measure/structural_report.py +339 -0
  104. package/skills/token-optimizer/scripts/_measure/structural_seed.py +164 -0
  105. package/skills/token-optimizer/scripts/_measure/structural_value.py +248 -0
  106. package/skills/token-optimizer/scripts/_measure/structure_funnel.py +97 -0
  107. package/skills/token-optimizer/scripts/_measure/timestamp_cache.py +11 -0
  108. package/skills/token-optimizer/scripts/_measure/token_type_split.py +29 -0
  109. package/skills/token-optimizer/scripts/_measure/transcript_backfill.py +419 -0
  110. package/skills/token-optimizer/scripts/_measure/transcript_product.py +228 -0
  111. package/skills/token-optimizer/scripts/_measure/transcript_stream.py +279 -0
  112. package/skills/token-optimizer/scripts/_measure/trends.py +44 -185
  113. package/skills/token-optimizer/scripts/_measure/ttl_period.py +6 -0
  114. package/skills/token-optimizer/scripts/_measure/upgrade_drain_control.py +287 -0
  115. package/skills/token-optimizer/scripts/_measure/weekly_activity.py +69 -0
  116. package/skills/token-optimizer/scripts/activity_tracker.py +4 -33
  117. package/skills/token-optimizer/scripts/antigravity_install.py +6 -0
  118. package/skills/token-optimizer/scripts/archive_result.py +15 -19
  119. package/skills/token-optimizer/scripts/archive_verify.py +165 -0
  120. package/skills/token-optimizer/scripts/bash_compress.py +22 -83
  121. package/skills/token-optimizer/scripts/bash_compress_hook.py +137 -1
  122. package/skills/token-optimizer/scripts/bash_search_results.py +43 -0
  123. package/skills/token-optimizer/scripts/checkpoint_state.py +2 -2
  124. package/skills/token-optimizer/scripts/cloud_kit.py +3 -6
  125. package/skills/token-optimizer/scripts/codemap.py +274 -0
  126. package/skills/token-optimizer/scripts/codemap_hint.py +153 -0
  127. package/skills/token-optimizer/scripts/codemap_index.py +656 -0
  128. package/skills/token-optimizer/scripts/codemap_ledger.py +309 -0
  129. package/skills/token-optimizer/scripts/codemap_reread.py +161 -0
  130. package/skills/token-optimizer/scripts/codex_doctor.py +9 -1
  131. package/skills/token-optimizer/scripts/codex_log_index.py +34 -15
  132. package/skills/token-optimizer/scripts/codex_session.py +16 -216
  133. package/skills/token-optimizer/scripts/compression_backfill.py +4 -35
  134. package/skills/token-optimizer/scripts/context_intel.py +5 -3
  135. package/skills/token-optimizer/scripts/copilot_install.py +6 -0
  136. package/skills/token-optimizer/scripts/coverage_funnel.py +261 -0
  137. package/skills/token-optimizer/scripts/credential_patterns.py +4 -19
  138. package/skills/token-optimizer/scripts/credential_url_patterns.py +42 -0
  139. package/skills/token-optimizer/scripts/cursor_audit.py +723 -0
  140. package/skills/token-optimizer/scripts/cursor_bridge_checkpoint.py +213 -0
  141. package/skills/token-optimizer/scripts/cursor_bridge_payload.py +170 -0
  142. package/skills/token-optimizer/scripts/cursor_bridge_rewrite.py +106 -0
  143. package/skills/token-optimizer/scripts/cursor_bridge_rollup.py +115 -0
  144. package/skills/token-optimizer/scripts/cursor_coach.py +485 -0
  145. package/skills/token-optimizer/scripts/cursor_doctor.py +89 -9
  146. package/skills/token-optimizer/scripts/cursor_hook_bridge.py +393 -276
  147. package/skills/token-optimizer/scripts/cursor_install.py +118 -19
  148. package/skills/token-optimizer/scripts/cursor_quality.py +457 -0
  149. package/skills/token-optimizer/scripts/cursor_read_cache.py +597 -0
  150. package/skills/token-optimizer/scripts/cursor_session.py +26 -5
  151. package/skills/token-optimizer/scripts/cursor_state.py +8 -0
  152. package/skills/token-optimizer/scripts/cursor_statusline.py +372 -0
  153. package/skills/token-optimizer/scripts/cursor_thrash.py +78 -0
  154. package/skills/token-optimizer/scripts/cursor_transcript.py +223 -0
  155. package/skills/token-optimizer/scripts/dashboard_assets.py +21 -0
  156. package/skills/token-optimizer/scripts/deterministic_candidates.py +2 -10
  157. package/skills/token-optimizer/scripts/devin_source.py +19 -4
  158. package/skills/token-optimizer/scripts/devin_verify.py +13 -6
  159. package/skills/token-optimizer/scripts/grok_install.py +6 -0
  160. package/skills/token-optimizer/scripts/heal_report.py +7 -6
  161. package/skills/token-optimizer/scripts/hermes_doctor.py +12 -1
  162. package/skills/token-optimizer/scripts/hermes_install.py +10 -1
  163. package/skills/token-optimizer/scripts/hermes_session.py +14 -136
  164. package/skills/token-optimizer/scripts/hint_paths.py +21 -0
  165. package/skills/token-optimizer/scripts/holdout.py +136 -0
  166. package/skills/token-optimizer/scripts/hook_runtime.py +1 -0
  167. package/skills/token-optimizer/scripts/hook_skip_log.py +89 -0
  168. package/skills/token-optimizer/scripts/large_transcripts.py +31 -0
  169. package/skills/token-optimizer/scripts/lean_resume_carry.py +518 -0
  170. package/skills/token-optimizer/scripts/measure.py +36 -78
  171. package/skills/token-optimizer/scripts/post_run_classify.py +349 -0
  172. package/skills/token-optimizer/scripts/preserved_reinject.py +54 -0
  173. package/skills/token-optimizer/scripts/read_cache.py +99 -100
  174. package/skills/token-optimizer/scripts/reset_epoch.py +3 -3
  175. package/skills/token-optimizer/scripts/session_store.py +49 -99
  176. package/skills/token-optimizer/scripts/session_store_guard.py +75 -0
  177. package/skills/token-optimizer/scripts/settings_backup.py +379 -0
  178. package/skills/token-optimizer/scripts/shipped_hook_templates.py +1 -0
  179. package/skills/token-optimizer/scripts/statusline.js +1 -1
  180. package/skills/token-optimizer/scripts/structural.py +25 -0
  181. package/skills/token-optimizer/scripts/structure_map.py +4 -26
  182. package/skills/token-optimizer/scripts/thrash_guard.py +10 -5
@@ -14,8 +14,7 @@ PRIMARY KEY, legacy rows backfilled by a one-time ``rebuild``). A bounded
14
14
 
15
15
  Configuration:
16
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)
17
+ - busy_timeout=50ms: bound database waits; tracking events can be queued
19
18
  - synchronous=NORMAL (WAL-safe relaxation for performance)
20
19
  - 50MB cap per session DB
21
20
  - PreToolUse hooks: READ-ONLY queries only
@@ -28,11 +27,15 @@ import hashlib
28
27
  import json
29
28
  import re
30
29
  import sqlite3
30
+ import sys
31
31
  import time
32
32
  import uuid
33
+ import session_store_guard
34
+ from _measure import session_store_spool
33
35
  from pathlib import Path
34
36
  from typing import Any, Optional
35
37
 
38
+ from hint_paths import normalize_hint_path
36
39
  from plugin_env import resolve_snapshot_dir
37
40
  from reset_epoch import ResetEpochMixin, bump_reset_epoch
38
41
 
@@ -69,7 +72,7 @@ CREATE TABLE IF NOT EXISTS file_reads (
69
72
  last_structure_confidence REAL DEFAULT 0.0,
70
73
  last_tool_use_id TEXT DEFAULT ''
71
74
  );
72
-
75
+ CREATE INDEX IF NOT EXISTS idx_file_reads_last_access ON file_reads(last_access DESC);
73
76
  CREATE TABLE IF NOT EXISTS tool_outputs (
74
77
  tool_use_id TEXT PRIMARY KEY,
75
78
  tool_name TEXT NOT NULL,
@@ -130,7 +133,7 @@ CREATE TABLE IF NOT EXISTS context_intel_events (
130
133
  output_chars INTEGER NOT NULL,
131
134
  timestamp REAL NOT NULL
132
135
  );
133
-
136
+ CREATE INDEX IF NOT EXISTS idx_intel_timestamp ON context_intel_events(timestamp DESC); CREATE INDEX IF NOT EXISTS idx_intel_tool_use ON context_intel_events(tool_use_id);
134
137
  CREATE TABLE IF NOT EXISTS activity_log (
135
138
  id INTEGER PRIMARY KEY AUTOINCREMENT,
136
139
  tool_name TEXT NOT NULL,
@@ -220,29 +223,25 @@ class SessionStore(ResetEpochMixin):
220
223
  if self._conn is not None:
221
224
  return self._conn
222
225
  self._store_dir.mkdir(parents=True, exist_ok=True, mode=0o700)
223
- # Align the connect timeout (seconds) with the PRAGMA busy_timeout (ms)
224
- # so the schema init AND later writes honor the same lock-wait budget.
225
226
  timeout_s = max(0.05, self._busy_timeout_ms / 1000.0)
226
- self._conn = sqlite3.connect(str(self.db_path), timeout=timeout_s)
227
- self._conn.execute("PRAGMA journal_mode=WAL")
228
- self._conn.execute(f"PRAGMA busy_timeout={int(self._busy_timeout_ms)}")
229
- self._conn.execute("PRAGMA synchronous=NORMAL")
230
- # Defense-in-depth privacy (the parent dir is already 0700): the DB and
231
- # its WAL/SHM sidecars hold cached tool output, so restrict them to the
232
- # owner (0600). sqlite creates them honoring umask (commonly 0644), so
233
- # tighten explicitly. Best-effort; never break a connect on chmod.
234
- import os as _os
235
- for _p in (
236
- self.db_path,
237
- self.db_path.with_suffix(".db-wal"),
238
- self.db_path.with_suffix(".db-shm"),
239
- ):
240
- try:
241
- _os.chmod(_p, 0o600)
242
- except OSError:
243
- pass
244
- self._conn.row_factory = sqlite3.Row
245
- self._init_schema()
227
+ self._conn = session_store_guard.connect(self, timeout_s)
228
+ try:
229
+ self._conn.execute("PRAGMA journal_mode=WAL")
230
+ self._conn.execute(f"PRAGMA busy_timeout={int(self._busy_timeout_ms)}")
231
+ self._conn.execute("PRAGMA synchronous=NORMAL")
232
+ # The DB and its sidecars contain private cached output.
233
+ import os as _os
234
+ for _p in (self.db_path, self.db_path.with_suffix(".db-wal"),
235
+ self.db_path.with_suffix(".db-shm")):
236
+ try:
237
+ _os.chmod(_p, 0o600)
238
+ except OSError:
239
+ pass
240
+ self._conn.row_factory = sqlite3.Row
241
+ self._init_schema()
242
+ except BaseException:
243
+ self.close()
244
+ raise
246
245
  return self._conn
247
246
 
248
247
  def _init_schema(self) -> None:
@@ -268,8 +267,6 @@ class SessionStore(ResetEpochMixin):
268
267
  # U6/fix-1: probe + setup the external-content FTS5 mirror (LIKE
269
268
  # fallback). Backfills legacy rows once, gated on prior_version < 2.
270
269
  self._ensure_fts5_index(conn, prior_version)
271
- # Stamp the current schema version last (INSERT OR REPLACE so the bump
272
- # actually lands on pre-existing DBs, not just brand-new ones).
273
270
  conn.execute(
274
271
  "INSERT OR REPLACE INTO session_meta (key, value) VALUES (?, ?)",
275
272
  ("_schema_version", str(_SCHEMA_VERSION)),
@@ -510,8 +507,9 @@ class SessionStore(ResetEpochMixin):
510
507
  try:
511
508
  self._conn.close()
512
509
  except Exception:
513
- pass
510
+ return
514
511
  self._conn = None
512
+ session_store_guard.release(self)
515
513
 
516
514
  _cap_warned = False
517
515
 
@@ -649,32 +647,14 @@ class SessionStore(ResetEpochMixin):
649
647
  output_text: Optional[str] = None,
650
648
  truncated: Optional[int] = None,
651
649
  ) -> None:
652
- if self._is_over_size_cap():
653
- return
654
650
  index_text, index_truncated = _bound_tool_output_index(output_text)
655
- conn = self._connect()
656
- conn.execute(
657
- """INSERT OR IGNORE INTO tool_outputs
658
- (tool_use_id, tool_name, tool_type, command_or_path,
659
- output_hash, output_chars, output_tokens_est,
660
- compressed_preview, timestamp,
661
- source_file_path, language, archived_from, output_text,
662
- truncated, index_truncated)
663
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
664
- """,
665
- (
651
+ session_store_spool.enqueue(self, {"kind": "tool_output", "values": (
666
652
  tool_use_id, tool_name, tool_type, command_or_path,
667
653
  output_hash, output_chars, output_tokens_est,
668
654
  compressed_preview, time.time(),
669
655
  source_file_path, language, archived_from, index_text,
670
656
  truncated, index_truncated,
671
- ),
672
- )
673
- # fix-1: the external-content FTS mirror is maintained by the AFTER
674
- # INSERT trigger, which fires only when the INSERT OR IGNORE above
675
- # actually writes a new row. No manual FTS write here -- that was the
676
- # source of duplicate FTS rows on re-insert of the same tool_use_id.
677
- conn.commit()
657
+ )})
678
658
 
679
659
  # ----- tool_outputs search (U6: FTS5 with LIKE fallback) -----
680
660
 
@@ -846,7 +826,7 @@ class SessionStore(ResetEpochMixin):
846
826
  def record_file_edit(self, file_path: str) -> None:
847
827
  """Keep edit evidence without persisting credential-shaped path text."""
848
828
  fingerprint = hashlib.sha256(file_path.encode("utf-8")).hexdigest()
849
- self.set_meta("checkpoint_edit:" + fingerprint, "1")
829
+ session_store_spool.enqueue(self, {"kind": "file_edit", "fingerprint": fingerprint})
850
830
 
851
831
  def was_file_edited(self, file_path: str) -> bool:
852
832
  fingerprint = hashlib.sha256(file_path.encode("utf-8")).hexdigest()
@@ -861,16 +841,7 @@ class SessionStore(ResetEpochMixin):
861
841
  summary: str,
862
842
  output_chars: int,
863
843
  ) -> None:
864
- if self._is_over_size_cap():
865
- return
866
- conn = self._connect()
867
- conn.execute(
868
- """INSERT INTO context_intel_events
869
- (tool_name, tool_use_id, summary, output_chars, timestamp)
870
- VALUES (?, ?, ?, ?, ?)""",
871
- (tool_name, tool_use_id, summary, output_chars, time.time()),
872
- )
873
- conn.commit()
844
+ session_store_spool.enqueue_intel(self, tool_name, tool_use_id, summary, output_chars)
874
845
 
875
846
  def get_intel_events(self, limit: int = 20) -> list[dict[str, Any]]:
876
847
  conn = self._connect()
@@ -937,26 +908,17 @@ class SessionStore(ResetEpochMixin):
937
908
  """Record that a proactive prior-session hint surfaced these files to
938
909
  this session. A later read of one of them is observed evidence the hint
939
910
  spared an exploratory search (credited once via claim_hint_follow)."""
940
- paths = [str(p).strip() for p in (file_paths or []) if str(p or "").strip()]
911
+ paths = [normalize_hint_path(p) for p in (file_paths or []) if str(p or "").strip()]
941
912
  if not paths:
942
913
  return
943
- # Defensive cap independent of the call site (which already slices to ~5):
944
- # a hint never legitimately surfaces dozens of files, so bound the write.
914
+ # Defensive cap, independent of the call site (which slices to ~5).
945
915
  paths = paths[:25]
946
- conn = self._connect()
947
- now = time.time()
948
- conn.executemany(
949
- """INSERT INTO hint_serves (file_path, served_at, credited)
950
- VALUES (?, ?, 0)
951
- ON CONFLICT(file_path) DO NOTHING""",
952
- [(p, now) for p in paths],
953
- )
954
- conn.commit()
916
+ epoch = session_store_spool.hint_epoch(self)
917
+ session_store_spool.enqueue(self, {"kind": "hint_serves", "paths": paths, "timestamp": time.time(),
918
+ "reset_epoch": epoch})
955
919
 
956
- # Only credit a hint follow when the read happens within this window of the
957
- # hint being served. Beyond it, a read of the same file is more likely a
958
- # coincidence than the hint doing its job -- keeps the avoided-search credit
959
- # causally honest (and conservative).
920
+ # Credit a follow only within this window of the serve; later reads of the
921
+ # same file are more likely coincidence (keeps the credit conservative).
960
922
  HINT_FOLLOW_MAX_AGE_SECONDS = 4 * 60 * 60
961
923
 
962
924
  def claim_hint_follow(self, file_path: str, max_age_seconds: float = HINT_FOLLOW_MAX_AGE_SECONDS) -> bool:
@@ -972,17 +934,18 @@ class SessionStore(ResetEpochMixin):
972
934
  return False
973
935
  conn = self._connect()
974
936
  fresh_after = time.time() - max(0.0, max_age_seconds)
937
+ keys = (normalize_hint_path(file_path), str(file_path)) # raw: pre-normalization rows
975
938
  hit = conn.execute(
976
939
  "SELECT 1 FROM hint_serves "
977
- "WHERE file_path = ? AND credited = 0 AND served_at >= ? LIMIT 1",
978
- (str(file_path), fresh_after),
940
+ "WHERE file_path IN (?, ?) AND credited = 0 AND served_at >= ? LIMIT 1",
941
+ (*keys, fresh_after),
979
942
  ).fetchone()
980
943
  if not hit:
981
944
  return False
982
945
  cur = conn.execute(
983
946
  "UPDATE hint_serves SET credited = 1 "
984
- "WHERE file_path = ? AND credited = 0 AND served_at >= ?",
985
- (str(file_path), fresh_after),
947
+ "WHERE file_path IN (?, ?) AND credited = 0 AND served_at >= ?",
948
+ (*keys, fresh_after),
986
949
  )
987
950
  conn.commit()
988
951
  return cur.rowcount > 0
@@ -1024,10 +987,11 @@ def mark_context_reset(session_id: str, snapshot_dir: Optional[Path] = None) ->
1024
987
  marker = _context_reset_marker(session_id, snapshot_dir)
1025
988
  if marker is None:
1026
989
  return
1027
- marker.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
1028
- marker.write_text(repr(time.time()), encoding="utf-8")
1029
- except OSError:
1030
- pass
990
+ from _measure import context_reset_marker
991
+ if not context_reset_marker.publish(marker, time.time()):
992
+ print("[Session Store] Context reset marker not updated: lock busy", file=sys.stderr)
993
+ except OSError as exc:
994
+ print("[Session Store] Context reset marker not updated: " + str(exc), file=sys.stderr)
1031
995
 
1032
996
 
1033
997
  def context_reset_at(session_id: str, snapshot_dir: Optional[Path] = None) -> float:
@@ -1043,18 +1007,4 @@ def context_reset_at(session_id: str, snapshot_dir: Optional[Path] = None) -> fl
1043
1007
 
1044
1008
  def cleanup_old_stores(max_age_hours: int = CLEANUP_AGE_HOURS) -> int:
1045
1009
  """Delete session store DBs older than max_age_hours. Returns count deleted."""
1046
- if not SESSION_STORE_DIR.exists():
1047
- return 0
1048
- cutoff = time.time() - (max_age_hours * 3600)
1049
- deleted = 0
1050
- for db_file in SESSION_STORE_DIR.glob("*.db"):
1051
- try:
1052
- if db_file.stat().st_mtime < cutoff:
1053
- db_file.unlink()
1054
- for wal in (db_file.with_suffix(".db-wal"), db_file.with_suffix(".db-shm")):
1055
- if wal.exists():
1056
- wal.unlink()
1057
- deleted += 1
1058
- except OSError:
1059
- pass
1060
- return deleted
1010
+ return session_store_guard.prune_old_stores(SESSION_STORE_DIR, time.time() - max_age_hours * 3600)
@@ -0,0 +1,75 @@
1
+ """Coordinate session-store connections with age-based cleanup."""
2
+ import errno
3
+ import os
4
+ import sqlite3
5
+ import time
6
+
7
+ try:
8
+ import fcntl
9
+ except ImportError:
10
+ fcntl = None
11
+
12
+
13
+ def _open_guard(db_path):
14
+ flags = os.O_RDWR | os.O_CREAT | getattr(os, "O_NOFOLLOW", 0)
15
+ return os.fdopen(os.open(str(db_path.with_suffix(".db.guard")), flags, 0o600), "r+b")
16
+
17
+
18
+ def connect(store, timeout):
19
+ if fcntl is None:
20
+ return sqlite3.connect(str(store.db_path), timeout=timeout)
21
+ guard = _open_guard(store.db_path)
22
+ try:
23
+ try:
24
+ deadline = time.monotonic() + timeout
25
+ while True:
26
+ try:
27
+ fcntl.flock(guard.fileno(), fcntl.LOCK_SH | fcntl.LOCK_NB)
28
+ break
29
+ except BlockingIOError as exc:
30
+ remaining = deadline - time.monotonic()
31
+ if remaining <= 0:
32
+ raise sqlite3.OperationalError("session store cleanup lock timed out") from exc
33
+ time.sleep(min(0.01, remaining))
34
+ except OSError as exc:
35
+ if exc.errno in (errno.ENOSYS, errno.ENOTSUP, errno.EOPNOTSUPP):
36
+ guard.close()
37
+ return sqlite3.connect(str(store.db_path), timeout=timeout)
38
+ raise
39
+ conn = sqlite3.connect(str(store.db_path), timeout=timeout)
40
+ except BaseException:
41
+ guard.close()
42
+ raise
43
+ store._cleanup_guard = guard
44
+ return conn
45
+
46
+
47
+ def release(store):
48
+ guard = getattr(store, "_cleanup_guard", None)
49
+ if guard is not None:
50
+ store._cleanup_guard = None
51
+ guard.close()
52
+
53
+
54
+ def prune_old_stores(directory, cutoff):
55
+ # Unsupported platforms retain stores rather than race an active connection.
56
+ if fcntl is None or not directory.exists():
57
+ return 0
58
+ deleted = 0
59
+ for db_path in directory.glob("*.db"):
60
+ try:
61
+ with _open_guard(db_path) as guard:
62
+ try:
63
+ fcntl.flock(guard.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
64
+ except BlockingIOError:
65
+ continue
66
+ if db_path.stat().st_mtime >= cutoff or db_path.with_suffix(".db-wal").exists():
67
+ continue
68
+ db_path.unlink()
69
+ shm = db_path.with_suffix(".db-shm")
70
+ if shm.exists():
71
+ shm.unlink()
72
+ deleted += 1
73
+ except OSError:
74
+ continue
75
+ return deleted