From 5dd413c397aff038a6bfc67072fcdb77f4f8cbc8 Mon Sep 17 00:00:00 2001 From: Riz Ashraf Date: Sat, 26 Sep 2026 02:21:42 +0100 Subject: [PATCH] chore: migrate global agent rules into repository and update deployment scripts --- agent-rules/agent_communication.md | 15 ++++++++ agent-rules/global_subagents.md | 27 +++++++++++++ agent-rules/junior_developer_constraints.md | 4 ++ agent-rules/mcp_memory_integrity.md | 7 ++++ agent-rules/mcp_memory_workflow.md | 20 ++++++++++ agent-rules/neovim_ux.md | 18 +++++++++ agent-rules/nvim_architecture.md | 38 +++++++++++++++++++ agent-rules/nvim_editing.md | 34 +++++++++++++++++ agent-rules/nvim_mcp_enforcement.md | 7 ++++ agent-rules/nvim_sync.md | 21 ++++++++++ agent-rules/rule_1_network_testing.md | 5 +++ agent-rules/rule_2_empirical_logging.md | 5 +++ agent-rules/rule_3_resiliency_testing.md | 7 ++++ .../rule_4_skeletal_troubleshooting.md | 5 +++ agent-rules/rule_5_client_centric_testing.md | 5 +++ agent-rules/rust_concurrency_quirks.md | 10 +++++ agent-rules/state_management.md | 15 ++++++++ agent-rules/strict-no-verify.md | 13 +++++++ agent-rules/workflow-constraints.md | 34 +++++++++++++++++ justfile | 5 +++ 20 files changed, 295 insertions(+) create mode 100644 agent-rules/agent_communication.md create mode 100644 agent-rules/global_subagents.md create mode 100644 agent-rules/junior_developer_constraints.md create mode 100644 agent-rules/mcp_memory_integrity.md create mode 100644 agent-rules/mcp_memory_workflow.md create mode 100644 agent-rules/neovim_ux.md create mode 100644 agent-rules/nvim_architecture.md create mode 100644 agent-rules/nvim_editing.md create mode 100644 agent-rules/nvim_mcp_enforcement.md create mode 100644 agent-rules/nvim_sync.md create mode 100644 agent-rules/rule_1_network_testing.md create mode 100644 agent-rules/rule_2_empirical_logging.md create mode 100644 agent-rules/rule_3_resiliency_testing.md create mode 100644 agent-rules/rule_4_skeletal_troubleshooting.md create mode 100644 agent-rules/rule_5_client_centric_testing.md create mode 100644 agent-rules/rust_concurrency_quirks.md create mode 100644 agent-rules/state_management.md create mode 100644 agent-rules/strict-no-verify.md create mode 100644 agent-rules/workflow-constraints.md diff --git a/agent-rules/agent_communication.md b/agent-rules/agent_communication.md new file mode 100644 index 0000000..1a9632d --- /dev/null +++ b/agent-rules/agent_communication.md @@ -0,0 +1,15 @@ +# CRITICAL BEHAVIOR: PRIORITIZE THE USER +- **NEVER ignore the user.** When the user asks a question or sends a message, you MUST stop all autonomous debugging/thrashing loops and address the user's message DIRECTLY in your very next turn. +- **Stop before reacting.** If the user points out a flaw (e.g., "why aren't you using MCP memory?", "is this an ansible config?"), do NOT just quietly fix it and continue firing commands. Acknowledge the question, explain the mistake, and answer them. +- **Do not hide behind tools.** A tool execution is not a response to the user. +- **Do not rush.** There is no time limit. Prioritize accuracy, safety, and proper engineering patterns over speed. If you realize a mistake, do not panic and deploy a hacky hotfix. Take a breath, analyze the architecture, and propose the correct fix before acting. +- **Fail Fast & Avoid Execution Loops:** If an action (like checking logs, running a test, or searching for a file) does not yield the expected result after 2 or 3 attempts, STOP. Do not blindly iterate on grep commands or wait endlessly. Fail fast, report the anomaly to the user, and question the fundamental assumptions (e.g., "Is the code actually deployed?", "Is there a cache?"). Never trap the user in a 15-minute execution loop. +- **Enforce Pre-Push Gates Strictly:** Never propose or execute a `git push` without first running the full local test suite or delegating to the `PrePushAuditor`. If tests are broken, fixing them is the only acceptable next step. + +- **Decouple Development from Git Lifecycle (Strict Boundary):** Fixing a bug or a test requires *local verification* (e.g., running `uv run pytest`), NOT deployment. Never automatically chain a `git commit` or `git push` at the end of a debugging or coding loop. Git operations are administrative and must be explicitly separated from development work. Do not commit or push without explicit user authorization. + +- **Strict Environment Terminology (Never Conflate Staging and Live):** Never use the word "live" when referring to a testing, staging, or QA environment (e.g., `staging`, `aipoc`, `gemini-poc.gs.inseinc.com`). "Live" strictly implies Production. Using these interchangeably causes panic and misrepresents the blast radius of actions. Always use exact environment names: say "deployed to staging" or "testing in QA", reserving "production" or "live" ONLY for the actual production environment. + +- **Branching Strategy (No Direct Master Pushes):** Never commit or push directly to `master`. You must always create a new branch (e.g., `git checkout -b feature/xyz` or `bugfix/xyz`), make your changes, squash commits if necessary, and push the feature branch. Merging to master is handled strictly via Pull Requests. + +- **Git Worktrees ONLY:** Never use `git checkout -b` or `git switch -c` to change branches inside an existing directory. We use Git Worktrees exclusively. To create a new branch, you must step out of the current directory and run `git worktree add ../ -b master`. Changing branches in-place destroys the worktree-to-directory mapping. diff --git a/agent-rules/global_subagents.md b/agent-rules/global_subagents.md new file mode 100644 index 0000000..e502439 --- /dev/null +++ b/agent-rules/global_subagents.md @@ -0,0 +1,27 @@ +--- +name: global-subagents +description: Defines the standard global subagents (MemoryLibrarian, PrePushAuditor, BugDiagnostician) that must be dynamically invoked for standard workflow steps. +always_on: true +--- +# Antigravity Subagents + +Invoke these dynamically using the `invoke_subagent` tool. Use `send_message` to communicate. +**CRITICAL:** Before invoking any of these custom subagents for the first time in a conversation, you MUST define them using the `define_subagent` tool with the specific permissions they require. + +## 1. MemoryLibrarian +* **Role:** The Knowledge Graph Curator +* **Permissions:** You MUST define this subagent with `enable_mcp_tools: true` and `enable_write_tools: true` so it can autonomously update the graph without hitting permission boundaries. +* **Trigger:** After completing a coding task, refactor, or bug fix. +* **Action:** Send a message detailing the work (with exact git hashes and branches). The Librarian will use MCP tools (`log_code_change`, `log_error_fix`, `create_entities`, etc.) in the background to organize the knowledge graph. + +## 2. PrePushAuditor +* **Role:** Quality Gate Enforcer +* **Permissions:** You MUST define this subagent with `enable_write_tools: true` so it can run tests and scripts. +* **Trigger:** Before executing `git push`. +* **Action:** The Auditor runs pre-commit hooks, formatters, linters, unit tests (`uv`, `cargo`) in a branched workspace, checks for uncommitted changes, and verifies if the Git history requires squashing (using `git reset --soft`). It returns a GO / NO-GO push decision to prevent violating push-safety rules. + +## 3. BugDiagnostician +* **Role:** Observability & Root Cause Analyst +* **Permissions:** You MUST define this subagent with `enable_write_tools: true`. +* **Trigger:** When facing complex architectural bugs, race conditions, or eventually consistent state issues that are hard to track down. +* **Action:** Instead of guessing or patching blindly, this subagent creates diagnostic scripts, enhances reproducers with detailed logs, and isolates the bug. Once root cause is definitively proven, it hands the diagnostic evidence back to you to implement the fix. diff --git a/agent-rules/junior_developer_constraints.md b/agent-rules/junior_developer_constraints.md new file mode 100644 index 0000000..310ff25 --- /dev/null +++ b/agent-rules/junior_developer_constraints.md @@ -0,0 +1,4 @@ +# 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. diff --git a/agent-rules/mcp_memory_integrity.md b/agent-rules/mcp_memory_integrity.md new file mode 100644 index 0000000..076410b --- /dev/null +++ b/agent-rules/mcp_memory_integrity.md @@ -0,0 +1,7 @@ +# MCP Memory Integrity Rule + +**CRITICAL RULE:** Under NO CIRCUMSTANCES should any agent or subagent directly manipulate, edit, or write raw JSON/data to the MCP Memory Graph files (e.g., `knowledge_graph_master.json`, `.db` files, or any files inside `~/.gemini/mcp_memory/`). + +All interactions, additions, creations, and updates to the knowledge graph or task tracker MUST go through the officially exposed MCP tools (such as `add_task`, `set_acceptance_criteria`, `verify_acceptance_criteria`, `log_code_change`, `create_entities`, etc.). + +Bypassing the MCP API by using file-editing tools (like `replace_file_content` or `write_to_file`) on the database files corrupts the state, bypasses indexing, and destroys the Redb Write-Ahead Log (WAL). If an agent attempts to do this, immediately stop them and route the request correctly through the provided MCP API tools. diff --git a/agent-rules/mcp_memory_workflow.md b/agent-rules/mcp_memory_workflow.md new file mode 100644 index 0000000..d784b46 --- /dev/null +++ b/agent-rules/mcp_memory_workflow.md @@ -0,0 +1,20 @@ +--- +name: MCP Memory Centrality & Safety +description: Strict guidelines for interacting with the mcp-memory server, ensuring it remains the central brain and is never forcefully shut down. +--- + +# MCP Memory Centrality & Safety + +## 1. Safety & Port Constraints (NEVER SHUT DOWN) +- **CRITICAL**: NEVER attempt to shut down, kill, or send a POST `/shutdown` request to the `mcp-memory` server (typically running on port 3000). +- If a port conflict occurs (e.g., a Rust panic `AddrInUse` during a `git push` gatekeeper check), **STOP** and immediately notify the user. Do not attempt to auto-resolve the conflict by killing the existing memory server process. + +## 2. Proactive "Central Brain" Usage +The MCP Memory server is the central brain. You must be PROACTIVE, not reactive, in using it: +- **Session Starts & Context Drops**: Always begin by checking `list_active_tasks`, `list_pinned_files`, and `read_sticky_notes`. +- **Sticky Notes**: Use sticky notes for transient, session-scoped operational constraints (e.g., "Do not touch file X until Y is done"). +- **Error Fixes**: The moment a tricky, undocumented, or environment-specific bug is resolved (e.g., Bitbucket markdown rendering quirks, nuanced framework bugs), IMMEDIATELY call `log_error_fix`. Do not wait for the user to ask. +- **Tech Debt**: If you notice an anti-pattern (e.g., nested `if` statements, arrow anti-pattern) but deliberately skip fixing it to focus on a feature, IMMEDIATELY call `log_tech_debt`. + +## 3. Delegation +Continue to use the `MemoryLibrarian` subagent to log routine code changes (`log_code_change`) in the background to prevent cluttering the main conversation context. diff --git a/agent-rules/neovim_ux.md b/agent-rules/neovim_ux.md new file mode 100644 index 0000000..1f005bb --- /dev/null +++ b/agent-rules/neovim_ux.md @@ -0,0 +1,18 @@ +# 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). + +## 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. + +**Lua snippet to execute:** +``lua +_G.gemini.show_progress("Analyzing...") +`` + +## 2. Live Undo-able Code Injection +Instead of using replace_file_content to write code directly to the hard drive, you can pipe your code changes directly into the user's active buffer memory. This allows the user to instantly press undo to revert your code. + +**Workflow Rule:** +If the user asks you to "refactor this block", use vim.api.nvim_buf_set_lines to inject your response instantly into their live editor. Do NOT write to disk unless they explicitly say "save the file". + diff --git a/agent-rules/nvim_architecture.md b/agent-rules/nvim_architecture.md new file mode 100644 index 0000000..e0afac6 --- /dev/null +++ b/agent-rules/nvim_architecture.md @@ -0,0 +1,38 @@ +# Neovim MCP Architecture (Dual-OS) + +We use a modular, multi-binary approach for MCP Neovim integration to cleanly separate Windows and Linux concerns, avoiding complex cross-OS `wsl.exe` bridging within the main `mcp-memory-server`. + +## The Architecture +1. **`mcp-memory-server`:** The core Windows daemon (handles state, lock-files, and global graph). +2. **`mcp-memory-stub`:** The WSL proxy that forwards standard json-rpc to the Windows daemon. +3. **`mcp-memory-win-nvim`:** A dedicated Windows-native MCP server. Its sole responsibility is finding active Neovim instances running natively on Windows and sending RPC commands to them. +4. **`mcp-memory-linux-nvim`:** A dedicated Linux-native MCP server running inside WSL. Its sole responsibility is finding active Neovim instances inside WSL (including Tmux sessions) and sending RPC commands to them. + +This isolates editor-control logic to the native OS where the editor is actually running. + +## How the Respective MCP Servers Get Called + +The Antigravity CLI (`agy`) acts as the MCP Client and automatically manages the lifecycle of these servers. + +1. **Registration:** The servers are registered in the global configuration file: + - WSL: `/home/riz/.gemini/config/mcp_config.json` + - Windows: `C:\Users\reazul.ashraf\.gemini\config\mcp_config.json` + +2. **Execution:** + When `agy` starts up, it reads `mcp_config.json`. If it finds `"linux-nvim": { "command": "/home/riz/.local/bin/mcp-memory-linux-nvim" }`, it will spawn that binary as a background subprocess using standard `stdio`. + +3. **Communication:** + - The LLM requests to use a tool (e.g., `nvim_goto_line`). + - The `agy` CLI sends a JSON-RPC request to the `mcp-memory-linux-nvim` subprocess via its `stdin`. + - The Rust MCP Server receives the request, connects to the Neovim active socket (`~/.gemini/active_nvim.txt`), 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. + +## Capabilities & Requirements +To use this architecture, Neovim must run the `gemini-integration.lua` script to broadcast its active socket to `~/.gemini/active_nvim.txt`. + +The MCP servers provide 5 core tools: +1. **`nvim_goto_line`** +2. **`nvim_set_diagnostics`** +3. **`nvim_get_active_buffer`** +4. **`nvim_get_cursor`** +5. **`nvim_get_visual_selection`** diff --git a/agent-rules/nvim_editing.md b/agent-rules/nvim_editing.md new file mode 100644 index 0000000..12fd7e3 --- /dev/null +++ b/agent-rules/nvim_editing.md @@ -0,0 +1,34 @@ +--- +name: nvim_editing +description: Route code edits to Neovim buffers instead of disk/console when Neovim is running. +trigger: always_on +--- +# Neovim Code Editing + +## Never Spawn Headless Instances (CRITICAL) +**NEVER** run `nvim ` via bash/terminal commands (`run_command`) to "open" or "show" a file to the user. Because agent terminal commands run in the background, this spawns an invisible ghost process. + +If the user asks to "open", "show", or "see" a file in Neovim, you MUST use the `linux-nvim` (or `win-nvim`) MCP Server to communicate with their *active* UI (e.g., using `nvim_execute_lua` with `vim.cmd('edit ')`). + +When making code edits or displaying search results/outputs: +1. Verify if the win-nvim (on Windows) or linux-nvim (on WSL) MCP server is responsive. +2. If Neovim is running, apply code changes directly into the relevant Neovim buffers using nvim_execute_lua (e.g., using vim.api.nvim_buf_set_lines or vim.cmd). +3. DO NOT output large diffs or file contents to the chat console. Prefer live buffer manipulation over replace_file_content if the file is open in Neovim. +4. **Fallback Constraint (CRITICAL):** If Neovim is NOT running, you MUST use the `replace_file_content` tool to edit files. This ensures the user is presented with a visual diff block in the chat. **NEVER** use `sed`, `awk`, or `echo` to blindly modify file contents from the terminal. + +## Visual Cues & Auto-Save Policy (MANDATORY) +When manipulating buffers via Lua, you MUST provide visual feedback: +1. **Notifications:** Always trigger a notification explaining what you did using `require("notify")("Antigravity edited [File]: [Summary]", "info", { title = "Antigravity" })` (since `rcarriga/nvim-notify` and `noice.nvim` are installed). +2. **Buffer Focus:** Always switch the active Neovim window to the buffer you just edited (e.g., `vim.cmd('b ' .. bufnr)`). +3. **Cursor Jump:** Move the cursor to the line you edited (`vim.api.nvim_win_set_cursor(0, {line, 0})`). +4. **Auto-Save by Default:** You MUST save the buffer (`vim.cmd('write')`) after making edits so that external tools (tests, compilers, linters, git) can see the changes immediately and unattended tasks are not stalled. +5. **Interactive Review Mode (Exception):** The ONLY time you should disable auto-save (leaving the buffer modified and unsaved) is when you are actively halting execution to seek manual user confirmation for a highly sensitive change. This allows the user to visually review the `gitsigns` diff in the gutter before manually saving (`:w`). + +## Interactive Review & Automatic Wakeup (MANDATORY) +When you modify a buffer and disable auto-save to allow the user to visually review the changes, you MUST NOT just wait idly for them to chat back. +You MUST spawn a background task to listen for their :w save event: +1. Use the un_command tool to execute: + curl -s "http://127.0.0.1:3000/events/wait?topic=nvim:save:$((Get-Item $File).FullName.Replace('\', '/'))&session_id=$SessionId" +2. Set WaitMsBeforeAsync to a low value (e.g., 500ms) so it goes to the background immediately. +3. Stop calling tools and end your turn. +When the user saves the file, the curl command will complete and the system will automatically wake you up to proceed. diff --git a/agent-rules/nvim_mcp_enforcement.md b/agent-rules/nvim_mcp_enforcement.md new file mode 100644 index 0000000..5b75872 --- /dev/null +++ b/agent-rules/nvim_mcp_enforcement.md @@ -0,0 +1,7 @@ +# Neovim MCP Enforcement Rule + +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 `linux-nvim` (WSL/Linux) or `win-nvim` (Windows) MCP servers. + +- 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 MCP tool registry (e.g., `nvim_goto_line`, `nvim_get_active_buffer`, `nvim_get_cursor`, `nvim_get_visual_selection`, `nvim_set_diagnostics`). +- If the tool is eagerly loaded, use it natively as an agent tool. If lazy-loaded, invoke it via the `call_mcp_tool` mechanism. diff --git a/agent-rules/nvim_sync.md b/agent-rules/nvim_sync.md new file mode 100644 index 0000000..fb0325a --- /dev/null +++ b/agent-rules/nvim_sync.md @@ -0,0 +1,21 @@ +# Neovim Auto-Sync Rule + +When the user asks you to "open these files", "show me what you're working on in nvim", or after a large refactor where visual verification is needed, you MUST push the relevant files to the user's active Neovim buffer. + +## Execution Paths + +### 1. Neovim RPC (Preferred when outside Tmux) +If the `$NVIM` environment variable is available (e.g., you are running inside a Neovim terminal like toggleterm), or if you can locate the Neovim server socket in `/tmp/nvim.*/0`, use the remote feature: +```bash +nvim --server /tmp/nvim.sock --remote file1.py file2.py +``` +*(Tip: You may need to run `lsof -c nvim | grep "tmp"` or search `/tmp/` to dynamically find the exact socket path if `$NVIM` is not exported to your current shell session).* + +### 2. Tmux Injection (Fallback when inside Tmux) +If Neovim is running inside Tmux (and not easily reachable via RPC), use `tmux send-keys` to inject the files into the Neovim args list: +```bash +tmux send-keys -t 0:1 Escape ":args file1.py file2.py" C-m Escape ":argdo e" C-m +``` +*(Tip: Adjust the tmux target `-t 0:1` if the user's nvim pane is elsewhere, e.g., `-t 0:1.2`).* + +This ensures the user does not have to manually open files you have just modified, regardless of whether they are using Tmux or not. diff --git a/agent-rules/rule_1_network_testing.md b/agent-rules/rule_1_network_testing.md new file mode 100644 index 0000000..d342938 --- /dev/null +++ b/agent-rules/rule_1_network_testing.md @@ -0,0 +1,5 @@ +# 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. diff --git a/agent-rules/rule_2_empirical_logging.md b/agent-rules/rule_2_empirical_logging.md new file mode 100644 index 0000000..7bacefb --- /dev/null +++ b/agent-rules/rule_2_empirical_logging.md @@ -0,0 +1,5 @@ +# 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. diff --git a/agent-rules/rule_3_resiliency_testing.md b/agent-rules/rule_3_resiliency_testing.md new file mode 100644 index 0000000..c844033 --- /dev/null +++ b/agent-rules/rule_3_resiliency_testing.md @@ -0,0 +1,7 @@ +# 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. diff --git a/agent-rules/rule_4_skeletal_troubleshooting.md b/agent-rules/rule_4_skeletal_troubleshooting.md new file mode 100644 index 0000000..d5b96c1 --- /dev/null +++ b/agent-rules/rule_4_skeletal_troubleshooting.md @@ -0,0 +1,5 @@ +# 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. diff --git a/agent-rules/rule_5_client_centric_testing.md b/agent-rules/rule_5_client_centric_testing.md new file mode 100644 index 0000000..c396a52 --- /dev/null +++ b/agent-rules/rule_5_client_centric_testing.md @@ -0,0 +1,5 @@ +# 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. diff --git a/agent-rules/rust_concurrency_quirks.md b/agent-rules/rust_concurrency_quirks.md new file mode 100644 index 0000000..988330d --- /dev/null +++ b/agent-rules/rust_concurrency_quirks.md @@ -0,0 +1,10 @@ +# Rust Guidelines & Quirks + +## Concurrency & Locking +- **Lock Poisoning Protection:** NEVER use `.unwrap()` when acquiring a `Mutex` or `RwLock` (e.g., `lock.write().unwrap()`). ALWAYS use `.unwrap_or_else(|e| e.into_inner())` to gracefully recover the underlying data from poisoned locks and prevent cascading panics across threads or async tasks. +- **Panic-Free Architecture:** Avoid `.unwrap()` anywhere in production code. Use `.expect()` for startup initialization errors, and `.unwrap_or_else()`, `.unwrap_or_default()`, or proper `Result` propagation for runtime operations. + +## IDE & Rust-Analyzer Quirks +- **Boolean NOT Operator (E0600):** Avoid using the unary `!` operator on complex boolean expressions inside closures (e.g., `!(a == b && c == d)`). `rust-analyzer` may lose track of the type boundary and falsely report an E0600 error (`cannot apply unary operator ! to type bool`). Rewrite these expressions using De Morgan's laws (e.g., `a != b || c != d`). +- **Option::None Shadowing:** If `rust-analyzer` throws a `non_snake_case` warning for `None` during pattern matching (often caused by wildcard imports like `use crate::models::*;` shadowing standard prelude variants), explicitly namespace the variant as `std::option::Option::None` to satisfy the LSP. +- **Deep Cloning across Thread Boundaries:** When moving large structs (like entities with large text vectors) into a `tokio::task::spawn_blocking` closure for indexing or processing, construct the required primitive payloads or target structs on the main thread *before* the closure to avoid `.clone()`ing the entire massive struct across the `'static` boundary. diff --git a/agent-rules/state_management.md b/agent-rules/state_management.md new file mode 100644 index 0000000..9b2e037 --- /dev/null +++ b/agent-rules/state_management.md @@ -0,0 +1,15 @@ +# Antigravity State Management & Git Worktree Rules + +## State Tracking & Persistent Memory +- **Long-term Knowledge (MCP):** Use the MCP memory graph strictly for long-term, persistent facts such as architectural decisions, environment invariants, SSH mappings, and user preferences. +- **Transient State (Git):** Do NOT write transient task progress (e.g., "currently editing line 42") to MCP memory. Continue to use verbose, incremental local `git` commits to track short-term state and maintain rollback safety. + +## Branching Strategy & Workflow (Git Worktrees) +- **Architecture:** This environment utilizes Git Bare repositories with worktrees (e.g., a `.bare` directory alongside branch directories like `master`, `feature-x`). +- **Navigation Rule (CRITICAL):** NEVER attempt to run tests, execute git commands, or invoke subagents against the root project folder or the `.bare` directory. ALWAYS navigate into the specific active worktree directory (e.g., `cd project-name/master`). +- **Never Modify Master Directly:** Do NOT make code modifications or dirty the working tree of the `master` or `main` directories. +- **Isolated Worktrees:** Before beginning a new task, create an isolated sibling worktree directory for a new feature branch. + - *Example:* From inside `master/`, run `git worktree add ../feat-my-new-task -b feat-my-new-task`. +- **Standard Workflow:** Change directory into the newly created worktree (`cd ../feat-my-new-task`) and make all verbose incremental commits there. +- **Cleanup:** Once the task is complete, squashed, pushed, and merged, delete the local worktree branch (`git worktree remove ../feat-my-new-task`). +- **Initialization:** If the project is not using a bare worktree layout, invoke the `setup-bare-worktree` skill first. diff --git a/agent-rules/strict-no-verify.md b/agent-rules/strict-no-verify.md new file mode 100644 index 0000000..4bbbac4 --- /dev/null +++ b/agent-rules/strict-no-verify.md @@ -0,0 +1,13 @@ +--- +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. diff --git a/agent-rules/workflow-constraints.md b/agent-rules/workflow-constraints.md new file mode 100644 index 0000000..368b879 --- /dev/null +++ b/agent-rules/workflow-constraints.md @@ -0,0 +1,34 @@ +--- +name: workflow-constraints +description: Strict behavioral constraints for Jenkins, staging deployments, git investigations, and background tasks. +trigger: always_on +--- + +# 1. Strict Background Task Control +- **Rule:** Do not run continuous background polling, background loops, or test suites unless explicitly requested. +- **Rule:** If the user says 'stop' or 'don't run anything', kill all tasks immediately and stop launching new ones. + +# 2. No Unauthorized Jenkins Deployments +- **Rule:** Never trigger Jenkins CI/CD pipelines (`jn run`) automatically. Always wait for explicit user approval before deploying via Jenkins. + +# 3. Hot Deploy & Visual Verification +- **Rule:** In `ai-pr-review`, never `git push` without first hot-deploying to staging using `just deploy-code aipoc` and running the relevant sandbox E2E test to allow visual confirmation, and wait for human visual verification to complete before git push. +- **WARNING (Jenkins Conflict):** Hot-deploying creates manual containers on `aipoc`. If you subsequently trigger a Jenkins deployment to `aipoc` (`ai-pr-review-ansible-deploy`), the Ansible playbook will fail with a Docker naming conflict (`Error when allocating new name: Conflict`). You MUST SSH into `aipoc` and manually remove the conflicting containers (`sudo docker rm -f `) before running the Jenkins deployment. + +# 4. Git Investigation Constraints +- **Rule:** Confine code investigations and debugging to actual code diffs. Never rely lazily on git commit messages to determine what changed. + +# 5. Git Push and Gatekeeper Constraints +- **Rule:** Before running `git push`, you MUST ensure the git working tree is completely clean (`git status`). Untracked scratch scripts or uncommitted formatting changes will cause the pre-push gatekeeper to hang indefinitely. +- **Rule:** If a `git push` task hangs, kill it, investigate and clean the working tree (using `git clean -fd` or `git restore`), and retry. NEVER poll a hanging push task in a loop. +- **Rule:** NEVER use `git push --no-verify` to bypass a hanging pre-push hook. The hook is hanging due to environment state, not failing tests. +# 6. Strict Process Termination (Zombie Cleanups) +- **Rule (CRITICAL):** NEVER kill processes using broad wildcard name matches (e.g., Get-Process | Where-Object Name -match "cargo|rustc"). This causes collateral damage to globally deployed binaries (e.g., in ~/.local/bin/). +- **Rule:** When cleaning up zombie files or locked compiler processes, you MUST strictly target the process by its Path to ensure it originates from the current workspace's arget/ directory (e.g., Get-Process | Where-Object { $_.Path -match "\\target\\" } | Stop-Process -Force). + +# 7. GCP / GCR Troubleshooting Constraints +- **Rule (GCR 403 Forbidden):** Google Container Registry obscures `404 Not Found` errors as `403 Forbidden` for security reasons. If a `docker pull` or `podman pull` from GCR fails with `403 Forbidden`, you MUST explicitly verify that the image path and tag are 100% correct (checking prefixes, project IDs, and typos) before assuming it is an IAM or Service Account permission issue. + +# 8. GCP Infrastructure Provisioning (gcloud & Cloud Armor) +- **Rule (Cloud Armor IP Limits):** GCP Cloud Armor security policies strictly enforce a limit of **10 IP ranges per rule** (`--src-ip-ranges`). When allowlisting large services (like Atlassian Bitbucket which has 11+ IP CIDR blocks), you MUST split the ranges across multiple rules (e.g., priority 1000 and 1001) to prevent the `Only a maximum of 10 IP ranges allowed per rule` API error. +- **Rule (gcloud Idempotency):** When writing bash scripts to provision GCP infrastructure, NEVER use bare `gcloud ... create` commands. You MUST wrap all creation commands in existence checks (e.g., `if ! gcloud ... describe ... >/dev/null 2>&1; then ... fi`) to ensure the script is fully idempotent and can be safely retried upon failure. diff --git a/justfile b/justfile index ab54733..8b16de2 100644 --- a/justfile +++ b/justfile @@ -31,6 +31,9 @@ deploy-win: shutdown-server Write-Host "Deploying Windows binaries..." -ForegroundColor Cyan Copy-Item -Force target\release\mcp-memory-stub.exe "C:\Users\reazul.ashraf\.local\bin\"; Copy-Item -Force target\release\mcp-memory-win-nvim.exe "C:\Users\reazul.ashraf\.local\bin\" Copy-Item -Force target\release\mcp-memory-server.exe "C:\Users\reazul.ashraf\.local\bin\" + Write-Host "Deploying global Agent rules (Windows)..." -ForegroundColor Cyan + if (!(Test-Path "C:\Users\reazul.ashraf\.gemini\config\rules")) { New-Item -ItemType Directory -Force -Path "C:\Users\reazul.ashraf\.gemini\config\rules" | Out-Null } + Copy-Item -Force -Recurse agent-rules\* "C:\Users\reazul.ashraf\.gemini\config\rules\" # Build WSL-native binaries build-wsl: @@ -41,6 +44,8 @@ build-wsl: deploy-wsl: Write-Host "Deploying WSL binaries natively..." -ForegroundColor Cyan wsl.exe -d Ubuntu -e bash -c 'export PATH="$PATH:/home/riz/.cargo/bin" && cd /mnt/c/Users/reazul.ashraf/workspace/rust/mcp-memory && cp target/release/mcp-memory-stub /home/riz/.local/bin/ && cp target/release/mcp-memory-linux-nvim /home/riz/.local/bin/' + Write-Host "Deploying global Agent rules (WSL)..." -ForegroundColor Cyan + wsl.exe -d Ubuntu -e bash -c 'mkdir -p /home/riz/.gemini/config/rules && cp -r /mnt/c/Users/reazul.ashraf/workspace/rust/mcp-memory/agent-rules/* /home/riz/.gemini/config/rules/' # Run configuration tests to ensure eagerTools parity test-config: