antigravity-plugin-context-mode 1.3.2 → 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 CHANGED
@@ -2,6 +2,24 @@
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
+
5
23
  ## [1.3.2] - 2026-11-17
6
24
 
7
25
  ### Documentation
package/README.md CHANGED
@@ -12,7 +12,8 @@
12
12
 
13
13
  > 🌐 **Interactive Live Simulator & Documentation:** [domush.github.io/antigravity-plugin-context-mode](https://domush.github.io/antigravity-plugin-context-mode/)
14
14
 
15
- <img width="846" height="503" alt="image" src="https://github.com/user-attachments/assets/2b89e947-4b53-42a6-a0ad-ea744de96c41" />
15
+ <img width="715" height="632" alt="image" src="https://github.com/user-attachments/assets/952b84a0-3e71-4bd6-99ae-e604532c1c7f" />
16
+
16
17
  ---
17
18
 
18
19
  ## Quick Install (10 Seconds)
@@ -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
+ }
@@ -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 { ContextModeStore } from "../lib/store.js";
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 getMaxLineRange(maxReadBytes = DEFAULT_MAX_READ_BYTES) {
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 append '| head -n 50'.`,
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 append a limiter such as '| Select-Object -First 50'.`,
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: cleanTarget
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 append a limiter such as '| Select-Object -First 50' or '| head -n 50'.`,
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 provide a tight StartLine/EndLine range (<= ${maxLineRange} lines).` : "";
451
- const reason =
452
- `[context-mode protection] File is ${formatBytes(stat.size)} (~${Math.round(stat.size / 4).toLocaleString()} tokens), exceeding the ${formatBytes(maxReadBytes)} context limit. ` +
453
- `Reading the entire file risks severe context bloat. ` +
454
- `Please use 'mcp_context-mode_ctx_index(path: "${filePath}")' followed by 'mcp_context-mode_ctx_search'${lineInstruction}`;
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: filePath,
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
- main().catch(() => {
518
- process.stdout.write(JSON.stringify({ decision: "allow" }) + "\n");
519
- process.exit(0);
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
+ }
@@ -1,5 +1,8 @@
1
1
  #!/usr/bin/env node
2
- import { ContextModeStore } from "../lib/store.js";
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
- main().catch(() => {
41
- process.stdout.write(JSON.stringify({}) + "\n");
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
@@ -18,6 +18,13 @@
18
18
  "command": "node ./hooks/session-start.js",
19
19
  "timeout": 10
20
20
  }
21
+ ],
22
+ "PreInvocation": [
23
+ {
24
+ "type": "command",
25
+ "command": "node ./hooks/pre-invocation.js",
26
+ "timeout": 10
27
+ }
21
28
  ]
22
29
  }
23
30
  }
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 e.tool = 'ctx_index'
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 e.tool = 'ctx_index'
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 e.tool = 'ctx_index'
663
- AND e.sandbox_bytes = s.bytes_total
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: s,
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: doc,
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.2",
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.3.2",
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. **Zero Raw Log Dumps**: Never run unbounded log commands (`cat`, `Get-Content`, `type`) or read files exceeding 400 lines without pagination or line ranges.
6
- 2. **Thinking in Code**: When analyzing large files (>32 KB), parse and filter the data inside a `ctx_execute` script (Node.js, Python, or PowerShell) instead of bringing the raw file content into context.
7
- 3. **FTS5 Search Over Brute Force**: Index reference documents or massive outputs with `ctx_index` and query them with `ctx_search` using precise BM25/Trigram keywords.
8
- 4. **Token Verification**: Verify token savings and database health using `ctx_stats` and `ctx_doctor`.
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` (> 400 lines) | `ctx_index(path: "...")` $\rightarrow$ `ctx_search(queries: ["..."])` |
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 how many raw bytes and estimated tokens were kept out of the model's context window:
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. **Write focused extraction scripts**: In `ctx_execute`, print only the final data structures or count summaries rather than raw loops.
83
- 2. **Never dump full logs**: If a log file is > 100 KB, never call `read_file` or bare `Get-Content`. Route it through `ctx_execute` or `ctx_index`.
84
- 3. **Use Trigram for identifiers**: `ctx_search` matches code symbols, GUIDs, and file paths via trigram indexing even if English stemming does not match.
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.