tokensafe 1.3.12 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -23,6 +23,7 @@
23
23
  <a href="#-1-click-universal-install">Install</a> •
24
24
  <a href="#-universal-mcp-server-configuration">MCP Setup</a> •
25
25
  <a href="#-the-breakthrough-how-it-saves-6090-tokens">How It Works</a> •
26
+ <a href="#-tokensafe-guard-proactive-agent-security--hygiene-shield">TokenSafe Guard</a> •
26
27
  <a href="#-pricing--plans">Pricing</a> •
27
28
  <a href="https://tokensafe.dev">Official Website & Docs</a>
28
29
  </p>
@@ -88,6 +89,7 @@ Traditional AI code interactions suffer from massive context bloat:
88
89
  - **Environment Overhead Auditor (`tokensafe doctor`):** Inspects active MCP servers and Antigravity skills, measuring system prompt token tax and pruning redundant tool schemas.
89
90
  - **MCP Tool Schema Bloat Guard:** Stops heavy MCP servers (50–200+ tools) from injecting 5,000–15,000 hidden schema tokens into every API turn. 1-click toggle (`tokensafe mcp disable <name>`) and real-time in-chat bloat alerts.
90
91
  - **Data Retention & Compact Rollups (`tokensafe prune` / `vacuum`):** Automated sliding-window log cleanup with lifetime metric rollups, cutting telemetry database disk footprint by up to 40%.
92
+ - **TokenSafe Guard:** Proactive agent security & hygiene shield. Blocks hardcoded secret fallbacks in `os.environ` / `process.env`, SSL/TLS bypass (`verify=False`), raw SQL injection f-strings, insecure CORS credentials, blanket `git add .` on `.env` files, and destructive shell commands (`rm -rf /`).
91
93
  - **Local Secret Redactor:** Sanitizes Stripe, AWS, JWT, and database credentials before network transmission.
92
94
  - **Output Guard & Loop Guard:** Blocks destructive full-file rewrites on files $\ge 40$ lines and halts command loops.
93
95
 
@@ -112,6 +114,7 @@ Turns out, there's a simple reason for this:
112
114
  | **Terminal Log Poisoning**<br>`npm test` or `pytest` fails and dumps 4,000 lines of stack traces and lockfile diffs. The model panics and rewrites unrelated code. | **Command Sanitizer** (`src/command_sanitizer.py`) snips the matrix down to the exact failing assertion line and call frame. | **Laser Focus.** The agent fixes the actual bug instead of hallucinating workarounds for log noise. |
113
115
  | **The 5-Attempt Doom Loop**<br>Agent tries a broken fix, fails, tries the exact same broken fix again, and oscillates until your session context limit catches fire. | **Anti-Stuck Loop Guard** (`src/loop_detector.py`) intercepts repeated tool calls and cyclic edits in flight. | **No Cascading Regressions.** The loop is halted before the agent can butcher working modules. |
114
116
  | **Vague Human Prompts**<br>*"Hey, fix the auth bug but don't break the cache or whatever."* The model takes creative liberties and breaks three other files. | **TOCP Intent Compactor** (`src/compactor.py`) distills messy instructions into explicit S-Expressions with hard constraint boundaries. | **Zero Ambiguity.** The model executes `(DEBUG auth.ts [jwt] "fix 401 token expiry")` with strict parameter bounds. |
117
+ | **Unsafe Agent Actions & Secret Leaks**<br>Agent hardcodes fallback API keys, disables SSL validation (`verify=False`), uses SQL f-strings, or runs `git add .` staging `.env` files. | **TokenSafe Guard** (`src/guard.py`) audits and blocks hazardous code edits and terminal commands before execution. | **Zero-Leak Workspace.** Hardcoded credentials, SQLi, and catastrophic deletions (`rm -rf /`) are intercepted in real time. |
115
118
 
116
119
  ---
117
120
 
@@ -170,6 +173,48 @@ How TokenSafe complements or supersedes static graph tools like **Graphify** (`g
170
173
 
171
174
  ---
172
175
 
176
+ ## 🛡️ TokenSafe Guard: Proactive Agent Security & Hygiene Shield
177
+
178
+ Autonomous AI coding agents operate with powerful tool access—executing arbitrary shell commands, modifying critical source files, and interacting with remote systems. Without proactive guardrails, models frequently introduce subtle security vulnerabilities, bypass TLS safeguards, or leak sensitive credentials directly into git repositories.
179
+
180
+ **TokenSafe Guard** (`src/guard.py`) intercepts and audits agent tool calls in real time before execution, enforcing strict code hygiene and repository safety with zero token overhead:
181
+
182
+ ### 1. Secret & Private Key Leak Prevention (Zero Hardcoded Fallbacks)
183
+ - **Live Provider Secrets**: Blocks hardcoded Stripe live keys, AWS access keys, OpenAI project keys, Anthropic tokens, and GitHub personal access tokens anywhere in code.
184
+ - **Default Fallback Hardcoding**: AI models frequently write `os.environ.get("DB_PASSWORD", "prod_secret_123")` or `process.env.JWT_SECRET || "production_secret"`. TokenSafe Guard strictly blocks non-placeholder fallbacks for sensitive environment variable names.
185
+ - **Raw Hexadecimal Private Keys**: Blocks 64-character raw hex private keys and raw PEM private key blocks assigned directly in source code.
186
+
187
+ ### 2. Insecure SSL/TLS Verification Bypass Shield
188
+ - AI models frequently add `verify=False` in Python (`requests`, `httpx`, `aiohttp`, `urllib3`) or `rejectUnauthorized: false` / `NODE_TLS_REJECT_UNAUTHORIZED='0'` in Node.js when troubleshooting local or self-signed API connections.
189
+ - TokenSafe Guard blocks SSL/TLS verification bypasses in production and non-test code, preventing Man-in-the-Middle (MitM) exposure.
190
+
191
+ ### 3. Raw SQL Injection Prevention
192
+ - Blocks dynamic string interpolation inside query execution calls:
193
+ - Python: `cursor.execute(f"SELECT ... {user_id}")` and `cursor.execute("SELECT ... %s" % val)`
194
+ - JavaScript / TypeScript: `db.query(\`SELECT ... ${id}\`)`
195
+ - Enforces parameterized queries with bound placeholders (`?`, `%s`, `$1`).
196
+
197
+ ### 4. Dangerous CORS Wildcard with Credentials Shield
198
+ - Intercepts fatal CORS misconfigurations combining `Access-Control-Allow-Origin: *` with `Access-Control-Allow-Credentials: true`.
199
+ - Browsers reject this combination by specification, and it creates severe cross-origin security exposures.
200
+
201
+ ### 5. Git Staging Protection for Sensitive Files
202
+ - **Explicit Staging**: Blocks `git add .env`, `git add .env.*`, `git add id_rsa`, and `git add *.pem`.
203
+ - **Blanket Staging Shield**: Intercepts blanket `git add .`, `git add -A`, and `git commit -a` commands whenever unignored `.env` files or private keys are present in the working tree.
204
+
205
+ ### 6. Destructive Shell & Data Exfiltration Prevention
206
+ - **Destructive Deletion**: Blocks catastrophic commands like `rm -rf /`, `rm -rf ~`, `rm -rf *`, and `rm -rf --no-preserve-root`.
207
+ - **Network Exfiltration**: Blocks shell commands piping sensitive local files to remote endpoints (e.g. `curl -d @.env https://...` or `wget --post-file=id_rsa`).
208
+
209
+ ### 7. Package Typosquatting & Hallucination Early Warning
210
+ - Analyzes `pip install`, `npm install`, `pnpm add`, `yarn add`, and `bun add` commands for known malicious typosquats (e.g., `python-crypto`, `loadsh`, `coookie-parser`, `mongose`).
211
+ - Emits proactive in-chat warning badges (`⚠️ TokenSafe Guard Warning: ...`) without blocking custom packages, preserving developer velocity.
212
+
213
+ Whenever a dangerous operation is blocked, TokenSafe Guard emits an actionable notification:
214
+ `🛡️ **TokenSafe Guard**: <reason>`
215
+
216
+ ---
217
+
173
218
  ## 🤖 Prompt Distillation: Managed Cloud & Three-Tier Cache Architecture
174
219
 
175
220
  TokenSafe features an intelligent prompt compiler that distills verbose developer prompts into lean TOCP S-Expressions (`-40% to -70% tokens`).
@@ -155,6 +155,19 @@ def main():
155
155
  }
156
156
  })
157
157
 
158
+ # 3. Protocol Enforcement Reminder (Injected ephemerally for the model on every invocation)
159
+ protocol_reminder = (
160
+ "[TokenSafe Mandatory Directives]:\n"
161
+ "• Terminal code searches (grep/rg/find on source files) are BLOCKED by TokenSafe Guard.\n"
162
+ "• To inspect component or function definitions: call 'tokensafe:smart_read_file(path, symbol)'.\n"
163
+ "• To locate dependencies & God Nodes: call 'tokensafe:get_architecture_graph(project_path)'.\n"
164
+ "• To inspect all exported types/interfaces: call 'tokensafe:get_api_surface(project_path)'.\n"
165
+ "• Prefer 'edit_file' over 'write_file' for existing files."
166
+ )
167
+ inject_steps.append({
168
+ "ephemeralMessage": protocol_reminder
169
+ })
170
+
158
171
  response = {}
159
172
  if inject_steps:
160
173
  response["injectSteps"] = inject_steps
@@ -25,6 +25,8 @@ from src.tokenizer import count_tokens
25
25
  from src.agent_firewall import AgentFirewall
26
26
  from src.diff_slicer import DiffSlicer
27
27
  from src.license_manager import LicenseManager
28
+ from src.secret_redactor import SecretRedactor
29
+ from src.guard import TokenSafeGuard
28
30
 
29
31
  def main():
30
32
  try:
@@ -66,7 +68,30 @@ def main():
66
68
 
67
69
  response = {"decision": "allow"}
68
70
 
69
- # 2. Output Guard: Block write_file on large existing files to enforce edit_file
71
+ # 2. TokenSafe Guard: Inspect file writes and edits for security violations
72
+ if tool_name in ("write_file", "edit_file"):
73
+ path = args.get("Path", "")
74
+ code_to_check = args.get("Content", "") if tool_name == "write_file" else args.get("Replacement", "")
75
+ guard_res = TokenSafeGuard.inspect_file_write(path, code_to_check)
76
+ if guard_res.blocked:
77
+ tracker.record_event(
78
+ session_id=conversation_id,
79
+ event_type=f"GUARD_{guard_res.check_name}",
80
+ original_tokens=count_tokens(code_to_check),
81
+ optimized_tokens=0,
82
+ details={
83
+ "tool": tool_name,
84
+ "target_file": os.path.basename(path) if path else "unknown",
85
+ "reason": guard_res.reason
86
+ }
87
+ )
88
+ print(json.dumps({
89
+ "decision": "deny",
90
+ "reason": f"🛡️ TokenSafe Guard: {guard_res.reason}"
91
+ }))
92
+ return
93
+
94
+ # 3. Output Guard: Block write_file on large existing files to enforce edit_file
70
95
  if tool_name == "write_file":
71
96
  path = args.get("Path", "")
72
97
  content = args.get("Content", "")
@@ -198,9 +223,26 @@ def main():
198
223
  print(json.dumps(response))
199
224
  return
200
225
 
201
- # 4. run_command Optimization (Command Sanitizer & Diff Slicer)
226
+ # 4. run_command Optimization & TokenSafe Guard
202
227
  elif tool_name == "run_command":
203
228
  cmd = args.get("CommandLine", "")
229
+ guard_res = TokenSafeGuard.inspect_command(cmd)
230
+ if guard_res.blocked:
231
+ tracker.record_event(
232
+ session_id=conversation_id,
233
+ event_type=f"GUARD_{guard_res.check_name}",
234
+ original_tokens=count_tokens(cmd),
235
+ optimized_tokens=0,
236
+ details={"cmd": cmd[:100], "reason": guard_res.reason}
237
+ )
238
+ print(json.dumps({
239
+ "decision": "deny",
240
+ "reason": f"🛡️ TokenSafe Guard: {guard_res.reason}"
241
+ }))
242
+ return
243
+ elif guard_res.warning_only:
244
+ response["reason"] = f"⚠️ TokenSafe Guard Warning: {guard_res.reason}"
245
+
204
246
  if is_quota_exceeded:
205
247
  # Free tier quota reached: pass through without AST diff slicing or savings tracking
206
248
  new_cmd, est_saved, reason = CommandSanitizer.sanitize(cmd)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tokensafe",
3
- "version": "1.3.12",
3
+ "version": "1.4.0",
4
4
  "description": "Autonomous Zero-Loss Token Economy & Context Optimizer for AI Coding Agents",
5
5
  "main": "bin/tokensafe.js",
6
6
  "bin": {
package/plugin.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "agy-token-optimizer",
3
3
  "displayName": "TokenSafe",
4
- "version": "1.3.12",
4
+ "version": "1.4.0",
5
5
  "description": "Zero-Loss Token Economy & Context Optimizer for AI Agents. Compresses prompts, slices AST/tool outputs, and prevents stuck loops.",
6
6
  "logo": "assets/logo.svg",
7
7
  "author": {
package/rules/AGENTS.md CHANGED
@@ -26,12 +26,20 @@ Execute the specified action directly based on these extracted parameters.
26
26
  4. **Dense Formatting**: Use compact bullet points and direct technical prose.
27
27
 
28
28
  ### 3. Architecture & Code Navigation Directives (Graph-Guided)
29
- 1. **Never Crawl with Raw Grep/Find**: Before executing exploratory searches or answering architecture questions, inspect `tokensafe:get_architecture_graph` or `tokensafe-out/API_SURFACE.md`. It provides project God Nodes and dependencies in < 250 tokens without file crawling.
30
- 2. **Graph-Guided File Reading**: When inspecting code implementations, call `tokensafe:smart_read_file` with the targeted `symbol`. It preserves full executable bodies for the target function and its 1-hop callees while folding inert code into signatures (-85% to -92% tokens).
31
- 3. **Bounded Reads**: Never call `read_file` without `StartLine`/`EndLine` on files > 100 lines unless inspecting a skeleton.
29
+ 1. **Zero Raw Terminal Grep/Find (Blocked)**: Strictly NEVER execute terminal `grep`, `egrep`, `ripgrep`, or `find` on source code files or directories (`src/`, `views/`, `components/`, `.ts`, `.tsx`, `.py`, `.js`). These commands are hard-blocked by TokenSafe Guard.
30
+ 2. **Mandatory Symbol & Component Inspection**: Whenever locating or reading a function, class, component, or method, ALWAYS call `tokensafe:smart_read_file` with `path` and `symbol`. It preserves the full executable target and 1-hop dependencies while folding inert code into signatures (-85% to -92% tokens).
31
+ 3. **Architecture Discovery**: Before executing multi-file exploration, ALWAYS call `tokensafe:get_architecture_graph(project_path)` to locate God Nodes and dependency topology in < 250 tokens without file crawling.
32
+ 4. **API Surface Map**: Use `tokensafe:get_api_surface(project_path)` to get all exported classes, types, and interfaces in a single markdown map.
33
+ 5. **Bounded Reads**: Never call `read_file` without `StartLine`/`EndLine` on files > 100 lines unless inspecting a skeleton.
32
34
 
33
35
  ### 4. Turn Token Savings Footer (Proof-of-Savings)
34
36
  At the end of your response for any turn where tools were executed, files were inspected, commands were sanitized, or prompts were compacted, append a compact 1-line footer:
35
37
  `⚡ **TokenSafe Turn Savings**: +<tokens> tokens saved on this turn (<breakdown>) | Cumulative Total: <total> tokens`
36
38
  Example:
37
39
  `⚡ **TokenSafe Turn Savings**: +3,520 tokens (~88%) | Cumulative Total: 3.04M tokens ($4.56)`
40
+
41
+ ### 5. Secret Leak Prevention Directive (Zero Hardcoded Fallbacks)
42
+ 1. **Never Hardcode Credential Fallbacks**: Never provide real private keys, API secrets, access tokens, or webhook secrets as default fallback arguments in `os.environ.get()`, `os.getenv()`, or `process.env`. If an environment variable is absent, raise an explicit configuration error or use an empty string / test mock. Real credentials must exist strictly in environment variables.
43
+ 2. **Leak Prevention Notification (English)**:
44
+ Whenever a tool execution, code edit, or command attempts to write or commit a hardcoded secret fallback, block it and include an explicit notification alert in your response:
45
+ `🛡️ **TokenSafe Security Guard**: Prevented secret / private key leak into git (<target_file>: <details>)`
@@ -1,87 +1,167 @@
1
1
  ---
2
2
  name: token-optimizer
3
3
  description: >-
4
- Inspect token efficiency metrics, view cost savings dashboard, test prompt compression,
5
- navigate codebases via zero-token AST architecture graphs, and operate the Token-Optimized Communication Protocol (TOCP).
4
+ MANDATORY code inspection and architecture navigation skill.
5
+ Activate whenever inspecting files, searching code, locating components/functions/classes,
6
+ reading implementations, analyzing dependencies, or navigating codebase architecture.
7
+ Replaces wasteful terminal grep/find with zero-loss AST smart slicing (-90% tokens),
8
+ extracts definitions with 1-hop dependencies, enforces security guards, and tracks token efficiency metrics.
6
9
  ---
7
10
 
8
11
  # TokenSafe Optimization & Architecture Intelligence Skill
9
12
 
10
- This skill provides autonomous AI coding assistants with deterministic, zero-token AST architecture indexing, graph-guided code slicing, command sanitization, and context optimization metrics.
13
+ TokenSafe is the zero-loss token economy, context governor, and security engine for autonomous AI coding agents.
14
+ It replaces brute-force terminal crawls (`grep`, `find`, `cat`) with deterministic AST symbol extraction,
15
+ folds multi-turn conversation history, slices verbose tool outputs, and guards against secret leaks and destructive actions.
11
16
 
12
- ## When to Activate This Skill
13
- 1. **Architecture Discovery**: Mapping new or unfamiliar codebases, finding God Nodes and key dependency hubs without LLM token burn.
14
- 2. **Graph-Guided Code Inspection**: Reading functions or classes with their 1-hop dependencies while folding inert boilerplate (-85% to -92% tokens).
15
- 3. **Telemetry & Economics**: Inspecting token savings, breakdown by optimization source, and ROI.
16
- 4. **Command & Prompt Optimization**: Sanitizing terminal output and testing TOCP compression.
17
+ ---
18
+
19
+ ## MANDATORY AGENT DIRECTIVES
20
+
21
+ 1. **ZERO RAW TERMINAL GREP / FIND (HARD-BLOCKED)**:
22
+ - Strictly NEVER run `grep`, `egrep`, `ripgrep`, or `find` in `run_command` on source code files (`.ts`, `.tsx`, `.py`, `.js`, `src/`, `views/`, `components/`).
23
+ - Raw code searches via bash burn thousands of context tokens and are blocked by **TokenSafe Guard** (`decision: deny`).
24
+
25
+ 2. **SYMBOL & COMPONENT EXTRACTION (`smart_read_file`)**:
26
+ - When locating or reading any function, component, class, or handler (e.g. `<LuckyWheelTab>`, `areSectorEqual`, `useWallet`), ALWAYS call `tokensafe:smart_read_file` with `path` and `symbol`.
27
+ - **Result**: Preserves the exact target definition and its direct 1-hop dependencies while folding surrounding inert code into 1-line signatures (-85% to -92% tokens).
28
+
29
+ 3. **ARCHITECTURE SURVEY BEFORE BROWSING (`get_architecture_graph`)**:
30
+ - Before multi-file exploration or asking where things are located, ALWAYS call `tokensafe:get_architecture_graph(project_path)`.
31
+ - **Result**: Returns top architectural God Nodes, dependency hubs, and centrality rankings in < 250 tokens without file crawling.
32
+
33
+ 4. **API SURFACE INSPECTION (`get_api_surface`)**:
34
+ - Call `tokensafe:get_api_surface(project_path)` to get all exported classes, types, interfaces, and function signatures in a single compact markdown map.
35
+
36
+ 5. **SURGICAL FILE EDITS (`edit_file`)**:
37
+ - On existing files with >= 40 lines, wholesale rewrites via `write_file` are blocked by **Output Guard**. Always use `edit_file` with precise `Target` and `Replacement` blocks.
38
+
39
+ 6. **SECRET LEAK PREVENTION (ZERO HARDCODED FALLBACKS)**:
40
+ - Never provide real private keys, API secrets, or credentials as fallback values in `os.environ.get()` or `process.env`. Real credentials must exist strictly in environment variables.
41
+
42
+ ---
17
43
 
18
44
  ## Core MCP Tools (`tokensafe`)
19
45
 
20
- | MCP Tool | Purpose | Token Cost |
46
+ All tools are exposed via Model Context Protocol (stdio JSON-RPC 2.0).
47
+
48
+ | MCP Tool | Description | Efficiency Impact |
21
49
  |---|---|---|
22
- | `tokensafe:get_architecture_graph` | Analyzes AST topology, God Nodes, and hub centrality for `project_path`. | ~150-250 tokens |
23
- | `tokensafe:get_api_surface` | Exports public signatures and types for the entire project. | ~300-600 tokens |
24
- | `tokensafe:smart_read_file` | Reads `path` focusing on `symbol` + 1-hop dependencies; folds inert code into signatures. | -85% to -92% vs raw read |
25
- | `tokensafe:sanitize_command` | Strips lockfiles, limits test/build output, and prevents context poisoning. | Saves 10k-50k tokens |
26
- | `tokensafe:slice_diff` | Slices unified git diffs, eliminates lockfiles, and minimizes hunk context lines. | -50% to -80% |
27
- | `tokensafe:compress_prompt` | Compresses verbose user instructions into lean TOCP S-expressions. | -40% to -65% |
28
- | `tokensafe:get_token_savings_metrics` | Returns total tokens saved, USD value, and breakdown by source. | ~100 tokens |
29
-
30
- ## Agent Graph-First Workflow
31
-
32
- ### 1. Zero-Token Architecture Survey
33
- Before running recursive searches or reading multi-file structures, query the architecture graph:
50
+ | `tokensafe:smart_read_file` | Graph-guided AST reader with target `symbol` body retention and 1-hop dependency inlining. | **-85% to -92%** token reduction |
51
+ | `tokensafe:get_architecture_graph` | Computes dependency topology, hub centrality, and identifies top God Nodes for `project_path`. | **~200 tokens** (replaces 50k crawl) |
52
+ | `tokensafe:get_api_surface` | Generates a compact markdown map of all exported types, interfaces, and classes. | **~500 tokens** for entire project |
53
+ | `tokensafe:sanitize_command` | Intercepts shell commands to strip lockfiles, cap unbounded git logs, and quiet test tracebacks. | Saves **10k-50k tokens** per run |
54
+ | `tokensafe:slice_diff` | Slices unified git diffs, eliminating lockfiles and minimizing hunk context lines. | **-50% to -80%** diff size |
55
+ | `tokensafe:compress_prompt` | Compresses verbose user instructions into lean TOCP S-expressions via DeepSeek/Regex. | **-40% to -65%** prompt tokens |
56
+ | `tokensafe:get_token_savings_metrics` | Returns cumulative analytics: tokens saved, context ratio, USD value, and optimization source breakdown. | Persistent SQLite analytics |
57
+
58
+ ---
59
+
60
+ ## Agent Workflows
61
+
62
+ ### 1. Architecture Exploration Workflow
34
63
  ```json
35
64
  {
36
65
  "ServerName": "tokensafe",
37
66
  "ToolName": "get_architecture_graph",
38
67
  "Arguments": {
39
- "project_path": "/absolute/path/to/project"
68
+ "project_path": "/Users/.../projects/my-app"
40
69
  }
41
70
  }
42
71
  ```
43
- * **Output**: Centrality scores, dependent counts, and identified God Nodes (e.g., `src/graph_engine.py (71 deps)`).
72
+ *Identifies core architectural hubs and dependency weights before inspecting files.*
44
73
 
45
- ### 2. Graph-Guided Symbol Inspection
46
- To read a targeted function or class without reading hundreds of lines of inert code:
74
+ ### 2. Targeted Symbol Inspection Workflow
47
75
  ```json
48
76
  {
49
77
  "ServerName": "tokensafe",
50
78
  "ToolName": "smart_read_file",
51
79
  "Arguments": {
52
- "path": "/absolute/path/to/file.py",
53
- "symbol": "TargetClassName"
80
+ "path": "/Users/.../projects/my-app/src/views/StatsView.tsx",
81
+ "symbol": "LuckyWheelTab"
54
82
  }
55
83
  }
56
84
  ```
57
- * **Output**: The target definition and its direct 1-hop callees are shown in full; all other classes/methods are folded into 1-line signatures.
85
+ *Extracts only the `LuckyWheelTab` implementation and its direct sub-components with inert code folded.*
58
86
 
59
- ### 3. Command Sanitization
60
- Before executing potentially verbose terminal commands (`git diff`, `git grep`, `pytest`, `find`):
87
+ ### 3. Public API Map Workflow
61
88
  ```json
62
89
  {
63
90
  "ServerName": "tokensafe",
64
- "ToolName": "sanitize_command",
91
+ "ToolName": "get_api_surface",
65
92
  "Arguments": {
66
- "command": "git diff HEAD~1"
93
+ "project_path": "/Users/.../projects/my-app"
67
94
  }
68
95
  }
69
96
  ```
97
+ *Returns all exported interfaces and types without reading hundreds of module files.*
98
+
99
+ ---
70
100
 
71
- ## CLI Usage
101
+ ## Security & Hygiene Engine (TokenSafe Guard)
72
102
 
73
- Developers and agents can run `tokensafe` directly from the terminal:
103
+ TokenSafe Guard automatically intercepts dangerous operations in `PreToolUse`:
104
+
105
+ | Guard Check | Monitored Operation | Action Taken |
106
+ |---|---|---|
107
+ | **RAW_CODE_SEARCH** | Terminal `grep`, `egrep`, `rg`, `find` on source code | **Blocked** (`decision: deny`), directs to `smart_read_file` |
108
+ | **SECRET_FALLBACK** | Hardcoded secrets in `os.environ.get()` / `process.env` | **Blocked** (`decision: deny`), prevents credential commit |
109
+ | **TLS_VERIFY_BYPASS** | Insecure TLS bypass (`verify=False` / `rejectUnauthorized: false`) | **Blocked** (`decision: deny`), MitM attack prevention |
110
+ | **SQL_INJECTION** | Unsafe f-string / template string interpolation in queries | **Blocked** (`decision: deny`), enforces parameterized queries |
111
+ | **GIT_SECRET_STAGING** | `git add .env` or blanket staging with unignored secrets | **Blocked** (`decision: deny`), prevents staging credentials |
112
+ | **DESTRUCTIVE_RM** | `rm -rf /`, `rm -rf ~`, `rm -rf *` | **Blocked** (`decision: deny`), prevents catastrophic deletion |
113
+ | **DATA_EXFILTRATION** | Piping `.env` or private keys to `curl`/`wget` | **Blocked** (`decision: deny`), prevents secret leakage |
114
+ | **PACKAGE_TYPOSQUAT** | Installing known typosquatted packages | **Warning** injected into turn context |
115
+
116
+ ---
117
+
118
+ ## Context Governor & History Compactor
119
+
120
+ For long-running autonomous sessions, TokenSafe actively manages context bloat:
121
+
122
+ 1. **Multi-Turn History Compaction**:
123
+ - At conversation turn >= 3, automatically compiles past turns into a lean **Consolidated State Ledger**.
124
+ - Preserves active file paths, modified symbols, and pending tasks while discarding transient tool output noise.
125
+ 2. **Subagent Deduplication Firewall**:
126
+ - Caches file reads across subagents. If subagent B attempts to read a file already inspected by subagent A, returns the cached skeleton instantly.
127
+ 3. **Loop Guard**:
128
+ - Detects repeated identical tool calls and triggers `force_ask` to prevent runaway infinite agent loops.
129
+ 4. **Output Token Guard**:
130
+ - Intercepts wholesale `write_file` calls on existing files with >= 40 lines to prevent expensive output token burn.
131
+
132
+ ---
133
+
134
+ ## CLI Reference (`tokensafe`)
135
+
136
+ Run standalone in the terminal or invoke via agent:
74
137
 
75
138
  ```bash
76
- # View terminal breakdown & recent optimizations
77
- tokensafe stats
139
+ # Telemetry & Economics
140
+ tokensafe stats # View terminal report with tokens saved & USD ROI
141
+ tokensafe html # Launch interactive Apple-style HTML dashboard
142
+ tokensafe benchmark # Run zero-loss SWE-bench benchmark suite
78
143
 
79
- # Open interactive Apple-style HTML dashboard in browser
80
- tokensafe html
144
+ # Code Intelligence & Architecture
145
+ tokensafe graph [path] # Inspect God Nodes and centrality ranking
146
+ tokensafe map [path] # Generate tokensafe-out/API_SURFACE.md
147
+ tokensafe skeleton <file> # View AST skeleton for a specific file
81
148
 
82
- # Run universal agent installer/synchronizer
83
- tokensafe install
149
+ # Multi-Agent Ecosystem Management
150
+ tokensafe install # Interactive agent installer (Cursor, Windsurf, Claude, etc.)
151
+ tokensafe install --all # Automatically configure all 9 detected agent environments
152
+ tokensafe update # One-click self-update & multi-agent re-synchronization
84
153
 
85
- # Test prompt compression
86
- tokensafe test "Refactor get_user_balance with redis caching"
154
+ # System Health & Hygiene
155
+ tokensafe doctor # Audit MCP tool overhead and token tax
156
+ tokensafe prune # Compact metrics database and prune old events
157
+ tokensafe vacuum # Reclaim SQLite database disk space
158
+ tokensafe test "<prompt>" # Test TOCP S-expression prompt compaction
87
159
  ```
160
+
161
+ ---
162
+
163
+ ## Proof-of-Savings Turn Footer
164
+
165
+ 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:
166
+ `⚡ **TokenSafe Turn Savings**: +<tokens> tokens saved on this turn (<breakdown>) | Cumulative Total: <total> tokens ($<usd>)`
167
+
package/src/guard.py ADDED
@@ -0,0 +1,385 @@
1
+ """
2
+ TokenSafe Guard: Security & Hygiene Guardian for AI Coding Assistants.
3
+ Protects local workspaces and repository integrity by intercepting dangerous operations:
4
+ 1. Secret & Private Key Leak Prevention (Zero Hardcoded Fallbacks)
5
+ 2. Insecure SSL/TLS Verification Bypass Detection (verify=False)
6
+ 3. Raw SQL Injection Prevention (String Interpolation in queries)
7
+ 4. Dangerous CORS Wildcard with Credentials Detection
8
+ 5. Git Staging Protection for Sensitive Files (.env*, *.key, *.pem)
9
+ 6. Destructive Shell Command & Unbounded Deletion Prevention (rm -rf /)
10
+ 7. Network Data Exfiltration Prevention (piping secrets to curl/wget)
11
+ 8. Package Typosquatting & Hallucination Early Warning
12
+ """
13
+
14
+ import os
15
+ import re
16
+ import fnmatch
17
+ from typing import Tuple, Optional, Dict, Any, List, NamedTuple
18
+ from src.secret_redactor import SecretRedactor
19
+
20
+ class GuardResult(NamedTuple):
21
+ blocked: bool
22
+ reason: Optional[str] = None
23
+ check_name: Optional[str] = None
24
+ warning_only: bool = False
25
+
26
+ class TokenSafeGuard:
27
+ """Security and hygiene enforcement engine for agentic tool use."""
28
+
29
+ KNOWN_TYPOSQUATS = {
30
+ "python-crypto", "requests-html5", "colorama-v2", "discord-self",
31
+ "setup-tools", "py-cord-v2", "expressjs-router", "cross-env-v2",
32
+ "loadsh", "coookie-parser", "mongose", "dot-env"
33
+ }
34
+
35
+ SENSITIVE_GIT_FILES = (
36
+ ".env", ".env.local", ".env.production", ".env.staging", ".env.development",
37
+ "id_rsa", "id_ed25519", "credentials.json", "service_account.json"
38
+ )
39
+
40
+ CODE_EXTENSIONS = (
41
+ ".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs",
42
+ ".py", ".pyw",
43
+ ".go", ".rs", ".java", ".cpp", ".cc", ".c", ".h", ".hpp",
44
+ ".php", ".rb", ".vue", ".svelte"
45
+ )
46
+
47
+ CODE_DIRS = (
48
+ "src", "lib", "app", "views", "components", "pages", "routes",
49
+ "services", "controllers", "models", "internal", "pkg", "hooks"
50
+ )
51
+
52
+ @classmethod
53
+ def is_doc_file(cls, file_path: str) -> bool:
54
+ """Determines if the targeted file is documentation or non-executable text."""
55
+ if not file_path:
56
+ return False
57
+ return file_path.lower().endswith((".md", ".markdown", ".rst", ".txt", ".json", ".yaml", ".yml"))
58
+
59
+ @classmethod
60
+ def is_test_file(cls, file_path: str) -> bool:
61
+ """Determines if the targeted file is part of a test suite or mock fixture."""
62
+ if not file_path:
63
+ return False
64
+ p = file_path.lower()
65
+ return any(part in p for part in ("test", "mock", "fixture", "spec", "__tests__"))
66
+
67
+ @classmethod
68
+ def inspect_file_write(cls, file_path: str, code_snippet: str) -> GuardResult:
69
+ """
70
+ Audits file writes and surgical code edits before applying to disk.
71
+ Returns GuardResult with blocked status and actionable explanation.
72
+ """
73
+ if not code_snippet or not isinstance(code_snippet, str):
74
+ return GuardResult(blocked=False)
75
+
76
+ is_test = cls.is_test_file(file_path)
77
+ is_doc = cls.is_doc_file(file_path)
78
+ skip_code_checks = is_test or is_doc
79
+
80
+ # 1. Secret & Private Key Fallback Guard
81
+ is_leak, leak_reason = SecretRedactor.check_secret_fallback(code_snippet, file_path=file_path)
82
+ if is_leak:
83
+ return GuardResult(
84
+ blocked=True,
85
+ check_name="SECRET_FALLBACK",
86
+ reason=f"{leak_reason} in '{os.path.basename(file_path) if file_path else 'code'}'"
87
+ )
88
+
89
+ # 2. Insecure SSL/TLS Verification Bypass Detection
90
+ if not skip_code_checks:
91
+ # Python: verify=False in requests, httpx, urllib3, aiohttp
92
+ if re.search(r"\bverify\s*=\s*False\b", code_snippet):
93
+ return GuardResult(
94
+ blocked=True,
95
+ check_name="TLS_VERIFY_BYPASS",
96
+ reason=(
97
+ f"Insecure SSL/TLS verification bypass detected ('verify=False') in "
98
+ f"'{os.path.basename(file_path) if file_path else 'code'}'. "
99
+ f"Disabling TLS certificate checks exposes connections to Man-in-the-Middle (MitM) attacks."
100
+ )
101
+ )
102
+
103
+ # Node.js: NODE_TLS_REJECT_UNAUTHORIZED = '0' or rejectUnauthorized: false
104
+ if re.search(r"""(?:NODE_TLS_REJECT_UNAUTHORIZED\s*=\s*['"]0['"]|\brejectUnauthorized\s*:\s*false\b)""", code_snippet):
105
+ return GuardResult(
106
+ blocked=True,
107
+ check_name="TLS_VERIFY_BYPASS",
108
+ reason=(
109
+ f"Insecure SSL/TLS verification bypass detected ('rejectUnauthorized: false' or 'NODE_TLS_REJECT_UNAUTHORIZED=0') in "
110
+ f"'{os.path.basename(file_path) if file_path else 'code'}'. "
111
+ f"Disabling TLS certificate validation exposes connections to Man-in-the-Middle (MitM) attacks."
112
+ )
113
+ )
114
+
115
+ # 3. Raw SQL Injection in Query Execution
116
+ if not skip_code_checks:
117
+ # Python: cursor.execute(f"...") or conn.execute(f"...")
118
+ py_fstring_sql = re.search(
119
+ r"""\b(?:cursor|conn|connection|db)\.execute\s*\(\s*f["'](?:\s*SELECT|\s*INSERT|\s*UPDATE|\s*DELETE|\s*DROP|\s*ALTER)""",
120
+ code_snippet,
121
+ re.IGNORECASE
122
+ )
123
+ if py_fstring_sql:
124
+ return GuardResult(
125
+ blocked=True,
126
+ check_name="SQL_INJECTION",
127
+ reason=(
128
+ f"Potential SQL injection detected: f-string interpolation inside query execution in "
129
+ f"'{os.path.basename(file_path) if file_path else 'code'}'. "
130
+ f"Use parameterized queries with bound placeholders ('?' or '%s') instead of dynamic string formatting."
131
+ )
132
+ )
133
+
134
+ # Python: .execute("... %s ..." % (...)) or .format(...)
135
+ py_format_sql = re.search(
136
+ r"""\b(?:cursor|conn|connection|db)\.execute\s*\(\s*["'](?:\s*SELECT|\s*INSERT|\s*UPDATE|\s*DELETE)[^"']+['"]\s*(?:%|\.format\s*\()""",
137
+ code_snippet,
138
+ re.IGNORECASE
139
+ )
140
+ if py_format_sql:
141
+ return GuardResult(
142
+ blocked=True,
143
+ check_name="SQL_INJECTION",
144
+ reason=(
145
+ f"Potential SQL injection detected: string '%'/format() interpolation inside query execution in "
146
+ f"'{os.path.basename(file_path) if file_path else 'code'}'. "
147
+ f"Use parameterized queries with bound placeholders instead of string formatting."
148
+ )
149
+ )
150
+
151
+ # JS/TS: db.query(`SELECT ... ${var}`) or pool.query(`... ${var}`)
152
+ js_template_sql = re.search(
153
+ r"""\b(?:db|pool|client|connection|knex)\.(?:query|execute|raw)\s*\(\s*`(?:\s*SELECT|\s*INSERT|\s*UPDATE|\s*DELETE|\s*DROP)[^`]*\$\{[^}]+\}""",
154
+ code_snippet,
155
+ re.IGNORECASE
156
+ )
157
+ if js_template_sql:
158
+ return GuardResult(
159
+ blocked=True,
160
+ check_name="SQL_INJECTION",
161
+ reason=(
162
+ f"Potential SQL injection detected: template literal interpolation '${{...}}' inside query execution in "
163
+ f"'{os.path.basename(file_path) if file_path else 'code'}'. "
164
+ f"Use parameterized queries with bound placeholders ('$1', '$2' or '?') instead of string template interpolation."
165
+ )
166
+ )
167
+
168
+ # 4. Dangerous CORS Wildcard with Credentials
169
+ if not skip_code_checks:
170
+ has_wildcard_origin = bool(re.search(
171
+ r"""(?:Access-Control-Allow-Origin['"]?\s*[:=,]\s*['"]\*['"]|origin\s*:\s*['"]\*['"])""",
172
+ code_snippet,
173
+ re.IGNORECASE
174
+ ))
175
+ has_credentials_true = bool(re.search(
176
+ r"""(?:Access-Control-Allow-Credentials['"]?\s*[:=,]\s*['"]?true['"]?|credentials\s*:\s*true)""",
177
+ code_snippet,
178
+ re.IGNORECASE
179
+ ))
180
+ if has_wildcard_origin and has_credentials_true:
181
+ return GuardResult(
182
+ blocked=True,
183
+ check_name="INSECURE_CORS",
184
+ reason=(
185
+ f"Insecure CORS configuration detected in '{os.path.basename(file_path) if file_path else 'code'}': "
186
+ f"'Access-Control-Allow-Origin: *' cannot be combined with 'Access-Control-Allow-Credentials: true'. "
187
+ f"Browsers reject this combination, and it poses significant cross-origin security risks. Specify explicit trusted origins."
188
+ )
189
+ )
190
+
191
+ return GuardResult(blocked=False)
192
+
193
+ @classmethod
194
+ def inspect_command(cls, command: str, cwd: str = "") -> GuardResult:
195
+ """
196
+ Audits shell and terminal commands before execution.
197
+ Returns GuardResult with blocked status or non-blocking warnings.
198
+ """
199
+ if not command or not isinstance(command, str):
200
+ return GuardResult(blocked=False)
201
+
202
+ cmd = command.strip()
203
+
204
+ # 1. Destructive Unbounded File Deletion (rm -rf / or rm -rf ~ or rm -rf *)
205
+ rm_dangerous = re.search(
206
+ r"""\brm\s+(?:-[a-zA-Z]*[rf][a-zA-Z]*\s+)+(?:/|~|\$HOME|\.\.|\.|\.\/|\*|/\*|\.\/\*)(?:\s|$|;|&|\|)""",
207
+ cmd
208
+ )
209
+ if rm_dangerous or re.search(r"""\brm\s+-[a-zA-Z]*[rf][a-zA-Z]*\s+--no-preserve-root\b""", cmd):
210
+ return GuardResult(
211
+ blocked=True,
212
+ check_name="DESTRUCTIVE_RM",
213
+ reason=(
214
+ f"Destructive unbounded file deletion blocked: '{cmd}'. "
215
+ f"Running 'rm -rf' on root, home, parent directories, or wildcards poses catastrophic data loss risk."
216
+ )
217
+ )
218
+
219
+ # 2. Git Staging Protection for Sensitive Files (.env, private keys)
220
+ # Explicit git add of sensitive file
221
+ git_add_explicit = re.search(
222
+ r"""\bgit\s+add\s+(?:.*?\s+)?(?:['"]?(?:\.env|\.env\.[a-zA-Z0-9_-]+|[^'"]*\.pem|[^'"]*\.key|id_rsa|id_ed25519|credentials\.json)['"]?)(?:\s|$|;|&|\|)""",
223
+ cmd,
224
+ re.IGNORECASE
225
+ )
226
+ if git_add_explicit:
227
+ return GuardResult(
228
+ blocked=True,
229
+ check_name="GIT_SECRET_STAGING",
230
+ reason=(
231
+ f"Blocked staging of sensitive credential file into git repository: '{cmd}'. "
232
+ f"Environment files and private keys must be added to .gitignore and never committed to source control."
233
+ )
234
+ )
235
+
236
+ # Catch blanket 'git add .' or 'git add -A' when sensitive files exist in directory
237
+ if re.search(r"""\bgit\s+(?:add\s+(?:\.|\-A|\*)|commit\s+-[a-zA-Z]*a)""", cmd):
238
+ target_dir = cwd or os.getcwd()
239
+ for root, dirs, files in os.walk(target_dir):
240
+ # Prune common heavy/inert subtrees
241
+ dirs[:] = [d for d in dirs if d not in (".git", "node_modules", ".venv", "venv", "__pycache__", "dist", "build", ".next", ".turbo")]
242
+ for f in files:
243
+ if f in cls.SENSITIVE_GIT_FILES or (f.startswith(".env") and not f.endswith(".example")):
244
+ rel_path = os.path.relpath(os.path.join(root, f), target_dir)
245
+ # Check if explicitly ignored
246
+ if not cls._is_git_ignored(os.path.join(root, f), target_dir):
247
+ return GuardResult(
248
+ blocked=True,
249
+ check_name="GIT_SECRET_STAGING",
250
+ reason=(
251
+ f"Blocked blanket git staging: '{cmd}'. "
252
+ f"Unignored sensitive file '{rel_path}' detected in working tree. "
253
+ f"Add '{rel_path}' to .gitignore or stage files explicitly to prevent credential leaks into git."
254
+ )
255
+ )
256
+
257
+ # 3. Network Data Exfiltration Prevention (piping secrets to curl/wget)
258
+ exfil_pattern = re.search(
259
+ r"""\b(?:curl|wget|nc|ncat|netcat)\b.*?(?:\$\(cat\s+[^)]*(?:\.env|id_rsa|\.key|\.pem|secret|password|token)[^)]*\)|`cat\s+[^`]*(?:\.env|id_rsa|\.key|\.pem|secret|password|token)[^`]*`|-d\s+@(?:[^\s]*(?:\.env|id_rsa|\.key|\.pem))|-F\s+[^=]*=@(?:[^\s]*(?:\.env|id_rsa|\.key|\.pem))|--post-file[=\s]+(?:[^\s]*(?:\.env|id_rsa|\.key|\.pem)))""",
260
+ cmd,
261
+ re.IGNORECASE
262
+ )
263
+ if exfil_pattern:
264
+ return GuardResult(
265
+ blocked=True,
266
+ check_name="DATA_EXFILTRATION",
267
+ reason=(
268
+ f"Blocked potential credential exfiltration via network command: '{cmd}'. "
269
+ f"Piping or posting local sensitive files (.env / private keys) to remote endpoints is prohibited."
270
+ )
271
+ )
272
+
273
+ # 4. Package Typosquatting / Hallucination Early Warning (Non-blocking warning)
274
+ pkg_install_match = re.search(
275
+ r"""\b(?:pip(?:3)?\s+install|npm\s+(?:i|install)|pnpm\s+add|yarn\s+add|bun\s+add)\s+([a-zA-Z0-9_\-\s@/]+)""",
276
+ cmd
277
+ )
278
+ if pkg_install_match:
279
+ pkg_str = pkg_install_match.group(1)
280
+ tokens = [t.strip().lower() for t in pkg_str.split() if t.strip() and not t.startswith("-")]
281
+ for tok in tokens:
282
+ if tok.startswith("@"):
283
+ # Scoped package e.g. @org/pkg or @org/pkg@1.0.0
284
+ sub = tok[1:]
285
+ base_pkg = sub.split("@")[0].strip()
286
+ else:
287
+ base_pkg = tok.split("==")[0].split("@")[0].strip()
288
+
289
+ if base_pkg in cls.KNOWN_TYPOSQUATS or f"@{base_pkg}" in cls.KNOWN_TYPOSQUATS:
290
+ return GuardResult(
291
+ blocked=False,
292
+ warning_only=True,
293
+ check_name="PACKAGE_TYPOSQUAT_WARNING",
294
+ reason=(
295
+ f"Package '{tok}' matches a known malicious typosquatting package. "
296
+ f"Verify package legitimacy before installing."
297
+ )
298
+ )
299
+
300
+ # 5. Raw Code Search Interception (Enforce TokenSafe MCP tools over terminal grep/find)
301
+ code_search_err = cls._check_raw_code_search(cmd)
302
+ if code_search_err:
303
+ return GuardResult(
304
+ blocked=True,
305
+ check_name="RAW_CODE_SEARCH",
306
+ reason=code_search_err
307
+ )
308
+
309
+ return GuardResult(blocked=False)
310
+
311
+ @classmethod
312
+ def _check_raw_code_search(cls, cmd: str) -> Optional[str]:
313
+ """
314
+ Detects unconstrained terminal code searches (grep/rg/find targeting source files).
315
+ Enforces use of TokenSafe MCP tools (smart_read_file, get_architecture_graph).
316
+ Excludes safe pipe filters (e.g., git log | grep, ps | grep, npm test | grep).
317
+ """
318
+ # Split compound commands (&&, ||, ;)
319
+ stages = [s.strip() for s in re.split(r'(?:&&|\|\||;)', cmd) if s.strip()]
320
+
321
+ for stage in stages:
322
+ pipe_parts = [p.strip() for p in stage.split('|')]
323
+
324
+ # If grep is preceded by a non-code command (ps, git log, docker, npm test), it's a pipe filter
325
+ if len(pipe_parts) > 1:
326
+ first_part = pipe_parts[0]
327
+ is_file_dump = bool(re.search(r'\b(cat|less|more)\s+[\w\.\/\-]+', first_part))
328
+ if not is_file_dump:
329
+ continue
330
+
331
+ sub_cmd = pipe_parts[-1]
332
+
333
+ # 1. Check for grep / egrep / ripgrep (rg)
334
+ grep_match = re.search(r'\b(grep|egrep|rg|ripgrep)\b', sub_cmd)
335
+ if grep_match:
336
+ has_code_ext = any(ext in sub_cmd for ext in cls.CODE_EXTENSIONS)
337
+ has_code_dir = any(re.search(rf'\b{re.escape(d)}(?:/|\b)', sub_cmd) for d in cls.CODE_DIRS)
338
+ is_recursive_all = bool(re.search(r'\b(grep|egrep)\b.*?\s-[a-zA-Z]*[rR]\b', sub_cmd)) or \
339
+ bool(re.search(r'\brg\b', sub_cmd))
340
+
341
+ if has_code_ext or has_code_dir or is_recursive_all:
342
+ return (
343
+ f"Raw terminal code search blocked: '{sub_cmd}'. "
344
+ f"TokenSafe Protocol mandates using MCP tools to prevent context window bloat:\n"
345
+ f"• To inspect definitions/symbols in a file: call 'tokensafe:smart_read_file(path, symbol)'\n"
346
+ f"• To locate God Nodes & architecture: call 'tokensafe:get_architecture_graph(project_path)'\n"
347
+ f"• To inspect project exports & types: call 'tokensafe:get_api_surface(project_path)'"
348
+ )
349
+
350
+ # 2. Check for find on source code
351
+ find_match = re.search(r'\bfind\b\s+([\w\.\/\-]+)', sub_cmd)
352
+ if find_match:
353
+ has_code_ext = any(ext in sub_cmd for ext in cls.CODE_EXTENSIONS)
354
+ has_code_dir = any(re.search(rf'\b{re.escape(d)}(?:/|\b)', sub_cmd) for d in cls.CODE_DIRS)
355
+ if has_code_ext or has_code_dir:
356
+ return (
357
+ f"Raw file crawl via 'find' blocked: '{sub_cmd}'. "
358
+ f"Use 'tokensafe:get_architecture_graph(project_path)' or "
359
+ f"'tokensafe:get_api_surface(project_path)' instead of scanning directory trees."
360
+ )
361
+
362
+ return None
363
+
364
+ @classmethod
365
+ def _is_git_ignored(cls, file_path: str, repo_root: str) -> bool:
366
+ """Checks if a file is covered by .gitignore in the repository."""
367
+ gitignore_path = os.path.join(repo_root, ".gitignore")
368
+ if not os.path.exists(gitignore_path):
369
+ return False
370
+ try:
371
+ filename = os.path.basename(file_path)
372
+ rel_path = os.path.relpath(file_path, repo_root).replace("\\", "/")
373
+ with open(gitignore_path, "r", encoding="utf-8", errors="replace") as f:
374
+ for raw_line in f:
375
+ line = raw_line.strip()
376
+ if not line or line.startswith("#"):
377
+ continue
378
+ clean_pattern = line.lstrip("/")
379
+ if fnmatch.fnmatch(filename, clean_pattern) or fnmatch.fnmatch(rel_path, clean_pattern):
380
+ return True
381
+ if clean_pattern.endswith("/") and rel_path.startswith(clean_pattern):
382
+ return True
383
+ except Exception:
384
+ pass
385
+ return False
package/src/installer.py CHANGED
@@ -32,12 +32,13 @@ PYTHON_BIN = sys.executable
32
32
 
33
33
  UNIFIED_TOKENSAFE_RULE = (
34
34
  "## TOKENSAFE GRAPH-FIRST OPTIMIZATION PROTOCOL\n"
35
- "Always prioritize `tokensafe` MCP tools over default raw file reads or high-output terminal executions to prevent context window exhaustion.\n\n"
36
- "1. **Architecture Discovery**: Always call `tokensafe:get_architecture_graph` before grep or multi-file reading. Returns project God Nodes and key dependency hubs in < 250 tokens without file crawling.\n"
37
- "2. **Graph-Guided Symbol Inspection**: When inspecting code implementations, prioritize `tokensafe:smart_read_file` with the targeted `symbol`. Returns full executable bodies for the symbol and 1-hop dependencies while folding inert code into signatures (-85% to -92% tokens).\n"
38
- "3. **No Unconstrained Shell Grep/Find**: Strictly avoid running raw recursive grep/find across projects. Use `get_architecture_graph` or `get_api_surface`.\n"
39
- "4. **Command Sanitization**: Use `sanitize_command` on high-output terminal commands (`git diff`, `pytest`, `find`, `grep`) to prevent lockfile or test log context contamination.\n"
40
- "5. **Proof-of-Savings Turn Footer (English default)**:\n"
35
+ "Always use `tokensafe` MCP tools over default raw file reads or high-output terminal executions to prevent context window exhaustion.\n\n"
36
+ "1. **Zero Raw Grep/Find (Blocked)**: Strictly NEVER execute terminal `grep`, `egrep`, `ripgrep`, or `find` on source code files or directories (`src/`, `views/`, `components/`, `.ts`, `.tsx`, `.py`, `.js`). These commands are hard-blocked by TokenSafe Guard.\n"
37
+ "2. **Mandatory Symbol & Component Inspection**: Whenever locating or reading a function, class, component, or method, ALWAYS call `tokensafe:smart_read_file` with `path` and `symbol`. It preserves the full executable target and 1-hop dependencies while folding inert code into signatures (-85% to -92% tokens).\n"
38
+ "3. **Architecture Discovery**: Always call `tokensafe:get_architecture_graph(project_path)` before exploratory multi-file reading. Returns project God Nodes and key dependency hubs in < 250 tokens without file crawling.\n"
39
+ "4. **API Surface Map**: Use `tokensafe:get_api_surface(project_path)` to get all exported classes, types, and interfaces in a single markdown map.\n"
40
+ "5. **Command Sanitization**: Use `sanitize_command` on high-output terminal commands (`git diff`, `pytest`, `find`, `grep`) to prevent lockfile or test log context contamination.\n"
41
+ "6. **Proof-of-Savings Turn Footer (English default)**:\n"
41
42
  "At the end of your response for any turn where tools were executed, files were inspected, commands were sanitized, or prompts were compacted, append a compact 1-line footer in English:\n"
42
43
  "`⚡ **TokenSafe Turn Savings**: +<tokens> tokens saved on this turn (<breakdown>) | Cumulative Total: <total> tokens ($<usd>)`\n"
43
44
  )
package/src/mcp_server.py CHANGED
@@ -8,6 +8,7 @@ import sys
8
8
  import os
9
9
  import json
10
10
  import traceback
11
+ from typing import Tuple, Optional
11
12
 
12
13
  # Ensure project root in sys.path
13
14
  BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
@@ -28,7 +29,7 @@ from src.diff_slicer import DiffSlicer
28
29
 
29
30
  SERVER_INFO = {
30
31
  "name": "tokensafe-mcp",
31
- "version": "1.3.4"
32
+ "version": "1.4.0"
32
33
  }
33
34
 
34
35
  TOOLS = [
@@ -48,11 +49,11 @@ TOOLS = [
48
49
  },
49
50
  {
50
51
  "name": "get_architecture_graph",
51
- "description": "Returns top architectural God Nodes and dependency topology for the target project.",
52
+ "description": "Returns top architectural God Nodes and dependency topology for the target project. Call this BEFORE reading files or searching.",
52
53
  "inputSchema": {
53
54
  "type": "object",
54
55
  "properties": {
55
- "project_path": {"type": "string", "description": "Optional: root directory or file path of the project"}
56
+ "project_path": {"type": "string", "description": "Absolute root path of the project directory. Highly recommended to pass explicitly."}
56
57
  }
57
58
  }
58
59
  },
@@ -62,7 +63,7 @@ TOOLS = [
62
63
  "inputSchema": {
63
64
  "type": "object",
64
65
  "properties": {
65
- "project_path": {"type": "string", "description": "Optional: root directory or file path of the project"}
66
+ "project_path": {"type": "string", "description": "Absolute root path of the project directory. Highly recommended to pass explicitly."}
66
67
  }
67
68
  }
68
69
  },
@@ -110,6 +111,48 @@ TOOLS = [
110
111
  }
111
112
  ]
112
113
 
114
+ def _resolve_project_root(args: dict) -> Tuple[Optional[str], Optional[str]]:
115
+ """
116
+ Safely resolves the target project root without falling back to system root dirs.
117
+ """
118
+ target = args.get("project_path") or args.get("root_dir") or args.get("path") or args.get("directory")
119
+ system_roots = {"/", "/Users", "/home", "/root", os.path.expanduser("~")}
120
+
121
+ if target:
122
+ target_abs = os.path.abspath(target)
123
+ if os.path.isfile(target_abs):
124
+ target_abs = os.path.dirname(target_abs)
125
+ if target_abs not in system_roots and os.path.isdir(target_abs):
126
+ return target_abs, None
127
+
128
+ # Check environment variables
129
+ for env_var in ("AGY_PROJECT_PATH", "WORKSPACE_FOLDER", "PROJECT_DIR", "PWD"):
130
+ candidate = os.environ.get(env_var)
131
+ if candidate:
132
+ cand_abs = os.path.abspath(candidate)
133
+ if cand_abs not in system_roots and os.path.isdir(cand_abs):
134
+ return cand_abs, None
135
+
136
+ # Check cwd
137
+ cwd = os.getcwd()
138
+ if cwd:
139
+ cwd_abs = os.path.abspath(cwd)
140
+ if cwd_abs not in system_roots and os.path.isdir(cwd_abs):
141
+ return cwd_abs, None
142
+
143
+ # Hint with active projects if found under ~/Documents/projects
144
+ projects_dir = os.path.expanduser("~/Documents/projects")
145
+ if os.path.isdir(projects_dir):
146
+ try:
147
+ subdirs = [d for d in os.listdir(projects_dir) if not d.startswith(".") and os.path.isdir(os.path.join(projects_dir, d))]
148
+ if subdirs:
149
+ examples = ", ".join([f"'{d}'" for d in subdirs[:4]])
150
+ return None, f"Error: Please specify 'project_path' explicitly. Available projects in ~/Documents/projects: {examples}. Example: project_path='{os.path.join(projects_dir, subdirs[0])}'"
151
+ except Exception:
152
+ pass
153
+
154
+ return None, "Error: Invalid or root project_path. Please specify an explicit 'project_path' pointing to your project directory (e.g. project_path='/path/to/project')."
155
+
113
156
  def handle_tool_call(name: str, args: dict) -> dict:
114
157
  tracker = MetricsTracker()
115
158
 
@@ -222,13 +265,11 @@ def handle_tool_call(name: str, args: dict) -> dict:
222
265
  return {"content": [{"type": "text", "text": dashboard.render_markdown()}]}
223
266
 
224
267
  elif name == "get_architecture_graph":
225
- target = args.get("project_path") or args.get("root_dir") or args.get("path") or args.get("directory") or os.getcwd()
226
- target_abs = os.path.abspath(target)
227
- system_roots = {"/", "/Users", "/home", "/root", os.path.expanduser("~")}
228
- if target_abs in system_roots:
268
+ target_abs, err = _resolve_project_root(args)
269
+ if err or not target_abs:
229
270
  return {
230
271
  "isError": True,
231
- "content": [{"type": "text", "text": "Error: Invalid or root project_path. Please specify an explicit 'project_path' pointing to your project directory."}]
272
+ "content": [{"type": "text", "text": err or "Error: Invalid project_path."}]
232
273
  }
233
274
  graph = GraphEngine.get_instance(target_abs)
234
275
  god_nodes = graph.get_god_nodes(7)
@@ -254,13 +295,11 @@ def handle_tool_call(name: str, args: dict) -> dict:
254
295
  return {"content": [{"type": "text", "text": json.dumps(payload, indent=2, ensure_ascii=False)}]}
255
296
 
256
297
  elif name == "get_api_surface":
257
- target = args.get("project_path") or args.get("root_dir") or args.get("path") or args.get("directory") or os.getcwd()
258
- target_abs = os.path.abspath(target)
259
- system_roots = {"/", "/Users", "/home", "/root", os.path.expanduser("~")}
260
- if target_abs in system_roots:
298
+ target_abs, err = _resolve_project_root(args)
299
+ if err or not target_abs:
261
300
  return {
262
301
  "isError": True,
263
- "content": [{"type": "text", "text": "Error: Invalid or root project_path. Please specify an explicit 'project_path' pointing to your project directory."}]
302
+ "content": [{"type": "text", "text": err or "Error: Invalid project_path."}]
264
303
  }
265
304
  graph = GraphEngine.get_instance(target_abs)
266
305
  surface_md = graph.generate_api_surface()
@@ -5,11 +5,17 @@ Replaces detected secrets with mock anchors to prevent leaks and save tokens.
5
5
  """
6
6
 
7
7
  import re
8
- from typing import Tuple, Dict, Any, List
8
+ from typing import Tuple, Dict, Any, List, Optional
9
9
 
10
10
  class SecretRedactor:
11
11
  """Detects and redacts high-risk secrets and credentials in text."""
12
12
 
13
+ SAFE_PLACEHOLDERS = (
14
+ "mock", "test", "dummy", "placeholder", "changeme", "example",
15
+ "your_", "fake", "sample", "none", "null", "undefined",
16
+ "localhost", "127.0.0.1", "0.0.0.0"
17
+ )
18
+
13
19
  PATTERNS: List[Tuple[str, re.Pattern, str]] = [
14
20
  # Stripe API Keys (Secret, Restricted, Webhook)
15
21
  (
@@ -132,3 +138,93 @@ class SecretRedactor:
132
138
  total += count
133
139
 
134
140
  return messages, total
141
+
142
+ @classmethod
143
+ def _is_safe_placeholder(cls, val: str) -> bool:
144
+ """Determines if a fallback value is an innocuous placeholder/mock rather than a real secret."""
145
+ if not val or len(val.strip()) == 0:
146
+ return True
147
+ v = val.strip().lower()
148
+ if any(w in v for w in cls.SAFE_PLACEHOLDERS):
149
+ return True
150
+ # Check all identical characters (e.g. "00000000000000000000000000000000...")
151
+ if len(set(v)) <= 2:
152
+ return True
153
+ # Short non-secret strings (less than 16 chars)
154
+ if len(v) < 16 and not any(v.startswith(prefix) for prefix in ("sk_", "whsec_", "ghp_", "ts_sec_", "xoxb-")):
155
+ return True
156
+ return False
157
+
158
+ @classmethod
159
+ def _is_secret_var_name(cls, name: str) -> bool:
160
+ """Checks if variable name represents a sensitive credential while ignoring public keys."""
161
+ n = name.upper()
162
+ if any(pub in n for pub in ("PUBLIC", "PUBKEY", "PUB_KEY", "_PUB", "PUB_HEX")):
163
+ return False
164
+ secret_markers = ("KEY", "SECRET", "TOKEN", "PASS", "AUTH", "CREDENTIAL", "PRIV")
165
+ return any(m in n for m in secret_markers)
166
+
167
+ @classmethod
168
+ def check_secret_fallback(cls, code_snippet: str, file_path: str = "") -> Tuple[bool, Optional[str]]:
169
+ """
170
+ Inspects code edits and file writes to detect dangerous hardcoded secrets
171
+ or private key fallbacks in environment variable loading.
172
+ Returns: (is_dangerous, reason_message)
173
+ """
174
+ if not code_snippet or not isinstance(code_snippet, str):
175
+ return False, None
176
+
177
+ is_test = bool(file_path and any(p in file_path.lower() for p in ("test", "mock", "fixture")))
178
+
179
+ # 1. Live provider keys (Stripe live, AWS, OpenAI, Anthropic, GitHub) anywhere
180
+ if re.search(r"\b(?:sk|rk)_live_[0-9a-zA-Z]{24,}\b", code_snippet):
181
+ return True, "Detected live Stripe secret key hardcoded in code"
182
+ if re.search(r"\bwhsec_[0-9a-zA-Z]{32,}\b", code_snippet):
183
+ return True, "Detected Stripe webhook signing secret hardcoded in code"
184
+ if re.search(r"\b(?:AKIA|ASIA|AROA)[A-Z0-9]{16}\b", code_snippet):
185
+ return True, "Detected live AWS access key ID hardcoded in code"
186
+ if re.search(r"\bsk-proj-[A-Za-z0-9_-]{40,}\b", code_snippet):
187
+ return True, "Detected live OpenAI project API key hardcoded in code"
188
+ if re.search(r"\bsk-ant-[A-Za-z0-9_-]{40,}\b", code_snippet):
189
+ return True, "Detected live Anthropic API key hardcoded in code"
190
+ if re.search(r"\b(?:ghp|gho|ghs|ghr)_[A-Za-z0-9]{36}\b", code_snippet):
191
+ return True, "Detected GitHub personal access token hardcoded in code"
192
+ if re.search(r"-----BEGIN (?:RSA |EC |OPENSSH |DSA )?PRIVATE KEY-----", code_snippet):
193
+ if not is_test:
194
+ return True, "Detected raw PEM private key block hardcoded in non-test source code"
195
+
196
+ # 2. Python environment variable fallback patterns: os.environ.get("...KEY|SECRET...", "val")
197
+ env_py_matches = re.finditer(
198
+ r"""os\.(?:environ\.get|getenv)\s*\(\s*['"]([^'"]+)['"]\s*,\s*['"]([^'"]+)['"]\s*\)""",
199
+ code_snippet,
200
+ re.IGNORECASE
201
+ )
202
+ for m in env_py_matches:
203
+ var_name, fallback_val = m.group(1), m.group(2)
204
+ if cls._is_secret_var_name(var_name) and not cls._is_safe_placeholder(fallback_val):
205
+ return True, f"Dangerous hardcoded fallback for sensitive environment variable '{var_name}'"
206
+
207
+ # 3. JS/TS: process.env.XYZ_KEY || "val" or ?? "val"
208
+ env_js_matches = re.finditer(
209
+ r"""process\.env\.([A-Za-z0-9_]+)\s*(?:\|\||\?\?)\s*['"]([^'"]+)['"]""",
210
+ code_snippet,
211
+ re.IGNORECASE
212
+ )
213
+ for m in env_js_matches:
214
+ var_name, fallback_val = m.group(1), m.group(2)
215
+ if cls._is_secret_var_name(var_name) and not cls._is_safe_placeholder(fallback_val):
216
+ return True, f"Dangerous hardcoded fallback for sensitive environment variable 'process.env.{var_name}'"
217
+
218
+ # 4. Raw 64-character hexadecimal private key assignments in non-test code
219
+ if not is_test:
220
+ hex_priv_match = re.search(
221
+ r"""(?:^|[\s;])(?:DEFAULT_)?(?:ED25519_|SECP256K1_|RSA_)?(?:PRIV|PRIVATE)_(?:KEY|HEX)\s*=\s*(?:os\.(?:environ\.get|getenv)\([^)]*\)\s*or\s*)?['"]([0-9a-fA-F]{64})['"]""",
222
+ code_snippet,
223
+ re.MULTILINE
224
+ )
225
+ if hex_priv_match:
226
+ val = hex_priv_match.group(1)
227
+ if not cls._is_safe_placeholder(val):
228
+ return True, "Detected raw 64-character hexadecimal private key assigned in source code"
229
+
230
+ return False, None