# 🛡️ MANDATORY PROTOCOL: Remote & Local Execution (AgentBox)

> [!CAUTION]
> **CRITICAL PRE-FLIGHT RULES (READ BEFORE FIRST TOOL CALL):**
> 1. **CALL MCP TOOLS DIRECTLY ON STEP 1:** Call `call_mcp_tool` (`ServerName: "agentbox"`) immediately using the JSON signatures below. **NEVER** read, list, or search `.json` schema files in `~/.gemini` or `C:\Users\...\antigravity\mcp\`!
> 2. **DYNAMIC `.agentbox.json` (LOCAL & SSH):** `agentbox mcp` automatically reloads `.agentbox.json` from the project directory on every call (including SSH `host`, `cwd`, `venv`). Always pass `"cwd": "<workspace_root>"` or full file paths so `agentbox mcp` locks onto the project's `.agentbox.json`.
> 3. **NO FULL-FILE DUMPS:** Never read entire 200+ line files — start with `agentbox_outline` or `agentbox_get_fn`, then slice with `agentbox_view`.
> 4. **BATCH MULTIPLE STEPS:** Use `agentbox_batch` when combining 2 or more operations in a single turn.

### 🚫 STRICTLY BANNED COMMANDS (LOCAL & OVER SSH):
1. DO NOT read entire files: never use `cat <file>` or download full 200+ line files -> USE `agentbox_outline` or `agentbox_view`.
2. DO NOT search files using raw find/grep: never use `find .` or raw `grep` -> USE `agentbox_tree`, `agentbox_refs`, or `agentbox_grep`.
3. DO NOT stream noisy builds or tests: never run raw `pytest`, `cargo build`, or `npm test` -> USE `agentbox_test` or `agentbox_run`.
4. DO NOT write files via `cat << 'EOF'`: shell escaping breaks quotes and symbols -> USE `agentbox_write`, `agentbox_patch`, or `agentbox_patch_lines`.
5. DO NOT dump raw git diff or log: never run raw `git diff` or `git log -p` -> USE `agentbox_diff`, `agentbox_git_log`, or `agentbox_git_view`.

### ⚡ MANDATORY MCP SIGNATURES (`call_mcp_tool`, `ServerName: "agentbox"`):
*(Вызывай `call_mcp_tool` сразу с первого же шага, НЕ читая файлы схем в `~/.gemini`!)*

#### 1. Code Navigation & Slicing
#### 1. Code Navigation & Slicing
* `agentbox_outline` → `{"path": "<file_or_dir_or_list>", "cwd"?: "<proj_dir>"}`
* `agentbox_get_fn` → `{"path": "<file>", "name": "<fn_or_Class.method>", "cwd"?: "<proj_dir>"}`
* `agentbox_find_fn` → `{"name": "<symbol>", "path"?: "<dir>", "exact"?: false, "max"?: 30}`
* `agentbox_refs` → `{"name": "<symbol>", "path"?: "<dir>", "max"?: 40}`
* `agentbox_view` → `{"path": "<file>", "start"?: 1, "end"?: 100, "tail"?: 50, "cwd"?: "<proj_dir>"}`

#### 2. Safe File Writing & Atomic Patching
* `agentbox_patch_lines` → `{"path": "<file>", "start": 1, "end": 10, "content": "...", "check_syntax"?: true, "cwd"?: "<proj_dir>"}` *(Preferred standard)*
* `agentbox_patch` → `{"path": "<file>", "old": "...", "new": "...", "all"?: false, "check_syntax"?: true, "cwd"?: "<proj_dir>"}`
* `agentbox_write` → `{"path": "<file>", "content": "...", "append"?: false, "cwd"?: "<proj_dir>"}`
* `agentbox_rollback` → `{"path": "<file>", "cwd"?: "<proj_dir>"}` *(Restores from `.agentbox/backups/`)*

#### 3. Search, Silent Builds, Tests, Venv & Batching
* `agentbox_tree` → `{"path"?: "<dir>", "depth"?: 2, "cwd"?: "<proj_dir>"}`
* `agentbox_grep` → `{"query": "<regex_or_string>", "path"?: "<dir_or_file>", "fixed"?: false, "max"?: 20, "cwd"?: "<proj_dir>"}`
* `agentbox_test` → `{"cmd": "<test_cmd>", "cwd"?: "<proj_dir>", "max_lines"?: 30, "timeout"?: 300, "venv"?: "<path>"}`
* `agentbox_run` → `{"cmd": "<build_cmd>", "cwd"?: "<proj_dir>", "tail"?: 15, "timeout"?: 300, "venv"?: "<path>"}`
* `agentbox_pip` → `{"pip_args": "install <pkg>", "cwd"?: "<proj_dir>", "venv"?: "<path>"}`
* `agentbox_batch` → `{"steps": [{"action": "view", "path": "f.py", "start": 1, "end": 20}, {"action": "patch_lines", "path": "f.py", "start": 5, "end": 8, "content": "..."}], "stop_on_error"?: true, "cwd"?: "<proj_dir>"}`
* `agentbox_stats` → `{"clear"?: false}`

#### 4. Token-Efficient Git History & Changes
* `agentbox_git_status` → `{"path"?: "<repo_dir>", "cwd"?: "<proj_dir>"}`
* `agentbox_diff` → `{"path"?: "<file_or_dir>", "rev"?: "<rev>", "cached"?: false, "max_lines"?: 100, "cwd"?: "<proj_dir>"}`
* `agentbox_git_log` → `{"path"?: "<file_or_dir>", "limit"?: 5, "cwd"?: "<proj_dir>"}`

### 💻 CLI WORKFLOW & POWERSHELL SAFE PATTERNS:

#### 1. Code Navigation & Slicing
* `agentbox outline <file> [files...]` — extracts AST classes and function signatures with line ranges (~120 tokens vs 3,000).
* `agentbox get-fn <file> <name>` — extracts exact target function, class, or `ClassName.method_name` definition.
* `agentbox find-fn <name> [path]` — scans project AST to locate where a function or class is defined across files.
* `agentbox refs <name> [path]` — finds all symbol references (imports, calls, attributes, inheritance) across the codebase.
* `agentbox view <file> --start N --end M` — views an exact line slice with 1-indexed numbers.
* `agentbox view <file> --tail N` — views last N lines of a file (or log) in a single step.

#### 2. Safe File Writing & Atomic Patching
* `agentbox patch-lines <file> --start N --end M --content "..."` — replaces 1-indexed line range `[N..M]` with auto-backup (`.agentbox/backups/`) and AST check.
* `agentbox patch-lines <file> --start N --end M --base64 <b64>` — 100% immune to PowerShell/SSH quoting and Cyrillic encoding bugs:
  ```powershell
  $b64 = [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes(@'
  Любой сложный код с "кавычками", $переменными и кириллицей
  '@))
  agentbox patch-lines file.py --start 10 --end 20 --base64 $b64
  ```
* `agentbox write <file> --content "..." [--base64 <b64>]` — safely writes/overwrites file.
* `agentbox patch <file> --old "..." --new "..."` — in-place atomic search-and-replace with auto-backup and AST check.
* `agentbox rollback <file>` — restores from `.agentbox/backups/` keeping workspace clean.

#### 3. Search, Silent Builds, Tests, Venv & Batching
* `agentbox grep "<query>" [path_or_file] [-F]` — fast search across directories OR a single file (case-insensitive regex or `-F` literal string).
* `agentbox test "<test_cmd>"` — silent test runner; suppresses passing tests and extracts high-signal failure tracebacks (auto-detects `.agentbox/venv` / `.venv`).
* `agentbox run "<build_cmd>"` — suppresses intermediate noisy terminal stream, buffering to log (auto-detects `.agentbox/venv` / `.venv`).
* `agentbox pip <args>` — runs `pip` inside isolated `.agentbox/venv` (auto-creating it if no virtualenv exists).
* `agentbox batch '<json_steps>'` / `agentbox batch --base64 <b64>` — executes multiple actions in 1 turn:
  ```json
  [
    {"action": "view", "path": "src/app.py", "start": 1, "end": 30},
    {"action": "patch_lines", "path": "src/app.py", "start": 10, "end": 12, "content": "    return True
"}
  ]
  ```
* `agentbox stats` — displays token savings and execution statistics dashboard.
* `agentbox spawn "<cmd>"` / `agentbox status <id>` / `agentbox logs <id> -f` — detached background tasks.

#### 4. Architecture & Knowledge Graph
* `agentbox graphify-query "<question>"` — queries code connections and God nodes directly on host without dumping large JSON.

#### 5. Token-Efficient Git History & Changes
* `agentbox git-status` — compact changed file status with (+add, -del) counts.
* `agentbox diff [file]` — noise-free diff (ignores lockfiles and whitespace changes).
* `agentbox git-log [file] -n N` — ultra-compact 1-line commit log.
* `agentbox git-view <file> [rev] --start N --end M` — views line slice from any Git revision without downloading full file.
* `agentbox git-fn-history <file> <fn>` — traces AST modification history of a function across Git commits.

#### 6. Project Tasks & Recipes (.agentbox.json)
* `agentbox task` / `agentbox task list` — lists available project recipes and tasks.
* `agentbox task <name> [args]` — executes saved task with optional argument substitution ({args} or appended).
* `agentbox task add <name> "<cmd>"` — saves or updates a task recipe in project `.agentbox.json`.
* `agentbox task rm <name>` — removes a task from `.agentbox.json`.

<!-- AGENTBOX_TASKS_START -->
##### 📋 Verified Project Recipes (Auto-Memoized):
* `agentbox task test` — `python -m unittest discover -s tests`
* `agentbox task test:verbose` — `python -m unittest discover -s tests -v`
<!-- AGENTBOX_TASKS_END -->

### 🔄 Самообучение и рецепты (Task Auto-Memoization):
Если в процессе работы потребовалось подобрать сложную или неочевидную команду проекта (подключение к БД, вызов внутреннего скрипта, миграция, перезапуск сервиса) — после её успешного выполнения ОБЯЗАТЕЛЬНО сохрани её как рецепт:
`agentbox task add <name> "<command>"`
и используй в дальнейшем `agentbox task <name>`, чтобы не подбирать параметры повторно.
