tokensafe 4.14.0 → 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.
- package/.codex-plugin/plugin.json +1 -1
- package/hooks/claude_code_hook.py +8 -2
- package/hooks/cursor_hook.py +2 -1
- package/hooks/kimi_hook.py +2 -1
- package/hooks/post_tool_use.py +15 -1
- package/hooks/pre_invocation.py +4 -2
- package/hooks/pre_tool_use.py +13 -6
- package/hooks/session_start.py +7 -2
- package/hooks/stop_hook.py +2 -1
- package/hooks/zcode_hook.py +2 -1
- package/kimi.plugin.json +1 -1
- package/package.json +1 -1
- package/plugin.json +1 -1
- package/server.json +3 -3
- package/src/acp/server.py +5 -0
- package/src/auto_inject.py +6 -2
- package/src/cli.py +10 -0
- package/src/command_sanitizer.py +1 -1
- package/src/context_index.py +954 -0
- package/src/file_state.py +4 -3
- package/src/fts_index.py +12 -32
- package/src/graph_engine.py +43 -95
- package/src/guard.py +1 -1
- package/src/installer.py +64 -4
- package/src/license_manager.py +66 -0
- package/src/mcp_proxy.py +3 -0
- package/src/mcp_server.py +103 -5
- package/src/mistakes.py +45 -21
- package/src/oumv_gateway.py +17 -13
- package/src/paths.py +5 -12
- package/src/project_memory.py +264 -0
- package/src/result_ledger.py +40 -0
- package/src/retrofit.py +9 -4
- package/src/scoped_search.py +93 -53
- package/src/session_brief.py +14 -3
- package/src/skeletonizer.py +44 -2
- package/src/snapshot.py +17 -1
- package/src/stdio_io.py +50 -0
- package/src/telemetry_sync.py +1 -1
- package/src/version_checker.py +1 -1
- package/src/win_paths.py +172 -0
- 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.
|
|
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
|
-
|
|
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
|
-
|
|
25
|
-
|
|
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
|
|
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
|
-
|
|
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
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
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
|
|
173
|
-
|
|
192
|
+
if isinstance(item, dict):
|
|
193
|
+
cached.append(item)
|
|
174
194
|
except Exception:
|
|
175
195
|
pass
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
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
|
package/src/oumv_gateway.py
CHANGED
|
@@ -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):
|
|
@@ -621,7 +622,7 @@ class OUMVGateway:
|
|
|
621
622
|
|
|
622
623
|
# 1. Tool: oumv_status
|
|
623
624
|
@classmethod
|
|
624
|
-
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]:
|
|
625
626
|
cls.mark_oumv_used(workspace_dir)
|
|
626
627
|
ws = workspace_dir or get_active_workspace() or os.getcwd()
|
|
627
628
|
cls.scan(workspace_dir=ws)
|
|
@@ -633,8 +634,8 @@ class OUMVGateway:
|
|
|
633
634
|
# Out-of-the-box stack detection
|
|
634
635
|
stack_info = {}
|
|
635
636
|
try:
|
|
636
|
-
from src.retrofit import
|
|
637
|
-
stack_info =
|
|
637
|
+
from src.retrofit import detect_project_stack_cached
|
|
638
|
+
stack_info = detect_project_stack_cached(ws)
|
|
638
639
|
except Exception:
|
|
639
640
|
pass
|
|
640
641
|
|
|
@@ -678,13 +679,15 @@ class OUMVGateway:
|
|
|
678
679
|
if recorded_stale:
|
|
679
680
|
result["staleRuntimes"] = result.get("staleRuntimes", []) + recorded_stale
|
|
680
681
|
# A cold AST crawl costs ~15 s on a large monorepo. Start it now, in the
|
|
681
|
-
# background
|
|
682
|
-
#
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
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
|
|
688
691
|
return result
|
|
689
692
|
|
|
690
693
|
@staticmethod
|
|
@@ -1126,8 +1129,9 @@ class OUMVGateway:
|
|
|
1126
1129
|
# Out-of-the-box direct fallback when live dev-servers are offline
|
|
1127
1130
|
if replacement is not None:
|
|
1128
1131
|
abs_path = os.path.normpath(os.path.join(ws, path))
|
|
1129
|
-
#
|
|
1130
|
-
|
|
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):
|
|
1131
1135
|
raise RuntimeError(f"[OUMV SECURITY_VIOLATION: -32003] Path traversal blocked: {path}")
|
|
1132
1136
|
|
|
1133
1137
|
import hashlib
|
|
@@ -1605,7 +1609,7 @@ class OUMVGateway:
|
|
|
1605
1609
|
offline["detail"] = "offline preview requires 'replacement' (whole-file content)"
|
|
1606
1610
|
return offline
|
|
1607
1611
|
abs_path = os.path.normpath(os.path.join(ws, path))
|
|
1608
|
-
if not
|
|
1612
|
+
if not is_within(ws, abs_path):
|
|
1609
1613
|
return {"mode": "OFFLINE_FULL_FILE_PREVIEW", "error": "SECURITY_VIOLATION", "detail": f"Path traversal blocked: {path}"}
|
|
1610
1614
|
current = ""
|
|
1611
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
|
-
|
|
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 = (
|
|
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
|
|
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()))
|
|
@@ -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 ""
|