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
@@ -0,0 +1,264 @@
1
+ """Project memory that survives sessions — machine-local, never in the repo.
2
+
3
+ `mistakes.jsonl` already remembers dead ends per project; this module adds the
4
+ three kinds of memory an agent cannot re-derive cheaply: decisions (why a shape
5
+ was chosen), known-good commands (what actually passed here), and free-form
6
+ notes/preferences.
7
+
8
+ Storage: ``~/.tokensafe/data/projects/<sha256(realpath(root))[:16]>/memory.json``
9
+ Written atomically (``src.atomic_io``) and redacted through ``secret_redactor``
10
+ before it touches disk. Nothing is ever written into the workspace, so memory
11
+ cannot leak into a public repository through a commit.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import hashlib
17
+ import json
18
+ import os
19
+ import time
20
+ import uuid
21
+ from typing import Any, Dict, List, Optional
22
+
23
+ from src.atomic_io import write_text_atomic
24
+ from src.paths import resolve_data_dir
25
+
26
+ MEMORY_SCHEMA_VERSION = 1
27
+ MAX_DECISIONS = 100
28
+ MAX_NOTES = 100
29
+ MAX_COMMANDS = 50
30
+ MAX_TEXT_CHARS = 2000
31
+ MAX_COMMAND_CHARS = 200
32
+
33
+ _KINDS = ("decision", "note", "preference")
34
+
35
+
36
+ def project_key(root: str) -> str:
37
+ return hashlib.sha256(os.path.realpath(os.path.abspath(root)).encode("utf-8")).hexdigest()[:16]
38
+
39
+
40
+ def memory_path(root: str) -> str:
41
+ return os.path.join(resolve_data_dir(), "projects", project_key(root), "memory.json")
42
+
43
+
44
+ def _empty() -> Dict[str, Any]:
45
+ return {
46
+ "version": MEMORY_SCHEMA_VERSION,
47
+ "updated_at": 0.0,
48
+ "decisions": [],
49
+ "notes": [],
50
+ "preferences": {},
51
+ "commands": [],
52
+ }
53
+
54
+
55
+ def _redact(text: str) -> str:
56
+ try:
57
+ from src.secret_redactor import SecretRedactor
58
+
59
+ cleaned, _count, _kinds = SecretRedactor.redact_text(text)
60
+ return cleaned
61
+ except Exception:
62
+ return text
63
+
64
+
65
+ def _command_kind(cmd: str) -> str:
66
+ lowered = cmd.lower()
67
+ if any(token in lowered for token in ("test", "pytest", "unittest", "vitest", "jest", "go test", "cargo test")):
68
+ return "test"
69
+ if any(token in lowered for token in ("build", "compile", "bundle", "tsc", "go build", "cargo build", "make")):
70
+ return "build"
71
+ if any(token in lowered for token in ("lint", "ruff", "eslint", "flake8", "mypy", "typecheck")):
72
+ return "lint"
73
+ if any(token in lowered for token in ("dev", "serve", "start", "watch")):
74
+ return "dev"
75
+ if any(token in lowered for token in ("install", "npm i", "npm ci", "pip install", "bun add", "pnpm add")):
76
+ return "install"
77
+ if lowered.startswith(("git ", "gh ")):
78
+ return "git"
79
+ return "other"
80
+
81
+
82
+ class ProjectMemory:
83
+ """Read-modify-write memory for one workspace root."""
84
+
85
+ def __init__(self, root: str = "."):
86
+ self.root = os.path.realpath(os.path.abspath(root or "."))
87
+ self.path = memory_path(self.root)
88
+
89
+ # ------------------------------------------------------------------ io
90
+ def load(self) -> Dict[str, Any]:
91
+ try:
92
+ with open(self.path, "r", encoding="utf-8") as handle:
93
+ data = json.load(handle)
94
+ if not isinstance(data, dict):
95
+ return _empty()
96
+ except (OSError, ValueError):
97
+ return _empty()
98
+ base = _empty()
99
+ for key, value in data.items():
100
+ if key in base:
101
+ base[key] = value
102
+ for key in ("decisions", "notes", "commands"):
103
+ if not isinstance(base[key], list):
104
+ base[key] = []
105
+ if not isinstance(base["preferences"], dict):
106
+ base["preferences"] = {}
107
+ return base
108
+
109
+ def _save(self, data: Dict[str, Any]) -> None:
110
+ data["version"] = MEMORY_SCHEMA_VERSION
111
+ data["updated_at"] = time.time()
112
+ write_text_atomic(self.path, json.dumps(data, ensure_ascii=False, indent=2) + "\n")
113
+
114
+ # -------------------------------------------------------------- writes
115
+ def remember(self, kind: str, text: str, files: Optional[List[str]] = None) -> Dict[str, Any]:
116
+ kind = (kind or "decision").strip().lower()
117
+ if kind not in _KINDS:
118
+ kind = "note"
119
+ cleaned = _redact(str(text or "").strip())[:MAX_TEXT_CHARS]
120
+ if not cleaned:
121
+ raise ValueError("memory text is empty")
122
+ data = self.load()
123
+ now = time.time()
124
+ if kind == "preference":
125
+ key_part, _, value_part = cleaned.partition("=")
126
+ key = key_part.strip().lower().replace(" ", "_")[:64]
127
+ value = (value_part or cleaned).strip()[:200]
128
+ data["preferences"][key or "note"] = value
129
+ self._save(data)
130
+ return {"id": f"pref:{key}", "kind": "preference", "key": key, "value": value}
131
+
132
+ bucket = "decisions" if kind == "decision" else "notes"
133
+ normalized = " ".join(cleaned.split()).lower()
134
+ for entry in data[bucket]:
135
+ if " ".join(str(entry.get("text", "")).split()).lower() == normalized:
136
+ entry["ts"] = now
137
+ self._save(data)
138
+ return entry
139
+ entry = {
140
+ "id": uuid.uuid4().hex[:12],
141
+ "kind": kind,
142
+ "text": cleaned,
143
+ "files": [str(f) for f in (files or [])][:20],
144
+ "ts": now,
145
+ }
146
+ data[bucket].insert(0, entry)
147
+ cap = MAX_DECISIONS if kind == "decision" else MAX_NOTES
148
+ del data[bucket][cap:]
149
+ self._save(data)
150
+ return entry
151
+
152
+ def record_command(self, cmd: str, cwd: str = "", exit_code: int = 0) -> Optional[Dict[str, Any]]:
153
+ cleaned = _redact(" ".join(str(cmd or "").split()))[:MAX_COMMAND_CHARS]
154
+ if not cleaned:
155
+ return None
156
+ kind = _command_kind(cleaned)
157
+ if kind == "other":
158
+ # Known-good commands are the point; ls/cd/git noise is not.
159
+ return None
160
+ data = self.load()
161
+ success = int(exit_code) == 0
162
+ for entry in data["commands"]:
163
+ if entry.get("cmd") == cleaned:
164
+ entry["ok" if success else "fail"] = int(entry.get("ok" if success else "fail", 0)) + 1
165
+ entry["last_ts"] = time.time()
166
+ if cwd:
167
+ entry["cwd"] = cwd[:400]
168
+ self._save(data)
169
+ return entry
170
+ entry = {
171
+ "cmd": cleaned,
172
+ "kind": kind,
173
+ "cwd": str(cwd or "")[:400],
174
+ "ok": 1 if success else 0,
175
+ "fail": 0 if success else 1,
176
+ "last_ts": time.time(),
177
+ }
178
+ data["commands"].insert(0, entry)
179
+ data["commands"].sort(key=lambda item: (item.get("ok", 0), item.get("last_ts", 0)), reverse=True)
180
+ del data["commands"][MAX_COMMANDS:]
181
+ self._save(data)
182
+ return entry
183
+
184
+ def forget(self, entry_id: str) -> bool:
185
+ target = str(entry_id or "").strip()
186
+ if not target:
187
+ return False
188
+ data = self.load()
189
+ removed = False
190
+ for bucket in ("decisions", "notes"):
191
+ kept = [entry for entry in data[bucket] if str(entry.get("id")) != target]
192
+ removed = removed or len(kept) != len(data[bucket])
193
+ data[bucket] = kept
194
+ if target.startswith("pref:"):
195
+ removed = data["preferences"].pop(target[5:], None) is not None or removed
196
+ if removed:
197
+ self._save(data)
198
+ return removed
199
+
200
+ # --------------------------------------------------------------- reads
201
+ def recall(self, query: str = "", limit: int = 10) -> Dict[str, Any]:
202
+ data = self.load()
203
+ limit = max(1, min(int(limit or 10), 50))
204
+ tokens = [token for token in str(query or "").lower().split() if token]
205
+
206
+ def _score(entry: Dict[str, Any]) -> int:
207
+ if not tokens:
208
+ return 0
209
+ haystack = (str(entry.get("text", "")) + " " + " ".join(entry.get("files") or [])).lower()
210
+ return sum(1 for token in tokens if token in haystack)
211
+
212
+ decisions = sorted(data["decisions"], key=lambda e: (_score(e), e.get("ts", 0)), reverse=True)
213
+ notes = sorted(data["notes"], key=lambda e: (_score(e), e.get("ts", 0)), reverse=True)
214
+ if tokens:
215
+ decisions = [entry for entry in decisions if _score(entry) > 0]
216
+ notes = [entry for entry in notes if _score(entry) > 0]
217
+ return {
218
+ "root": self.root,
219
+ "path": self.path,
220
+ "query": query,
221
+ "decisions": decisions[:limit],
222
+ "notes": notes[:limit],
223
+ "preferences": data["preferences"],
224
+ "commands": data["commands"][:limit],
225
+ "preferred": {
226
+ kind: self.preferred_command(kind, data=data)
227
+ for kind in ("test", "build", "lint", "dev")
228
+ },
229
+ }
230
+
231
+ def preferred_command(self, kind: str = "test", data: Optional[Dict[str, Any]] = None) -> Optional[str]:
232
+ data = data or self.load()
233
+ candidates = [entry for entry in data["commands"] if entry.get("kind") == kind]
234
+ if not candidates:
235
+ return None
236
+ candidates.sort(key=lambda entry: (entry.get("ok", 0) - entry.get("fail", 0), entry.get("last_ts", 0)), reverse=True)
237
+ best = candidates[0]
238
+ return str(best.get("cmd")) if best.get("ok", 0) else None
239
+
240
+ def summary(self, max_chars: int = 300) -> str:
241
+ data = self.load()
242
+ if not data["decisions"] and not data["notes"] and not data["commands"]:
243
+ return ""
244
+ parts = []
245
+ if data["decisions"]:
246
+ parts.append(f"{len(data['decisions'])} decision(s)")
247
+ test_cmd = self.preferred_command("test", data=data)
248
+ if test_cmd:
249
+ parts.append(f"test: {test_cmd}")
250
+ build_cmd = self.preferred_command("build", data=data)
251
+ if build_cmd:
252
+ parts.append(f"build: {build_cmd}")
253
+ if data["decisions"]:
254
+ parts.append(f"latest: {str(data['decisions'][0].get('text', ''))[:80]}")
255
+ text = "Project memory: " + "; ".join(parts)
256
+ return text[:max_chars]
257
+
258
+
259
+ def memory_summary(root: str = ".", max_chars: int = 300) -> str:
260
+ """Cheap read for the session brief; never creates the memory file."""
261
+ try:
262
+ return ProjectMemory(root).summary(max_chars=max_chars)
263
+ except Exception:
264
+ return ""
@@ -78,6 +78,46 @@ def _archive_result(text: str, sha: str) -> Optional[str]:
78
78
  return None
79
79
 
80
80
 
81
+ def prune_archives(max_files: int = 2000, max_age_days: float = 30.0) -> int:
82
+ """Bounds ``data/tool_ledger`` archives and returns the removed count.
83
+
84
+ Archived tool results had no cleanup path at all; the ledger only ever
85
+ grew. Called by ``tokensafe oumv doctor --prune``.
86
+ """
87
+ import time
88
+
89
+ try:
90
+ from src.paths import resolve_data_dir
91
+
92
+ archive_dir = os.path.join(resolve_data_dir(), ARCHIVE_DIRNAME)
93
+ names = os.listdir(archive_dir)
94
+ except OSError:
95
+ return 0
96
+ now = time.time()
97
+ entries = []
98
+ for name in names:
99
+ if not name.endswith(".json"):
100
+ continue
101
+ path = os.path.join(archive_dir, name)
102
+ try:
103
+ entries.append((os.stat(path).st_mtime, path))
104
+ except OSError:
105
+ continue
106
+ entries.sort(reverse=True)
107
+ removed = 0
108
+ for idx, (mtime, path) in enumerate(entries):
109
+ too_old = (now - mtime) > max_age_days * 86400
110
+ over_cap = idx >= max_files
111
+ if not (too_old or over_cap):
112
+ continue
113
+ try:
114
+ os.remove(path)
115
+ removed += 1
116
+ except OSError:
117
+ pass
118
+ return removed
119
+
120
+
81
121
  def _head_tail(text: str, head: int = HEAD_LINES, tail: int = TAIL_LINES) -> str:
82
122
  lines = text.splitlines()
83
123
  if len(lines) <= head + tail + 2:
package/src/retrofit.py CHANGED
@@ -11,6 +11,8 @@ import time
11
11
  from pathlib import Path
12
12
  from typing import Dict, Any, List, Optional, Tuple
13
13
 
14
+ from src.backend_release import BACKEND_NPM_VERSION, BACKEND_WIRE_VERSION
15
+
14
16
  # Top-level directories that hold frontend source in a repo-root app (as opposed to
15
17
  # scripts/, tooling/ and configs, which are .ts/.js but not OUMV-observable).
16
18
  _FRONTEND_SOURCE_DIRS = frozenset({
@@ -808,7 +810,7 @@ def get_adapters_catalog() -> List[Dict[str, Any]]:
808
810
  "technology": {
809
811
  "language": "typescript",
810
812
  "framework": "express | fastify",
811
- "package": {"manager": "npm", "name": "tokensafe-backend-node", "install": "npm install tokensafe-backend-node"},
813
+ "package": {"manager": "npm", "name": "tokensafe-backend-node", "install": f"npm install tokensafe-backend-node@{BACKEND_NPM_VERSION}"},
812
814
  },
813
815
  "capabilities": [
814
816
  {"name": "observe.pulse", "constraints": {"readOnly": True, "developmentOnly": True}},
@@ -834,7 +836,7 @@ def get_adapters_catalog() -> List[Dict[str, Any]]:
834
836
  "technology": {
835
837
  "language": "typescript",
836
838
  "framework": "elysia (bun)",
837
- "package": {"manager": "bun", "name": "tokensafe-backend-node", "install": "bun add tokensafe-backend-node"},
839
+ "package": {"manager": "bun", "name": "tokensafe-backend-node", "install": f"bun add tokensafe-backend-node@{BACKEND_NPM_VERSION}"},
838
840
  },
839
841
  "capabilities": [
840
842
  {"name": "observe.pulse", "constraints": {"readOnly": True, "developmentOnly": True}},
@@ -862,7 +864,7 @@ def get_adapters_catalog() -> List[Dict[str, Any]]:
862
864
  "technology": {
863
865
  "language": "typescript",
864
866
  "framework": "next (app router)",
865
- "package": {"manager": "npm", "name": "tokensafe-backend-node", "install": "npm install --save-dev tokensafe-backend-node"},
867
+ "package": {"manager": "npm", "name": "tokensafe-backend-node", "install": f"npm install --save-dev tokensafe-backend-node@{BACKEND_NPM_VERSION}"},
866
868
  },
867
869
  "capabilities": [
868
870
  {"name": "observe.pulse", "constraints": {"readOnly": True, "developmentOnly": True}},
@@ -886,7 +888,7 @@ def get_adapters_catalog() -> List[Dict[str, Any]]:
886
888
  "repo": "tokensafe-backend/dotnet",
887
889
  "mode": "hybrid",
888
890
  "status": "ready",
889
- "description": "In-process endpoint dispatch for minimal APIs and controllers, Roslyn syntax pre-flight, the full wire 1.6.0 surface (previewEdit, index, query, build, cancel), and verify.sandboxRollback that rolls every auto-discovered EF Core DbContext back",
891
+ "description": f"In-process endpoint dispatch for minimal APIs and controllers, Roslyn syntax pre-flight, the full wire {BACKEND_WIRE_VERSION} surface (previewEdit, index, query, build, cancel), and verify.sandboxRollback that rolls every auto-discovered EF Core DbContext back",
890
892
  "technology": {
891
893
  "language": "csharp",
892
894
  "framework": "aspnetcore",
@@ -1193,10 +1195,12 @@ def _resolve_tokensafe_ui_cli_uncached(workspace_dir: str) -> Optional[Tuple[Lis
1193
1195
  if env_cli and os.path.isfile(env_cli):
1194
1196
  return (["node", env_cli], "TOKENSAFE_UI_CLI")
1195
1197
 
1196
- # 2. Local project node_modules/.bin/tokensafe-ui (if present)
1198
+ # 2. Local project node_modules/.bin/tokensafe-ui (if present). Windows
1199
+ # package managers install a ``.cmd`` shim, not a POSIX script.
1197
1200
  local_bin = os.path.join(ws, "node_modules", ".bin", "tokensafe-ui")
1198
- if os.path.isfile(local_bin):
1199
- return ([local_bin], "local node_modules")
1201
+ for candidate in (local_bin, local_bin + ".cmd", local_bin + ".bat"):
1202
+ if os.path.isfile(candidate):
1203
+ return ([candidate], "local node_modules")
1200
1204
 
1201
1205
  # 3. Global tokensafe-ui binary on PATH
1202
1206
  global_bin = shutil.which("tokensafe-ui")
@@ -1205,7 +1209,10 @@ def _resolve_tokensafe_ui_cli_uncached(workspace_dir: str) -> Optional[Tuple[Lis
1205
1209
 
1206
1210
  # 4. npm global root package (nvm-style installs whose bin dir is not on PATH)
1207
1211
  try:
1208
- res = subprocess.run(["npm", "root", "-g"], capture_output=True, text=True, timeout=3)
1212
+ from src.win_paths import resolve_executable
1213
+
1214
+ npm_bin = resolve_executable("npm") or "npm"
1215
+ res = subprocess.run([npm_bin, "root", "-g"], capture_output=True, text=True, timeout=3)
1209
1216
  if res.returncode == 0:
1210
1217
  cli_js = os.path.join(res.stdout.strip(), "tokensafe-ui", "bin", "cli.js")
1211
1218
  if os.path.isfile(cli_js):
@@ -102,6 +102,89 @@ class ScopedSearch:
102
102
  return per_file
103
103
  return max(4, min(8, max_results // 3))
104
104
 
105
+ @classmethod
106
+ def _symbol_lookup(
107
+ cls,
108
+ query: str,
109
+ root_dir: str,
110
+ scope: str,
111
+ max_results: int,
112
+ per_file: int,
113
+ ) -> Optional[Dict[str, Any]]:
114
+ """One symbol-index answer, or None when the corpus must be asked.
115
+
116
+ Runs for identifier-shaped queries before the FTS corpus, so a graph
117
+ written moments ago cannot be shadowed by a text generation that is a
118
+ scan behind. ``index_age_s``/``stale`` keep the answer honest about how
119
+ old the index it came from is.
120
+ """
121
+ if not re.fullmatch(r"[A-Za-z_$][\w$]{2,}", query or ""):
122
+ return None
123
+ graph = cls._graph_symbol_index(root_dir)
124
+ matches = cls._symbol_matches(query, root_dir, scope, max_results, per_file, graph=graph)
125
+ if matches is None:
126
+ return None
127
+ hit_files = {m["file"] for m in matches}
128
+ indexed = 0
129
+ try:
130
+ indexed = len(set(graph.file_stats) | set(graph.file_symbols)) if graph else 0
131
+ except Exception:
132
+ indexed = 0
133
+ age: Optional[float] = None
134
+ if graph is not None and getattr(graph, "last_scanned", 0):
135
+ age = max(0.0, time.time() - float(graph.last_scanned))
136
+ try:
137
+ ttl = float(os.environ.get("TOKENSAFE_GRAPH_TTL", "60.0"))
138
+ except ValueError:
139
+ ttl = 60.0
140
+ stale = bool(age is not None and age > ttl)
141
+ stopped = "index_stale" if stale else "index_only"
142
+ markdown = cls._render_markdown(
143
+ query, matches, indexed or len(hit_files), False, max_results,
144
+ hit_files=hit_files, scope=scope, root_dir=root_dir,
145
+ total_files=indexed or len(hit_files),
146
+ stopped_reason=stopped,
147
+ coverage_complete=False,
148
+ coverage_source="graph_symbol_index",
149
+ )
150
+ if indexed:
151
+ age_note = f", index age {int(age)}s" if age is not None else ""
152
+ if stale:
153
+ age_note += " — stale, refresh with any graph tool"
154
+ markdown += (
155
+ f"\n_Answered from the AST symbol index ({indexed} indexed files{age_note}): "
156
+ f"declarations only, source files covered._"
157
+ )
158
+ return {
159
+ "success": True,
160
+ "query": query,
161
+ "scope": scope,
162
+ "source": "graph_symbol_index",
163
+ "path_is_file": False,
164
+ "files_matched": len(hit_files),
165
+ "scanned_files": indexed or len(hit_files),
166
+ "total_files": indexed or len(hit_files),
167
+ "total_matches": len(matches),
168
+ "overflow_matches": 0,
169
+ "per_file_cap": cls._resolve_per_file(per_file, max_results),
170
+ "timed_out": False,
171
+ "partial": False,
172
+ "truncated": len(matches) >= max_results,
173
+ "index_age_s": None if age is None else round(age, 3),
174
+ "stale": stale,
175
+ "coverage": {
176
+ "complete": False,
177
+ "stopped_reason": stopped,
178
+ "source": "graph_symbol_index",
179
+ "index_only": True,
180
+ "indexed_files": indexed,
181
+ "index_age_s": None if age is None else round(age, 3),
182
+ "stale": stale,
183
+ },
184
+ "matches": matches,
185
+ "markdown": markdown,
186
+ }
187
+
105
188
  @classmethod
106
189
  def _graph_symbol_index(cls, root_dir: str):
107
190
  """Cache-only view of the AST symbol index; never starts a repository crawl.
@@ -270,6 +353,14 @@ class ScopedSearch:
270
353
  per_file=per_file,
271
354
  )
272
355
 
356
+ # Identifier queries are lookups: ask the AST index before the text
357
+ # corpus, so a graph written moments ago cannot be shadowed by an FTS
358
+ # generation that is a scan behind.
359
+ if not regex_mode and not case_sensitive:
360
+ symbol_result = cls._symbol_lookup(query, root_dir, scope, max_results, per_file)
361
+ if symbol_result is not None:
362
+ return symbol_result
363
+
273
364
  # Fast-path: SQLite FTS5 trigram BM25 search for plain case-insensitive queries
274
365
  if not regex_mode and not case_sensitive and len(query) >= 3 and not any(c in query for c in "*?[]{}()^$+\\|"):
275
366
  try:
@@ -341,59 +432,8 @@ class ScopedSearch:
341
432
  except Exception:
342
433
  pass # Seamless fallback to disk scan
343
434
 
344
- # Symbol fast path: an identifier is a lookup, and the AST index covers every
345
- # file while the bounded disk walk below covers only the first 2,500.
346
- if not regex_mode and not case_sensitive:
347
- # One index load per query: the symbol fast path and its coverage
348
- # count used to deserialize the same graph twice.
349
- graph = cls._graph_symbol_index(root_dir)
350
- symbol_matches = cls._symbol_matches(query, root_dir, scope, max_results, per_file, graph=graph)
351
- if symbol_matches is not None:
352
- hit_files = {m["file"] for m in symbol_matches}
353
- indexed = 0
354
- try:
355
- indexed = len(set(graph.file_stats) | set(graph.file_symbols)) if graph else 0
356
- except Exception:
357
- indexed = 0
358
- markdown = cls._render_markdown(
359
- query, symbol_matches, indexed or len(hit_files), False, max_results,
360
- hit_files=hit_files, scope=scope, root_dir=root_dir,
361
- total_files=indexed or len(hit_files),
362
- stopped_reason="index_only",
363
- coverage_complete=False,
364
- coverage_source="graph_symbol_index",
365
- )
366
- if indexed:
367
- markdown += (
368
- f"\n_Answered from the AST symbol index ({indexed} indexed files): "
369
- f"declarations only, complete across the repository._"
370
- )
371
- return {
372
- "success": True,
373
- "query": query,
374
- "scope": scope,
375
- "source": "graph_symbol_index",
376
- "path_is_file": False,
377
- "files_matched": len(hit_files),
378
- "scanned_files": indexed or len(hit_files),
379
- "total_files": indexed or len(hit_files),
380
- "total_matches": len(symbol_matches),
381
- "overflow_matches": 0,
382
- "per_file_cap": cls._resolve_per_file(per_file, max_results),
383
- "timed_out": False,
384
- "partial": False,
385
- "truncated": len(symbol_matches) >= max_results,
386
- "coverage": {
387
- "complete": False,
388
- "stopped_reason": "index_only",
389
- "source": "graph_symbol_index",
390
- "index_only": True,
391
- "indexed_files": indexed,
392
- },
393
- "matches": symbol_matches,
394
- "markdown": markdown,
395
- }
396
-
435
+ # Identifiers were answered from the AST symbol index before the text
436
+ # corpus; prose that found no declaration continues to the disk walk.
397
437
 
398
438
  matches: List[Dict[str, Any]] = []
399
439
  total_scanned_files = 0
@@ -372,8 +372,8 @@ def build_workspace_brief(
372
372
  return ""
373
373
 
374
374
  try:
375
- from src.retrofit import detect_project_stack
376
- stack = detect_project_stack(workspace)
375
+ from src.retrofit import detect_project_stack_cached
376
+ stack = detect_project_stack_cached(workspace)
377
377
  except Exception:
378
378
  return ""
379
379
 
@@ -419,10 +419,21 @@ def build_workspace_brief(
419
419
  if mutate else "disabled by .tokensafe/oumv.json (permissions.mutate=false)"),
420
420
  ))
421
421
 
422
+ # Machine-local project memory: decisions, known-good commands, notes.
423
+ # One line, capped, and only when memory actually exists.
424
+ try:
425
+ from src.project_memory import memory_summary
426
+
427
+ memory_line = memory_summary(workspace, max_chars=300)
428
+ if memory_line:
429
+ entries.append((5, "- " + memory_line))
430
+ except Exception:
431
+ pass
432
+
422
433
  if include_live:
423
434
  try:
424
435
  from src.oumv_gateway import OUMVGateway
425
- status = OUMVGateway.status(workspace_dir=workspace)
436
+ status = OUMVGateway.status(workspace_dir=workspace, warm_graph=False)
426
437
  live = []
427
438
  for profile in ("frontend", "backend"):
428
439
  item = status.get(profile) or {}
@@ -737,6 +737,43 @@ class Skeletonizer:
737
737
 
738
738
  return "\n".join(out)
739
739
 
740
+ @classmethod
741
+ def prune(cls, max_files: int = 5000, max_age_days: float = 30.0) -> int:
742
+ """Bounds the rendered-skeleton cache and returns the removed count.
743
+
744
+ The cache had no eviction path at all (6274 files / 35 MB on a working
745
+ machine): every (path, symbol, dep_mode) combination stayed forever.
746
+ Called by ``tokensafe oumv doctor --prune``.
747
+ """
748
+ import time
749
+
750
+ try:
751
+ names = os.listdir(cls.CACHE_DIR)
752
+ except OSError:
753
+ return 0
754
+ now = time.time()
755
+ entries = []
756
+ for name in names:
757
+ path = os.path.join(cls.CACHE_DIR, name)
758
+ try:
759
+ st = os.stat(path)
760
+ except OSError:
761
+ continue
762
+ entries.append((st.st_mtime, path))
763
+ entries.sort(reverse=True)
764
+ removed = 0
765
+ for idx, (mtime, path) in enumerate(entries):
766
+ too_old = (now - mtime) > max_age_days * 86400
767
+ over_cap = idx >= max_files
768
+ if not (too_old or over_cap):
769
+ continue
770
+ try:
771
+ os.remove(path)
772
+ removed += 1
773
+ except OSError:
774
+ pass
775
+ return removed
776
+
740
777
  @classmethod
741
778
  def get_skeleton_file(cls, original_path: str, target_symbol: Optional[str] = None, dep_mode: str = "signature") -> Tuple[Optional[str], int, int]:
742
779
  """
@@ -757,8 +794,13 @@ class Skeletonizer:
757
794
 
758
795
  # Ensure cache directory exists
759
796
  os.makedirs(cls.CACHE_DIR, exist_ok=True)
760
- path_hash = hashlib.md5(original_path.encode("utf-8")).hexdigest()[:8]
761
- base_name = os.path.basename(original_path)
797
+ from src.win_paths import state_key
798
+
799
+ # Windows forbids reserved device names, trailing dots/spaces and
800
+ # punctuation in file names; a repo basename must never abort a read.
801
+ safe_name = re.sub(r"[^A-Za-z0-9_. -]+", "_", os.path.basename(original_path)).strip(" .") or "file"
802
+ path_hash = hashlib.md5(state_key(original_path).encode("utf-8")).hexdigest()[:8]
803
+ base_name = safe_name
762
804
  if target_symbol:
763
805
  safe_sym = re.sub(r"[^A-Za-z0-9_.-]+", "_", target_symbol).strip("_")[:48] or "sym"
764
806
  sym_suffix = f"_{safe_sym}_{dep_mode}"
package/src/snapshot.py CHANGED
@@ -65,6 +65,22 @@ def _is_system_or_home_root(p: str) -> bool:
65
65
  return False
66
66
 
67
67
 
68
+ def _decode_git_path(path: str) -> str:
69
+ """Decodes git's C-style quoting (non-ASCII paths arrive as octal escapes)."""
70
+ if len(path) < 2 or not (path.startswith('"') and path.endswith('"')):
71
+ return path
72
+ body = path[1:-1]
73
+ if "\\" not in body:
74
+ return body
75
+ try:
76
+ import codecs
77
+
78
+ raw = codecs.escape_decode(body.encode("utf-8"))[0]
79
+ return raw.decode("utf-8", "replace")
80
+ except Exception:
81
+ return body
82
+
83
+
68
84
  def _parse_porcelain_paths(status_raw: str, limit: int = 6) -> List[str]:
69
85
  """Extracts display paths from `git status --porcelain=v1` output.
70
86
 
@@ -79,7 +95,7 @@ def _parse_porcelain_paths(status_raw: str, limit: int = 6) -> List[str]:
79
95
  if " -> " in path: # renames: "R old -> new"
80
96
  path = path.split(" -> ", 1)[1]
81
97
  if len(path) >= 2 and path.startswith('"') and path.endswith('"'):
82
- path = path[1:-1]
98
+ path = _decode_git_path(path)
83
99
  paths.append(path)
84
100
  return paths
85
101