Compare commits

..
35 changed files with 214 additions and 1490 deletions

No files matched your search

-65
View File
@@ -1,65 +0,0 @@
# Integrating MCP Memory: A Strategy Guide for LLMs and Agents
This guide documents the approach and rationale for integrating the `mcp-memory` server with agentic LLMs (like Antigravity). Because `mcp-memory` is a central hub for context, tasks, and environment state, it is critical that LLMs interact with it efficiently without exhausting their primary context window or causing workflow ambiguity.
## 1. The Core Philosophy: "The Central Brain"
The `mcp-memory` server is the persistence layer for the AI development lifecycle. It holds:
* **The Knowledge Graph:** Code changes, bug fixes, architecture decisions, and tech debt.
* **Project State:** Milestones, tasks, acceptance criteria, and PR checklists.
* **Environment State:** Handoff memos, standup reports, and environment fingerprints.
* **Live UI Integrations:** Neovim buffer manipulation and user-action webhooks.
**Rationale:** The LLM's context window is ephemeral and expensive. By pushing state to the `mcp-memory` server (via a local database and Tantivy index), the LLM can selectively retrieve only what it needs, when it needs it.
## 2. Global Rules vs. Subagents
To maximize efficiency, we split interactions into two categories: **Synchronous Rules** (executed by the primary conversational agent) and **Asynchronous Subagents** (delegated background tasks).
### A. Synchronous Rules (The Primary Loop)
The main LLM interacting with the user should be constrained by global system rules to ensure basic context synchronization. These actions must happen synchronously so the main agent never loses the plot.
* **Context Initialization (`tasks` list, `get_preflight_context`):** Executed when a session starts. This gives the LLM immediate awareness of the current workflow.
* **Context Switching (`manage_checkpoint`):** Executed when moving between branches or large features. This prevents context bleed between disparate tasks.
* **End-of-Day Handoff (`add_session_summary`, `generate_standup_report`):** Triggered when the user logs off, seamlessly serializing the mental state of the LLM for tomorrow.
### B. Subagent Orchestration (The Background Team)
Heavy or verbose interactions with the MCP server are delegated to specialized background subagents. This keeps the primary chat fast and focused on the code, while the "team" handles project management.
#### 1. `MemoryLibrarian` (The Graph Curator)
* **Role:** Analyzes git diffs and chat history to structure the Knowledge Graph.
* **Tools:** `log_code_change`, `log_error_fix`, `create_entities`, `log_tech_debt`.
* **Rationale:** Parsing diffs and determining entity relationships is token-heavy. Delegating this prevents the main agent from wasting reasoning cycles on database normalization.
#### 2. `ScrumMaster` (The Project Manager)
* **Role:** Manages the task lifecycle and acceptance criteria.
* **Tools:** `add_task`, `update_task_status`, `add_milestone`, `verify_acceptance_criteria`.
* **Rationale:** The main agent shouldn't have to repeatedly query "are we done yet?" The `ScrumMaster` runs alongside the session, validating criteria in the background and updating the board autonomously.
#### 3. `DevOpsSRE` (The Environment Manager)
* **Role:** Monitors dependencies and manages session transitions.
* **Tools:** `update_env_fingerprint`, `leave_handoff_memo`.
* **Rationale:** Prevents "it works on my machine" failures by passively updating fingerprints when build files (e.g., `Cargo.toml`) change.
## 3. Graceful Degradation & Server Resilience
The `mcp-memory` server is a distinct background process (typically port 3000). The LLM ecosystem must handle server downtime gracefully:
1. **Event Webhooks:** If the server goes down, waiting webhook tasks (e.g., waiting for a user to save a file in Neovim) will drop. These *do not* self-heal. The LLM must recognize the dropped connection and prompt the user to retry the action.
2. **Persistent Storage:** Data (tasks, graph, ledger) is persisted to `mcp_store.redb`. When the server comes back online, no data is lost. The LLM can immediately resume querying.
3. **Subagent Fast-Failing:** If the `MemoryLibrarian` attempts to log a change while the server is offline, it will instantly fail. It is designed to abandon the background task and notify the primary agent. To recover, the primary agent can manually re-invoke the Librarian once the connection is restored, instructing it to analyze recent commits to backfill the graph.
## Conclusion
By treating `mcp-memory` as the durable brain, and enforcing a strict division of labor between the primary agent loop and background subagents, we achieve a highly autonomous, highly resilient AI pair-programming environment that scales across long-running projects and multiple terminal sessions.
## 4. MCP Feature Differentiation (Cognitive Boundaries)
The MCP protocol exposes three primary primitives. To prevent LLM confusion and API hallucination, the LLM must strictly adhere to the following interaction boundaries:
### A. Tools (For Stateful Mutation)
* **When to use:** Use tools *exclusively* for mutating state (e.g., dd_task, log_code_change) or for highly targeted semantic searches (e.g., search_nodes, query_graph_path).
* **LLM Awareness:** The LLM must not use tools to repeatedly poll for state changes. Tools represent active, expensive computing steps.
### B. Resources (For Passive Awareness)
* **When to use:** Use URIs (e.g., memory://tasks/active, memory://session/delta) to read holistic project state.
* **LLM Awareness:** The client integration should map these URIs to the LLM's context window. Instead of the LLM invoking a list_active_tasks tool (which costs a round-trip), the LLM should simply read the memory://tasks/active resource content if it needs to know what to do next. Resources are for passive, zero-cost reading.
### C. Prompts (For Macro-Workflows)
* **When to use:** Use server-defined prompts to execute complex, multi-step routines that require bundled context.
* **LLM Awareness:** Instead of the user or main agent trying to manually figure out the correct sequence of tools to end a session, the LLM should trigger the handoff_routine prompt. The server will respond with a strictly formatted message array that perfectly primes the LLM on exactly what to do next. Prompts act as "macro-instructions" to prevent the LLM from wandering off-script during complex transitions.
-77
View File
@@ -1,77 +0,0 @@
# Architecture Design: MCP Resources & Prompts
## 1. Current Architecture (Tools)
Currently, the `mcp-memory` server handles MCP tools using an elegant trait-based approach in `router.rs`:
```rust
#[async_trait]
pub trait McpTool: Send + Sync {
fn name(&self) -> &'static str;
fn schema(&self) -> Value;
async fn execute(&self, args: Value, state: Arc<MemoryState>) -> Result<String, String>;
}
```
Tools are registered into a `HashMap<String, Box<dyn McpTool>>` within the `MemoryHandler`. This prevents the main JSON-RPC match block from becoming a monolithic switch statement.
## 2. The Problem
Currently, the `resources/list`, `resources/read`, `prompts/list`, and `prompts/get` endpoints are hardcoded directly inside the `MemoryHandler::handle_request` match block in `router.rs`.
As we expand our usage of Resources (to expose the database state dynamically) and Prompts (to bundle complex workflows), continuing to hardcode them in `router.rs` will result in massive code duplication and tearup.
## 3. The Proposed Solution (Trait Extensibility)
We will replicate the success of the `McpTool` trait by introducing `McpResource` and `McpPrompt` traits.
### A. MCP Resources
**Trait Definition (`router.rs` or `resources.rs`):**
```rust
#[async_trait]
pub trait McpResource: Send + Sync {
/// The exact URI the client requests (e.g. "memory://tasks/active")
fn uri(&self) -> &'static str;
/// Human-readable name for the client UI
fn name(&self) -> &'static str;
/// Description for the client UI
fn description(&self) -> Option<&'static str> { None }
/// Mime type of the content (usually "application/json" or "text/markdown")
fn mime_type(&self) -> Option<&'static str> { Some("application/json") }
/// Retrieve the resource content
async fn read(&self, state: Arc<MemoryState>) -> Result<String, String>;
}
```
**Implementation:**
* Add `pub resources: std::collections::HashMap<String, Box<dyn McpResource>>` to `MemoryHandler`.
* In `handle_request("resources/list")`, iterate over `self.resources.values()` and build the JSON payload.
* In `handle_request("resources/read")`, lookup the requested URI in `self.resources` and call `.read(state).await`.
* Move the existing `memory://graph/entities` logic into its own handler struct.
### B. MCP Prompts
**Trait Definition (`router.rs` or `prompts.rs`):**
```rust
#[async_trait]
pub trait McpPrompt: Send + Sync {
/// The unique name of the prompt (e.g. "analyze_tech_debt")
fn name(&self) -> &'static str;
/// Description for the client UI
fn description(&self) -> Option<&'static str> { None }
/// Schema or array defining arguments (can default to empty)
fn arguments(&self) -> serde_json::Value { serde_json::json!([]) }
/// Execute the prompt and return the `messages` array payload
async fn get(&self, args: Value, state: Arc<MemoryState>) -> Result<serde_json::Value, String>;
}
```
**Implementation:**
* Add `pub prompts: std::collections::HashMap<String, Box<dyn McpPrompt>>` to `MemoryHandler`.
* In `handle_request("prompts/list")`, map over `self.prompts.values()`.
* In `handle_request("prompts/get")`, call `.get(args, state).await`.
## 4. Execution Plan
1. **Refactor `router.rs` (No functional changes yet):** Define the `McpResource` and `McpPrompt` traits. Update the `MemoryHandler` struct to hold these HashMaps. Migrate the existing hardcoded stubs (`memory://graph/entities` and `analyze_tech_debt`) into structs implementing these traits.
2. **Expand Resources (Phase 1):** Add new handlers for `memory://tasks/active`, `memory://session/delta`, etc.
3. **Expand Prompts (Phase 2):** Add new handlers for `handoff_routine`, etc.
This design guarantees we do not needlessly tear up code—we merely extend the existing robust `McpTool` pattern to the rest of the protocol.
-131
View File
@@ -1,131 +0,0 @@
# Effective Discourse: LLM Prompting Guide for MCP Memory
To get the most out of the Antigravity MCP Memory server and its advanced developer tools, use specific phrases that clearly state your intent. This guides the LLM to use the most efficient tools, reducing token consumption, speeding up time-to-resolve (T2R), and avoiding brute-force file reading.
---
## 1. Global Semantic Code Search & Navigation
Instead of having the LLM use brute-force text searches or `grep` to find abstract logic, instruct it to use local vector embeddings.
* **Don't say:** "Grep the codebase for database connection strings."
* **Do say:** "Perform a semantic code search for how database connections are established."
* **Tool Triggered:** `semantic_code_search`
---
## 2. Subgraph Expansion & Neighborhood Exploration
When inspecting complex system interactions or module dependencies around a target component.
* **Don't say:** "Tell me everything connected to the DatabaseTable node."
* **Do say:** "Get the subgraph expansion around 'DatabaseTable' up to 2 hops."
* **Tool Triggered:** `get_subgraph`
---
## 3. Automated Error Fix Suggestions
When encountering build failures, runtime crashes, or stack traces.
* **Don't say:** "Here is a stack trace, let's debug from scratch: [paste stack trace]"
* **Do say:** "Suggest an error fix for this stack trace before we start debugging."
* **Tool Triggered:** `suggest_error_fix`
---
## 4. Memory State Checkpointing & Safety Rollbacks
Before initiating risky refactors or running experimental multi-step subagents.
* **Don't say:** "Hope this refactor doesn't mess up our task board or memory graph."
* **Do say:** "Checkpoint the memory state under 'pre-refactor' before we begin."
* **Tool Triggered:** `checkpoint_state` / `restore_state`
---
## 5. Codebase Exploration & Token Efficiency
When entering a new file, avoid having the LLM read the entire contents blindly.
* **Don't say:** "Read server.rs and tell me what it does." *(Consumes massive tokens)*
* **Do say:** "Extract the AST skeleton of server.rs to understand its structure first."
* **Tool Triggered:** `read_file_skeleton`
---
## 6. Debugging & Log Parsing
Stop copy-pasting giant walls of logs into the chat interface.
* **Don't say:** "Here is the error: [paste 500 lines of logs]"
* **Do say:** "The daemon crashed. Fetch the recent logs from daemon.log." or "Watch the process logs for server.log."
* **Tool Triggered:** `process_logs` (action: "get", action: "watch")
---
## 7. Git & Context Handoff
When you've been working independently and need to loop the LLM back in on your current state.
* **Don't say:** "I changed some files, here are the diffs..."
* **Do say:** "Get the active git worktree context to review my uncommitted changes before we continue."
* **Tool Triggered:** `get_active_worktree_context`
---
## 8. Inter-Agent Signal Bus & Coordination
When multiple subagents collaborate or background tasks complete.
* **Don't say:** "Let me manually tell the ScrumMaster that testing finished."
* **Do say:** "Broadcast an agent signal that unit tests passed and ping the PrePushAuditor."
* **Tool Triggered:** `agent_signals` (action: "broadcast", action: "query")
---
## 9. Structural AST Editing
When asking the LLM to modify complex files, prevent indentation bugs and regex failures by guiding it to use tree-sitter.
* **Don't say:** "Search for `fn process()` and replace it with this string."
* **Do say:** "Use the AST node replacer to swap out the `process` function in `server.rs`."
* **Tool Triggered:** `replace_ast_node`
---
## 10. Bird's-Eye Repository Exploration
When the LLM is first analyzing a repository, don't let it run `ls -R` and guess.
* **Don't say:** "List the files in the directory and guess where the database code is."
* **Do say:** "Read the directory architecture to get a summary of what each file is responsible for."
* **Tool Triggered:** `read_directory_architecture`
---
## 11. Graph, Memory & Casing Standards
Actively instruct the LLM to maintain its memory constraints and use canonical casing.
* **Do say:** "Log this architectural decision in the knowledge graph using PascalCase for entity types."
* **Do say:** "Leave a handoff memo with the test database credentials and session action items."
* **Do say:** "Create a milestone for the 'Rich Clipboard' feature and break it down into active tasks."
* **Tools Triggered:** `create_entities`, `decisions` (log), `handoff_memos` (leave), `milestones` (add), `tasks` (add)
---
## 12. Self-Healing Graph Maintenance
* **Don't say:** "Search for duplicates and orphaned entities in the graph manually."
* **Do say:** "Sweep graph health to identify orphaned entities and duplicate candidates."
* **Tool Triggered:** `sweep_graph_health`
---
## 13. Causal Lineage & Provenance
* **Don't say:** "Search all tasks, ADRs, and commits to explain why this file was changed."
* **Do say:** "Query lineage for `server/src/state.rs` to construct a causal timeline."
* **Tool Triggered:** `query_lineage`
---
## 14. Actionable Task Resolution
* **Don't say:** "List all tasks and figure out which ones are blocked."
* **Do say:** "Get the next actionable tasks to find unblocked work ready for execution."
* **Tool Triggered:** `get_next_actionable_tasks`
---
## 15. Diagnostic Hypotheses & Reasoning Traces
* **Don't say:** "Let's test three guesses and remember what we tried in chat."
* **Do say:** "Log a hypothesis for this memory leak with tested evidence."
* **Tool Triggered:** `hypotheses` (action: "log", action: "query")
---
## 16. State Checkpoints & Rollbacks
* **Don't say:** "Save a backup snapshot before we do this refactor."
* **Do say:** "Create a checkpoint named 'pre-refactor' before editing the database layer."
* **Tool Triggered:** `manage_checkpoint`
---
By phrasing requests around *actions* rather than *information retrieval*, the LLM is primed to leverage the rich MCP toolset built into the Antigravity Memory Server.
@@ -1,4 +0,0 @@
# Role & Competency Constraints
- **Role**: Junior Developer.
- **Discretion**: NO autonomous discretion allowed. The agent must operate strictly under the direct guidance of the user and must not make autonomous decisions or execute sweeping, unchecked actions.
+1 -1
View File
@@ -1,6 +1,6 @@
# Neovim UX Protocol & Live Editing
Whenever you need to actively interact with the user's Neovim UI or dynamically inject code edits into their live buffers, use the nvim_execute_lua tool (the "God Mode" escape hatch).
Whenever you need to actively interact with the user's Neovim UI or dynamically inject code edits into their live buffers, use the nvim_exec tool (with action 'lua') (the "God Mode" escape hatch).
## 1. Showing UI Feedback (Agent Notifications)
The user has a global Lua table _G.gemini loaded in their Neovim environment. You can use it to pop up a floating notification window when you are starting a background task.
+7 -9
View File
@@ -21,7 +21,7 @@ The Antigravity CLI (`agy`) acts as the MCP Client and automatically manages the
When `agy` starts up, it reads `mcp_config.json`. If it finds `"win-nvim": { "command": "C:\\Users\\reazul.ashraf\\.local\\bin\\mcp-memory-nvim.exe" }`, it will spawn that binary as a background subprocess using standard `stdio`.
3. **Communication:**
- The LLM requests to use a consolidated tool (e.g., `nvim_view` with action `goto_line`, or `nvim_execute_lua`).
- The LLM requests to use a consolidated tool (e.g., `nvim_workspace` with action `focus`, or `nvim_exec`).
- The `agy` CLI sends a JSON-RPC request to the `mcp-memory-nvim` subprocess via its `stdin`.
- The Rust MCP Server receives the request, connects to the Neovim active socket/pipe (`~/.gemini/active_nvim.txt` or `\\.\pipe\nvim.*`), sends the Msgpack-RPC command, and writes the JSON-RPC response back to `stdout`.
- The `agy` CLI reads the response from `stdout` and returns it to the LLM context.
@@ -29,12 +29,10 @@ The Antigravity CLI (`agy`) acts as the MCP Client and automatically manages the
## Capabilities & Requirements
To use this architecture, Neovim must run the `gemini-integration.lua` script to broadcast its active socket to `~/.gemini/active_nvim.txt`.
The MCP server provides 7 cohesive domain tools:
1. **`nvim_buffer`** (actions: `get_active`, `read`, `open`, `create_scratch`, `save`, `reload`, `close`, `list`, `search`)
2. **`nvim_window`** (actions: `list`, `get_active`, `focus`, `split`, `close`)
3. **`nvim_view`** (actions: `goto_line`, `get_cursor`, `get_viewport`, `get_selection`)
4. **`nvim_diagnostics`** (actions: `get`, `set`, `set_quickfix`)
5. **`nvim_visual`** (actions: `preview`, `extmark`, `highlight`, `clear_highlight`)
6. **`nvim_execute_lua`** (direct Lua execution escape hatch)
7. **`nvim_system`** (actions: `get_info`, `get_messages`, `send_to_terminal`)
The MCP server provides 5 cohesive mega-tools:
1. **`nvim_buffer`** (actions: `read`, `replace`, `save`, `undo`, `redo`, `create_scratch`)
2. **`nvim_workspace`** (actions: `list_buffers`, `list_windows`, `focus`, `split`, `cwd`)
3. **`nvim_intelligence`** (actions: `hover`, `definition`, `references`, `outline`, `query`, `diagnostics`, `rename`, `code_action`)
4. **`nvim_ui`** (actions: `highlight`, `ghost_text`, `clear`)
5. **`nvim_exec`** (actions: `lua`, `vimscript`, `terminal`)
+4 -4
View File
@@ -16,9 +16,9 @@ File edits must use EXACTLY one of two paths:
## 2. Strict Tool Adherence (No Raw Lua RCE)
You must strictly use the specialized, sandboxed Neovim MCP tools:
- `nvim_buffer`: For reading, writing, saving, and creating scratch buffers.
- `nvim_window`: For creating splits and focusing panes.
- `nvim_visual`: For highlighting diffs, adding ghost text, and showing previews.
**DO NOT** use `nvim_execute_lua` to mutate editor state. It is restricted to **READ-ONLY** queries.
- `nvim_workspace`: For creating splits and focusing panes.
- `nvim_ui`: For highlighting diffs, adding ghost text, and showing previews.
**DO NOT** use `nvim_exec` (action `lua`) to mutate editor state. It is restricted to **READ-ONLY** queries.
## 3. Headless Quarantine
Headless mode (`nvim --headless`) is strictly banned for interactive edits.
@@ -26,7 +26,7 @@ Headless mode (`nvim --headless`) is strictly banned for interactive edits.
Headless instances are allowed ONLY for non-interactive background batch processing (e.g., project-wide formatting or linting).
## 4. UI Presentation & Chat Console Minimization
Never output large plans, context blocks, or architectural discussions to the chat console if Neovim is running. You MUST use the `nvim_buffer` and `nvim_window` tools to open a vertical split (e.g., `Antigravity_Plan.md` scratch buffer) and present the markdown natively. Reserve the chat console strictly for brief confirmations.
Never output large plans, context blocks, or architectural discussions to the chat console if Neovim is running. You MUST use the `nvim_buffer` and `nvim_workspace` tools to open a vertical split (e.g., `Antigravity_Plan.md` scratch buffer) and present the markdown natively. Reserve the chat console strictly for brief confirmations.
## 5. Visual Cues & Auto-Save
When manipulating buffers via MCP:
+1 -1
View File
@@ -3,6 +3,6 @@
When interacting with the user's Neovim editor (e.g., opening a file, moving the cursor, reading the active buffer, setting diagnostics), you MUST ALWAYS use the MCP tools provided by the `win-nvim` (Neovim) MCP server.
- You are strictly forbidden from using bash scripts, `nvim --server`, or other raw terminal/shell hacks to remote-control Neovim.
- You must rely entirely on the consolidated MCP tool registry (`nvim_buffer`, `nvim_window`, `nvim_view`, `nvim_diagnostics`, `nvim_visual`, `nvim_execute_lua`, `nvim_system`).
- You must rely entirely on the consolidated MCP tool registry (`nvim_buffer`, `nvim_workspace`, `nvim_intelligence`, `nvim_ui`, `nvim_exec`).
- If the tool is eagerly loaded, use it natively as an agent tool. If lazy-loaded, invoke it via the `call_mcp_tool` mechanism.
-5
View File
@@ -1,5 +0,0 @@
# Rule 1: Network Connectivity Testing
- **Mandatory Tooling**: When testing ANY network connectivity, you MUST use the exact same Rust crates used in the production code.
- **Methodology**: You must create standalone Rust applications (e.g., small test binaries or examples in the repository) that utilize the exact same networking plumbing as the main application.
- **Forbidden Tools**: You CANNOT use bash (e.g., curl, netcat), Python, Java, Perl, wscat, or any other external scripting/CLI tools to validate network connectivity. Testing with these tools creates false positives and bypasses the actual networking crates causing issues.
-5
View File
@@ -1,5 +0,0 @@
# Rule 2: Empirical Evidence & Logging
- **Mandatory Logging**: If an issue occurs and there are no logs (or insufficient logs) to diagnose it, you must STOP immediately and add logging.
- **Replication**: After adding logging, you must repeat the test to replicate the exact issue so that the logs capture the failure.
- **No Blind Changes**: NO business logic can be altered blindly or based on guesses. You must have empirical evidence (derived from the logs) proving the root cause before attempting any changes to the logic.
-7
View File
@@ -1,7 +0,0 @@
# Rule 3: Resiliency & Cross-OS Load Testing
- **Resiliency Requirement**: A fix must be resilient and work under load. It is not enough for it to work just once.
- **Mandatory 5x Matrix Testing**: Any request/response cycle must be explicitly tested five (5) times for each of the following boundaries:
1. Windows to Windows (`win - win`)
2. WSL to Windows (`wsl - win`)
- **Documentation**: The results of these load tests MUST be recorded permanently (e.g., in an artifact or log) to prove resilience and to avoid repeating needless re-tests.
@@ -1,5 +0,0 @@
# Rule 4: Component Isolation & Skeletal Troubleshooting
- **Targeted Testing**: If a bug is found, DO NOT rely on testing the full stack. You must isolate and test the offending class or method directly.
- **Skeletal Reproducers**: If the issue spans across boundaries (e.g., between server, stub, or nvim), you must create skeletal (minimal reproducible) versions of those components.
- **Purpose**: Troubleshooting must be done on these skeletal versions to isolate the broken feature or aspect without the noise, side-effects, or overhead of the full application stack.
@@ -1,5 +0,0 @@
# Rule 5: Client-Centric Testing Personas
- **Avoid Server Bias**: Unit tests and integration tests must NOT be exclusively server-centric.
- **Client Personas**: Tests must explicitly adopt the persona, perspective, and constraints of the client components (e.g., the `stub` or `nvim`).
- **Validation**: Testing must validate the interaction from the client's side, ensuring that the client component correctly constructs the request, handles the connection lifecycle, and properly parses the response, rather than just verifying that the server successfully processed an isolated payload.
-13
View File
@@ -1,13 +0,0 @@
---
name: strict-no-verify
description: Strictly forbids the use of --no-verify or -n when interacting with git to ensure quality gates are run.
always_on: true
---
# STRICT GIT HOOK ENFORCEMENT
- **NEVER** use `--no-verify` or `-n` with `git commit` or `git push`.
- Bypassing git hooks is considered a critical violation of trust.
- You must allow the local git hooks (e.g., `pre-push`) to validate the code.
- If a hook fails (e.g., `ruff` check, `pytest`), you MUST fix the underlying issues iteratively until the hook passes natively. Do not assume a single fix attempt works without re-verifying.
- BEFORE running `git push`, you MUST use the `ask_question` tool to pop up an interactive modal to request explicit user permission. Wait for the user's approval before executing the push.
-4
View File
@@ -1,4 +0,0 @@
Write-Host "Building Windows Server..." -ForegroundColor Cyan
Building Windows Server...
cargo build --release -p mcp-memory-server
Compiling tantivy v0.26.2
-39
View File
@@ -1,39 +0,0 @@
use std::process::Command;
fn main() {
let mut git_hash = Command::new("git")
.args(["rev-parse", "--short", "HEAD"])
.output()
.ok()
.and_then(|out| String::from_utf8(out.stdout).ok())
.unwrap_or_else(|| "unknown".to_string());
git_hash = git_hash.trim().to_string();
let is_dirty = Command::new("git")
.args(["status", "--porcelain"])
.output()
.is_ok_and(|out| !out.stdout.is_empty());
if is_dirty {
let dirty_ts = chrono::Local::now().format("%y.%m.%d.%H%M%S").to_string();
git_hash.push_str(&format!("-dirty-{dirty_ts}"));
}
let git_date = Command::new("git")
.args(["log", "-1", "--format=%cd", "--date=format:%y.%m.%d.%H%M%S"])
.output()
.ok()
.and_then(|out| String::from_utf8(out.stdout).ok())
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
.unwrap_or_else(|| chrono::Local::now().format("%y.%m.%d.%H%M%S").to_string());
let version = format!("v{git_date} ({git_hash})");
println!("cargo:rustc-env=APP_VERSION={version}");
println!("cargo:rerun-if-changed=../.git/HEAD");
println!("cargo:rerun-if-changed=../.git/index");
println!("cargo:rerun-if-changed=src");
println!("cargo:rerun-if-changed=Cargo.toml");
println!("cargo:rerun-if-changed=build.rs");
}
BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 82 KiB

-199
View File
@@ -1,199 +0,0 @@
# MCP Memory Server Architecture & Workflow Design
## 1. Core Architecture
The `mcp-memory` system runs as a **single, continuously running background daemon natively on Windows**. It manages the state of the Antigravity knowledge graph and serves as a universal backend for both Windows and WSL environments.
### Why this design?
* **Cross-OS I/O Optimization:** Prevents the WSL agent from performing slow, heavy filesystem writes against the mounted Windows `C:\` drive.
* **Concurrency & Locking:** A single daemon holds the lock on the `mcp_memory` JSON files, preventing data corruption and eliminating complex delta-reconciliation between parallel WSL and Windows processes.
* **Dual Transport System:** Utilizes both `stdio` and HTTP transports concurrently. The local Windows `agy` instance connects natively via standard `stdio`, while the Axum HTTP server provides synchronous, non-blocking access for WSL clients and external scripts.
## 2. Server Transport & Endpoints (Axum)
The daemon uses the `axum` and `rust-mcp-axum` crates, binding to `0.0.0.0:3000` to serve the network.
### Standard MCP Endpoints
* `GET /ws`: The WebSocket endpoint for efficient, low-latency, full-duplex JSON-RPC communication (preferred for proxies and the UI dashboard).
* `GET /sse`: The Server-Sent Events (SSE) endpoint. Antigravity clients connect here to keep a one-way pipe open for receiving pushed responses.
* `POST /messages`: The JSON-RPC endpoint. Clients use this to send tool calls and resource reads up to the server when connected via SSE.
### Dashboard REST API
The server hosts a rich Single Page Application (SPA) natively on the root route, backed by a suite of REST endpoints:
* `GET /`: The Brain Monitor live HTML dashboard SPA.
* `GET /api/graph`: Returns the full node/edge topology for the interactive physics-simulated canvas.
* `GET /api/tasks` & `POST /api/tasks/{id}/complete`: Drives the actionable Kanban board.
* `GET /api/ledger` & `GET /api/search`: Powers the code change ledger and global fuzzy search UI.
* `GET /api/stats`: Returns a JSON snapshot of current entity, relation, task, and tech debt counts.
### Git & IDE Integration Endpoints
* `UDP /nvim/telemetry`: A one-way connectionless datagram listener that Neovim instances hit on `FocusGained` or `BufEnter` to globally broadcast the user's active file to the UI and Agent.
* `GET /gate/verify`: A lightweight, deterministic endpoint used by external scripts (like a `git push` wrapper) to verify if an action is authorized based on the current state.
## 3. Client Connections
The Antigravity configurations (`mcp_config.json`) utilize the dual-transport system:
* **Windows `agy`:** Spawns and connects to the local daemon natively via `stdio` subprocess execution.
* **WSL (Linux) `agy`:** Connects to the running Windows HTTP daemon via the host network proxy, e.g., `http://127.0.0.1:3000/sse`.
## 4. Git Integration (Global Wrapper)
Instead of relying on localized per-repository Git hooks (like `.git/hooks/pre-push`), the system leverages a **global bash/PowerShell alias wrapper** for the `git` command. This intercepts `git` commands universally across the OS.
### Workflow Example (Push Safety Gate)
1. The user types `git push`.
2. The global wrapper intercepts the command.
3. It makes a synchronous HTTP request to the local daemon: `curl -s http://localhost:3000/gate/verify`.
4. If the endpoint returns `200 OK` (indicating the `PrePushAuditor` subagent has verified that unit tests pass and history is squashed), the push proceeds.
5. If not `200 OK`, the wrapper blocks the push and alerts the user to fix tests or run `gsquash`.
### Benefits of the Wrapper Approach
* **Universal Enforcement:** The push safety gate is protected across all repositories automatically, without copying hook scripts.
* **No File Locks:** Uses safe, lightweight, parallelizable HTTP requests rather than executing the Rust binary directly.
* **Action Logging:** The wrapper can be seamlessly extended to log actions (like `checkout` or `commit`) directly into the knowledge graph in real-time.
## 5. Storage Architecture & Persistence (Redb LSM-Tree)
The daemon has completely eliminated raw JSON file sprawl and fragmented delta-file reconciliation. It now utilizes a pure-Rust, embedded Key-Value engine (`redb`) that implements a robust Log-Structured Merge-Tree (LSM-tree) architecture.
### Key Principles:
* **Embedded Database Engine:** All structured components (Tasks, Snippets, Tech Debt, Checklists, etc.) are stored as binary-encoded values inside a unified `redb` database file (`store.redb`).
* **ACID Compliance & File Locks:** The Windows daemon holds an exclusive read-write lock on the database file, guaranteeing zero data corruption, race conditions, or lock contention during concurrent access.
* **Atomic Write-Guard Scope:** Store modification methods (`Store::modify` and `Store::modify_async`) retain the write lock through both the in-memory mutation and JSON serialization phases, eliminating lock-release TOCTOU race conditions.
* **Store Quarantine Mode:** If deserialization fails during `Store::load_from_db`, the store flags `is_corrupted = true` and refuses to overwrite database keys with default values on subsequent writes.
* **Asynchronous Checkpointing:** The core Knowledge Graph (Entities, Relations, Observations) still utilizes a Write-Ahead Logging (WAL) pattern (`wal.jsonl`) and a master snapshot (`master.json`) to allow safe, lock-free memory mutations which are reconciled in the background.
## 6. Domain Models & Component Stores
The system leverages a modular, thread-safe generic `Store<T>` abstraction that automatically transparently serializes and deserializes native Rust structs directly into the underlying `redb` tables.
Currently implemented persistent stores include:
* **Audit Ledger & Tasks:** Tracks agent actions and active background tasks.
* **Context & Handoffs:** Session Summaries, Handoff Memos, Hypotheses, and Agent Signals.
* **Engineering Tracking:** ADRs (Architecture Decision Records), Snippets, Error Fixes, Tech Debt, and PR Checklists.
* **Environment State:** Pinned Files, Env Fingerprints, Milestones, and Environments.
* **Safety Gates:** Authorized execution gates (Push Safety).
## 7. Full-Text & Semantic Search Engine (Tantivy + FastEmbed)
To support blazing-fast, intelligent semantic retrieval across the sprawling knowledge graph, the daemon embeds **Tantivy** (a full-text search engine inspired by Apache Lucene) alongside **FastEmbed** (a local ONNX runtime for vector embeddings).
* **The `MemoryIndex`:** Whenever the graph or auxiliary stores mutate, a background thread dynamically rebuilds the Tantivy index (`tantivy_index/` dir) and computes semantic vectors.
* **Pre-cached Vector Embeddings:** `SearchService::semantic_search` reuses pre-cached snippet embedding vectors (`snippet.embedding`), bypassing redundant ONNX neural network inference calls during query execution.
* **Global Omni-Search:** This architecture powers the `omni_search` tool, allowing subagents to instantly fuzzy-search and semantically rank documents across Entities, Tasks, Snippets, Error Fixes, and ADRs simultaneously in milliseconds, without loading massive JSON arrays into RAM.
## 8. Webhook Telemetry & Passive Ingestion
The server features a suite of webhook listeners that passively ingest development activity to build context without requiring human copy-pasting:
* **Terminal Ingestion (`/terminal/telemetry`):** Shell hooks (PowerShell/Nushell) silently POST command execution history and exit codes, allowing agents to read recent stack traces via the `memory://terminal/recent` resource.
* **IDE Telemetry (`/nvim/telemetry`):** A connectionless UDP datagram listener receives focus events from Neovim, broadcasting the user's active file to the UI and Agent instantly.
## 9. The Gate System (Push Safety Verification)
The binary supports a flexible safety gate authorization system, accessible both via the HTTP API and CLI subcommands.
* **API / CLI set**: Records an authorization status (`authorized`, `blocked`, or `pending`) for a specific target and namespace. Can be invoked via `POST /gate/set` (JSON) or `mcp-memory-stub gate set`.
* **API / CLI verify**: Evaluates a pending action against the gate store. It returns standard HTTP status codes (`200 OK`, `403 Forbidden`, `404 Not Found`) via `GET /gate/verify?action=...` or POSIX exit codes (0, 1, 2) via `mcp-memory-stub gate verify`. Both support a `consume` parameter/flag to immediately revoke the authorization after a successful check.
## 9. Operational Configuration & Paths
The physical storage location of the knowledge graph and all persistent stores is strictly controlled by the MCP_MEMORY_STORE_DIR environment variable.
* **Default Path:** If not set, the daemon defaults to ~/.gemini/mcp_memory.
* **Port Binding:** The Axum HTTP server strictly binds to .0.0.0:3000.
## 10. Exposed MCP Capabilities (Tools)
The server implements the Model Context Protocol (MCP) by exposing a vast suite of tools via the JSON-RPC interface, categorized broadly into:
* **Graph Management:** create_entities, create_relations, merge_entities,
read_graph, etc.
* **Task & Context Tracking:** tasks, milestones, handoff_memos, hypotheses, agent_signals, process_logs, add_session_summary, etc.
* **Engineering & DevOps:** log_code_change, log_error_fix, tech_debt, decisions, etc.
* **Environment & Workspaces:** environment, manage_checkpoint, manage_subagent_namespace, snippets, etc.
## 11. Concurrency & Thread Safety
With the introduction of the Dual Transport System, the daemon must safely handle simultaneous read/write requests from both Stdio (Windows agy) and HTTP (WSL agy) clients.
* **Shared State:** The entire server operates on a cloned Arc<MemoryState>.
* **Locking Mechanism:** The unified Knowledge Graph and modular Store<T> components are protected by RwLock primitives.
* **Safe Mutation:** Store modifications utilize closure-based modify(|store| { ... }) methods to ensure locks are safely acquired, mutations applied, and file writes executed sequentially without deadlocking the asynchronous Tokio runtimes.
## 12. Lifecycle & Startup Management (Server/Stub Architecture)
The mcp-memory daemon employs a strict Server/Client paradigm to maintain separation of concerns. There are no dual roles or morphing executables.
### The Windows Background Daemon (`mcp-memory-server.exe`)
The server executable is responsible exclusively for running the Axum HTTP and WebSockets daemon and managing the Knowledge Graph. It does not contain any proxy logic. If port 3000 is already in use by an existing server instance, it gracefully exits instead of attempting to run.
* **Non-Blocking Startup & Indexing:** Upon launch, the server uses a `tokio::spawn` task to rebuild the Tantivy index in the background. This ensures the Axum HTTP server binds immediately to port 3000, allowing instantaneous liveness checks via the `/ping` endpoint without waiting for the synchronous I/O operations of the index rebuild to complete.
* **Robust Background Detachment:** To ensure the server survives the death of the parent shell that spawns it (such as a deployment script), it uses Windows `WScript.Shell` (via `start_server.ps1`) to spawn the binary with a strictly hidden window style (`SW_HIDE`). This completely detaches it from the parent process tree, preventing `CTRL_CLOSE_EVENT` signals from killing the background daemon when the deploying terminal closes.
### The Client Proxy (`mcp-memory-stub.exe`)
All Antigravity sessions (Windows and WSL) use the lightweight `mcp-memory-stub` as their proxy. The stub connects to the server via WebSockets and acts as the bridge for standard `stdio` JSON-RPC traffic.
* **Startup via Interop/Spawn:** Upon launch, the stub attempts to connect to the Windows host on port 3000. If the server is offline, the stub automatically executes a spawn command (e.g., executing `Start-Process` natively, or via WSL interop) to silently wake up the Windows Leader before commencing the proxy loop.
* **MPSC Queue Resilience:** The stub utilizes an asynchronous multi-producer, single-consumer (MPSC) channel queue. If the Windows Leader daemon restarts or momentarily drops, the proxy buffers incoming JSON-RPC tool calls and infinitely retries them until the connection is restored. This guarantees **zero message loss** and **zero thread leaks** without crashing the active `agy` session.
* **Zero I/O Penalty (WSL):** This ensures the Linux binary never directly touches the Windows NTFS files, reserving all heavy disk operations for the native Windows host.
## 13. Cargo Workspace & Binary Artifacts
To optimize for different environments, the codebase is structured as a Cargo Workspace containing two distinct crates:
### 1. mcp-memory-server (The "Full-Fat" Daemon)
* **Path:** server/
* **Size/Complexity:** Heavy (contains Axum, MCP SDK, JSON parsing, Tokio runtime).
* **Role:** This is the primary background daemon. It binds to .0.0.0:3000, holds file locks, and manages the graph.
* **Windows Behavior:** It is designed to run in the background as a standalone service.
### 2. mcp-memory-stub (The Ultra-Lightweight Proxy)
* **Path:** stub/
* **Size/Complexity:** Extremely light (only relies on
eqwest and okio).
* **Role:** A dedicated, OS-agnostic proxy binary used strictly for routing stdio JSON-RPC traffic over HTTP to a remote Leader. Windows gy clients point directly to this binary to bypass loading the heavy Server daemon into memory.
* **WSL Behavior:** Compiled as a Linux native binary (x86_64-unknown-linux-musl). When executed by WSL agy, it acts as a transparent proxy to http://127.0.0.1:3000. It can also execute wake_cmd (e.g., WSL interop) to silently wake the Windows host if the Leader is offline.
## 14. Neovim Integration Architecture & "God Mode"
To enable seamless pair-programming inside Neovim, the daemon integrates with Neovim using two complementary systems: a Webhook Telemetry pipeline and dedicated MCP binaries.
### Telemetry Pipeline (Last Focused Wins)
A lightweight Lua script (`gemini-integration.lua`) is loaded into Neovim, which fires an asynchronous UDP datagram to `127.0.0.1:3002` (fire-and-forget via native libuv) whenever the user focuses a buffer or moves the cursor. The server then writes this data (including `session_id`, `file`, `line`, and `col`) to both the Windows and WSL `active_nvim.txt` files and broadcasts it over WebSockets.
### Native MCP Binaries (win-nvim & linux-nvim)
The project compiles two standalone, highly-performant binaries that implement the MCP JSON-RPC protocol over Stdio and bridge it directly to Neovim's Msgpack-RPC Named Pipes/Sockets. These binaries avoid hardcoding infinite tools by utilizing a "God Mode" escape hatch.
Exposed Neovim Tools:
* **
vim_get_active_buffer &
vim_get_cursor**: Read file state.
* **
vim_goto_line &
vim_set_diagnostics**: Manipulate IDE state.
* **
vim_get_visual_selection**: Read exact highlight coordinates (handles mode dynamically).
* **
vim_list_buffers**: Discover unsaved work and context.
* **
vim_get_diagnostics**: Read live LSP errors dynamically instead of requiring a compiler.
* **
vim_execute_lua ("God Mode")**: The ultimate fallback tool. Evaluates raw Lua scripts inside the active Neovim instance and returns JSON. This prevents the need to continuously recompile the Rust server whenever a new Neovim capability is required.
## 15. Build & Deployment Strategy
Because the background server operates as an always-on Windows daemon, standard recompilation and file-copying strategies will fail due to active Windows OS file locks.
### Randomized Lock Bypassing
The \uild.ps1\ deployment pipeline intercepts locked \.exe\ files by appending a unique, timestamped/randomized suffix (e.g., \mcp-memory-server.exe.12345.old\) when forcing a \Move-Item\. This guarantees that rapid sequential deployments (where a previous \.old\ file might still be locked by a zombie process) never silently fail or collide.
### Dynamic Versioning
To trace binary provenances during rapid deployment cycles, all binaries embed dynamic versioning directly at compile time (via \uild.rs\ and \uild_template.rs\). The injected \APP_VERSION\ environment variable combines the static Cargo \ ersion\ with the live \git\ short hash and UTC timestamp, allowing the CLI \--version\ commands and the HTTP \/api/version\ endpoints to guarantee exactly which iteration of the code is actively executing.
## 16. Testing Architecture (Native Rust E2E)
Historically, the project relied on a complex Python testing suite (\pytest\ + \mcp_client.py\) to validate the server over HTTP/SSE. This has been fully deprecated in favor of **Native Rust End-to-End Testing**.
* **Unit Tests:** Handlers and business logic are tested directly inside \server/src/handlers.rs\ using native \ okio::test\ constructs.
* **E2E Tests:** Integration and full-system tests run via \stub/tests/e2e.rs\ and \win-nvim/tests/integration_test.rs\, ensuring type safety, faster execution, and eliminating Python environment dependencies.
## 17. Automated Git Context Binding (git2)
Instead of forcing the LLM client to manually run `git rev-parse HEAD` and pass `git_branch` / `git_commit` arguments for every single code change, the server integrates the native **`git2`** C bindings.
When engineering endpoints (`log_code_change`, `log_error_fix`, `log_tech_debt`) are invoked, the server asynchronously discovers the surrounding Git repository, peels the HEAD reference, and automatically injects the current commit hash, commit message, and branch name directly into the stored entities and audit logs. This guarantees airtight VCS traceability without wasting LLM tokens or relying on the agent's memory.
## 18. Upcoming Enhancements
### A. Graph Summarization & Decay
To prevent context window bloat, the Redb engine will enforce TTLs on ephemeral nodes (`StickyNotes`, minor `Tasks`). Furthermore, an `archive_routine` prompt will allow subagents to automatically compress older `SessionSummaries` into dense milestone retrospectives.
### B. Proactive Subagent Triggers
The daemon will eventually gain the ability to autonomously spawn background subagents (like the `BugDiagnostician`) when specific events are detected in the webhook telemetry, rather than relying strictly on the human user to initiate the agent.
## 11. Advanced Clipboard Capabilities
The memory server bypasses typical cross-OS Linux/Windows clipboard restrictions by proxying operations from the WSL stub back to the Windows Axum host.
It supports reading and writing rich formats natively to the Windows Host OS using the clipboard-win and rboard crates:
* **Plain & Rich Text:** CF_UNICODETEXT and CF_HTML are supported for rich copying/pasting.
* **File Drops (CF_HDROP):** The server can parse file lists copied from Windows Explorer, and can inversely synthesize file drops into the clipboard from absolute paths.
* **Images (CF_BITMAP):** The server natively rasterizes clipboard bitmaps to JPEG on read, and can write raw RgbaImage buffers back to the clipboard on write.
* **Developer Tooling:** read_file_skeleton (AST), get_active_worktree_context (Git), get_recent_logs, toggle_clipboard_watch_mode.
## 19. High-Performance Concurrency & Resilience Guarantees
* **Async Channel Backpressure (`push_async`)**: `Store::modify_async` uses `DbWriteQueue::push_async` with `tx.send(task).await` backpressure to guarantee database write persistence under heavy async write loads without dropping write transactions.
* **Atomic Search Index Swaps**: `MemoryState::rebuild_index` constructs and populates a new `MemoryIndex` instance in isolation before performing an atomic pointer swap (`*self.search_index.write().await = new_idx`), eliminating transient empty search result windows.
* **SIMD-Friendly Single-Pass Cosine Similarity**: `cosine_similarity` calculates dot product and Euclidean norm squares in a single linear pass over float vectors, enabling SIMD compiler auto-vectorization.
* **Safe Stream Decoding on Log Tails**: Log tail operations (`get_recent_logs`) read raw bytes and decode using lossy UTF-8 conversion (`String::from_utf8_lossy`) to ensure resilience when seeking across multi-byte UTF-8 boundaries.
* **Serde Parameter & Enum Tolerance**: All action enums (`StickyNoteAction`, `SnippetSearchMode`, `Relation`) support case-insensitive variants and field aliases (`source`/`from`, `target`/`to`, `relationType`/`relation_type`) to ensure seamless execution when LLMs pass varied string formatting.
-12
View File
@@ -10,18 +10,6 @@ vim.api.nvim_create_autocmd({"VimEnter", "FocusGained", "BufEnter", "BufWritePos
if #vim.api.nvim_list_uis() > 0 then
local server_name = vim.v.servername
if server_name then
-- 1. Legacy Disk Write (Fallback)
local home = os.getenv("HOME") or os.getenv("USERPROFILE")
if home then
os.execute("mkdir -p " .. home .. "/.gemini")
local path = home .. "/.gemini/active_nvim.txt"
local f = io.open(path, "w")
if f then
f:write(server_name)
f:close()
end
end
-- 2. V2 Telemetry Push (HTTP with Knowledge Projection + UDP Fast Mirror)
local file = vim.api.nvim_buf_get_name(0)
local cursor = vim.api.nvim_win_get_cursor(0)
+1 -1
View File
@@ -59,7 +59,7 @@ The server registers 5 high-signal workflow prompts to initiate standardized age
## 5. Consolidated Smart Tools Architecture (11 Primary Tools)
The server consolidates granular single-purpose tools into domain-named smart tools. Always prefer the consolidated tools over legacy aliases:
The server consolidates granular single-purpose tools into domain-named smart tools.
* **`tasks`**: Complete task lifecycle management.
- `action: "add"`: Create a new task (requires `title`, optional `description`, `git_branch`, `repo_name`, `priority: "low" | "medium" | "high" | "urgent"`, `assigned_agent`, `verification_command`, `parent_id`, `dependencies`).
-74
View File
@@ -1,74 +0,0 @@
rebuild_index: found 229 entities, 24 tasks
spawn_blocking started in rebuild_index
add_task_sync called for task: 8da665f7-107c-41c8-b203-d39a9ff1f9a5
Writer add_document returned id/result
Needs_commit set to true in add_task_sync
add_task_sync called for task: 01a788f0-7adb-456c-bf37-02bbd7e1d2f8
Writer add_document returned id/result
Needs_commit set to true in add_task_sync
add_task_sync called for task: 5e8d9b26-ae31-4136-a4c4-6ead74887bb5
Writer add_document returned id/result
Needs_commit set to true in add_task_sync
add_task_sync called for task: ed184dd6-55ce-4d37-a06a-b34733795e03
Writer add_document returned id/result
Needs_commit set to true in add_task_sync
add_task_sync called for task: 3cea859d-c1ce-4f6c-bdc5-6eb65dbd8e4f
Writer add_document returned id/result
Needs_commit set to true in add_task_sync
add_task_sync called for task: 62446699-39b3-496b-9af8-99b331fe6c08
Writer add_document returned id/result
Needs_commit set to true in add_task_sync
add_task_sync called for task: 4b0e2179-1e70-4b64-9c2d-ff2fe2d05fdf
Writer add_document returned id/result
Needs_commit set to true in add_task_sync
add_task_sync called for task: 16dd35e4-eadd-4597-a5b6-9844852cfb76
Writer add_document returned id/result
Needs_commit set to true in add_task_sync
add_task_sync called for task: c85f352b-f15b-4f90-a6ae-18fe914212b2
Writer add_document returned id/result
Needs_commit set to true in add_task_sync
add_task_sync called for task: d1e907a2-89a2-4814-8722-22c754cc943c
Writer add_document returned id/result
Needs_commit set to true in add_task_sync
add_task_sync called for task: c382a511-a5d6-4114-ad2c-f09fdd36d66a
Writer add_document returned id/result
Needs_commit set to true in add_task_sync
add_task_sync called for task: 42ca3765-5c69-4cdd-8324-5a174c34d4ae
Writer add_document returned id/result
Needs_commit set to true in add_task_sync
add_task_sync called for task: 05792eaa-4bc5-45e5-b9a0-d9027b3b3974
Writer add_document returned id/result
Needs_commit set to true in add_task_sync
add_task_sync called for task: 15c9fd58-8d8f-4c2f-80f4-15a46ba54588
Writer add_document returned id/result
Needs_commit set to true in add_task_sync
add_task_sync called for task: 9b55e54c-ac1b-4219-acf3-68f7cb34a1fd
Writer add_document returned id/result
Needs_commit set to true in add_task_sync
add_task_sync called for task: a04923ea-6abf-41ba-9c45-f7d9cdac3440
Writer add_document returned id/result
Needs_commit set to true in add_task_sync
add_task_sync called for task: 4233293e-6d93-4c46-b9aa-f9e712af0e86
Writer add_document returned id/result
Needs_commit set to true in add_task_sync
add_task_sync called for task: 93451cd9-25c5-4323-8dce-79bba124242d
Writer add_document returned id/result
Needs_commit set to true in add_task_sync
add_task_sync called for task: 949f1d59-e1e2-421c-9682-43a79f41679b
Writer add_document returned id/result
Needs_commit set to true in add_task_sync
add_task_sync called for task: cd680df7-2e1a-4486-bb9b-3881476c762e
Writer add_document returned id/result
Needs_commit set to true in add_task_sync
add_task_sync called for task: 561daa2b-ddb5-44ae-8fb8-8155405759fb
Writer add_document returned id/result
Needs_commit set to true in add_task_sync
add_task_sync called for task: e36b0eba-aa79-493f-b89b-3da46a44fa11
Writer add_document returned id/result
Needs_commit set to true in add_task_sync
add_task_sync called for task: a3a717b3-438a-42a7-83ec-2f2eb5d775b4
Writer add_document returned id/result
Needs_commit set to true in add_task_sync
add_task_sync called for task: 6a1b05d5-0ffd-4b0c-bb65-f45e0cb5540a
Writer add_document returned id/result
Needs_commit set to true in add_task_sync
-53
View File
@@ -1,53 +0,0 @@
# MCP Tools Review & Enhancement Strategy
## Part 1: Current Arsenal Review
Our current MCP ecosystem is highly advanced, utilizing a **Dual-Transport Leader/Stub Architecture** (Windows Host + WSL Proxy) to completely eliminate cross-OS I/O latency.
### 1. Context & Token Optimization
* `read_file_skeleton`: Highly effective. Uses tree-sitter to extract ASTs (Rust, Python, TS). **Score: A+ (Massive token savings)**
* `get_active_worktree_context`: Native git2 integration. Bypasses shell parsing for clean JSON diffs. **Score: A**
* `process_logs`: Direct file seeking and daemon log management (`watch`, `get`, `clear`). Prevents LLMs from reading multi-megabyte log files. **Score: A**
### 2. Neovim IDE Integration (nvim-core)
* `nvim_buffer`, `nvim_window`, `nvim_view`, `nvim_diagnostics`, `nvim_visual`, `nvim_execute_lua`, `nvim_system`.
* **Review:** Exceptional human QoL. The agent interacts with the code where the human's eyes actually are. Ghost text and diagnostic extmarks provide an IDE-like experience usually reserved for closed-source tools like Cursor. **Score: S-Tier**
### 3. Clipboard & Workflow
* `clipboard` (`read`, `write`).
* **Review:** Native cross-OS clipboard-win and arboard implementation with on-demand image grab. Bridges the gap between manual human research and the agent's context. **Score: A**
### 4. Graph & Memory Management
* `create_entities`, `hypotheses`, `agent_signals`, `handoff_routine`.
* **Review:** Solid foundation for state persistence across branches and days. **Score: A**
---
## Part 2: Proposed Enhancements (Focus: T2R, Token Cost, QoL)
To push the system to the absolute bleeding edge of autonomous coding, I propose the following 5 new tools/enhancements.
### 1. `replace_ast_node` (Robust Structural Editing)
* **The Problem:** Standard text replacement uses exact string matching and line numbers. Line numbers change when humans edit simultaneously, and string matching fails on whitespace/indentation.
* **The Solution:** An MCP tool that takes `(file_path, node_type, node_name, new_content)`. It uses tree-sitter to find the exact boundary of `fn execute(...)` and replaces just that AST node.
* **Impact:** Zero LLM syntax/indentation errors. 100% robust edits. Drastically lowers Time-to-Resolve (T2R) by eliminating failed edit loops.
### 2. `semantic_code_search` (Local Vector Embeddings)
* **The Problem:** Text search relies on exact regex. If the LLM guesses the wrong variable name, it wastes tokens searching and reading the wrong files.
* **The Solution:** Using Tantivy and BERT embeddings in our backend. We index the AST blocks of the codebase in the background. The LLM can query *"Where is the auth token validated?"* and get the exact 3 relevant functions instantly.
* **Impact:** Massive token cost reduction (no blind file reading). Instant T2R for codebase exploration.
### 3. `nvim_system` terminal execution (Interactive Execution QoL)
* **The Problem:** When the agent runs a background terminal command (`cargo build`, `npm run dev`), the output is hidden from the human, and interactive prompts cause the background task to hang indefinitely.
* **The Solution:** Dispatch to Neovim terminal splits where the human can watch the tests run natively, interact with prompts, see ANSI colors, and interact seamlessly.
* **Impact:** Massive Human QoL.
### 4. `read_directory_architecture` (Bird's-Eye View)
* **The Problem:** Single file inspection works for one file. When entering a new repository, the LLM usually runs `ls -R` and then has to guess what files do based on their names.
* **The Solution:** A tool that scans a directory structure and returns a clean hierarchical tree alongside summaries of what each directory and key file is responsible for.
* **Impact:** Immediate holistic context. Eliminates the "exploration phase" token tax.
### 5. `query_database_schema` (Introspection)
* **The Problem:** Working with databases usually involves the LLM writing clunky scripts to view table definitions, which often fail due to missing env vars or wrong dialects.
* **The Solution:** A direct MCP tool that parses the local `.env`, connects to the database (PostgreSQL), and returns a clean Markdown representation of the schema (Tables, Columns, Types, Foreign Keys).
* **Impact:** Prevents hallucinations about database structure. Fixes DB-related bugs significantly faster (T2R).
+12 -39
View File
@@ -2,48 +2,22 @@
When connected to this Neovim MCP server (`win-nvim`), you have powerful tools to interact directly with the active Neovim editor.
## The Consolidated Tool Arsenal (v2)
The server consolidates granular Neovim operations into 7 smart domain tools:
- **`nvim_buffer`**: Buffer and file management.
- `action: "open_file"`: Open file in buffer (args: `file`, `line`, `col`).
- `action: "open"`: Open buffer (args: `bufnr`).
- `action: "close"`: Close buffer (args: `bufnr`, `force`).
- `action: "reload"`: Reload buffer from disk (args: `bufnr`).
- `action: "save"`: Save buffer to disk (args: `bufnr`).
- `action: "list"`: List all loaded buffers.
- **`nvim_window`**: Window split and focus management.
- `action: "split"`: Split window (args: `direction: "horizontal" | "vertical"`, `file`).
- `action: "close"`: Close window (args: `winnr`).
- `action: "list"`: List open windows.
- `action: "get_active"`: Get active window details.
- `action: "set_active"`: Set active window focus (args: `winnr`).
- **`nvim_view`**: Editor viewport and navigation.
- `action: "get_active_buffer"`: Get active buffer details.
- `action: "get_cursor"`: Get current cursor line/col.
- `action: "goto_line"`: Jump cursor to line (args: `line`, `col`).
- `action: "get_viewport"`: Get visible line range in viewport.
- `action: "get_messages"`: Get Neovim command-line messages.
- **`nvim_diagnostics`**: LSP diagnostics querying and publishing.
- `action: "get"`: Get diagnostics (args: `bufnr`, `severity`).
- `action: "set"`: Set buffer diagnostics (args: `bufnr`, `diagnostics`).
- **`nvim_visual`**: Visual highlighting, extmarks, and quickfix.
- `action: "get_selection"`: Get current visual selection text and range.
- `action: "highlight_lines"`: Highlight line ranges (args: `bufnr`, `hl_group`, `start_line`, `end_line`).
- `action: "set_extmark"`: Place virtual text or sign extmarks (args: `bufnr`, `ns_id`, `line`, `col`, `opts`).
- `action: "set_quickfix"`: Populate quickfix list (args: `items`, `title`).
- **`nvim_execute_lua`**: God Mode arbitrary Lua evaluation.
- Arguments: `code: String`.
- **`nvim_system`**: System diagnostics and connection heartbeat.
- `action: "ping"`: Heartbeat test.
- `action: "status"`: Server and socket bridge health status.
## The Consolidated Tool Arsenal (v3)
The server consolidates granular Neovim operations into 5 smart mega-tools:
- **`nvim_buffer`**: Buffer and file management. Actions: `read`, `replace`, `save`, `undo`, `redo`, `create_scratch`.
- **`nvim_workspace`**: Window split and focus management. Actions: `list_buffers`, `list_windows`, `focus`, `split`, `cwd`.
- **`nvim_intelligence`**: Code intelligence and LSP. Actions: `hover`, `definition`, `references`, `outline`, `query`, `diagnostics`, `rename`, `code_action`.
- **`nvim_ui`**: Visual highlighting, diff previews, and ghost text. Actions: `highlight`, `ghost_text`, `clear`.
- **`nvim_exec`**: Escape hatch for raw evaluation. Actions: `lua`, `vimscript`, `terminal`.
## 1. Using Consolidated Domain Tools First
Always prefer the specific consolidated tools (like `nvim_buffer`, `nvim_window`, `nvim_visual`, etc.) over writing raw Lua scripts. These tools are strongly typed, tested, and safe.
Always prefer the specific consolidated tools (like `nvim_buffer`, `nvim_workspace`, `nvim_ui`, etc.) over writing raw Lua scripts. These tools are strongly typed, tested, and safe.
## 2. Lua God Mode (`nvim_execute_lua`)
If you need to access *any* Neovim API that does not have a dedicated tool (e.g., complex buffer edits, changing options, custom LSP interactions), you MUST use `nvim_execute_lua` as your escape hatch.
## 2. Lua God Mode (`nvim_exec` with action `lua`)
If you need to access *any* Neovim API that does not have a dedicated tool (e.g., changing options, setting autocmds), you MUST use `nvim_exec` with action `lua` as your escape hatch.
**CRITICAL**: `nvim_exec` is restricted to **READ-ONLY** queries. Do NOT use it to mutate editor state.
### CRITICAL RULES for `nvim_execute_lua`:
### CRITICAL RULES for `nvim_exec` (`lua`):
1. **Never Block:** Never use interactive prompt functions or interactive confirmation flags in substitutions (e.g., `%s/old/new/gc`). This will cause the headless MCP bridge to deadlock forever.
2. **Visual Feedback:** Always trigger a notification using `require("notify")("Antigravity: [Action]", "info", { title = "Antigravity" })`.
3. **Auto-Save:** If you modify a file buffer, always save it using `vim.cmd('write')` within the same Lua script so external tools can see the changes, unless you explicitly want to pause for manual human review.
@@ -57,4 +31,3 @@ While the headless background instance is great for autonomous, routine tasks, i
## 4. Tool Schema Discovery
Do **NOT** grep or search the Rust source code to find tool schemas or arguments. All lazy-loaded MCP tool schemas are automatically cached as JSON files on your disk. To understand a tool's arguments, directly read `~/.gemini/antigravity-cli/mcp/win-nvim/<tool_name>.json` (or linux-nvim).
+176 -204
View File
@@ -1083,208 +1083,125 @@ pub async fn run_mcp_loop(app_name: &str, app_version: &str) {
jsonrpc: "2.0".to_string(),
id,
result: Some(json!({
"tools": [
{
"name": "nvim_buffer",
"description": "Unified buffer management: inspect, open, read, search, save, reload, or close Neovim buffers.",
"inputSchema": {
"type": "object",
"properties": {
"action": {
"type": "string",
"enum": ["get_active", "read", "open", "create_scratch", "save", "reload", "close", "list", "search", "edit", "undo", "redo"],
"description": "Action to perform on the buffer"
},
"file": { "type": "string", "description": "Target file path (for open, read, search)" },
"buf_id": { "type": "integer", "description": "Buffer ID (for close, reload, or split)" },
"steps": { "type": "integer", "description": "Number of undo/redo steps to apply (default: 1)" },
"content": { "type": "string", "description": "Initial text content (for create_scratch)" },
"name": { "type": "string", "description": "Buffer display name (for create_scratch)" },
"filetype": { "type": "string", "description": "Filetype syntax (for open, create_scratch)" },
"start_line": { "type": "integer", "description": "1-indexed start line (for read)" },
"end_line": { "type": "integer", "description": "1-indexed end line (for read)" },
"pattern": { "type": "string", "description": "Regex or substring pattern to search for (for search)" },
"force": { "type": "boolean", "description": "Force reload or close (for reload, close)" },
"edits": {
"type": "array",
"description": "Array of edits to apply sequentially (for edit). Grouped by file, applied in descending order.",
"items": {
"type": "object",
"properties": {
"file": { "type": "string", "description": "Target file path" },
"start_line": { "type": "integer", "description": "1-indexed start line" },
"end_line": { "type": "integer", "description": "1-indexed end line" },
"replacement_content": { "type": "string", "description": "New content" },
"expected_content": { "type": "string", "description": "Optional: exact content expected in the replacement range to prevent line drift corruption" }
},
"required": ["file", "start_line", "end_line", "replacement_content"]
}
}
},
"required": ["action"]
}
},
{
"name": "nvim_window",
"description": "Manage Neovim windows and splits: list open windows, query or focus active window, create splits, or close windows.",
"inputSchema": {
"type": "object",
"properties": {
"action": {
"type": "string",
"enum": ["list", "get_active", "focus", "split", "close"],
"description": "Window operation to perform"
},
"win_id": { "type": "integer", "description": "Window ID to focus or close" },
"file": { "type": "string", "description": "File to open in split" },
"buf_id": { "type": "integer", "description": "Buffer ID to attach to split" },
"direction": { "type": "string", "enum": ["vertical", "horizontal"], "description": "Split orientation (default: vertical)" },
"force": { "type": "boolean", "description": "Force close window" }
},
"required": ["action"]
}
},
{
"name": "nvim_view",
"description": "Editor navigation and viewport introspection: jump to line, query cursor position, get visible viewport lines, or get visual selection.",
"inputSchema": {
"type": "object",
"properties": {
"action": {
"type": "string",
"enum": ["goto_line", "get_cursor", "get_viewport", "get_selection"],
"description": "Navigation/inspection action to perform"
},
"file": { "type": "string", "description": "File path (for goto_line)" },
"line": { "type": "integer", "description": "Target line number (1-indexed, for goto_line)" }
},
"required": ["action"]
}
},
{
"name": "nvim_diagnostics",
"description": "LSP diagnostics and quickfix integration: fetch current diagnostics, inject LSP diagnostic markers, or populate the quickfix list.",
"inputSchema": {
"type": "object",
"properties": {
"action": {
"type": "string",
"enum": ["get", "set", "set_quickfix"],
"description": "Diagnostic action to perform"
},
"line": { "type": "integer", "description": "Line number (1-indexed, for set)" },
"message": { "type": "string", "description": "Diagnostic warning/error message (for set)" },
"items": {
"type": "array",
"description": "Quickfix entries (for set_quickfix)",
"items": {
"type": "object",
"properties": {
"filename": { "type": "string" },
"lnum": { "type": "integer" },
"text": { "type": "string" }
},
"required": ["filename", "lnum", "text"]
}
},
"qf_action": { "type": "string", "enum": ["replace", "append", "prepend"], "description": "Quickfix list modification action (for set_quickfix)" }
},
"required": ["action"]
}
},
{
"name": "nvim_visual",
"description": "Visual feedback, syntax highlighting, ghost text extmarks, and diff preview overlays.",
"inputSchema": {
"type": "object",
"properties": {
"action": {
"type": "string",
"enum": ["preview", "extmark", "highlight", "clear_highlight"],
"description": "Visual feedback action"
},
"file_path": { "type": "string", "description": "File path (for preview)" },
"start_line": { "type": "integer", "description": "Start line (1-indexed, for preview, highlight)" },
"end_line": { "type": "integer", "description": "End line (1-indexed, for preview, highlight)" },
"preview_content": { "type": "string", "description": "Proposed replacement code (for preview)" },
"line": { "type": "integer", "description": "Line number (1-indexed, for extmark)" },
"text": { "type": "string", "description": "Virtual ghost text to display (for extmark)" },
"highlight_group": { "type": "string", "description": "Highlight group (for extmark, highlight, e.g. 'Comment', 'IncSearch')" },
"buf_id": { "type": "integer", "description": "Buffer ID (for highlight, clear_highlight)" },
"duration_ms": { "type": "integer", "description": "Auto-clear duration in ms (for highlight, default: 5000)" }
},
"required": ["action"]
}
},
{
"name": "nvim_execute_lua",
"description": "Execute arbitrary Lua code directly in the active Neovim session. Primary tool for editing files via vim.api.nvim_buf_set_lines, querying editor state, and triggering notifications.",
"inputSchema": {
"type": "object",
"properties": {
"code": {
"type": "string",
"description": "The Lua code string to execute in Neovim"
}
},
"required": ["code"]
}
},
{
"name": "nvim_system",
"description": "System diagnostics, terminal interaction, and editor notification messages.",
"inputSchema": {
"type": "object",
"properties": {
"action": {
"type": "string",
"enum": ["get_info", "get_messages", "send_to_terminal"],
"description": "System action to perform"
},
"command": { "type": "string", "description": "Shell command to send (for send_to_terminal)" },
"tail": { "type": "integer", "description": "Number of message lines to return (for get_messages)" }
},
"required": ["action"]
}
},
{
"name": "nvim_lsp",
"description": "Language Server Protocol integration for semantic queries and safe workspace-wide refactoring.",
"inputSchema": {
"type": "object",
"properties": {
"action": {
"type": "string",
"enum": ["rename", "definition", "references", "hover", "code_action"],
"description": "LSP action to perform"
},
"file": { "type": "string", "description": "Target file path" },
"line": { "type": "integer", "description": "1-indexed line number" },
"col": { "type": "integer", "description": "0-indexed column number" },
"new_name": { "type": "string", "description": "New name for rename action" }
},
"required": ["action"]
}
},
{
"name": "nvim_ast",
"description": "Tree-sitter AST queries for semantic code exploration and outlining.",
"inputSchema": {
"type": "object",
"properties": {
"action": {
"type": "string",
"enum": ["query", "outline"],
"description": "AST action to perform"
},
"file": { "type": "string", "description": "Target file path" },
"query": { "type": "string", "description": "Tree-sitter query string" },
"preset": { "type": "string", "description": "Query preset (e.g., 'functions', 'classes')" }
},
"required": ["action"]
}
}
]
"tools":
[
{
"name": "nvim_buffer",
"description": "Core Text Editing: read, replace, save, and manipulate Neovim buffers in memory.",
"inputSchema": {
"type": "object",
"properties": {
"action": {
"type": "string",
"enum": ["read", "replace", "save", "undo", "redo", "create_scratch"],
"description": "Action to perform on the buffer"
},
"file": { "type": "string", "description": "Target file path (for read, replace, save)" },
"start_line": { "type": "integer", "description": "1-indexed start line (for read)" },
"end_line": { "type": "integer", "description": "1-indexed end line (for read)" },
"content": { "type": "string", "description": "Initial text content (for create_scratch)" },
"name": { "type": "string", "description": "Buffer display name (for create_scratch)" },
"steps": { "type": "integer", "description": "Number of undo/redo steps to apply (default: 1)" },
"edits": {
"type": "array",
"description": "Array of edits to apply sequentially (for replace). Grouped by file, applied in descending order.",
"items": {
"type": "object",
"properties": {
"file": { "type": "string" },
"start_line": { "type": "integer" },
"end_line": { "type": "integer" },
"replacement_content": { "type": "string" },
"expected_content": { "type": "string" }
},
"required": ["file", "start_line", "end_line", "replacement_content"]
}
}
},
"required": ["action"]
}
},
{
"name": "nvim_workspace",
"description": "Window & Editor State: list buffers, windows, focus splits, and manage cwd.",
"inputSchema": {
"type": "object",
"properties": {
"action": {
"type": "string",
"enum": ["list_buffers", "list_windows", "focus", "split", "cwd"],
"description": "Workspace operation to perform"
},
"win_id": { "type": "integer", "description": "Window ID to focus" },
"file": { "type": "string", "description": "File to open in split" },
"direction": { "type": "string", "enum": ["vertical", "horizontal"], "description": "Split orientation (default: vertical)" },
"path": { "type": "string", "description": "Target directory (for cwd action)" }
},
"required": ["action"]
}
},
{
"name": "nvim_intelligence",
"description": "Code Semantics: LSP queries (hover, definition, references, code_action, rename, diagnostics) and AST outlining/queries.",
"inputSchema": {
"type": "object",
"properties": {
"action": {
"type": "string",
"enum": ["hover", "definition", "references", "outline", "query", "diagnostics", "rename", "code_action"],
"description": "Intelligence action to perform"
},
"file": { "type": "string", "description": "Target file path" },
"line": { "type": "integer", "description": "1-indexed line number (for LSP)" },
"col": { "type": "integer", "description": "0-indexed column number (for LSP)" },
"new_name": { "type": "string", "description": "New name (for rename action)" },
"query": { "type": "string", "description": "Tree-sitter query string (for AST query)" },
"preset": { "type": "string", "description": "Query preset (e.g., 'functions', 'classes' for AST query)" }
},
"required": ["action"]
}
},
{
"name": "nvim_ui",
"description": "Visual Feedback: communicating visually with the human user via highlights and ghost text.",
"inputSchema": {
"type": "object",
"properties": {
"action": {
"type": "string",
"enum": ["highlight", "ghost_text", "clear"],
"description": "UI action"
},
"buf_id": { "type": "integer", "description": "Buffer ID to apply to" },
"start_line": { "type": "integer", "description": "1-indexed start line (for highlight)" },
"end_line": { "type": "integer", "description": "1-indexed end line (for highlight)" },
"line": { "type": "integer", "description": "1-indexed line number (for ghost_text)" },
"text": { "type": "string", "description": "Virtual text to display (for ghost_text)" },
"highlight_group": { "type": "string", "description": "Highlight group (e.g. 'Comment', 'IncSearch')" },
"duration_ms": { "type": "integer", "description": "Auto-clear duration in ms (for highlight, default: 5000)" }
},
"required": ["action"]
}
},
{
"name": "nvim_exec",
"description": "The Escape Hatch: execute lua read-only queries, run vimscript commands, or send commands to the terminal.",
"inputSchema": {
"type": "object",
"properties": {
"action": {
"type": "string",
"enum": ["lua", "vimscript", "terminal"],
"description": "Execution action"
},
"code": { "type": "string", "description": "Lua code or Vimscript command to execute" },
"command": { "type": "string", "description": "Shell command to send (for terminal)" }
},
"required": ["action"]
}
}
]
})),
error: None,
}).await;
@@ -1297,8 +1214,42 @@ pub async fn run_mcp_loop(app_name: &str, app_version: &str) {
let action = args.get("action").and_then(|v| v.as_str()).unwrap_or("");
match name {
"nvim_buffer" => match action {
let (mapped_name, mapped_action) = match (name, action) {
("nvim_buffer", "read") => ("nvim_buffer", "read"),
("nvim_buffer", "replace") => ("nvim_buffer", "edit"),
("nvim_buffer", "save") => ("nvim_buffer", "save"),
("nvim_buffer", "undo") => ("nvim_buffer", "undo"),
("nvim_buffer", "redo") => ("nvim_buffer", "redo"),
("nvim_buffer", "create_scratch") => ("nvim_buffer", "create_scratch"),
("nvim_workspace", "list_buffers") => ("nvim_buffer", "list"),
("nvim_workspace", "list_windows") => ("nvim_window", "list"),
("nvim_workspace", "focus") => ("nvim_window", "focus"),
("nvim_workspace", "split") => ("nvim_window", "split"),
("nvim_workspace", "cwd") => ("nvim_system", "cwd"),
("nvim_intelligence", "hover") => ("nvim_lsp", "hover"),
("nvim_intelligence", "definition") => ("nvim_lsp", "definition"),
("nvim_intelligence", "references") => ("nvim_lsp", "references"),
("nvim_intelligence", "rename") => ("nvim_lsp", "rename"),
("nvim_intelligence", "code_action") => ("nvim_lsp", "code_action"),
("nvim_intelligence", "outline") => ("nvim_ast", "outline"),
("nvim_intelligence", "query") => ("nvim_ast", "query"),
("nvim_intelligence", "diagnostics") => ("nvim_diagnostics", "get"),
("nvim_ui", "highlight") => ("nvim_visual", "highlight"),
("nvim_ui", "ghost_text") => ("nvim_visual", "extmark"),
("nvim_ui", "clear") => ("nvim_visual", "clear_highlight"),
("nvim_exec", "lua") => ("nvim_execute_lua", ""),
("nvim_exec", "vimscript") => ("nvim_system", "vimscript"),
("nvim_exec", "terminal") => ("nvim_system", "send_to_terminal"),
(n, a) => (n, a),
};
match mapped_name {
"nvim_buffer" => match mapped_action {
"get_active" => match get_nvim_active_buffer().await {
Ok(content) => {
send_text_result!(id.clone(), content);
@@ -2147,6 +2098,27 @@ pub async fn run_mcp_loop(app_name: &str, app_version: &str) {
send_error(id, -32602, "Missing 'command'").await;
}
}
"cwd" => {
let lua_code =
if let Some(path) = args.get("path").and_then(|v| v.as_str()) {
format!(
"vim.cmd('cd {}'); return vim.fn.getcwd()",
path.replace("\\", "\\\\").replace("'", "\\'")
)
} else {
"return vim.fn.getcwd()".to_string()
};
handle_lua_result!(id, execute_nvim_lua(&lua_code));
}
"vimscript" => {
if let Some(code) = args.get("code").and_then(|v| v.as_str()) {
let lua_code =
format!("vim.cmd([=[{}]=]); return 'Success'", code);
handle_lua_result!(id, execute_nvim_lua(&lua_code));
} else {
send_error(id, -32602, "Missing 'code'").await;
}
}
_ => {
send_error(
id,
-1
View File
@@ -1 +0,0 @@
{"code": "local buf = vim.fn.bufnr('server/src/search.rs')\nif buf == -1 then\n vim.cmd('e server/src/search.rs')\n buf = vim.api.nvim_get_current_buf()\nend\n\nvim.api.nvim_buf_set_lines(buf, 216, 222, false, {\n ' &self,',\n ' entities: &[Entity],',\n ' tasks: &[Task],',\n ' snippets: &[Snippet],',\n ' adrs: &[Adr],'\n})\n\n-- We need to change the loop variables inside the task from values to clones if they are passed as slices\n-- Actually we can just clone the slice data before moving it into spawn_blocking\nvim.api.nvim_buf_set_lines(buf, 222, 223, false, {\n ' ) -> tokio::task::JoinHandle<tantivy::Result<()>> {',\n ' let entities = entities.to_vec();',\n ' let tasks = tasks.to_vec();',\n ' let snippets = snippets.to_vec();',\n ' let adrs = adrs.to_vec();'\n})\n\nvim.cmd('write')\nrequire('notify')('Updated search index_batch signature', 'info', { title = 'Antigravity' })\nreturn 'ok'\n"}
-74
View File
@@ -1,74 +0,0 @@
rebuild_index: found 228 entities, 24 tasks
spawn_blocking started in rebuild_index
add_task_sync called for task: 8da665f7-107c-41c8-b203-d39a9ff1f9a5
Writer add_document returned id/result
Needs_commit set to true in add_task_sync
add_task_sync called for task: 01a788f0-7adb-456c-bf37-02bbd7e1d2f8
Writer add_document returned id/result
Needs_commit set to true in add_task_sync
add_task_sync called for task: 5e8d9b26-ae31-4136-a4c4-6ead74887bb5
Writer add_document returned id/result
Needs_commit set to true in add_task_sync
add_task_sync called for task: ed184dd6-55ce-4d37-a06a-b34733795e03
Writer add_document returned id/result
Needs_commit set to true in add_task_sync
add_task_sync called for task: 3cea859d-c1ce-4f6c-bdc5-6eb65dbd8e4f
Writer add_document returned id/result
Needs_commit set to true in add_task_sync
add_task_sync called for task: 62446699-39b3-496b-9af8-99b331fe6c08
Writer add_document returned id/result
Needs_commit set to true in add_task_sync
add_task_sync called for task: 4b0e2179-1e70-4b64-9c2d-ff2fe2d05fdf
Writer add_document returned id/result
Needs_commit set to true in add_task_sync
add_task_sync called for task: 16dd35e4-eadd-4597-a5b6-9844852cfb76
Writer add_document returned id/result
Needs_commit set to true in add_task_sync
add_task_sync called for task: c85f352b-f15b-4f90-a6ae-18fe914212b2
Writer add_document returned id/result
Needs_commit set to true in add_task_sync
add_task_sync called for task: d1e907a2-89a2-4814-8722-22c754cc943c
Writer add_document returned id/result
Needs_commit set to true in add_task_sync
add_task_sync called for task: c382a511-a5d6-4114-ad2c-f09fdd36d66a
Writer add_document returned id/result
Needs_commit set to true in add_task_sync
add_task_sync called for task: 42ca3765-5c69-4cdd-8324-5a174c34d4ae
Writer add_document returned id/result
Needs_commit set to true in add_task_sync
add_task_sync called for task: 05792eaa-4bc5-45e5-b9a0-d9027b3b3974
Writer add_document returned id/result
Needs_commit set to true in add_task_sync
add_task_sync called for task: 15c9fd58-8d8f-4c2f-80f4-15a46ba54588
Writer add_document returned id/result
Needs_commit set to true in add_task_sync
add_task_sync called for task: 9b55e54c-ac1b-4219-acf3-68f7cb34a1fd
Writer add_document returned id/result
Needs_commit set to true in add_task_sync
add_task_sync called for task: a04923ea-6abf-41ba-9c45-f7d9cdac3440
Writer add_document returned id/result
Needs_commit set to true in add_task_sync
add_task_sync called for task: 4233293e-6d93-4c46-b9aa-f9e712af0e86
Writer add_document returned id/result
Needs_commit set to true in add_task_sync
add_task_sync called for task: 93451cd9-25c5-4323-8dce-79bba124242d
Writer add_document returned id/result
Needs_commit set to true in add_task_sync
add_task_sync called for task: 949f1d59-e1e2-421c-9682-43a79f41679b
Writer add_document returned id/result
Needs_commit set to true in add_task_sync
add_task_sync called for task: cd680df7-2e1a-4486-bb9b-3881476c762e
Writer add_document returned id/result
Needs_commit set to true in add_task_sync
add_task_sync called for task: 561daa2b-ddb5-44ae-8fb8-8155405759fb
Writer add_document returned id/result
Needs_commit set to true in add_task_sync
add_task_sync called for task: e36b0eba-aa79-493f-b89b-3da46a44fa11
Writer add_document returned id/result
Needs_commit set to true in add_task_sync
add_task_sync called for task: a3a717b3-438a-42a7-83ec-2f2eb5d775b4
Writer add_document returned id/result
Needs_commit set to true in add_task_sync
add_task_sync called for task: 6a1b05d5-0ffd-4b0c-bb65-f45e0cb5540a
Writer add_document returned id/result
Needs_commit set to true in add_task_sync
-293
View File
@@ -1,293 +0,0 @@
if let Some(idx) = gates.iter().position(|g| {
g.action == q.action
&& g.target == q.target
&& g.namespace == q.namespace
&& g.params == q.params
}) {
found = Some(gates[idx].clone());
if q.consume {
to_remove = Some(idx);
}
}
if let Some(idx) = to_remove {
gates.remove(idx);
}
});
match found {
Some(record) => {
if record.status == "authorized" {
(axum::http::StatusCode::OK, "Authorized").into_response()
} else {
let msg = if let Some(r) = record.reason {
format!("Action blocked. Reason: {}", r)
} else {
"Action blocked.".to_string()
};
(axum::http::StatusCode::FORBIDDEN, msg).into_response()
}
}
None => (
axum::http::StatusCode::NOT_FOUND,
"Action not yet authorized (no gate record found).",
)
.into_response(),
}
}
async fn gate_set_handler(
State(app_state): State<Arc<AppState>>,
Json(body): Json<GateSetReq>,
) -> axum::response::Response {
let status = if body.block.unwrap_or(false) {
"blocked".to_string()
} else if body.authorize.unwrap_or(false) {
"authorized".to_string()
} else {
"pending".to_string()
};
let record = GateRecord {
id: uuid::Uuid::new_v4().to_string(),
action: body.action.clone(),
target: body.target.clone(),
namespace: body.namespace.clone(),
params: body.params.clone(),
status,
reason: body.reason.clone(),
timestamp: crate::handlers::utils::now_secs(),
};
app_state.handler.state.gates.modify(|gates| {
gates.retain(|g| !(g.action == record.action && g.target == record.target));
gates.push(record);
});
(axum::http::StatusCode::OK, "Gate state updated.").into_response()
}
async fn run_server(state: Arc<MemoryState>) -> Result<(), Box<dyn std::error::Error>> {
state.rebuild_index().await;
tokio::spawn(index_committer_worker(Arc::clone(&state)));
let app_state = Arc::new(AppState {
handler: Arc::new(MemoryHandler::new(Arc::clone(&state))),
clients: RwLock::new(HashMap::new()),
next_id: AtomicUsize::new(1),
});
let app_state_clone = Arc::clone(&app_state);
let mut rx = state.activity_tx.subscribe();
tokio::spawn(async move {
while let Ok(msg) = rx.recv().await {
let senders: Vec<_> = app_state_clone
.clients
.read()
.unwrap_or_else(|e| e.into_inner())
.values()
.cloned()
.collect();
for client_tx in senders {
let _ = client_tx.try_send(msg.clone());
}
}
});
let app = Router::new()
.route(
"/api/version",
get(|| async move {
axum::Json(serde_json::json!({
"version": env!("APP_VERSION"),
"git_hash": option_env!("GIT_HASH").unwrap_or("unknown")
}))
}),
)
.route("/ws", get(ws_handler))
.route("/health", get(health_handler))
.route("/nvim/telemetry", post(nvim_telemetry_handler))
.route("/gate/verify", get(gate_verify_handler))
.route("/gate/set", post(gate_set_handler))
.route(
"/shutdown",
post(
|headers: axum::http::HeaderMap, State(state): State<Arc<AppState>>| async move {
let token_path = state.handler.state.base_dir.join("admin.token");
let expected_token = tokio::fs::read_to_string(&token_path)
.await
.unwrap_or_default()
.trim()
.to_string();
let auth_header = headers
.get(axum::http::header::AUTHORIZATION)
.and_then(|h| h.to_str().ok())
.unwrap_or_default();
if expected_token.is_empty() || auth_header != format!("Bearer {}", expected_token) {
return (axum::http::StatusCode::UNAUTHORIZED, "Unauthorized").into_response();
}
std::thread::spawn(|| {
tracing::info!(
"Received shutdown request via /shutdown endpoint. Exiting process cleanly."
);
std::thread::sleep(std::time::Duration::from_millis(100));
std::process::exit(0);
});
(axum::http::StatusCode::OK, "Shutting down...").into_response()
},
),
)
.route(
"/",
get(|| async move { axum::response::Html(include_str!("dashboard.html")) }),
)
.route(
"/api/graph",
get({
let state_clone = app_state.handler.state.clone();
move || async move {
let graph_json = state_clone.read_graph(|g| serde_json::to_string(g).unwrap_or_else(|_| "{}".to_string()));
([(axum::http::header::CONTENT_TYPE, "application/json")], graph_json)
}
}),
)
.route(
"/api/tasks/{id}/complete",
post({
let state_clone = app_state.handler.state.clone();
move |axum::extract::Path(id): axum::extract::Path<String>| async move {
state_clone.tasks.modify(|tasks| {
for t in tasks.iter_mut() {
if t.id == id {
t.status = "completed".to_string();
break;
}
}
});
axum::Json(serde_json::json!({"status": "success"}))
}
}),
)
.route(
"/api/tasks",
get({
let state_clone = app_state.handler.state.clone();
move || async move {
let tasks_json = state_clone.tasks.read_with(|t| serde_json::to_string(t).unwrap_or_else(|_| "[]".to_string()));
([(axum::http::header::CONTENT_TYPE, "application/json")], tasks_json)
}
}),
)
.route(
"/api/sticky",
get({
let state_clone = app_state.handler.state.clone();
move || async move {
let sticky_json = state_clone.sticky.read_with(|s| serde_json::to_string(s).unwrap_or_else(|_| "[]".to_string()));
([(axum::http::header::CONTENT_TYPE, "application/json")], sticky_json)
}
}),
)
.route(
"/api/search",
get({
let state_clone = app_state.handler.state.clone();
move |axum::extract::Query(params): axum::extract::Query<
std::collections::HashMap<String, String>,
>| async move {
if let Some(q) = params.get("q")
&& let Ok(idx) = state_clone.search_index.read()
&& let Ok(results) = idx.search(q, None) {
let mut formatted_results = Vec::new();
for (id, doc_type, title, body, score) in results {
formatted_results.push(serde_json::json!({
"id": id,
"type_name": doc_type,
"title": title,
"content": body,
"score": score
}));
}
return axum::Json(
serde_json::json!({ "results": formatted_results }),
);
}
axum::Json(serde_json::json!({ "results": [] }))
}
}),
)
.route(
"/api/activity",
get({
let state_clone = app_state.handler.state.clone();
move || async move {
let activities_json = state_clone.recent_activities.read_with(|a| serde_json::to_string(a).unwrap_or_else(|_| "[]".to_string()));
([(axum::http::header::CONTENT_TYPE, "application/json")], activities_json)
}
}),
)
.route(
"/api/stats",
get({
let state_clone = app_state.handler.state.clone();
move || async move {
let (entities, relations) = state_clone.read_graph(|g| (g.entities.len(), g.relations.len()));
let tasks = state_clone.tasks.read_with(|items| items.len());
let snippets = state_clone.snippets.read_with(|items| items.len());
let tech_debts = state_clone.tech_debts.read_with(|items| items.len());
let adrs = state_clone.adrs.read_with(|items| items.len());
let ledger = state_clone.ledger.read_with(|items| items.len());
let error_fixes = state_clone.error_fixes.read_with(|items| items.len());
let session_summaries = state_clone.session_summaries.read_with(|items| items.len());
let handoff_memos = state_clone.handoff_memos.read_with(|items| items.len());
let env_fingerprints = state_clone.env_fingerprints.read_with(|items| items.len());
let env_requirements = state_clone.env_requirements.read_with(|items| items.len());
let milestones = state_clone.milestones.read_with(|items| items.len());
let environments = state_clone.environments.read_with(|items| items.len());
let gates = state_clone.gates.read_with(|items| items.len());
axum::Json(serde_json::json!({
"entities": entities,
"relations": relations,
"tasks": tasks,
"snippets": snippets,
"tech_debts": tech_debts,
"adrs": adrs,
"ledger": ledger,
"error_fixes": error_fixes,
"session_summaries": session_summaries,
"handoff_memos": handoff_memos,
"env_fingerprints": env_fingerprints,
"env_requirements": env_requirements,
"milestones": milestones,
"environments": environments,
"gates": gates
}))
}
}),
)
.with_state(app_state);
tracing::info!("MCP Memory Server running on http://127.0.0.1:3000/sse");
let addr = std::env::var("MCP_PORT").unwrap_or_else(|_| "3000".to_string());
let addr: std::net::SocketAddr = format!("127.0.0.1:{}", addr)
.parse()
.expect("Invalid bind address");
let listener = match tokio::net::TcpListener::bind(&addr).await {
Ok(l) => l,
Err(e) => {
let log_path = dirs::home_dir()
.unwrap_or_default()
.join(".gemini/mcp_memory/daemon_error.log");
let _ =
tokio::fs::write(&log_path, format!("Failed to bind to {}: {}\n", addr, e)).await;
return Ok(());
}
};
if let Err(e) = axum::serve(listener, app.into_make_service()).await {
let log_path = dirs::home_dir()
.unwrap_or_default()
.join(".gemini/mcp_memory/daemon_error.log");
let _ = tokio::fs::write(&log_path, format!("Server crashed: {}\n", e)).await;
}
+7 -60
View File
@@ -117,75 +117,22 @@ pub fn init_redb(base: &Path) -> Arc<Database> {
}
};
// Ensure the table exists and migrate legacy JSON files
// Ensure the table exists
match db.begin_write() {
Ok(write_txn) => {
let mut opened_ok = false;
if let Ok(mut table) = write_txn.open_table(STORE_TABLE) {
if let Ok(_) = write_txn.open_table(STORE_TABLE) {
opened_ok = true;
if !is_in_memory {
let stores = vec![
("knowledge_graph_master", "knowledge_graph_master.json"),
("audit_ledger", "audit_ledger.json"),
("tasks", "tasks.json"),
("snippets", "snippets.json"),
("adrs", "adrs.json"),
("error_fixes", "error_fixes.json"),
("session_summaries", "session_summaries.json"),
("handoff_memos", "handoff_memos.json"),
("env_fingerprints", "env_fingerprints.json"),
("env_requirements", "env_requirements.json"),
("milestones", "milestones.json"),
("environments", "environments.json"),
("tech_debts", "tech_debts.json"),
("gates", "gates.json"),
("state_snapshots", "state_snapshots.json"),
("hypotheses", "hypotheses.json"),
("agent_signals", "agent_signals.json"),
];
for (key, file_name) in stores.iter() {
let is_missing = match table.get(*key) {
Ok(res) => res.is_none(),
Err(e) => {
tracing::warn!("Failed to read key '{}' from redb: {}", key, e);
false
}
};
if is_missing {
let json_path = base.join(file_name);
if json_path.exists()
&& let Ok(data) = std::fs::read(&json_path)
&& serde_json::from_slice::<serde_json::Value>(&data).is_ok()
{
if let Err(e) = table.insert(*key, data.as_slice()) {
tracing::error!(
"Failed to insert migrated key '{}': {}",
key,
e
);
} else {
let migrated_path = json_path.with_extension("json.migrated");
if std::fs::rename(&json_path, &migrated_path).is_err()
&& migrated_path.exists()
{
let _ = std::fs::remove_file(&migrated_path);
let _ = std::fs::rename(&json_path, &migrated_path);
}
}
}
}
}
}
}
if opened_ok && let Err(e) = write_txn.commit() {
tracing::error!("Failed to commit database migration transaction: {}", e);
if opened_ok {
if let Err(e) = write_txn.commit() {
tracing::error!("Failed to commit database initialization transaction: {}", e);
}
}
}
Err(e) => {
tracing::error!(
"Failed to begin write transaction for redb migration: {}",
"Failed to begin write transaction for redb initialization: {}",
e
);
}
+3 -3
View File
@@ -977,8 +977,8 @@ impl McpTool for GetSubgraphHandler {
async fn execute(&self, args: Value, state: Arc<MemoryState>) -> crate::error::Result<String> {
let req: GetSubgraphTool = serde_json::from_value(args).map_err(|e| e.to_string())?;
let root = req.root_entity.or(req.root_node).ok_or_else(|| {
crate::error::AppError::Internal("root_entity or root_node is required".to_string())
let root = req.root_entity.ok_or_else(|| {
crate::error::AppError::Internal("root_entity is required".to_string())
})?;
let depth = req.depth.unwrap_or(2);
let format = req.format.unwrap_or(SubgraphFormat::Json);
@@ -1043,7 +1043,7 @@ impl McpTool for GetSubgraphHandler {
}
let result = serde_json::json!({
"root_node": root,
"root_entity": root,
"depth": depth,
"entities": matched_entities,
"relations": matched_relations,
-93
View File
@@ -843,69 +843,7 @@ impl McpTool for ClipboardHandler {
})
.to_string())
}
ClipboardAction::Read => {
let engine = ensure_ocr_engine().await;
let out = tokio::task::spawn_blocking(
move || -> crate::error::Result<serde_json::Map<String, Value>> {
let mut out = serde_json::Map::new();
if let Some(text) = get_native_clipboard_text() {
out.insert("text".into(), json!(text));
}
if let Some(dynamic_img) = get_native_clipboard_image() {
let mut img = dynamic_img.clone();
let max_dim = 1440;
if img.width() > max_dim || img.height() > max_dim {
img = img.resize(max_dim, max_dim, FilterType::Lanczos3);
}
let rgb_img = img.into_rgb8();
let mut jpeg_bytes = std::io::Cursor::new(Vec::new());
let mut encoder = image::codecs::jpeg::JpegEncoder::new_with_quality(
&mut jpeg_bytes,
88,
);
if encoder
.encode(
&rgb_img,
rgb_img.width(),
rgb_img.height(),
image::ExtendedColorType::Rgb8,
)
.is_ok()
{
let bytes = jpeg_bytes.into_inner();
let cache_dir = dirs::home_dir()
.unwrap_or_default()
.join(".gemini/mcp_memory/clipboard");
let _ = std::fs::create_dir_all(&cache_dir);
let file_path = cache_dir.join("clipboard_latest_image.jpg");
if std::fs::write(&file_path, &bytes).is_ok() {
let path_str = file_path.to_string_lossy().to_string();
out.insert("image_path".into(), json!(path_str));
let wsl_path = to_wsl_path(&path_str);
out.insert("image_path_wsl".into(), json!(wsl_path));
}
}
if let Some(eng) = engine
&& let Some(ocr_text) = perform_ocrs_ocr(eng, &dynamic_img)
{
out.insert("image_analysis".to_string(), json!(ocr_text.trim()));
}
}
Ok(out)
},
)
.await
.map_err(|e| crate::error::AppError::Internal(format!("Task panic: {}", e)))??;
state.record_activity("clipboard", "Read contents from OS clipboard", None);
Ok::<String, crate::error::AppError>(serde_yaml::to_string(&Value::Object(out))?)
}
ClipboardAction::Write => {
let text_opt = req.text;
let image_path_opt = req.image_path;
@@ -1023,38 +961,7 @@ mod tests {
);
}
#[tokio::test]
async fn test_read_clipboard() {
let dir = tempdir().unwrap();
let state = Arc::new(MemoryState::new(dir.path().to_str().unwrap()));
let handler = ClipboardHandler;
let result = handler
.execute(json!({"action": "read"}), state)
.await
.map_err(|e| format!("Failed to read clipboard: {}", e))
.unwrap();
// Returns a JSON string, possibly {}
let parsed: serde_json::Value = serde_yaml::from_str(&result).unwrap();
assert!(parsed.is_object());
}
#[tokio::test]
async fn test_read_clipboard_empty() {
let dir = tempfile::tempdir().unwrap();
let state = Arc::new(MemoryState::new(dir.path().to_str().unwrap()));
let handler = ClipboardHandler;
let result = handler
.execute(serde_json::json!({"action": "read"}), state)
.await
.map_err(|e| format!("Failed to read clipboard: {}", e))
.unwrap();
let parsed: serde_json::Value = serde_yaml::from_str(&result).unwrap();
assert!(parsed.is_object());
}
#[test]
fn test_no_subprocess_clipboard_regression() {
+1 -1
View File
@@ -59,7 +59,7 @@ The server registers 5 high-signal workflow prompts to initiate standardized age
## 5. Consolidated Smart Tools Architecture (11 Primary Tools)
The server consolidates granular single-purpose tools into domain-named smart tools. Always prefer the consolidated tools over legacy aliases:
The server consolidates granular single-purpose tools into domain-named smart tools.
* **`tasks`**: Complete task lifecycle management.
- `action: "add"`: Create a new task (requires `title`, optional `description`, `git_branch`, `repo_name`, `priority: "low" | "medium" | "high" | "urgent"`, `assigned_agent`, `verification_command`, `parent_id`, `dependencies`).
+1 -1
View File
@@ -1428,7 +1428,7 @@ mod tests {
("decisions", json!({"action": "query"})),
("tech_debt", json!({"action": "list"})),
("snippets", json!({"action": "search", "query": "test"})),
("clipboard", json!({"action": "read"})),
("clipboard", json!({"action": "history"})),
("environment", json!({"action": "read_fingerprint"})),
("omni_search", json!({"query": "test"})),
("get_project_health", json!({})),
-5
View File
@@ -172,8 +172,6 @@ pub enum SubgraphFormat {
pub struct GetSubgraphTool {
/// The root entity name to start the subgraph search from.
pub root_entity: Option<String>,
/// Legacy alias for root_entity.
pub root_node: Option<String>,
/// Maximum search depth (hops). Defaults to 2.
pub depth: Option<u32>,
/// Output format: 'json' (raw entities and relations) or 'markdown_tree' (compact topology tree). Defaults to 'json'.
@@ -1014,8 +1012,6 @@ pub enum ClipboardAction {
History,
#[serde(alias = "clear", alias = "CLEAR", alias = "Clear")]
Clear,
#[serde(alias = "read", alias = "READ", alias = "Read")]
Read,
#[serde(alias = "write", alias = "WRITE", alias = "Write")]
Write,
}
@@ -1026,7 +1022,6 @@ pub enum ClipboardAction {
/// - 'text': Get latest clipboard text (or normalized Markdown if HTML was copied).
/// - 'history': View recent clipboard history ring buffer (images and text with timestamps).
/// - 'clear': Clear OS clipboard and memory cache.
/// - 'read': Read current clipboard contents (legacy alias).
/// - 'write': Write content to OS clipboard. Optional: text, html, files, image_path.
///
/// Triggers: Call 'image' immediately when user says "look at image in clipboard", "see screenshot",
-1
View File
@@ -1 +0,0 @@
test
-1
View File
@@ -1 +0,0 @@
test