tokensafe 4.13.3 → 4.15.0

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 (46) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/README.md +1 -1
  3. package/hooks/claude_code_hook.py +8 -2
  4. package/hooks/cursor_hook.py +2 -1
  5. package/hooks/kimi_hook.py +2 -1
  6. package/hooks/post_tool_use.py +15 -1
  7. package/hooks/pre_invocation.py +4 -2
  8. package/hooks/pre_tool_use.py +13 -6
  9. package/hooks/session_start.py +7 -2
  10. package/hooks/stop_hook.py +2 -1
  11. package/hooks/zcode_hook.py +2 -1
  12. package/kimi.plugin.json +1 -1
  13. package/package.json +1 -1
  14. package/plugin.json +1 -1
  15. package/server.json +3 -3
  16. package/src/acp/server.py +5 -0
  17. package/src/atomic_io.py +74 -0
  18. package/src/auto_inject.py +8 -4
  19. package/src/backend_release.py +3 -3
  20. package/src/batch_editor.py +2 -14
  21. package/src/cli.py +10 -0
  22. package/src/command_sanitizer.py +1 -1
  23. package/src/context_index.py +954 -0
  24. package/src/file_state.py +4 -3
  25. package/src/fts_index.py +12 -32
  26. package/src/graph_engine.py +43 -95
  27. package/src/guard.py +1 -1
  28. package/src/installer.py +64 -4
  29. package/src/license_manager.py +66 -0
  30. package/src/mcp_proxy.py +3 -0
  31. package/src/mcp_server.py +103 -5
  32. package/src/mistakes.py +45 -21
  33. package/src/oumv_gateway.py +61 -18
  34. package/src/paths.py +5 -12
  35. package/src/project_memory.py +264 -0
  36. package/src/result_ledger.py +40 -0
  37. package/src/retrofit.py +15 -8
  38. package/src/scoped_search.py +93 -53
  39. package/src/session_brief.py +14 -3
  40. package/src/skeletonizer.py +44 -2
  41. package/src/snapshot.py +17 -1
  42. package/src/stdio_io.py +50 -0
  43. package/src/telemetry_sync.py +1 -1
  44. package/src/version_checker.py +1 -1
  45. package/src/win_paths.py +172 -0
  46. package/src/workspace_roots.py +2 -6
package/src/mcp_server.py CHANGED
@@ -46,7 +46,7 @@ from src.session_context import current_root, current_session_id
46
46
 
47
47
  SERVER_INFO = {
48
48
  "name": "tokensafe-mcp",
49
- "version": "4.13.3"
49
+ "version": "4.15.0"
50
50
  }
51
51
 
52
52
  # MCP client attribution: the initialize handshake carries clientInfo, which
@@ -858,12 +858,26 @@ TOOLS = [{'name': 'smart_read_file',
858
858
  {'name': 'session_context',
859
859
  'annotations': {'readOnlyHint': False},
860
860
  'description': "Context hygiene: 'budget' (score S-F), 'compact' (fold transcript), 'prune' (drop "
861
- "superseded reads), 'mistakes', 'metrics'.",
861
+ "superseded reads), 'mistakes', 'metrics', 'remember' (store a decision/note/preference), "
862
+ "'recall' (read project memory), 'forget' (remove one entry by id).",
862
863
  'inputSchema': {'type': 'object',
863
864
  'properties': {'action': {'type': 'string',
864
- 'enum': ['budget', 'compact', 'prune', 'mistakes', 'metrics']},
865
+ 'enum': ['budget', 'compact', 'prune', 'mistakes', 'metrics',
866
+ 'remember', 'recall', 'forget']},
865
867
  'model': {'type': 'string'},
866
- 'transcript_path': {'type': 'string'}}}},
868
+ 'transcript_path': {'type': 'string'},
869
+ 'kind': {'type': 'string',
870
+ 'enum': ['decision', 'note', 'preference'],
871
+ 'description': 'remember: what kind of memory to store'},
872
+ 'text': {'type': 'string',
873
+ 'description': 'remember: the memory text (preferences as key=value)'},
874
+ 'files': {'type': 'array',
875
+ 'items': {'type': 'string'},
876
+ 'description': 'remember: files this decision touches'},
877
+ 'id': {'type': 'string', 'description': 'forget: entry id'},
878
+ 'query': {'type': 'string', 'description': 'recall: optional filter'},
879
+ 'limit': {'type': 'integer'},
880
+ 'workspace_dir': {'type': 'string'}}}},
867
881
  {'name': 'oumv',
868
882
  'annotations': {'readOnlyHint': False},
869
883
  'description': "Call this FIRST on an OUMV-supported stack: status/brief/observe before grep or full-file "
@@ -1180,7 +1194,9 @@ def _shared_batch_root(paths: List[str], real_cwd: str) -> Optional[str]:
1180
1194
  return None
1181
1195
  if os.path.isfile(shared):
1182
1196
  shared = os.path.dirname(shared)
1183
- if not shared or shared == os.path.abspath(os.sep) or not os.path.isdir(shared):
1197
+ from src.win_paths import is_system_root
1198
+
1199
+ if not shared or is_system_root(shared) or not os.path.isdir(shared):
1184
1200
  return None
1185
1201
 
1186
1202
  def _swallows_cwd(candidate: str) -> bool:
@@ -1835,6 +1851,24 @@ def _render_endpoint_slice(
1835
1851
  try:
1836
1852
  graph = GraphEngine.get_instance(root)
1837
1853
  files = list(graph.file_stats.keys())
1854
+ # Routes are already extracted into the graph; use them as file hints so
1855
+ # the endpoint slice does not re-parse every candidate in the repo.
1856
+ hints = []
1857
+ for rel_hint, eps in getattr(graph, "file_endpoints", {}).items():
1858
+ for ep in eps:
1859
+ ep_route = str(ep[0] or "")
1860
+ if ep_route and (ep_route == route or ep_route.endswith(route) or route.endswith(ep_route)):
1861
+ hints.append(rel_hint)
1862
+ break
1863
+ if hints:
1864
+ seen_hints = set()
1865
+ ordered = []
1866
+ for rel_hint in hints + [f for f in files if f not in hints]:
1867
+ if rel_hint in seen_hints:
1868
+ continue
1869
+ seen_hints.add(rel_hint)
1870
+ ordered.append(rel_hint)
1871
+ files = ordered
1838
1872
  except Exception:
1839
1873
  files = None
1840
1874
  prefer_rel = ""
@@ -2019,6 +2053,59 @@ def _observe_seed_read_cache(res, level, target, path_arg, workspace_dir) -> Non
2019
2053
  pass
2020
2054
 
2021
2055
 
2056
+ def _brief_seed_read_cache(res, workspace_dir) -> None:
2057
+ """Seeds the read cache with the exact skeleton a later read returns.
2058
+
2059
+ ``oumv brief`` already delivered a skeleton. Seeding ``_default_read_text``
2060
+ (the read path's own renderer) instead of brief's graph-guided variant keeps
2061
+ a later pointer honest: it promises the same payload, not a similar one.
2062
+ """
2063
+ if not isinstance(res, dict) or not res.get("targetResolved"):
2064
+ return
2065
+ rel = str(res.get("target") or "").strip()
2066
+ if not rel:
2067
+ return
2068
+ synthetic = {"targetKind": "file", "targetResolved": True, "file": {"path": rel}}
2069
+ _observe_seed_read_cache(synthetic, "L1", rel, None, workspace_dir)
2070
+
2071
+
2072
+ def _project_memory_action(action: str, args: dict) -> dict:
2073
+ """`session_context(remember|recall|forget)` — project memory without a new tool.
2074
+
2075
+ Memory is machine-local (``~/.tokensafe/data/projects/<hash>/memory.json``),
2076
+ so it survives sessions and can never leak into a public repository.
2077
+ """
2078
+ from src.project_memory import ProjectMemory
2079
+
2080
+ root = str(
2081
+ args.get("workspace_dir")
2082
+ or args.get("cwd")
2083
+ or args.get("project_path")
2084
+ or _workspace_root()
2085
+ or os.getcwd()
2086
+ )
2087
+ memory = ProjectMemory(root)
2088
+ if action == "remember":
2089
+ text = str(args.get("text") or args.get("content") or "").strip()
2090
+ if not text:
2091
+ return _fallback_error("session_context", "remember needs `text`")
2092
+ try:
2093
+ entry = memory.remember(
2094
+ str(args.get("kind") or "decision"),
2095
+ text,
2096
+ files=args.get("files") if isinstance(args.get("files"), list) else None,
2097
+ )
2098
+ except ValueError as exc:
2099
+ return _fallback_error("session_context", str(exc))
2100
+ payload = {"ok": True, "action": "remember", "entry": entry, "stored_at": memory.path}
2101
+ elif action == "recall":
2102
+ payload = memory.recall(str(args.get("query") or ""), limit=int(args.get("limit") or 10))
2103
+ payload["ok"] = True
2104
+ else:
2105
+ payload = {"ok": memory.forget(str(args.get("id") or "")), "path": memory.path}
2106
+ return {"content": [{"type": "text", "text": json.dumps(payload, indent=2, ensure_ascii=False)}]}
2107
+
2108
+
2022
2109
  def handle_tool_call(name: str, args: dict) -> dict:
2023
2110
  if args is None or not isinstance(args, dict):
2024
2111
  args = {}
@@ -2192,6 +2279,8 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
2192
2279
  name = mapped
2193
2280
  elif name == "session_context":
2194
2281
  action = str(args.get("action") or "budget").strip().lower()
2282
+ if action in ("remember", "recall", "forget"):
2283
+ return _project_memory_action(action, args)
2195
2284
  if action not in _SESSION_CONTEXT_ACTIONS:
2196
2285
  return _fallback_error("session_context", f"unknown action '{action}'")
2197
2286
  name = _SESSION_CONTEXT_ACTIONS[action]
@@ -3678,6 +3767,10 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
3678
3767
  if ws_err:
3679
3768
  return _fallback_error("oumv_brief", ws_err)
3680
3769
  res = OUMVGateway.brief(target=tgt, symbol=sym, workspace_dir=ws, path=raw_path)
3770
+ try:
3771
+ _brief_seed_read_cache(res, ws)
3772
+ except Exception:
3773
+ pass
3681
3774
  return {"content": [{"type": "text", "text": json.dumps(res, indent=2, ensure_ascii=False)}]}
3682
3775
  except Exception as e:
3683
3776
  return _fallback_error("oumv_brief", f"failed to build brief: {e}")
@@ -4373,6 +4466,11 @@ def _get_watched_mtimes() -> Tuple[Optional[float], ...]:
4373
4466
  def run_mcp_server():
4374
4467
  """Runs stdio JSON-RPC 2.0 loop with per-call timeout, resilient recovery & auto-reload on upgrade."""
4375
4468
  global _MCP_CLIENT_NAME, _TOOLS_LISTED, _EPOCH_GEN
4469
+ # Windows pipes default to the ANSI code page; one emoji in a response used
4470
+ # to raise UnicodeEncodeError and exit the whole server loop.
4471
+ from src.stdio_io import ensure_utf8_stdio
4472
+
4473
+ ensure_utf8_stdio()
4376
4474
  _MCP_CLIENT_NAME = ""
4377
4475
  _TOOLS_LISTED = False
4378
4476
  _EPOCH_GEN = 0
package/src/mistakes.py CHANGED
@@ -20,20 +20,35 @@ from typing import Dict, Any, List, Optional, Tuple
20
20
  from src.paths import resolve_data_dir, ensure_tokensafe_gitignore
21
21
  from src.secret_redactor import SecretRedactor
22
22
 
23
+ # (path, mtime, size) -> parsed entries: one hook run reads the ledger twice.
24
+ _READ_CACHE: Dict[Tuple[str, float, int], List[Dict[str, Any]]] = {}
23
25
 
24
- def _find_project_mistakes_file(project_root: Optional[str] = None) -> str:
25
- """Finds or creates .tokensafe/mistakes.jsonl in project or user data dir."""
26
+
27
+ def _find_project_mistakes_file(project_root: Optional[str] = None, create: bool = True) -> str:
28
+ """Finds (and on a write, creates) the mistakes ledger for a project.
29
+
30
+ Reads must not touch the workspace: ``list_mistakes`` used to ``makedirs``
31
+ and append to ``.gitignore`` on every hook turn just to look at a file that
32
+ might not exist.
33
+ """
26
34
  if project_root and os.path.isdir(project_root):
27
35
  proj_dir = os.path.join(project_root, ".tokensafe")
36
+ ledger = os.path.join(proj_dir, "mistakes.jsonl")
37
+ if not create:
38
+ # Reads see only this project's ledger: falling back to the global
39
+ # file would merge every other workspace's dead ends into a project
40
+ # that has recorded none.
41
+ return ledger
28
42
  try:
29
43
  os.makedirs(proj_dir, exist_ok=True)
30
44
  ensure_tokensafe_gitignore(project_root)
31
- return os.path.join(proj_dir, "mistakes.jsonl")
45
+ return ledger
32
46
  except Exception:
33
47
  pass
34
48
  # Fallback to global data dir
35
49
  global_dir = resolve_data_dir()
36
- os.makedirs(global_dir, exist_ok=True)
50
+ if create:
51
+ os.makedirs(global_dir, exist_ok=True)
37
52
  return os.path.join(global_dir, "mistakes.jsonl")
38
53
 
39
54
 
@@ -156,36 +171,45 @@ class MistakesLedger:
156
171
  project_root: Optional[str] = None,
157
172
  active_only: bool = True
158
173
  ) -> List[Dict[str, Any]]:
159
- """Loads all recorded mistakes from the ledger."""
160
- ledger_path = _find_project_mistakes_file(project_root)
161
- if not os.path.exists(ledger_path):
162
- return []
163
-
164
- entries = []
174
+ """Loads all recorded mistakes from the ledger (read-only, memoized per run)."""
175
+ ledger_path = _find_project_mistakes_file(project_root, create=False)
165
176
  try:
166
- with open(ledger_path, "r", encoding="utf-8", errors="replace") as f:
167
- for line in f:
168
- line = line.strip()
169
- if line:
177
+ st = os.stat(ledger_path)
178
+ except OSError:
179
+ return []
180
+ key = (ledger_path, st.st_mtime, st.st_size)
181
+ cached = _READ_CACHE.get(key)
182
+ if cached is None:
183
+ cached = []
184
+ try:
185
+ with open(ledger_path, "r", encoding="utf-8", errors="replace") as f:
186
+ for line in f:
187
+ line = line.strip()
188
+ if not line:
189
+ continue
170
190
  try:
171
191
  item = json.loads(line)
172
- if not active_only or item.get("active", True):
173
- entries.append(item)
192
+ if isinstance(item, dict):
193
+ cached.append(item)
174
194
  except Exception:
175
195
  pass
176
- except Exception:
177
- return []
178
-
179
- return entries
196
+ except Exception:
197
+ return []
198
+ _READ_CACHE.clear()
199
+ _READ_CACHE[key] = cached
200
+ if not active_only:
201
+ return list(cached)
202
+ return [item for item in cached if item.get("active", True)]
180
203
 
181
204
  @classmethod
182
205
  def clear_mistakes(cls, project_root: Optional[str] = None) -> int:
183
206
  """Clears all entries from the mistakes ledger."""
184
- ledger_path = _find_project_mistakes_file(project_root)
207
+ ledger_path = _find_project_mistakes_file(project_root, create=False)
185
208
  if os.path.exists(ledger_path):
186
209
  try:
187
210
  entries = cls.list_mistakes(project_root=project_root, active_only=False)
188
211
  os.remove(ledger_path)
212
+ _READ_CACHE.clear()
189
213
  return len(entries)
190
214
  except Exception:
191
215
  pass
@@ -16,6 +16,7 @@ import urllib.parse
16
16
  from concurrent.futures import ThreadPoolExecutor, as_completed
17
17
  from typing import Dict, Any, Optional, Tuple, List
18
18
  from src.paths import get_active_workspace
19
+ from src.win_paths import is_within
19
20
 
20
21
 
21
22
  class OUMVRpcError(RuntimeError):
@@ -351,6 +352,42 @@ class OUMVGateway:
351
352
  removed.append(path)
352
353
  return removed
353
354
 
355
+ @classmethod
356
+ def prune_backups(cls, workspace_dir: str, *, keep_per_file: int = 20,
357
+ max_age_days: int = 30) -> List[str]:
358
+ """Bounds ``.tokensafe/backups``: the newest ``keep_per_file`` per source
359
+ file and nothing older than ``max_age_days``. Best-effort by design — a
360
+ retention failure must never fail the mutation that triggered it."""
361
+ directory = os.path.join(workspace_dir, ".tokensafe", "backups")
362
+ if not os.path.isdir(directory):
363
+ return []
364
+ try:
365
+ entries = list(os.scandir(directory))
366
+ except OSError:
367
+ return []
368
+ groups: Dict[str, List[Any]] = {}
369
+ for entry in entries:
370
+ if not entry.is_file() or not entry.name.endswith(".bak"):
371
+ continue
372
+ stem = entry.name.split("_", 1)[1] if "_" in entry.name else entry.name
373
+ groups.setdefault(stem, []).append(entry)
374
+ now = time.time()
375
+ removed: List[str] = []
376
+ for backups in groups.values():
377
+ backups.sort(key=lambda item: item.stat().st_mtime, reverse=True)
378
+ for index, entry in enumerate(backups):
379
+ try:
380
+ age_days = (now - entry.stat().st_mtime) / 86400
381
+ except OSError:
382
+ continue
383
+ if index >= keep_per_file or age_days > max_age_days:
384
+ try:
385
+ os.unlink(entry.path)
386
+ removed.append(entry.path)
387
+ except OSError:
388
+ pass
389
+ return removed
390
+
354
391
  @classmethod
355
392
  def _probe_candidates(cls, urls: List[str], kind: str) -> Optional[Dict[str, Any]]:
356
393
  for url in urls:
@@ -585,7 +622,7 @@ class OUMVGateway:
585
622
 
586
623
  # 1. Tool: oumv_status
587
624
  @classmethod
588
- def status(cls, workspace_dir: Optional[str] = None) -> Dict[str, Any]:
625
+ def status(cls, workspace_dir: Optional[str] = None, warm_graph: bool = True) -> Dict[str, Any]:
589
626
  cls.mark_oumv_used(workspace_dir)
590
627
  ws = workspace_dir or get_active_workspace() or os.getcwd()
591
628
  cls.scan(workspace_dir=ws)
@@ -597,8 +634,8 @@ class OUMVGateway:
597
634
  # Out-of-the-box stack detection
598
635
  stack_info = {}
599
636
  try:
600
- from src.retrofit import detect_project_stack
601
- stack_info = detect_project_stack(ws)
637
+ from src.retrofit import detect_project_stack_cached
638
+ stack_info = detect_project_stack_cached(ws)
602
639
  except Exception:
603
640
  pass
604
641
 
@@ -642,13 +679,15 @@ class OUMVGateway:
642
679
  if recorded_stale:
643
680
  result["staleRuntimes"] = result.get("staleRuntimes", []) + recorded_stale
644
681
  # A cold AST crawl costs ~15 s on a large monorepo. Start it now, in the
645
- # background: the first repo_map/observe/mutate call then finds it warm
646
- # instead of spending the whole tool budget waiting for it.
647
- try:
648
- from src.graph_engine import GraphEngine
649
- GraphEngine.warm_async(ws)
650
- except Exception:
651
- pass
682
+ # background, so the first repo_map/observe/mutate call finds it warm.
683
+ # Short-lived hooks pass warm_graph=False: the interpreter waits for the
684
+ # crawl thread at exit, so warming there costs the same seconds.
685
+ if warm_graph:
686
+ try:
687
+ from src.graph_engine import GraphEngine
688
+ GraphEngine.warm_async(ws)
689
+ except Exception:
690
+ pass
652
691
  return result
653
692
 
654
693
  @staticmethod
@@ -1090,8 +1129,9 @@ class OUMVGateway:
1090
1129
  # Out-of-the-box direct fallback when live dev-servers are offline
1091
1130
  if replacement is not None:
1092
1131
  abs_path = os.path.normpath(os.path.join(ws, path))
1093
- # Validate workspace boundary
1094
- if not abs_path.startswith(os.path.abspath(ws)):
1132
+ # Real-path containment: a raw prefix test accepts sibling
1133
+ # directories whose names share a prefix (`app` vs `application`).
1134
+ if not is_within(ws, abs_path):
1095
1135
  raise RuntimeError(f"[OUMV SECURITY_VIOLATION: -32003] Path traversal blocked: {path}")
1096
1136
 
1097
1137
  import hashlib
@@ -1145,16 +1185,19 @@ class OUMVGateway:
1145
1185
  os.makedirs(backup_dir, exist_ok=True)
1146
1186
  digest = hashlib.sha256(content).hexdigest()[:8]
1147
1187
  backup_path = os.path.join(backup_dir, f"{digest}_{os.path.basename(abs_path)}.bak")
1148
- with open(backup_path, "wb") as f:
1149
- f.write(content)
1188
+ from src.atomic_io import write_atomic
1189
+ write_atomic(backup_path, content)
1150
1190
  except Exception:
1151
1191
  backup_path = None
1152
1192
 
1153
- os.makedirs(os.path.dirname(abs_path), exist_ok=True)
1154
- with open(abs_path, "w", encoding="utf-8") as f:
1155
- f.write(new_content)
1193
+ from src.atomic_io import write_atomic
1194
+ write_atomic(abs_path, new_content)
1156
1195
 
1157
1196
  new_version = "sha256:" + hashlib.sha256(new_content.encode("utf-8")).hexdigest()
1197
+ try:
1198
+ OUMVGateway.prune_backups(ws)
1199
+ except Exception:
1200
+ pass
1158
1201
  result = {
1159
1202
  "success": True,
1160
1203
  "path": path,
@@ -1566,7 +1609,7 @@ class OUMVGateway:
1566
1609
  offline["detail"] = "offline preview requires 'replacement' (whole-file content)"
1567
1610
  return offline
1568
1611
  abs_path = os.path.normpath(os.path.join(ws, path))
1569
- if not abs_path.startswith(os.path.abspath(ws)):
1612
+ if not is_within(ws, abs_path):
1570
1613
  return {"mode": "OFFLINE_FULL_FILE_PREVIEW", "error": "SECURITY_VIOLATION", "detail": f"Path traversal blocked: {path}"}
1571
1614
  current = ""
1572
1615
  if os.path.isfile(abs_path):
package/src/paths.py CHANGED
@@ -21,6 +21,8 @@ import shutil
21
21
  import sqlite3
22
22
  from typing import Optional
23
23
 
24
+ from src.win_paths import is_plugin_dir, is_system_root, transient_roots
25
+
24
26
  PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
25
27
 
26
28
  # Well-known state files carried over into the canonical directory.
@@ -115,19 +117,10 @@ def _migrate_into(target: str) -> None:
115
117
 
116
118
  def is_plugin_or_system_dir(path: str) -> bool:
117
119
  """Returns True if path is a system root or inside an agent plugin directory."""
118
- if not path:
119
- return True
120
- abs_p = os.path.abspath(path)
121
- system_roots = {"/", "/Users", "/home", "/root", os.path.expanduser("~")}
122
- if abs_p in system_roots:
123
- return True
124
- lower = abs_p.lower()
125
- if any(k in lower for k in (".gemini/config/plugins", "/.tokensafe", "plugins/tokensafe", ".cursor/extensions")):
126
- return True
127
- return False
120
+ return is_system_root(path) or is_plugin_dir(path)
128
121
 
129
122
 
130
- _TRANSIENT_ROOTS = ("/tmp", "/var/tmp", "/private/tmp", "/var/folders", "/private/var/folders")
123
+ _TRANSIENT_ROOTS = ()
131
124
 
132
125
 
133
126
  def is_transient_dir(path: str) -> bool:
@@ -141,7 +134,7 @@ def is_transient_dir(path: str) -> bool:
141
134
  if not path:
142
135
  return True
143
136
  real = os.path.realpath(os.path.abspath(path))
144
- roots = [os.path.realpath(p) for p in _TRANSIENT_ROOTS]
137
+ roots = [os.path.realpath(p) for p in transient_roots()]
145
138
  try:
146
139
  import tempfile
147
140
  roots.append(os.path.realpath(tempfile.gettempdir()))