tokensafe 4.1.6 → 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 CHANGED
@@ -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 with bounded output and ANSI escape sequence stripping |
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 |
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "tokensafe",
3
3
  "mcpName": "dev.tokensafe/tokensafe",
4
- "version": "4.1.6",
4
+ "version": "4.1.7",
5
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": {
package/plugin.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "tokensafe",
3
3
  "displayName": "TokenSafe",
4
- "version": "4.1.6",
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",
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.6",
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.6",
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]` so passing test suites emit a single-line summary (`PASS: ...`) rather than flooding `Messages` history with hundreds of verbose log lines. Full traceback is strictly preserved on failure.
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 without breaking operators. Pass the optional `cwd` argument for test-runner commands: the guard reads `<cwd>/package.json` to identify the runner behind opaque `yarn/npm test` scripts and forces jest/vitest into run-once mode (`CI=true`, `--watch=false`, `--forceExit`) so agents never hang waiting on watch mode. | Saves **10k-50k tokens** per run |
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 |
@@ -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.
@@ -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)
@@ -593,21 +671,7 @@ class CommandSanitizer:
593
671
  if not is_build:
594
672
  return None
595
673
 
596
- # Check if `tokensafe` is available in PATH or local project bin
597
- import shutil
598
- has_tokensafe = bool(shutil.which("tokensafe"))
599
- if not has_tokensafe:
600
- for candidate in (
601
- os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "bin", "tokensafe"),
602
- os.path.expanduser("~/.tokensafe/bin/tokensafe"),
603
- os.path.expanduser("~/.local/bin/tokensafe"),
604
- "/usr/local/bin/tokensafe"
605
- ):
606
- if os.path.exists(candidate):
607
- has_tokensafe = True
608
- break
609
-
610
- if not has_tokensafe:
674
+ if not cls._is_tokensafe_available():
611
675
  return None
612
676
 
613
677
  wrapped = f"tokensafe wrap {shlex.quote(stage)}"
@@ -755,6 +819,15 @@ class CommandSanitizer:
755
819
  if line.startswith("ok \t") or line.startswith("PASS"):
756
820
  return f"PASS: {line}"
757
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
+
758
831
  # Fallback for verbose outputs: if > 12 lines, cap to first line + last line
759
832
  if len(lines) > 12:
760
833
  return f"PASS: {lines[0]} ... {lines[-1]} (exit code 0)"
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/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 via `tokensafe wrap '<command>'` or `tokensafe tests [cmd]` (clean 3-line build/pass summary, full traceback/compiler error only on failure) instead of raw verbose test crawls; never leave `vitest`/`jest` 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"
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"
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.6"
45
+ "version": "4.1.7"
46
46
  }
47
47
 
48
48
  # MCP client attribution: the initialize handshake carries clientInfo, which
@@ -180,11 +180,12 @@ 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, quiets npm/pip installs, bounds cat/curl output. Compound commands "
184
- "(a && b ; c) are optimized per stage without breaking operators. For unit-test runs prefer "
185
- "the `tests` CLI wrapper (tokensafe tests [pytest]) over raw `python3 -m unittest discover`. "
186
- "Pass cwd for test-runner commands: the guard reads <cwd>/package.json to force jest/vitest "
187
- "into run-once mode (CI=true, --watch=false, --forceExit) so agents never hang on watch mode.",
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": {
@@ -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.6"
244
+ "User-Agent": "TokenSafe-Sync/4.1.7"
245
245
  }
246
246
  if active_key:
247
247
  headers["Authorization"] = f"Bearer {active_key}"
@@ -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 == "pytest":
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
- return f"✓ {ran} — all tests passed", True
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")
@@ -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.6"
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