agy-context-saver 0.0.0-stage → 1.2.1

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 ADDED
@@ -0,0 +1,60 @@
1
+ # Changelog
2
+
3
+ All notable changes to `Agy-Context-Saver` will be documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
+
8
+ ## [1.2.1] - 2026-10-07
9
+
10
+ ### Documentation & Developer Experience
11
+ - **MCP Prompts Documentation**: Formally documented the `/mcp:agy-context-saver:context_shield` prompt across `README.md` and the documentation site, clarifying the operational difference between user slash commands (Prompts) and autonomous agent capabilities (Tools).
12
+ - **Quickstart Optimization**: Repositioned the Quickstart installation block to the very top of `README.md` and `docs/index.md` for immediate onboarding.
13
+ - **Zensical Docs Site Overhaul**: Added `context_shield` reference and tip callouts across `docs/index.md`, `docs/tools.md`, and `docs/governance.md`; updated navigation title to `Tools & Prompts`.
14
+ - **Dynamic Test Assertions**: Updated installed MCP server verification test to dynamically synchronize with `package.json` version.
15
+
16
+ ---
17
+
18
+ ## [1.2.0] - 2026-10-07
19
+
20
+ ### Performance & Forensics
21
+ - **Batch Full-Transcript Dereferencing**: Replaced sequential full-transcript scans with `batchFindFullSteps()`, reducing $N$-item dereferencing from $O(N)$ full-file passes down to a single streaming pass ($O(1)$) in 18.4ms.
22
+ - **Sliding-Window Turn Retention**: Bounded transcript memory retention in `read_transcript` (`WINDOW_SIZE = Math.max(100, lastTurns * 15)`) with an early-stopping block formatter, parsing 2,000 steps in 21.8ms under 24 KB memory.
23
+ - **Regex LRU Caching**: Added in-memory LRU cache (`regexCache`, capacity: 100) for query pattern compilation in `query_transcript`.
24
+ - **Short-Circuit Field Search**: Converted transcript search to test fields sequentially (`content` $\to$ `thinking` $\to$ `tool_calls`), avoiding heavy string concatenations.
25
+ - **Fast-Path Message Cleaning**: Added fast-path bypass in `cleanMessageContent` for strings $\le 120$ characters, eliminating redundant base64 regexes and newline splits.
26
+ - **Static Rules In-Memory Cache**: Cached `rules/AGENTS.md` in memory with `mtimeMs` file stat invalidation, eliminating disk I/O on `resources/read` and `prompts/get`.
27
+
28
+ ### Execution Governor & Hook
29
+ - **Fast-Path Builtin Bypass**: Added `NON_REWRITABLE_BINARIES` set (`node`, `powershell`, `pwsh`, `cmd`, `dir`, `echo`, `cd`, `del`, etc.) and PowerShell cmdlet prefixes to bypass `spawnSync("rtk")`, dropping execution latency from ~30ms to $< 0.05$ms.
30
+ - **Persistent Command Rewrite LRU Cache**: Implemented persistent disk LRU cache (`agy-rtk-rewrite-cache.json` in `os.tmpdir()`) for rewritable commands, reducing repeat rewrite lookups to $< 0.1$ms.
31
+ - **Session Ledger State Partitioning**: Partitioned session state by conversation ID (`agy-session-${safeId}.json`) to eliminate cross-session file contention.
32
+
33
+ ### Registration & Lifecycle
34
+ - **Idempotent Config & Schema Synchronization**: Added `safeWriteFileIfChanged` and `safeCopyFileIfChanged` across all configuration (`hooks.json`, `mcp_config.json`) and MCP tool schemas (`~/.gemini/antigravity/mcp/agy-context-saver/`), eliminating disk churn during repeat syncs.
35
+ - **RTK Provisioning Check Reuse**: Passed pre-detected RTK metadata to `ensureRtkInstalled()` to eliminate redundant `execSync` version checks during installation.
36
+
37
+ ### Security & Reliability
38
+ - **Stdio Payload Safety Ceiling**: Added 10 MB payload guard (`MAX_STDIO_PAYLOAD_BYTES`) on the MCP stdio line reader, emitting standard JSON-RPC `-32600 Invalid Request` on oversized payloads.
39
+ - **New Performance Verification Suite**: Added `tests/test-performance-probes.mjs` verifying batch dereferencing, sliding window bounds, stdio safety ceiling, and idempotent writes.
40
+
41
+ ---
42
+
43
+ ## [1.1.0] - 2026-10-07
44
+
45
+ ### Added
46
+ - **Closed Execution Topology & Governance Invariants**: Comprehensive PreToolUse hook intercepting native inspection tools (`view_file`, `grep_search`, `list_dir`, `find_by_name`) and hard-routing them to RTK.
47
+ - **Root-Based Antigravity State Protection**: Denied direct access to `.system_generated/` internal files to prevent transcript bloat and loop degradation.
48
+ - **Session-Wide Lifecycle Ledger**: Non-resettable session task polling counter with Tier 3 `force_ask` circuit breaker at 5 denials.
49
+ - **Evaluator & Benchmark Mutation Safeguard**: Gated mutation of evaluator or benchmark artifacts behind user confirmation.
50
+ - **Platform-Aware Windows Routing**: Windows-native routing for `rtk rg "<pattern>" .` and `rtk find <path>` to eliminate stdin hangs.
51
+ - **Universal MCP Server**: 6 core tools (`check_context_health`, `subagent_brief`, `get_installation_status`, `sync_installation`, `read_transcript`, `query_transcript`).
52
+
53
+ ---
54
+
55
+ ## [1.0.0] - 2026-10-07
56
+
57
+ ### Initial Release
58
+ - Initial release of Agy-Context-Saver.
59
+ - Antigravity Model Context Protocol (MCP) server.
60
+ - Background task lifecycle governance and reactive wakeup enforcement.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 paragon-ux
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,173 @@
1
- # Temporary Holding Version
1
+ # Agy-Context-Saver 🛡️
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ **Model Context Protocol (MCP) Server & Lifecycle Governor for Google Antigravity (Powered by RTK)**
4
+
5
+ [![npm version](https://img.shields.io/npm/v/agy-context-saver.svg)](https://www.npmjs.com/package/agy-context-saver)
6
+ [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
7
+ [![Docs](https://img.shields.io/badge/docs-Zensical-purple.svg)](https://paragon-ux.github.io/agy-context-saver/)
8
+ [![Tests](https://img.shields.io/badge/tests-100%25%20passing-brightgreen.svg)](https://github.com/paragon-ux/agy-context-saver/actions)
9
+
10
+ `Agy-Context-Saver` is a high-performance lifecycle governor and zero-dependency MCP server purpose-built for **Google Antigravity** (`agy`), paired with **RTK (Rust Token Killer)** for transparent CLI output reduction.
11
+
12
+ It permanently eliminates session degradation, memory bloat, and context window exhaustion caused by **background task busy-wait polling**, **uncompressed terminal outputs**, and **raw JSON transcript reading**.
13
+
14
+ ---
15
+
16
+ ## Quickstart (Instant Install)
17
+
18
+ Install and synchronize the governor and RTK across your Antigravity environment:
19
+
20
+ ```bash
21
+ # Fastest: one-line registration via npx
22
+ npx agy-context-saver install
23
+
24
+ # Or locally from this repository
25
+ npm run setup
26
+
27
+ # Audit health across all layers at any time
28
+ npm run status
29
+ ```
30
+
31
+ ---
32
+
33
+ ## Architectural Division of Responsibilities
34
+
35
+ ```text
36
+ Antigravity Agent
37
+ |
38
+ +------------------+------------------+
39
+ | |
40
+ run_command native inspection /
41
+ | lifecycle tools
42
+ v |
43
+ RTK hook |
44
+ | +---------+----------+
45
+ v | |
46
+ RTK execution inspection tools lifecycle
47
+ | | |
48
+ v v v
49
+ compact command output Agy DENY + route Agy governance
50
+ | |
51
+ v v
52
+ RTK read/grep/find Agy MCP
53
+ | |
54
+ +---------+----------+
55
+ |
56
+ v
57
+ useful context
58
+ ```
59
+
60
+ ### RTK Owns:
61
+ - Transparent `run_command` rewriting (`rtk rewrite`)
62
+ - Shell command output reduction (`git`, `pytest`, `cargo`, `npm`, `docker`, etc.)
63
+ - Canonical codebase inspection CLI (`rtk read`, `rtk grep`, `rtk find`, `rtk ls`, `rtk tree`)
64
+ - Focused diagnostic utilities (`rtk err`, `rtk summary`)
65
+
66
+ ### Agy Owns:
67
+ - Antigravity lifecycle management & Reactive Wakeup enforcement
68
+ - Background task polling governance & 5-strike circuit breaker
69
+ - Antigravity internal state protection (`.system_generated/`)
70
+ - Zero-JSON Markdown transcript extraction (`read_transcript`, `query_transcript`)
71
+ - Subagent delegation formulation (`subagent_brief`)
72
+ - Benchmark and evaluation artifact mutation protection
73
+
74
+ ---
75
+
76
+ ## The Core Problems Solved
77
+
78
+ 1. **The Polling Trap**: When shell tasks detach to background jobs (`task-XYZ`), agents waste tokens repeatedly polling `manage_task(Action='status')` or scheduling artificial timers. Agy enforces native **Reactive Wakeup** (`<SYSTEM_MESSAGE>`).
79
+ 2. **The Terminal Bloat Trap**: Routine test runs and git operations dump hundreds of lines of noise into context. RTK compresses these outputs natively before they enter model context.
80
+ 3. **The Raw Transcript Trap**: Reading `transcript.jsonl` dumps megabytes of raw JSON into context. Agy blocks direct reads of `.system_generated` and provides high-density Markdown streaming tools.
81
+ 4. **Native Inspection Bypass**: Native inspection tools (`view_file`, `grep_search`, `find_by_name`, `list_dir`) bypass token reduction. Agy hard-routes workspace inspection to RTK's canonical CLI (`rtk read`, `rtk grep`, `rtk find`, `rtk ls`).
82
+
83
+ ---
84
+
85
+ ## Key Capabilities
86
+
87
+ - **Transparent RTK Rewriting**: Native `run_command` calls are automatically rewritten (e.g. `pytest` $\to$ `rtk pytest`) via Antigravity PreToolUse hooks.
88
+ - **Canonical Codebase Inspection**:
89
+ - `rtk read <file>`: Read file with intelligent token filtering and line ranges.
90
+ - `rtk find <path>`: Compact file search tree and directory listing (cross-platform, works on Windows & POSIX).
91
+ - Search by platform:
92
+ - **Windows**: `rtk rg "<pattern>" .` (explicit target `.` prevents child process stdin stalls) or `rg "<pattern>" .`.
93
+ - **POSIX / Linux / macOS**: `rtk grep "<pattern>"` or `rtk rg "<pattern>"`.
94
+ - Directory listing by platform:
95
+ - **Windows**: `rtk find <path>` or PowerShell `dir` / `Get-ChildItem`. (Avoid `rtk ls` / `rtk tree` on Windows as they rely on POSIX binaries/flags).
96
+ - **POSIX / Linux / macOS**: `rtk ls <path>` or `rtk tree`.
97
+ - `rtk err <cmd>`: Run command and show only errors/warnings.
98
+ - `rtk summary <cmd>`: Run command and produce a 2-line heuristic summary.
99
+ - **Antigravity Special Files Safe Harbor**: Direct `view_file` access to `SKILL.md`, brain artifacts, and config files is preserved.
100
+ - **Protected Internal State**: Root-based guard prevents reading `.system_generated/` (transcripts, task logs, progress).
101
+ - **Session-Wide Lifecycle Ledger**: Polling checks are tracked globally per session; changing task IDs or waiting does not reset governance.
102
+ - **Zero-JSON Transcript Streaming**: Stream conversation turns without raw JSON syntax using `read_transcript` and `query_transcript`.
103
+
104
+ ---
105
+
106
+ ## Zero-Guesswork Testing & Verification Playbook
107
+
108
+ To cleanly test every layer of the framework without guesswork or interactive stalls:
109
+
110
+ ### 1. Audit Live Registration
111
+ ```bash
112
+ npm run status
113
+ # or
114
+ node mcp/index.js status
115
+ ```
116
+ *Confirms that all 4 integration layers (Plugin link, Lifecycle Hook, MCP Server, Schemas) and RTK are active.*
117
+
118
+ ### 2. Run Complete Automated Test Suite
119
+ ```bash
120
+ npm test
121
+ ```
122
+ *Runs all 5 test suites (28 hook tests, MCP protocol tests, E2E probes, installed verification, lifecycle rollback).*
123
+
124
+ ### 3. Run Targeted Tests Individually
125
+ ```bash
126
+ # Governance hook unit tests (28 closed-topology tests)
127
+ node tests/test-hook.mjs
128
+
129
+ # MCP server protocol & method tests
130
+ node tests/test-mcp.mjs
131
+
132
+ # End-to-end edge case & probe tests
133
+ node tests/test-e2e-probes.mjs
134
+
135
+ # Live installed environment verification
136
+ node tests/test-installed-verification.mjs
137
+
138
+ # Clean install/uninstall/restore lifecycle test
139
+ node tests/test-lifecycle-rollback.mjs
140
+ ```
141
+
142
+ ### 4. Test MCP Tools from Antigravity Agent
143
+ - `get_installation_status`: Call with `{}` to audit all 4 layers + RTK.
144
+ - `check_context_health`: Call with `{ "transcriptPath": "<path-to-transcript.jsonl>" }`.
145
+ - `read_transcript`: Call with `{ "conversationId": "<uuid>", "lastTurns": 3, "mode": "compact" }`.
146
+ - `query_transcript`: Call with `{ "conversationId": "<uuid>", "query": "<term>", "summaryOnly": true }`.
147
+ - `subagent_brief`: Call with `{ "objective": "<goal>", "scopeFiles": ["..."] }`.
148
+
149
+ ### 5. Testing Pitfalls & Anti-Patterns to Avoid
150
+ - ❌ **Do NOT run `npm start` or `node mcp/index.js` interactively**: It starts the stdio JSON-RPC daemon and waits indefinitely on `stdin`.
151
+ - ❌ **Do NOT loop on `manage_task(Action='status')`**: Polling triggers the session ledger circuit breaker at 5 cumulative denials. Rely on native Reactive Wakeup (`<SYSTEM_MESSAGE>`).
152
+ - ❌ **Do NOT run `npm run uninstall` as a standalone check**: It unregisters the live hook. If run, immediately re-run `npm run setup`.
153
+ - ❌ **On Windows, do NOT omit the directory in `rtk rg`**: Always run `rtk rg "<pattern>" .` to avoid stdin pipe blocking.
154
+
155
+ ---
156
+
157
+ ## MCP Tools & Slash Commands
158
+
159
+ * **User Slash Command (`/mcp:...`)**:
160
+ - `/mcp:agy-context-saver:context_shield`: Injects 3-layer governance rules and RTK standards into any session with one click. *(MCP Prompts appear in your chat autocomplete menu; MCP Tools are called autonomously by the agent).*
161
+ * **Agent MCP Tools**:
162
+ 1. `check_context_health`: Diagnoses conversation transcript turn budgets, payload size, RTK status, and polling loops.
163
+ 2. `subagent_brief`: Formulates scope-isolated prompts for delegated subagents.
164
+ 3. `read_transcript`: Reads recent conversation history in clean Markdown format (compact/full).
165
+ 4. `query_transcript`: Forensic filtering and regex search engine for conversation logs.
166
+ 5. `get_installation_status`: Inspects live Antigravity plugin link, hook, MCP server, tool schemas, and RTK binary.
167
+ 6. `sync_installation`: Re-verifies and repairs all integration layers in ~25ms.
168
+
169
+ ---
170
+
171
+ ## License
172
+
173
+ MIT License. Copyright (c) 2026 paragon-ux.
package/hooks.json ADDED
@@ -0,0 +1,16 @@
1
+ {
2
+ "agy-context-saver": {
3
+ "PreToolUse": [
4
+ {
5
+ "matcher": "manage_task|run_command|schedule",
6
+ "hooks": [
7
+ {
8
+ "type": "command",
9
+ "command": "node scripts/execution-guard-hook.mjs",
10
+ "timeout": 5
11
+ }
12
+ ]
13
+ }
14
+ ]
15
+ }
16
+ }
package/install.ps1 ADDED
@@ -0,0 +1,42 @@
1
+ # Agy-Context-Saver Universal Installer for Windows
2
+ # Installs hook script, wrapper, and registers in ~/.gemini/config/hooks.json & mcp_config.json
3
+
4
+ $ErrorActionPreference = "Stop"
5
+
6
+ $GeminiConfigDir = [System.IO.Path]::Combine($env:USERPROFILE, ".gemini", "config")
7
+ $DestHook = [System.IO.Path]::Combine($GeminiConfigDir, "scripts", "execution-guard-hook.mjs")
8
+
9
+ # 1. Ensure ~/.gemini/config exists
10
+ if (-not (Test-Path $GeminiConfigDir)) {
11
+ New-Item -ItemType Directory -Path $GeminiConfigDir -Force | Out-Null
12
+ }
13
+
14
+ # 2. Create node.cmd wrapper in ~/.gemini/config (prevents Windows cmd quote issues)
15
+ $NodeCmdPath = [System.IO.Path]::Combine($GeminiConfigDir, "node.cmd")
16
+ $NodeCmdLines = @(
17
+ '@echo off',
18
+ 'setlocal',
19
+ 'set "ARGS=%*"',
20
+ '',
21
+ 'echo %ARGS% | findstr /i "execution-guard" >nul',
22
+ 'if %errorlevel% equ 0 (',
23
+ " `"C:\Program Files\nodejs\node.exe`" `"$DestHook`"",
24
+ ' exit /b %errorlevel%',
25
+ ')',
26
+ '',
27
+ 'echo %ARGS% | findstr /i "waymark" >nul',
28
+ 'if %errorlevel% equ 0 (',
29
+ ' "C:\Program Files\nodejs\node.exe" "%USERPROFILE%\Desktop\Frameworks\Deepseek-Project\Waymark\scripts\hooks\waymark-compact-hook.mjs"',
30
+ ' exit /b %errorlevel%',
31
+ ')',
32
+ '',
33
+ 'echo {"decision": "allow"}',
34
+ 'exit /b 0'
35
+ )
36
+ $NodeCmdContent = $NodeCmdLines -join "`r`n"
37
+ Set-Content -Path $NodeCmdPath -Value $NodeCmdContent -Encoding ASCII
38
+ Write-Host "[OK] Node wrapper installed to: $NodeCmdPath" -ForegroundColor Green
39
+
40
+ # 3. Run cross-platform registration engine
41
+ $RegisterScript = [System.IO.Path]::Combine($PSScriptRoot, "scripts", "install-register.mjs")
42
+ & node "$RegisterScript"
package/install.sh ADDED
@@ -0,0 +1,6 @@
1
+ #!/usr/bin/env bash
2
+ # Agy-Context-Saver Zero-Delay Installer for macOS & Linux
3
+ set -euo pipefail
4
+
5
+ SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
6
+ node "$SCRIPT_DIR/scripts/install-register.mjs" "$@"