docs: synchronize documentation, agent rules, instructions, tools/list, and resources/list

- Document all 53 MCP tools, 9 passive MCP resources, and 5 workflow prompts
- Document 100% ADR implementation status and automated post-commit reconciliation engine
- Update and deploy agent-rules (mcp_memory_workflow.md) to Windows and WSL
- Fix dashboard live ADR tab refresh and Cache-Control headers
- Synchronize instructions.md across root, server embedded, Windows, and WSL MCP configs
This commit is contained in:
Riz Ashraf committed 2026-10-07 21:34:43 +01:00
1 parent 37fc811752
commit 3b08f45618
8 files changed
+493 -283

No files matched your search

+2 -2
View File
@@ -305,7 +305,7 @@ pub fn create_router(app_state: Arc<AppState>) -> Router {
let state_clone = app_state.handler.state.clone();
move || async move {
let json = state_clone.code.tech_debts.read_with(|items| serde_json::to_string(items).unwrap_or_else(|_| "[]".to_string()));
([(axum::http::header::CONTENT_TYPE, "application/json")], json)
([(axum::http::header::CONTENT_TYPE, "application/json"), (axum::http::header::CACHE_CONTROL, "no-cache, no-store, must-revalidate")], json)
}
}),
)
@@ -315,7 +315,7 @@ pub fn create_router(app_state: Arc<AppState>) -> Router {
let state_clone = app_state.handler.state.clone();
move || async move {
let json = state_clone.code.adrs.read_with(|items| serde_json::to_string(items).unwrap_or_else(|_| "[]".to_string()));
([(axum::http::header::CONTENT_TYPE, "application/json")], json)
([(axum::http::header::CONTENT_TYPE, "application/json"), (axum::http::header::CACHE_CONTROL, "no-cache, no-store, must-revalidate")], json)
}
}),
)
+3 -1
View File
@@ -72,7 +72,9 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
if instructions_src.exists() {
let _ = fs::copy(&instructions_src, win_dir.join("instructions.md"));
let _ = fs::copy(&instructions_src, wsl_dir.join("instructions.md"));
println!(" [OK] Synchronized instructions.md to Win and WSL");
let server_instructions = PathBuf::from(r"C:\Users\reazul.ashraf\workspace\rust\mcp-memory\server\src\instructions.md");
let _ = fs::copy(&instructions_src, server_instructions);
println!(" [OK] Synchronized instructions.md to Win, WSL, and server/src/instructions.md");
}
let _ = fs::remove_dir_all(&temp_dir);
+11 -4
View File
@@ -216,7 +216,7 @@ Type: ${entity.entity_type}`,
}
async function loadGraph() {
try {
const res = await fetch("/api/graph");
const res = await fetch("/api/graph", { cache: "no-store" });
const dataText = await res.text();
if (dataText === lastGraphJson && network) {
return;
@@ -459,7 +459,7 @@ function applyTaskFilters() {
}
async function loadTasks() {
try {
const res = await fetch("/api/tasks");
const res = await fetch("/api/tasks", { cache: "no-store" });
cachedTasks = await res.json();
applyTaskFilters();
} catch (err) {
@@ -689,6 +689,7 @@ function requestDomainRefresh(domain) {
graph: "graph-tab",
task: "task-tab",
techdebt: "techdebt-tab",
adrs: "adrs-tab",
snippets: "snippets-tab",
terminal: "terminal-tab",
ledger: "ledger-tab",
@@ -713,6 +714,9 @@ function requestDomainRefresh(domain) {
case "techdebt":
loadTechDebt();
break;
case "adrs":
loadADRs();
break;
case "snippets":
loadSnippets();
break;
@@ -739,7 +743,10 @@ function handleIncomingActivity(payload) {
category = (payload.category || payload.type || "").toUpperCase();
}
}
if (method === "notifications/resources/updated" || category === "GRAPH" || category === "DECISION") {
if (method === "notifications/resources/updated" || category === "GRAPH") {
requestDomainRefresh("graph");
} else if (category === "DECISION" || category === "ADR") {
requestDomainRefresh("adrs");
requestDomainRefresh("graph");
} else if (method === "notifications/task/completed" || category.startsWith("TASK")) {
requestDomainRefresh("task");
@@ -1124,7 +1131,7 @@ async function loadGenericList(endpoint, containerId, formatter, options) {
state.formatter = formatter;
listControllers.set(containerId, state);
try {
const res = await fetch(endpoint);
const res = await fetch(endpoint, { cache: "no-store" });
if (!res.ok) {
container.innerHTML = `<div style="color:var(--error-color); padding:20px; text-align:center;">⚠️ Failed to load ${escapeHtml(endpoint)} (${res.status} ${escapeHtml(res.statusText)})</div>`;
return;
+43 -24
View File
@@ -113,7 +113,9 @@ function switchTab(tabId: string, btn?: HTMLElement | null): void {
const targetTab = document.getElementById(tabId);
if (targetTab) targetTab.classList.add("active");
const targetBtn = btn || document.querySelector<HTMLElement>(`.tab-button[onclick*="'${tabId}'"]`);
const targetBtn =
btn ||
document.querySelector<HTMLElement>(`.tab-button[onclick*="'${tabId}'"]`);
if (targetBtn) targetBtn.classList.add("active");
switch (tabId) {
@@ -236,10 +238,16 @@ function showInspector(nodeId: string): void {
const metaEl = document.querySelector<HTMLElement>(".inspector-meta");
if (metaEl) {
const createdStr = entity.created_at
? new Date(entity.created_at * 1000).toISOString().replace("T", " ").substring(0, 19)
? new Date(entity.created_at * 1000)
.toISOString()
.replace("T", " ")
.substring(0, 19)
: "";
const updatedStr = entity.updated_at
? new Date(entity.updated_at * 1000).toISOString().replace("T", " ").substring(0, 19)
? new Date(entity.updated_at * 1000)
.toISOString()
.replace("T", " ")
.substring(0, 19)
: "";
metaEl.innerHTML = `
<div><strong>Type:</strong> <span id="inspector-type">${escapeHtml(entity.entity_type)}</span></div>
@@ -365,7 +373,7 @@ function updateGraphData(): void {
async function loadGraph(): Promise<void> {
try {
const res = await fetch("/api/graph");
const res = await fetch("/api/graph", { cache: "no-store" });
const dataText = await res.text();
if (dataText === lastGraphJson && network) {
return;
@@ -584,8 +592,10 @@ function buildTaskTreeHTML(
if (t.git_branch || t.repo_name) {
html += `<div style="margin-top:8px; font-size:0.75em; display:flex; gap:6px; flex-wrap:wrap; color:var(--text-secondary);">`;
if (t.repo_name) html += `<span style="background:var(--canvas-bg); padding:1px 6px; border-radius:3px; border:1px solid var(--border-color);">📦 ${escapeHtml(t.repo_name)}</span>`;
if (t.git_branch) html += `<span style="background:var(--canvas-bg); padding:1px 6px; border-radius:3px; border:1px solid var(--border-color);">🌿 ${escapeHtml(t.git_branch)}</span>`;
if (t.repo_name)
html += `<span style="background:var(--canvas-bg); padding:1px 6px; border-radius:3px; border:1px solid var(--border-color);">📦 ${escapeHtml(t.repo_name)}</span>`;
if (t.git_branch)
html += `<span style="background:var(--canvas-bg); padding:1px 6px; border-radius:3px; border:1px solid var(--border-color);">🌿 ${escapeHtml(t.git_branch)}</span>`;
html += `</div>`;
}
@@ -625,9 +635,11 @@ function applyTaskFilters(): void {
filtered = filtered.filter(
(t) =>
(t.title && t.title.toLowerCase().includes(taskFilterQuery)) ||
(t.description && t.description.toLowerCase().includes(taskFilterQuery)) ||
(t.description &&
t.description.toLowerCase().includes(taskFilterQuery)) ||
(t.id && t.id.toLowerCase().includes(taskFilterQuery)) ||
(t.assigned_agent && t.assigned_agent.toLowerCase().includes(taskFilterQuery)),
(t.assigned_agent &&
t.assigned_agent.toLowerCase().includes(taskFilterQuery)),
);
}
@@ -664,7 +676,7 @@ function applyTaskFilters(): void {
async function loadTasks(): Promise<void> {
try {
const res = await fetch("/api/tasks");
const res = await fetch("/api/tasks", { cache: "no-store" });
cachedTasks = await res.json();
applyTaskFilters();
} catch (err) {
@@ -922,6 +934,7 @@ function requestDomainRefresh(domain: string): void {
graph: "graph-tab",
task: "task-tab",
techdebt: "techdebt-tab",
adrs: "adrs-tab",
snippets: "snippets-tab",
terminal: "terminal-tab",
ledger: "ledger-tab",
@@ -949,6 +962,9 @@ function requestDomainRefresh(domain: string): void {
case "techdebt":
loadTechDebt();
break;
case "adrs":
loadADRs();
break;
case "snippets":
loadSnippets();
break;
@@ -981,11 +997,10 @@ function handleIncomingActivity(payload: any): void {
}
}
if (
method === "notifications/resources/updated" ||
category === "GRAPH" ||
category === "DECISION"
) {
if (method === "notifications/resources/updated" || category === "GRAPH") {
requestDomainRefresh("graph");
} else if (category === "DECISION" || category === "ADR") {
requestDomainRefresh("adrs");
requestDomainRefresh("graph");
} else if (
method === "notifications/task/completed" ||
@@ -1011,7 +1026,6 @@ function handleIncomingActivity(payload: any): void {
) {
requestDomainRefresh("memos");
}
const feed = document.getElementById("activity-feed");
if (feed) {
if (feed.querySelector(".feed-entry") === null) {
@@ -1506,7 +1520,7 @@ async function loadGenericList(
listControllers.set(containerId, state);
try {
const res = await fetch(endpoint);
const res = await fetch(endpoint, { cache: "no-store" });
if (!res.ok) {
container.innerHTML = `<div style="color:var(--error-color); padding:20px; text-align:center;">⚠️ Failed to load ${escapeHtml(endpoint)} (${res.status} ${escapeHtml(res.statusText)})</div>`;
return;
@@ -1679,12 +1693,16 @@ function loadTerminal(): void {
</div>
${item.status_reason ? `<div style="margin-top:6px; font-size:0.85em; color:var(--error-color);"><strong>Reason:</strong> ${escapeHtml(item.status_reason)}</div>` : ""}
${item.stdout_summary ? `<div style="margin-top:6px; font-size:0.85em; color:var(--text-secondary);"><strong>Output:</strong> ${escapeHtml(item.stdout_summary)}</div>` : ""}
${item.error_output ? `
${
item.error_output
? `
<details style="margin-top:8px;" ${!isSuccess ? "open" : ""}>
<summary style="font-size:0.8em; color:var(--error-color); cursor:pointer; font-weight:600;">Error Output</summary>
<pre style="background:#1a0f0f; color:#ff6b6b; padding:8px; border-radius:4px; border:1px solid rgba(231,76,60,0.3); font-size:0.8em; overflow-x:auto; margin-top:4px; white-space:pre-wrap;">${escapeHtml(item.error_output)}</pre>
</details>
` : ""}
`
: ""
}
`;
},
{
@@ -1832,12 +1850,16 @@ function loadTechDebt(): void {
<span style="color:var(--success-color); font-weight:bold; background: rgba(46, 204, 113, 0.15); padding: 2px 6px; border-radius: 4px; border: 1px solid var(--success-color); flex-shrink:0;">✓ Resolved</span>
</div>
<div style="margin-top:8px; font-size:0.9em; line-height:1.4;"><strong>Solution:</strong> ${escapeHtml(item.solution || "")}</div>
${item.stack_trace ? `
${
item.stack_trace
? `
<details style="margin-top:8px;">
<summary style="font-size:0.8em; color:var(--text-secondary); cursor:pointer; font-weight:600;">Stack Trace</summary>
<pre style="background:#111417; color:#ff7b72; padding:8px; border-radius:4px; border:1px solid var(--border-color); font-size:0.8em; overflow-x:auto; margin-top:4px; white-space:pre-wrap;">${escapeHtml(item.stack_trace)}</pre>
</details>
` : ""}
`
: ""
}
<div style="margin-top:8px; font-size:0.8em; display:flex; gap:8px; flex-wrap:wrap; align-items:center;">
${item.repo_name ? `<span style="background:var(--canvas-bg); padding:2px 6px; border-radius:4px; border:1px solid var(--border-color);">📦 ${escapeHtml(item.repo_name)}</span>` : ""}
<span style="background:var(--canvas-bg); padding:2px 6px; border-radius:4px; font-family:monospace; border:1px solid var(--border-color);">Commit: ${item.git_commit ? escapeHtml(item.git_commit.substring(0, 8)) : "None"}</span>
@@ -1914,10 +1936,7 @@ function loadADRs(): void {
<span style="background:var(--canvas-bg); padding:2px 8px; border-radius:4px; font-size:0.8em; border:1px solid var(--border-color); ${badgeStyle}">${badgeText}</span>
</div>
${
item.git_commit ||
item.git_branch ||
item.task_id ||
item.resolved_at
item.git_commit || item.git_branch || item.task_id || item.resolved_at
? `
<div style="font-size:0.8em; color:var(--text-secondary); margin-top:4px; font-family:monospace; display:flex; gap:12px; flex-wrap:wrap;">
${item.git_branch || item.git_commit ? `<span>📦 ${escapeHtml(item.git_branch || "repo")} @ ${escapeHtml((item.git_commit || "").substring(0, 8))}</span>` : ""}
+147 -50
View File
@@ -1,7 +1,7 @@
# Memory MCP Strategic Guidelines
This document outlines the STRATEGY, SEMANTICS, and CASING STANDARDS for using the MCP Memory Server.
You do not need to memorize JSON schemas for these tools; they are strictly defined and typed in the `tools/list` endpoint. Focus purely on WHEN and WHY to use them.
This document outlines the STRATEGY, SEMANTICS, RESOURCE SCHEMAS, and CASING STANDARDS for using the MCP Memory Server.
You do not need to memorize individual JSON schemas for every tool; they are strictly defined and typed in the `tools/list` endpoint. Focus on WHEN, WHY, and HOW to leverage them effectively.
---
@@ -19,7 +19,45 @@ To prevent graph fragmentation and ensure seamless LLM context retrieval:
---
## 2. Consolidated Smart Tools Architecture
## 2. The Two-Tier Context Paradigm
> [!IMPORTANT]
> * **Tier 1 (Static Markdown)**: Repository rules, constraints, architectural patterns, and developer preferences are maintained directly in static git-tracked files (`agent-rules/*.md`, `instructions.md`) and system prompts. This guarantees 0ms turn-0 availability without relying on proactive agent tool retrieval.
> * **Tier 2 (Telemetry & Ephemeral DB)**: High-frequency operational history—the Code Change Ledger (`audit_ledger`), terminal command history, compiler error fixes (`log_error_fix`), active tasks, and preflight context—is handled by the MCP Memory Server and surfaced via the Brain Monitor Web UI and MCP resources.
---
## 3. Passive MCP Resources (`resources/list`)
The server exposes 9 real-time, read-only MCP resources. Agents should read these resources directly to regain context without incurring tool call latency:
| Resource URI | Resource Name | Description & Usage |
|:---|:---|:---|
| `memory://graph/entities` | Graph Entities | All nodes and entities in the knowledge graph (top 100 with pagination guidance). |
| `memory://graph/relations` | Graph Relations | All relationships between graph entities (top 200 with subgraph guidance). |
| `memory://tasks/active` | Active Tasks | Current active tasks with status, priority, and assigned subagents. |
| `memory://decisions/active` | Active ADR Decisions | Architectural decisions currently in `accepted` status. |
| `memory://tech_debt/unresolved` | Unresolved Tech Debt | All open engineering debt items requiring future refactoring. |
| `memory://session/delta` | Session Delta | Code modifications, commits, active tasks, and notes created in the last 2 hours. |
| `memory://terminal/recent` | Terminal History | Recent terminal commands, interpreters (`pwsh`, `bash`, `nu`), working dirs, and exit codes. |
| `memory://activity/recent` | Recent Activity | Real-time IDE and developer activity event stream. |
| `memory://milestones` | Milestones | Project milestones, deliverables, target dates, and progress. |
---
## 4. MCP Workflow Prompts (`prompts/list`)
The server registers 5 high-signal workflow prompts to initiate standardized agent routines:
1. **`context_warmup`**: Executed at session startup. Prompts the agent to read `memory://tasks/active` and `memory://session/delta`, inspect the workspace worktree, and assemble immediate working context.
2. **`analyze_tech_debt`**: Prompts the agent to review unresolved technical debt from `memory://tech_debt/unresolved` and generate a prioritized remediation plan.
3. **`summarize_architecture`**: Synthesizes active ADRs from `memory://decisions/active` and graph entities from `memory://graph/entities` into an architectural overview.
4. **`handoff_routine`**: Triggers the `DevOpsSRE` subagent at session end to generate a standup report, audit active tasks, and record a handoff memo for future sessions.
5. **`archive_routine`**: Compresses historical session summaries into a dense milestone retrospective entity and purges pruned entries.
---
## 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:
@@ -48,7 +86,8 @@ The server consolidates granular single-purpose tools into domain-named smart to
- `action: "tag"`: Attach classification tags (requires `id`, `tags: Vec<String>`).
* **`decisions`**: Architectural Decision Records (ADRs).
- `action: "log"`: Log ADR (requires `title`, optional `status: "accepted" | "proposed" | "deprecated" | "superseded"`, `context`, `decision`, `consequence`, `author`, `affected_components: Vec<String>`, `alternatives_considered: Vec<String>`, `supersedes`, `repo_name`).
- `action: "log"`: Log ADR (requires `title`, optional `status: "accepted" | "proposed" | "deprecated" | "superseded" | "implemented"`, `context`, `decision`, `consequence`, `author`, `affected_components: Vec<String>`, `alternatives_considered: Vec<String>`, `supersedes`, `repo_name`).
- `action: "update"`: Update ADR status and metadata (requires `id`, optional `status`, `git_commit`, `git_branch`).
- `action: "query"`: Query ADRs (optional `query`).
- `action: "delete"`: Delete ADR (requires `id`).
@@ -83,89 +122,155 @@ The server consolidates granular single-purpose tools into domain-named smart to
---
## 3. VCS & SVN Agnosticism & Multi-Repo Provenance
## 6. Complete Tool Catalog (All 53 Tools)
The server exposes 53 specialized and smart MCP tools organized into 7 functional domains:
### 1. Knowledge Graph Core (18 Tools)
1. `create_entities`: Batch-create entities with `name`, `entity_type`, and `observations`.
2. `create_relations`: Batch-create relationships (`from`, `to`, `relation_type`).
3. `add_observations`: Append observations to existing entities.
4. `delete_entities`: Delete entity nodes and cascading relations.
5. `delete_relations`: Delete specific relation edges between entities.
6. `delete_observations`: Remove specific observations from an entity.
7. `read_graph`: Return full or namespace-filtered knowledge graph.
8. `search_nodes`: Search entity names and observations using Tantivy BM25.
9. `open_nodes`: Inspect full details of specified entity nodes by name.
10. `visualize_graph`: Generate Mermaid markdown or SVG diagram of the graph.
11. `condense_entity`: Summarize entity observations into dense summaries.
12. `merge_entities`: Merge source entity into target entity, re-pointing relations and pruning self-loops.
13. `find_orphans`: Detect entities with zero relationships for pruning.
14. `get_subgraph`: BFS graph traversal expanding $N$ hops from a root node.
15. `sweep_graph_health`: Audit graph for orphans, calculate name similarity, and recommend merges.
16. `resolve_stale_symbols`: Cross-reference graph symbols against the workspace AST to remove deleted code nodes.
17. `summarize_subgraph`: LLM-ready concise synthesis of a localized subgraph.
18. `query_graph_path`: BFS shortest path between two entities in the knowledge graph.
### 2. Task & Milestone Operations (2 Tools)
19. `tasks`: Consolidated task board manager (`add`, `update`, `delete`, `list`, `set_criteria`, `verify`).
20. `milestones`: Milestone lifecycle management (`add`, `update`, `list`).
### 3. Notes, Handoffs & Reporting (4 Tools)
21. `handoff_memos`: Cross-session scratchpad and handoff memos (`leave`, `read`, `clear`).
22. `add_session_summary`: Record session summary notes and highlights.
23. `generate_standup_report`: Synthesize tasks, ledger changes, and session summaries into a standup report.
24. `promote_to_entity`: Promote an ephemeral note or memo into a permanent knowledge graph entity.
### 4. Meta, Audit & Intelligence (15 Tools)
25. `decisions`: Consolidated Architectural Decision Records (ADRs) manager (`log`, `update`, `query`, `delete`).
26. `tech_debt`: Consolidated technical debt backlog manager (`log`, `resolve`, `list`).
27. `log_error_fix`: Record an error resolution with stack trace, root cause, and git commit.
28. `search_error_fixes`: Embedding-based and keyword search over past error resolutions.
29. `log_code_change`: Record a file modification in the VCS-agnostic audit ledger.
30. `query_recent_changes`: Retrieve recent code changes with lookback time filters.
31. `omni_search`: Reciprocal Rank Fusion (RRF) search across all graph entities, snippets, ADRs, debt, and fixes.
32. `get_project_health`: Health dashboard summarizing task completion, debt backlog, and graph consistency.
33. `manage_checkpoint`: Create or restore named memory snapshots for safe rollback.
34. `query_lineage`: Causal lineage tracker linking tasks, ADRs, commits, and error fixes.
35. `get_next_actionable_tasks`: Topologically resolved list of unblocked tasks ready for execution.
36. `hypotheses`: Structured diagnostic hypothesis tracker (`log`, `query`).
37. `get_preflight_context`: Aggregated operational context at session start (tasks, debt, recent changes).
38. `agent_signals`: Inter-agent signal bus (`broadcast`, `query`).
39. `auto_session_checkpoint`: Automatic session boundary checkpointing.
### 5. System, Environment & Telemetry (4 Tools)
40. `environment`: Tool fingerprinting, requirements, and environment registry (`update_fingerprint`, `read_fingerprint`, `log_requirement`, `register`, `get_details`).
41. `snippets`: Reusable code snippet vault with hybrid search (`store`, `search`, `delete`, `tag`).
42. `clipboard`: Pure native Rust OS clipboard interface (`read`, `write`).
43. `process_logs`: Live process and daemon log watcher and tailer (`watch`, `get`, `clear`).
### 6. Git & Worktree Context (2 Tools)
44. `get_active_worktree_context`: Inspect git status, modified files, diff summary, and current branch.
45. `query_git_diffs`: Retrieve detailed git diffs for specific files or commit ranges.
### 7. AST & Code Intelligence (8 Tools)
46. `read_file_skeleton`: Tree-sitter AST structural outline of functions, structs, and methods without implementation bodies.
47. `replace_ast_node`: Precise AST node replacement preserving indentation and comments.
48. `find_symbol_references`: Search for symbol references across snippets and disk source files.
49. `get_callers`: Find call sites and callers of a specified function or method across the codebase.
50. `analyze_impact`: Blast-radius impact analysis of modifying a symbol or file.
51. `read_directory_architecture`: Recursive directory structure analysis capped at depth 10.
52. `semantic_code_search`: Dense vector semantic code search over indexed source code.
53. `manage_subagent_namespace`: Create, isolate, or merge subagent-scoped memory namespaces.
---
## 7. VCS & SVN Agnosticism & Multi-Repo Provenance
To support diverse enterprise repositories (Git, Subversion / SVN, Mercurial / Hg, Monorepos):
* **`vcs_type`**: Designates the VCS engine (`"git"`, `"svn"`, `"hg"`, `"perforce"`, or `"none"`).
* **`vcs_revision`**: Agnostic commit hash or SVN revision identifier (e.g., `"r12458"`, `"3e4f7a9"`).
* **`upstream_url`**: Canonical remote repository URL (e.g. `https://svn.corp/repo/trunk`, `git@bitbucket.org:org/repo.git`).
* **`repo_name`**: Logical project or repository identifier allowing multiple repositories to share or partition memory namespaces cleanly without collision.
* **`repo_name`**: Logical project identifier allowing multiple repositories to share or partition memory namespaces cleanly without collision.
* **Audit Ledger (`log_code_change`)**: Enriched with `vcs_type`, `vcs_revision`, `upstream_url`, `author`, `diff_summary`, and extensible `metadata: HashMap<String, String>`.
---
## 4. Terminal & Process Telemetry
## 8. Terminal & Process Telemetry
The server ingests and tracks active terminal commands and sessions:
* **Active Terminals**: Tracks PIDs, shell interpreters (`pwsh`, `bash`, `nu`, `zsh`), current working directories (`cwd`), command exit codes, and timestamps.
* **Terminal History Endpoint**: `/terminal/history` exposes recent shell commands and output streams to dashboard and LLMs to prevent lost shell context.
* **Quality Gate Enforcement**: `GateRecord` captures pre-flight and pre-push validation passes with `gate_type`, `enforcer`, `status`, `validation_log`, and `repo_name`.
* **Terminal History Endpoint & Resource**: `/terminal/history` and `memory://terminal/recent` expose recent shell commands and output streams to dashboard and LLMs to prevent lost shell context.
* **Zero-Latency UDP Streams**: Terminal and IDE telemetry stream over UDP (`MCP_UDP_PORT1`, `MCP_UDP_PORT2`) with zero disk I/O bottlenecks.
---
## 4. High-Signal Tool Responses & Performance Guidelines
To optimize context usage, response times, and LLM reasoning efficiency:
* **High-Signal Feedback**:
- MCP tool calls (such as `create_entities`, `create_relations`, `add_observations`, `pin_file`) return explicit, structured summaries containing created names, types, edge counts, and relation paths.
- LLMs do NOT need to execute follow-up `open_nodes` calls merely to confirm successful creation.
* **Batch Operations**:
- When creating or updating multiple entities, snippets, or observations, always batch items into a single tool call array (e.g. `create_entities` with multiple array items) rather than making separate calls.
- The server handles batch store mutations serially in a single transaction pass with single-permit event-driven flushes.
* **Real-time Tantivy Search Indexing**:
- The Tantivy search engine automatically checks pending commits and reloads search readers prior to executing `omni_search` or `search_nodes`. Search queries always return up-to-date document results immediately following mutations.
- Single-item deletions use targeted document removal rather than global index wipes.
* **Real-Time AST & Workspace Source Code Symbol Scanning**:
- `find_symbol_references`, `get_callers`, and `analyze_impact` scan both stored code snippets and physical workspace source code files on disk (`.rs`, `.ts`, `.py`, `.go`, `.java`, `.c`, `.cpp`), providing accurate AST symbol references and call site tracking.
* **Graph Entity Merge & Self-Loop Protection**:
- `merge_entities` re-points all relations from `source_entity` to `target_entity` and automatically prunes cyclic self-loops (`target -> target`).
* **Safe UTF-8 Token Truncation**:
- Large responses (e.g. `get_active_worktree_context`, `read_graph`, `summarize_subgraph`) are safely truncated along UTF-8 character boundaries (`floor_char_boundary`), ensuring response bounds without runtime panics.
## 4. Automated Error Fix Auto-Matcher
## 9. Automated Error Fix Auto-Matcher
- **Tools:** `log_error_fix`, `search_error_fixes` (and alias `suggest_error_fix`)
- **When to use:** When encountering a build error, test failure, or stack trace. Call `search_error_fixes` with either a text `query` or `stack_trace` before attempting a fix from scratch.
- **Behavior:** Computes cosine similarity between error trace embeddings and past resolution logs when `stack_trace` is provided, or keyword filtering when `query` is provided, returning top matched solutions, modified files, and git commits.
---
## 5. Memory State Checkpointing & Rollbacks
- **Tool:** `checkpoint_state`, `restore_state` (or `create_snapshot`, `restore_snapshot`)
## 10. Memory State Checkpointing & Rollbacks
- **Tool:** `manage_checkpoint` (action: `"create"` | `"restore"`)
- **When to use:** Before initiating a large refactor, running experimental subagent tasks, or executing destructive batch operations.
- **Behavior:** Saves or restores a point-in-time snapshot of graph entities, active tasks, and tech debt backlogs.
---
## 6. Self-Healing Graph Health Sweeper
## 11. Self-Healing Graph Health Sweeper
- **Tool:** `sweep_graph_health`
- **When to use:** Periodically or before committing major graph changes to audit entity consistency.
- **Behavior:** Detects orphaned nodes (0 relations), computes name similarity using pre-computed lowercase keys to identify near-duplicates (e.g., `APIGateway` vs `ApiGateway`), and provides structured `merge_entities` recommendations or auto-prunes orphans.
---
## 7. Causal Lineage & Provenance Tracker
## 12. Causal Lineage & Provenance Tracker
- **Tool:** `query_lineage`
- **When to use:** When asking *"Why was this component modified?"* or *"What task or ADR led to this code change?"*
- **Behavior:** Searches across tasks, ADRs, audit ledger entries, and error fixes to assemble a unified chronological timeline explaining the provenance behind any file, symbol, or commit.
---
## 9. Native Rust Invariants & Subprocess Prohibition (CRITICAL)
## 13. ADR Lifecycle & Automated Git Post-Commit Reconciliation
- **The Golden ADR Rule**: When code implementing an ADR is committed, you MUST IMMEDIATELY update the ADR status to `implemented`:
```json
{
"action": "update",
"id": "ADR-XXXX",
"status": "implemented",
"git_commit": "<commit_hash>",
"git_branch": "<branch>"
}
```
- **Automated Post-Commit Hook**: The repository provides an automated reconciliation script (`scripts/git-reconcile.py`) installed via `just install-git-hooks`. Upon every `git commit`, the hook scans the commit message for `ADR-XXXX` or task identifiers and reconciles their status in the persistent store.
- **Current Architecture Status**: 100% of defined ADRs (ADR-0080 through ADR-0104) are fully implemented and reconciled in the store.
---
## 14. Native Rust Invariants & Subprocess Prohibition (CRITICAL)
To maintain maximum security, speed, and cross-platform reliability:
* **Zero Subprocess Fallbacks**: System and server tools (`clipboard`, `ast`, `search`, `db`) MUST strictly use pure native Rust crates (`arboard`, `tree-sitter`, `tantivy`, `psycopg`). Invocations of external shell commands (`powershell.exe`, `wl-paste`, `xclip`, `cmd.exe`) are strictly prohibited in native handlers.
* **Transient Lock Recovery**: Transient OS handle collisions (such as Win32 OLE `OpenClipboard` lock contention) must be handled using native retry loops with backoffs directly in Rust.
* **Automated Static Regression Gates**: Automated AST/source audit tests (e.g. `test_no_subprocess_clipboard_regression`) verify at test time that forbidden subprocess patterns are absent from handler implementations.
* **Automated Static Regression Gates**: Automated AST/source audit tests (`test_no_subprocess_clipboard_regression`) verify at test time that forbidden subprocess patterns are absent from handler implementations.
---
## 10. High-Performance Concurrency & Resilience Guarantees
## 15. High-Performance Concurrency & Resilience Guarantees
* **Explicit Fail-Fast Persistence Safety**: Replaced silent fallback to temporary databases (`/tmp/mcp_store_fallback_*`) with an explicit open retry and fail-fast panic unless `MCP_ALLOW_TMP_FALLBACK=1` is explicitly set, preventing silent data loss.
* **Async Mutex Deadlock Elimination**: Converted shared state and Neovim connection locks (`shutdown_tx`, `NVIM_CONN`, `ACTIVE_SOCKET`, `HEADLESS_PROC`) to `tokio::sync::Mutex` to prevent worker thread pool starvation across `.await` points.
* **Telemetry Session Deduplication & Channel Pruning**: Added `LAST_SESSION` in-memory state deduplication for UDP telemetry writes (eliminating disk I/O thrashing) and distinguished WebSocket `TrySendError::Full` backpressure vs `TrySendError::Closed` client pruning.
@@ -186,7 +291,6 @@ To maintain maximum security, speed, and cross-platform reliability:
* **AST Recursion Depth Safeguard & Zero-Copy Borrowing**: Tree-sitter AST traversal caps recursion depth at 100 to prevent thread stack overflows and borrows string slices (`&str`) during AST node walking.
* **Strongly-Typed SearchResult & Pre-Allocated Search Vectors**: `search.rs` uses a strongly-typed `SearchResult` struct with named fields and pre-allocates result vector capacity (`Vec::with_capacity(top_docs.len())`).
* **BFS Graph Traversal Pre-allocation & Visited Node Upper Bound**: `GraphQueryBuilder::find_shortest_path` pre-allocates adjacency map capacity (`HashMap::with_capacity(relations.len() * 2)`) and enforces a visited node upper bound (10,000 max) to guarantee deterministic BFS runtime.
* **LLM Tool Schema Ergonomics & Context Guidance**: `ReadGraphHandler` schema explicitly instructs LLMs on `namespace` filtering and `search_nodes` / `get_subgraph` tools for large graph discovery.
* **Filesystem Event Debouncing & Proactive State Refresh**: `spawn_watcher` implements a sliding 250ms debouncing window per file path, ignores `.git`, `target`, `.gemini`, and `node_modules`, and broadcasts activity events to `MemoryState`.
* **Buffered Line-by-Line AST Workspace Symbol Scanning**: `scan_workspace_for_symbol` reads workspace files via `BufReader` line streams instead of loading entire files into heap strings, preventing memory spikes when traversing source trees.
* **AST Node Type Aliasing & Skeleton Preallocation**: `replace_ast_node` documents friendly node aliases (`function`, `fn`, `method`, `struct`, `class`, `enum`, `trait`, `type`), and `read_file_skeleton` preallocates string buffer capacity (`code.len() / 2`).
@@ -195,20 +299,13 @@ To maintain maximum security, speed, and cross-platform reliability:
* **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 (`process_logs`, action: "get") 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.
* **Task Summary UTF-8 Truncation Safety**: `tasks` tool (`action = "list"`) truncates serialized task text strictly along UTF-8 character boundaries using `floor_char_boundary` when enforcing `max_tokens`.
* **Sequential Snapshot Lock Scope Flattening**: `GenerateStandupReportHandler` reads `tasks`, `ledger`, and `session_summaries` sequentially rather than nesting read locks, preventing multi-lock deadlocks during concurrent store modifications.
* **Directory Tree Depth Safeguard**: `ReadDirectoryArchitectureHandler` caps directory recursion at depth 10 to prevent stack overflow on deep or cyclic directory structures.
* **Deterministic Total-Order Score Ranking**: `OmniSearchHandler` uses `f64::total_cmp` for Reciprocal Rank Fusion (RRF) score sorting, guaranteeing deterministic NaN-safe search result ordering.
* **RPC Timeout Memory Hygiene**: `nvim-core` maintains request hygiene by removing pending request entries from static RPC maps upon timeout or channel drop, eliminating orphan memory leaks.
* **Embedding Input Safeguard**: `generate_embedding_async` returns explicit errors for empty/0-length text inputs instead of returning empty vectors, preventing downstream vector dimension mismatches during cosine similarity calculations.
* **Path Traversal Security Guards**: `validate_safe_path` enforces path canonicalization and rejects relative parent traversal components (`..`) across file and process log handlers (`process_logs` / `ProcessLogsTool`).
* **Watcher Map Memory Eviction**: Proactive daemon file watcher in `watcher.rs` caps `last_processed` map size at 1,000 entries and purges entries older than 10 minutes to prevent monotonic memory leakage.
* **Comprehensive Serde Casing Aliases**: All 11 consolidated tool action enums (TaskAction, MilestoneAction, SnippetAction, DecisionAction, TechDebtAction, EnvAction, ClipboardAction, HandoffMemoAction, HypothesisAction, AgentSignalAction, ProcessLogAction) include serde alias attributes supporting `snake_case`, `camelCase`, `PascalCase`, and uppercase variants for maximum LLM casing resilience.
* **Two-Phase Graph Condensation**: `condense_graph_worker` uses a 2-phase commit (non-destructive `read_with` -> graph insert -> prune by timestamp/content) to prevent data loss if summarization or graph insertion fails.
* **Store Write Lock Minimization**: `Store::modify` and `Store::modify_async` unblock concurrent readers during JSON serialization by releasing the write lock immediately after mutating memory state.
* **Redb Database Lock Retry Backoff**: `init_db` retries transient Redb lock contention with exponential backoff (3 attempts, 150ms delay) before falling back.
* **Offloaded Background Index Rebuilds**: `MemoryState::rebuild_index` offloads graph snapshot cloning and Tantivy document re-indexing into `tokio::task::spawn_blocking` to avoid stalling async event loops.
* **Broadcast Watch-Based Shutdown Channels**: Background workers utilize `tokio::sync::watch` for broadcast shutdown notifications without consuming cancellation signals.
* **Consolidated Neovim Tool Suite (v2)**: The Neovim server exposes 7 consolidated domain tools (`nvim_buffer`, `nvim_window`, `nvim_view`, `nvim_diagnostics`, `nvim_visual`, `nvim_execute_lua`, `nvim_system`) with comprehensive action dispatching.
* **Fallback Vector Search Parity**: In-memory vector search fallback indexes Knowledge Graph entities, observations, and error fixes when external vector databases are unavailable.