tokensafe 2.0.1 → 2.2.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 +184 -334
- package/bin/tokensafe.js +2 -1
- package/hooks/pre_tool_use.py +11 -6
- package/package.json +4 -3
- package/plugin.json +1 -1
- package/server.json +3 -3
- package/skills/token-optimizer/SKILL.md +16 -8
- package/src/__init__.py +1 -1
- package/src/adapter_core.py +37 -3
- package/src/cli.py +127 -1
- package/src/command_sanitizer.py +264 -120
- package/src/dashboard.py +1 -1
- package/src/diff_slicer.py +18 -2
- package/src/guard.py +3 -1
- package/src/installer.py +1 -1
- package/src/mcp_server.py +66 -3
- package/src/metrics.py +16 -1
- package/src/slicer.py +69 -3
- package/src/telemetry_sync.py +1 -1
- package/src/version_checker.py +1 -1
- package/src/weekly_digest.py +118 -42
package/bin/tokensafe.js
CHANGED
|
@@ -36,7 +36,7 @@ const firstArg = args[0] || '';
|
|
|
36
36
|
|
|
37
37
|
if (firstArg === 'help' || firstArg === '--help' || firstArg === '-h') {
|
|
38
38
|
console.log(`
|
|
39
|
-
⚡ TokenSafe -
|
|
39
|
+
⚡ TokenSafe - Local-First AI Coding Guardrails & Context Optimizer
|
|
40
40
|
Website: https://tokensafe.dev
|
|
41
41
|
|
|
42
42
|
Usage:
|
|
@@ -57,6 +57,7 @@ Commands:
|
|
|
57
57
|
tokensafe vacuum Compact SQLite metrics database storage
|
|
58
58
|
tokensafe prune Prune granular telemetry events into lifetime rollup
|
|
59
59
|
tokensafe digest Preview or send weekly team ROI digest email
|
|
60
|
+
tokensafe tests Run the unit test suite (compact failure report)
|
|
60
61
|
tokensafe activate <key> Activate commercial Solo or Team seat license key
|
|
61
62
|
tokensafe license Show current license status and active tier
|
|
62
63
|
tokensafe update One-click self-update for npm, pip & all AI agent rules
|
package/hooks/pre_tool_use.py
CHANGED
|
@@ -251,14 +251,19 @@ def main():
|
|
|
251
251
|
print(json.dumps(response))
|
|
252
252
|
return
|
|
253
253
|
|
|
254
|
-
# Check AST Diff Slicer first
|
|
254
|
+
# Check AST Diff Slicer first (per-stage rewrite of git diff stages),
|
|
255
|
+
# then run the Command Sanitizer on the result so other stages
|
|
256
|
+
# (git log, pytest, rg, ...) in the same compound command still
|
|
257
|
+
# get their rules applied.
|
|
255
258
|
diff_cmd, diff_saved, diff_reason = DiffSlicer.optimize_git_diff_command(cmd)
|
|
256
259
|
if diff_cmd:
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
260
|
+
cmd = diff_cmd
|
|
261
|
+
new_cmd, san_saved, san_reason = CommandSanitizer.sanitize(cmd)
|
|
262
|
+
if new_cmd:
|
|
263
|
+
est_saved = san_saved + (diff_saved if diff_cmd else 0)
|
|
264
|
+
reason = (f"{diff_reason}; {san_reason}" if diff_cmd else san_reason)
|
|
265
|
+
elif diff_cmd:
|
|
266
|
+
new_cmd, est_saved, reason = diff_cmd, diff_saved, diff_reason
|
|
262
267
|
|
|
263
268
|
if new_cmd and est_saved > 0:
|
|
264
269
|
response["overwrite"] = {"CommandLine": new_cmd}
|
package/package.json
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tokensafe",
|
|
3
3
|
"mcpName": "dev.tokensafe/tokensafe",
|
|
4
|
-
"version": "2.0
|
|
5
|
-
"description": "
|
|
4
|
+
"version": "2.2.0",
|
|
5
|
+
"description": "Local-first AI coding guardrails, context slicing, and team ROI telemetry for AI coding agents",
|
|
6
6
|
"main": "bin/tokensafe.js",
|
|
7
7
|
"bin": {
|
|
8
8
|
"tokensafe": "bin/tokensafe.js"
|
|
@@ -57,5 +57,6 @@
|
|
|
57
57
|
"bugs": {
|
|
58
58
|
"url": "https://github.com/NekoSin4eG/tokensafe/issues"
|
|
59
59
|
},
|
|
60
|
-
"homepage": "https://tokensafe.dev"
|
|
60
|
+
"homepage": "https://tokensafe.dev",
|
|
61
|
+
"packageManager": "yarn@1.22.22+sha512.a6b2f7906b721bba3d67d4aff083df04dad64c399707841b7acf00f6b133b7ac24255f2652fa22ae3534329dc6180534e98d17432037ff6fd140556e2bb3137e"
|
|
61
62
|
}
|
package/plugin.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "agy-token-optimizer",
|
|
3
3
|
"displayName": "TokenSafe",
|
|
4
|
-
"version": "2.0
|
|
4
|
+
"version": "2.2.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/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.0
|
|
6
|
+
"version": "2.2.0",
|
|
7
7
|
"websiteUrl": "https://tokensafe.dev",
|
|
8
8
|
"repository": {
|
|
9
9
|
"url": "https://github.com/NekoSin4eG/tokensafe",
|
|
@@ -30,7 +30,7 @@
|
|
|
30
30
|
"registryType": "npm",
|
|
31
31
|
"registryBaseUrl": "https://registry.npmjs.org",
|
|
32
32
|
"identifier": "tokensafe",
|
|
33
|
-
"version": "2.0
|
|
33
|
+
"version": "2.2.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.0
|
|
49
|
+
"version": "2.2.0",
|
|
50
50
|
"runtimeHint": "uvx",
|
|
51
51
|
"transport": {
|
|
52
52
|
"type": "stdio"
|
|
@@ -53,13 +53,13 @@ All tools are exposed via Model Context Protocol (stdio JSON-RPC 2.0).
|
|
|
53
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
54
|
| `tokensafe:get_architecture_graph` | Computes dependency topology, hub centrality, and identifies top God Nodes for `project_path`. | **~200 tokens** (replaces 50k crawl) |
|
|
55
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` |
|
|
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
57
|
| `tokensafe:slice_diff` | Slices unified git diffs, eliminating lockfiles and minimizing hunk context lines. | **-50% to -80%** diff size |
|
|
58
58
|
| `tokensafe:compress_prompt` | Compresses verbose user instructions into lean TOCP S-expressions via DeepSeek/Regex. | **-40% to -65%** prompt tokens |
|
|
59
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
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
|
|
62
|
-
| `tokensafe:get_token_savings_metrics` | Returns cumulative analytics: tokens saved, context ratio, USD value, and optimization source breakdown. | Persistent SQLite analytics |
|
|
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 |
|
|
63
63
|
|
|
64
64
|
---
|
|
65
65
|
|
|
@@ -152,7 +152,7 @@ TokenSafe Guard automatically intercepts dangerous operations in `PreToolUse`:
|
|
|
152
152
|
|
|
153
153
|
| Guard Check | Monitored Operation | Action Taken |
|
|
154
154
|
|---|---|---|
|
|
155
|
-
| **RAW_CODE_SEARCH** | Terminal `grep`, `egrep`, `rg`, `find` on source code | **Blocked** (`decision: deny`), directs to `smart_read_file` |
|
|
155
|
+
| **RAW_CODE_SEARCH** | Terminal `grep`, `egrep`, `rg`, `find` on source code | **Blocked** (`decision: deny`), directs to `scoped_search` / `smart_read_file` |
|
|
156
156
|
| **SECRET_FALLBACK** | Hardcoded secrets in `os.environ.get()` / `process.env` | **Blocked** (`decision: deny`), prevents credential commit |
|
|
157
157
|
| **TLS_VERIFY_BYPASS** | Insecure TLS bypass (`verify=False` / `rejectUnauthorized: false`) | **Blocked** (`decision: deny`), MitM attack prevention |
|
|
158
158
|
| **SQL_INJECTION** | Unsafe f-string / template string interpolation in queries | **Blocked** (`decision: deny`), enforces parameterized queries |
|
|
@@ -160,6 +160,9 @@ TokenSafe Guard automatically intercepts dangerous operations in `PreToolUse`:
|
|
|
160
160
|
| **DESTRUCTIVE_RM** | `rm -rf /`, `rm -rf ~`, `rm -rf *` | **Blocked** (`decision: deny`), prevents catastrophic deletion |
|
|
161
161
|
| **DATA_EXFILTRATION** | Piping `.env` or private keys to `curl`/`wget` | **Blocked** (`decision: deny`), prevents secret leakage |
|
|
162
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`.
|
|
163
166
|
|
|
164
167
|
---
|
|
165
168
|
|
|
@@ -185,10 +188,13 @@ For long-running autonomous sessions, TokenSafe actively manages context bloat:
|
|
|
185
188
|
Run standalone in the terminal or invoke via agent:
|
|
186
189
|
|
|
187
190
|
```bash
|
|
191
|
+
tokensafe --version # Print version and exit (no metrics side effects)
|
|
192
|
+
|
|
188
193
|
# Telemetry & Economics
|
|
189
194
|
tokensafe stats # View terminal report with tokens saved & USD ROI
|
|
190
195
|
tokensafe html # Launch interactive Apple-style HTML dashboard
|
|
191
|
-
tokensafe benchmark # Run zero-loss SWE-bench
|
|
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)
|
|
192
198
|
|
|
193
199
|
# Code Intelligence & Architecture
|
|
194
200
|
tokensafe graph [path] # Inspect God Nodes and centrality ranking
|
|
@@ -211,8 +217,10 @@ tokensafe test "<prompt>" # Test TOCP S-expression prompt compaction
|
|
|
211
217
|
|
|
212
218
|
---
|
|
213
219
|
|
|
214
|
-
## Proof-of-Savings Turn Footer
|
|
220
|
+
## Proof-of-Savings Turn Footer (always in English)
|
|
221
|
+
|
|
222
|
+
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
|
+
`⚡ **TokenSafe Turn Savings**: +<tokens> tokens saved on this turn (<breakdown>) | Cumulative Total: <total> tokens (≈$<usd> approx)`
|
|
215
224
|
|
|
216
|
-
|
|
217
|
-
`⚡ **TokenSafe Turn Savings**: +<tokens> tokens saved on this turn (<breakdown>) | Cumulative Total: <total> tokens ($<usd>)`
|
|
225
|
+
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.
|
|
218
226
|
|
package/src/__init__.py
CHANGED
package/src/adapter_core.py
CHANGED
|
@@ -2,9 +2,11 @@
|
|
|
2
2
|
Shared core for cross-agent lifecycle-hook adapters (Claude Code, Cursor, ZCode).
|
|
3
3
|
|
|
4
4
|
Design rules (see METRICS.md):
|
|
5
|
-
- Savings are only recorded for REAL reductions
|
|
6
|
-
|
|
7
|
-
|
|
5
|
+
- Savings are only recorded for REAL reductions. Blocked reads/commands never
|
|
6
|
+
reach the model, but their "would-have-been" mass is a heuristic guess, so
|
|
7
|
+
PROMPT injections and GUARD_*/COMMAND_FILTER/LOOP_GUARD events are labeled
|
|
8
|
+
estimated; events whose original/optimized tokens come from real bytes or
|
|
9
|
+
metered I/O stay measured.
|
|
8
10
|
- Adapters ALWAYS fail open: an adapter crash must never block the host agent.
|
|
9
11
|
(Cursor additionally blocks on invalid JSON, so adapters return valid
|
|
10
12
|
allow-JSON from the exception handler.)
|
|
@@ -41,6 +43,20 @@ _TLS_BYPASS_PATTERNS = [
|
|
|
41
43
|
r"curl\s+.*--insecure",
|
|
42
44
|
r"NODE_TLS_REJECT_UNAUTHORIZED\s*=\s*0",
|
|
43
45
|
r"wget\s+.*--no-check-certificate",
|
|
46
|
+
r"git\s+-c\s+[a-z.]*sslVerify\s*=\s*false",
|
|
47
|
+
r"GIT_SSL_NO_VERIFY\s*=\s*(?:true|1)",
|
|
48
|
+
]
|
|
49
|
+
# Commands that never terminate on their own — an agent burning a turn on them
|
|
50
|
+
# stalls until timeout. Intentional runs can still proceed via the "ask" path.
|
|
51
|
+
_INFINITE_PATTERNS = [
|
|
52
|
+
r"\btail\b[^|;&]*\s-f\b",
|
|
53
|
+
r"\bwatch\s+",
|
|
54
|
+
r"\bdocker\s+logs\b[^|;&]*\s(?:-f\b|--follow)",
|
|
55
|
+
r"\bkubectl\s+logs\b[^|;&]*\s-f\b",
|
|
56
|
+
r"\bdocker\s+attach\b",
|
|
57
|
+
# vitest runs an interactive watcher unless the `run` subcommand is given
|
|
58
|
+
r"\bvitest\b(?![^|;&]*\brun\b)",
|
|
59
|
+
r"\b(?:jest|vitest)\b[^|;&]*--watch\b",
|
|
44
60
|
]
|
|
45
61
|
|
|
46
62
|
# Lockfiles/junk that must never be dumped into an agent context.
|
|
@@ -128,10 +144,28 @@ def guard_command(command: str, agent: str, session_id: str = "") -> Dict[str, A
|
|
|
128
144
|
if re.search(pat, text):
|
|
129
145
|
blocked("DESTRUCTIVE", "Blocked: irreversible/destructive operation")
|
|
130
146
|
return result
|
|
147
|
+
# RAW_CODE_SEARCH (deny): recursive grep/rg/find crawls over source trees
|
|
148
|
+
# are the exact workflow the tokensafe MCP tools replace. TokenSafeGuard
|
|
149
|
+
# already enforces this on the Antigravity path (inspect_command) — share
|
|
150
|
+
# its check here so Claude Code / Cursor adapters honor the same policy
|
|
151
|
+
# with the same "use tokensafe:scoped_search" guidance. Fail-open on
|
|
152
|
+
# import problems, like every adapter guard path.
|
|
153
|
+
try:
|
|
154
|
+
from src.guard import TokenSafeGuard
|
|
155
|
+
search_err = TokenSafeGuard._check_raw_code_search(cmd)
|
|
156
|
+
except Exception:
|
|
157
|
+
search_err = None
|
|
158
|
+
if search_err:
|
|
159
|
+
blocked("RAW_CODE_SEARCH", search_err)
|
|
160
|
+
return result
|
|
131
161
|
for pat in _TLS_BYPASS_PATTERNS:
|
|
132
162
|
if re.search(pat, text):
|
|
133
163
|
blocked("TLS_VERIFY_BYPASS", "Certificate verification disabled — confirm this is intentional", decision="ask")
|
|
134
164
|
return result
|
|
165
|
+
for pat in _INFINITE_PATTERNS:
|
|
166
|
+
if re.search(pat, text):
|
|
167
|
+
blocked("INFINITE", "Command never terminates on its own (follow/streaming) — run it in the background or confirm intent", decision="ask")
|
|
168
|
+
return result
|
|
135
169
|
return result
|
|
136
170
|
|
|
137
171
|
|
package/src/cli.py
CHANGED
|
@@ -21,6 +21,77 @@ from src.dashboard import Dashboard, render_bar
|
|
|
21
21
|
from src.compactor import PromptCompactor
|
|
22
22
|
from src.tokenizer import count_tokens
|
|
23
23
|
|
|
24
|
+
def summarize_unittest_output(raw: str, full_traceback: bool = False) -> str:
|
|
25
|
+
"""Compacts `python3 -m unittest discover` output to what a developer
|
|
26
|
+
actually needs: one green line, or per-failure test name + root cause.
|
|
27
|
+
Keeps the suite run out of the context window (the raw output of a
|
|
28
|
+
300+ test run with tracebacks is thousands of tokens)."""
|
|
29
|
+
lines = raw.splitlines()
|
|
30
|
+
ran = status = ""
|
|
31
|
+
for ln in lines:
|
|
32
|
+
s = ln.strip()
|
|
33
|
+
if s.startswith("Ran ") and " test" in s:
|
|
34
|
+
ran = s
|
|
35
|
+
elif s == "OK" or s.startswith("FAILED"):
|
|
36
|
+
status = s
|
|
37
|
+
# Failure blocks: one '=' * 70 line PER failure, then the title line,
|
|
38
|
+
# a '-' * 70 rule and the traceback — each block is self-contained.
|
|
39
|
+
blocks, cur = [], None
|
|
40
|
+
for ln in lines:
|
|
41
|
+
if len(ln) >= 10 and set(ln) == {"="}:
|
|
42
|
+
if cur is not None:
|
|
43
|
+
blocks.append(cur)
|
|
44
|
+
cur = []
|
|
45
|
+
continue
|
|
46
|
+
if cur is not None:
|
|
47
|
+
cur.append(ln)
|
|
48
|
+
if cur is not None:
|
|
49
|
+
blocks.append(cur)
|
|
50
|
+
|
|
51
|
+
failures = []
|
|
52
|
+
for block in blocks:
|
|
53
|
+
title_idx = next((j for j, l in enumerate(block) if l.startswith(("FAIL: ", "ERROR: "))), None)
|
|
54
|
+
if title_idx is None:
|
|
55
|
+
continue
|
|
56
|
+
title = block[title_idx]
|
|
57
|
+
body = [l for l in block[title_idx + 1:]
|
|
58
|
+
if not (len(l) >= 10 and set(l) == {"-"})
|
|
59
|
+
and not l.strip().startswith(("Ran ", "FAILED", "OK"))]
|
|
60
|
+
kind, name = title.split(" ", 1)
|
|
61
|
+
if full_traceback:
|
|
62
|
+
detail = [l.rstrip() for l in body if l.strip()]
|
|
63
|
+
else:
|
|
64
|
+
loc = next((l.strip() for l in reversed(body) if l.strip().startswith('File "')), "")
|
|
65
|
+
cause_lines = [l.strip() for l in reversed(body)
|
|
66
|
+
if l.strip() and not l.strip().startswith('File "')
|
|
67
|
+
and not l.strip().startswith(("self.", "assert", "raise"))]
|
|
68
|
+
# assertEqual-style failures end with a diff block ('- a' / '+ b');
|
|
69
|
+
# the actual AssertionError line sits above it.
|
|
70
|
+
cause = next((l for l in cause_lines if not l.startswith(("+", "-", "?", "!"))),
|
|
71
|
+
cause_lines[0] if cause_lines else "")
|
|
72
|
+
if len(cause) > 200:
|
|
73
|
+
cause = cause[:200] + " …"
|
|
74
|
+
detail = [l for l in (loc, cause) if l]
|
|
75
|
+
failures.append((kind.rstrip(": "), name, detail))
|
|
76
|
+
|
|
77
|
+
if not ran and not failures:
|
|
78
|
+
# Crash before unittest could report (import error, bad path):
|
|
79
|
+
# fall back to the tail, which carries the exception.
|
|
80
|
+
tail = [l for l in lines if l.strip()][-15:]
|
|
81
|
+
return "\n".join(tail) if tail else "(no unittest output captured)"
|
|
82
|
+
|
|
83
|
+
if status == "OK":
|
|
84
|
+
return f"\033[32m✓ {ran} — all tests passed\033[0m"
|
|
85
|
+
|
|
86
|
+
out = [f"\033[31m✗ {ran} — {status}\033[0m"]
|
|
87
|
+
for kind, name, detail in failures:
|
|
88
|
+
out.append(f" \033[31m{kind}\033[0m {name}")
|
|
89
|
+
for d in detail:
|
|
90
|
+
out.append(f" {d}")
|
|
91
|
+
out.append("Full output: python3 -m unittest discover tests (or: tokensafe tests --traceback)")
|
|
92
|
+
return "\n".join(out)
|
|
93
|
+
|
|
94
|
+
|
|
24
95
|
def main():
|
|
25
96
|
args = sys.argv[1:]
|
|
26
97
|
command = args[0] if args else "stats"
|
|
@@ -352,6 +423,39 @@ def main():
|
|
|
352
423
|
print(f"\033[1mCompacted Tokens:\033[0m {res['compact_tokens']}")
|
|
353
424
|
print(f"\033[1mTokens Saved:\033[0m \033[32m\033[1m+{res['saved_tokens']} tokens\033[0m ({render_bar(res['reduction_pct'])})\n")
|
|
354
425
|
|
|
426
|
+
elif command in ("tests", "testsuite", "unittest"):
|
|
427
|
+
tests_dir = os.path.join(PROJECT_ROOT, "tests")
|
|
428
|
+
if not os.path.isdir(tests_dir):
|
|
429
|
+
print("No tests/ directory found — run from a repository checkout "
|
|
430
|
+
"(installed packages do not ship the unit-test suite).")
|
|
431
|
+
sys.exit(1)
|
|
432
|
+
verbose = "--verbose" in args or "-v" in args
|
|
433
|
+
full_tb = "--traceback" in args or "-tb" in args
|
|
434
|
+
launcher = next((a for a in args[1:] if not a.startswith("-")), "unittest")
|
|
435
|
+
if launcher == "unittest":
|
|
436
|
+
cmd = [sys.executable, "-m", "unittest", "discover", "tests"]
|
|
437
|
+
elif launcher == "pytest":
|
|
438
|
+
# pytest is natively compact with quiet flags; the wrapper
|
|
439
|
+
# guarantees them instead of trusting the caller.
|
|
440
|
+
cmd = [sys.executable, "-m", "pytest", "-q", "--tb=short"]
|
|
441
|
+
else:
|
|
442
|
+
print(f"Unknown test launcher '{launcher}' — supported: unittest (default), pytest.")
|
|
443
|
+
sys.exit(1)
|
|
444
|
+
print(f"\n⚡ Running the unit test suite ({launcher})...")
|
|
445
|
+
try:
|
|
446
|
+
proc = subprocess.run(cmd, cwd=PROJECT_ROOT, capture_output=True, text=True)
|
|
447
|
+
except FileNotFoundError:
|
|
448
|
+
print(f"Launcher '{launcher}' is not available — install it (e.g. pip install pytest) and retry.")
|
|
449
|
+
sys.exit(1)
|
|
450
|
+
raw = (proc.stdout or "") + (proc.stderr or "")
|
|
451
|
+
if verbose:
|
|
452
|
+
print(raw)
|
|
453
|
+
elif launcher == "pytest":
|
|
454
|
+
print(raw.rstrip() or "(no output)")
|
|
455
|
+
else:
|
|
456
|
+
print(summarize_unittest_output(raw, full_traceback=full_tb))
|
|
457
|
+
sys.exit(proc.returncode)
|
|
458
|
+
|
|
355
459
|
elif command in ("prune", "cleanup"):
|
|
356
460
|
days = None
|
|
357
461
|
max_events = None
|
|
@@ -458,8 +562,30 @@ def main():
|
|
|
458
562
|
print("Reset cancelled.")
|
|
459
563
|
|
|
460
564
|
else:
|
|
565
|
+
if command in ("--help", "-h", "help"):
|
|
566
|
+
print("TokenSafe CLI — usage: tokensafe <command> [args]\n")
|
|
567
|
+
print("Commands:")
|
|
568
|
+
print(" stats / markdown / html Savings analytics (terminal / .md report / dashboard)")
|
|
569
|
+
print(" benchmark Zero-context-loss benchmark suite (simulated SWE-bench harness)")
|
|
570
|
+
print(" graph / map / skeleton Architecture graph / API surface / AST skeleton of a file")
|
|
571
|
+
print(" test <prompt> Preview TOCP S-expression prompt compaction")
|
|
572
|
+
print(" digest [--send] [--email=...] Compile (and optionally dispatch) the weekly team digest")
|
|
573
|
+
print(" guard <command> Pre-flight safety check for a shell command")
|
|
574
|
+
print(" doctor Audit MCP tool overhead and token tax")
|
|
575
|
+
print(" tests [pytest] [--traceback] Run the unit test suite (compact failure report)")
|
|
576
|
+
print(" prune [--days N | --max N] Compact metrics database (roll old events)")
|
|
577
|
+
print(" vacuum Reclaim SQLite disk space")
|
|
578
|
+
print(" reset Reset all local token metrics")
|
|
579
|
+
print(" install | setup [--all] Configure detected agent environments")
|
|
580
|
+
print(" update | upgrade Self-update npm/PyPI package and re-sync agents")
|
|
581
|
+
print(" check-update Check for a newer published version")
|
|
582
|
+
print(" activate / license License activation and status")
|
|
583
|
+
print(" sync Sync telemetry with the cloud backend")
|
|
584
|
+
print(" providers / proxy / mcp Providers info / proxy server / MCP stdio server")
|
|
585
|
+
print(" --version Print version and exit")
|
|
586
|
+
sys.exit(0)
|
|
461
587
|
print(f"Unknown command: {command}")
|
|
462
|
-
print("Available commands: stats, sync, html, test, doctor, providers, mcp, benchmark, proxy, graph, map, vacuum, prune, digest, activate, license, markdown, setup, reset")
|
|
588
|
+
print("Available commands: stats, sync, html, test, tests, doctor, providers, mcp, benchmark, proxy, graph, map, skeleton, guard, vacuum, prune, digest, activate, license, markdown, install, setup, update, check-update, reset. Run 'tokensafe help' for details.")
|
|
463
589
|
sys.exit(1)
|
|
464
590
|
|
|
465
591
|
if __name__ == "__main__":
|