tokensafe 2.2.1 → 2.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/server.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "name": "dev.tokensafe/tokensafe",
4
4
  "title": "TokenSafe",
5
5
  "description": "Cut AI coding agent token usage up to 90% via AST slicing, dependency graphs & security guards.",
6
- "version": "2.2.1",
6
+ "version": "2.4.0",
7
7
  "websiteUrl": "https://tokensafe.dev",
8
8
  "repository": {
9
9
  "url": "https://github.com/tokensafe-dev/tokensafe",
@@ -30,7 +30,7 @@
30
30
  "registryType": "npm",
31
31
  "registryBaseUrl": "https://registry.npmjs.org",
32
32
  "identifier": "tokensafe",
33
- "version": "2.2.1",
33
+ "version": "2.4.0",
34
34
  "runtimeHint": "npx",
35
35
  "transport": {
36
36
  "type": "stdio"
@@ -46,7 +46,7 @@
46
46
  "registryType": "pypi",
47
47
  "registryBaseUrl": "https://pypi.org",
48
48
  "identifier": "tokensafe",
49
- "version": "2.2.1",
49
+ "version": "2.4.0",
50
50
  "runtimeHint": "uvx",
51
51
  "transport": {
52
52
  "type": "stdio"
@@ -58,5 +58,25 @@
58
58
  }
59
59
  ]
60
60
  }
61
+ ],
62
+ "remotes": [
63
+ {
64
+ "type": "streamable-http",
65
+ "url": "https://api.tokensafe.dev/mcp",
66
+ "headers": [
67
+ {
68
+ "name": "Authorization",
69
+ "value": "Bearer {tokensafe_license_key}",
70
+ "isSecret": true,
71
+ "variables": {
72
+ "tokensafe_license_key": {
73
+ "description": "TokenSafe license key (TS1./TS2.) from tokensafe.dev. Optional: public tools (stats, docs, setup) work without it.",
74
+ "isSecret": true,
75
+ "required": false
76
+ }
77
+ }
78
+ }
79
+ ]
80
+ }
61
81
  ]
62
82
  }
@@ -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
@@ -32,7 +32,8 @@ def summarize_unittest_output(raw: str, full_traceback: bool = False) -> str:
32
32
  s = ln.strip()
33
33
  if s.startswith("Ran ") and " test" in s:
34
34
  ran = s
35
- elif s == "OK" or s.startswith("FAILED"):
35
+ elif s.startswith("OK") or s.startswith("FAILED"):
36
+ # "OK (skipped=N)" must count as success too, not just bare "OK".
36
37
  status = s
37
38
  # Failure blocks: one '=' * 70 line PER failure, then the title line,
38
39
  # a '-' * 70 rule and the traceback — each block is self-contained.
@@ -80,7 +81,7 @@ def summarize_unittest_output(raw: str, full_traceback: bool = False) -> str:
80
81
  tail = [l for l in lines if l.strip()][-15:]
81
82
  return "\n".join(tail) if tail else "(no unittest output captured)"
82
83
 
83
- if status == "OK":
84
+ if status.startswith("OK"):
84
85
  return f"\033[32m✓ {ran} — all tests passed\033[0m"
85
86
 
86
87
  out = [f"\033[31m✗ {ran} — {status}\033[0m"]
@@ -124,8 +125,9 @@ def main():
124
125
  print(dashboard.render_terminal())
125
126
 
126
127
  elif command in ("html", "web"):
128
+ from src.paths import resolve_data_dir
127
129
  html_content = dashboard.render_html()
128
- out_path = os.path.join(PROJECT_ROOT, "data", "dashboard.html")
130
+ out_path = os.path.join(resolve_data_dir(), "dashboard.html")
129
131
  os.makedirs(os.path.dirname(out_path), exist_ok=True)
130
132
  with open(out_path, "w", encoding="utf-8") as f:
131
133
  f.write(html_content)
@@ -138,10 +140,11 @@ def main():
138
140
 
139
141
  elif command in ("benchmark", "bench"):
140
142
  from src.benchmark import BenchmarkSuite
143
+ from src.paths import resolve_data_dir
141
144
  print("\n⚡ Running Zero-Loss SWE-bench Benchmark Suite across real-world scenarios...")
142
145
  data = BenchmarkSuite.run_all()
143
146
  print(BenchmarkSuite.render_report(data))
144
- out_md = os.path.join(PROJECT_ROOT, "data", "BENCHMARK_REPORT.md")
147
+ out_md = os.path.join(resolve_data_dir(), "BENCHMARK_REPORT.md")
145
148
  BenchmarkSuite.export_markdown_report(data, out_md)
146
149
  print(f"📊 Publication-ready markdown report saved to: {out_md}\n")
147
150
 
@@ -156,7 +159,12 @@ def main():
156
159
  print(f" {status} \033[1m{r['name']:<28}\033[0m: {r['message']}")
157
160
  print(f"\n\033[32m✔ Universal project rules injected into: {', '.join(res['project_rules'])}\033[0m\n")
158
161
  elif "--project" in args:
159
- res = AgentInstaller.install_project(os.getcwd())
162
+ agents_plugin = None
163
+ if "--agents-plugin" in args:
164
+ idx = args.index("--agents-plugin")
165
+ if idx + 1 < len(args):
166
+ agents_plugin = args[idx + 1]
167
+ res = AgentInstaller.install_project(os.getcwd(), agents_plugin_path=agents_plugin)
160
168
  print(f"\n\033[32m✔ TokenSafe rules injected into project: {', '.join(res['created_rules'])}\033[0m\n")
161
169
  else:
162
170
  AgentInstaller.run_interactive()
@@ -538,7 +546,8 @@ def main():
538
546
 
539
547
  print(WeeklyDigestGenerator.render_email_text(stats))
540
548
 
541
- out_html = os.path.join(PROJECT_ROOT, "data", "weekly_digest_preview.html")
549
+ from src.paths import resolve_data_dir
550
+ out_html = os.path.join(resolve_data_dir(), "weekly_digest_preview.html")
542
551
  os.makedirs(os.path.dirname(out_html), exist_ok=True)
543
552
  with open(out_html, "w", encoding="utf-8") as f:
544
553
  f.write(WeeklyDigestGenerator.render_email_html(stats))