tokensafe 4.4.9 → 4.5.1

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 (65) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/bin/agy-tokens +10 -1
  3. package/bin/tokensafe.js +2 -1
  4. package/hooks/claude_code_hook.py +38 -126
  5. package/hooks/cursor_hook.py +45 -1
  6. package/hooks/kimi_hook.py +46 -90
  7. package/hooks/pre_invocation.py +23 -4
  8. package/hooks/pre_tool_use.py +40 -22
  9. package/hooks/session_start.py +44 -15
  10. package/hooks/zcode_hook.py +95 -0
  11. package/hooks.json +1 -1
  12. package/kimi.plugin.json +17 -1
  13. package/mcp_config.json +24 -1
  14. package/package.json +1 -1
  15. package/plugin.json +1 -1
  16. package/rules/AGENTS.md +24 -21
  17. package/server.json +3 -3
  18. package/skills/token-optimizer/SKILL.md +61 -76
  19. package/skills/token-optimizer/references/mcp-tools.md +32 -132
  20. package/src/adapter_core.py +231 -7
  21. package/src/batch_editor.py +403 -0
  22. package/src/batch_search.py +428 -0
  23. package/src/burn_monitor.py +581 -0
  24. package/src/cache_normalizer.py +2 -0
  25. package/src/cli.py +85 -4
  26. package/src/compactor.py +1 -1
  27. package/src/dashboard.py +17 -9
  28. package/src/diff_slicer.py +1 -1
  29. package/src/distiller.py +11 -1
  30. package/src/environment_auditor.py +30 -6
  31. package/src/format_parsers/ansi.py +1 -1
  32. package/src/format_parsers/lockfiles.py +22 -17
  33. package/src/format_parsers/tabular.py +6 -3
  34. package/src/fts_index.py +26 -20
  35. package/src/governor.py +2 -2
  36. package/src/graph_engine.py +232 -52
  37. package/src/guard.py +3 -3
  38. package/src/image_downscale.py +26 -0
  39. package/src/installer.py +61 -48
  40. package/src/license_manager.py +49 -16
  41. package/src/live_relay.py +9 -8
  42. package/src/mcp_proxy.py +13 -7
  43. package/src/mcp_server.py +758 -26
  44. package/src/metrics.py +10 -1
  45. package/src/mistakes.py +4 -2
  46. package/src/oumv_gateway.py +81 -7
  47. package/src/paths.py +4 -1
  48. package/src/proxy.py +302 -123
  49. package/src/result_ledger.py +39 -1
  50. package/src/schema_slicer.py +40 -18
  51. package/src/scoped_search.py +66 -23
  52. package/src/skeletonizer.py +22 -11
  53. package/src/slicer.py +6 -4
  54. package/src/snapshot.py +249 -0
  55. package/src/stash.py +37 -7
  56. package/src/superseded.py +42 -23
  57. package/src/syntax_guard.py +86 -0
  58. package/src/team_cache.py +3 -0
  59. package/src/telemetry_sync.py +66 -53
  60. package/src/thinking_fold.py +50 -12
  61. package/src/transcript_analyzer.py +483 -0
  62. package/src/treesitter_backend.py +2 -0
  63. package/src/type_slicer.py +60 -18
  64. package/src/version_checker.py +1 -1
  65. package/src/web_reader.py +55 -22
package/src/cli.py CHANGED
@@ -106,6 +106,8 @@ def _print_help():
106
106
  print(" status One-screen health check: hooks, weekly savings, tier, sync")
107
107
  print(" budget [--transcript=...] Context Window Budget HUD & Context Quality Score (Grade S-F)")
108
108
  print(" compact <transcript.jsonl> Fold conversation transcript into Consolidated State Ledger")
109
+ print(" transcripts [--recent N] Analyze agent transcripts (Antigravity/Claude/Codex)")
110
+ print(" [--compare A B] A/B comparison of two session transcripts")
109
111
  print(" benchmark Zero-context-loss benchmark suite (simulated SWE-bench harness)")
110
112
  print(" bench --real [--repo=key|--here] Measured benchmark on real repos (zero-loss gates)")
111
113
  print(" graph / map / skeleton Architecture graph / API surface / AST skeleton of a file")
@@ -728,6 +730,84 @@ def main(argv: Optional[List[str]] = None):
728
730
  print(f" Backend Runtime: {status['backend'].get('status', 'OK')} ({status['backend'].get('name', 'N/A')})")
729
731
  print(f" Workspace: {status.get('workspace')}\n")
730
732
 
733
+ elif command in ("burn", "burn-monitor"):
734
+ from src.burn_monitor import collect_live_burn_snapshot, evaluate_burn_warnings, is_zai_peak_hour
735
+ from src.transcript_analyzer import discover_transcript_paths, analyze_transcript, render_transcripts_report
736
+ agent_filter = "auto"
737
+ for i, a in enumerate(args):
738
+ if a.startswith("--agent="):
739
+ agent_filter = a.split("=", 1)[1]
740
+ elif a in ("--agent", "-a") and i + 1 < len(args):
741
+ agent_filter = args[i + 1]
742
+ print("\n\033[1m\033[36m🔥 TOKENSAFE MULTI-AGENT LIVE BURN MONITOR 🔥\033[0m\n")
743
+ print(f" Z.ai Peak Hours (Mon-Fri 14:00-18:00 SST): {'ACTIVE (1.0x = 2x off-peak)' if is_zai_peak_hour() else 'OFF-PEAK (0.5x rate)'}")
744
+ found = discover_transcript_paths(agent=agent_filter, limit=8)
745
+ if not found:
746
+ print(" No active session transcripts/rollouts found.\n")
747
+ sys.exit(0)
748
+ analyzed = [analyze_transcript(fp, agent_type=ag_type) for ag_type, fp, _ in found]
749
+ print(render_transcripts_report(analyzed))
750
+ for ag in ("zcode", "claude_code", "antigravity"):
751
+ if agent_filter not in ("auto", ag):
752
+ continue
753
+ snap = collect_live_burn_snapshot(agent=ag)
754
+ if snap:
755
+ warns = evaluate_burn_warnings(snap)
756
+ if warns:
757
+ print(f" [{ag}] Active session alerts:")
758
+ for w in warns:
759
+ print(f" • {w['message']}")
760
+ sys.exit(0)
761
+
762
+ elif command in ("transcripts", "transcript"):
763
+ from src.transcript_analyzer import (
764
+ discover_transcript_paths,
765
+ analyze_transcript,
766
+ compare_transcripts,
767
+ render_transcripts_report,
768
+ render_comparison_report
769
+ )
770
+ if "--compare" in args:
771
+ c_idx = args.index("--compare")
772
+ if len(args) < c_idx + 3:
773
+ print("Usage: tokensafe transcripts --compare <before.jsonl> <after.jsonl>")
774
+ sys.exit(1)
775
+ before_f = args[c_idx + 1]
776
+ after_f = args[c_idx + 2]
777
+ res = compare_transcripts(before_f, after_f)
778
+ print(render_comparison_report(res))
779
+ sys.exit(0)
780
+
781
+ agent_type = "auto"
782
+ explicit_path = None
783
+ limit = 10
784
+ for i, a in enumerate(args):
785
+ if a in ("--recent", "-n") and i + 1 < len(args):
786
+ try:
787
+ limit = int(args[i + 1])
788
+ except ValueError:
789
+ pass
790
+ elif a.startswith("--agent="):
791
+ agent_type = a.split("=", 1)[1]
792
+ elif a in ("--agent", "-a") and i + 1 < len(args):
793
+ agent_type = args[i + 1]
794
+ elif a.startswith("--path="):
795
+ explicit_path = a.split("=", 1)[1]
796
+ elif a in ("--path", "-p") and i + 1 < len(args):
797
+ explicit_path = args[i + 1]
798
+
799
+ found = discover_transcript_paths(agent=agent_type, explicit_path=explicit_path, limit=limit)
800
+ if not found:
801
+ print("No transcripts found. Specify path via --path <path_or_dir> or --agent <antigravity|claude|codex>.")
802
+ sys.exit(0)
803
+
804
+ analyzed = []
805
+ for ag_type, fp, _ in found:
806
+ analyzed.append(analyze_transcript(fp, agent_type=ag_type))
807
+
808
+ print(render_transcripts_report(analyzed))
809
+ sys.exit(0)
810
+
731
811
  elif command == "proxy":
732
812
  from src.proxy import run_proxy
733
813
  sub = args[1] if len(args) > 1 else ""
@@ -990,13 +1070,14 @@ def main(argv: Optional[List[str]] = None):
990
1070
  sys.exit(0)
991
1071
 
992
1072
  # 1. Request device code
1073
+ from src.version_checker import CURRENT_VERSION
993
1074
  machine_fp = LicenseManager.get_machine_fingerprint()
994
1075
  payload = {
995
1076
  "machine_fp": machine_fp,
996
1077
  "platform": platform.system()[:32],
997
1078
  "arch": platform.machine()[:32],
998
1079
  "agent": str(LicenseManager.detect_agent())[:32],
999
- "version": "",
1080
+ "version": CURRENT_VERSION[:32],
1000
1081
  "hostname": platform.node()[:64]
1001
1082
  }
1002
1083
  try:
@@ -1013,7 +1094,7 @@ def main(argv: Optional[List[str]] = None):
1013
1094
  print(" Check your internet connection and try again.\n")
1014
1095
  sys.exit(1)
1015
1096
 
1016
- if not init_data.get("success"):
1097
+ if not (init_data.get("success") or init_data.get("ok")):
1017
1098
  print(f"\033[31m✖ Authorization initiation failed: {init_data.get('error')}\033[0m\n")
1018
1099
  sys.exit(1)
1019
1100
 
@@ -1083,7 +1164,7 @@ def main(argv: Optional[List[str]] = None):
1083
1164
  # 3. Save license and device token
1084
1165
  lic_key = approved_data.get("license_key", "")
1085
1166
  dev_tok = approved_data.get("device_token", "")
1086
- auth_email = approved_data.get("email", "")
1167
+ auth_email = approved_data.get("email") or approved_data.get("user_email") or ""
1087
1168
 
1088
1169
  ok, msg = LicenseManager.save_license(lic_key, device_token=dev_tok)
1089
1170
  if ok:
@@ -1563,7 +1644,7 @@ def main(argv: Optional[List[str]] = None):
1563
1644
 
1564
1645
  else:
1565
1646
  print(f"Unknown command: {command}")
1566
- print("Available commands: stats, status, sync, html, test, tests, doctor, providers, mcp, benchmark, proxy, graph, map, skeleton, guard, vacuum, prune, digest, activate, license, markdown, install, setup, update, check-update, reset. Run 'tokensafe help' for details.")
1647
+ print("Available commands: init, login, logout, stats, status, sync, html, test, tests, expand-ref, wrap, web, doctor, providers, mcp, benchmark, proxy, graph, map, skeleton, guard, mistakes, vacuum, prune, digest, activate, license, markdown, install, uninstall, setup, update, check-update, reset. Run 'tokensafe help' for details.")
1567
1648
  sys.exit(1)
1568
1649
 
1569
1650
  if __name__ == "__main__":
package/src/compactor.py CHANGED
@@ -79,7 +79,7 @@ class PromptCompactor:
79
79
  r"\b(можешь ли ты|можешь|не мог бы ты|помоги мне|помоги пожалуйста|мне нужно|я хочу чтобы ты|я хочу|нужно чтобы|надо чтобы|надо|нужно|давай)\b",
80
80
  r"\b(подскажи как|подскажи пожалуйста|подскажи|расскажи как|сделай так чтобы|сделай пожалуйста|попробуй|попробуем)\b",
81
81
  r"\b(как думаешь|как считаешь|по твоему мнению|в чем проблема|почему|почему падает|не работает)\b",
82
- r"\b(в файле|из файла|внутри файла|файле|файл|функцию|функция|функции|метод|методе|метода|класс|классе|класса|код|кода|строку|строка|проект|проекта|проекте|описани\w*|пояснени\w*|информаци\w*|баз\w*\s+данных|баз[аеуоы]|бд|database)\b",
82
+ r"\b(в файле|из файла|внутри файла|файле|файл|функцию|функция|функции|метод|методе|метода|класс|классе|класса|код|кода|строку|строка|проект|проекта|проекте|описани\w*|пояснени\w*|информаци\w*)\b",
83
83
  r"\b(добавь туда|сделай её|сделай его|сделай их|чтобы было|чтобы он|чтобы она|чтобы оно|для этого|для того чтобы)\b",
84
84
  # Note: «не» (negation) is deliberately NOT stripped — removing it inverted
85
85
  # the meaning of prompts like "не удаляй файл" ("do not delete the file").
package/src/dashboard.py CHANGED
@@ -321,16 +321,18 @@ class Dashboard:
321
321
  """
322
322
 
323
323
  tier, payload = LicenseManager.get_active_license()
324
- if tier == "free":
324
+ if tier in ("guest", "free"):
325
325
  monthly_saved = self.tracker.get_monthly_saved_tokens()
326
- limit = 500_000
326
+ limit = 50_000 if tier == "guest" else 500_000
327
327
  q_pct = min(100.0, round(monthly_saved / limit * 100.0, 1))
328
+ edition_label = "Guest Mode (50k):" if tier == "guest" else "Community Edition:"
329
+ cta_text = "Login / Upgrade" if tier == "guest" else "Upgrade to Solo (Unlimited)"
328
330
  banner_html = f"""
329
331
  <div style="background: rgba(234, 179, 8, 0.1); border: 1px solid rgba(234, 179, 8, 0.3); border-radius: 12px; padding: 14px 18px; margin-bottom: 24px; display: flex; justify-content: space-between; align-items: center; font-size: 13px;">
330
332
  <div>
331
- <strong style="color: #eab308;">⚡ Community Edition:</strong> {monthly_saved:,} / {limit:,} free measured tokens saved this month ({q_pct}%).
333
+ <strong style="color: #eab308;">⚡ {edition_label}</strong> {monthly_saved:,} / {limit:,} free measured tokens saved this month ({q_pct}%).
332
334
  </div>
333
- <a href="https://tokensafe.dev/signup" target="_blank" style="background: #10b981; color: #090a0f; font-weight: 700; padding: 6px 14px; border-radius: 8px; text-decoration: none; font-size: 12px;">Upgrade to Solo (Unlimited)</a>
335
+ <a href="https://tokensafe.dev/pricing" target="_blank" style="background: #10b981; color: #090a0f; font-weight: 700; padding: 6px 14px; border-radius: 8px; text-decoration: none; font-size: 12px;">{cta_text}</a>
334
336
  </div>
335
337
  """
336
338
  else:
@@ -454,13 +456,17 @@ class Dashboard:
454
456
  </div>
455
457
  </div>
456
458
  <script>
457
- if (window.EventSource) {{
458
- const source = new EventSource('/api/events');
459
+ (function() {{
459
460
  const pill = document.getElementById('live-pill');
461
+ if (location.protocol === 'file:' || !window.EventSource) {{
462
+ if (pill) pill.innerHTML = '<span style="color: #64748b;">●</span> Static Snapshot (local HTML)';
463
+ return;
464
+ }}
465
+ const source = new EventSource('/api/events');
460
466
  source.onopen = () => {{
461
467
  if (pill) pill.innerHTML = '<span style="color: #10b981;">●</span> LIVE SSE STREAMING';
462
468
  }};
463
- source.addEventListener('stats_update', (e) => {{
469
+ const applyStats = (e) => {{
464
470
  try {{
465
471
  const data = JSON.parse(e.data);
466
472
  if (data.total_saved_tokens !== undefined) {{
@@ -480,11 +486,13 @@ class Dashboard:
480
486
  if (el) el.innerText = Number(data.total_original_tokens).toLocaleString() + ' ➔ ' + Number(data.total_optimized_tokens).toLocaleString();
481
487
  }}
482
488
  }} catch (err) {{}}
483
- }});
489
+ }};
490
+ source.addEventListener('init', applyStats);
491
+ source.addEventListener('stats_update', applyStats);
484
492
  source.onerror = () => {{
485
493
  if (pill) pill.innerHTML = '<span style="color: #64748b;">○</span> Disconnected (Reconnecting)';
486
494
  }};
487
- }}
495
+ }})();
488
496
  </script>
489
497
  </body>
490
498
  </html>
@@ -131,7 +131,7 @@ class DiffSlicer:
131
131
  continue
132
132
  if ":!" in stage or re.search(r"(?:^|\s)(?:--unified=\d+|-U\d*)\b", stage):
133
133
  continue
134
- new_stage = re.sub(r"\bdiff\b", "diff -U2", stage, count=1)
134
+ new_stage = re.sub(r"(\bgit(?:\s+-C\s+\S+)?\s+diff)\b", r"\1 -U2", stage, count=1)
135
135
  if "-- " not in stage and not stage.rstrip().endswith("--"):
136
136
  toks = CommandSanitizer._split_tokens_safe(stage)
137
137
  diff_pos = toks.index("diff") if "diff" in toks else 1
package/src/distiller.py CHANGED
@@ -182,8 +182,18 @@ Rules:
182
182
  }
183
183
  )
184
184
  try:
185
+ from src.ssl_context import shared_ssl_context
185
186
  _egress_increment("booster")
186
- with urllib.request.urlopen(req, timeout=timeout) as resp:
187
+ ssl_ctx = shared_ssl_context()
188
+ try:
189
+ resp_ctx = (
190
+ urllib.request.urlopen(req, timeout=timeout, context=ssl_ctx)
191
+ if ssl_ctx is not None
192
+ else urllib.request.urlopen(req, timeout=timeout)
193
+ )
194
+ except TypeError:
195
+ resp_ctx = urllib.request.urlopen(req, timeout=timeout)
196
+ with resp_ctx as resp:
187
197
  if resp.status == 200:
188
198
  data = json.loads(resp.read().decode("utf-8"))
189
199
  if data.get("success") and data.get("distilled"):
@@ -37,7 +37,12 @@ class EnvironmentAuditor:
37
37
  home = os.path.expanduser("~")
38
38
  return [
39
39
  os.path.join(home, ".gemini", "config", "mcp_config.json"),
40
- os.path.join(home, ".gemini", "antigravity", "mcp_config.json")
40
+ os.path.join(home, ".gemini", "antigravity", "mcp_config.json"),
41
+ os.path.join(home, ".zcode", "cli", "config.json"),
42
+ os.path.join(home, ".claude.json"),
43
+ os.path.join(home, ".cursor", "mcp.json"),
44
+ os.path.join(home, ".kimi-code", "mcp.json"),
45
+ os.path.join(home, ".codex", "config.toml"),
41
46
  ]
42
47
 
43
48
  @classmethod
@@ -102,14 +107,33 @@ class EnvironmentAuditor:
102
107
  # antigravity dir can legitimately carry servers (they are merged by
103
108
  # Antigravity too), so breaking on the first one undercounts.
104
109
  for p in cls.get_config_paths():
105
- if os.path.isfile(p):
110
+ if not os.path.isfile(p):
111
+ continue
112
+ if p.endswith(".toml"):
106
113
  try:
107
- with open(p, "r", encoding="utf-8") as f:
108
- loaded = json.load(f)
109
- if isinstance(loaded, dict) and isinstance(loaded.get("mcpServers"), dict):
110
- configured.update(loaded["mcpServers"])
114
+ with open(p, "rb") as f:
115
+ raw_bytes = f.read()
116
+ try:
117
+ import tomllib
118
+ loaded_toml = tomllib.loads(raw_bytes.decode("utf-8", errors="replace"))
119
+ if isinstance(loaded_toml.get("mcp_servers"), dict):
120
+ configured.update(loaded_toml["mcp_servers"])
121
+ except Exception:
122
+ text = raw_bytes.decode("utf-8", errors="replace")
123
+ for m in re.finditer(r"^\s*\[mcp_servers\.([^\]]+)\]", text, re.MULTILINE):
124
+ s_name = m.group(1).strip().strip('"\'')
125
+ if s_name:
126
+ configured.setdefault(s_name, {})
111
127
  except Exception:
112
128
  continue
129
+ continue
130
+ try:
131
+ with open(p, "r", encoding="utf-8") as f:
132
+ loaded = json.load(f)
133
+ if isinstance(loaded, dict) and isinstance(loaded.get("mcpServers"), dict):
134
+ configured.update(loaded["mcpServers"])
135
+ except Exception:
136
+ continue
113
137
  # Plugin-declared servers (plugins/<name>/mcp_config.json) are loaded
114
138
  # by Antigravity together with the plugin — audit them too, unless the
115
139
  # plugin itself is disabled.
@@ -12,7 +12,7 @@ import re
12
12
  # 1. CSI sequences: \x1b\[[0-9;]*[A-Za-z] (colors, cursor movements, erase line)
13
13
  # 2. OSC sequences: \x1b\][^\x07\x1b]*(\x07|\x1b\\) (hyperlinks, window titles)
14
14
  # 3. Simple escapes: \x1b[()][AB012], \x1b[=>]
15
- _ANSI_CSI_RE = re.compile(r"\x1b\[[0-9;]*[a-zA-Z]")
15
+ _ANSI_CSI_RE = re.compile(r"\x1b\[[0-9;?=<>*!]*[ -/]*[@-~]")
16
16
  _ANSI_OSC_RE = re.compile(r"\x1b\][^\x07\x1b]*(\x07|\x1b\\)")
17
17
  _ANSI_OTHER_RE = re.compile(r"\x1b[()][AB012]|\x1b[=>]")
18
18
 
@@ -530,21 +530,26 @@ class LockfileReducer:
530
530
  pass
531
531
 
532
532
  elif "cargo.lock" in fname or "poetry.lock" in fname:
533
- pattern = re.compile(
534
- rf'\[\[package\]\]\s+name\s*=\s*"{re.escape(norm_pkg)}"\s+version\s*=\s*"([^"]+)"'
535
- r'(?:\s+source\s*=\s*"([^"]*)")?'
536
- r'(?:\s+dependencies\s*=\s*(\[[^\]]*\]))?',
537
- re.MULTILINE
538
- )
539
- m = pattern.search(content)
540
- if m:
541
- ver = m.group(1)
542
- source_val = m.group(2)
543
- deps_raw = m.group(3) or "[]"
544
- try:
545
- deps = json.loads(deps_raw) if deps_raw.startswith("[") else []
546
- except Exception:
547
- deps = []
533
+ # Parse TOML [[package]] sections resiliently (supports optional checksum & TOML dependency arrays)
534
+ sections = re.split(r'(?m)^\[\[package\]\]\s*$', content)
535
+ for sec in sections[1:]:
536
+ m_name = re.search(r'(?m)^name\s*=\s*"([^"]+)"', sec)
537
+ if not m_name or m_name.group(1) != norm_pkg:
538
+ continue
539
+ m_ver = re.search(r'(?m)^version\s*=\s*"([^"]+)"', sec)
540
+ ver = m_ver.group(1) if m_ver else "*"
541
+ m_src = re.search(r'(?m)^source\s*=\s*"([^"]*)"', sec)
542
+ source_val = m_src.group(1) if m_src else None
543
+ m_deps = re.search(r'(?ms)^dependencies\s*=\s*\[(.*?)\]', sec)
544
+ deps: List[str] = []
545
+ if m_deps:
546
+ raw_arr = m_deps.group(1)
547
+ try:
548
+ parsed = json.loads(f"[{raw_arr}]")
549
+ if isinstance(parsed, list):
550
+ deps = [str(d) for d in parsed]
551
+ except Exception:
552
+ deps = re.findall(r'"([^"]+)"', raw_arr)
548
553
  res_dict = {
549
554
  "found": True,
550
555
  "package": norm_pkg,
@@ -556,8 +561,8 @@ class LockfileReducer:
556
561
  return res_dict
557
562
 
558
563
  elif "pnpm-lock" in fname:
559
- # Pnpm regex lookup: /pkg@ver or 'pkg': ver
560
- pnpm_re = re.compile(rf'["\']?/?{re.escape(norm_pkg)}[@/]([0-9a-zA-Z._-]+)["\']?:')
564
+ # Pnpm regex lookup with strict left boundary so 'react' never matches 'preact'
565
+ pnpm_re = re.compile(rf'(?:^|[\s"\'/]){re.escape(norm_pkg)}[@/]([0-9a-zA-Z._+-]+)["\']?:', re.MULTILINE)
561
566
  m = pnpm_re.search(content)
562
567
  if m:
563
568
  return {
@@ -154,9 +154,12 @@ class TabularReducer:
154
154
  resp = e.get("response", {})
155
155
  method = req.get("method", "GET")
156
156
  url = req.get("url", "")
157
- status = resp.get("status", 0)
158
- body_size = resp.get("bodySize", 0)
159
- time_ms = int(e.get("time", 0))
157
+ status = resp.get("status", 0) or 0
158
+ body_size = resp.get("bodySize") or 0
159
+ try:
160
+ time_ms = int(float(e.get("time") or 0))
161
+ except (TypeError, ValueError):
162
+ time_ms = 0
160
163
 
161
164
  # Strip query params if too long
162
165
  clean_url = url.split("?")[0] if len(url) > 80 else url
package/src/fts_index.py CHANGED
@@ -178,15 +178,8 @@ class CodeFTSIndex:
178
178
  if prev and abs(prev[0] - f_mtime) < 0.001 and prev[1] == f_size:
179
179
  continue # File unchanged
180
180
 
181
- files_to_index.append((rel_path, full_path, f_mtime, f_size))
182
- # Cap the INDEXING work per run, never the walk: files
183
- # beyond the cap must still enter found_paths, or the
184
- # prune step below would treat them as deleted on every
185
- # run (repos > max_files lost their tail permanently).
186
- if len(files_to_index) >= max_files:
187
- break
188
- if len(files_to_index) >= max_files:
189
- break
181
+ if len(files_to_index) < max_files:
182
+ files_to_index.append((rel_path, full_path, f_mtime, f_size))
190
183
 
191
184
  # Index modified/new files in batches
192
185
  for rel_path, full_path, f_mtime, f_size in files_to_index:
@@ -257,6 +250,9 @@ class CodeFTSIndex:
257
250
  escaped_q = clean_q.replace('"', '""')
258
251
  fts_query = f'"{escaped_q}"'
259
252
 
253
+ def _escape_like(val: str) -> str:
254
+ return val.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
255
+
260
256
  results = []
261
257
  try:
262
258
  con = self._get_connection()
@@ -265,11 +261,11 @@ class CodeFTSIndex:
265
261
  sql = """
266
262
  SELECT rel_path, line_no, content, bm25(code_lines) AS rank
267
263
  FROM code_lines
268
- WHERE code_lines MATCH ? AND rel_path LIKE ?
264
+ WHERE code_lines MATCH ? AND rel_path LIKE ? ESCAPE '\\'
269
265
  ORDER BY rank
270
266
  LIMIT ?;
271
267
  """
272
- cur = con.execute(sql, (fts_query, f"%{path_filter}%", limit))
268
+ cur = con.execute(sql, (fts_query, f"%{_escape_like(path_filter)}%", limit))
273
269
  else:
274
270
  sql = """
275
271
  SELECT rel_path, line_no, content, bm25(code_lines) AS rank
@@ -295,7 +291,7 @@ class CodeFTSIndex:
295
291
  and_query = " AND ".join(
296
292
  f'"{term.replace(chr(34), chr(34) * 2)}"' for term in clean_q.split()
297
293
  )
298
- params2 = ([f"%{path_filter}%"] if path_filter else []) + [limit]
294
+ params2 = ([f"%{_escape_like(path_filter)}%"] if path_filter else []) + [limit]
299
295
  cur = con.execute(sql, (and_query, *params2))
300
296
  for row in cur.fetchall():
301
297
  results.append({
@@ -305,14 +301,24 @@ class CodeFTSIndex:
305
301
  "bm25_rank": row[3]
306
302
  })
307
303
  except sqlite3.OperationalError:
308
- # If trigram MATCH fails (e.g. query < 3 chars), fallback to LIKE
309
- like_sql = """
310
- SELECT rel_path, line_no, content, 0.0 AS rank
311
- FROM code_lines
312
- WHERE content LIKE ?
313
- LIMIT ?;
314
- """
315
- cur = con.execute(like_sql, (f"%{clean_q}%", limit))
304
+ # If trigram MATCH fails (e.g. query < 3 chars), fallback to escaped LIKE
305
+ escaped_q_like = f"%{_escape_like(clean_q)}%"
306
+ if path_filter:
307
+ like_sql = """
308
+ SELECT rel_path, line_no, content, 0.0 AS rank
309
+ FROM code_lines
310
+ WHERE content LIKE ? ESCAPE '\\' AND rel_path LIKE ? ESCAPE '\\'
311
+ LIMIT ?;
312
+ """
313
+ cur = con.execute(like_sql, (escaped_q_like, f"%{_escape_like(path_filter)}%", limit))
314
+ else:
315
+ like_sql = """
316
+ SELECT rel_path, line_no, content, 0.0 AS rank
317
+ FROM code_lines
318
+ WHERE content LIKE ? ESCAPE '\\'
319
+ LIMIT ?;
320
+ """
321
+ cur = con.execute(like_sql, (escaped_q_like, limit))
316
322
  for row in cur.fetchall():
317
323
  results.append({
318
324
  "file": row[0],
package/src/governor.py CHANGED
@@ -379,12 +379,12 @@ class ContextBudget:
379
379
  pct = round(used / window * 100.0, 1) if window > 0 else 0.0
380
380
  if pct >= 95:
381
381
  threshold, recommendation = "critical", (
382
- "Context nearly exhausted. Call tokensafe:compact_conversation on the "
382
+ "Context nearly exhausted. Call tokensafe:session_context(action='compact', ...) on the "
383
383
  "session transcript now, or start a fresh session carrying the ledger.")
384
384
  elif pct >= 80:
385
385
  threshold, recommendation = "warning", (
386
386
  "Context is heavy. Prefer tokensafe:smart_read_file with symbol= for "
387
- "further reads and consider tokensafe:compact_conversation.")
387
+ "further reads and consider tokensafe:session_context(action='compact', ...).")
388
388
  elif pct >= 50:
389
389
  threshold, recommendation = "notice", (
390
390
  "Half the estimated window is used. Keep reads surgical (symbol=, include_deps=false).")