token-pilot 0.19.2 → 0.23.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.
Files changed (96) hide show
  1. package/.claude-plugin/hooks/hooks.json +30 -0
  2. package/.claude-plugin/plugin.json +2 -2
  3. package/CHANGELOG.md +165 -0
  4. package/README.md +194 -313
  5. package/dist/agents/tp-audit-scanner.md +49 -0
  6. package/dist/agents/tp-commit-writer.md +41 -0
  7. package/dist/agents/tp-dead-code-finder.md +43 -0
  8. package/dist/agents/tp-debugger.md +45 -0
  9. package/dist/agents/tp-history-explorer.md +43 -0
  10. package/dist/agents/tp-impact-analyzer.md +44 -0
  11. package/dist/agents/tp-migration-scout.md +43 -0
  12. package/dist/agents/tp-onboard.md +40 -0
  13. package/dist/agents/tp-pr-reviewer.md +41 -0
  14. package/dist/agents/tp-refactor-planner.md +42 -0
  15. package/dist/agents/tp-run.md +48 -0
  16. package/dist/agents/tp-session-restorer.md +47 -0
  17. package/dist/agents/tp-test-triage.md +40 -0
  18. package/dist/agents/tp-test-writer.md +46 -0
  19. package/dist/cli/agent-frontmatter.d.ts +48 -0
  20. package/dist/cli/agent-frontmatter.js +189 -0
  21. package/dist/cli/bless-agents.d.ts +65 -0
  22. package/dist/cli/bless-agents.js +307 -0
  23. package/dist/cli/claudeignore.d.ts +33 -0
  24. package/dist/cli/claudeignore.js +88 -0
  25. package/dist/cli/claudemd-hygiene.d.ts +26 -0
  26. package/dist/cli/claudemd-hygiene.js +43 -0
  27. package/dist/cli/doctor-drift.d.ts +31 -0
  28. package/dist/cli/doctor-drift.js +130 -0
  29. package/dist/cli/doctor-env-check.d.ts +25 -0
  30. package/dist/cli/doctor-env-check.js +91 -0
  31. package/dist/cli/install-agents.d.ts +108 -0
  32. package/dist/cli/install-agents.js +402 -0
  33. package/dist/cli/save-doc.d.ts +42 -0
  34. package/dist/cli/save-doc.js +145 -0
  35. package/dist/cli/scan-agents.d.ts +46 -0
  36. package/dist/cli/scan-agents.js +227 -0
  37. package/dist/cli/stats.d.ts +36 -0
  38. package/dist/cli/stats.js +131 -0
  39. package/dist/cli/typo-guard.d.ts +27 -0
  40. package/dist/cli/typo-guard.js +119 -0
  41. package/dist/cli/unbless-agents.d.ts +33 -0
  42. package/dist/cli/unbless-agents.js +85 -0
  43. package/dist/cli/uninstall-agents.d.ts +36 -0
  44. package/dist/cli/uninstall-agents.js +117 -0
  45. package/dist/config/defaults.d.ts +1 -1
  46. package/dist/config/defaults.js +14 -8
  47. package/dist/config/loader.d.ts +1 -1
  48. package/dist/config/loader.js +105 -11
  49. package/dist/core/context-registry.d.ts +16 -1
  50. package/dist/core/context-registry.js +60 -28
  51. package/dist/core/event-log.d.ts +79 -0
  52. package/dist/core/event-log.js +190 -0
  53. package/dist/core/session-registry.d.ts +43 -0
  54. package/dist/core/session-registry.js +113 -0
  55. package/dist/core/session-savings.d.ts +19 -0
  56. package/dist/core/session-savings.js +60 -0
  57. package/dist/handlers/session-budget.d.ts +32 -0
  58. package/dist/handlers/session-budget.js +61 -0
  59. package/dist/handlers/session-snapshot-persist.d.ts +22 -0
  60. package/dist/handlers/session-snapshot-persist.js +76 -0
  61. package/dist/hooks/adaptive-threshold.d.ts +27 -0
  62. package/dist/hooks/adaptive-threshold.js +46 -0
  63. package/dist/hooks/format-deny-message.d.ts +21 -0
  64. package/dist/hooks/format-deny-message.js +147 -0
  65. package/dist/hooks/installer.js +130 -31
  66. package/dist/hooks/path-safety.d.ts +16 -0
  67. package/dist/hooks/path-safety.js +34 -0
  68. package/dist/hooks/post-bash.d.ts +46 -0
  69. package/dist/hooks/post-bash.js +77 -0
  70. package/dist/hooks/post-task.d.ts +67 -0
  71. package/dist/hooks/post-task.js +136 -0
  72. package/dist/hooks/session-start.d.ts +45 -0
  73. package/dist/hooks/session-start.js +179 -0
  74. package/dist/hooks/summary-ast-index.d.ts +28 -0
  75. package/dist/hooks/summary-ast-index.js +122 -0
  76. package/dist/hooks/summary-head-tail.d.ts +15 -0
  77. package/dist/hooks/summary-head-tail.js +78 -0
  78. package/dist/hooks/summary-pipeline.d.ts +35 -0
  79. package/dist/hooks/summary-pipeline.js +63 -0
  80. package/dist/hooks/summary-regex.d.ts +14 -0
  81. package/dist/hooks/summary-regex.js +130 -0
  82. package/dist/hooks/summary-types.d.ts +29 -0
  83. package/dist/hooks/summary-types.js +9 -0
  84. package/dist/index.d.ts +15 -3
  85. package/dist/index.js +538 -149
  86. package/dist/integration/context-mode-detector.d.ts +7 -1
  87. package/dist/integration/context-mode-detector.js +51 -15
  88. package/dist/server/tool-definitions.d.ts +149 -0
  89. package/dist/server/tool-definitions.js +424 -202
  90. package/dist/server.d.ts +1 -1
  91. package/dist/server.js +456 -179
  92. package/dist/templates/agent-builder.d.ts +49 -0
  93. package/dist/templates/agent-builder.js +104 -0
  94. package/dist/types.d.ts +38 -4
  95. package/package.json +4 -2
  96. package/skills/stats/SKILL.md +13 -2
package/README.md CHANGED
@@ -1,8 +1,12 @@
1
1
  # Token Pilot
2
2
 
3
- MCP server that reduces token consumption in AI coding assistants by **up to 90%** via AST-aware lazy file reading.
3
+ **Token-efficient AI coding, enforced.** Cuts context consumption in AI coding assistants by up to **90%** without changing the way you work.
4
4
 
5
- Instead of dumping entire files into the LLM context, Token Pilot returns structural overviews (classes, functions, signatures, line ranges) and lets the AI load only the specific symbols it needs.
5
+ Three layers, each useful on its own, stronger together:
6
+
7
+ 1. **MCP tools** — structural reads (`smart_read`, `read_symbol`, `read_for_edit`, …). Ask for an outline or load one function by name instead of the whole file.
8
+ 2. **Read hook** — intercepts large raw `Read` calls and answers with a structural summary in the denial reason itself. Works for every agent, including ones that only have basic tools.
9
+ 3. **`tp-*` subagents** — Claude Code delegates with MCP-first behaviour and tight response budgets. Tier 1 workhorses (`tp-run`, `tp-onboard`, `tp-pr-reviewer`, `tp-impact-analyzer`, `tp-refactor-planner`, `tp-test-triage`) plus Tier 2 specialists (`tp-debugger`, `tp-migration-scout`, `tp-test-writer`, `tp-dead-code-finder`, `tp-commit-writer`).
6
10
 
7
11
  ## How It Works
8
12
 
@@ -13,11 +17,11 @@ Token Pilot: smart_read("user-service.ts") → 15-line outline → ~200 tok
13
17
  After edit: read_diff("user-service.ts") → ~20 tokens
14
18
  ```
15
19
 
16
- **Up to 90% reduction** on large files. Files under 200 lines are returned in full automatically (zero overhead for small files).
20
+ Files under 200 lines are returned in full (zero overhead for small files).
17
21
 
18
- ### Benchmarks (real data)
22
+ ### Benchmarks
19
23
 
20
- Measured on public open-source repos using the regex fallback parser (no ast-index binary). Files ≥50 lines only:
24
+ Measured on public open-source repos. Files ≥50 lines only:
21
25
 
22
26
  | Repo | Files | Raw Tokens | Outline Tokens | Savings |
23
27
  |------|------:|----------:|--------------:|--------:|
@@ -27,408 +31,285 @@ Measured on public open-source repos using the regex fallback parser (no ast-ind
27
31
  | [flask](https://github.com/pallets/flask) (Python) | 20 | 78,236 | 7,418 | **91%** |
28
32
  | **Total** | **104** | **244,743** | **19,764** | **92%** |
29
33
 
30
- > This measures `smart_read` structural outline savings only. Real sessions also benefit from session cache, dedup reminders, `read_symbol` targeted loading, and `read_for_edit` minimal context.
31
- >
32
- > Run the benchmark yourself: `npx tsx scripts/benchmark.ts`
33
-
34
- ## Why This Approach Works
35
-
36
- The biggest source of token waste in AI coding sessions isn't verbose prompts — it's **redundant context**. Every time a model re-reads a file, re-sends conversation history, or loads code it doesn't need, you pay for tokens that add no value.
37
-
38
- Token Pilot attacks this at three levels:
39
-
40
- 1. **Symbol-first reading** — load outlines instead of full files, drill into specific functions on demand. This alone saves 60-90% on most reads.
41
- 2. **Context budget control** — `max_tokens` parameter on `smart_read` auto-downgrades output (full → outline → compact) to fit within a token budget per step.
42
- 3. **Session state management** — `session_snapshot` captures session state as a compact markdown block (<200 tokens), enabling clean context compaction without losing track of what you're doing.
43
-
44
- These aren't theoretical gains. In real sessions, the combination of structural reading + targeted symbol access + session snapshots consistently reduces token usage by 80-90% compared to raw file reads.
45
-
46
- ## Installation
34
+ > Measures `smart_read` outline savings only. Real sessions additionally benefit from session cache, `read_symbol` targeted loading, and `read_for_edit` minimal edit context. Reproduce: `npx tsx scripts/benchmark.ts`.
47
35
 
48
- ### Quick Start (recommended)
49
-
50
- One command creates `.mcp.json` with token-pilot + context-mode:
36
+ ## Quick Start
51
37
 
52
38
  ```bash
53
39
  npx -y token-pilot init
54
40
  ```
55
41
 
56
- Safe to run in any project — if `.mcp.json` already exists, only adds missing servers without overwriting existing config.
42
+ This does two things:
57
43
 
58
- This generates:
44
+ 1. Creates (or merges into) `.mcp.json` with `token-pilot` + [`context-mode`](https://github.com/mksglu/claude-context-mode).
45
+ 2. If you're on a TTY, asks whether to install the `tp-*` subagents now — pick `user` (available in every project) or `project` scope.
59
46
 
60
- ```json
61
- {
62
- "mcpServers": {
63
- "token-pilot": { "command": "npx", "args": ["-y", "token-pilot"] },
64
- "context-mode": { "command": "npx", "args": ["-y", "claude-context-mode"] }
65
- }
66
- }
67
- ```
47
+ Restart your AI assistant to activate. The Read hook auto-installs the first time `token-pilot` starts inside Claude Code. Works with **Claude Code, Cursor, Codex, Antigravity, Cline**, and any MCP-compatible client.
68
48
 
69
- **That's it.** Restart your AI assistant. Both packages are downloaded automatically, ast-index binary is fetched on first run. No Rust, no Cargo, no manual setup.
49
+ <details>
50
+ <summary>Manual install (other MCP clients, from source, scripted CI)</summary>
70
51
 
71
- ### Manual Setup
72
-
73
- Add to your `.mcp.json` (project-level or `~/.mcp.json` for global):
52
+ Add to your `.mcp.json`:
74
53
 
75
54
  ```json
76
55
  {
77
56
  "mcpServers": {
78
- "token-pilot": {
79
- "command": "npx",
80
- "args": ["-y", "token-pilot"]
81
- }
57
+ "token-pilot": { "command": "npx", "args": ["-y", "token-pilot"] }
82
58
  }
83
59
  }
84
60
  ```
85
61
 
86
- Works with: **Claude Code**, **Cursor**, **Codex**, **Antigravity**, **Cline**, and any MCP-compatible client.
87
-
88
- #### Cursor
89
-
90
- Settings → MCP Servers → Add:
91
- - Command: `npx`
92
- - Args: `-y token-pilot`
93
-
94
- #### Claude Code
62
+ Claude Code shortcuts:
95
63
 
96
64
  ```bash
97
- # Current project only
98
65
  claude mcp add token-pilot -- npx -y token-pilot
99
-
100
- # All projects (global)
101
66
  claude mcp add --scope user token-pilot -- npx -y token-pilot
102
-
103
- # Shared via git (adds to .mcp.json)
104
- claude mcp add --scope project token-pilot -- npx -y token-pilot
105
67
  ```
106
68
 
107
- ### From Source
69
+ From source:
108
70
 
109
71
  ```bash
110
72
  git clone https://github.com/Digital-Threads/token-pilot.git
111
- cd token-pilot
112
- npm install && npm run build
113
- ```
114
-
115
- ```json
116
- {
117
- "mcpServers": {
118
- "token-pilot": {
119
- "command": "node",
120
- "args": ["/path/to/token-pilot/dist/index.js"]
121
- }
122
- }
123
- }
73
+ cd token-pilot && npm install && npm run build
74
+ # then point .mcp.json at dist/index.js
124
75
  ```
125
76
 
126
- ### ast-index (auto-installed)
127
-
128
- ast-index is downloaded automatically on first run. If you prefer manual install:
77
+ Non-interactive subagent install (CI):
129
78
 
130
79
  ```bash
131
- # Homebrew (macOS / Linux)
132
- brew tap defendend/ast-index && brew install ast-index
133
-
134
- # Or via Token Pilot CLI
135
- npx token-pilot install-ast-index
80
+ npx token-pilot install-agents --scope=user|project [--force]
136
81
  ```
82
+ </details>
137
83
 
138
- ### ast-grep (bundled)
139
-
140
- [ast-grep](https://ast-grep.github.io/) (`sg`) is included as optional dependency for structural code pattern search via `code_audit(check="pattern")`. Installs automatically with `npm i -g token-pilot`.
141
-
142
- ### PreToolUse Hook (Claude Code only)
84
+ ## Modes
143
85
 
144
- Optional Claude Code hook support:
86
+ The Read hook has three modes. Set in `.token-pilot.json`:
145
87
 
146
- - blocks unbounded `Read` on large code files (>500 lines) and points the agent to `smart_read`
147
- - adds `read_for_edit` guidance before `Edit`
88
+ | Mode | Behaviour |
89
+ |------|-----------|
90
+ | `off` | Hook is inert. |
91
+ | `advisory` | Denies unbounded Read with a short tip pointing at `smart_read` / `read_for_edit`. |
92
+ | `deny-enhanced` *(default)* | Denies the Read and returns a full structural summary (imports, exports, declarations) **inside** the denial reason. Works for subagents that lack MCP access. |
148
93
 
149
- ```bash
150
- npx token-pilot install-hook # Install
151
- npx token-pilot uninstall-hook # Remove
94
+ ```json
95
+ { "hooks": { "mode": "deny-enhanced", "denyThreshold": 300 } }
152
96
  ```
153
97
 
154
- > **Note:** With v0.7.4+ MCP instructions, the hook is less critical — AI agents already know to prefer Token Pilot tools.
98
+ Env var overrides: `TOKEN_PILOT_MODE=off`, `TOKEN_PILOT_DENY_THRESHOLD=500`, `TOKEN_PILOT_BYPASS=1`.
155
99
 
156
- ## How AI Agents Know to Use Token Pilot
100
+ ## Subagents
157
101
 
158
- **No configuration needed.** Token Pilot uses the MCP protocol's `instructions` field to automatically tell AI agents when to use its tools instead of built-in defaults (Read, cat, Grep).
102
+ Claude Code subagents guarantee MCP-first behaviour with tight response budgets and verdict-first output. **Tier 1** are everyday workhorses invoked proactively; **Tier 2** are focused specialists you reach for when a specific kind of work comes up (debugging, migration, test authoring, cleanup, commits).
159
103
 
160
- When connected, every MCP client receives rules like:
104
+ **Tier 1 workhorses:**
161
105
 
162
- ```
163
- WHEN TO USE TOKEN PILOT (saves up to 80% tokens):
164
- Reading code files smart_read (returns structure, not raw content)
165
- Need one function/class read_symbol (loads only that symbol)
166
- Exploring a directory outline (all symbols in one call)
167
- Long session? session_snapshot (capture state before compaction)
168
- ...
169
- WHEN TO USE DEFAULT TOOLS (Token Pilot adds no value):
170
- • Regex/pattern search → use Grep/ripgrep, NOT find_usages
171
- You need exact raw content for copy-paste → use Read
172
- ```
106
+ | Agent | When to invoke | Budget |
107
+ |-------|---------------|-------:|
108
+ | `tp-run` | General MCP-first workhorse; use proactively when no specialised agent fits | 800 |
109
+ | `tp-onboard` | Orient to an unfamiliar repo (layout, entry points, modules) | 600 |
110
+ | `tp-pr-reviewer` | Review a diff / PR / changeset; verdict-first, Critical/Important tiers | 600 |
111
+ | `tp-impact-analyzer` | Trace blast-radius of a change (callers, transitive deps) | 400 |
112
+ | `tp-refactor-planner` | Plan a refactor with exact edit context per step | 500 |
113
+ | `tp-test-triage` | Investigate test failures root cause → minimal fix | 500 |
114
+
115
+ **Tier 2 specialists:**
173
116
 
174
- This works on **Claude Code, Cursor, Codex, Antigravity**, and any MCP-compatible client — no project-level rules files needed.
117
+ | Agent | When to invoke | Budget |
118
+ |-------|---------------|-------:|
119
+ | `tp-debugger` | Stack trace / error → root-cause line via call-tree traversal | 700 |
120
+ | `tp-migration-scout` | Pre-migration impact map grouped by effort class | 800 |
121
+ | `tp-test-writer` | Write tests for ONE symbol, mirrors project style, runs tests | 900 |
122
+ | `tp-dead-code-finder` | Cross-checked dead-code detection, output-only (never deletes) | 600 |
123
+ | `tp-commit-writer` | Draft Conventional-Commit from staged diff; refuses failing tests | 400 |
124
+ | `tp-history-explorer` | "Why is this like this?" — minimum commit chain explaining current state | 600 |
125
+ | `tp-audit-scanner` | Read-only security / quality audit; Critical / Important / Minor findings | 800 |
126
+ | `tp-session-restorer` | Rehydrate state after /clear or compaction from latest snapshot | 400 |
175
127
 
176
- ### Optional: Project-Level Rules
128
+ Every agent's budget is enforced post-response — overshoots beyond 10 % land in `.token-pilot/over-budget.log`.
177
129
 
178
- For more control, you can add rules to your project:
130
+ `init` offers to install these; to do it later or add them to another project, run `npx token-pilot install-agents`. Remove with `npx token-pilot uninstall-agents --scope=user|project`.
179
131
 
180
- - **Claude Code** `CLAUDE.md` in project root
181
- - **Cursor** → `.cursorrules` in project root
182
- - **Codex** → `AGENTS.md` in project root
132
+ For third-party agents (e.g. `acc-*` plugins) whose tool allowlist excludes token-pilot MCP, `npx token-pilot bless-agents` creates project-level overrides that add the missing tools. `doctor` warns when the original agent has changed since blessing; `unbless-agents` reverses.
183
133
 
184
- ## MCP Tools (21)
134
+ ## MCP Tools
185
135
 
186
- ### Core Reading
136
+ ### Reading
187
137
 
188
- | Tool | Instead of | Description |
189
- |------|-----------|-------------|
190
- | `smart_read` | `Read` | AST structural overview: classes, functions, methods with signatures. Up to 90% savings on large files. Framework-aware: shows HTTP routes, column types, validation rules. `max_tokens` param for budget-constrained sessions. |
191
- | `read_symbol` | `Read` + scroll | Load source of a specific symbol. Supports `Class.method`. `show` param: full/head/tail/outline. |
192
- | `read_symbols` | N x `read_symbol` | Batch read multiple symbols from one file in a single call (max 10). One round-trip instead of N. |
193
- | `read_for_edit` | `Read` before `Edit` | Minimal RAW code around a symbol — copy directly as `old_string` for Edit tool. Batch mode: pass `symbols` array for multiple edit contexts. |
194
- | `read_range` | `Read` offset | Read a specific line range from a file. |
195
- | `read_diff` | re-`Read` | Show only changed hunks since last smart_read. Requires smart_read before editing (for baseline). Works with any edit tool. |
196
- | `smart_read_many` | multiple `Read` | Batch smart_read for up to 20 files in one call. |
138
+ | Tool | Instead of | Purpose |
139
+ |------|-----------|---------|
140
+ | `smart_read` | `Read` | AST outline; 90% fewer tokens on large files |
141
+ | `read_symbol` | `Read`+scroll | One class/function by name (`Class.method` supported) |
142
+ | `read_symbols` | N × `read_symbol` | Batch up to 10 symbols from one file |
143
+ | `read_for_edit` | `Read` before `Edit` | Minimal raw code around a symbol — copy directly as `old_string` |
144
+ | `read_range` | `Read` offset | Specific line range |
145
+ | `read_section` | `Read` | Section by heading (Markdown) or key (YAML/JSON/CSV) |
146
+ | `read_diff` | re-`Read` | Changed hunks since last `smart_read` |
147
+ | `smart_read_many` | multiple `Read` | Batch smart_read for up to 20 files |
197
148
 
198
149
  ### Search & Navigation
199
150
 
200
- | Tool | Instead of | Description |
201
- |------|-----------|-------------|
202
- | `find_usages` | `Grep` (refs) | All usages of a symbol: definitions, imports, references. Filters: `scope`, `kind`, `lang`, `limit`. Use `context_lines` to include surrounding source code. |
203
- | `project_overview` | `ls` + explore | Dual-detection (ast-index + config files) with confidence scoring. Project type, frameworks, quality tools, CI, architecture, directory map. Filter sections with `include`. |
204
- | `related_files` | manual explore | Import graph: what a file imports, what imports it, test files. |
205
- | `outline` | multiple `smart_read` | Compact overview of all code files in a directory. One call instead of 5-6. Supports `recursive` mode with `max_depth` for deep exploration. |
206
- | `find_unused` | manual | Detect dead code unused functions, classes, variables. |
207
- | `code_audit` | multiple `Grep` | Code quality issues in one call: TODO/FIXME comments, deprecated symbols, structural code patterns (via ast-grep), decorator search. |
208
- | `module_info` | manual analysis | Module dependency analysis: dependencies, dependents, public API, unused deps. Use for architecture understanding and dependency cleanup. |
209
- | `smart_diff` | raw `git diff` | Structural diff with AST symbol mapping — shows which functions/classes changed instead of raw patch. Affected symbols summary at top. Scopes: unstaged, staged, commit, branch. |
210
- | `explore_area` | outline + related_files + git log | One-call directory exploration: structure, imports, tests, recent changes. Replaces 3-5 separate calls. |
211
- | `smart_log` | raw `git log` | Structured commit history with category detection (feat/fix/refactor/docs), file stats, author breakdown. Filters by path and ref. |
212
- | `test_summary` | raw test output | Run tests and get structured summary: total/passed/failed + failure details. Supports vitest, jest, pytest, phpunit, go, cargo, rspec, mocha. |
213
-
214
- ### Session & Analytics
215
-
216
- | Tool | Description |
217
- |------|-------------|
218
- | `session_snapshot` | Capture session state as a compact markdown block (<200 tokens): goal, decisions (with reasoning), confirmed facts, relevant files, blockers, next step. Decisions field prevents revisiting rejected approaches after compaction. |
219
- | `session_analytics` | Token savings report: total saved, per-tool breakdown, top files, per-intent breakdown, decision insights, policy advisories. |
220
-
221
- ## CLI Commands
151
+ | Tool | Instead of | Purpose |
152
+ |------|-----------|---------|
153
+ | `find_usages` | `Grep` (refs) | All usages of a symbol; filters by scope/kind/lang |
154
+ | `project_overview` | `ls` + explore | Project type, frameworks, architecture, directory map |
155
+ | `related_files` | manual | Import graph: imports, importers, test files |
156
+ | `outline` | multiple `smart_read` | Compact overview of all code in a directory |
157
+ | `find_unused` | manual | Dead code detection |
158
+ | `code_audit` | multiple `Grep` | TODOs, deprecated symbols, structural patterns |
159
+ | `module_info` | manual | Deps, dependents, public API, unused deps |
160
+ | `smart_diff` | raw `git diff` | Structural diff with symbol mapping |
161
+ | `explore_area` | 3-5 calls | Structure + imports + tests + recent changes |
162
+ | `smart_log` | raw `git log` | Structured commits with category detection |
163
+ | `test_summary` | raw test output | Run tests pass/fail summary + failure details |
164
+
165
+ ### Session
166
+
167
+ | Tool | Purpose |
168
+ |------|---------|
169
+ | `session_snapshot` | Compact markdown snapshot (<200 tokens) of goal, decisions, facts, blockers, next step. Auto-persisted to `.token-pilot/snapshots/latest.md`; SessionStart surfaces a pointer when recent. |
170
+ | `session_budget` | Hook-suppression pressure for this session: saved tokens, burn fraction, effective denyThreshold, time-to-compact projection |
171
+ | `session_analytics` | Token savings: per-tool breakdown, top files, policy advisories |
172
+
173
+ ## CLI
222
174
 
223
175
  ```bash
224
- token-pilot # Start MCP server (uses cwd as project root)
225
- token-pilot /path/to/project # Start with specific project root
226
- token-pilot init [dir] # Create/update .mcp.json (token-pilot + context-mode)
227
- token-pilot install-ast-index # Download ast-index binary (auto on first run)
228
- token-pilot install-hook [root] # Install PreToolUse hook
229
- token-pilot uninstall-hook # Remove hook
230
- token-pilot hook-read <file> # Hook handler (called by Claude Code)
231
- token-pilot hook-edit # Edit hook handler (called by Claude Code)
232
- token-pilot doctor # Run diagnostics (ast-index, config, updates)
233
- token-pilot --version # Show version
234
- token-pilot --help # Show help
176
+ token-pilot # Start MCP server
177
+ token-pilot init # Create/merge .mcp.json; offers to install subagents
178
+ token-pilot install-agents [--scope=user|project] [--force]
179
+ token-pilot uninstall-agents --scope=user|project
180
+ token-pilot bless-agents # Extend third-party agents with token-pilot MCP
181
+ token-pilot unbless-agents <name>... | --all
182
+ token-pilot install-hook # Install PreToolUse hook
183
+ token-pilot uninstall-hook
184
+ token-pilot stats # Totals + top files from hook-events.jsonl
185
+ token-pilot stats --session[=<id>] | --by-agent
186
+ token-pilot doctor # Diagnostics (ast-index, config, upstream drift)
187
+ token-pilot install-ast-index # Download ast-index binary (auto on first run)
235
188
  ```
236
189
 
190
+ ### Environment variables
191
+
192
+ | Var | Effect |
193
+ |-----|--------|
194
+ | `TOKEN_PILOT_MODE=off` | Disable the hook for this process |
195
+ | `TOKEN_PILOT_BYPASS=1` | Pass every Read through |
196
+ | `TOKEN_PILOT_DENY_THRESHOLD=<n>` | Override `hooks.denyThreshold` |
197
+ | `TOKEN_PILOT_DEBUG=1` | Verbose hook logging to stderr |
198
+ | `TOKEN_PILOT_NO_AGENT_REMINDER=1` | Suppress the "tp-* not installed" stderr nudge |
199
+ | `TOKEN_PILOT_SUBAGENT=1` | Mark the MCP server as running inside a subagent |
200
+
237
201
  ## Configuration
238
202
 
239
- Create `.token-pilot.json` in your project root to customize behavior:
203
+ Drop `.token-pilot.json` in your project root. All fields optional.
240
204
 
241
205
  ```json
242
206
  {
243
- "smartRead": {
244
- "smallFileThreshold": 200,
245
- "advisoryReminders": true
246
- },
247
- "cache": {
248
- "maxSizeMB": 100,
249
- "watchFiles": true
250
- },
251
- "git": {
252
- "watchHead": true,
253
- "selectiveInvalidation": true
254
- },
255
- "contextMode": {
256
- "enabled": "auto",
257
- "adviseDelegation": true,
258
- "largeNonCodeThreshold": 200
259
- },
260
- "policies": {
261
- "preferCheapReads": true,
262
- "maxFullFileReads": 10,
263
- "warnOnLargeReads": true,
264
- "largeReadThreshold": 2000,
265
- "requireReadForEditBeforeEdit": true
266
- },
267
- "display": {
268
- "showImports": true,
269
- "showDocs": true,
270
- "maxDepth": 2,
271
- "showTokenSavings": true
272
- },
273
- "ignore": [
274
- "node_modules/**",
275
- "dist/**",
276
- ".git/**"
277
- ]
207
+ "hooks": { "mode": "deny-enhanced", "denyThreshold": 300 },
208
+ "sessionStart": { "enabled": true, "showStats": false, "maxReminderTokens": 250 },
209
+ "agents": { "scope": null, "reminder": true },
210
+ "smartRead": { "smallFileThreshold": 200 },
211
+ "cache": { "maxSizeMB": 100, "watchFiles": true },
212
+ "policies": { "maxFullFileReads": 10, "largeReadThreshold": 2000 },
213
+ "ignore": ["node_modules/**", "dist/**", ".git/**"]
278
214
  }
279
215
  ```
280
216
 
281
- All fields are optional sensible defaults are used for anything not specified.
217
+ | Option | Default | What it does |
218
+ |--------|---------|--------------|
219
+ | `hooks.mode` | `"deny-enhanced"` | `off` / `advisory` / `deny-enhanced` |
220
+ | `hooks.denyThreshold` | `300` | Line count above which the hook starts denying unbounded Read |
221
+ | `sessionStart.enabled` | `true` | Re-inject MCP-rules reminder at every new session / `/clear` / `/compact` |
222
+ | `agents.scope` | `null` | Persisted scope of last `install-agents` run; reused silently |
223
+ | `agents.reminder` | `true` | Show the "agents not installed" startup nudge |
224
+ | `smartRead.smallFileThreshold` | `200` | Files with fewer lines bypass AST overhead |
225
+ | `cache.maxSizeMB` | `100` | File cache ceiling (LRU eviction) |
226
+ | `policies.maxFullFileReads` | `10` | Warn after N full-file reads in session |
282
227
 
283
- ### Key Config Options
228
+ ## Ecosystem
284
229
 
285
- | Option | Default | Description |
286
- |--------|---------|-------------|
287
- | `smartRead.smallFileThreshold` | `200` | Files with fewer lines are returned in full (no AST overhead). |
288
- | `cache.maxSizeMB` | `100` | Max memory for file cache. LRU eviction when exceeded. |
289
- | `cache.watchFiles` | `true` | Auto-invalidate cache on file changes (chokidar). |
290
- | `git.watchHead` | `true` | Watch `.git/HEAD` for branch switches, invalidate changed files. |
291
- | `contextMode.enabled` | `"auto"` | Detect context-mode plugin. `true`/`false` to force. |
292
- | `contextMode.adviseDelegation` | `true` | Suggest context-mode for large non-code files. |
293
- | `policies.preferCheapReads` | `true` | Advisory hints when expensive tool used where cheaper exists. |
294
- | `policies.maxFullFileReads` | `10` | Warn after N full-file reads in session. |
295
- | `policies.warnOnLargeReads` | `true` | Warn when single response exceeds threshold. |
296
- | `policies.largeReadThreshold` | `2000` | Token threshold for large read warning. |
230
+ Token Pilot sits in a small toolkit of three orthogonal pieces. Each has a single job; none overlaps with another.
297
231
 
298
- ## Integration with context-mode
232
+ ```
233
+ Agent
234
+ ├─ Read code file → smart_read / read_symbol (Token Pilot MCP)
235
+ │ └→ ast-index (structural backend)
236
+ ├─ Need a fresh Read? → force: true (Token Pilot MCP)
237
+ ├─ Run code / inspect logs → execute (context-mode MCP)
238
+ └─ Bash agent, no MCP? → ast-index <subcmd> (CLI binary)
239
+ ```
299
240
 
300
- Token Pilot is **complementary** to [claude-context-mode](https://github.com/mksglu/claude-context-mode):
241
+ | Tool | Role | When it fires |
242
+ |------|------|---------------|
243
+ | **[Token Pilot](.)** | Enforcement layer — Read hook, MCP structural reads, dedup, snapshots, subagents | Every code Read / Edit / session |
244
+ | **[ast-index](https://github.com/defendend/Claude-ast-index-search)** | Structural indexer. Symbols, usages, hierarchy. Used by Token Pilot under the hood; also a standalone CLI for bash-only agents. | Auto-installed by Token Pilot; CLI available as `ast-index` |
245
+ | **[context-mode](https://github.com/mksglu/claude-context-mode)** | Sandbox executor — runs shell / python / js, only stdout enters the window. Orthogonal: not for reading source. | Large `Bash` outputs, `execute(language, code)` calls |
301
246
 
302
- | Responsibility | Token Pilot | context-mode |
303
- |----------------|-------------|--------------|
304
- | Code files (.ts, .py, .rs, ...) | AST-level structural reading | - |
305
- | Shell output (npm test, git log) | - | Sandbox + BM25 |
306
- | Large data files (JSON, CSV, logs) | Structural summary | Deep BM25-indexed analysis |
307
- | Re-reads of unchanged files | Compact reminders (~20 tokens) | - |
247
+ **Rules of thumb:**
308
248
 
309
- When both are configured, Token Pilot automatically:
310
- - Detects context-mode via `.mcp.json`
311
- - Suggests context-mode for large non-code files
312
- - Shows combined architecture info in `session_analytics`
249
+ - Read code Token Pilot `smart_read` / `read_symbol` (automatic via hook or MCP).
250
+ - Execute code that produces big output → context-mode `execute`.
251
+ - Bash agent or pre-flight shell command → `ast-index` CLI directly.
252
+ - Never all three in `CLAUDE.md` — Token Pilot's `doctor` warns when `CLAUDE.md` exceeds 60 lines for this reason.
313
253
 
314
- **Combined savings: up to 90%** in a typical coding session.
254
+ `npx token-pilot init` wires Token Pilot + context-mode into `.mcp.json`; ast-index installs on first run. If any single tool is missing, the other two still work standalone.
315
255
 
316
256
  ## Supported Languages
317
257
 
318
- Token Pilot supports all 29 languages that [ast-index](https://github.com/defendend/Claude-ast-index-search) supports:
319
-
320
- TypeScript, JavaScript, Python, Rust, Go, Java, Kotlin, Swift, Objective-C, C#, C++, C, PHP, Ruby, Scala, Dart, Lua, Shell/Bash, SQL, R, Vue, Svelte, Perl, Groovy, Elixir, Common Lisp, Matlab, Protocol Buffers, BSL (1C:Enterprise)
321
-
322
- Plus structural summaries for non-code files: JSON, YAML, Markdown, TOML, XML, CSV.
258
+ TypeScript, JavaScript, Python, Go, Rust, Java, Kotlin, C#, C/C++, PHP, Ruby. Non-code (JSON/YAML/Markdown/TOML) gets structural summaries. Regex fallback handles most other languages.
323
259
 
324
260
  ## Troubleshooting
325
261
 
326
- ### Verify installation
327
-
328
262
  ```bash
329
- npx token-pilot --help # Should print CLI help
330
- npx token-pilot --version # Should print current version
331
- npx token-pilot doctor # Run diagnostics (checks ast-index, config, etc.)
332
- ```
333
-
334
- ### Common issues
335
-
336
- | Problem | Fix |
337
- |---------|-----|
338
- | `smart_read` returns full file content (no savings) | ast-index not found. Run `npx token-pilot install-ast-index` |
339
- | `command not found: token-pilot` | Use `npx -y token-pilot` (npx downloads automatically) |
340
- | MCP server doesn't start in Claude Code | Check `claude mcp list` — server should be listed. Restart Claude Code after adding. |
341
- | ast-index binary not found | Run `npx token-pilot doctor` to diagnose. Try `npx token-pilot install-ast-index` to re-download. |
342
-
343
- ### Updating
263
+ # Verify installation
264
+ npx token-pilot doctor
344
265
 
345
- `npx -y token-pilot` always fetches the latest version from npm. To force a clean update:
266
+ # Common issues:
267
+ # - "ast-index not found" → npx token-pilot install-ast-index
268
+ # - "hooks not firing" → restart your AI assistant
269
+ # - "stats shows No events" → hook events accumulate in .token-pilot/hook-events.jsonl after the first denied Read
346
270
 
347
- ```bash
348
- npx clear-npx-cache # Clear npx cache
349
- npx -y token-pilot --version # Verify new version
350
- ```
351
-
352
- Token Pilot also checks for updates on startup and logs a notice to stderr if a newer version is available.
353
-
354
- ## Development
355
-
356
- ```bash
357
- npm install # Install dependencies
358
- npm run build # Compile TypeScript
359
- npm test # Run tests
360
- npm run test:watch # Run tests in watch mode
361
- npm run dev # TypeScript watch mode
271
+ # Update everything
272
+ npm i -g token-pilot@latest
362
273
  ```
363
274
 
364
275
  ## Architecture
365
276
 
366
277
  ```
367
278
  src/
368
- index.ts — CLI entry point and server bootstrap
369
- server.ts — MCP server setup, tool definitions, instructions
370
- types.ts Core domain types
371
- ast-index/
372
- client.ts — ast-index CLI wrapper (22+ methods)
373
- binary-manager.ts — Auto-download & manage ast-index binary
374
- tar-extract.ts — Minimal tar extractor (zero deps)
375
- types.ts — ast-index response types (20+ interfaces)
279
+ index.ts — CLI entry + MCP server bootstrap
280
+ server.ts — MCP server setup, 21 tool definitions
281
+ ast-index/ ast-index binary client + auto-install
376
282
  core/
377
- file-cache.ts LRU file cache with staleness detection
378
- context-registry.ts Advisory context tracking + compact reminders
379
- symbol-resolver.ts — Qualified symbol resolution
380
- token-estimator.ts — Token count estimation
381
- session-analytics.ts — Token savings tracking with intent + decision trace
382
- validation.ts — Input validators for all tools
383
- format-duration.ts — Shared duration formatter
384
- project-detector.ts — Config-based project detection (frameworks, CI, quality tools)
385
- confidence.ts — Confidence metadata for response completeness
386
- intent-classifier.ts — Tool → intent mapping (edit/debug/explore/review/analyze/search/read)
387
- budget-planner.ts — Advisory: suggests cheaper tool alternatives
388
- decision-trace.ts — Per-call instrumentation (cost, context state, alternatives)
389
- session-cache.ts — Tool-result-level caching with invalidation
390
- architecture-fingerprint.ts — Cross-session architecture caching
391
- policy-engine.ts — Configurable team policies for consistent savings
392
- config/
393
- loader.ts — Config loading + deep merge
394
- defaults.ts — Default config values
395
- formatters/
396
- structure.ts — AST outline → text formatter
397
- handlers/
398
- smart-read.ts — smart_read handler
399
- read-symbol.ts — read_symbol handler
400
- read-range.ts — read_range handler
401
- read-diff.ts — read_diff handler (O(n) diff)
402
- smart-read-many.ts — Batch smart_read
403
- find-usages.ts — find_usages handler (scope/kind/lang/limit filters)
404
- read-for-edit.ts — read_for_edit handler (minimal edit context)
405
- related-files.ts — related_files handler (import graph)
406
- outline.ts — outline handler (recursive directory overview)
407
- find-unused.ts — find_unused handler
408
- code-audit.ts — code_audit handler (TODOs, deprecated, patterns)
409
- project-overview.ts — project_overview (dual-detection + confidence)
410
- module-info.ts — module_info handler (deps, dependents, API, unused)
411
- smart-diff.ts — smart_diff handler (structural git diff + symbol mapping)
412
- explore-area.ts — explore_area handler (outline + imports + tests + changes)
413
- smart-log.ts — smart_log handler (structured git log + category detection)
414
- test-summary.ts — test_summary handler (run tests + parse output)
415
- non-code.ts — JSON/YAML/MD/TOML structural summaries
416
- git/
417
- watcher.ts — Git HEAD watcher (branch switch detection)
418
- file-watcher.ts — File system watcher (cache invalidation)
283
+ event-log.ts hook-events.jsonl + rotation + retention
284
+ session-analytics.ts, policy-engine.ts, intent-classifier.ts
419
285
  hooks/
420
286
  installer.ts — Hook install/uninstall for Claude Code
421
- integration/
422
- context-mode-detector.ts — context-mode presence detection
287
+ session-start.ts — SessionStart reminder handler
288
+ summary-pipeline.ts — ast-index regex → head+tail → pass-through
289
+ cli/
290
+ install-agents.ts, uninstall-agents.ts
291
+ bless-agents.ts, unbless-agents.ts, doctor-drift.ts
292
+ stats.ts
293
+ templates/agent-builder.ts
294
+ config/loader.ts, defaults.ts
295
+ handlers/ — 21 MCP tool handlers
296
+ git/ — HEAD + file watchers (cache invalidation)
297
+
298
+ scripts/
299
+ build-agents.mjs — Render templates/ → dist/agents/
300
+ bench-hook.mjs — Hook latency benchmark
301
+
302
+ templates/agents/ — Source for tp-* family + shared preamble + contract
423
303
  ```
424
304
 
425
305
  ## Credits
426
306
 
427
- Token Pilot is built on top of these excellent open-source projects:
307
+ Built on top of:
428
308
 
429
- - **[ast-index](https://github.com/defendend/Claude-ast-index-search)** by [@defendend](https://github.com/defendend) Rust-based AST indexing engine with tree-sitter, SQLite FTS5, and support for 29 programming languages. Token Pilot uses it as the backend for all code analysis.
430
- - **[claude-context-mode](https://github.com/mksglu/claude-context-mode)** by [@mksglu](https://github.com/mksglu) — Complementary MCP plugin for shell output and data file processing via sandbox + BM25. Token Pilot integrates with it for maximum combined savings.
431
- - **[Model Context Protocol](https://modelcontextprotocol.io/)** by Anthropic The protocol that makes all of this possible.
309
+ - [ast-index](https://github.com/defendend/ast-index) — Tree-sitter AST indexer in Rust (auto-installed)
310
+ - [@ast-grep/cli](https://ast-grep.github.io/) — Structural code pattern search
311
+ - [MCP SDK](https://github.com/modelcontextprotocol/typescript-sdk) — Model Context Protocol
312
+ - [chokidar](https://github.com/paulmillr/chokidar) — File watching
432
313
 
433
314
  ## License
434
315