tokensafe 3.1.5 → 4.0.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/README.md +79 -58
- package/bin/tokensafe.js +25 -9
- package/hooks/claude_code_hook.py +7 -0
- package/hooks/pre_tool_use.py +24 -0
- package/hooks/session_start.py +8 -0
- package/package.json +3 -3
- package/plugin.json +1 -1
- package/rules/AGENTS.md +13 -7
- package/server.json +3 -3
- package/skills/token-optimizer/SKILL.md +7 -2
- package/skills/token-optimizer/references/cli-reference.md +11 -1
- package/skills/token-optimizer/references/mcp-tools.md +44 -2
- package/src/bench_scenarios.json +376 -0
- package/src/cache_normalizer.py +21 -0
- package/src/cli.py +425 -4
- package/src/command_sanitizer.py +2 -0
- package/src/compactor.py +1 -1
- package/src/competitors.py +179 -0
- package/src/environment_auditor.py +110 -1
- package/src/format_parsers/__init__.py +20 -0
- package/src/format_parsers/ansi.py +41 -0
- package/src/format_parsers/compiler_errors.py +159 -0
- package/src/format_parsers/docker_k8s.py +95 -0
- package/src/format_parsers/json_log.py +89 -0
- package/src/format_parsers/lockfiles.py +157 -0
- package/src/format_parsers/tabular.py +175 -0
- package/src/fts_index.py +296 -0
- package/src/graph_engine.py +395 -48
- package/src/image_downscale.py +228 -0
- package/src/installer.py +47 -1
- package/src/license_manager.py +103 -7
- package/src/loop_detector.py +5 -0
- package/src/mcp_config_manager.py +197 -0
- package/src/mcp_proxy.py +154 -0
- package/src/mcp_server.py +215 -1
- package/src/mistakes.py +203 -0
- package/src/result_ledger.py +8 -1
- package/src/scoped_search.py +32 -0
- package/src/stash.py +199 -0
- package/src/superseded.py +220 -0
- package/src/telemetry_sync.py +14 -1
- package/src/test_parsers.py +271 -0
- package/src/version_checker.py +1 -1
- package/src/web_reader.py +202 -0
package/src/mcp_proxy.py
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
"""
|
|
2
|
+
TokenSafe MCP Response Proxy (v3.3.0).
|
|
3
|
+
|
|
4
|
+
Transparent stdio JSON-RPC 2.0 proxy for third-party MCP servers.
|
|
5
|
+
Spawns the target MCP server as a subprocess, relays messages bidirectionally,
|
|
6
|
+
and intercepts oversized tool responses (e.g. GitHub, Linear, Slack, Context7).
|
|
7
|
+
When a tool response exceeds MAX_UNFOLDED_CHARS (1500 chars / ~400 tokens), it
|
|
8
|
+
folds the payload, saves the raw original into TokenSafe Reversible Stash, and
|
|
9
|
+
attaches a hash anchor:
|
|
10
|
+
[TokenSafe folded: #a1b2c3d4 — call tokensafe:expand_ref('a1b2c3d4') to restore raw content]
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
import sys
|
|
14
|
+
import os
|
|
15
|
+
import json
|
|
16
|
+
import subprocess
|
|
17
|
+
import threading
|
|
18
|
+
from typing import Dict, Any, Optional, List, Tuple
|
|
19
|
+
|
|
20
|
+
from src.stash import stash_block
|
|
21
|
+
|
|
22
|
+
MAX_UNFOLDED_CHARS = 1500
|
|
23
|
+
MAX_UNFOLDED_LINES = 35
|
|
24
|
+
HEAD_LINES = 15
|
|
25
|
+
TAIL_LINES = 10
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def fold_tool_text(text: str, tool_name: str = "mcp_tool") -> Tuple[str, bool]:
|
|
29
|
+
"""Folds oversized text and returns (folded_text, was_folded)."""
|
|
30
|
+
if not text:
|
|
31
|
+
return text, False
|
|
32
|
+
from src.format_parsers.ansi import strip_ansi
|
|
33
|
+
text = strip_ansi(text)
|
|
34
|
+
if len(text) <= MAX_UNFOLDED_CHARS:
|
|
35
|
+
return text, False
|
|
36
|
+
|
|
37
|
+
lines = text.splitlines()
|
|
38
|
+
if len(lines) <= MAX_UNFOLDED_LINES:
|
|
39
|
+
return text, False
|
|
40
|
+
|
|
41
|
+
hash8, marker = stash_block(text, source=f"mcp:{tool_name}")
|
|
42
|
+
head = lines[:HEAD_LINES]
|
|
43
|
+
tail = lines[-TAIL_LINES:]
|
|
44
|
+
omitted = len(lines) - (HEAD_LINES + TAIL_LINES)
|
|
45
|
+
|
|
46
|
+
folded_lines = head + [
|
|
47
|
+
f"... [{omitted} lines folded by TokenSafe MCP Proxy] ...",
|
|
48
|
+
] + tail + [marker]
|
|
49
|
+
|
|
50
|
+
return "\n".join(folded_lines), True
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def compact_mcp_response(resp: Dict[str, Any]) -> Dict[str, Any]:
|
|
54
|
+
"""Inspects an MCP JSON-RPC response and compacts tools/call content blocks."""
|
|
55
|
+
if not isinstance(resp, dict):
|
|
56
|
+
return resp
|
|
57
|
+
|
|
58
|
+
result = resp.get("result")
|
|
59
|
+
if not isinstance(result, dict):
|
|
60
|
+
return resp
|
|
61
|
+
|
|
62
|
+
content = result.get("content")
|
|
63
|
+
if not isinstance(content, list):
|
|
64
|
+
return resp
|
|
65
|
+
|
|
66
|
+
modified = False
|
|
67
|
+
new_content = []
|
|
68
|
+
for block in content:
|
|
69
|
+
if isinstance(block, dict) and block.get("type") == "text":
|
|
70
|
+
raw_text = block.get("text", "")
|
|
71
|
+
folded_text, was_folded = fold_tool_text(raw_text)
|
|
72
|
+
if was_folded:
|
|
73
|
+
new_block = dict(block)
|
|
74
|
+
new_block["text"] = folded_text
|
|
75
|
+
new_content.append(new_block)
|
|
76
|
+
modified = True
|
|
77
|
+
else:
|
|
78
|
+
new_content.append(block)
|
|
79
|
+
else:
|
|
80
|
+
new_content.append(block)
|
|
81
|
+
|
|
82
|
+
if modified:
|
|
83
|
+
new_resp = dict(resp)
|
|
84
|
+
new_result = dict(result)
|
|
85
|
+
new_result["content"] = new_content
|
|
86
|
+
new_resp["result"] = new_result
|
|
87
|
+
return new_resp
|
|
88
|
+
|
|
89
|
+
return resp
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def run_proxy(target_cmd: List[str]):
|
|
93
|
+
"""Runs the stdio proxy bridging sys.stdin/stdout with target_cmd."""
|
|
94
|
+
if not target_cmd:
|
|
95
|
+
sys.stderr.write("TokenSafe MCP Proxy Error: No target command specified.\n")
|
|
96
|
+
sys.exit(1)
|
|
97
|
+
|
|
98
|
+
try:
|
|
99
|
+
proc = subprocess.Popen(
|
|
100
|
+
target_cmd,
|
|
101
|
+
stdin=subprocess.PIPE,
|
|
102
|
+
stdout=subprocess.PIPE,
|
|
103
|
+
stderr=sys.stderr,
|
|
104
|
+
bufsize=0,
|
|
105
|
+
)
|
|
106
|
+
except Exception as e:
|
|
107
|
+
sys.stderr.write(f"TokenSafe MCP Proxy Error: Failed to spawn {' '.join(target_cmd)}: {e}\n")
|
|
108
|
+
sys.exit(1)
|
|
109
|
+
|
|
110
|
+
def _forward_stdin():
|
|
111
|
+
try:
|
|
112
|
+
while True:
|
|
113
|
+
line = sys.stdin.readline()
|
|
114
|
+
if not line:
|
|
115
|
+
break
|
|
116
|
+
if proc.stdin and not proc.stdin.closed:
|
|
117
|
+
proc.stdin.write(line.encode("utf-8"))
|
|
118
|
+
proc.stdin.flush()
|
|
119
|
+
except Exception:
|
|
120
|
+
pass
|
|
121
|
+
finally:
|
|
122
|
+
if proc.stdin and not proc.stdin.closed:
|
|
123
|
+
try:
|
|
124
|
+
proc.stdin.close()
|
|
125
|
+
except Exception:
|
|
126
|
+
pass
|
|
127
|
+
|
|
128
|
+
t_in = threading.Thread(target=_forward_stdin, daemon=True)
|
|
129
|
+
t_in.start()
|
|
130
|
+
|
|
131
|
+
try:
|
|
132
|
+
while True:
|
|
133
|
+
line_bytes = proc.stdout.readline()
|
|
134
|
+
if not line_bytes:
|
|
135
|
+
break
|
|
136
|
+
line_str = line_bytes.decode("utf-8", errors="replace").strip()
|
|
137
|
+
if not line_str:
|
|
138
|
+
continue
|
|
139
|
+
|
|
140
|
+
# Parse JSON-RPC line
|
|
141
|
+
try:
|
|
142
|
+
msg = json.loads(line_str)
|
|
143
|
+
compacted = compact_mcp_response(msg)
|
|
144
|
+
out_line = json.dumps(compacted, ensure_ascii=False) + "\n"
|
|
145
|
+
except Exception:
|
|
146
|
+
out_line = line_str + "\n"
|
|
147
|
+
|
|
148
|
+
sys.stdout.write(out_line)
|
|
149
|
+
sys.stdout.flush()
|
|
150
|
+
except Exception:
|
|
151
|
+
pass
|
|
152
|
+
finally:
|
|
153
|
+
proc.wait()
|
|
154
|
+
sys.exit(proc.returncode or 0)
|
package/src/mcp_server.py
CHANGED
|
@@ -42,7 +42,7 @@ from src.paths import get_active_workspace, is_plugin_or_system_dir
|
|
|
42
42
|
|
|
43
43
|
SERVER_INFO = {
|
|
44
44
|
"name": "tokensafe-mcp",
|
|
45
|
-
"version": "
|
|
45
|
+
"version": "4.0.0"
|
|
46
46
|
}
|
|
47
47
|
|
|
48
48
|
# MCP client attribution: the initialize handshake carries clientInfo, which
|
|
@@ -276,6 +276,68 @@ TOOLS = [
|
|
|
276
276
|
},
|
|
277
277
|
"required": ["query"]
|
|
278
278
|
}
|
|
279
|
+
},
|
|
280
|
+
{
|
|
281
|
+
"name": "expand_ref",
|
|
282
|
+
"description": "Expands a previously folded or stashed tool, command, file, or MCP result by its 8-character hex hash anchor (e.g. 'a1b2c3d4' or '#a1b2c3d4'). Returns the full original text that TokenSafe folded.",
|
|
283
|
+
"inputSchema": {
|
|
284
|
+
"type": "object",
|
|
285
|
+
"properties": {
|
|
286
|
+
"hash": {
|
|
287
|
+
"type": "string",
|
|
288
|
+
"description": "8-character hex hash from the fold marker (e.g. 'a1b2c3d4' or '#a1b2c3d4')"
|
|
289
|
+
}
|
|
290
|
+
},
|
|
291
|
+
"required": ["hash"]
|
|
292
|
+
}
|
|
293
|
+
},
|
|
294
|
+
{
|
|
295
|
+
"name": "read_web_page",
|
|
296
|
+
"description": "Fetches a web page URL and converts it to clean, readable Markdown, stripping scripts, styles, navbars, and ads (-80-95% tokens compared to raw HTML).",
|
|
297
|
+
"inputSchema": {
|
|
298
|
+
"type": "object",
|
|
299
|
+
"properties": {
|
|
300
|
+
"url": {
|
|
301
|
+
"type": "string",
|
|
302
|
+
"description": "Web URL to fetch and convert to Markdown"
|
|
303
|
+
}
|
|
304
|
+
},
|
|
305
|
+
"required": ["url"]
|
|
306
|
+
}
|
|
307
|
+
},
|
|
308
|
+
{
|
|
309
|
+
"name": "optimize_image",
|
|
310
|
+
"description": "Downscales oversized screenshots/diagrams before passing them to LLM vision endpoints. Resizes images exceeding max_edge (default: 1024px) while preserving aspect ratio and crispness, keeping the original image intact on disk (-50-75% vision tokens).",
|
|
311
|
+
"inputSchema": {
|
|
312
|
+
"type": "object",
|
|
313
|
+
"properties": {
|
|
314
|
+
"image_path": {"type": "string", "description": "Absolute or relative path to the image file"},
|
|
315
|
+
"max_edge": {"type": "integer", "description": "Maximum width/height in pixels (default: 1024)"}
|
|
316
|
+
},
|
|
317
|
+
"required": ["image_path"]
|
|
318
|
+
}
|
|
319
|
+
},
|
|
320
|
+
{
|
|
321
|
+
"name": "prune_superseded",
|
|
322
|
+
"description": "Prunes obsolete intermediate tool read outputs in long conversation transcripts that have since been modified by subsequent edits or re-read in later steps (-30-40% context mass).",
|
|
323
|
+
"inputSchema": {
|
|
324
|
+
"type": "object",
|
|
325
|
+
"properties": {
|
|
326
|
+
"transcript_path": {"type": "string", "description": "Path to the JSONL conversation transcript to prune"}
|
|
327
|
+
},
|
|
328
|
+
"required": ["transcript_path"]
|
|
329
|
+
}
|
|
330
|
+
},
|
|
331
|
+
{
|
|
332
|
+
"name": "get_mistakes",
|
|
333
|
+
"description": "Returns known dead-ends, failed hypotheses, and reverted code changes for this project to prevent repeating unsuccessful approaches.",
|
|
334
|
+
"inputSchema": {
|
|
335
|
+
"type": "object",
|
|
336
|
+
"properties": {
|
|
337
|
+
"project_root": {"type": "string", "description": "Optional project root directory (defaults to current project)"},
|
|
338
|
+
"clear": {"type": "boolean", "description": "If true, clears the mistakes ledger"}
|
|
339
|
+
}
|
|
340
|
+
}
|
|
279
341
|
}
|
|
280
342
|
]
|
|
281
343
|
|
|
@@ -765,6 +827,59 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
|
|
|
765
827
|
if _is_binary_file(path):
|
|
766
828
|
return _fallback_error("smart_read_file", f"'{os.path.basename(path)}' appears to be a binary file")
|
|
767
829
|
|
|
830
|
+
# Bloated lockfiles (package-lock.json, Cargo.lock, poetry.lock, pnpm-lock.yaml):
|
|
831
|
+
# Extract compact dependency bill with reversible hash anchor instead of a 30k token dump.
|
|
832
|
+
from src.format_parsers.lockfiles import LockfileReducer
|
|
833
|
+
if LockfileReducer.is_lockfile(path):
|
|
834
|
+
try:
|
|
835
|
+
with open(path, "r", encoding="utf-8", errors="replace") as f:
|
|
836
|
+
raw_lock_text = f.read()
|
|
837
|
+
reduced_lock, was_reduced = LockfileReducer.reduce(raw_lock_text, os.path.basename(path))
|
|
838
|
+
if was_reduced:
|
|
839
|
+
orig_t = count_tokens(raw_lock_text)
|
|
840
|
+
opt_t = count_tokens(reduced_lock)
|
|
841
|
+
tracker.record_event(
|
|
842
|
+
session_id=_mcp_session_id(),
|
|
843
|
+
event_type="LOCKFILE_REDUCE",
|
|
844
|
+
original_tokens=orig_t,
|
|
845
|
+
optimized_tokens=opt_t,
|
|
846
|
+
details={"file": os.path.basename(path), "saved": orig_t - opt_t}
|
|
847
|
+
)
|
|
848
|
+
return {"content": [{"type": "text", "text": reduced_lock}]}
|
|
849
|
+
except Exception:
|
|
850
|
+
pass
|
|
851
|
+
|
|
852
|
+
# Tabular and database dump files (CSV, TSV, SQL, HAR):
|
|
853
|
+
# Extract schema, data types, and sample rows instead of dumping 10k rows into context.
|
|
854
|
+
from src.format_parsers.tabular import TabularReducer
|
|
855
|
+
if TabularReducer.is_tabular_or_dump(path):
|
|
856
|
+
try:
|
|
857
|
+
with open(path, "r", encoding="utf-8", errors="replace") as f:
|
|
858
|
+
raw_data_text = f.read()
|
|
859
|
+
ext_lower = os.path.splitext(path)[1].lower()
|
|
860
|
+
if ext_lower in (".csv", ".tsv"):
|
|
861
|
+
reduced_tab, was_reduced = TabularReducer.reduce_csv(raw_data_text)
|
|
862
|
+
elif ext_lower == ".sql":
|
|
863
|
+
reduced_tab, was_reduced = TabularReducer.reduce_sql_dump(raw_data_text)
|
|
864
|
+
elif ext_lower == ".har":
|
|
865
|
+
reduced_tab, was_reduced = TabularReducer.reduce_har(raw_data_text)
|
|
866
|
+
else:
|
|
867
|
+
reduced_tab, was_reduced = raw_data_text, False
|
|
868
|
+
|
|
869
|
+
if was_reduced:
|
|
870
|
+
orig_t = count_tokens(raw_data_text)
|
|
871
|
+
opt_t = count_tokens(reduced_tab)
|
|
872
|
+
tracker.record_event(
|
|
873
|
+
session_id=_mcp_session_id(),
|
|
874
|
+
event_type="TABULAR_REDUCE",
|
|
875
|
+
original_tokens=orig_t,
|
|
876
|
+
optimized_tokens=opt_t,
|
|
877
|
+
details={"file": os.path.basename(path), "saved": orig_t - opt_t}
|
|
878
|
+
)
|
|
879
|
+
return {"content": [{"type": "text", "text": reduced_tab}]}
|
|
880
|
+
except Exception:
|
|
881
|
+
pass
|
|
882
|
+
|
|
768
883
|
# Heavy declarative schema files (OpenAPI/Swagger/Prisma/GraphQL/SQL DDL):
|
|
769
884
|
# generic AST skeletonization does not apply — route to the schema slicer.
|
|
770
885
|
# `symbol` carries the target (a spec path, model, type or table); an empty
|
|
@@ -1562,6 +1677,105 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
|
|
|
1562
1677
|
)
|
|
1563
1678
|
return {"content": [{"type": "text", "text": md_text}]}
|
|
1564
1679
|
|
|
1680
|
+
elif name == "expand_ref":
|
|
1681
|
+
raw_hash = args.get("hash") or args.get("ref") or args.get("id") or ""
|
|
1682
|
+
if not raw_hash:
|
|
1683
|
+
return _fallback_error("expand_ref", "missing required 'hash' argument")
|
|
1684
|
+
try:
|
|
1685
|
+
from src.stash import retrieve_block
|
|
1686
|
+
content = retrieve_block(str(raw_hash))
|
|
1687
|
+
if content is None:
|
|
1688
|
+
return {
|
|
1689
|
+
"isError": True,
|
|
1690
|
+
"content": [{"type": "text", "text": f"Error: Stashed reference '{raw_hash}' not found or expired (retention is 7 days)."}]
|
|
1691
|
+
}
|
|
1692
|
+
return {"content": [{"type": "text", "text": content}]}
|
|
1693
|
+
except Exception as e:
|
|
1694
|
+
return _fallback_error("expand_ref", f"cannot retrieve stashed ref: {e}")
|
|
1695
|
+
|
|
1696
|
+
elif name == "read_web_page":
|
|
1697
|
+
target_url = str(args.get("url") or args.get("link") or "").strip()
|
|
1698
|
+
if not target_url:
|
|
1699
|
+
return _fallback_error("read_web_page", "missing required 'url' argument")
|
|
1700
|
+
try:
|
|
1701
|
+
from src.web_reader import WebReader
|
|
1702
|
+
content, ok, err = WebReader.fetch_url(target_url)
|
|
1703
|
+
if not ok:
|
|
1704
|
+
return _fallback_error("read_web_page", err or "failed to fetch web page")
|
|
1705
|
+
orig_t = max(1000, len(content) // 2)
|
|
1706
|
+
opt_t = count_tokens(content)
|
|
1707
|
+
tracker.record_event(
|
|
1708
|
+
session_id=_mcp_session_id(),
|
|
1709
|
+
event_type="WEB_READ",
|
|
1710
|
+
original_tokens=orig_t,
|
|
1711
|
+
optimized_tokens=opt_t,
|
|
1712
|
+
details={"url": target_url[:80], "saved": max(0, orig_t - opt_t)}
|
|
1713
|
+
)
|
|
1714
|
+
return {"content": [{"type": "text", "text": content}]}
|
|
1715
|
+
except Exception as e:
|
|
1716
|
+
return _fallback_error("read_web_page", f"error reading web page: {e}")
|
|
1717
|
+
|
|
1718
|
+
elif name == "optimize_image":
|
|
1719
|
+
img_path = str(args.get("image_path") or args.get("path") or "").strip()
|
|
1720
|
+
if not img_path:
|
|
1721
|
+
return _fallback_error("optimize_image", "missing required 'image_path' argument")
|
|
1722
|
+
try:
|
|
1723
|
+
max_edge = _safe_int(args.get("max_edge"), 1024, lo=256, hi=4096)
|
|
1724
|
+
from src.image_downscale import ImageDownscaler
|
|
1725
|
+
res = ImageDownscaler.optimize(img_path, max_edge=max_edge)
|
|
1726
|
+
if not res.get("success"):
|
|
1727
|
+
return _fallback_error("optimize_image", res.get("error", "optimization failed"))
|
|
1728
|
+
if res.get("was_downscaled"):
|
|
1729
|
+
tracker.record_event(
|
|
1730
|
+
session_id=_mcp_session_id(),
|
|
1731
|
+
event_type="IMAGE_OPTIMIZATION",
|
|
1732
|
+
original_tokens=res.get("orig_tokens", 1000),
|
|
1733
|
+
optimized_tokens=res.get("new_tokens", 500),
|
|
1734
|
+
details={"path": os.path.basename(img_path), "saved": res.get("saved_tokens", 0)}
|
|
1735
|
+
)
|
|
1736
|
+
return {"content": [{"type": "text", "text": json.dumps(res, indent=2, ensure_ascii=False)}]}
|
|
1737
|
+
except Exception as e:
|
|
1738
|
+
return _fallback_error("optimize_image", f"error optimizing image: {e}")
|
|
1739
|
+
|
|
1740
|
+
elif name == "prune_superseded":
|
|
1741
|
+
t_path = str(args.get("transcript_path") or "").strip()
|
|
1742
|
+
if not t_path:
|
|
1743
|
+
return _fallback_error("prune_superseded", "missing required 'transcript_path' argument")
|
|
1744
|
+
try:
|
|
1745
|
+
from src.superseded import SupersededPruner
|
|
1746
|
+
res = SupersededPruner.prune_transcript(t_path)
|
|
1747
|
+
if not res.get("success"):
|
|
1748
|
+
return _fallback_error("prune_superseded", res.get("error", "pruning failed"))
|
|
1749
|
+
if res.get("saved_tokens", 0) > 0:
|
|
1750
|
+
tracker.record_event(
|
|
1751
|
+
session_id=_mcp_session_id(),
|
|
1752
|
+
event_type="SUPERSEDED_PRUNE",
|
|
1753
|
+
original_tokens=res.get("orig_tokens", 0),
|
|
1754
|
+
optimized_tokens=res.get("pruned_tokens", 0),
|
|
1755
|
+
details={"pruned_count": res.get("pruned_count", 0), "saved": res.get("saved_tokens", 0)}
|
|
1756
|
+
)
|
|
1757
|
+
return {"content": [{"type": "text", "text": json.dumps(res, indent=2, ensure_ascii=False)}]}
|
|
1758
|
+
except Exception as e:
|
|
1759
|
+
return _fallback_error("prune_superseded", f"error pruning transcript: {e}")
|
|
1760
|
+
|
|
1761
|
+
elif name == "get_mistakes":
|
|
1762
|
+
proj_root = str(args.get("project_root") or "").strip() or None
|
|
1763
|
+
if args.get("clear"):
|
|
1764
|
+
from src.mistakes import MistakesLedger
|
|
1765
|
+
cleared = MistakesLedger.clear_mistakes(project_root=proj_root)
|
|
1766
|
+
return {"content": [{"type": "text", "text": json.dumps({"cleared": cleared}, indent=2)}]}
|
|
1767
|
+
try:
|
|
1768
|
+
from src.mistakes import MistakesLedger
|
|
1769
|
+
entries = MistakesLedger.list_mistakes(project_root=proj_root)
|
|
1770
|
+
guard = MistakesLedger.get_guard_prompt(project_root=proj_root)
|
|
1771
|
+
return {"content": [{"type": "text", "text": json.dumps({
|
|
1772
|
+
"count": len(entries),
|
|
1773
|
+
"entries": entries,
|
|
1774
|
+
"active_guard": guard
|
|
1775
|
+
}, indent=2, ensure_ascii=False)}]}
|
|
1776
|
+
except Exception as e:
|
|
1777
|
+
return _fallback_error("get_mistakes", f"error reading mistakes ledger: {e}")
|
|
1778
|
+
|
|
1565
1779
|
return _fallback_error(name, f"unknown tool '{name}'")
|
|
1566
1780
|
|
|
1567
1781
|
|
package/src/mistakes.py
ADDED
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
"""
|
|
2
|
+
TokenSafe Persistent Revert & Failure Memory (Mistakes Ledger) (v3.3.0).
|
|
3
|
+
|
|
4
|
+
Prevents AI coding agents from repeating known dead-ends, failed hypotheses,
|
|
5
|
+
and reverted code patterns across turns and sessions.
|
|
6
|
+
|
|
7
|
+
Synergizes directly with:
|
|
8
|
+
1. `LoopDetector`: Captures repetitive tool-execution loops and converts them to persistent memory.
|
|
9
|
+
2. Git Rollback Tracking: Detects git reverts/checkouts and logs the abandoned direction.
|
|
10
|
+
3. Anti-Stuck Prompt Guard: Injects a compact (<80 tokens) warning into context before execution.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
import os
|
|
14
|
+
import json
|
|
15
|
+
import time
|
|
16
|
+
import hashlib
|
|
17
|
+
import subprocess
|
|
18
|
+
from typing import Dict, Any, List, Optional
|
|
19
|
+
from src.paths import resolve_data_dir
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _find_project_mistakes_file(project_root: Optional[str] = None) -> str:
|
|
23
|
+
"""Finds or creates .tokensafe/mistakes.jsonl in project or user data dir."""
|
|
24
|
+
if project_root and os.path.isdir(project_root):
|
|
25
|
+
proj_dir = os.path.join(project_root, ".tokensafe")
|
|
26
|
+
try:
|
|
27
|
+
os.makedirs(proj_dir, exist_ok=True)
|
|
28
|
+
return os.path.join(proj_dir, "mistakes.jsonl")
|
|
29
|
+
except Exception:
|
|
30
|
+
pass
|
|
31
|
+
# Fallback to global data dir
|
|
32
|
+
global_dir = resolve_data_dir()
|
|
33
|
+
os.makedirs(global_dir, exist_ok=True)
|
|
34
|
+
return os.path.join(global_dir, "mistakes.jsonl")
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class MistakesLedger:
|
|
38
|
+
"""Persistent ledger of failed hypotheses and reverted code patterns."""
|
|
39
|
+
|
|
40
|
+
MAX_ENTRIES = 50
|
|
41
|
+
|
|
42
|
+
@classmethod
|
|
43
|
+
def record_failure(
|
|
44
|
+
cls,
|
|
45
|
+
summary: str,
|
|
46
|
+
file_path: Optional[str] = None,
|
|
47
|
+
source: str = "loop_guard",
|
|
48
|
+
details: Optional[str] = None,
|
|
49
|
+
project_root: Optional[str] = None
|
|
50
|
+
) -> Dict[str, Any]:
|
|
51
|
+
"""
|
|
52
|
+
Records a failed attempt or dead-end in the persistent ledger.
|
|
53
|
+
"""
|
|
54
|
+
ledger_path = _find_project_mistakes_file(project_root)
|
|
55
|
+
f_basename = os.path.basename(file_path) if file_path else ""
|
|
56
|
+
|
|
57
|
+
entry = {
|
|
58
|
+
"id": hashlib.sha256(f"{f_basename}:{summary}:{time.time()}".encode("utf-8")).hexdigest()[:12],
|
|
59
|
+
"timestamp": time.time(),
|
|
60
|
+
"source": source,
|
|
61
|
+
"file": f_basename,
|
|
62
|
+
"file_full": file_path or "",
|
|
63
|
+
"summary": summary.strip()[:200],
|
|
64
|
+
"details": (details or "").strip()[:500],
|
|
65
|
+
"active": True
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
entries = cls.list_mistakes(project_root=project_root, active_only=False)
|
|
69
|
+
|
|
70
|
+
# Deduplicate identical summary + file
|
|
71
|
+
filtered = [
|
|
72
|
+
e for e in entries
|
|
73
|
+
if not (e.get("file") == entry["file"] and e.get("summary") == entry["summary"])
|
|
74
|
+
]
|
|
75
|
+
filtered.append(entry)
|
|
76
|
+
|
|
77
|
+
# Cap to MAX_ENTRIES
|
|
78
|
+
if len(filtered) > cls.MAX_ENTRIES:
|
|
79
|
+
filtered = filtered[-cls.MAX_ENTRIES:]
|
|
80
|
+
|
|
81
|
+
tmp_path = f"{ledger_path}.tmp.{os.getpid()}"
|
|
82
|
+
try:
|
|
83
|
+
with open(tmp_path, "w", encoding="utf-8") as f:
|
|
84
|
+
for e in filtered:
|
|
85
|
+
f.write(json.dumps(e, ensure_ascii=False) + "\n")
|
|
86
|
+
os.replace(tmp_path, ledger_path)
|
|
87
|
+
except Exception:
|
|
88
|
+
try:
|
|
89
|
+
if os.path.exists(tmp_path):
|
|
90
|
+
os.unlink(tmp_path)
|
|
91
|
+
except OSError:
|
|
92
|
+
pass
|
|
93
|
+
|
|
94
|
+
return entry
|
|
95
|
+
|
|
96
|
+
@classmethod
|
|
97
|
+
def record_from_loop(
|
|
98
|
+
cls,
|
|
99
|
+
tool_name: str,
|
|
100
|
+
args: Dict[str, Any],
|
|
101
|
+
repeats: int,
|
|
102
|
+
project_root: Optional[str] = None
|
|
103
|
+
) -> Dict[str, Any]:
|
|
104
|
+
"""
|
|
105
|
+
Anti-stuck synergy: converts a tripped LoopDetector event into a persistent mistake record.
|
|
106
|
+
"""
|
|
107
|
+
target = args.get("Path") or args.get("path") or args.get("CommandLine") or args.get("command") or ""
|
|
108
|
+
target_str = str(target)
|
|
109
|
+
if len(target_str) > 80:
|
|
110
|
+
target_str = target_str[:80] + "..."
|
|
111
|
+
|
|
112
|
+
summary = f"Tool '{tool_name}' stuck in {repeats}x loop with target: {target_str}"
|
|
113
|
+
fpath = args.get("Path") or args.get("path")
|
|
114
|
+
return cls.record_failure(
|
|
115
|
+
summary=summary,
|
|
116
|
+
file_path=str(fpath) if fpath else None,
|
|
117
|
+
source="loop_detector",
|
|
118
|
+
details=f"Identical parameters executed {repeats} times in a row without progress.",
|
|
119
|
+
project_root=project_root
|
|
120
|
+
)
|
|
121
|
+
|
|
122
|
+
@classmethod
|
|
123
|
+
def record_revert(
|
|
124
|
+
cls,
|
|
125
|
+
file_path: str,
|
|
126
|
+
reason: str,
|
|
127
|
+
project_root: Optional[str] = None
|
|
128
|
+
) -> Dict[str, Any]:
|
|
129
|
+
"""
|
|
130
|
+
Records a reverted code change or git rollback.
|
|
131
|
+
"""
|
|
132
|
+
summary = f"Reverted change: {reason.strip()}"
|
|
133
|
+
return cls.record_failure(
|
|
134
|
+
summary=summary,
|
|
135
|
+
file_path=file_path,
|
|
136
|
+
source="git_revert",
|
|
137
|
+
project_root=project_root
|
|
138
|
+
)
|
|
139
|
+
|
|
140
|
+
@classmethod
|
|
141
|
+
def list_mistakes(
|
|
142
|
+
cls,
|
|
143
|
+
project_root: Optional[str] = None,
|
|
144
|
+
active_only: bool = True
|
|
145
|
+
) -> List[Dict[str, Any]]:
|
|
146
|
+
"""Loads all recorded mistakes from the ledger."""
|
|
147
|
+
ledger_path = _find_project_mistakes_file(project_root)
|
|
148
|
+
if not os.path.exists(ledger_path):
|
|
149
|
+
return []
|
|
150
|
+
|
|
151
|
+
entries = []
|
|
152
|
+
try:
|
|
153
|
+
with open(ledger_path, "r", encoding="utf-8", errors="replace") as f:
|
|
154
|
+
for line in f:
|
|
155
|
+
line = line.strip()
|
|
156
|
+
if line:
|
|
157
|
+
try:
|
|
158
|
+
item = json.loads(line)
|
|
159
|
+
if not active_only or item.get("active", True):
|
|
160
|
+
entries.append(item)
|
|
161
|
+
except Exception:
|
|
162
|
+
pass
|
|
163
|
+
except Exception:
|
|
164
|
+
return []
|
|
165
|
+
|
|
166
|
+
return entries
|
|
167
|
+
|
|
168
|
+
@classmethod
|
|
169
|
+
def clear_mistakes(cls, project_root: Optional[str] = None) -> int:
|
|
170
|
+
"""Clears all entries from the mistakes ledger."""
|
|
171
|
+
ledger_path = _find_project_mistakes_file(project_root)
|
|
172
|
+
if os.path.exists(ledger_path):
|
|
173
|
+
try:
|
|
174
|
+
entries = cls.list_mistakes(project_root=project_root, active_only=False)
|
|
175
|
+
os.remove(ledger_path)
|
|
176
|
+
return len(entries)
|
|
177
|
+
except Exception:
|
|
178
|
+
pass
|
|
179
|
+
return 0
|
|
180
|
+
|
|
181
|
+
@classmethod
|
|
182
|
+
def get_guard_prompt(
|
|
183
|
+
cls,
|
|
184
|
+
project_root: Optional[str] = None,
|
|
185
|
+
max_items: int = 3
|
|
186
|
+
) -> Optional[str]:
|
|
187
|
+
"""
|
|
188
|
+
Generates a compact (<80 tokens) prompt guard from recent active mistakes.
|
|
189
|
+
Injectable into system instructions or PreInvocation hooks.
|
|
190
|
+
"""
|
|
191
|
+
mistakes = cls.list_mistakes(project_root=project_root, active_only=True)
|
|
192
|
+
if not mistakes:
|
|
193
|
+
return None
|
|
194
|
+
|
|
195
|
+
# Take the most recent active entries
|
|
196
|
+
recent = mistakes[-max_items:]
|
|
197
|
+
lines = ["[TokenSafe Anti-Stuck Guard: Prior Dead-Ends to Avoid in this Project]:"]
|
|
198
|
+
for m in reversed(recent):
|
|
199
|
+
f = m.get("file")
|
|
200
|
+
f_prefix = f"{f}: " if f else ""
|
|
201
|
+
lines.append(f"• {f_prefix}{m.get('summary', '')}")
|
|
202
|
+
|
|
203
|
+
return "\n".join(lines)
|
package/src/result_ledger.py
CHANGED
|
@@ -114,6 +114,13 @@ def _compact_read_result(text: str, path: str) -> Optional[str]:
|
|
|
114
114
|
|
|
115
115
|
def _compact_command_result(text: str) -> Optional[str]:
|
|
116
116
|
"""Test summaries first (PASS: ...), log-style head/tail otherwise."""
|
|
117
|
+
try:
|
|
118
|
+
from src.test_parsers import TestOutputParser
|
|
119
|
+
compacted, was_test = TestOutputParser.compact(text)
|
|
120
|
+
if was_test:
|
|
121
|
+
return compacted
|
|
122
|
+
except Exception:
|
|
123
|
+
pass
|
|
117
124
|
try:
|
|
118
125
|
from src.command_sanitizer import CommandSanitizer
|
|
119
126
|
compacted = CommandSanitizer.compact_test_output(text, 0)
|
|
@@ -183,7 +190,7 @@ def _fold_anchor(tool_name: str, preview: str, orig_tokens: int, new_tokens: int
|
|
|
183
190
|
return (
|
|
184
191
|
f"{FOLD_MARKER} {tool_name} ({preview}) result consumed earlier — folded "
|
|
185
192
|
f"~{orig_tokens}→{new_tokens} tokens (sha256:{sha[:8]}).{archive_note} "
|
|
186
|
-
f"To re-inspect: re-run {tool_name}, or use smart_read_file(force_full=true)
|
|
193
|
+
f"To re-inspect: call tokensafe:expand_ref('{sha[:8]}'), re-run {tool_name}, or use smart_read_file(force_full=true).]"
|
|
187
194
|
)
|
|
188
195
|
|
|
189
196
|
|
package/src/scoped_search.py
CHANGED
|
@@ -165,6 +165,38 @@ class ScopedSearch:
|
|
|
165
165
|
"markdown": f"Regex compilation error: {str(e)}"
|
|
166
166
|
}
|
|
167
167
|
|
|
168
|
+
# Fast-path: SQLite FTS5 trigram BM25 search for plain identifier queries
|
|
169
|
+
if not regex_mode and len(query) >= 3 and not any(c in query for c in "*?[]{}()^$+\\|"):
|
|
170
|
+
try:
|
|
171
|
+
from src.fts_index import CodeFTSIndex
|
|
172
|
+
fts = CodeFTSIndex(root_dir)
|
|
173
|
+
fts_results = fts.search(query, limit=max_results)
|
|
174
|
+
if fts_results:
|
|
175
|
+
fts_matches = []
|
|
176
|
+
fts_hit_files = set()
|
|
177
|
+
for r in fts_results:
|
|
178
|
+
f_rel = r["file"]
|
|
179
|
+
if cls.is_match_file(os.path.basename(f_rel), f_rel, scope):
|
|
180
|
+
fts_matches.append({
|
|
181
|
+
"file": f_rel,
|
|
182
|
+
"line": r["line"],
|
|
183
|
+
"content": r["content"]
|
|
184
|
+
})
|
|
185
|
+
fts_hit_files.add(f_rel)
|
|
186
|
+
if fts_matches:
|
|
187
|
+
return {
|
|
188
|
+
"success": True,
|
|
189
|
+
"query": query,
|
|
190
|
+
"scope": scope,
|
|
191
|
+
"total_scanned_files": len(fts_hit_files),
|
|
192
|
+
"total_matches": len(fts_matches),
|
|
193
|
+
"timed_out": False,
|
|
194
|
+
"matches": fts_matches,
|
|
195
|
+
"markdown": cls._render_markdown(query, fts_matches, len(fts_hit_files), False, max_results)
|
|
196
|
+
}
|
|
197
|
+
except Exception:
|
|
198
|
+
pass # Seamless fallback to disk scan
|
|
199
|
+
|
|
168
200
|
matches: List[Dict[str, Any]] = []
|
|
169
201
|
total_scanned_files = 0
|
|
170
202
|
hit_files = set()
|