Context Anchor Anchors
by Over9rowth
README.md
<p align="center">
<img src="./assets/logo.svg" alt="Context Anchor Logo" width="96" height="96" />
</p>
<h1 align="center">Context Anchor</h1>
<p align="center">
<strong>Let the running Antigravity agent actively choose, curate, and preserve critical context across context compression.</strong>
</p>
<p align="center">
<a href="./LICENSE"><img src="https://img.shields.io/badge/License-MIT-blue.svg" alt="License: MIT" /></a>
<a href="./package.json"><img src="https://img.shields.io/badge/Zero%20Dependencies-Node.js%20Stdlib-yellow.svg" alt="Zero Dependencies" /></a>
<a href="https://github.com/Over9rowth"><img src="https://img.shields.io/badge/Author-Over9rowth-purple.svg" alt="Author: Over9rowth" /></a>
<a href="https://github.com/Over9rowth"><img src="https://img.shields.io/badge/%E7%87%A7%E4%BA%BA%E8%AE%A1%E5%88%92-Suiren%20Plan-f59e0b.svg" alt="燧人计划" /></a>
</p>
<p align="center">
<a href="https://github.com/Over9rowth">
<img src="./assets/suiren-badge.svg" alt="OVER9ROWTH · 燧人计划" width="420" />
</a>
</p>
<p align="center">
English | <a href="./README.zh-CN.md">简体中文</a>
</p>
---
## Why Context Anchor?
When long coding or research sessions hit token limits, automatic context compression summarizes raw history—often discarding exact file paths, subtle constraints, rejected approaches, and active task state.
Antigravity does not currently expose a `PreCompact` lifecycle hook or allow plugins to rewrite its internal compaction prompt. **Context Anchor** solves this within Antigravity's native plugin architecture by pairing:
1. **Agent-Selected Context Anchoring (MCP Tools)** — Gives the running agent first-class tools (`pin_context`, `unpin_context`, `list_pinned_context`, `get_pinned_context`, `replace_session_anchors`) so *the agent itself* decides what must survive compression.
2. **Proactive Token & Compaction Watcher (Lifecycle Hooks)** — Tails `transcript.jsonl` on `PreInvocation` to warn the agent before auto-compaction hits, and automatically re-injects pinned anchors when a context drop is detected.
3. **Always-On Curation Rule & `/context-anchor` Skill** — Guides the agent to pin concise conclusions and exact pointers (never bloated raw logs), and lets you trigger manual curation at any time via `/context-anchor`.
4. **Zero Dependencies** — Pure Node.js (`>= 18`) standard library; works across Windows, macOS, and Linux without `npm install`.
---
## How It Works
```mermaid
flowchart LR
A[SessionStart / PreInvocation Hook] -->|Register session_id & tail transcript.jsonl| B{Token Check}
B -->|Tokens >= 80k| C[Inject Pre-Compression Nudge]
C -->|Agent curates important context| D[MCP: pin_context / replace_session_anchors]
D -->|Atomic JSON write| E[(Session & Workspace Anchors)]
B -->|Token drop >= 35% or step reset| F[Compaction Detected]
E -->|Priority sort: critical > high > normal| F
F -->|Inject systemMessage| G[Agent Continues Without Amnesia]
```
---
## Features & Components
### 1. MCP Server (`anchors` -> `context-anchor_anchors`)
| Tool | Purpose |
| :--- | :--- |
| `pin_context` | Pin or update a context anchor (`critical` / `high` / `normal`) in `session` or `workspace` scope. |
| `unpin_context` | Remove completed or obsolete anchors by `anchor_id`, `title`, or `clear_all`. |
| `list_pinned_context` | Inspect all active anchors with priorities, categories, and estimated token usage. |
| `get_pinned_context` | Retrieve the formatted survival bundle on demand. |
| `replace_session_anchors` | Atomically deduplicate, merge, and replace all session anchors in one call. |
**Supported categories:** `decision`, `constraint`, `state`, `file_map`, `pitfall`, `task`.
**Supported scopes:**
- `session` (default): Isolated to the current `conversationId`.
- `workspace`: Persists across conversations in the same workspace directory.
### 2. Lifecycle Hooks (`hooks.json`)
- **`SessionStart`**: Registers the active `conversationId`, injects `session_id`, and restores any `workspace`-scoped anchors.
- **`PreInvocation`**: Reads only the last 128 KB of `transcript.jsonl`:
- Sends a non-spammy reminder when prompt tokens cross `80k` (and every `+40k` thereafter).
- Detects compaction when a compaction/checkpoint step appears, step count resets, or prompt tokens drop by `>= 35%` (and `>= 10k` tokens)—ignoring stale pre-compaction `PLANNER_RESPONSE` token telemetry so a `CHECKPOINT` never double-triggers recovery—and injects preserved anchors ordered by priority along with a post-compaction core context recap instruction.
- **`Stop`**: Updates session metadata cleanly without blocking turn completion.
### 3. CLI Fallback (`scripts/cli.mjs`)
For manual inspection or pre-existing sessions where MCP tools have not yet attached:
```bash
node ./scripts/cli.mjs pin --title "API Contract" --content "Keep v1 response shape." --priority critical --category constraint
node ./scripts/cli.mjs list
node ./scripts/cli.mjs get
node ./scripts/cli.mjs unpin --title "API Contract"
```
---
## Installation
### Option 1: Install via Antigravity CLI (`agy`)
```bash
# Install directly from a local clone or GitHub repository URL
agy plugin install https://github.com/Over9rowth/context-anchor
```
### Option 2: Manual Local Installation (Antigravity App / IDE / CLI)
Copy or clone this repository into your global Antigravity plugins folder:
- **macOS / Linux:**
```bash
git clone https://github.com/Over9rowth/context-anchor.git ~/.gemini/config/plugins/context-anchor
```
- **Windows (PowerShell):**
```powershell
git clone https://github.com/Over9rowth/context-anchor.git "$env:USERPROFILE\.gemini\config\plugins\context-anchor"
```
> **Note:** After installing, **open a new conversation** (or reload) so the MCP server `context-anchor_anchors` attaches its tool declarations to the session.
---
## Usage
- **Automatic mode:** Just work normally. The always-on rule (`rules/AGENTS.md`) and `PreInvocation` hook nudge the agent to curate critical context as sessions grow, restore it once after compression, and automatically recap the restored core context at the start of the post-compaction reply.
- **Recommended `/context-anchor` -> `/compact` flow:**
1. Type `/context-anchor` to have the agent audit, deduplicate, and save key context anchors, then prompt you with a `/compact` handoff.
2. Type `/compact` in chat to compact the conversation window *(Antigravity restricts slash commands to direct user input, so plugins/agents cannot run `/compact` automatically)*.
3. Send any short follow-up (e.g., `继续` / `continue`)—`context-anchor` injects your curated anchors and instructs the agent to briefly recap the restored core context before resuming work.
- **Natural language:** Ask the agent directly, e.g., *"Pin our current architecture decisions and modified files with `pin_context`."*
---
## Configuration (Optional Environment Variables)
| Variable | Default | Description |
| :--- | :--- | :--- |
| `CONTEXT_ANCHOR_NUDGE_START_TOKENS` | `80000` | Token count at which the first pre-compression curation nudge fires. |
| `CONTEXT_ANCHOR_NUDGE_INTERVAL_TOKENS` | `40000` | Additional token growth required before another nudge fires. |
| `CONTEXT_ANCHOR_DROP_RATIO` | `0.65` | Ratio threshold (`current <= previous * ratio`) used to detect token drop compaction. |
| `CONTEXT_ANCHOR_MAX_INJECT_CHARS` | `14000` | Maximum character budget for auto-injected anchor recovery blocks. |
| `CONTEXT_ANCHOR_POST_COMPACT_RECAP` | `true` | Instructs the agent to briefly recap restored core anchors in its first reply after compaction recovery (`false`/`0` disables). |
| `CONTEXT_ANCHOR_DATA_DIR` | `$PLUGIN_DATA` or `~/.gemini/antigravity/plugin-data/context-anchor` | Override where session and workspace anchor JSON files are stored. |
---
## Development & Testing
Requires Node.js `>= 18.0.0`. No dependencies to install:
```bash
npm test
# or
node --test ./scripts/test.mjs
```
---
## License
[MIT](./LICENSE)
This server cannot be deployed
Maintenance
ActivityMaintained
ResponsivenessNo recent community issues