tokensafe 2.2.0 → 2.3.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.
@@ -44,125 +44,18 @@ folds multi-turn conversation history, slices verbose tool outputs, and guards a
44
44
 
45
45
  ## Core MCP Tools (`tokensafe`)
46
46
 
47
- All tools are exposed via Model Context Protocol (stdio JSON-RPC 2.0).
48
-
49
- | MCP Tool | Description | Efficiency Impact |
50
- |---|---|---|
51
- | `tokensafe:smart_read_file` | Graph-guided AST reader with target `symbol` body retention and 1-hop dependency inlining. | **-85% to -92%** token reduction |
52
- | `tokensafe:scoped_search` | Safe, token-bounded keyword, symbol, or config search across the codebase (supports `path`, 4s safety timeout, system root protection). | **-90% to -95%** vs raw grep/find |
53
- | `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` |
54
- | `tokensafe:get_architecture_graph` | Computes dependency topology, hub centrality, and identifies top God Nodes for `project_path`. | **~200 tokens** (replaces 50k crawl) |
55
- | `tokensafe:get_api_surface` | Generates a compact markdown map of all exported types, interfaces, and classes. | **~500 tokens** for entire project |
56
- | `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. | Saves **10k-50k tokens** per run |
57
- | `tokensafe:slice_diff` | Slices unified git diffs, eliminating lockfiles and minimizing hunk context lines. | **-50% to -80%** diff size |
58
- | `tokensafe:compress_prompt` | Compresses verbose user instructions into lean TOCP S-expressions via DeepSeek/Regex. | **-40% to -65%** prompt tokens |
59
- | `tokensafe:compact_conversation` | On-demand context compaction: folds a long JSONL session transcript into a lean Consolidated State Ledger (`transcript_path`, optional `invocation_num`). Call when the context window feels heavy or before a new subtask. | **-80% to -95%** history tokens |
60
- | `tokensafe:context_budget` | Context Budget HUD: estimated window usage (`model`/`window_tokens`/`session_id`) with tools/history/prompts breakdown and 50/80/95% thresholds. Call before deciding to compact. | Floor estimate, always labeled estimated |
61
- | `tokensafe:guard_inspect` | Pre-flight security & hygiene audit: denies literal secrets/destructive commands in shell lines (secrets, TLS, SQLi, raw grep); advisory for never-terminating streams (`tail -f`, `watch`, `docker attach`) and TLS bypasses. | **Zero-Risk** pre-flight gate |
62
- | `tokensafe:get_token_savings_metrics` | Returns cumulative analytics: tokens saved (measured/estimated split), context ratio, ≈USD value (derived), and optimization source breakdown. | Persistent SQLite analytics |
47
+ The full tool table with efficiency impact, JSON workflow examples, the Guard check matrix, and the CLI reference live in `references/` — read only the file you need:
63
48
 
64
- ---
65
-
66
- ## Agent Workflows
67
-
68
- ### 1. Architecture Exploration Workflow
69
- ```json
70
- {
71
- "ServerName": "tokensafe",
72
- "ToolName": "get_architecture_graph",
73
- "Arguments": {
74
- "project_path": "/Users/.../projects/my-app"
75
- }
76
- }
77
- ```
78
- *Identifies core architectural hubs and dependency weights before inspecting files.*
79
-
80
- ### 2. Scoped Code & Config Search Workflow
81
- ```json
82
- {
83
- "ServerName": "tokensafe",
84
- "ToolName": "scoped_search",
85
- "Arguments": {
86
- "query": "HARDCODED_VERSION",
87
- "path": "/Users/.../projects/my-app/src",
88
- "scope": "code"
89
- }
90
- }
91
- ```
92
- *Locates exact occurrences with file and line references in < 100 tokens. Always pass explicit `path` or `project_path` (auto-guarded against system roots with 4s safety timeout).*
93
-
94
- ### 2b. Directory Navigation Workflow (`list_dir`)
95
- ```json
96
- {
97
- "ServerName": "tokensafe",
98
- "ToolName": "list_dir",
99
- "Arguments": {
100
- "path": "/Users/.../projects/my-app/src",
101
- "depth": 2
102
- }
103
- }
104
- ```
105
- *Renders a clean directory tree without permissions, timestamps, lockfiles, or heavy directories (`node_modules`, `.git`, `dist`).*
106
-
107
- ### 3. Targeted Symbol Inspection Workflow
108
- ```json
109
- {
110
- "ServerName": "tokensafe",
111
- "ToolName": "smart_read_file",
112
- "Arguments": {
113
- "path": "/Users/.../projects/my-app/src/views/StatsView.tsx",
114
- "symbol": "LuckyWheelTab",
115
- "include_deps": false
116
- }
117
- }
118
- ```
119
- *Extracts only the targeted `LuckyWheelTab` implementation with inert code and docstrings folded. Omit `include_deps` or set `true` to also inline 1-hop internal dependencies.*
120
-
121
- ### 3. Public API Map Workflow
122
- ```json
123
- {
124
- "ServerName": "tokensafe",
125
- "ToolName": "get_api_surface",
126
- "Arguments": {
127
- "project_path": "/Users/.../projects/my-app"
128
- }
129
- }
130
- ```
131
- *Returns all exported interfaces and types without reading hundreds of module files.*
132
-
133
- ### 4. Pre-flight Security & Hygiene Audit
134
- ```json
135
- {
136
- "ServerName": "tokensafe",
137
- "ToolName": "guard_inspect",
138
- "Arguments": {
139
- "command": "git add .env",
140
- "code": "const key = process.env.JWT_SECRET || 'hardcoded_secret';",
141
- "file_path": "src/auth.ts"
142
- }
143
- }
144
- ```
145
- *Validates commands and code snippets before execution; returns structured pass/block verdict with check_name.*
146
-
147
- ---
49
+ - [`references/mcp-tools.md`](references/mcp-tools.md) — Core MCP Tools table + Agent Workflow JSON examples
50
+ - [`references/guard-checks.md`](references/guard-checks.md) — Security & Hygiene Guard check matrix (deny/ask per operation)
51
+ - [`references/cli-reference.md`](references/cli-reference.md) — `tokensafe` CLI command reference
148
52
 
149
- ## Security & Hygiene Engine (TokenSafe Guard)
53
+ Quick pointers:
150
54
 
151
- TokenSafe Guard automatically intercepts dangerous operations in `PreToolUse`:
152
-
153
- | Guard Check | Monitored Operation | Action Taken |
154
- |---|---|---|
155
- | **RAW_CODE_SEARCH** | Terminal `grep`, `egrep`, `rg`, `find` on source code | **Blocked** (`decision: deny`), directs to `scoped_search` / `smart_read_file` |
156
- | **SECRET_FALLBACK** | Hardcoded secrets in `os.environ.get()` / `process.env` | **Blocked** (`decision: deny`), prevents credential commit |
157
- | **TLS_VERIFY_BYPASS** | Insecure TLS bypass (`verify=False` / `rejectUnauthorized: false`) | **Blocked** (`decision: deny`), MitM attack prevention |
158
- | **SQL_INJECTION** | Unsafe f-string / template string interpolation in queries | **Blocked** (`decision: deny`), enforces parameterized queries |
159
- | **GIT_SECRET_STAGING** | `git add .env` or blanket staging with unignored secrets | **Blocked** (`decision: deny`), prevents staging credentials |
160
- | **DESTRUCTIVE_RM** | `rm -rf /`, `rm -rf ~`, `rm -rf *` | **Blocked** (`decision: deny`), prevents catastrophic deletion |
161
- | **DATA_EXFILTRATION** | Piping `.env` or private keys to `curl`/`wget` | **Blocked** (`decision: deny`), prevents secret leakage |
162
- | **PACKAGE_TYPOSQUAT** | Installing known typosquatted packages | **Warning** injected into turn context |
163
- | **INFINITE_STREAM** (adapters) | Never-terminating commands: `tail -f`, `watch`, `docker attach`, `docker/kubectl logs -f`, `vitest` (watch by default — use `vitest run`), `jest`/`vitest --watch` | **Asked** (`decision: ask`) — intentional runs proceed via confirmation |
164
-
165
- Adapter-level checks (Claude Code / Cursor / ZCode hooks) classify command-level TLS bypass (`curl -k`, `git -c http.sslVerify=false`, `GIT_SSL_NO_VERIFY=1`) and infinite streams as `ask`, and hard-deny raw recursive code search (`grep -rn src/`, `rg`, `find` over source trees) as `RAW_CODE_SEARCH` with a redirect to `tokensafe:scoped_search` — TokenSafe Guard's code-level checks above remain `deny`.
55
+ - Search: `tokensafe:scoped_search(query, scope)` — never raw grep.
56
+ - Inspect: `tokensafe:smart_read_file(path, symbol)` — definition + 1-hop deps.
57
+ - Navigate: `tokensafe:get_architecture_graph(project_path)` / `tokensafe:get_api_surface(project_path)`.
58
+ - Context: `tokensafe:compact_conversation(transcript_path)` / `tokensafe:context_budget`.
166
59
 
167
60
  ---
168
61
 
@@ -183,44 +76,9 @@ For long-running autonomous sessions, TokenSafe actively manages context bloat:
183
76
 
184
77
  ---
185
78
 
186
- ## CLI Reference (`tokensafe`)
187
-
188
- Run standalone in the terminal or invoke via agent:
189
-
190
- ```bash
191
- tokensafe --version # Print version and exit (no metrics side effects)
192
-
193
- # Telemetry & Economics
194
- tokensafe stats # View terminal report with tokens saved & USD ROI
195
- tokensafe html # Launch interactive Apple-style HTML dashboard
196
- tokensafe benchmark # Run the zero-context-loss benchmark suite (simulated SWE-bench harness; see BENCHMARK_REPORT.md)
197
- tokensafe tests [pytest] # Run the unit test suite (compact failure report; --traceback for full stacks)
198
-
199
- # Code Intelligence & Architecture
200
- tokensafe graph [path] # Inspect God Nodes and centrality ranking
201
- tokensafe map [path] # Generate tokensafe-out/API_SURFACE.md
202
- tokensafe skeleton <file> # View AST skeleton for a specific file
203
-
204
- # Multi-Agent Ecosystem Management
205
- tokensafe install # Interactive agent installer (Cursor, Windsurf, Claude, etc.)
206
- tokensafe install --all # Automatically configure all 9 detected agent environments
207
- tokensafe update # One-click self-update & multi-agent re-synchronization
208
-
209
- # System Health & Hygiene
210
- tokensafe guard "<command>" # Pre-flight check command safety (rm, secrets, grep)
211
- tokensafe guard audit [path] # Recursively audit project files for security violations
212
- tokensafe doctor # Audit MCP tool overhead and token tax
213
- tokensafe prune # Compact metrics database and prune old events
214
- tokensafe vacuum # Reclaim SQLite database disk space
215
- tokensafe test "<prompt>" # Test TOCP S-expression prompt compaction
216
- ```
217
-
218
- ---
219
-
220
79
  ## Proof-of-Savings Turn Footer (always in English)
221
80
 
222
81
  At the end of any response where tools were executed, files were inspected, commands were sanitized, or prompts were compacted, append a compact 1-line footer in English:
223
82
  `⚡ **TokenSafe Turn Savings**: +<tokens> tokens saved on this turn (<breakdown>) | Cumulative Total: <total> tokens (≈$<usd> approx)`
224
83
 
225
84
  The USD figure is **derived** (tokens × $1.5/M blended rate) — an approximation for planning, never a bill. Cumulative analytics distinguish `measured` (metered I/O delta) from `estimated` (counterfactual baseline) savings — see METRICS.md.
226
-
@@ -0,0 +1,31 @@
1
+ # CLI Reference (`tokensafe`)
2
+
3
+ Run standalone in the terminal or invoke via agent:
4
+
5
+ ```bash
6
+ tokensafe --version # Print version and exit (no metrics side effects)
7
+
8
+ # Telemetry & Economics
9
+ tokensafe stats # View terminal report with tokens saved & USD ROI
10
+ tokensafe html # Launch interactive Apple-style HTML dashboard
11
+ tokensafe benchmark # Run the zero-context-loss benchmark suite (simulated SWE-bench harness; see BENCHMARK_REPORT.md)
12
+ tokensafe tests [pytest] # Run the unit test suite (compact failure report; --traceback for full stacks)
13
+
14
+ # Code Intelligence & Architecture
15
+ tokensafe graph [path] # Inspect God Nodes and centrality ranking
16
+ tokensafe map [path] # Generate tokensafe-out/API_SURFACE.md
17
+ tokensafe skeleton <file> # View AST skeleton for a specific file
18
+
19
+ # Multi-Agent Ecosystem Management
20
+ tokensafe install # Interactive agent installer (Cursor, Windsurf, Claude, etc.)
21
+ tokensafe install --all # Automatically configure all 9 detected agent environments
22
+ tokensafe update # One-click self-update & multi-agent re-synchronization
23
+
24
+ # System Health & Hygiene
25
+ tokensafe guard "<command>" # Pre-flight check command safety (rm, secrets, grep)
26
+ tokensafe guard audit [path] # Recursively audit project files for security violations
27
+ tokensafe doctor # Audit MCP tool overhead and token tax
28
+ tokensafe prune # Compact metrics database and prune old events
29
+ tokensafe vacuum # Reclaim SQLite database disk space
30
+ tokensafe test "<prompt>" # Test TOCP S-expression prompt compaction
31
+ ```
@@ -0,0 +1,17 @@
1
+ # Security & Hygiene Engine (TokenSafe Guard)
2
+
3
+ TokenSafe Guard automatically intercepts dangerous operations in `PreToolUse`:
4
+
5
+ | Guard Check | Monitored Operation | Action Taken |
6
+ |---|---|---|
7
+ | **RAW_CODE_SEARCH** | Terminal `grep`, `egrep`, `rg`, `find` on source code | **Blocked** (`decision: deny`), directs to `scoped_search` / `smart_read_file` |
8
+ | **SECRET_FALLBACK** | Hardcoded secrets in `os.environ.get()` / `process.env` | **Blocked** (`decision: deny`), prevents credential commit |
9
+ | **TLS_VERIFY_BYPASS** | Insecure TLS bypass (`verify=False` / `rejectUnauthorized: false`) | **Blocked** (`decision: deny`), MitM attack prevention |
10
+ | **SQL_INJECTION** | Unsafe f-string / template string interpolation in queries | **Blocked** (`decision: deny`), enforces parameterized queries |
11
+ | **GIT_SECRET_STAGING** | `git add .env` or blanket staging with unignored secrets | **Blocked** (`decision: deny`), prevents staging credentials |
12
+ | **DESTRUCTIVE_RM** | `rm -rf /`, `rm -rf ~`, `rm -rf *` | **Blocked** (`decision: deny`), prevents catastrophic deletion |
13
+ | **DATA_EXFILTRATION** | Piping `.env` or private keys to `curl`/`wget` | **Blocked** (`decision: deny`), prevents secret leakage |
14
+ | **PACKAGE_TYPOSQUAT** | Installing known typosquatted packages | **Warning** injected into turn context |
15
+ | **INFINITE_STREAM** (adapters) | Never-terminating commands: `tail -f`, `watch`, `docker attach`, `docker/kubectl logs -f`, `vitest` (watch by default — use `vitest run`), `jest`/`vitest --watch` | **Asked** (`decision: ask`) — intentional runs proceed via confirmation |
16
+
17
+ Adapter-level checks (Claude Code / Cursor / ZCode hooks) classify command-level TLS bypass (`curl -k`, `git -c http.sslVerify=false`, `GIT_SSL_NO_VERIFY=1`) and infinite streams as `ask`, and hard-deny raw recursive code search (`grep -rn src/`, `rg`, `find` over source trees) as `RAW_CODE_SEARCH` with a redirect to `tokensafe:scoped_search` — TokenSafe Guard's code-level checks above remain `deny`.
@@ -0,0 +1,101 @@
1
+ # Core MCP Tools Reference (`tokensafe`)
2
+
3
+ All tools are exposed via Model Context Protocol (stdio JSON-RPC 2.0).
4
+
5
+ | MCP Tool | Description | Efficiency Impact |
6
+ |---|---|---|
7
+ | `tokensafe:smart_read_file` | Graph-guided AST reader with target `symbol` body retention and 1-hop dependency inlining. | **-85% to -92%** token reduction |
8
+ | `tokensafe:scoped_search` | Safe, token-bounded keyword, symbol, or config search across the codebase (supports `path`, 4s safety timeout, system root protection). | **-90% to -95%** vs raw grep/find |
9
+ | `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` |
10
+ | `tokensafe:get_architecture_graph` | Computes dependency topology, hub centrality, and identifies top God Nodes for `project_path`. | **~200 tokens** (replaces 50k crawl) |
11
+ | `tokensafe:get_api_surface` | Generates a compact markdown map of all exported types, interfaces, and classes. | **~500 tokens** for entire project |
12
+ | `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 |
13
+ | `tokensafe:slice_diff` | Slices unified git diffs, eliminating lockfiles and minimizing hunk context lines. | **-50% to -80%** diff size |
14
+ | `tokensafe:compress_prompt` | Compresses verbose user instructions into lean TOCP S-expressions via DeepSeek/Regex. | **-40% to -65%** prompt tokens |
15
+ | `tokensafe:compact_conversation` | On-demand context compaction: folds a long JSONL session transcript into a lean Consolidated State Ledger (`transcript_path`, optional `invocation_num`). Call when the context window feels heavy or before a new subtask. | **-80% to -95%** history tokens |
16
+ | `tokensafe:context_budget` | Context Budget HUD: estimated window usage (`model`/`window_tokens`/`session_id`) with tools/history/prompts breakdown and 50/80/95% thresholds. Call before deciding to compact. | Floor estimate, always labeled estimated |
17
+ | `tokensafe:guard_inspect` | Pre-flight security & hygiene audit: denies literal secrets/destructive commands in shell lines (secrets, TLS, SQLi, raw grep); advisory for never-terminating streams (`tail -f`, `watch`, `docker attach`) and TLS bypasses. | **Zero-Risk** pre-flight gate |
18
+ | `tokensafe:get_token_savings_metrics` | Returns cumulative analytics: tokens saved (measured/estimated split), context ratio, ≈USD value (derived), and optimization source breakdown. | Persistent SQLite analytics |
19
+
20
+ ---
21
+
22
+ ## Agent Workflows
23
+
24
+ ### 1. Architecture Exploration Workflow
25
+ ```json
26
+ {
27
+ "ServerName": "tokensafe",
28
+ "ToolName": "get_architecture_graph",
29
+ "Arguments": {
30
+ "project_path": "/Users/.../projects/my-app"
31
+ }
32
+ }
33
+ ```
34
+ *Identifies core architectural hubs and dependency weights before inspecting files.*
35
+
36
+ ### 2. Scoped Code & Config Search Workflow
37
+ ```json
38
+ {
39
+ "ServerName": "tokensafe",
40
+ "ToolName": "scoped_search",
41
+ "Arguments": {
42
+ "query": "HARDCODED_VERSION",
43
+ "path": "/Users/.../projects/my-app/src",
44
+ "scope": "code"
45
+ }
46
+ }
47
+ ```
48
+ *Locates exact occurrences with file and line references in < 100 tokens. Always pass explicit `path` or `project_path` (auto-guarded against system roots with 4s safety timeout).*
49
+
50
+ ### 2b. Directory Navigation Workflow (`list_dir`)
51
+ ```json
52
+ {
53
+ "ServerName": "tokensafe",
54
+ "ToolName": "list_dir",
55
+ "Arguments": {
56
+ "path": "/Users/.../projects/my-app/src",
57
+ "depth": 2
58
+ }
59
+ }
60
+ ```
61
+ *Renders a clean directory tree without permissions, timestamps, lockfiles, or heavy directories (`node_modules`, `.git`, `dist`).*
62
+
63
+ ### 3. Targeted Symbol Inspection Workflow
64
+ ```json
65
+ {
66
+ "ServerName": "tokensafe",
67
+ "ToolName": "smart_read_file",
68
+ "Arguments": {
69
+ "path": "/Users/.../projects/my-app/src/views/StatsView.tsx",
70
+ "symbol": "LuckyWheelTab",
71
+ "include_deps": false
72
+ }
73
+ }
74
+ ```
75
+ *Extracts only the targeted `LuckyWheelTab` implementation with inert code and docstrings folded. Omit `include_deps` or set `true` to also inline 1-hop internal dependencies.*
76
+
77
+ ### 3. Public API Map Workflow
78
+ ```json
79
+ {
80
+ "ServerName": "tokensafe",
81
+ "ToolName": "get_api_surface",
82
+ "Arguments": {
83
+ "project_path": "/Users/.../projects/my-app"
84
+ }
85
+ }
86
+ ```
87
+ *Returns all exported interfaces and types without reading hundreds of module files.*
88
+
89
+ ### 4. Pre-flight Security & Hygiene Audit
90
+ ```json
91
+ {
92
+ "ServerName": "tokensafe",
93
+ "ToolName": "guard_inspect",
94
+ "Arguments": {
95
+ "command": "git add .env",
96
+ "code": "const key = process.env.JWT_SECRET || 'hardcoded_secret';",
97
+ "file_path": "src/auth.ts"
98
+ }
99
+ }
100
+ ```
101
+ *Validates commands and code snippets before execution; returns structured pass/block verdict with check_name.*
@@ -22,6 +22,19 @@ PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
22
22
  if PROJECT_ROOT not in sys.path:
23
23
  sys.path.insert(0, PROJECT_ROOT)
24
24
 
25
+ # One-shot session directives, injected once per session by every agent's
26
+ # SessionStart surface (Antigravity hooks/session_start.py as a persistent
27
+ # systemMessage, Claude Code as hookSpecificOutput.additionalContext).
28
+ TOKENSAFE_DIRECTIVES = (
29
+ "[TokenSafe Mandatory Directives]:\n"
30
+ "• Terminal code searches (grep/rg/find on source files) are BLOCKED by TokenSafe Guard.\n"
31
+ "• To search keywords, symbols, or configs: call 'tokensafe:scoped_search(query, scope)'.\n"
32
+ "• To inspect component or function definitions: call 'tokensafe:smart_read_file(path, symbol)'.\n"
33
+ "• To locate dependencies & God Nodes: call 'tokensafe:get_architecture_graph(project_path)'.\n"
34
+ "• To inspect all exported types/interfaces: call 'tokensafe:get_api_surface(project_path)'.\n"
35
+ "• Prefer 'edit_file' over 'write_file' for existing files."
36
+ )
37
+
25
38
  # High-precision deny patterns: secrets and irreversible destruction only.
26
39
  _SECRET_PATTERNS = [
27
40
  r"sk_live_[0-9a-zA-Z]{10,}",
package/src/cli.py CHANGED
@@ -124,8 +124,9 @@ def main():
124
124
  print(dashboard.render_terminal())
125
125
 
126
126
  elif command in ("html", "web"):
127
+ from src.paths import resolve_data_dir
127
128
  html_content = dashboard.render_html()
128
- out_path = os.path.join(PROJECT_ROOT, "data", "dashboard.html")
129
+ out_path = os.path.join(resolve_data_dir(), "dashboard.html")
129
130
  os.makedirs(os.path.dirname(out_path), exist_ok=True)
130
131
  with open(out_path, "w", encoding="utf-8") as f:
131
132
  f.write(html_content)
@@ -138,10 +139,11 @@ def main():
138
139
 
139
140
  elif command in ("benchmark", "bench"):
140
141
  from src.benchmark import BenchmarkSuite
142
+ from src.paths import resolve_data_dir
141
143
  print("\n⚡ Running Zero-Loss SWE-bench Benchmark Suite across real-world scenarios...")
142
144
  data = BenchmarkSuite.run_all()
143
145
  print(BenchmarkSuite.render_report(data))
144
- out_md = os.path.join(PROJECT_ROOT, "data", "BENCHMARK_REPORT.md")
146
+ out_md = os.path.join(resolve_data_dir(), "BENCHMARK_REPORT.md")
145
147
  BenchmarkSuite.export_markdown_report(data, out_md)
146
148
  print(f"📊 Publication-ready markdown report saved to: {out_md}\n")
147
149
 
@@ -156,7 +158,12 @@ def main():
156
158
  print(f" {status} \033[1m{r['name']:<28}\033[0m: {r['message']}")
157
159
  print(f"\n\033[32m✔ Universal project rules injected into: {', '.join(res['project_rules'])}\033[0m\n")
158
160
  elif "--project" in args:
159
- res = AgentInstaller.install_project(os.getcwd())
161
+ agents_plugin = None
162
+ if "--agents-plugin" in args:
163
+ idx = args.index("--agents-plugin")
164
+ if idx + 1 < len(args):
165
+ agents_plugin = args[idx + 1]
166
+ res = AgentInstaller.install_project(os.getcwd(), agents_plugin_path=agents_plugin)
160
167
  print(f"\n\033[32m✔ TokenSafe rules injected into project: {', '.join(res['created_rules'])}\033[0m\n")
161
168
  else:
162
169
  AgentInstaller.run_interactive()
@@ -538,7 +545,8 @@ def main():
538
545
 
539
546
  print(WeeklyDigestGenerator.render_email_text(stats))
540
547
 
541
- out_html = os.path.join(PROJECT_ROOT, "data", "weekly_digest_preview.html")
548
+ from src.paths import resolve_data_dir
549
+ out_html = os.path.join(resolve_data_dir(), "weekly_digest_preview.html")
542
550
  os.makedirs(os.path.dirname(out_html), exist_ok=True)
543
551
  with open(out_html, "w", encoding="utf-8") as f:
544
552
  f.write(WeeklyDigestGenerator.render_email_html(stats))
@@ -9,12 +9,28 @@ so rewrites never leak pathspecs into an unrelated stage (e.g. lockfile
9
9
  excludes landing on `npm test` after `git diff && npm test`).
10
10
  """
11
11
 
12
+ import json
13
+ import os
12
14
  import re
13
15
  from typing import Tuple, Dict, Any, List, Optional
14
16
 
15
17
  class CommandSanitizer:
16
18
  """Optimizes terminal command lines to eliminate token waste."""
17
19
 
20
+ # Test-runner guard: spots jest/vitest/package-manager test stages so they
21
+ # can be forced into run-once mode (a watch-mode command never exits, and
22
+ # an agent blocked on its completion waits forever)
23
+ _TOKENSAFE_TESTS_RE = re.compile(r"\btokensafe\s+tests?\b")
24
+ _VITEST_RE = re.compile(r"^\s*(?:[A-Za-z_]\w*=\S*\s+)*(?:sudo\s+)?(?:npx\s+|yarn\s+|pnpm\s+|bunx\s+)?vitest(?:\s|$)")
25
+ _JEST_RE = re.compile(r"^\s*(?:[A-Za-z_]\w*=\S*\s+)*(?:sudo\s+)?(?:npx\s+|yarn\s+|pnpm\s+|bunx\s+)?jest(?:\s|$)")
26
+ _JEST_SCRIPT_RE = re.compile(r"\b(?:react-scripts|craco)\s+test\b")
27
+ _PKG_MANAGER_TEST_RE = re.compile(r"\b(?:yarn|npm|pnpm|bun)\s+(?:run\s+)?test\b")
28
+ # Jest-only flags positively fingerprint jest behind an opaque test script
29
+ _JEST_FINGERPRINT_RE = re.compile(r"--watchAll|--detectOpenHandles|--testPathPattern|--testMatch|--runInBand")
30
+ _BARE_WATCH_RE = re.compile(r"\s--watch(?=[\s]|$)")
31
+ _NPM_TEST_RE = re.compile(r"\bnpm\s+(?:run\s+)?test[\w:./-]*")
32
+ _CD_RE = re.compile(r'^\s*cd\s+(["\']?)(.+?)\1\s*$')
33
+
18
34
  # Lockfiles and binary patterns that should never be dumped in git diffs or searches
19
35
  LOCKFILE_EXCLUDES = [
20
36
  "':!package-lock.json'",
@@ -151,7 +167,7 @@ class CommandSanitizer:
151
167
  return bool(re.search(r"(^|\s)[0-9&]*>{1,2}", stage))
152
168
 
153
169
  @classmethod
154
- def _optimize_stage(cls, stage: str) -> Optional[Tuple[str, int, str, Optional[Tuple[str, int]]]]:
170
+ def _optimize_stage(cls, stage: str, cwd: Optional[str] = None) -> Optional[Tuple[str, int, str, Optional[Tuple[str, int]]]]:
155
171
  """
156
172
  Applies one rewrite rule to a single stage.
157
173
  Returns (new_stage, est_saved, reason, cap_spec) or None.
@@ -190,6 +206,12 @@ class CommandSanitizer:
190
206
  if not has_tb:
191
207
  return f"{stage} -q --tb=short", 800, "Applied short traceback to pytest", None
192
208
 
209
+ # test runners: agents block on these in the background; watch mode or
210
+ # an unclosed jest handle means the process never exits (infinite wait)
211
+ guard = cls._optimize_test_stage(stage, cwd)
212
+ if guard:
213
+ return guard
214
+
193
215
  # find: prune unbounded recursion
194
216
  if re.search(r"\bfind\s+(\.|\/|\w+)\s*$", stage) or re.search(r"\bfind\s+\.\s+-name\b", stage):
195
217
  if "node_modules" not in stage and ".git" not in stage:
@@ -274,11 +296,132 @@ class CommandSanitizer:
274
296
  return None
275
297
 
276
298
  @classmethod
277
- def sanitize(cls, command: str) -> Tuple[Optional[str], int, str]:
299
+ def _optimize_test_stage(cls, stage: str, cwd: Optional[str] = None) -> Optional[Tuple[str, int, str, None]]:
300
+ """
301
+ Forces run-once mode on JS test-runner stages. Agents launch these in
302
+ the background and block until process exit; watch mode or an unclosed
303
+ jest handle ("Jest did not exit one second after the test run has
304
+ completed") means the process never terminates and the agent waits
305
+ forever. The guard:
306
+ - normalizes bare --watch / --watchAll to =false for jest-family,
307
+ - rewrites bare `vitest` to `vitest run` (--watch=false is unreliable),
308
+ - appends --forceExit for jest-family so open handles cannot stall exit,
309
+ - inserts ` -- ` after `npm test` so args reach the runner (npm
310
+ silently swallows them otherwise, leaving default watch mode on),
311
+ - prepends CI=true as a run-once fallback for opaque package scripts
312
+ (CRA and vitest both gate watch mode on the CI variable).
313
+ An opaque `yarn/npm test` script is classified via a jest-only flag
314
+ fingerprint (--watchAll, --detectOpenHandles...) when present; without
315
+ one, `cwd` unlocks a package.json peek at scripts.test ("react-scripts
316
+ test" -> script-jest, "vitest" -> script-vitest). No cwd or an
317
+ unrecognized script falls back to the conservative generic treatment.
318
+ """
319
+ if cls._TOKENSAFE_TESTS_RE.search(stage):
320
+ return None
321
+ if cls._VITEST_RE.match(stage):
322
+ runner = "vitest"
323
+ elif cls._JEST_RE.match(stage) or cls._JEST_SCRIPT_RE.search(stage):
324
+ runner = "jest"
325
+ elif cls._PKG_MANAGER_TEST_RE.search(stage):
326
+ if cls._JEST_FINGERPRINT_RE.search(stage):
327
+ runner = "jest"
328
+ else:
329
+ script_runner = cls._peek_test_script_runner(cwd)
330
+ runner = {"jest": "script-jest", "vitest": "script-vitest"}.get(script_runner, "generic")
331
+ else:
332
+ return None
333
+
334
+ new_stage = stage
335
+ reasons: List[str] = []
336
+ saved = 0
337
+
338
+ if runner in ("vitest", "script-vitest"):
339
+ if cls._BARE_WATCH_RE.search(new_stage):
340
+ new_stage = cls._BARE_WATCH_RE.sub("", new_stage)
341
+ reasons.append("Dropped bare --watch from vitest command")
342
+ saved += 300
343
+ if runner == "vitest" and not re.search(r"\bvitest\s+run\b", new_stage):
344
+ new_stage = re.sub(r"\bvitest\b", "vitest run", new_stage, count=1)
345
+ reasons.append("Rewrote vitest to one-shot `vitest run`")
346
+ saved += 400
347
+ elif runner in ("jest", "script-jest"):
348
+ if cls._BARE_WATCH_RE.search(new_stage):
349
+ new_stage = cls._BARE_WATCH_RE.sub(" --watch=false", new_stage)
350
+ reasons.append("Normalized bare --watch to --watch=false")
351
+ saved += 400
352
+ if re.search(r"\s--watchAll(?=[\s]|$)", new_stage):
353
+ new_stage = re.sub(r"\s--watchAll(?=[\s]|$)", " --watchAll=false", new_stage)
354
+ reasons.append("Normalized bare --watchAll to --watchAll=false")
355
+ saved += 400
356
+ if runner == "script-jest" and "--watch=false" not in new_stage:
357
+ # A script like "jest --watch" can bake watch mode in; jest's
358
+ # yargs parser takes the last flag, so this one wins over it
359
+ new_stage += " --watch=false"
360
+ reasons.append("Appended --watch=false (package.json script may bake watch mode in)")
361
+ saved += 300
362
+ if "--forceExit" not in new_stage:
363
+ new_stage += " --forceExit"
364
+ reasons.append("Appended --forceExit so jest exits despite open handles")
365
+ saved += 800
366
+
367
+ # npm silently swallows args without ` -- `: in `npm test --watchAll=false`
368
+ # the flag never reaches jest, which then stays on its default watch mode
369
+ npm_match = cls._NPM_TEST_RE.search(new_stage)
370
+ if npm_match and " -- " not in new_stage and new_stage[npm_match.end():].strip():
371
+ new_stage = new_stage[:npm_match.end()] + " -- " + new_stage[npm_match.end():].lstrip()
372
+ reasons.append("Inserted ` -- ` so npm forwards args to the test runner")
373
+ saved += 600
374
+
375
+ if not re.search(r"\bCI=", new_stage):
376
+ new_stage = f"CI=true {new_stage}"
377
+ saved += 300
378
+ if runner == "generic":
379
+ reasons.append("Prepended CI=true so an unknown test runner stays in run-once mode")
380
+ else:
381
+ reasons.append("Prepended CI=true for run-once mode")
382
+
383
+ if not reasons:
384
+ return None
385
+ return new_stage, saved, "; ".join(reasons), None
386
+
387
+ @classmethod
388
+ def _peek_test_script_runner(cls, cwd: Optional[str]) -> Optional[str]:
389
+ """
390
+ Classifies the runner behind an opaque package.json test script
391
+ (e.g. "test": "react-scripts test" -> "jest"). Returns "jest",
392
+ "vitest", or None when cwd is unknown, package.json is missing or
393
+ unreadable, or the script is an unrecognized runner — callers then
394
+ fall back to the conservative generic treatment.
395
+ """
396
+ if not cwd:
397
+ return None
398
+ try:
399
+ with open(os.path.join(cwd, "package.json"), "r", encoding="utf-8") as fh:
400
+ data = json.load(fh)
401
+ except (OSError, ValueError):
402
+ return None
403
+ if not isinstance(data, dict):
404
+ return None
405
+ scripts = data.get("scripts")
406
+ script = scripts.get("test") if isinstance(scripts, dict) else None
407
+ if not isinstance(script, str):
408
+ return None
409
+ if re.search(r"\bvitest\b", script):
410
+ return "vitest"
411
+ if re.search(r"\bjest\b", script) or cls._JEST_SCRIPT_RE.search(script):
412
+ return "jest"
413
+ return None
414
+
415
+ @classmethod
416
+ def sanitize(cls, command: str, cwd: Optional[str] = None) -> Tuple[Optional[str], int, str]:
278
417
  """
279
418
  Analyzes a shell command stage by stage. If any stage creates massive
280
419
  token waste, returns (rewritten_command, est_tokens_saved, reason).
281
420
  If no change is needed, returns (None, 0, "").
421
+ `cwd` is the working directory the command will run in; when provided,
422
+ the test-runner guard may read <cwd>/package.json to identify the
423
+ runner behind an opaque test script. A `cd` stage updates that
424
+ directory for the stages that follow (cd app && yarn test ...).
282
425
  """
283
426
  if not command or not command.strip():
284
427
  return None, 0, ""
@@ -288,9 +431,18 @@ class CommandSanitizer:
288
431
  total_saved = 0
289
432
  reasons: List[str] = []
290
433
  cap_spec: Optional[Tuple[str, int]] = None
434
+ current_dir = os.path.abspath(os.path.expanduser(cwd)) if cwd else None
291
435
 
292
436
  for i, (op, stage) in enumerate(pairs):
293
- res = cls._optimize_stage(stage)
437
+ cd_match = cls._CD_RE.match(stage)
438
+ if cd_match:
439
+ target = os.path.expanduser(cd_match.group(2).strip())
440
+ if target and target != "-":
441
+ base = current_dir or os.getcwd()
442
+ current_dir = os.path.normpath(
443
+ target if os.path.isabs(target) else os.path.join(base, target)
444
+ )
445
+ res = cls._optimize_stage(stage, current_dir)
294
446
  if not res:
295
447
  continue
296
448
  new_stage, saved, reason, rule_cap = res
package/src/compactor.py CHANGED
@@ -268,7 +268,6 @@ class PromptCompactor:
268
268
  (re.compile(r"\b(mysql)\b", re.I), "mysql"),
269
269
  (re.compile(r"\b(prisma|призма)\b", re.I), "prisma"),
270
270
  (re.compile(r"\b(docker|докер)\b", re.I), "docker"),
271
- (re.compile(r"\b(bunny|банни)\b", re.I), "bunny"),
272
271
  (re.compile(r"\b(jwt|токен\w*|auth|авторизац\w*|autenticaci[oó]n|authentification|token)\b|(认证|認証)", re.I), "jwt"),
273
272
  (re.compile(r"\b(oauth)\b", re.I), "oauth"),
274
273
  (re.compile(r"\b(zero_alloc|без\s+аллокаций|sin\s+asignaciones|ohne\s+allokation)\b", re.I), "zero_alloc"),
@@ -12,6 +12,8 @@ from collections import OrderedDict
12
12
  from datetime import datetime
13
13
  from typing import Optional, Dict, Any
14
14
 
15
+ from src.paths import resolve_data_dir
16
+
15
17
  class DistillationCache:
16
18
  """Thread-safe two-tier cache (In-Memory LRU + Persistent SQLite)."""
17
19
 
@@ -39,8 +41,7 @@ class DistillationCache:
39
41
  if cls._db_path:
40
42
  return cls._db_path
41
43
 
42
- base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
43
- data_dir = os.environ.get("TOKENSAFE_DATA_DIR", os.path.join(base_dir, "data"))
44
+ data_dir = resolve_data_dir()
44
45
  os.makedirs(data_dir, exist_ok=True)
45
46
  cls._db_path = os.path.join(data_dir, "metrics.db")
46
47
  return cls._db_path