tokensafe 4.1.5 → 4.1.7
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 +4 -4
- package/hooks/claude_code_hook.py +2 -2
- package/hooks/session_start.py +2 -1
- package/package.json +2 -2
- package/plugin.json +1 -1
- package/rules/AGENTS.md +1 -1
- package/server.json +3 -3
- package/skills/token-optimizer/SKILL.md +4 -3
- package/skills/token-optimizer/references/cli-reference.md +1 -1
- package/skills/token-optimizer/references/mcp-tools.md +1 -1
- package/src/adapter_core.py +1 -1
- package/src/build_parsers.py +10 -0
- package/src/cli.py +21 -0
- package/src/command_sanitizer.py +135 -10
- package/src/fts_index.py +25 -6
- package/src/installer.py +8 -1
- package/src/mcp_server.py +62 -17
- package/src/mistakes.py +2 -1
- package/src/paths.py +44 -0
- package/src/result_ledger.py +23 -1
- package/src/telemetry_sync.py +1 -1
- package/src/test_parsers.py +110 -2
- package/src/version_checker.py +1 -1
package/README.md
CHANGED
|
@@ -6,9 +6,9 @@
|
|
|
6
6
|
<!-- mcp-name: dev.tokensafe/tokensafe -->
|
|
7
7
|
|
|
8
8
|
<p align="center">
|
|
9
|
-
<b>
|
|
10
|
-
|
|
11
|
-
TokenSafe
|
|
9
|
+
<b>Your coding agent isn't getting dumber. Your context is just full of trash.</b><br>
|
|
10
|
+
When chat sessions fill up with massive lockfiles and endless build logs, your AI loses focus.<br>
|
|
11
|
+
TokenSafe strips the noise with Tree-sitter AST slicing so your agent stays razor-sharp, changes only the lines you asked for, and never leaks your secrets.<br>
|
|
12
12
|
Works with <b>Cursor, Claude Code, Codex, Windsurf, Google Antigravity, Gemini CLI, and ChatGPT</b>.
|
|
13
13
|
</p>
|
|
14
14
|
|
|
@@ -406,7 +406,7 @@ All hook adapters fail open: an internal error never stalls your agent. Failures
|
|
|
406
406
|
| `get_mistakes` | Anti-stuck persistent ledger: retrieves past dead-ends, loop guard trips, and git reverts to prevent repeating failed paths |
|
|
407
407
|
| `list_dir` | Clean directory tree without permissions, timestamps, or lockfiles |
|
|
408
408
|
| `slice_diff` | Unified diff slicing omitting lockfiles and minimizing context lines |
|
|
409
|
-
| `sanitize_command` | Per-stage shell command rewrites
|
|
409
|
+
| `sanitize_command` | Per-stage shell command rewrites (`git push` --no-progress, `git commit` hook wrapping, bun/python/jest test folding, lockfile exclusions, bounded logs) |
|
|
410
410
|
| `guard_inspect` | Pre-flight security and hygiene audit for commands or code snippets |
|
|
411
411
|
| `context_budget` | Context window usage estimate with thresholds and recommendations |
|
|
412
412
|
| `compress_prompt` | Compiles a verbose developer prompt into a compact S-expression |
|
|
@@ -231,8 +231,8 @@ def handle(event: str, payload: dict) -> dict:
|
|
|
231
231
|
return {
|
|
232
232
|
"decision": "block",
|
|
233
233
|
"reason": (
|
|
234
|
-
f"[TokenSafe] {tool}
|
|
235
|
-
f"({orig:,} → {new:,} chars).
|
|
234
|
+
f"[TokenSafe] {tool} output auto-compacted "
|
|
235
|
+
f"({orig:,} → {new:,} chars). Output summary:\n{compacted}"
|
|
236
236
|
),
|
|
237
237
|
}
|
|
238
238
|
return {}
|
package/hooks/session_start.py
CHANGED
|
@@ -61,8 +61,9 @@ def main():
|
|
|
61
61
|
workspace_paths = raw_ws if isinstance(raw_ws, list) else []
|
|
62
62
|
workspace_root = str(workspace_paths[0]) if workspace_paths else os.getcwd()
|
|
63
63
|
try:
|
|
64
|
-
from src.paths import save_active_workspace
|
|
64
|
+
from src.paths import save_active_workspace, ensure_tokensafe_gitignore
|
|
65
65
|
save_active_workspace(workspace_root)
|
|
66
|
+
ensure_tokensafe_gitignore(workspace_root)
|
|
66
67
|
except Exception:
|
|
67
68
|
pass
|
|
68
69
|
|
package/package.json
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tokensafe",
|
|
3
3
|
"mcpName": "dev.tokensafe/tokensafe",
|
|
4
|
-
"version": "4.1.
|
|
5
|
-
"description": "
|
|
4
|
+
"version": "4.1.7",
|
|
5
|
+
"description": "Your coding agent isn't getting dumber. Your context is just full of trash. Local context firewall & zero-loss runtime for Cursor, Claude Code, and autonomous agents.",
|
|
6
6
|
"main": "bin/tokensafe.js",
|
|
7
7
|
"bin": {
|
|
8
8
|
"tokensafe": "bin/tokensafe.js"
|
package/plugin.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tokensafe",
|
|
3
3
|
"displayName": "TokenSafe",
|
|
4
|
-
"version": "4.1.
|
|
4
|
+
"version": "4.1.7",
|
|
5
5
|
"description": "Reduce your AI bills by up to 99% locally. Your agents read only needed code, keep prompt caches intact across turns, and keep secrets out of git.",
|
|
6
6
|
"logo": "assets/logo.svg",
|
|
7
7
|
"author": {
|
package/rules/AGENTS.md
CHANGED
|
@@ -37,7 +37,7 @@ Execute the specified action directly based on these extracted parameters.
|
|
|
37
37
|
7. **Bounded Reads**: Never call `read_file` without `StartLine`/`EndLine` on files > 100 lines unless inspecting a skeleton.
|
|
38
38
|
8. **Directory Navigation**: Never run verbose `ls -la` or `ls -l`; use `tokensafe:list_dir(path=".", depth=2)` to inspect directory trees without permissions, timestamps, or lockfiles (-90% tokens). Supports relative subfolders (`path="src"`).
|
|
39
39
|
9. **Style & Design Tokens**: When inspecting CSS/SCSS/LESS/Tailwind, `tokensafe:smart_read_file` automatically preserves all design tokens (`:root`, `@theme`, CSS variables) in full while folding component selectors.
|
|
40
|
-
10. **Command Output Wrapping & Test Execution**: Run noisy commands and test suites via `tokensafe wrap '<command>'` or `tokensafe tests [cmd]`. Passing tests return a 1-line summary (`✓ PASS: ...`), and failures return focused failure blocks with full tracebacks preserved in stash.
|
|
40
|
+
10. **Command Output Wrapping & Test Execution**: Run noisy commands, builds, and test suites (`bun test`, `pytest`, `python -m unittest`, `vitest`, `jest`, `cargo test`, `go test`) via `tokensafe wrap '<command>'` or `tokensafe tests [cmd]`. Sanitization automatically strips `git push` progress animation frames (`--no-progress`), wraps `git commit` when pre-commit/husky hooks exist, and forces test runners into run-once mode. Passing tests return a 1-line summary (`✓ PASS: ...`), and failures return focused failure blocks with full tracebacks preserved in stash.
|
|
41
41
|
11. **Context Budget & Smart Compaction**: Before large multi-step tasks, call `tokensafe:context_budget(model=...)` to check window usage and Context Quality Score (Grade S-F). When it reports `warning`, `critical`, or Grade C/F, call `tokensafe:compact_conversation(transcript_path=...)` to fold past turns into a Consolidated State Ledger with a 3-line Post-Compaction Orientation Digest (Active Goal, Last State, Next Focus) before continuing.
|
|
42
42
|
12. **Vision Image Optimization (`optimize_image`)**: When handling screenshots or visual diagrams, call `tokensafe:optimize_image` or run `tokensafe optimize-image <file>` to downscale images exceeding 1024px (-50-75% vision tokens) while preserving original disk files.
|
|
43
43
|
13. **Superseded Output Pruning (`prune_superseded`)**: In long multi-turn sessions, prune obsolete intermediate file reads via `tokensafe:prune_superseded(transcript_path)` to free up context without losing history.
|
package/server.json
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
"name": "dev.tokensafe/tokensafe",
|
|
4
4
|
"title": "TokenSafe",
|
|
5
5
|
"description": "Reduce your AI bills by up to 99% locally: focused code, warm prompt caches & zero secret leaks.",
|
|
6
|
-
"version": "4.1.
|
|
6
|
+
"version": "4.1.7",
|
|
7
7
|
"websiteUrl": "https://tokensafe.dev",
|
|
8
8
|
"repository": {
|
|
9
9
|
"url": "https://github.com/tokensafe-dev/tokensafe",
|
|
@@ -30,7 +30,7 @@
|
|
|
30
30
|
"registryType": "npm",
|
|
31
31
|
"registryBaseUrl": "https://registry.npmjs.org",
|
|
32
32
|
"identifier": "tokensafe",
|
|
33
|
-
"version": "4.1.
|
|
33
|
+
"version": "4.1.7",
|
|
34
34
|
"runtimeHint": "npx",
|
|
35
35
|
"transport": {
|
|
36
36
|
"type": "stdio"
|
|
@@ -46,7 +46,7 @@
|
|
|
46
46
|
"registryType": "pypi",
|
|
47
47
|
"registryBaseUrl": "https://pypi.org",
|
|
48
48
|
"identifier": "tokensafe",
|
|
49
|
-
"version": "4.1.
|
|
49
|
+
"version": "4.1.7",
|
|
50
50
|
"runtimeHint": "uvx",
|
|
51
51
|
"transport": {
|
|
52
52
|
"type": "stdio"
|
|
@@ -60,8 +60,9 @@ folds multi-turn conversation history, slices verbose tool outputs, and guards a
|
|
|
60
60
|
- Eliminate conversational preambles, courtesy fillers, and trailing sign-offs.
|
|
61
61
|
- Never reprint full unmodified files or lengthy boilerplate; cite line ranges and provide targeted diffs.
|
|
62
62
|
|
|
63
|
-
11. **COMPACT TEST EXECUTION**:
|
|
64
|
-
- Run unit tests with concise flags or via `tokensafe tests [cmd]`
|
|
63
|
+
11. **COMPACT TEST EXECUTION & PIPELINE SANITIZATION**:
|
|
64
|
+
- Run unit tests with concise flags or via `tokensafe wrap '<cmd>'` or `tokensafe tests [cmd]`. Native support for `bun test`, `pytest`, `python -m unittest`, `vitest`, `jest`, `cargo test`, and `go test` collapses passing test suites into a single-line summary (`✓ PASS: ...`) rather than flooding `Messages` history with hundreds of verbose log lines. Full traceback is strictly preserved on failure.
|
|
65
|
+
- Commands like `git push` automatically strip interactive object-counting progress spam (`--no-progress`), and `git commit` is wrapped when pre-commit/husky hooks exist.
|
|
65
66
|
|
|
66
67
|
---
|
|
67
68
|
|
|
@@ -82,7 +83,7 @@ Quick pointers:
|
|
|
82
83
|
- Bundle: `tokensafe:smart_bundle(targets=[{path, symbol}])` — 3-8 related symbols across files in one call, shared imports deduplicated.
|
|
83
84
|
- Navigate: `tokensafe:get_architecture_graph(project_path)` / `tokensafe:get_api_surface(project_path)`.
|
|
84
85
|
- Directory: `tokensafe:list_dir(path, depth=2)` — clean tree, never verbose `ls -la`.
|
|
85
|
-
- Terminal: `tokensafe:sanitize_command(command, cwd)` or run via `tokensafe wrap '<cmd>'
|
|
86
|
+
- Terminal: `tokensafe:sanitize_command(command, cwd)` or run via `tokensafe wrap '<cmd>'` — rewrites git push (--no-progress), wraps git commit hooks, and folds test suites (bun, python unittest/pytest, vitest, jest, cargo, go) to 1-line summaries.
|
|
86
87
|
- Context: `tokensafe:compact_conversation(transcript_path)` / `tokensafe:context_budget`.
|
|
87
88
|
- Vision: `tokensafe:optimize_image(image_path, max_edge=1024)` — downscale images >1024px (-50-75% vision tokens).
|
|
88
89
|
- Prune Reads: `tokensafe:prune_superseded(transcript_path)` — drops obsolete intermediate file reads (-30-40% context).
|
|
@@ -28,7 +28,7 @@ tokensafe guard "<command>" # Pre-flight check command safety (rm, secrets, gr
|
|
|
28
28
|
tokensafe guard audit [path] # Recursively audit project files for security violations
|
|
29
29
|
tokensafe doctor [--cleanup] # Audit MCP tool overhead, token tax & clean competitor conflicts
|
|
30
30
|
tokensafe expand-ref <hash> # Restore original raw content of any folded block by its 8-char hash
|
|
31
|
-
tokensafe wrap "<cmd>" # Run noisy command with compact output folding (e.g. tests, tsc, builds)
|
|
31
|
+
tokensafe wrap "<cmd>" # Run noisy command with compact output folding (e.g. bun/python/jest tests, git commit hooks, tsc, builds)
|
|
32
32
|
tokensafe web <url> # Fetch web page/docs and print clean compact Markdown
|
|
33
33
|
tokensafe optimize-image <img># Downscale oversized screenshot to max 1024px (-50-75% vision tokens)
|
|
34
34
|
tokensafe prune-superseded <t># Prune outdated intermediate reads from conversation transcript
|
|
@@ -12,7 +12,7 @@ All tools are exposed via Model Context Protocol (stdio JSON-RPC 2.0).
|
|
|
12
12
|
| `tokensafe:list_dir` | Token-efficient directory tree without lockfiles, timestamps, or ignored folders (node_modules, .git, dist, .env). Replaces `ls -la`. | **-90%** vs verbose `ls` |
|
|
13
13
|
| `tokensafe:get_architecture_graph` | Computes dependency topology, hub centrality, and identifies top God Nodes for `project_path`. | **~200 tokens** (replaces 50k crawl) |
|
|
14
14
|
| `tokensafe:get_api_surface` | Generates a compact markdown map of all exported types, interfaces, and classes. | **~500 tokens** for entire project |
|
|
15
|
-
| `tokensafe:sanitize_command` | Per-stage command rewrites: lockfile diffs, unbounded `git log`/`git show`/`git blame`/`rg`, docker/kubectl log caps, quiet npm/pip installs, bounded `cat`/`curl` output. Compound commands (`a && b ; c`) are optimized per stage
|
|
15
|
+
| `tokensafe:sanitize_command` | Per-stage command rewrites: lockfile diffs, unbounded `git log`/`git show`/`git blame`/`rg`, docker/kubectl log caps, quiet npm/pip installs, bounded `cat`/`curl` output, `git push` object-counting strip (`--no-progress`), and `git commit` hook wrapping. Compound commands (`a && b ; c`) are optimized per stage. Test commands (`bun test`, `pytest`, `python -m unittest`, `vitest`, `jest`) are wrapped or forced into run-once mode (`CI=true`, `--watch=false`, `--forceExit`) so passing suites emit a clean 1-line summary and agents never hang on watch mode. Pass optional `cwd` to identify runners behind opaque `yarn/npm test` scripts. | Saves **10k-50k tokens** per run |
|
|
16
16
|
| `tokensafe:slice_diff` | Slices unified git diffs, eliminating lockfiles and minimizing hunk context lines. | **-50% to -80%** diff size |
|
|
17
17
|
| `tokensafe:compress_prompt` | Compresses verbose user instructions into lean TOCP S-expressions via DeepSeek/Regex. | **-40% to -65%** prompt tokens |
|
|
18
18
|
| `tokensafe:compact_conversation` | On-demand context compaction: folds a long JSONL session transcript into a lean Consolidated State Ledger with a 3-line Post-Compaction Orientation Digest (`transcript_path`, optional `invocation_num`). Preserves flow instantly without post-compaction amnesia. | **-80% to -95%** history tokens |
|
package/src/adapter_core.py
CHANGED
|
@@ -79,7 +79,7 @@ _INFINITE_PATTERNS = [
|
|
|
79
79
|
r"\bdocker\s+attach\b",
|
|
80
80
|
# vitest runs an interactive watcher unless the `run` subcommand is given
|
|
81
81
|
r"\bvitest\b(?![^|;&]*\brun\b)",
|
|
82
|
-
r"\b(?:jest|vitest)\b[^|;&]*--watch\b",
|
|
82
|
+
r"\b(?:jest|vitest|bun)\b[^|;&]*--watch\b",
|
|
83
83
|
]
|
|
84
84
|
|
|
85
85
|
# Lockfiles/junk that must never be dumped into an agent context.
|
package/src/build_parsers.py
CHANGED
|
@@ -153,6 +153,16 @@ class BuildOutputParser:
|
|
|
153
153
|
error_lines.append(ln)
|
|
154
154
|
|
|
155
155
|
result = "\n".join(error_lines).strip()
|
|
156
|
+
# If the build failure contains TypeScript compiler error cascades (e.g. vue-tsc, vite build type error),
|
|
157
|
+
# compact using CompilerErrorCompactor to save massive token cascades.
|
|
158
|
+
try:
|
|
159
|
+
from src.format_parsers.compiler_errors import CompilerErrorCompactor
|
|
160
|
+
if CompilerErrorCompactor.is_tsc_output(result or cleaned):
|
|
161
|
+
compacted_tsc, was_tsc = CompilerErrorCompactor.compact_tsc(result or cleaned)
|
|
162
|
+
if was_tsc:
|
|
163
|
+
return compacted_tsc, True
|
|
164
|
+
except Exception:
|
|
165
|
+
pass
|
|
156
166
|
return result or cleaned.strip(), True
|
|
157
167
|
|
|
158
168
|
@classmethod
|
package/src/cli.py
CHANGED
|
@@ -1021,6 +1021,27 @@ def main(argv: Optional[List[str]] = None):
|
|
|
1021
1021
|
print(compacted_build)
|
|
1022
1022
|
sys.exit(proc.returncode)
|
|
1023
1023
|
|
|
1024
|
+
# Container build reducer (docker build, docker compose build)
|
|
1025
|
+
try:
|
|
1026
|
+
from src.format_parsers.docker_k8s import ContainerAndK8sReducer
|
|
1027
|
+
compacted_docker, was_docker = ContainerAndK8sReducer.reduce_docker_build(raw)
|
|
1028
|
+
if was_docker:
|
|
1029
|
+
print(compacted_docker)
|
|
1030
|
+
sys.exit(proc.returncode)
|
|
1031
|
+
except Exception:
|
|
1032
|
+
pass
|
|
1033
|
+
|
|
1034
|
+
# Structured NDJSON / JSON log reducer
|
|
1035
|
+
try:
|
|
1036
|
+
from src.format_parsers.json_log import JSONLogReducer
|
|
1037
|
+
if JSONLogReducer.is_ndjson_log(raw):
|
|
1038
|
+
compacted_logs, was_logs = JSONLogReducer.reduce(raw)
|
|
1039
|
+
if was_logs:
|
|
1040
|
+
print(compacted_logs)
|
|
1041
|
+
sys.exit(proc.returncode)
|
|
1042
|
+
except Exception:
|
|
1043
|
+
pass
|
|
1044
|
+
|
|
1024
1045
|
lines = raw.splitlines()
|
|
1025
1046
|
if len(lines) > 40:
|
|
1026
1047
|
head = lines[:15]
|
package/src/command_sanitizer.py
CHANGED
|
@@ -227,6 +227,42 @@ class CommandSanitizer:
|
|
|
227
227
|
cmd_tok = os.path.basename(tokens[idx])
|
|
228
228
|
return cmd_tok, tokens[idx + 1 :]
|
|
229
229
|
|
|
230
|
+
@classmethod
|
|
231
|
+
def _has_git_hooks(cls, cwd: Optional[str] = None) -> bool:
|
|
232
|
+
"""Checks if pre-commit hooks exist in cwd or git root."""
|
|
233
|
+
base = os.path.abspath(os.path.expanduser(cwd)) if cwd else os.getcwd()
|
|
234
|
+
cur = base
|
|
235
|
+
for _ in range(5):
|
|
236
|
+
if os.path.isfile(os.path.join(cur, ".husky", "pre-commit")):
|
|
237
|
+
return True
|
|
238
|
+
if os.path.isfile(os.path.join(cur, ".git", "hooks", "pre-commit")):
|
|
239
|
+
return True
|
|
240
|
+
if os.path.isfile(os.path.join(cur, ".pre-commit-config.yaml")):
|
|
241
|
+
return True
|
|
242
|
+
if os.path.isfile(os.path.join(cur, "lefthook.yml")):
|
|
243
|
+
return True
|
|
244
|
+
parent = os.path.dirname(cur)
|
|
245
|
+
if parent == cur:
|
|
246
|
+
break
|
|
247
|
+
cur = parent
|
|
248
|
+
return False
|
|
249
|
+
|
|
250
|
+
@classmethod
|
|
251
|
+
def _is_tokensafe_available(cls) -> bool:
|
|
252
|
+
"""Returns True if tokensafe executable is in PATH or known install locations."""
|
|
253
|
+
import shutil
|
|
254
|
+
if shutil.which("tokensafe"):
|
|
255
|
+
return True
|
|
256
|
+
for candidate in (
|
|
257
|
+
os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "bin", "tokensafe"),
|
|
258
|
+
os.path.expanduser("~/.tokensafe/bin/tokensafe"),
|
|
259
|
+
os.path.expanduser("~/.local/bin/tokensafe"),
|
|
260
|
+
"/usr/local/bin/tokensafe",
|
|
261
|
+
):
|
|
262
|
+
if os.path.exists(candidate):
|
|
263
|
+
return True
|
|
264
|
+
return False
|
|
265
|
+
|
|
230
266
|
@classmethod
|
|
231
267
|
def _optimize_stage(cls, stage: str, cwd: Optional[str] = None) -> Optional[Tuple[str, int, str, Optional[Tuple[str, int]]]]:
|
|
232
268
|
"""
|
|
@@ -303,11 +339,34 @@ class CommandSanitizer:
|
|
|
303
339
|
if "-L" not in sub_args and not any(a.startswith("-L") for a in sub_args):
|
|
304
340
|
return stage, 1500, "Capped git blame output", cls._CAP_LINES_200
|
|
305
341
|
|
|
342
|
+
# git push: eliminate interactive progress animation spam (Counting objects, Writing objects)
|
|
343
|
+
elif subcmd == "push":
|
|
344
|
+
if "--no-progress" not in sub_args and "-q" not in sub_args and "--quiet" not in sub_args:
|
|
345
|
+
new_stage = re.sub(r"\b(git(?:\s+-C\s+\S+)?\s+push)\b", r"\1 --no-progress", stage, count=1)
|
|
346
|
+
return new_stage, 800, "Added --no-progress to git push to eliminate object counting animation spam", None
|
|
347
|
+
|
|
348
|
+
# git commit: wrap with tokensafe wrap when hooks exist and message is provided
|
|
349
|
+
elif subcmd == "commit":
|
|
350
|
+
has_msg = any(
|
|
351
|
+
a in ("-m", "--message", "-F", "--file", "--no-edit")
|
|
352
|
+
or a.startswith(("-m=", "--message=", "-F=", "--file="))
|
|
353
|
+
for a in sub_args
|
|
354
|
+
)
|
|
355
|
+
if has_msg and cls._has_git_hooks(cwd) and cls._is_tokensafe_available() and not cls._TOKENSAFE_WRAP_RE.search(stage):
|
|
356
|
+
wrapped = f"tokensafe wrap {shlex.quote(stage)}"
|
|
357
|
+
return wrapped, 2500, "Wrapped git commit with tokensafe wrap to compact pre-commit hooks and test output", None
|
|
358
|
+
|
|
306
359
|
# pytest (or python -m pytest): compact quiet traceback
|
|
307
360
|
if cmd_tok == "pytest" or (cmd_tok.startswith("python") and "-m" in cmd_args and "pytest" in cmd_args):
|
|
308
361
|
if "--tb=" not in stage and "-q" not in cmd_args and "--quiet" not in cmd_args:
|
|
309
362
|
return f"{stage} -q --tb=short", 800, "Applied short traceback to pytest", None
|
|
310
363
|
|
|
364
|
+
# python -m unittest (or python3 -m unittest): wrap with tokensafe wrap to fold test noise
|
|
365
|
+
if cmd_tok.startswith("python") and "-m" in cmd_args and "unittest" in cmd_args:
|
|
366
|
+
if cls._is_tokensafe_available() and not cls._TOKENSAFE_WRAP_RE.search(stage):
|
|
367
|
+
wrapped = f"tokensafe wrap {shlex.quote(stage)}"
|
|
368
|
+
return wrapped, 2000, "Wrapped python unittest with tokensafe wrap to compact test results into one-line summary", None
|
|
369
|
+
|
|
311
370
|
# cargo test: quiet test runner by default when not specified
|
|
312
371
|
if cmd_tok == "cargo" and cmd_args[:1] == ["test"]:
|
|
313
372
|
if "--quiet" not in stage and "-q" not in stage and "--" not in stage:
|
|
@@ -425,9 +484,13 @@ class CommandSanitizer:
|
|
|
425
484
|
runner = "vitest"
|
|
426
485
|
elif cls._JEST_RE.match(stage) or cls._JEST_SCRIPT_RE.search(stage):
|
|
427
486
|
runner = "jest"
|
|
487
|
+
elif (cmd_tok == "bun" and cmd_args[:1] == ["test"]) or (cmd_tok in ("bunx",) and cmd_args[1:2] == ["test"]):
|
|
488
|
+
runner = "bun"
|
|
428
489
|
elif cls._PKG_MANAGER_TEST_RE.match(cls._strip_cmd_prefix(stage)):
|
|
429
490
|
if cls._JEST_FINGERPRINT_RE.search(stage):
|
|
430
491
|
runner = "jest"
|
|
492
|
+
elif cls._strip_cmd_prefix(stage).startswith("bun "):
|
|
493
|
+
runner = "bun"
|
|
431
494
|
else:
|
|
432
495
|
script_runner = cls._peek_test_script_runner(cwd)
|
|
433
496
|
runner = {"jest": "script-jest", "vitest": "script-vitest"}.get(script_runner, "generic")
|
|
@@ -438,6 +501,21 @@ class CommandSanitizer:
|
|
|
438
501
|
reasons: List[str] = []
|
|
439
502
|
saved = 0
|
|
440
503
|
|
|
504
|
+
if runner == "bun":
|
|
505
|
+
if cls._BARE_WATCH_RE.search(new_stage):
|
|
506
|
+
new_stage = cls._BARE_WATCH_RE.sub("", new_stage)
|
|
507
|
+
reasons.append("Dropped bare --watch from bun test command")
|
|
508
|
+
saved += 300
|
|
509
|
+
if not re.search(r"\bCI=", new_stage):
|
|
510
|
+
new_stage = f"CI=true {new_stage}"
|
|
511
|
+
saved += 300
|
|
512
|
+
reasons.append("Prepended CI=true for bun test run-once mode")
|
|
513
|
+
if cls._is_tokensafe_available() and not cls._TOKENSAFE_WRAP_RE.search(new_stage):
|
|
514
|
+
new_stage = f"tokensafe wrap {shlex.quote(new_stage)}"
|
|
515
|
+
saved += 2000
|
|
516
|
+
reasons.append("Wrapped bun test with tokensafe wrap to fold passing tests into compact summary")
|
|
517
|
+
return new_stage, saved, "; ".join(reasons), None
|
|
518
|
+
|
|
441
519
|
if runner in ("vitest", "script-vitest"):
|
|
442
520
|
if cls._BARE_WATCH_RE.search(new_stage):
|
|
443
521
|
new_stage = cls._BARE_WATCH_RE.sub("", new_stage)
|
|
@@ -540,6 +618,10 @@ class CommandSanitizer:
|
|
|
540
618
|
return None
|
|
541
619
|
|
|
542
620
|
is_build = False
|
|
621
|
+
saved = 1800
|
|
622
|
+
reason = "Wrapped build command with tokensafe wrap to fold progress noise and asset tables"
|
|
623
|
+
|
|
624
|
+
# 1. Build commands
|
|
543
625
|
if cmd_tok == "npm":
|
|
544
626
|
is_build = any(a in ("build", "build:prod", "build:cloud") or a.startswith("build:") for a in cmd_args) or (
|
|
545
627
|
"run" in cmd_args and any("build" in a for a in cmd_args)
|
|
@@ -555,22 +637,45 @@ class CommandSanitizer:
|
|
|
555
637
|
elif cmd_tok == "cargo" and cmd_args[:1] == ["build"]:
|
|
556
638
|
is_build = True
|
|
557
639
|
|
|
640
|
+
# 2. TypeScript compiler & type-checking commands (tsc, npx tsc, npm run typecheck)
|
|
558
641
|
if not is_build:
|
|
559
|
-
|
|
642
|
+
if cmd_tok == "tsc":
|
|
643
|
+
is_build = True
|
|
644
|
+
saved = 2500
|
|
645
|
+
reason = "Wrapped TypeScript compiler command with tokensafe wrap to compact error cascades"
|
|
646
|
+
elif cmd_tok in ("npx", "bunx") and "tsc" in cmd_args:
|
|
647
|
+
is_build = True
|
|
648
|
+
saved = 2500
|
|
649
|
+
reason = f"Wrapped {cmd_tok} tsc command with tokensafe wrap to compact error cascades"
|
|
650
|
+
elif cmd_tok in ("npm", "yarn", "pnpm", "bun"):
|
|
651
|
+
typecheck_hit = any(
|
|
652
|
+
a in ("typecheck", "type-check", "tsc", "check-types") or "typecheck" in a or "type-check" in a
|
|
653
|
+
for a in cmd_args
|
|
654
|
+
)
|
|
655
|
+
if typecheck_hit:
|
|
656
|
+
is_build = True
|
|
657
|
+
saved = 2500
|
|
658
|
+
reason = f"Wrapped {cmd_tok} typecheck command with tokensafe wrap to compact error cascades"
|
|
659
|
+
|
|
660
|
+
# 3. Linter commands (eslint, npx eslint, biome, npx biome)
|
|
661
|
+
if not is_build:
|
|
662
|
+
if cmd_tok in ("eslint", "biome"):
|
|
663
|
+
is_build = True
|
|
664
|
+
saved = 1500
|
|
665
|
+
reason = f"Wrapped {cmd_tok} linter command with tokensafe wrap to bound output"
|
|
666
|
+
elif cmd_tok in ("npx", "bunx") and any(a in ("eslint", "biome") for a in cmd_args):
|
|
667
|
+
is_build = True
|
|
668
|
+
saved = 1500
|
|
669
|
+
reason = f"Wrapped {cmd_tok} linter command with tokensafe wrap to bound output"
|
|
560
670
|
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
has_tokensafe = bool(shutil.which("tokensafe"))
|
|
564
|
-
if not has_tokensafe:
|
|
565
|
-
bin_path = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "bin", "tokensafe")
|
|
566
|
-
if os.path.exists(bin_path):
|
|
567
|
-
has_tokensafe = True
|
|
671
|
+
if not is_build:
|
|
672
|
+
return None
|
|
568
673
|
|
|
569
|
-
if not
|
|
674
|
+
if not cls._is_tokensafe_available():
|
|
570
675
|
return None
|
|
571
676
|
|
|
572
677
|
wrapped = f"tokensafe wrap {shlex.quote(stage)}"
|
|
573
|
-
return wrapped,
|
|
678
|
+
return wrapped, saved, reason, None
|
|
574
679
|
|
|
575
680
|
@classmethod
|
|
576
681
|
def sanitize(cls, command: str, cwd: Optional[str] = None) -> Tuple[Optional[str], int, str]:
|
|
@@ -714,6 +819,15 @@ class CommandSanitizer:
|
|
|
714
819
|
if line.startswith("ok \t") or line.startswith("PASS"):
|
|
715
820
|
return f"PASS: {line}"
|
|
716
821
|
|
|
822
|
+
# 6. bun test check
|
|
823
|
+
for line in reversed(lines):
|
|
824
|
+
if "test files passed in" in line:
|
|
825
|
+
return f"PASS: {line} (bun test)"
|
|
826
|
+
if line.startswith("Ran ") and "tests across" in line and "file" in line:
|
|
827
|
+
return f"PASS: {line} (bun test)"
|
|
828
|
+
if re.search(r"^\d+\s+pass\b", line):
|
|
829
|
+
return f"PASS: {line} (bun test)"
|
|
830
|
+
|
|
717
831
|
# Fallback for verbose outputs: if > 12 lines, cap to first line + last line
|
|
718
832
|
if len(lines) > 12:
|
|
719
833
|
return f"PASS: {lines[0]} ... {lines[-1]} (exit code 0)"
|
|
@@ -787,6 +901,17 @@ class CommandSanitizer:
|
|
|
787
901
|
return None
|
|
788
902
|
resolved_exit = 0
|
|
789
903
|
elif resolved_exit != 0:
|
|
904
|
+
# Check test & compiler error compactor first (tsc error cascades, pytest failures)
|
|
905
|
+
from src.test_parsers import TestOutputParser
|
|
906
|
+
compacted_test, was_test = TestOutputParser.compact(raw)
|
|
907
|
+
if was_test and len(compacted_test) < len(raw) * 0.85:
|
|
908
|
+
return compacted_test, len(raw), len(compacted_test)
|
|
909
|
+
|
|
910
|
+
from src.build_parsers import BuildOutputParser
|
|
911
|
+
compacted_build, was_build = BuildOutputParser.compact(raw, resolved_exit)
|
|
912
|
+
if was_build and len(compacted_build) < len(raw) * 0.85:
|
|
913
|
+
return compacted_build, len(raw), len(compacted_build)
|
|
914
|
+
|
|
790
915
|
# Failed run: failure noise (progress dots / blank runs / verbose PASSED lines)
|
|
791
916
|
# is stripped while every traceback frame stays intact; skip when it saves <15%.
|
|
792
917
|
stripped = cls._strip_failure_noise(raw)
|
package/src/fts_index.py
CHANGED
|
@@ -13,6 +13,7 @@ import os
|
|
|
13
13
|
import sqlite3
|
|
14
14
|
import time
|
|
15
15
|
import hashlib
|
|
16
|
+
import shutil
|
|
16
17
|
from typing import List, Dict, Any, Optional, Tuple
|
|
17
18
|
|
|
18
19
|
from src.paths import resolve_data_dir
|
|
@@ -41,18 +42,36 @@ CODE_EXTS = {
|
|
|
41
42
|
}
|
|
42
43
|
|
|
43
44
|
|
|
45
|
+
from src.paths import resolve_data_dir, ensure_tokensafe_gitignore
|
|
46
|
+
|
|
47
|
+
|
|
44
48
|
def _resolve_fts_db_path(project_root: str) -> str:
|
|
45
|
-
"""Returns path to the SQLite FTS database for a project.
|
|
46
|
-
|
|
49
|
+
"""Returns path to the SQLite FTS database for a project.
|
|
50
|
+
|
|
51
|
+
Always stores index in global user cache ~/.tokensafe/cache/fts/<project_hash>.db
|
|
52
|
+
so the project working tree is never polluted with binary database files.
|
|
53
|
+
"""
|
|
54
|
+
ensure_tokensafe_gitignore(project_root)
|
|
55
|
+
|
|
56
|
+
# Legacy cleanup: if fts.db was mistakenly created in project .tokensafe, migrate or remove
|
|
47
57
|
proj_tokensafe = os.path.join(project_root, ".tokensafe")
|
|
48
|
-
|
|
49
|
-
return os.path.join(proj_tokensafe, "fts.db")
|
|
58
|
+
legacy_file = os.path.join(proj_tokensafe, "fts.db")
|
|
50
59
|
|
|
51
|
-
# Otherwise store in ~/.tokensafe/cache/fts/<project_hash>.db
|
|
52
60
|
cache_dir = os.path.join(resolve_data_dir(), "cache", "fts")
|
|
53
61
|
os.makedirs(cache_dir, exist_ok=True)
|
|
54
62
|
p_hash = hashlib.sha256(os.path.abspath(project_root).encode("utf-8")).hexdigest()[:16]
|
|
55
|
-
|
|
63
|
+
target_path = os.path.join(cache_dir, f"fts_{p_hash}.db")
|
|
64
|
+
|
|
65
|
+
if os.path.isfile(legacy_file) and not os.path.isfile(target_path):
|
|
66
|
+
try:
|
|
67
|
+
shutil.move(legacy_file, target_path)
|
|
68
|
+
for extra in (f"{legacy_file}-wal", f"{legacy_file}-shm"):
|
|
69
|
+
if os.path.isfile(extra):
|
|
70
|
+
os.remove(extra)
|
|
71
|
+
except Exception:
|
|
72
|
+
pass
|
|
73
|
+
|
|
74
|
+
return target_path
|
|
56
75
|
|
|
57
76
|
|
|
58
77
|
class CodeFTSIndex:
|
package/src/installer.py
CHANGED
|
@@ -53,7 +53,7 @@ UNIFIED_TOKENSAFE_RULE = (
|
|
|
53
53
|
"5. **Architecture Discovery**: Always call `tokensafe:get_architecture_graph(project_path='.')` before exploratory multi-file reading (`project_path` defaults to active workspace). Returns project God Nodes and key dependency hubs in < 250 tokens without file crawling.\n"
|
|
54
54
|
"6. **API Surface Map**: Use `tokensafe:get_api_surface(project_path='.')` to get all exported classes, types, and interfaces in a single markdown map without crawling files.\n"
|
|
55
55
|
"7. **No Unconstrained Shell Grep/Find & No Verbose ls -la**: Strictly avoid running raw recursive grep/find across projects. Never run verbose `ls -la` or `ls -l`; use `tokensafe:list_dir(path='.', depth=2)` to inspect directory trees in clean markdown without permissions, timestamps, or lockfiles (-90% tokens). Supports relative subfolders (`path='src'`).\n"
|
|
56
|
-
"8. **Command Sanitization, Build Compaction & Compact Tests**: Use `sanitize_command` on high-output terminal commands (`git diff/log/show/blame`, `rg`, `find`, `grep`, `docker`/`kubectl logs`, `npm`/`pip install`, `cat` of lockfiles, `curl`, and build commands like `npm run build`, `vite build`, `next build`, `cargo build`) — compound commands (`a && b ; c`) are rewritten per stage. Run noisy commands, builds, and test suites via `tokensafe wrap '<command>'` or `tokensafe tests [cmd]` (clean
|
|
56
|
+
"8. **Command Sanitization, Build Compaction & Compact Tests**: Use `sanitize_command` on high-output terminal commands (`git diff/log/show/blame`, `git push` --no-progress, `git commit` hook protection, `rg`, `find`, `grep`, `docker`/`kubectl logs`, `npm`/`pip install`, `cat` of lockfiles, `curl`, and build/typecheck commands like `npm run build`, `vite build`, `next build`, `cargo build`, `tsc`, `tsc --noEmit`, `npm run typecheck`, `npx eslint`) — compound commands (`a && b ; c`) are rewritten per stage. Run noisy commands, builds, and test suites (`bun test`, `pytest`, `python -m unittest`, `vitest`, `jest`, `cargo test`, `go test`) via `tokensafe wrap '<command>'` or `tokensafe tests [cmd]` (clean 1-line build/pass summary, full traceback/compiler error only on failure) instead of raw verbose test crawls; never leave `vitest`/`jest`/`bun` in watch mode — pass the optional `cwd` to `sanitize_command` for test commands so the package.json peek can identify the runner behind opaque `yarn/npm test` scripts.\n"
|
|
57
57
|
"9. **Styles & Design Token Preservation**: When inspecting CSS, SCSS, LESS, or Tailwind, `smart_read_file` automatically preserves all design tokens (`:root`, `@theme`, CSS variables) in full while folding component selectors to protect project design integrity.\n"
|
|
58
58
|
"10. **Context Budget & Smart Compaction**: Before large multi-step tasks, call `tokensafe:context_budget(model=...)` to inspect window usage and Context Quality Score (Grade S-F); when it reports `warning` or `critical` (or Grade C/F), call `tokensafe:compact_conversation(transcript_path=...)` to fold history into a State Ledger with a 3-line Post-Compaction Orientation Digest before continuing.\n"
|
|
59
59
|
"11. **Secret Leak Prevention Directive (Zero Hardcoded Fallbacks)**:\n"
|
|
@@ -1016,6 +1016,13 @@ WantedBy=default.target
|
|
|
1016
1016
|
cls._write_agents_plugins_config(project_dir, agents_plugin_path)
|
|
1017
1017
|
created.append(".agents/plugins.json")
|
|
1018
1018
|
|
|
1019
|
+
try:
|
|
1020
|
+
from src.paths import ensure_tokensafe_gitignore
|
|
1021
|
+
if ensure_tokensafe_gitignore(project_dir):
|
|
1022
|
+
created.append(".gitignore (.tokensafe/ registered)")
|
|
1023
|
+
except Exception:
|
|
1024
|
+
pass
|
|
1025
|
+
|
|
1019
1026
|
return {
|
|
1020
1027
|
"success": True,
|
|
1021
1028
|
"project_dir": project_dir,
|
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": "4.1.
|
|
45
|
+
"version": "4.1.7"
|
|
46
46
|
}
|
|
47
47
|
|
|
48
48
|
# MCP client attribution: the initialize handshake carries clientInfo, which
|
|
@@ -180,18 +180,19 @@ TOOLS = [
|
|
|
180
180
|
{
|
|
181
181
|
"name": "sanitize_command",
|
|
182
182
|
"description": "Per-stage shell command rewrites: prunes lockfiles, caps unbounded git log/show/blame/rg "
|
|
183
|
-
"and docker/kubectl logs,
|
|
184
|
-
"
|
|
185
|
-
"
|
|
186
|
-
"
|
|
187
|
-
"
|
|
183
|
+
"and docker/kubectl logs, strips git push progress animations (--no-progress), wraps git commit "
|
|
184
|
+
"with tokensafe wrap when pre-commit/husky hooks exist, and quiets npm/pip installs, bounds cat/curl output. "
|
|
185
|
+
"Compound commands (a && b ; c) are optimized per stage without breaking operators. Test commands "
|
|
186
|
+
"(bun test, pytest, python -m unittest, vitest, jest) are automatically wrapped or forced into run-once mode "
|
|
187
|
+
"(CI=true, --watch=false, --forceExit) so passing suites emit a clean 1-line summary and agents never hang on watch mode. "
|
|
188
|
+
"Pass optional cwd for test commands to unlock package.json runner detection for opaque yarn/npm test scripts.",
|
|
188
189
|
"inputSchema": {
|
|
189
190
|
"type": "object",
|
|
190
191
|
"properties": {
|
|
191
192
|
"command": {"type": "string", "description": "Raw bash command line"},
|
|
193
|
+
"cmd": {"type": "string", "description": "Alias for command"},
|
|
192
194
|
"cwd": {"type": "string", "description": "Optional working directory the command will run in; enables the package.json peek that identifies the runner behind opaque yarn/npm test scripts"}
|
|
193
|
-
}
|
|
194
|
-
"required": ["command"]
|
|
195
|
+
}
|
|
195
196
|
}
|
|
196
197
|
},
|
|
197
198
|
{
|
|
@@ -221,6 +222,7 @@ TOOLS = [
|
|
|
221
222
|
"type": "object",
|
|
222
223
|
"properties": {
|
|
223
224
|
"command": {"type": "string", "description": "Optional: Terminal command line to audit"},
|
|
225
|
+
"cmd": {"type": "string", "description": "Alias for command"},
|
|
224
226
|
"code": {"type": "string", "description": "Optional: Code snippet, replacement diff, or file content to audit"},
|
|
225
227
|
"file_path": {"type": "string", "description": "Optional: File path being written or modified"}
|
|
226
228
|
}
|
|
@@ -735,8 +737,8 @@ def handle_tool_call(name: str, args: dict) -> dict:
|
|
|
735
737
|
if name == "smart_read_file" and isinstance(result, dict) and not result.get("isError"):
|
|
736
738
|
content_parts = result.get("content") or []
|
|
737
739
|
text_out = "".join(p.get("text", "") for p in content_parts if isinstance(p, dict))
|
|
738
|
-
path = args.get("path"
|
|
739
|
-
symbol = (args.get("symbol") or "").strip()
|
|
740
|
+
path = args.get("path") or args.get("file_path") or args.get("file") or ""
|
|
741
|
+
symbol = (args.get("symbol") or args.get("sym") or args.get("target") or "").strip()
|
|
740
742
|
_, eff_dep_mode = _resolve_dep_mode(args)
|
|
741
743
|
cache_sym = f"{symbol}@{eff_dep_mode}" if (symbol and eff_dep_mode != "signature") else symbol
|
|
742
744
|
is_ranged = args.get("start_line") is not None or args.get("end_line") is not None
|
|
@@ -779,8 +781,8 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
|
|
|
779
781
|
is_quota_exceeded = bool(quota.get("is_quota_exceeded", False))
|
|
780
782
|
|
|
781
783
|
if name == "smart_read_file":
|
|
782
|
-
path = args.get("path"
|
|
783
|
-
symbol = args.get("symbol"
|
|
784
|
+
path = args.get("path") or args.get("file_path") or args.get("file") or ""
|
|
785
|
+
symbol = args.get("symbol") or args.get("sym") or args.get("target") or ""
|
|
784
786
|
inc_deps, eff_dep_mode = _resolve_dep_mode(args)
|
|
785
787
|
force_full = bool(args.get("force_full", False))
|
|
786
788
|
start_line = args.get("start_line")
|
|
@@ -880,6 +882,49 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
|
|
|
880
882
|
except Exception:
|
|
881
883
|
pass
|
|
882
884
|
|
|
885
|
+
# Kubernetes manifests (.yaml / .yml with multiple resources):
|
|
886
|
+
if path.lower().endswith((".yaml", ".yml")):
|
|
887
|
+
from src.format_parsers.docker_k8s import ContainerAndK8sReducer
|
|
888
|
+
try:
|
|
889
|
+
with open(path, "r", encoding="utf-8", errors="replace") as f:
|
|
890
|
+
raw_k8s_text = f.read()
|
|
891
|
+
reduced_k8s, was_k8s = ContainerAndK8sReducer.reduce_k8s_yaml(raw_k8s_text)
|
|
892
|
+
if was_k8s:
|
|
893
|
+
orig_t = count_tokens(raw_k8s_text)
|
|
894
|
+
opt_t = count_tokens(reduced_k8s)
|
|
895
|
+
tracker.record_event(
|
|
896
|
+
session_id=_mcp_session_id(),
|
|
897
|
+
event_type="K8S_MANIFEST_REDUCE",
|
|
898
|
+
original_tokens=orig_t,
|
|
899
|
+
optimized_tokens=opt_t,
|
|
900
|
+
details={"file": os.path.basename(path), "saved": orig_t - opt_t}
|
|
901
|
+
)
|
|
902
|
+
return {"content": [{"type": "text", "text": reduced_k8s}]}
|
|
903
|
+
except Exception:
|
|
904
|
+
pass
|
|
905
|
+
|
|
906
|
+
# Structured NDJSON / JSON log files (.ndjson, .log, .jsonl):
|
|
907
|
+
if path.lower().endswith((".ndjson", ".log", ".jsonl")):
|
|
908
|
+
from src.format_parsers.json_log import JSONLogReducer
|
|
909
|
+
try:
|
|
910
|
+
with open(path, "r", encoding="utf-8", errors="replace") as f:
|
|
911
|
+
raw_log_text = f.read()
|
|
912
|
+
if JSONLogReducer.is_ndjson_log(raw_log_text):
|
|
913
|
+
reduced_log, was_log = JSONLogReducer.reduce(raw_log_text)
|
|
914
|
+
if was_log:
|
|
915
|
+
orig_t = count_tokens(raw_log_text)
|
|
916
|
+
opt_t = count_tokens(reduced_log)
|
|
917
|
+
tracker.record_event(
|
|
918
|
+
session_id=_mcp_session_id(),
|
|
919
|
+
event_type="JSON_LOG_REDUCE",
|
|
920
|
+
original_tokens=orig_t,
|
|
921
|
+
optimized_tokens=opt_t,
|
|
922
|
+
details={"file": os.path.basename(path), "saved": orig_t - opt_t}
|
|
923
|
+
)
|
|
924
|
+
return {"content": [{"type": "text", "text": reduced_log}]}
|
|
925
|
+
except Exception:
|
|
926
|
+
pass
|
|
927
|
+
|
|
883
928
|
# Heavy declarative schema files (OpenAPI/Swagger/Prisma/GraphQL/SQL DDL):
|
|
884
929
|
# generic AST skeletonization does not apply — route to the schema slicer.
|
|
885
930
|
# `symbol` carries the target (a spec path, model, type or table); an empty
|
|
@@ -1274,7 +1319,7 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
|
|
|
1274
1319
|
}, indent=2, ensure_ascii=False)}]}
|
|
1275
1320
|
|
|
1276
1321
|
elif name == "sanitize_command":
|
|
1277
|
-
cmd = args.get("command"
|
|
1322
|
+
cmd = args.get("command") or args.get("cmd") or args.get("c") or ""
|
|
1278
1323
|
# Step 1: TokenSafe Guard security inspection
|
|
1279
1324
|
guard_res = TokenSafeGuard.inspect_command(cmd)
|
|
1280
1325
|
if guard_res.blocked:
|
|
@@ -1323,9 +1368,9 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
|
|
|
1323
1368
|
return {"content": [{"type": "text", "text": json.dumps(result, indent=2)}]}
|
|
1324
1369
|
|
|
1325
1370
|
elif name == "guard_inspect":
|
|
1326
|
-
cmd = args.get("command")
|
|
1327
|
-
code = args.get("code")
|
|
1328
|
-
file_path = args.get("file_path"
|
|
1371
|
+
cmd = args.get("command") or args.get("cmd") or args.get("c")
|
|
1372
|
+
code = args.get("code") or args.get("snippet")
|
|
1373
|
+
file_path = args.get("file_path") or args.get("path") or args.get("file") or ""
|
|
1329
1374
|
|
|
1330
1375
|
results = []
|
|
1331
1376
|
if cmd is not None:
|
|
@@ -1618,7 +1663,7 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
|
|
|
1618
1663
|
return {"content": [{"type": "text", "text": tree_output}]}
|
|
1619
1664
|
|
|
1620
1665
|
elif name == "scoped_search":
|
|
1621
|
-
query = args.get("query"
|
|
1666
|
+
query = args.get("query") or args.get("q") or args.get("pattern") or args.get("text") or ""
|
|
1622
1667
|
if not query:
|
|
1623
1668
|
return _fallback_error("scoped_search", "missing required 'query' argument")
|
|
1624
1669
|
|
package/src/mistakes.py
CHANGED
|
@@ -16,7 +16,7 @@ import time
|
|
|
16
16
|
import hashlib
|
|
17
17
|
import subprocess
|
|
18
18
|
from typing import Dict, Any, List, Optional
|
|
19
|
-
from src.paths import resolve_data_dir
|
|
19
|
+
from src.paths import resolve_data_dir, ensure_tokensafe_gitignore
|
|
20
20
|
|
|
21
21
|
|
|
22
22
|
def _find_project_mistakes_file(project_root: Optional[str] = None) -> str:
|
|
@@ -25,6 +25,7 @@ def _find_project_mistakes_file(project_root: Optional[str] = None) -> str:
|
|
|
25
25
|
proj_dir = os.path.join(project_root, ".tokensafe")
|
|
26
26
|
try:
|
|
27
27
|
os.makedirs(proj_dir, exist_ok=True)
|
|
28
|
+
ensure_tokensafe_gitignore(project_root)
|
|
28
29
|
return os.path.join(proj_dir, "mistakes.jsonl")
|
|
29
30
|
except Exception:
|
|
30
31
|
pass
|
package/src/paths.py
CHANGED
|
@@ -157,3 +157,47 @@ def get_active_workspace() -> Optional[str]:
|
|
|
157
157
|
except Exception:
|
|
158
158
|
pass
|
|
159
159
|
return None
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def ensure_tokensafe_gitignore(project_root: Optional[str]) -> bool:
|
|
163
|
+
"""
|
|
164
|
+
Ensures .tokensafe/ and local caches never leak into git.
|
|
165
|
+
1. If <project_root>/.tokensafe exists, drops an internal .gitignore (*\n!.gitignore\n).
|
|
166
|
+
2. If <project_root>/.gitignore exists, ensures .tokensafe/ is ignored.
|
|
167
|
+
"""
|
|
168
|
+
if not project_root or not os.path.isdir(project_root):
|
|
169
|
+
return False
|
|
170
|
+
|
|
171
|
+
updated = False
|
|
172
|
+
proj_tokensafe = os.path.join(project_root, ".tokensafe")
|
|
173
|
+
if os.path.isdir(proj_tokensafe):
|
|
174
|
+
inner_ignore = os.path.join(proj_tokensafe, ".gitignore")
|
|
175
|
+
if not os.path.isfile(inner_ignore):
|
|
176
|
+
try:
|
|
177
|
+
with open(inner_ignore, "w", encoding="utf-8") as f:
|
|
178
|
+
f.write("# TokenSafe local runtime artifacts & caches\n*\n!.gitignore\n")
|
|
179
|
+
updated = True
|
|
180
|
+
except Exception:
|
|
181
|
+
pass
|
|
182
|
+
|
|
183
|
+
root_gitignore = os.path.join(project_root, ".gitignore")
|
|
184
|
+
if os.path.isfile(root_gitignore):
|
|
185
|
+
try:
|
|
186
|
+
with open(root_gitignore, "r", encoding="utf-8", errors="replace") as f:
|
|
187
|
+
content = f.read()
|
|
188
|
+
lines = [ln.strip() for ln in content.splitlines()]
|
|
189
|
+
has_entry = any(
|
|
190
|
+
ln in (".tokensafe", ".tokensafe/", "/.tokensafe", "/.tokensafe/")
|
|
191
|
+
for ln in lines
|
|
192
|
+
)
|
|
193
|
+
if not has_entry:
|
|
194
|
+
with open(root_gitignore, "a", encoding="utf-8") as f:
|
|
195
|
+
if content and not content.endswith("\n"):
|
|
196
|
+
f.write("\n")
|
|
197
|
+
f.write("\n# TokenSafe local cache & runtime metrics\n.tokensafe/\n")
|
|
198
|
+
updated = True
|
|
199
|
+
except Exception:
|
|
200
|
+
pass
|
|
201
|
+
|
|
202
|
+
return updated
|
|
203
|
+
|
package/src/result_ledger.py
CHANGED
|
@@ -113,7 +113,7 @@ def _compact_read_result(text: str, path: str) -> Optional[str]:
|
|
|
113
113
|
|
|
114
114
|
|
|
115
115
|
def _compact_command_result(text: str) -> Optional[str]:
|
|
116
|
-
"""Test summaries first (PASS: ...), log-style head/tail otherwise."""
|
|
116
|
+
"""Test summaries first (PASS: ...), build/docker/log compaction next, log-style head/tail otherwise."""
|
|
117
117
|
try:
|
|
118
118
|
from src.test_parsers import TestOutputParser
|
|
119
119
|
compacted, was_test = TestOutputParser.compact(text)
|
|
@@ -121,6 +121,28 @@ def _compact_command_result(text: str) -> Optional[str]:
|
|
|
121
121
|
return compacted
|
|
122
122
|
except Exception:
|
|
123
123
|
pass
|
|
124
|
+
try:
|
|
125
|
+
from src.build_parsers import BuildOutputParser
|
|
126
|
+
compacted_b, was_b = BuildOutputParser.compact(text)
|
|
127
|
+
if was_b:
|
|
128
|
+
return compacted_b
|
|
129
|
+
except Exception:
|
|
130
|
+
pass
|
|
131
|
+
try:
|
|
132
|
+
from src.format_parsers.docker_k8s import ContainerAndK8sReducer
|
|
133
|
+
compacted_d, was_d = ContainerAndK8sReducer.reduce_docker_build(text)
|
|
134
|
+
if was_d:
|
|
135
|
+
return compacted_d
|
|
136
|
+
except Exception:
|
|
137
|
+
pass
|
|
138
|
+
try:
|
|
139
|
+
from src.format_parsers.json_log import JSONLogReducer
|
|
140
|
+
if JSONLogReducer.is_ndjson_log(text):
|
|
141
|
+
compacted_j, was_j = JSONLogReducer.reduce(text)
|
|
142
|
+
if was_j:
|
|
143
|
+
return compacted_j
|
|
144
|
+
except Exception:
|
|
145
|
+
pass
|
|
124
146
|
try:
|
|
125
147
|
from src.command_sanitizer import CommandSanitizer
|
|
126
148
|
compacted = CommandSanitizer.compact_test_output(text, 0)
|
package/src/telemetry_sync.py
CHANGED
|
@@ -241,7 +241,7 @@ class TelemetrySync:
|
|
|
241
241
|
current_last_id = last_id
|
|
242
242
|
headers = {
|
|
243
243
|
"Content-Type": "application/json",
|
|
244
|
-
"User-Agent": "TokenSafe-Sync/4.1.
|
|
244
|
+
"User-Agent": "TokenSafe-Sync/4.1.7"
|
|
245
245
|
}
|
|
246
246
|
if active_key:
|
|
247
247
|
headers["Authorization"] = f"Bearer {active_key}"
|
package/src/test_parsers.py
CHANGED
|
@@ -42,6 +42,23 @@ _CARGO_DUR_RE = re.compile(r"finished in\s+(?P<dur>[0-9.]+[a-zA-Z]*)", re.IGNORE
|
|
|
42
42
|
_GO_TEST_OK_RE = re.compile(r"^ok\s+(\S+)\s+([0-9.]+[ms]+)", re.MULTILINE)
|
|
43
43
|
_GO_TEST_FAIL_RE = re.compile(r"^FAIL\s+(\S+)\s+([0-9.]+[ms]+)", re.MULTILINE)
|
|
44
44
|
|
|
45
|
+
# bun test regexes
|
|
46
|
+
_BUN_FILES_SUMMARY_RE = re.compile(
|
|
47
|
+
r"(?P<passed_files>\d+)/(?P<total_files>\d+)\s+test files passed in\s+(?P<dur>[0-9.]+[a-zA-Z]*)",
|
|
48
|
+
re.IGNORECASE
|
|
49
|
+
)
|
|
50
|
+
_BUN_RAN_RE = re.compile(
|
|
51
|
+
r"Ran\s+(?P<tests>\d+)\s+tests?\s+across\s+(?P<files>\d+)\s+files?\.?\s*\[(?P<dur>[0-9.]+[a-zA-Z]*)\]",
|
|
52
|
+
re.IGNORECASE
|
|
53
|
+
)
|
|
54
|
+
_BUN_PASS_RE = re.compile(r"^\s*(?P<pass>\d+)\s+pass\b", re.MULTILINE | re.IGNORECASE)
|
|
55
|
+
_BUN_FAIL_RE = re.compile(r"^\s*(?P<fail>\d+)\s+fail\b", re.MULTILINE | re.IGNORECASE)
|
|
56
|
+
_BUN_EXPECTS_RE = re.compile(r"^\s*(?P<expects>\d+)\s+expect\(\)\s+calls\b", re.MULTILINE | re.IGNORECASE)
|
|
57
|
+
_GIT_COMMIT_CONFIRM_RE = re.compile(
|
|
58
|
+
r"(\[[^\]\r\n]+\s+[0-9a-f]{7,40}\][^\r\n]*(?:\n\s*\d+\s+files?\s+changed[^\r\n]*)?)",
|
|
59
|
+
re.IGNORECASE
|
|
60
|
+
)
|
|
61
|
+
|
|
45
62
|
|
|
46
63
|
class TestOutputParser:
|
|
47
64
|
"""Parses and folds test runner terminal outputs."""
|
|
@@ -49,6 +66,14 @@ class TestOutputParser:
|
|
|
49
66
|
@classmethod
|
|
50
67
|
def detect_runner(cls, cmd_or_output: str) -> Optional[str]:
|
|
51
68
|
s = cmd_or_output.lower()
|
|
69
|
+
if "bun test" in s or "bun:test" in s:
|
|
70
|
+
return "bun test"
|
|
71
|
+
if "expect() calls" in s and ("pass\n" in s or " pass" in s):
|
|
72
|
+
return "bun test"
|
|
73
|
+
if "test files passed in" in s:
|
|
74
|
+
return "bun test"
|
|
75
|
+
if re.search(r"\bran\s+\d+\s+tests?\s+across\s+\d+\s+files?", s):
|
|
76
|
+
return "bun test"
|
|
52
77
|
if "pytest" in s:
|
|
53
78
|
return "pytest"
|
|
54
79
|
if "unittest" in s or ("ran " in s and " tests in " in s):
|
|
@@ -80,7 +105,9 @@ class TestOutputParser:
|
|
|
80
105
|
if not detected:
|
|
81
106
|
return raw, False
|
|
82
107
|
|
|
83
|
-
if detected == "
|
|
108
|
+
if detected == "bun test":
|
|
109
|
+
return cls._compact_bun_test(raw)
|
|
110
|
+
elif detected == "pytest":
|
|
84
111
|
return cls._compact_pytest(raw)
|
|
85
112
|
elif detected == "unittest":
|
|
86
113
|
return cls._compact_unittest(raw)
|
|
@@ -139,6 +166,86 @@ class TestOutputParser:
|
|
|
139
166
|
]
|
|
140
167
|
return "\n".join(res), True
|
|
141
168
|
|
|
169
|
+
@classmethod
|
|
170
|
+
def _compact_bun_test(cls, raw: str) -> Tuple[str, bool]:
|
|
171
|
+
files_m = _BUN_FILES_SUMMARY_RE.search(raw)
|
|
172
|
+
ran_m = _BUN_RAN_RE.search(raw)
|
|
173
|
+
pass_matches = _BUN_PASS_RE.findall(raw)
|
|
174
|
+
fail_matches = _BUN_FAIL_RE.findall(raw)
|
|
175
|
+
expects_matches = _BUN_EXPECTS_RE.findall(raw)
|
|
176
|
+
|
|
177
|
+
if not files_m and not ran_m and not pass_matches:
|
|
178
|
+
return raw, False
|
|
179
|
+
|
|
180
|
+
passed = int(pass_matches[-1]) if pass_matches else 0
|
|
181
|
+
failed = int(fail_matches[-1]) if fail_matches else 0
|
|
182
|
+
|
|
183
|
+
if files_m:
|
|
184
|
+
passed_files = int(files_m.group("passed_files"))
|
|
185
|
+
total_files = int(files_m.group("total_files"))
|
|
186
|
+
dur = files_m.group("dur")
|
|
187
|
+
if passed_files < total_files:
|
|
188
|
+
failed = max(failed, total_files - passed_files)
|
|
189
|
+
else:
|
|
190
|
+
passed_files = total_files = 0
|
|
191
|
+
dur = ran_m.group("dur") if ran_m else ""
|
|
192
|
+
|
|
193
|
+
commit_m = _GIT_COMMIT_CONFIRM_RE.search(raw)
|
|
194
|
+
commit_suffix = f"\n{commit_m.group(1)}" if commit_m else ""
|
|
195
|
+
|
|
196
|
+
if failed == 0:
|
|
197
|
+
if files_m:
|
|
198
|
+
if ran_m:
|
|
199
|
+
tests = ran_m.group("tests")
|
|
200
|
+
exp_str = f", {expects_matches[-1]} expects" if expects_matches else ""
|
|
201
|
+
summary = f"✓ PASS: {passed_files}/{total_files} test files passed ({tests} pass{exp_str} in {dur}) [bun test]{commit_suffix}"
|
|
202
|
+
else:
|
|
203
|
+
summary = f"✓ PASS: {passed_files}/{total_files} test files passed in {dur} [bun test]{commit_suffix}"
|
|
204
|
+
elif ran_m:
|
|
205
|
+
tests = ran_m.group("tests")
|
|
206
|
+
files = ran_m.group("files")
|
|
207
|
+
dur = ran_m.group("dur")
|
|
208
|
+
exp_str = f" ({expects_matches[-1]} expects)" if expects_matches else ""
|
|
209
|
+
summary = f"✓ PASS: {tests} tests passed across {files} file(s) in {dur}{exp_str} [bun test]{commit_suffix}"
|
|
210
|
+
else:
|
|
211
|
+
exp_str = f" ({expects_matches[-1]} expects)" if expects_matches else ""
|
|
212
|
+
summary = f"✓ PASS: {passed} tests passed{exp_str} [bun test]{commit_suffix}"
|
|
213
|
+
return summary, True
|
|
214
|
+
|
|
215
|
+
# Failed run: extract failures and stash full output
|
|
216
|
+
_, marker = stash_block(raw, source="bun_test")
|
|
217
|
+
lines = raw.splitlines()
|
|
218
|
+
failures = []
|
|
219
|
+
cur_fail = []
|
|
220
|
+
in_fail = False
|
|
221
|
+
|
|
222
|
+
for ln in lines:
|
|
223
|
+
s = ln.strip()
|
|
224
|
+
if "✗ " in ln or ln.startswith("error: ") or "Expected:" in ln or "Received:" in ln:
|
|
225
|
+
in_fail = True
|
|
226
|
+
if in_fail:
|
|
227
|
+
cur_fail.append(ln)
|
|
228
|
+
if len(cur_fail) >= 8 or ("✗ " in ln and len(cur_fail) > 1):
|
|
229
|
+
failures.append("\n".join(cur_fail))
|
|
230
|
+
cur_fail = []
|
|
231
|
+
in_fail = False
|
|
232
|
+
if len(failures) >= 5:
|
|
233
|
+
break
|
|
234
|
+
if cur_fail and len(failures) < 5:
|
|
235
|
+
failures.append("\n".join(cur_fail))
|
|
236
|
+
|
|
237
|
+
dur_str = f" in {dur}" if dur else ""
|
|
238
|
+
out = [
|
|
239
|
+
f"✗ FAIL: {failed} failed, {passed} passed{dur_str} [bun test]",
|
|
240
|
+
"Failures excerpt:"
|
|
241
|
+
]
|
|
242
|
+
for fb in failures:
|
|
243
|
+
out.append(f" {fb}")
|
|
244
|
+
out.append(marker)
|
|
245
|
+
if commit_suffix:
|
|
246
|
+
out.append(commit_suffix.strip())
|
|
247
|
+
return "\n".join(out), True
|
|
248
|
+
|
|
142
249
|
@classmethod
|
|
143
250
|
def _compact_unittest(cls, raw: str) -> Tuple[str, bool]:
|
|
144
251
|
lines = raw.splitlines()
|
|
@@ -154,7 +261,8 @@ class TestOutputParser:
|
|
|
154
261
|
return raw, False
|
|
155
262
|
|
|
156
263
|
if status.startswith("OK"):
|
|
157
|
-
|
|
264
|
+
status_clean = f" ({status})" if status else ""
|
|
265
|
+
return f"✓ {ran} — all tests passed{status_clean}", True
|
|
158
266
|
|
|
159
267
|
# Extract failure blocks
|
|
160
268
|
_, marker = stash_block(raw, source="unittest")
|
package/src/version_checker.py
CHANGED
|
@@ -17,7 +17,7 @@ import urllib.request
|
|
|
17
17
|
import urllib.error
|
|
18
18
|
from typing import Dict, Any, Optional, Tuple
|
|
19
19
|
|
|
20
|
-
CURRENT_VERSION = "4.1.
|
|
20
|
+
CURRENT_VERSION = "4.1.7"
|
|
21
21
|
CACHE_TTL = 86400 # 24 hours
|
|
22
22
|
# When the cloud is unreachable we must NOT cache the synthesized "up to date"
|
|
23
23
|
# answer for a full day — otherwise an update released right after an outage
|