Compare commits

..
13 Commits
Author SHA1 Message Date
Riz Ashraf c326166311 chore(cleanup): remove legacy aliases and cruft from codebase, docs, and tests 2026-10-09 08:29:05 +01:00
Riz Ashraf 5311167898 chore: remove legacy documentation, unused test scripts, and obsolete agent rules 2026-10-09 07:38:10 +01:00
Riz Ashraf 7fed3a2e77 docs(nvim-core): prune obsolete tool names from configuration and docs 2026-10-09 06:16:29 +01:00
Riz Ashraf bce9b82b66 feat(nvim-core): consolidate nvim tools into 5 mega-tools 2026-10-09 06:08:08 +01:00
Riz Ashraf 03f8786d24 chore: resolve clippy warnings for pre-push audit 2026-10-09 01:06:30 +01:00
Riz Ashraf bd20482cea fix(embedding): resolve large_enum_variant clippy error 2026-10-09 00:56:47 +01:00
Riz Ashraf 1ed75ca156 feat(nvim): add nvim_lsp, nvim_ast, buffer undo/redo 2026-10-09 00:51:05 +01:00
Riz Ashraf 3765e6b05d chore: fix clippy warnings and run rustfmt 2026-10-09 00:39:50 +01:00
Riz Ashraf fecd8bf33f fix(tests): replace serde_json::from_str with serde_yaml::from_str for tool output assertions 2026-10-09 00:30:05 +01:00
Riz Ashraf b4431a4dcd feat(nvim): update nvim_buffer edit to handle multiple block edits 2026-10-09 00:18:01 +01:00
Riz Ashraf d6acd885dd fix(nvim): eliminate \r corruption in buffer mutations
- Pre-process and strip carriage returns natively in Rust before RPC serialization.

- Pass replacement strings to Neovim as native MsgPack arrays to bypass Lua vim.split overhead.

- Directly feed table arrays into vim.api.nvim_buf_set_lines for exact buffer matches.
2026-10-08 23:58:49 +01:00
Riz Ashraf cb0c55775a feat(mcp): switch to YAML serialization for tool outputs
- Replaced serde_json with serde_yaml in all handler endpoints.

- This drastically reduces token consumption for large list/graph responses by removing JSON braces and quotes.
2026-10-08 23:46:32 +01:00
Riz Ashraf 410b0c42ca feat(ollama): enforce JSON logits & add nvim_buffer edit action
- Added format parameter to Ollama generate for JSON logit enforcement.

- Implemented safe edit action in nvim_buffer MCP tool to replace raw Lua.
2026-10-08 23:41:57 +01:00
60 changed files with 1073 additions and 1861 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.
Generated
+20
View File
@@ -2654,6 +2654,7 @@ dependencies = [
"schemars", "schemars",
"serde", "serde",
"serde_json", "serde_json",
"serde_yaml",
"tantivy", "tantivy",
"tempfile", "tempfile",
"thiserror 2.0.20", "thiserror 2.0.20",
@@ -4342,6 +4343,19 @@ dependencies = [
"serde", "serde",
] ]
[[package]]
name = "serde_yaml"
version = "0.9.34+deprecated"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6a8b1a1a2ebf674015cc02edccce75287f1a0130d394307b36743c2f5d504b47"
dependencies = [
"indexmap",
"itoa",
"ryu",
"serde",
"unsafe-libyaml",
]
[[package]] [[package]]
name = "sha1" name = "sha1"
version = "0.10.7" version = "0.10.7"
@@ -5438,6 +5452,12 @@ version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "39ec24b3121d976906ece63c9daad25b85969647682eee313cb5779fdd69e14e" checksum = "39ec24b3121d976906ece63c9daad25b85969647682eee313cb5779fdd69e14e"
[[package]]
name = "unsafe-libyaml"
version = "0.2.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "673aac59facbab8a9007c7f6108d11f63b603f7cabff99fabf650fea5c32b861"
[[package]] [[package]]
name = "untrusted" name = "untrusted"
version = "0.9.0" version = "0.9.0"
-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 # 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) ## 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. 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`. 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:** 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 `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 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. - 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 ## Capabilities & Requirements
To use this architecture, Neovim must run the `gemini-integration.lua` script to broadcast its active socket to `~/.gemini/active_nvim.txt`. 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: The MCP server provides 5 cohesive mega-tools:
1. **`nvim_buffer`** (actions: `get_active`, `read`, `open`, `create_scratch`, `save`, `reload`, `close`, `list`, `search`) 1. **`nvim_buffer`** (actions: `read`, `replace`, `save`, `undo`, `redo`, `create_scratch`)
2. **`nvim_window`** (actions: `list`, `get_active`, `focus`, `split`, `close`) 2. **`nvim_workspace`** (actions: `list_buffers`, `list_windows`, `focus`, `split`, `cwd`)
3. **`nvim_view`** (actions: `goto_line`, `get_cursor`, `get_viewport`, `get_selection`) 3. **`nvim_intelligence`** (actions: `hover`, `definition`, `references`, `outline`, `query`, `diagnostics`, `rename`, `code_action`)
4. **`nvim_diagnostics`** (actions: `get`, `set`, `set_quickfix`) 4. **`nvim_ui`** (actions: `highlight`, `ghost_text`, `clear`)
5. **`nvim_visual`** (actions: `preview`, `extmark`, `highlight`, `clear_highlight`) 5. **`nvim_exec`** (actions: `lua`, `vimscript`, `terminal`)
6. **`nvim_execute_lua`** (direct Lua execution escape hatch)
7. **`nvim_system`** (actions: `get_info`, `get_messages`, `send_to_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) ## 2. Strict Tool Adherence (No Raw Lua RCE)
You must strictly use the specialized, sandboxed Neovim MCP tools: You must strictly use the specialized, sandboxed Neovim MCP tools:
- `nvim_buffer`: For reading, writing, saving, and creating scratch buffers. - `nvim_buffer`: For reading, writing, saving, and creating scratch buffers.
- `nvim_window`: For creating splits and focusing panes. - `nvim_workspace`: For creating splits and focusing panes.
- `nvim_visual`: For highlighting diffs, adding ghost text, and showing previews. - `nvim_ui`: 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. **DO NOT** use `nvim_exec` (action `lua`) to mutate editor state. It is restricted to **READ-ONLY** queries.
## 3. Headless Quarantine ## 3. Headless Quarantine
Headless mode (`nvim --headless`) is strictly banned for interactive edits. 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). Headless instances are allowed ONLY for non-interactive background batch processing (e.g., project-wide formatting or linting).
## 4. UI Presentation & Chat Console Minimization ## 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 ## 5. Visual Cues & Auto-Save
When manipulating buffers via MCP: 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. 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 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. - 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 if #vim.api.nvim_list_uis() > 0 then
local server_name = vim.v.servername local server_name = vim.v.servername
if server_name then 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) -- 2. V2 Telemetry Push (HTTP with Knowledge Projection + UDP Fast Mirror)
local file = vim.api.nvim_buf_get_name(0) local file = vim.api.nvim_buf_get_name(0)
local cursor = vim.api.nvim_win_get_cursor(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) ## 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. * **`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`). - `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. 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 Consolidated Tool Arsenal (v3)
The server consolidates granular Neovim operations into 7 smart domain tools: The server consolidates granular Neovim operations into 5 smart mega-tools:
- **`nvim_buffer`**: Buffer and file management. - **`nvim_buffer`**: Buffer and file management. Actions: `read`, `replace`, `save`, `undo`, `redo`, `create_scratch`.
- `action: "open_file"`: Open file in buffer (args: `file`, `line`, `col`). - **`nvim_workspace`**: Window split and focus management. Actions: `list_buffers`, `list_windows`, `focus`, `split`, `cwd`.
- `action: "open"`: Open buffer (args: `bufnr`). - **`nvim_intelligence`**: Code intelligence and LSP. Actions: `hover`, `definition`, `references`, `outline`, `query`, `diagnostics`, `rename`, `code_action`.
- `action: "close"`: Close buffer (args: `bufnr`, `force`). - **`nvim_ui`**: Visual highlighting, diff previews, and ghost text. Actions: `highlight`, `ghost_text`, `clear`.
- `action: "reload"`: Reload buffer from disk (args: `bufnr`). - **`nvim_exec`**: Escape hatch for raw evaluation. Actions: `lua`, `vimscript`, `terminal`.
- `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.
## 1. Using Consolidated Domain Tools First ## 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`) ## 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., complex buffer edits, changing options, custom LSP interactions), you MUST use `nvim_execute_lua` as your escape hatch. 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. 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" })`. 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. 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 ## 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). 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).
+563 -169
View File
@@ -378,14 +378,17 @@ async fn get_nvim_connection() -> Result<mpsc::Sender<NvimRequest>, String> {
{ {
let conn_lock = NVIM_CONN.lock().await; let conn_lock = NVIM_CONN.lock().await;
if let Some(sender) = conn_lock.as_ref() if let Some(sender) = conn_lock.as_ref()
&& !sender.is_closed() { && !sender.is_closed()
let active_lock = ACTIVE_SOCKET.lock().await; {
if let Some(ref current_socket) = *active_lock let active_lock = ACTIVE_SOCKET.lock().await;
&& let Ok(target) = read_active_socket_file().await if let Some(ref current_socket) = *active_lock
&& !target.is_empty() && &target == current_socket { && let Ok(target) = read_active_socket_file().await
return Ok(sender.clone()); && !target.is_empty()
} && &target == current_socket
{
return Ok(sender.clone());
} }
}
} }
let interactive_socket = get_socket_path().await.ok(); let interactive_socket = get_socket_path().await.ok();
@@ -671,13 +674,14 @@ async fn call_nvim(req: rmpv::Value) -> Result<rmpv::Value, String> {
}; };
let (reply_tx, reply_rx) = oneshot::channel(); let (reply_tx, reply_rx) = oneshot::channel();
if let Err(_) = tx if tx
.send(NvimRequest { .send(NvimRequest {
msgid, msgid,
req, req,
reply: reply_tx, reply: reply_tx,
}) })
.await .await
.is_err()
{ {
PENDING_REQUESTS.remove(&msgid); PENDING_REQUESTS.remove(&msgid);
let mut conn = NVIM_CONN.lock().await; let mut conn = NVIM_CONN.lock().await;
@@ -1079,155 +1083,125 @@ pub async fn run_mcp_loop(app_name: &str, app_version: &str) {
jsonrpc: "2.0".to_string(), jsonrpc: "2.0".to_string(),
id, id,
result: Some(json!({ result: Some(json!({
"tools": [ "tools":
{ [
"name": "nvim_buffer", {
"description": "Unified buffer management: inspect, open, read, search, save, reload, or close Neovim buffers.", "name": "nvim_buffer",
"inputSchema": { "description": "Core Text Editing: read, replace, save, and manipulate Neovim buffers in memory.",
"type": "object", "inputSchema": {
"properties": { "type": "object",
"action": { "properties": {
"type": "string", "action": {
"enum": ["get_active", "read", "open", "create_scratch", "save", "reload", "close", "list", "search"], "type": "string",
"description": "Action to perform on the buffer" "enum": ["read", "replace", "save", "undo", "redo", "create_scratch"],
}, "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)" }, "file": { "type": "string", "description": "Target file path (for read, replace, save)" },
"content": { "type": "string", "description": "Initial text content (for create_scratch)" }, "start_line": { "type": "integer", "description": "1-indexed start line (for read)" },
"name": { "type": "string", "description": "Buffer display name (for create_scratch)" }, "end_line": { "type": "integer", "description": "1-indexed end line (for read)" },
"filetype": { "type": "string", "description": "Filetype syntax (for open, create_scratch)" }, "content": { "type": "string", "description": "Initial text content (for create_scratch)" },
"start_line": { "type": "integer", "description": "1-indexed start line (for read)" }, "name": { "type": "string", "description": "Buffer display name (for create_scratch)" },
"end_line": { "type": "integer", "description": "1-indexed end line (for read)" }, "steps": { "type": "integer", "description": "Number of undo/redo steps to apply (default: 1)" },
"pattern": { "type": "string", "description": "Regex or substring pattern to search for (for search)" }, "edits": {
"force": { "type": "boolean", "description": "Force reload or close (for reload, close)" } "type": "array",
}, "description": "Array of edits to apply sequentially (for replace). Grouped by file, applied in descending order.",
"required": ["action"] "items": {
} "type": "object",
}, "properties": {
{ "file": { "type": "string" },
"name": "nvim_window", "start_line": { "type": "integer" },
"description": "Manage Neovim windows and splits: list open windows, query or focus active window, create splits, or close windows.", "end_line": { "type": "integer" },
"inputSchema": { "replacement_content": { "type": "string" },
"type": "object", "expected_content": { "type": "string" }
"properties": { },
"action": { "required": ["file", "start_line", "end_line", "replacement_content"]
"type": "string", }
"enum": ["list", "get_active", "focus", "split", "close"], }
"description": "Window operation to perform" },
}, "required": ["action"]
"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)" }, "name": "nvim_workspace",
"force": { "type": "boolean", "description": "Force close window" } "description": "Window & Editor State: list buffers, windows, focus splits, and manage cwd.",
}, "inputSchema": {
"required": ["action"] "type": "object",
} "properties": {
}, "action": {
{ "type": "string",
"name": "nvim_view", "enum": ["list_buffers", "list_windows", "focus", "split", "cwd"],
"description": "Editor navigation and viewport introspection: jump to line, query cursor position, get visible viewport lines, or get visual selection.", "description": "Workspace operation to perform"
"inputSchema": { },
"type": "object", "win_id": { "type": "integer", "description": "Window ID to focus" },
"properties": { "file": { "type": "string", "description": "File to open in split" },
"action": { "direction": { "type": "string", "enum": ["vertical", "horizontal"], "description": "Split orientation (default: vertical)" },
"type": "string", "path": { "type": "string", "description": "Target directory (for cwd action)" }
"enum": ["goto_line", "get_cursor", "get_viewport", "get_selection"], },
"description": "Navigation/inspection action to perform" "required": ["action"]
}, }
"file": { "type": "string", "description": "File path (for goto_line)" }, },
"line": { "type": "integer", "description": "Target line number (1-indexed, for goto_line)" } {
}, "name": "nvim_intelligence",
"required": ["action"] "description": "Code Semantics: LSP queries (hover, definition, references, code_action, rename, diagnostics) and AST outlining/queries.",
} "inputSchema": {
}, "type": "object",
{ "properties": {
"name": "nvim_diagnostics", "action": {
"description": "LSP diagnostics and quickfix integration: fetch current diagnostics, inject LSP diagnostic markers, or populate the quickfix list.", "type": "string",
"inputSchema": { "enum": ["hover", "definition", "references", "outline", "query", "diagnostics", "rename", "code_action"],
"type": "object", "description": "Intelligence action to perform"
"properties": { },
"action": { "file": { "type": "string", "description": "Target file path" },
"type": "string", "line": { "type": "integer", "description": "1-indexed line number (for LSP)" },
"enum": ["get", "set", "set_quickfix"], "col": { "type": "integer", "description": "0-indexed column number (for LSP)" },
"description": "Diagnostic action to perform" "new_name": { "type": "string", "description": "New name (for rename action)" },
}, "query": { "type": "string", "description": "Tree-sitter query string (for AST query)" },
"line": { "type": "integer", "description": "Line number (1-indexed, for set)" }, "preset": { "type": "string", "description": "Query preset (e.g., 'functions', 'classes' for AST query)" }
"message": { "type": "string", "description": "Diagnostic warning/error message (for set)" }, },
"items": { "required": ["action"]
"type": "array", }
"description": "Quickfix entries (for set_quickfix)", },
"items": { {
"type": "object", "name": "nvim_ui",
"properties": { "description": "Visual Feedback: communicating visually with the human user via highlights and ghost text.",
"filename": { "type": "string" }, "inputSchema": {
"lnum": { "type": "integer" }, "type": "object",
"text": { "type": "string" } "properties": {
}, "action": {
"required": ["filename", "lnum", "text"] "type": "string",
} "enum": ["highlight", "ghost_text", "clear"],
}, "description": "UI action"
"qf_action": { "type": "string", "enum": ["replace", "append", "prepend"], "description": "Quickfix list modification action (for set_quickfix)" } },
}, "buf_id": { "type": "integer", "description": "Buffer ID to apply to" },
"required": ["action"] "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)" },
"name": "nvim_visual", "highlight_group": { "type": "string", "description": "Highlight group (e.g. 'Comment', 'IncSearch')" },
"description": "Visual feedback, syntax highlighting, ghost text extmarks, and diff preview overlays.", "duration_ms": { "type": "integer", "description": "Auto-clear duration in ms (for highlight, default: 5000)" }
"inputSchema": { },
"type": "object", "required": ["action"]
"properties": { }
"action": { },
"type": "string", {
"enum": ["preview", "extmark", "highlight", "clear_highlight"], "name": "nvim_exec",
"description": "Visual feedback action" "description": "The Escape Hatch: execute lua read-only queries, run vimscript commands, or send commands to the terminal.",
}, "inputSchema": {
"file_path": { "type": "string", "description": "File path (for preview)" }, "type": "object",
"start_line": { "type": "integer", "description": "Start line (1-indexed, for preview, highlight)" }, "properties": {
"end_line": { "type": "integer", "description": "End line (1-indexed, for preview, highlight)" }, "action": {
"preview_content": { "type": "string", "description": "Proposed replacement code (for preview)" }, "type": "string",
"line": { "type": "integer", "description": "Line number (1-indexed, for extmark)" }, "enum": ["lua", "vimscript", "terminal"],
"text": { "type": "string", "description": "Virtual ghost text to display (for extmark)" }, "description": "Execution action"
"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)" }, "code": { "type": "string", "description": "Lua code or Vimscript command to execute" },
"duration_ms": { "type": "integer", "description": "Auto-clear duration in ms (for highlight, default: 5000)" } "command": { "type": "string", "description": "Shell command to send (for terminal)" }
}, },
"required": ["action"] "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"]
}
}
]
})), })),
error: None, error: None,
}).await; }).await;
@@ -1240,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(""); let action = args.get("action").and_then(|v| v.as_str()).unwrap_or("");
match name { let (mapped_name, mapped_action) = match (name, action) {
"nvim_buffer" => match 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 { "get_active" => match get_nvim_active_buffer().await {
Ok(content) => { Ok(content) => {
send_text_result!(id.clone(), content); send_text_result!(id.clone(), content);
@@ -1324,6 +1332,141 @@ pub async fn run_mcp_loop(app_name: &str, app_version: &str) {
execute_nvim_lua_with_args(code, vec![args_rmp]) execute_nvim_lua_with_args(code, vec![args_rmp])
) )
} }
"edit" => {
let mut modified_args = args.clone();
if let Some(edits) = modified_args
.get_mut("edits")
.and_then(|v| v.as_array_mut())
{
for edit in edits.iter_mut() {
if let Some(content) = edit.get_mut("replacement_content")
&& let Some(s) = content.as_str()
{
let lines: Vec<String> = s
.split('\n')
.map(|l| l.trim_end_matches('\r').to_string())
.collect();
*content = serde_json::json!(lines);
}
}
} else if let Some(content) =
modified_args.get_mut("replacement_content")
&& let Some(s) = content.as_str()
{
let lines: Vec<String> = s
.split('\n')
.map(|l| l.trim_end_matches('\r').to_string())
.collect();
*content = serde_json::json!(lines);
}
let args_rmp = json_to_rmpv(&modified_args);
let code = "
local args = ...
local edits = args.edits
if not edits or type(edits) ~= 'table' then
if args.file and args.start_line and args.end_line and args.replacement_content then
edits = {
{
file = args.file,
start_line = tonumber(args.start_line),
end_line = tonumber(args.end_line),
replacement_content = args.replacement_content,
expected_content = args.expected_content
}
}
else
error(\"Missing 'edits' array or valid single edit parameters\")
end
end
local grouped_edits = {}
for i, edit in ipairs(edits) do
local file = edit.file
if not file or file == '' or file == vim.NIL then
error(\"Edit missing 'file'\")
end
if not grouped_edits[file] then
grouped_edits[file] = {}
end
table.insert(grouped_edits[file], {
start_line = tonumber(edit.start_line),
end_line = tonumber(edit.end_line),
replacement_content = edit.replacement_content,
expected_content = edit.expected_content,
original_index = i
})
end
local results = {}
for file, file_edits in pairs(grouped_edits) do
local bufnr = vim.fn.bufnr(file, true)
if vim.fn.bufloaded(bufnr) == 0 then
vim.fn.bufload(bufnr)
end
table.sort(file_edits, function(a, b)
return a.start_line > b.start_line
end)
for _, edit in ipairs(file_edits) do
local sl = edit.start_line
local el = edit.end_line
local rc = edit.replacement_content
local ec = edit.expected_content
if not sl then error(\"Edit missing 'start_line'\") end
if not el then error(\"Edit missing 'end_line'\") end
if not rc or rc == vim.NIL then error(\"Edit missing 'replacement_content'\") end
if ec and type(ec) == 'string' and ec ~= vim.NIL and ec ~= '' then
local current_lines = vim.api.nvim_buf_get_lines(bufnr, sl - 1, el, false)
local current_text = table.concat(current_lines, '\\n')
local ec_clean = string.gsub(ec, '\\r', '')
if current_text ~= ec_clean then
error(\"Safety check failed in \" .. file .. \": Expected content at lines \" .. tostring(sl) .. \"-\" .. tostring(el) .. \" does not match actual content.\\nExpected:\\n\" .. ec_clean .. \"\\nActual:\\n\" .. current_text)
end
end
vim.api.nvim_buf_set_lines(bufnr, sl - 1, el, false, rc)
end
local win = vim.fn.bufwinid(bufnr)
if win ~= -1 and #file_edits > 0 then
pcall(vim.api.nvim_win_set_cursor, win, {file_edits[#file_edits].start_line, 0})
end
table.insert(results, \"Edited \" .. file .. \" (\" .. tostring(#file_edits) .. \" blocks)\")
end
return table.concat(results, ', ')
";
handle_lua_result!(
id,
execute_nvim_lua_with_args(code, vec![args_rmp])
)
}
"undo" | "redo" => {
let is_undo = action == "undo";
let steps = args.get("steps").and_then(|v| v.as_i64()).unwrap_or(1);
let cmd = if is_undo {
format!("{}u", steps)
} else {
format!("{}<C-r>", steps)
};
let code = format!(
"
local pcall_ok, err = pcall(function()
vim.cmd('normal! {}')
end)
if not pcall_ok then
error('Failed to {}: ' .. tostring(err))
end
return '{} applied {} step(s)'
",
cmd, action, action, steps
);
handle_lua_result!(id, execute_nvim_lua(&code));
}
"open" => { "open" => {
let args_rmp = json_to_rmpv(args); let args_rmp = json_to_rmpv(args);
let code = " let code = "
@@ -1356,7 +1499,17 @@ pub async fn run_mcp_loop(app_name: &str, app_version: &str) {
) )
} }
"create_scratch" | "open_buffer" => { "create_scratch" | "open_buffer" => {
let args_rmp = json_to_rmpv(args); let mut modified_args = args.clone();
if let Some(content) = modified_args.get_mut("content")
&& let Some(s) = content.as_str()
{
let lines: Vec<String> = s
.split('\n')
.map(|l| l.trim_end_matches('\r').to_string())
.collect();
*content = serde_json::json!(lines);
}
let args_rmp = json_to_rmpv(&modified_args);
let code = " let code = "
local args = ... local args = ...
local name = (args.name and args.name ~= '') and args.name or '[Antigravity Scratch]' local name = (args.name and args.name ~= '') and args.name or '[Antigravity Scratch]'
@@ -1366,8 +1519,7 @@ pub async fn run_mcp_loop(app_name: &str, app_version: &str) {
vim.bo[buf].buftype = 'nofile' vim.bo[buf].buftype = 'nofile'
vim.bo[buf].bufhidden = 'hide' vim.bo[buf].bufhidden = 'hide'
if args.content then if args.content then
local lines = vim.split(args.content, '\\n') vim.api.nvim_buf_set_lines(buf, 0, -1, false, args.content)
vim.api.nvim_buf_set_lines(buf, 0, -1, false, lines)
end end
if args.filetype and args.filetype ~= '' then if args.filetype and args.filetype ~= '' then
vim.bo[buf].filetype = args.filetype vim.bo[buf].filetype = args.filetype
@@ -1818,9 +1970,10 @@ pub async fn run_mcp_loop(app_name: &str, app_version: &str) {
"highlight" | "clear_highlight" => { "highlight" | "clear_highlight" => {
let mut modified_args = args.clone(); let mut modified_args = args.clone();
if action == "clear_highlight" if action == "clear_highlight"
&& let Some(obj) = modified_args.as_object_mut() { && let Some(obj) = modified_args.as_object_mut()
obj.insert("clear_only".to_string(), json!(true)); {
} obj.insert("clear_only".to_string(), json!(true));
}
let args_rmp = json_to_rmpv(&modified_args); let args_rmp = json_to_rmpv(&modified_args);
let code = " let code = "
local args = ... local args = ...
@@ -1945,6 +2098,27 @@ pub async fn run_mcp_loop(app_name: &str, app_version: &str) {
send_error(id, -32602, "Missing 'command'").await; 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( send_error(
id, id,
@@ -1958,6 +2132,229 @@ pub async fn run_mcp_loop(app_name: &str, app_version: &str) {
} }
}, },
"nvim_lsp" => {
let args_rmp = json_to_rmpv(args);
let lua_code = match action {
"hover" => {
r#"
local args = ...
local bufnr = vim.fn.bufnr(args.file)
if bufnr == -1 then return "Buffer not found" end
local params = vim.lsp.util.make_position_params(0)
params.position.line = (tonumber(args.line) or 1) - 1
params.position.character = tonumber(args.col) or 0
params.textDocument.uri = vim.uri_from_bufnr(bufnr)
local res, err = vim.lsp.buf_request_sync(bufnr, 'textDocument/hover', params, 2000)
if err or not res then return "Error or timeout" end
for client_id, response in pairs(res) do
if response.result and response.result.contents then
local contents = response.result.contents
if type(contents) == 'table' and contents.value then return contents.value end
if type(contents) == 'string' then return contents end
end
end
return "No hover info"
"#
}
"definition" => {
r#"
local args = ...
local bufnr = vim.fn.bufnr(args.file)
if bufnr == -1 then return "Buffer not found" end
local params = vim.lsp.util.make_position_params(0)
params.position.line = (tonumber(args.line) or 1) - 1
params.position.character = tonumber(args.col) or 0
params.textDocument.uri = vim.uri_from_bufnr(bufnr)
local res, err = vim.lsp.buf_request_sync(bufnr, 'textDocument/definition', params, 2000)
if err or not res then return "Error or timeout" end
local locations = {}
for client_id, response in pairs(res) do
if response.result then
local res_locs = vim.tbl_islist(response.result) and response.result or {response.result}
for _, loc in ipairs(res_locs) do
local uri = loc.uri or loc.targetUri
local range = loc.range or loc.targetSelectionRange
table.insert(locations, vim.uri_to_fname(uri) .. ":" .. (range.start.line + 1))
end
end
end
if #locations == 0 then return "No definition found" end
return table.concat(locations, "\n")
"#
}
"references" => {
r#"
local args = ...
local bufnr = vim.fn.bufnr(args.file)
if bufnr == -1 then return "Buffer not found" end
local params = vim.lsp.util.make_position_params(0)
params.position.line = (tonumber(args.line) or 1) - 1
params.position.character = tonumber(args.col) or 0
params.context = { includeDeclaration = true }
params.textDocument.uri = vim.uri_from_bufnr(bufnr)
local res, err = vim.lsp.buf_request_sync(bufnr, 'textDocument/references', params, 5000)
if err or not res then return "Error or timeout" end
local locations = {}
for client_id, response in pairs(res) do
if response.result then
for _, loc in ipairs(response.result) do
table.insert(locations, vim.uri_to_fname(loc.uri) .. ":" .. (loc.range.start.line + 1))
end
end
end
if #locations == 0 then return "No references found" end
return table.concat(locations, "\n")
"#
}
"rename" => {
r#"
local args = ...
local bufnr = vim.fn.bufnr(args.file)
if bufnr == -1 then return "Buffer not found" end
local new_name = args.new_name
if not new_name then return "Missing new_name" end
local params = vim.lsp.util.make_position_params(0)
params.position.line = (tonumber(args.line) or 1) - 1
params.position.character = tonumber(args.col) or 0
params.newName = new_name
params.textDocument.uri = vim.uri_from_bufnr(bufnr)
local res, err = vim.lsp.buf_request_sync(bufnr, 'textDocument/rename', params, 2000)
if err or not res then return "Error or timeout" end
local applied = false
for client_id, response in pairs(res) do
if response.result then
vim.lsp.util.apply_workspace_edit(response.result, vim.lsp.get_client_by_id(client_id).offset_encoding)
applied = true
end
end
return applied and "Rename applied" or "No rename edits"
"#
}
"code_action" => {
r#"
local args = ...
local bufnr = vim.fn.bufnr(args.file)
if bufnr == -1 then return "Buffer not found" end
local params = vim.lsp.util.make_range_params(0)
params.position = nil
params.range.start.line = (tonumber(args.line) or 1) - 1
params.range.start.character = tonumber(args.col) or 0
params.range['end'] = params.range.start
params.context = { diagnostics = vim.lsp.diagnostic.get_line_diagnostics(bufnr, params.range.start.line) }
params.textDocument.uri = vim.uri_from_bufnr(bufnr)
local res, err = vim.lsp.buf_request_sync(bufnr, 'textDocument/codeAction', params, 2000)
if err or not res then return "Error or timeout" end
local actions = {}
for client_id, response in pairs(res) do
if response.result then
for _, action in ipairs(response.result) do
if action.edit then
vim.lsp.util.apply_workspace_edit(action.edit, vim.lsp.get_client_by_id(client_id).offset_encoding)
table.insert(actions, "Applied: " .. (action.title or "unnamed"))
elseif action.command then
table.insert(actions, "Found command (not auto-applied): " .. (action.title or "unnamed"))
end
end
end
end
if #actions == 0 then return "No code actions available or applied" end
return table.concat(actions, "\n")
"#
}
_ => "",
};
if lua_code.is_empty() {
send_error(
id,
-32602,
&format!("Invalid nvim_lsp action: {}", action),
)
.await;
} else {
handle_lua_result!(
id,
execute_nvim_lua_with_args(lua_code, vec![args_rmp])
);
}
}
"nvim_ast" => {
let args_rmp = json_to_rmpv(args);
let lua_code = match action {
"query" => {
r#"
local args = ...
local bufnr = vim.fn.bufnr(args.file)
if bufnr == -1 then return "Buffer not found" end
local query_str = args.query
if not query_str then return "Missing query string" end
local parser = vim.treesitter.get_parser(bufnr)
if not parser then return "No TS parser for buffer" end
local tree = parser:parse()[1]
local root = tree:root()
local query = vim.treesitter.query.parse(parser:lang(), query_str)
local results = {}
for id, node, metadata in query:iter_captures(root, bufnr, 0, -1) do
local name = query.captures[id]
local row1, col1, row2, col2 = node:range()
local text = vim.treesitter.get_node_text(node, bufnr)
table.insert(results, name .. " at line " .. tostring(row1 + 1) .. ":\n" .. text)
end
return table.concat(results, "\n\n")
"#
}
"outline" => {
r#"
local args = ...
local bufnr = vim.fn.bufnr(args.file)
if bufnr == -1 then return "Buffer not found" end
local parser = vim.treesitter.get_parser(bufnr)
if not parser then return "No TS parser for buffer" end
local tree = parser:parse()[1]
local root = tree:root()
local lang = parser:lang()
local q_str = ""
if lang == "rust" then
q_str = "(function_item name: (identifier) @name) (impl_item type: (type_identifier) @name) (struct_item name: (type_identifier) @name) (trait_item name: (type_identifier) @name)"
elseif lang == "python" then
q_str = "(function_definition name: (identifier) @name) (class_definition name: (identifier) @name)"
elseif lang == "javascript" or lang == "typescript" then
q_str = "(function_declaration name: (identifier) @name) (class_declaration name: (identifier) @name) (method_definition name: (property_identifier) @name)"
else
return "Outline preset not supported for language: " .. lang
end
local query = vim.treesitter.query.parse(lang, q_str)
local results = {}
for id, node, metadata in query:iter_captures(root, bufnr, 0, -1) do
local name_text = vim.treesitter.get_node_text(node, bufnr)
local parent = node:parent()
local row1, col1, row2, col2 = parent:range()
table.insert(results, name_text .. " (Line " .. tostring(row1 + 1) .. "-" .. tostring(row2 + 1) .. ")")
end
return table.concat(results, "\n")
"#
}
_ => "",
};
if lua_code.is_empty() {
send_error(
id,
-32602,
&format!("Invalid nvim_ast action: {}", action),
)
.await;
} else {
handle_lua_result!(
id,
execute_nvim_lua_with_args(lua_code, vec![args_rmp])
);
}
}
_ => send_error(id, -32601, "Method not found").await, _ => send_error(id, -32601, "Method not found").await,
} }
} }
@@ -2126,10 +2523,7 @@ mod tests {
rmpv_to_json(&rmpv::Value::Integer(42.into())), rmpv_to_json(&rmpv::Value::Integer(42.into())),
serde_json::json!(42) serde_json::json!(42)
); );
assert_eq!( assert_eq!(rmpv_to_json(&rmpv::Value::F64(3.5)), serde_json::json!(3.5));
rmpv_to_json(&rmpv::Value::F64(3.14)),
serde_json::json!(3.14)
);
assert_eq!( assert_eq!(
rmpv_to_json(&rmpv::Value::String("hello".into())), rmpv_to_json(&rmpv::Value::String("hello".into())),
serde_json::json!("hello") serde_json::json!("hello")
-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
+1
View File
@@ -51,6 +51,7 @@ tokio-stream = { version = "0.1", features = ["sync"] }
chrono = { version = "0.4.45", features = ["serde"] } chrono = { version = "0.4.45", features = ["serde"] }
ocrs = "0.13.1" ocrs = "0.13.1"
rten = "0.26.0" rten = "0.26.0"
serde_yaml = "0.9.34"
[build-dependencies] [build-dependencies]
chrono = "0.4.45" chrono = "0.4.45"
-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;
}
+23 -26
View File
@@ -68,18 +68,18 @@ pub async fn handle_socket(socket: WebSocket, state: Arc<AppState>, _client_type
.filter_map(|act_val| { .filter_map(|act_val| {
if act_val["category"] == "TASK_EVENT" if act_val["category"] == "TASK_EVENT"
&& let Some(details_str) = act_val["details"].as_str() && let Some(details_str) = act_val["details"].as_str()
&& let Ok(event_val) = && let Ok(event_val) =
serde_json::from_str::<serde_json::Value>(details_str) serde_json::from_str::<serde_json::Value>(details_str)
{ {
return Some( return Some(
serde_json::json!({ serde_json::json!({
"jsonrpc": "2.0", "jsonrpc": "2.0",
"method": "notifications/task/completed", "method": "notifications/task/completed",
"params": event_val "params": event_val
}) })
.to_string(), .to_string(),
); );
} }
None None
}) })
.take(5) .take(5)
@@ -295,20 +295,17 @@ mod tests {
.iter() .iter()
.filter_map(|act_val| { .filter_map(|act_val| {
if act_val["category"] == "TASK_EVENT" { if act_val["category"] == "TASK_EVENT" {
if let Some(details_str) = act_val["details"].as_str() { let details_str = act_val["details"].as_str()?;
if let Ok(event_val) = let event_val =
serde_json::from_str::<serde_json::Value>(details_str) serde_json::from_str::<serde_json::Value>(details_str).ok()?;
{ return Some(
return Some( serde_json::json!({
serde_json::json!({ "jsonrpc": "2.0",
"jsonrpc": "2.0", "method": "notifications/task/completed",
"method": "notifications/task/completed", "params": event_val
"params": event_val })
}) .to_string(),
.to_string(), );
);
}
}
} }
None None
}) })
+10 -8
View File
@@ -44,10 +44,11 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
let path = entry.path(); let path = entry.path();
if path.extension().is_some_and(|ext| ext == "json") if path.extension().is_some_and(|ext| ext == "json")
&& let Some(stem) = path.file_stem().and_then(|s| s.to_str()) && let Some(stem) = path.file_stem().and_then(|s| s.to_str())
&& !active_tools.contains(stem) { && !active_tools.contains(stem)
println!(" [STALE REMOVED Win] {}", path.display()); {
let _ = fs::remove_file(&path); println!(" [STALE REMOVED Win] {}", path.display());
} let _ = fs::remove_file(&path);
}
} }
} }
@@ -57,10 +58,11 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
let path = entry.path(); let path = entry.path();
if path.extension().is_some_and(|ext| ext == "json") if path.extension().is_some_and(|ext| ext == "json")
&& let Some(stem) = path.file_stem().and_then(|s| s.to_str()) && let Some(stem) = path.file_stem().and_then(|s| s.to_str())
&& !active_tools.contains(stem) { && !active_tools.contains(stem)
println!(" [STALE REMOVED WSL] {}", path.display()); {
let _ = fs::remove_file(&path); println!(" [STALE REMOVED WSL] {}", path.display());
} let _ = fs::remove_file(&path);
}
} }
} }
+6 -5
View File
@@ -31,12 +31,13 @@ pub fn load_mcp_config_env() {
{ {
for (key, val) in env_obj { for (key, val) in env_obj {
if let Some(val_str) = val.as_str() if let Some(val_str) = val.as_str()
&& env::var(key).is_err() { && env::var(key).is_err()
unsafe { {
env::set_var(key, val_str); unsafe {
} env::set_var(key, val_str);
info!("Loaded env var {} from mcp_config.json", key);
} }
info!("Loaded env var {} from mcp_config.json", key);
}
} }
} }
} }
+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() { match db.begin_write() {
Ok(write_txn) => { Ok(write_txn) => {
let mut opened_ok = false; 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; opened_ok = true;
if !is_in_memory { }
let stores = vec![ if opened_ok {
("knowledge_graph_master", "knowledge_graph_master.json"), if let Err(e) = write_txn.commit() {
("audit_ledger", "audit_ledger.json"), tracing::error!("Failed to commit database initialization transaction: {}", e);
("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);
}
} }
Err(e) => { Err(e) => {
tracing::error!( tracing::error!(
"Failed to begin write transaction for redb migration: {}", "Failed to begin write transaction for redb initialization: {}",
e e
); );
} }
+5 -8
View File
@@ -193,14 +193,14 @@ fn fallback_embed(text: &str) -> Vec<f32> {
} }
enum EmbeddingModel { enum EmbeddingModel {
Candle(CandleEmbeddingModel), Candle(Box<CandleEmbeddingModel>),
Fallback, Fallback,
} }
impl EmbeddingModel { impl EmbeddingModel {
fn new() -> Self { fn new() -> Self {
match CandleEmbeddingModel::new() { match CandleEmbeddingModel::new() {
Ok(model) => EmbeddingModel::Candle(model), Ok(model) => EmbeddingModel::Candle(Box::new(model)),
Err(e) => { Err(e) => {
tracing::warn!( tracing::warn!(
"Failed to initialize Candle BERT model ({e}); falling back to deterministic offline embeddings." "Failed to initialize Candle BERT model ({e}); falling back to deterministic offline embeddings."
@@ -259,13 +259,10 @@ pub fn cosine_similarity(a: &[f32], b: &[f32]) -> f32 {
let mut norm_a_sq = 0.0f32; let mut norm_a_sq = 0.0f32;
let mut norm_b_sq = 0.0f32; let mut norm_b_sq = 0.0f32;
let chunks_a = a.chunks_exact(8); let (chunks_a, remainder_a) = a.as_chunks::<8>();
let chunks_b = b.chunks_exact(8); let (chunks_b, remainder_b) = b.as_chunks::<8>();
let remainder_a = chunks_a.remainder(); for (ca, cb) in chunks_a.iter().zip(chunks_b.iter()) {
let remainder_b = chunks_b.remainder();
for (ca, cb) in chunks_a.zip(chunks_b) {
for i in 0..8 { for i in 0..8 {
let x = ca[i]; let x = ca[i];
let y = cb[i]; let y = cb[i];
+7
View File
@@ -40,6 +40,9 @@ pub enum AppError {
#[error("I/O Error: {0}")] #[error("I/O Error: {0}")]
IoError(#[from] std::io::Error), IoError(#[from] std::io::Error),
#[error("YAML Serialization Error: {0}")]
YamlError(#[from] serde_yaml::Error),
} }
impl From<AppError> for String { impl From<AppError> for String {
@@ -81,6 +84,10 @@ impl IntoResponse for AppError {
StatusCode::INTERNAL_SERVER_ERROR, StatusCode::INTERNAL_SERVER_ERROR,
format!("I/O Error: {}", e), format!("I/O Error: {}", e),
), ),
AppError::YamlError(e) => (
StatusCode::INTERNAL_SERVER_ERROR,
format!("YAML Serialization Error: {}", e),
),
}; };
let body = Json(json!({ let body = Json(json!({
+11 -9
View File
@@ -120,9 +120,10 @@ impl McpTool for ReadFileSkeletonHandler {
} }
} }
if header.is_empty() if header.is_empty()
&& let Some(first_line) = node_text.lines().next() { && let Some(first_line) = node_text.lines().next()
header = first_line.to_string(); {
} header = first_line.to_string();
}
out.push_str(&indent); out.push_str(&indent);
out.push_str(header.trim()); out.push_str(header.trim());
@@ -425,9 +426,10 @@ fn scan_workspace_for_symbol(
break; break;
} }
if let Ok(meta) = std::fs::metadata(path) if let Ok(meta) = std::fs::metadata(path)
&& meta.len() > 1024 * 1024 { && meta.len() > 1024 * 1024
continue; {
} continue;
}
if let Ok(content) = std::fs::read_to_string(path) { if let Ok(content) = std::fs::read_to_string(path) {
for (line_num, line) in content.lines().enumerate() { for (line_num, line) in content.lines().enumerate() {
let is_match = if filter_fn_call { let is_match = if filter_fn_call {
@@ -504,7 +506,7 @@ impl McpTool for FindSymbolReferencesHandler {
matches.extend(disk_matches); matches.extend(disk_matches);
} }
Ok(serde_json::to_string_pretty(&matches)?) Ok(serde_yaml::to_string(&matches)?)
} }
} }
@@ -560,7 +562,7 @@ impl McpTool for GetCallersHandler {
callers.extend(disk_callers); callers.extend(disk_callers);
} }
Ok(serde_json::to_string_pretty(&callers)?) Ok(serde_yaml::to_string(&callers)?)
} }
} }
@@ -649,7 +651,7 @@ impl McpTool for AnalyzeImpactHandler {
} }
}); });
Ok(serde_json::to_string_pretty(&result)?) Ok(serde_yaml::to_string(&result)?)
} }
} }
+2 -2
View File
@@ -70,7 +70,7 @@ impl McpTool for EnvironmentHandler {
.env_fingerprints .env_fingerprints
.read_with(|fps| fps.get(&ns).cloned()); .read_with(|fps| fps.get(&ns).cloned());
if let Some(fp) = data { if let Some(fp) = data {
let data = Ok::<String, crate::error::AppError>(serde_json::to_string(&fp)?)?; let data = Ok::<String, crate::error::AppError>(serde_yaml::to_string(&fp)?)?;
Ok(data) Ok(data)
} else { } else {
Ok("{}".to_string()) Ok("{}".to_string())
@@ -118,7 +118,7 @@ impl McpTool for EnvironmentHandler {
EnvAction::GetDetails => { EnvAction::GetDetails => {
let data = state.env.environments.read_with(|envs| { let data = state.env.environments.read_with(|envs| {
let filtered: Vec<_> = envs.iter().filter(|e| e.namespace == ns).collect(); let filtered: Vec<_> = envs.iter().filter(|e| e.namespace == ns).collect();
Ok::<String, crate::error::AppError>(serde_json::to_string(&filtered)?) Ok::<String, crate::error::AppError>(serde_yaml::to_string(&filtered)?)
})?; })?;
Ok(data) Ok(data)
} }
+23 -22
View File
@@ -87,7 +87,7 @@ impl McpTool for GetActiveWorktreeContextHandler {
.await .await
.map_err(|e| crate::error::AppError::Internal(format!("Task panic: {}", e)))??; .map_err(|e| crate::error::AppError::Internal(format!("Task panic: {}", e)))??;
Ok::<String, crate::error::AppError>(serde_json::to_string_pretty(&result)?) Ok::<String, crate::error::AppError>(serde_yaml::to_string(&result)?)
} }
} }
@@ -140,27 +140,28 @@ impl McpTool for QueryGitDiffsHandler {
let mut results = Vec::new(); let mut results = Vec::new();
let cwd = env::current_dir().unwrap_or_default(); let cwd = env::current_dir().unwrap_or_default();
if let Ok(repo) = git2::Repository::discover(&cwd) if let Ok(repo) = git2::Repository::discover(&cwd)
&& let Ok(mut revwalk) = repo.revwalk() { && let Ok(mut revwalk) = repo.revwalk()
let _ = revwalk.push_head(); {
let mut count = 0; let _ = revwalk.push_head();
for oid in revwalk.flatten() { let mut count = 0;
if count >= remaining { for oid in revwalk.flatten() {
break; if count >= remaining {
} break;
if let Ok(commit) = repo.find_commit(oid) { }
let summary = commit.summary().unwrap_or(""); if let Ok(commit) = repo.find_commit(oid) {
if summary.to_lowercase().contains(&q) { let summary = commit.summary().unwrap_or("");
count += 1; if summary.to_lowercase().contains(&q) {
results.push(json!({ count += 1;
"commit_id": oid.to_string(), results.push(json!({
"author": commit.author().name().unwrap_or("unknown"), "commit_id": oid.to_string(),
"message": summary, "author": commit.author().name().unwrap_or("unknown"),
"timestamp": commit.time().seconds(), "message": summary,
})); "timestamp": commit.time().seconds(),
} }));
} }
} }
} }
}
results results
}) })
.await .await
@@ -168,7 +169,7 @@ impl McpTool for QueryGitDiffsHandler {
matches.extend(git_matches); matches.extend(git_matches);
} }
Ok(serde_json::to_string_pretty(&matches)?) Ok(serde_yaml::to_string(&matches)?)
} }
} }
@@ -191,7 +192,7 @@ mod tests {
.map_err(|e| format!("Failed to get worktree context: {}", e)) .map_err(|e| format!("Failed to get worktree context: {}", e))
.unwrap(); .unwrap();
let parsed: serde_json::Value = serde_json::from_str(&result).unwrap(); let parsed: serde_json::Value = serde_yaml::from_str(&result).unwrap();
assert!(parsed.get("branch").is_some()); assert!(parsed.get("branch").is_some());
assert!(parsed.get("modified_files").is_some()); assert!(parsed.get("modified_files").is_some());
assert!(parsed.get("diff").is_some()); assert!(parsed.get("diff").is_some());
@@ -210,7 +211,7 @@ mod tests {
.map_err(|e| format!("Failed to get worktree context: {}", e)) .map_err(|e| format!("Failed to get worktree context: {}", e))
.unwrap(); .unwrap();
let parsed: serde_json::Value = serde_json::from_str(&result).unwrap(); let parsed: serde_json::Value = serde_yaml::from_str(&result).unwrap();
assert!(parsed.get("branch").is_some() || parsed.is_object()); assert!(parsed.get("branch").is_some() || parsed.is_object());
} }
} }
+33 -29
View File
@@ -63,16 +63,17 @@ impl<'a> GraphQueryBuilder<'a> {
} }
nodes_at_current_depth -= 1; nodes_at_current_depth -= 1;
if current_depth < self.max_depth if current_depth < self.max_depth
&& let Some(neighbors) = adj.get(current) { && let Some(neighbors) = adj.get(current)
for &(neighbor, rel_type, is_inverse) in neighbors { {
if !visited.contains(neighbor) { for &(neighbor, rel_type, is_inverse) in neighbors {
visited.insert(neighbor); if !visited.contains(neighbor) {
parents.insert(neighbor, (current, rel_type, is_inverse)); visited.insert(neighbor);
queue.push_back(neighbor); parents.insert(neighbor, (current, rel_type, is_inverse));
nodes_at_next_depth += 1; queue.push_back(neighbor);
} nodes_at_next_depth += 1;
} }
} }
}
if nodes_at_current_depth == 0 { if nodes_at_current_depth == 0 {
current_depth += 1; current_depth += 1;
nodes_at_current_depth = nodes_at_next_depth; nodes_at_current_depth = nodes_at_next_depth;
@@ -542,7 +543,7 @@ impl McpTool for ReadGraphHandler {
}) })
}; };
let mut result_json = serde_json::to_string(&serialized)?; let mut result_json = serde_yaml::to_string(&serialized)?;
if let Some(max_tok) = max_tokens { if let Some(max_tok) = max_tokens {
let max_chars = max_tok * 4; let max_chars = max_tok * 4;
@@ -579,7 +580,7 @@ impl McpTool for ReadGraphHandler {
obj.insert("has_more".to_string(), serde_json::Value::Bool(true)); obj.insert("has_more".to_string(), serde_json::Value::Bool(true));
} }
if let Ok(trunc_str) = serde_json::to_string(&truncated_val) if let Ok(trunc_str) = serde_yaml::to_string(&truncated_val)
&& (trunc_str.len() <= max_chars || keep_count == 1) { && (trunc_str.len() <= max_chars || keep_count == 1) {
result_json = trunc_str; result_json = trunc_str;
break; break;
@@ -638,7 +639,7 @@ impl McpTool for SearchNodesHandler {
} }
} }
} }
Ok::<String, crate::error::AppError>(serde_json::to_string(&matched_entities)?) Ok::<String, crate::error::AppError>(serde_yaml::to_string(&matched_entities)?)
})?; })?;
Ok(data) Ok(data)
} }
@@ -679,7 +680,7 @@ impl McpTool for OpenNodesHandler {
result.entities.insert(name, e); result.entities.insert(name, e);
} }
} }
Ok::<String, crate::error::AppError>(serde_json::to_string(&result)?) Ok::<String, crate::error::AppError>(serde_yaml::to_string(&result)?)
})?; })?;
Ok(data) Ok(data)
} }
@@ -824,7 +825,7 @@ impl McpTool for CondenseEntityHandler {
req.entity_name, req.entity_name,
unique_obs.join("\n- ") unique_obs.join("\n- ")
); );
if let Ok(summary) = state.ollama.generate(&prompt, None, None).await { if let Ok(summary) = state.ollama.generate(&prompt, None, None, None).await {
let lines: Vec<String> = summary let lines: Vec<String> = summary
.lines() .lines()
.map(|l| l.trim().trim_start_matches('-').trim().to_string()) .map(|l| l.trim().trim_start_matches('-').trim().to_string())
@@ -954,7 +955,7 @@ impl McpTool for FindOrphansHandler {
.cloned() .cloned()
.collect::<Vec<String>>() .collect::<Vec<String>>()
}); });
let data = Ok::<String, crate::error::AppError>(serde_json::to_string(&orphans)?)?; let data = Ok::<String, crate::error::AppError>(serde_yaml::to_string(&orphans)?)?;
Ok(data) Ok(data)
} }
} }
@@ -976,8 +977,8 @@ impl McpTool for GetSubgraphHandler {
async fn execute(&self, args: Value, state: Arc<MemoryState>) -> crate::error::Result<String> { 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 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(|| { let root = req.root_entity.ok_or_else(|| {
crate::error::AppError::Internal("root_entity or root_node is required".to_string()) crate::error::AppError::Internal("root_entity is required".to_string())
})?; })?;
let depth = req.depth.unwrap_or(2); let depth = req.depth.unwrap_or(2);
let format = req.format.unwrap_or(SubgraphFormat::Json); let format = req.format.unwrap_or(SubgraphFormat::Json);
@@ -997,13 +998,14 @@ impl McpTool for GetSubgraphHandler {
while let Some((curr, d)) = queue.pop_front() { while let Some((curr, d)) = queue.pop_front() {
if d < depth if d < depth
&& let Some(neighbors) = adj.get(curr) { && let Some(neighbors) = adj.get(curr)
for &next in neighbors { {
if visited.insert(next.to_string()) { for &next in neighbors {
queue.push_back((next, d + 1)); if visited.insert(next.to_string()) {
} queue.push_back((next, d + 1));
} }
} }
}
} }
let ent: std::collections::HashMap<String, crate::models::Entity> = visited let ent: std::collections::HashMap<String, crate::models::Entity> = visited
@@ -1041,13 +1043,13 @@ impl McpTool for GetSubgraphHandler {
} }
let result = serde_json::json!({ let result = serde_json::json!({
"root_node": root, "root_entity": root,
"depth": depth, "depth": depth,
"entities": matched_entities, "entities": matched_entities,
"relations": matched_relations, "relations": matched_relations,
}); });
Ok(serde_json::to_string_pretty(&result)?) Ok(serde_yaml::to_string(&result)?)
} }
} }
@@ -1146,7 +1148,7 @@ impl McpTool for SweepGraphHealthHandler {
"health_score": if orphans.is_empty() && duplicates.is_empty() && stale_entities.is_empty() { "100%" } else { "Needs Maintenance" } "health_score": if orphans.is_empty() && duplicates.is_empty() && stale_entities.is_empty() { "100%" } else { "Needs Maintenance" }
}); });
Ok(serde_json::to_string_pretty(&report)?) Ok(serde_yaml::to_string(&report)?)
} }
} }
@@ -1176,9 +1178,11 @@ impl McpTool for ResolveStaleSymbolsHandler {
state.modify_graph(|g| { state.modify_graph(|g| {
for name in g.entities.keys() { for name in g.entities.keys() {
if let Some(target) = &req.target if let Some(target) = &req.target
&& name != target && !name.contains(target) { && name != target
continue; && !name.contains(target)
} {
continue;
}
checked += 1; checked += 1;
let path = std::path::Path::new(name); let path = std::path::Path::new(name);
if (name.contains('/') || name.contains('\\') || name.contains('.')) if (name.contains('/') || name.contains('\\') || name.contains('.'))
@@ -1203,7 +1207,7 @@ impl McpTool for ResolveStaleSymbolsHandler {
"status": "success" "status": "success"
}); });
Ok(serde_json::to_string_pretty(&report)?) Ok(serde_yaml::to_string(&report)?)
} }
} }
@@ -1643,7 +1647,7 @@ mod tests {
.execute(json!({"limit": 1, "offset": 0}), state.clone()) .execute(json!({"limit": 1, "offset": 0}), state.clone())
.await .await
.unwrap(); .unwrap();
let parsed_paged: serde_json::Value = serde_json::from_str(&paged_res).unwrap(); let parsed_paged: serde_json::Value = serde_yaml::from_str(&paged_res).unwrap();
assert_eq!(parsed_paged["total_count"], 2); assert_eq!(parsed_paged["total_count"], 2);
assert_eq!(parsed_paged["has_more"], true); assert_eq!(parsed_paged["has_more"], true);
} }
+84 -70
View File
@@ -33,7 +33,7 @@ impl McpTool for LogErrorFixHandler {
); );
if let Ok(summary) = state if let Ok(summary) = state
.ollama .ollama
.generate(&prompt, Some(&state.ollama.reasoning_model), None) .generate(&prompt, Some(&state.ollama.reasoning_model), None, None)
.await .await
{ {
let clean = summary.trim(); let clean = summary.trim();
@@ -111,9 +111,10 @@ impl McpTool for SearchErrorFixesHandler {
score += 0.5; score += 0.5;
} }
if let Some(emb) = &f.embedding if let Some(emb) = &f.embedding
&& !query_emb.is_empty() { && !query_emb.is_empty()
score += crate::embedding::cosine_similarity(&query_emb, emb); {
} score += crate::embedding::cosine_similarity(&query_emb, emb);
}
(f, score) (f, score)
}) })
.filter(|(_, score)| *score > 0.1) .filter(|(_, score)| *score > 0.1)
@@ -142,7 +143,7 @@ impl McpTool for SearchErrorFixesHandler {
}) })
.collect(); .collect();
Ok::<String, crate::error::AppError>(serde_json::to_string_pretty(&suggestions)?) Ok::<String, crate::error::AppError>(serde_yaml::to_string(&suggestions)?)
})?; })?;
return Ok(data); return Ok(data);
} }
@@ -169,7 +170,7 @@ impl McpTool for SearchErrorFixesHandler {
} }
}) })
.collect(); .collect();
Ok::<String, crate::error::AppError>(serde_json::to_string_pretty(&filtered)?) Ok::<String, crate::error::AppError>(serde_yaml::to_string(&filtered)?)
})?; })?;
Ok(data) Ok(data)
} }
@@ -198,16 +199,17 @@ impl McpTool for LogCodeChangeHandler {
description = format!("{} [Line Range: {}]", description, range); description = format!("{} [Line Range: {}]", description, range);
} }
if let Some(symbols) = &req.symbol_references if let Some(symbols) = &req.symbol_references
&& !symbols.is_empty() { && !symbols.is_empty()
description = format!("{} [Symbols: {}]", description, symbols.join(", ")); {
} description = format!("{} [Symbols: {}]", description, symbols.join(", "));
}
if state.ollama.is_available().await { if state.ollama.is_available().await {
let prompt = format!( let prompt = format!(
"Summarize in 1 concise sentence the architectural impact of changing file '{}': {}", "Summarize in 1 concise sentence the architectural impact of changing file '{}': {}",
req.file_path, description req.file_path, description
); );
if let Ok(summary) = state.ollama.generate(&prompt, None, None).await { if let Ok(summary) = state.ollama.generate(&prompt, None, None, None).await {
let clean = summary.trim(); let clean = summary.trim();
if !clean.is_empty() { if !clean.is_empty() {
description = format!("{} (AI Summary: {})", description, clean); description = format!("{} (AI Summary: {})", description, clean);
@@ -244,13 +246,12 @@ impl McpTool for LogCodeChangeHandler {
let detected_vcs = if let Some(vcs) = req.vcs_type.clone() { let detected_vcs = if let Some(vcs) = req.vcs_type.clone() {
Some(vcs) Some(vcs)
} else if let Some(ref rev) = effective_rev { } else if let Some(ref rev) = effective_rev {
if rev.starts_with('r') && rev[1..].chars().all(|c| c.is_ascii_digit()) { if (rev.starts_with('r') && rev[1..].chars().all(|c| c.is_ascii_digit()))
Some("svn".to_string()) || req
} else if req .repo_url
.repo_url .as_deref()
.as_deref() .map(|u| u.contains("/svn/"))
.map(|u| u.contains("/svn/")) .unwrap_or(false)
.unwrap_or(false)
{ {
Some("svn".to_string()) Some("svn".to_string())
} else { } else {
@@ -337,28 +338,30 @@ impl McpTool for QueryRecentChangesHandler {
.rev() .rev()
.filter(|c| { .filter(|c| {
if let Some(ns) = &req.namespace if let Some(ns) = &req.namespace
&& !c.namespace.eq_ignore_ascii_case(ns) { && !c.namespace.eq_ignore_ascii_case(ns)
return false; {
} return false;
}
if let Some(repo) = &req.repo_name if let Some(repo) = &req.repo_name
&& c.repo_name && c.repo_name
.as_ref() .as_ref()
.map(|rn| !rn.eq_ignore_ascii_case(repo)) .map(|rn| !rn.eq_ignore_ascii_case(repo))
.unwrap_or(true) .unwrap_or(true)
{ {
return false; return false;
} }
if let Some(vcs) = &req.vcs_type if let Some(vcs) = &req.vcs_type
&& !c.effective_vcs().eq_ignore_ascii_case(vcs) { && !c.effective_vcs().eq_ignore_ascii_case(vcs)
return false; {
} return false;
}
true true
}) })
.skip(offset) .skip(offset)
.take(limit) .take(limit)
.cloned() .cloned()
.collect(); .collect();
Ok::<String, crate::error::AppError>(serde_json::to_string(&filtered)?) Ok::<String, crate::error::AppError>(serde_yaml::to_string(&filtered)?)
})?; })?;
Ok(data) Ok(data)
} }
@@ -464,10 +467,11 @@ impl McpTool for DecisionsHandler {
&& let Some(s_pos) = adrs && let Some(s_pos) = adrs
.iter() .iter()
.position(|a| a.id.eq_ignore_ascii_case(superseded_id)) .position(|a| a.id.eq_ignore_ascii_case(superseded_id))
&& s_pos != pos { && s_pos != pos
adrs[s_pos].status = "superseded".to_string(); {
adrs_to_index.push(adrs[s_pos].clone()); adrs[s_pos].status = "superseded".to_string();
} adrs_to_index.push(adrs[s_pos].clone());
}
let a = &mut adrs[pos]; let a = &mut adrs[pos];
if let Some(t) = req.title { if let Some(t) = req.title {
@@ -575,7 +579,7 @@ impl McpTool for DecisionsHandler {
.collect(); .collect();
if include_body { if include_body {
Ok::<String, crate::error::AppError>(serde_json::to_string(&filtered)?) Ok::<String, crate::error::AppError>(serde_yaml::to_string(&filtered)?)
} else { } else {
let compact: Vec<_> = filtered let compact: Vec<_> = filtered
.iter() .iter()
@@ -592,7 +596,7 @@ impl McpTool for DecisionsHandler {
}) })
}) })
.collect(); .collect();
Ok::<String, crate::error::AppError>(serde_json::to_string(&compact)?) Ok::<String, crate::error::AppError>(serde_yaml::to_string(&compact)?)
} }
})?; })?;
Ok(data) Ok(data)
@@ -738,7 +742,7 @@ impl McpTool for TechDebtHandler {
}), }),
}) })
.collect(); .collect();
let mut json_str = serde_json::to_string(&filtered)?; let mut json_str = serde_yaml::to_string(&filtered)?;
if let Some(max_t) = req.max_tokens { if let Some(max_t) = req.max_tokens {
let char_limit = max_t * 4; let char_limit = max_t * 4;
if json_str.len() > char_limit { if json_str.len() > char_limit {
@@ -1273,20 +1277,23 @@ impl McpTool for ManageCheckpointHandler {
} }
if let Ok(graph_content) = std::fs::read_to_string(target_dir.join("graph.json")) if let Ok(graph_content) = std::fs::read_to_string(target_dir.join("graph.json"))
&& let Ok(graph) = serde_json::from_str(&graph_content) { && let Ok(graph) = serde_json::from_str(&graph_content)
state.graph.modify(|g| *g = graph); {
} state.graph.modify(|g| *g = graph);
}
if let Ok(tasks_content) = std::fs::read_to_string(target_dir.join("tasks.json")) if let Ok(tasks_content) = std::fs::read_to_string(target_dir.join("tasks.json"))
&& let Ok(tasks) = serde_json::from_str(&tasks_content) { && let Ok(tasks) = serde_json::from_str(&tasks_content)
state.project.tasks.modify(|t| *t = tasks); {
} state.project.tasks.modify(|t| *t = tasks);
}
if let Ok(debts_content) = if let Ok(debts_content) =
std::fs::read_to_string(target_dir.join("tech_debts.json")) std::fs::read_to_string(target_dir.join("tech_debts.json"))
&& let Ok(debts) = serde_json::from_str(&debts_content) { && let Ok(debts) = serde_json::from_str(&debts_content)
state.code.tech_debts.modify(|d| *d = debts); {
} state.code.tech_debts.modify(|d| *d = debts);
}
Ok(format!("Checkpoint '{}' restored successfully.", name)) Ok(format!("Checkpoint '{}' restored successfully.", name))
} }
@@ -1296,16 +1303,17 @@ impl McpTool for ManageCheckpointHandler {
if let Ok(entries) = std::fs::read_dir(&checkpoints_dir) { if let Ok(entries) = std::fs::read_dir(&checkpoints_dir) {
for entry in entries.flatten() { for entry in entries.flatten() {
if entry.path().is_dir() if entry.path().is_dir()
&& let Some(n) = entry.file_name().to_str() { && let Some(n) = entry.file_name().to_str()
list.push(serde_json::json!({"type": "checkpoint", "name": n})); {
} list.push(serde_json::json!({"type": "checkpoint", "name": n}));
}
} }
} }
let snaps = state.project.snapshots.read_with(|snaps| snaps.clone()); let snaps = state.project.snapshots.read_with(|snaps| snaps.clone());
for s in snaps { for s in snaps {
list.push(serde_json::json!({"type": "snapshot", "id": s.id, "description": s.description, "namespace": s.namespace})); list.push(serde_json::json!({"type": "snapshot", "id": s.id, "description": s.description, "namespace": s.namespace}));
} }
Ok(serde_json::to_string_pretty(&list)?) Ok(serde_yaml::to_string(&list)?)
} }
CheckpointAction::Delete => { CheckpointAction::Delete => {
let name = req.name_or_id.ok_or_else(|| { let name = req.name_or_id.ok_or_else(|| {
@@ -1427,7 +1435,7 @@ impl McpTool for QueryLineageHandler {
"timeline": timeline "timeline": timeline
}); });
Ok(serde_json::to_string_pretty(&res)?) Ok(serde_yaml::to_string(&res)?)
} }
} }
@@ -1467,9 +1475,10 @@ impl McpTool for GetNextActionableTasksHandler {
if let Some(branch) = &req.git_branch if let Some(branch) = &req.git_branch
&& let Some(tb) = &task.git_branch && let Some(tb) = &task.git_branch
&& tb != branch { && tb != branch
continue; {
} continue;
}
let unblocked = task.dependencies.is_empty() let unblocked = task.dependencies.is_empty()
|| task.dependencies.iter().all(|d| completed_ids.contains(d)); || task.dependencies.iter().all(|d| completed_ids.contains(d));
@@ -1486,7 +1495,7 @@ impl McpTool for GetNextActionableTasksHandler {
"tasks": actionable "tasks": actionable
}); });
Ok(serde_json::to_string_pretty(&res)?) Ok(serde_yaml::to_string(&res)?)
} }
} }
@@ -1541,9 +1550,10 @@ impl McpTool for HypothesesHandler {
.into_iter() .into_iter()
.filter(|h| { .filter(|h| {
if let Some(tid) = &req.task_id if let Some(tid) = &req.task_id
&& h.task_id.as_ref() != Some(tid) { && h.task_id.as_ref() != Some(tid)
return false; {
} return false;
}
if let Some(q) = &req.query { if let Some(q) = &req.query {
let lq = q.to_lowercase(); let lq = q.to_lowercase();
return h.hypothesis.to_lowercase().contains(&lq) return h.hypothesis.to_lowercase().contains(&lq)
@@ -1555,7 +1565,7 @@ impl McpTool for HypothesesHandler {
}) })
.collect(); .collect();
Ok(serde_json::to_string_pretty(&filtered)?) Ok(serde_yaml::to_string(&filtered)?)
} }
} }
} }
@@ -1634,7 +1644,7 @@ impl McpTool for GetPreflightContextHandler {
"recent_activities": recent_activities "recent_activities": recent_activities
}); });
Ok(serde_json::to_string_pretty(&preflight)?) Ok(serde_yaml::to_string(&preflight)?)
} }
} }
@@ -1725,24 +1735,28 @@ impl McpTool for AgentSignalsHandler {
.iter() .iter()
.filter(|s| { .filter(|s| {
if let Some(ttl) = s.ttl_seconds if let Some(ttl) = s.ttl_seconds
&& now > s.timestamp + ttl { && now > s.timestamp + ttl
return false; {
} return false;
}
if let Some(sender) = &req.sender if let Some(sender) = &req.sender
&& s.sender.to_lowercase() != sender.to_lowercase() { && s.sender.to_lowercase() != sender.to_lowercase()
return false; {
} return false;
}
if let Some(st) = &req.signal_type if let Some(st) = &req.signal_type
&& s.signal_type.to_lowercase() != st.to_lowercase() { && s.signal_type.to_lowercase() != st.to_lowercase()
return false; {
} return false;
}
true true
}) })
.take(req.limit.unwrap_or(20)).cloned() .take(req.limit.unwrap_or(20))
.cloned()
.collect::<Vec<_>>() .collect::<Vec<_>>()
}); });
Ok(serde_json::to_string_pretty(&filtered)?) Ok(serde_yaml::to_string(&filtered)?)
} }
} }
} }
@@ -1985,8 +1999,8 @@ mod tests {
.await .await
.map_err(|e| crate::error::AppError::Internal(e.to_string())) .map_err(|e| crate::error::AppError::Internal(e.to_string()))
.unwrap(); .unwrap();
let uuid_start = debt_list.find("id\":\"").unwrap() + 5; let debt_list_val: serde_json::Value = serde_yaml::from_str(&debt_list).unwrap();
let uuid = &debt_list[uuid_start..uuid_start + 36]; let uuid = debt_list_val[0]["id"].as_str().unwrap();
let resolve_debt = TechDebtHandler; let resolve_debt = TechDebtHandler;
resolve_debt resolve_debt
+1 -1
View File
@@ -60,7 +60,7 @@ impl McpTool for HandoffMemosHandler {
} }
}) })
.collect(); .collect();
Ok::<String, crate::error::AppError>(serde_json::to_string(&filtered)?) Ok::<String, crate::error::AppError>(serde_yaml::to_string(&filtered)?)
})?; })?;
Ok(data) Ok(data)
} }
+9 -8
View File
@@ -245,11 +245,11 @@ pub fn recalculate_milestones(state: &MemoryState) -> Vec<String> {
&& (t.status == "in_progress" || t.status == "active") && (t.status == "in_progress" || t.status == "active")
})) }))
&& !m.status.eq_ignore_ascii_case("in_progress") && !m.status.eq_ignore_ascii_case("in_progress")
&& !m.status.eq_ignore_ascii_case("completed") && !m.status.eq_ignore_ascii_case("completed")
{ {
m.status = "in_progress".to_string(); m.status = "in_progress".to_string();
updated.push(m.id.clone()); updated.push(m.id.clone());
} }
} }
}); });
@@ -287,9 +287,10 @@ pub async fn reconcile_commit_or_code_change(
return true; return true;
} }
if let (Some(n1), Some(n2)) = (adr_numeric_id(&adr.id), adr_numeric_id(cand)) if let (Some(n1), Some(n2)) = (adr_numeric_id(&adr.id), adr_numeric_id(cand))
&& n1 == n2 { && n1 == n2
return true; {
} return true;
}
false false
}); });
+7 -7
View File
@@ -50,7 +50,6 @@ impl McpTool for TasksHandler {
priority: req.priority, priority: req.priority,
assigned_agent: req.assigned_agent, assigned_agent: req.assigned_agent,
verification_command: req.verification_command, verification_command: req.verification_command,
..Default::default()
}; };
let idx = state.get_search_index().await; let idx = state.get_search_index().await;
drop(idx.index_task(&task)); drop(idx.index_task(&task));
@@ -297,12 +296,12 @@ impl McpTool for TasksHandler {
_ => serde_json::json!({ "id": t.id, "title": t.title, "status": t.status, "description": t.description, "git_branch": t.git_branch }), _ => serde_json::json!({ "id": t.id, "title": t.title, "status": t.status, "description": t.description, "git_branch": t.git_branch }),
}) })
.collect(); .collect();
let mut json_str = serde_json::to_string(&filtered)?; let mut json_str = serde_yaml::to_string(&filtered)?;
if let Some(max_t) = req.max_tokens { if let Some(max_t) = req.max_tokens {
let char_limit = max_t * 4; let char_limit = max_t * 4;
while json_str.len() > char_limit && !filtered.is_empty() { while json_str.len() > char_limit && !filtered.is_empty() {
filtered.pop(); filtered.pop();
json_str = serde_json::to_string(&filtered)?; json_str = serde_yaml::to_string(&filtered)?;
} }
} }
Ok::<String, crate::error::AppError>(json_str) Ok::<String, crate::error::AppError>(json_str)
@@ -479,9 +478,10 @@ impl McpTool for MilestonesHandler {
m.status = status.clone(); m.status = status.clone();
if (status.eq_ignore_ascii_case("completed") if (status.eq_ignore_ascii_case("completed")
|| status.eq_ignore_ascii_case("done")) || status.eq_ignore_ascii_case("done"))
&& m.completed_at.is_none() { && m.completed_at.is_none()
m.completed_at = Some(crate::handlers::utils::now_secs()); {
} m.completed_at = Some(crate::handlers::utils::now_secs());
}
if let Some(task_ids) = &req.task_ids { if let Some(task_ids) = &req.task_ids {
m.task_ids = task_ids.clone(); m.task_ids = task_ids.clone();
if let Some(deliverables) = &req.deliverables { if let Some(deliverables) = &req.deliverables {
@@ -514,7 +514,7 @@ impl McpTool for MilestonesHandler {
} }
}) })
.collect(); .collect();
Ok::<String, crate::error::AppError>(serde_json::to_string(&filtered)?) Ok::<String, crate::error::AppError>(serde_yaml::to_string(&filtered)?)
})?; })?;
Ok(data) Ok(data)
} }
+15 -111
View File
@@ -191,10 +191,9 @@ pub fn html_to_markdown(html: &str) -> String {
out.push_str("* "); out.push_str("* ");
} }
} }
"/li" "/li" if !in_cell => {
if !in_cell => { out.push('\n');
out.push('\n'); }
}
_ => {} _ => {}
} }
} else if c == '&' { } else if c == '&' {
@@ -510,7 +509,8 @@ pub async fn process_clipboard_snapshot(state: Arc<MemoryState>) {
.search_index .search_index
.read() .read()
.await .await
.index_clipboard_image(&doc_id, &path_str, text); .index_clipboard_image(&doc_id, &path_str, text)
.await;
} }
let cached = crate::state::CachedClipboardImage { let cached = crate::state::CachedClipboardImage {
@@ -567,9 +567,10 @@ pub async fn process_clipboard_snapshot(state: Arc<MemoryState>) {
let mut cache = state.clipboard_cache.write().await; let mut cache = state.clipboard_cache.write().await;
if let Some(ref prev) = cache.last_text if let Some(ref prev) = cache.last_text
&& prev.text == cached.text { && prev.text == cached.text
return; {
} return;
}
cache.last_text = Some(cached.clone()); cache.last_text = Some(cached.clone());
cache cache
.history .history
@@ -758,7 +759,7 @@ impl McpTool for ClipboardHandler {
); );
if let Some(img) = item { if let Some(img) = item {
Ok(serde_json::to_string_pretty(&img)?) Ok(serde_yaml::to_string(&img)?)
} else { } else {
Ok(json!({ Ok(json!({
"status": "no_image_in_clipboard", "status": "no_image_in_clipboard",
@@ -786,7 +787,7 @@ impl McpTool for ClipboardHandler {
state.record_activity("clipboard", "Retrieved text from clipboard cache", None); state.record_activity("clipboard", "Retrieved text from clipboard cache", None);
if let Some(txt) = item { if let Some(txt) = item {
Ok(serde_json::to_string_pretty(&txt)?) Ok(serde_yaml::to_string(&txt)?)
} else { } else {
Ok(json!({ Ok(json!({
"text": "", "text": "",
@@ -818,7 +819,7 @@ impl McpTool for ClipboardHandler {
}; };
state.record_activity("clipboard", "Viewed clipboard history ring buffer", None); state.record_activity("clipboard", "Viewed clipboard history ring buffer", None);
Ok(serde_json::to_string_pretty(&history)?) Ok(serde_yaml::to_string(&history)?)
} }
ClipboardAction::Clear => { ClipboardAction::Clear => {
tokio::task::spawn_blocking(|| { tokio::task::spawn_blocking(|| {
@@ -842,73 +843,7 @@ impl McpTool for ClipboardHandler {
}) })
.to_string()) .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_json::to_string_pretty(&Value::Object(
out,
))?)
}
ClipboardAction::Write => { ClipboardAction::Write => {
let text_opt = req.text; let text_opt = req.text;
let image_path_opt = req.image_path; let image_path_opt = req.image_path;
@@ -1026,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_json::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_json::from_str(&result).unwrap();
assert!(parsed.is_object());
}
#[test] #[test]
fn test_no_subprocess_clipboard_regression() { fn test_no_subprocess_clipboard_regression() {
@@ -1175,7 +1079,7 @@ mod tests {
.execute(json!({ "action": "image" }), Arc::clone(&state)) .execute(json!({ "action": "image" }), Arc::clone(&state))
.await .await
.unwrap(); .unwrap();
let img_val: Value = serde_json::from_str(&img_res_str).unwrap(); let img_val: Value = serde_yaml::from_str(&img_res_str).unwrap();
assert_eq!(img_val["file_path"], "C:\\tmp\\image_b.jpg"); assert_eq!(img_val["file_path"], "C:\\tmp\\image_b.jpg");
assert_eq!(img_val["file_path_wsl"], "/mnt/c/tmp/image_b.jpg"); assert_eq!(img_val["file_path_wsl"], "/mnt/c/tmp/image_b.jpg");
assert_eq!(img_val["width"], 1200); assert_eq!(img_val["width"], 1200);
@@ -1188,7 +1092,7 @@ mod tests {
.execute(json!({ "action": "text" }), Arc::clone(&state)) .execute(json!({ "action": "text" }), Arc::clone(&state))
.await .await
.unwrap(); .unwrap();
let text_val: Value = serde_json::from_str(&text_res_str).unwrap(); let text_val: Value = serde_yaml::from_str(&text_res_str).unwrap();
assert_eq!(text_val["text"], "Some random stackoverflow URL"); assert_eq!(text_val["text"], "Some random stackoverflow URL");
// Action 'history' MUST show both items // Action 'history' MUST show both items
@@ -1196,7 +1100,7 @@ mod tests {
.execute(json!({ "action": "history" }), Arc::clone(&state)) .execute(json!({ "action": "history" }), Arc::clone(&state))
.await .await
.unwrap(); .unwrap();
let hist_val: Value = serde_json::from_str(&hist_res_str).unwrap(); let hist_val: Value = serde_yaml::from_str(&hist_res_str).unwrap();
let history = hist_val.as_array().unwrap(); let history = hist_val.as_array().unwrap();
assert!(history.len() >= 4); assert!(history.len() >= 4);
} }
+3 -3
View File
@@ -122,7 +122,7 @@ impl McpTool for SnippetsHandler {
.total_cmp(&a["score"].as_f64().unwrap_or(0.0)) .total_cmp(&a["score"].as_f64().unwrap_or(0.0))
}); });
scored.truncate(10); scored.truncate(10);
Ok(serde_json::to_string_pretty(&scored)?) Ok(serde_yaml::to_string(&scored)?)
} else { } else {
let data = state.code.snippets.read_with(|snippets| { let data = state.code.snippets.read_with(|snippets| {
let results: Vec<_> = snippets let results: Vec<_> = snippets
@@ -153,7 +153,7 @@ impl McpTool for SnippetsHandler {
}) })
}) })
.collect::<Vec<_>>(); .collect::<Vec<_>>();
serde_json::to_string_pretty(&results) serde_yaml::to_string(&results)
})?; })?;
Ok(data) Ok(data)
} }
@@ -359,7 +359,7 @@ impl McpTool for SemanticCodeSearchHandler {
); );
if let Ok(summary) = state if let Ok(summary) = state
.ollama .ollama
.generate(&prompt, None, Some("Respond clearly and concisely.")) .generate(&prompt, None, Some("Respond clearly and concisely."), None)
.await .await
{ {
out.push_str("\n\n--- Local GraphRAG Summary ---\n"); out.push_str("\n\n--- Local GraphRAG Summary ---\n");
+2 -2
View File
@@ -163,7 +163,7 @@ fn extract_chunks_with_parent(
node: Node, node: Node,
code: &str, code: &str,
chunks: &mut Vec<(String, String, String)>, chunks: &mut Vec<(String, String, String)>,
ext: &str, _ext: &str,
parent_scope: Option<&str>, parent_scope: Option<&str>,
depth: usize, depth: usize,
) { ) {
@@ -229,7 +229,7 @@ fn extract_chunks_with_parent(
} else { } else {
let mut cursor = node.walk(); let mut cursor = node.walk();
for child in node.named_children(&mut cursor) { for child in node.named_children(&mut cursor) {
extract_chunks_with_parent(child, code, chunks, ext, current_scope, depth + 1); extract_chunks_with_parent(child, code, chunks, _ext, current_scope, depth + 1);
} }
} }
} }
+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) ## 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. * **`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`). - `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`).
+68 -62
View File
@@ -107,9 +107,10 @@ pub async fn ttl_sweeper_worker(state: Arc<MemoryState>) {
state.project.tasks.read_with(|tasks| { state.project.tasks.read_with(|tasks| {
for t in tasks.iter() { for t in tasks.iter() {
if let Some(exp) = t.expires_at if let Some(exp) = t.expires_at
&& t.is_active() { && t.is_active()
next_expiry = Some(next_expiry.map_or(exp, |curr| curr.min(exp))); {
} next_expiry = Some(next_expiry.map_or(exp, |curr| curr.min(exp)));
}
} }
}); });
@@ -140,7 +141,7 @@ pub async fn ttl_sweeper_worker(state: Arc<MemoryState>) {
let sleep_duration = match next_expiry { let sleep_duration = match next_expiry {
Some(exp) if exp > now => { Some(exp) if exp > now => {
let diff = exp - now; let diff = exp - now;
std::time::Duration::from_secs(diff.min(60).max(1)) std::time::Duration::from_secs(diff.clamp(1, 60))
} }
Some(_) => std::time::Duration::from_millis(50), Some(_) => std::time::Duration::from_millis(50),
None => std::time::Duration::from_secs(60), None => std::time::Duration::from_secs(60),
@@ -161,11 +162,13 @@ pub async fn ttl_sweeper_worker(state: Arc<MemoryState>) {
state.project.tasks.modify(|tasks| { state.project.tasks.modify(|tasks| {
for t in tasks.iter_mut() { for t in tasks.iter_mut() {
if let Some(exp) = t.expires_at if let Some(exp) = t.expires_at
&& exp <= now && t.is_active() { && exp <= now
t.status = "expired".to_string(); && t.is_active()
t.updated_at = now; {
expired_tasks.push(t.id.clone()); t.status = "expired".to_string();
} t.updated_at = now;
expired_tasks.push(t.id.clone());
}
} }
}); });
@@ -249,27 +252,28 @@ pub async fn condense_graph_worker(state: Arc<MemoryState>) {
}); });
if let Some((content, names)) = snippet_condensation if let Some((content, names)) = snippet_condensation
&& !content.is_empty() { && !content.is_empty()
let name = format!("Snippet History {}", now); {
state.modify_graph(|graph| { let name = format!("Snippet History {}", now);
graph.entities.insert( state.modify_graph(|graph| {
name.clone(), graph.entities.insert(
crate::models::Entity { name.clone(),
name: name.clone(), crate::models::Entity {
entity_type: "Historical Summary".to_string(), name: name.clone(),
observations: vec![content], entity_type: "Historical Summary".to_string(),
namespace: crate::models::default_namespace(), observations: vec![content],
git_branch: None, namespace: crate::models::default_namespace(),
..Default::default() git_branch: None,
}, ..Default::default()
); },
}); );
let name_set: std::collections::HashSet<String> = names.into_iter().collect(); });
state.code.snippets.modify(|snippets| { let name_set: std::collections::HashSet<String> = names.into_iter().collect();
snippets.retain(|s| !name_set.contains(&s.name)); state.code.snippets.modify(|snippets| {
}); snippets.retain(|s| !name_set.contains(&s.name));
tracing::info!("Condensed snippets into Historical Summary."); });
} tracing::info!("Condensed snippets into Historical Summary.");
}
} }
} }
@@ -308,6 +312,7 @@ pub async fn memory_consolidation_worker(state: Arc<MemoryState>) {
&prompt, &prompt,
None, None,
Some("You are a helpful JSON-only data deduplication assistant. Output only JSON."), Some("You are a helpful JSON-only data deduplication assistant. Output only JSON."),
Some("json"),
) )
.await .await
{ {
@@ -318,36 +323,37 @@ pub async fn memory_consolidation_worker(state: Arc<MemoryState>) {
.trim_end_matches("```") .trim_end_matches("```")
.trim(); .trim();
if let Ok(duplicates) = serde_json::from_str::<Vec<String>>(cleaned) if let Ok(duplicates) = serde_json::from_str::<Vec<String>>(cleaned)
&& duplicates.len() == 2 { && duplicates.len() == 2
let e1_name = &duplicates[0]; {
let e2_name = &duplicates[1]; let e1_name = &duplicates[0];
let e2_name = &duplicates[1];
if e1_name != e2_name { if e1_name != e2_name {
tracing::info!( tracing::info!(
"Memory Consolidation Daemon: Merging '{}' into '{}'", "Memory Consolidation Daemon: Merging '{}' into '{}'",
e2_name, e2_name,
e1_name e1_name
); );
state.modify_graph(|g| { state.modify_graph(|g| {
if let Some(mut e2) = g.entities.remove(e2_name) { if let Some(mut e2) = g.entities.remove(e2_name) {
if let Some(e1) = g.entities.get_mut(e1_name) { if let Some(e1) = g.entities.get_mut(e1_name) {
e1.observations.append(&mut e2.observations); e1.observations.append(&mut e2.observations);
} else { } else {
g.entities.insert(e2_name.clone(), e2); g.entities.insert(e2_name.clone(), e2);
}
} }
}
for rel in g.relations.iter_mut() { for rel in g.relations.iter_mut() {
if rel.from == *e2_name { if rel.from == *e2_name {
rel.from = e1_name.clone(); rel.from = e1_name.clone();
}
if rel.to == *e2_name {
rel.to = e1_name.clone();
}
} }
}); if rel.to == *e2_name {
} rel.to = e1_name.clone();
}
}
});
} }
}
} }
} }
} }
@@ -465,13 +471,12 @@ pub async fn run_server(state: Arc<MemoryState>) -> Result<(), Box<dyn std::erro
event.payload.get("action").and_then(|a| a.as_str()), event.payload.get("action").and_then(|a| a.as_str()),
event.payload.get("target").and_then(|t| t.as_str()), event.payload.get("target").and_then(|t| t.as_str()),
event.payload.get("status").and_then(|s| s.as_str()), event.payload.get("status").and_then(|s| s.as_str()),
) { )
if (status == "authorized" || status == "blocked") && (status == "authorized" || status == "blocked")
&& let Some(addr) = subscribers.remove(&(action.to_string(), target.to_string())) { && let Some(addr) = subscribers.remove(&(action.to_string(), target.to_string())) {
let response = if status == "authorized" { b"APPROVED" } else { b"REJECTED" }; let response = if status == "authorized" { b"APPROVED" } else { b"REJECTED" };
let _ = socket.send_to(response, addr).await; let _ = socket.send_to(response, addr).await;
} }
}
} }
} }
} }
@@ -803,7 +808,7 @@ mod tests {
#[test] #[test]
fn test_cli_parsing_default() { fn test_cli_parsing_default() {
let cli = Cli::try_parse_from(&["mcp-memory-server"]).unwrap(); let cli = Cli::try_parse_from(["mcp-memory-server"]).unwrap();
assert!(cli.command.is_none()); assert!(cli.command.is_none());
assert!(!cli.exit); assert!(!cli.exit);
assert!(!cli.restart); assert!(!cli.restart);
@@ -811,7 +816,7 @@ mod tests {
#[test] #[test]
fn test_cli_parsing_exit_and_target() { fn test_cli_parsing_exit_and_target() {
let cli = Cli::try_parse_from(&[ let cli = Cli::try_parse_from([
"mcp-memory-server", "mcp-memory-server",
"--exit", "--exit",
"--target", "--target",
@@ -824,7 +829,7 @@ mod tests {
#[test] #[test]
fn test_cli_parsing_gate_set() { fn test_cli_parsing_gate_set() {
let cli = Cli::try_parse_from(&[ let cli = Cli::try_parse_from([
"mcp-memory-server", "mcp-memory-server",
"gate", "gate",
"set", "set",
@@ -860,7 +865,7 @@ mod tests {
#[test] #[test]
fn test_cli_parsing_gate_verify() { fn test_cli_parsing_gate_verify() {
let cli = Cli::try_parse_from(&[ let cli = Cli::try_parse_from([
"mcp-memory-server", "mcp-memory-server",
"gate", "gate",
"verify", "verify",
@@ -925,6 +930,7 @@ mod tests {
} }
#[tokio::test] #[tokio::test]
#[allow(clippy::await_holding_lock)]
async fn test_run_server_graceful_shutdown() { async fn test_run_server_graceful_shutdown() {
let _lock = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner()); let _lock = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
let temp_dir = tempfile::tempdir().unwrap(); let temp_dir = tempfile::tempdir().unwrap();
+12 -10
View File
@@ -13,7 +13,6 @@ pub enum ChangeKind {
Renamed, Renamed,
} }
#[derive(Debug, Clone, Serialize, Deserialize, Default)] #[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct CodeChange { pub struct CodeChange {
pub timestamp: u64, pub timestamp: u64,
@@ -55,16 +54,18 @@ impl CodeChange {
return vcs.as_str(); return vcs.as_str();
} }
if let Some(rev) = self.revision.as_deref().or(self.git_commit.as_deref()) if let Some(rev) = self.revision.as_deref().or(self.git_commit.as_deref())
&& rev.starts_with('r') && rev[1..].chars().all(|c| c.is_ascii_digit()) { && rev.starts_with('r')
return "svn"; && rev[1..].chars().all(|c| c.is_ascii_digit())
} {
return "svn";
}
if let Some(br) = self.branch.as_deref().or(self.git_branch.as_deref()) if let Some(br) = self.branch.as_deref().or(self.git_branch.as_deref())
&& (br.eq_ignore_ascii_case("trunk") && (br.eq_ignore_ascii_case("trunk")
|| br.starts_with("branches/") || br.starts_with("branches/")
|| br.starts_with("tags/")) || br.starts_with("tags/"))
{ {
return "svn"; return "svn";
} }
"git" "git"
} }
@@ -262,9 +263,10 @@ impl KnowledgeGraph {
HashMap::with_capacity(self.relations.len() * 2); HashMap::with_capacity(self.relations.len() * 2);
for rel in &self.relations { for rel in &self.relations {
if let Some(rf) = relation_filter if let Some(rf) = relation_filter
&& rel.relation_type != rf { && rel.relation_type != rf
continue; {
} continue;
}
adj.entry(rel.from.as_str()).or_default().push(( adj.entry(rel.from.as_str()).or_default().push((
rel.to.as_str(), rel.to.as_str(),
rel.relation_type.as_str(), rel.relation_type.as_str(),
+5
View File
@@ -27,6 +27,8 @@ struct GenerateRequest<'a> {
options: Option<serde_json::Value>, options: Option<serde_json::Value>,
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
keep_alive: Option<&'a str>, keep_alive: Option<&'a str>,
#[serde(skip_serializing_if = "Option::is_none")]
format: Option<&'a str>,
} }
#[derive(Deserialize)] #[derive(Deserialize)]
@@ -113,6 +115,7 @@ impl OllamaClient {
prompt: &str, prompt: &str,
model_override: Option<&str>, model_override: Option<&str>,
system: Option<&str>, system: Option<&str>,
format: Option<&str>,
) -> Result<String, AppError> { ) -> Result<String, AppError> {
let model = model_override.unwrap_or(&self.coder_model); let model = model_override.unwrap_or(&self.coder_model);
let url = format!("{}/api/generate", self.base_url.trim_end_matches('/')); let url = format!("{}/api/generate", self.base_url.trim_end_matches('/'));
@@ -128,6 +131,7 @@ impl OllamaClient {
"num_predict": 4096 // Give reasoning models plenty of output room "num_predict": 4096 // Give reasoning models plenty of output room
})), })),
keep_alive: Some("1h"), keep_alive: Some("1h"),
format,
}; };
let res = self let res = self
@@ -172,6 +176,7 @@ impl OllamaClient {
"num_predict": 1024 "num_predict": 1024
})), })),
keep_alive: Some("1h"), keep_alive: Some("1h"),
format: None,
}; };
let res = self let res = self
+2 -2
View File
@@ -1398,7 +1398,7 @@ mod tests {
let handler = MemoryHandler::new(state); let handler = MemoryHandler::new(state);
// 1. Verify invalid LLM requests fail gracefully with isError: true or structured response // 1. Verify invalid LLM requests fail gracefully with isError: true or structured response
for (tool_name, _tool) in &handler.tools { for tool_name in handler.tools.keys() {
let invalid_req = json!({ let invalid_req = json!({
"jsonrpc": "2.0", "jsonrpc": "2.0",
"id": 200, "id": 200,
@@ -1428,7 +1428,7 @@ mod tests {
("decisions", json!({"action": "query"})), ("decisions", json!({"action": "query"})),
("tech_debt", json!({"action": "list"})), ("tech_debt", json!({"action": "list"})),
("snippets", json!({"action": "search", "query": "test"})), ("snippets", json!({"action": "search", "query": "test"})),
("clipboard", json!({"action": "read"})), ("clipboard", json!({"action": "history"})),
("environment", json!({"action": "read_fingerprint"})), ("environment", json!({"action": "read_fingerprint"})),
("omni_search", json!({"query": "test"})), ("omni_search", json!({"query": "test"})),
("get_project_health", json!({})), ("get_project_health", json!({})),
+4 -3
View File
@@ -552,9 +552,10 @@ impl SearchService {
self.state.read_graph(|graph| { self.state.read_graph(|graph| {
for entity in graph.entities.values() { for entity in graph.entities.values() {
if let Some(ns) = filter_namespace if let Some(ns) = filter_namespace
&& entity.namespace != ns { && entity.namespace != ns
continue; {
} continue;
}
let obs = entity.observations.join("; "); let obs = entity.observations.join("; ");
let desc = format!("{}: {}", entity.entity_type, obs); let desc = format!("{}: {}", entity.entity_type, obs);
if let Some(ref emb) = entity.embedding { if let Some(ref emb) = entity.embedding {
+8 -9
View File
@@ -1,5 +1,6 @@
use crate::models::*; use crate::models::*;
use crate::search::MemoryIndex; use crate::search::MemoryIndex;
pub use crate::search::{SearchResult as UnifiedSearchResult, SearchService};
use crate::store::Store; use crate::store::Store;
use std::collections::HashMap; use std::collections::HashMap;
use std::path::PathBuf; use std::path::PathBuf;
@@ -87,9 +88,10 @@ impl ClipboardCacheState {
pub fn push_text(&mut self, text: CachedClipboardText) { pub fn push_text(&mut self, text: CachedClipboardText) {
if let Some(ref prev) = self.last_text if let Some(ref prev) = self.last_text
&& prev.text == text.text { && prev.text == text.text
return; {
} return;
}
self.last_text = Some(text.clone()); self.last_text = Some(text.clone());
self.history.push_front(ClipboardHistoryItem::Text(text)); self.history.push_front(ClipboardHistoryItem::Text(text));
if self.history.len() > 20 { if self.history.len() > 20 {
@@ -141,10 +143,9 @@ impl MemoryState {
pub fn new(base_dir_str: &str) -> Self { pub fn new(base_dir_str: &str) -> Self {
let is_in_memory = base_dir_str == ":memory:"; let is_in_memory = base_dir_str == ":memory:";
let base = std::path::PathBuf::from(base_dir_str); let base = std::path::PathBuf::from(base_dir_str);
if !is_in_memory if !is_in_memory && let Err(e) = std::fs::create_dir_all(&base) {
&& let Err(e) = std::fs::create_dir_all(&base) { tracing::error!("Failed to create store directory at {:?}: {}", base, e);
tracing::error!("Failed to create store directory at {:?}: {}", base, e); }
}
let db = crate::db::init_redb(&base); let db = crate::db::init_redb(&base);
@@ -575,5 +576,3 @@ mod tests {
assert!(activities_updated[0].timestamp >= activities_updated[1].timestamp); assert!(activities_updated[0].timestamp >= activities_updated[1].timestamp);
} }
} }
pub use crate::search::{SearchResult as UnifiedSearchResult, SearchService};
+6 -3
View File
@@ -34,9 +34,11 @@ static QUEUE_REGISTRY: std::sync::Mutex<Option<(Arc<Database>, DbWriteQueue)>> =
fn get_or_create_queue(db: Arc<Database>) -> DbWriteQueue { fn get_or_create_queue(db: Arc<Database>) -> DbWriteQueue {
let mut reg = QUEUE_REGISTRY.lock().unwrap_or_else(|e| e.into_inner()); let mut reg = QUEUE_REGISTRY.lock().unwrap_or_else(|e| e.into_inner());
if let Some((ref existing_db, ref queue)) = *reg if let Some((ref existing_db, ref queue)) = *reg
&& Arc::ptr_eq(existing_db, &db) && !queue.tx.is_closed() { && Arc::ptr_eq(existing_db, &db)
return queue.clone(); && !queue.tx.is_closed()
} {
return queue.clone();
}
let new_queue = DbWriteQueue::new(db.clone()); let new_queue = DbWriteQueue::new(db.clone());
*reg = Some((db, new_queue.clone())); *reg = Some((db, new_queue.clone()));
new_queue new_queue
@@ -458,6 +460,7 @@ impl<T: DeserializeOwned + Default + Serialize + Send + Sync + 'static> Store<T>
} }
} }
#[allow(clippy::type_complexity)]
fn prepare_batch( fn prepare_batch(
&self, &self,
new_snapshot: &T, new_snapshot: &T,
+7 -5
View File
@@ -172,8 +172,6 @@ pub enum SubgraphFormat {
pub struct GetSubgraphTool { pub struct GetSubgraphTool {
/// The root entity name to start the subgraph search from. /// The root entity name to start the subgraph search from.
pub root_entity: Option<String>, pub root_entity: Option<String>,
/// Legacy alias for root_entity.
pub root_node: Option<String>,
/// Maximum search depth (hops). Defaults to 2. /// Maximum search depth (hops). Defaults to 2.
pub depth: Option<u32>, pub depth: Option<u32>,
/// Output format: 'json' (raw entities and relations) or 'markdown_tree' (compact topology tree). Defaults to 'json'. /// Output format: 'json' (raw entities and relations) or 'markdown_tree' (compact topology tree). Defaults to 'json'.
@@ -612,6 +610,7 @@ pub enum HandoffMemoAction {
/// - 'leave': Post a handoff memo. Required: content. Optional: namespace. /// - 'leave': Post a handoff memo. Required: content. Optional: namespace.
/// - 'read': Inspect active memos. Optional: namespace. /// - 'read': Inspect active memos. Optional: namespace.
/// - 'clear': Clear memos. Optional: namespace, ids. /// - 'clear': Clear memos. Optional: namespace, ids.
///
/// Next steps on error: Check parameter requirements for 'leave' or 'clear' actions. /// Next steps on error: Check parameter requirements for 'leave' or 'clear' actions.
#[derive(Debug, Deserialize, Serialize, JsonSchema)] #[derive(Debug, Deserialize, Serialize, JsonSchema)]
pub struct HandoffMemosTool { pub struct HandoffMemosTool {
@@ -655,6 +654,7 @@ pub enum TaskAction {
/// - 'list': List active tasks. Optional: git_branch, summary_level ('compact'|'detailed'|'full'), max_tokens. /// - 'list': List active tasks. Optional: git_branch, summary_level ('compact'|'detailed'|'full'), max_tokens.
/// - 'set_criteria': Set acceptance criteria. Required: id, criteria (array of strings). /// - 'set_criteria': Set acceptance criteria. Required: id, criteria (array of strings).
/// - 'verify': Verify criteria met. Required: id. /// - 'verify': Verify criteria met. Required: id.
///
/// Next steps on error: Check required parameters or call list to verify task IDs. /// Next steps on error: Check required parameters or call list to verify task IDs.
#[derive(Debug, Deserialize, Serialize, JsonSchema)] #[derive(Debug, Deserialize, Serialize, JsonSchema)]
pub struct TasksTool { pub struct TasksTool {
@@ -719,6 +719,7 @@ pub enum MilestoneAction {
/// - 'add': Create milestone. Required: title. Optional: namespace. /// - 'add': Create milestone. Required: title. Optional: namespace.
/// - 'update': Update milestone status. Required: id, status. /// - 'update': Update milestone status. Required: id, status.
/// - 'list': List milestones. Optional: namespace. /// - 'list': List milestones. Optional: namespace.
///
/// Next steps on error: Provide required title for 'add' or id/status for 'update'. /// Next steps on error: Provide required title for 'add' or id/status for 'update'.
#[derive(Debug, Deserialize, Serialize, JsonSchema)] #[derive(Debug, Deserialize, Serialize, JsonSchema)]
pub struct MilestonesTool { pub struct MilestonesTool {
@@ -765,6 +766,7 @@ pub enum SnippetAction {
/// - 'search': Search snippets. Optional: query, tags, hybrid (boolean for BM25+vector search). /// - 'search': Search snippets. Optional: query, tags, hybrid (boolean for BM25+vector search).
/// - 'delete': Delete snippet. Required: id (or query) as snippet name. /// - 'delete': Delete snippet. Required: id (or query) as snippet name.
/// - 'tag': Tag snippet. Required: id (or query), tags (array of strings). /// - 'tag': Tag snippet. Required: id (or query), tags (array of strings).
///
/// Next steps on error: Ensure snippet name/query or id is provided. /// Next steps on error: Ensure snippet name/query or id is provided.
#[derive(Debug, Deserialize, Serialize, JsonSchema)] #[derive(Debug, Deserialize, Serialize, JsonSchema)]
pub struct SnippetsTool { pub struct SnippetsTool {
@@ -815,6 +817,7 @@ pub enum DecisionAction {
/// - 'query': Search ADRs. Optional: query, namespace. /// - 'query': Search ADRs. Optional: query, namespace.
/// - 'update': Update ADR status or implementation info. Required: id. Optional: status, git_commit, git_branch, task_id, context, decision, consequences, title. /// - 'update': Update ADR status or implementation info. Required: id. Optional: status, git_commit, git_branch, task_id, context, decision, consequences, title.
/// - 'delete': Remove ADR. Required: id. /// - 'delete': Remove ADR. Required: id.
///
/// Next steps on error: Provide title for 'log' or id for 'update'/'delete'. /// Next steps on error: Provide title for 'log' or id for 'update'/'delete'.
#[derive(Deserialize, Serialize, JsonSchema, Debug, Clone)] #[derive(Deserialize, Serialize, JsonSchema, Debug, Clone)]
pub struct DecisionsTool { pub struct DecisionsTool {
@@ -875,6 +878,7 @@ pub enum TechDebtAction {
/// - 'log': Record technical debt. Required: description. Optional: ideal_solution, git_commit, git_branch, symbol_references, line_range, namespace. /// - 'log': Record technical debt. Required: description. Optional: ideal_solution, git_commit, git_branch, symbol_references, line_range, namespace.
/// - 'resolve': Mark tech debt resolved. Required: id. /// - 'resolve': Mark tech debt resolved. Required: id.
/// - 'list': List tech debt items. Optional: include_resolved, namespace. /// - 'list': List tech debt items. Optional: include_resolved, namespace.
///
/// Next steps on error: Provide description for 'log' or valid ID for 'resolve'. /// Next steps on error: Provide description for 'log' or valid ID for 'resolve'.
#[derive(Debug, Deserialize, Serialize, JsonSchema)] #[derive(Debug, Deserialize, Serialize, JsonSchema)]
pub struct TechDebtTool { pub struct TechDebtTool {
@@ -963,6 +967,7 @@ pub enum EnvAction {
/// - 'log_requirement': Log environment variable requirement. Required: key. Optional: description, is_secret, namespace. /// - 'log_requirement': Log environment variable requirement. Required: key. Optional: description, is_secret, namespace.
/// - 'register': Register remote target environment. Required: name. Optional: url, description, requires_vpn, namespace. /// - 'register': Register remote target environment. Required: name. Optional: url, description, requires_vpn, namespace.
/// - 'get_details': Get full environment details. Optional: namespace. /// - 'get_details': Get full environment details. Optional: namespace.
///
/// Next steps on error: Provide key for 'log_requirement' or name for 'register'. /// Next steps on error: Provide key for 'log_requirement' or name for 'register'.
#[derive(Debug, Deserialize, Serialize, JsonSchema)] #[derive(Debug, Deserialize, Serialize, JsonSchema)]
pub struct EnvironmentTool { pub struct EnvironmentTool {
@@ -1007,8 +1012,6 @@ pub enum ClipboardAction {
History, History,
#[serde(alias = "clear", alias = "CLEAR", alias = "Clear")] #[serde(alias = "clear", alias = "CLEAR", alias = "Clear")]
Clear, Clear,
#[serde(alias = "read", alias = "READ", alias = "Read")]
Read,
#[serde(alias = "write", alias = "WRITE", alias = "Write")] #[serde(alias = "write", alias = "WRITE", alias = "Write")]
Write, Write,
} }
@@ -1019,7 +1022,6 @@ pub enum ClipboardAction {
/// - 'text': Get latest clipboard text (or normalized Markdown if HTML was copied). /// - 'text': Get latest clipboard text (or normalized Markdown if HTML was copied).
/// - 'history': View recent clipboard history ring buffer (images and text with timestamps). /// - 'history': View recent clipboard history ring buffer (images and text with timestamps).
/// - 'clear': Clear OS clipboard and memory cache. /// - '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. /// - '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", /// 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
+94 -97
View File
@@ -105,109 +105,106 @@ async fn trigger_autonomous_review(path: &Path, state: Arc<MemoryState>) {
// ADR-0109: Incremental Background AST Indexing & Differential Graph Updates // ADR-0109: Incremental Background AST Indexing & Differential Graph Updates
let ext = path.extension().and_then(|e| e.to_str()).unwrap_or(""); let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("");
if matches!(ext, "rs" | "ts" | "js" | "py" | "go" | "java" | "c" | "cpp") if matches!(ext, "rs" | "ts" | "js" | "py" | "go" | "java" | "c" | "cpp")
&& let Ok(content) = std::fs::read_to_string(path) { && let Ok(content) = std::fs::read_to_string(path)
let language = match ext { {
"rs" => Some(tree_sitter_rust::LANGUAGE), let language = match ext {
"ts" | "js" => Some(tree_sitter_typescript::LANGUAGE_TYPESCRIPT), "rs" => Some(tree_sitter_rust::LANGUAGE),
"py" => Some(tree_sitter_python::LANGUAGE), "ts" | "js" => Some(tree_sitter_typescript::LANGUAGE_TYPESCRIPT),
"java" => Some(tree_sitter_java::LANGUAGE), "py" => Some(tree_sitter_python::LANGUAGE),
"c" => Some(tree_sitter_c::LANGUAGE), "java" => Some(tree_sitter_java::LANGUAGE),
"cpp" => Some(tree_sitter_cpp::LANGUAGE), "c" => Some(tree_sitter_c::LANGUAGE),
"go" => Some(tree_sitter_go::LANGUAGE), "cpp" => Some(tree_sitter_cpp::LANGUAGE),
_ => None, "go" => Some(tree_sitter_go::LANGUAGE),
}; _ => None,
};
if let Some(lang) = language { if let Some(lang) = language {
let mut parser = tree_sitter::Parser::new(); let mut parser = tree_sitter::Parser::new();
if parser.set_language(&lang.into()).is_ok() if parser.set_language(&lang.into()).is_ok()
&& let Some(tree) = parser.parse(&content, None) { && let Some(tree) = parser.parse(&content, None)
let mut chunks = Vec::new(); {
crate::indexer::extract_chunks( let mut chunks = Vec::new();
tree.root_node(), crate::indexer::extract_chunks(tree.root_node(), &content, &mut chunks, ext);
&content, let file_str = path.to_string_lossy().to_string();
&mut chunks, let now = std::time::SystemTime::now()
ext, .duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_secs();
let chunks_count = chunks.len();
let file_str_clone = file_str.clone();
state.modify_graph(|g| {
// Ensure File entity exists
g.entities
.entry(file_str.clone())
.or_insert_with(|| crate::models::Entity {
name: file_str.clone(),
entity_type: "File".to_string(),
namespace: "global".to_string(),
file_path: Some(file_str.clone()),
created_at: Some(now),
updated_at: Some(now),
..Default::default()
});
for (chunk_name, chunk_code, chunk_desc) in chunks {
let symbol_name = format!("{}::{}", file_str, chunk_name);
let symbol_type = if chunk_desc.contains("struct") {
"DataStructure".to_string()
} else {
"McpTool".to_string()
};
g.entities.insert(
symbol_name.clone(),
crate::models::Entity {
name: symbol_name.clone(),
entity_type: symbol_type,
observations: vec![format!(
"AST definition: {} chars",
chunk_code.len()
)],
namespace: "global".to_string(),
file_path: Some(file_str.clone()),
created_at: Some(now),
updated_at: Some(now),
..Default::default()
},
); );
let file_str = path.to_string_lossy().to_string();
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_secs();
let chunks_count = chunks.len(); let rel = crate::models::Relation {
let file_str_clone = file_str.clone(); from: file_str.clone(),
state.modify_graph(|g| { to: symbol_name,
// Ensure File entity exists relation_type: "declares".to_string(),
g.entities.entry(file_str.clone()).or_insert_with(|| { namespace: "global".to_string(),
crate::models::Entity { ..Default::default()
name: file_str.clone(), };
entity_type: "File".to_string(), if !g.relations.contains(&rel) {
namespace: "global".to_string(), g.relations.push(rel);
file_path: Some(file_str.clone()), }
created_at: Some(now),
updated_at: Some(now),
..Default::default()
}
});
for (chunk_name, chunk_code, chunk_desc) in chunks {
let symbol_name = format!("{}::{}", file_str, chunk_name);
let symbol_type = if chunk_desc.contains("struct") {
"DataStructure".to_string()
} else {
"McpTool".to_string()
};
g.entities.insert(
symbol_name.clone(),
crate::models::Entity {
name: symbol_name.clone(),
entity_type: symbol_type,
observations: vec![format!(
"AST definition: {} chars",
chunk_code.len()
)],
namespace: "global".to_string(),
file_path: Some(file_str.clone()),
created_at: Some(now),
updated_at: Some(now),
..Default::default()
},
);
let rel = crate::models::Relation {
from: file_str.clone(),
to: symbol_name,
relation_type: "declares".to_string(),
namespace: "global".to_string(),
..Default::default()
};
if !g.relations.contains(&rel) {
g.relations.push(rel);
}
}
});
let _ = state.event_bus_tx.send(crate::state::GenericEvent {
topic: "ast:symbol_updated".to_string(),
session_id: None,
payload: serde_json::json!({
"file": file_str_clone,
"extension": ext,
"symbols_count": chunks_count,
}),
});
let _ = state.event_bus_tx.send(crate::state::GenericEvent {
topic: "resource:updated".to_string(),
session_id: None,
payload: serde_json::json!({
"uri": "memory://graph"
}),
});
} }
});
let _ = state.event_bus_tx.send(crate::state::GenericEvent {
topic: "ast:symbol_updated".to_string(),
session_id: None,
payload: serde_json::json!({
"file": file_str_clone,
"extension": ext,
"symbols_count": chunks_count,
}),
});
let _ = state.event_bus_tx.send(crate::state::GenericEvent {
topic: "resource:updated".to_string(),
session_id: None,
payload: serde_json::json!({
"uri": "memory://graph"
}),
});
} }
} }
}
info!( info!(
"Autonomous review & incremental AST index complete for {:?}", "Autonomous review & incremental AST index complete for {:?}",
+1 -2
View File
@@ -1,7 +1,6 @@
use image::DynamicImage;
#[test] #[test]
fn test_img() { fn test_img() {
let mut img = image::DynamicImage::new_rgb8(10, 10); let mut img = image::DynamicImage::new_rgb8(10, 10);
img.invert(); img.invert();
let img2 = img.adjust_contrast(20.0); let _img2 = img.adjust_contrast(20.0);
} }
+7 -4
View File
@@ -101,9 +101,10 @@ fn test_dashboard_route_parity() {
let mut registered_routes = HashSet::new(); let mut registered_routes = HashSet::new();
for part in setup_content.split(".route(") { for part in setup_content.split(".route(") {
let trimmed = part.trim_start(); let trimmed = part.trim_start();
if trimmed.starts_with('"') { #[allow(clippy::collapsible_if)]
if let Some(end_quote) = trimmed[1..].find('"') { if let Some(stripped) = trimmed.strip_prefix('"') {
let route = &trimmed[1..=end_quote]; if let Some(end_quote) = stripped.find('"') {
let route = &stripped[..end_quote];
registered_routes.insert(route.to_string()); registered_routes.insert(route.to_string());
} }
} }
@@ -119,8 +120,10 @@ fn test_dashboard_route_parity() {
let rest = &dashboard_content[start..]; let rest = &dashboard_content[start..];
let quote_char = dashboard_content[..start].chars().last(); let quote_char = dashboard_content[..start].chars().last();
let mut endpoint = String::new(); let mut endpoint = String::new();
#[allow(clippy::collapsible_if)]
if let Some(q) = quote_char { if let Some(q) = quote_char {
if q == '`' || q == '"' || q == '\'' { let is_quote = q == '`' || q == '"' || q == '\'';
if is_quote {
if let Some(close_idx) = rest.find(q) { if let Some(close_idx) = rest.find(q) {
let full_call = &rest[..close_idx]; let full_call = &rest[..close_idx];
let clean = if let Some(q_idx) = full_call.find('?') { let clean = if let Some(q_idx) = full_call.find('?') {