# AI Repo Commander - Technical Design Document ## 1. Overview A browser userscript that enables AI assistants to securely interact with git repositories via YAML-style commands, with comprehensive safety measures and real-time feedback. ## 1.1 Diagrams (PlantUML) - Architecture Overview: Docs/diagrams/architecture-overview.puml - Command Execution Sequence: Docs/diagrams/sequence-command-execution.puml - Command Processing State Machine: Docs/diagrams/state-machine.puml How to view: open the .puml files with any PlantUML viewer (IDE plugin or web renderer) to generate images. ## 2. Core Architecture ### 2.1 Safety-First Design ```javascript // Configuration - MUST be manually enabled for production const CONFIG = { ENABLE_API: false, // Master kill switch DEBUG_MODE: true, // Development logging DEBOUNCE_DELAY: 5000, // 5-second bot typing protection MAX_RETRIES: 2, // API retry attempts VERSION: '1.0.0' }; ``` ### 2.2 Module Structure ``` AI Repo Commander ├── Core Monitor ├── Command Parser ├── Validation Engine ├── Execution Manager └── UI Feedback System ``` ## 3. Detailed Component Specifications ### 3.1 Core Monitor **Purpose:** Detect and track command messages safely **Implementation:** ```javascript class CommandMonitor { private trackedMessages: Map; // Message states static STATES = { DETECTED: 'detected', // ^%$bridge found PARSING: 'parsing', // YAML parsing in progress VALIDATING: 'validating', // Field validation DEBOUNCING: 'debouncing', // 5-second wait period EXECUTING: 'executing', // API call in progress COMPLETE: 'complete', // Command finished ERROR: 'error' // Command failed }; scanMessages(): void // Find new command messages trackMessage(element, text): void // Begin processing pipeline updateState(messageId, state): void // State machine transitions } ``` ### 3.2 Command Parser **Purpose:** Extract structured data from YAML commands **Input Format:** ```yaml ^%$bridge action: update_file repo: ai-workflow-test path: README.md content: | Multi-line content with proper formatting --- ``` **Parsing Logic:** ```javascript class CommandParser { parseYAMLCommand(text): ParsedCommand { // 1. Extract command block (^%$bridge to ---) // 2. Parse key-value pairs // 3. Handle multi-line content with | syntax // 4. Set defaults (url, owner if missing) // 5. Return structured object } validateStructure(parsed): ValidationResult { // Check for required fields based on action type // Validate field formats // Return { isValid: boolean, errors: string[] } } } ``` ### 3.3 Validation Engine **Purpose:** Ensure command completeness and safety **Required Fields Matrix:** ```javascript const REQUIRED_FIELDS = { 'update_file': ['action', 'repo', 'path', 'content'], 'get_file': ['action', 'repo', 'path'], 'create_repo': ['action', 'repo'], 'create_file': ['action', 'repo', 'path', 'content'], 'delete_file': ['action', 'repo', 'path'], 'list_files': ['action', 'repo', 'path'] }; const FIELD_VALIDATORS = { 'repo': (value) => /^[\w\-\.]+$/.test(value), 'path': (value) => !value.includes('..') && !value.startsWith('/'), 'action': (value) => Object.keys(REQUIRED_FIELDS).includes(value) }; ``` ### 3.4 Execution Manager **Purpose:** Handle API calls with comprehensive safety **Execution Flow:** ```javascript class ExecutionManager { async executeCommand(command, sourceElement): Promise { // 1. Pre-execution safety checks if (!CONFIG.ENABLE_API) { return this.mockExecution(command, sourceElement); } // 2. API call with retry logic try { const response = await this.makeAPICall(command); return this.handleSuccess(response, sourceElement); } catch (error) { return this.handleError(error, sourceElement); } } makeAPICall(command): Promise { return new Promise((resolve, reject) => { GM_xmlhttpRequest({ method: 'POST', url: command.url || 'https://n8n.brrd.tech/webhook/ai-gitea-bridge', headers: { 'X-Bridge-Key': 'mango-rocket-82', 'Content-Type': 'application/json' }, data: JSON.stringify(command), timeout: 30000, onload: resolve, onerror: reject, ontimeout: reject }); }); } } ``` ### 3.5 UI Feedback System **Purpose:** Provide clear, consistent user feedback **Status Message Templates:** ```javascript const STATUS_TEMPLATES = { SUCCESS: '[{action}: Success] {details}', ERROR: '[{action}: Error] {details}', VALIDATION_ERROR: '[{action}: Invalid] {details}', EXECUTING: '[{action}: Processing...]', MOCK: '[{action}: Mock] {details}' }; class UIFeedback { replaceWithStatus(sourceElement, template, data): void { // 1. Create status element matching original style // 2. Apply appropriate color coding // 3. Replace original message // 4. Add copy-friendly formatting } colorCodeStatus(type): string { return { 'success': '#10B981', // Green 'error': '#EF4444', // Red 'warning': '#F59E0B', // Yellow 'info': '#3B82F6' // Blue }[type]; } } ``` ## 4. Processing Pipeline ### 4.1 Step-by-Step Flow ``` 1. MONITOR: Detect ^%$bridge in new messages 2. TRACK: Assign unique ID and initial state 3. PARSE: Extract YAML into structured command 4. VALIDATE: Check required fields and formats 5. DEBOUNCE: Wait 5 seconds for bot typing completion 6. EXECUTE: Make API call (or mock if disabled) 7. FEEDBACK: Replace with status message 8. CLEANUP: Update state to complete ``` ### 4.2 Error Handling Flow ``` Parse Error → [Action: Invalid] Invalid YAML format Validation Error → [Action: Invalid] Missing field: content API Error → [Action: Error] Network timeout Network Error → [Action: Error] Cannot reach bridge ``` ## 5. Safety Mechanisms ### 5.1 Multiple Protection Layers - **API Master Switch:** ENABLE_API must be explicitly true - **Command Validation:** Required fields and format checking - **Bot Debouncing:** 5-second wait prevents partial command execution - **Network Timeouts:** 30-second API call limits - **Error Boundaries:** Isolated error handling per command - **State Tracking:** Prevents duplicate processing ### 5.2 Emergency Stop Options ```javascript // Manual stop mechanisms const emergencyStop = () => { CONFIG.ENABLE_API = false; CommandMonitor.stopAllProcessing(); clearAllIntervals(); }; // Browser console commands window.AI_REPO_STOP = emergencyStop; ``` ## 6. Cross-Platform Compatibility ### 6.1 DOM Selectors by Platform ```javascript const PLATFORM_SELECTORS = { 'chat.openai.com': { messages: '[class*="message"]', input: '#prompt-textarea' }, 'claude.ai': { messages: '.chat-message', input: '[contenteditable="true"]' }, 'gemini.google.com': { messages: '.message-content', input: 'textarea, [contenteditable="true"]' } }; ``` ## 7. Testing Strategy ### 7.1 Development Testing Commands ```javascript // Test command generator for safe testing const TEST_COMMANDS = { validUpdate: `^%$bridge action: update_file repo: test-repo path: TEST.md content: | Test content Multiple lines ---`, invalidCommand: `^%$bridge action: update_file repo: test-repo ---`, getFile: `^%$bridge action: get_file repo: test-repo path: README.md ---` }; ``` ## 8. Deployment Checklist ### 8.1 Pre-Launch Verification - ENABLE_API = false in production code - All error cases handled gracefully - Status messages clear and informative - Bot typing protection working - Cross-browser compatibility verified - Memory leaks checked (interval cleanup) - Performance impact acceptable ### 8.2 Production Enablement Steps 1. Test thoroughly with ENABLE_API = false 2. Verify mock executions work correctly 3. Enable API for single test command 4. Monitor real API interactions 5. Enable for full usage --- This design provides a comprehensive, safe, and extensible foundation for your AI Repo Commander.