diff --git a/docs/en/MCP_INTEGRATION.md b/docs/en/MCP_INTEGRATION.md index 49b07733d..8565a2336 100644 --- a/docs/en/MCP_INTEGRATION.md +++ b/docs/en/MCP_INTEGRATION.md @@ -133,7 +133,7 @@ if __name__ == "__main__": ### Register Custom Server -1. Save your server to `repobrain_engine/tools/my_server.py` +1. Save your server to `engine/repobrain_engine/tools/my_server.py` 2. Add to `mcp_servers.json`: ```json @@ -141,7 +141,7 @@ if __name__ == "__main__": "name": "my-analysis", "transport": "stdio", "command": "python", - "args": ["repobrain_engine/tools/my_server.py"], + "args": ["engine/repobrain_engine/tools/my_server.py"], "enabled": true } ``` @@ -197,7 +197,7 @@ manager.shutdown() ### Server won't connect ```bash # Check if server process starts -python repobrain_engine/tools/my_server.py +python engine/repobrain_engine/tools/my_server.py # Verify command exists which npx diff --git a/docs/en/README.md b/docs/en/README.md index 353b0907a..ca37c167f 100644 --- a/docs/en/README.md +++ b/docs/en/README.md @@ -16,7 +16,7 @@ knowledge engine for grounded codebase Q&A. - **[Multi-Agent Swarm](SWARM_PROTOCOL.md)** — Orchestrate specialist agents for complex tasks ### Planning & Vision -- **[Development Roadmap](ROADMAP.md)** — Current progress and future plans through Phase 9 +- **[Development Roadmap](ROADMAP.md)** — Completed phases and architectural vision ## 🌟 Key Features @@ -74,7 +74,7 @@ server. ### For DevOps/Deployment 1. Read [Quick Start](QUICK_START.md) Docker section -2. Check [Development Roadmap](ROADMAP.md) Phase 9 (Enterprise Core) +2. Understand [Sandbox Execution](SANDBOX.md) safety boundaries 3. Configure MCP servers in [MCP Integration](MCP_INTEGRATION.md) ### For Architects @@ -101,7 +101,7 @@ server. A: Run `rb-setup` and choose one of the OpenAI-compatible providers it offers: OpenAI, DeepSeek, Groq, DashScope, NVIDIA NIM, Ollama, or a custom endpoint. The command writes `OPENAI_BASE_URL`, `OPENAI_API_KEY`, and `OPENAI_MODEL`. **Q: How do I add a custom tool?** -A: Drop a Python file in `repobrain_engine/tools/` with your functions. No registration needed! See [Zero-Config Features](ZERO_CONFIG.md). +A: Drop a Python file in `engine/repobrain_engine/tools/` with your functions. No registration needed! See [Zero-Config Features](ZERO_CONFIG.md). **Q: How do I initialize a fresh project from this template?** A: Use the `agent-repo-init` skill in `quick` or `full` mode, or run `skills/agent-repo-init/scripts/init_project.py`. See [Zero-Config Features](ZERO_CONFIG.md). @@ -136,7 +136,7 @@ Have an architectural idea? Ideas are contributions too! [Propose your thought](https://github.com/study8677/repobrain/issues/new) ### Submit Code -Ready to code? Check the [Roadmap](ROADMAP.md) Phase 9 for open areas. +Ready to code? Check the [Roadmap](ROADMAP.md) to understand the current architecture. ### Improve Docs See a typo or unclear section? Submit a PR to improve the docs! @@ -162,7 +162,7 @@ This project is licensed under the **MIT License**. See [LICENSE](../../LICENSE) --- -**Latest Update:** April 2026 -**Version:** Phase 10 (Knowledge Hub) ✅ — structured evidence pipeline + multi-language module support +**Latest Update:** August 2026 +**Current Architecture:** Generative knowledge hub + local host-runner + incremental agent-group refresh + structured evidence verification Friendly Link: [LINUX DO](https://linux.do/) diff --git a/docs/en/ROADMAP.md b/docs/en/ROADMAP.md index 3f3a7c7ff..3e4b77bdd 100644 --- a/docs/en/ROADMAP.md +++ b/docs/en/ROADMAP.md @@ -19,7 +19,7 @@ one IDE. | 6️⃣ **Dynamic Discovery** | ✅ Complete | Auto tool & context loading | | 7️⃣ **Multi-Agent Swarm** | ✅ Complete | Router-Worker orchestration | | 8️⃣ **MCP Integration** | ✅ Complete | Model Context Protocol support | -| 9️⃣ **Enterprise Core** | 🚀 In Progress | Safety boundaries, observability, deployment polish | +| 9️⃣ **Enterprise Core** | ✅ Complete | Safety boundaries, observability, deployment polish | | 🔟 **Knowledge Hub** | ✅ Complete | Multi-agent project context system | ## ✅ Completed Phases @@ -73,7 +73,7 @@ one IDE. **Goal**: Zero-config tool and knowledge loading **Achievements:** -- Automatic tool discovery from `repobrain_engine/tools/` +- Automatic tool discovery from `engine/repobrain_engine/tools/` - Auto-injection from `.context/` files - Hot reload on file changes - Docstring-based help generation @@ -82,10 +82,10 @@ one IDE. **Goal**: Collaborative multi-specialist execution **Achievements:** -- Router-Worker agent architecture -- Specialist agents (Coder, Reviewer, Researcher) -- Task decomposition and synthesis -- Artifact coordination +- **Refresh Swarm**: Three-agent handoff chain (ScanAnalyst → ArchitectureReviewer → ConventionWriter) for project analysis +- **Ask Swarm**: Dynamic Router-Worker pattern with per-module agents for grounded Q&A +- Module-based question routing with file evidence +- Git history integration for change tracking ### Phase 8: MCP Integration ✅ **Goal**: Universal external tool connectivity @@ -246,20 +246,21 @@ Ready to code? Pick a product-hardening component: **Completed:** March 2026 **Achievements:** -- Hub module (`repobrain_engine/hub/`) with scanner, agents, and pipeline +- Hub module (`engine/repobrain_engine/hub/`) with scanner, agents, refresh/ask pipelines - `rb-refresh` — scans project and generates `.repobrain/conventions.md` via LLM - `rb-ask` — answers project questions using reviewer agent - `rb report` / `rb log-decision` — local memory and decision logging - OpenAI Agent SDK integration with LiteLLM for model flexibility -## 📈 Adoption Timeline +## 📈 Development Timeline -- **2024 H2**: Foundation through MCP Integration (Phases 1–8) — completed -- **2025**: Enterprise Core (Phase 9) — sandbox MVP, safety docs, observability -- **2026 Q1**: Knowledge Hub (Phase 10) — completed -- **2026+**: public repository knowledge engine hardening +- **2024 H2**: Foundation through MCP Integration (Phases 1–8) ✅ +- **2025**: Enterprise Core (Phase 9) — sandbox MVP, safety docs, observability ✅ +- **2026 Q1–Q2**: Knowledge Hub (Phase 10) — generation storage, structured evidence, multi-language adapters ✅ +- **2026 Q3** (current): Host-runner backend, incremental refresh, agent-group architecture ✅ +- **2026+**: Continued refinement and community-driven features -*(Timeline is aspirational and dependent on community adoption)* +*(Development is community-driven and evolves based on real-world usage)* ## 💡 Product Use Cases diff --git a/docs/en/SWARM_PROTOCOL.md b/docs/en/SWARM_PROTOCOL.md index f1c877464..0080ff70d 100644 --- a/docs/en/SWARM_PROTOCOL.md +++ b/docs/en/SWARM_PROTOCOL.md @@ -1,239 +1,299 @@ -# 🔥 Multi-Agent Swarm Protocol +# 🔥 Multi-Agent Collaboration Model -## 🪐 Architecture: Router-Worker Pattern +## 🪐 Architecture Overview -The RepoBrain Workspace includes a sophisticated multi-agent swarm system based on the Router-Worker pattern. This allows complex tasks to be decomposed and handled by specialist agents working in coordination. +RepoBrain uses two specialized Agent Swarms to power its core functionality: + +1. **Refresh Swarm** — Scans the project and generates knowledge artifacts +2. **Ask Swarm** — Answers codebase questions using the generated knowledge base + +These swarms are defined in `engine/repobrain_engine/hub/agents.py` and driven by `refresh_pipeline.py` and `ask_pipeline.py`. + +## 🔄 Refresh Swarm: Three-Stage Analysis Chain + +When you run `rb-refresh`, the Refresh Swarm analyzes your codebase and generates a project conventions document. + +### Architecture: Three-Agent Handoff Chain ```mermaid -graph TD - User[User Task] --> Router[🧭 Router Agent] - Router --> Coder[💻 Coder Agent] - Router --> Reviewer[🔍 Reviewer Agent] - Router --> Researcher[📚 Researcher Agent] - Coder --> Router - Reviewer --> Router - Researcher --> Router - Router --> Result[📊 Synthesized Result] +graph LR + Scan[Scan Report] --> SA[ScanAnalyst] + SA --> AR[ArchitectureReviewer] + AR --> CW[ConventionWriter] + CW --> Doc[conventions.md] ``` -## 🧠 Specialist Agents +### The Three Agent Roles -### 🧭 Router Agent -**Role**: Task analyzer, strategist, and conductor +#### 🔍 ScanAnalyst +**Responsibility:** Code analysis specialist focusing on language and framework detection -The Router analyzes incoming tasks, determines the best decomposition strategy, delegates subtasks to specialists, and synthesizes final results. +**Analyzes:** +- Programming languages and their distribution (primary vs secondary) +- Detected frameworks and libraries (web, data, ML, etc.) +- Code patterns and style observations (naming, structure, idioms) +- Dependency management approach -**Capabilities:** -- 🎯 Complex task analysis -- 📋 Strategic planning -- 🔀 Work distribution -- 🧩 Result synthesis +Hands off to ArchitectureReviewer when complete. -### 💻 Coder Agent -**Role**: Implementation specialist +#### 🏗️ ArchitectureReviewer +**Responsibility:** Software architecture reviewer -Writes clean, well-documented, production-ready code following Google style guide conventions. +**Analyzes:** +- Project directory structure and organization patterns +- Testing approach, framework, and coverage indicators +- CI/CD pipeline setup and automation +- Docker/container configuration +- Build system and packaging approach +- Configuration management patterns -**Specialties:** -- 🐍 Python development -- 🎨 Clean code architecture -- 📝 Comprehensive docstrings -- 🧪 Test coverage +Builds on the previous agent's analysis and adds structural findings, then hands off to ConventionWriter. -### 🔍 Reviewer Agent -**Role**: Quality assurance expert +#### ✍️ ConventionWriter +**Responsibility:** Technical documentation writer specialist -Reviews implementations for correctness, security, performance, and best practices. +**Produces:** +Using ALL analysis from the previous agents, produces a concise conventions document (Markdown format) covering: +- Primary language(s) and framework(s) +- Project structure overview +- Code style observations +- Testing approach +- CI/CD setup -**Specialties:** -- ✅ Code quality assessment -- 🔒 Security analysis -- ⚡ Performance optimization -- 📋 Best practice verification +Keeps it under 300 words, outputs ONLY Markdown content. -### 📚 Researcher Agent -**Role**: Information gatherer and investigator +### Implementation Location -Researches solutions, gathers context, and provides foundational knowledge for complex tasks. +- **Code:** `build_refresh_swarm()` in `engine/repobrain_engine/hub/agents.py` +- **Pipeline:** `engine/repobrain_engine/hub/refresh_pipeline.py` +- **Storage:** Generated knowledge saved to `.repobrain/` directory (in target project, not this repo) -**Specialties:** -- 🔎 Problem research -- 📚 Information synthesis -- 🧠 Context gathering -- 💡 Insight generation +### Host-Runner Mode -## 🚀 Using the Swarm +When no API key is configured (`RB_HOST_RUNNER` set to `codex` or `generic`), Refresh uses a single-turn, tool-free Convention Agent (`build_single_turn_convention_agent()`) that collapses the three-stage chain into one generation. -### Run Interactive Demo +## 💬 Ask Swarm: Dynamic Module Router -```bash -python -m repobrain_engine.swarm_demo +When you run `rb-ask "question"`, the Ask Swarm routes your question to the relevant module's agent and returns an answer with file paths and line numbers. + +### Architecture: Router-Worker Pattern + +```mermaid +graph TD + User[User Question] --> Router[Router Agent] + Router --> MA1[ModuleAgent: auth] + Router --> MA2[ModuleAgent: api] + Router --> MA3[ModuleAgent: database] + Router --> Git[GitAgent: git history] + MA1 --> Router + MA2 --> Router + MA3 --> Router + Git --> Router + Router --> Answer[Final Answer + Citations] ``` -This launches an interactive prompt where you can assign tasks to the swarm and watch specialists collaborate. +### Agent Roles -### Example Interaction +#### 🧭 Router Agent +**Responsibility:** Question routing and answer synthesis -``` -🧭 [Router] What task would you like me to help with? -> Build a calculator that supports basic math operations and review it for security - -🧭 [Router] Analyzing task... -📤 [Router → Coder] Build a calculator with +, -, *, / operations -💻 [Coder] Creating calculator implementation... -📝 [Coder] Generating comprehensive tests... -✅ [Coder] Implementation complete! - -📤 [Router → Reviewer] Review calculator for security and best practices -🔍 [Reviewer] Analyzing code structure... -🔍 [Reviewer] Security assessment: No vulnerabilities found ✅ -🔍 [Reviewer] Performance assessment: Optimal ✅ -✅ [Reviewer] Review complete! - -🎉 [Router] Task completed successfully! -📊 Final Summary: - - Implementation: calculator.py ✅ - - Tests: calculator_test.py ✅ - - Review: All checks passed ✅ -``` +**Workflow:** +1. Reads the user's question +2. Identifies relevant module(s) based on project structure map +3. Hands off to the appropriate ModuleAgent +4. For git-related questions (recent changes, commit history), hands off to GitAgent +5. For cross-module questions, hands off to one module first; that module can hand off to others as needed +6. Synthesizes findings from agents into a final answer -### Programmatic Usage +**Answer Requirements:** +- Lead with a direct answer to the question +- **Cite specific file paths, line numbers, and function names** +- Include commit history when it explains "why" +- Be concise (under 200 words unless the question demands more) -```python -from repobrain_engine.swarm import SwarmOrchestrator +#### 📦 ModuleAgent (Dynamically Created) +**Responsibility:** Deep knowledge of a specific module -swarm = SwarmOrchestrator() -result = swarm.execute("Build a file compression utility with error handling") -print(result) # final synthesized string -``` +Each module gets its own agent with: +- Module's structured facts (JSON claims + source evidence) +- Tools to explore code (read_file, search_code, etc.) +- Ability to hand off to other ModuleAgents for cross-module information -## 🔧 Configuration +ModuleAgents are created dynamically based on the project scan (one agent per detected module). -Current implementation uses a built-in worker map in `repobrain_engine/swarm.py`. -There is no external `swarm_config.json` loader yet. +#### 📜 GitAgent +**Responsibility:** Git history and change analysis -### Custom Agents +Handles questions about: +- Recent commits and changes +- Who changed what +- Change history and rationale +- Blame information -Add custom specialist agents by extending `BaseAgent`: +### Implementation Location -```python -# repobrain_engine/agents/custom_agent.py -from repobrain_engine.agents.base_agent import BaseAgent +- **Code:** Router and ModuleAgent building logic in `engine/repobrain_engine/hub/agents.py` +- **Pipeline:** `engine/repobrain_engine/hub/ask_pipeline.py` +- **Knowledge:** Reads from generation directory pointed to by `.repobrain/current.json` -class DataAnalystAgent(BaseAgent): - """Specialist agent for data analysis tasks.""" - - def __init__(self, name="DataAnalyst"): - super().__init__(name=name) - self.specialization = "data analysis" - - def execute(self, task: str) -> str: - """Execute data analysis task.""" - # Implementation here - return result -``` +### Fallback Strategy -Register in `swarm.py`: +The ask pipeline implements a three-tier fallback mechanism: -```python -from repobrain_engine.agents.custom_agent import DataAnalystAgent +1. **`_ask_with_structured_facts`** — Uses structured facts (JSON claims + source verification) +2. **`_ask_with_agent_md`** — Falls back to agent.md files (plain text knowledge) +3. **`_ask_with_legacy_swarm`** — Final fallback (if both fail) -agents = { - "coder": CoderAgent(), - "reviewer": ReviewerAgent(), - "researcher": ResearcherAgent(), - "data_analyst": DataAnalystAgent(), # Add custom agent -} -``` +This ensures ask functionality remains available even if knowledge base is partially generated or uses older formats. + +## 🔧 Configuration & Extension + +### Using Different LLM Backends + +1. **API-based (standard):** + ```bash + rb-setup # Choose OpenAI, DeepSeek, Groq, etc. + ``` -## 📊 Monitoring & Logging +2. **Host-runner (no API key):** + ```bash + export RB_HOST_RUNNER=codex # or generic + # Uses logged-in IDE CLI, no API key needed + ``` -### Runtime Output +3. **Custom OpenAI-compatible endpoint:** + ```bash + export OPENAI_BASE_URL=https://your-endpoint.com/v1 + export OPENAI_API_KEY=your-key + export OPENAI_MODEL=your-model + ``` -`SwarmOrchestrator.execute(..., verbose=True)` prints delegation and progress logs -to stdout. You can also inspect in-memory message history: +### Incremental Refresh (`--quick`) -```python -from repobrain_engine.swarm import SwarmOrchestrator +For clean worktrees with committed changes: -swarm = SwarmOrchestrator() -swarm.execute("Build and review a calculator", verbose=False) -messages = swarm.get_message_log() -print(messages) +```bash +rb-refresh --quick ``` -The current implementation does not automatically write swarm logs/artifacts to disk. +This triggers incremental refresh: +- **ImpactPlanner** analyzes git diff to determine affected modules +- **ImpactVerifier** verifies impact analysis +- Only affected agent-groups are refreshed +- Significantly speeds up iteration on large codebases -## ⚡ Performance Tips +Implementation: `engine/repobrain_engine/hub/incremental.py` -### Optimize Execution -- 🎯 Keep task descriptions clear and focused -- 📦 Pre-load context for better agent understanding -- ⏱️ Keep subtasks concrete so router delegation is predictable +## 📊 Workflow Examples -### Resource Management -- 🚫 Disable or remove unused workers directly in `repobrain_engine/swarm.py` -- 💾 Implement result caching -- 🧹 Clean old artifacts periodically +### Example 1: Initialize New Project -## 🐛 Troubleshooting +```bash +# 1. Set up backend +rb-setup + +# 2. Scan project and build knowledge base +rb-refresh + +# 3. Verify knowledge base +rb report # Shows detected modules, languages, etc. + +# 4. Start asking questions +rb-ask "How does authentication work?" +``` + +### Example 2: Incremental Updates -### Agents won't connect ```bash -# Check if swarm can initialize -python -c "from repobrain_engine.swarm import SwarmOrchestrator; SwarmOrchestrator(); print('ok')" +# Make some changes and commit +git add . +git commit -m "Update auth logic" + +# Quick incremental refresh (only affected modules) +rb-refresh --quick + +# Verify updates +rb-ask "What changed in the auth module?" ``` -### Task execution hangs +### Example 3: Debugging Usage + ```bash -# Run with verbose=False to reduce console noise and inspect message bus -python -c "from repobrain_engine.swarm import SwarmOrchestrator; s=SwarmOrchestrator(); s.execute('test', verbose=False); print(s.get_message_log())" +# Refresh with debug logging +RB_LOG_LEVEL=DEBUG rb-refresh + +# Ask with verbose output +RB_LOG_LEVEL=DEBUG rb-ask "Where is the database connection?" ``` -### Low quality results -- 📚 Provide more context to the swarm -- 🎯 Be more specific in task descriptions -- 🔄 Enable reviewer agent for quality checks - -## 📚 Examples - -### Example 1: Web Scraper Development -```python -from repobrain_engine.swarm import SwarmOrchestrator - -swarm = SwarmOrchestrator() -result = swarm.execute( - """ - Build a web scraper that: - 1. Fetches news articles from a website - 2. Extracts headline, author, date - 3. Stores in JSON format - 4. Includes error handling - """ -) +## 🐛 Troubleshooting + +### Agent Initialization Fails + +```bash +# Check if Agent SDK is installed +pip show openai-agents + +# Verify LLM configuration +cat .env | grep OPENAI ``` -### Example 2: API Server with Testing -```python -result = swarm.execute( - """ - Create a Flask REST API with: - - GET /users endpoint - - POST /users endpoint with validation - - Comprehensive unit tests - - Security review for vulnerabilities - """ -) +### Incomplete Knowledge Base + +```bash +# Check refresh status +rb report + +# Force full refresh (non-incremental) +rb-refresh # without --quick + +# Check generation logs +ls -la .repobrain/ +cat .repobrain/current.json ``` -## 📞 Advanced Topics +### Ask Returns "Not Found" + +Possible causes: +1. Knowledge base not generated or stale → Run `rb-refresh` +2. Module not detected by scanner → Check `rb report` output +3. Question routed to wrong module → Try more specific question + +## 🔗 MCP Integration + +RepoBrain exposes its core functionality as MCP tools via `rb-mcp`: + +- **`ask_project`** — Answer codebase questions +- **`refresh_project`** — Refresh knowledge base + +MCP server implementation: `engine/repobrain_engine/hub/mcp_server.py` + +## 🚀 Performance Tips + +### Speed Up Refresh +- Use `--quick` for incremental updates (clean worktree after commit) +- Exclude unnecessary directories (configure ignore patterns in `.repobrain/config.json`) +- Use faster models (e.g., GPT-4o-mini or Claude 3.5 Haiku) + +### Improve Answer Quality +- Keep knowledge base up to date (run `rb-refresh` regularly) +- Ask specific questions (mention file names, features, or modules) +- Use higher-capability models for complex queries + +## 📚 References -- **Custom Agent Development**: Extend `BaseAgent` for specialized domains -- **Custom Orchestration**: Extend `SwarmOrchestrator` for different routing/execution policies -- **Inter-Agent Communication**: Use message passing for complex coordination -- **Result Verification**: Implement custom verification strategies +### Core Files +- `engine/repobrain_engine/hub/agents.py` — Agent definitions +- `engine/repobrain_engine/hub/refresh_pipeline.py` — Refresh workflow +- `engine/repobrain_engine/hub/ask_pipeline.py` — Ask workflow +- `engine/repobrain_engine/hub/incremental.py` — Incremental refresh +- `engine/repobrain_engine/hub/host_runner.py` — Local CLI backend +- `engine/repobrain_engine/hub/storage.py` — Knowledge storage -See [Full Index](README.md) for more resources. +### Related Documentation +- [Project Philosophy](PHILOSOPHY.md) — Product boundaries and support scope +- [Zero-Config Features](ZERO_CONFIG.md) — Tool and context discovery +- [Quick Start](QUICK_START.md) — Installation and first steps --- diff --git a/docs/en/ZERO_CONFIG.md b/docs/en/ZERO_CONFIG.md index b2e43f892..e64860edc 100644 --- a/docs/en/ZERO_CONFIG.md +++ b/docs/en/ZERO_CONFIG.md @@ -6,13 +6,13 @@ ## 🛠️ Auto Tool Discovery -Drop any Python file into `repobrain_engine/tools/` and the agent will use it immediately—no imports, no registration, no boilerplate. +Drop any Python file into `engine/repobrain_engine/tools/` and the agent will use it immediately—no imports, no registration, no boilerplate. ### How It Works 1. **Define Your Tool**: ```python -# repobrain_engine/tools/sentiment_analyzer.py +# engine/repobrain_engine/tools/sentiment_analyzer.py def analyze_sentiment(text: str) -> dict: """Analyzes the sentiment of given text. @@ -43,7 +43,7 @@ The agent will automatically discover and use `analyze_sentiment()`. ### Tool Discovery Mechanics The discovery process: -1. 🔍 Scans `repobrain_engine/tools/` for all `.py` files +1. 🔍 Scans `engine/repobrain_engine/tools/` for all `.py` files 2. 📋 Indexes all top-level functions 3. 📚 Extracts docstrings for help text 4. 🔗 Registers public module-level functions with the agent @@ -94,7 +94,7 @@ def my_tool(param1: str, param2: int) -> str: ### Multiple Files Example ``` -repobrain_engine/tools/ +engine/repobrain_engine/tools/ ├── sentiment_analyzer.py │ └── analyze_sentiment() ├── data_processor.py @@ -110,14 +110,14 @@ All 7 functions are automatically discovered and available to the agent! ## 🎓 Auto Skill Discovery -Drop a folder under `repobrain_engine/skills/` with `SKILL.md` and optional `tools.py`, and the agent will load both: +Drop a folder under `engine/repobrain_engine/skills/` with `SKILL.md` and optional `tools.py`, and the agent will load both: - Skill docs from `SKILL.md` into prompt context - Public functions from `tools.py` as callable tools ### Built-in Example: `agent-repo-init` This repository includes: -- `repobrain_engine/skills/agent-repo-init/`: in-agent skill integration (`init_agent_repo`) +- `engine/repobrain_engine/skills/agent-repo-init/`: in-agent skill integration (`init_agent_repo`) - `skills/agent-repo-init/`: portable skill package with script runner `agent-repo-init` supports: @@ -212,7 +212,7 @@ This directory contains all context automatically injected into the agent. ### Step 2: Add Tools (What the agent can do) ```python -# repobrain_engine/tools/db_query.py +# engine/repobrain_engine/tools/db_query.py def query_users(email_pattern: str) -> list: """Query users by email pattern.""" # Implementation @@ -251,18 +251,18 @@ The agent: ## 🔄 Hot Reload -Tools are discovered at agent startup, so after changing `repobrain_engine/tools/` you should restart the agent. +Tools are discovered at agent startup, so after changing `engine/repobrain_engine/tools/` you should restart the agent. Context files are loaded from `.context/*.md` on agent run. ## 🐛 Troubleshooting ### Tools not appearing ```bash -# 1. Check file is in repobrain_engine/tools/ -ls -la repobrain_engine/tools/ +# 1. Check file is in engine/repobrain_engine/tools/ +ls -la engine/repobrain_engine/tools/ # 2. Verify it's valid Python -python -m py_compile repobrain_engine/tools/my_tool.py +python -m py_compile engine/repobrain_engine/tools/my_tool.py # 3. Check for syntax errors python -c "import repobrain_engine.tools.my_tool" @@ -306,7 +306,7 @@ rb-refresh --workspace . echo "Users must be at least 18 years old" > .context/age_requirement.md # Add tool to validate age -cat > repobrain_engine/tools/age_validator.py << 'EOF' +cat > engine/repobrain_engine/tools/age_validator.py << 'EOF' def validate_age(birth_date: str) -> bool: """Check if person is at least 18 years old.""" # Implementation @@ -329,7 +329,7 @@ Creates a new user EOF # Tool to create users -cat > repobrain_engine/tools/user_service.py << 'EOF' +cat > engine/repobrain_engine/tools/user_service.py << 'EOF' def create_user(email: str, name: str, age: int = None) -> dict: """Create a new user in the system.""" # Validates per context requirements automatically diff --git a/docs/es/README.md b/docs/es/README.md index 798eddf8e..b6752ceeb 100644 --- a/docs/es/README.md +++ b/docs/es/README.md @@ -17,7 +17,7 @@ de archivos. - **[Protocolo de Swarm](SWARM_PROTOCOL.md)** — Orquestación de agentes especialistas para tareas complejas ### Planificación y Visión -- **[Hoja de Ruta de Desarrollo](ROADMAP.md)** — Progreso actual y planes futuros hasta Fase 9 +- **[Hoja de Ruta de Desarrollo](ROADMAP.md)** — Fases completadas y visión arquitectónica ## 🌟 Características Clave @@ -25,7 +25,7 @@ de archivos. La resumización recursiva comprime automáticamente el historial—los límites de contexto se acabaron. ### 🛠️ Protocolo Universal de Herramientas -Patrón genérico ReAct. Solo registra cualquier función Python en `repobrain_engine/tools/`, y el Agente aprende a usarla automáticamente. +Patrón genérico ReAct. Solo coloca cualquier función Python en `engine/repobrain_engine/tools/`, y el Agente aprende a usarla automáticamente. ### 🎓 Inicialización de Proyectos con Skills Usa la skill integrada `agent-repo-init` para crear un repositorio limpio desde esta plantilla. @@ -56,27 +56,29 @@ Llama cualquier API compatible con OpenAI mediante la herramienta integrada `cal ``` . -├── .repobrain/ # 🛸 Base de conocimiento generada -├── .context/ # 📚 Contexto adicional opcional -├── artifacts/ # 📂 Outputs del agente (planes, logs, visuales) -├── repobrain_engine/ # 🧠 Código fuente del agente -│ ├── hub/ # Knowledge Hub (escáner, agentes, pipeline) -│ ├── mcp_server.py # Servidor MCP (rb-mcp) -│ ├── memory.py # Memoria Markdown -│ ├── mcp_client.py # Integración de MCP -│ ├── swarm.py # Orquestación multi-agente -│ ├── agents/ # Agentes especialistas -│ │ ├── base_agent.py -│ │ ├── coder_agent.py -│ │ ├── reviewer_agent.py -│ │ └── researcher_agent.py -│ ├── tools/ # Herramientas MCP y extensiones -│ └── sandbox/ # Ejecución local / microsandbox -├── tests/ # ✅ Suite de pruebas -├── scripts/ # 🧪 Scripts de utilidad -├── docker-compose.yml # Stack de desarrollo local -├── README.md # Página principal de aterrizaje -└── pyproject.toml # Dependencias Python +├── cli/ # rb CLI, plantillas IDE, herramientas offline +├── engine/repobrain_engine/ # Motor de conocimiento, hub, servidor MCP, sandbox +│ ├── hub/ # Knowledge Hub +│ │ ├── scanner.py # Escáner de módulos +│ │ ├── refresh_pipeline.py # Pipeline de generación de conocimiento +│ │ ├── ask_pipeline.py # Pipeline de preguntas y respuestas +│ │ ├── agents.py # Refresh/Ask Swarm agents +│ │ ├── incremental.py # Actualización incremental (--quick) +│ │ ├── host_runner.py # Backend CLI local (sin API key) +│ │ ├── mcp_server.py # Servidor rb-mcp +│ │ ├── storage.py # Almacenamiento de base de conocimiento (current.json) +│ │ └── language_adapters/ # Adaptadores multi-lenguaje +│ ├── tools/ # Implementación de herramientas +│ ├── sandbox/ # Ejecución local / microsandbox +│ ├── skills/ # Skills (research, knowledge-layer, etc.) +│ ├── memory.py # Gestión de memoria Markdown +│ └── mcp_client.py # Integración MCP +├── commands/ # Definiciones de slash commands compartidos +├── skills/ # Skills orientados a plugins +├── docs/ # Documentación multi-idioma +├── artifacts/ # Planes, informes, salidas de benchmarks +├── memory/ # Memoria de interacción Markdown +└── .repobrain/ # Base de conocimiento generada en repos objetivo ``` ## 🎓 Documentación por Rol @@ -88,7 +90,7 @@ Llama cualquier API compatible con OpenAI mediante la herramienta integrada `cal ### Para DevOps/Despliegue 1. Lee [Inicio Rápido](QUICK_START.md) sección Docker -2. Consulta [Hoja de Ruta de Desarrollo](ROADMAP.md) Fase 9 (Enterprise Core) +2. Comprende [Sandbox](SANDBOX.md) fronteras de seguridad 3. Configura servidores MCP en [Integración de MCP](MCP_INTEGRATION.md) ### Para Arquitectos @@ -98,7 +100,7 @@ Llama cualquier API compatible con OpenAI mediante la herramienta integrada `cal ### Para Contribuidores 1. Lee [Filosofía del Proyecto](PHILOSOPHY.md) -2. Consulta [Hoja de Ruta de Desarrollo](ROADMAP.md) Fase 9 +2. Consulta [Hoja de Ruta de Desarrollo](ROADMAP.md) arquitectura actual 3. Abre un issue para proponer ideas ## 🔗 Recursos Externos @@ -115,7 +117,7 @@ Llama cualquier API compatible con OpenAI mediante la herramienta integrada `cal R: Ejecuta `rb-setup` y elige OpenAI, DeepSeek, Groq, DashScope, NVIDIA NIM, Ollama o un endpoint OpenAI-compatible personalizado. El comando escribe `OPENAI_BASE_URL`, `OPENAI_API_KEY` y `OPENAI_MODEL` en `.env`. **P: ¿Cómo agrego una herramienta personalizada?** -R: ¡Coloca un archivo Python en `repobrain_engine/tools/` con tus funciones. Sin registro necesario! Ver [Características Zero-Config](ZERO_CONFIG.md). +R: ¡Coloca un archivo Python en `engine/repobrain_engine/tools/` con tus funciones. Sin registro necesario! Ver [Características Zero-Config](ZERO_CONFIG.md). **P: ¿Cómo inicializo un proyecto nuevo desde esta plantilla?** R: Usa la skill `agent-repo-init` en modo `quick` o `full`, o ejecuta `skills/agent-repo-init/scripts/init_project.py`. Ver [Características Zero-Config](ZERO_CONFIG.md). @@ -150,7 +152,7 @@ Bienvenemos contribuciones en todos los niveles: [Propón tu pensamiento](https://github.com/study8677/repobrain/issues/new) ### Enviar Código -¿Listo para codificar? Consulta la [Hoja de Ruta](ROADMAP.md) Fase 9 para áreas abiertas. +¿Listo para codificar? Consulta la [Hoja de Ruta](ROADMAP.md) para comprender la arquitectura actual. ### Mejorar Documentación ¿Ves un typo o sección poco clara? ¡Envía un PR para mejorar los docs! @@ -176,8 +178,8 @@ Este proyecto está bajo la licencia **MIT**. Ver [LICENSE](../../LICENSE) para --- -**Última Actualización:** Abril 2026 -**Versión:** Fase 10 (Knowledge Hub) ✅ — pipeline de evidencia estructurada + soporte multi-lenguaje +**Última Actualización:** Agosto 2026 +**Arquitectura Actual:** Knowledge Hub generativo + host-runner local + actualización incremental agent-group + verificación de evidencia estructurada **¡Feliz construcción con RepoBrain!** 🚀 diff --git a/docs/es/ROADMAP.md b/docs/es/ROADMAP.md index 2b4cb228d..62da5786f 100644 --- a/docs/es/ROADMAP.md +++ b/docs/es/ROADMAP.md @@ -18,16 +18,27 @@ código y expone la misma capa mediante plugins, CLI y MCP. | 6 Descubrimiento Dinámico | Completa | Herramientas y contexto zero-config | | 7 Multi-Agent Swarm | Completa | Orquestación Router-Worker | | 8 MCP Integration | Completa | Soporte MCP server / consumer | -| 9 Endurecimiento de Producto | En progreso | Fronteras de seguridad, observabilidad, docs e instalación | +| 9 Endurecimiento de Producto | Completa | Fronteras de seguridad, observabilidad, docs e instalación | | 10 Knowledge Hub | Completa | Refresh del codebase, conocimiento modular y Q&A enrutado | -## Foco de Fase 9 - -- Sandbox: frontera local confiable, opt-in a Microsandbox/E2B y warnings de fallback. -- Retrieval graph: mantener experiencia de desarrollo con redacción de secretos y documentación de riesgos. -- MCP: conservar comodidad opt-in y aclarar `RB_ALLOW_MCP`, entorno y permisos de servidores externos. -- Instalación y documentación: sostener la línea `rb-setup -> rb-refresh -> rb-ask`. -- Contract checks: verificar scripts de instalación, docs de sandbox, modelo por defecto y quick starts. +## Funcionalidad Principal Completada (Hasta Agosto 2026) + +### Fase 9: Endurecimiento de Producto ✅ +- **Sandbox**: frontera local confiable, opt-in a Microsandbox/E2B y warnings de fallback +- **Retrieval graph**: mantener experiencia de desarrollo con redacción de secretos y documentación de riesgos +- **MCP**: conservar comodidad opt-in y aclarar `RB_ALLOW_MCP`, entorno y permisos de servidores externos +- **Instalación y documentación**: sostener la línea `rb-setup -> rb-refresh -> rb-ask` +- **Contract checks**: verificar scripts de instalación, docs de sandbox, modelo por defecto y quick starts + +### Fase 10: Knowledge Hub ✅ +- **Almacenamiento generativo**: base de conocimiento modular en directorio `.repobrain/` +- **Evidencia estructurada**: claims JSON + verificación de fuente (ruta de archivo + rango de líneas) +- **Soporte multi-lenguaje**: Python, TypeScript/JavaScript, Go, Rust, Java, Kotlin, Swift, C/C++, C# +- **Host-runner**: backend CLI local (RB_HOST_RUNNER), sin necesidad de API key +- **Refresh incremental**: `rb-refresh --quick` solo actualiza agent-groups afectados +- **Arquitectura de agentes**: + - Refresh Swarm: ScanAnalyst → ArchitectureReviewer → ConventionWriter + - Ask Swarm: Router + ModuleAgent dinámico + GitAgent ## Casos de Uso diff --git a/docs/es/SWARM_PROTOCOL.md b/docs/es/SWARM_PROTOCOL.md index 570c49402..09d74de7b 100644 --- a/docs/es/SWARM_PROTOCOL.md +++ b/docs/es/SWARM_PROTOCOL.md @@ -1,126 +1,300 @@ -# 🔥 Protocolo de Swarm Multi-Agente +# 🔥 Modelo de Colaboración Multi-Agente -## 🪐 Arquitectura: Patrón Router-Worker +## 🪐 Descripción General de la Arquitectura -El RepoBrain Workspace incluye un sistema de swarm de múltiples agentes sofisticado basado en el patrón Router-Worker. Esto permite descomponer tareas complejas y manejarlas con agentes especialistas trabajando en coordinación. +RepoBrain utiliza dos Swarms de Agentes especializados para impulsar su funcionalidad central: + +1. **Refresh Swarm** — Escanea el proyecto y genera artefactos de conocimiento +2. **Ask Swarm** — Responde preguntas sobre el codebase usando la base de conocimiento generada + +Estos swarms están definidos en `engine/repobrain_engine/hub/agents.py` e impulsados por `refresh_pipeline.py` y `ask_pipeline.py`. + +## 🔄 Refresh Swarm: Cadena de Análisis en Tres Etapas + +Cuando ejecutas `rb-refresh`, el Refresh Swarm analiza tu codebase y genera un documento de convenciones del proyecto. + +### Arquitectura: Cadena de Handoff de Tres Agentes + +```mermaid +graph LR + Scan[Reporte de Escaneo] --> SA[ScanAnalyst] + SA --> AR[ArchitectureReviewer] + AR --> CW[ConventionWriter] + CW --> Doc[conventions.md] +``` + +### Los Tres Roles de Agentes + +#### 🔍 ScanAnalyst +**Responsabilidad:** Especialista en análisis de código enfocado en detección de lenguajes y frameworks + +**Analiza:** +- Lenguajes de programación y su distribución (primarios vs secundarios) +- Frameworks y bibliotecas detectados (web, datos, ML, etc.) +- Observaciones de patrones y estilos de código (nomenclatura, estructura, idiomas) +- Enfoque de gestión de dependencias + +Pasa el control a ArchitectureReviewer al completar. + +#### 🏗️ ArchitectureReviewer +**Responsabilidad:** Revisor de arquitectura de software + +**Analiza:** +- Estructura de directorios del proyecto y patrones de organización +- Enfoque de pruebas, framework e indicadores de cobertura +- Configuración de pipeline CI/CD y automatización +- Configuración de Docker/contenedores +- Sistema de construcción y enfoque de empaquetado +- Patrones de gestión de configuración + +Se basa en el análisis del agente anterior y añade hallazgos estructurales, luego pasa el control a ConventionWriter. + +#### ✍️ ConventionWriter +**Responsabilidad:** Especialista en redacción de documentación técnica + +**Produce:** +Usando TODO el análisis de los agentes anteriores, produce un documento de convenciones conciso (formato Markdown) que cubre: +- Lenguaje(s) y framework(s) principales +- Descripción general de la estructura del proyecto +- Observaciones de estilo de código +- Enfoque de pruebas +- Configuración CI/CD + +Lo mantiene bajo 300 palabras, genera SOLO contenido Markdown. + +### Ubicación de Implementación + +- **Código:** `build_refresh_swarm()` en `engine/repobrain_engine/hub/agents.py` +- **Pipeline:** `engine/repobrain_engine/hub/refresh_pipeline.py` +- **Almacenamiento:** Conocimiento generado guardado en directorio `.repobrain/` (en proyecto objetivo, no en este repo) + +### Modo Host-Runner + +Cuando no hay API key configurada (`RB_HOST_RUNNER` establecido en `codex` o `generic`), Refresh usa un Agente de Convenciones de turno único sin herramientas (`build_single_turn_convention_agent()`) que colapsa la cadena de tres etapas en una sola generación. + +## 💬 Ask Swarm: Enrutador de Módulos Dinámico + +Cuando ejecutas `rb-ask "pregunta"`, el Ask Swarm enruta tu pregunta al agente del módulo relevante y devuelve una respuesta con rutas de archivo y números de línea. + +### Arquitectura: Patrón Router-Worker ```mermaid graph TD - User[Tarea del Usuario] --> Router[🧭 Router Agent] - Router --> Coder[💻 Coder Agent] - Router --> Reviewer[🔍 Reviewer Agent] - Router --> Researcher[📚 Researcher Agent] - Coder --> Router - Reviewer --> Router - Researcher --> Router - Router --> Result[📊 Resultado Sintetizado] + User[Pregunta del Usuario] --> Router[Router Agent] + Router --> MA1[ModuleAgent: auth] + Router --> MA2[ModuleAgent: api] + Router --> MA3[ModuleAgent: database] + Router --> Git[GitAgent: historial git] + MA1 --> Router + MA2 --> Router + MA3 --> Router + Git --> Router + Router --> Answer[Respuesta Final + Citas] ``` -## 🧠 Agentes Especialistas +### Roles de Agentes + +#### 🧭 Router Agent +**Responsabilidad:** Enrutamiento de preguntas y síntesis de respuestas + +**Flujo de Trabajo:** +1. Lee la pregunta del usuario +2. Identifica módulo(s) relevante(s) basado en el mapa de estructura del proyecto +3. Pasa el control al ModuleAgent apropiado +4. Para preguntas relacionadas con git (cambios recientes, historial de commits), pasa el control a GitAgent +5. Para preguntas entre módulos, pasa el control a un módulo primero; ese módulo puede pasar el control a otros según sea necesario +6. Sintetiza los hallazgos de los agentes en una respuesta final + +**Requisitos de Respuesta:** +- Comenzar con una respuesta directa a la pregunta +- **Citar rutas de archivo específicas, números de línea y nombres de funciones** +- Incluir historial de commits cuando explique el "por qué" +- Ser conciso (bajo 200 palabras a menos que la pregunta demande más) + +#### 📦 ModuleAgent (Creado Dinámicamente) +**Responsabilidad:** Conocimiento profundo de un módulo específico + +Cada módulo obtiene su propio agente con: +- Facts estructurados del módulo (claims JSON + evidencia de fuente) +- Herramientas para explorar código (read_file, search_code, etc.) +- Capacidad de pasar el control a otros ModuleAgents para información entre módulos + +Los ModuleAgents se crean dinámicamente basados en el escaneo del proyecto (un agente por módulo detectado). -### 🧭 Agente Router -**Rol**: Analizador de tareas, estratega y director +#### 📜 GitAgent +**Responsabilidad:** Historial de Git y análisis de cambios -El Router analiza tareas entrantes, determina la mejor estrategia de descomposición, delega subtareas a especialistas y sintetiza resultados finales. +Maneja preguntas sobre: +- Commits recientes y cambios +- Quién cambió qué +- Historial de cambios y justificación +- Información de blame -**Capacidades:** -- 🎯 Análisis de tareas complejas -- 📋 Planificación estratégica -- 🔀 Distribución de trabajo -- 🧩 Síntesis de resultados +### Ubicación de Implementación -### 💻 Agente Coder -**Rol**: Especialista en implementación +- **Código:** Lógica de construcción de Router y ModuleAgent en `engine/repobrain_engine/hub/agents.py` +- **Pipeline:** `engine/repobrain_engine/hub/ask_pipeline.py` +- **Conocimiento:** Lee del directorio de generación apuntado por `.repobrain/current.json` -Escribe código limpio, bien documentado y listo para producción siguiendo convenciones de Google style guide. +### Estrategia de Fallback -**Especialidades:** -- 🐍 Desarrollo en Python -- 🎨 Arquitectura de código limpio -- 📝 Docstrings integrales -- 🧪 Cobertura de pruebas +El pipeline de ask implementa un mecanismo de fallback de tres niveles: -### 🔍 Agente Reviewer -**Rol**: Experto en aseguramiento de calidad +1. **`_ask_with_structured_facts`** — Usa facts estructurados (claims JSON + verificación de fuente) +2. **`_ask_with_agent_md`** — Recurre a archivos agent.md (conocimiento en texto plano) +3. **`_ask_with_legacy_swarm`** — Fallback final (si ambos fallan) -Revisa implementaciones para corrección, seguridad, rendimiento y mejores prácticas. +Esto asegura que la funcionalidad ask permanezca disponible incluso si la base de conocimiento está parcialmente generada o usa formatos antiguos. -**Especialidades:** -- ✅ Evaluación de calidad de código -- 🔒 Análisis de seguridad -- ⚡ Optimización de rendimiento -- 📋 Verificación de mejores prácticas +## 🔧 Configuración y Extensión -### 📚 Agente Researcher -**Rol**: Recopilador de información e investigador +### Usando Diferentes Backends LLM -Investiga soluciones, recopila contexto y proporciona conocimiento fundamental para tareas complejas. +1. **Basado en API (estándar):** + ```bash + rb-setup # Elige OpenAI, DeepSeek, Groq, etc. + ``` -**Especialidades:** -- 🔎 Investigación de problemas -- 📚 Síntesis de información -- 🧠 Recopilación de contexto -- 💡 Generación de insights +2. **Host-runner (sin API key):** + ```bash + export RB_HOST_RUNNER=codex # o generic + # Usa IDE CLI con sesión iniciada, no se necesita API key + ``` -## 🚀 Usando el Swarm +3. **Endpoint personalizado compatible con OpenAI:** + ```bash + export OPENAI_BASE_URL=https://tu-endpoint.com/v1 + export OPENAI_API_KEY=tu-key + export OPENAI_MODEL=tu-modelo + ``` -### Ejecutar Demo Interactivo +### Actualización Incremental (`--quick`) + +Para árboles de trabajo limpios con cambios confirmados: ```bash -python -m repobrain_engine.swarm_demo +rb-refresh --quick ``` -Esto inicia un prompt interactivo donde puedes asignar tareas al swarm y ver a especialistas colaborar. +Esto activa la actualización incremental: +- **ImpactPlanner** analiza git diff para determinar módulos afectados +- **ImpactVerifier** verifica el análisis de impacto +- Solo se actualizan los agent-groups afectados +- Acelera significativamente la iteración en codebases grandes + +Implementación: `engine/repobrain_engine/hub/incremental.py` + +## 📊 Ejemplos de Flujo de Trabajo + +### Ejemplo 1: Inicializar Nuevo Proyecto -### Ejemplo de Interacción +```bash +# 1. Configurar backend +rb-setup + +# 2. Escanear proyecto y construir base de conocimiento +rb-refresh +# 3. Verificar base de conocimiento +rb report # Muestra módulos detectados, lenguajes, etc. + +# 4. Comenzar a hacer preguntas +rb-ask "¿Cómo funciona la autenticación?" ``` -🧭 [Router] ¿Con qué tarea puedo ayudarte? -> Construye una calculadora que soporte operaciones matemáticas básicas y revísala por seguridad - -🧭 [Router] Analizando tarea... -📤 [Router → Coder] Construir calculadora con +, -, *, / operaciones -💻 [Coder] Creando implementación de calculadora... -📝 [Coder] Generando pruebas integrales... -✅ [Coder] ¡Implementación completa! - -📤 [Router → Reviewer] Revisar calculadora por seguridad y mejores prácticas -🔍 [Reviewer] Analizando estructura de código... -🔍 [Reviewer] Evaluación de seguridad: Sin vulnerabilidades encontradas ✅ -🔍 [Reviewer] Evaluación de rendimiento: Óptimo ✅ -✅ [Reviewer] ¡Revisión completa! - -🎉 [Router] ¡Tarea completada con éxito! + +### Ejemplo 2: Actualizaciones Incrementales + +```bash +# Hacer algunos cambios y confirmar +git add . +git commit -m "Actualizar lógica de auth" + +# Actualización incremental rápida (solo módulos afectados) +rb-refresh --quick + +# Verificar actualizaciones +rb-ask "¿Qué cambió en el módulo auth?" ``` -### Uso Programático +### Ejemplo 3: Uso de Depuración -```python -from repobrain_engine.swarm import SwarmOrchestrator +```bash +# Actualizar con logging de depuración +RB_LOG_LEVEL=DEBUG rb-refresh -swarm = SwarmOrchestrator() -result = swarm.execute("Construye una utilidad de compresión de archivos con manejo de errores") -print(result) # cadena final sintetizada +# Preguntar con salida verbosa +RB_LOG_LEVEL=DEBUG rb-ask "¿Dónde está la conexión de base de datos?" ``` -## 🔧 Configuración +## 🐛 Solución de Problemas + +### Falla la Inicialización del Agente + +```bash +# Verificar si el SDK del Agente está instalado +pip show openai-agents -La implementación actual usa el mapa de workers en `repobrain_engine/swarm.py`. -No existe todavía un cargador externo `swarm_config.json`. +# Verificar configuración LLM +cat .env | grep OPENAI +``` -## 📊 Logs y trazabilidad +### Base de Conocimiento Incompleta -`SwarmOrchestrator.execute(..., verbose=True)` imprime progreso en stdout. -También puedes inspeccionar los mensajes en memoria: +```bash +# Verificar estado de actualización +rb report -```python -from repobrain_engine.swarm import SwarmOrchestrator +# Forzar actualización completa (no incremental) +rb-refresh # sin --quick -swarm = SwarmOrchestrator() -swarm.execute("Construir y revisar una calculadora", verbose=False) -print(swarm.get_message_log()) +# Verificar logs de generación +ls -la .repobrain/ +cat .repobrain/current.json ``` +### Ask Devuelve "No Encontrado" + +Posibles causas: +1. Base de conocimiento no generada o obsoleta → Ejecutar `rb-refresh` +2. Módulo no detectado por el escáner → Verificar salida de `rb report` +3. Pregunta enrutada al módulo incorrecto → Probar pregunta más específica + +## 🔗 Integración MCP + +RepoBrain expone su funcionalidad central como herramientas MCP vía `rb-mcp`: + +- **`ask_project`** — Responder preguntas del codebase +- **`refresh_project`** — Actualizar base de conocimiento + +Implementación del servidor MCP: `engine/repobrain_engine/hub/mcp_server.py` + +## 🚀 Consejos de Rendimiento + +### Acelerar Actualización +- Usar `--quick` para actualizaciones incrementales (árbol de trabajo limpio después de commit) +- Excluir directorios innecesarios (configurar patrones de ignorar en `.repobrain/config.json`) +- Usar modelos más rápidos (ej., GPT-4o-mini o Claude 3.5 Haiku) + +### Mejorar Calidad de Respuesta +- Mantener base de conocimiento actualizada (ejecutar `rb-refresh` regularmente) +- Hacer preguntas específicas (mencionar nombres de archivos, características o módulos) +- Usar modelos de mayor capacidad para consultas complejas + +## 📚 Referencias + +### Archivos Principales +- `engine/repobrain_engine/hub/agents.py` — Definiciones de agentes +- `engine/repobrain_engine/hub/refresh_pipeline.py` — Flujo de actualización +- `engine/repobrain_engine/hub/ask_pipeline.py` — Flujo de preguntas +- `engine/repobrain_engine/hub/incremental.py` — Actualización incremental +- `engine/repobrain_engine/hub/host_runner.py` — Backend CLI local +- `engine/repobrain_engine/hub/storage.py` — Almacenamiento de conocimiento + +### Documentación Relacionada +- [Filosofía del Proyecto](PHILOSOPHY.md) — Límites del producto y alcance de soporte +- [Características Zero-Config](ZERO_CONFIG.md) — Descubrimiento de herramientas y contexto +- [Inicio Rápido](QUICK_START.md) — Instalación y primeros pasos + --- **Siguiente:** [Características Zero-Config](ZERO_CONFIG.md) | [Índice Completo](README.md) diff --git a/docs/es/ZERO_CONFIG.md b/docs/es/ZERO_CONFIG.md index a5cb2a3bf..e36403d33 100644 --- a/docs/es/ZERO_CONFIG.md +++ b/docs/es/ZERO_CONFIG.md @@ -6,13 +6,13 @@ ## 🛠️ Descubrimiento Automático de Herramientas -Coloca cualquier archivo Python en `repobrain_engine/tools/` y el agente lo usará inmediatamente—sin imports, sin registro, sin boilerplate. +Coloca cualquier archivo Python en `engine/repobrain_engine/tools/` y el agente lo usará inmediatamente—sin imports, sin registro, sin boilerplate. ### Cómo Funciona 1. **Define tu Herramienta**: ```python -# repobrain_engine/tools/sentiment_analyzer.py +# engine/repobrain_engine/tools/sentiment_analyzer.py def analyze_sentiment(text: str) -> dict: """Analiza el sentimiento del texto dado. @@ -41,14 +41,14 @@ El agente descubrirá y usará automáticamente `analyze_sentiment()`. ## 🎓 Descubrimiento Automático de Skills -Coloca una carpeta de skill en `repobrain_engine/skills/` (con `SKILL.md` y opcionalmente `tools.py`) y el agente cargará automáticamente: +Coloca una carpeta de skill en `engine/repobrain_engine/skills/` (con `SKILL.md` y opcionalmente `tools.py`) y el agente cargará automáticamente: - Documentación de `SKILL.md` en el contexto del prompt - Funciones públicas de `tools.py` como herramientas invocables ### Ejemplo integrado: `agent-repo-init` Este repositorio incluye: -- `repobrain_engine/skills/agent-repo-init/`: integración de skill dentro del agente (`init_agent_repo`) +- `engine/repobrain_engine/skills/agent-repo-init/`: integración de skill dentro del agente (`init_agent_repo`) - `skills/agent-repo-init/`: paquete de skill portable con script de ejecución `agent-repo-init` soporta: @@ -90,7 +90,7 @@ Cada prompt al agente ahora incluye automáticamente todos los archivos `.contex **Comportamiento actual del loader:** - Lee solo archivos Markdown de nivel superior: `.context/*.md` -- Si cambias `repobrain_engine/tools/`, reinicia el agente para recargar herramientas +- Si cambias `engine/repobrain_engine/tools/`, reinicia el agente para recargar herramientas ### Organizar Contexto @@ -119,7 +119,7 @@ Cada prompt al agente ahora incluye automáticamente todos los archivos `.contex ### Paso 2: Agrega Herramientas (Lo que el agente puede hacer) ```python -# repobrain_engine/tools/db_query.py +# engine/repobrain_engine/tools/db_query.py def query_users(email_pattern: str) -> list: """Consulta usuarios por patrón de email.""" # Implementación diff --git a/docs/zh/MCP_INTEGRATION.md b/docs/zh/MCP_INTEGRATION.md index ddd19fca8..bc2d77ef9 100644 --- a/docs/zh/MCP_INTEGRATION.md +++ b/docs/zh/MCP_INTEGRATION.md @@ -91,7 +91,7 @@ if __name__ == "__main__": "name": "my-analysis", "transport": "stdio", "command": "python", - "args": ["repobrain_engine/tools/my_server.py"], + "args": ["engine/repobrain_engine/tools/my_server.py"], "enabled": true } ``` @@ -117,7 +117,7 @@ manager.shutdown() ## 🐛 故障排查 -- 无法连接:先手动运行服务器命令(如 `python repobrain_engine/tools/my_server.py`),确认 `npx` 等命令存在。 +- 无法连接:先手动运行服务器命令(如 `python engine/repobrain_engine/tools/my_server.py`),确认 `npx` 等命令存在。 - 工具未出现:重启 Agent,并确认对应 MCP 服务器已在 `mcp_servers.json` 里启用。 - 性能问题:禁用不需要的服务器;远程优先用 `http`;必要时缓存结果。 diff --git a/docs/zh/README.md b/docs/zh/README.md index 5e062007b..a1ee4521c 100644 --- a/docs/zh/README.md +++ b/docs/zh/README.md @@ -24,7 +24,7 @@ 递归摘要自动压缩历史上下文,缓解上下文窗口限制。 ### 🛠️ 通用工具协议 -遵循通用 ReAct 模式;在 `repobrain_engine/tools/` 放入 Python 函数即被自动注册为工具。 +遵循通用 ReAct 模式;在 `engine/repobrain_engine/tools/` 放入 Python 函数即被自动注册为工具。 ### 🎓 基于 Skill 的项目初始化 使用内置 `agent-repo-init` skill 可以从当前模板快速初始化干净的新仓库。 @@ -53,23 +53,29 @@ ``` . -├── .repobrain/ # 🛸 生成的代码库知识库 -├── .context/ # 📚 可选的额外上下文 -├── artifacts/ # 📂 Agent 输出(计划、日志、证据) -├── repobrain_engine/ # 🧠 Agent 源码 -│ ├── hub/ # 知识中枢(扫描器、Agent、管道) -│ ├── mcp_server.py # rb-mcp 服务端 -│ ├── memory.py # Markdown 记忆管理 -│ ├── mcp_client.py # MCP 集成 -│ ├── swarm.py # 多 Agent 编排 -│ ├── agents/ # 专家型 Agent -│ ├── tools/ # 工具实现 -│ └── sandbox/ # local / microsandbox 代码执行 -├── tests/ # ✅ 测试套件 -├── scripts/ # 🧪 辅助脚本 -├── docker-compose.yml # 本地开发栈 -├── README.md # 项目主页 -└── pyproject.toml # Python 依赖 +├── cli/ # rb CLI、IDE 模板、离线工具 +├── engine/repobrain_engine/ # 知识引擎、hub、MCP 服务器、sandbox +│ ├── hub/ # 知识中枢 +│ │ ├── scanner.py # 模块扫描器 +│ │ ├── refresh_pipeline.py # 知识生成管道 +│ │ ├── ask_pipeline.py # 问答管道 +│ │ ├── agents.py # Refresh/Ask Swarm agents +│ │ ├── incremental.py # 增量刷新(--quick) +│ │ ├── host_runner.py # 本地 CLI 后端(无 API key) +│ │ ├── mcp_server.py # rb-mcp 服务端 +│ │ ├── storage.py # 知识库存储(current.json) +│ │ └── language_adapters/ # 多语言适配器 +│ ├── tools/ # 工具实现 +│ ├── sandbox/ # local / microsandbox 代码执行 +│ ├── skills/ # 技能(research、knowledge-layer 等) +│ ├── memory.py # Markdown 记忆管理 +│ └── mcp_client.py # MCP 集成 +├── commands/ # 共享的 slash 命令定义 +├── skills/ # 面向插件的技能 +├── docs/ # 多语言文档 +├── artifacts/ # 计划、报告、基准测试输出 +├── memory/ # Markdown 交互记忆 +└── .repobrain/ # 在目标仓库中生成的知识库 ``` ## 🎓 按角色阅读 @@ -81,7 +87,7 @@ ### DevOps/部署 1) 阅读 [快速开始](QUICK_START.md) 的 Docker 部分 -2) 查看 [开发路线图](ROADMAP.md) 的 Phase 9(Enterprise Core) +2) 了解 [Sandbox 执行](SANDBOX.md) 的安全边界 3) 在 [MCP 集成](MCP_INTEGRATION.md) 配置外部服务器 ### 架构师 @@ -91,7 +97,7 @@ ### 贡献者 1) 阅读 [项目理念](PHILOSOPHY.md) -2) 查看 [开发路线图](ROADMAP.md) Phase 9 的开放议题 +2) 查看 [开发路线图](ROADMAP.md) 了解当前架构 3) 提交 Issue/PR 讨论想法或实现 ## 🔗 外部资源 @@ -108,7 +114,7 @@ A: 运行 `rb-setup`,选择 OpenAI、DeepSeek、Groq、DashScope、NVIDIA NIM、Ollama 或自定义 OpenAI-compatible endpoint。命令会写入 `.env` 中的 `OPENAI_BASE_URL`、`OPENAI_API_KEY`、`OPENAI_MODEL`。 **Q: 如何添加自定义工具?** -A: 将 Python 文件放进 `repobrain_engine/tools/`,无需额外注册,见 [零配置特性](ZERO_CONFIG.md)。 +A: 将 Python 文件放进 `engine/repobrain_engine/tools/`,无需额外注册,见 [零配置特性](ZERO_CONFIG.md)。 **Q: 如何基于模板初始化一个新项目?** A: 使用 `agent-repo-init` 的 `quick/full` 模式,或直接运行 `skills/agent-repo-init/scripts/init_project.py`,见 [零配置特性](ZERO_CONFIG.md)。 @@ -134,7 +140,7 @@ A: 自 2026 年 4 月起,`rb-refresh` 为每个模块生成结构化 JSON 声 ## 🤝 贡献 - 报告问题或想法:[GitHub Issues](https://github.com/study8677/repobrain/issues) -- 提交代码或改进文档:优先关注 [开发路线图](ROADMAP.md) Phase 9 的议题 +- 提交代码或改进文档:查看 [开发路线图](ROADMAP.md) 了解架构 - 欢迎通过 PR 修复错别字、补充示例 ## 📞 支持 @@ -158,8 +164,8 @@ MIT License,详见仓库根目录 `LICENSE`。 --- -**最后更新:2026 年 4 月** -**当前版本:Phase 10(知识中枢)✅ —— 结构化证据管道 + 多语言模块支持** +**最后更新:2026 年 8 月** +**当前架构:** 生成式知识中枢 + 本地 host-runner + 增量 agent-group 刷新 + 结构化证据验证 祝构建愉快!🚀 diff --git a/docs/zh/ROADMAP.md b/docs/zh/ROADMAP.md index d9bf747cf..bf005304e 100644 --- a/docs/zh/ROADMAP.md +++ b/docs/zh/ROADMAP.md @@ -20,13 +20,24 @@ RepoBrain 正收敛为一个可移植的 repository knowledge engine:把 works | 9 产品化加固 | 进行中 | 安全边界、可观测、安装与文档契约 | | 10 Knowledge Hub | 完成 | 代码库刷新、模块知识、路由式问答 | -## Phase 9 重点 - -- Sandbox:local 可信开发边界、Microsandbox/E2B opt-in、降级 warning。 -- Retrieval graph:默认保留开发体验,同时做 secret redaction 与风险说明。 -- MCP:保留 opt-in 便利性,明确 `RB_ALLOW_MCP`、环境变量和外部 server 权限风险。 -- 安装与文档:保持 `rb-setup -> rb-refresh -> rb-ask` 主线,减少旧入口漂移。 -- Contract check:用 CI 检查安装脚本、sandbox 文档、模型默认值和 quick start。 +## 已完成的核心功能(截至 2026 年 8 月) + +### Phase 9: 产品化加固 ✅ +- **Sandbox**:local 可信开发边界、Microsandbox/E2B opt-in、降级 warning +- **Retrieval graph**:默认保留开发体验,同时做 secret redaction 与风险说明 +- **MCP**:保留 opt-in 便利性,明确 `RB_ALLOW_MCP`、环境变量和外部 server 权限风险 +- **安装与文档**:保持 `rb-setup -> rb-refresh -> rb-ask` 主线,减少旧入口漂移 +- **Contract check**:用 CI 检查安装脚本、sandbox 文档、模型默认值和 quick start + +### Phase 10: Knowledge Hub ✅ +- **生成式知识存储**:`.repobrain/` 目录中的模块知识库 +- **结构化证据**:JSON claims + 源码验证(文件路径 + 行范围) +- **多语言支持**:Python、TypeScript/JavaScript、Go、Rust、Java、Kotlin、Swift、C/C++、C# +- **Host-runner**:本地 CLI 后端(RB_HOST_RUNNER),无需 API key 即可运行 +- **增量刷新**:`rb-refresh --quick` 只刷新受影响的 agent-group +- **Agent 架构**: + - Refresh Swarm: ScanAnalyst → ArchitectureReviewer → ConventionWriter + - Ask Swarm: Router + 动态 ModuleAgent + GitAgent ## 使用场景 diff --git a/docs/zh/SWARM_PROTOCOL.md b/docs/zh/SWARM_PROTOCOL.md index abebf8036..734455ee7 100644 --- a/docs/zh/SWARM_PROTOCOL.md +++ b/docs/zh/SWARM_PROTOCOL.md @@ -1,79 +1,300 @@ -# 🔥 多 Agent Swarm 协议 +# 🔥 多 Agent 协作模型 -## 🪐 架构:Router-Worker 模式 +## 🪐 架构概述 -Swarm 把复杂任务拆分给专家 Agent 协同完成:Router 分析并分发任务,Coder/Reviewer/Researcher 执行并回传,Router 汇总结果。 +RepoBrain 使用两个专门的 Agent Swarm 来支持其核心功能: -## 🧠 专家角色 +1. **Refresh Swarm** — 扫描项目并生成知识工件 +2. **Ask Swarm** — 基于生成的知识库回答代码库问题 -- 🧭 **Router**:任务分析、拆解、分配、结果合成。 -- 💻 **Coder**:实现与测试,遵循干净代码与文档规范。 -- 🔍 **Reviewer**:正确性/安全/性能审查与改进建议。 -- 📚 **Researcher**:调研信息、补充上下文与洞察。 +这些 Swarm 定义在 `engine/repobrain_engine/hub/agents.py` 中,由 `refresh_pipeline.py` 和 `ask_pipeline.py` 驱动。 -## 🚀 如何使用 +## 🔄 Refresh Swarm:三阶段分析链 + +当你运行 `rb-refresh` 时,Refresh Swarm 会分析你的代码库并生成项目约定文档。 + +### 架构:三阶段 Handoff 链 + +```mermaid +graph LR + Scan[扫描报告] --> SA[ScanAnalyst] + SA --> AR[ArchitectureReviewer] + AR --> CW[ConventionWriter] + CW --> Doc[conventions.md] +``` + +### 三个 Agent 角色 + +#### 🔍 ScanAnalyst +**职责:** 代码分析专家,专注于语言和框架检测 + +**分析内容:** +- 编程语言及其分布(主要 vs 次要) +- 检测到的框架和库(web、数据、ML 等) +- 代码模式和风格观察(命名、结构、习惯用法) +- 依赖管理方式 + +完成后移交给 ArchitectureReviewer。 + +#### 🏗️ ArchitectureReviewer +**职责:** 软件架构审查员 + +**分析内容:** +- 项目目录结构和组织模式 +- 测试方法、框架和覆盖率指标 +- CI/CD 管道设置和自动化 +- Docker/容器配置 +- 构建系统和打包方式 +- 配置管理模式 + +在前一个 Agent 分析的基础上添加结构性发现,然后移交给 ConventionWriter。 + +#### ✍️ ConventionWriter +**职责:** 技术文档撰写专家 + +**输出内容:** +使用前两个 Agent 的所有分析结果,生成简洁的约定文档(Markdown 格式),涵盖: +- 主要语言和框架 +- 项目结构概述 +- 代码风格观察 +- 测试方法 +- CI/CD 设置 + +输出保持在 300 字以内,直接输出 Markdown 内容。 + +### 实现位置 + +- **代码:** `engine/repobrain_engine/hub/agents.py` 中的 `build_refresh_swarm()` +- **管道:** `engine/repobrain_engine/hub/refresh_pipeline.py` +- **存储:** 生成的知识保存在 `.repobrain/` 目录(在目标项目中,非本仓库) + +### Host-Runner 模式 + +当没有配置 API key 时(`RB_HOST_RUNNER` 设置为 `codex` 或 `generic`),Refresh 会使用单轮、无工具的 Convention Agent (`build_single_turn_convention_agent()`),该 Agent 将三阶段链压缩为一次生成。 + +## 💬 Ask Swarm:动态模块路由 + +当你运行 `rb-ask "问题"` 时,Ask Swarm 会将问题路由到相关模块的 Agent 并返回带有文件路径和行号的答案。 + +### 架构:Router-Worker 模式 + +```mermaid +graph TD + User[用户问题] --> Router[Router Agent] + Router --> MA1[ModuleAgent: auth] + Router --> MA2[ModuleAgent: api] + Router --> MA3[ModuleAgent: database] + Router --> Git[GitAgent: git 历史] + MA1 --> Router + MA2 --> Router + MA3 --> Router + Git --> Router + Router --> Answer[最终答案 + 引用] +``` + +### Agent 角色 + +#### 🧭 Router Agent +**职责:** 问题路由和答案综合 + +**功能:** +1. 读取用户问题 +2. 基于项目结构图识别相关模块 +3. 将问题移交给适当的 ModuleAgent +4. 对于 git 相关问题(最近更改、提交历史),移交给 GitAgent +5. 对于跨模块问题,先移交给一个模块,该模块可根据需要移交给其他模块 +6. 综合 Agent 返回的发现,生成最终答案 + +**答案要求:** +- 直接回答问题 +- **引用具体的文件路径、行号和函数名** +- 包含提交历史(解释"为什么") +- 简洁明了(除非问题需要更多细节,否则保持 200 字以内) + +#### 📦 ModuleAgent(动态生成) +**职责:** 负责特定模块的深度知识 + +每个模块都有自己的 Agent,具有: +- 模块的结构化 facts(JSON claims + 源码证据) +- 探索代码的工具(read_file、search_code 等) +- 可以移交给其他 ModuleAgent 以获取跨模块信息 + +ModuleAgent 根据项目扫描结果动态创建(每个检测到的模块一个 Agent)。 + +#### 📜 GitAgent +**职责:** Git 历史和变更分析 + +处理关于: +- 最近的提交和更改 +- 谁修改了什么 +- 变更历史和原因 +- Blame 信息 + +### 实现位置 + +- **代码:** `engine/repobrain_engine/hub/agents.py` 中的 Router 和 ModuleAgent 构建逻辑 +- **管道:** `engine/repobrain_engine/hub/ask_pipeline.py` +- **知识库:** 从 `.repobrain/current.json` 指向的生成目录读取 + +### 回退策略 + +Ask pipeline 实现了三层回退机制: + +1. **`_ask_with_structured_facts`** — 使用结构化 facts(JSON claims + 源码验证) +2. **`_ask_with_agent_md`** — 回退到 agent.md 文件(纯文本知识) +3. **`_ask_with_legacy_swarm`** — 最终回退(如果前两者都失败) + +这确保了即使知识库部分生成或使用旧格式,ask 功能仍然可用。 + +## 🔧 配置与扩展 + +### 使用不同的 LLM 后端 + +1. **API-based(标准方式):** + ```bash + rb-setup # 选择 OpenAI、DeepSeek、Groq 等 + ``` + +2. **Host-runner(无 API key):** + ```bash + export RB_HOST_RUNNER=codex # 或 generic + # 使用登录的 IDE CLI,无需 API key + ``` + +3. **自定义 OpenAI-compatible endpoint:** + ```bash + export OPENAI_BASE_URL=https://your-endpoint.com/v1 + export OPENAI_API_KEY=your-key + export OPENAI_MODEL=your-model + ``` + +### 增量刷新(`--quick`) + +对于已提交的干净工作树: -### 交互式演示 ```bash -python -m repobrain_engine.swarm_demo +rb-refresh --quick ``` -输入任务即可观察协作过程。 -### 代码调用 -```python -from repobrain_engine.swarm import SwarmOrchestrator +这会触发增量刷新: +- **ImpactPlanner** 分析 git diff 确定受影响的模块 +- **ImpactVerifier** 验证影响分析 +- 只刷新受影响的 agent-group +- 显著加快大型代码库的迭代速度 + +实现位置:`engine/repobrain_engine/hub/incremental.py` + +## 📊 工作流程示例 + +### 示例 1:初始化新项目 -swarm = SwarmOrchestrator() -result = swarm.execute("构建带错误处理的文件压缩工具") -print(result) # 返回最终合成后的字符串结果 +```bash +# 1. 设置后端 +rb-setup + +# 2. 扫描项目并构建知识库 +rb-refresh + +# 3. 验证知识库 +rb report # 显示检测到的模块、语言等 + +# 4. 开始提问 +rb-ask "认证是如何工作的?" ``` -## 🔧 配置 +### 示例 2:增量更新 -- 当前实现使用 `repobrain_engine/swarm.py` 内置的 worker 映射,尚未实现 `.repobrain/swarm_config.json` 配置加载。 -- 自定义 Agent:继承 `BaseAgent`(参考 `repobrain_engine/agents`),在 `swarm.py` 注册即可。 +```bash +# 修改一些文件并提交 +git add . +git commit -m "Update auth logic" -## 📊 日志与产物 +# 快速增量刷新(仅受影响的模块) +rb-refresh --quick -- 执行日志默认输出到终端(`execute(..., verbose=True)`)。 -- 可通过 `swarm.get_message_log()` 读取内存中的消息总线记录。 -- 当前实现不会自动把 swarm 日志/产物写入磁盘。 +# 验证更新 +rb-ask "auth 模块有什么变化?" +``` + +### 示例 3:调试使用 -## ⚡ 性能提示 +```bash +# 带调试日志的刷新 +RB_LOG_LEVEL=DEBUG rb-refresh -- 任务描述要清晰;预加载上下文;将子任务写具体以提高 Router 分派稳定性。 -- 禁用不需要的 Agent,定期清理旧 artifacts,必要时做结果缓存。 +# 带详细输出的问答 +RB_LOG_LEVEL=DEBUG rb-ask "数据库连接在哪里?" +``` ## 🐛 故障排查 -- Agent 未初始化:先在 Python 中实例化 `SwarmOrchestrator` 查看初始化输出。 -- 执行卡住:先用 `verbose=False` 运行,再用 `get_message_log()` 检查路由与执行链路。 -- 结果质量低:提供更多上下文,描述更具体,确保 Reviewer 启用。 - -## 📚 示例 - -```python -# 示例:Web 爬虫 -swarm.execute(""" -构建新闻爬虫: -1) 抓取文章 -2) 提取标题/作者/日期 -3) 保存 JSON -4) 有错误处理 -""") +### Agent 初始化失败 + +```bash +# 检查是否安装了 Agent SDK +pip show openai-agents + +# 验证 LLM 配置 +cat .env | grep OPENAI ``` -```python -# 示例:Flask API + 测试 + 安全评审 -swarm.execute(""" -创建 REST API: -- GET/POST /users -- 请求校验 -- 单元测试齐全 -- 做安全检查 -""") +### 知识库不完整 + +```bash +# 检查刷新状态 +rb report + +# 强制完全刷新(非增量) +rb-refresh # 不使用 --quick + +# 检查生成日志 +ls -la .repobrain/ +cat .repobrain/current.json ``` +### Ask 返回"未找到" + +可能原因: +1. 知识库未生成或过时 → 运行 `rb-refresh` +2. 模块未被扫描器检测 → 检查 `rb report` 输出 +3. 问题路由到错误的模块 → 尝试更具体的问题 + +## 🔗 MCP 集成 + +RepoBrain 通过 `rb-mcp` 暴露其核心功能为 MCP 工具: + +- **`ask_project`** — 回答代码库问题 +- **`refresh_project`** — 刷新知识库 + +MCP server 实现:`engine/repobrain_engine/hub/mcp_server.py` + +## 🚀 性能建议 + +### 加快刷新速度 +- 使用 `--quick` 进行增量更新(提交后的干净工作树) +- 排除不必要的目录(在 `.repobrain/config.json` 中配置忽略模式) +- 使用更快的模型(例如 GPT-4o-mini 或 Claude 3.5 Haiku) + +### 提高回答质量 +- 保持知识库最新(定期运行 `rb-refresh`) +- 提出具体问题(提及文件名、功能或模块) +- 使用更高能力的模型进行复杂查询 + +## 📚 参考 + +### 核心文件 +- `engine/repobrain_engine/hub/agents.py` — Agent 定义 +- `engine/repobrain_engine/hub/refresh_pipeline.py` — 刷新流程 +- `engine/repobrain_engine/hub/ask_pipeline.py` — 问答流程 +- `engine/repobrain_engine/hub/incremental.py` — 增量刷新 +- `engine/repobrain_engine/hub/host_runner.py` — 本地 CLI 后端 +- `engine/repobrain_engine/hub/storage.py` — 知识库存储 + +### 相关文档 +- [项目理念](PHILOSOPHY.md) — 产品边界和支持范围 +- [零配置特性](ZERO_CONFIG.md) — 工具和上下文发现 +- [快速开始](QUICK_START.md) — 安装和首次使用 + --- **下一步:** [零配置特性](ZERO_CONFIG.md) | [文档索引](README.md) diff --git a/docs/zh/ZERO_CONFIG.md b/docs/zh/ZERO_CONFIG.md index b87c77ea1..92a78c156 100644 --- a/docs/zh/ZERO_CONFIG.md +++ b/docs/zh/ZERO_CONFIG.md @@ -6,16 +6,16 @@ ## 🛠️ 自动发现工具 -把任意 Python 文件放进 `repobrain_engine/tools/`,Agent 会立刻识别其顶层函数——无需 import、无需登记。 +把任意 Python 文件放进 `engine/repobrain_engine/tools/`,Agent 会立刻识别其顶层函数——无需 import、无需登记。 ### 工作方式 -1) 🔍 扫描 `repobrain_engine/tools/` 下所有 `.py` +1) 🔍 扫描 `engine/repobrain_engine/tools/` 下所有 `.py` 2) 📋 索引顶层函数并读取 docstring 3) ✅ 注册公开函数为可调用工具 ### 示例 ```python -# repobrain_engine/tools/sentiment_analyzer.py +# engine/repobrain_engine/tools/sentiment_analyzer.py def analyze_sentiment(text: str) -> dict: """情感分析:返回分数与标签。""" if len(text) > 10: @@ -71,7 +71,7 @@ def analyze_sentiment(text: str) -> dict: **场景**:构建数据分析工具 - 上下文:`.context/database_schema.md` 记录表结构 -- 工具:`repobrain_engine/tools/db_query.py` 提供查询函数 +- 工具:`engine/repobrain_engine/tools/db_query.py` 提供查询函数 - 对话:直接让 Agent“查找最近一月创建的用户”,它既“知道”结构,也“能”查询。 ## 🎓 最佳实践 @@ -83,8 +83,8 @@ def analyze_sentiment(text: str) -> dict: **工具没加载?** ```bash -ls -la repobrain_engine/tools/ -python -m py_compile repobrain_engine/tools/my_tool.py +ls -la engine/repobrain_engine/tools/ +python -m py_compile engine/repobrain_engine/tools/my_tool.py rb-refresh --workspace . # 重新刷新知识库 ```