antigravity-plugin-context-mode 1.2.1 → 1.3.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,19 @@
2
2
 
3
3
  All notable changes to `antigravity-plugin-context-mode` will be documented in this file.
4
4
 
5
+ ## [1.3.0] - 2026-11-15
6
+
7
+ ### Added
8
+ - **Subagent & Primary Agent Unified Lifecycle Hooks**: `PreToolUse` now evaluates all lifecycle checks (un-paged file reads, unbounded command dumps, active cutoffs, and file category exemptions) identically across both primary agents and subagents.
9
+ - **Shared Conversation Dashboard for Subagents**: Interceptions and metrics generated by subagents now resolve to the root/parent conversation ID (`resolveSharedSessionId`), feeding directly into the active conversation dashboard in real-time. Added dedicated subagent badges in the recent activity feed to indicate which subagent triggered the event.
10
+ - **Session Lifecycle Overrides Reset**: Added `clearSessionOverrides()` to `ContextModeStore`. Wired into the `SessionStart` hook and server process initialization so that when a new application session begins (app restart), transient session overrides are cleared and the session starts fresh with the Lifetime default.
11
+ - **Direct Indexing Telemetry (`ctx_index`)**: `ctx_index` now records an event in the `events` journal upon successful indexing, immediately updating dashboard call counts and crediting kept-out tokens.
12
+
13
+ ### Fixed
14
+ - **Lifetime Cutoff Propagation to New Sessions and Conversations**: Changing the cutoff in Lifetime scope (`"all"`, `"lifetime"`, or `null`) now updates `cutoff:global` in SQLite and clears any transient session-level (`cutoff:session:app`) and fallback default (`cutoff:session:default`) overrides. New sessions and new conversations automatically inherit the new Lifetime cutoff as their default.
15
+ - **Accurate Context Saved Calculations (Eliminated Double-Counting)**: Refactored `getStats()` to prevent execution outputs from being counted twice across `events` (`sandbox_bytes`) and `sources` (`bytes_total`). Raw, returned, and kept-out bytes are now computed on a per-event basis with `MAX(sandbox_bytes, bytes, returned_bytes)`, ensuring passthrough commands with full returns do not penalize the savings of other tools.
16
+ - **MCP Server Root Session Binding**: `server.js` and `createTools` now bind session ID resolution to `process.env.ANTIGRAVITY_ROOT_CONVERSATION_ID` and `process.env.ANTIGRAVITY_PARENT_CONVERSATION_ID`, ensuring MCP tool calls from subagents share indexed chunks and search states with the primary conversation.
17
+
5
18
  ## [1.2.1] - 2026-11-15
6
19
 
7
20
  ### Fixed
package/README.md CHANGED
@@ -59,10 +59,10 @@ When an AI coding agent runs tools, standard workflows dump everything directly
59
59
  relevant answer to the chat!
60
60
  ```
61
61
 
62
- 1. **Smart Lifecycle Gating (`hooks.json`)**: Before a command or file read executes, Context Mode checks if it will cause a context flood. If it exceeds 8 KB or attempts an unbounded file dump, the hook intercepts it and guides the agent to query or sandbox the data instead.
62
+ 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.
63
63
  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.
64
- 3. **Local SQLite FTS5 Storage (`ctx_search`, `ctx_index`)**: Raw outputs 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.
65
- 4. **Live Sidecar Dashboard**: A native side pane right inside the Antigravity App that displays real-time context savings, lets you toggle file categories on the fly, and search indexed data with a click.
64
+ 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.
65
+ 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.
66
66
 
67
67
  ---
68
68
 
@@ -115,9 +115,10 @@ Context Mode includes a native web dashboard that opens directly in Antigravity'
115
115
  * **Dynamic Version Badge:** Automatically reflects the active plugin version in the top-right header.
116
116
  * **Context Saved Progress Bar:** Visual indicator displaying the exact percentage of context window preserved.
117
117
  * **3-Way Scope Toggle:** Seamlessly inspect telemetry at three distinct levels:
118
- * **Conversation**: Metrics strictly for the active chat; clean slate on new conversations.
119
- * **Session**: Metrics aggregated across all conversations since the app restarted.
120
- * **Lifetime**: All-time cumulative database metrics and persistent totals.
118
+ * **Conversation**: Metrics strictly for the active chat; clean slate on new conversations. Subagent actions within the conversation feed directly into this view.
119
+ * **Session**: Metrics aggregated across all conversations since the app restarted. Automatically resets transient overrides on app reboot.
120
+ * **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.
121
+ * **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.
121
122
  * **File Category Toggles:** Clean, one-click pills for grouping exemptions without reading massive lists:
122
123
  * **Images** (`.png`, `.jpg`, `.jpeg`, `.gif`, `.webp`, `.svg`, `.bmp`, `.ico`, `.tiff`, `.psd`) — *Enabled by default*
123
124
  * **Documents** (`.pdf`, `.docx`, `.doc`, `.xlsx`, `.xls`, `.pptx`, `.ppt`, `.odt`, `.rtf`) — *Enabled by default*
@@ -194,7 +195,10 @@ Verifies:
194
195
  * SQLite FTS5 schema initialization, chunking, Porter BM25, and Trigram search.
195
196
  * Reciprocal Rank Fusion (RRF) ranking.
196
197
  * Sandbox execution and process timeout termination.
197
- * `PreToolUse` and `SessionStart` lifecycle hook gating.
198
+ * `PreToolUse` and `SessionStart` lifecycle hook gating for primary agents and subagents.
199
+ * Shared conversation dashboard linking and subagent interception event journal.
200
+ * Lifetime cutoff inheritance across new sessions and new conversations.
201
+ * Mathematically accurate context savings calculations without double-counting.
198
202
  * File category toggles and custom extension management.
199
203
  * Active / Paused state toggle and bypass logic.
200
204
  * MCP stdio JSON-RPC protocol compliance.
@@ -185,13 +185,42 @@ function isBinaryFile(absPath, ext) {
185
185
  return false;
186
186
  }
187
187
 
188
- function recordInterception({ sessionId, cwd, toolName, path: targetPath, size, reason }) {
188
+ export function resolveSharedSessionId(payload = {}) {
189
+ return (
190
+ payload.rootConversationId ||
191
+ payload.root_conversation_id ||
192
+ payload.parentConversationId ||
193
+ payload.parent_conversation_id ||
194
+ process.env.ANTIGRAVITY_ROOT_CONVERSATION_ID ||
195
+ process.env.ANTIGRAVITY_PARENT_CONVERSATION_ID ||
196
+ process.env.ANTIGRAVITY_CONVERSATION_ID ||
197
+ payload.conversationId ||
198
+ payload.conversation_id ||
199
+ payload.sessionId ||
200
+ payload.session_id ||
201
+ "default"
202
+ );
203
+ }
204
+
205
+ export function resolveAgentName(payload = {}) {
206
+ return (
207
+ payload.agent ||
208
+ payload.agentName ||
209
+ payload.agent_name ||
210
+ payload.agentType ||
211
+ payload.agent_type ||
212
+ payload.role ||
213
+ (payload.subagent ? "subagent" : "antigravity")
214
+ );
215
+ }
216
+
217
+ function recordInterception({ sessionId, agent, cwd, toolName, path: targetPath, size, reason }) {
189
218
  try {
190
219
  const store = new ContextModeStore();
191
220
  store.recordEvent({
192
221
  sessionId: sessionId || "default",
193
222
  worktree: cwd || process.cwd(),
194
- agent: "antigravity",
223
+ agent: agent || "antigravity",
195
224
  kind: "interception",
196
225
  tool: toolName,
197
226
  key: "blocked",
@@ -379,12 +408,8 @@ async function main() {
379
408
  const toolName = toolCall.name || "";
380
409
  const args = toolCall.args || {};
381
410
  const cwd = payload.cwd || process.cwd();
382
- const sessionId =
383
- payload.sessionId ||
384
- payload.session_id ||
385
- payload.conversationId ||
386
- process.env.ANTIGRAVITY_CONVERSATION_ID ||
387
- null;
411
+ const sessionId = resolveSharedSessionId(payload);
412
+ const agentName = resolveAgentName(payload);
388
413
 
389
414
  // If Context Mode protection is paused, allow all tool calls through without interception
390
415
  if (isProtectionPaused(sessionId)) {
@@ -431,6 +456,7 @@ async function main() {
431
456
  // Record interception event in SQLite store so dashboard telemetry updates immediately
432
457
  recordInterception({
433
458
  sessionId,
459
+ agent: agentName,
434
460
  cwd,
435
461
  toolName,
436
462
  path: filePath,
@@ -465,6 +491,7 @@ async function main() {
465
491
  if (inspection.shouldDeny) {
466
492
  recordInterception({
467
493
  sessionId,
494
+ agent: agentName,
468
495
  cwd,
469
496
  toolName,
470
497
  path: inspection.targetPath || cleanStringArg(rawCommandLine),
@@ -1,4 +1,5 @@
1
1
  #!/usr/bin/env node
2
+ import { ContextModeStore } from "../lib/store.js";
2
3
 
3
4
  function readStdin() {
4
5
  return new Promise((resolve) => {
@@ -16,6 +17,12 @@ function readStdin() {
16
17
  async function main() {
17
18
  await readStdin();
18
19
 
20
+ try {
21
+ const store = new ContextModeStore();
22
+ store.clearSessionOverrides();
23
+ store.close();
24
+ } catch {}
25
+
19
26
  const response = {
20
27
  injectSteps: [
21
28
  {
package/lib/store.js CHANGED
@@ -492,7 +492,7 @@ export class ContextModeStore {
492
492
  .all(limit);
493
493
  events = this.db
494
494
  .prepare(`
495
- SELECT seq, tool, kind, key, path, ok, sandbox_bytes, returned_bytes, created_at
495
+ SELECT seq, tool, kind, key, path, ok, sandbox_bytes, returned_bytes, agent, created_at
496
496
  FROM events
497
497
  ORDER BY seq DESC
498
498
  LIMIT ?
@@ -510,7 +510,7 @@ export class ContextModeStore {
510
510
  .all(sinceIso, sinceTs, limit);
511
511
  events = this.db
512
512
  .prepare(`
513
- SELECT seq, tool, kind, key, path, ok, sandbox_bytes, returned_bytes, created_at
513
+ SELECT seq, tool, kind, key, path, ok, sandbox_bytes, returned_bytes, agent, created_at
514
514
  FROM events
515
515
  WHERE created_at >= ?
516
516
  ORDER BY seq DESC
@@ -529,7 +529,7 @@ export class ContextModeStore {
529
529
  .all(sid, limit);
530
530
  events = this.db
531
531
  .prepare(`
532
- SELECT seq, tool, kind, key, path, ok, sandbox_bytes, returned_bytes, created_at
532
+ SELECT seq, tool, kind, key, path, ok, sandbox_bytes, returned_bytes, agent, created_at
533
533
  FROM events
534
534
  WHERE session_id = ?
535
535
  ORDER BY seq DESC
@@ -570,13 +570,15 @@ export class ContextModeStore {
570
570
 
571
571
  let eventStats;
572
572
  let sourceStats;
573
+ let unrecordedSources;
573
574
 
574
575
  if (sid === "all" || sid === "lifetime") {
575
576
  eventStats = this.db.prepare(`
576
577
  SELECT
577
578
  COUNT(*) AS total_calls,
578
- SUM(sandbox_bytes) AS total_sandbox_bytes,
579
- SUM(returned_bytes) AS total_returned_bytes
579
+ SUM(MAX(sandbox_bytes, bytes, returned_bytes)) AS total_raw_bytes,
580
+ SUM(returned_bytes) AS total_returned_bytes,
581
+ SUM(MAX(0, MAX(sandbox_bytes, bytes, returned_bytes) - returned_bytes)) AS total_kept_out_bytes
580
582
  FROM events
581
583
  `).get();
582
584
 
@@ -587,12 +589,24 @@ export class ContextModeStore {
587
589
  SUM(chunk_count) AS total_chunks
588
590
  FROM sources
589
591
  `).get();
592
+
593
+ unrecordedSources = this.db.prepare(`
594
+ SELECT COALESCE(SUM(bytes_total), 0) AS unrecorded_source_bytes
595
+ FROM sources s
596
+ WHERE s.kind NOT IN ('execution', 'batch', 'tool_output', 'exec')
597
+ AND NOT EXISTS (
598
+ SELECT 1 FROM events e
599
+ WHERE e.tool = 'ctx_index'
600
+ AND e.sandbox_bytes = s.bytes_total
601
+ )
602
+ `).get();
590
603
  } else if (sid === "app" && sinceIso) {
591
604
  eventStats = this.db.prepare(`
592
605
  SELECT
593
606
  COUNT(*) AS total_calls,
594
- SUM(sandbox_bytes) AS total_sandbox_bytes,
595
- SUM(returned_bytes) AS total_returned_bytes
607
+ SUM(MAX(sandbox_bytes, bytes, returned_bytes)) AS total_raw_bytes,
608
+ SUM(returned_bytes) AS total_returned_bytes,
609
+ SUM(MAX(0, MAX(sandbox_bytes, bytes, returned_bytes) - returned_bytes)) AS total_kept_out_bytes
596
610
  FROM events
597
611
  WHERE created_at >= ?
598
612
  `).get(sinceIso);
@@ -605,12 +619,25 @@ export class ContextModeStore {
605
619
  FROM sources
606
620
  WHERE created_at >= ? OR created_ts >= ?
607
621
  `).get(sinceIso, sinceTs);
622
+
623
+ unrecordedSources = this.db.prepare(`
624
+ SELECT COALESCE(SUM(bytes_total), 0) AS unrecorded_source_bytes
625
+ FROM sources s
626
+ WHERE (created_at >= ? OR created_ts >= ?)
627
+ AND s.kind NOT IN ('execution', 'batch', 'tool_output', 'exec')
628
+ AND NOT EXISTS (
629
+ SELECT 1 FROM events e
630
+ WHERE e.tool = 'ctx_index'
631
+ AND e.sandbox_bytes = s.bytes_total
632
+ )
633
+ `).get(sinceIso, sinceTs);
608
634
  } else {
609
635
  eventStats = this.db.prepare(`
610
636
  SELECT
611
637
  COUNT(*) AS total_calls,
612
- SUM(sandbox_bytes) AS total_sandbox_bytes,
613
- SUM(returned_bytes) AS total_returned_bytes
638
+ SUM(MAX(sandbox_bytes, bytes, returned_bytes)) AS total_raw_bytes,
639
+ SUM(returned_bytes) AS total_returned_bytes,
640
+ SUM(MAX(0, MAX(sandbox_bytes, bytes, returned_bytes) - returned_bytes)) AS total_kept_out_bytes
614
641
  FROM events
615
642
  WHERE session_id = ?
616
643
  `).get(sid);
@@ -623,11 +650,25 @@ export class ContextModeStore {
623
650
  FROM sources
624
651
  WHERE session_id = ?
625
652
  `).get(sid);
653
+
654
+ unrecordedSources = this.db.prepare(`
655
+ SELECT COALESCE(SUM(bytes_total), 0) AS unrecorded_source_bytes
656
+ FROM sources s
657
+ WHERE s.session_id = ?
658
+ AND s.kind NOT IN ('execution', 'batch', 'tool_output', 'exec')
659
+ AND NOT EXISTS (
660
+ SELECT 1 FROM events e
661
+ WHERE e.session_id = s.session_id
662
+ AND e.tool = 'ctx_index'
663
+ AND e.sandbox_bytes = s.bytes_total
664
+ )
665
+ `).get(sid);
626
666
  }
627
667
 
628
- const totalRawBytes = (eventStats?.total_sandbox_bytes || 0) + (sourceStats?.total_source_bytes || 0);
668
+ const unrecordedBytes = unrecordedSources?.unrecorded_source_bytes || 0;
669
+ const totalRawBytes = (eventStats?.total_raw_bytes || 0) + unrecordedBytes;
629
670
  const totalReturnedBytes = eventStats?.total_returned_bytes || 0;
630
- const keptOutBytes = Math.max(0, totalRawBytes - totalReturnedBytes);
671
+ const keptOutBytes = (eventStats?.total_kept_out_bytes || 0) + unrecordedBytes;
631
672
  const savingsPercent = totalRawBytes > 0 ? Number(((keptOutBytes / totalRawBytes) * 100).toFixed(1)) : 0;
632
673
  const tokensKeptOut = Math.round(keptOutBytes / 4);
633
674
 
@@ -728,11 +769,30 @@ export class ContextModeStore {
728
769
  .run(key, String(value));
729
770
  }
730
771
 
772
+ /** Delete a key from meta table */
773
+ deleteMeta(key) {
774
+ this.open();
775
+ this.db.prepare("DELETE FROM meta WHERE key = ?").run(key);
776
+ }
777
+
778
+ /** Clear all session-level overrides so new sessions start with lifetime defaults */
779
+ clearSessionOverrides() {
780
+ this.open();
781
+ this.db.prepare("DELETE FROM meta WHERE key LIKE '%:session:app' OR key LIKE '%:session:default'").run();
782
+ }
783
+
784
+ /** Check if a session or conversation has an explicit cutoff override */
785
+ hasCutoffOverride(sessionId) {
786
+ if (!sessionId || sessionId === "all" || sessionId === "lifetime") return false;
787
+ this.open();
788
+ return this.getMeta(`cutoff:session:${sessionId}`) !== null;
789
+ }
790
+
731
791
  /** Get active cutoff in bytes (0 = none/disabled) */
732
792
  getCutoff(sessionId = null) {
733
793
  this.open();
734
794
  // 1. Session/Conversation override
735
- if (sessionId && sessionId !== "all") {
795
+ if (sessionId && sessionId !== "all" && sessionId !== "lifetime") {
736
796
  const sessionCutoff = this.getMeta(`cutoff:session:${sessionId}`);
737
797
  if (sessionCutoff !== null) {
738
798
  return parseInt(sessionCutoff, 10);
@@ -768,10 +828,14 @@ export class ContextModeStore {
768
828
  this.open();
769
829
  const val = parseInt(bytes, 10);
770
830
  const numVal = Number.isNaN(val) ? 8192 : Math.max(0, val);
771
- if (sessionId && sessionId !== "all") {
831
+ if (sessionId && sessionId !== "all" && sessionId !== "lifetime") {
772
832
  this.setMeta(`cutoff:session:${sessionId}`, numVal);
773
833
  } else {
774
834
  this.setMeta("cutoff:global", numVal);
835
+ // When changing cutoff in lifetime, clear session-level and default overrides
836
+ // so new sessions and new conversations inherit this global setting as their default.
837
+ this.deleteMeta("cutoff:session:app");
838
+ this.deleteMeta("cutoff:session:default");
775
839
  }
776
840
  return numVal;
777
841
  }
package/lib/tools.js CHANGED
@@ -233,13 +233,31 @@ export function createTools({ store, getCwd = () => process.cwd(), getSessionId
233
233
  content: rawText
234
234
  });
235
235
 
236
- return {
236
+ const returnObj = {
237
237
  sourceId: indexed.sourceId,
238
238
  label: indexed.label,
239
239
  bytesTotal: indexed.bytesTotal,
240
240
  chunkCount: indexed.chunkCount,
241
241
  message: `Indexed ${formatBytes(indexed.bytesTotal)} into ${indexed.chunkCount} chunks. Query with ctx_search.`
242
242
  };
243
+
244
+ const returnedBytes = Buffer.byteLength(JSON.stringify(returnObj), "utf8");
245
+
246
+ store.recordEvent({
247
+ sessionId,
248
+ worktree: cwd,
249
+ agent: "antigravity",
250
+ kind: "index",
251
+ tool: "ctx_index",
252
+ path: filePath || url || null,
253
+ ok: 1,
254
+ bytes: indexed.bytesTotal,
255
+ body: returnObj.message,
256
+ sandboxBytes: indexed.bytesTotal,
257
+ returnedBytes
258
+ });
259
+
260
+ return returnObj;
243
261
  },
244
262
 
245
263
  // 4. ctx_search
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "antigravity-plugin-context-mode",
3
- "version": "1.2.1",
3
+ "version": "1.3.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.2.1",
5
+ "version": "1.3.0",
6
6
  "author": "Phillip Webber <github@webbsense.com>",
7
7
  "repository": {
8
8
  "type": "git",
package/server.js CHANGED
@@ -24,6 +24,8 @@ const tools = createTools({
24
24
  store,
25
25
  getCwd: () => currentCwd,
26
26
  getSessionId: () =>
27
+ process.env.ANTIGRAVITY_ROOT_CONVERSATION_ID ||
28
+ process.env.ANTIGRAVITY_PARENT_CONVERSATION_ID ||
27
29
  process.env.ANTIGRAVITY_CONVERSATION_ID ||
28
30
  process.env.CONVERSATION_ID ||
29
31
  currentSessionId ||