antigravity-plugin-context-mode 1.3.1 → 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/CHANGELOG.md +24 -0
- package/README.md +78 -161
- package/hooks/pre-invocation.js +84 -0
- package/hooks/pre-tool-use.js +126 -23
- package/hooks/session-start.js +75 -7
- package/hooks.json +7 -0
- package/lib/store.js +128 -6
- package/lib/tools.js +41 -4
- package/package.json +1 -1
- package/plugin.json +1 -1
- package/rules/AGENTS.md +17 -5
- package/skills/context-mode/SKILL.md +19 -6
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,30 @@
|
|
|
2
2
|
|
|
3
3
|
All notable changes to `antigravity-plugin-context-mode` will be documented in this file.
|
|
4
4
|
|
|
5
|
+
## [1.4.0] - 2026-11-21
|
|
6
|
+
|
|
7
|
+
### Added
|
|
8
|
+
- **Live Active Cutoff & Exemption Injections (`SessionStart` & `PreInvocation`)**: Injected system messages dynamically report the active single-operation read cutoff and enumerate all active exempt file categories and custom extensions. Explicitly clarifies to LLM agents that the cutoff is a single-read tool threshold, not the model's context window.
|
|
9
|
+
- **Mid-Session Dynamic Configuration Tracking (`PreInvocation`)**: Added `hooks/pre-invocation.js` registered under `PreInvocation` in `hooks.json`. Automatically detects when cutoff limits or file exemptions are modified mid-session (via dashboard or API) and immediately informs the agent on the subsequent turn while remaining completely quiet when unchanged.
|
|
10
|
+
- **Automatic Indexing Redirection on Interception (`PreToolUse`)**: Instead of simply rejecting large `read_file` operations or un-paged file dump commands (`cat`, `Get-Content`, `type`), `PreToolUse` now automatically reads and indexes the target file into SQLite FTS5 (up to a configurable 50 MB ceiling) and returns `[context-mode protection: auto-indexed]` with the intuitive workspace-relative `sourceId` and immediate search instructions (`ctx_search(queries: [...], sourceId: "...")`).
|
|
11
|
+
- **Workspace-Relative Source IDs (`resolveFileSourceId`)**: Normalized file `sourceId` generation in `lib/store.js` and `ctx_index`. Files inside the active project directory resolve to clean, intuitive relative paths (e.g. `src/utils.js`, `Logs/Editor.log`) rather than opaque hashes, making `ctx_search` queries with `sourceId` natural and effortless for LLM agents.
|
|
12
|
+
- **Auto-Index Limit Dashboard Control & API**: Added a Max Auto-Index dropdown selector (`1 MB`, `5 MB`, `10 MB`, `50 MB`, `100 MB`, `Off`) directly adjacent to the Cutoff dropdown in the sidecar dashboard. Added `/api/auto-index-limit` (`GET` and `POST`) endpoint in `server.mjs`.
|
|
13
|
+
- **Configurable Auto-Index Limits Cascade**: Configurable via `CONTEXT_MODE_MAX_AUTO_INDEX_BYTES` env variable, session overrides, or SQLite global setting (`store.getMaxAutoIndexBytes()` and `store.setMaxAutoIndexBytes()`).
|
|
14
|
+
- **Idempotent File Re-indexing**: Re-indexing an existing file sourceId cleans up prior chunk entries before writing new ones, preventing chunk duplication when files are edited and re-indexed.
|
|
15
|
+
- **Active Limit & Exemption Diagnostics in MCP Tools**: Enhanced `ctx_stats` and `ctx_doctor` to return active cutoff bytes, formatted cutoff strings, and active exempt categories/extensions.
|
|
16
|
+
|
|
17
|
+
### Fixed
|
|
18
|
+
- **Debunked 8 KB Context Window Hallucination in Agent Rules (`rules/AGENTS.md`)**: Updated behavioral guidelines to explicitly distinguish between the tool-level read cutoff and the model's actual context window, and instructed agents that exempt files (PDFs, images, Office documents, 3D models, audio, video, archives, and prompt attachments) bypass cutoff protection and can be read directly with `read_file` without hesitation.
|
|
19
|
+
- **Dynamic PreToolUse Denial Messages**: Refactored denial messages in `hooks/pre-tool-use.js` to dynamically generate the live active exempt categories and custom extensions from SQLite rather than displaying a static hardcoded note.
|
|
20
|
+
- **Double-Counting Prevention in Statistics**: Updated `getStats()` in `lib/store.js` to ensure auto-indexed files logged through `read_file` or `run_command` interceptions are not double-counted between `events` and `sources`.
|
|
21
|
+
- **Safe ES Module Hook Imports**: Added `isMain` execution guards to `hooks/pre-tool-use.js` and `hooks/session-start.js` to prevent unintended top-level execution when importing helper utilities across hooks and test suites.
|
|
22
|
+
|
|
23
|
+
## [1.3.2] - 2026-11-17
|
|
24
|
+
|
|
25
|
+
### Documentation
|
|
26
|
+
- **User-Friendly Documentation**: Streamlined `README.md` to focus on end-user benefits, 1-click `npx` installation (global & workspace modes), real-world token savings benchmarks, and interactive sidecar controls.
|
|
27
|
+
- **Synchronized Manifest Version**: Updated `plugin.json` version to match release tag.
|
|
28
|
+
|
|
5
29
|
## [1.3.1] - 2026-11-16
|
|
6
30
|
|
|
7
31
|
### Added
|
package/README.md
CHANGED
|
@@ -1,77 +1,82 @@
|
|
|
1
1
|
# Antigravity Context Mode
|
|
2
2
|
|
|
3
|
-
> **Stop context bloat. Save 90%+ of your prompt tokens. Keep your agent fast, focused, and
|
|
3
|
+
> **Stop context bloat. Save 90%+ of your prompt tokens. Keep your agent fast, focused, and sharp.**
|
|
4
4
|
|
|
5
5
|
[](https://www.npmjs.com/package/antigravity-plugin-context-mode)
|
|
6
|
-
[](https://domush.github.io/antigravity-plugin-context-mode/)
|
|
7
7
|
[](LICENSE)
|
|
8
8
|
[]()
|
|
9
9
|
[]()
|
|
10
10
|
|
|
11
|
-
**Antigravity Context Mode** is a free, local-first plugin built specifically for the **Google Antigravity App**. It prevents terminal commands, build
|
|
11
|
+
**Antigravity Context Mode** is a free, local-first plugin built specifically for the **Google Antigravity App**. It prevents terminal commands, build logs, and multi-megabyte source files from flooding your conversation history — saving thousands of tokens per turn and stopping "agent amnesia" in its tracks.
|
|
12
12
|
|
|
13
|
-
> 🌐 **Live
|
|
13
|
+
> 🌐 **Interactive Live Simulator & Documentation:** [domush.github.io/antigravity-plugin-context-mode](https://domush.github.io/antigravity-plugin-context-mode/)
|
|
14
|
+
|
|
15
|
+
<img width="715" height="632" alt="image" src="https://github.com/user-attachments/assets/952b84a0-3e71-4bd6-99ae-e604532c1c7f" />
|
|
16
|
+
|
|
17
|
+
---
|
|
18
|
+
|
|
19
|
+
## Quick Install (10 Seconds)
|
|
20
|
+
|
|
21
|
+
Install directly into Google Antigravity using `npx`:
|
|
22
|
+
|
|
23
|
+
```bash
|
|
24
|
+
# Global install (available across all Antigravity chats)
|
|
25
|
+
npx antigravity-plugin-context-mode install
|
|
26
|
+
|
|
27
|
+
# Or per-project install (scoped to current workspace only)
|
|
28
|
+
npx antigravity-plugin-context-mode install --workspace
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
Restart or open the **Google Antigravity App**, and Context Mode is active immediately.
|
|
14
32
|
|
|
15
33
|
---
|
|
16
|
-
<img width="817" height="690" alt="Antigravity Context Mode Dashboard" src="https://github.com/user-attachments/assets/dbf6d666-58d0-48f3-bc02-9783acf3fb37" />
|
|
17
34
|
|
|
18
35
|
## The Problem: Context Window Bloat
|
|
19
36
|
|
|
20
|
-
When an AI coding agent
|
|
37
|
+
When an AI coding agent executes tools, standard workflows dump everything directly into your conversation context:
|
|
21
38
|
|
|
22
39
|
* Running `Get-Content Logs/Editor.log` dumps **65 KB (~16,000 tokens)** into your prompt.
|
|
23
40
|
* Running test suites, compiler outputs, or git diffs dumps **100+ KB** of repetitive text.
|
|
24
|
-
* Reading large
|
|
41
|
+
* Reading large files or documentation dumps **thousands of lines** of irrelevant boilerplate.
|
|
25
42
|
|
|
26
43
|
### Why this hurts:
|
|
27
|
-
1. **Agent Amnesia**: Important system instructions, user constraints, and earlier architectural decisions get drowned out
|
|
28
|
-
2. **Slower Responses**:
|
|
29
|
-
3. **Burned Quota
|
|
44
|
+
1. **Agent Amnesia**: Important system instructions, user constraints, and earlier architectural decisions get drowned out.
|
|
45
|
+
2. **Slower Responses**: Generation times climb as the context window fills up with raw text.
|
|
46
|
+
3. **Burned Quota**: You hit model context ceilings and rate limits after only a few turns.
|
|
30
47
|
|
|
31
48
|
---
|
|
32
49
|
|
|
33
|
-
##
|
|
50
|
+
## How It Works
|
|
34
51
|
|
|
35
52
|
```text
|
|
36
|
-
|
|
37
|
-
│
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
│
|
|
44
|
-
│
|
|
45
|
-
│
|
|
46
|
-
│
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
│ 2. SQLite FTS5 Indexing │
|
|
57
|
-
│ 3. BM25 + Trigram RRF Search │
|
|
58
|
-
└───────────────────────────────────┘
|
|
59
|
-
│
|
|
60
|
-
▼
|
|
61
|
-
Returns only the filtered,
|
|
62
|
-
relevant answer to the chat!
|
|
53
|
+
┌────────────────────────────────────────────────────────┐
|
|
54
|
+
│ 1. Agent attempts to read a large file or command │
|
|
55
|
+
│ (e.g. 5,000-line build log or 40 KB source file) │
|
|
56
|
+
└───────────────────────────┬────────────────────────────┘
|
|
57
|
+
│
|
|
58
|
+
▼
|
|
59
|
+
┌────────────────────────────────────────────────────────┐
|
|
60
|
+
│ 2. Pre-Tool Lifecycle Hook Intercepts Unbounded Dumps │
|
|
61
|
+
│ • Files under 8 KB pass through normally │
|
|
62
|
+
│ • Un-paged dumps over 8 KB are safely intercepted │
|
|
63
|
+
│ • Images, docs, and chat attachments are exempted │
|
|
64
|
+
└───────────────────────────┬────────────────────────────┘
|
|
65
|
+
│
|
|
66
|
+
▼
|
|
67
|
+
┌────────────────────────────────────────────────────────┐
|
|
68
|
+
│ 3. Sandboxed Execution ("Thinking in Code") │
|
|
69
|
+
│ • Agent filters data locally using Node/Python │
|
|
70
|
+
│ • Indexes text into local SQLite FTS5 BM25 database │
|
|
71
|
+
│ • Returns only the exact answer or error to chat! │
|
|
72
|
+
└────────────────────────────────────────────────────────┘
|
|
63
73
|
```
|
|
64
74
|
|
|
65
|
-
1. **Smart Lifecycle Gating (`hooks.json`)**: Before a command or file read executes, Context Mode checks if it will cause a context flood. Applied identically to primary agents and subagents, the hook intercepts un-paged reads exceeding the active cutoff (default 8 KB) and unbounded dumps, guiding agents to query or sandbox the data instead.
|
|
66
|
-
2. **"Thinking in Code" (`ctx_execute`)**: Instead of reading a 5,000-line log into memory, the agent executes a concise local script (Node.js, Python, or PowerShell). The script filters the data in **50 ms** and returns *only* the specific answer or error to the conversation.
|
|
67
|
-
3. **Local SQLite FTS5 Storage (`ctx_search`, `ctx_index`)**: Raw outputs and indexed files are saved safely on your local disk in `~/.context-mode/context.db`. The agent uses reciprocal rank fusion search to fetch only the exact snippets it needs.
|
|
68
|
-
4. **Live Sidecar Dashboard**: A native side pane right inside the Antigravity App that displays real-time context savings across primary agents and subagents, lets you toggle file categories on the fly, and search indexed data with a click.
|
|
69
|
-
|
|
70
75
|
---
|
|
71
76
|
|
|
72
77
|
## Proven Results
|
|
73
78
|
|
|
74
|
-
Tested live on real-world build logs
|
|
79
|
+
Tested live on real-world build logs and source files in the Antigravity App:
|
|
75
80
|
|
|
76
81
|
| Operation | Without Context Mode | With Context Mode | Savings |
|
|
77
82
|
| :--- | :---: | :---: | :---: |
|
|
@@ -81,141 +86,53 @@ Tested live on real-world build logs, source files, and datasets in the Antigrav
|
|
|
81
86
|
|
|
82
87
|
---
|
|
83
88
|
|
|
84
|
-
##
|
|
85
|
-
|
|
86
|
-
### Method 1: 1-Click CLI Installer (Fastest)
|
|
87
|
-
Run this command from any terminal:
|
|
88
|
-
|
|
89
|
-
```bash
|
|
90
|
-
npx antigravity-plugin-context-mode install
|
|
91
|
-
```
|
|
92
|
-
|
|
93
|
-
This automatically detects your operating system, unpacks the latest release into `~/.gemini/config/plugins/antigravity-plugin-context-mode`, and activates hooks and MCP tools. Restart the Antigravity App to activate!
|
|
94
|
-
|
|
95
|
-
> **Workspace-only install:** To install only for the current project, add `--workspace`:
|
|
96
|
-
> ```bash
|
|
97
|
-
> npx antigravity-plugin-context-mode install --workspace
|
|
98
|
-
> ```
|
|
99
|
-
|
|
100
|
-
---
|
|
101
|
-
|
|
102
|
-
### Method 2: Git Clone (Ideal for Easy Updates)
|
|
103
|
-
If you prefer managing the plugin via Git for easy `git pull` updates:
|
|
89
|
+
## Key Features
|
|
104
90
|
|
|
105
|
-
**
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
**
|
|
111
|
-
```bash
|
|
112
|
-
git clone https://github.com/Domush/antigravity-plugin-context-mode.git ~/.gemini/config/plugins/antigravity-plugin-context-mode
|
|
113
|
-
```
|
|
114
|
-
|
|
115
|
-
**To update later:**
|
|
116
|
-
```bash
|
|
117
|
-
cd ~/.gemini/config/plugins/antigravity-plugin-context-mode && git pull
|
|
118
|
-
```
|
|
119
|
-
|
|
120
|
-
---
|
|
121
|
-
|
|
122
|
-
## Live Auxiliary Sidecar Dashboard
|
|
123
|
-
|
|
124
|
-
Context Mode includes a native web dashboard that opens directly in Antigravity's **Auxiliary (Side) Pane**:
|
|
125
|
-
|
|
126
|
-
* **One-Click Open Pill:** Click `[Open Context Mode Dashboard](sidecar://antigravity-plugin-context-mode/dashboard/)` in chat anytime.
|
|
127
|
-
* **Active / Paused Toggle:** Click the status pill in the top header to instantly pause protection when you intentionally need un-gated operations, and click again to re-activate.
|
|
128
|
-
* **Dynamic Version Badge:** Automatically reflects the active plugin version in the top-right header.
|
|
129
|
-
* **Context Saved Progress Bar:** Visual indicator displaying the exact percentage of context window preserved.
|
|
130
|
-
* **3-Way Scope Toggle:** Seamlessly inspect telemetry at three distinct levels:
|
|
131
|
-
* **Conversation**: Metrics strictly for the active chat; clean slate on new conversations. Subagent actions within the conversation feed directly into this view.
|
|
132
|
-
* **Session**: Metrics aggregated across all conversations since the app restarted. Automatically resets transient overrides on app reboot.
|
|
133
|
-
* **Lifetime**: All-time cumulative database metrics and persistent totals. Changing the cutoff in Lifetime updates the baseline defaults for all new sessions and new conversations.
|
|
134
|
-
* **Shared Subagent Feed:** Interceptions triggered by subagents (`researcher`, `browser`, etc.) are badged by role and displayed alongside primary agent events in the same conversation feed.
|
|
135
|
-
* **File Category Toggles:** Clean, one-click pills for grouping exemptions without reading massive lists:
|
|
136
|
-
* **Images** (`.png`, `.jpg`, `.jpeg`, `.gif`, `.webp`, `.svg`, `.bmp`, `.ico`, `.tiff`, `.psd`) — *Enabled by default*
|
|
137
|
-
* **Documents** (`.pdf`, `.docx`, `.doc`, `.xlsx`, `.xls`, `.pptx`, `.ppt`, `.odt`, `.rtf`) — *Enabled by default*
|
|
138
|
-
* **3D Models** (`.blend`, `.fbx`, `.obj`, `.gltf`, `.glb`, `.stl`, `.dae`, `.3ds`, `.step`, `.iges`) — *Enabled by default*
|
|
139
|
-
* **Music** (`.mp3`, `.wav`, `.ogg`, `.flac`, `.aac`, `.m4a`, `.wma`, `.midi`) — *Enabled by default*
|
|
140
|
-
* **Video** (`.mp4`, `.mov`, `.avi`, `.mkv`, `.webm`, `.flv`, `.wmv`, `.m4v`) — *Enabled by default*
|
|
141
|
-
* **Archives** (`.zip`, `.tar`, `.gz`, `.7z`, `.rar`, `.wasm`) — *Enabled by default*
|
|
142
|
-
* **Source Code** (`.js`, `.ts`, `.py`, `.rs`, `.go`, `.java`, `.c`, `.cpp`, `.cs`, `.html`, `.css`, etc.) — *Disabled by default to protect context*
|
|
143
|
-
* **Custom File Extensions:** Dedicated section displaying only user-added file extensions (e.g. `.csv`, `.parquet`, `.log`) with instant removal.
|
|
144
|
-
* **Chat Attachment Exemption:** Files attached directly in chat messages (`@` mentions and drag-and-drops) always bypass size cutoffs so the agent can inspect them in full.
|
|
145
|
-
* **Interactive Cutoff Dropdown:** Switch size cutoffs on the fly (`2 KB`, `4 KB`, `8 KB`, `16 KB`, `32 KB`, `64 KB`, or `none`). Line slice limits scale dynamically (2 KB: ≤ 50 lines, 8 KB: ≤ 200 lines, 32 KB: ≤ 800 lines).
|
|
146
|
-
* **Interactive FTS5 Search Inspector:** Search your indexed logs and files directly from the UI to inspect what the agent has indexed.
|
|
147
|
-
* **1-Click Session Purge:** Wipe session indexes and reset counters whenever you start a fresh task.
|
|
91
|
+
* 🛡️ **Automated Interception**: Blocks unbounded file dumps and commands before they bloat your context window.
|
|
92
|
+
* ⚡ **Thinking in Code**: Filters multi-thousand-line outputs in 50 ms via local sandboxed scripts.
|
|
93
|
+
* 🔍 **Local SQLite FTS5 Search**: Indexes files and logs locally on your machine with BM25 keyword matching and trigram search.
|
|
94
|
+
* 📊 **Built-In Sidecar Dashboard**: Real-time stats pane inside Antigravity showing tokens kept out of context.
|
|
95
|
+
* 🔒 **100% Local & Private**: All indexed data stays on your machine in `~/.context-mode/context.db`. Zero network calls.
|
|
96
|
+
* 📦 **Zero Dependencies**: Pure native Node.js (`node:sqlite`). No native builds, no `node-gyp`.
|
|
148
97
|
|
|
149
98
|
---
|
|
150
99
|
|
|
151
100
|
## Available MCP Tools
|
|
152
101
|
|
|
153
|
-
Once installed,
|
|
102
|
+
Once installed, Context Mode provides 8 specialized tools for your agent:
|
|
154
103
|
|
|
155
|
-
| Tool | What It Does |
|
|
156
|
-
| :--- | :--- |
|
|
157
|
-
| **`ctx_execute`** | Runs sandboxed Node.js, Python, or PowerShell scripts
|
|
158
|
-
| **`ctx_search`** | Searches
|
|
159
|
-
| **`ctx_index`** | Indexes local files
|
|
160
|
-
| **`ctx_batch`** | Runs multiple
|
|
161
|
-
| **`ctx_stats`** | Displays a formatted savings report and token metrics. |
|
|
162
|
-
| **`ctx_resume`** | Returns recent indexed sources and state pointers
|
|
163
|
-
| **`ctx_doctor`** | Checks SQLite database health, WAL mode, and
|
|
164
|
-
| **`ctx_purge`** | Clears stored sources and events from SQLite. |
|
|
104
|
+
| Tool | What It Does |
|
|
105
|
+
| :--- | :--- |
|
|
106
|
+
| **`ctx_execute`** | Runs sandboxed Node.js, Python, or PowerShell scripts to inspect files and extract answers without context dumps. |
|
|
107
|
+
| **`ctx_search`** | Searches indexed logs and documentation using local SQLite FTS5 BM25 stemming. |
|
|
108
|
+
| **`ctx_index`** | Indexes local files or documentation into searchable chunks for the agent. |
|
|
109
|
+
| **`ctx_batch`** | Runs multiple terminal commands in batch and indexes the combined output. |
|
|
110
|
+
| **`ctx_stats`** | Displays a formatted context savings report and token metrics. |
|
|
111
|
+
| **`ctx_resume`** | Returns recent indexed sources and state pointers after context compactions. |
|
|
112
|
+
| **`ctx_doctor`** | Checks SQLite database health, WAL mode, and platform runtimes. |
|
|
113
|
+
| **`ctx_purge`** | Clears stored sources and events from SQLite. |
|
|
165
114
|
|
|
166
115
|
---
|
|
167
116
|
|
|
168
|
-
##
|
|
117
|
+
## Managing the Plugin
|
|
169
118
|
|
|
170
|
-
|
|
119
|
+
### Enable / Disable Anytime
|
|
120
|
+
Open the **Google Antigravity App** → **Customizations** → **Plugins**, and toggle **Context Mode** on or off with one click.
|
|
171
121
|
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
| `CONTEXT_MODE_MAX_READ_BYTES` | `8192` (8 KB) | Size threshold beyond which un-paged file reads are rejected. Set `0` to disable. |
|
|
175
|
-
| `CONTEXT_MODE_MAX_LINE_RANGE` | *Dynamic* (or `200`) | Maximum allowable line slice range before pagination rejection (scales with cutoff). |
|
|
176
|
-
| `CONTEXT_MODE_MAX_OUTPUT_BYTES` | *Dynamic* (or `16384`) | Maximum raw preview bytes returned by `ctx_execute` (defaults to 2x cutoff). |
|
|
177
|
-
| `CONTEXT_MODE_TIMEOUT_MS` | `30000` (30s) | Execution timeout for sandboxed code snippets. |
|
|
122
|
+
### Adjust Cutoffs
|
|
123
|
+
You can adjust the file read cutoff directly in the sidecar dashboard dropdown (`2 KB`, `4 KB`, `8 KB`, `16 KB`, `32 KB`, `64 KB`, or `none`).
|
|
178
124
|
|
|
179
|
-
###
|
|
180
|
-
|
|
181
|
-
$env:CONTEXT_MODE_MAX_READ_BYTES = "4096" # Enforce strict 4 KB cutoff
|
|
182
|
-
```
|
|
125
|
+
### Uninstall
|
|
126
|
+
To remove the plugin from your system:
|
|
183
127
|
|
|
184
|
-
### How to set on macOS / Linux:
|
|
185
128
|
```bash
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
---
|
|
129
|
+
# Remove global plugin
|
|
130
|
+
npx antigravity-plugin-context-mode uninstall
|
|
190
131
|
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
* **100% Local**: All indexed data lives on your machine in `~/.context-mode/context.db`. Zero network calls are made.
|
|
194
|
-
* **Zero 3rd-Party Dependencies**: Built exclusively on native Node.js (`node:sqlite` / `DatabaseSync`, `child_process`, and `http`). No native C++ builds, no `node-gyp`, and no dependency security vulnerabilities.
|
|
195
|
-
* **Safe Sandboxing**: Process execution in `ctx_execute` enforces strict execution timeouts and output caps to prevent runaway processes.
|
|
196
|
-
|
|
197
|
-
---
|
|
198
|
-
|
|
199
|
-
## Running Tests
|
|
200
|
-
|
|
201
|
-
Context Mode ships with a complete test suite using Node's native test runner:
|
|
202
|
-
|
|
203
|
-
```bash
|
|
204
|
-
npm test
|
|
132
|
+
# Remove per-project plugin
|
|
133
|
+
npx antigravity-plugin-context-mode uninstall --workspace
|
|
205
134
|
```
|
|
206
135
|
|
|
207
|
-
Verifies:
|
|
208
|
-
* SQLite FTS5 schema initialization, chunking, Porter BM25, and Trigram search.
|
|
209
|
-
* Reciprocal Rank Fusion (RRF) ranking.
|
|
210
|
-
* Sandbox execution and process timeout termination.
|
|
211
|
-
* `PreToolUse` and `SessionStart` lifecycle hook gating for primary agents and subagents.
|
|
212
|
-
* Shared conversation dashboard linking and subagent interception event journal.
|
|
213
|
-
* Lifetime cutoff inheritance across new sessions and new conversations.
|
|
214
|
-
* Mathematically accurate context savings calculations without double-counting.
|
|
215
|
-
* File category toggles and custom extension management.
|
|
216
|
-
* Active / Paused state toggle and bypass logic.
|
|
217
|
-
* MCP stdio JSON-RPC protocol compliance.
|
|
218
|
-
|
|
219
136
|
---
|
|
220
137
|
|
|
221
138
|
## License
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { fileURLToPath } from "node:url";
|
|
4
|
+
import { ContextModeStore } from "../lib/store.js";
|
|
5
|
+
import { resolveSharedSessionId } from "./pre-tool-use.js";
|
|
6
|
+
import { buildStatusMessage } from "./session-start.js";
|
|
7
|
+
|
|
8
|
+
function readStdin() {
|
|
9
|
+
return new Promise((resolve) => {
|
|
10
|
+
let data = "";
|
|
11
|
+
process.stdin.setEncoding("utf8");
|
|
12
|
+
process.stdin.on("data", (chunk) => {
|
|
13
|
+
data += chunk;
|
|
14
|
+
});
|
|
15
|
+
process.stdin.on("end", () => {
|
|
16
|
+
resolve(data);
|
|
17
|
+
});
|
|
18
|
+
});
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
async function main() {
|
|
22
|
+
const rawInput = await readStdin();
|
|
23
|
+
let payload = {};
|
|
24
|
+
try {
|
|
25
|
+
if (rawInput && rawInput.trim()) {
|
|
26
|
+
payload = JSON.parse(rawInput);
|
|
27
|
+
}
|
|
28
|
+
} catch {}
|
|
29
|
+
|
|
30
|
+
const sessionId = resolveSharedSessionId(payload);
|
|
31
|
+
|
|
32
|
+
try {
|
|
33
|
+
const store = new ContextModeStore();
|
|
34
|
+
const cutoff = store.getCutoff(sessionId);
|
|
35
|
+
const exemptCats = store.getExemptCategories(sessionId);
|
|
36
|
+
const exemptExts = store.getExemptExtensions(sessionId);
|
|
37
|
+
const customExts = store.getCustomExemptExtensions(sessionId);
|
|
38
|
+
|
|
39
|
+
const sig = `${cutoff}:${exemptExts.slice().sort().join(",")}`;
|
|
40
|
+
const lastInformed = store.getMeta(`informed_config:session:${sessionId}`);
|
|
41
|
+
|
|
42
|
+
if (lastInformed !== sig) {
|
|
43
|
+
store.setMeta(`informed_config:session:${sessionId}`, sig);
|
|
44
|
+
store.close();
|
|
45
|
+
|
|
46
|
+
const message = buildStatusMessage({
|
|
47
|
+
cutoff,
|
|
48
|
+
exemptCategories: exemptCats,
|
|
49
|
+
exemptExtensions: exemptExts,
|
|
50
|
+
customExtensions: customExts,
|
|
51
|
+
isUpdate: Boolean(lastInformed)
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
const response = {
|
|
55
|
+
injectSteps: [
|
|
56
|
+
{
|
|
57
|
+
systemMessage: {
|
|
58
|
+
systemMessage: message
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
]
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
process.stdout.write(JSON.stringify(response) + "\n");
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
store.close();
|
|
69
|
+
} catch {}
|
|
70
|
+
|
|
71
|
+
process.stdout.write(JSON.stringify({}) + "\n");
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
const isMain = Boolean(
|
|
75
|
+
process.argv[1] &&
|
|
76
|
+
path.resolve(fileURLToPath(import.meta.url)).toLowerCase() ===
|
|
77
|
+
path.resolve(process.argv[1]).toLowerCase()
|
|
78
|
+
);
|
|
79
|
+
|
|
80
|
+
if (isMain) {
|
|
81
|
+
main().catch(() => {
|
|
82
|
+
process.stdout.write(JSON.stringify({}) + "\n");
|
|
83
|
+
});
|
|
84
|
+
}
|
package/hooks/pre-tool-use.js
CHANGED
|
@@ -1,11 +1,28 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import fs from "node:fs";
|
|
3
3
|
import path from "node:path";
|
|
4
|
-
import {
|
|
4
|
+
import { fileURLToPath } from "node:url";
|
|
5
|
+
import { ContextModeStore, DEFAULT_MAX_AUTO_INDEX_BYTES, resolveFileSourceId } from "../lib/store.js";
|
|
5
6
|
|
|
6
7
|
export const DEFAULT_MAX_READ_BYTES = 8192; // 8 KB default cutoff
|
|
7
8
|
export const DEFAULT_MAX_LINE_RANGE = 200; // 200 lines max un-indexed slice
|
|
8
9
|
|
|
10
|
+
export function getMaxAutoIndexBytes(sessionId = null) {
|
|
11
|
+
try {
|
|
12
|
+
const store = new ContextModeStore();
|
|
13
|
+
const limit = store.getMaxAutoIndexBytes(sessionId);
|
|
14
|
+
store.close();
|
|
15
|
+
return limit;
|
|
16
|
+
} catch {
|
|
17
|
+
const envVal = process.env.CONTEXT_MODE_MAX_AUTO_INDEX_BYTES;
|
|
18
|
+
if (envVal) {
|
|
19
|
+
const parsed = parseInt(envVal, 10);
|
|
20
|
+
if (!Number.isNaN(parsed)) return parsed;
|
|
21
|
+
}
|
|
22
|
+
return DEFAULT_MAX_AUTO_INDEX_BYTES;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
9
26
|
function isProtectionPaused(sessionId = null) {
|
|
10
27
|
try {
|
|
11
28
|
const store = new ContextModeStore();
|
|
@@ -17,7 +34,7 @@ function isProtectionPaused(sessionId = null) {
|
|
|
17
34
|
}
|
|
18
35
|
}
|
|
19
36
|
|
|
20
|
-
function getMaxReadBytes(sessionId = null) {
|
|
37
|
+
export function getMaxReadBytes(sessionId = null) {
|
|
21
38
|
try {
|
|
22
39
|
const store = new ContextModeStore();
|
|
23
40
|
const cutoff = store.getCutoff(sessionId);
|
|
@@ -33,7 +50,7 @@ function getMaxReadBytes(sessionId = null) {
|
|
|
33
50
|
}
|
|
34
51
|
}
|
|
35
52
|
|
|
36
|
-
function getExemptExtensions(sessionId = null) {
|
|
53
|
+
export function getExemptExtensions(sessionId = null) {
|
|
37
54
|
try {
|
|
38
55
|
const store = new ContextModeStore();
|
|
39
56
|
const exts = store.getExemptExtensions(sessionId);
|
|
@@ -44,7 +61,18 @@ function getExemptExtensions(sessionId = null) {
|
|
|
44
61
|
}
|
|
45
62
|
}
|
|
46
63
|
|
|
47
|
-
function
|
|
64
|
+
export function getActiveExemptSummary(sessionId = null) {
|
|
65
|
+
try {
|
|
66
|
+
const store = new ContextModeStore();
|
|
67
|
+
const summary = store.getExemptSummary(sessionId);
|
|
68
|
+
store.close();
|
|
69
|
+
return summary;
|
|
70
|
+
} catch {
|
|
71
|
+
return "prompt attachments in .user_uploaded/";
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export function getMaxLineRange(maxReadBytes = DEFAULT_MAX_READ_BYTES) {
|
|
48
76
|
const envVal = process.env.CONTEXT_MODE_MAX_LINE_RANGE;
|
|
49
77
|
if (envVal) {
|
|
50
78
|
const parsed = parseInt(envVal, 10);
|
|
@@ -54,7 +82,7 @@ function getMaxLineRange(maxReadBytes = DEFAULT_MAX_READ_BYTES) {
|
|
|
54
82
|
return Math.max(50, Math.round(maxReadBytes / 40));
|
|
55
83
|
}
|
|
56
84
|
|
|
57
|
-
function formatBytes(bytes) {
|
|
85
|
+
export function formatBytes(bytes) {
|
|
58
86
|
if (bytes < 1024) return `${bytes} B`;
|
|
59
87
|
if (bytes < 1024 * 1024) {
|
|
60
88
|
const kb = bytes / 1024;
|
|
@@ -269,6 +297,7 @@ export function inspectCommand({ commandLine, cwd, sessionId }) {
|
|
|
269
297
|
|
|
270
298
|
const cleanCmd = cleanStringArg(commandLine);
|
|
271
299
|
const maxReadBytes = getMaxReadBytes(sessionId);
|
|
300
|
+
const maxLineRange = getMaxLineRange(maxReadBytes);
|
|
272
301
|
const exemptExtensions = getExemptExtensions(sessionId);
|
|
273
302
|
|
|
274
303
|
// 1. Git log without count limiter
|
|
@@ -307,7 +336,7 @@ export function inspectCommand({ commandLine, cwd, sessionId }) {
|
|
|
307
336
|
shouldDeny: true,
|
|
308
337
|
reason:
|
|
309
338
|
`[context-mode protection] Direct curl/wget download to stdout risks flooding the context window. ` +
|
|
310
|
-
`Please use 'mcp_context-mode_ctx_execute', save to disk ('-o <file>'), or
|
|
339
|
+
`Please use 'mcp_context-mode_ctx_execute', save to disk ('-o <file>'), or limit output (e.g. '| head -n <lines>').`,
|
|
311
340
|
size: 32768,
|
|
312
341
|
targetPath: urlMatch ? urlMatch[0] : cleanCmd
|
|
313
342
|
};
|
|
@@ -337,7 +366,7 @@ export function inspectCommand({ commandLine, cwd, sessionId }) {
|
|
|
337
366
|
shouldDeny: true,
|
|
338
367
|
reason:
|
|
339
368
|
`[context-mode protection] Wildcard file dump ('${rawTarget}') risks flooding the context window. ` +
|
|
340
|
-
`Please use 'mcp_context-mode_ctx_execute' or
|
|
369
|
+
`Please use 'mcp_context-mode_ctx_execute' or limit output to only the needed lines (<= ${maxLineRange} lines, e.g. '| Select-Object -First <lines>').`,
|
|
341
370
|
size: 32768,
|
|
342
371
|
targetPath: rawTarget
|
|
343
372
|
};
|
|
@@ -358,14 +387,47 @@ export function inspectCommand({ commandLine, cwd, sessionId }) {
|
|
|
358
387
|
const stat = fs.statSync(absPath);
|
|
359
388
|
// Dynamic cutoff check against active setting
|
|
360
389
|
if (maxReadBytes > 0 && stat.size > maxReadBytes) {
|
|
390
|
+
const maxAutoIndexBytes = getMaxAutoIndexBytes(sessionId);
|
|
391
|
+
const sourceId = resolveFileSourceId(absPath, cwd) || cleanTarget;
|
|
392
|
+
|
|
393
|
+
let isAutoIndexed = false;
|
|
394
|
+
if (maxAutoIndexBytes > 0 && stat.size <= maxAutoIndexBytes) {
|
|
395
|
+
try {
|
|
396
|
+
const store = new ContextModeStore();
|
|
397
|
+
const content = fs.readFileSync(absPath, "utf8");
|
|
398
|
+
store.indexContent({
|
|
399
|
+
sessionId,
|
|
400
|
+
worktree: cwd,
|
|
401
|
+
agent: "antigravity",
|
|
402
|
+
kind: "file",
|
|
403
|
+
label: sourceId,
|
|
404
|
+
sourceId,
|
|
405
|
+
content
|
|
406
|
+
});
|
|
407
|
+
store.close();
|
|
408
|
+
isAutoIndexed = true;
|
|
409
|
+
} catch {}
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
let reason = "";
|
|
413
|
+
if (isAutoIndexed) {
|
|
414
|
+
reason =
|
|
415
|
+
`[context-mode protection: auto-indexed] Command attempts an un-paged dump of '${cleanTarget}' (${formatBytes(stat.size)}), ` +
|
|
416
|
+
`exceeding the active ${formatBytes(maxReadBytes)} context limit. ` +
|
|
417
|
+
`The file has been automatically indexed as source '${sourceId}'. ` +
|
|
418
|
+
`Query it with 'mcp_context-mode_ctx_search(queries: [...], sourceId: "${sourceId}")' or limit output to only needed lines (<= ${maxLineRange} lines, e.g. -Head <lines> or '| Select-Object -First <lines>').`;
|
|
419
|
+
} else {
|
|
420
|
+
reason =
|
|
421
|
+
`[context-mode protection] Command attempts an un-paged dump of '${cleanTarget}' (${formatBytes(stat.size)}), ` +
|
|
422
|
+
`exceeding the active ${formatBytes(maxReadBytes)} context limit. ` +
|
|
423
|
+
`Please use 'mcp_context-mode_ctx_execute' or limit output to only needed lines (<= ${maxLineRange} lines, e.g. -Head <lines> or '| Select-Object -First <lines>').`;
|
|
424
|
+
}
|
|
425
|
+
|
|
361
426
|
return {
|
|
362
427
|
shouldDeny: true,
|
|
363
|
-
reason
|
|
364
|
-
`[context-mode protection] Command attempts an un-paged dump of '${cleanTarget}' (${formatBytes(stat.size)}), ` +
|
|
365
|
-
`exceeding the ${formatBytes(maxReadBytes)} context limit. ` +
|
|
366
|
-
`Please use 'mcp_context-mode_ctx_execute' or append '| Select-Object -First 50' or '-Head 50'.`,
|
|
428
|
+
reason,
|
|
367
429
|
size: stat.size,
|
|
368
|
-
targetPath:
|
|
430
|
+
targetPath: sourceId
|
|
369
431
|
};
|
|
370
432
|
}
|
|
371
433
|
|
|
@@ -379,7 +441,7 @@ export function inspectCommand({ commandLine, cwd, sessionId }) {
|
|
|
379
441
|
shouldDeny: true,
|
|
380
442
|
reason:
|
|
381
443
|
`[context-mode protection] Command matches an un-paged file dump ('${rawTarget}') that could flood the context window. ` +
|
|
382
|
-
`Please use 'mcp_context-mode_ctx_execute' or
|
|
444
|
+
`Please use 'mcp_context-mode_ctx_execute' or limit output to only needed lines (<= ${maxLineRange} lines, e.g. '| Select-Object -First <lines>' or '| head -n <lines>').`,
|
|
383
445
|
size: 32768,
|
|
384
446
|
targetPath: cleanTarget || rawTarget
|
|
385
447
|
};
|
|
@@ -447,11 +509,44 @@ async function main() {
|
|
|
447
509
|
const isWideRange = maxLineRange > 0 && (endLine === null || (endLine - startLine) > maxLineRange);
|
|
448
510
|
|
|
449
511
|
if (isLargeFile && isWideRange) {
|
|
450
|
-
const lineInstruction = maxLineRange > 0 ? ` or
|
|
451
|
-
const
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
512
|
+
const lineInstruction = maxLineRange > 0 ? ` or read only the needed lines with StartLine/EndLine (<= ${maxLineRange} lines).` : "";
|
|
513
|
+
const maxAutoIndexBytes = getMaxAutoIndexBytes(sessionId);
|
|
514
|
+
const sourceId = resolveFileSourceId(absPath, cwd) || filePath;
|
|
515
|
+
|
|
516
|
+
let isAutoIndexed = false;
|
|
517
|
+
if (maxAutoIndexBytes > 0 && stat.size <= maxAutoIndexBytes) {
|
|
518
|
+
try {
|
|
519
|
+
const store = new ContextModeStore();
|
|
520
|
+
const content = fs.readFileSync(absPath, "utf8");
|
|
521
|
+
store.indexContent({
|
|
522
|
+
sessionId,
|
|
523
|
+
worktree: cwd,
|
|
524
|
+
agent: agentName,
|
|
525
|
+
kind: "file",
|
|
526
|
+
label: sourceId,
|
|
527
|
+
sourceId,
|
|
528
|
+
content
|
|
529
|
+
});
|
|
530
|
+
store.close();
|
|
531
|
+
isAutoIndexed = true;
|
|
532
|
+
} catch {}
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
let reason = "";
|
|
536
|
+
if (isAutoIndexed) {
|
|
537
|
+
reason =
|
|
538
|
+
`[context-mode protection: auto-indexed] File '${sourceId}' (${formatBytes(stat.size)}) ` +
|
|
539
|
+
`exceeded the active ${formatBytes(maxReadBytes)} context limit. ` +
|
|
540
|
+
`The file has been automatically indexed into Context Mode as source '${sourceId}'. ` +
|
|
541
|
+
`Query it immediately using 'mcp_context-mode_ctx_search(queries: [...], sourceId: "${sourceId}")'${lineInstruction}`;
|
|
542
|
+
} else {
|
|
543
|
+
const ceilingNote = maxAutoIndexBytes > 0 && stat.size > maxAutoIndexBytes
|
|
544
|
+
? ` and the ${formatBytes(maxAutoIndexBytes)} auto-indexing ceiling`
|
|
545
|
+
: "";
|
|
546
|
+
reason =
|
|
547
|
+
`[context-mode protection] File is ${formatBytes(stat.size)}, exceeding the active ${formatBytes(maxReadBytes)} context limit${ceilingNote}. ` +
|
|
548
|
+
`Please use 'mcp_context-mode_ctx_index(path: "${filePath}")' or 'mcp_context-mode_ctx_execute'${lineInstruction}`;
|
|
549
|
+
}
|
|
455
550
|
|
|
456
551
|
// Record interception event in SQLite store so dashboard telemetry updates immediately
|
|
457
552
|
recordInterception({
|
|
@@ -459,7 +554,7 @@ async function main() {
|
|
|
459
554
|
agent: agentName,
|
|
460
555
|
cwd,
|
|
461
556
|
toolName,
|
|
462
|
-
path:
|
|
557
|
+
path: sourceId,
|
|
463
558
|
size: stat.size,
|
|
464
559
|
reason
|
|
465
560
|
});
|
|
@@ -514,7 +609,15 @@ async function main() {
|
|
|
514
609
|
process.exit(0);
|
|
515
610
|
}
|
|
516
611
|
|
|
517
|
-
|
|
518
|
-
process.
|
|
519
|
-
|
|
520
|
-
|
|
612
|
+
const isMain = Boolean(
|
|
613
|
+
process.argv[1] &&
|
|
614
|
+
path.resolve(fileURLToPath(import.meta.url)).toLowerCase() ===
|
|
615
|
+
path.resolve(process.argv[1]).toLowerCase()
|
|
616
|
+
);
|
|
617
|
+
|
|
618
|
+
if (isMain) {
|
|
619
|
+
main().catch(() => {
|
|
620
|
+
process.stdout.write(JSON.stringify({ decision: "allow" }) + "\n");
|
|
621
|
+
process.exit(0);
|
|
622
|
+
});
|
|
623
|
+
}
|
package/hooks/session-start.js
CHANGED
|
@@ -1,5 +1,8 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { fileURLToPath } from "node:url";
|
|
4
|
+
import { ContextModeStore, formatExemptSummary } from "../lib/store.js";
|
|
5
|
+
import { resolveSharedSessionId, formatBytes, getMaxLineRange } from "./pre-tool-use.js";
|
|
3
6
|
|
|
4
7
|
function readStdin() {
|
|
5
8
|
return new Promise((resolve) => {
|
|
@@ -14,21 +17,78 @@ function readStdin() {
|
|
|
14
17
|
});
|
|
15
18
|
}
|
|
16
19
|
|
|
20
|
+
export function buildStatusMessage({
|
|
21
|
+
cutoff = 8192,
|
|
22
|
+
exemptCategories = [],
|
|
23
|
+
exemptExtensions = [],
|
|
24
|
+
customExtensions = [],
|
|
25
|
+
isUpdate = false
|
|
26
|
+
} = {}) {
|
|
27
|
+
const cutoffFormatted =
|
|
28
|
+
cutoff === 0
|
|
29
|
+
? "Disabled (unlimited)"
|
|
30
|
+
: `${formatBytes(cutoff)} (${cutoff.toLocaleString()} bytes)`;
|
|
31
|
+
|
|
32
|
+
const exemptSummary = formatExemptSummary({
|
|
33
|
+
activeCats: exemptCategories,
|
|
34
|
+
customs: customExtensions
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
const header = isUpdate
|
|
38
|
+
? "[context-mode config update]"
|
|
39
|
+
: "[context-mode active]";
|
|
40
|
+
|
|
41
|
+
const lines = [
|
|
42
|
+
header,
|
|
43
|
+
`• Read cutoff: ${cutoffFormatted}`,
|
|
44
|
+
`• Exempt file types: ${exemptSummary || "None"}`
|
|
45
|
+
];
|
|
46
|
+
|
|
47
|
+
return lines.join("\n");
|
|
48
|
+
}
|
|
49
|
+
|
|
17
50
|
async function main() {
|
|
18
|
-
await readStdin();
|
|
51
|
+
const rawInput = await readStdin();
|
|
52
|
+
let payload = {};
|
|
53
|
+
try {
|
|
54
|
+
if (rawInput && rawInput.trim()) {
|
|
55
|
+
payload = JSON.parse(rawInput);
|
|
56
|
+
}
|
|
57
|
+
} catch {}
|
|
58
|
+
|
|
59
|
+
const sessionId = resolveSharedSessionId(payload);
|
|
60
|
+
let cutoff = 8192;
|
|
61
|
+
let exemptCats = [];
|
|
62
|
+
let exemptExts = [];
|
|
63
|
+
let customExts = [];
|
|
19
64
|
|
|
20
65
|
try {
|
|
21
66
|
const store = new ContextModeStore();
|
|
22
67
|
store.clearSessionOverrides();
|
|
68
|
+
cutoff = store.getCutoff(sessionId);
|
|
69
|
+
exemptCats = store.getExemptCategories(sessionId);
|
|
70
|
+
exemptExts = store.getExemptExtensions(sessionId);
|
|
71
|
+
customExts = store.getCustomExemptExtensions(sessionId);
|
|
72
|
+
|
|
73
|
+
// Save informed configuration signature for this session so PreInvocation stays in sync
|
|
74
|
+
const sig = `${cutoff}:${exemptExts.slice().sort().join(",")}`;
|
|
75
|
+
store.setMeta(`informed_config:session:${sessionId}`, sig);
|
|
23
76
|
store.close();
|
|
24
77
|
} catch {}
|
|
25
78
|
|
|
79
|
+
const message = buildStatusMessage({
|
|
80
|
+
cutoff,
|
|
81
|
+
exemptCategories: exemptCats,
|
|
82
|
+
exemptExtensions: exemptExts,
|
|
83
|
+
customExtensions: customExts,
|
|
84
|
+
isUpdate: false
|
|
85
|
+
});
|
|
86
|
+
|
|
26
87
|
const response = {
|
|
27
88
|
injectSteps: [
|
|
28
89
|
{
|
|
29
90
|
systemMessage: {
|
|
30
|
-
systemMessage:
|
|
31
|
-
"context-mode active: Tool executions are protected against context window bloat via SQLite FTS5 BM25 search and local sandboxed execution. For heavy logs, large files, or bulk queries, use ctx_execute or ctx_search."
|
|
91
|
+
systemMessage: message
|
|
32
92
|
}
|
|
33
93
|
}
|
|
34
94
|
]
|
|
@@ -37,6 +97,14 @@ async function main() {
|
|
|
37
97
|
process.stdout.write(JSON.stringify(response) + "\n");
|
|
38
98
|
}
|
|
39
99
|
|
|
40
|
-
|
|
41
|
-
process.
|
|
42
|
-
|
|
100
|
+
const isMain = Boolean(
|
|
101
|
+
process.argv[1] &&
|
|
102
|
+
path.resolve(fileURLToPath(import.meta.url)).toLowerCase() ===
|
|
103
|
+
path.resolve(process.argv[1]).toLowerCase()
|
|
104
|
+
);
|
|
105
|
+
|
|
106
|
+
if (isMain) {
|
|
107
|
+
main().catch(() => {
|
|
108
|
+
process.stdout.write(JSON.stringify({}) + "\n");
|
|
109
|
+
});
|
|
110
|
+
}
|
package/hooks.json
CHANGED
package/lib/store.js
CHANGED
|
@@ -54,6 +54,53 @@ export const DEFAULT_EXEMPT_EXTENSIONS = Array.from(
|
|
|
54
54
|
)
|
|
55
55
|
);
|
|
56
56
|
|
|
57
|
+
/** Format active categories and custom extensions into a human-readable summary */
|
|
58
|
+
export function formatExemptSummary({ activeCats = [], customs = [] } = {}) {
|
|
59
|
+
const categoryLabels = {
|
|
60
|
+
images: "Images (.png, .jpg, etc.)",
|
|
61
|
+
documents: "Documents & Office (.pdf, .docx, etc.)",
|
|
62
|
+
code: "Source Code (.js, .py, etc.)",
|
|
63
|
+
models3d: "3D Models (.blend, .obj, etc.)",
|
|
64
|
+
music: "Audio (.mp3, .wav, etc.)",
|
|
65
|
+
video: "Video (.mp4, .mkv, etc.)",
|
|
66
|
+
archives: "Archives & Binaries (.zip, .tar, etc.)"
|
|
67
|
+
};
|
|
68
|
+
|
|
69
|
+
const labels = activeCats
|
|
70
|
+
.map((c) => categoryLabels[c] || (FILE_CATEGORIES[c] ? `${FILE_CATEGORIES[c].name}` : c))
|
|
71
|
+
.filter(Boolean);
|
|
72
|
+
|
|
73
|
+
const parts = [];
|
|
74
|
+
if (labels.length > 0) {
|
|
75
|
+
parts.push(labels.join(", "));
|
|
76
|
+
} else {
|
|
77
|
+
parts.push("No categories");
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
if (customs && customs.length > 0) {
|
|
81
|
+
parts.push(`Custom (${customs.join(", ")})`);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
parts.push("prompt attachments in .user_uploaded/");
|
|
85
|
+
return parts.join(", ");
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** Default max file size (50 MB) automatically indexed on cutoff block */
|
|
89
|
+
export const DEFAULT_MAX_AUTO_INDEX_BYTES = 50 * 1024 * 1024; // 52,428,800 bytes
|
|
90
|
+
|
|
91
|
+
/** Resolve intuitive file sourceId: workspace-relative when inside project, normalized absolute when outside */
|
|
92
|
+
export function resolveFileSourceId(filePath, cwd = process.cwd()) {
|
|
93
|
+
if (!filePath) return null;
|
|
94
|
+
const absPath = path.isAbsolute(filePath) ? path.normalize(filePath) : path.resolve(cwd, filePath);
|
|
95
|
+
const normCwd = path.normalize(cwd);
|
|
96
|
+
|
|
97
|
+
const rel = path.relative(normCwd, absPath);
|
|
98
|
+
if (!rel.startsWith("..") && !path.isAbsolute(rel)) {
|
|
99
|
+
return rel.replace(/\\/g, "/");
|
|
100
|
+
}
|
|
101
|
+
return absPath.replace(/\\/g, "/");
|
|
102
|
+
}
|
|
103
|
+
|
|
57
104
|
/** Default path to context database (~/.context-mode/context.db) */
|
|
58
105
|
export function getDefaultDbPath() {
|
|
59
106
|
if (process.env.CONTEXT_MODE_DB_PATH && process.env.CONTEXT_MODE_DB_PATH.trim()) {
|
|
@@ -268,6 +315,10 @@ export class ContextModeStore {
|
|
|
268
315
|
|
|
269
316
|
insertSource.run(id, sid, wt, ag, k, lbl, totalBytes, chunkCount, now, isoDate, now);
|
|
270
317
|
|
|
318
|
+
// Clean up any existing chunks for this sourceId to ensure idempotent re-indexing
|
|
319
|
+
this.db.prepare("DELETE FROM chunks WHERE source_id = ?").run(id);
|
|
320
|
+
this.db.prepare("DELETE FROM chunks_tri WHERE source_id = ?").run(id);
|
|
321
|
+
|
|
271
322
|
for (let ord = 0; ord < chunkCount; ord++) {
|
|
272
323
|
const chunkText = chunks[ord];
|
|
273
324
|
insertChunk.run(id, sid, wt, ag, ord, chunkText, lbl);
|
|
@@ -596,8 +647,11 @@ export class ContextModeStore {
|
|
|
596
647
|
WHERE s.kind NOT IN ('execution', 'batch', 'tool_output', 'exec')
|
|
597
648
|
AND NOT EXISTS (
|
|
598
649
|
SELECT 1 FROM events e
|
|
599
|
-
WHERE
|
|
600
|
-
AND e.sandbox_bytes = s.bytes_total
|
|
650
|
+
WHERE (
|
|
651
|
+
(e.tool = 'ctx_index' AND e.sandbox_bytes = s.bytes_total)
|
|
652
|
+
OR e.path = s.id
|
|
653
|
+
OR e.path = s.label
|
|
654
|
+
)
|
|
601
655
|
)
|
|
602
656
|
`).get();
|
|
603
657
|
} else if (sid === "app" && sinceIso) {
|
|
@@ -627,8 +681,11 @@ export class ContextModeStore {
|
|
|
627
681
|
AND s.kind NOT IN ('execution', 'batch', 'tool_output', 'exec')
|
|
628
682
|
AND NOT EXISTS (
|
|
629
683
|
SELECT 1 FROM events e
|
|
630
|
-
WHERE
|
|
631
|
-
AND e.sandbox_bytes = s.bytes_total
|
|
684
|
+
WHERE (
|
|
685
|
+
(e.tool = 'ctx_index' AND e.sandbox_bytes = s.bytes_total)
|
|
686
|
+
OR e.path = s.id
|
|
687
|
+
OR e.path = s.label
|
|
688
|
+
)
|
|
632
689
|
)
|
|
633
690
|
`).get(sinceIso, sinceTs);
|
|
634
691
|
} else {
|
|
@@ -659,8 +716,11 @@ export class ContextModeStore {
|
|
|
659
716
|
AND NOT EXISTS (
|
|
660
717
|
SELECT 1 FROM events e
|
|
661
718
|
WHERE e.session_id = s.session_id
|
|
662
|
-
AND
|
|
663
|
-
|
|
719
|
+
AND (
|
|
720
|
+
(e.tool = 'ctx_index' AND e.sandbox_bytes = s.bytes_total)
|
|
721
|
+
OR e.path = s.id
|
|
722
|
+
OR e.path = s.label
|
|
723
|
+
)
|
|
664
724
|
)
|
|
665
725
|
`).get(sid);
|
|
666
726
|
}
|
|
@@ -840,6 +900,60 @@ export class ContextModeStore {
|
|
|
840
900
|
return numVal;
|
|
841
901
|
}
|
|
842
902
|
|
|
903
|
+
/** Get active auto-indexing max file size in bytes (default 50 MB, 0 = disabled) */
|
|
904
|
+
getMaxAutoIndexBytes(sessionId = null) {
|
|
905
|
+
this.open();
|
|
906
|
+
// 1. Session/Conversation override
|
|
907
|
+
if (sessionId && sessionId !== "all" && sessionId !== "lifetime") {
|
|
908
|
+
const sessionVal = this.getMeta(`max_auto_index:session:${sessionId}`);
|
|
909
|
+
if (sessionVal !== null) {
|
|
910
|
+
return parseInt(sessionVal, 10);
|
|
911
|
+
}
|
|
912
|
+
if (sessionId !== "app") {
|
|
913
|
+
const appVal = this.getMeta("max_auto_index:session:app");
|
|
914
|
+
if (appVal !== null) {
|
|
915
|
+
return parseInt(appVal, 10);
|
|
916
|
+
}
|
|
917
|
+
}
|
|
918
|
+
}
|
|
919
|
+
|
|
920
|
+
// 2. Environment variable if explicitly set
|
|
921
|
+
const envVal = process.env.CONTEXT_MODE_MAX_AUTO_INDEX_BYTES;
|
|
922
|
+
if (envVal) {
|
|
923
|
+
const parsed = parseInt(envVal, 10);
|
|
924
|
+
if (!Number.isNaN(parsed)) return parsed;
|
|
925
|
+
}
|
|
926
|
+
|
|
927
|
+
// 3. Saved global setting in SQLite
|
|
928
|
+
const globalVal = this.getMeta("max_auto_index:global");
|
|
929
|
+
if (globalVal !== null) {
|
|
930
|
+
return parseInt(globalVal, 10);
|
|
931
|
+
}
|
|
932
|
+
|
|
933
|
+
// 4. Default 50 MB
|
|
934
|
+
return DEFAULT_MAX_AUTO_INDEX_BYTES;
|
|
935
|
+
}
|
|
936
|
+
|
|
937
|
+
/** Set auto-indexing max file size in bytes (0 = disabled) */
|
|
938
|
+
setMaxAutoIndexBytes(bytes, sessionId = null) {
|
|
939
|
+
this.open();
|
|
940
|
+
const val = parseInt(bytes, 10);
|
|
941
|
+
const numVal = Number.isNaN(val) ? DEFAULT_MAX_AUTO_INDEX_BYTES : Math.max(0, val);
|
|
942
|
+
if (sessionId && sessionId !== "all" && sessionId !== "lifetime") {
|
|
943
|
+
this.setMeta(`max_auto_index:session:${sessionId}`, numVal);
|
|
944
|
+
} else {
|
|
945
|
+
this.setMeta("max_auto_index:global", numVal);
|
|
946
|
+
this.deleteMeta("max_auto_index:session:app");
|
|
947
|
+
this.deleteMeta("max_auto_index:session:default");
|
|
948
|
+
}
|
|
949
|
+
return numVal;
|
|
950
|
+
}
|
|
951
|
+
|
|
952
|
+
/** Resolve intuitive file sourceId: workspace-relative when inside project, normalized absolute when outside */
|
|
953
|
+
resolveFileSourceId(filePath, cwd = process.cwd()) {
|
|
954
|
+
return resolveFileSourceId(filePath, cwd);
|
|
955
|
+
}
|
|
956
|
+
|
|
843
957
|
/** Internal helper to recompute and save the combined exempt_ext list */
|
|
844
958
|
_recomputeExemptExtensions(sessionId = null) {
|
|
845
959
|
const activeCats = this.getExemptCategories(sessionId);
|
|
@@ -1038,6 +1152,14 @@ export class ContextModeStore {
|
|
|
1038
1152
|
return [...DEFAULT_EXEMPT_EXTENSIONS];
|
|
1039
1153
|
}
|
|
1040
1154
|
|
|
1155
|
+
/** Get live human-readable summary of active exempt categories and custom extensions */
|
|
1156
|
+
getExemptSummary(sessionId = null) {
|
|
1157
|
+
this.open();
|
|
1158
|
+
const activeCats = this.getExemptCategories(sessionId);
|
|
1159
|
+
const customs = this.getCustomExemptExtensions(sessionId);
|
|
1160
|
+
return formatExemptSummary({ activeCats, customs });
|
|
1161
|
+
}
|
|
1162
|
+
|
|
1041
1163
|
/** Set list of file extensions exempt from the size cutoff */
|
|
1042
1164
|
setExemptExtensions(extensions, sessionId = null) {
|
|
1043
1165
|
this.open();
|
package/lib/tools.js
CHANGED
|
@@ -3,7 +3,7 @@ import path from "node:path";
|
|
|
3
3
|
import http from "node:http";
|
|
4
4
|
import https from "node:https";
|
|
5
5
|
import { executeCode, runProcess, OUTPUT_CAP } from "./executor.js";
|
|
6
|
-
import { SNIPPET_MAX_BYTES } from "./store.js";
|
|
6
|
+
import { SNIPPET_MAX_BYTES, resolveFileSourceId } from "./store.js";
|
|
7
7
|
|
|
8
8
|
const EXEC_PREVIEW_BYTES = 4096;
|
|
9
9
|
|
|
@@ -224,12 +224,15 @@ export function createTools({ store, getCwd = () => process.cwd(), getSessionId
|
|
|
224
224
|
throw new Error("No content, file path, or url provided to index");
|
|
225
225
|
}
|
|
226
226
|
|
|
227
|
+
const fileSourceId = filePath ? resolveFileSourceId(filePath, cwd) : null;
|
|
228
|
+
|
|
227
229
|
const indexed = store.indexContent({
|
|
228
230
|
sessionId,
|
|
229
231
|
worktree: cwd,
|
|
230
232
|
agent: "antigravity",
|
|
231
233
|
kind: url ? "web" : filePath ? "file" : "text",
|
|
232
|
-
label: resolvedLabel || "manual_index",
|
|
234
|
+
label: resolvedLabel || fileSourceId || "manual_index",
|
|
235
|
+
sourceId: fileSourceId || undefined,
|
|
233
236
|
content: rawText
|
|
234
237
|
});
|
|
235
238
|
|
|
@@ -317,6 +320,14 @@ export function createTools({ store, getCwd = () => process.cwd(), getSessionId
|
|
|
317
320
|
}
|
|
318
321
|
|
|
319
322
|
const s = store.getStats(sessionId);
|
|
323
|
+
const cutoffBytes = store.getCutoff(sessionId);
|
|
324
|
+
const cutoffStr = cutoffBytes === 0 ? "Disabled (unlimited)" : `${formatBytes(cutoffBytes)} (${cutoffBytes.toLocaleString()} bytes)`;
|
|
325
|
+
const autoIndexBytes = store.getMaxAutoIndexBytes(sessionId);
|
|
326
|
+
const autoIndexStr = autoIndexBytes === 0 ? "Disabled (off)" : `${formatBytes(autoIndexBytes)} (${autoIndexBytes.toLocaleString()} bytes)`;
|
|
327
|
+
const exemptCats = store.getExemptCategories(sessionId);
|
|
328
|
+
const exemptExts = store.getExemptExtensions(sessionId);
|
|
329
|
+
const customExts = store.getCustomExemptExtensions(sessionId);
|
|
330
|
+
|
|
320
331
|
const report = [
|
|
321
332
|
"────────────────────────────────────────────────────────────────────────────────",
|
|
322
333
|
` Antigravity context-mode stats [session: ${sessionId}]`,
|
|
@@ -327,22 +338,48 @@ export function createTools({ store, getCwd = () => process.cwd(), getSessionId
|
|
|
327
338
|
` Tokens Kept Out: ~${s.tokensKeptOut.toLocaleString()} tokens (${formatBytes(s.keptOutBytes)})`,
|
|
328
339
|
` Reduction Rate: ${s.savingsPercent}% saved`,
|
|
329
340
|
"",
|
|
341
|
+
` Active Read Cutoff: ${cutoffStr} (tool read cutoff, NOT LLM context window)`,
|
|
342
|
+
` Auto-Index Ceiling: ${autoIndexStr} (auto-indexes files on block)`,
|
|
343
|
+
` Exempt Categories: ${exemptCats.join(", ")}`,
|
|
344
|
+
` Exempt Extensions: ${exemptExts.length} extensions (e.g. .png, .pdf, .docx, .zip; never blocked)`,
|
|
345
|
+
...(customExts.length > 0 ? [` Custom Exemptions: ${customExts.join(", ")}`] : []),
|
|
346
|
+
"",
|
|
330
347
|
` Without context-mode ${renderBar(1.0)} ${formatBytes(s.totalRawBytes)}`,
|
|
331
348
|
` With context-mode ${renderBar(s.totalRawBytes > 0 ? s.totalReturnedBytes / s.totalRawBytes : 0)} ${formatBytes(s.totalReturnedBytes)}`,
|
|
332
349
|
"────────────────────────────────────────────────────────────────────────────────"
|
|
333
350
|
].join("\n");
|
|
334
351
|
|
|
335
352
|
return {
|
|
336
|
-
stats:
|
|
353
|
+
stats: {
|
|
354
|
+
...s,
|
|
355
|
+
activeCutoffBytes: cutoffBytes,
|
|
356
|
+
activeCutoffFormatted: cutoffStr,
|
|
357
|
+
maxAutoIndexBytes: autoIndexBytes,
|
|
358
|
+
maxAutoIndexFormatted: autoIndexStr,
|
|
359
|
+
exemptCategories: exemptCats,
|
|
360
|
+
exemptExtensions: exemptExts,
|
|
361
|
+
customExemptExtensions: customExts
|
|
362
|
+
},
|
|
337
363
|
report
|
|
338
364
|
};
|
|
339
365
|
},
|
|
340
366
|
|
|
341
367
|
// 7. ctx_doctor
|
|
342
368
|
async ctx_doctor() {
|
|
369
|
+
const sessionId = getSessionId();
|
|
343
370
|
const doc = store.doctor();
|
|
371
|
+
const cutoffBytes = store.getCutoff(sessionId);
|
|
372
|
+
const exemptCats = store.getExemptCategories(sessionId);
|
|
373
|
+
const exemptExts = store.getExemptExtensions(sessionId);
|
|
374
|
+
|
|
344
375
|
return {
|
|
345
|
-
doctor:
|
|
376
|
+
doctor: {
|
|
377
|
+
...doc,
|
|
378
|
+
activeCutoffBytes: cutoffBytes,
|
|
379
|
+
activeCutoffFormatted: cutoffBytes === 0 ? "Disabled (unlimited)" : `${formatBytes(cutoffBytes)} (${cutoffBytes.toLocaleString()} bytes)`,
|
|
380
|
+
exemptCategories: exemptCats,
|
|
381
|
+
exemptExtensionsCount: exemptExts.length
|
|
382
|
+
},
|
|
346
383
|
runtimes: {
|
|
347
384
|
node: process.version,
|
|
348
385
|
platform: process.platform,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "antigravity-plugin-context-mode",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.4.0",
|
|
4
4
|
"description": "Native Antigravity plugin for context-mode: SQLite FTS5 indexing, sandboxed execution, and lifecycle hook protection against context window bloat",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
package/plugin.json
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"name": "antigravity-plugin-context-mode",
|
|
3
3
|
"displayName": "Context Mode",
|
|
4
4
|
"description": "Context window protection for Antigravity: local SQLite FTS5 search, sandboxed execution, and lifecycle hook gating against token bloat.",
|
|
5
|
-
"version": "1.
|
|
5
|
+
"version": "1.4.0",
|
|
6
6
|
"author": "Phillip Webber <github@webbsense.com>",
|
|
7
7
|
"repository": {
|
|
8
8
|
"type": "git",
|
package/rules/AGENTS.md
CHANGED
|
@@ -1,8 +1,20 @@
|
|
|
1
1
|
# Context Mode Behavioral Standards
|
|
2
2
|
|
|
3
|
-
When `antigravity-plugin-context-mode` is active, agents MUST adhere to context budgeting laws:
|
|
3
|
+
When `antigravity-plugin-context-mode` is active, agents MUST adhere to context budgeting laws while understanding active limits:
|
|
4
4
|
|
|
5
|
-
1. **
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
5
|
+
1. **Active Read Cutoff vs LLM Context Window**:
|
|
6
|
+
- The active cutoff limit (default 8 KB per file/command, or as configured per session) is a **single-operation tool read/command cutoff** enforced by `PreToolUse` to prevent accidental token bloat.
|
|
7
|
+
- It is **NOT your LLM context window**. Your LLM context window is vastly larger. Do NOT assume your context window is 8 KB.
|
|
8
|
+
- Files or command outputs within the active cutoff limit can always be read directly.
|
|
9
|
+
|
|
10
|
+
2. **Non-Exempt Text and Code Files & Automatic Indexing**:
|
|
11
|
+
- For non-exempt text files (code, logs, json, yaml, etc.) that exceed the active cutoff:
|
|
12
|
+
- **Automatic Indexing**: Intercepted file reads and unpaged dumps of files up to 50 MB are **automatically indexed** into Context Mode. The denial notice provides the intuitive file-path `sourceId` (e.g. `Logs/Editor.log`) so you can immediately search it via `ctx_search(queries: [...], sourceId: "...")` without needing to call `ctx_index` manually.
|
|
13
|
+
- **Line Slices**: Or read only the lines needed with `StartLine` and `EndLine` (within the active line limit).
|
|
14
|
+
- **Script Filtering**: Or inspect/filter with short scripts via `ctx_execute`.
|
|
15
|
+
|
|
16
|
+
3. **Zero Raw Log Dumps**: Never run unbounded terminal commands (`cat`, `Get-Content`, `type`, unpaged `git log`, direct `curl`/`wget` to stdout). Pipe to limiters for only the specific lines needed (e.g. `| Select-Object -First <lines>` or `| head -n <lines>`) or run via `ctx_execute`.
|
|
17
|
+
|
|
18
|
+
4. **Token Verification & Active Status**:
|
|
19
|
+
- The active cutoff limit and currently active exempt file types are dynamically announced in the session status message and on configuration changes.
|
|
20
|
+
- To inspect live token savings, the active cutoff, and live exemption status at any time, run `ctx_stats` or `ctx_doctor`.
|
|
@@ -10,12 +10,23 @@ Instead of dumping megabytes of text into the conversation, Context Mode indexes
|
|
|
10
10
|
|
|
11
11
|
---
|
|
12
12
|
|
|
13
|
+
## Active Read Cutoff vs LLM Context Window
|
|
14
|
+
|
|
15
|
+
Context Mode enforces a single-operation read/command cutoff (default 8 KB, configurable per session or globally).
|
|
16
|
+
|
|
17
|
+
* **Tool-Level Read Cutoff**: This threshold applies strictly to individual `read_file` calls or terminal dump commands (`cat`, `Get-Content`, `type`) on non-exempt text/code files to protect against accidental bloat.
|
|
18
|
+
* **NOT the LLM Context Window**: The model retains its full, large context window capacity. Do **not** confuse the tool-level read cutoff (e.g. 8 KB) with the model's context window.
|
|
19
|
+
* **Dynamic Active Exemptions**: Active file category exemptions and custom extensions are dynamically loaded from SQLite and injected into your session by the `SessionStart` and `PreInvocation` hooks. Files matching active exemptions bypass cutoff protection. Use `ctx_stats` or `ctx_doctor` to check live exemptions at any time.
|
|
20
|
+
* **Automatic Indexing on Interception**: When a non-exempt file read or unpaged command dump exceeds the active cutoff, Context Mode automatically indexes files up to 50 MB (configurable) into SQLite FTS5. The denial message returns the intuitive file-path `sourceId` (e.g. `Logs/Editor.log`), enabling you to immediately search it using `ctx_search(queries: [...], sourceId: "...")` without having to run `ctx_index` first.
|
|
21
|
+
|
|
22
|
+
---
|
|
23
|
+
|
|
13
24
|
## When to Use Context Mode
|
|
14
25
|
|
|
15
26
|
| Task | Traditional Tool (High Bloat) | Context Mode Solution (Zero Bloat) |
|
|
16
27
|
| :--- | :--- | :--- |
|
|
17
28
|
| **Analyzing build or server logs** | `run_command("Get-Content Logs/Editor.log")` | `ctx_execute(code: "...", intent: "Find compile errors in Editor.log")` |
|
|
18
|
-
| **Searching huge documentation or code** | Full `read_file`
|
|
29
|
+
| **Searching huge documentation or code** | Full un-paged `read_file` | `ctx_index(path: "...")` $\rightarrow$ `ctx_search(queries: ["..."])` |
|
|
19
30
|
| **Processing API JSON responses** | Fetching and dumping 5,000 JSON items | `ctx_execute(language: "javascript", code: "fetch(...)")` |
|
|
20
31
|
| **Running multi-command batches** | Running 10 commands in separate tool calls | `ctx_batch(commands: [...], queries: [...])` |
|
|
21
32
|
| **Session recovery & token stats** | Re-reading entire past conversation | `ctx_resume()` / `ctx_stats()` |
|
|
@@ -67,18 +78,20 @@ Executes multiple shell commands in batch. The combined outputs are indexed and
|
|
|
67
78
|
```
|
|
68
79
|
|
|
69
80
|
### 5. `ctx_stats`
|
|
70
|
-
Generates a token savings report showing
|
|
81
|
+
Generates a token savings and status report showing active cutoff, exempt categories, raw bytes handled, and estimated tokens kept out of the model's context window:
|
|
71
82
|
```json
|
|
72
83
|
{}
|
|
73
84
|
```
|
|
74
85
|
|
|
75
86
|
### 6. `ctx_doctor`
|
|
76
|
-
Checks SQLite database health, FTS5 availability, and active runtimes.
|
|
87
|
+
Checks SQLite database health, active cutoff limits, exempt categories, FTS5 availability, and active runtimes.
|
|
77
88
|
|
|
78
89
|
---
|
|
79
90
|
|
|
80
91
|
## Best Practices
|
|
81
92
|
|
|
82
|
-
1. **
|
|
83
|
-
2. **
|
|
84
|
-
3. **
|
|
93
|
+
1. **Check Active Limits & Exemptions**: At session start or anytime via `ctx_stats` or `ctx_doctor`, verify the active cutoff limit and active exemptions.
|
|
94
|
+
2. **Read Exempt Media Directly**: Multimodal files (images, audio, video, PDFs, Office files, 3D models) are exempt from cutoff limits and will never be blocked by `read_file`.
|
|
95
|
+
3. **Write focused extraction scripts**: In `ctx_execute`, print only the final data structures or count summaries rather than raw loops.
|
|
96
|
+
4. **Never dump full logs**: If a text log file is > 100 KB, never call un-paged `read_file` or bare `Get-Content`. Route it through `ctx_execute` or `ctx_index`.
|
|
97
|
+
5. **Use Trigram for identifiers**: `ctx_search` matches code symbols, GUIDs, and file paths via trigram indexing even if English stemming does not match.
|