Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

docs(agents): simplify and unify guidelines

cyhhao88c3165a91fc
diff --git a/AGENTS.md b/AGENTS.md
index b3a4305ac..9c5688728 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -1,30 +1,93 @@
-# Repository Guidelines
+# Agent Guidelines
-## Project Structure & Module Organization
-`main.py` is the entry point that wires `config.AppConfig` into the runtime `Controller`. Core orchestration和 handlers live under `core/` (e.g., `core/controller.py`, `core/handlers/*`). Agent integrations now live in `modules/agents/` (shared base, Claude/Codex backends, registry), while IM transports stay in `modules/im/`. Configuration defaults live in `config/` (`agent_routes.example.yaml` + gitignored `agent_routes.yaml` at repo root control per-channel routing), reference docs in `docs/`, static assets in `assets/`, and `_tmp/` is the default remote working directory for agent sessions. Keep runtime logs inside `logs/vibe_remote.log` and persist chat state in `user_settings.json`.
+This file defines how coding agents should work in this repository.
-## Build, Test, and Development Commands
-- `python -m venv .venv && source .venv/bin/activate` – create an isolated environment before installing dependencies.
-- `pip install -r requirements.txt` – install the Slack/Telegram/Claude clients plus Codex routing deps (`PyYAML` for route parsing).
-- `cp .env.example .env` – seed configuration; update IM platform tokens, `CLAUDE_DEFAULT_CWD`, and permission mode.
-- `./start.sh` (or `python main.py`) – run the bot locally; prefers Slack when both tokens exist.
-- `./status.sh` / `./stop.sh` – check or terminate the background process when using the helper scripts.
+## 1) General (Reusable)
-## Coding Style & Naming Conventions
-Follow PEP 8 with four-space indentation, descriptive `snake_case` for functions, and `PascalCase` for classes/dataclasses (see `config/settings.py`). Type hints are expected for public functions, and inline logging should use the structured format in `main.py` for traceability. Keep modules small and cohesive; new handlers belong in `core/handlers/`, new IM transports under `modules/im/`. No repo-wide formatter is enforced—run your preferred tool (Black/Ruff) before opening a PR and document deviations.
+### Language
-## Testing Guidelines
-There is no committed automated test suite yet; favor fast pytest-style modules named `test_<feature>.py` co-located with the code or under `tests/`. Exercise controller flows by faking IM payloads via lightweight fixtures and assert session state mutations. Run `pytest -q` (add it to your dev extras) before pushing; where live integrations are involved, stub Slack/Telegram clients and verify that outbound payloads match the documented schemas. Treat manual end-to-end checks (start bot, send `/start`) as mandatory until CI is in place.
+- Default to English for all comments, docs, user-facing copy, and logs.
+- Use non-English text only when required for i18n/localization.
-## Commit & Pull Request Guidelines
-Commits follow the `type(scope): summary` pattern visible in history (`fix(slack): …`, `feat(status): …`). Keep them small and focused on a single concern, referencing issues when relevant. Every PR must describe intent, list functional changes, attach logs or screenshots for UX-affecting updates, and call out config impacts (new env vars, migrations). Update README/docs whenever behavior or setup steps change, and ensure `pip install -r requirements.txt && ./start.sh` still works from a clean clone.
+### Workflow (Branches + PRs)
-## Security & Configuration Tips
-Never commit `.env`, tokens, or Slack/Telegram secrets; rely on `.env.example` plus local overrides. Validate IM scopes (`SLACK_REQUIRE_MENTION`, `TELEGRAM_TARGET_CHAT_ID`) through `config/settings.py` before shipping, and document any new flags. Keep `CLAUDE_DEFAULT_CWD` scoped to `_tmp/` or another sanitized path so that remote agents cannot escape the intended workspace. Logs may contain sensitive thread context—rotate `logs/vibe_remote.log` in production and scrub before sharing.
+- Always branch from the latest `master` when starting a new feature or bug fix.
+- Implement work on a new branch, validate changes, then open a PR to `master` for review.
+- Keep commits small and focused; avoid mixing unrelated changes.
-## Agent Routing & Codex Notes
-- Enable Codex (on by default) via `CODEX_ENABLED=true` and ensure the CLI is reachable (`CODEX_CLI_PATH`).
-- Copy `agent_routes.example.yaml` → `agent_routes.yaml` to map Slack channel / Telegram chat IDs to agents; see `docs/CODEX_SETUP.md` for a full walkthrough.
-- The `modules/agents` architecture is ready for additional backends; add a new agent class, register it in `core/controller.py`, then expose it via the routing file.
-- Route Slack channel IDs or Telegram chat IDs in `AGENT_ROUTE_FILE` (`agent_routes.yaml` at repo root by default; copy from `agent_routes.example.yaml`). Keys map to agent names (`claude`, `codex`, future backends). Missing entries fall back to the platform default, then to the global default.
-- Session mappings inside `user_settings.json` are now namespaced per agent; avoid manual edits unless you know the nested structure `{agent -> base_session_id -> cwd -> session_id}`.
+### Planning (When Work Is Non-trivial)
+
+- If the task is complex or ambiguous, propose a short plan and confirm it with the user before large changes.
+- If a plan-related subagent exists, prefer calling it to draft/refine the plan.
+
+### Code Review
+
+- If a review-related subagent exists, call it when the code is ready for review.
+- Address review findings as appropriate until no must-fix issues remain.
+
+### Quality Bar
+
+- Prefer root-cause fixes over defensive patches.
+- Run the smallest relevant checks first (unit tests, targeted scripts), then broader checks when needed.
+- Add tests when there is an existing test pattern; do not introduce a brand-new testing framework unless requested.
+
+### Git Hygiene & Security
+
+- Commit messages: use `type(scope): summary`.
+- Never commit secrets (e.g., `.env`, tokens, credentials files).
+- Avoid destructive git operations unless explicitly requested (e.g., `reset --hard`, force-push).
+
+## 2) Project-Specific (Vibe Remote)
+
+### Structure
+
+- Entry point: `main.py` wires `config.AppConfig` into `core/controller.py`.
+- Core orchestration and handlers: `core/` (notably `core/handlers/`).
+- Agent backends: `modules/agents/` (shared base, Claude/Codex backends, registry).
+- IM transports: `modules/im/` (Slack/Telegram).
+- Config:
+ - Defaults and validation: `config/` (see `config/settings.py`).
+ - Agent routing: `agent_routes.example.yaml` (template) and local `agent_routes.yaml` (gitignored).
+- Runtime data:
+ - Logs: `logs/vibe_remote.log`.
+ - Persisted state: `user_settings.json`.
+ - Default remote working dir: `_tmp/`.
+
+### Common Commands
+
+- Setup:
+ - `python -m venv .venv && source .venv/bin/activate`
+ - `pip install -r requirements.txt`
+ - `cp .env.example .env`
+- Run:
+ - `./start.sh` (preferred) or `python main.py`
+ - `./status.sh` / `./stop.sh`
+
+### Coding Conventions
+
+- Follow PEP 8, 4-space indentation.
+- Naming: `snake_case` for functions, `PascalCase` for classes/dataclasses.
+- Use type hints for public functions.
+- Keep modules cohesive; add new handlers under `core/handlers/`, new IM transports under `modules/im/`.
+- No repo-wide formatter is enforced; use Black/Ruff if you want, keep diffs focused.
+
+### Testing
+
+- No committed automated suite yet.
+- Prefer fast `pytest`-style tests (`test_<feature>.py`) colocated or under `tests/`.
+- For IM integrations, stub Slack/Telegram clients and validate outbound payload schemas.
+- Do a manual E2E sanity check (start bot, send `/start`) until CI exists.
+
+### Agent Routing / Codex
+
+- Codex enablement: `CODEX_ENABLED=true` and `CODEX_CLI_PATH` points to the CLI.
+- Routing file:
+ - Copy `agent_routes.example.yaml` to `agent_routes.yaml` (local).
+ - Controlled by `AGENT_ROUTE_FILE` (defaults to repo-root `agent_routes.yaml`).
+ - Keys are Slack channel IDs / Telegram chat IDs; values are agent names (e.g., `claude`, `codex`).
+ - Missing entries fall back to platform default, then to global default.
+
+### Safety Notes
+
+- Keep `CLAUDE_DEFAULT_CWD` scoped to `_tmp/` (or another sanitized directory).
+- Logs can contain sensitive context; scrub before sharing.
diff --git a/CLAUDE.md b/CLAUDE.md
index 8d167fb57..9c5688728 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -1,287 +1,93 @@
-# CLAUDE.md
+# Agent Guidelines
-This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
+This file defines how coding agents should work in this repository.
-## Project Overview
+## 1) General (Reusable)
-Vibe Remote is a multi-platform, chat-native controller for vibe coding. It supports Slack and Telegram, letting users remote-control Claude Code (and future coding CLIs) from chat. The system provides persistent sessions, real-time streaming feedback, and maintains conversation context.
+### Language
-## Project Name & Vision
+- Default to English for all comments, docs, user-facing copy, and logs.
+- Use non-English text only when required for i18n/localization.
-Vibe Remote — hands-free vibe coding from chat.
+### Workflow (Branches + PRs)
-Vision:
+- Always branch from the latest `master` when starting a new feature or bug fix.
+- Implement work on a new branch, validate changes, then open a PR to `master` for review.
+- Keep commits small and focused; avoid mixing unrelated changes.
-- Minimize manual review; let the AI drive coding based on intent and constraints
-- Enable work-from-anywhere by controlling coding CLIs via Slack/Telegram
-- Stay extensible beyond Claude Code to other coding agents and toolchains
+### Planning (When Work Is Non-trivial)
-## Development Commands
+- If the task is complex or ambiguous, propose a short plan and confirm it with the user before large changes.
+- If a plan-related subagent exists, prefer calling it to draft/refine the plan.
-### Environment Setup
+### Code Review
-```bash
-# Create virtual environment and install dependencies
-python3 -m venv venv
-source venv/bin/activate # On Windows: venv\Scripts\activate
-pip install -r requirements.txt
+- If a review-related subagent exists, call it when the code is ready for review.
+- Address review findings as appropriate until no must-fix issues remain.
-# Create configuration from template
-cp .env.example .env
-# Edit .env with your platform and credentials
-```
+### Quality Bar
-### Running the Bot
+- Prefer root-cause fixes over defensive patches.
+- Run the smallest relevant checks first (unit tests, targeted scripts), then broader checks when needed.
+- Add tests when there is an existing test pattern; do not introduce a brand-new testing framework unless requested.
-```bash
-# Start the bot (preferred - includes process management)
-./start.sh
+### Git Hygiene & Security
-# Alternative direct start
-python main.py
+- Commit messages: use `type(scope): summary`.
+- Never commit secrets (e.g., `.env`, tokens, credentials files).
+- Avoid destructive git operations unless explicitly requested (e.g., `reset --hard`, force-push).
-# Stop the bot
-./stop.sh
+## 2) Project-Specific (Vibe Remote)
-# Check bot status
-./status.sh
-```
+### Structure
-### Development Testing
+- Entry point: `main.py` wires `config.AppConfig` into `core/controller.py`.
+- Core orchestration and handlers: `core/` (notably `core/handlers/`).
+- Agent backends: `modules/agents/` (shared base, Claude/Codex backends, registry).
+- IM transports: `modules/im/` (Slack/Telegram).
+- Config:
+ - Defaults and validation: `config/` (see `config/settings.py`).
+ - Agent routing: `agent_routes.example.yaml` (template) and local `agent_routes.yaml` (gitignored).
+- Runtime data:
+ - Logs: `logs/vibe_remote.log`.
+ - Persisted state: `user_settings.json`.
+ - Default remote working dir: `_tmp/`.
-```bash
-# Test imports and basic functionality
-python3 -c "from config.settings import AppConfig; from modules.im import IMFactory; print('Imports successful!')"
+### Common Commands
-# Check logs in real-time
-tail -f logs/bot_*.log
+- Setup:
+ - `python -m venv .venv && source .venv/bin/activate`
+ - `pip install -r requirements.txt`
+ - `cp .env.example .env`
+- Run:
+ - `./start.sh` (preferred) or `python main.py`
+ - `./status.sh` / `./stop.sh`
-# Manual testing with specific platform
-IM_PLATFORM=telegram python main.py
-IM_PLATFORM=slack python main.py
-```
+### Coding Conventions
-## Architecture Overview
+- Follow PEP 8, 4-space indentation.
+- Naming: `snake_case` for functions, `PascalCase` for classes/dataclasses.
+- Use type hints for public functions.
+- Keep modules cohesive; add new handlers under `core/handlers/`, new IM transports under `modules/im/`.
+- No repo-wide formatter is enforced; use Black/Ruff if you want, keep diffs focused.
-### Multi-Platform Design Pattern
+### Testing
-The system uses an abstract factory pattern with platform-agnostic interfaces:
+- No committed automated suite yet.
+- Prefer fast `pytest`-style tests (`test_<feature>.py`) colocated or under `tests/`.
+- For IM integrations, stub Slack/Telegram clients and validate outbound payload schemas.
+- Do a manual E2E sanity check (start bot, send `/start`) until CI exists.
-1. **BaseIMClient** (`modules/im/base.py`): Abstract base class defining the IM interface
-2. **IMFactory** (`modules/im/factory.py`): Creates appropriate platform clients
-3. **Controller** (`core/controller.py`): Platform-agnostic business logic coordinator
+### Agent Routing / Codex
-### Key Components
+- Codex enablement: `CODEX_ENABLED=true` and `CODEX_CLI_PATH` points to the CLI.
+- Routing file:
+ - Copy `agent_routes.example.yaml` to `agent_routes.yaml` (local).
+ - Controlled by `AGENT_ROUTE_FILE` (defaults to repo-root `agent_routes.yaml`).
+ - Keys are Slack channel IDs / Telegram chat IDs; values are agent names (e.g., `claude`, `codex`).
+ - Missing entries fall back to platform default, then to global default.
-- **Configuration System** (`config/settings.py`): Environment-based config with platform-specific validation
-- **Session Management** (`modules/session_manager.py`): Manages ClaudeSDKClient instances for persistent conversations
-- **Claude Integration** (`modules/claude_client.py`): Message formatting and platform-specific rendering
-- **Settings Management** (`modules/settings_manager.py`): User preferences, message visibility, and session ID mappings
+### Safety Notes
-### Platform Implementations
-
-- **TelegramBot** (`modules/im/telegram.py`): Telegram-specific implementation with inline keyboards
-- **SlackBot** (`modules/im/slack.py`): Slack-specific implementation with thread support and Socket Mode
-
-### Message Flow
-
-1. User sends message via IM platform
-2. Platform-specific client converts to `MessageContext`
-3. Controller immediately sends message to Claude Code via persistent session
-4. Real-time output streamed back through same IM platform
-5. Conversation context maintained for follow-up messages
-
-## User Interface
-
-### Slack Commands
-
-Slack uses a simplified command structure with only one slash command:
-
-- `/start` - Opens the main menu with interactive buttons
-
-All functionality is accessed through buttons in the /start menu:
-
-- **Current Dir** - Display current working directory
-- **Change Work Dir** - Open modal to change working directory
-- **Reset Session** - Clear conversation context and start fresh
-- **Settings** - Configure message visibility preferences
-- **How it Works** - Display help information
-
-### Telegram Commands
-
-Telegram supports traditional slash commands:
-
-- `/start` - Show welcome message and available commands
-- `/clear` - Reset conversation and start fresh
-- `/cwd` - Show current working directory
-- `/set_cwd <path>` - Change working directory
-- `/settings` - Open personalization settings
-
-## Configuration Requirements
-
-### Essential Environment Variables
-
-- `IM_PLATFORM`: Must be "telegram" or "slack"
-- Platform-specific tokens (see `.env.example`)
-- `CLAUDE_DEFAULT_CWD`: Working directory for Claude Code execution
-
-### Platform Switching
-
-The system dynamically loads the appropriate IM client based on `IM_PLATFORM`. Configuration validation ensures required tokens are present for the selected platform.
-
-## Adding New IM Platforms
-
-To extend support to new platforms (Discord, Teams, etc.):
-
-1. Create new client class inheriting from `BaseIMClient`
-2. Implement all abstract methods (send_message, edit_message, etc.)
-3. Create platform config class inheriting from `BaseIMConfig`
-4. Add platform to `IMFactory.create_client()`
-5. Update `AppConfig.from_env()` validation
-6. Add environment variables to `.env` template
-
-Reference `modules/im/slack.py` for a complete implementation example.
-
-## Thread and Session Management
-
-### Slack Thread Handling
-
-Slack conversations are automatically organized into threads. Each user message creates a thread, and all bot responses are posted as replies in that thread for better organization.
-
-### Session Management
-
-- **Telegram**: Each chat/group maintains its own Claude session
-- **Slack**: Each thread maintains its own Claude session
-- Sessions persist across messages for continuous conversations
-- Use `/clear` or Reset Session button to start fresh
-
-### Callback System
-
-The controller registers command handlers with IM clients through a callback system, allowing platform-agnostic command handling while preserving platform-specific features (inline keyboards, thread replies, etc.).
-
-## Deployment Notes
-
-### Process Management
-
-- `start.sh` provides daemon-style execution with PID tracking
-- Logs are automatically rotated and stored in `logs/` directory
-- Virtual environment detection and activation is automatic
-
-### Error Handling
-
-- Graceful degradation for missing optional tokens
-- Automatic retry with exponential backoff for network failures
-- Comprehensive logging for debugging platform-specific issues
-
-### Socket Mode vs Webhooks
-
-For Slack, Socket Mode is preferred as it doesn't require public endpoints. The system automatically uses Socket Mode if `SLACK_APP_TOKEN` is provided.
-
-## Technical Implementation Details
-
-### ClaudeSDKClient vs query()
-
-The project uses `ClaudeSDKClient` for persistent bidirectional communication instead of the simpler `query()` function. This provides:
-
-- Persistent WebSocket-like connections per session
-- Real-time message streaming without polling
-- Proper session management with resume capability
-- Better error handling and reconnection support
-
-### Session ID Mapping
-
-The system captures Claude's internal `session_id` from the `SystemMessage` and maintains a mapping:
-
-- **Purpose**: Allows precise session restoration after bot restarts
-- **Storage**: Maps IM session IDs (chat_id/thread_id) to Claude session_ids in `user_settings.json`
-- **Usage**: Uses `resume` parameter with stored session_id instead of deprecated `continue_conversation`
-
-### Concurrent Message Handling
-
-Each session has:
-
-- A dedicated `ClaudeSDKClient` instance
-- A persistent message receiver task running in the background
-- Proper cleanup mechanisms to prevent resource leaks
-
-### Platform-Specific Markdown Formatting
-
-Different platforms have unique markdown requirements:
-
-- **Telegram**: Uses MarkdownV2 with extensive character escaping
-- **Slack**: Uses mrkdwn format with different escaping rules
-- Formatter pattern allows clean separation of concerns
-
-## Common Development Challenges
-
-### Async/Await Error: "read() called while another coroutine is already waiting"
-
-**Problem**: Multiple coroutines trying to read from the same ClaudeSDKClient
-**Solution**: Implement a single persistent receiver per session that handles all messages
-
-### Session Management Edge Cases
-
-1. **Bot Restart**: Sessions are restored using stored session_id mappings
-2. **Network Errors**: Broken sessions are cleaned up and recreated automatically
-3. **User Switching Chats**: Each chat/thread maintains independent session
-
-### Safe Cleanup (Runtime Tasks)
-
-- Controlled by `CLEANUP_ENABLED` (default: `false`).
-- When enabled, the system only removes completed receiver tasks in-memory during message handling.
-- It will not disconnect active Claude clients and will not modify persisted session mappings in `user_settings.json`.
-- Goal: prevent task buildup without risking historical session restoration.
-
-### Debugging Tips
-
-1. **Enable Debug Logging**:
-
- ```python
- logging.basicConfig(level=logging.DEBUG)
- ```
-
-2. **Check Session State**:
-
- - View active sessions in `user_settings.json`
- - Monitor session creation/cleanup in logs
- - Use `/cwd` command to verify session is active
-
-3. **Platform-Specific Issues**:
- - **Telegram**: Check for markdown parsing errors in logs
- - **Slack**: Verify Socket Mode connection with app-level token
- - Both: Ensure proper environment variables are set
-
-### Testing Strategies
-
-1. **Session Persistence**:
-
- - Send message → Restart bot → Send follow-up message
- - Verify conversation context is maintained
-
-2. **Concurrent Users**:
-
- - Test multiple users sending messages simultaneously
- - Verify sessions don't interfere with each other
-
-3. **Error Recovery**:
- - Simulate network errors by disconnecting internet
- - Verify graceful error messages and recovery
-
-## Performance Optimizations
-
-1. **Message Batching**: Controller processes messages immediately without queuing
-2. **Resource Cleanup**: Proper session cleanup prevents memory leaks
-3. **Lazy Loading**: Claude clients created only when needed
-4. **Persistent Connections**: Reduces overhead of creating new connections
-
-## Security Considerations
-
-1. **Token Storage**: Never commit tokens to git
-2. **Session Isolation**: Each user's sessions are completely isolated
-3. **Command Validation**: All user inputs are validated before execution
-4. **File Path Security**: Working directory restrictions prevent unauthorized access
-
-## Best Practices
-
-- **Process Management**:
- - 不要直接执行杀进程来重启服务,使用./start.sh 会自动杀掉对应进程并重启
+- Keep `CLAUDE_DEFAULT_CWD` scoped to `_tmp/` (or another sanitized directory).
+- Logs can contain sensitive context; scrub before sharing.