# Custom Executors Source: https://docs.namastex.ai/forge/advanced/custom-executors Build your own AI agent executors for Forge ## Overview Custom executors allow you to integrate any AI coding tool or custom logic into Forge. Extend beyond the 8 built-in agents to add your own automation. **Use cases**: Custom APIs, internal tools, specialized workflows, proprietary models *** ## Executor Interface Create a custom executor by implementing the Executor interface: ```typescript theme={null} interface Executor { name: string; version: string; // Execute a task execute(task: Task, options: ExecutorOptions): Promise; // Check if executor can handle this task canHandle(task: Task): boolean; // Optional: Estimate cost estimateCost?(task: Task): Promise; // Optional: Cancel execution cancel?(executionId: string): Promise; } ``` *** ## Basic Custom Executor ### Simple Example ```typescript theme={null} import { Executor, Task, ExecutionResult } from '@automagik/forge-sdk'; export class MyCustomExecutor implements Executor { name = 'my-custom-executor'; version = '1.0.0'; async execute(task: Task, options: any): Promise { console.log(`Executing task: ${task.title}`); // Your custom logic here const result = await this.runCustomLogic(task); return { success: true, output: result, filesChanged: [], cost: 0 }; } canHandle(task: Task): boolean { // Only handle tasks with specific label return task.labels.includes('custom-executor'); } private async runCustomLogic(task: Task): Promise { // Implement your custom logic return `Task ${task.title} completed!`; } } ``` ### Register Executor ```typescript theme={null} import { ForgeClient } from '@automagik/forge-sdk'; import { MyCustomExecutor } from './my-custom-executor'; const forge = new ForgeClient(); // Register custom executor forge.executors.register(new MyCustomExecutor()); // Now use it await forge.tasks.create({ title: 'Custom task', labels: ['custom-executor'] // Will use MyCustomExecutor }); ``` *** ## Advanced Executor ### Full-Featured Executor ```typescript theme={null} import { Executor, Task, ExecutionResult } from '@automagik/forge-sdk'; import axios from 'axios'; export class CustomAPIExecutor implements Executor { name = 'custom-api-executor'; version = '1.0.0'; private apiKey: string; private baseUrl: string; private activeExecutions: Map; constructor(config: { apiKey: string; baseUrl: string }) { this.apiKey = config.apiKey; this.baseUrl = config.baseUrl; this.activeExecutions = new Map(); } async execute(task: Task, options: any): Promise { const executionId = this.generateExecutionId(); const controller = new AbortController(); this.activeExecutions.set(executionId, controller); try { // Call your custom API const response = await axios.post( `${this.baseUrl}/execute`, { task: { title: task.title, description: task.description, files: task.metadata?.files || [] }, options }, { headers: { 'Authorization': `Bearer ${this.apiKey}`, 'Content-Type': 'application/json' }, signal: controller.signal } ); // Process response const result = this.processResponse(response.data); return { success: true, output: result.output, filesChanged: result.filesChanged, cost: result.cost || 0, metadata: { executionId, duration: result.duration } }; } catch (error) { return { success: false, error: error.message, cost: 0 }; } finally { this.activeExecutions.delete(executionId); } } canHandle(task: Task): boolean { // Handle tasks with specific metadata return task.metadata?.executor === 'custom-api'; } async estimateCost(task: Task): Promise { // Estimate based on task complexity const complexity = this.calculateComplexity(task); return complexity * 0.01; // $0.01 per complexity point } async cancel(executionId: string): Promise { const controller = this.activeExecutions.get(executionId); if (controller) { controller.abort(); this.activeExecutions.delete(executionId); } } private generateExecutionId(): string { return `exec_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`; } private calculateComplexity(task: Task): number { const descriptionLength = task.description?.length || 0; const fileCount = task.metadata?.files?.length || 0; return Math.ceil(descriptionLength / 100) + fileCount * 10; } private processResponse(data: any): any { // Process your API response return { output: data.result, filesChanged: data.files || [], cost: data.cost, duration: data.duration }; } } ``` *** ## Use Cases ### Internal Company Tool ```typescript theme={null} export class InternalToolExecutor implements Executor { name = 'company-internal-tool'; version = '1.0.0'; async execute(task: Task, options: any): Promise { // Connect to internal tool const tool = await this.connectToInternalTool(); // Run company-specific workflow const result = await tool.generateCode({ spec: task.description, template: options.template, standards: 'company-standards-v2' }); return { success: true, output: result.code, filesChanged: result.files, cost: 0 // Internal tool, no cost }; } canHandle(task: Task): boolean { return task.labels.includes('company-tool'); } private async connectToInternalTool() { // Internal API connection return { generateCode: async (params: any) => { // Implementation return { code: '// Generated code', files: [] }; } }; } } ``` ### Proprietary Model ```typescript theme={null} export class ProprietaryModelExecutor implements Executor { name = 'proprietary-model'; version = '1.0.0'; private modelEndpoint: string; async execute(task: Task, options: any): Promise { // Use your proprietary model const response = await fetch(this.modelEndpoint, { method: 'POST', body: JSON.stringify({ prompt: this.buildPrompt(task), temperature: options.temperature || 0.7 }) }); const result = await response.json(); return { success: true, output: result.generated_code, filesChanged: this.extractFiles(result), cost: result.cost || 0 }; } canHandle(task: Task): boolean { return task.metadata?.model === 'proprietary'; } private buildPrompt(task: Task): string { return ` Task: ${task.title} Description: ${task.description} Generate production-ready code following our standards. `; } private extractFiles(result: any): string[] { // Extract changed files from result return result.files || []; } } ``` ### Hybrid Human-AI ```typescript theme={null} export class HumanReviewExecutor implements Executor { name = 'human-review'; version = '1.0.0'; async execute(task: Task, options: any): Promise { // Step 1: AI generates initial code const aiResult = await this.runAI(task); // Step 2: Send to human for review const reviewRequest = await this.requestHumanReview({ task, aiOutput: aiResult, reviewers: options.reviewers || ['team-lead'] }); // Step 3: Wait for human approval const approved = await this.waitForApproval(reviewRequest.id); if (approved.status === 'approved') { return { success: true, output: approved.finalCode, filesChanged: aiResult.filesChanged, cost: aiResult.cost, metadata: { aiGenerated: true, humanReviewed: true, reviewer: approved.reviewer } }; } else { return { success: false, error: 'Human review rejected', cost: aiResult.cost }; } } canHandle(task: Task): boolean { return task.priority === 'critical'; } private async runAI(task: Task) { // Use AI to generate initial code return { code: '// AI generated code', filesChanged: [], cost: 0.23 }; } private async requestHumanReview(params: any) { // Send to review system (Slack, email, etc.) return { id: 'review_123' }; } private async waitForApproval(reviewId: string) { // Poll or wait for webhook return { status: 'approved', finalCode: '// Reviewed code', reviewer: 'john@company.com' }; } } ``` *** ## Configuration ### Executor Config File Create `.forge/executors/my-executor.json`: ```json theme={null} { "name": "my-custom-executor", "enabled": true, "config": { "apiKey": "${CUSTOM_API_KEY}", "baseUrl": "https://api.example.com", "timeout": 60000, "retries": 3 }, "priority": 10, "capabilities": ["code-generation", "refactoring"], "supportedLanguages": ["typescript", "python", "go"] } ``` ### Load Executors ```typescript theme={null} import { ForgeClient } from '@automagik/forge-sdk'; import { loadExecutorConfig } from './executor-loader'; const forge = new ForgeClient(); // Load from config const executorConfig = loadExecutorConfig('.forge/executors'); for (const config of executorConfig) { const executor = createExecutor(config); forge.executors.register(executor); } ``` *** ## Testing Custom Executors ### Unit Tests ```typescript theme={null} import { MyCustomExecutor } from './my-custom-executor'; describe('MyCustomExecutor', () => { let executor: MyCustomExecutor; beforeEach(() => { executor = new MyCustomExecutor({ apiKey: 'test-key', baseUrl: 'http://localhost:3000' }); }); it('should execute task successfully', async () => { const task = { id: 'task_1', title: 'Test task', description: 'Test description', labels: ['custom-executor'] }; const result = await executor.execute(task, {}); expect(result.success).toBe(true); expect(result.output).toBeDefined(); }); it('should handle errors gracefully', async () => { const task = { id: 'task_2', title: 'Failing task', description: 'This will fail', labels: ['custom-executor'] }; const result = await executor.execute(task, {}); expect(result.success).toBe(false); expect(result.error).toBeDefined(); }); it('should estimate cost accurately', async () => { const task = { id: 'task_3', title: 'Cost estimation test', description: 'A'.repeat(1000), // 1000 chars labels: [] }; const cost = await executor.estimateCost(task); expect(cost).toBeGreaterThan(0); }); }); ``` *** ## Publishing Executors ### NPM Package ```json theme={null} // package.json { "name": "@your-org/forge-executor-custom", "version": "1.0.0", "main": "dist/index.js", "types": "dist/index.d.ts", "peerDependencies": { "@automagik/forge-sdk": "^0.4.0" } } ``` ### Usage by Others ```bash theme={null} # Install your executor npm install @your-org/forge-executor-custom ``` ```typescript theme={null} import { CustomExecutor } from '@your-org/forge-executor-custom'; import { ForgeClient } from '@automagik/forge-sdk'; const forge = new ForgeClient(); forge.executors.register(new CustomExecutor({ apiKey: process.env.CUSTOM_API_KEY })); ``` *** ## Best Practices ```typescript theme={null} async execute(task: Task): Promise { try { const result = await this.runTask(task); return { success: true, ...result }; } catch (error) { return { success: false, error: error.message, cost: 0 }; } } ``` Never throw unhandled errors ```typescript theme={null} async execute(task: Task): Promise { const startCost = await this.getCurrentCost(); // Execute task const result = await this.runTask(task); const endCost = await this.getCurrentCost(); return { success: true, output: result, cost: endCost - startCost }; } ``` Track actual costs ```typescript theme={null} private activeExecutions = new Map(); async cancel(executionId: string) { const controller = this.activeExecutions.get(executionId); if (controller) { controller.abort(); } } ``` Allow cancelling long-running tasks ```typescript theme={null} async execute(task: Task, options: any) { const onProgress = options.onProgress; onProgress?.({ stage: 'initializing', percent: 0 }); // ... work ... onProgress?.({ stage: 'generating', percent: 50 }); // ... work ... onProgress?.({ stage: 'complete', percent: 100 }); } ``` Report progress for long tasks *** ## Next Steps Combine with specialized agents Trigger executors via webhooks Integrate with Forge API Full SDK reference # Parallel Execution Source: https://docs.namastex.ai/forge/advanced/parallel-execution Run multiple AI agents simultaneously ## Overview Parallel execution allows running multiple task attempts simultaneously, dramatically reducing total execution time. Perfect for comparing approaches or working on independent tasks. **Speed boost**: Run 3 attempts in parallel = 3x faster than sequential execution! *** ## Why Parallel Execution? ### Sequential (Slow) ``` Task 1 (Claude): [====] 5 min Task 2 (Gemini): [===] 3 min Task 3 (GPT-4): [====] 4 min Total time: 12 minutes ``` ### Parallel (Fast) ``` Task 1 (Claude): [====] 5 min Task 2 (Gemini): [===] 3 min Task 3 (GPT-4): [====] 4 min Total time: 5 minutes (limited by slowest) ``` **Result**: 2.4x faster! *** ## Basic Parallel Execution ### Via CLI ```bash theme={null} # Run multiple attempts in parallel forge task create "Add authentication" --llm claude & forge task fork 1 --llm gemini & forge task fork 1 --llm gpt-4 & wait # All three run simultaneously! ``` ### Via SDK ```typescript theme={null} import { ForgeClient } from '@automagik/forge-sdk'; const forge = new ForgeClient(); // Create task const task = await forge.tasks.create({ title: 'Add authentication', projectId: 'proj_123' }); // Start 3 attempts in parallel const attempts = await Promise.all([ forge.attempts.create({ taskId: task.id, llm: 'claude' }), forge.attempts.create({ taskId: task.id, llm: 'gemini' }), forge.attempts.create({ taskId: task.id, llm: 'gpt-4' }) ]); console.log('All attempts started!'); ``` *** ## Advanced Parallel Patterns ### Parallel Task Creation Create and start multiple tasks at once: ```typescript theme={null} const tasks = await Promise.all([ forge.tasks.create({ title: 'Add authentication', llm: 'claude' }), forge.tasks.create({ title: 'Add dark mode', llm: 'gemini' }), forge.tasks.create({ title: 'Add search', llm: 'cursor' }) ]); // Start all tasks await Promise.all( tasks.map(task => forge.tasks.start(task.id)) ); ``` ### Parallel Comparison Compare multiple agents on the same task: ```typescript theme={null} async function compareAgents(taskId: string) { const agents = ['claude', 'gemini', 'gpt-4', 'cursor']; // Create attempts in parallel const attempts = await Promise.all( agents.map(agent => forge.attempts.create({ taskId, llm: agent }) ) ); // Wait for all to complete await Promise.all( attempts.map(attempt => forge.attempts.waitForCompletion(attempt.id) ) ); // Compare results return forge.attempts.compare( attempts.map(a => a.id) ); } ``` *** ## Resource Management ### Concurrency Limits Don't run too many at once: ```typescript theme={null} import pLimit from 'p-limit'; // Limit to 3 concurrent executions const limit = pLimit(3); const tasks = [/* 10 tasks */]; await Promise.all( tasks.map(task => limit(() => forge.tasks.start(task.id)) ) ); // Only 3 run at a time ``` ### Rate Limiting Respect API rate limits: ```typescript theme={null} import pThrottle from 'p-throttle'; // Max 5 requests per second const throttle = pThrottle({ limit: 5, interval: 1000 }); const throttled = throttle(async (task) => { return forge.tasks.create(task); }); await Promise.all( taskData.map(data => throttled(data)) ); ``` *** ## Git Worktree Isolation Each parallel attempt gets its own worktree: ``` .forge/worktrees/ ├── task-1-claude/ ← Isolated workspace ├── task-1-gemini/ ← Isolated workspace ├── task-1-gpt-4/ ← Isolated workspace └── task-2-cursor/ ← Different task ``` **Benefits**: * No conflicts between attempts * Safe parallel modifications * Easy to compare results **Automatic cleanup**: ```bash theme={null} # Forge automatically cleans up after merge forge task merge 1 --attempt 2 # Or manually forge worktree cleanup ``` *** ## Monitoring Parallel Execution ### Real-Time Dashboard ```typescript theme={null} async function monitorParallelTasks(taskIds: string[]) { const interval = setInterval(async () => { const statuses = await Promise.all( taskIds.map(async id => { const task = await forge.tasks.get(id); return { id, title: task.title, status: task.status, progress: task.attempts[0]?.progress || 0 }; }) ); console.clear(); console.table(statuses); if (statuses.every(s => s.status === 'completed')) { clearInterval(interval); } }, 1000); } ``` ### Progress Aggregation ```typescript theme={null} async function getOverallProgress(taskIds: string[]) { const tasks = await Promise.all( taskIds.map(id => forge.tasks.get(id)) ); const total = tasks.length; const completed = tasks.filter(t => t.status === 'completed').length; const inProgress = tasks.filter(t => t.status === 'in_progress').length; return { total, completed, inProgress, percentage: (completed / total) * 100 }; } ``` *** ## Error Handling ### Graceful Degradation ```typescript theme={null} async function parallelWithFallback(taskId: string) { const agents = ['claude', 'gemini', 'gpt-4']; const results = await Promise.allSettled( agents.map(agent => forge.attempts.create({ taskId, llm: agent }) .then(attempt => forge.attempts.start(attempt.id)) ) ); // Check which succeeded const succeeded = results.filter(r => r.status === 'fulfilled'); const failed = results.filter(r => r.status === 'rejected'); console.log(`${succeeded.length} succeeded, ${failed.length} failed`); // Use whichever succeeded return succeeded.map(r => r.value); } ``` ### Timeout Handling ```typescript theme={null} async function withTimeout( promise: Promise, timeoutMs: number ): Promise { const timeout = new Promise((_, reject) => setTimeout(() => reject(new Error('Timeout')), timeoutMs) ); return Promise.race([promise, timeout]); } // Use it const attempts = await Promise.all([ withTimeout( forge.attempts.create({ taskId, llm: 'claude' }), 60000 // 1 minute timeout ), withTimeout( forge.attempts.create({ taskId, llm: 'gemini' }), 60000 ) ]); ``` *** ## Cost Optimization ### Smart Parallel Strategy ```typescript theme={null} async function costOptimizedParallel(taskId: string) { // Step 1: Quick exploration with cheap models const cheapAttempts = await Promise.all([ forge.attempts.create({ taskId, llm: 'gemini' }), // Free! forge.attempts.create({ taskId, llm: 'claude-haiku' }) // Cheap ]); await Promise.all( cheapAttempts.map(a => forge.attempts.waitForCompletion(a.id)) ); // Step 2: Review cheap results const cheapResults = await forge.attempts.compare( cheapAttempts.map(a => a.id) ); // Step 3: Only use expensive model if needed if (cheapResults.quality < 0.8) { const expensiveAttempt = await forge.attempts.create({ taskId, llm: 'claude-sonnet' }); await forge.attempts.waitForCompletion(expensiveAttempt.id); } // Saved money by not always using expensive model! } ``` *** ## Batch Operations ### Bulk Task Processing ```typescript theme={null} async function processBulkTasks(tasks: TaskInput[]) { // Create all tasks in parallel const created = await Promise.all( tasks.map(task => forge.tasks.create(task)) ); // Start all tasks in parallel (with concurrency limit) const limit = pLimit(5); await Promise.all( created.map(task => limit(() => forge.tasks.start(task.id)) ) ); // Wait for all to complete await Promise.all( created.map(task => forge.tasks.waitForCompletion(task.id) ) ); return created; } ``` ### Parallel Template Execution ```typescript theme={null} async function parallelTemplateRun( templateName: string, configs: TemplateConfig[] ) { // Use template with different configs in parallel const results = await Promise.all( configs.map(config => forge.templates.use(templateName, config) ) ); return results; } // Example: Test API with different configurations await parallelTemplateRun('api-endpoint', [ { resourceName: 'user', methods: ['GET', 'POST'] }, { resourceName: 'product', methods: ['GET', 'POST', 'PUT'] }, { resourceName: 'order', methods: ['GET', 'POST', 'DELETE'] } ]); ``` *** ## Real-World Examples ### Example 1: A/B/C Testing ```typescript theme={null} async function abcTest(featureName: string) { // Try 3 different implementations simultaneously const approaches = [ { llm: 'claude', agent: 'performance-optimizer' }, { llm: 'gemini', agent: 'simple-clean' }, { llm: 'gpt-4', agent: 'comprehensive' } ]; const task = await forge.tasks.create({ title: `Implement ${featureName}`, description: 'Try different approaches' }); // Run all approaches in parallel const attempts = await Promise.all( approaches.map(({ llm, agent }) => forge.attempts.create({ taskId: task.id, llm, agent }) ) ); // Wait for completion await Promise.all( attempts.map(a => forge.attempts.waitForCompletion(a.id)) ); // Compare results const comparison = await forge.attempts.compare( attempts.map(a => a.id) ); // Pick winner return comparison.winner; } ``` ### Example 2: Multi-Platform Development ```typescript theme={null} async function multiPlatformDevelopment(feature: string) { // Develop for multiple platforms simultaneously const platforms = [ { platform: 'web', llm: 'cursor' }, { platform: 'mobile', llm: 'claude' }, { platform: 'desktop', llm: 'gemini' } ]; const tasks = await Promise.all( platforms.map(({ platform, llm }) => forge.tasks.create({ title: `${feature} for ${platform}`, llm }) ) ); // All platforms developed in parallel! await Promise.all( tasks.map(task => forge.tasks.start(task.id)) ); return tasks; } ``` *** ## Best Practices ```typescript theme={null} // Good ✅ const limit = pLimit(3); await Promise.all( tasks.map(t => limit(() => runTask(t))) ); // Bad ❌ await Promise.all( tasks.map(t => runTask(t)) ); // Could spawn 100+ parallel tasks! ``` ```typescript theme={null} // Use Promise.allSettled const results = await Promise.allSettled([ attempt1, attempt2, attempt3 ]); // Check which succeeded const successful = results .filter(r => r.status === 'fulfilled') .map(r => r.value); ``` ```bash theme={null} # Check system resources htop # Watch Forge processes forge processes list --watch # Check disk usage du -sh .forge/worktrees ``` ```typescript theme={null} // After parallel execution await forge.worktrees.cleanup(); // Remove failed attempts await forge.attempts.deleteWhere({ status: 'failed' }); ``` *** ## Performance Metrics Track parallel execution performance: ```typescript theme={null} async function measureParallelPerformance() { const sequential = await measureSequential(); const parallel = await measureParallel(); return { sequential: { time: sequential.time, cost: sequential.cost }, parallel: { time: parallel.time, cost: parallel.cost }, speedup: sequential.time / parallel.time, costRatio: parallel.cost / sequential.cost }; } // Example output: // { // sequential: { time: 720000, cost: 0.45 }, // parallel: { time: 300000, cost: 0.45 }, // speedup: 2.4, // costRatio: 1.0 // } // Result: 2.4x faster, same cost! ``` *** ## Next Steps Run different agents in parallel Templates with parallel tasks Monitor parallel executions Complete workflows with parallelism # Specialized Agents Source: https://docs.namastex.ai/forge/advanced/specialized-agents Create custom agent personas for specific tasks ## Overview Specialized agents are custom configurations that modify how any base AI agent behaves. Apply "personas" like "security expert" or "test writer" to any LLM for task-specific optimization. **Key Concept**: Specialized agents are prompts + configurations, not separate models. They work with ANY base LLM! *** ## How They Work ``` Base Agent (Claude) + Specialized Profile (Security Expert) = Secure Code Focus Base Agent (Gemini) + Specialized Profile (Test Writer) = Comprehensive Tests Base Agent (GPT-4) + Specialized Profile (Performance) = Optimized Code ``` *** ## Built-in Specialized Agents ### Security Expert Focus on security best practices and vulnerability prevention. ```bash theme={null} forge task create \ --title "Add file upload" \ --llm claude \ --agent security-expert ``` **Behaviors**: * Always validates input * Considers injection attacks * Implements proper sanitization * Adds rate limiting * Includes security headers * Documents security decisions **Best for**: Auth systems, API endpoints, data handling *** ### Test Writer Comprehensive test coverage with edge cases. ```bash theme={null} forge task create \ --title "Add authentication" \ --llm gemini \ --agent test-writer ``` **Behaviors**: * Writes tests first (TDD) * Covers edge cases * Tests error handling * Adds integration tests * Achieves 90%+ coverage * Documents test scenarios **Best for**: New features, refactoring, bug fixes *** ### Performance Optimizer Optimize for speed and efficiency. ```bash theme={null} forge task create \ --title "Speed up API" \ --llm claude \ --agent performance-optimizer ``` **Behaviors**: * Profiles bottlenecks * Adds caching * Optimizes queries * Reduces allocations * Implements lazy loading * Measures improvements **Best for**: Slow endpoints, database queries, large datasets *** ### Documentation Writer Clear, comprehensive documentation. ```bash theme={null} forge task create \ --title "Document API" \ --llm openai \ --agent docs-writer ``` **Behaviors**: * Writes clear JSDoc/docstrings * Includes usage examples * Explains edge cases * Creates README sections * Adds inline comments * Documents assumptions **Best for**: Public APIs, complex logic, team projects *** ### Code Reviewer Thorough code review with suggestions. ```bash theme={null} forge task create \ --title "Review authentication PR" \ --llm claude \ --agent code-reviewer ``` **Behaviors**: * Checks code style * Identifies bugs * Suggests improvements * Reviews tests * Validates architecture * Provides constructive feedback **Best for**: PR reviews, code audits, refactoring validation *** ### Accessibility Expert WCAG-compliant accessible interfaces. ```bash theme={null} forge task create \ --title "Build form component" \ --llm cursor \ --agent accessibility-expert ``` **Behaviors**: * Adds ARIA labels * Ensures keyboard navigation * Proper focus management * Screen reader support * Color contrast compliance * Semantic HTML **Best for**: UI components, forms, interactive features *** ## Creating Custom Agents ### Configuration File Create `.forge/agents.yaml`: ```yaml theme={null} agents: # Custom agent for your team's style team-style: name: "Team Style Enforcer" description: "Enforces our coding standards" systemPrompt: | You are a code generator following our team's style guide: - Use TypeScript with strict mode - Prefer functional programming - Use async/await, never callbacks - Write tests with Jest - Follow our naming conventions: PascalCase for components, camelCase for functions - Always add JSDoc comments temperature: 0.3 # Less creative, more consistent examples: - input: "Create user component" output: | /** * User profile component * @param {UserProps} props - Component props */ export const UserProfile: React.FC = ({ user }) => { // Implementation following team style } # Database expert database-expert: name: "Database Optimization Expert" systemPrompt: | You are a database optimization expert. For every query: - Consider indexing strategies - Avoid N+1 problems - Use prepared statements - Optimize JOIN operations - Add query performance comments - Include EXPLAIN plans in comments focusAreas: - "Query optimization" - "Index design" - "Transaction management" # API designer api-designer: name: "RESTful API Designer" systemPrompt: | You design clean, RESTful APIs following best practices: - Use proper HTTP methods (GET, POST, PUT, PATCH, DELETE) - Design resource-oriented URLs - Version APIs (v1, v2) - Include pagination for lists - Implement proper error responses - Add request/response examples - Follow OpenAPI spec guidelines: - "REST principles" - "HTTP status codes" - "API versioning" ``` *** ## Using Custom Agents ```bash theme={null} # Use your custom agent forge task create \ --title "Add user endpoint" \ --llm claude \ --agent team-style # Load from file forge task create \ --title "Optimize queries" \ --llm gemini \ --agent database-expert \ --agent-config .forge/agents.yaml ``` *** ## Agent Combinations Apply multiple agents to same task: ```bash theme={null} # Security + Testing forge task create \ --title "Add payment processing" \ --llm claude \ --agents security-expert,test-writer # Performance + Documentation forge task create \ --title "Optimize search" \ --llm gemini \ --agents performance-optimizer,docs-writer ``` **Result**: Code that's secure, well-tested, AND fast! *** ## Agent Templates ### Frontend Component Agent ```yaml theme={null} frontend-component: name: "React Component Expert" systemPrompt: | Create React components following best practices: - Use TypeScript with proper types - Implement proper prop validation - Add accessibility (ARIA) - Make components responsive - Add loading and error states - Include Storybook stories - Write comprehensive tests preferredPatterns: - "Functional components with hooks" - "Composition over inheritance" - "Single responsibility" ``` ### Backend API Agent ```yaml theme={null} backend-api: name: "Backend API Expert" systemPrompt: | Create backend APIs with: - Proper error handling - Input validation - Request logging - Authentication middleware - Rate limiting - API documentation (OpenAPI) - Integration tests frameworks: - "Express.js" - "Fastify" patterns: - "Controller-Service-Repository" - "Dependency injection" ``` ### Infrastructure Agent ```yaml theme={null} infrastructure: name: "Infrastructure as Code Expert" systemPrompt: | Create infrastructure code following best practices: - Modular and reusable - Environment-specific configs - Secrets management - Resource tagging - Cost optimization - Disaster recovery tools: - "Terraform" - "Docker" - "Kubernetes" ``` *** ## SDK Usage ### JavaScript/TypeScript ```typescript theme={null} import { ForgeClient } from '@automagik/forge-sdk'; const forge = new ForgeClient(); // Use built-in agent await forge.tasks.create({ title: 'Add authentication', llm: 'claude', agent: 'security-expert' }); // Use custom agent await forge.tasks.create({ title: 'Add component', llm: 'cursor', agent: 'frontend-component', agentConfig: './forge/agents.yaml' }); // Multiple agents await forge.tasks.create({ title: 'Critical feature', llm: 'claude', agents: ['security-expert', 'test-writer', 'docs-writer'] }); ``` *** ## Best Practices ```bash theme={null} # Security-critical → security-expert forge task create "Add auth" \ --agent security-expert # Public API → docs-writer forge task create "Document API" \ --agent docs-writer ``` Don't use all agents at once: **Good**: security-expert + test-writer **Bad**: All 8 agents (conflicting priorities) Codify your team's style: ```yaml theme={null} team-standard: systemPrompt: | Follow our team's standards: - [Your specific rules] ``` Test agent configs: ```bash theme={null} # Try different temperatures # Adjust system prompts # Add examples # Measure results ``` *** ## Agent Configuration Options ### Temperature Controls creativity vs consistency: ```yaml theme={null} agents: consistent-coder: temperature: 0.3 # Very consistent creative-designer: temperature: 0.9 # More creative ``` ### Max Tokens Control response length: ```yaml theme={null} agents: concise: maxTokens: 1024 # Short responses comprehensive: maxTokens: 8192 # Detailed responses ``` ### Examples Provide examples for better results: ```yaml theme={null} agents: our-style: examples: - input: "Create function to add numbers" output: | /** * Adds two numbers together * @param a First number * @param b Second number * @returns Sum of a and b */ export const add = (a: number, b: number): number => { return a + b; }; ``` *** ## Measuring Agent Effectiveness Track which agents work best: ```bash theme={null} # Generate report forge agent-stats --month january # Output: # Agent Tasks Success Avg Cost # security-expert 12 100% $0.28 # test-writer 18 94% $0.19 # performance 8 88% $0.31 # docs-writer 15 100% $0.15 ``` *** ## Troubleshooting **Issue**: Agent behavior not visible **Solutions**: * Check agent config is loaded * Verify agent name matches * Inspect system prompt in logs * Try more explicit instructions **Issue**: Multiple agents conflict **Solution**: Limit to 2-3 compatible agents: **Good**: security + testing **Bad**: performance + comprehensive-docs (conflicting goals) **Issue**: Agent over-optimizes for one aspect **Solution**: Adjust temperature or prompt: ```yaml theme={null} agents: balanced-security: temperature: 0.7 # More flexible systemPrompt: "Consider security but balance with readability" ``` *** ## Real-World Examples ### Example 1: Secure Payment Processing ```bash theme={null} forge task create \ --title "Implement Stripe payment" \ --description " Add Stripe payment processing: - Webhook handler - Payment intent creation - Subscription management " \ --llm claude \ --agents security-expert,test-writer ``` **Result**: * Input validation on all endpoints * Webhook signature verification * Idempotency keys * Error handling * Comprehensive tests (95% coverage) * Security documentation ### Example 2: Public API ```bash theme={null} forge task create \ --title "Create REST API" \ --llm openai \ --agents api-designer,docs-writer ``` **Result**: * RESTful URL design * Proper HTTP methods * OpenAPI specification * Request/response examples * Error documentation * Rate limiting docs *** ## Next Steps Reusable task patterns Run multiple agents simultaneously Learn about base AI agents Complete development workflows # Task Templates Source: https://docs.namastex.ai/forge/advanced/task-templates Reusable task patterns and templates ## Overview Task templates are pre-configured patterns for common workflows. Save time by reusing proven approaches instead of starting from scratch every time. Templates capture task structure, description patterns, labels, and agent preferences. *** ## Built-in Templates ### Authentication Template ```bash theme={null} forge task create --template auth # Creates task with: # - Title: "Implement authentication system" # - Description: JWT, login/signup endpoints, middleware # - Labels: feature, backend, security # - Recommended agent: security-expert # - Subtasks: JWT generation, endpoints, middleware, tests ``` ### CRUD Template ```bash theme={null} forge task create --template crud --resource User # Creates tasks for: # - Create endpoint (POST /users) # - Read endpoints (GET /users, GET /users/:id) # - Update endpoint (PUT /users/:id) # - Delete endpoint (DELETE /users/:id) # - Validation and tests ``` ### Component Template ```bash theme={null} forge task create --template component --name "UserProfile" # Creates React component task with: # - TypeScript types # - Props interface # - Accessibility requirements # - Tests with React Testing Library # - Storybook story ``` ### API Integration Template ```bash theme={null} forge task create --template api-integration --service "Stripe" # Creates integration tasks: # - Client wrapper # - Error handling # - Webhook handler # - Tests with mocks # - Documentation ``` *** ## Creating Custom Templates ### Template File Structure Create `.forge/templates/my-template.yaml`: ```yaml theme={null} name: "My Custom Template" description: "Template for our team's standard feature" version: "1.0.0" metadata: author: "Your Team" tags: ["backend", "api"] # Default values defaults: priority: "medium" llm: "claude" agent: "team-standard" labels: - "feature" # Template variables variables: - name: "resourceName" description: "Name of the resource (e.g., User, Product)" required: true type: "string" - name: "includeAuth" description: "Include authentication" required: false type: "boolean" default: true # Task structure task: title: "Implement {{resourceName}} management" description: | Create complete {{resourceName}} management system: ## Endpoints - POST /api/{{resourceName | lowercase}}s - GET /api/{{resourceName | lowercase}}s - GET /api/{{resourceName | lowercase}}s/:id - PUT /api/{{resourceName | lowercase}}s/:id - DELETE /api/{{resourceName | lowercase}}s/:id ## Requirements {{#if includeAuth}} - Authentication required - Role-based access control {{/if}} - Input validation - Error handling - Tests (90%+ coverage) - API documentation labels: - "feature" - "api" - "{{resourceName | lowercase}}" priority: "{{priority}}" # Subtasks subtasks: - title: "Design {{resourceName}} data model" description: "Create database schema and types" labels: ["database", "model"] - title: "Implement CRUD operations" description: "Create repository layer" labels: ["backend", "repository"] - title: "Create API endpoints" description: "Implement REST endpoints" labels: ["api", "endpoints"] depends_on: ["database"] - title: "Add validation" description: "Input validation for all endpoints" labels: ["validation"] - title: "Write tests" description: "Integration and unit tests" labels: ["testing"] agent: "test-writer" depends_on: ["endpoints"] - title: "Generate documentation" description: "API docs with OpenAPI" labels: ["documentation"] agent: "docs-writer" ``` *** ## Using Templates ### CLI ```bash theme={null} # Use built-in template forge task create --template auth # Use custom template forge task create --template .forge/templates/my-template.yaml \ --var resourceName=Product \ --var includeAuth=true # List available templates forge template list # View template details forge template show auth ``` ### Via API ```typescript theme={null} import { ForgeClient } from '@automagik/forge-sdk'; const forge = new ForgeClient(); // Create from template const task = await forge.tasks.createFromTemplate({ template: 'crud', variables: { resourceName: 'Product', includeAuth: true }, projectId: 'proj_abc123' }); ``` *** ## Template Variables ### Variable Types ```yaml theme={null} variables: # String - name: "componentName" type: "string" required: true # Boolean - name: "includeTests" type: "boolean" default: true # Choice - name: "framework" type: "choice" options: ["react", "vue", "angular"] default: "react" # Number - name: "timeout" type: "number" default: 5000 min: 1000 max: 60000 # Array - name: "features" type: "array" items: "string" default: ["auth", "profile"] ``` ### Template Filters ```yaml theme={null} task: title: "{{name | capitalize}}" description: "{{name | lowercase | pluralize}}" # Available filters: # - capitalize: "user" → "User" # - lowercase: "User" → "user" # - uppercase: "user" → "USER" # - pluralize: "user" → "users" # - singularize: "users" → "user" # - kebabcase: "UserProfile" → "user-profile" # - snakecase: "UserProfile" → "user_profile" # - camelcase: "user-profile" → "userProfile" ``` *** ## Real-World Templates ### Full-Stack Feature Template ```yaml theme={null} name: "Full-Stack Feature" description: "Complete feature with frontend and backend" variables: - name: "featureName" type: "string" required: true task: title: "Implement {{featureName}} feature" subtasks: # Backend - title: "Design {{featureName}} API" description: "Design RESTful API endpoints" labels: ["backend", "api", "design"] llm: "claude" - title: "Implement {{featureName}} backend" description: "Create API endpoints and business logic" labels: ["backend", "implementation"] depends_on: ["api-design"] - title: "Add backend tests" description: "Unit and integration tests" labels: ["backend", "testing"] agent: "test-writer" depends_on: ["backend"] # Frontend - title: "Design {{featureName}} UI" description: "Create UI mockups and component structure" labels: ["frontend", "ui", "design"] llm: "cursor" - title: "Implement {{featureName}} UI" description: "Build React components" labels: ["frontend", "implementation"] llm: "cursor" depends_on: ["ui-design", "backend"] - title: "Add frontend tests" description: "Component and E2E tests" labels: ["frontend", "testing"] agent: "test-writer" depends_on: ["ui"] # Integration - title: "Integration testing" description: "End-to-end integration tests" labels: ["integration", "testing"] depends_on: ["backend-tests", "frontend-tests"] - title: "Documentation" description: "User and developer docs" labels: ["documentation"] agent: "docs-writer" depends_on: ["integration"] ``` ### Microservice Template ```yaml theme={null} name: "Microservice" description: "New microservice with full setup" variables: - name: "serviceName" type: "string" required: true - name: "language" type: "choice" options: ["typescript", "python", "go"] default: "typescript" task: title: "Create {{serviceName}} microservice" subtasks: - title: "Project setup" description: | Initialize {{language}} project with: - Package manager setup - TypeScript/linting config - Docker setup - CI/CD pipeline - title: "Service implementation" description: "Core service logic and API" - title: "Database integration" description: "Database schema and migrations" agent: "database-expert" - title: "Authentication" description: "JWT validation and authorization" agent: "security-expert" - title: "Observability" description: | Add monitoring and logging: - Structured logging - Metrics (Prometheus) - Tracing (Jaeger) - Health checks - title: "Testing" description: "Unit, integration, and contract tests" agent: "test-writer" - title: "Documentation" description: | Complete documentation: - API documentation - Deployment guide - Runbook agent: "docs-writer" ``` *** ## Template Marketplace ### Sharing Templates ```bash theme={null} # Publish template forge template publish .forge/templates/my-template.yaml # Install from marketplace forge template install auth-advanced # Search templates forge template search "authentication" ``` ### Community Templates Browse templates at: [https://templates.forge.automag.ik](https://templates.forge.automag.ik) Categories: * **Authentication**: OAuth, JWT, SAML * **CRUD Operations**: REST, GraphQL * **Frontend Components**: React, Vue, Angular * **Microservices**: API Gateway, Service Mesh * **Infrastructure**: Terraform, Kubernetes * **Testing**: Unit, E2E, Performance *** ## Best Practices One template = one purpose **Good**: "JWT Authentication" **Bad**: "Complete application" ```yaml theme={null} # Essential variables only variables: - name: "resourceName" # Yes - name: "indentSize" # No (too specific) ``` ```yaml theme={null} description: | This template creates a REST API with: - CRUD endpoints - Validation - Tests Best for: Resource management ``` ```yaml theme={null} version: "2.1.0" changelog: - "2.1.0: Added pagination support" - "2.0.0: Breaking: Changed to TypeScript" ``` *** ## Advanced Features ### Conditional Subtasks ```yaml theme={null} subtasks: - title: "Add authentication" condition: "{{includeAuth}}" - title: "Setup Redis cache" condition: "{{caching === 'redis'}}" ``` ### Dynamic Dependencies ```yaml theme={null} subtasks: - id: "frontend" title: "Build frontend" - id: "backend" title: "Build backend" - id: "integration" title: "Integration tests" depends_on: - "{{frontend}}" - "{{backend}}" ``` ### Template Inheritance ```yaml theme={null} extends: "base-api-template" # Override specific parts task: description: "Custom description" # Add extra subtasks subtasks: - title: "Custom step" description: "Team-specific requirement" ``` *** ## Troubleshooting **Error**: "Template 'my-template' not found" **Solutions**: * Check template path is correct * List available: `forge template list` * Verify template file exists * Check template syntax: `forge template validate my-template.yaml` **Error**: "Required variable 'resourceName' not provided" **Solutions**: * Provide variable: `--var resourceName=User` * Check variable names match template * Use quotes for multi-word values: `--var name="User Profile"` **Error**: "Template parse error" **Solutions**: * Validate YAML: `forge template validate` * Check indentation (use spaces, not tabs) * Verify variable syntax: `{{varName}}` * Check filter syntax: `{{var | filter}}` *** ## Next Steps Combine templates with agents Complete development workflows Learn task creation basics Browse community templates # Webhooks & Events Source: https://docs.namastex.ai/forge/advanced/webhooks-events Automate workflows with webhooks and event listeners ## Overview Webhooks allow external systems to react to Forge events in real-time. Trigger CI/CD pipelines, send notifications, update project management tools, or run custom automation. **Real-time integration**: Get notified instantly when tasks complete, attempts fail, or processes finish. *** ## Available Events ### Task Events | Event | When Triggered | Payload | | --------------------- | --------------------------- | ---------------------------- | | `task.created` | New task created | Task object | | `task.updated` | Task properties changed | Task object + changes | | `task.status_changed` | Task status changes | Task object + old/new status | | `task.completed` | Task successfully completed | Task object + result | | `task.failed` | Task execution failed | Task object + error | | `task.deleted` | Task removed | Task ID | ### Attempt Events | Event | When Triggered | Payload | | ------------------- | ----------------------------- | --------------------------- | | `attempt.created` | New attempt created | Attempt object | | `attempt.started` | Attempt execution begins | Attempt object | | `attempt.progress` | Progress update (every 10%) | Attempt object + progress | | `attempt.completed` | Attempt finished successfully | Attempt object + result | | `attempt.failed` | Attempt execution failed | Attempt object + error | | `attempt.cancelled` | Attempt cancelled by user | Attempt object | | `attempt.merged` | Attempt merged to main | Attempt object + commit SHA | ### Process Events | Event | When Triggered | Payload | | ------------------- | ------------------------ | ------------------------ | | `process.started` | Process begins execution | Process object | | `process.progress` | Progress update | Process object + metrics | | `process.completed` | Process finished | Process object + result | | `process.failed` | Process failed | Process object + error | | `process.cancelled` | Process terminated | Process object | *** ## Creating Webhooks ### Via API ```bash theme={null} curl -X POST http://localhost:8887/api/webhooks \ -H "Content-Type: application/json" \ -d '{ "url": "https://your-server.com/webhook", "events": ["task.completed", "attempt.failed"], "secret": "your-webhook-secret" }' ``` ### Via SDK ```typescript theme={null} import { ForgeClient } from '@automagik/forge-sdk'; const forge = new ForgeClient(); const webhook = await forge.webhooks.create({ url: 'https://your-server.com/webhook', events: ['task.completed', 'attempt.failed'], secret: 'your-webhook-secret', active: true }); ``` *** ## Webhook Payload ### Structure ```json theme={null} { "id": "evt_abc123", "event": "task.completed", "timestamp": "2024-01-15T10:30:00Z", "data": { "taskId": "task_xyz789", "title": "Add user authentication", "status": "completed", "completedAt": "2024-01-15T10:30:00Z", "duration": 900000, "cost": 0.23, "attempt": { "id": "attempt_abc123", "llm": "claude", "filesChanged": 8 } }, "signature": "sha256=abc123def456..." } ``` ### Signature Verification Verify webhook authenticity: ```typescript theme={null} import crypto from 'crypto'; function verifyWebhookSignature( payload: string, signature: string, secret: string ): boolean { const expectedSignature = crypto .createHmac('sha256', secret) .update(payload) .digest('hex'); return `sha256=${expectedSignature}` === signature; } // Usage in Express app.post('/webhook', (req, res) => { const signature = req.headers['x-forge-signature']; const payload = JSON.stringify(req.body); if (!verifyWebhookSignature(payload, signature, webhookSecret)) { return res.status(401).send('Invalid signature'); } // Process webhook handleForgeWebhook(req.body); res.sendStatus(200); }); ``` *** ## Use Cases ### Deploy on Task Completion ```typescript theme={null} // webhook-handler.ts export async function handleForgeWebhook(event: WebhookEvent) { if (event.event === 'task.completed') { // Trigger deployment await deployToProduction({ taskId: event.data.taskId, commit: event.data.commitSha }); // Send notification await sendSlackMessage({ channel: '#deployments', message: `✅ Task ${event.data.title} deployed to production!` }); } } ``` ### CI/CD Integration ```typescript theme={null} export async function handleForgeWebhook(event: WebhookEvent) { if (event.event === 'attempt.merged') { // Trigger GitHub Actions workflow await triggerGitHubAction({ workflow: 'test-and-deploy.yml', ref: 'main', inputs: { taskId: event.data.taskId, commitSha: event.data.commitSha } }); } } ``` ### Notification System ```typescript theme={null} export async function handleForgeWebhook(event: WebhookEvent) { const notifications = { 'task.completed': () => notifySuccess(event.data), 'task.failed': () => notifyFailure(event.data), 'attempt.completed': () => notifyAttemptDone(event.data) }; const handler = notifications[event.event]; if (handler) { await handler(); } } async function notifySuccess(data: any) { await sendEmail({ to: 'team@company.com', subject: `✅ Task Complete: ${data.title}`, body: `Task ${data.title} completed successfully!` }); await sendSlack({ channel: '#engineering', message: `:white_check_mark: Task ${data.title} completed in ${data.duration}ms` }); } ``` ### Project Management Integration ```typescript theme={null} export async function handleForgeWebhook(event: WebhookEvent) { if (event.event === 'task.completed') { // Update Jira ticket await updateJiraTicket({ ticketId: event.data.metadata?.jiraId, status: 'Done', comment: `Completed via Forge: ${event.data.attempt.id}` }); // Update Linear issue await updateLinearIssue({ issueId: event.data.metadata?.linearId, state: 'Done' }); } } ``` *** ## Event Listeners ### In-Process Listeners For running logic in the same process as Forge: ```typescript theme={null} import { ForgeClient } from '@automagik/forge-sdk'; const forge = new ForgeClient(); // Listen to events forge.on('task.completed', async (task) => { console.log(`Task ${task.title} completed!`); // Run custom logic await runCustomLogic(task); }); forge.on('attempt.failed', async (attempt) => { console.error(`Attempt ${attempt.id} failed:`, attempt.error); // Alert team await alertTeam(attempt); }); ``` ### Event Filtering ```typescript theme={null} // Only listen to high-priority tasks forge.on('task.completed', async (task) => { if (task.priority === 'high' || task.priority === 'critical') { await alertManagement(task); } }); // Only specific projects forge.on('task.created', async (task) => { if (task.projectId === 'proj_production') { await auditLog(task); } }); ``` *** ## Retry Logic ### Automatic Retries Forge automatically retries failed webhook deliveries: ``` Attempt 1: Immediate Attempt 2: 1 second later Attempt 3: 5 seconds later Attempt 4: 30 seconds later Attempt 5: 1 minute later ``` ### Manual Retry ```typescript theme={null} // Via API await forge.webhooks.retry('webhook_123', 'evt_abc123'); // Get failed deliveries const failed = await forge.webhooks.getFailedDeliveries('webhook_123'); for (const delivery of failed) { await forge.webhooks.retry('webhook_123', delivery.eventId); } ``` *** ## Webhook Management ### List Webhooks ```typescript theme={null} const webhooks = await forge.webhooks.list(); for (const webhook of webhooks) { console.log(`${webhook.url}: ${webhook.events.join(', ')}`); } ``` ### Update Webhook ```typescript theme={null} await forge.webhooks.update('webhook_123', { events: ['task.completed', 'task.failed', 'attempt.merged'], active: true }); ``` ### Delete Webhook ```typescript theme={null} await forge.webhooks.delete('webhook_123'); ``` ### Test Webhook ```typescript theme={null} // Send test event await forge.webhooks.test('webhook_123', { event: 'task.completed', data: { taskId: 'test_task', title: 'Test Task' } }); ``` *** ## Webhook Endpoints ### Express Example ```typescript theme={null} import express from 'express'; import { verifyWebhookSignature } from './utils'; const app = express(); app.post('/forge-webhook', express.json(), async (req, res) => { // Verify signature const signature = req.headers['x-forge-signature'] as string; const payload = JSON.stringify(req.body); if (!verifyWebhookSignature(payload, signature, process.env.WEBHOOK_SECRET!)) { return res.status(401).json({ error: 'Invalid signature' }); } // Process event try { await handleWebhook(req.body); res.sendStatus(200); } catch (error) { console.error('Webhook processing failed:', error); res.status(500).json({ error: 'Processing failed' }); } }); async function handleWebhook(event: WebhookEvent) { const handlers = { 'task.completed': handleTaskCompleted, 'task.failed': handleTaskFailed, 'attempt.merged': handleAttemptMerged }; const handler = handlers[event.event]; if (handler) { await handler(event.data); } } ``` ### Next.js API Route ```typescript theme={null} // pages/api/forge-webhook.ts import type { NextApiRequest, NextApiResponse } from 'next'; import { verifyWebhookSignature } from '@/lib/utils'; export default async function handler( req: NextApiRequest, res: NextApiResponse ) { if (req.method !== 'POST') { return res.status(405).json({ error: 'Method not allowed' }); } // Verify signature const signature = req.headers['x-forge-signature'] as string; const payload = JSON.stringify(req.body); if (!verifyWebhookSignature(payload, signature, process.env.WEBHOOK_SECRET!)) { return res.status(401).json({ error: 'Invalid signature' }); } // Process webhook await handleForgeWebhook(req.body); res.status(200).json({ received: true }); } ``` *** ## Best Practices ```typescript theme={null} if (!verifySignature(payload, signature, secret)) { return res.status(401).send('Invalid'); } ``` Prevents unauthorized webhooks ```typescript theme={null} // Good ✅ res.sendStatus(200); processWebhookAsync(event); // Bad ❌ await longRunningTask(); res.sendStatus(200); ``` Respond within 5 seconds ```typescript theme={null} const processedEvents = new Set(); if (processedEvents.has(event.id)) { return; // Already processed } await processEvent(event); processedEvents.add(event.id); ``` Events may be delivered multiple times ```typescript theme={null} console.log('Webhook received:', { event: event.event, id: event.id, timestamp: event.timestamp }); try { await process(event); console.log('Processed successfully'); } catch (error) { console.error('Processing failed:', error); } ``` Essential for debugging *** ## Troubleshooting **Checklist**: * Is webhook URL publicly accessible? * Is firewall allowing incoming requests? * Is webhook active? (`active: true`) * Check Forge logs: `forge logs --filter webhooks` **Causes**: * Wrong secret * Payload modified (middleware parsing) * Incorrect signature algorithm **Solution**: ```typescript theme={null} // Use raw body app.use(express.json({ verify: (req, res, buf) => { req.rawBody = buf.toString(); } })); // Verify with raw body verifySignature(req.rawBody, signature, secret); ``` **Check**: ```typescript theme={null} const deliveries = await forge.webhooks.getDeliveries('webhook_123', { status: 'failed' }); for (const delivery of deliveries) { console.log(delivery.error); } ``` **Common issues**: * Timeout (endpoint too slow) * 500 errors (server crash) * SSL certificate errors *** ## Next Steps Trigger custom executors via webhooks Complete automation workflows Webhook API documentation # Claude Code Source: https://docs.namastex.ai/forge/agents/claude-code Setup and use Anthropic's Claude with Forge ## Overview Claude Code by Anthropic is one of the most powerful AI coding assistants available. Known for exceptional reasoning, clear explanations, and robust code generation. **Claude 3.5 Sonnet** (released Oct 2024) is currently the best all-around model for coding tasks. *** ## Quick Start 1. Go to [console.anthropic.com](https://console.anthropic.com) 2. Sign up or log in 3. Navigate to **API Keys** 4. Click **Create Key** 5. Copy your API key (starts with `sk-ant-`) Edit `.forge/config.json`: ```json theme={null} { "llms": { "claude": { "apiKey": "sk-ant-api03-...", "model": "claude-3-5-sonnet-20241022" } } } ``` ```bash theme={null} forge task create \ --title "Test Claude" \ --description "Print 'Hello from Claude!'" \ --llm claude ``` *** ## Available Models ### Claude 3.5 Family (Recommended) **Best all-around model for coding** * Context: 200K tokens * Speed: Fast * Cost: $3/MTok input, $15/MTok output * Best for: Most coding tasks ```json theme={null} { "llms": { "claude": { "model": "claude-3-5-sonnet-20241022" } } } ``` **Fastest and most cost-effective** * Context: 200K tokens * Speed: Very fast (3x faster than Sonnet) * Cost: $0.25/MTok input, $1.25/MTok output * Best for: Simple tasks, quick fixes ```json theme={null} { "llms": { "claude-haiku": { "apiKey": "sk-ant-...", "model": "claude-3-5-haiku-20241022" } } } ``` ### Claude 3 Family (Legacy) **Most powerful, most expensive** * Context: 200K tokens * Speed: Slower * Cost: $15/MTok input, $75/MTok output * Best for: Critical architecture decisions Opus is 5x more expensive than Sonnet. Use sparingly! *** ## Model Comparison | Model | Speed | Quality | Cost | Best For | | -------------- | ----- | ------- | ---------- | ------------------------ | | **3.5 Sonnet** | ⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ | \$\$\$ | Most tasks (recommended) | | **3.5 Haiku** | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐ | \$ | Quick iterations | | **3 Opus** | ⭐⭐⭐ | ⭐⭐⭐⭐⭐ | \$\$\$\$\$ | Critical work only | *** ## Configuration Options ### Basic Configuration ```json theme={null} { "llms": { "claude": { "apiKey": "sk-ant-api03-...", "model": "claude-3-5-sonnet-20241022" } } } ``` ### Advanced Configuration ```json theme={null} { "llms": { "claude": { "apiKey": "sk-ant-api03-...", "model": "claude-3-5-sonnet-20241022", "maxTokens": 8192, "temperature": 0.7, "timeout": 60000, "retries": 3, "baseUrl": "https://api.anthropic.com" } } } ``` Maximum tokens in response * Min: 1 * Max: 8192 * Higher = longer responses, more cost Randomness of responses (0-1) * 0 = Deterministic, consistent * 1 = Creative, varied * 0.7 = Good balance Request timeout in milliseconds Number of retry attempts on failure *** ## Claude's Strengths ### Complex Reasoning Claude excels at multi-step logic: ```bash theme={null} forge task create \ --title "Design authentication system" \ --description " Design a complete auth system with: - JWT token management - Refresh token rotation - Role-based access control - Session management - Password reset flow Consider security, scalability, and maintainability. " \ --llm claude ``` Claude will: * Break down the problem systematically * Consider edge cases * Suggest architectural patterns * Explain trade-offs ### Code Refactoring Claude maintains code coherence during refactoring: ```bash theme={null} forge task create \ --title "Refactor user service to clean architecture" \ --description " Current: Monolithic UserService with 800 lines Goal: Clean architecture with: - Separate domain, application, infrastructure layers - Dependency injection - Unit testable components Preserve all existing functionality. " \ --llm claude ``` ### Security-Aware Claude considers security implications: ```bash theme={null} forge task create \ --title "Add file upload endpoint" \ --description " Allow users to upload profile pictures " \ --llm claude ``` Claude will add: * File type validation * Size limits * Malware scanning considerations * Secure file storage * Path traversal protection *** ## Claude's Weaknesses ### Can Be Verbose Claude sometimes over-explains: **Solution**: Use concise prompts: ```bash theme={null} forge task create \ --title "Add validation" \ --description "Add email validation. Keep it simple." \ --llm claude ``` ### May Over-Engineer For simple tasks, Claude might create complex solutions: **Solution**: Use Haiku for simple tasks: ```bash theme={null} forge task create \ --title "Add console.log for debugging" \ --llm claude-haiku ``` *** ## Pricing & Cost Management ### Current Pricing (as of Oct 2024) | Model | Input | Output | Example Cost | | ---------- | ----------- | ----------- | ----------------------------------- | | 3.5 Sonnet | \$3/MTok | \$15/MTok | 10K context + 2K response = \$0.06 | | 3.5 Haiku | \$0.25/MTok | \$1.25/MTok | 10K context + 2K response = \$0.005 | | 3 Opus | \$15/MTok | \$75/MTok | 10K context + 2K response = \$0.30 | ### Cost Optimization ```bash theme={null} # Start with Haiku forge task create "Add button" --llm claude-haiku # If not good enough, try Sonnet forge task fork 1 --llm claude ``` Saves money on simple tasks ```bash theme={null} # Don't send entire codebase forge task create "Fix login bug" \ --files "src/auth/login.ts" \ --llm claude ``` Less context = lower input costs ```json theme={null} { "llms": { "claude": { "maxTokens": 2048 // Instead of 8192 } } } ``` Shorter responses = lower output costs ```bash theme={null} # Check costs per task forge task cost 1 # Monthly summary forge cost summary --month january ``` Track and optimize spending *** ## Best Practices ### Task Descriptions Claude responds well to structured descriptions: **Good** ✅: ```bash theme={null} forge task create \ --title "Add caching" \ --description " # Goal Add Redis caching to product API # Requirements - Cache GET /api/products for 5 minutes - Invalidate on POST/PUT/DELETE - Handle Redis connection errors gracefully # Constraints - Don't cache user-specific data - Keep existing API contract unchanged " \ --llm claude ``` **Bad** ❌: ```bash theme={null} forge task create \ --title "make it faster" \ --description "add cache or something" \ --llm claude ``` ### Using Multiple Claude Models ```bash theme={null} # Quick exploration with Haiku forge task create "Add dark mode" --llm claude-haiku # Refined implementation with Sonnet forge task fork 1 --llm claude # Critical review with Opus forge task fork 1 --llm claude-opus ``` *** ## Integration with Forge ### MCP Support Claude Code works seamlessly with Forge's MCP server: ```json theme={null} // In Claude Code settings { "mcpServers": { "automagik-forge": { "command": "npx", "args": ["automagik-forge", "--mcp"], "env": { "PROJECT_ID": "your-project-id" } } } } ``` Now you can: ``` You: "Create a task to add user authentication" Claude Code: [Uses MCP to create task in Forge] ``` ### Specialized Profiles Create Claude variants for specific tasks: ```json theme={null} { "llms": { "claude": { "model": "claude-3-5-sonnet-20241022" }, "claude-security": { "model": "claude-3-5-sonnet-20241022", "systemPrompt": "You are a security expert. Always consider security implications..." }, "claude-tester": { "model": "claude-3-5-sonnet-20241022", "systemPrompt": "You are a testing expert. Write comprehensive tests..." } } } ``` *** ## Troubleshooting **Error**: "Invalid API key" **Solutions**: * Verify API key is correct (starts with `sk-ant-api03-`) * Check for extra spaces or quotes * Ensure key hasn't been rotated * Generate new key from console.anthropic.com **Error**: "Rate limit exceeded" **Solutions**: * Wait a few minutes * Reduce concurrent tasks * Upgrade Anthropic plan for higher limits * Use exponential backoff: ```json theme={null} { "llms": { "claude": { "retries": 5, "retryDelay": 1000 } } } ``` **Issue**: Claude taking too long **Solutions**: * Use Haiku instead of Sonnet * Reduce maxTokens * Simplify task description * Check network latency **Error**: "Prompt is too long" **Solutions**: * Reduce context sent to Claude * Don't include entire codebase * Use `--files` to limit scope * Split into smaller tasks **Issue**: Different results each time **Normal behavior!** AI is non-deterministic. **For consistency**: ```json theme={null} { "llms": { "claude": { "temperature": 0 } } } ``` *** ## Rate Limits ### Anthropic API Limits | Tier | RPM | TPM | TPD | | ------------------ | ------ | ------ | ------ | | **Free** | 5 | 10K | 100K | | **Build (Tier 1)** | 50 | 40K | 1M | | **Scale (Tier 2)** | 1000 | 80K | 2.5M | | **Enterprise** | Custom | Custom | Custom | RPM = Requests per minute TPM = Tokens per minute TPD = Tokens per day Check your tier: [console.anthropic.com/settings/limits](https://console.anthropic.com/settings/limits) *** ## Advanced Features ### Streaming Responses Watch Claude's output in real-time: ```bash theme={null} forge task start 1 --llm claude --stream ``` ### Vision Support Claude can analyze images: ```bash theme={null} forge task create \ --title "Implement this design" \ --attach mockup.png \ --llm claude ``` ### Extended Thinking For complex problems, enable extended thinking: ```json theme={null} { "llms": { "claude": { "thinkingTokens": 10000 } } } ``` *** ## Comparison with Other Agents | Feature | Claude 3.5 | GPT-4 | Gemini Pro | | ------------ | ---------- | -------- | ---------- | | Context | 200K | 128K | 2M | | Reasoning | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐ | ⭐⭐⭐ | | Speed | ⭐⭐⭐⭐ | ⭐⭐⭐ | ⭐⭐⭐⭐⭐ | | Cost | \$\$\$ | \$\$\$\$ | \$\$ | | Code Quality | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐ | ⭐⭐⭐⭐ | **Claude wins**: Complex reasoning, architecture, security **GPT-4 wins**: Consistency, documentation **Gemini wins**: Speed, cost, context window *** ## Real-World Examples ### Example 1: API Refactoring ```bash theme={null} forge task create \ --title "Refactor REST API to GraphQL" \ --description " Current: 15 REST endpoints in src/api/ Goal: Single GraphQL endpoint with: - Schema matching REST capabilities - Resolvers for all queries/mutations - DataLoader for N+1 prevention - Maintain backward compatibility via REST wrapper " \ --llm claude ``` **Result**: Claude created comprehensive GraphQL schema, resolvers, and maintained REST compatibility. ### Example 2: Security Audit ```bash theme={null} forge task create \ --title "Security audit of payment processing" \ --description " Review src/payment/ for security issues: - Input validation - SQL injection - XSS vulnerabilities - Sensitive data exposure - Rate limiting " \ --llm claude ``` **Result**: Claude identified 7 security issues with detailed explanations and fixes. *** ## Next Steps Create your first task with Claude Compare with other AI agents Create Claude variants for specific tasks Optimize your Claude spending # Cursor CLI Source: https://docs.namastex.ai/forge/agents/cursor-cli Setup and use Cursor's command-line agent with Forge ## Overview Cursor CLI is the command-line interface for Cursor's AI coding assistant. Known for excellent UI/UX intuition and fast iteration cycles, perfect for frontend development. **Note**: Cursor CLI is separate from the Cursor IDE. You can use the CLI without using the IDE! *** ## Quick Start ```bash theme={null} npm install -g @cursor/cli ``` ```bash theme={null} cursor auth login ``` Opens browser for authentication with your Cursor account Edit `.forge/config.json`: ```json theme={null} { "llms": { "cursor": { "enabled": true, "workingDirectory": "." } } } ``` ```bash theme={null} forge task create \ --title "Test Cursor" \ --description "Create a React button component" \ --llm cursor ``` *** ## Configuration ### Basic Setup ```json theme={null} { "llms": { "cursor": { "enabled": true, "workingDirectory": "." } } } ``` ### Advanced Configuration ```json theme={null} { "llms": { "cursor": { "enabled": true, "workingDirectory": ".", "model": "claude-3.5-sonnet", // Model via your Cursor subscription "timeout": 60000, "context": { "includeOpenFiles": true, "maxFiles": 10 } } } } ``` Which model to use through Cursor Options depend on your Cursor subscription: * `claude-3.5-sonnet` (recommended) * `gpt-4-turbo` * `gpt-3.5-turbo` Base directory for Cursor operations *** ## Cursor's Strengths ### UI/UX Intuition Cursor excels at frontend work: ```bash theme={null} forge task create \ --title "Create user profile card" \ --description " Build a user profile card component with: - Avatar image - Name and bio - Social links - Follow button Make it responsive and accessible. " \ --llm cursor ``` **Result**: Cursor creates beautiful, accessible UI with proper ARIA labels, responsive design, and smooth animations. ### Rapid Iteration Fast feedback loops: ```bash theme={null} # Initial version forge task create "Add dark mode toggle" --llm cursor # Quick iteration forge task fork 1 --llm cursor \ --description "Make it smoother with animation" # Another iteration forge task fork 1 --llm cursor \ --description "Add system preference detection" ``` ### Context Awareness Cursor understands your project structure: ```bash theme={null} forge task create \ --title "Add new API endpoint" \ --description "Create /api/users endpoint following existing patterns" \ --llm cursor ``` Cursor will: * Match your existing code style * Follow your project's patterns * Use the same libraries and frameworks * Maintain consistency *** ## Cursor's Weaknesses ### Less Depth on Algorithms For complex algorithmic problems, use Claude or GPT-4: ```bash theme={null} # Better with Claude forge task create \ --title "Implement optimal pathfinding algorithm" \ --llm claude # Not cursor ``` ### Subscription Required Unlike API-based agents, Cursor requires an active subscription: | Plan | Cost | Features | | ------------ | ------------ | -------------------- | | **Free** | \$0/mo | Limited requests | | **Pro** | \$20/mo | 500 fast requests/mo | | **Business** | \$40/user/mo | Unlimited + priority | ### Tied to Cursor Ecosystem * Requires Cursor account * Uses Cursor's model selection * Can't switch models without subscription change *** ## Pricing Cursor uses a subscription model, not pay-per-token: ``` Cursor Pro ($20/month): ├── 500 fast premium requests ├── Unlimited slow requests ├── Claude 3.5 Sonnet access ├── GPT-4 access └── Priority support Forge integration = No additional cost! ``` Unlike Claude/GPT-4 where you pay per token, Cursor's flat rate can be more economical for heavy usage! *** ## Best Use Cases ### Frontend Development ```bash theme={null} forge task create \ --title "Build product listing page" \ --description " Grid layout with: - Product cards (image, title, price) - Filters (category, price range) - Sorting options - Pagination - Mobile responsive " \ --llm cursor ``` ### Component Creation ```bash theme={null} forge task create \ --title "Create reusable modal component" \ --description " Modal with: - Backdrop click to close - ESC key to close - Focus trap - Accessible (ARIA) - Smooth animations " \ --llm cursor ``` ### Styling & Polish ```bash theme={null} forge task create \ --title "Improve button hover states" \ --description " Add smooth transitions and better visual feedback to all buttons in src/components/ " \ --llm cursor ``` *** ## Integration with Forge ### Using in Tasks ```bash theme={null} # Basic usage forge task create "Add navigation bar" --llm cursor # With specific instructions forge task create \ --title "Refactor forms to use React Hook Form" \ --llm cursor \ --files "src/forms/**/*.tsx" # With design reference forge task create \ --title "Implement this design" \ --attach mockup.png \ --llm cursor ``` ### Combining with Other Agents Use Cursor for UI, Claude for logic: ```bash theme={null} # Step 1: Claude designs the API forge task create \ --title "Design GraphQL schema" \ --llm claude # Step 2: Cursor builds the UI forge task create \ --title "Build GraphQL query components" \ --llm cursor ``` *** ## Authentication ### Initial Setup ```bash theme={null} # Login via browser cursor auth login # Verify authentication cursor auth status # Output: # ✓ Logged in as user@example.com # ✓ Pro subscription active # ✓ 450/500 fast requests remaining ``` ### Checking Quota ```bash theme={null} # Check remaining requests cursor quota # Output: # Fast requests: 450/500 # Resets: Jan 20, 2024 ``` ### Re-authentication If authentication expires: ```bash theme={null} # Logout cursor auth logout # Login again cursor auth login ``` *** ## Troubleshooting **Error**: "Please log in with `cursor auth login`" **Solution**: ```bash theme={null} cursor auth logout cursor auth login ``` Follow browser prompt to authenticate **Error**: "Fast request quota exceeded" **Options**: 1. Wait for monthly reset 2. Use slow requests (automatic fallback) 3. Upgrade to Business plan 4. Use different agent: ```bash theme={null} forge task fork 1 --llm claude ``` **Error**: "cursor: command not found" **Solution**: ```bash theme={null} # Reinstall npm install -g @cursor/cli # Verify installation which cursor # Check version cursor --version ``` **Issue**: Cursor taking too long **Causes**: * Using slow requests (quota exceeded) * Large context window * Network latency **Solutions**: * Check quota: `cursor quota` * Reduce context: use `--files` to limit scope * Wait for quota reset *** ## Best Practices Cursor shines on UI/UX work: * Component creation * Styling and polish * Responsive design * Accessibility Not ideal for: Algorithms, backend logic Cursor works well with mockups: ```bash theme={null} forge task create \ --title "Build login page" \ --attach design.png \ --llm cursor ``` Visual context improves results Check usage regularly: ```bash theme={null} cursor quota ``` Plan accordingly for quota limits Use Cursor's speed advantage: ```bash theme={null} # Try, iterate, refine forge task create "Add button" --llm cursor forge task fork 1 --llm cursor \ --description "Add loading state" forge task fork 1 --llm cursor \ --description "Add error state" ``` *** ## Cursor vs Other Agents | Feature | Cursor | Claude | Gemini | GPT-4 | | ----------- | ------------- | ----------- | --------- | ----------- | | **UI/UX** | ⭐⭐⭐⭐⭐ | ⭐⭐⭐ | ⭐⭐⭐ | ⭐⭐⭐ | | **Backend** | ⭐⭐⭐ | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐ | ⭐⭐⭐⭐ | | **Speed** | ⭐⭐⭐⭐ | ⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ | ⭐⭐⭐ | | **Cost** | Subscription | Per-token | Free/Paid | Per-token | | **Context** | Project-aware | 200K tokens | 2M tokens | 128K tokens | **Choose Cursor for**: Frontend, UI components, rapid iteration **Choose Claude for**: Architecture, complex logic, security **Choose Gemini for**: Speed, experimentation, cost **Choose GPT-4 for**: General purpose, documentation *** ## Real-World Examples ### Example 1: Dashboard Component ```bash theme={null} forge task create \ --title "Build analytics dashboard" \ --description " Create dashboard with: - 4 stat cards (users, revenue, sessions, conversion) - Line chart for trends - Table with recent activity - Responsive grid layout - Dark mode support Use Tailwind CSS and Recharts " \ --llm cursor ``` **Time**: \~3 minutes **Quality**: Professional, responsive, accessible **Cost**: 1 fast request ### Example 2: Form Component ```bash theme={null} forge task create \ --title "Create user profile edit form" \ --description " Form with: - Input fields: name, email, bio, avatar upload - Validation (email format, required fields) - Loading state during submission - Success/error messages - Accessible form controls " \ --llm cursor ``` **Time**: \~2 minutes **Quality**: Comprehensive validation, great UX **Cost**: 1 fast request *** ## Tips for Better Results ### Be Specific About Design ```bash theme={null} # Good ✅ forge task create \ --title "Add pricing cards" \ --description " 3 pricing tiers (Basic, Pro, Enterprise) - Vertical cards on mobile - Horizontal comparison on desktop - Highlight 'Pro' tier - Include feature lists - Use brand colors: #FF00FF, #00FFFF " \ --llm cursor # Bad ❌ forge task create \ --title "pricing page" \ --llm cursor ``` ### Reference Existing Patterns ```bash theme={null} forge task create \ --title "Add product modal" \ --description " Similar to existing CartModal in src/components/CartModal.tsx but for product details instead of cart " \ --llm cursor ``` ### Specify Frameworks ```bash theme={null} forge task create \ --title "Add animation to hero section" \ --description " Use Framer Motion for: - Fade in on mount - Stagger child elements - Smooth scroll parallax " \ --llm cursor ``` *** ## Next Steps Create your first Cursor task Compare with other AI agents Frontend development workflows View Cursor subscription plans # Gemini Source: https://docs.namastex.ai/forge/agents/gemini Setup and use Google's Gemini with Forge ## Overview Google's Gemini is a powerful, fast AI model with an incredibly generous **free tier** and massive context windows. Perfect for experimentation, rapid iteration, and cost-conscious development. **Gemini 2.0 Flash** offers the best speed-to-quality ratio and includes a free tier! *** ## Quick Start 1. Go to [aistudio.google.com](https://aistudio.google.com) 2. Click **"Get API Key"** 3. Create new project (or select existing) 4. Click **"Create API Key"** 5. Copy your API key (starts with `AIza`) Edit `.forge/config.json`: ```json theme={null} { "llms": { "gemini": { "apiKey": "AIza...", "model": "gemini-2.0-flash-exp" } } } ``` ```bash theme={null} forge task create \ --title "Test Gemini" \ --description "Print 'Hello from Gemini!'" \ --llm gemini ``` *** ## Available Models ### Gemini 2.0 (Latest - Recommended) **Fastest model with experimental features** * Context: 1M tokens * Speed: ⚡ Blazing fast * Cost: **FREE** (rate limited) * Best for: Quick iterations, experimentation ```json theme={null} { "llms": { "gemini": { "model": "gemini-2.0-flash-exp" } } } ``` This is the recommended model for most tasks! ### Gemini 1.5 (Stable) **Most capable, largest context** * Context: **2M tokens** (!) * Speed: Fast * Cost: $1.25/MTok input, $5/MTok output * Best for: Large codebase analysis ```json theme={null} { "llms": { "gemini": { "model": "gemini-1.5-pro" } } } ``` 2 million token context = \~50,000 lines of code! **Balanced speed and quality** * Context: 1M tokens * Speed: Very fast * Cost: $0.075/MTok input, $0.30/MTok output * Best for: Most coding tasks ```json theme={null} { "llms": { "gemini": { "model": "gemini-1.5-flash" } } } ``` *** ## Model Comparison | Model | Context | Speed | Cost | Best For | | ----------------- | ------- | ----- | ---- | ----------------------------- | | **2.0 Flash Exp** | 1M | ⭐⭐⭐⭐⭐ | FREE | Experimentation (recommended) | | **1.5 Pro** | 2M | ⭐⭐⭐⭐ | \$\$ | Large codebases | | **1.5 Flash** | 1M | ⭐⭐⭐⭐⭐ | \$ | General coding | *** ## Configuration ### Basic Setup ```json theme={null} { "llms": { "gemini": { "apiKey": "AIza...", "model": "gemini-2.0-flash-exp" } } } ``` ### Advanced Configuration ```json theme={null} { "llms": { "gemini": { "apiKey": "AIza...", "model": "gemini-2.0-flash-exp", "temperature": 0.7, "maxOutputTokens": 8192, "topP": 0.95, "topK": 40, "timeout": 30000, "retries": 3 } } } ``` Randomness (0-2) * 0 = Deterministic * 1 = Balanced (default) * 2 = Creative Maximum response length * Max: 8192 tokens Nucleus sampling parameter Top-K sampling parameter *** ## Gemini's Strengths ### Blazing Fast ⚡ Gemini is the **fastest** major coding agent: ```bash theme={null} # Benchmark: "Add user authentication" Claude Sonnet: 5m 22s GPT-4: 6m 01s Gemini Flash: 2m 15s ← Fastest! ``` Perfect for rapid iteration: ```bash theme={null} forge task create "Add button" --llm gemini # Done in seconds! forge task fork 1 --llm gemini \ --description "Change to primary color" # Done in seconds! ``` ### Free Tier! 💰 Unlike Claude/GPT-4, Gemini has a generous free tier: ``` Free Tier (No credit card required): ├── 15 requests per minute ├── 1,500 requests per day ├── 1M requests per month └── No expiration! Perfect for: - Learning and experimentation - Side projects - Prototyping - Testing ideas ``` Start every project with Gemini's free tier. Upgrade to paid models only when needed! ### Massive Context Windows Gemini 1.5 Pro: **2 million tokens** ```bash theme={null} # Analyze entire medium-sized codebase in one go forge task create \ --title "Find all API endpoints and document them" \ --files "src/**/*" \ --llm gemini-1.5-pro ``` Can fit: * \~50,000 lines of code * \~1.5 million words * Entire small-to-medium codebases ### Multimodal Gemini can process images: ```bash theme={null} forge task create \ --title "Implement this design" \ --attach mockup.png \ --llm gemini ``` *** ## Gemini's Weaknesses ### Less Sophisticated Reasoning For complex architecture, use Claude: ```bash theme={null} # Better with Claude forge task create \ --title "Design microservices architecture" \ --llm claude # Not gemini ``` ### May Miss Edge Cases Gemini optimizes for speed, sometimes at the cost of thoroughness: ```bash theme={null} # Good for initial implementation forge task create "Add login endpoint" --llm gemini # Then review with Claude forge task fork 1 --llm claude \ --description "Add comprehensive error handling and edge cases" ``` ### Shorter Explanations Gemini provides concise code, less explanation: **Gemini** ✅: ```typescript theme={null} // Concise, works export const validateEmail = (email: string) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email); ``` **Claude** 📝: ```typescript theme={null} /** * Validates email addresses according to RFC 5322 * @param email - Email string to validate * @returns true if valid, false otherwise * @example * validateEmail('user@example.com') // true * validateEmail('invalid') // false */ export const validateEmail = (email: string): boolean => { const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; return emailRegex.test(email); }; ``` *** ## Pricing ### Free Tier ``` Rate Limits: ├── 15 RPM (requests per minute) ├── 1,500 RPD (requests per day) └── 1M RPM (requests per month) Models included: ├── Gemini 2.0 Flash Exp ✅ ├── Gemini 1.5 Flash ✅ └── Gemini 1.5 Pro ✅ (limited) ``` ### Paid Tier ``` Pay-as-you-go: ├── Gemini 1.5 Flash │ ├── Input: $0.075/MTok │ └── Output: $0.30/MTok └── Gemini 1.5 Pro ├── Input: $1.25/MTok └── Output: $5/MTok Example cost: 10K input + 2K output with Flash = $0.0013 (vs Claude Sonnet: $0.06) ``` **20x cheaper** than Claude Sonnet, **50x cheaper** than GPT-4! *** ## Best Use Cases ### Rapid Prototyping ```bash theme={null} # Try ideas quickly with free tier forge task create "Add dark mode" --llm gemini forge task create "Add search" --llm gemini forge task create "Add filters" --llm gemini # All free, all fast! ``` ### Simple Features ```bash theme={null} forge task create \ --title "Add pagination to user list" \ --llm gemini ``` ### Bug Fixes ```bash theme={null} forge task create \ --title "Fix TypeError in login component" \ --description "Error: Cannot read property 'email' of undefined" \ --llm gemini ``` ### Large Codebase Analysis ```bash theme={null} # Only Gemini Pro can handle this much context forge task create \ --title "Find all TODO comments across codebase" \ --files "**/*.{ts,js,py}" \ --llm gemini-1.5-pro ``` *** ## Cost Optimization Strategy ### Start with Free Tier ```bash theme={null} # 1. Quick first pass with Gemini (free) forge task create "Add authentication" --llm gemini # 2. If good enough → done! # 3. If needs refinement → use Claude forge task fork 1 --llm claude \ --description "Add comprehensive security checks" ``` ### Use for Iteration ```bash theme={null} # Use free Gemini for rapid iteration forge task create "Add button" --llm gemini forge task fork 1 --llm gemini --description "Change color" forge task fork 1 --llm gemini --description "Add icon" # Final polish with Claude if needed forge task fork 1 --llm claude --description "Production-ready" ``` *** ## Integration with Forge ### Default Agent Set Gemini as default for cost savings: ```json theme={null} { "defaultLLM": "gemini", "llms": { "gemini": { "apiKey": "AIza...", "model": "gemini-2.0-flash-exp" } } } ``` ### Fallback Strategy Use Gemini first, fallback to Claude: ```yaml .forge/strategies.yaml theme={null} default: - try: gemini - if_fails: claude - if_complex: claude ``` *** ## Troubleshooting **Error**: "API key not valid" **Solutions**: * Verify API key from aistudio.google.com * Check key hasn't been deleted * Ensure no extra spaces * Generate new key if needed **Error**: "Resource exhausted" **You've hit free tier limits**: Options: 1. Wait for reset (15 RPM, 1500 RPD) 2. Switch to paid tier (add billing) 3. Use different agent temporarily: ```bash theme={null} forge task fork 1 --llm claude ``` **Issue**: Gemini gives brief responses **Solution**: Increase max output tokens ```json theme={null} { "llms": { "gemini": { "maxOutputTokens": 8192 } } } ``` **Issue**: Code works but misses edge cases **This is expected** - Gemini optimizes for speed **Solution**: Two-pass approach ```bash theme={null} # 1. Quick implementation (Gemini) forge task create "Add feature" --llm gemini # 2. Edge case handling (Claude) forge task fork 1 --llm claude \ --description "Add edge case handling" ``` *** ## Rate Limits ### Free Tier Limits | Metric | Limit | | -------- | ------------------------ | | **RPM** | 15 requests/minute | | **RPD** | 1,500 requests/day | | **RPMo** | 1,000,000 requests/month | ### Paid Tier Limits | Model | RPM | RPD | | --------- | ----- | ------ | | **Flash** | 2,000 | 10,000 | | **Pro** | 360 | 10,000 | Check limits: [ai.google.dev/pricing](https://ai.google.dev/pricing) *** ## Best Practices ```bash theme={null} # Start free forge task create "Add feature" --llm gemini # Upgrade only if needed forge task fork 1 --llm claude ``` Save money on simple tasks Gemini's speed enables rapid iteration: ```bash theme={null} # Try multiple approaches quickly forge task create "Layout A" --llm gemini & forge task create "Layout B" --llm gemini & forge task create "Layout C" --llm gemini & ``` All done in minutes, all free! Perfect for trying ideas: ```bash theme={null} forge task create "Try approach 1" --llm gemini forge task create "Try approach 2" --llm gemini forge task create "Try approach 3" --llm gemini # Pick best, refine with Claude forge task fork --llm claude ``` Use Pro for codebase-wide tasks: ```bash theme={null} forge task create \ --title "Refactor import paths" \ --files "src/**/*" \ --llm gemini-1.5-pro ``` 2M context = entire codebase *** ## Gemini vs Other Agents | Feature | Gemini | Claude | GPT-4 | Cursor | | ------------- | ------ | ------ | -------- | ------------ | | **Speed** | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐ | ⭐⭐⭐ | ⭐⭐⭐⭐ | | **Free Tier** | ✅ Yes | ❌ No | ❌ No | Limited | | **Context** | 2M | 200K | 128K | Variable | | **Quality** | ⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐ | ⭐⭐⭐⭐ | | **Cost** | \$ | \$\$\$ | \$\$\$\$ | Subscription | **Choose Gemini for**: Speed, cost, experimentation, large context **Choose Claude for**: Quality, reasoning, architecture **Choose GPT-4 for**: Consistency, documentation **Choose Cursor for**: UI/UX, rapid frontend work *** ## Real-World Examples ### Example 1: Quick Bug Fix (Free!) ```bash theme={null} forge task create \ --title "Fix login redirect bug" \ --description "After login, redirects to /undefined instead of /dashboard" \ --llm gemini # Time: 45 seconds # Cost: $0.00 # Result: Fixed! ``` ### Example 2: Rapid Prototyping (Free!) ```bash theme={null} # Try 5 different approaches for approach in A B C D E; do forge task create "Try design ${approach}" --llm gemini & done wait # Compare and pick winner forge task compare 1 2 3 4 5 # Total cost: $0.00 # Total time: ~3 minutes ``` *** ## Next Steps Create your first Gemini task (free!) Compare with other AI agents Maximize free tier usage Get your API key # Open Source Agents Source: https://docs.namastex.ai/forge/agents/open-source Run AI coding agents locally with OpenCode and Qwen ## Overview Run powerful AI coding agents **completely local** - no API keys, no cloud services, no data leaving your machine. Perfect for privacy-sensitive work, learning, or unlimited free usage. **Privacy First**: All code stays on your machine. No external API calls. *** ## Supported Models ### OpenCode **Open-source coding model** * **By**: Open-source community * **Size**: 15B parameters * **Context**: 16K tokens * **Requirements**: 16GB+ RAM, GPU recommended * **License**: Apache 2.0 Best for: General coding, privacy-sensitive work ### Qwen Code **Alibaba's open-source coder** * **By**: Alibaba DAMO Academy * **Size**: 7B, 14B, 32B parameters * **Context**: 32K tokens * **Requirements**: 8GB-64GB RAM depending on size * **License**: Apache 2.0 Best for: Cost-conscious development, competitive with commercial *** ## Quick Start with Ollama [Ollama](https://ollama.ai) makes running local models easy: ```bash theme={null} # macOS brew install ollama # Linux curl https://ollama.ai/install.sh | sh # Windows # Download from https://ollama.ai ``` ```bash theme={null} ollama serve ``` Runs on [http://localhost:11434](http://localhost:11434) ```bash theme={null} # OpenCode ollama pull opencode # Qwen Code (choose size) ollama pull qwen2.5-coder:7b # Small, fast ollama pull qwen2.5-coder:14b # Balanced ollama pull qwen2.5-coder:32b # Best quality ``` Edit `.forge/config.json`: ```json theme={null} { "llms": { "opencode": { "type": "ollama", "model": "opencode", "endpoint": "http://localhost:11434" }, "qwen": { "type": "ollama", "model": "qwen2.5-coder:32b", "endpoint": "http://localhost:11434" } } } ``` ```bash theme={null} forge task create \ --title "Test local model" \ --description "Print 'Hello from OpenCode!'" \ --llm opencode ``` *** ## Hardware Requirements ### Minimum Specs | Model | RAM | GPU | Storage | Speed | | ------------ | ---- | ----------- | ------- | ------ | | **Qwen 7B** | 8GB | Optional | 5GB | Good | | **Qwen 14B** | 16GB | Recommended | 10GB | Better | | **OpenCode** | 16GB | Recommended | 12GB | Good | | **Qwen 32B** | 32GB | Required | 25GB | Best | ### Recommended Setup For best experience: ``` CPU: Modern multi-core (8+ cores) RAM: 32GB+ GPU: NVIDIA RTX 3060+ (12GB VRAM) or Apple Silicon M1/M2/M3 Storage: SSD with 50GB+ free space ``` **Apple Silicon users**: Metal acceleration makes M1/M2/M3 excellent for local models! *** ## Configuration ### Basic Ollama Setup ```json theme={null} { "llms": { "opencode": { "type": "ollama", "model": "opencode", "endpoint": "http://localhost:11434" } } } ``` ### Advanced Configuration ```json theme={null} { "llms": { "qwen": { "type": "ollama", "model": "qwen2.5-coder:32b", "endpoint": "http://localhost:11434", "options": { "temperature": 0.7, "num_ctx": 32768, // Context window "num_predict": 2048, // Max output tokens "top_p": 0.9, "top_k": 40, "repeat_penalty": 1.1 }, "timeout": 120000 // 2 minutes } } } ``` ### GPU Acceleration Enable GPU support for faster inference: ```json theme={null} { "llms": { "qwen": { "type": "ollama", "model": "qwen2.5-coder:32b", "options": { "num_gpu": 1, // Number of GPUs "main_gpu": 0, // Primary GPU index "low_vram": false // Enable for under 8GB VRAM } } } } ``` *** ## Strengths of Local Models ### Complete Privacy * Code never leaves your machine * No API calls to external services * No telemetry or tracking * Perfect for sensitive codebases * GDPR compliant by design * No third-party data sharing * Full audit trail * Meets enterprise security requirements ### No Usage Limits ```bash theme={null} # Unlimited usage! forge task create "Task 1" --llm qwen forge task create "Task 2" --llm qwen forge task create "Task 3" --llm qwen # ... as many as you want # No rate limits # No token costs # No monthly fees ``` ### No Internet Required Work anywhere: * ✈️ On airplanes * 🏔️ Remote locations * 🔌 During outages * 🔒 Air-gapped environments *** ## Limitations ### Lower Quality Local models are less capable than cloud models: | Task Type | Local | Claude | GPT-4 | | ---------------- | ----- | ------ | ----- | | **Simple fixes** | ⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ | | **Architecture** | ⭐⭐ | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐ | | **Bug fixing** | ⭐⭐⭐ | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐ | | **Testing** | ⭐⭐⭐ | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ | ### Slower ```bash theme={null} # Speed comparison: "Add authentication" Gemini Flash: 2m 15s ⚡ Claude Sonnet: 5m 22s GPT-4 Turbo: 6m 01s Qwen 32B: 12m 30s (local) OpenCode: 15m 45s (local) ``` ### Hardware Intensive * Requires powerful machine * GPU strongly recommended * High RAM usage * Slower on CPU-only *** ## Best Use Cases ### Privacy-Sensitive Work ```bash theme={null} # Medical records processing forge task create \ --title "Process patient data" \ --files "data/patients/*.csv" \ --llm qwen # Stays local! ``` ### Learning & Experimentation ```bash theme={null} # Unlimited free usage for learning forge task create "Try approach 1" --llm opencode forge task create "Try approach 2" --llm opencode forge task create "Try approach 3" --llm opencode # ... no cost! ``` ### Air-Gapped Environments ```bash theme={null} # Government, military, high-security environments # No internet connection required forge task create "Classified work" --llm qwen ``` ### Cost Reduction ```bash theme={null} # After initial hardware investment # Zero ongoing costs forge task create "Feature 1" --llm qwen # $0 forge task create "Feature 2" --llm qwen # $0 forge task create "Feature 3" --llm qwen # $0 ``` *** ## Model Comparison ### OpenCode vs Qwen | Feature | OpenCode | Qwen 7B | Qwen 14B | Qwen 32B | | ------------ | -------- | ----------- | -------- | -------- | | **Quality** | ⭐⭐⭐ | ⭐⭐⭐ | ⭐⭐⭐⭐ | ⭐⭐⭐⭐ | | **Speed** | ⭐⭐ | ⭐⭐⭐⭐ | ⭐⭐⭐ | ⭐⭐ | | **RAM** | 16GB | 8GB | 16GB | 32GB | | **Best for** | General | Quick tasks | Balanced | Quality | ### Local vs Cloud | Feature | Local (Qwen 32B) | Claude Sonnet | Gemini Pro | | ----------- | -------------------------- | -------------------------- | ------------------------ | | **Privacy** | ⭐⭐⭐⭐⭐ | ⭐⭐ | ⭐⭐ | | **Quality** | ⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐ | | **Speed** | ⭐⭐ | ⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ | | **Cost** | \$\$\$ hardware, \$0 usage | \$0 hardware, \$\$\$ usage | \$0 hardware, \$\$ usage | *** ## Performance Optimization ### Use GPU ```bash theme={null} # Check GPU usage nvidia-smi # Or on Mac system_profiler SPDisplaysDataType ``` ### Adjust Context Window ```json theme={null} { "llms": { "qwen": { "options": { "num_ctx": 16384 // Reduce for speed } } } } ``` ### Use Smaller Models for Simple Tasks ```bash theme={null} # Simple task → Qwen 7B (fast) forge task create "Add comment" --llm qwen-7b # Complex task → Qwen 32B (quality) forge task create "Refactor architecture" --llm qwen-32b ``` *** ## Troubleshooting **Error**: "Connection refused to localhost:11434" **Solution**: ```bash theme={null} # Start Ollama ollama serve # Or as background service (Linux) systemctl start ollama # macOS (via brew services) brew services start ollama ``` **Error**: "Failed to allocate memory" **Solutions**: * Use smaller model (7B instead of 32B) * Close other applications * Enable low VRAM mode: ```json theme={null} { "llms": { "qwen": { "options": { "low_vram": true } } } } ``` * Upgrade RAM **Issue**: Model taking forever **Solutions**: * Enable GPU acceleration * Use smaller model * Reduce context window * Close background apps * Check CPU usage (should be high) **Error**: "Model 'qwen2.5-coder:32b' not found" **Solution**: ```bash theme={null} # Pull the model ollama pull qwen2.5-coder:32b # List available models ollama list # Check model size before pulling ollama show qwen2.5-coder:32b ``` *** ## Cost Analysis ### Hardware Investment ``` One-time costs: ├── Mid-range GPU (RTX 4060): $300 ├── Additional RAM (32GB): $100 └── SSD storage (1TB): $80 ──────────────────────────── Total: ~$480 Break-even vs Claude: $480 / $50/month = ~10 months of usage ``` ### Ongoing Costs ``` Electricity: ├── GPU power: ~200W ├── Running 8hrs/day └── Cost: ~$5-10/month vs Cloud APIs: ├── Claude: $50-200/month typical usage ├── GPT-4: $80-300/month └── Gemini: $0-50/month (free tier) ``` **Heavy users** (>\$100/month on APIs) break even quickly with local setup! *** ## Best Practices ```bash theme={null} # Proprietary code forge task create \ --title "Refactor proprietary algorithm" \ --llm qwen # Stays local ``` Begin with Qwen 7B: ```bash theme={null} ollama pull qwen2.5-coder:7b ``` Upgrade to 32B if needed ```bash theme={null} # Check resource usage htop nvidia-smi # GPU # Adjust if needed ``` ```bash theme={null} # Quick iteration: local forge task create "Try A" --llm qwen # Final polish: cloud forge task fork 1 --llm claude ``` Best of both worlds! *** ## Hybrid Strategy Combine local and cloud models: ### Strategy 1: Privacy Tiers ```bash theme={null} # Sensitive code → local forge task create \ --title "Process customer data" \ --llm qwen # Public code → cloud (faster, better) forge task create \ --title "Update README" \ --llm gemini ``` ### Strategy 2: Cost Optimization ```bash theme={null} # Experimentation → local (free) forge task create "Try approach A" --llm qwen forge task create "Try approach B" --llm qwen forge task create "Try approach C" --llm qwen # Production → cloud (quality) forge task fork --llm claude ``` ### Strategy 3: Network-Aware ```bash theme={null} # Offline → local if ping -c 1 8.8.8.8 >/dev/null 2>&1; then LLM=gemini # Online, use fast cloud else LLM=qwen # Offline, use local fi forge task create "Task" --llm $LLM ``` *** ## Real-World Example ### Setup for Privacy-First Development ```bash theme={null} # 1. Install Ollama brew install ollama # 2. Pull Qwen 32B (best quality) ollama pull qwen2.5-coder:32b # 3. Configure Forge cat > .forge/config.json < Get started with local models Compare with cloud agents Privacy-first development patterns Browse available models # OpenAI Codex Source: https://docs.namastex.ai/forge/agents/openai-codex Setup and use OpenAI's GPT models with Forge ## Overview OpenAI's GPT-4 and GPT-3.5 models are reliable, well-documented AI coding assistants. Known for consistency, strong general-purpose capabilities, and excellent documentation generation. **GPT-4 Turbo** offers the best balance of performance and cost for most coding tasks. *** ## Quick Start 1. Go to [platform.openai.com](https://platform.openai.com) 2. Sign up or log in 3. Navigate to **API Keys** 4. Click **Create new secret key** 5. Copy your API key (starts with `sk-`) OpenAI requires prepaid credits: 1. Go to **Billing** → **Add payment method** 2. Add credit card 3. Purchase credits (\$5+ recommended) Edit `.forge/config.json`: ```json theme={null} { "llms": { "openai": { "apiKey": "sk-...", "model": "gpt-4-turbo" } } } ``` ```bash theme={null} forge task create \ --title "Test GPT-4" \ --description "Print 'Hello from OpenAI!'" \ --llm openai ``` *** ## Available Models ### GPT-4 Family **Best overall GPT-4 model** * Context: 128K tokens * Speed: Fast * Cost: $10/MTok input, $30/MTok output * Best for: Complex coding tasks ```json theme={null} { "llms": { "openai": { "model": "gpt-4-turbo" } } } ``` **Original GPT-4 (legacy)** * Context: 8K tokens * Speed: Slower * Cost: $30/MTok input, $60/MTok output * Best for: Nothing (use Turbo instead) Use `gpt-4-turbo` instead - faster and cheaper! ### GPT-3.5 Family **Fast and affordable** * Context: 16K tokens * Speed: Very fast * Cost: $0.50/MTok input, $1.50/MTok output * Best for: Simple tasks, quick fixes ```json theme={null} { "llms": { "openai-cheap": { "apiKey": "sk-...", "model": "gpt-3.5-turbo" } } } ``` *** ## Model Comparison | Model | Context | Speed | Cost | Quality | | ----------------- | ------- | ----- | -------- | ------- | | **GPT-4 Turbo** | 128K | ⭐⭐⭐⭐ | \$\$\$ | ⭐⭐⭐⭐ | | **GPT-4** | 8K | ⭐⭐ | \$\$\$\$ | ⭐⭐⭐⭐ | | **GPT-3.5 Turbo** | 16K | ⭐⭐⭐⭐⭐ | \$ | ⭐⭐⭐ | **Recommendation**: Use GPT-4 Turbo for most tasks, GPT-3.5 Turbo for simple fixes. *** ## Configuration ### Basic Setup ```json theme={null} { "llms": { "openai": { "apiKey": "sk-...", "model": "gpt-4-turbo" } } } ``` ### Advanced Configuration ```json theme={null} { "llms": { "openai": { "apiKey": "sk-...", "model": "gpt-4-turbo", "organization": "org-...", // Optional "maxTokens": 4096, "temperature": 0.7, "topP": 1, "frequencyPenalty": 0, "presencePenalty": 0, "timeout": 60000, "retries": 3 } } } ``` Your OpenAI organization ID (for enterprise accounts) Maximum tokens in response (1-4096) Randomness (0-2) * 0 = Deterministic * 1 = Balanced * 2 = Creative *** ## OpenAI's Strengths ### Consistency GPT-4 produces reliable, consistent results: ```bash theme={null} # Same task multiple times = similar results forge task create "Add validation" --llm openai # More predictable than Claude/Gemini ``` ### General Purpose Good at everything, great at nothing: ```bash theme={null} # Works well for: - Backend APIs - Frontend components - Data processing - Testing - Documentation ``` ### Documentation Excellent at writing clear documentation: ```bash theme={null} forge task create \ --title "Document authentication flow" \ --description " Create comprehensive documentation for: - How JWT tokens work - Login/signup flow - Password reset process - Include code examples " \ --llm openai ``` **Result**: Clear, well-structured docs with examples. ### Large Ecosystem Most tools integrate with OpenAI: * Extensive docs * Large community * Many examples * Well-tested *** ## OpenAI's Weaknesses ### Expensive GPT-4 is one of the most expensive options: ``` Cost comparison (10K input + 2K output): - GPT-4 Turbo: $0.16 - Claude Sonnet: $0.06 (2.6x cheaper) - Gemini Flash: $0.00 (free!) ``` ### Not Exceptional Jack of all trades, master of none: * Claude better at reasoning * Gemini faster and cheaper * Cursor better at UI ### Requires Prepaid Credits Can't pay-as-you-go: * Must purchase credits upfront * Minimum \$5 * Credits expire (usually 1 year) *** ## Pricing ### Per-Token Costs | Model | Input | Output | Example | | ----------------- | ----------- | ----------- | ------------------------- | | **GPT-4 Turbo** | \$10/MTok | \$30/MTok | 10K in + 2K out = \$0.16 | | **GPT-4** | \$30/MTok | \$60/MTok | 10K in + 2K out = \$0.48 | | **GPT-3.5 Turbo** | \$0.50/MTok | \$1.50/MTok | 10K in + 2K out = \$0.008 | ### Prepaid Credits ``` Minimum purchase: $5 Recommended: $20-50 for hobby projects Credits expire after 1 year ``` *** ## Best Use Cases ### Documentation ```bash theme={null} forge task create \ --title "Write API documentation" \ --description " Document all endpoints in src/api/ Include: - Request/response examples - Error codes - Authentication requirements " \ --llm openai ``` ### General Coding ```bash theme={null} forge task create \ --title "Implement user CRUD endpoints" \ --llm openai ``` ### Testing ```bash theme={null} forge task create \ --title "Add unit tests for auth service" \ --description "Aim for 90%+ coverage" \ --llm openai ``` ### Consistency-Critical Tasks When you need predictable results: ```bash theme={null} forge task create \ --title "Generate migration scripts" \ --llm openai # Consistent output important ``` *** ## Integration with Forge ### Using in Tasks ```bash theme={null} # Basic usage forge task create "Add feature" --llm openai # Specify model forge task create "Quick fix" --llm openai-cheap # GPT-3.5 # With organization forge task create "Enterprise task" --llm openai \ --org org-your-org-id ``` ### Multiple OpenAI Configs Configure both GPT-4 and GPT-3.5: ```json theme={null} { "llms": { "openai": { "apiKey": "sk-...", "model": "gpt-4-turbo" }, "openai-cheap": { "apiKey": "sk-...", "model": "gpt-3.5-turbo" } } } ``` Use appropriately: ```bash theme={null} # Complex task → GPT-4 forge task create "Design system architecture" --llm openai # Simple task → GPT-3.5 forge task create "Add console.log" --llm openai-cheap ``` *** ## Cost Optimization ### Use GPT-3.5 for Simple Tasks ```bash theme={null} # Simple tasks (20x cheaper) forge task create "Fix typo" --llm openai-cheap forge task create "Add comment" --llm openai-cheap # Complex tasks forge task create "Refactor architecture" --llm openai ``` ### Reduce Context ```bash theme={null} # Send less context forge task create "Fix bug in login.ts" \ --files "src/auth/login.ts" \ # Only this file --llm openai ``` ### Lower Max Tokens ```json theme={null} { "llms": { "openai": { "maxTokens": 2048 // Instead of 4096 } } } ``` ### Monitor Spending ```bash theme={null} # Check costs forge cost summary --month january # Set budget alerts forge config set budget.monthly 50 # $50/month forge config set budget.alert true ``` *** ## Troubleshooting **Error**: "Incorrect API key provided" **Solutions**: * Verify API key from platform.openai.com * Check for extra spaces * Ensure key hasn't been deleted * Generate new key **Error**: "Rate limit reached" **Solutions**: * Wait a few seconds * Reduce concurrent requests * Upgrade tier (Tier 1 → Tier 2) * Use exponential backoff **Error**: "You exceeded your current quota" **Solutions**: * Add more credits: platform.openai.com/billing * Check billing dashboard * Verify payment method **Issue**: GPT-4 taking too long **Solutions**: * Use GPT-4 Turbo (not regular GPT-4) * Use GPT-3.5 for simple tasks * Reduce maxTokens * Check OpenAI status page **Error**: "This model's maximum context length is..." **Solutions**: * Use GPT-4 Turbo (128K context) * Reduce input context * Split task into smaller pieces *** ## Rate Limits ### By Tier | Tier | RPM | TPM | How to Reach | | ---------- | ----- | ---- | --------------------- | | **Free** | 3 | 40K | New account | | **Tier 1** | 500 | 30K | \$5+ paid | | **Tier 2** | 5000 | 450K | \$50+ paid + 7 days | | **Tier 3** | 10000 | 1M | \$1000+ paid + 7 days | RPM = Requests per minute TPM = Tokens per minute Check your tier: [platform.openai.com/account/limits](https://platform.openai.com/account/limits) *** ## Best Practices ```bash theme={null} # 20x cheaper! forge task create "Quick fix" --llm openai-cheap ``` Reserve GPT-4 for complex work ```bash theme={null} # Check OpenAI dashboard open https://platform.openai.com/usage # Track in Forge forge cost summary ``` On OpenAI dashboard: * Set hard limit (\$50/month) * Email alerts at 75%, 90% GPT-4 excels at docs: ```bash theme={null} forge task create "Document code" --llm openai ``` *** ## OpenAI vs Other Agents | Feature | OpenAI | Claude | Gemini | Cursor | | --------------- | -------- | ------ | ------ | ------------ | | **Quality** | ⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐ | ⭐⭐⭐⭐ | | **Cost** | \$\$\$\$ | \$\$\$ | \$ | Subscription | | **Speed** | ⭐⭐⭐ | ⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐ | | **Context** | 128K | 200K | 2M | Variable | | **Consistency** | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐ | ⭐⭐⭐ | ⭐⭐⭐⭐ | **Choose OpenAI for**: Documentation, consistency, general purpose **Choose Claude for**: Complex reasoning, architecture **Choose Gemini for**: Speed, cost, large context **Choose Cursor for**: UI/UX, frontend *** ## Real-World Examples ### Example 1: API Documentation ```bash theme={null} forge task create \ --title "Document REST API" \ --description " Create OpenAPI spec for all endpoints in src/api/ Include examples and error codes " \ --llm openai # Time: ~5 minutes # Cost: ~$0.25 # Quality: Excellent, comprehensive ``` ### Example 2: Test Generation ```bash theme={null} forge task create \ --title "Add tests for user service" \ --description "Unit tests with 90%+ coverage" \ --llm openai # Time: ~4 minutes # Cost: ~$0.18 # Result: 95% coverage achieved ``` *** ## Next Steps Create your first GPT-4 task Compare with other AI agents Reduce OpenAI spending Manage your API keys and billing # AI Agents Overview Source: https://docs.namastex.ai/forge/agents/overview Understanding the 8 coding agents supported by Forge ## Overview Forge supports **8 different AI coding agents** - giving you the freedom to choose the best tool for each task. This is the core of Forge's **BYOL (Bring Your Own LLM)** philosophy. *** ## The Agent Landscape ```mermaid theme={null} graph TB A[AI Coding Agents] --> B[Commercial APIs] A --> C[Open Source] A --> D[LLM Agnostic] B --> E[Claude Code] B --> F[Cursor CLI] B --> G[Gemini] B --> H[OpenAI Codex] C --> I[OpenCode] C --> J[Qwen Code] D --> K[Claude Code Router] D --> L[Amp] ``` *** ## Supported Agents ### Commercial API-Based **By**: Anthropic **Models**: Claude 3.5 Sonnet, Opus, Haiku **Best for**: Complex logic, architecture **Cost**: \$3-15/MTok Excellent reasoning, great for system design **By**: Cursor **Models**: Multiple (via Cursor account) **Best for**: UI/UX, rapid iteration **Cost**: Subscription-based Intuitive for frontend work, fast iterations **By**: Google **Models**: Gemini 2.0 Flash, 1.5 Pro **Best for**: Fast tasks, experimentation **Cost**: Free tier available! Blazing fast, generous free tier **By**: OpenAI **Models**: GPT-4 Turbo, GPT-3.5 **Best for**: General purpose coding **Cost**: \$0.50-30/MTok Reliable, well-documented ### Open Source & Local **Type**: Open source **Run**: Locally via Ollama **Best for**: Privacy-sensitive work **Cost**: Free (your hardware) Fully local, no data leaves your machine **Type**: Open source (Alibaba) **Run**: Locally via Ollama **Best for**: Cost-conscious development **Cost**: Free (your hardware) Strong performance, competitive with commercial ### LLM-Agnostic **Type**: LLM proxy **Use**: Any OpenAI-compatible API **Best for**: Flexibility, vendor independence **Cost**: Varies by backend Route to ANY model - OpenAI, Anthropic, local, custom **By**: Sourcegraph **Type**: Code intelligence **Best for**: Large codebase navigation **Cost**: Based on usage Excels at understanding existing code *** ## Choosing the Right Agent ### By Task Type | Task Type | Best Agent | Why | | ------------------------ | ------------------ | ---------------------- | | **Complex Architecture** | Claude Sonnet/Opus | Superior reasoning | | **Quick Fixes** | Gemini Flash | Fastest, free | | **UI Components** | Cursor | UI/UX intuition | | **Refactoring** | Claude Sonnet | Maintains coherence | | **Testing** | Claude/GPT-4 | Comprehensive coverage | | **Documentation** | GPT-4 | Clear writing | | **Privacy-Critical** | OpenCode/Qwen | Runs locally | | **Experimentation** | Gemini | Free tier, fast | ### By Budget **💰 Budget-Conscious**: 1. Gemini Flash (free tier!) 2. OpenCode (local, free) 3. GPT-3.5 Turbo (cheap) **💵 Balanced**: 1. Claude Haiku (fast + cheap) 2. Gemini Pro 3. Cursor (subscription) **💎 Premium**: 1. Claude Opus (best quality) 2. GPT-4 Turbo 3. Claude Sonnet ### By Context Window | Agent | Context | Best For | | -------------- | ----------- | ----------------- | | Gemini 1.5 Pro | 2M tokens | Massive codebases | | Claude 3.5 | 200K tokens | Large projects | | GPT-4 Turbo | 128K tokens | Standard projects | | GPT-3.5 | 16K tokens | Small files | *** ## Agent Comparison ### Speed vs Quality ``` Quality ↑ │ Claude Opus ● │ Claude Sonnet ● │ GPT-4 ● │ Cursor ● │ Claude Haiku ● │ Gemini Pro ● │ GPT-3.5 ● │ Gemini Flash ● └──────────────────────────────────────────────────────────→ Speed ``` ### Cost vs Capability ``` Capability ↑ │ Claude Opus ● │ GPT-4 ● │ Claude Sonnet ● │ Gemini Pro ● │ Claude Haiku ● │ GPT-3.5 ● │ Gemini Flash ● │ OpenCode/Qwen ● └──────────────────────────────────────────────────────────→ Cost (cheaper) ``` *** ## Real-World Performance ### Benchmark: "Add JWT Authentication" Same task, different agents: ``` ╭───────────┬──────────┬─────────┬────────┬───────╮ │ Agent │ Duration │ Quality │ Tests │ Cost │ ├───────────┼──────────┼─────────┼────────┼───────┤ │ Claude S │ 5m 22s │ A+ │ 95% │ $0.23 │ │ Gemini F │ 2m 15s │ B+ │ 78% │ $0.00 │ │ GPT-4 │ 6m 01s │ A │ 88% │ $0.45 │ │ Cursor │ 4m 18s │ A- │ 85% │ $0.19 │ │ OpenCode │ 8m 33s │ B │ 70% │ $0.00 │ ╰───────────┴──────────┴─────────┴────────┴───────╯ Winner: Claude Sonnet (best balance) Budget: Gemini Flash (free!) Speed: Gemini Flash (2m 15s) ``` *** ## Switching Between Agents One of Forge's superpowers: **try multiple agents on the same task**! ```bash theme={null} # Start with fast, cheap agent forge task create "Add authentication" --llm gemini # If not satisfied, try Claude forge task fork 1 --llm claude # Compare results forge task compare 1 # Choose winner forge task merge 1 --attempt 2 ``` *** ## Agent Configuration ### Quick Setup See detailed setup for each agent: * [Claude Code Setup](/forge/agents/claude-code) * [Cursor CLI Setup](/forge/agents/cursor-cli) * [Gemini Setup](/forge/agents/gemini) * [OpenAI Setup](/forge/agents/openai-codex) * [Open Source Setup](/forge/agents/open-source) ### Configuration File `.forge/config.json`: ```json theme={null} { "llms": { "claude": { "apiKey": "sk-ant-...", "model": "claude-3-5-sonnet-20241022" }, "gemini": { "apiKey": "AIza...", "model": "gemini-2.0-flash-exp" }, "openai": { "apiKey": "sk-...", "model": "gpt-4-turbo" }, "cursor": { "enabled": true } } } ``` *** ## Specialized Agent Profiles Apply "personas" to any base agent: ```bash theme={null} # Security-focused Claude forge task create "Add auth" \ --llm claude \ --agent "security-expert" # Test-focused Gemini forge task create "Add feature" \ --llm gemini \ --agent "test-writer" # Performance-focused GPT-4 forge task create "Optimize query" \ --llm openai \ --agent "performance-optimizer" ``` See [Specialized Agents](/forge/advanced/specialized-agents) for details. *** ## Agent Strengths & Weaknesses ### Claude Code **Strengths** ✅: * Complex reasoning * System design * Edge case handling * Clear explanations **Weaknesses** ⚠️: * Can be verbose * Sometimes over-engineers * More expensive **Best for**: Architecture, refactoring, security ### Gemini **Strengths** ✅: * Blazing fast * Free tier (!) * Good for simple tasks * Concise code **Weaknesses** ⚠️: * May miss edge cases * Less sophisticated reasoning * Shorter responses **Best for**: Quick fixes, iteration, experimentation ### Cursor CLI **Strengths** ✅: * Great UI/UX intuition * Fast iterations * Context-aware * Good for frontend **Weaknesses** ⚠️: * Subscription required * Less depth on algorithms * Tied to Cursor ecosystem **Best for**: UI components, rapid prototyping ### OpenAI Codex (GPT-4) **Strengths** ✅: * Reliable and consistent * Well-documented * Good all-rounder * Strong community **Weaknesses** ⚠️: * Expensive * Slower than alternatives * Nothing exceptional **Best for**: General coding, documentation ### Open Source (OpenCode/Qwen) **Strengths** ✅: * Fully local * Privacy guaranteed * Free (your hardware) * No rate limits **Weaknesses** ⚠️: * Slower * Lower quality * Requires powerful hardware * More setup needed **Best for**: Privacy-sensitive, learning, cost control *** ## Multi-Agent Workflows ### Sequential Workflow Use different agents for different stages: ```bash theme={null} # 1. Design with Claude (best at architecture) forge task create "Build payment system" --llm claude # 2. Implement with Cursor (fast iteration) forge task create "Build UI components" --llm cursor # 3. Test with GPT-4 (comprehensive tests) forge task create "Add integration tests" --llm openai # 4. Document with Gemini (fast, cheap) forge task create "Write API docs" --llm gemini ``` ### Parallel Comparison Run multiple agents simultaneously: ```bash theme={null} # Try 3 agents at once forge task create "Optimize database query" --llm claude & forge task fork 1 --llm gemini & forge task fork 1 --llm openai & wait # Compare and choose best forge task compare 1 ``` *** ## Cost Tracking Monitor spending per agent: ```bash theme={null} # This month's costs forge cost summary --month january # Output: ╭──────────┬─────────┬────────╮ │ Agent │ Tasks │ Cost │ ├──────────┼─────────┼────────┤ │ Claude │ 24 │ $5.67 │ │ Gemini │ 48 │ $0.00 │ │ GPT-4 │ 12 │ $8.23 │ │ Cursor │ 15 │ (sub) │ ╰──────────┴─────────┴────────╯ Total: $13.90 ``` *** ## Best Practices Begin with Gemini Flash (free!) to validate approach, then use premium agents for refinement Don't use Claude Opus for simple fixes. Don't use Gemini Flash for architecture. Track which agent works best for which task types in your codebase Configure multiple agents. Vendor lock-in is the enemy of productivity. *** ## Troubleshooting **Error**: "Agent 'claude' not configured" **Solution**: * Check `.forge/config.json` has API key * Verify API key is valid * Run `forge config validate` **Issue**: Even "fast" agents are slow **Possible causes**: * Network latency * Large context window * Complex task description **Solutions**: * Check internet speed * Reduce context * Simplify task description **Issue**: Same task, different results each time **This is normal!** AI is non-deterministic. Use temperature=0 for more consistency: ```json theme={null} { "llms": { "claude": { "temperature": 0 } } } ``` *** ## Next Steps Configure Claude for Forge Setup Gemini (free tier!) Run agents locally Create custom agent personas # Approvals Source: https://docs.namastex.ai/forge/api/approvals POST /api/approvals Manage approval workflows for task attempts ## Overview The Approvals API enables approval workflows where task attempts can request human approval before proceeding with critical operations like merging or deployment. **Base URL**: `http://localhost:8887/api/approvals` *** ## Create Approval Request Create a new approval request for a task attempt. ```http theme={null} POST /api/approvals ``` ### Request Body ```json theme={null} { "taskAttemptId": "attempt_abc123", "type": "merge", "title": "Approve merge for authentication system", "description": "This will merge 8 files with 245 additions into main branch", "metadata": { "filesChanged": 8, "linesAdded": 245, "linesRemoved": 12, "targetBranch": "main" }, "approvers": [ "user@example.com", "lead@example.com" ], "expiresAt": "2024-01-16T10:00:00Z" } ``` ### Parameters | Parameter | Type | Required | Description | | --------------- | ------ | -------- | ---------------------------------------------- | | `taskAttemptId` | string | ✅ | Task attempt ID requesting approval | | `type` | enum | ✅ | Approval type: `merge`, `deploy`, `custom` | | `title` | string | ✅ | Approval request title | | `description` | string | ⚠️ | Detailed description | | `metadata` | object | ⚠️ | Additional context data | | `approvers` | array | ⚠️ | List of approver emails (all users if omitted) | | `expiresAt` | string | ⚠️ | Expiration timestamp | ### Example Response ```json theme={null} { "success": true, "data": { "id": "approval_def456", "taskAttemptId": "attempt_abc123", "type": "merge", "title": "Approve merge for authentication system", "description": "This will merge 8 files with 245 additions into main branch", "status": "pending", "createdBy": "ai@automagik.ai", "createdAt": "2024-01-15T11:00:00Z", "expiresAt": "2024-01-16T10:00:00Z", "approvers": [ "user@example.com", "lead@example.com" ], "responses": [] } } ``` *** ## Get Approval Status Get detailed information about an approval request. ```http theme={null} GET /api/approvals/:id ``` ### Example Response ```json theme={null} { "success": true, "data": { "id": "approval_def456", "taskAttemptId": "attempt_abc123", "type": "merge", "title": "Approve merge for authentication system", "status": "approved", "createdBy": "ai@automagik.ai", "createdAt": "2024-01-15T11:00:00Z", "expiresAt": "2024-01-16T10:00:00Z", "approvers": [ "user@example.com", "lead@example.com" ], "responses": [ { "approver": "user@example.com", "decision": "approved", "comment": "Looks good to me", "respondedAt": "2024-01-15T11:15:00Z" }, { "approver": "lead@example.com", "decision": "approved", "comment": "LGTM, ship it!", "respondedAt": "2024-01-15T11:20:00Z" } ], "metadata": { "filesChanged": 8, "linesAdded": 245, "linesRemoved": 12, "targetBranch": "main" } } } ``` ### Status Values * `pending` - Awaiting approval responses * `approved` - All required approvers approved * `rejected` - At least one approver rejected * `expired` - Expired before all approvals received * `cancelled` - Cancelled by requester *** ## Respond to Approval Approve or reject an approval request. ```http theme={null} POST /api/approvals/:id/respond ``` ### Request Body ```json theme={null} { "decision": "approved", "comment": "Looks good, merge approved!" } ``` ### Parameters | Parameter | Type | Required | Description | | ---------- | ------ | -------- | ------------------------------------ | | `decision` | enum | ✅ | Response: `approved`, `rejected` | | `comment` | string | ⚠️ | Optional comment explaining decision | ### Example Response ```json theme={null} { "success": true, "data": { "approvalId": "approval_def456", "decision": "approved", "comment": "Looks good, merge approved!", "respondedAt": "2024-01-15T11:15:00Z", "approvalStatus": "approved" } } ``` **Note**: `approvalStatus` indicates the overall approval request status after this response. *** ## Get Pending Approvals List all pending approval requests for the current user. ```http theme={null} GET /api/approvals/pending ``` ### Query Parameters | Parameter | Type | Description | | --------- | ------- | ------------------------------------------- | | `type` | enum | Filter by type: `merge`, `deploy`, `custom` | | `page` | integer | Page number (default: 1) | | `limit` | integer | Items per page (default: 20) | ```bash cURL theme={null} curl "http://localhost:8887/api/approvals/pending?type=merge&limit=10" ``` ```javascript JavaScript theme={null} const response = await fetch('http://localhost:8887/api/approvals/pending?type=merge&limit=10'); const data = await response.json(); ``` ```python Python theme={null} import requests response = requests.get('http://localhost:8887/api/approvals/pending?type=merge&limit=10') data = response.json() ``` ```json 200 Success theme={null} { "success": true, "data": [ { "id": "approval_def456", "taskAttemptId": "attempt_abc123", "type": "merge", "title": "Approve merge for authentication system", "status": "pending", "createdBy": "ai@automagik.ai", "createdAt": "2024-01-15T11:00:00Z", "expiresAt": "2024-01-16T10:00:00Z" }, { "id": "approval_ghi789", "taskAttemptId": "attempt_xyz456", "type": "merge", "title": "Approve merge for payment integration", "status": "pending", "createdBy": "ai@automagik.ai", "createdAt": "2024-01-15T10:30:00Z", "expiresAt": "2024-01-16T09:00:00Z" } ], "pagination": { "page": 1, "limit": 10, "total": 2, "pages": 1 } } ``` ```json 401 Unauthorized theme={null} { "success": false, "error": { "code": "UNAUTHORIZED", "message": "Authentication required" } } ``` *** ## Approval Workflows ### Merge Approval Workflow ```mermaid theme={null} sequenceDiagram participant AI as AI Agent participant Forge as Forge participant Approver as Human Approver AI->>Forge: Create task attempt Forge->>Forge: Execute task AI->>Forge: POST /api/approvals (merge request) Forge->>Approver: Notification Approver->>Forge: GET /api/approvals/pending Approver->>Forge: Review changes Approver->>Forge: POST /api/approvals/:id/respond Forge->>AI: Approval granted AI->>Forge: POST /api/task-attempts/:id/merge ``` ### Deployment Approval Workflow ```mermaid theme={null} sequenceDiagram participant AI as AI Agent participant Forge as Forge participant Lead as Tech Lead participant Manager as Manager AI->>Forge: Create approval (deploy to prod) Forge->>Lead: Notify tech lead Forge->>Manager: Notify manager Lead->>Forge: Approve Manager->>Forge: Approve Forge->>AI: All approvals received AI->>Forge: Execute deployment ``` *** ## SDK Examples ### JavaScript/TypeScript ```typescript theme={null} import { ForgeClient } from '@automagik/forge-sdk'; const forge = new ForgeClient(); // Create approval request const approval = await forge.approvals.create({ taskAttemptId: 'attempt_abc123', type: 'merge', title: 'Approve merge for authentication system', description: 'Merging 8 files with 245 additions', approvers: ['tech-lead@example.com', 'manager@example.com'] }); // Get pending approvals const pending = await forge.approvals.pending({ type: 'merge' }); // Respond to approval await forge.approvals.respond('approval_def456', { decision: 'approved', comment: 'LGTM!' }); // Check approval status const status = await forge.approvals.get('approval_def456'); console.log(`Approval status: ${status.status}`); ``` ### Python ```python theme={null} from automagik_forge import ForgeClient forge = ForgeClient() # Create approval request approval = forge.approvals.create( task_attempt_id='attempt_abc123', type='merge', title='Approve merge for authentication system', approvers=['tech-lead@example.com'] ) # Get pending approvals pending = forge.approvals.pending(type='merge') # Respond to approval forge.approvals.respond( 'approval_def456', decision='approved', comment='Looks good!' ) ``` *** ## Best Practices ```json theme={null} // Good ✅ { "title": "Approve merge: Add JWT authentication with refresh tokens", "description": "Changes: 8 files, +245/-12 lines. Adds auth middleware and user routes." } // Avoid ❌ { "title": "Approve merge", "description": "Code changes" } ``` ```json theme={null} { "metadata": { "filesChanged": 8, "linesAdded": 245, "linesRemoved": 12, "targetBranch": "main", "diffUrl": "/api/task-attempts/abc123/diff", "tests": "all passing", "securityScan": "no issues found" } } ``` ```javascript theme={null} // For urgent changes - 4 hours expiresAt: new Date(Date.now() + 4 * 60 * 60 * 1000) // For normal changes - 24 hours expiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000) // For low priority - 3 days expiresAt: new Date(Date.now() + 3 * 24 * 60 * 60 * 1000) ``` ```json theme={null} // Good - specific approvers ✅ { "approvers": [ "security-lead@example.com", // For auth changes "tech-lead@example.com" // For code review ] } // Avoid - too many approvers ❌ { "approvers": [ "user1@example.com", "user2@example.com", "user3@example.com", "user4@example.com", "user5@example.com" ] } ``` *** ## Next Steps Manage task attempts that require approval Approval workflow patterns Real-time approval notifications Create tasks that trigger approvals # Attempts Source: https://docs.namastex.ai/forge/api/attempts POST /api/tasks/:taskId/attempts Execute and manage task attempts ## Overview Attempts represent individual executions of tasks by AI agents. Each task can have multiple attempts with different agents or configurations. **Base URL**: `http://localhost:8887/api/attempts` *** ## List Attempts Get all attempts with filtering. ```http theme={null} GET /api/attempts ``` ### Query Parameters | Parameter | Type | Description | | --------- | ------- | ------------------ | | `taskId` | string | Filter by task | | `llm` | string | Filter by AI agent | | `status` | enum | Filter by status | | `page` | integer | Page number | | `limit` | integer | Items per page | ### Status Values * `created` - Queued, not started * `running` - Currently executing * `completed` - Finished successfully * `failed` - Execution failed * `cancelled` - Cancelled by user ```bash cURL theme={null} curl "http://localhost:8887/api/attempts?taskId=task_abc123&status=completed" ``` ```javascript JavaScript theme={null} const response = await fetch('http://localhost:8887/api/attempts?taskId=task_abc123&status=completed'); const data = await response.json(); ``` ```python Python theme={null} import requests response = requests.get('http://localhost:8887/api/attempts?taskId=task_abc123&status=completed') data = response.json() ``` ```json 200 Success theme={null} { "success": true, "data": [ { "id": "attempt_abc123", "taskId": "task_xyz789", "llm": "claude", "status": "completed", "worktreePath": ".forge/worktrees/task-xyz-claude", "startedAt": "2024-01-15T10:30:00Z", "completedAt": "2024-01-15T10:45:00Z", "duration": 900000, "filesChanged": 8, "linesAdded": 245, "linesRemoved": 12, "cost": { "inputTokens": 15420, "outputTokens": 3890, "totalCost": 0.23 } } ] } ``` ```json 401 Unauthorized theme={null} { "success": false, "error": { "code": "UNAUTHORIZED", "message": "Authentication required" } } ``` *** ## Get Attempt Retrieve detailed attempt information. ```http theme={null} GET /api/attempts/:id ``` ### Example Response ```json theme={null} { "success": true, "data": { "id": "attempt_abc123", "taskId": "task_xyz789", "llm": "claude", "model": "claude-3-5-sonnet-20241022", "status": "completed", "worktreePath": ".forge/worktrees/task-xyz-claude", "startedAt": "2024-01-15T10:30:00Z", "completedAt": "2024-01-15T10:45:00Z", "duration": 900000, "changes": { "filesChanged": 8, "filesCreated": 2, "filesModified": 6, "filesDeleted": 0, "linesAdded": 245, "linesRemoved": 12 }, "cost": { "inputTokens": 15420, "outputTokens": 3890, "totalCost": 0.23 }, "output": { "summary": "Successfully implemented JWT authentication", "changes": [ "Created src/auth/jwt.ts for token generation", "Added login endpoint to src/api/auth.ts", "Added signup endpoint with validation", "Created authentication middleware", "Added comprehensive tests" ] } } } ``` *** ## Create Attempt Start a new attempt for a task. ```http theme={null} POST /api/attempts ``` ### Request Body ```json theme={null} { "taskId": "task_xyz789", "llm": "claude", "options": { "temperature": 0.7, "maxTokens": 4096, "timeout": 60000 }, "description": "Focus on security and edge cases" } ``` ```bash cURL theme={null} curl -X POST http://localhost:8887/api/attempts \ -H "Content-Type: application/json" \ -d '{ "taskId": "task_xyz789", "llm": "claude" }' ``` ```javascript JavaScript theme={null} const response = await fetch('http://localhost:8887/api/attempts', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({...}) }); const data = await response.json(); ``` ```python Python theme={null} import requests response = requests.post( 'http://localhost:8887/api/attempts', json={...} ) data = response.json() ``` ```json 200 Success theme={null} { "success": true, "data": { "id": "attempt_new123", "taskId": "task_xyz789", "llm": "claude", "status": "created", "createdAt": "2024-01-15T11:00:00Z" } } ``` ```json 401 Unauthorized theme={null} { "success": false, "error": { "code": "UNAUTHORIZED", "message": "Authentication required" } } ``` *** ## Start Attempt Begin execution of a created attempt. ```http theme={null} POST /api/attempts/:id/start ``` ```bash cURL theme={null} curl -X POST http://localhost:8887/api/attempts/attempt_new123/start ``` ```javascript JavaScript theme={null} const response = await fetch('http://localhost:8887/api/attempts/attempt_new123/start', { method: 'POST' }); const data = await response.json(); ``` ```python Python theme={null} import requests response = requests.post( 'http://localhost:8887/api/attempts/attempt_new123/start', json={...} ) data = response.json() ``` ```json 200 Success theme={null} { "success": true, "data": { "id": "attempt_new123", "status": "running", "startedAt": "2024-01-15T11:00:00Z", "processId": "proc_abc123" } } ``` ```json 401 Unauthorized theme={null} { "success": false, "error": { "code": "UNAUTHORIZED", "message": "Authentication required" } } ``` *** ## Cancel Attempt Stop a running attempt. ```http theme={null} POST /api/attempts/:id/cancel ``` ```bash cURL theme={null} curl -X POST http://localhost:8887/api/attempts/attempt_abc123/cancel ``` ```javascript JavaScript theme={null} const response = await fetch('http://localhost:8887/api/attempts/attempt_abc123/cancel', { method: 'POST' }); const data = await response.json(); ``` ```python Python theme={null} import requests response = requests.post( 'http://localhost:8887/api/attempts/attempt_abc123/cancel', json={...} ) data = response.json() ``` ```json 200 Success theme={null} { "success": true, "data": { "id": "attempt_abc123", "status": "cancelled", "cancelledAt": "2024-01-15T11:05:00Z" } } ``` ```json 401 Unauthorized theme={null} { "success": false, "error": { "code": "UNAUTHORIZED", "message": "Authentication required" } } ``` *** ## Delete Attempt Remove an attempt and cleanup worktree. ```http theme={null} DELETE /api/attempts/:id ``` This permanently deletes the attempt and removes the associated Git worktree. ```bash cURL theme={null} curl -X DELETE http://localhost:8887/api/attempts/attempt_abc123 ``` ```javascript JavaScript theme={null} const response = await fetch('http://localhost:8887/api/attempts/attempt_abc123', { method: 'DELETE' }); const data = await response.json(); ``` ```python Python theme={null} import requests response = requests.delete('http://localhost:8887/api/attempts/attempt_abc123') data = response.json() ``` ```json 200 Success theme={null} { "success": true, "data": { "deleted": true, "attemptId": "attempt_abc123" } } ``` ```json 404 Not Found theme={null} { "success": false, "error": { "code": "NOT_FOUND", "message": "Attempt not found" } } ``` *** ## Get Attempt Logs Retrieve execution logs for an attempt. ```http theme={null} GET /api/attempts/:id/logs ``` ### Query Parameters | Parameter | Type | Description | | --------- | --------- | ------------------------- | | `follow` | boolean | Stream logs in real-time | | `level` | enum | Filter by log level | | `since` | timestamp | Only logs after this time | ```bash cURL theme={null} curl "http://localhost:8887/api/attempts/attempt_abc123/logs?follow=true" ``` ```javascript JavaScript theme={null} const response = await fetch('http://localhost:8887/api/attempts/attempt_abc123/logs?follow=true'); const reader = response.body.getReader(); // Stream logs line by line while (true) { const {done, value} = await reader.read(); if (done) break; console.log(new TextDecoder().decode(value)); } ``` ```python Python theme={null} import requests response = requests.get( 'http://localhost:8887/api/attempts/attempt_abc123/logs', params={'follow': True}, stream=True ) for line in response.iter_lines(): if line: print(line.decode('utf-8')) ``` ```json 200 Success (Streaming) theme={null} {"level":"info","message":"Starting attempt execution","timestamp":"2024-01-15T10:30:00Z"} {"level":"info","message":"Creating git worktree","timestamp":"2024-01-15T10:30:01Z"} {"level":"info","message":"Worktree created: .forge/worktrees/task-xyz-claude","timestamp":"2024-01-15T10:30:02Z"} {"level":"info","message":"Initializing LLM: claude","timestamp":"2024-01-15T10:30:03Z"} {"level":"info","message":"Generating code...","timestamp":"2024-01-15T10:30:05Z"} {"level":"info","message":"Created file: src/auth/jwt.ts","timestamp":"2024-01-15T10:32:15Z"} ``` ```json 401 Unauthorized theme={null} { "success": false, "error": { "code": "UNAUTHORIZED", "message": "Authentication required" } } ``` *** ## Get Attempt Diff Get code changes made by the attempt. ```http theme={null} GET /api/attempts/:id/diff ``` ### Query Parameters | Parameter | Type | Description | | --------- | ------ | --------------------------------------------- | | `file` | string | Specific file to diff | | `format` | enum | `unified`, `split`, `json` (default: unified) | ```bash cURL theme={null} curl "http://localhost:8887/api/attempts/attempt_abc123/diff?format=json" ``` ```javascript JavaScript theme={null} const response = await fetch('http://localhost:8887/api/attempts/attempt_abc123/diff?format=json'); const diff = await response.json(); ``` ```python Python theme={null} import requests response = requests.get( 'http://localhost:8887/api/attempts/attempt_abc123/diff', params={'format': 'json'} ) diff = response.json() ``` ```json 200 Success theme={null} { "success": true, "data": { "files": [ { "path": "src/auth/jwt.ts", "status": "added", "additions": 67, "deletions": 0, "changes": [ { "type": "add", "lineNumber": 1, "content": "import jwt from 'jsonwebtoken';" } ] }, { "path": "src/api/auth.ts", "status": "modified", "additions": 132, "deletions": 13, "changes": [...] } ], "summary": { "filesChanged": 8, "additions": 245, "deletions": 12 } } } ``` ```json 401 Unauthorized theme={null} { "success": false, "error": { "code": "UNAUTHORIZED", "message": "Authentication required" } } ``` *** ## Merge Attempt Merge attempt changes into main branch. ```http theme={null} POST /api/attempts/:id/merge ``` ### Request Body ```json theme={null} { "message": "Add JWT authentication", "strategy": "squash", "cleanup": true } ``` ### Merge Strategies * `ff` - Fast-forward merge (default) * `no-ff` - Create merge commit * `squash` - Squash commits into one ```bash cURL theme={null} curl -X POST http://localhost:8887/api/attempts/attempt_abc123/merge \ -H "Content-Type: application/json" \ -d '{ "message": "Add JWT authentication (Claude implementation)", "strategy": "squash", "cleanup": true }' ``` ```javascript JavaScript theme={null} const response = await fetch('http://localhost:8887/api/attempts/attempt_abc123/merge', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({...}) }); const data = await response.json(); ``` ```python Python theme={null} import requests response = requests.post( 'http://localhost:8887/api/attempts/attempt_abc123/merge', json={...} ) data = response.json() ``` ```json 200 Success theme={null} { "success": true, "data": { "attemptId": "attempt_abc123", "commitSha": "abc123def456", "merged": true, "mergedAt": "2024-01-15T11:10:00Z", "cleanup": true } } ``` ```json 401 Unauthorized theme={null} { "success": false, "error": { "code": "UNAUTHORIZED", "message": "Authentication required" } } ``` *** ## Compare Attempts Compare two attempts side-by-side. ```http theme={null} POST /api/attempts/compare ``` ### Request Body ```json theme={null} { "attemptIds": ["attempt_1", "attempt_2"] } ``` ### Example Response ```json theme={null} { "success": true, "data": { "attempts": [ { "id": "attempt_1", "llm": "claude", "duration": 900000, "cost": 0.23, "filesChanged": 8, "linesAdded": 245 }, { "id": "attempt_2", "llm": "gemini", "duration": 450000, "cost": 0.00, "filesChanged": 6, "linesAdded": 189 } ], "comparison": { "fasterAttempt": "attempt_2", "cheaperAttempt": "attempt_2", "moreCompleteAttempt": "attempt_1" } } } ``` *** ## Get Commit Info Get commit information for a task attempt. ```http theme={null} GET /api/task-attempts/:id/commit-info ``` ### Example Response ```json theme={null} { "success": true, "data": { "commitId": "abc123def456", "message": "Add user authentication (automagik-forge a1b2)", "author": "Claude AI ", "timestamp": "2024-01-15T10:45:00Z", "filesChanged": 8, "insertions": 245, "deletions": 12 } } ``` *** ## Compare to Head Compare task attempt branch to HEAD of target branch. ```http theme={null} GET /api/task-attempts/:id/compare-to-head ``` ### Example Response ```json theme={null} { "success": true, "data": { "diff": "diff --git a/src/auth.ts...", "filesChanged": 8, "ahead": 3, "behind": 0, "conflicts": [] } } ``` *** ## Merge Attempt Merge task attempt into target branch. ```http theme={null} POST /api/task-attempts/:id/merge ``` ### Request Body ```json theme={null} { "strategy": "squash", "message": "Add authentication system", "cleanup": true } ``` ### Parameters | Parameter | Type | Default | Description | | ---------- | ------- | -------- | ------------------------------------------- | | `strategy` | enum | `squash` | Merge strategy: `squash`, `merge`, `rebase` | | `message` | string | auto | Custom commit message | | `cleanup` | boolean | `true` | Delete worktree after merge | ### Example Response ```json theme={null} { "success": true, "data": { "commitId": "abc123def456", "mergedAt": "2024-01-15T11:00:00Z", "branch": "main", "filesChanged": 8 } } ``` *** ## Push Branch Push task attempt branch to remote. ```http theme={null} POST /api/task-attempts/:id/push ``` ### Request Body ```json theme={null} { "remote": "origin", "force": false } ``` ### Example Response ```json theme={null} { "success": true, "data": { "remote": "origin", "branch": "forge/task-abc123-attempt-1", "pushedAt": "2024-01-15T10:50:00Z" } } ``` *** ## Create GitHub PR Create a pull request from task attempt branch. ```http theme={null} POST /api/task-attempts/:id/create-pr ``` ### Request Body ```json theme={null} { "title": "Add user authentication", "body": "Implements JWT-based authentication with refresh tokens", "baseBranch": "main", "draft": false } ``` ### Example Response ```json theme={null} { "success": true, "data": { "prNumber": 42, "url": "https://github.com/user/repo/pull/42", "createdAt": "2024-01-15T10:55:00Z" } } ``` *** ## Attach Existing PR Attach an existing GitHub PR to this attempt. ```http theme={null} POST /api/task-attempts/:id/attach-pr ``` ### Request Body ```json theme={null} { "prNumber": 42, "repository": "user/repo" } ``` ### Example Response ```json theme={null} { "success": true, "data": { "prNumber": 42, "url": "https://github.com/user/repo/pull/42", "status": "open" } } ``` *** ## Open in Editor Open task attempt worktree in IDE/editor. ```http theme={null} POST /api/task-attempts/:id/open-in-editor ``` ### Request Body ```json theme={null} { "editor": "vscode" } ``` ### Supported Editors * `vscode` - Visual Studio Code * `cursor` - Cursor IDE * `idea` - IntelliJ IDEA * `sublime` - Sublime Text ### Example Response ```json theme={null} { "success": true, "data": { "editor": "vscode", "worktreePath": "/path/to/.forge/worktrees/task-abc123", "opened": true } } ``` *** ## Get Branch Status Get git status of task attempt branch. ```http theme={null} GET /api/task-attempts/:id/branch-status ``` ### Example Response ```json theme={null} { "success": true, "data": { "branch": "forge/task-abc123-attempt-1", "baseBranch": "main", "ahead": 3, "behind": 0, "conflicted": false, "modifiedFiles": [], "untrackedFiles": [], "status": "clean" } } ``` *** ## Change Target Branch Change the base branch for this attempt. ```http theme={null} POST /api/task-attempts/:id/change-target-branch ``` ### Request Body ```json theme={null} { "newBaseBranch": "develop" } ``` ### Example Response ```json theme={null} { "success": true, "data": { "previousBase": "main", "newBase": "develop", "conflicts": [] } } ``` *** ## Rebase Attempt Rebase task attempt onto latest base branch. ```http theme={null} POST /api/task-attempts/:id/rebase ``` ### Request Body ```json theme={null} { "interactive": false } ``` ### Example Response ```json theme={null} { "success": true, "data": { "status": "success", "conflicts": [], "commitsReplayed": 3 } } ``` **Conflict Response**: ```json theme={null} { "success": false, "data": { "status": "conflict", "conflicts": [ "src/auth.ts", "src/users.ts" ] } } ``` *** ## Abort Conflicts Abort merge/rebase conflicts and return to clean state. ```http theme={null} POST /api/task-attempts/:id/abort-conflicts ``` ### Example Response ```json theme={null} { "success": true, "data": { "status": "clean", "abortedOperation": "rebase" } } ``` *** ## Delete File Delete a file from task attempt worktree. ```http theme={null} DELETE /api/task-attempts/:id/files/:path ``` ### Example ```bash theme={null} curl -X DELETE \ http://localhost:8887/api/task-attempts/attempt_123/files/src/old-file.ts ``` ### Example Response ```json theme={null} { "success": true, "data": { "path": "src/old-file.ts", "deleted": true } } ``` *** ## Start Dev Server Start development server in task attempt worktree. ```http theme={null} POST /api/task-attempts/:id/start-dev-server ``` ### Request Body ```json theme={null} { "script": "dev", "port": 3000 } ``` ### Example Response ```json theme={null} { "success": true, "data": { "processId": "process_abc123", "port": 3000, "url": "http://localhost:3000", "status": "running" } } ``` *** ## Get Child Tasks Get tasks created from this attempt (subtasks). ```http theme={null} GET /api/task-attempts/:id/children ``` ### Example Response ```json theme={null} { "success": true, "data": [ { "id": "task_child1", "title": "Add unit tests for auth", "status": "todo", "createdAt": "2024-01-15T11:00:00Z" } ] } ``` *** ## Replace Process Replace the running execution process with a new one. ```http theme={null} POST /api/task-attempts/:id/replace-process ``` ### Request Body ```json theme={null} { "executorProfileId": { "executor": "CLAUDE_CODE", "variant": null }, "prompt": "Continue with different approach" } ``` ### Example Response ```json theme={null} { "success": true, "data": { "oldProcessId": "process_123", "newProcessId": "process_456", "status": "running" } } ``` *** ## SDK Examples ### JavaScript/TypeScript ```typescript theme={null} import { ForgeClient } from '@automagik/forge-sdk'; const forge = new ForgeClient(); // List attempts const attempts = await forge.attempts.list({ taskId: 'task_xyz789', status: 'completed' }); // Create and start attempt const attempt = await forge.attempts.create({ taskId: 'task_xyz789', llm: 'claude' }); await forge.attempts.start(attempt.id); // Get logs (streaming) const logs = await forge.attempts.logs(attempt.id, { follow: true }); for await (const log of logs) { console.log(log.message); } // Get diff const diff = await forge.attempts.diff(attempt.id); // Merge when ready await forge.attempts.merge(attempt.id, { message: 'Add authentication', strategy: 'squash', cleanup: true }); // Compare attempts const comparison = await forge.attempts.compare([ 'attempt_1', 'attempt_2' ]); ``` ### Python ```python theme={null} from automagik_forge import ForgeClient forge = ForgeClient() # Create and start attempt attempt = forge.attempts.create( task_id='task_xyz789', llm='claude' ) forge.attempts.start(attempt.id) # Stream logs for log in forge.attempts.logs(attempt.id, follow=True): print(log.message) # Get diff diff = forge.attempts.diff(attempt.id) # Merge forge.attempts.merge( attempt.id, message='Add authentication', strategy='squash', cleanup=True ) ``` *** ## WebSocket Events Subscribe to real-time attempt updates: ```javascript theme={null} const ws = new WebSocket('ws://localhost:8887/ws'); ws.send(JSON.stringify({ type: 'subscribe', channel: 'attempts', attemptId: 'attempt_abc123' })); ws.onmessage = (event) => { const update = JSON.parse(event.data); // { type: 'attempt.status_changed', attemptId: '...', status: 'running' } }; ``` *** ## Next Steps Manage tasks Monitor running processes Use from AI agents # Containers Source: https://docs.namastex.ai/forge/api/containers GET /api/containers/:id Get information about worktree containers ## Overview The Containers API provides information about git worktree containers used by task attempts. Each container represents an isolated workspace where AI agents execute tasks. **Base URL**: `http://localhost:8887/api/containers` *** ## Get Container Info Get detailed information about a worktree container. ```http theme={null} GET /api/containers/:id ``` ### Path Parameters | Parameter | Type | Description | | --------- | ------ | --------------------- | | `id` | string | Container/worktree ID | ### Example Response ```json theme={null} { "success": true, "data": { "id": "container_abc123", "taskAttemptId": "attempt_xyz789", "worktreePath": "/path/to/.forge/worktrees/task-abc123-attempt-1", "branch": "forge/task-abc123-attempt-1", "baseBranch": "main", "status": "active", "createdAt": "2024-01-15T10:30:00Z", "diskUsage": { "total": 52428800, "used": 15728640, "available": 36700160 }, "gitStatus": { "ahead": 3, "behind": 0, "modified": 2, "untracked": 1, "conflicted": 0 }, "files": { "total": 156, "modified": 8, "added": 3, "deleted": 1 } } } ``` ### Response Fields | Field | Type | Description | | --------------- | ------ | ----------------------------------------- | | `id` | string | Container ID | | `taskAttemptId` | string | Associated task attempt | | `worktreePath` | string | Absolute path to worktree | | `branch` | string | Worktree branch name | | `baseBranch` | string | Target branch for merge | | `status` | enum | `active`, `inactive`, `merged`, `deleted` | | `createdAt` | string | Creation timestamp | | `diskUsage` | object | Disk space information | | `gitStatus` | object | Git status summary | | `files` | object | File statistics | *** ## Use Cases ### Monitor Disk Usage Track worktree disk usage to prevent space issues: ```javascript theme={null} const container = await forge.containers.get('container_abc123'); if (container.diskUsage.available < 1000000000) { // < 1GB console.warn('Low disk space in worktree'); } ``` ### Check Git Status Verify worktree state before merging: ```javascript theme={null} const container = await forge.containers.get('container_abc123'); if (container.gitStatus.conflicted > 0) { console.error('Container has merge conflicts'); } else if (container.gitStatus.modified === 0) { console.log('No changes in worktree'); } ``` *** ## SDK Examples ### JavaScript/TypeScript ```typescript theme={null} import { ForgeClient } from '@automagik/forge-sdk'; const forge = new ForgeClient(); // Get container info const container = await forge.containers.get('container_abc123'); console.log('Worktree path:', container.worktreePath); console.log('Modified files:', container.files.modified); console.log('Disk usage:', container.diskUsage.used / 1024 / 1024, 'MB'); ``` ### Python ```python theme={null} from automagik_forge import ForgeClient forge = ForgeClient() # Get container info container = forge.containers.get('container_abc123') print(f"Worktree: {container['worktreePath']}") print(f"Modified: {container['files']['modified']} files") ``` *** ## Next Steps Task attempts using containers Learn about worktree isolation # Drafts Source: https://docs.namastex.ai/forge/api/drafts POST /api/task-attempts/:id/drafts Manage draft prompts and follow-up queues ## Overview The Drafts API allows you to save, manage, and queue prompts for task attempts. Useful for preparing follow-up instructions or retry strategies before execution. **Base URL**: `http://localhost:8887/api/task-attempts/:id/drafts` *** ## Save Draft Save a draft prompt for a task attempt. ```http theme={null} POST /api/task-attempts/:id/drafts ``` ### Parameters | Parameter | Type | Required | Description | | ---------- | ------ | -------- | ------------------------------------------- | | `content` | string | ✅ | Draft prompt content | | `type` | enum | ✅ | Draft type: `follow_up`, `retry`, `initial` | | `metadata` | object | ⚠️ | Additional metadata | ```bash cURL theme={null} curl -X POST http://localhost:8887/api/task-attempts/attempt_xyz789/drafts \ -H "Content-Type: application/json" \ -d '{ "content": "Add unit tests for the authentication functions", "type": "follow_up", "metadata": { "priority": "high", "category": "testing" } }' ``` ```javascript JavaScript theme={null} const response = await fetch('http://localhost:8887/api/task-attempts/attempt_xyz789/drafts', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ content: 'Add unit tests for the authentication functions', type: 'follow_up', metadata: { priority: 'high', category: 'testing' } }) }); const data = await response.json(); ``` ```python Python theme={null} import requests response = requests.post( 'http://localhost:8887/api/task-attempts/attempt_xyz789/drafts', json={ 'content': 'Add unit tests for the authentication functions', 'type': 'follow_up', 'metadata': { 'priority': 'high', 'category': 'testing' } } ) data = response.json() ``` ```json 201 Created theme={null} { "success": true, "data": { "id": "draft_abc123", "taskAttemptId": "attempt_xyz789", "content": "Add unit tests for the authentication functions", "type": "follow_up", "createdAt": "2024-01-15T10:30:00Z", "updatedAt": "2024-01-15T10:30:00Z", "metadata": { "priority": "high", "category": "testing" } } } ``` ```json 400 Bad Request theme={null} { "success": false, "error": { "code": "INVALID_REQUEST", "message": "Missing required field: content" } } ``` *** ## Get Draft Retrieve a saved draft. ```http theme={null} GET /api/task-attempts/:attemptId/drafts/:draftId ``` ```bash cURL theme={null} curl http://localhost:8887/api/task-attempts/attempt_xyz789/drafts/draft_abc123 ``` ```javascript JavaScript theme={null} const response = await fetch('http://localhost:8887/api/task-attempts/attempt_xyz789/drafts/draft_abc123'); const data = await response.json(); ``` ```python Python theme={null} import requests response = requests.get('http://localhost:8887/api/task-attempts/attempt_xyz789/drafts/draft_abc123') data = response.json() ``` ```json 200 Success theme={null} { "success": true, "data": { "id": "draft_abc123", "taskAttemptId": "attempt_xyz789", "content": "Add unit tests for the authentication functions", "type": "follow_up", "createdAt": "2024-01-15T10:30:00Z", "updatedAt": "2024-01-15T10:30:00Z" } } ``` ```json 404 Not Found theme={null} { "success": false, "error": { "code": "NOT_FOUND", "message": "Draft not found" } } ``` *** ## Delete Draft Delete a saved draft. ```http theme={null} DELETE /api/task-attempts/:attemptId/drafts/:draftId ``` ```bash cURL theme={null} curl -X DELETE http://localhost:8887/api/task-attempts/attempt_xyz789/drafts/draft_abc123 ``` ```javascript JavaScript theme={null} const response = await fetch('http://localhost:8887/api/task-attempts/attempt_xyz789/drafts/draft_abc123', { method: 'DELETE' }); const data = await response.json(); ``` ```python Python theme={null} import requests response = requests.delete('http://localhost:8887/api/task-attempts/attempt_xyz789/drafts/draft_abc123') data = response.json() ``` ```json 200 Success theme={null} { "success": true, "data": { "deleted": true, "draftId": "draft_abc123" } } ``` ```json 404 Not Found theme={null} { "success": false, "error": { "code": "NOT_FOUND", "message": "Draft not found" } } ``` *** ## Save Follow-Up Draft Save a draft for follow-up instructions to a running task. ```http theme={null} POST /api/task-attempts/:id/follow-up-draft ``` ### Parameters | Parameter | Type | Default | Description | | ----------- | ------- | ------- | ----------------------------- | | `prompt` | string | - | Follow-up instruction | | `autoSend` | boolean | `false` | Automatically send when ready | | `sendAfter` | string | null | Schedule send time | ```bash cURL theme={null} curl -X POST http://localhost:8887/api/task-attempts/attempt_xyz789/follow-up-draft \ -H "Content-Type: application/json" \ -d '{ "prompt": "Also add integration tests for the login flow", "autoSend": false, "sendAfter": "2024-01-15T11:00:00Z" }' ``` ```javascript JavaScript theme={null} const response = await fetch('http://localhost:8887/api/task-attempts/attempt_xyz789/follow-up-draft', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ prompt: 'Also add integration tests for the login flow', autoSend: false, sendAfter: '2024-01-15T11:00:00Z' }) }); const data = await response.json(); ``` ```python Python theme={null} import requests response = requests.post( 'http://localhost:8887/api/task-attempts/attempt_xyz789/follow-up-draft', json={ 'prompt': 'Also add integration tests for the login flow', 'autoSend': False, 'sendAfter': '2024-01-15T11:00:00Z' } ) data = response.json() ``` ```json 201 Created theme={null} { "success": true, "data": { "id": "draft_followup_abc123", "taskAttemptId": "attempt_xyz789", "prompt": "Also add integration tests for the login flow", "autoSend": false, "sendAfter": "2024-01-15T11:00:00Z", "status": "scheduled", "createdAt": "2024-01-15T10:30:00Z" } } ``` ```json 400 Bad Request theme={null} { "success": false, "error": { "code": "INVALID_REQUEST", "message": "Missing required field: prompt" } } ``` *** ## Save Retry Follow-Up Draft Save a draft for retry attempts with modified prompts. ```http theme={null} POST /api/task-attempts/:id/retry-follow-up-draft ``` ```bash cURL theme={null} curl -X POST http://localhost:8887/api/task-attempts/attempt_xyz789/retry-follow-up-draft \ -H "Content-Type: application/json" \ -d '{ "originalPrompt": "Implement authentication", "retryPrompt": "Implement authentication using JWT with refresh tokens", "retryReason": "Initial attempt didn'\''t include refresh token logic" }' ``` ```javascript JavaScript theme={null} const response = await fetch('http://localhost:8887/api/task-attempts/attempt_xyz789/retry-follow-up-draft', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ originalPrompt: 'Implement authentication', retryPrompt: 'Implement authentication using JWT with refresh tokens', retryReason: 'Initial attempt didn\'t include refresh token logic' }) }); const data = await response.json(); ``` ```python Python theme={null} import requests response = requests.post( 'http://localhost:8887/api/task-attempts/attempt_xyz789/retry-follow-up-draft', json={ 'originalPrompt': 'Implement authentication', 'retryPrompt': 'Implement authentication using JWT with refresh tokens', 'retryReason': 'Initial attempt didn\'t include refresh token logic' } ) data = response.json() ``` ```json 201 Created theme={null} { "success": true, "data": { "id": "draft_retry_abc123", "taskAttemptId": "attempt_xyz789", "originalPrompt": "Implement authentication", "retryPrompt": "Implement authentication using JWT with refresh tokens", "retryReason": "Initial attempt didn't include refresh token logic", "createdAt": "2024-01-15T10:35:00Z" } } ``` ```json 400 Bad Request theme={null} { "success": false, "error": { "code": "INVALID_REQUEST", "message": "Missing required field: retryPrompt" } } ``` *** ## Delete Retry Follow-Up Draft Delete a retry follow-up draft. ```http theme={null} DELETE /api/task-attempts/:id/retry-follow-up-draft/:draftId ``` ```bash cURL theme={null} curl -X DELETE http://localhost:8887/api/task-attempts/attempt_xyz789/retry-follow-up-draft/draft_retry_abc123 ``` ```javascript JavaScript theme={null} const response = await fetch('http://localhost:8887/api/task-attempts/attempt_xyz789/retry-follow-up-draft/draft_retry_abc123', { method: 'DELETE' }); const data = await response.json(); ``` ```python Python theme={null} import requests response = requests.delete('http://localhost:8887/api/task-attempts/attempt_xyz789/retry-follow-up-draft/draft_retry_abc123') data = response.json() ``` ```json 200 Success theme={null} { "success": true, "data": { "deleted": true, "draftId": "draft_retry_abc123" } } ``` ```json 404 Not Found theme={null} { "success": false, "error": { "code": "NOT_FOUND", "message": "Draft not found" } } ``` *** ## Set Follow-Up Queue Set a queue of follow-up prompts to be executed in sequence. ```http theme={null} POST /api/task-attempts/:id/follow-up-queue ``` ### Parameters | Parameter | Type | Default | Description | | ---------------- | ------- | ------- | --------------------------------- | | `queue` | array | - | Ordered list of follow-up prompts | | `queue[].prompt` | string | - | Follow-up instruction | | `queue[].order` | integer | - | Execution order | | `autoExecute` | boolean | `false` | Auto-execute queue | ```bash cURL theme={null} curl -X POST http://localhost:8887/api/task-attempts/attempt_xyz789/follow-up-queue \ -H "Content-Type: application/json" \ -d '{ "queue": [ { "prompt": "Add input validation", "order": 1 }, { "prompt": "Add error handling", "order": 2 }, { "prompt": "Add unit tests", "order": 3 } ], "autoExecute": false }' ``` ```javascript JavaScript theme={null} const response = await fetch('http://localhost:8887/api/task-attempts/attempt_xyz789/follow-up-queue', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ queue: [ { prompt: 'Add input validation', order: 1 }, { prompt: 'Add error handling', order: 2 }, { prompt: 'Add unit tests', order: 3 } ], autoExecute: false }) }); const data = await response.json(); ``` ```python Python theme={null} import requests response = requests.post( 'http://localhost:8887/api/task-attempts/attempt_xyz789/follow-up-queue', json={ 'queue': [ {'prompt': 'Add input validation', 'order': 1}, {'prompt': 'Add error handling', 'order': 2}, {'prompt': 'Add unit tests', 'order': 3} ], 'autoExecute': False } ) data = response.json() ``` ```json 201 Created theme={null} { "success": true, "data": { "taskAttemptId": "attempt_xyz789", "queue": [ { "id": "queue_item_1", "prompt": "Add input validation", "order": 1, "status": "pending" }, { "id": "queue_item_2", "prompt": "Add error handling", "order": 2, "status": "pending" }, { "id": "queue_item_3", "prompt": "Add unit tests", "order": 3, "status": "pending" } ], "autoExecute": false, "createdAt": "2024-01-15T10:30:00Z" } } ``` ```json 400 Bad Request theme={null} { "success": false, "error": { "code": "INVALID_REQUEST", "message": "Queue must be an array with at least one item" } } ``` *** ## Set Draft Queue Set a queue of draft prompts for task creation. ```http theme={null} POST /api/task-attempts/:id/draft-queue ``` ```bash cURL theme={null} curl -X POST http://localhost:8887/api/task-attempts/attempt_xyz789/draft-queue \ -H "Content-Type: application/json" \ -d '{ "queue": [ { "title": "Implement user registration", "description": "Create registration endpoint with email validation", "order": 1 }, { "title": "Implement user login", "description": "Create login endpoint with JWT generation", "order": 2 } ] }' ``` ```javascript JavaScript theme={null} const response = await fetch('http://localhost:8887/api/task-attempts/attempt_xyz789/draft-queue', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ queue: [ { title: 'Implement user registration', description: 'Create registration endpoint with email validation', order: 1 }, { title: 'Implement user login', description: 'Create login endpoint with JWT generation', order: 2 } ] }) }); const data = await response.json(); ``` ```python Python theme={null} import requests response = requests.post( 'http://localhost:8887/api/task-attempts/attempt_xyz789/draft-queue', json={ 'queue': [ { 'title': 'Implement user registration', 'description': 'Create registration endpoint with email validation', 'order': 1 }, { 'title': 'Implement user login', 'description': 'Create login endpoint with JWT generation', 'order': 2 } ] } ) data = response.json() ``` ```json 201 Created theme={null} { "success": true, "data": { "projectId": "proj_abc123", "queue": [ { "id": "queue_draft_1", "title": "Implement user registration", "description": "Create registration endpoint with email validation", "order": 1, "status": "queued" }, { "id": "queue_draft_2", "title": "Implement user login", "description": "Create login endpoint with JWT generation", "order": 2, "status": "queued" } ] } } ``` ```json 400 Bad Request theme={null} { "success": false, "error": { "code": "INVALID_REQUEST", "message": "Queue must be an array with at least one item" } } ``` *** ## Stream Project Drafts Stream real-time updates of project drafts via WebSocket. ``` ws://localhost:8887/ws/projects/:projectId/drafts ``` **Example**: ```javascript theme={null} const projectId = 'proj_abc123'; const ws = new WebSocket(`ws://localhost:8887/ws/projects/${projectId}/drafts`); ws.onmessage = (event) => { const update = JSON.parse(event.data); switch (update.type) { case 'draft_created': console.log('New draft:', update.draft); break; case 'draft_updated': console.log('Draft updated:', update.draft); break; case 'draft_deleted': console.log('Draft deleted:', update.draftId); break; } }; ``` *** ## Use Cases ### Batch Follow-Ups Queue multiple follow-up instructions for sequential execution: ```javascript theme={null} // Set up a series of refinements await forge.attempts.setFollowUpQueue('attempt_123', { queue: [ { prompt: 'Add TypeScript types', order: 1 }, { prompt: 'Add JSDoc comments', order: 2 }, { prompt: 'Add unit tests', order: 3 }, { prompt: 'Add integration tests', order: 4 } ], autoExecute: true }); ``` ### Scheduled Follow-Ups Schedule follow-up instructions for later: ```javascript theme={null} // Schedule a follow-up for after code review await forge.attempts.saveFollowUpDraft('attempt_123', { prompt: 'Address code review comments', autoSend: true, sendAfter: new Date(Date.now() + 2 * 60 * 60 * 1000) // 2 hours from now }); ``` ### Retry Strategy Save retry prompts with improved instructions: ```javascript theme={null} // If first attempt fails, retry with more specific instructions await forge.attempts.saveRetryFollowUpDraft('attempt_123', { originalPrompt: 'Add authentication', retryPrompt: 'Add authentication using Passport.js with JWT strategy and refresh tokens', retryReason: 'Need more specific implementation approach' }); ``` *** ## SDK Examples ### JavaScript/TypeScript ```typescript theme={null} import { ForgeClient } from '@automagik/forge-sdk'; const forge = new ForgeClient(); // Save a draft const draft = await forge.attempts.saveDraft('attempt_123', { content: 'Add error handling', type: 'follow_up', metadata: { priority: 'high' } }); // Get draft const savedDraft = await forge.attempts.getDraft('attempt_123', 'draft_abc'); // Delete draft await forge.attempts.deleteDraft('attempt_123', 'draft_abc'); // Save follow-up draft with auto-send await forge.attempts.saveFollowUpDraft('attempt_123', { prompt: 'Add unit tests', autoSend: true, sendAfter: new Date('2024-01-15T11:00:00Z') }); // Set follow-up queue await forge.attempts.setFollowUpQueue('attempt_123', { queue: [ { prompt: 'Add validation', order: 1 }, { prompt: 'Add tests', order: 2 } ], autoExecute: false }); // Stream drafts const draftStream = forge.projects.streamDrafts('proj_123'); draftStream.on('draft_created', (draft) => { console.log('New draft:', draft); }); ``` ### Python ```python theme={null} from automagik_forge import ForgeClient forge = ForgeClient() # Save draft draft = forge.attempts.save_draft( 'attempt_123', content='Add error handling', type='follow_up' ) # Set follow-up queue forge.attempts.set_follow_up_queue( 'attempt_123', queue=[ {'prompt': 'Add validation', 'order': 1}, {'prompt': 'Add tests', 'order': 2} ], auto_execute=False ) ``` *** ## Best Practices ```javascript theme={null} // Good ✅ queue: [ { prompt: 'Add feature', order: 1 }, { prompt: 'Add tests', order: 2 }, { prompt: 'Add docs', order: 3 } ] // Avoid ❌ queue: [ { prompt: 'Add docs', order: 1 }, { prompt: 'Add feature', order: 2 }, { prompt: 'Add tests', order: 3 } ] ``` Only auto-execute follow-ups when you're confident they won't require review: ```javascript theme={null} // Safe for auto-execute ✅ { prompt: 'Format code', autoExecute: true } // Review first ❌ { prompt: 'Refactor architecture', autoExecute: true } ``` ```javascript theme={null} // Good ✅ { retryPrompt: 'Use bcrypt for password hashing with salt rounds of 12', retryReason: 'Initial attempt used plain text storage' } // Unclear ❌ { retryPrompt: 'Fix it', retryReason: 'Didn't work' } ``` ```javascript theme={null} // Delete obsolete drafts const drafts = await forge.attempts.listDrafts('attempt_123'); for (const draft of drafts) { if (draft.createdAt < oneWeekAgo) { await forge.attempts.deleteDraft('attempt_123', draft.id); } } ``` *** ## Next Steps Task attempt execution Real-time draft updates Create tasks from drafts Draft-based workflows # Filesystem Source: https://docs.namastex.ai/forge/api/filesystem GET /api/filesystem/list Browse repository files and discover git repositories ## Overview The Filesystem API provides endpoints for browsing repository files and discovering git repositories on the local filesystem. **Base URL**: `http://localhost:8887/api/filesystem` *** ## List Directory List files and subdirectories in a given path. ```http theme={null} GET /api/filesystem/list ``` ### Query Parameters | Parameter | Type | Required | Description | | ------------ | ------- | -------- | ------------------------------------------------ | | `path` | string | ✅ | Directory path to list | | `showHidden` | boolean | ⚠️ | Include hidden files (default: false) | | `recursive` | boolean | ⚠️ | Recursively list subdirectories (default: false) | | `maxDepth` | integer | ⚠️ | Max recursion depth (default: 1) | ```bash cURL theme={null} curl "http://localhost:8887/api/filesystem/list?path=/home/user/projects&showHidden=false" ``` ```javascript JavaScript theme={null} const response = await fetch('http://localhost:8887/api/filesystem/list?path=/home/user/projects&showHidden=false'); const data = await response.json(); ``` ```python Python theme={null} import requests response = requests.get('http://localhost:8887/api/filesystem/list?path=/home/user/projects&showHidden=false') data = response.json() ``` ```json 200 Success theme={null} { "success": true, "data": { "path": "/home/user/projects", "entries": [ { "name": "my-app", "path": "/home/user/projects/my-app", "type": "directory", "isGitRepo": true, "size": 4096, "modifiedAt": "2024-01-15T10:00:00Z", "permissions": "rwxr-xr-x" }, { "name": "package.json", "path": "/home/user/projects/my-app/package.json", "type": "file", "size": 1024, "modifiedAt": "2024-01-15T09:30:00Z", "permissions": "rw-r--r--" }, { "name": "src", "path": "/home/user/projects/my-app/src", "type": "directory", "size": 4096, "modifiedAt": "2024-01-15T10:15:00Z", "permissions": "rwxr-xr-x" }, { "name": ".git", "path": "/home/user/projects/my-app/.git", "type": "directory", "isGitRepo": true, "hidden": true, "size": 4096, "modifiedAt": "2024-01-15T11:00:00Z", "permissions": "rwxr-xr-x" } ], "totalEntries": 4, "directories": 3, "files": 1, "gitRepos": 1 } } ``` ```json 401 Unauthorized theme={null} { "success": false, "error": { "code": "UNAUTHORIZED", "message": "Authentication required" } } ``` ### Response Fields | Field | Type | Description | | ----------------------- | ------- | -------------------------------------- | | `path` | string | Directory path that was listed | | `entries` | array | List of files and directories | | `entries[].name` | string | File or directory name | | `entries[].path` | string | Absolute path | | `entries[].type` | enum | `file` or `directory` | | `entries[].isGitRepo` | boolean | Is a git repository (directories only) | | `entries[].hidden` | boolean | Hidden file/directory | | `entries[].size` | integer | Size in bytes | | `entries[].modifiedAt` | string | Last modified timestamp | | `entries[].permissions` | string | Unix-style permissions | | `totalEntries` | integer | Total number of entries | | `directories` | integer | Number of directories | | `files` | integer | Number of files | | `gitRepos` | integer | Number of git repositories found | *** ## List Git Repositories Discover all git repositories under a given path. ```http theme={null} GET /api/filesystem/git-repos ``` ### Query Parameters | Parameter | Type | Required | Description | | ------------------- | ------- | -------- | -------------------------------------- | | `path` | string | ✅ | Root path to search | | `maxDepth` | integer | ⚠️ | Max directory depth (default: 3) | | `includeSubmodules` | boolean | ⚠️ | Include git submodules (default: true) | ```bash cURL theme={null} curl "http://localhost:8887/api/filesystem/git-repos?path=/home/user/projects&maxDepth=2" ``` ```javascript JavaScript theme={null} const response = await fetch('http://localhost:8887/api/filesystem/git-repos?path=/home/user/projects&maxDepth=2'); const data = await response.json(); ``` ```python Python theme={null} import requests response = requests.get('http://localhost:8887/api/filesystem/git-repos?path=/home/user/projects&maxDepth=2') data = response.json() ``` ```json 200 Success theme={null} { "success": true, "data": { "searchPath": "/home/user/projects", "repositories": [ { "name": "my-app", "path": "/home/user/projects/my-app", "gitPath": "/home/user/projects/my-app/.git", "isSubmodule": false, "branch": "main", "hasUncommittedChanges": false, "hasUnpushedCommits": true, "remotes": [ { "name": "origin", "url": "https://github.com/user/my-app.git", "type": "https" } ], "lastCommit": { "hash": "abc123def456", "message": "Add authentication", "author": "John Doe", "date": "2024-01-15T10:00:00Z" } }, { "name": "another-project", "path": "/home/user/projects/another-project", "gitPath": "/home/user/projects/another-project/.git", "isSubmodule": false, "branch": "develop", "hasUncommittedChanges": true, "hasUnpushedCommits": false, "remotes": [ { "name": "origin", "url": "git@github.com:user/another-project.git", "type": "ssh" } ], "lastCommit": { "hash": "def456ghi789", "message": "Work in progress", "author": "Jane Smith", "date": "2024-01-14T15:30:00Z" } } ], "totalFound": 2, "searchDepth": 2, "searchDuration": 145 } } ``` ```json 401 Unauthorized theme={null} { "success": false, "error": { "code": "UNAUTHORIZED", "message": "Authentication required" } } ``` ### Response Fields | Field | Type | Description | | -------------------------------------- | ------- | ----------------------------------- | | `searchPath` | string | Root path that was searched | | `repositories` | array | List of discovered git repositories | | `repositories[].name` | string | Repository name (directory name) | | `repositories[].path` | string | Absolute path to repository | | `repositories[].gitPath` | string | Path to .git directory | | `repositories[].isSubmodule` | boolean | Is a git submodule | | `repositories[].branch` | string | Current branch | | `repositories[].hasUncommittedChanges` | boolean | Has uncommitted changes | | `repositories[].hasUnpushedCommits` | boolean | Has unpushed commits | | `repositories[].remotes` | array | Configured git remotes | | `repositories[].lastCommit` | object | Most recent commit info | | `totalFound` | integer | Total repositories found | | `searchDepth` | integer | Depth of search performed | | `searchDuration` | integer | Search duration in milliseconds | *** ## Use Cases ### Project Selection Use filesystem browsing to help users select a git repository when creating a new Forge project: ```javascript theme={null} // 1. List user's common project directories const dirs = await forge.filesystem.list({ path: '/home/user/projects' }); // 2. Find git repositories const repos = await forge.filesystem.gitRepos({ path: '/home/user/projects', maxDepth: 2 }); // 3. Present repos to user for selection repos.repositories.forEach(repo => { console.log(`${repo.name} - ${repo.branch} (${repo.lastCommit.message})`); }); ``` ### Repository Discovery Automatically discover all git repositories on the system: ```javascript theme={null} // Search common locations const searchPaths = [ '/home/user/projects', '/home/user/Documents/code', '/workspace' ]; const allRepos = []; for (const path of searchPaths) { const result = await forge.filesystem.gitRepos({ path }); allRepos.push(...result.repositories); } console.log(`Found ${allRepos.length} repositories`); ``` ### File Browser Build a file browser interface for selecting files to include in task context: ```javascript theme={null} async function browseDirectory(path, depth = 0) { const result = await forge.filesystem.list({ path, showHidden: false }); result.entries.forEach(entry => { const indent = ' '.repeat(depth); const icon = entry.type === 'directory' ? '📁' : '📄'; const gitBadge = entry.isGitRepo ? ' [GIT]' : ''; console.log(`${indent}${icon} ${entry.name}${gitBadge}`); }); } ``` *** ## SDK Examples ### JavaScript/TypeScript ```typescript theme={null} import { ForgeClient } from '@automagik/forge-sdk'; const forge = new ForgeClient(); // List directory contents const contents = await forge.filesystem.list({ path: '/home/user/projects', showHidden: false, recursive: false }); console.log(`Found ${contents.directories} directories and ${contents.files} files`); // Find all git repositories const repos = await forge.filesystem.gitRepos({ path: '/home/user', maxDepth: 3, includeSubmodules: true }); repos.repositories.forEach(repo => { console.log(`${repo.name}: ${repo.branch}`); if (repo.hasUncommittedChanges) { console.log(' ⚠️ Uncommitted changes'); } if (repo.hasUnpushedCommits) { console.log(' 📤 Unpushed commits'); } }); // Recursive directory listing const tree = await forge.filesystem.list({ path: '/home/user/my-project', recursive: true, maxDepth: 3 }); ``` ### Python ```python theme={null} from automagik_forge import ForgeClient forge = ForgeClient() # List directory contents = forge.filesystem.list( path='/home/user/projects', show_hidden=False ) print(f"Found {contents['directories']} directories") # Find git repositories repos = forge.filesystem.git_repos( path='/home/user', max_depth=3 ) for repo in repos['repositories']: print(f"{repo['name']}: {repo['branch']}") if repo['hasUncommittedChanges']: print(" ⚠️ Uncommitted changes") ``` *** ## Security Considerations **Path Traversal Protection**: The Filesystem API includes built-in protection against path traversal attacks. Requests attempting to access paths outside allowed directories will be rejected. ### Allowed Directories By default, filesystem access is restricted to: * User's home directory * Common project directories (`~/projects`, `~/Documents`, `~/workspace`) * Directories explicitly added to Forge projects ### Blocked Paths The following paths are always blocked: * `/etc` - System configuration * `/var` - System variables * `/sys` - System files * `/proc` - Process information * Root filesystem access (requires explicit configuration) ### Configuration Customize allowed paths in Forge configuration: ```json theme={null} { "filesystem": { "allowedPaths": [ "/home/user/projects", "/workspace", "/custom/path" ], "blockedPaths": [ "/home/user/secrets", "/home/user/.ssh" ] } } ``` *** ## Error Responses ### Path Not Found ```json theme={null} { "success": false, "error": { "code": "PATH_NOT_FOUND", "message": "Path '/nonexistent/path' does not exist" } } ``` ### Access Denied ```json theme={null} { "success": false, "error": { "code": "ACCESS_DENIED", "message": "Access to path '/etc/passwd' is not allowed" } } ``` ### Not a Directory ```json theme={null} { "success": false, "error": { "code": "NOT_A_DIRECTORY", "message": "Path '/home/user/file.txt' is not a directory" } } ``` *** ## Next Steps Create projects from discovered repositories Configure allowed filesystem paths API fundamentals Security best practices # GitHub Integration Source: https://docs.namastex.ai/forge/api/github POST /api/task-attempts/:id/create-pr GitHub integration for PRs and repository management ## Overview Forge integrates with GitHub for authentication, pull request creation, and repository operations. **Base URL**: `http://localhost:8887/api/github` *** ## Authentication ### GitHub OAuth Device Flow Forge uses GitHub's device flow for authentication. #### Step 1: Initiate Device Flow ```http theme={null} POST /api/auth/github/device ``` **Response**: ```json theme={null} { "success": true, "data": { "device_code": "abc123...", "user_code": "ABCD-1234", "verification_uri": "https://github.com/login/device", "expires_in": 900, "interval": 5 } } ``` #### Step 2: Poll for Token ```http theme={null} POST /api/auth/github/device/poll ``` **Request**: ```json theme={null} { "device_code": "abc123..." } ``` **Response (pending)**: ```json theme={null} { "success": false, "error": "authorization_pending" } ``` **Response (success)**: ```json theme={null} { "success": true, "data": { "access_token": "gho_...", "token_type": "bearer", "scope": "repo,read:user" } } ``` *** ## Pull Requests ### Create Pull Request Create a GitHub PR from task attempt branch (covered in Attempts API). The task attempt ID ```http theme={null} POST /api/task-attempts/:id/create-pr ``` ```curl theme={null} curl -X POST http://localhost:8887/api/task-attempts/attempt_abc123/create-pr \ -H "Content-Type: application/json" \ -d '{ "title": "Add authentication system", "body": "Implements JWT authentication for the application", "baseBranch": "main", "draft": false }' ``` ```javascript theme={null} const response = await fetch('http://localhost:8887/api/task-attempts/attempt_abc123/create-pr', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ title: 'Add authentication system', body: 'Implements JWT authentication for the application', baseBranch: 'main', draft: false }) }); const data = await response.json(); console.log(`PR created: ${data.data.htmlUrl}`); ``` ```python theme={null} import requests response = requests.post( 'http://localhost:8887/api/task-attempts/attempt_abc123/create-pr', json={ 'title': 'Add authentication system', 'body': 'Implements JWT authentication for the application', 'baseBranch': 'main', 'draft': False } ) data = response.json() print(f"PR created: {data['data']['htmlUrl']}") ``` ```json Success theme={null} { "success": true, "data": { "number": 42, "title": "Add authentication system", "body": "Implements JWT authentication for the application", "state": "open", "author": "forge-bot", "createdAt": "2024-01-15T10:00:00Z", "htmlUrl": "https://github.com/owner/repo/pull/42", "head": "forge/task-abc123-attempt-1", "base": "main", "url": "https://api.github.com/repos/owner/repo/pulls/42" } } ``` ```json Error theme={null} { "success": false, "error": "github_auth_required", "message": "GitHub authentication is required. Please authenticate first." } ``` See [Attempts API - Create GitHub PR](/forge/api/attempts#create-github-pr) for details. *** ### Attach Existing PR Link an existing GitHub PR to a task attempt. The task attempt ID ```http theme={null} POST /api/task-attempts/:id/attach-pr ``` ```curl theme={null} curl -X POST http://localhost:8887/api/task-attempts/attempt_abc123/attach-pr \ -H "Content-Type: application/json" \ -d '{ "owner": "namastexlabs", "repo": "automagik-forge", "prNumber": 42 }' ``` ```javascript theme={null} const response = await fetch('http://localhost:8887/api/task-attempts/attempt_abc123/attach-pr', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ owner: 'namastexlabs', repo: 'automagik-forge', prNumber: 42 }) }); const data = await response.json(); console.log('PR attached successfully'); ``` ```python theme={null} import requests response = requests.post( 'http://localhost:8887/api/task-attempts/attempt_abc123/attach-pr', json={ 'owner': 'namastexlabs', 'repo': 'automagik-forge', 'prNumber': 42 } ) print('PR attached successfully') ``` ```json Success theme={null} { "success": true, "data": { "attemptId": "attempt_abc123", "prUrl": "https://github.com/namastexlabs/automagik-forge/pull/42", "prNumber": 42, "attachedAt": "2024-01-15T10:00:00Z" } } ``` ```json Error theme={null} { "success": false, "error": "pr_not_found", "message": "Pull request #42 not found in namastexlabs/automagik-forge" } ``` See [Attempts API - Attach Existing PR](/forge/api/attempts#attach-existing-pr) for details. *** ## Repository Operations ### Get Repository Info Get information about the project's GitHub repository. The project ID ```http theme={null} GET /api/projects/:id/github/repository ``` ```curl theme={null} curl -X GET http://localhost:8887/api/projects/proj_abc123/github/repository ``` ```javascript theme={null} const response = await fetch('http://localhost:8887/api/projects/proj_abc123/github/repository'); const data = await response.json(); console.log(`Repository: ${data.data.fullName}`); console.log(`Default branch: ${data.data.defaultBranch}`); ``` ```python theme={null} import requests response = requests.get('http://localhost:8887/api/projects/proj_abc123/github/repository') data = response.json() print(f"Repository: {data['data']['fullName']}") print(f"Default branch: {data['data']['defaultBranch']}") ``` ```json Success theme={null} { "success": true, "data": { "owner": "namastexlabs", "repo": "automagik-forge", "fullName": "namastexlabs/automagik-forge", "defaultBranch": "main", "private": false, "htmlUrl": "https://github.com/namastexlabs/automagik-forge", "cloneUrl": "https://github.com/namastexlabs/automagik-forge.git" } } ``` ```json Error theme={null} { "success": false, "error": "project_not_found", "message": "Project proj_abc123 not found" } ``` *** ### List Pull Requests List pull requests for a project. The project ID Filter by PR state: `open`, `closed`, or `all` Page number for pagination Items per page (max 100) ```http theme={null} GET /api/projects/:id/github/pulls ``` ```curl theme={null} curl -X GET "http://localhost:8887/api/projects/proj_abc123/github/pulls?state=open&limit=10" ``` ```javascript theme={null} const response = await fetch( 'http://localhost:8887/api/projects/proj_abc123/github/pulls?state=open&limit=10' ); const data = await response.json(); data.data.forEach(pr => { console.log(`PR #${pr.number}: ${pr.title} (${pr.state})`); console.log(` Author: ${pr.author}`); console.log(` Created: ${pr.createdAt}`); }); ``` ```python theme={null} import requests response = requests.get( 'http://localhost:8887/api/projects/proj_abc123/github/pulls', params={ 'state': 'open', 'limit': 10 } ) data = response.json() for pr in data['data']: print(f"PR #{pr['number']}: {pr['title']} ({pr['state']})") print(f" Author: {pr['author']}") print(f" Created: {pr['createdAt']}") ``` ```json Success theme={null} { "success": true, "data": [ { "number": 42, "title": "Add authentication system", "state": "open", "author": "user", "createdAt": "2024-01-15T10:00:00Z", "htmlUrl": "https://github.com/owner/repo/pull/42", "head": "forge/task-abc123-attempt-1", "base": "main" }, { "number": 41, "title": "Fix database connection", "state": "open", "author": "bot", "createdAt": "2024-01-14T15:30:00Z", "htmlUrl": "https://github.com/owner/repo/pull/41", "head": "forge/task-xyz789-attempt-2", "base": "main" } ] } ``` ```json Error theme={null} { "success": false, "error": "project_not_found", "message": "Project proj_abc123 not found" } ``` *** ## Webhooks ### Configure Webhook Set up GitHub webhook to receive events. The project ID Array of events to subscribe to: `pull_request`, `push`, `issue_comment`, `pull_request_review` The webhook endpoint URL to receive GitHub events ```http theme={null} POST /api/projects/:id/github/webhook ``` ```curl theme={null} curl -X POST http://localhost:8887/api/projects/proj_abc123/github/webhook \ -H "Content-Type: application/json" \ -d '{ "events": ["pull_request", "push", "issue_comment"], "url": "https://forge.yourdomain.com/webhooks/github" }' ``` ```javascript theme={null} const response = await fetch('http://localhost:8887/api/projects/proj_abc123/github/webhook', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ events: ['pull_request', 'push', 'issue_comment'], url: 'https://forge.yourdomain.com/webhooks/github' }) }); const data = await response.json(); if (data.success) { console.log('Webhook configured successfully'); } ``` ```python theme={null} import requests response = requests.post( 'http://localhost:8887/api/projects/proj_abc123/github/webhook', json={ 'events': ['pull_request', 'push', 'issue_comment'], 'url': 'https://forge.yourdomain.com/webhooks/github' } ) data = response.json() if data['success']: print('Webhook configured successfully') ``` ```json Success theme={null} { "success": true, "data": { "webhookId": "webhook_abc123", "url": "https://forge.yourdomain.com/webhooks/github", "events": ["pull_request", "push", "issue_comment"], "active": true, "createdAt": "2024-01-15T10:00:00Z" } } ``` ```json Error theme={null} { "success": false, "error": "invalid_webhook_url", "message": "Webhook URL is not accessible or invalid" } ``` **Supported Events**: * `pull_request` - PR opened, closed, merged * `push` - Commits pushed * `issue_comment` - Comments on issues/PRs * `pull_request_review` - PR reviews *** ## SDK Examples ```typescript theme={null} import { ForgeClient } from '@automagik/forge-sdk'; const forge = new ForgeClient(); // Authenticate with GitHub const deviceFlow = await forge.auth.github.initiateDeviceFlow(); console.log(`Visit: ${deviceFlow.verification_uri}`); console.log(`Enter code: ${deviceFlow.user_code}`); // Poll for token const token = await forge.auth.github.pollForToken(deviceFlow.device_code); // Create PR from attempt const pr = await forge.attempts.createPR('attempt_123', { title: 'Add authentication', body: 'Implements JWT auth', baseBranch: 'main', draft: false }); console.log(`PR created: ${pr.url}`); // List PRs const prs = await forge.projects.listPRs('proj_123', { state: 'open' }); ``` *** ## Next Steps Create PRs from task attempts Configure GitHub OAuth # MCP Tools Source: https://docs.namastex.ai/forge/api/mcp-tools Control Forge from AI coding agents via MCP ## Overview Forge's Model Context Protocol (MCP) server enables AI coding agents to programmatically manage tasks. Control your Forge instance directly from Claude Code, Cursor, or any MCP-compatible agent. MCP Tools allow bidirectional communication between your AI agent and Forge! *** ## Available Tools ### list\_projects Get all Forge projects. **Parameters**: None **Returns**: Array of projects **Example**: ``` You: "Show me all my Forge projects" Claude: [Uses list_projects tool] Projects: 1. my-web-app (42 tasks) 2. mobile-app (18 tasks) 3. api-backend (35 tasks) ``` *** ### list\_tasks Get tasks with optional filtering. **Parameters**: * `projectId` (optional): Filter by project * `status` (optional): Filter by status * `limit` (optional): Number of tasks to return **Returns**: Array of tasks **Example**: ``` You: "Show me all high-priority tasks" Claude: [Uses list_tasks tool with filters] High Priority Tasks: 1. #42 - Add user authentication (pending) 2. #38 - Fix security vulnerability (in_progress) 3. #35 - Optimize database queries (review) ``` *** ### create\_task Create a new task in Forge. **Parameters**: * `projectId` (required): Project ID * `title` (required): Task title * `description` (optional): Task description * `priority` (optional): low, medium, high, critical * `labels` (optional): Array of labels **Returns**: Created task object **Example**: ``` You: "Create a task to add dark mode with LocalStorage persistence" Claude: [Uses create_task tool] Task #43 created: "Add dark mode toggle" - Priority: medium - Labels: feature, ui - Status: pending Ready to start this task? ``` *** ### get\_task Get detailed information about a task. **Parameters**: * `taskId` (required): Task ID **Returns**: Task object with attempts **Example**: ``` You: "Show me details for task #42" Claude: [Uses get_task tool] Task #42: Add user authentication - Status: completed - Created: 2024-01-15 - Attempts: 2 - Attempt 1 (claude): completed, $0.23 - Attempt 2 (gemini): completed, $0.00 - Winner: Attempt 1 (better error handling) ``` *** ### update\_task Update task properties. **Parameters**: * `taskId` (required): Task ID * `title` (optional): New title * `description` (optional): New description * `status` (optional): New status * `priority` (optional): New priority **Returns**: Updated task object **Example**: ``` You: "Mark task #42 as high priority and move to review" Claude: [Uses update_task tool] Task #42 updated: - Priority: high ← Changed - Status: review ← Changed ``` *** ### delete\_task Delete a task. **Parameters**: * `taskId` (required): Task ID **Returns**: Deletion confirmation **Example**: ``` You: "Delete task #35, it's no longer needed" Claude: [Uses delete_task tool] Task #35 "Old feature" deleted successfully. All associated attempts and worktrees have been cleaned up. ``` *** ## Setup Instructions ### Claude Code Add to your MCP configuration: ```json theme={null} { "mcpServers": { "automagik-forge": { "command": "npx", "args": ["automagik-forge", "--mcp"], "env": { "PROJECT_ID": "your-project-uuid" } } } } ``` See [Claude Code Setup](/forge/mcp/claude-code-setup) for details. ### Cursor Add to Cursor settings: ```json theme={null} { "mcp.servers": { "automagik-forge": { "command": "npx", "args": ["automagik-forge", "--mcp"], "projectId": "your-project-uuid" } } } ``` See [Cursor Setup](/forge/mcp/cursor-setup) for details. *** ## Usage Examples ### Planning Phase ``` You: "Help me plan a user authentication system" Claude: Let me help you break this down into tasks using Forge. [Uses create_task multiple times] I've created 5 tasks in Forge: 1. #44 - Design authentication schema 2. #45 - Implement JWT generation 3. #46 - Add login/signup endpoints 4. #47 - Create auth middleware 5. #48 - Write integration tests Ready to start with task #44? ``` ### Bug Discovery ``` You: "I found a bug in the payment processing" Claude: Let me create a bug report in Forge. [Uses create_task] Bug task #49 created: - Title: "Fix payment processing error" - Description: [Captured from conversation] - Priority: high - Labels: bug, payment, urgent I'll also add reproduction steps from our conversation. ``` ### Status Updates ``` You: "What's the status of all my auth tasks?" Claude: [Uses list_tasks with filter] Authentication Tasks: - #44: Design schema ✅ completed - #45: JWT generation 🔄 in_progress - #46: Endpoints ⏳ pending - #47: Middleware ⏳ pending - #48: Tests ⏳ pending Currently working on JWT generation. ETA: 5 minutes. ``` *** ## Advanced Mode Enable advanced mode for access to **56 total tools**: ```json theme={null} { "mcpServers": { "automagik-forge": { "command": "npx", "args": ["automagik-forge", "--mcp-advanced"], "env": { "PROJECT_ID": "your-project-uuid" } } } } ``` **Additional tools in advanced mode**: * Attempt management * Process control * Worktree operations * Draft management * Container operations * Filesystem access * Omni integration *** ## Best Practices Use natural language - the AI handles tool calls: ``` "Create a high-priority task for adding tests" ``` Not: ``` "Use create_task with priority=high" ``` Let the AI break down work: ``` "Help me implement a payment system" ``` AI will create multiple tasks automatically Update tasks conversationally: ``` "That auth task is done, mark it complete" ``` AI uses update\_task for you AI maintains context: ``` You: "Create a task for dark mode" AI: [Creates task #50] You: "Actually make it high priority" AI: [Updates task #50 automatically] ``` *** ## Troubleshooting **Issue**: AI says "I don't have access to Forge" **Solutions**: * Verify Forge is running: `forge start` * Check MCP configuration is correct * Restart your AI agent * Check PROJECT\_ID is set **Error**: "Project not found" **Solution**: 1. Open Forge UI: [http://localhost:3000](http://localhost:3000) 2. Select or create project 3. Copy PROJECT\_ID from URL: ``` http://localhost:3000/projects/{PROJECT_ID}/tasks ``` 4. Update MCP config with correct ID **Issue**: Tools return errors **Solutions**: * Check Forge backend is running on port 8080 * Verify firewall allows localhost connections * Check Forge logs: `forge logs` * Try basic mode instead of advanced *** ## Programmatic Access ### Via SDK ```typescript theme={null} import { ForgeMCPClient } from '@automagik/forge-mcp'; const mcp = new ForgeMCPClient({ projectId: 'your-project-uuid' }); // Use MCP tools programmatically const tasks = await mcp.listTasks({ status: 'pending', priority: 'high' }); const newTask = await mcp.createTask({ title: 'Add feature', description: 'Feature description', priority: 'medium' }); ``` *** ## Next Steps Complete MCP integration guide Configure Claude Code Direct API access MCP-powered workflows # Processes Source: https://docs.namastex.ai/forge/api/processes GET /api/processes Monitor and control running processes ## Overview Processes represent the actual execution of attempts. Monitor running AI agents, check resource usage, and control execution. **Base URL**: `http://localhost:8887/api/processes` *** ## List Processes Get all active processes. ```http theme={null} GET /api/processes ``` ### Query Parameters | Parameter | Type | Description | | --------- | ------ | --------------------------------------------- | | `status` | enum | Filter by status (running, completed, failed) | | `llm` | string | Filter by AI agent | ```bash cURL theme={null} curl http://localhost:8887/api/processes?status=running ``` ```javascript JavaScript theme={null} const response = await fetch('http://localhost:8887/api/processes?status=running'); const data = await response.json(); ``` ```python Python theme={null} import requests response = requests.get('http://localhost:8887/api/processes?status=running') data = response.json() ``` ```json 200 Success theme={null} { "success": true, "data": [ { "id": "proc_abc123", "attemptId": "attempt_xyz789", "taskId": "task_def456", "llm": "claude", "status": "running", "startedAt": "2024-01-15T10:30:00Z", "duration": 45000, "resources": { "cpuUsage": 45.2, "memoryUsage": 512000000, "diskIO": 1024000 }, "progress": { "current": "Generating authentication logic", "percentage": 65 } } ] } ``` ```json 401 Unauthorized theme={null} { "success": false, "error": { "code": "UNAUTHORIZED", "message": "Authentication required" } } ``` *** ## Get Process Get detailed process information. ```http theme={null} GET /api/processes/:id ``` ### Example Response ```json theme={null} { "success": true, "data": { "id": "proc_abc123", "attemptId": "attempt_xyz789", "taskId": "task_def456", "llm": "claude", "model": "claude-3-5-sonnet-20241022", "status": "running", "startedAt": "2024-01-15T10:30:00Z", "duration": 45000, "resources": { "cpuUsage": 45.2, "memoryUsage": 512000000, "diskIO": 1024000, "networkIO": 204800 }, "progress": { "stage": "code_generation", "current": "Generating authentication logic", "percentage": 65, "estimatedRemaining": 25000 }, "tokens": { "inputTokens": 8420, "outputTokens": 1250, "estimatedCost": 0.12 } } } ``` *** ## Cancel Process Stop a running process. ```http theme={null} POST /api/processes/:id/cancel ``` ```bash cURL theme={null} curl -X POST http://localhost:8887/api/processes/proc_abc123/cancel ``` ```javascript JavaScript theme={null} const response = await fetch('http://localhost:8887/api/processes/proc_abc123/cancel', { method: 'POST' }); const data = await response.json(); ``` ```python Python theme={null} import requests response = requests.post( 'http://localhost:8887/api/processes/proc_abc123/cancel', json={...} ) data = response.json() ``` ```json 200 Success theme={null} { "success": true, "data": { "id": "proc_abc123", "status": "cancelled", "cancelledAt": "2024-01-15T10:32:00Z" } } ``` ```json 401 Unauthorized theme={null} { "success": false, "error": { "code": "UNAUTHORIZED", "message": "Authentication required" } } ``` *** ## Get Process Logs Stream real-time logs from a process. ```http theme={null} GET /api/processes/:id/logs ``` ### Query Parameters | Parameter | Type | Description | | --------- | ------- | ------------------------------ | | `follow` | boolean | Stream logs in real-time | | `tail` | integer | Number of recent lines to show | ```bash cURL theme={null} curl "http://localhost:8887/api/processes/proc_abc123/logs?follow=true" ``` *** ## Get Process Metrics Get resource usage metrics. ```http theme={null} GET /api/processes/:id/metrics ``` ```javascript JavaScript theme={null} const response = await fetch('http://localhost:8887/api/processes/proc_abc123/logs?follow=true'); const data = await response.json(); ``` ```python Python theme={null} import requests response = requests.get('http://localhost:8887/api/processes/proc_abc123/logs?follow=true') data = response.json() ``` ```json 200 Success theme={null} { "success": true, "data": { "processId": "proc_abc123", "metrics": [ { "timestamp": "2024-01-15T10:30:00Z", "cpu": 45.2, "memory": 512000000, "diskIO": 1024000, "networkIO": 204800 }, { "timestamp": "2024-01-15T10:30:01Z", "cpu": 48.5, "memory": 524000000, "diskIO": 1126400, "networkIO": 225280 } ], "averages": { "cpu": 46.8, "memory": 518000000 } } } ``` ```json 401 Unauthorized theme={null} { "success": false, "error": { "code": "UNAUTHORIZED", "message": "Authentication required" } } ``` *** ## Stop Process Stop a running execution process. ```http theme={null} POST /api/execution-processes/:id/stop ``` ### Example Response ```json theme={null} { "success": true, "data": { "id": "proc_abc123", "status": "stopped", "stoppedAt": "2024-01-15T10:35:00Z", "duration": 300000 } } ``` *** ## WebSocket: Stream Process Logs Stream real-time process logs via WebSocket. ### Raw Logs Stream ``` ws://localhost:8887/ws/execution-processes/:id/logs/raw ``` Streams raw, unprocessed log output from the execution process. **Example**: ```javascript theme={null} const ws = new WebSocket('ws://localhost:8887/ws/execution-processes/proc_abc123/logs/raw'); ws.onmessage = (event) => { console.log('Raw log:', event.data); }; ws.onerror = (error) => { console.error('WebSocket error:', error); }; ``` ### Normalized Logs Stream ``` ws://localhost:8887/ws/execution-processes/:id/logs/normalized ``` Streams processed, structured log messages. **Example**: ```javascript theme={null} const ws = new WebSocket('ws://localhost:8887/ws/execution-processes/proc_abc123/logs/normalized'); ws.onmessage = (event) => { const log = JSON.parse(event.data); // { level: 'info', message: '...', timestamp: '...', source: 'executor' } console.log(`[${log.level}] ${log.message}`); }; ``` **Message Format**: ```json theme={null} { "level": "info", "message": "Generating authentication logic", "timestamp": "2024-01-15T10:30:45Z", "source": "executor", "metadata": { "file": "src/auth.ts", "action": "code_generation" } } ``` *** ## WebSocket: Stream All Processes Monitor all execution processes in real-time. ``` ws://localhost:8887/ws/execution-processes ``` Receives updates when any process status changes. **Example**: ```javascript theme={null} const ws = new WebSocket('ws://localhost:8887/ws/execution-processes'); ws.onmessage = (event) => { const update = JSON.parse(event.data); // { type: 'process_started', processId: '...', ... } // { type: 'process_completed', processId: '...', ... } // { type: 'process_failed', processId: '...', error: '...' } console.log('Process update:', update); }; ``` **Event Types**: * `process_started` - New process began execution * `process_progress` - Progress update * `process_completed` - Process finished successfully * `process_failed` - Process encountered error * `process_stopped` - Process was stopped by user *** ## SDK Examples ```typescript theme={null} import { ForgeClient } from '@automagik/forge-sdk'; const forge = new ForgeClient(); // List running processes const processes = await forge.processes.list({ status: 'running' }); // Get process details const process = await forge.processes.get('proc_abc123'); // Stop a process await forge.processes.stop('proc_abc123'); // Monitor progress const interval = setInterval(async () => { const proc = await forge.processes.get('proc_abc123'); console.log(`Progress: ${proc.progress.percentage}%`); if (proc.status !== 'running') { clearInterval(interval); } }, 1000); // Stream raw logs via WebSocket const rawWs = new WebSocket('ws://localhost:8887/ws/execution-processes/proc_abc123/logs/raw'); rawWs.onmessage = (event) => console.log('Raw:', event.data); // Stream normalized logs via WebSocket const normalizedWs = new WebSocket('ws://localhost:8887/ws/execution-processes/proc_abc123/logs/normalized'); normalizedWs.onmessage = (event) => { const log = JSON.parse(event.data); console.log(`[${log.level}] ${log.message}`); }; // Monitor all processes const allProcessesWs = new WebSocket('ws://localhost:8887/ws/execution-processes'); allProcessesWs.onmessage = (event) => { const update = JSON.parse(event.data); console.log(`Process ${update.type}:`, update.processId); }; ``` *** ## Next Steps Manage task attempts Create and manage tasks # Projects Source: https://docs.namastex.ai/forge/api/projects GET /api/projects Manage Forge projects via REST API ## Overview Projects are the top-level organizational unit in Forge. Each project contains tasks, attempts, and configuration. **Base URL**: `http://localhost:8887/api/projects` *** ## List Projects ```bash cURL theme={null} curl http://localhost:8887/api/projects?page=1&limit=10 ``` ```javascript JavaScript theme={null} const response = await fetch('http://localhost:8887/api/projects?page=1&limit=10'); const data = await response.json(); console.log(data); ``` ```python Python theme={null} import requests response = requests.get( 'http://localhost:8887/api/projects', params={'page': 1, 'limit': 10} ) projects = response.json() ``` ```json 200 Success theme={null} { "success": true, "data": [ { "id": "proj_abc123", "name": "My Web App", "description": "E-commerce platform", "git_repo_path": "/home/user/projects/my-web-app", "setup_script": "npm install", "dev_script": "npm run dev", "createdAt": "2024-01-15T10:30:00Z", "updatedAt": "2024-01-15T15:45:00Z" } ] } ``` ```json 401 Unauthorized theme={null} { "success": false, "error": { "code": "UNAUTHORIZED", "message": "Authentication required" } } ``` *** ## Get Project Retrieve a specific project by ID. ```http theme={null} GET /api/projects/:id ``` ### Example Request ```bash theme={null} curl http://localhost:8887/api/projects/proj_abc123 ``` ### Example Response ```json theme={null} { "success": true, "data": { "id": "proj_abc123", "name": "My Web App", "description": "E-commerce platform", "repository": { "url": "https://github.com/user/repo", "branch": "main", "lastSync": "2024-01-15T15:45:00Z" }, "defaultLLM": "claude", "config": { "worktrees": { "enabled": true, "basePath": "./.forge/worktrees" }, "llms": { "claude": { "model": "claude-3-5-sonnet-20241022" } } }, "createdAt": "2024-01-15T10:30:00Z", "updatedAt": "2024-01-15T15:45:00Z", "stats": { "tasks": 42, "completedTasks": 38, "inProgressTasks": 3, "failedTasks": 1, "activeAttempts": 2, "totalCost": 12.45 } } } ``` *** ## Create Project Create a new Forge project. Project name Project description Repository configuration * `url` (string, required): GitHub repository URL * `branch` (string): Branch name (default: "main") Default AI agent (claude, gemini, gpt-4, etc.) ```bash cURL theme={null} curl -X POST http://localhost:8887/api/projects \ -H "Content-Type: application/json" \ -d '{ "name": "My New Project", "repository": { "url": "https://github.com/user/repo" }, "defaultLLM": "claude" }' ``` ```javascript JavaScript theme={null} const response = await fetch('http://localhost:8887/api/projects', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name: 'My New Project', repository: { url: 'https://github.com/user/repo' }, defaultLLM: 'claude' }) }); const project = await response.json(); ``` ```python Python theme={null} import requests response = requests.post('http://localhost:8887/api/projects', json={ 'name': 'My New Project', 'repository': { 'url': 'https://github.com/user/repo' }, 'defaultLLM': 'claude' }) project = response.json() ``` ### Response ```json 201 Created theme={null} { "success": true, "data": { "id": "proj_xyz789", "name": "My New Project", "repository": { "url": "https://github.com/user/repo", "branch": "main" }, "defaultLLM": "claude", "createdAt": "2024-01-15T16:00:00Z", "updatedAt": "2024-01-15T16:00:00Z" } } ``` ```json 400 Bad Request theme={null} { "success": false, "error": { "code": "VALIDATION_ERROR", "message": "Invalid project data", "details": { "name": "Project name is required", "repository.url": "Invalid repository URL" } } } ``` ```json 409 Conflict theme={null} { "success": false, "error": { "code": "PROJECT_EXISTS", "message": "Project with name 'My New Project' already exists" } } ``` *** ## Update Project Update project properties. ```http theme={null} PATCH /api/projects/:id ``` ### Request Body ```json theme={null} { "name": "Updated Project Name", "description": "New description", "defaultLLM": "gemini" } ``` ### Example Request ```bash theme={null} curl -X PATCH http://localhost:8887/api/projects/proj_abc123 \ -H "Content-Type: application/json" \ -d '{ "name": "Updated Project Name", "defaultLLM": "gemini" }' ``` ### Example Response ```json theme={null} { "success": true, "data": { "id": "proj_abc123", "name": "Updated Project Name", "defaultLLM": "gemini", "updatedAt": "2024-01-15T16:05:00Z" } } ``` *** ## Delete Project Delete a project and all associated data. ```http theme={null} DELETE /api/projects/:id ``` This permanently deletes the project, all tasks, attempts, and associated data. This action cannot be undone. ### Example Request ```bash theme={null} curl -X DELETE http://localhost:8887/api/projects/proj_abc123 ``` ### Example Response ```json theme={null} { "success": true, "data": { "id": "proj_abc123", "deleted": true, "deletedAt": "2024-01-15T16:10:00Z" } } ``` *** ## Get Project Tasks Get all tasks for a specific project. ```http theme={null} GET /api/projects/:id/tasks ``` ### Query Parameters Same as [Tasks API](/forge/api/tasks) list parameters. ### Example Request ```bash theme={null} curl http://localhost:8887/api/projects/proj_abc123/tasks?status=in_progress ``` *** ## Get Project Stats Get detailed statistics for a project. ```http theme={null} GET /api/projects/:id/stats ``` ### Example Response ```json theme={null} { "success": true, "data": { "tasks": { "total": 42, "pending": 3, "inProgress": 2, "completed": 36, "failed": 1 }, "attempts": { "total": 67, "successful": 58, "failed": 9 }, "costs": { "total": 12.45, "byLLM": { "claude": 8.23, "gemini": 0.00, "gpt-4": 4.22 } }, "performance": { "averageTaskDuration": 285000, "successRate": 0.86, "averageCostPerTask": 0.30 } } } ``` *** ## SDK Examples ### JavaScript/TypeScript ```typescript theme={null} import { ForgeClient } from '@automagik/forge-sdk'; const forge = new ForgeClient(); // List projects const projects = await forge.projects.list({ page: 1, limit: 10 }); // Get project const project = await forge.projects.get('proj_abc123'); // Create project const newProject = await forge.projects.create({ name: 'My New Project', repository: { url: 'https://github.com/user/repo' }, defaultLLM: 'claude' }); // Update project await forge.projects.update('proj_abc123', { name: 'Updated Name', defaultLLM: 'gemini' }); // Delete project await forge.projects.delete('proj_abc123'); // Get project stats const stats = await forge.projects.stats('proj_abc123'); ``` ### Python ```python theme={null} from automagik_forge import ForgeClient forge = ForgeClient() # List projects projects = forge.projects.list(page=1, limit=10) # Get project project = forge.projects.get('proj_abc123') # Create project new_project = forge.projects.create( name='My New Project', repository={'url': 'https://github.com/user/repo'}, default_llm='claude' ) # Update project forge.projects.update('proj_abc123', { 'name': 'Updated Name', 'default_llm': 'gemini' }) # Delete project forge.projects.delete('proj_abc123') # Get stats stats = forge.projects.stats('proj_abc123') ``` *** ## Get Project Branches List all git branches for a project. ```http theme={null} GET /api/projects/:id/branches ``` ### Example Response ```json theme={null} { "success": true, "data": { "currentBranch": "main", "branches": [ { "name": "main", "commit": "abc123def456", "isCurrent": true, "isDefault": true, "lastCommit": { "hash": "abc123def456", "message": "Add authentication", "author": "John Doe", "date": "2024-01-15T10:00:00Z" } }, { "name": "develop", "commit": "def456ghi789", "isCurrent": false, "isDefault": false, "lastCommit": { "hash": "def456ghi789", "message": "Work in progress", "author": "Jane Smith", "date": "2024-01-14T15:30:00Z" } }, { "name": "forge/task-abc123-attempt-1", "commit": "ghi789jkl012", "isCurrent": false, "isDefault": false, "isForgeWorktree": true, "taskId": "abc123", "attemptId": "attempt-1", "lastCommit": { "hash": "ghi789jkl012", "message": "Add user authentication (automagik-forge abc1)", "author": "Claude AI", "date": "2024-01-15T11:00:00Z" } } ], "forgeBranches": [ { "name": "forge/task-abc123-attempt-1", "taskId": "abc123", "attemptId": "attempt-1" } ] } } ``` ### Response Fields | Field | Type | Description | | ---------------------------- | ------- | ------------------------------------------- | | `currentBranch` | string | Currently checked out branch | | `branches` | array | All branches in repository | | `branches[].name` | string | Branch name | | `branches[].commit` | string | Latest commit hash | | `branches[].isCurrent` | boolean | Currently checked out | | `branches[].isDefault` | boolean | Default branch (main/master) | | `branches[].isForgeWorktree` | boolean | Created by Forge for task attempt | | `branches[].taskId` | string | Associated task ID (Forge branches only) | | `branches[].attemptId` | string | Associated attempt ID (Forge branches only) | | `forgeBranches` | array | Filtered list of Forge-created branches | ### Use Cases * List available target branches for merging * Identify Forge worktree branches * Check current repository state * Find branches associated with specific tasks *** ## Error Responses ### Project Not Found ```json theme={null} { "success": false, "error": { "code": "PROJECT_NOT_FOUND", "message": "Project with id 'proj_abc123' not found" } } ``` ### Validation Error ```json theme={null} { "success": false, "error": { "code": "VALIDATION_ERROR", "message": "Invalid project data", "details": { "name": "Project name is required", "repository.url": "Invalid repository URL" } } } ``` ### Conflict Error ```json theme={null} { "success": false, "error": { "code": "PROJECT_EXISTS", "message": "Project with name 'My Project' already exists" } } ``` *** ## Next Steps Manage tasks within projects Execute tasks with AI agents API fundamentals and authentication # REST Overview Source: https://docs.namastex.ai/forge/api/rest-overview GET /api/tasks Complete reference for Forge's REST API ## Overview Forge provides a comprehensive REST API for programmatic access to all features. Build integrations, automate workflows, or create custom tooling. **Base URL**: `http://localhost:8887/api` (default) *** ## Authentication ### API Keys (Coming Soon) Currently, Forge runs locally without authentication. API key authentication will be added for remote deployments. ```bash theme={null} # Future API key usage curl -H "Authorization: Bearer YOUR_API_KEY" \ http://localhost:8887/api/projects ``` ### GitHub OAuth For web UI access, GitHub OAuth is used. API access uses session cookies. *** ## Base URL ```bash theme={null} # Local development (default) BASE_URL=http://localhost:8887 # Custom port (if configured) BASE_URL=http://localhost:9000 # Remote deployment BASE_URL=https://forge.yourdomain.com ``` *** ## Response Format ### Success Response ```json theme={null} { "success": true, "data": { // Response data }, "meta": { "timestamp": "2024-01-15T10:30:00Z", "version": "0.4.4" } } ``` ### Error Response ```json theme={null} { "success": false, "error": { "code": "TASK_NOT_FOUND", "message": "Task with id 'abc123' not found", "details": {} }, "meta": { "timestamp": "2024-01-15T10:30:00Z" } } ``` *** ## Error Codes | Code | HTTP Status | Description | | ------------------ | ----------- | -------------------------- | | `VALIDATION_ERROR` | 400 | Invalid request parameters | | `UNAUTHORIZED` | 401 | Authentication required | | `FORBIDDEN` | 403 | Insufficient permissions | | `NOT_FOUND` | 404 | Resource not found | | `CONFLICT` | 409 | Resource conflict | | `RATE_LIMIT` | 429 | Too many requests | | `INTERNAL_ERROR` | 500 | Server error | *** ## Pagination List endpoints support pagination: ```bash theme={null} GET /api/tasks?page=1&limit=20 ``` **Response**: ```json theme={null} { "success": true, "data": [...], "pagination": { "page": 1, "limit": 20, "total": 156, "pages": 8, "hasNext": true, "hasPrev": false } } ``` **Parameters**: * `page`: Page number (1-indexed) * `limit`: Items per page (max: 100) *** ## Filtering & Sorting ### Filtering ```bash theme={null} # Filter by status GET /api/tasks?status=in_progress # Multiple filters GET /api/tasks?status=pending&priority=high # Filter by label GET /api/tasks?labels=feature,backend ``` ### Sorting ```bash theme={null} # Sort by created date (descending) GET /api/tasks?sort=-created_at # Sort by priority (ascending) GET /api/tasks?sort=priority # Multiple sort fields GET /api/tasks?sort=-priority,created_at ``` **Sort prefix**: * `-` = Descending * No prefix = Ascending *** ## API Endpoints ### Core Resources Manage Forge projects * `GET /api/projects` * `POST /api/projects` * `GET /api/projects/:id` * `PATCH /api/projects/:id` * `DELETE /api/projects/:id` Manage tasks and workflows * `GET /api/tasks` * `POST /api/tasks` * `GET /api/tasks/:id` * `PATCH /api/tasks/:id` * `DELETE /api/tasks/:id` Manage task attempts * `GET /api/attempts` * `POST /api/attempts` * `GET /api/attempts/:id` * `DELETE /api/attempts/:id` Monitor running processes * `GET /api/processes` * `GET /api/processes/:id` * `POST /api/processes/:id/cancel` *** ## Quick Examples ### Get All Tasks ```bash theme={null} curl http://localhost:8887/api/tasks ``` ### Create New Task ```bash theme={null} curl -X POST http://localhost:8887/api/tasks \ -H "Content-Type: application/json" \ -d '{ "title": "Add user authentication", "description": "Implement JWT-based auth", "projectId": "project-123", "llm": "claude", "priority": "high", "labels": ["feature", "backend"] }' ``` ### Update Task Status ```bash theme={null} curl -X PATCH http://localhost:8887/api/tasks/task-123 \ -H "Content-Type: application/json" \ -d '{ "status": "in_progress" }' ``` ### Start Task Attempt ```bash theme={null} curl -X POST http://localhost:8887/api/attempts \ -H "Content-Type: application/json" \ -d '{ "taskId": "task-123", "llm": "claude", "options": {} }' ``` *** ## Rate Limiting Current limits (local deployment): ``` No rate limits for local usage ``` Future limits (remote deployment): ``` - 60 requests per minute per IP - 1000 requests per hour per user ``` **Rate limit headers**: ``` X-RateLimit-Limit: 60 X-RateLimit-Remaining: 45 X-RateLimit-Reset: 1642248000 ``` *** ## Webhooks Subscribe to Forge events: ```bash theme={null} POST /api/webhooks { "url": "https://your-server.com/webhook", "events": ["task.created", "task.completed", "attempt.failed"], "secret": "your-webhook-secret" } ``` **Webhook payload**: ```json theme={null} { "event": "task.completed", "timestamp": "2024-01-15T10:30:00Z", "data": { "taskId": "task-123", "status": "completed", "duration": 322000 }, "signature": "sha256=abc123..." } ``` *** ## WebSocket API Real-time updates via WebSocket: ```javascript theme={null} const ws = new WebSocket('ws://localhost:8887/ws'); ws.onopen = () => { // Subscribe to task updates ws.send(JSON.stringify({ type: 'subscribe', channel: 'tasks', taskId: 'task-123' })); }; ws.onmessage = (event) => { const update = JSON.parse(event.data); console.log('Task update:', update); }; ``` **Update messages**: ```json theme={null} { "type": "task.status_changed", "taskId": "task-123", "status": "in_progress", "timestamp": "2024-01-15T10:30:00Z" } ``` *** ## SDK Libraries ### JavaScript/TypeScript ```bash theme={null} npm install @automagik/forge-sdk ``` ```typescript theme={null} import { ForgeClient } from '@automagik/forge-sdk'; const forge = new ForgeClient({ baseUrl: 'http://localhost:8887' }); // Create task const task = await forge.tasks.create({ title: 'Add authentication', projectId: 'project-123', llm: 'claude' }); // Start attempt const attempt = await forge.attempts.create({ taskId: task.id, llm: 'claude' }); ``` ### Python ```bash theme={null} pip install automagik-forge ``` ```python theme={null} from automagik_forge import ForgeClient forge = ForgeClient(base_url='http://localhost:8887') # Create task task = forge.tasks.create( title='Add authentication', project_id='project-123', llm='claude' ) # Start attempt attempt = forge.attempts.create( task_id=task.id, llm='claude' ) ``` *** ## API Versioning Current version: **v1** (implicit) Future versioning: ```bash theme={null} # Explicit version in URL GET /api/v1/tasks # Or via header GET /api/tasks Accept: application/vnd.forge.v1+json ``` *** ## OpenAPI Specification Download the full OpenAPI spec: ```bash theme={null} # JSON format curl http://localhost:8887/api/openapi.json > forge-api.json # YAML format curl http://localhost:8887/api/openapi.yaml > forge-api.yaml ``` Import into tools like: * Postman * Insomnia * Swagger UI * API clients *** ## Testing the API ### Using cURL ```bash theme={null} # Set base URL BASE=http://localhost:8887/api # Get all tasks curl $BASE/tasks # Create task curl -X POST $BASE/tasks \ -H "Content-Type: application/json" \ -d @task.json # Pretty print JSON curl $BASE/tasks | jq ``` ### Using HTTPie ```bash theme={null} # Install HTTPie brew install httpie # Get tasks (cleaner syntax) http localhost:8887/api/tasks # Create task http POST localhost:8887/api/tasks \ title="Add feature" \ projectId="project-123" \ llm="claude" ``` ### Using Postman 1. Import OpenAPI spec: `http://localhost:8887/api/openapi.json` 2. Set environment variable: `baseUrl = http://localhost:8887` 3. Start making requests *** ## Best Practices Use official SDKs instead of raw HTTP: ```typescript theme={null} // Good ✅ forge.tasks.create({...}) // Avoid ❌ fetch('/api/tasks', {...}) ``` SDKs handle auth, retries, typing ```typescript theme={null} try { const task = await forge.tasks.create({...}); } catch (error) { if (error.code === 'VALIDATION_ERROR') { // Handle validation } else if (error.code === 'NOT_FOUND') { // Handle not found } } ``` Don't fetch all at once: ```typescript theme={null} // Good ✅ const tasks = await forge.tasks.list({ page: 1, limit: 20 }); // Bad ❌ const allTasks = await forge.tasks.list({ limit: 10000 }); ``` ```typescript theme={null} const cache = new Map(); async function getTask(id) { if (cache.has(id)) { return cache.get(id); } const task = await forge.tasks.get(id); cache.set(id, task); return task; } ``` *** ## Next Steps Manage Forge projects Create and manage tasks Execute tasks with AI agents Use Forge from AI coding agents # Tasks Source: https://docs.namastex.ai/forge/api/tasks GET /api/tasks Create and manage tasks via REST API ## Overview Tasks represent individual pieces of work to be executed by AI agents. **Base URL**: `http://localhost:8887/api/tasks` *** ## List Tasks Get all tasks with filtering and pagination. ```http theme={null} GET /api/tasks ``` ### Query Parameters | Parameter | Type | Description | | ----------- | ------- | ------------------------ | | `projectId` | string | Filter by project | | `status` | enum | Filter by status | | `priority` | enum | Filter by priority | | `labels` | string | Comma-separated labels | | `assignee` | string | Filter by assignee | | `search` | string | Search title/description | | `page` | integer | Page number | | `limit` | integer | Items per page | | `sort` | string | Sort field | ### Status Values * `pending` - Not started * `in_progress` - Being executed * `review` - Awaiting review * `completed` - Successfully completed * `failed` - Execution failed * `cancelled` - Cancelled by user ### Priority Values * `low` * `medium` * `high` * `critical` ```bash cURL theme={null} curl "http://localhost:8887/api/tasks?status=in_progress&priority=high&limit=20" ``` ```javascript JavaScript theme={null} const response = await fetch('http://localhost:8887/api/tasks?status=in_progress&priority=high&limit=20'); const data = await response.json(); ``` ```python Python theme={null} import requests response = requests.get( 'http://localhost:8887/api/tasks', params={'status': 'in_progress', 'priority': 'high', 'limit': 20} ) tasks = response.json() ``` ```json 200 Success theme={null} { "success": true, "data": [ { "id": "task_abc123", "projectId": "proj_xyz789", "title": "Add user authentication", "description": "Implement JWT-based authentication", "status": "in_progress", "priority": "high", "labels": ["feature", "backend", "auth"], "assignee": "claude", "createdBy": "user_123", "createdAt": "2024-01-15T10:00:00Z", "updatedAt": "2024-01-15T10:30:00Z" } ], "pagination": { "page": 1, "limit": 20, "total": 1, "pages": 1 } } ``` ```json 401 Unauthorized theme={null} { "success": false, "error": { "code": "UNAUTHORIZED", "message": "Authentication required" } } ``` *** ## Get Task Retrieve a specific task with all details. ```http theme={null} GET /api/tasks/:id ``` ```bash cURL theme={null} curl http://localhost:8887/api/tasks/task_abc123 ``` ```javascript JavaScript theme={null} const response = await fetch('http://localhost:8887/api/tasks/task_abc123'); const data = await response.json(); ``` ```python Python theme={null} import requests response = requests.get('http://localhost:8887/api/tasks/task_abc123') data = response.json() ``` ```json 200 Success theme={null} { "success": true, "data": { "id": "task_abc123", "projectId": "proj_xyz789", "title": "Add user authentication", "description": "Implement JWT-based authentication with login and signup endpoints", "status": "completed", "priority": "high", "labels": ["feature", "backend", "auth"], "assignee": "claude", "createdBy": "user_123", "createdAt": "2024-01-15T10:00:00Z", "updatedAt": "2024-01-15T10:45:00Z", "completedAt": "2024-01-15T10:45:00Z", "attempts": [ { "id": "attempt_1", "llm": "claude", "status": "completed", "startedAt": "2024-01-15T10:30:00Z", "completedAt": "2024-01-15T10:45:00Z", "duration": 900000, "cost": 0.23, "filesChanged": 8, "linesAdded": 245, "linesRemoved": 12 } ], "metadata": { "repository": "https://github.com/user/repo", "branch": "feature/auth", "worktreePath": ".forge/worktrees/task-abc123-claude" }, "stats": { "totalAttempts": 1, "successfulAttempts": 1, "failedAttempts": 0, "totalCost": 0.23, "totalDuration": 900000 } } } ``` ```json 401 Unauthorized theme={null} { "success": false, "error": { "code": "UNAUTHORIZED", "message": "Authentication required" } } ``` *** ## Create Task Create a new task. ```http theme={null} POST /api/tasks ``` ### Request Body ```json theme={null} { "projectId": "proj_xyz789", "title": "Add dark mode toggle", "description": "Create a toggle component for dark/light mode with LocalStorage persistence", "priority": "medium", "labels": ["feature", "ui"], "assignee": "gemini", "metadata": { "files": ["src/components/ThemeToggle.tsx"] } } ``` ```bash cURL theme={null} curl -X POST http://localhost:8887/api/tasks \ -H "Content-Type: application/json" \ -d '{ "projectId": "proj_xyz789", "title": "Add dark mode toggle", "description": "Create toggle component with LocalStorage", "priority": "medium", "labels": ["feature", "ui"] }' ``` ```javascript JavaScript theme={null} const response = await fetch('http://localhost:8887/api/tasks', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({...}) }); const data = await response.json(); ``` ```python Python theme={null} import requests response = requests.post( 'http://localhost:8887/api/tasks', json={...} ) data = response.json() ``` ```json 200 Success theme={null} { "success": true, "data": { "id": "task_def456", "projectId": "proj_xyz789", "title": "Add dark mode toggle", "status": "pending", "priority": "medium", "createdAt": "2024-01-15T11:00:00Z" } } ``` ```json 401 Unauthorized theme={null} { "success": false, "error": { "code": "UNAUTHORIZED", "message": "Authentication required" } } ``` *** ## Update Task Update task properties. ```http theme={null} PATCH /api/tasks/:id ``` ### Request Body ```json theme={null} { "title": "Updated title", "description": "Updated description", "status": "in_progress", "priority": "high", "labels": ["feature", "ui", "priority:high"], "assignee": "claude" } ``` ```bash cURL theme={null} curl -X PATCH http://localhost:8887/api/tasks/task_abc123 \ -H "Content-Type: application/json" \ -d '{ "status": "review", "priority": "high" }' ``` *** ## Delete Task Delete a task and all associated attempts. ```http theme={null} DELETE /api/tasks/:id ``` This deletes the task and all attempts permanently. ```bash cURL theme={null} curl -X DELETE http://localhost:8887/api/tasks/task_abc123 ``` ```javascript JavaScript theme={null} const response = await fetch('http://localhost:8887/api/tasks/task_abc123', { method: 'DELETE' }); const data = await response.json(); ``` ```python Python theme={null} import requests response = requests.delete('http://localhost:8887/api/tasks/task_abc123') data = response.json() ``` ```json 200 Success theme={null} { "success": true, "data": { "deleted": true, "taskId": "task_abc123" } } ``` ```json 404 Not Found theme={null} { "success": false, "error": { "code": "NOT_FOUND", "message": "Task not found" } } ``` *** ## Start Task Start executing a task with an AI agent. ```http theme={null} POST /api/tasks/:id/start ``` ### Request Body ```json theme={null} { "llm": "claude", "options": { "temperature": 0.7, "maxTokens": 4096 } } ``` ```bash cURL theme={null} curl -X POST http://localhost:8887/api/tasks/task_abc123/start \ -H "Content-Type: application/json" \ -d '{ "llm": "claude" }' ``` ```javascript JavaScript theme={null} const response = await fetch('http://localhost:8887/api/tasks/task_abc123/start', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ llm: 'claude', options: { temperature: 0.7, maxTokens: 4096 } }) }); const data = await response.json(); ``` ```python Python theme={null} import requests response = requests.post( 'http://localhost:8887/api/tasks/task_abc123/start', json={'llm': 'claude', 'options': {'temperature': 0.7, 'maxTokens': 4096}} ) data = response.json() ``` ```json 200 Success theme={null} { "success": true, "data": { "attemptId": "attempt_new123", "status": "running", "startedAt": "2024-01-15T10:30:00Z" } } ``` ```json 401 Unauthorized theme={null} { "success": false, "error": { "code": "UNAUTHORIZED", "message": "Authentication required" } } ``` ```python Python theme={null} import requests response = requests.post( 'http://localhost:8887/api/tasks/task_abc123', json={...} ) data = response.json() ``` ```json 200 Success theme={null} { "success": true, "data": { "attemptId": "attempt_new123", "status": "running", "startedAt": "2024-01-15T11:05:00Z" } } ``` ```json 401 Unauthorized theme={null} { "success": false, "error": { "code": "UNAUTHORIZED", "message": "Authentication required" } } ``` *** ## Cancel Task Cancel a running task. ```http theme={null} POST /api/tasks/:id/cancel ``` ```bash cURL theme={null} curl -X POST http://localhost:8887/api/tasks/task_abc123/cancel ``` *** ## Get Task Attempts Get all attempts for a task. ```http theme={null} GET /api/tasks/:id/attempts ``` ```javascript JavaScript theme={null} const response = await fetch('http://localhost:8887/api/tasks/task_abc123/cancel', { method: 'POST' }); const data = await response.json(); ``` ```python Python theme={null} import requests response = requests.post( 'http://localhost:8887/api/tasks/task_abc123/cancel', json={...} ) data = response.json() ``` ```json 200 Success theme={null} { "success": true, "data": [ { "id": "attempt_1", "llm": "claude", "status": "completed", "duration": 900000, "cost": 0.23 }, { "id": "attempt_2", "llm": "gemini", "status": "completed", "duration": 450000, "cost": 0.00 } ] } ``` ```json 401 Unauthorized theme={null} { "success": false, "error": { "code": "UNAUTHORIZED", "message": "Authentication required" } } ``` *** ## Get Task Logs Get execution logs for a task. ```http theme={null} GET /api/tasks/:id/logs ``` ### Query Parameters | Parameter | Type | Description | | ----------- | ------- | --------------------------------------- | | `attemptId` | string | Filter by specific attempt | | `level` | enum | Filter by log level (info, warn, error) | | `follow` | boolean | Stream logs in real-time | ```bash cURL theme={null} curl "http://localhost:8887/api/tasks/task_abc123/logs?attemptId=attempt_1&follow=true" ``` ```javascript JavaScript theme={null} const response = await fetch('http://localhost:8887/api/tasks/task_abc123/logs?attemptId=attempt_1&follow=true'); const data = await response.json(); ``` ```python Python theme={null} import requests response = requests.get( 'http://localhost:8887/api/tasks/task_abc123/logs', params={'attemptId': 'attempt_1', 'follow': True} ) logs = response.json() ``` *** ## Bulk Operations ### Bulk Update Update multiple tasks at once. ```http theme={null} POST /api/tasks/bulk/update ``` ### Request Body ```json theme={null} { "taskIds": ["task_1", "task_2", "task_3"], "updates": { "status": "review", "priority": "high" } } ``` ### Bulk Delete ```http theme={null} POST /api/tasks/bulk/delete ``` ### Request Body ```json theme={null} { "taskIds": ["task_1", "task_2", "task_3"] } ``` *** ## SDK Examples ### JavaScript/TypeScript ```typescript theme={null} import { ForgeClient } from '@automagik/forge-sdk'; const forge = new ForgeClient(); // List tasks const tasks = await forge.tasks.list({ status: 'in_progress', priority: 'high', page: 1, limit: 20 }); // Get task const task = await forge.tasks.get('task_abc123'); // Create task const newTask = await forge.tasks.create({ projectId: 'proj_xyz789', title: 'Add dark mode', description: 'Implement dark mode toggle', priority: 'medium', labels: ['feature', 'ui'] }); // Update task await forge.tasks.update('task_abc123', { status: 'review', priority: 'high' }); // Start task const attempt = await forge.tasks.start('task_abc123', { llm: 'claude' }); // Cancel task await forge.tasks.cancel('task_abc123'); // Get attempts const attempts = await forge.tasks.attempts('task_abc123'); // Get logs const logs = await forge.tasks.logs('task_abc123', { attemptId: 'attempt_1', follow: true }); ``` ### Python ```python theme={null} from automagik_forge import ForgeClient forge = ForgeClient() # List tasks tasks = forge.tasks.list( status='in_progress', priority='high', page=1, limit=20 ) # Create task new_task = forge.tasks.create( project_id='proj_xyz789', title='Add dark mode', description='Implement dark mode toggle', priority='medium', labels=['feature', 'ui'] ) # Start task attempt = forge.tasks.start('task_abc123', llm='claude') # Get logs (streaming) for log in forge.tasks.logs('task_abc123', follow=True): print(log) ``` *** ## Next Steps Manage task attempts Organize tasks in projects Monitor running processes # Task Templates Source: https://docs.namastex.ai/forge/api/templates GET /api/task-templates Manage reusable task templates ## Overview Task Templates allow you to create reusable task configurations for common workflows like bug fixes, feature development, code reviews, and refactoring. **Base URL**: `http://localhost:8887/api/task-templates` *** ## List Templates Get all available task templates. ```http theme={null} GET /api/task-templates ``` ### Query Parameters | Parameter | Type | Description | | ---------- | ------- | ---------------------------- | | `page` | integer | Page number (default: 1) | | `limit` | integer | Items per page (default: 20) | | `category` | string | Filter by template category | | `search` | string | Search by template name | ```bash cURL theme={null} curl "http://localhost:8887/api/task-templates?page=1&limit=10" ``` ```javascript JavaScript theme={null} const response = await fetch('http://localhost:8887/api/task-templates?page=1&limit=10'); const data = await response.json(); console.log(data); ``` ```python Python theme={null} import requests response = requests.get( 'http://localhost:8887/api/task-templates', params={'page': 1, 'limit': 10} ) templates = response.json() ``` ```json 200 Success theme={null} { "success": true, "data": [ { "id": "template_bug_fix", "name": "Bug Fix Workflow", "description": "Standard bug fix workflow with reproduction, fix, and testing", "category": "bugfix", "tasks": [ { "title": "Reproduce bug", "description": "Create minimal reproduction", "order": 1 }, { "title": "Fix bug", "description": "Implement fix", "order": 2 }, { "title": "Add tests", "description": "Add regression tests", "order": 3 } ], "createdAt": "2024-01-10T00:00:00Z" } ], "pagination": { "page": 1, "limit": 10, "total": 5, "pages": 1 } } ``` ```json 401 Unauthorized theme={null} { "success": false, "error": { "code": "UNAUTHORIZED", "message": "Authentication required" } } ``` *** ## Get Template Get a specific template by ID. ```http theme={null} GET /api/task-templates/:id ``` ```bash cURL theme={null} curl http://localhost:8887/api/task-templates/template_feature ``` ```javascript JavaScript theme={null} const response = await fetch('http://localhost:8887/api/task-templates/template_feature'); const data = await response.json(); console.log(data); ``` ```python Python theme={null} import requests response = requests.get('http://localhost:8887/api/task-templates/template_feature') template = response.json() ``` ```json 200 Success theme={null} { "success": true, "data": { "id": "template_feature", "name": "Feature Development", "description": "Complete feature development workflow", "category": "feature", "tasks": [ { "title": "Design feature", "description": "Create technical design", "order": 1, "estimatedTime": 60 }, { "title": "Implement feature", "description": "Write implementation code", "order": 2, "estimatedTime": 180 }, { "title": "Write tests", "description": "Add unit and integration tests", "order": 3, "estimatedTime": 90 }, { "title": "Update documentation", "description": "Document new feature", "order": 4, "estimatedTime": 30 } ], "metadata": { "totalEstimatedTime": 360, "difficulty": "medium" } } } ``` ```json 404 Not Found theme={null} { "success": false, "error": { "code": "NOT_FOUND", "message": "Template not found" } } ``` ```json 401 Unauthorized theme={null} { "success": false, "error": { "code": "UNAUTHORIZED", "message": "Authentication required" } } ``` *** ## Create Template Create a new task template. ```http theme={null} POST /api/task-templates ``` Template name Template description Template category (e.g., "bugfix", "feature", "refactor", "review") Array of task definitions with title, description, and order ```bash cURL theme={null} curl -X POST http://localhost:8887/api/task-templates \ -H "Content-Type: application/json" \ -d '{ "name": "API Endpoint Template", "description": "Template for creating new API endpoints", "category": "development", "tasks": [ { "title": "Define API schema", "description": "Create OpenAPI specification", "order": 1 }, { "title": "Implement endpoint", "description": "Write handler and validation", "order": 2 }, { "title": "Add tests", "description": "Unit and integration tests", "order": 3 }, { "title": "Update API docs", "description": "Document in API reference", "order": 4 } ] }' ``` ```javascript JavaScript theme={null} const response = await fetch('http://localhost:8887/api/task-templates', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name: 'API Endpoint Template', description: 'Template for creating new API endpoints', category: 'development', tasks: [...] }) }); const data = await response.json(); ``` ```python Python theme={null} import requests response = requests.post( 'http://localhost:8887/api/task-templates', json={ 'name': 'API Endpoint Template', 'description': 'Template for creating new API endpoints', 'category': 'development', 'tasks': [...] } ) template = response.json() ``` ```json 200 Success theme={null} { "success": true, "data": { "id": "template_api_endpoint", "name": "API Endpoint Template", "description": "Template for creating new API endpoints", "category": "development", "tasks": [ { "title": "Define API schema", "description": "Create OpenAPI specification", "order": 1 }, { "title": "Implement endpoint", "description": "Write handler and validation", "order": 2 }, { "title": "Add tests", "description": "Unit and integration tests", "order": 3 }, { "title": "Update API docs", "description": "Document in API reference", "order": 4 } ], "createdAt": "2024-01-15T11:00:00Z" } } ``` ```json 401 Unauthorized theme={null} { "success": false, "error": { "code": "UNAUTHORIZED", "message": "Authentication required" } } ``` *** ## Update Template Update an existing template. ```http theme={null} PUT /api/task-templates/:id ``` Updated template name Updated template description Updated template category Updated task definitions array ```bash cURL theme={null} curl -X PUT http://localhost:8887/api/task-templates/template_api_endpoint \ -H "Content-Type: application/json" \ -d '{ "name": "Updated Template Name", "description": "Updated description with new details" }' ``` ```javascript JavaScript theme={null} const response = await fetch('http://localhost:8887/api/task-templates/template_api_endpoint', { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name: 'Updated Template Name', description: 'Updated description' }) }); const data = await response.json(); ``` ```python Python theme={null} import requests response = requests.put( 'http://localhost:8887/api/task-templates/template_api_endpoint', json={ 'name': 'Updated Template Name', 'description': 'Updated description' } ) template = response.json() ``` ```json 200 Success theme={null} { "success": true, "data": { "id": "template_api_endpoint", "name": "Updated Template Name", "description": "Updated description with new details", "category": "development", "tasks": [...], "updatedAt": "2024-01-15T14:30:00Z" } } ``` ```json 404 Not Found theme={null} { "success": false, "error": { "code": "NOT_FOUND", "message": "Template not found" } } ``` ```json 401 Unauthorized theme={null} { "success": false, "error": { "code": "UNAUTHORIZED", "message": "Authentication required" } } ``` *** ## Delete Template Delete a template. ```http theme={null} DELETE /api/task-templates/:id ``` Deleting a template is permanent and cannot be undone. ```bash cURL theme={null} curl -X DELETE http://localhost:8887/api/task-templates/template_api_endpoint ``` ```javascript JavaScript theme={null} const response = await fetch('http://localhost:8887/api/task-templates/template_api_endpoint', { method: 'DELETE' }); const data = await response.json(); ``` ```python Python theme={null} import requests response = requests.delete('http://localhost:8887/api/task-templates/template_api_endpoint') result = response.json() ``` ```json 200 Success theme={null} { "success": true, "data": { "deleted": true, "templateId": "template_api_endpoint" } } ``` ```json 404 Not Found theme={null} { "success": false, "error": { "code": "NOT_FOUND", "message": "Template not found" } } ``` ```json 401 Unauthorized theme={null} { "success": false, "error": { "code": "UNAUTHORIZED", "message": "Authentication required" } } ``` *** ## Built-in Templates Forge includes several built-in templates: ### Bug Fix ```yaml theme={null} name: Bug Fix Workflow tasks: - Reproduce bug - Fix issue - Add regression tests - Update changelog ``` ### Feature Development ```yaml theme={null} name: Feature Development tasks: - Design feature - Implement code - Write tests - Update documentation ``` ### Code Review ```yaml theme={null} name: Code Review tasks: - Review code quality - Check test coverage - Verify documentation - Approve or request changes ``` ### Refactoring ```yaml theme={null} name: Refactoring tasks: - Analyze current code - Plan refactoring approach - Execute refactoring - Verify tests pass ``` *** ## SDK Examples ```typescript theme={null} import { ForgeClient } from '@automagik/forge-sdk'; const forge = new ForgeClient(); // List templates const templates = await forge.templates.list(); // Get template const template = await forge.templates.get('template_bug_fix'); // Create from template const tasks = await forge.templates.createTasks('proj_123', 'template_feature', { context: { feature: 'User notifications', description: 'Add email and push notifications' } }); // Create custom template const newTemplate = await forge.templates.create({ name: 'My Custom Template', category: 'custom', tasks: [...] }); ``` *** ## Next Steps Create tasks from templates Template-based workflows # WebSocket Source: https://docs.namastex.ai/forge/api/websockets Real-time updates via WebSocket connections ## Overview Forge provides WebSocket endpoints for real-time updates on process execution, task attempts, and system events. **WebSocket Base URL**: `ws://localhost:8887/ws` *** ## Connection Basics ### Establishing Connection ```javascript theme={null} const ws = new WebSocket('ws://localhost:8887/ws/execution-processes'); ws.onopen = () => { console.log('WebSocket connected'); }; ws.onmessage = (event) => { const data = JSON.parse(event.data); console.log('Received:', data); }; ws.onerror = (error) => { console.error('WebSocket error:', error); }; ws.onclose = () => { console.log('WebSocket disconnected'); }; ``` ### Authentication WebSocket connections use the same GitHub OAuth authentication as REST API: ```javascript theme={null} // Include auth token in connection URL const token = 'your-github-oauth-token'; const ws = new WebSocket(`ws://localhost:8887/ws/execution-processes?token=${token}`); ``` Or use cookies from authenticated REST session. *** ## Process Log Streaming ### Raw Logs Stream Stream unprocessed output from execution processes. ``` ws://localhost:8887/ws/execution-processes/:id/logs/raw ``` **Example**: ```javascript theme={null} const processId = 'proc_abc123'; const ws = new WebSocket(`ws://localhost:8887/ws/execution-processes/${processId}/logs/raw`); ws.onmessage = (event) => { // Raw text output console.log(event.data); }; ``` **Output Example**: ``` Installing dependencies... npm install ✓ Installed 245 packages Running tests... ✓ All tests passed (12/12) ``` *** ### Normalized Logs Stream Stream structured, processed log messages. ``` ws://localhost:8887/ws/execution-processes/:id/logs/normalized ``` **Example**: ```javascript theme={null} const processId = 'proc_abc123'; const ws = new WebSocket(`ws://localhost:8887/ws/execution-processes/${processId}/logs/normalized`); ws.onmessage = (event) => { const log = JSON.parse(event.data); // Structured log object console.log(`[${log.level}] ${log.message}`); if (log.metadata) { console.log('Metadata:', log.metadata); } }; ``` **Message Format**: ```json theme={null} { "level": "info", "message": "Installing dependencies", "timestamp": "2024-01-15T10:30:15Z", "source": "executor", "metadata": { "stage": "setup", "progress": 15 } } ``` **Log Levels**: * `debug` - Detailed diagnostic information * `info` - General informational messages * `warn` - Warning messages * `error` - Error messages * `success` - Success/completion messages *** ## Process Status Streaming Monitor all execution processes in real-time. ``` ws://localhost:8887/ws/execution-processes ``` **Example**: ```javascript theme={null} const ws = new WebSocket('ws://localhost:8887/ws/execution-processes'); ws.onmessage = (event) => { const update = JSON.parse(event.data); switch (update.type) { case 'process_started': console.log(`Process ${update.processId} started`); break; case 'process_progress': console.log(`Progress: ${update.progress}%`); break; case 'process_completed': console.log(`Process ${update.processId} completed`); break; case 'process_failed': console.error(`Process ${update.processId} failed:`, update.error); break; } }; ``` **Event Types**: ### process\_started ```json theme={null} { "type": "process_started", "processId": "proc_abc123", "taskAttemptId": "attempt_xyz789", "executor": "CLAUDE_CODE", "startedAt": "2024-01-15T10:30:00Z" } ``` ### process\_progress ```json theme={null} { "type": "process_progress", "processId": "proc_abc123", "progress": { "percentage": 65, "stage": "code_generation", "message": "Generating authentication logic", "estimatedRemaining": 25000 } } ``` ### process\_completed ```json theme={null} { "type": "process_completed", "processId": "proc_abc123", "completedAt": "2024-01-15T10:45:00Z", "duration": 900000, "exitCode": 0, "stats": { "filesChanged": 8, "linesAdded": 245, "linesRemoved": 12 } } ``` ### process\_failed ```json theme={null} { "type": "process_failed", "processId": "proc_abc123", "failedAt": "2024-01-15T10:35:00Z", "error": { "code": "EXECUTION_ERROR", "message": "Compilation failed", "details": "TypeError: Cannot read property 'map' of undefined" } } ``` ### process\_stopped ```json theme={null} { "type": "process_stopped", "processId": "proc_abc123", "stoppedAt": "2024-01-15T10:35:00Z", "stoppedBy": "user@example.com", "reason": "Manual stop requested" } ``` *** ## Task Attempt Diff Streaming Stream git diff updates as task attempt progresses. ``` ws://localhost:8887/ws/task-attempts/:id/diff ``` **Example**: ```javascript theme={null} const attemptId = 'attempt_abc123'; const ws = new WebSocket(`ws://localhost:8887/ws/task-attempts/${attemptId}/diff`); ws.onmessage = (event) => { const update = JSON.parse(event.data); console.log('Files changed:', update.filesChanged); console.log('Diff:', update.diff); }; ``` **Message Format**: ```json theme={null} { "type": "diff_update", "attemptId": "attempt_abc123", "diff": "diff --git a/src/auth.ts b/src/auth.ts\nindex abc123..def456 100644\n--- a/src/auth.ts\n+++ b/src/auth.ts\n@@ -1,5 +1,10 @@\n+import jwt from 'jsonwebtoken';\n+", "filesChanged": 3, "insertions": 125, "deletions": 8, "timestamp": "2024-01-15T10:35:00Z" } ``` *** ## Advanced Usage ### Reconnection Strategy Implement automatic reconnection for production use: ```javascript theme={null} class ForgeWebSocket { constructor(url) { this.url = url; this.reconnectDelay = 1000; this.maxReconnectDelay = 30000; this.connect(); } connect() { this.ws = new WebSocket(this.url); this.ws.onopen = () => { console.log('Connected'); this.reconnectDelay = 1000; // Reset delay on successful connection }; this.ws.onmessage = (event) => { this.handleMessage(JSON.parse(event.data)); }; this.ws.onerror = (error) => { console.error('WebSocket error:', error); }; this.ws.onclose = () => { console.log('Disconnected, reconnecting...'); setTimeout(() => { this.reconnectDelay = Math.min( this.reconnectDelay * 2, this.maxReconnectDelay ); this.connect(); }, this.reconnectDelay); }; } handleMessage(data) { // Override this method } send(data) { if (this.ws.readyState === WebSocket.OPEN) { this.ws.send(JSON.stringify(data)); } } close() { this.ws.close(); } } // Usage const processWs = new ForgeWebSocket('ws://localhost:8887/ws/execution-processes'); processWs.handleMessage = (data) => { console.log('Process update:', data); }; ``` ### Heartbeat / Keep-Alive Maintain connection with periodic heartbeat: ```javascript theme={null} const ws = new WebSocket('ws://localhost:8887/ws/execution-processes'); let heartbeatInterval; ws.onopen = () => { // Send heartbeat every 30 seconds heartbeatInterval = setInterval(() => { if (ws.readyState === WebSocket.OPEN) { ws.send(JSON.stringify({ type: 'ping' })); } }, 30000); }; ws.onmessage = (event) => { const data = JSON.parse(event.data); if (data.type === 'pong') { // Server acknowledged heartbeat return; } // Handle other messages }; ws.onclose = () => { clearInterval(heartbeatInterval); }; ``` ### Message Buffering Buffer messages when connection is unavailable: ```javascript theme={null} class BufferedWebSocket { constructor(url) { this.url = url; this.buffer = []; this.connect(); } connect() { this.ws = new WebSocket(this.url); this.ws.onopen = () => { // Send buffered messages while (this.buffer.length > 0) { const message = this.buffer.shift(); this.ws.send(JSON.stringify(message)); } }; } send(data) { if (this.ws.readyState === WebSocket.OPEN) { this.ws.send(JSON.stringify(data)); } else { // Buffer message for later this.buffer.push(data); } } } ``` *** ## SDK Integration ### JavaScript/TypeScript ```typescript theme={null} import { ForgeClient } from '@automagik/forge-sdk'; const forge = new ForgeClient(); // Stream process logs const logStream = forge.processes.streamLogs('proc_abc123', { format: 'normalized' }); logStream.on('log', (log) => { console.log(`[${log.level}] ${log.message}`); }); logStream.on('error', (error) => { console.error('Stream error:', error); }); // Monitor all processes const processMonitor = forge.processes.monitor(); processMonitor.on('started', (process) => { console.log(`Process ${process.id} started`); }); processMonitor.on('completed', (process) => { console.log(`Process ${process.id} completed`); }); // Stream task attempt diff const diffStream = forge.attempts.streamDiff('attempt_abc123'); diffStream.on('update', (diff) => { console.log('Files changed:', diff.filesChanged); }); ``` ### Python ```python theme={null} from automagik_forge import ForgeClient import asyncio forge = ForgeClient() # Stream process logs async def stream_logs(): async for log in forge.processes.stream_logs('proc_abc123', format='normalized'): print(f"[{log.level}] {log.message}") # Monitor processes async def monitor_processes(): async for event in forge.processes.monitor(): if event.type == 'process_started': print(f"Process {event.process_id} started") elif event.type == 'process_completed': print(f"Process {event.process_id} completed") asyncio.run(stream_logs()) ``` *** ## Best Practices Always implement reconnection logic and handle connection failures gracefully: ```javascript theme={null} ws.onerror = (error) => { console.error('Connection failed:', error); // Show user notification // Attempt reconnection }; ws.onclose = () => { // Reconnect after delay setTimeout(reconnect, 5000); }; ``` Close WebSocket connections when no longer needed: ```javascript theme={null} // Component unmount / cleanup componentWillUnmount() { if (this.ws) { this.ws.close(); this.ws = null; } } ``` Prefer normalized logs over raw logs for easier parsing: ```javascript theme={null} // Preferred ✅ const ws = new WebSocket('.../logs/normalized'); // Avoid for production ❌ const ws = new WebSocket('.../logs/raw'); ``` Implement heartbeat to detect stale connections: ```javascript theme={null} let lastHeartbeat = Date.now(); setInterval(() => { if (Date.now() - lastHeartbeat > 60000) { // No heartbeat for 60s, reconnect ws.close(); reconnect(); } }, 10000); ``` *** ## Troubleshooting ### Connection Refused **Error**: `WebSocket connection to 'ws://localhost:8887/ws/...' failed` **Solutions**: * Verify Forge backend is running * Check firewall allows WebSocket connections * Ensure port 8080 is not blocked * Try HTTP upgrade instead of direct WebSocket ### Unexpected Disconnections **Issue**: WebSocket disconnects frequently **Solutions**: * Implement heartbeat/ping-pong * Check network stability * Increase timeout settings * Use reconnection strategy ### Missing Messages **Issue**: Not receiving all events **Solutions**: * Check message handler for errors * Verify WebSocket is in OPEN state before sending * Implement message buffering * Check server-side logs *** ## Next Steps Process execution endpoints Task attempt management Server-Sent Events alternative Use SDK for simpler integration # Configuration Commands Source: https://docs.namastex.ai/forge/cli/config-commands Configuring Automagik Forge ## Overview Forge configuration is managed through a combination of: * **Configuration file**: `.forge/config.json` * **Environment variables**: Runtime settings * **Web UI settings**: Visual configuration interface *** ## Configuration File Location: `.forge/config.json` ```json theme={null} { "project_id": "uuid", "name": "Project Name", "repository": { "type": "git", "remote": "https://github.com/owner/repo.git", "default_branch": "main" }, "github": { "enabled": false, "owner": "", "repo": "", "client_id": "", "token_encrypted": "" }, "worktrees": { "enabled": true, "base_path": "./.forge/worktrees", "cleanup_on_exit": true, "max_concurrent": 5, "branch_prefix": "forge/task-", "auto_delete_merged": true }, "executors": { "default": "claude-code", "enabled": ["claude-code", "cursor-cli", "gemini", "codex"] }, "preferences": { "auto_cleanup_worktrees": true, "stream_logs": true, "theme": "dark" } } ``` *** ## Environment Variables Configure Forge behavior via environment variables: ### Server Configuration ```bash theme={null} # Backend server port (auto-assigned if not set) export BACKEND_PORT=5000 # Frontend server port export FRONTEND_PORT=3000 # Server host address export HOST=127.0.0.1 # Or bind to all interfaces export HOST=0.0.0.0 ``` ### GitHub OAuth ```bash theme={null} # GitHub OAuth App Client ID export GITHUB_CLIENT_ID=your_github_oauth_app_id # Optionally set in .env file echo "GITHUB_CLIENT_ID=your_id" >> .env ``` ### AI Agent API Keys ```bash theme={null} # Claude Code (Anthropic) export ANTHROPIC_API_KEY=sk-ant-... # Gemini (Google AI) export GOOGLE_AI_API_KEY=AIza... # OpenAI Codex export OPENAI_API_KEY=sk-... # These are used by executors when running tasks ``` ### Analytics (Optional) ```bash theme={null} # PostHog analytics key export POSTHOG_API_KEY=phc_... ``` ### Debug Options ```bash theme={null} # Enable debug logging export RUST_LOG=debug # Disable worktree cleanup (for debugging) export DISABLE_WORKTREE_ORPHAN_CLEANUP=1 # Verbose execution logs export FORGE_DEBUG=1 ``` *** ## Configuration via Web UI Access settings at `http://localhost:3000/settings` ### General Settings * Project Name * Project ID (read-only) * Repository URL * Default Branch Configure AI agents: **Claude Code:** * Enable/Disable * API Key (from env) * Model selection * Max tokens **Cursor CLI:** * Enable/Disable * CLI path * Arguments **Gemini:** * Enable/Disable * API Key (from env) * Model selection **OpenAI Codex:** * Enable/Disable * API Key (from env) * Model selection * Enable/Disable worktrees * Base path * Auto-cleanup settings * Max concurrent worktrees * Branch naming prefix * OAuth authentication * Repository selection * Issue sync settings * PR integration *** ## Executor Configuration Configure each AI agent in `.forge/config.json`: ### Claude Code ```json theme={null} { "executors": { "claude-code": { "enabled": true, "api_key_env": "ANTHROPIC_API_KEY", "model": "claude-3-5-sonnet-20241022", "max_tokens": 8192, "temperature": 0.7, "timeout": 300000 } } } ``` ### Cursor CLI ```json theme={null} { "executors": { "cursor-cli": { "enabled": true, "cli_path": "/usr/local/bin/cursor", "args": ["--headless"], "timeout": 300000 } } } ``` ### Gemini ```json theme={null} { "executors": { "gemini": { "enabled": true, "api_key_env": "GOOGLE_AI_API_KEY", "model": "gemini-2.0-flash-exp", "temperature": 0.7, "timeout": 300000 } } } ``` ### OpenAI Codex ```json theme={null} { "executors": { "codex": { "enabled": true, "api_key_env": "OPENAI_API_KEY", "model": "gpt-4", "max_tokens": 8192, "temperature": 0.7, "timeout": 300000 } } } ``` ### Open Source Agents ```json theme={null} { "executors": { "opencode": { "enabled": true, "endpoint": "http://localhost:11434", "model": "codellama:latest" }, "qwen-code": { "enabled": true, "endpoint": "http://localhost:11434", "model": "qwen-coder:latest" } } } ``` *** ## Worktree Configuration Fine-tune git worktree behavior: ```json theme={null} { "worktrees": { // Enable git worktree isolation "enabled": true, // Where to create worktrees "base_path": "./.forge/worktrees", // Clean up when Forge exits "cleanup_on_exit": true, // Maximum simultaneous worktrees "max_concurrent": 5, // Branch name format: forge/task-{task-id} "branch_prefix": "forge/task-", // Auto-delete worktrees after merge "auto_delete_merged": true, // Keep worktrees for failed tasks "keep_on_failure": false, // Orphan cleanup interval (seconds) "cleanup_interval": 3600 } } ``` *** ## GitHub OAuth Configuration ### Create GitHub OAuth App Navigate to: [https://github.com/settings/developers](https://github.com/settings/developers) Click "New OAuth App" **Settings:** * Application name: "Automagik Forge" * Homepage URL: `http://localhost:3000` * Authorization callback URL: `http://localhost:3000/auth/callback` Copy the Client ID from the OAuth app page ```bash theme={null} export GITHUB_CLIENT_ID=your_client_id_here # Or add to .env file echo "GITHUB_CLIENT_ID=your_client_id_here" >> .env ``` ```bash theme={null} automagik-forge ``` GitHub authentication will now be available in Settings → GitHub *** ## Configuration Validation Validate your configuration: ```bash theme={null} # Start Forge and check logs automagik-forge # Look for configuration warnings: # ✅ Configuration loaded successfully # ⚠️ Missing GitHub OAuth configuration # ⚠️ No API keys found for executors # ❌ Invalid worktree path # Check configuration file syntax cat .forge/config.json | jq . # Verify environment variables env | grep -E 'FORGE|BACKEND|FRONTEND|ANTHROPIC|GOOGLE|OPENAI' ``` *** ## Configuration Backup ### Manual Backup ```bash theme={null} # Backup configuration cp .forge/config.json .forge/config.backup.json # Backup entire .forge directory tar -czf forge-backup.tar.gz .forge/ # Restore from backup tar -xzf forge-backup.tar.gz ``` ### Export via API ```bash theme={null} # Export project configuration curl http://localhost:5000/api/projects/{project-id}/export > config-backup.json # Import configuration curl -X POST http://localhost:5000/api/projects/import \ -H "Content-Type: application/json" \ -d @config-backup.json ``` *** ## Configuration Migration ### From v0.3.x to v0.4.x ```bash theme={null} # Backup old config cp .forge/config.json .forge/config.v3.backup.json # Update structure (handled automatically on startup) automagik-forge # Verify migration cat .forge/config.json | jq . ``` Key changes: * Added `preferences` section * New executor configuration format * Enhanced worktree settings *** ## Advanced Configuration ### Custom Executor Add a custom AI agent executor: ```json theme={null} { "executors": { "custom-agent": { "enabled": true, "type": "http", "endpoint": "http://localhost:8887/api/execute", "headers": { "Authorization": "Bearer ${CUSTOM_AGENT_TOKEN}" }, "timeout": 600000 } } } ``` ### Proxy Configuration Route executor requests through a proxy: ```bash theme={null} # HTTP proxy export HTTP_PROXY=http://proxy.company.com:8080 export HTTPS_PROXY=http://proxy.company.com:8080 # No proxy for localhost export NO_PROXY=localhost,127.0.0.1 ``` ### Rate Limiting Configure executor rate limits: ```json theme={null} { "executors": { "claude-code": { "rate_limit": { "requests_per_minute": 50, "tokens_per_minute": 100000 } } } } ``` *** ## Security Best Practices **Never commit these files:** * `.forge/config.json` (may contain tokens) * `.env` (contains API keys) * `.forge/db.sqlite` (project data) Add to `.gitignore`: ``` .forge/ .env ``` ### Secure API Keys ```bash theme={null} # Use environment variables, not config file export ANTHROPIC_API_KEY=sk-ant-... # Or use a secrets manager # AWS Secrets Manager export ANTHROPIC_API_KEY=$(aws secretsmanager get-secret-value \ --secret-id forge/anthropic-key \ --query SecretString \ --output text) # 1Password CLI export ANTHROPIC_API_KEY=$(op read "op://Personal/Anthropic API Key/credential") ``` ### File Permissions ```bash theme={null} # Restrict config file permissions chmod 600 .forge/config.json # Restrict .forge directory chmod 700 .forge/ ``` *** ## Troubleshooting Configuration ```bash theme={null} # Check file exists ls -la .forge/config.json # Validate JSON syntax cat .forge/config.json | jq . # Check permissions ls -l .forge/config.json # View Forge logs automagik-forge 2>&1 | grep -i config ``` ```bash theme={null} # Verify API key is set echo $ANTHROPIC_API_KEY # Check executor enabled in config cat .forge/config.json | jq '.executors' # Test API key manually curl -H "x-api-key: $ANTHROPIC_API_KEY" \ https://api.anthropic.com/v1/messages ``` ```bash theme={null} # Verify client ID echo $GITHUB_CLIENT_ID # Check OAuth app settings on GitHub # Callback URL must match: http://localhost:3000/auth/callback # Clear cached tokens rm .forge/github-token.enc ``` ```bash theme={null} # Find what's using the port lsof -i :3000 # Use different ports automagik-forge --port 3001 --backend-port 5001 ``` *** ## Next Steps Complete environment variable reference Detailed GitHub integration setup Configure AI agents and models Common configuration issues # CLI Overview Source: https://docs.namastex.ai/forge/cli/overview Command-line interface for Automagik Forge ## Overview Automagik Forge provides a command-line interface for starting the web UI, managing the MCP server, and running the backend programmatically. *** ## Quick Start ```bash theme={null} # Install globally npm install -g @automagik/forge # Or run directly with npx npx automagik-forge ``` *** ## Main Command The primary command launches the Forge web interface: ```bash theme={null} automagik-forge [options] ``` ### Options | Option | Description | Default | | ----------------------- | ---------------------------------------------- | ------------- | | `--mcp` | Start in MCP server mode (basic, 6 tools) | Web UI mode | | `--mcp-advanced` | Start in MCP server mode (advanced, 56+ tools) | Web UI mode | | `--port ` | Specify frontend port | 3000 | | `--backend-port ` | Specify backend API port | Auto-assigned | | `--host ` | Specify host address | 127.0.0.1 | *** ## Usage Modes **Launch the full Kanban interface:** ```bash theme={null} # Start on default port (3000) automagik-forge # Custom port automagik-forge --port 8080 # Custom backend port automagik-forge --port 3000 --backend-port 5000 ``` Opens browser at `http://localhost:3000` with: * Visual Kanban board * Task management interface * Real-time execution logs * Project settings * GitHub integration **Run as Model Context Protocol server:** ```bash theme={null} # Basic MCP mode (6 core task management tools) automagik-forge --mcp # Advanced MCP mode (56+ tools including projects, attempts, processes) automagik-forge --mcp-advanced ``` **Basic Mode Tools (6):** * `list_projects` - List all projects * `list_tasks` - View tasks with filters * `create_task` - Create new tasks * `get_task` - Get task details * `update_task` - Modify task properties * `delete_task` - Remove tasks **Advanced Mode Tools (56+):** * All basic tools * Project management (create, update, archive) * Task attempts (multiple AI agent tries) * Process execution (start, stop, monitor) * Draft management * Container operations * Filesystem operations * Omni integration (messaging) See [MCP Tools Reference](/forge/api/mcp-tools) for complete list. *** ## Environment Variables Configure Forge behavior via environment variables: ```bash theme={null} # Backend configuration export BACKEND_PORT=5000 export HOST=0.0.0.0 # GitHub OAuth (optional) export GITHUB_CLIENT_ID=your_client_id # Analytics (optional) export POSTHOG_API_KEY=your_posthog_key # Debug options export RUST_LOG=debug export DISABLE_WORKTREE_ORPHAN_CLEANUP=1 ``` *** ## Configuration File Forge stores configuration in your project: ```bash theme={null} # Initialize configuration cd your-project automagik-forge # Creates .forge/ directory: .forge/ ├── config.json # Main configuration ├── db.sqlite # Task database ├── worktrees/ # Git worktrees for isolated execution └── logs/ # Execution logs ``` ### config.json Structure ```json theme={null} { "project_id": "uuid-here", "github": { "repository": "owner/repo", "token": "encrypted" }, "worktrees": { "enabled": true, "base_path": "./.forge/worktrees", "cleanup_on_exit": true }, "executors": { "default": "claude-code", "available": ["claude-code", "cursor-cli", "gemini", "codex"] } } ``` *** ## Platform Support Forge provides native binaries for multiple platforms: * x64 (Intel/AMD) * ARM64 * x64 (Intel) * ARM64 (Apple Silicon) * Rosetta detection * x64 * ARM64 *** ## Troubleshooting If you installed globally but can't run the command: ```bash theme={null} # Check NPM global bin path npm config get prefix # Add to PATH (add to ~/.bashrc or ~/.zshrc) export PATH="$(npm config get prefix)/bin:$PATH" # Reload shell source ~/.bashrc # or source ~/.zshrc ``` ```bash theme={null} # Find process using port lsof -i :3000 # macOS/Linux netstat -ano | findstr :3000 # Windows # Use different port automagik-forge --port 8080 ``` ``` ❌ Unsupported platform: linux-arm32 ``` Forge supports: * Linux x64, Linux ARM64 * macOS x64 (Intel), macOS ARM64 (Apple Silicon) * Windows x64, Windows ARM64 For unsupported platforms, build from source: ```bash theme={null} git clone https://github.com/namastexlabs/automagik-forge cd automagik-forge ./local-build.sh ``` ```bash theme={null} # Check if MCP server is running ps aux | grep automagik-forge # Check MCP server logs cat ~/.forge/mcp-server.log # Restart in MCP mode automagik-forge --mcp ``` *** ## Programmatic Usage While Forge is primarily a web UI, you can interact with it programmatically: ### Via MCP (Recommended) Configure in your AI agent (Claude Code, Cursor, etc.): ```json theme={null} { "mcpServers": { "automagik-forge": { "command": "npx", "args": ["automagik-forge", "--mcp"], "env": { "PROJECT_ID": "your-project-uuid" } } } } ``` ### Via REST API When Forge is running, it exposes a REST API: ```bash theme={null} # Start Forge automagik-forge --port 3000 --backend-port 5000 # API available at http://localhost:5000/api curl http://localhost:5000/api/projects curl http://localhost:5000/api/tasks ``` See [API Reference](/forge/api/rest-overview) for complete endpoints. *** ## Next Steps Manage projects and repositories Create and manage tasks Configuration management Complete MCP tool documentation *** **Note**: Forge is designed as a graphical web interface. The CLI primarily serves to launch the UI and provide MCP server functionality for AI agent integration. # Project Commands Source: https://docs.namastex.ai/forge/cli/project-commands Managing projects and repositories in Forge ## Overview Forge projects are managed through the **Web UI**. Each project represents a codebase with its own task board, git repository, and configuration. Projects are automatically created when you first launch Forge in a directory. *** ## Project Initialization When you run Forge for the first time in a directory: ```bash theme={null} cd your-project automagik-forge ``` Forge automatically: 1. Detects if it's a git repository 2. Creates `.forge/` directory with configuration 3. Initializes SQLite database 4. Generates unique project ID 5. Opens web UI at `http://localhost:3000` *** ## Project Structure ``` your-project/ ├── .forge/ │ ├── config.json # Project configuration │ ├── db.sqlite # Task database │ ├── worktrees/ # Git worktrees for tasks │ └── logs/ # Execution logs ├── .git/ # Git repository └── your-code/ # Your project files ``` *** ## Project Configuration The `.forge/config.json` file stores project settings: ```json theme={null} { "project_id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890", "name": "My Awesome Project", "repository": { "type": "git", "remote": "https://github.com/owner/repo.git", "default_branch": "main" }, "github": { "enabled": true, "owner": "owner", "repo": "repo", "token_encrypted": "..." }, "worktrees": { "enabled": true, "base_path": "./.forge/worktrees", "cleanup_on_exit": true, "max_concurrent": 5 }, "executors": { "default": "claude-code", "enabled": [ "claude-code", "cursor-cli", "gemini", "codex" ] }, "preferences": { "auto_cleanup_worktrees": true, "stream_logs": true, "theme": "dark" } } ``` *** ## GitHub Integration Connect your project to GitHub for OAuth and issue sync: ### Setup via Web UI ```bash theme={null} # Start Forge automagik-forge # Navigate to: Settings → GitHub Integration ``` Click "Connect GitHub" * Redirects to GitHub OAuth * Authorize Forge app * Returns with token * Choose repository from dropdown * Forge syncs repo metadata * Configuration saved * Green checkmark appears * Repository name displayed * Issue sync enabled ### Manual Configuration Edit `.forge/config.json`: ```json theme={null} { "github": { "enabled": true, "owner": "your-username", "repo": "your-repo", "client_id": "your-github-oauth-app-id" } } ``` Then authenticate via device flow: ```bash theme={null} # Forge will prompt for GitHub authentication automagik-forge ``` *** ## Project REST API Interact with projects programmatically: ### List Projects ```bash theme={null} curl http://localhost:5000/api/projects ``` **Response:** ```json theme={null} { "projects": [ { "id": "uuid-here", "name": "My Project", "path": "/home/user/my-project", "repository": { "remote": "https://github.com/owner/repo", "branch": "main" }, "task_count": 42, "created_at": "2024-10-31T10:00:00Z", "updated_at": "2024-10-31T15:30:00Z" } ] } ``` ### Get Project Details ```bash theme={null} curl http://localhost:5000/api/projects/{project-id} ``` ### Update Project ```bash theme={null} curl -X PATCH http://localhost:5000/api/projects/{project-id} \ -H "Content-Type: application/json" \ -d '{ "name": "Updated Project Name", "default_executor": "gemini" }' ``` ### Delete Project ```bash theme={null} # Warning: This deletes all tasks and configuration curl -X DELETE http://localhost:5000/api/projects/{project-id} ``` *** ## MCP Project Tools When running in MCP mode, use these tools from AI agents: **List all projects** ```json theme={null} { "tool": "list_projects", "arguments": {} } ``` Returns array of all Forge projects. **Get project details** Available in `--mcp-advanced` mode only. ```json theme={null} { "tool": "get_project", "arguments": { "project_id": "uuid-here" } } ``` **Create new project** Available in `--mcp-advanced` mode only. ```json theme={null} { "tool": "create_project", "arguments": { "name": "New Project", "path": "/path/to/project", "repository_url": "https://github.com/owner/repo" } } ``` **Update project settings** Available in `--mcp-advanced` mode only. ```json theme={null} { "tool": "update_project", "arguments": { "project_id": "uuid-here", "name": "Updated Name", "default_executor": "claude-code" } } ``` *** ## Project Settings Configure project behavior via Web UI: ### General Settings * **Project Name**: Display name * **Default Branch**: Git branch for new worktrees * **Default Executor**: AI agent for new tasks * **Auto-cleanup**: Remove worktrees after merge ### GitHub Settings * **OAuth Token**: GitHub authentication * **Issue Sync**: Auto-create tasks from issues * **PR Integration**: Link tasks to pull requests * **Webhook**: Real-time updates ### Executor Settings Configure available AI agents: ```json theme={null} { "executors": { "claude-code": { "enabled": true, "api_key_env": "ANTHROPIC_API_KEY", "model": "claude-3-5-sonnet-20241022", "max_tokens": 8192 } } } ``` ```json theme={null} { "executors": { "cursor-cli": { "enabled": true, "cli_path": "/usr/local/bin/cursor", "args": ["--headless"] } } } ``` ```json theme={null} { "executors": { "gemini": { "enabled": true, "api_key_env": "GOOGLE_AI_API_KEY", "model": "gemini-2.0-flash-exp" } } } ``` ```json theme={null} { "executors": { "codex": { "enabled": true, "api_key_env": "OPENAI_API_KEY", "model": "gpt-4" } } } ``` ### Worktree Settings ```json theme={null} { "worktrees": { "enabled": true, "base_path": "./.forge/worktrees", "cleanup_on_exit": true, "max_concurrent": 5, "branch_prefix": "forge/task-", "auto_delete_merged": true } } ``` *** ## Multi-Project Workflow Work with multiple projects: ```bash theme={null} cd ~/projects/frontend-app automagik-forge --port 3000 --backend-port 5000 ``` Opens at `http://localhost:3000` ```bash theme={null} cd ~/projects/backend-api automagik-forge --port 3001 --backend-port 5001 ``` Opens at `http://localhost:3001` ```bash theme={null} cd ~/projects/mobile-app automagik-forge --port 3002 --backend-port 5002 ``` Opens at `http://localhost:3002` Each project runs independently with its own: * Task board * Database * Worktrees * Configuration *** ## Project Export/Import ### Export Project ```bash theme={null} # Via API curl http://localhost:5000/api/projects/{project-id}/export > project-backup.json ``` **Exports:** * Project configuration * All tasks and attempts * Execution history * Labels and metadata ### Import Project ```bash theme={null} # Via API curl -X POST http://localhost:5000/api/projects/import \ -H "Content-Type: application/json" \ -d @project-backup.json ``` *** ## Project Migration Moving a project to a new location: ```bash theme={null} # Export project data curl http://localhost:5000/api/projects/{id}/export > backup.json # Copy .forge directory cp -r .forge/ .forge-backup/ ``` ```bash theme={null} # Move to new location mv ~/old-location ~/new-location cd ~/new-location ``` ```bash theme={null} # Edit .forge/config.json # Update any absolute paths # Verify repository settings ``` ```bash theme={null} # Start Forge automagik-forge # Verify tasks and settings loaded ``` *** ## Project Analytics View project statistics via Web UI or API: ```bash theme={null} curl http://localhost:5000/api/projects/{project-id}/analytics ``` **Metrics:** * Total tasks created * Tasks by status * Tasks by executor * Average completion time * Success rate per executor * Active worktrees * Repository activity *** ## Common Issues **Symptom**: MCP tools return "Project not found" **Solution**: ```bash theme={null} # Get project ID from Web UI # Settings → Project Info → Project ID # Or from config cat .forge/config.json | grep project_id # Update MCP configuration with correct ID ``` **Symptom**: "GitHub OAuth failed" error **Solution**: ```bash theme={null} # 1. Verify GitHub OAuth app settings # 2. Check redirect URL: http://localhost:3000/auth/callback # 3. Re-authenticate via Web UI # 4. Or set GITHUB_CLIENT_ID env var ``` **Symptom**: Port already in use **Solution**: ```bash theme={null} # Use different ports for each project automagik-forge --port 3001 --backend-port 5001 ``` **Symptom**: .forge/worktrees/ consuming disk space **Solution**: ```bash theme={null} # Clean up old worktrees # Via Web UI: Settings → Cleanup → Remove Old Worktrees # Or enable auto-cleanup in config.json { "worktrees": { "auto_delete_merged": true, "cleanup_on_exit": true } } ``` *** ## Next Steps Manage tasks within projects Configure project settings Complete API reference Set up GitHub OAuth # Task Commands Source: https://docs.namastex.ai/forge/cli/task-commands Managing tasks in Automagik Forge ## Overview Forge tasks are managed primarily through the **Web UI** at `http://localhost:3000`. While there's no dedicated CLI for task operations, you can interact with tasks programmatically via REST API or MCP tools. *** ## Web UI Task Management The primary way to work with tasks: ```bash theme={null} # Start Forge automagik-forge # Open browser at http://localhost:3000 # Use the visual Kanban board to: # - Create tasks # - Drag & drop to change status # - Assign to AI agents # - Monitor execution # - Review results ``` *** ## Task Lifecycle Tasks flow through these states: ```mermaid theme={null} graph LR A[Backlog] --> B[Todo] B --> C[In Progress] C --> D[In Review] D --> E[Done] D --> C C --> F[Blocked] F --> C ``` **Initial State**: Tasks waiting to be prioritized * Created but not yet scheduled * Can be refined and estimated * Not assigned to agents yet **Ready for Work**: Prioritized and ready to execute * Clear acceptance criteria * Assigned to agent (optional) * Dependencies resolved **Active Execution**: AI agent working on task * Git worktree created * Agent executing code changes * Real-time logs streaming **Awaiting Approval**: Implementation complete * Code changes ready * Tests passing (ideally) * Waiting for human review **Completed**: Merged to main branch * Changes merged * Worktree cleaned up * Task archived **Waiting**: Dependencies or issues blocking progress * Missing information * External dependencies * Technical blockers *** ## Task Properties Each task has these fields: ```typescript theme={null} interface Task { id: string; // Unique identifier title: string; // Short description description: string; // Detailed requirements status: TaskStatus; // Current lifecycle state priority: "low" | "medium" | "high" | "critical"; labels: string[]; // Tags for organization assignee?: string; // AI agent or human createdAt: Date; updatedAt: Date; dueDate?: Date; // Execution details attempts: TaskAttempt[]; // Multiple AI agent tries worktreePath?: string; // Git worktree location branchName?: string; // Associated git branch // Integration githubIssue?: number; // Linked GitHub issue dependsOn?: string[]; // Task dependencies } ``` *** ## REST API Task Operations Interact with tasks programmatically when Forge is running: ### List Tasks ```bash theme={null} # Get all tasks curl http://localhost:5000/api/tasks # Filter by status curl "http://localhost:5000/api/tasks?status=in_progress" # Filter by label curl "http://localhost:5000/api/tasks?labels=bug,high-priority" ``` ### Create Task ```bash theme={null} curl -X POST http://localhost:5000/api/tasks \ -H "Content-Type: application/json" \ -d '{ "title": "Add user authentication", "description": "Implement JWT-based authentication with login and signup", "priority": "high", "labels": ["feature", "backend", "security"] }' ``` ### Get Task Details ```bash theme={null} curl http://localhost:5000/api/tasks/{task-id} ``` ### Update Task ```bash theme={null} curl -X PATCH http://localhost:5000/api/tasks/{task-id} \ -H "Content-Type: application/json" \ -d '{ "status": "in_progress", "assignee": "claude-code" }' ``` ### Delete Task ```bash theme={null} curl -X DELETE http://localhost:5000/api/tasks/{task-id} ``` *** ## MCP Task Tools When running in MCP mode (`--mcp` or `--mcp-advanced`), use these tools: **List and filter tasks** ```json theme={null} { "tool": "list_tasks", "arguments": { "project_id": "uuid-here", "status": "in_progress", "labels": ["bug"] } } ``` Returns array of tasks matching filters. **Create new task** ```json theme={null} { "tool": "create_task", "arguments": { "project_id": "uuid-here", "title": "Fix memory leak in WebSocket handler", "description": "Connections not cleaned up on disconnect", "priority": "high", "labels": ["bug", "performance"] } } ``` Returns created task with ID. **Get task details** ```json theme={null} { "tool": "get_task", "arguments": { "task_id": "task-uuid-here" } } ``` Returns complete task object with attempts and execution history. **Modify task properties** ```json theme={null} { "tool": "update_task", "arguments": { "task_id": "task-uuid-here", "status": "done", "labels": ["bug", "performance", "fixed"] } } ``` Returns updated task. **Remove task** ```json theme={null} { "tool": "delete_task", "arguments": { "task_id": "task-uuid-here" } } ``` Returns success confirmation. *** ## Task Attempts Each task can have multiple attempts from different AI agents. ### Creating Attempts ```bash theme={null} # Via Web UI: Click "New Attempt" button # Select agent: Claude Code, Gemini, Cursor CLI, etc. # Via API curl -X POST http://localhost:5000/api/tasks/{task-id}/attempts \ -H "Content-Type: application/json" \ -d '{ "agent": "claude-code", "prompt": "Implement this feature following best practices" }' ``` ### Comparing Attempts ```bash theme={null} # Get all attempts for a task curl http://localhost:5000/api/tasks/{task-id}/attempts # Get specific attempt curl http://localhost:5000/api/task-attempts/{attempt-id} # Stream diff for attempt curl http://localhost:5000/api/events/task-attempts/{attempt-id}/diff ``` ### Attempt States * **pending**: Queued for execution * **running**: AI agent actively working * **completed**: Finished successfully * **failed**: Execution failed * **cancelled**: Manually stopped *** ## Common Task Workflows ### Feature Development ```bash theme={null} # 1. Create feature task POST /api/tasks { "title": "Add dark mode toggle", "type": "feature", "labels": ["frontend", "ui"] } # 2. Try with multiple agents (via UI) # - Attempt 1: Claude Code # - Attempt 2: Cursor CLI # 3. Compare results (via UI) # Choose best implementation # 4. Merge to main PATCH /api/tasks/{id} { "status": "done" } ``` ### Bug Fix ```bash theme={null} # 1. Create bug task POST /api/tasks { "title": "Fix API timeout", "type": "bug", "priority": "high", "description": "API returns 504 after 30 seconds" } # 2. Assign to agent PATCH /api/tasks/{id} { "assignee": "claude-code" } # 3. Monitor execution GET /api/events/processes/{process-id}/logs # 4. Review and merge # Via Web UI ``` ### Code Refactoring ```bash theme={null} # 1. Create refactor task POST /api/tasks { "title": "Extract AuthService from UserController", "type": "refactor", "labels": ["backend", "cleanup"] } # 2. Try multiple approaches # Attempt 1: Extract methods # Attempt 2: Strategy pattern # Attempt 3: Service layer # 3. Compare and choose # Via Web UI comparison view # 4. Verify tests still pass # Check attempt test results # 5. Merge chosen approach ``` *** ## Task Labels Organize tasks with labels: * `feature` - New functionality * `bug` - Bug fixes * `refactor` - Code improvements * `docs` - Documentation * `test` - Testing * `chore` - Maintenance * `frontend` - UI/React code * `backend` - API/server code * `database` - Schema/queries * `devops` - Infrastructure * `security` - Security issues * `critical` - Urgent, blocking * `high` - Important, soon * `medium` - Normal priority * `low` - Nice to have Create your own: * `sprint-24` - Sprint tracking * `customer-reported` - Source * `technical-debt` - Cleanup * `experiment` - Exploratory *** ## Task Templates Create reusable task templates: ```json theme={null} // API Endpoint Template { "title": "Add {resource} API endpoint", "description": "Create REST API endpoint for {resource}\n\nRequirements:\n- Input validation\n- Error handling\n- Tests\n- Documentation", "labels": ["feature", "backend", "api"], "checklist": [ "Create route handler", "Add validation", "Write tests", "Update OpenAPI spec" ] } ``` *** ## Next Steps Manage projects and repositories Complete API documentation MCP integration details Task workflow examples # AI Agents & Executors Source: https://docs.namastex.ai/forge/concepts/agents-and-executors Understanding the 8 AI coding agents and specialized agents ## Introduction Forge supports **two types of agents** that work together to give you ultimate flexibility in AI-assisted development. Understanding the distinction is key to mastering Forge. **The Key Distinction:** * **AI Coding Agents** = The execution platforms (CLI tools that run AI models) * **Specialized Agents** = Custom prompts that work with ANY coding agent * **Example**: Your "test-writer" specialized agent can run on Claude today, Gemini tomorrow *** ## AI Coding Agents vs Specialized Agents ### The Concept Think of it like this: ```mermaid theme={null} graph LR A[Your Task] --> B{Choose AI Coding Agent} B --> C[Claude Code] B --> D[Gemini] B --> E[Cursor CLI] C --> F{Apply Specialized Agent?} D --> F E --> F F --> G[test-writer] F --> H[security-expert] F --> I[pr-reviewer] F --> J[default/none] G --> K[Execute Task] H --> K I --> K J --> K ``` ### Quick Comparison | Aspect | AI Coding Agents | Specialized Agents | | --------------------- | ------------------------------- | ---------------------------- | | **What it is** | The AI execution platform | Custom prompt/instructions | | **Examples** | Claude Code, Gemini, Cursor CLI | test-writer, security-expert | | **How many per task** | Pick ONE | Optional, pick ZERO or ONE | | **Reusability** | Locked to that agent | Works with ANY coding agent | | **Configuration** | API keys, models | Custom prompts, instructions | *** ## The 8 AI Coding Agents Forge can execute tasks using these AI coding agents - including open-source and LLM-agnostic options: **Provider**: Anthropic **Type**: Commercial **Best for**: Complex reasoning, refactoring, architecture ```bash theme={null} forge task attempt 42 --llm claude ``` **Provider**: Open-source **Type**: LLM-agnostic router **Best for**: Using ANY model instead of Claude ```bash theme={null} forge task attempt 42 --llm claude-router ``` Use this to route to local models, Groq, or any other provider! **Provider**: Cursor **Type**: Commercial **Best for**: Fast iterations, UI work, quick fixes ```bash theme={null} forge task attempt 42 --llm cursor ``` **Provider**: Google **Type**: Commercial **Best for**: Cost-effective, multimodal, large context ```bash theme={null} forge task attempt 42 --llm gemini ``` **Provider**: OpenAI **Type**: Commercial **Best for**: Code completion, established patterns ```bash theme={null} forge task attempt 42 --llm codex ``` **Provider**: Sourcegraph **Type**: Commercial **Best for**: Code intelligence, search-augmented ```bash theme={null} forge task attempt 42 --llm amp ``` **Provider**: Open-source **Type**: Fully local **Best for**: Privacy, offline work, cost savings ```bash theme={null} forge task attempt 42 --llm opencode ``` **Provider**: Alibaba (open-source) **Type**: Fully local **Best for**: Multilingual, Asian languages, local execution ```bash theme={null} forge task attempt 42 --llm qwen ``` ### The Power of Choice Unlike other platforms, Forge doesn't force you into specific subscriptions: * **Use open-source models** - OpenCode, Qwen Code run fully local * **Route to any LLM** - Claude Code Router lets you use any provider * **Bring your own API keys** - Pay providers directly, not through Forge * **Mix and match** - Use Claude for architecture, Gemini for tests, OpenCode for refactoring Try multiple agents and choose the best result: ```bash theme={null} # Attempt 1 with Claude forge task attempt 42 --llm claude # Attempt 2 with Gemini forge task attempt 42 --llm gemini # Attempt 3 with Cursor forge task attempt 42 --llm cursor # Compare all three forge task compare 42 # Merge the best one forge task merge 42 2 # Gemini won! ``` *** ## Specialized Agent System **Specialized agents** are custom prompts that modify how any AI coding agent approaches a task. They're reusable, portable, and work with ALL coding agents. ### How They Work ```mermaid theme={null} sequenceDiagram participant User participant Forge participant Specialized as Specialized Agent participant AI as AI Coding Agent User->>Forge: Start attempt with "test-writer" Forge->>Specialized: Load test-writer prompt Specialized->>AI: Inject instructions AI->>AI: Execute with modified behavior AI->>Forge: Return code + tests Forge->>User: Show results ``` ### Built-in Specialized Agents | Agent | Purpose | What it does | | ------------------------- | ------------------ | --------------------------------------------------- | | **test-writer** | Testing focus | Ensures comprehensive test coverage | | **security-expert** | Security hardening | Reviews for vulnerabilities, adds security measures | | **pr-reviewer** | Code review | Analyzes code quality, suggests improvements | | **auth-specialist** | Authentication | Expert in OAuth, JWT, session management | | **performance-optimizer** | Optimization | Focuses on speed, memory, efficiency | | **documentation-writer** | Documentation | Adds JSDoc, README, examples | ### Using Specialized Agents ```bash theme={null} # Use with any coding agent forge task attempt 42 --llm claude --specialized test-writer forge task attempt 42 --llm gemini --specialized security-expert forge task attempt 42 --llm cursor --specialized pr-reviewer # Or configure as default for a task type forge config set task.type.test.specialized test-writer ``` ### Creating Custom Specialized Agents Create your own in `.forge/specialized/`: ```yaml theme={null} # .forge/specialized/api-expert.yaml name: api-expert description: Expert in REST API design and implementation prompt: | You are an expert in REST API design. When implementing this task: 1. Follow RESTful principles strictly 2. Use proper HTTP methods and status codes 3. Implement comprehensive error handling 4. Add request/response validation 5. Include OpenAPI/Swagger documentation 6. Write integration tests for all endpoints Focus on: - Clean resource naming - Versioning strategy - Authentication/authorization - Rate limiting - Caching headers ``` Use it: ```bash theme={null} forge task attempt 42 --llm claude --specialized api-expert ``` *** ## Agent Selection Matrix Choose the right agent for the job: | Task Type | Recommended Agent | Why | | --------------------- | -------------------------- | ---------------------------------- | | **Architecture** | Claude Code | Best reasoning, handles complexity | | **Refactoring** | Claude Code, Cursor | Strong code understanding | | **New Features** | Gemini, Cursor | Fast, cost-effective | | **Bug Fixes** | Cursor CLI | Quick iterations | | **UI Work** | Cursor CLI | Visual focus | | **Security** | Claude + security-expert | Deep analysis | | **Testing** | Gemini + test-writer | Comprehensive, cheap | | **Documentation** | Any + documentation-writer | Consistent style | | **Privacy-sensitive** | OpenCode, Qwen Code | Fully local | | Priority | Strategy | Agents | | --------------- | ----------------- | ------------------------ | | **Speed** | Fast iteration | Cursor CLI, Gemini | | **Quality** | Multiple attempts | Claude + Gemini + Cursor | | **Cost** | Cheap models | Gemini, OpenCode, Qwen | | **Privacy** | Local execution | OpenCode, Qwen Code | | **Reliability** | Proven models | Claude Code | | Budget | Approach | Mix | | ------------- | ------------------------- | --------------------------------------------- | | **No budget** | Open-source only | OpenCode, Qwen Code | | **Limited** | Cheap + selective premium | Gemini (default), Claude (critical) | | **Flexible** | Best tool for job | Claude (complex), Cursor (UI), Gemini (tests) | | **Unlimited** | Quality first | Claude Code everywhere + multiple attempts | *** ## Performance Comparison Real-world data from Namastex Labs (50+ projects): ### Speed (Average task completion) ``` Cursor CLI: ████████░░ 3-5 min Gemini: █████████░ 4-6 min Claude Code: ██████████ 5-8 min Codex: ████████░░ 4-6 min OpenCode: ████░░░░░░ 8-12 min (local) ``` ### Quality (Code review score) ``` Claude Code: ██████████ 9.2/10 Cursor CLI: █████████░ 8.7/10 Gemini: ████████░░ 8.3/10 Codex: ████████░░ 8.1/10 OpenCode: ███████░░░ 7.5/10 ``` ### Cost (Per 1000 tasks) ``` OpenCode: Free (local hardware) Qwen Code: Free (local hardware) Gemini: $45-60 Codex: $80-120 Cursor CLI: $120-160 Claude Code: $180-240 ``` Costs are estimates and vary based on task complexity, context size, and model versions. Always monitor your actual usage. *** ## Best Practices ### Multiple Attempts Strategy For important features, use this proven workflow: ```bash theme={null} # Attempt 1: Quick iteration with Cursor forge task attempt 42 --llm cursor ``` Get a working prototype fast to validate approach. ```bash theme={null} # Attempt 2: Refined version with Claude forge task attempt 42 --llm claude --specialized security-expert ``` Get production-quality code with security review. ```bash theme={null} # Attempt 3: Budget option with Gemini forge task attempt 42 --llm gemini ``` See if cheaper model can match quality. ```bash theme={null} # Review all attempts side-by-side forge task compare 42 # Merge the best forge task merge 42 2 ``` ### Agent-Specific Tips Claude excels at: * System architecture decisions * Complex refactoring * Security-critical code * Understanding large codebases ```bash theme={null} # Good use case forge task create \ --title "Redesign authentication system" \ --llm claude \ --specialized security-expert ``` Gemini is perfect for: * Writing comprehensive tests * Documentation generation * Simple feature implementation * High-volume tasks ```bash theme={null} # Excellent cost/quality ratio forge task create \ --title "Add unit tests for API" \ --llm gemini \ --specialized test-writer ``` Cursor is fastest for: * Quick bug fixes * UI tweaks * Iterative development * Real-time experimentation ```bash theme={null} # When speed is priority forge task create \ --title "Fix button alignment" \ --llm cursor ``` Local models when you need: * Complete privacy (sensitive code) * Offline development * Zero API costs * Full control ```bash theme={null} # For sensitive projects forge task create \ --title "Implement payment processing" \ --llm opencode # Runs 100% locally ``` *** ## Next Steps Configure each AI coding agent Start using agents in your workflow Master the multiple attempts system See agents in action # Git Worktrees Source: https://docs.namastex.ai/forge/concepts/git-worktrees Isolation strategy using git worktrees ## Introduction Forge uses **Git worktrees** to provide complete isolation for every task attempt. This means each AI agent works in its own separate workspace, eliminating conflicts, race conditions, and the fear of breaking your main codebase. **Think of it this way**: Instead of one workspace where everyone fights for control, each task gets its own private sandbox to play in safely. *** ## What are Git Worktrees? Git worktrees allow you to check out multiple branches of the same repository simultaneously in different directories. Unlike traditional branching where you switch contexts in a single workspace, worktrees give you **parallel, isolated environments**. ### Traditional Git vs Git Worktrees ```bash theme={null} # You have ONE working directory ~/my-project/ # Switch branches (context switching) git checkout feature-a # Work on feature A git checkout feature-b # Oops, lost context of feature A # Can only work on one branch at a time # AI agents would conflict with each other ``` **Problem**: Context switching, conflicts, can't run multiple agents simultaneously ```bash theme={null} # You have MULTIPLE working directories ~/my-project/ # Main workspace .forge/worktrees/task-1/ # Feature A workspace .forge/worktrees/task-2/ # Feature B workspace .forge/worktrees/task-3/ # Bug fix workspace # All share the same .git repository # All exist simultaneously # No conflicts between tasks ``` **Solution**: Parallel development, zero conflicts, multiple agents working at once *** ## Why Forge Uses Worktrees ### The Problem Without Worktrees Imagine running multiple AI agents on the same codebase: ```mermaid theme={null} graph TD A[Main Workspace] --> B[Claude Agent Working] A --> C[Gemini Agent Working] A --> D[Cursor Agent Working] B -.->|Conflicts!| C C -.->|Race Conditions!| D D -.->|File Corruption!| B style A fill:#ff6b6b style B fill:#ff6b6b style C fill:#ff6b6b style D fill:#ff6b6b ``` **Result**: Chaos, file conflicts, unpredictable behavior ### The Solution With Worktrees Each task gets its own isolated environment: ```mermaid theme={null} graph TD A[Git Repository] --> B[Main Workspace] A --> C[Task 1 Worktree
Claude Agent] A --> D[Task 2 Worktree
Gemini Agent] A --> E[Task 3 Worktree
Cursor Agent] C -.->|No Conflicts| D D -.->|Fully Isolated| E E -.->|Safe & Parallel| C style A fill:#00D9FF style C fill:#51cf66 style D fill:#51cf66 style E fill:#51cf66 ``` **Result**: Safe parallel execution, no conflicts, easy comparison ### Key Benefits Each attempt runs in its own directory. No risk of agents interfering with each other or your main codebase. Run multiple agents simultaneously. Try Claude and Gemini on the same task at once. Your main branch stays pristine. Experiment fearlessly knowing you can always discard attempts. Review different approaches side-by-side. See exactly what each agent produced. *** ## Automatic Worktree Management Forge handles all worktree operations automatically. You don't need to know git worktree commands! ### What Forge Does For You When you create a task, Forge prepares to create worktrees for attempts: ```bash theme={null} # You do this forge task create --title "Add authentication" # Forge prepares (but doesn't create worktree yet) # Waits for actual attempt execution ``` When an agent starts working, Forge creates the worktree: ```bash theme={null} # You do this forge task attempt --llm claude # Forge does this automatically $ git worktree add .forge/worktrees/task-42-attempt-1 -b task-42-attempt-1 $ cd .forge/worktrees/task-42-attempt-1 $ # Agent works here in isolation ``` The AI agent works in complete isolation: ``` Main repo: Worktree: ~/my-project/ .forge/worktrees/task-42-attempt-1/ ├── src/ ├── src/ │ └── app.js (unchanged) │ └── app.js (modified by agent) ├── tests/ ├── tests/ │ └── ... (unchanged) │ └── auth.test.js (new file!) ``` Your main code is **never touched** during execution. You review changes in the isolated worktree: ```bash theme={null} # See what the agent changed forge task diff 42 1 # Compare multiple attempts forge task compare 42 ``` Choose to merge good work or discard bad attempts: ```bash theme={null} # Merge attempt 1 into main forge task merge 42 1 # Or discard attempt 2 forge task discard 42 2 ``` Forge removes worktrees when done: ```bash theme={null} # Automatic cleanup after merge/discard $ git worktree remove .forge/worktrees/task-42-attempt-1 ``` *** ## Worktree Lifecycle ```mermaid theme={null} sequenceDiagram participant User participant Forge participant Git participant Agent User->>Forge: Create task Forge->>Forge: Prepare task metadata User->>Forge: Start attempt Forge->>Git: git worktree add Git->>Git: Create isolated workspace Forge->>Agent: Execute in worktree Agent->>Agent: Modify code in isolation User->>Forge: Review changes Forge->>User: Show diff alt Approve User->>Forge: Merge attempt Forge->>Git: Merge changes to main Forge->>Git: Remove worktree else Reject User->>Forge: Discard attempt Forge->>Git: Remove worktree end ``` ### Worktree States | State | Description | Location | | ------------- | ---------------------------------------- | ------------------------------------ | | **Pending** | Task created, no worktree yet | N/A | | **Active** | Agent working in worktree | `.forge/worktrees/task-N-attempt-M/` | | **Review** | Work complete, awaiting review | `.forge/worktrees/task-N-attempt-M/` | | **Merged** | Changes merged to main, worktree removed | Deleted | | **Discarded** | Attempt rejected, worktree removed | Deleted | *** ## Best Practices ### DO ✅ Forge handles all worktree operations. Don't create/remove worktrees manually unless you know what you're doing. ```bash theme={null} # Good: Let Forge handle it forge task attempt --llm claude # Bad: Manual worktree creation git worktree add .forge/worktrees/my-task ``` Always check what the agent did before merging: ```bash theme={null} # Review the diff forge task diff 42 1 # Then merge if satisfied forge task merge 42 1 ``` Try different agents on critical features: ```bash theme={null} # Try Claude forge task attempt 42 --llm claude # Try Gemini forge task attempt 42 --llm gemini # Compare results forge task compare 42 ``` Discard failed or unwanted attempts promptly: ```bash theme={null} # Remove attempt 2 if not needed forge task discard 42 2 ``` ### DON'T ❌ **Don't manually modify worktree files** while an agent is running. Let the agent complete its work first. **Don't delete `.forge/worktrees/` manually**. Use `forge task discard` or `forge task merge` to properly clean up. **Don't commit directly in worktrees**. Forge manages all git operations. Manual commits can break the workflow. *** ## Troubleshooting ### Worktree Already Exists ```bash theme={null} Error: worktree '.forge/worktrees/task-42-attempt-1' already exists ``` **Solution**: ```bash theme={null} # List all worktrees git worktree list # Remove the stuck worktree forge task cleanup 42 # Or manually remove it git worktree remove .forge/worktrees/task-42-attempt-1 ``` ### Disk Space Issues Worktrees create full copies of your working directory. For large repos: ```bash theme={null} # Check worktree disk usage du -sh .forge/worktrees/* # Remove old attempts forge task cleanup --all # Configure max concurrent attempts forge config set max_attempts 3 ``` ### Locked Worktrees ```bash theme={null} Error: 'task-42-attempt-1' is locked ``` **Solution**: ```bash theme={null} # Unlock the worktree git worktree unlock .forge/worktrees/task-42-attempt-1 # Remove it git worktree remove .forge/worktrees/task-42-attempt-1 ``` *** ## Advanced: Manual Worktree Operations You rarely need to do this! Forge handles everything automatically. But if you need manual control: ```bash theme={null} # Create a worktree manually git worktree add .forge/worktrees/my-experiment -b feature-xyz # Work in the worktree cd .forge/worktrees/my-experiment # Make changes... # List all worktrees git worktree list # Remove when done cd ../.. git worktree remove .forge/worktrees/my-experiment ``` *** ## Next Steps Learn about task lifecycle and attempts Understand the 8 AI coding agents Start creating tasks with worktree isolation Fix common worktree issues # MCP Architecture Source: https://docs.namastex.ai/forge/concepts/mcp-architecture Model Context Protocol integration and architecture ## Introduction Forge implements the **Model Context Protocol (MCP)** as a built-in server, enabling any MCP-compatible AI agent to programmatically manage your tasks. Think of it as **remote control for your Forge kanban** - control everything without leaving your coding environment. **MCP in one sentence**: A standardized protocol that lets AI agents interact with external tools and services in a structured, secure way. *** ## What is Model Context Protocol? ### The Concept MCP is an open standard that allows AI agents to: * **Discover** available tools and capabilities * **Invoke** operations with structured parameters * **Receive** structured responses * **Maintain** context across multiple operations ```mermaid theme={null} graph LR A[AI Agent
Claude, Cursor, etc.] -->|MCP Protocol| B[MCP Server
Forge] B -->|Tool Discovery| A A -->|Tool Invocation| B B -->|Structured Response| A B -->|Access| C[Forge Database] B -->|Manage| D[Git Worktrees] B -->|Execute| E[AI Coding Agents] ``` ### Why MCP Matters **The Old Way**: Manual context switching ``` 1. Code in your editor 2. Switch to Forge UI 3. Create task manually 4. Copy task details 5. Switch back to editor 6. Continue coding 7. Switch to Forge to check status 8. Repeat... ``` **Result**: Constant interruptions, lost context, broken flow **The New Way**: Stay in flow ``` You: "Create a task to add Redis caching" AI: [Uses MCP to create task in Forge] AI: "Task #47 created. Would you like me to start working on it?" You: "Yes, use Claude agent" AI: [Uses MCP to start attempt with Claude] AI: "Attempt started in isolated worktree. I'll implement caching..." You: "Show me all pending tasks" AI: [Uses MCP to list tasks] AI: "You have 3 pending tasks: #45, #46, #47..." ``` **Result**: Never leave your editor, AI handles Forge management *** ## Forge's MCP Implementation ### Architecture Overview Forge runs as both a **web application** AND an **MCP server** simultaneously: ```mermaid theme={null} graph TD A[Forge Process] --> B[Web Server
Port 3000] A --> C[API Server
Port 8080] A --> D[MCP Server
stdio/socket] E[Browser] -->|HTTP| B F[API Clients] -->|REST| C G[AI Agents] -->|MCP Protocol| D D --> H[Task Management] D --> I[Project Management] D --> J[Worktree Operations] D --> K[Agent Execution] H --> L[(Forge Database)] I --> L J --> M[Git Repository] K --> N[AI Coding Agents] ``` ### Communication Flow When you start your AI agent (Claude Code, Cursor, etc.), it connects to Forge's MCP server: ```bash theme={null} # Forge starts MCP server automatically $ npx automagik-forge --mcp # AI agent connects via stdio AI Agent → MCP Server: CONNECT ``` The AI agent asks what tools are available: ```json theme={null} AI Agent → Forge: "What tools do you have?" Forge → AI Agent: { "tools": [ { "name": "list_tasks", "description": "Get tasks with filters", "parameters": { "projectId": "string", "status": "string" } }, { "name": "create_task", "description": "Create a new task", "parameters": { "title": "string", "description": "string" } }, // ... more tools ] } ``` You ask the AI to do something, it calls the appropriate tool: ``` You: "Create a task to add dark mode" AI Agent → Forge MCP: call create_task({ "projectId": "proj_abc123", "title": "Add dark mode toggle", "description": "Implement dark mode with LocalStorage persistence" }) Forge → AI Agent: { "success": true, "taskId": "task_xyz789", "status": "pending" } ``` The AI processes the response and tells you: ``` AI: "Task #47 created successfully. It's in pending status. Would you like me to start working on it?" ``` *** ## Two Modes: Basic vs Advanced Forge offers two MCP modes with different tool sets: ### Basic Mode (7 Tools) **Use when**: You only need task management ```bash theme={null} # Start in basic mode npx automagik-forge --mcp ``` **Available Tools**: | Tool | Purpose | Example | | --------------- | ---------------------- | --------------------------- | | `list_projects` | Get all projects | "Show my projects" | | `list_tasks` | Get tasks with filters | "Show pending tasks" | | `create_task` | Create new task | "Add task: Fix bug in auth" | | `get_task` | Get task details | "Show task #42" | | `update_task` | Modify task | "Mark task #42 complete" | | `delete_task` | Remove task | "Delete task #38" | **Best for**: Most users. Lighter weight, faster startup, clearer AI responses. ### Advanced Mode (56 Tools) **Use when**: You need full Forge control including worktrees, processes, filesystem ```bash theme={null} # Start in advanced mode npx automagik-forge --mcp-advanced ``` **Available Tools** (Basic 7 + Additional 49): * `create_project` * `update_project` * `delete_project` * `get_project_stats` * `list_project_tasks` * `sync_project_repo` * `configure_project_llms` * `export_project` * `create_attempt` * `list_attempts` * `get_attempt` * `start_attempt` * `stop_attempt` * `retry_attempt` * `compare_attempts` * `merge_attempt` * `discard_attempt` * `get_attempt_diff` * `get_attempt_logs` * `set_attempt_status` * `list_processes` * `get_process` * `start_process` * `stop_process` * `restart_process` * `get_process_logs` * `kill_process` * `process_health_check` * `cleanup_processes` * `list_worktrees` * `create_worktree` * `remove_worktree` * `cleanup_worktrees` * `worktree_status` * `worktree_diff` * `lock_worktree` * `list_drafts` * `create_draft` * `apply_draft` * `list_templates` * `create_from_template` * `read_file` * `write_file` * `list_files` * `file_diff` * `search_files` * `get_file_info` * `send_notification` * `list_integrations` * `configure_webhook` * `send_message` (to WhatsApp, Discord, etc.) * `get_message_status` * And more... **Advanced mode can overwhelm AI agents** with too many tools. They may struggle to choose the right one or give verbose responses. Use basic mode unless you specifically need advanced features. *** ## Security & Authentication ### Project ID Requirement All MCP operations require a **Project ID** for security and isolation: ```json theme={null} { "mcpServers": { "automagik-forge": { "command": "npx", "args": ["automagik-forge", "--mcp"], "env": { "PROJECT_ID": "proj_abc123" // ← Required! } } } } ``` **Why?** * **Isolation**: Agent can only access specified project * **Multi-project**: Run multiple Forge instances with different agents * **Security**: Prevents accidental cross-project operations ### Getting Your Project ID ```bash theme={null} npx automagik-forge ``` Opens browser at `http://localhost:3000` * Create new project or select existing one * Navigate to the project's task board ``` http://localhost:3000/projects/a1b2c3d4-e5f6-7890-abcd-ef1234567890/tasks ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Your Project ID ``` Or find it in **Project Settings** panel. Copy the UUID and add to your AI agent's MCP configuration. ### Data Privacy **Forge MCP server runs locally on your machine**. No data is sent to external servers. All operations happen on localhost. *** ## Typical Workflows ### Planning Workflow ```mermaid theme={null} sequenceDiagram participant You participant AI as AI Agent participant MCP as Forge MCP participant DB as Forge DB You->>AI: "Help me plan authentication system" AI->>AI: Analyzes requirements AI->>MCP: create_task("OAuth integration") MCP->>DB: Store task AI->>MCP: create_task("JWT token management") AI->>MCP: create_task("Password reset flow") AI->>You: "Created 3 tasks. Want to see them?" You->>AI: "Yes" AI->>MCP: list_tasks(project_id) MCP->>AI: Returns tasks AI->>You: "Here are your tasks..." ``` ### Bug Discovery Workflow ```mermaid theme={null} sequenceDiagram participant You participant AI as AI Agent participant MCP as Forge MCP You->>AI: "Found a bug: API crashes on empty JSON" AI->>MCP: create_task({ title: "Fix API crash on empty JSON", type: "bug", priority: "high", description: "..." }) MCP->>AI: Task created #47 AI->>You: "Bug #47 logged. Start fixing now?" You->>AI: "Yes" AI->>MCP: create_attempt(task_id: 47, llm: "claude") MCP->>AI: Attempt started in worktree AI->>You: "Working on fix in isolated environment..." ``` ### Status Update Workflow ``` You: "Mark auth tasks as complete" AI → MCP: list_tasks(filter: "auth") MCP → AI: [Returns 3 auth tasks] AI → MCP: update_task(task_45, status: "completed") AI → MCP: update_task(task_46, status: "completed") AI → MCP: update_task(task_47, status: "completed") AI: "Marked 3 authentication tasks as completed ✅" ``` *** ## Best Practices ### DO ✅ Start with `--mcp` (7 tools). Only upgrade to `--mcp-advanced` if you need specific advanced features. ```bash theme={null} # Start here npx automagik-forge --mcp # Only if needed npx automagik-forge --mcp-advanced ``` Configure each AI agent with a specific project ID: ```json theme={null} // Claude Code → Project A { "env": { "PROJECT_ID": "proj_frontend123" } } // Cursor → Project B { "env": { "PROJECT_ID": "proj_backend456" } } ``` MCP tools work best with conversational requests: ``` ✅ "Create a task to add Redis caching with TTL config" ✅ "Show me all high-priority bugs" ✅ "Mark task #42 as complete and create a follow-up for documentation" ❌ create_task(title="Redis", desc="cache") ❌ list_tasks() ``` Let the AI translate your intent to MCP calls. ### DON'T ❌ **Don't mix MCP modes for the same project**. Pick basic OR advanced, not both. **Don't share Project IDs across users**. Each developer should have their own project or use different IDs. **Don't forget to restart your AI agent** after changing MCP configuration. *** ## Troubleshooting ### MCP Server Not Found ``` Error: MCP server 'automagik-forge' not found ``` **Solution**: 1. Make sure Forge is installed: `npm install -g @automagik/forge` 2. Verify command in config is correct: `"command": "npx"` 3. Check args: `"args": ["automagik-forge", "--mcp"]` 4. Restart your AI agent ### Project ID Invalid ``` Error: Project 'proj_abc123' not found ``` **Solution**: 1. Open Forge UI: `npx automagik-forge` 2. Verify project exists 3. Copy correct UUID from browser URL 4. Update MCP config with correct ID 5. Restart AI agent ### Too Many Tools (Advanced Mode) ``` AI: "I see many tools available. Which one should I use?" ``` **Solution**: Switch to basic mode ```json theme={null} { "args": ["automagik-forge", "--mcp"] // Remove -advanced } ``` *** ## Next Steps Configure MCP for your AI agent Complete list of all available tools MCP configuration for Claude Code MCP configuration for Cursor # Tasks & Attempts Source: https://docs.namastex.ai/forge/concepts/tasks-and-attempts Understanding task lifecycle and multiple attempts strategy ## The Power of Structured Task Management In Forge, every piece of work is organized as a **Task** - a persistent, trackable unit of work that maintains complete context, history, and results. Unlike chat-based AI interactions that disappear, Forge tasks live forever in your Kanban board. *** ## What is a Task? A **Forge Task** is a structured work unit that contains: * **Title & Description**: Clear statement of what needs to be done * **Context**: Files, screenshots, diagrams attached for AI understanding * **Agent Assignment**: Which AI coding agent will execute it * **Attempts**: Multiple execution attempts with different agents or approaches * **Git Worktree**: Isolated environment for each attempt * **Diffs & Results**: Complete history of changes made * **Status**: Lifecycle state (planning, in-progress, review, merged, archived) **Example Task Structure:** ```yaml theme={null} Task: "Implement JWT authentication" ├── Title: "Add JWT-based user authentication" ├── Description: "Create login/signup endpoints with JWT tokens" ├── Labels: ["feature", "auth", "priority:high"] ├── Context: [auth-flow-diagram.png, requirements.md] ├── Attempts: │ ├── Attempt 1: Claude Code (completed) │ ├── Attempt 2: Gemini (completed) │ └── Attempt 3: Cursor CLI (in-progress) └── Status: in-review ``` Tasks are **not temporary** - they persist in your board, maintaining full context even weeks or months later. *** ## Task Lifecycle Every task moves through a well-defined lifecycle: ```mermaid theme={null} graph LR A[Planning] --> B[Ready] B --> C[In Progress] C --> D[Review] D --> E{Approved?} E -->|Yes| F[Merged] E -->|No| C F --> G[Archived] style A fill:#FF00FF style C fill:#00FFFF style F fill:#00FF00 ``` ### Lifecycle States | State | Description | Actions Available | | --------------- | ---------------------------------------- | ------------------------------------------------------- | | **Planning** | Task created, context being gathered | Add context, assign agent, edit description | | **Ready** | Ready for execution | Start attempt, assign different agent | | **In Progress** | AI agent actively working | Monitor logs, cancel if needed | | **Review** | Attempt completed, awaiting human review | View diffs, compare with other attempts, approve/reject | | **Merged** | Approved changes merged to main branch | Archive task, create follow-up tasks | | **Archived** | Task completed and stored | View history, reference in future tasks | ### State Transitions * **Planning → Ready**: When you've added enough context and assigned an agent * **Ready → In Progress**: When you start an attempt * **In Progress → Review**: When the agent completes execution * **Review → In Progress**: If you reject and want to retry * **Review → Merged**: When you approve and merge changes * **Merged → Archived**: After verification and cleanup *** ## Multiple Attempts Strategy The **killer feature** of Forge: **every task can have multiple attempts** with different AI agents, configurations, or approaches. ### Why Multiple Attempts? Different AI models excel at different things: | Agent | Strengths | Best For | | ---------------- | --------------------------- | ----------------------------------------------- | | **Claude Code** | Complex logic, architecture | Large refactors, system design | | **Gemini** | Simplicity, speed | Quick features, straightforward implementations | | **Cursor CLI** | Balance, pragmatism | Production code, balanced solutions | | **OpenAI Codex** | Broad knowledge | General-purpose tasks | **The Problem with Single-Attempt AI:** * You're stuck with one agent's approach * No way to compare quality * Can't learn which agent works best for which task type * Miss better solutions from other models **The Forge Solution:** ```yaml theme={null} Task: "Optimize database queries" Attempt 1: Claude Code ├── Approach: Complex indexing strategy with materialized views ├── Result: 10x faster but complex to maintain └── Verdict: Too complex Attempt 2: Gemini ├── Approach: Simple query optimization, added indexes ├── Result: 3x faster, easy to understand └── Verdict: Good but could be better Attempt 3: Cursor CLI ├── Approach: Balanced - smart indexes + query rewrite ├── Result: 7x faster, maintainable └── Verdict: ✅ Perfect! Merge this one ``` ### Isolation is Key Each attempt runs in its own **Git worktree**: * No conflicts between attempts * Main branch stays clean * Easy to compare approaches side-by-side * Safe to experiment without fear *** ## When to Use Multiple Attempts Not every task needs multiple attempts. Here's when to use them: ### ✅ Use Multiple Attempts For: Features affecting many users or core business logic **Example**: Payment processing, authentication systems Major architectural changes with high risk **Example**: Migrating from REST to GraphQL When you need the best possible solution **Example**: Database query optimization, API response times When you want to see different approaches **Example**: Learning new patterns or best practices ### ❌ Single Attempt is Fine For: * Simple bug fixes * Documentation updates * Minor UI tweaks * Quick configuration changes * Low-risk experiments ### The Cost-Benefit Analysis **Multiple Attempts Cost:** * More time (each agent runs separately) * More API usage (multiple LLM calls) * More review time (comparing results) **Multiple Attempts Benefit:** * Higher quality solutions * Better understanding of the problem * Learning which agents work best * Reduced risk of bugs in production **Rule of Thumb**: If a bug would cost more than 30 minutes to fix in production, use multiple attempts during development. *** ## Comparing Attempts Forge makes it easy to compare different attempts: ### Comparison Features **1. Side-by-Side Diffs** ``` Attempt 1 (Claude) Attempt 2 (Gemini) ────────────────── ────────────────── function authenticate() { function auth() { // 50 lines of complex // 20 lines simple // logic with comments // straightforward } } ``` **2. Metrics Comparison** | Metric | Attempt 1 | Attempt 2 | Attempt 3 | | -------------- | --------- | --------- | --------- | | Lines Changed | 250 | 120 | 180 | | Files Modified | 8 | 4 | 5 | | Tests Added | 15 | 8 | 12 | | Execution Time | 8 min | 3 min | 5 min | | Complexity | High | Low | Medium | **3. Code Quality Indicators** * Test coverage added * Documentation quality * Code complexity metrics * Performance impact * Security considerations ### Making the Choice Read through each attempt's changes carefully Verify all attempts pass your test suite Which code will you understand in 6 months? Run benchmarks if relevant Select the best attempt or cherry-pick from multiple Merge the chosen attempt to your main branch ### Cherry-Picking Best Parts Sometimes you want parts from multiple attempts: ```bash theme={null} # Forge makes it easy to combine attempts forge attempt merge 1 --files src/auth.ts forge attempt merge 2 --files src/tests/ forge attempt merge 3 --files src/config.ts ``` *** ## Best Practices **Anti-Pattern**: Creating 10 attempts for every tiny task. This wastes time and API credits. **Best Practice**: Use judgment - critical features get 2-3 attempts, simple tasks get 1. ### Task Creation Tips 1. **Clear Titles**: "Add user auth" ✅ vs "Do stuff" ❌ 2. **Detailed Descriptions**: Include acceptance criteria, edge cases, examples 3. **Attach Context**: Screenshots, diagrams, related code files 4. **Label Appropriately**: feature, bug, refactor, docs, etc. 5. **Set Realistic Scope**: Smaller tasks = better AI results ### Attempt Management Tips 1. **Start with Your Best Agent**: Use the agent you trust most first 2. **Try Different Approaches**: Second attempt should use a different strategy 3. **Cancel Bad Attempts Early**: Don't waste time on obviously wrong directions 4. **Document Learnings**: Note which agents work best for which task types 5. **Review Before Merging**: Never auto-merge without human review *** ## Real-World Example ### Scenario: Adding File Upload Feature **Task Created:** ``` Title: "Add file upload with progress tracking" Description: "Users should be able to upload images/PDFs with real-time progress bars" Labels: ["feature", "frontend", "priority:medium"] Context: [design-mockup.png, API-spec.md] ``` **Attempt 1: Claude Code** * Generated comprehensive solution with chunked uploads * Added retry logic, error handling * 300 lines of code, very robust * **Review**: Too complex for MVP, over-engineered **Attempt 2: Gemini** * Simple FormData upload with progress event * Basic error handling * 80 lines of code * **Review**: Too simple, missing edge cases **Attempt 3: Cursor CLI** * Balanced approach with FormData + basic chunking * Good error handling without complexity * 150 lines of code * **Review**: ✅ Perfect balance - merged! **Outcome**: Shipped a maintainable feature by comparing 3 approaches in isolated environments. *** ## Next Steps Learn how isolation works under the hood Understand the 8 different AI coding agents Start creating your first task Deep dive into attempt comparison # Vibe Coding++™ Source: https://docs.namastex.ai/forge/concepts/vibe-coding-plus The philosophy behind human-AI collaboration in Forge ## The Evolution of AI-Assisted Development Forge introduces **Vibe Coding++™** - a revolutionary approach that transforms chaotic AI interactions into structured, maintainable development workflows. *** ## The Problem: Regular Vibe Coding ### The "2-Week Curse" You've experienced it: AI generates perfect code today. Two weeks later, something breaks, and you can't fix it because you don't understand what was built. **The 2-Week Curse**: Code that works perfectly when shipped but becomes unmaintainable within weeks because the developer never understood the AI-generated solution. ### Why Regular Vibe Coding Fails | Problem | Impact | | ---------------------- | ---------------------------------------------- | | **Lost Context** | Conversations scattered across chat histories | | **No Structure** | Random .md files, no task tracking | | **No Control** | AI makes all decisions autonomously | | **No Memory** | "What did we build last week?" Lost forever | | **No Experimentation** | Stuck with one agent's approach | | **No Review** | Code applied immediately without understanding | *** ## The Solution: Vibe Coding++™ ### Philosophy: You Orchestrate, AI Executes Vibe Coding++™ flips the script - **humans stay in control** while leveraging AI power: ```mermaid theme={null} graph LR A[You Plan Tasks] --> B[You Choose Agents] B --> C[Try Multiple Attempts] C --> D[Compare Results] D --> E[You Review & Decide] E --> F[Ship Confident Code] style A fill:#FF00FF style E fill:#00FFFF style F fill:#00FF00 ``` ### The Key Differences * AI acts autonomously * Lost in chat conversations * One AI, one approach * Direct code changes * Auto-applies changes * Black box magic * Mysterious bugs in 2 weeks * You orchestrate every decision * Persistent Kanban board * Try 8+ different AI agents * Isolated Git worktrees * Review before merge * You understand the code * Code that won't break mysteriously *** ## How Vibe Coding++™ Works ### 1. You Own the Kanban Tasks live in a persistent board, not lost in chat history or scattered .md files: Every task card contains complete context, attempts, results, and diffs - **permanent structured memory**. ### 2. You Pick the Agent Not happy with Claude's approach? Try Gemini. Want a third opinion? Use Cursor CLI: ```yaml theme={null} Task: "Implement user authentication" ├── Attempt 1: Claude Code → Too complex ├── Attempt 2: Gemini → Missing edge cases ├── Attempt 3: Cursor CLI → Perfect! ✅ └── Result: You choose Attempt 3 to merge ``` ### 3. Git Worktree Isolation Every attempt runs in its own isolated environment: * **No conflicts** between experiments * **No broken main branch** while testing * **Easy cleanup** after choosing the winner ### 4. You Review & Understand Before any code touches your main branch: * See **exactly what changed** * Understand **why** changes were made * Compare **different approaches** side-by-side * **Approve or reject** with full knowledge *** ## The Vibe Coding++™ Manifesto ### Our Core Principles * **You orchestrate** - AI executes * **You decide** - AI suggests * **You understand** - AI explains * **You own** - No vendor lock-in * **You experiment** - AI delivers options * **You review** - AI waits for approval *** ## Real-World Example ### Before: Regular Vibe Coding ``` Developer: "Build an auth system" AI: *generates code* Developer: "Looks good!" *ships it* [2 weeks later] Developer: "Why is auth broken?" AI: "Let me regenerate it..." Developer: "But I don't know what it does!" ``` ### After: Vibe Coding++™ ``` Developer: Creates task "Implement JWT authentication" Developer: Try Claude Code → Review: Too complex, over-engineered Developer: Try Gemini → Review: Simple but missing refresh tokens Developer: Try Cursor CLI → Review: Perfect balance! ✅ Developer: Merges Cursor's approach → Understands every line → Can maintain and extend it → No mysterious bugs in 2 weeks ``` *** ## The Power of Multiple Attempts Each task can have multiple attempts with different agents: Different AI models have different strengths: * Claude excels at complex logic * Gemini is great for simplicity * Cursor CLI balances both **Multiple attempts let you find the perfect fit.** Use multiple attempts for: * Critical features affecting many users * Complex refactoring with high risk * Security-sensitive implementations * Learning different approaches to a problem Forge shows side-by-side diffs: * See implementation differences * Compare code complexity * Review test coverage * Choose the best or combine approaches *** ## Breaking the 2-Week Curse Vibe Coding++™ breaks the curse through **structured human control**: You break down work into clear, focused tasks Try different agents in isolated worktrees Review diffs and understand every change Merge only what you understand and approve Code you understand is code you can maintain *** ## Comparison Table | Feature | Regular Vibe Coding | Vibe Coding++™ (Forge) | | ---------------------- | ---------------------- | -------------------------------- | | **Human Control** | ❌ AI acts autonomously | ✅ You orchestrate every decision | | **Task Persistence** | ❌ Lost in chat | ✅ Kanban board forever | | **Multiple Attempts** | ❌ One AI, one shot | ✅ Try 8+ agents per task | | **AI Coding Agents** | ❌ Single model | ✅ Claude, Cursor, Gemini, etc. | | **Specialized Agents** | ❌ Fixed behavior | ✅ Custom prompts for any agent | | **Git Isolation** | ❌ Direct changes | ✅ Worktree per attempt | | **Code Review** | ❌ Auto-applies | ✅ Review before merge | | **2-Week Protection** | ❌ Black box code | ✅ You understand everything | | **Visual Context** | ⚠️ Limited | ✅ Attach screenshots to tasks | | **Open Source** | ⚠️ Varies | ✅ 100% MIT licensed | | **Self-Hostable** | ⚠️ Varies | ✅ Your infrastructure | | **Vendor Lock-in** | ❌ Often locked | ✅ Agent-agnostic | *** ## Next Steps Learn about the task lifecycle and multiple attempts Understand isolation strategy Explore the 8 AI coding agents Try Vibe Coding++™ in 5 minutes *** **Vibe Coding++™ is not about replacing AI - it's about amplifying human potential through structured collaboration.** The future is not humans vs AI. It's humans **amplified** by AI. And Forge is the platform that makes this a reality. # Environment Variables Source: https://docs.namastex.ai/forge/config/environment-variables Configure Forge with environment variables ## Overview Forge uses environment variables for configuration. Set these in your shell, `.env` file, or deployment platform. **Never commit secrets!** Add `.env` to your `.gitignore` and use environment-specific configuration for production. *** ## Core Configuration ### Server Configuration The host address for the Forge backend server ```bash theme={null} HOST=0.0.0.0 # Listen on all interfaces ``` Port for the backend API server. Auto-assigned by `scripts/setup-dev-environment.js` in development ```bash theme={null} BACKEND_PORT=8080 ``` Port for the frontend development server ```bash theme={null} FRONTEND_PORT=3000 ``` *** ## GitHub Integration ### OAuth Configuration GitHub OAuth App Client ID for custom authentication ```bash theme={null} GITHUB_CLIENT_ID=Iv1.1234567890abcdef ``` Not required for basic usage. Forge includes default OAuth credentials for development. Set this only if you want to use your own GitHub OAuth App. GitHub OAuth App Client Secret (production only) ```bash theme={null} GITHUB_CLIENT_SECRET=your_secret_here ``` **Never commit this!** Use secret management services in production (AWS Secrets Manager, HashiCorp Vault, etc.) ### Creating Your Own GitHub OAuth App If you want to use your own GitHub OAuth credentials: Go to [GitHub Developer Settings](https://github.com/settings/developers) → OAuth Apps → New OAuth App * **Application name**: "My Forge Instance" * **Homepage URL**: `http://localhost:3000` * **Authorization callback URL**: `http://localhost:3000/auth/github/callback` After creating, copy the **Client ID** and generate a **Client Secret** ```bash theme={null} export GITHUB_CLIENT_ID=your_client_id export GITHUB_CLIENT_SECRET=your_client_secret ``` *** ## Analytics & Monitoring PostHog API key for analytics (optional) ```bash theme={null} POSTHOG_API_KEY=phc_1234567890abcdef ``` Forge includes optional PostHog integration for usage analytics. This is completely optional and disabled by default. *** ## Development & Debugging Disable automatic cleanup of orphaned git worktrees (debug mode) ```bash theme={null} DISABLE_WORKTREE_ORPHAN_CLEANUP=1 ``` Only use this for debugging worktree issues. Leaving it enabled will accumulate orphaned worktrees over time. Rust logging level for backend debugging ```bash theme={null} RUST_LOG=debug # Detailed logs RUST_LOG=info # Normal logs (default) RUST_LOG=warn # Warnings only RUST_LOG=error # Errors only ``` Enable Rust backtraces for debugging ```bash theme={null} RUST_BACKTRACE=1 # Basic backtraces RUST_BACKTRACE=full # Full backtraces with all details ``` *** ## Database Configuration Forge uses SQLite by default. The database is automatically created and seeded from `dev_assets_seed/` on first run. SQLite database path (advanced use only) ```bash theme={null} DATABASE_URL=sqlite:./my-custom-forge.db ``` Changing this requires manual database setup. Use the default unless you know what you're doing. *** ## Using .env Files Create a `.env` file in your project root: ```bash .env theme={null} # Server Configuration HOST=127.0.0.1 BACKEND_PORT=8080 FRONTEND_PORT=3000 # GitHub OAuth (optional) GITHUB_CLIENT_ID=your_client_id_here # Analytics (optional) # POSTHOG_API_KEY=your_key_here # Development RUST_LOG=info ``` **Multiple environments?** Use `.env.development`, `.env.production`, etc., and load them with tools like [dotenv](https://github.com/motdotla/dotenv) or deployment platform features. *** ## Environment-Specific Configuration ### Development ```bash .env.development theme={null} HOST=127.0.0.1 FRONTEND_PORT=3000 RUST_LOG=debug DISABLE_WORKTREE_ORPHAN_CLEANUP=1 ``` ### Production ```bash .env.production theme={null} HOST=0.0.0.0 BACKEND_PORT=8080 FRONTEND_PORT=80 RUST_LOG=warn # Use secret management for these GITHUB_CLIENT_ID=${GITHUB_CLIENT_ID} GITHUB_CLIENT_SECRET=${GITHUB_CLIENT_SECRET} ``` ### CI/CD ```bash .env.ci theme={null} RUST_LOG=error RUST_BACKTRACE=1 # Minimal config for testing ``` *** ## Verification Check your configuration is working: ```bash theme={null} # Start Forge automagik-forge # Should see output like: # ✓ Backend running on http://127.0.0.1:8080 # ✓ Frontend running on http://localhost:3000 # ✓ GitHub OAuth: Using default credentials ``` *** ## Troubleshooting Change `BACKEND_PORT` or `FRONTEND_PORT`: ```bash theme={null} FRONTEND_PORT=3001 automagik-forge ``` 1. Check `GITHUB_CLIENT_ID` is set correctly 2. Verify OAuth callback URL matches your GitHub App settings 3. Try using default credentials (remove `GITHUB_CLIENT_ID`) Remove the database and let Forge recreate it: ```bash theme={null} rm -rf dev_assets/ automagik-forge ``` *** ## Security Best Practices Add `.env` to `.gitignore` immediately ```bash .gitignore theme={null} .env .env.* !.env.example ``` In production, use services like: * AWS Secrets Manager * HashiCorp Vault * Kubernetes Secrets * Platform-specific solutions Regularly rotate OAuth secrets and API keys Grant minimal permissions to GitHub OAuth apps *** ## Next Steps Configure AI coding agents Deep dive into GitHub integration Understand Forge's file organization # GitHub OAuth Source: https://docs.namastex.ai/forge/config/github-oauth Configure GitHub authentication for Forge ## Overview Forge integrates deeply with GitHub for repository management, authentication, and collaboration. GitHub OAuth enables secure, seamless access to your repositories. **Good News**: Forge includes default OAuth credentials for development. Custom configuration is optional! *** ## Quick Start (Default Credentials) For most users, no configuration is needed: ```bash theme={null} forge start # Opens http://localhost:3000 ``` The UI will show "Sign in with GitHub" GitHub will ask to authorize the default Forge OAuth app You're authenticated and ready to create tasks! The default credentials are perfect for local development and testing. No setup required! *** ## Custom GitHub OAuth App Want to use your own OAuth app? Here's how to set it up. ### Why Use Custom OAuth? * **Production deployments** on custom domains * **Enterprise environments** with specific security requirements * **Team collaboration** with your organization's branding * **Higher rate limits** specific to your app *** ## Creating Your OAuth App Navigate to [GitHub Developer Settings](https://github.com/settings/developers) → **OAuth Apps** → **New OAuth App** ```yaml theme={null} Application name: My Forge Instance Homepage URL: http://localhost:3000 Authorization callback URL: http://localhost:3000/auth/github/callback ``` The **callback URL must match exactly**! Include protocol (`http://` or `https://`) Click "Register application" After creation, click **"Generate a new client secret"** **Copy the secret immediately!** GitHub only shows it once. You'll have: * **Client ID**: `Iv1.1234567890abcdef` * **Client Secret**: `1234567890abcdef1234567890abcdef12345678` *** ## Configuration ### Environment Variables Set your custom credentials via environment variables: ```bash theme={null} export GITHUB_CLIENT_ID=Iv1.1234567890abcdef export GITHUB_CLIENT_SECRET=1234567890abcdef1234567890abcdef12345678 ``` Or in a `.env` file: ```bash .env theme={null} GITHUB_CLIENT_ID=Iv1.1234567890abcdef GITHUB_CLIENT_SECRET=1234567890abcdef1234567890abcdef12345678 ``` ### Start Forge ```bash theme={null} forge start # You should see: # ✓ GitHub OAuth: Using custom credentials # ✓ Backend running on http://127.0.0.1:8080 # ✓ Frontend running on http://localhost:3000 ``` *** ## Multiple Environments ### Development ```bash .env.development theme={null} # Use default Forge credentials (no config needed) # OR set custom: GITHUB_CLIENT_ID=Iv1.dev_client_id GITHUB_CLIENT_SECRET=dev_secret ``` **OAuth App Settings**: ```yaml theme={null} Homepage URL: http://localhost:3000 Callback URL: http://localhost:3000/auth/github/callback ``` ### Staging ```bash .env.staging theme={null} GITHUB_CLIENT_ID=Iv1.staging_client_id GITHUB_CLIENT_SECRET=${STAGING_GITHUB_SECRET} ``` **OAuth App Settings**: ```yaml theme={null} Homepage URL: https://forge-staging.yourdomain.com Callback URL: https://forge-staging.yourdomain.com/auth/github/callback ``` ### Production ```bash .env.production theme={null} GITHUB_CLIENT_ID=${GITHUB_CLIENT_ID} GITHUB_CLIENT_SECRET=${GITHUB_CLIENT_SECRET} ``` **OAuth App Settings**: ```yaml theme={null} Homepage URL: https://forge.yourdomain.com Callback URL: https://forge.yourdomain.com/auth/github/callback ``` **Never hardcode production secrets!** Use secret management: * AWS Secrets Manager * HashiCorp Vault * Kubernetes Secrets * Azure Key Vault * Google Secret Manager *** ## Permissions & Scopes ### Required Scopes Forge requests these GitHub OAuth scopes: | Scope | Purpose | Required | | ------------ | ---------------------------- | ----------- | | `repo` | Read/write repository access | ✅ Yes | | `user:email` | Access user email | ✅ Yes | | `read:user` | Read user profile | ✅ Yes | | `workflow` | Manage GitHub Actions | ⚠️ Optional | ### Why Each Scope? **What it does**: Full control of private repositories **Why needed**: * Clone repositories for tasks * Create and manage git worktrees * Commit changes from AI agents * Push branches and create PRs This is the core permission Forge needs to function **What it does**: Access user email addresses **Why needed**: * Associate commits with correct author * Send notifications (if enabled) * User identification in audit logs **What it does**: Read user profile information **Why needed**: * Display username and avatar in UI * Team collaboration features * Activity tracking **What it does**: Access GitHub Actions workflows **Why needed**: * Trigger CI/CD on task completion * Monitor workflow status * Auto-deployment features Only needed if you use GitHub Actions integration *** ## Testing Your OAuth Setup ### Verify Configuration ```bash theme={null} # Start Forge with your credentials GITHUB_CLIENT_ID=your_id GITHUB_CLIENT_SECRET=your_secret forge start # Check logs for: ✓ GitHub OAuth: Using custom credentials ✓ Client ID: Iv1.xxx... ``` ### Test Authentication Flow Navigate to [http://localhost:3000](http://localhost:3000) Should redirect to GitHub authorization page Should show YOUR app name (not "Forge by Namastex Labs") Click "Authorize" and you should be redirected back You should see your GitHub avatar and username in Forge UI *** ## Troubleshooting **Error**: "The redirect\_uri MUST match the registered callback URL for this application" **Solution**: 1. Check your OAuth app settings on GitHub 2. Ensure callback URL exactly matches (including protocol and port) 3. For local dev: `http://localhost:3000/auth/github/callback` 4. Update OAuth app if needed **Error**: "Invalid OAuth client\_id" **Solution**: * Verify `GITHUB_CLIENT_ID` is correct * Check for extra spaces or quotes * Ensure OAuth app isn't deleted * Try regenerating client secret **Error**: Authentication completes but user not logged in **Solution**: * Check `GITHUB_CLIENT_SECRET` is correct * Ensure secret hasn't been rotated * Verify environment variables are loaded * Check backend logs for detailed errors **Error**: "API rate limit exceeded" **Solution**: * Create authenticated OAuth app (higher limits) * Use personal access token for development * Implement caching for repository data * Contact GitHub for higher limits **Error**: OAuth redirect fails in browser **Solution**: Use `127.0.0.1` instead of `localhost`: ```yaml theme={null} Callback URL: http://127.0.0.1:3000/auth/github/callback ``` Some browsers treat these differently! *** ## Security Best Practices Generate new client secrets every 90 days ```bash theme={null} # GitHub Settings → OAuth Apps # → Your App → Generate new client secret ``` Only request permissions you actually need Remove `workflow` scope if not using Actions Review GitHub OAuth authorizations periodically [github.com/settings/applications](https://github.com/settings/applications) Never commit secrets to version control ```bash .gitignore theme={null} .env .env.production .env.local ``` *** ## Advanced: Organization OAuth Apps For team deployments, use GitHub Organization OAuth apps: `https://github.com/organizations/YOUR_ORG/settings/applications` Same process as personal OAuth app Configure which repositories Forge can access Use organization OAuth credentials in Forge config ### Organization Benefits * **Centralized management**: Admins control OAuth apps * **Fine-grained permissions**: Restrict repository access * **Audit logs**: Track all OAuth usage * **Team collaboration**: Share Forge instance across team *** ## Production Deployment Checklist * Use your production domain * Set HTTPS callback URL * Document client ID/secret securely ```bash theme={null} # AWS Secrets Manager aws secretsmanager create-secret \ --name forge/github/client-secret \ --secret-string "your_secret" # Kubernetes kubectl create secret generic forge-github \ --from-literal=client-id=your_id \ --from-literal=client-secret=your_secret ``` ```bash theme={null} GITHUB_CLIENT_ID=$(get-secret forge/github/client-id) GITHUB_CLIENT_SECRET=$(get-secret forge/github/client-secret) ``` * Test OAuth from production domain * Verify callback redirects correctly * Check user can access repositories * Set calendar reminder for 90-day rotation * Monitor OAuth access logs * Track API rate limits *** ## Rate Limits ### GitHub API Limits | Authentication | Requests/Hour | Notes | | --------------- | ------------- | -------------- | | Unauthenticated | 60 | Very limited | | OAuth App | 5,000 | Standard limit | | GitHub App | 15,000+ | Higher limit | | Enterprise | Custom | Contact GitHub | ### Optimizing Rate Limit Usage ```typescript theme={null} // Cache repository data locally const cache = new Map(); async function getRepo(owner, repo) { const key = `${owner}/${repo}`; if (cache.has(key)) return cache.get(key); const data = await github.getRepo(owner, repo); cache.set(key, data); return data; } ``` ```typescript theme={null} // Batch multiple operations const repos = await github.listRepos({ per_page: 100 }); // Instead of: // for (const repo of repos) { // await github.getRepo(repo.name); // } ``` Use webhooks instead of polling: ```yaml theme={null} # Receive events instead of checking webhook_url: https://forge.yourdomain.com/webhooks/github events: - push - pull_request - issues ``` *** ## Next Steps Complete configuration reference Set up AI coding agents Create your first task Understand Forge's organization # LLM Configuration Source: https://docs.namastex.ai/forge/config/llm-configuration Configure AI coding agents in Forge ## Overview Forge supports **8 AI coding agents** out of the box. Each agent needs proper configuration before use. **BYOL Architecture**: Forge uses a "Bring Your Own LLM" model - you provide API keys, Forge handles orchestration. *** ## Supported AI Agents | Agent | Type | Setup Required | | ---------------------- | ----- | -------------------------- | | **Claude Code** | API | Anthropic API key | | **Claude Code Router** | API | Any LLM API key (agnostic) | | **Cursor CLI** | CLI | Cursor account | | **Gemini** | API | Google AI API key | | **OpenAI Codex** | API | OpenAI API key | | **Amp** | API | Sourcegraph token | | **OpenCode** | Local | Model weights | | **Qwen Code** | Local | Model weights | *** ## Configuration File Forge stores LLM configuration in `.forge/config.json`: ```json .forge/config.json theme={null} { "llms": { "claude": { "apiKey": "sk-ant-...", "model": "claude-3-5-sonnet-20241022", "maxTokens": 4096 }, "gemini": { "apiKey": "AIza...", "model": "gemini-2.0-flash-exp" }, "openai": { "apiKey": "sk-...", "model": "gpt-4-turbo", "organization": "org-..." } }, "worktrees": { "enabled": true, "basePath": "./.forge/worktrees" } } ``` **Never commit `.forge/config.json`!** Add it to `.gitignore` immediately: ```bash theme={null} echo ".forge/" >> .gitignore ``` *** ## Claude Code Setup ### Get Your API Key Go to [console.anthropic.com](https://console.anthropic.com) Navigate to API Keys → Create Key ```json theme={null} { "llms": { "claude": { "apiKey": "sk-ant-api03-...", "model": "claude-3-5-sonnet-20241022", "maxTokens": 8192 } } } ``` ### Available Models | Model | Context | Best For | | ---------------------------- | ------- | ---------------------------- | | `claude-3-5-sonnet-20241022` | 200K | General coding (recommended) | | `claude-3-opus-20240229` | 200K | Complex refactoring | | `claude-3-haiku-20240307` | 200K | Fast iterations | ### Advanced Configuration ```json theme={null} { "llms": { "claude": { "apiKey": "sk-ant-...", "model": "claude-3-5-sonnet-20241022", "maxTokens": 8192, "temperature": 0.7, "timeout": 60000, "retries": 3 } } } ``` *** ## Claude Code Router Setup Claude Code Router is **LLM-agnostic** - use any model with an OpenAI-compatible API! ### Configuration ```json theme={null} { "llms": { "claude-router": { "apiKey": "your-api-key", "baseUrl": "https://api.openai.com/v1", // Or any compatible endpoint "model": "gpt-4-turbo", "provider": "openai" // openai, anthropic, custom } } } ``` ### Supported Providers ```json theme={null} { "claude-router": { "apiKey": "sk-...", "baseUrl": "https://api.openai.com/v1", "model": "gpt-4-turbo", "provider": "openai" } } ``` ```json theme={null} { "claude-router": { "apiKey": "sk-ant-...", "baseUrl": "https://api.anthropic.com/v1", "model": "claude-3-5-sonnet-20241022", "provider": "anthropic" } } ``` ```json theme={null} { "claude-router": { "baseUrl": "http://localhost:11434/v1", "model": "codellama:34b", "provider": "ollama" } } ``` ```json theme={null} { "claude-router": { "apiKey": "your-key", "baseUrl": "https://your-api.example.com/v1", "model": "your-model", "provider": "custom" } } ``` *** ## Gemini Setup ### Get Your API Key Visit [aistudio.google.com](https://aistudio.google.com) Click "Get API Key" → Create API key ```json theme={null} { "llms": { "gemini": { "apiKey": "AIza...", "model": "gemini-2.0-flash-exp" } } } ``` ### Available Models | Model | Context | Best For | | ---------------------- | ------- | ----------------------------- | | `gemini-2.0-flash-exp` | 1M | Fast iterations (recommended) | | `gemini-1.5-pro` | 2M | Large codebases | | `gemini-1.5-flash` | 1M | Quick tasks | *** ## Cursor CLI Setup Cursor CLI is separate from the Cursor IDE. You can use it independently! ### Installation ```bash theme={null} # Install Cursor CLI npm install -g @cursor/cli # Authenticate cursor auth login ``` ### Configuration ```json theme={null} { "llms": { "cursor": { "enabled": true, "model": "claude-3.5-sonnet", "workingDirectory": "." } } } ``` Cursor CLI respects your Cursor account subscription - no additional API keys needed! *** ## OpenAI Codex Setup ### Get Your API Key Go to [platform.openai.com](https://platform.openai.com) Navigate to API Keys → Create new secret key ```json theme={null} { "llms": { "openai": { "apiKey": "sk-...", "model": "gpt-4-turbo", "organization": "org-..." // Optional } } } ``` ### Available Models | Model | Context | Best For | | --------------- | ------- | -------------- | | `gpt-4-turbo` | 128K | General coding | | `gpt-4` | 8K | Legacy tasks | | `gpt-3.5-turbo` | 16K | Simple tasks | *** ## Open Source Agents ### OpenCode (Local) ```bash theme={null} # Download model ollama pull opencode # Configure Forge ``` ```json theme={null} { "llms": { "opencode": { "enabled": true, "model": "opencode:latest", "endpoint": "http://localhost:11434" } } } ``` ### Qwen Code (Local) ```bash theme={null} # Download model ollama pull qwen2.5-coder:32b # Configure Forge ``` ```json theme={null} { "llms": { "qwen": { "enabled": true, "model": "qwen2.5-coder:32b", "endpoint": "http://localhost:11434" } } } ``` *** ## Configuration Best Practices Begin with one agent (Claude or Gemini), add more later Create a test task to verify configuration Never commit `.forge/config.json` to version control Track API costs per agent to optimize spending *** ## Validation Test your configuration: ```bash theme={null} # Start Forge forge start # Create test task forge task create \ --title "Test configuration" \ --description "Print 'Hello from Forge!'" \ --llm claude # Should execute successfully ``` *** ## Troubleshooting **Symptoms**: Authentication errors when running tasks **Solutions**: * Verify API key is correct (no extra spaces) * Check API key has proper permissions * Ensure API key isn't expired * Confirm you have credits/quota remaining **Symptoms**: "Model not available" errors **Solutions**: * Check model name spelling (case-sensitive) * Verify model is available in your region * Ensure your API tier has access to the model **Symptoms**: Tasks fail with timeout **Solutions**: * Increase `timeout` value in config * Check network connectivity * Try a faster model (e.g., Haiku, Flash) **Symptoms**: Cursor tasks fail immediately **Solutions**: ```bash theme={null} # Re-authenticate cursor auth logout cursor auth login ``` *** ## Cost Optimization ### Model Selection Strategy Start with fast, cheap models: * Claude Haiku * Gemini Flash * GPT-3.5 Turbo Switch to stronger models for: * Large refactoring * Architecture changes * Critical bug fixes Run the same task with multiple models to find the sweet spot for each task type ### Cost Comparison | Model | Input | Output | Sweet Spot | | ------------- | ----------- | ----------- | ---------------- | | Claude Haiku | \$0.25/MTok | \$1.25/MTok | Quick iterations | | Gemini Flash | Free tier | Free tier | Experimentation | | GPT-3.5 Turbo | \$0.50/MTok | \$1.50/MTok | Simple tasks | | Claude Sonnet | \$3/MTok | \$15/MTok | General work | | GPT-4 Turbo | \$10/MTok | \$30/MTok | Complex tasks | *** ## Advanced: Multiple Configurations Create environment-specific configs: ```bash theme={null} # Development .forge/config.dev.json # Production .forge/config.prod.json # CI/CD .forge/config.ci.json ``` Switch between them: ```bash theme={null} FORGE_CONFIG=.forge/config.prod.json forge start ``` *** ## Next Steps Put your configuration to work Deep dive into each agent's capabilities Additional configuration options # Project Structure Source: https://docs.namastex.ai/forge/config/project-structure Understanding Forge's file organization ## Overview Forge creates a specific directory structure to organize tasks, worktrees, configuration, and data. Understanding this structure helps you work effectively with Forge. *** ## Directory Structure ``` your-project/ ├── .forge/ # Forge configuration and data │ ├── config.json # LLM and Forge settings │ ├── forge.db # SQLite database │ ├── worktrees/ # Git worktrees for tasks │ │ ├── task-1-auth/ # Isolated workspace for task 1 │ │ ├── task-2-api/ # Isolated workspace for task 2 │ │ └── ... │ └── logs/ # Execution logs │ ├── task-1.log │ └── ... ├── .git/ # Your Git repository ├── .gitignore # Don't commit .forge/! ├── src/ # Your source code ├── package.json └── ... ``` **Always add `.forge/` to `.gitignore`!** This directory contains: * API keys and secrets * Local database * Temporary worktrees * Execution logs ```bash theme={null} echo ".forge/" >> .gitignore ``` *** ## The `.forge/` Directory ### Configuration Files Main configuration file containing LLM settings, OAuth tokens, and preferences ```json theme={null} { "llms": { "claude": { "apiKey": "...", "model": "..." }, "gemini": { "apiKey": "...", "model": "..." } }, "worktrees": { "enabled": true, "basePath": "./.forge/worktrees" }, "preferences": { "defaultLLM": "claude", "autoCleanup": true } } ``` SQLite database storing: * Projects and tasks * Task attempts and results * Execution history * User preferences This file is created automatically on first run. Backup regularly if you want to preserve history! ### Worktrees Directory Contains Git worktrees for each task attempt ``` .forge/worktrees/ ├── task-1-add-auth/ # Task 1, attempt 1 │ ├── src/ │ ├── package.json │ └── ... (full repository copy) ├── task-1-add-auth-gemini/ # Task 1, attempt 2 └── task-2-refactor-api/ # Task 2, attempt 1 ``` Each worktree is a **complete copy** of your repository at a specific commit, isolated from your main branch. Execution logs for debugging and audit trail ``` .forge/logs/ ├── task-1-claude-2024-01-15.log ├── task-1-gemini-2024-01-15.log └── task-2-cursor-2024-01-16.log ``` *** ## Git Worktrees Explained ### What Are Worktrees? Git worktrees allow multiple working directories from the same repository. Forge uses this for **task isolation**. ``` Main Branch: your-project/ ← Your main working directory └── src/ Task Worktrees: .forge/worktrees/ ├── task-1/ ← Isolated copy for task 1 │ └── src/ └── task-2/ ← Isolated copy for task 2 └── src/ ``` ### Why Worktrees? Each task works in its own environment - no conflicts! Run multiple AI agents simultaneously on different tasks Try risky changes without affecting your main codebase Compare different approaches side-by-side ### How It Works You create a task in Forge: "Add user authentication" ```bash theme={null} git worktree add .forge/worktrees/task-1-auth ``` Creates a complete copy of your repo at current commit Claude modifies files in `.forge/worktrees/task-1-auth/` Your main directory is **untouched** Compare worktree with main branch: ```bash theme={null} git diff main task-1-auth ``` If you approve: ```bash theme={null} git merge task-1-auth git worktree remove .forge/worktrees/task-1-auth ``` *** ## Database Schema The `.forge/forge.db` SQLite database contains: ### Projects Table ```sql theme={null} CREATE TABLE projects ( id TEXT PRIMARY KEY, name TEXT NOT NULL, repository_url TEXT, default_llm TEXT, created_at TIMESTAMP, updated_at TIMESTAMP ); ``` ### Tasks Table ```sql theme={null} CREATE TABLE tasks ( id TEXT PRIMARY KEY, project_id TEXT REFERENCES projects(id), title TEXT NOT NULL, description TEXT, status TEXT, -- 'pending', 'in_progress', 'completed', 'failed' priority TEXT, -- 'low', 'medium', 'high' labels TEXT, -- JSON array created_at TIMESTAMP, updated_at TIMESTAMP ); ``` ### Attempts Table ```sql theme={null} CREATE TABLE attempts ( id TEXT PRIMARY KEY, task_id TEXT REFERENCES tasks(id), llm TEXT NOT NULL, -- 'claude', 'gemini', etc. worktree_path TEXT, status TEXT, -- 'running', 'completed', 'failed' output_log TEXT, created_at TIMESTAMP, completed_at TIMESTAMP ); ``` *** ## Backup & Restore ### Backing Up Forge Data ```bash theme={null} # Backup configuration and database tar -czf forge-backup-$(date +%Y%m%d).tar.gz .forge/ # Or just the essentials cp .forge/config.json config-backup.json cp .forge/forge.db forge-backup.db ``` ### Restoring From Backup ```bash theme={null} # Restore full backup tar -xzf forge-backup-20240115.tar.gz # Or restore specific files cp config-backup.json .forge/config.json cp forge-backup.db .forge/forge.db ``` Restoring worktrees requires active Git branches. Usually better to just restore config and database. *** ## Cleanup & Maintenance ### Clean Old Worktrees ```bash theme={null} # List all worktrees git worktree list # Remove specific worktree git worktree remove .forge/worktrees/task-1-old # Remove all stale worktrees (Forge does this automatically) git worktree prune ``` ### Clean Old Logs ```bash theme={null} # Remove logs older than 30 days find .forge/logs -name "*.log" -mtime +30 -delete ``` ### Compact Database ```bash theme={null} # Reduce database size sqlite3 .forge/forge.db "VACUUM;" ``` ### Complete Clean ```bash theme={null} # Nuclear option: Remove everything Forge-related rm -rf .forge/ # Restart Forge to recreate forge start ``` This deletes all task history, configurations, and worktrees. **Backup first!** *** ## Multi-User Scenarios ### Personal Projects ``` your-project/ └── .forge/ # Your personal Forge data └── config.json # Your API keys ``` Standard setup - one developer, one Forge instance ### Team Projects Each team member has their own `.forge/` directory: ``` Alice's machine: your-project/ └── .forge/ # Alice's Forge data Bob's machine: your-project/ └── .forge/ # Bob's Forge data (different) ``` Add `.forge/` to `.gitignore` so team members don't conflict ### Shared Forge Instance (Advanced) For teams sharing one Forge deployment: ``` Server: /opt/forge/ ├── projects/ │ ├── project-a/ │ │ └── .forge/ │ └── project-b/ │ └── .forge/ └── shared-config/ ``` *** ## Best Practices ```bash .gitignore theme={null} # Forge .forge/ .forge.* # But keep examples !.forge.example.json ``` Add a README explaining Forge setup: ```markdown theme={null} ## Forge Setup 1. Install: `npm i -g automagik-forge` 2. Configure: `cp .forge.example.json .forge/config.json` 3. Add API keys to `.forge/config.json` ``` ```bash theme={null} # Add to cron 0 0 * * * cd ~/my-project && \ cp .forge/forge.db ~/.backups/forge-$(date +%F).db ``` Let Forge auto-cleanup, or manually: ```bash theme={null} forge worktree cleanup ``` *** ## Troubleshooting **Error**: "fatal: 'task-1' is already checked out at '.forge/worktrees/task-1'" **Solution**: ```bash theme={null} # Remove the worktree git worktree remove --force .forge/worktrees/task-1 # Or let Forge handle it forge worktree cleanup ``` **Error**: "database is locked" **Solution**: * Close all Forge instances * Check for zombie processes: `ps aux | grep forge` * Kill if needed: `pkill -f forge` * Restart Forge **Error**: "Configuration file not found" **Solution**: ```bash theme={null} # Re-initialize forge init # Or restore from backup cp config-backup.json .forge/config.json ``` **Error**: "No space left on device" **Solution**: Worktrees accumulate. Clean them: ```bash theme={null} # Check size du -sh .forge/worktrees # Remove old worktrees forge worktree cleanup # Or manually git worktree prune rm -rf .forge/worktrees/* ``` *** ## Next Steps Learn how to create and manage tasks Deep dive into worktree concepts Advanced configuration options Command-line interface guide # Installation Source: https://docs.namastex.ai/forge/installation Get Forge up and running ## Prerequisites Before installing Forge, make sure you have: ```bash theme={null} # Check your Node.js version node --version # Should output v18.0.0 or higher ``` If you need to install or upgrade Node.js: * **macOS**: `brew install node` * **Ubuntu/Debian**: `sudo apt install nodejs npm` * **Windows**: Download from [nodejs.org](https://nodejs.org) ```bash theme={null} # Check if Git is installed git --version ``` Forge uses Git worktrees for isolation, so Git is required. You'll need API keys for the LLMs you want to use: * **Claude**: Anthropic API key * **Gemini**: Google AI API key * **OpenAI**: OpenAI API key * Others as needed *** ## Installation Methods Install Forge globally to use it from anywhere: ```bash theme={null} npm install -g @automagik/forge ``` Verify installation: ```bash theme={null} forge --version ``` Install Forge as a project dependency: ```bash theme={null} npm install --save-dev @automagik/forge ``` Add to your `package.json` scripts: ```json theme={null} { "scripts": { "forge": "forge" } } ``` Run with: ```bash theme={null} npm run forge ``` Run Forge without installing: ```bash theme={null} npx automagik-forge ``` Great for trying it out or one-time use! Clone and build from source: ```bash theme={null} # Clone the repository git clone https://github.com/namastexlabs/automagik-forge.git cd automagik-forge # Install dependencies npm install # Build npm run build # Link globally npm link ``` *** ## Configuration After installation, configure Forge with your LLM API keys: ```bash theme={null} # Initialize Forge in your project forge init # This creates a .forge/ directory with configuration ``` Set up your API keys in `.forge/config.json`: ```json theme={null} { "llms": { "claude": { "apiKey": "your-anthropic-api-key", "model": "claude-3-5-sonnet-20241022" }, "gemini": { "apiKey": "your-google-api-key", "model": "gemini-2.0-flash-exp" } } } ``` **Security Tip**: Never commit `.forge/config.json` to version control! Add it to `.gitignore`. *** ## Verify Installation Test that everything is working: ```bash theme={null} # Check version forge --version # Get help forge --help # Initialize a project (if not done yet) forge init ``` You should see output similar to: ``` automagik-forge v1.0.0 Forge initialized successfully! Configuration saved to .forge/config.json ``` *** ## Troubleshooting If you installed globally but get "command not found": 1. Check NPM global bin path: ```bash theme={null} npm config get prefix ``` 2. Add to your PATH (add to `~/.bashrc` or `~/.zshrc`): ```bash theme={null} export PATH="$PATH:$(npm config get prefix)/bin" ``` 3. Reload your shell: ```bash theme={null} source ~/.bashrc # or ~/.zshrc ``` On macOS/Linux, you might need sudo for global installs: ```bash theme={null} sudo npm install -g @automagik/forge ``` Or configure NPM to use a different directory (recommended): ```bash theme={null} mkdir ~/.npm-global npm config set prefix '~/.npm-global' export PATH=~/.npm-global/bin:$PATH ``` Make sure you're in a Git repository: ```bash theme={null} git init # If not already a Git repo ``` Forge requires Git to create isolated worktrees. *** ## Next Steps Create your first AI-powered task Learn more about Forge # Introduction to Forge Source: https://docs.namastex.ai/forge/introduction Where Vibe Coding Meets Structure

Where Vibe Coding Meets Structure

## What is Forge? Forge is the **maestro of AI-powered development** - transforming "vibe coding" chaos into structured productivity. A Kanban board that not only organizes tasks but executes them through any AI agent (Claude, Gemini, Cursor, and more), with Git worktree isolation and multi-agent orchestration. ## The Problem AI-powered development often feels like this: * **Lost Context**: Chat histories disappear, ideas get forgotten * **Vendor Lock-in**: Stuck with a single AI provider * **Chaos**: No clear organization or task management * **Risk**: Experiments can break your main codebase * **Comparison Paralysis**: Can't easily compare different AI approaches ## The Solution Forge brings **structure to the creative chaos** of AI development: Work with 8+ different LLMs simultaneously. Compare Claude against Gemini, test Cursor's suggestions, find the best tool for each task. Experiment fearlessly. Each task gets its own isolated workspace - your main codebase stays pristine while you explore. Track AI-driven tasks with an intuitive interface. See what's planned, in progress, and shipped at a glance. **Bring Your Own LLM** - You choose, you control, you own the relationship with your AI providers. ## Key Features ### 🎯 Structured AI Development Transform vibe coding into a systematic workflow: * **Task Organization**: Kanban-based task management * **Multi-Agent Orchestration**: Coordinate multiple AIs on different tasks * **Result Comparison**: Side-by-side outputs from different models * **Production-Ready**: Ship code you actually understand and can maintain ### 🔧 Developer Experience Built by developers, for developers: * **Git Integration**: Native worktree support for safe experimentation * **LLM Agnostic**: Works with Claude, Gemini, Cursor, and more * **Visual Interface**: Clear, intuitive Kanban board * **Smart Context**: Maintains context across conversations ### 🚀 Workflow Acceleration * **Parallel Development**: Work on multiple features simultaneously * **AI Model Shopping**: Find the best AI for each specific task * **Safe Experimentation**: Try risky changes without fear * **Clear History**: Track what worked and what didn't ## Who is Forge For? Manage your personal projects with AI assistance, experiment with different models, and maintain a clear development workflow. Coordinate AI-assisted development across team members, share successful prompts, and maintain consistent code quality. Explore the capabilities of different AI models, compare their strengths and weaknesses, and master AI-powered development. Ship AI-assisted features with confidence, maintain code quality, and keep humans in control of the development process. ## Why "Forge"? A forge is where raw materials are **shaped into useful tools** through heat and hammering. Similarly, Forge takes the raw power of AI models and shapes them into structured, production-ready code through systematic workflows. ## Philosophy Forge embodies our core philosophy: * **You orchestrate** - AI executes * **You decide** - AI suggests * **You understand** - AI explains * **You own** - No vendor lock-in *** ## Next Steps Get Forge installed and configured Create your first AI-powered task View source code and contribute Install via NPM # Claude Code Setup Source: https://docs.namastex.ai/forge/mcp/claude-code-setup Configure MCP for Claude Desktop and Claude Code ## Claude Code MCP Setup Configure Forge as an MCP server for Claude Code in 3 minutes. Works with both **Claude Desktop** and **Claude Code** (CLI). Same configuration for both. *** ## Prerequisites ```bash theme={null} npm install -g @automagik/forge ``` ```bash theme={null} # Start Forge npx automagik-forge ``` Open browser, navigate to your project, and copy the UUID from the URL: ``` http://localhost:3000/projects/a1b2c3d4-e5f6-7890-abcd-ef1234567890/tasks ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Your Project ID ``` *** ## Configuration ### Option 1: Basic Mode (Recommended) **7 core tools** for task management. Best for most users. * **macOS**: `Cmd + ,` or Claude Code → Settings * **Windows/Linux**: `Ctrl + ,` * Navigate to **MCP Servers** section Add this to your MCP servers configuration: ```json theme={null} { "mcpServers": { "automagik-forge": { "command": "npx", "args": ["automagik-forge", "--mcp"], "env": { "PROJECT_ID": "your-project-uuid-here" } } } } ``` Replace `your-project-uuid-here` with your actual Project ID. Fully quit and restart Claude Code for changes to take effect. In Claude Code, try: ``` "Create a task to add a README file" ``` Claude should use the MCP tool to create the task in Forge! ### Option 2: Advanced Mode **56 tools** including worktrees, processes, filesystem. For power users. ```json theme={null} { "mcpServers": { "automagik-forge": { "command": "npx", "args": ["automagik-forge", "--mcp-advanced"], "env": { "PROJECT_ID": "your-project-uuid-here" } } } } ``` Advanced mode can overwhelm Claude with too many tools. Start with basic mode first! *** ## Available Tools ### Basic Mode (7 tools) | Tool | What it does | Example | | --------------- | ----------------------- | ------------------------ | | `list_projects` | Get all projects | "Show my projects" | | `list_tasks` | View tasks with filters | "Show pending tasks" | | `create_task` | Create new task | "Add task: Fix auth bug" | | `get_task` | Get task details | "Show task #42" | | `update_task` | Modify task properties | "Mark task #42 complete" | | `delete_task` | Remove task | "Delete task #38" | ### Advanced Mode (+49 additional tools) Includes all basic tools PLUS: * Project management (8 tools) * Task attempts (12 tools) * Process management (9 tools) * Git worktrees (7 tools) * File operations (6 tools) * Templates & drafts (5 tools) * Omni integration (8 tools) *** ## Usage Examples ### Task Creation ``` You: "Create a task to implement dark mode with LocalStorage persistence" Claude: [Uses create_task MCP tool] Claude: "I've created task #47: 'Implement dark mode toggle' - Priority: medium - Type: feature - Status: pending Would you like me to start working on it?" ``` ### Planning ``` You: "Help me plan a complete authentication system with OAuth, JWT, and RBAC" Claude: [Uses create_task multiple times via MCP] Claude: "I've created 8 tasks for your auth system: #42 - OAuth provider integration #43 - JWT token generation #44 - Refresh token mechanism #45 - Role-based permissions #46 - User session management #47 - Password reset flow #48 - Email verification #49 - Security audit Should I prioritize these or start on any?" ``` ### Status Checks ``` You: "Show me all high-priority bugs" Claude: [Uses list_tasks with filters via MCP] Claude: "You have 3 high-priority bugs: #35 - API crash on malformed JSON (pending) #38 - Memory leak in WebSocket (in progress) #41 - Auth token expiry issue (review) Want me to work on #35 first?" ``` *** ## Troubleshooting **Error**: `Could not connect to MCP server 'automagik-forge'` **Solutions**: 1. Verify Forge is installed: ```bash theme={null} npm list -g @automagik/forge ``` 2. Check configuration syntax (valid JSON, no trailing commas) 3. Ensure `"command": "npx"` (not `"node"` or full path) 4. Restart Claude Code completely (quit and reopen) **Error**: `Project 'proj_xyz' does not exist` **Solutions**: 1. Verify project exists in Forge UI 2. Copy correct UUID from browser URL 3. Update `PROJECT_ID` in config 4. Restart Claude Code **Symptom**: Claude doesn't seem to have Forge tools **Solutions**: 1. Ask Claude directly: "What MCP tools do you have access to?" 2. Check if `automagik-forge` appears in the list 3. If not, verify config and restart Claude Code **Symptom**: Claude lists many tool options or seems confused **Solution**: You're in advanced mode (56 tools). Switch to basic: ```json theme={null} { "args": ["automagik-forge", "--mcp"] } ``` Remove `-advanced` and restart. *** ## Configuration File Location Claude Code MCP configuration is stored in: ```bash theme={null} ~/Library/Application Support/Claude/config.json ``` Or edit via Claude Code Settings UI. ``` %APPDATA%\Claude\config.json ``` Or edit via Claude Code Settings UI. ```bash theme={null} ~/.config/Claude/config.json ``` Or edit via Claude Code Settings UI. *** ## Best Practices **Use natural language**: Don't try to call tools directly. Just describe what you want, and Claude will use the right MCP tool. ✅ Good: "Create a task to add Redis caching" ❌ Bad: "use create\_task with title Redis" **Start with basic mode**: Only upgrade to advanced if you need specific features like manual worktree control or filesystem operations. **One project per config**: If you work on multiple projects, create separate MCP server entries with different PROJECT\_IDs: ```json theme={null} { "mcpServers": { "forge-frontend": { "command": "npx", "args": ["automagik-forge", "--mcp"], "env": { "PROJECT_ID": "proj_frontend123" } }, "forge-backend": { "command": "npx", "args": ["automagik-forge", "--mcp"], "env": { "PROJECT_ID": "proj_backend456" } } } } ``` *** ## Next Steps Learn more about MCP integration Understand how MCP works Complete list of all MCP tools See MCP in action # Cursor Setup Source: https://docs.namastex.ai/forge/mcp/cursor-setup Configure MCP for Cursor IDE ## Cursor MCP Setup Configure Forge as an MCP server for Cursor in 3 minutes. *** ## Prerequisites ```bash theme={null} npm install -g @automagik/forge ``` ```bash theme={null} npx automagik-forge ``` Copy the UUID from your browser URL: ``` http://localhost:3000/projects/a1b2c3d4-e5f6-7890-abcd-ef1234567890/tasks ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Your Project ID ``` *** ## Configuration ### Option 1: Basic Mode (Recommended) * Press `Cmd/Ctrl + ,` * Or go to **Cursor → Settings** Type "MCP" in the settings search box Add this to your MCP configuration: ```json theme={null} { "mcp.servers": { "automagik-forge": { "command": "npx", "args": ["automagik-forge", "--mcp"], "projectId": "your-project-uuid-here" } } } ``` Replace `your-project-uuid-here` with your actual Project ID. * Press `Cmd/Ctrl + R` to reload Cursor * Or restart Cursor completely Try: `"Create a task to add a README file"` Cursor's AI should create the task via MCP! ### Option 2: Advanced Mode For power users who need full Forge control: ```json theme={null} { "mcp.servers": { "automagik-forge": { "command": "npx", "args": ["automagik-forge", "--mcp-advanced"], "projectId": "your-project-uuid-here" } } } ``` Start with basic mode (7 tools). Advanced mode has 56 tools which can confuse the AI. *** ## Usage in Cursor ### With Cursor Composer ``` You: "Create tasks for building an authentication system" Cursor AI: [Uses MCP to create multiple tasks in Forge] Cursor AI: "I've created 5 tasks: - OAuth integration - JWT token generation - User session management - Password reset - Security audit Want me to start on any?" ``` ### With @ Commands Access Forge tasks using `@`: ``` You: @automagik-forge "Show my pending tasks" Cursor AI: [Lists tasks via MCP] ``` *** ## Troubleshooting **Solutions**: 1. Verify Forge is installed: `npm list -g @automagik/forge` 2. Check settings JSON syntax (no trailing commas) 3. Ensure `"command": "npx"` not `"node"` 4. Reload Cursor window (`Cmd/Ctrl + R`) **Error**: `Project not found` **Fix**: 1. Open Forge UI: `npx automagik-forge` 2. Copy correct UUID from URL 3. Update `projectId` in Cursor settings 4. Reload Cursor **Check**: 1. Ask Cursor: "What MCP servers do you have?" 2. Verify `automagik-forge` appears 3. If not, check config and reload *** ## Configuration File Location Cursor stores MCP config in: ```bash theme={null} ~/Library/Application Support/Cursor/User/settings.json ``` ``` %APPDATA%\Cursor\User\settings.json ``` ```bash theme={null} ~/.config/Cursor/User/settings.json ``` *** ## Next Steps Learn about MCP integration See all available tools # Custom MCP Clients Source: https://docs.namastex.ai/forge/mcp/custom-clients Configure Forge MCP for any MCP-compatible client ## Custom MCP Client Setup Configure Forge as an MCP server for any MCP-compatible tool. *** ## Generic Configuration Pattern All MCP clients follow a similar pattern. Forge uses standard MCP protocol. ### Standard Configuration ```json theme={null} { "command": "npx", "args": ["automagik-forge", "--mcp"], "env": { "PROJECT_ID": "your-project-uuid-here" } } ``` ### Advanced Mode ```json theme={null} { "command": "npx", "args": ["automagik-forge", "--mcp-advanced"], "env": { "PROJECT_ID": "your-project-uuid-here" } } ``` *** ## Common MCP Clients ### Roo Code ```yaml theme={null} servers: automagik-forge: command: npx args: - automagik-forge - --mcp environment: PROJECT_ID: your-project-uuid-here ``` ### Gemini CLI ```json theme={null} { "mcp": { "servers": { "automagik-forge": { "type": "stdio", "command": "npx", "args": ["automagik-forge", "--mcp"], "env": { "PROJECT_ID": "your-project-uuid-here" } } } } } ``` ### Continue.dev ```json theme={null} { "mcpServers": { "automagik-forge": { "command": "npx", "args": ["automagik-forge", "--mcp"], "env": { "PROJECT_ID": "your-project-uuid-here" } } } } ``` *** ## Configuration Elements ### Required Fields | Field | Value | Description | | ------------ | ------------------------------ | ---------------------- | | `command` | `"npx"` | Package runner command | | `args` | `["automagik-forge", "--mcp"]` | Forge with MCP mode | | `PROJECT_ID` | UUID | Your Forge project ID | ### Optional Fields | Field | Value | Description | | ------------- | ------------------- | ---------------------- | | `name` | `"automagik-forge"` | Server name identifier | | `type` | `"stdio"` | Communication protocol | | `description` | Custom text | Server description | *** ## Getting Your Project ID ```bash theme={null} npx automagik-forge ``` Open browser, create or select your project From the browser URL: ``` http://localhost:3000/projects/a1b2c3d4-e5f6-7890-abcd-ef1234567890/tasks ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Copy this UUID ``` *** ## Testing Your Configuration After configuring, test with these commands: ``` "What MCP servers do you have?" ``` Should show `automagik-forge` in the list. ``` "Create a task to add a README file" ``` Should create task #X in Forge. ``` "Show my pending tasks" ``` Should list tasks from Forge. *** ## Troubleshooting Check your client's documentation for: * "MCP configuration" * "External tools" * "Model Context Protocol" * "Extensions" or "Plugins" Common locations: * Settings UI → MCP Servers * Preferences → Tools → MCP * Config file: `~/.config//config.json` Test Forge command directly: ```bash theme={null} npx automagik-forge --mcp ``` Should start the MCP server without errors. Ensure: 1. Project exists in Forge UI 2. UUID is exact (no extra spaces/quotes) 3. Format is correct: `proj_xxxxx` or full UUID Some clients support debug mode: ```json theme={null} { "env": { "PROJECT_ID": "...", "DEBUG": "mcp:*" } } ``` Check client logs for MCP connection errors. *** ## Configuration Formats Different clients use different formats: ### JSON (Most Common) ```json theme={null} { "mcpServers": { "automagik-forge": { "command": "npx", "args": ["automagik-forge", "--mcp"], "env": { "PROJECT_ID": "..." } } } } ``` ### YAML ```yaml theme={null} mcpServers: automagik-forge: command: npx args: - automagik-forge - --mcp env: PROJECT_ID: your-project-uuid ``` ### TOML ```toml theme={null} [mcpServers.automagik-forge] command = "npx" args = ["automagik-forge", "--mcp"] [mcpServers.automagik-forge.env] PROJECT_ID = "your-project-uuid" ``` *** ## Advanced: Multiple Projects Configure multiple Forge projects: ```json theme={null} { "mcpServers": { "forge-frontend": { "command": "npx", "args": ["automagik-forge", "--mcp"], "env": { "PROJECT_ID": "proj_frontend123" } }, "forge-backend": { "command": "npx", "args": ["automagik-forge", "--mcp"], "env": { "PROJECT_ID": "proj_backend456" } } } } ``` *** ## Next Steps Learn about MCP integration See all available MCP tools Get help with your specific client # MCP Integration Overview Source: https://docs.namastex.ai/forge/mcp/overview Control Forge from any MCP-compatible AI agent ## Introduction Forge's **Model Context Protocol (MCP) integration** lets you control your entire task board from inside your AI coding agent. Never leave your editor - your AI manages Forge for you via natural language. **Quick value**: Ask Claude "create a task to add dark mode" and it's done. No UI clicking, no context switching, just flow. *** ## What is MCP? **Model Context Protocol (MCP)** is an open standard that allows AI agents to interact with external tools and services in a structured way. Think of it as **"API for AI agents"** - instead of you making HTTP requests, your AI agent does it automatically based on your conversation. ### The Magic ``` ❌ Without MCP: You → Switch to Forge UI → Create task → Copy details → Switch back → Code ✅ With MCP: You → "Create a task to add Redis caching" AI → [Automatically creates task in Forge] AI → "Task #47 created. Want me to start on it?" You → Continue coding ``` *** ## Why Use MCP with Forge? Never leave your editor. AI handles all Forge interactions while you focus on coding. Use conversational commands. No need to remember CLI syntax or navigate UIs. "Plan an auth system" creates multiple tasks instantly. Seconds vs minutes. AI sees your Forge tasks and suggests next steps based on your workflow. *** ## Getting Started ### Step 1: Get Your Project ID ```bash theme={null} npx automagik-forge ``` Opens browser at `http://localhost:3000` Create or select a project and go to its task board. Find it in the browser URL: ``` http://localhost:3000/projects/a1b2c3d4-e5f6-7890-abcd-ef1234567890/tasks ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Copy this UUID ``` Or go to **Project Settings** and copy from there. \###Step 2: Choose Your Mode Forge offers two MCP modes: **7 core tools** for task management ```bash theme={null} npx automagik-forge --mcp ``` **Best for**: Most users. Clean, focused, fast. **Tools**: * `list_projects` - View all projects * `list_tasks` - Get tasks with filters * `create_task` - Add new tasks * `get_task` - View task details * `update_task` - Modify tasks * `delete_task` - Remove tasks Start here! Upgrade to advanced only if you need it. **56 tools** including worktrees, processes, filesystem ```bash theme={null} npx automagik-forge --mcp-advanced ``` **Best for**: Power users needing full control. **Additional capabilities**: * Git worktree management * Process control * File operations * Attempt management * Template system * Omni integration Can overwhelm AI agents with too many options. Use basic mode first! ### Step 3: Configure Your AI Agent Choose your setup guide: Setup for Claude Desktop and Claude Code Setup for Cursor IDE Setup for VSCode with Cline extension Generic setup for any MCP client *** ## Example Use Cases ### Planning & Task Creation ``` You: "Help me plan a complete authentication system with OAuth, JWT, and role-based access control" AI: [Uses MCP tools to analyze and create tasks] AI: "I've created 8 tasks for your auth system: #42 - OAuth provider integration (Google, GitHub) #43 - JWT token generation and validation #44 - Refresh token mechanism #45 - Role-based permission middleware #46 - User session management #47 - Password reset flow #48 - Email verification #49 - Security audit and rate limiting Want me to prioritize them or start on any?" ``` ### Bug Tracking ``` You: "Add bug: API returns 500 on malformed JSON input in /api/users endpoint. Priority high, affects production" AI: [Uses create_task via MCP] AI: "Bug #50 logged: Title: Fix API crash on malformed JSON Priority: High Type: Bug Description: Production issue in /api/users endpoint Should I create an attempt to fix this now?" ``` ### Status Updates ``` You: "Show me all high-priority tasks that are blocked or pending" AI: [Uses list_tasks with filters via MCP] AI: "You have 3 high-priority tasks: Blocked: #45 - Waiting on OAuth library decision Pending: #47 - Ready to start password reset flow #48 - Email verification implementation ready Want me to start working on #47 or #48?" ``` ### Batch Operations ``` You: "Mark all database migration tasks as complete and move API tasks to in-progress" AI: [Uses list_tasks + update_task via MCP] AI: "Done: ✅ Marked 4 migration tasks complete 🔄 Moved 3 API tasks to in-progress Current status: - 12 completed tasks - 3 in progress (API endpoints) - 5 pending Next priority is #52 - API documentation" ``` *** ## MCP Workflow Patterns ### The Planning Flow ```mermaid theme={null} sequenceDiagram You->>AI: "Plan feature X" AI->>AI: Analyze requirements AI->>MCP: create_task (subtask 1) AI->>MCP: create_task (subtask 2) AI->>MCP: create_task (subtask 3) MCP->>AI: Tasks created AI->>You: "Created 3 tasks, ready to start?" ``` ### The Execution Flow ```mermaid theme={null} sequenceDiagram You->>AI: "Start task #42" AI->>MCP: create_attempt(42, llm: claude) MCP->>Git: Create worktree MCP->>AI Agent: Start execution AI Agent->>AI Agent: Work in isolation AI Agent->>MCP: Complete MCP->>You: "Attempt ready for review" ``` ### The Review Flow ```mermaid theme={null} sequenceDiagram You->>AI: "Show me task #42 results" AI->>MCP: get_task(42) MCP->>AI: Task details + attempts AI->>You: "2 attempts completed:
Attempt 1 (Claude): Production-ready
Attempt 2 (Gemini): Needs refinement" You->>AI: "Merge attempt 1" AI->>MCP: merge_attempt(42, 1) MCP->>Git: Merge to main MCP->>You: "✅ Merged to main branch" ``` *** ## Basic vs Advanced Comparison | Feature | Basic Mode | Advanced Mode | | ----------------------- | ---------------- | ------------------------ | | **Tools** | 7 core tools | 56 total tools | | **Task Management** | ✅ Full | ✅ Full | | **Worktree Control** | ❌ Automatic only | ✅ Manual control | | **Process Management** | ❌ No | ✅ Yes | | **File Operations** | ❌ No | ✅ Yes | | **Template System** | ❌ No | ✅ Yes | | **Omni Integration** | ❌ No | ✅ Yes | | **AI Response Speed** | ⚡ Fast | 🐢 Slower (more options) | | **AI Response Quality** | 📝 Focused | 🔀 Can be verbose | | **Best For** | 👥 Most users | 🔧 Power users | **90% of users should use Basic Mode**. It's faster, clearer, and does everything most people need. *** ## Security & Privacy ### Local-First **Forge MCP server runs 100% locally**. No data leaves your machine. All operations happen on localhost. ### Project Isolation Each AI agent connects to a specific project ID: ```json theme={null} { "env": { "PROJECT_ID": "proj_abc123" // Agent can ONLY access this project } } ``` **Benefits**: * No accidental cross-project operations * Multiple agents, multiple projects * Secure team collaboration *** ## Troubleshooting **Check**: 1. Forge is installed: `npm list -g @automagik/forge` 2. Correct command in config: `"command": "npx"` 3. Correct args: `"args": ["automagik-forge", "--mcp"]` 4. Restart your AI agent after config changes **Solution**: Reinstall Forge if needed: ```bash theme={null} npm install -g @automagik/forge ``` **Error**: `Project 'proj_xyz' not found` **Solution**: 1. Open Forge: `npx automagik-forge` 2. Verify project exists in UI 3. Copy correct UUID from browser URL 4. Update MCP config 5. Restart AI agent **Symptom**: AI lists too many tools or seems uncertain **Solution**: You're in advanced mode with 56 tools. Switch to basic: ```json theme={null} { "args": ["automagik-forge", "--mcp"] // Remove -advanced } ``` **Solution**: Refresh your browser. MCP changes happen in the database; UI needs refresh to show them. *** ## Next Steps Pick which AI coding agent you use: * [Claude Code Setup](/forge/mcp/claude-code-setup) * [Cursor Setup](/forge/mcp/cursor-setup) * [VSCode + Cline Setup](/forge/mcp/vscode-cline-setup) * [Custom Client Setup](/forge/mcp/custom-clients) Follow the setup guide for your chosen agent. Takes 2-3 minutes. Try a simple command: ``` "Create a task to add a README file" ``` Your AI should create the task via MCP! Learn advanced patterns: * [MCP Architecture](/forge/concepts/mcp-architecture) * [MCP Tools Reference](/forge/api/mcp-tools) * [Workflows & Use Cases](/forge/workflows/feature-development) *** ## Learn More Deep dive into how MCP works in Forge Complete list of all available tools See MCP in action with real examples Fix common MCP issues # VSCode + Cline Setup Source: https://docs.namastex.ai/forge/mcp/vscode-cline-setup Configure MCP for VSCode with Cline extension ## VSCode + Cline MCP Setup Configure Forge as an MCP server for the Cline extension in VSCode. *** ## Prerequisites 1. Open VSCode 2. Go to Extensions (`Cmd/Ctrl + Shift + X`) 3. Search for "Cline" 4. Install the Cline extension ```bash theme={null} npm install -g @automagik/forge ``` ```bash theme={null} npx automagik-forge ``` Copy UUID from browser URL: ``` http://localhost:3000/projects/a1b2c3d4-e5f6-7890-abcd-ef1234567890/tasks ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ``` *** ## Configuration ### Option 1: Via Cline Settings UI * Press `Cmd/Ctrl + Shift + P` * Type "Cline: Settings" * Select and open In the MCP Servers section, add: **Name**: `automagik-forge` **Command**: `npx` **Args**: `automagik-forge --mcp` **Project ID**: `your-project-uuid-here` Save settings and reload VSCode window ### Option 2: Via JSON Configuration * `Cmd/Ctrl + Shift + P` * "Preferences: Open Settings (JSON)" ```json theme={null} { "cline.mcpServers": [ { "name": "automagik-forge", "command": "npx", "args": ["automagik-forge", "--mcp"], "env": { "PROJECT_ID": "your-project-uuid-here" } } ] } ``` `Cmd/Ctrl + Shift + P` → "Developer: Reload Window" ### Advanced Mode For power users: ```json theme={null} { "cline.mcpServers": [ { "name": "automagik-forge", "command": "npx", "args": ["automagik-forge", "--mcp-advanced"], "env": { "PROJECT_ID": "your-project-uuid-here" } } ] } ``` *** ## Usage with Cline ### Task Management ``` You: "Create a task to implement Redis caching" Cline: [Uses MCP to create task in Forge] Cline: "Task #47 created. Should I start implementing it?" ``` ### Planning ``` You: "Help me plan an e-commerce checkout flow" Cline: [Creates multiple tasks via MCP] Cline: "Created 6 tasks: - Cart management - Payment integration - Order processing - Email notifications - Receipt generation - Error handling" ``` *** ## Troubleshooting 1. Check Forge is installed: `npm list -g @automagik/forge` 2. Verify JSON syntax in settings 3. Reload VSCode window 4. Check Cline output panel for errors 1. Open Forge: `npx automagik-forge` 2. Verify project exists 3. Copy correct UUID 4. Update settings 5. Reload VSCode Ask Cline: "What MCP tools do you have?" If `automagik-forge` doesn't appear, check configuration. *** ## Next Steps Learn about MCP Available tools # Quick Start Source: https://docs.namastex.ai/forge/quickstart Create your first AI-powered task in Forge ## Your First AI-Powered Task in 5 Minutes This guide will walk you through creating your first task with Forge, comparing outputs from multiple LLMs, and shipping code you understand. *** ## Step 1: Initialize Forge Make sure you're in a Git repository, then initialize Forge: ```bash theme={null} # Make sure you're in a Git repo git init # if not already a Git repo # Initialize Forge forge init ``` This creates a `.forge/` directory with your configuration. *** ## Step 2: Configure Your LLMs Edit `.forge/config.json` to add your API keys: ```json theme={null} { "llms": { "claude": { "apiKey": "sk-ant-...", "model": "claude-3-5-sonnet-20241022" }, "gemini": { "apiKey": "AIza...", "model": "gemini-2.0-flash-exp" } }, "worktrees": { "enabled": true, "basePath": "./.forge/worktrees" } } ``` Start with just one LLM if you're trying it out. You can add more later to compare results! *** ## Step 3: Create Your First Task Open the Forge UI or use the CLI: ```bash theme={null} # Start Forge UI forge start # Or create task via CLI forge task create \ --title "Add user authentication" \ --description "Implement JWT-based authentication with login and signup endpoints" \ --llm claude ``` The Forge UI will open at `http://localhost:3000`. *** ## Step 4: Let AI Work in Isolation Forge creates a Git worktree for your task, keeping your main branch clean: ```bash theme={null} # Forge automatically creates a worktree # Your task runs in: .forge/worktrees/task-1-add-auth # Your main branch is untouched! # You can keep working on other things ``` *** ## Step 5: Review and Compare If you're using multiple LLMs, Forge shows you side-by-side results: ```bash theme={null} # Compare Claude vs Gemini on the same task forge task compare 1 # See the differences forge diff task-1-claude task-1-gemini ``` Choose the approach you understand best, or combine elements from both! *** ## Step 6: Merge When Ready Once you're happy with the result: ```bash theme={null} # Review changes forge task review 1 # Merge into main forge task merge 1 # Cleanup worktree forge task close 1 ``` *** ## Real-World Example Here's a complete workflow for adding a new feature: ```bash theme={null} forge task create \ --title "Add dark mode toggle" \ --description "Create a toggle component that switches between light and dark themes" \ --llm claude \ --labels "feature,ui" ``` Forge creates a worktree and Claude generates: * Theme toggle component * CSS variables for themes * LocalStorage persistence * Tests ```bash theme={null} # Try with Gemini for comparison forge task fork 1 --llm gemini ``` Now you have two implementations to compare! ```bash theme={null} # See them side-by-side forge task compare 1 # Claude's approach: CSS-in-JS with styled-components # Gemini's approach: Tailwind CSS with data attributes ``` ```bash theme={null} # You prefer Gemini's Tailwind approach forge task merge 1-gemini # Clean up forge task close 1-claude ``` *** ## Common Task Types ```bash theme={null} forge task create \ --title "Add export to PDF" \ --type feature \ --llm claude ``` ```bash theme={null} forge task create \ --title "Fix memory leak in WebSocket" \ --type bugfix \ --llm gemini ``` ```bash theme={null} forge task create \ --title "Refactor API client to use axios" \ --type refactor \ --llm claude ``` ```bash theme={null} forge task create \ --title "Add API documentation" \ --type docs \ --llm gemini ``` *** ## Pro Tips For important features, run the same task with 2-3 different LLMs and compare approaches: ```bash theme={null} forge task create --title "Critical feature" --llm claude forge task fork 1 --llm gemini forge task fork 1 --llm gpt-4 ``` Choose the best implementation or cherry-pick from each! Instead of: ```bash theme={null} forge task create --title "Rebuild entire auth system" ``` Do: ```bash theme={null} forge task create --title "Add JWT token generation" forge task create --title "Add token validation middleware" forge task create --title "Add refresh token logic" ``` Smaller tasks = better AI results! ```bash theme={null} forge task create \ --title "Add search" \ --labels "feature,ui,priority:high" # Filter by label forge task list --labels "priority:high" ``` *** ## Next Steps Explore the visual Kanban interface: ```bash theme={null} forge start ``` Open [http://localhost:3000](http://localhost:3000) Learn about: * Task dependencies * Automated testing integration * CI/CD integration * Team collaboration Add more LLMs: * OpenAI GPT-4 * Anthropic Claude * Google Gemini * Local models Deep dive into: * Parallel development * Feature branches * Safe experimentation *** ## Troubleshooting Make sure you're in a Git repository: ```bash theme={null} git status # Should not error git init # If needed ``` Check your API keys: ```bash theme={null} forge config validate ``` Clean up old worktrees: ```bash theme={null} forge worktree cleanup ``` *** **Congratulations!** 🎉 You've created your first AI-powered task with Forge. You're now ready to bring structure to your vibe coding! Get help, share your workflows, and learn from other Forge users # API Errors Source: https://docs.namastex.ai/forge/troubleshooting/api-errors Troubleshooting REST API and MCP connection issues ## Overview Forge exposes a REST API for the web UI and an MCP server for AI agent integration. This guide helps troubleshoot API connection and communication issues. *** ## Connection Errors ### Cannot Connect to Backend **Problem**: Frontend shows "Failed to connect to API" or network errors **Symptoms**: * Tasks don't load * Empty project list * Console errors: `net::ERR_CONNECTION_REFUSED` **Solutions**: ```bash theme={null} # Verify backend port in logs # Look for: "Backend server listening on: http://127.0.0.1:XXXX" # Test connection curl http://localhost:5000/api/projects # Should return JSON, not connection error ``` ```bash theme={null} # Backend auto-assigns port if not specified # Check what port it's using # Set explicit port export BACKEND_PORT=5000 automagik-forge --backend-port 5000 # Verify curl http://localhost:5000/api/projects ``` ```bash theme={null} # macOS sudo /usr/libexec/ApplicationFirewall/socketfilterfw --getglobalstate # Linux (ufw) sudo ufw status sudo ufw allow 5000/tcp # Windows Firewall # Allow automagik-forge in Windows Defender Firewall settings ``` ```bash theme={null} # See what's using the port lsof -i :5000 # macOS/Linux netstat -ano | findstr :5000 # Windows # Kill conflicting process or use different port automagik-forge --backend-port 5001 ``` *** ### CORS Errors **Problem**: `Access to fetch has been blocked by CORS policy` **Cause**: Backend and frontend on different origins **Solution**: ```bash theme={null} # Forge handles CORS automatically # But if you're using custom setup: # 1. Ensure backend allows frontend origin # Backend should already allow http://localhost:3000 # 2. Don't use IP address for frontend # Use localhost, not 127.0.0.1 # 3. Check browser console for exact CORS error # F12 → Console → Look for CORS details ``` *** ### Timeout Errors **Problem**: Requests timeout with no response **Solutions**: ```bash theme={null} # Increase timeout in frontend # (Already set to reasonable defaults) # Check if backend is overloaded top # Check CPU/memory # Check backend logs for errors # Forge outputs logs to console # Test API directly curl -v http://localhost:5000/api/projects # Look for response time ``` *** ## Authentication Errors ### Unauthorized (401) **Problem**: API returns 401 Unauthorized **Cause**: Missing or invalid auth token (GitHub OAuth) **Solution**: ```bash theme={null} # Re-authenticate with GitHub # Via UI: Settings → GitHub → Reconnect # Or clear cached token rm .forge/github-token.enc # Restart Forge automagik-forge ``` *** ### Forbidden (403) **Problem**: API returns 403 Forbidden **Cause**: Insufficient permissions for requested resource **Solution**: ```bash theme={null} # Check GitHub OAuth scopes # Ensure OAuth app has repo access # Verify you have access to the repository gh repo view owner/repo # Re-authorize with correct scopes ``` *** ## Request Errors ### Bad Request (400) **Problem**: API returns 400 Bad Request **Causes**: ```bash theme={null} # Check request body is valid JSON curl -X POST http://localhost:5000/api/tasks \ -H "Content-Type: application/json" \ -d '{"title":"Test"}' # Valid # Not this: -d '{title:"Test"}' # Invalid (missing quotes) ``` ```bash theme={null} # Check API documentation for required fields curl -X POST http://localhost:5000/api/tasks \ -H "Content-Type: application/json" \ -d '{ "title": "Required", "description": "Also required", "project_id": "uuid-required" }' ``` ```bash theme={null} # Check field validation # Example: status must be valid enum { "status": "in_progress" // Valid "status": "invalid_status" // Invalid } ``` *** ### Not Found (404) **Problem**: API returns 404 Not Found **Solutions**: ```bash theme={null} # Verify endpoint path curl http://localhost:5000/api/tasks # Correct curl http://localhost:5000/api/task # Wrong (singular) # Verify resource exists curl http://localhost:5000/api/tasks/{task-id} # Check if ID is correct UUID format # Valid: a1b2c3d4-e5f6-7890-abcd-ef1234567890 # Invalid: task-123 ``` *** ### Internal Server Error (500) **Problem**: API returns 500 Internal Server Error **Solution**: ```bash theme={null} # Check backend logs for stack trace # Forge outputs detailed error logs # Common causes: # 1. Database corruption sqlite3 .forge/db.sqlite "PRAGMA integrity_check;" # 2. Disk space full df -h # 3. Permission errors ls -la .forge/ # 4. Bug in Forge # Report to: https://github.com/namastexlabs/automagik-forge/issues ``` *** ## MCP Server Errors ### MCP Server Not Responding **Problem**: AI agent can't connect to Forge via MCP **Symptoms**: * MCP tools not available in AI agent * Connection timeoutErrors in AI agent logs **Solutions**: ```bash theme={null} # Start Forge in MCP mode automagik-forge --mcp # Or advanced mode for more tools automagik-forge --mcp-advanced # Verify it's running in MCP mode # Look for: "MCP server listening on stdio" ``` **Claude Code** (`.claude/mcp.json`): ```json theme={null} { "mcpServers": { "automagik-forge": { "command": "npx", "args": ["automagik-forge", "--mcp"], "env": { "PROJECT_ID": "your-project-uuid" } } } } ``` **Cursor** (settings.json): ```json theme={null} { "mcp.servers": { "automagik-forge": { "command": "npx", "args": ["automagik-forge", "--mcp"], "projectId": "your-project-uuid" } } } ``` ```bash theme={null} # Method 1: From UI # Settings → Project Info → Project ID # Method 2: From config file cat .forge/config.json | grep project_id # Method 3: From API curl http://localhost:5000/api/projects | jq '.[0].id' ``` ```bash theme={null} # MCP server logs to stderr # Check AI agent's MCP logs # Claude Code logs ~/.claude/logs/ # Cursor logs # Help → Show Logs → MCP # Look for connection errors or tool loading issues ``` *** ### MCP Tools Not Available **Problem**: `list_tasks`, `create_task`, etc. not showing up in AI agent **Solution**: ```bash theme={null} # Check AI agent recognized the MCP server # In AI agent, ask: "What MCP servers are available?" # Should list: automagik-forge ``` ```bash theme={null} # Basic mode: 6 core tools automagik-forge --mcp # Advanced mode: 56+ tools automagik-forge --mcp-advanced # Use advanced if you need all tools ``` ```bash theme={null} # Reload MCP servers # Claude Code: Cmd+Shift+P → "Reload MCP Servers" # Cursor: Reload window # Or restart the AI agent completely ``` *** ### MCP Tool Execution Failed **Problem**: MCP tool returns error when executed **Common Errors**: ```json theme={null} // Error: "Project with ID xxx not found" // Solution: Verify PROJECT_ID in MCP config { "env": { "PROJECT_ID": "correct-uuid-here" } } // Get correct ID: cat .forge/config.json | grep project_id ``` ```json theme={null} // Error: "Task xxx does not exist" // Solution: List tasks first to get valid IDs { "tool": "list_tasks", "arguments": { "project_id": "uuid" } } // Then use returned task IDs ``` ```json theme={null} // Error: "Missing required field: title" // Solution: Include all required fields { "tool": "create_task", "arguments": { "project_id": "uuid", "title": "Required field", "description": "Also required" } } ``` *** ## SSE (Server-Sent Events) Issues ### Real-time Logs Not Streaming **Problem**: Task execution logs don't appear in real-time **Causes & Solutions**: ```bash theme={null} # Some proxies block Server-Sent Events # Test SSE connection curl -N http://localhost:5000/api/events/processes/{id}/logs # Should stream data, not close immediately # If blocked, disable proxy temporarily unset HTTP_PROXY unset HTTPS_PROXY ``` ```bash theme={null} # Browsers limit concurrent SSE connections # Close other Forge tabs # Or use different browser # Firefox: about:config # network.http.max-persistent-connections-per-server = 10 ``` ```bash theme={null} # Check backend is configured to stream # This should be automatic in Forge # Verify in logs: # "Streaming process logs for ID: xxx" # If not streaming, restart Forge ``` *** ## Database Errors ### SQLite Errors **Problem**: API returns database-related errors ```bash theme={null} # Error: "database is locked" # Stop all Forge instances pkill -f automagik-forge # Remove lock files rm .forge/db.sqlite-shm rm .forge/db.sqlite-wal # Restart single instance automagik-forge ``` ```bash theme={null} # Check integrity sqlite3 .forge/db.sqlite "PRAGMA integrity_check;" # If corrupted, restore from backup cp .forge/db.backup.sqlite .forge/db.sqlite # Or rebuild database (loses data) mv .forge/db.sqlite .forge/db.sqlite.old automagik-forge # Creates new database ``` ```bash theme={null} # Error: "database migration failed" # Backup database cp .forge/db.sqlite .forge/db.backup.sqlite # Delete database (will rebuild) rm .forge/db.sqlite # Restart Forge automagik-forge ``` *** ## Performance Issues ### Slow API Responses **Problem**: API requests take very long to respond **Solutions**: ```bash theme={null} # Check database size du -h .forge/db.sqlite # If very large (>100MB), clean up old data sqlite3 .forge/db.sqlite "DELETE FROM tasks WHERE status='done' AND updated_at < datetime('now', '-30 days');" # Vacuum database to reclaim space sqlite3 .forge/db.sqlite "VACUUM;" # Restart Forge automagik-forge ``` *** ### Rate Limiting **Problem**: AI executor APIs return rate limit errors **Solution**: ```json theme={null} // Configure rate limits in .forge/config.json { "executors": { "claude-code": { "rate_limit": { "requests_per_minute": 50, "tokens_per_minute": 100000 }, "retry": { "max_retries": 3, "backoff_ms": 1000 } } } } ``` *** ## Debugging API Issues ### Enable Debug Logging ```bash theme={null} # Set debug log level export RUST_LOG=debug # Start Forge automagik-forge # Watch for API request/response logs # Each API call will be logged with details ``` ### Test API Directly ```bash theme={null} # Test with curl curl -v http://localhost:5000/api/projects # -v shows full request/response # Look for: # - Status code # - Response headers # - Response body # - Timing information # Test specific endpoints curl http://localhost:5000/api/tasks curl http://localhost:5000/api/tasks/{task-id} curl -X POST http://localhost:5000/api/tasks \ -H "Content-Type: application/json" \ -d '{"title":"Test","description":"Test task","project_id":"uuid"}' ``` ### Inspect Network Traffic ```bash theme={null} # Use browser DevTools # F12 → Network tab # Filter by "Fetch/XHR" # Click on request to see: # - Headers # - Payload # - Response # - Timing # Look for failed requests (red) # Check status codes and error messages ``` *** ## Next Steps General troubleshooting guide Worktree-specific issues Complete API documentation MCP integration reference # Common Issues Source: https://docs.namastex.ai/forge/troubleshooting/common-issues Solutions to frequently encountered problems ## Installation Issues ### Command Not Found **Problem**: `automagik-forge: command not found` after global install ```bash theme={null} # Find NPM global bin directory npm config get prefix # Add to PATH (Linux/macOS) echo 'export PATH="$(npm config get prefix)/bin:$PATH"' >> ~/.bashrc source ~/.bashrc # For zsh users echo 'export PATH="$(npm config get prefix)/bin:$PATH"' >> ~/.zshrc source ~/.zshrc # Verify which automagik-forge ``` ```bash theme={null} # Run directly without installing npx automagik-forge # Create alias for convenience echo 'alias forge="npx automagik-forge"' >> ~/.bashrc ``` ```bash theme={null} # Remove old installation npm uninstall -g @automagik/forge # Clear npm cache npm cache clean --force # Reinstall npm install -g @automagik/forge # Verify automagik-forge --version ``` *** ### Unsupported Platform **Problem**: `❌ Unsupported platform: linux-arm32` **Supported Platforms:** * Linux x64 * Linux ARM64 * macOS x64 (Intel) * macOS ARM64 (Apple Silicon) * Windows x64 * Windows ARM64 **Solution**: ```bash theme={null} # Build from source for unsupported platforms git clone https://github.com/namastexlabs/automagik-forge.git cd automagik-forge ./local-build.sh # This requires: # - Rust 1.83+ # - Node.js 18+ # - pnpm 8+ ``` *** ### Permission Denied **Problem**: `EACCES: permission denied` during installation **Fix NPM permissions** (don't use sudo): ```bash theme={null} # Create directory for global packages mkdir ~/.npm-global # Configure npm to use new directory npm config set prefix '~/.npm-global' # Add to PATH echo 'export PATH=~/.npm-global/bin:$PATH' >> ~/.bashrc source ~/.bashrc # Now install without sudo npm install -g @automagik/forge ``` ```bash theme={null} # Use sudo (not ideal, but works) sudo npm install -g @automagik/forge # You may need sudo to run it sudo automagik-forge ``` *** ## Server Issues ### Port Already in Use **Problem**: `Error: listen EADDRINUSE: address already in use :::3000` **Solution**: ```bash theme={null} # Find process using the port lsof -i :3000 # macOS/Linux netstat -ano | findstr :3000 # Windows # Kill the process kill -9 # macOS/Linux taskkill /PID /F # Windows # Or use different port automagik-forge --port 8080 --backend-port 5001 ``` *** ### Backend Not Responding **Problem**: Frontend loads but API requests fail **Symptoms**: * Empty task board * "Failed to fetch" errors * Network errors in console **Solutions**: ```bash theme={null} # Verify backend is running curl http://localhost:5000/api/projects # If it fails, check the port # Look for "Backend server listening on: http://127.0.0.1:XXXX" in logs # Update frontend proxy if needed # Frontend auto-detects backend port from environment ``` ```bash theme={null} # macOS sudo /usr/libexec/ApplicationFirewall/socketfilterfw --list # Linux (ufw) sudo ufw status # Windows # Check Windows Defender Firewall settings ``` ```bash theme={null} # Stop Forge (Ctrl+C) # Clear any stale processes pkill -f automagik-forge # Restart automagik-forge ``` *** ### Database Locked **Problem**: `database is locked` errors **Solution**: ```bash theme={null} # Stop Forge # Ctrl+C or pkill -f automagik-forge # Check for lock file ls -la .forge/ # Remove lock if exists rm .forge/db.sqlite-shm rm .forge/db.sqlite-wal # Restart Forge automagik-forge ``` *** ## GitHub Integration Issues ### OAuth Authentication Failed **Problem**: GitHub authentication fails or redirects to error page **Solutions**: Go to: [https://github.com/settings/developers](https://github.com/settings/developers) Check your OAuth app: * **Homepage URL**: `http://localhost:3000` * **Callback URL**: `http://localhost:3000/auth/callback` ```bash theme={null} # Set GitHub Client ID export GITHUB_CLIENT_ID=your_client_id_here # Or add to .env file echo "GITHUB_CLIENT_ID=your_client_id" >> .env ``` ```bash theme={null} # Remove cached GitHub token rm .forge/github-token.enc # Restart Forge automagik-forge ``` * Open Forge UI * Go to Settings → GitHub * Click "Connect GitHub" * Complete OAuth flow *** ### Repository Not Found **Problem**: "Repository not found" after GitHub authentication **Solution**: ```bash theme={null} # Verify repository access gh repo view owner/repo # Check if repo is private # Ensure OAuth app has correct permissions # Re-select repository in Forge UI # Settings → GitHub → Select Repository ``` *** ## Executor/AI Agent Issues ### API Key Not Working **Problem**: Tasks fail with "Invalid API key" or "Unauthorized" **Solution**: ```bash theme={null} # Verify API key is set echo $ANTHROPIC_API_KEY # For Claude echo $GOOGLE_AI_API_KEY # For Gemini echo $OPENAI_API_KEY # For OpenAI # Test API key directly curl -H "x-api-key: $ANTHROPIC_API_KEY" \ https://api.anthropic.com/v1/messages # Set if missing export ANTHROPIC_API_KEY=sk-ant-... # Or add to .env echo "ANTHROPIC_API_KEY=sk-ant-..." >> .env # Restart Forge automagik-forge ``` *** ### Executor Timeout **Problem**: Tasks fail with timeout errors **Solution**: ```json theme={null} // Edit .forge/config.json { "executors": { "claude-code": { // Increase timeout (milliseconds) "timeout": 600000 // 10 minutes instead of 5 } } } ``` *** ### Cursor CLI Not Found **Problem**: Cursor CLI executor fails with "command not found" **Solution**: ```bash theme={null} # Find Cursor CLI path which cursor # Update config with correct path { "executors": { "cursor-cli": { "cli_path": "/usr/local/bin/cursor", // or wherever it's installed "args": ["--headless"] } } } ``` *** ## Performance Issues ### Slow Task Execution **Problem**: Tasks take very long to complete **Solutions**: ```bash theme={null} # Check CPU and memory usage top # Check disk space df -h # Free up space if needed # Clean up old worktrees ``` ```json theme={null} // Edit .forge/config.json { "worktrees": { "max_concurrent": 3 // Reduce from 5 } } ``` ```bash theme={null} # Gemini is typically faster than Claude for simple tasks # Try different executors for comparison ``` *** ### High Memory Usage **Problem**: Forge consuming excessive memory **Solution**: ```bash theme={null} # Check memory usage ps aux | grep forge # Clean up worktrees # Via UI: Settings → Cleanup # Or manually rm -rf .forge/worktrees/* # Restart Forge automagik-forge ``` *** ## UI/Display Issues ### Blank Screen **Problem**: Forge UI shows blank white screen **Solutions**: ```bash theme={null} # Clear browser cache # Cmd+Shift+R (macOS) or Ctrl+Shift+R (Windows/Linux) # Check browser console for errors # F12 → Console tab # Try different browser # Chrome, Firefox, Safari, Edge # Verify frontend is running curl http://localhost:3000 ``` *** ### Real-time Updates Not Working **Problem**: Task logs don't stream, UI doesn't update **Solution**: ```bash theme={null} # Check if Server-Sent Events (SSE) are blocked # Some corporate proxies block SSE # Verify connection curl http://localhost:5000/api/events/processes/{id}/logs # Try different network # Disable VPN/proxy temporarily ``` *** ## Data Issues ### Lost Tasks After Restart **Problem**: Tasks disappeared after closing Forge **Solution**: ```bash theme={null} # Check database file exists ls -la .forge/db.sqlite # Verify database integrity sqlite3 .forge/db.sqlite "PRAGMA integrity_check;" # Restore from backup if available cp .forge/db.backup.sqlite .forge/db.sqlite ``` *** ### Cannot Delete Task **Problem**: Task won't delete, keeps reappearing **Solution**: ```bash theme={null} # Force delete via API curl -X DELETE http://localhost:5000/api/tasks/{task-id} # Or delete via database sqlite3 .forge/db.sqlite "DELETE FROM tasks WHERE id='task-id';" # Restart Forge ``` *** ## Next Steps Solutions for git worktree issues Troubleshoot API connection problems Frequently asked questions Get help from the community # FAQ Source: https://docs.namastex.ai/forge/troubleshooting/faq Frequently asked questions about Automagik Forge ## General Questions Automagik Forge is a **Vibe Coding++™ platform** that brings structure to AI-assisted development. It's a visual Kanban board where you plan tasks, choose AI agents to execute them in isolated git worktrees, compare results from multiple agents, and ship code you understand. **Key Features:** * Visual task management Kanban * 8+ AI coding agent integrations (Claude, Cursor, Gemini, etc.) * Git worktree isolation for safe experimentation * Multiple attempts per task (try different agents) * MCP server for AI agent integration * 100% open source and self-hostable **Regular "Vibe Coding" (Chaotic):** * Chat with AI, get code, ship it * Lost in chat history * Code breaks in 2 weeks * No experimentation or comparison * Vendor lock-in to one AI **Vibe Coding++™ with Forge (Structured):** * You plan tasks in persistent Kanban * AI agents execute in isolated worktrees * Compare multiple agent approaches * Review and understand before merge * Code stays maintainable * No vendor lock-in (8+ agents supported) **Yes!** Forge is **100% free and open source** (MIT License). * No subscription fees * No usage limits * Self-hostable on your machine * No vendor lock-in * Community-driven development **Costs you pay:** * AI agent API costs (Claude, Gemini, etc.) - BYOL (Bring Your Own LLM) * Or use free/open-source agents (OpenCode, Qwen Code) Forge supports **8+ AI coding agents**: **Commercial Agents:** * **Claude Code** (Anthropic) - Best for complex logic, security * **Cursor CLI** - Modern React patterns, frontend * **Gemini** (Google) - Fast iterations, good all-rounder * **OpenAI Codex** - GPT-4 based coding * **Amp** (Sourcegraph) - Code intelligence **Open Source/Local Agents:** * **OpenCode** - Free, runs locally * **Qwen Code** (Alibaba) - Open source * **Claude Router** - LLM-agnostic, use ANY model Plus: You can add custom agents! **No!** You only need API access to the agents you want to use. **Options:** 1. **Single AI** - Use just Claude or just Gemini 2. **Free Agents** - Use OpenCode or Qwen (100% free) 3. **Pay-as-you-go** - Most AI APIs are pay-per-use, not subscriptions **Recommendation:** * Start with one AI (Claude Code or Gemini) * Add more later to compare approaches * Use free agents for experimentation *** ## Technical Questions **Git worktrees** allow multiple working directories from one repository. **Normal git workflow:** ```bash theme={null} git checkout feature-branch # Switches your code # Risk: Can break your main branch ``` **Forge worktree workflow:** ```bash theme={null} # Main repo stays on main branch # Each task gets isolated worktree .forge/worktrees/task-1-attempt-1/ # AI works here .forge/worktrees/task-2-attempt-1/ # Another task here # Your main codebase is never touched # Review results, merge when ready ``` **Benefits:** * Multiple tasks execute simultaneously * Main branch stays clean * Safe experimentation * Easy rollback **Attempts** let you try the same task with different AI agents. **Example:** ``` Task: "Add user authentication" Attempt 1: Claude Code → Comprehensive but complex Attempt 2: Gemini → Simple but missing edge cases Attempt 3: Cursor → Perfect balance ✅ You choose: Attempt 3 to merge ``` **Benefits:** * Compare different approaches * Learn which agent works best for what * No risk (each in isolated worktree) * Choose best implementation **No**, Forge requires a git repository. **Why:** * Git worktrees provide isolation * Version control tracks changes * Safe rollback if needed **Quick setup if you don't have git:** ```bash theme={null} cd your-project git init git add . git commit -m "Initial commit" # Now run Forge automagik-forge ``` **Yes!** Forge works great with monorepos. Each sub-project can have its own Forge instance: ```bash theme={null} # Frontend cd monorepo/frontend automagik-forge --port 3000 # Backend cd monorepo/backend automagik-forge --port 3001 # Mobile cd monorepo/mobile automagik-forge --port 3002 ``` Or use one Forge for entire monorepo with labeled tasks. **Not recommended.** Forge is designed for **development**, not CI/CD. **Instead, use Forge to:** * Develop features locally * Review AI-generated code * Merge to main when approved **Then use normal CI/CD:** * GitHub Actions * GitLab CI * Jenkins * etc. Forge tasks create branches → you review → merge → CI/CD runs. *** ## Usage Questions ```bash theme={null} cd your-project automagik-forge ``` Opens at `http://localhost:3000` * Click "New Task" button * Title: "Add dark mode toggle" * Description: "Create toggle component for light/dark theme" * Labels: feature, frontend * Click "Create" * Click on task card * Click "New Attempt" * Select agent: Claude Code, Gemini, or Cursor * Click "Start" * Watch real-time logs * See code changes as they happen * Review when complete * If good: Click "Merge to Main" * If not: Create new attempt with different agent * Compare results Create a task normally * Choose agent (e.g., Claude Code) * Start execution * Wait for completion * Click "New Attempt" on same task * Choose different agent (e.g., Gemini) * Start execution * Click "Compare Attempts" * See side-by-side diff * Review pros/cons * Choose best approach * Select best attempt * Click "Merge" * Other attempts auto-cleanup **Yes!** Via **MCP (Model Context Protocol)**. **Supported AI agents:** * Claude Code * Cursor * VSCode + Cline * Roo Code * Gemini CLI * Any MCP-compatible agent **Setup:** 1. Get your Project ID: ```bash theme={null} cat .forge/config.json | grep project_id ``` 2. Configure MCP server (example for Claude Code): ```json theme={null} { "mcpServers": { "automagik-forge": { "command": "npx", "args": ["automagik-forge", "--mcp"], "env": { "PROJECT_ID": "your-uuid-here" } } } } ``` 3. Use from AI agent: ``` "Create a new task: Add user authentication with JWT" "List all high-priority tasks" "Update task-123 status to done" ``` See [MCP Integration](/forge/mcp/overview) for details. * Create GitHub OAuth App: [https://github.com/settings/developers](https://github.com/settings/developers) * Callback URL: `http://localhost:3000/auth/callback` * Copy Client ID ```bash theme={null} export GITHUB_CLIENT_ID=your_client_id automagik-forge ``` * Settings → GitHub * Click "Connect GitHub" * Authorize app * Select repository * Forge can import GitHub issues as tasks * Tasks can link to GitHub issues * PRs can be created from tasks **Possible but not recommended.** **Forge is designed for individual use:** * Each developer runs their own Forge instance * Tasks in personal Kanban * Individual git worktrees **For team collaboration:** * Each person runs Forge locally * Coordinate via GitHub/GitLab * Share task templates and patterns * Use same agents/settings across team **Future:** Team collaboration features planned for later versions. *** ## Troubleshooting Questions **Common causes:** 1. **API Key Issues:** ```bash theme={null} # Verify API key is set echo $ANTHROPIC_API_KEY # For Claude # Set if missing export ANTHROPIC_API_KEY=sk-ant-... ``` 2. **Git Issues:** ```bash theme={null} # Ensure you're in a git repo git status # Commit uncommitted changes git add . git commit -m "Save work" ``` 3. **Executor Not Configured:** ```bash theme={null} # Check executors enabled cat .forge/config.json | jq '.executors' # Enable in UI: Settings → Executors ``` 4. **Worktree Issues:** ```bash theme={null} # Clean up old worktrees git worktree prune rm -rf .forge/worktrees/* ``` See [Troubleshooting](/forge/troubleshooting/common-issues) for more. **Via UI (Recommended):** * Settings → Cleanup → Remove Old Worktrees **Manually:** ```bash theme={null} # Remove all worktree directories rm -rf .forge/worktrees/* # Prune git references git worktree prune # Restart Forge automagik-forge ``` **Automatically:** ```json theme={null} // In .forge/config.json { "worktrees": { "auto_delete_merged": true, "cleanup_on_exit": true } } ``` **Causes:** * Many git worktrees (each is full code copy) * Large git repository * Many task attempts * Database growth **Solutions:** 1. **Clean up worktrees:** ```bash theme={null} rm -rf .forge/worktrees/* git worktree prune ``` 2. **Clean up database:** ```bash theme={null} sqlite3 .forge/db.sqlite "DELETE FROM tasks WHERE status='done' AND updated_at < datetime('now', '-30 days');" sqlite3 .forge/db.sqlite "VACUUM;" ``` 3. **Enable auto-cleanup:** ```json theme={null} { "worktrees": { "auto_delete_merged": true, "max_concurrent": 3 } } ``` **Yes**, but with limitations. **Headless mode:** ```bash theme={null} # Start backend only BACKEND_PORT=5000 automagik-forge # Access via API curl http://server-ip:5000/api/projects # Or use MCP mode automagik-forge --mcp ``` **Limitations:** * No web UI (can build separately and point to API) * Need to manage via API or MCP only * GitHub OAuth requires redirect to localhost **Better approach:** * Run Forge on your local machine * Use git/GitHub to share code changes * Each developer has own Forge instance *** ## Advanced Questions **Yes!** You can add custom executors. **Example custom agent:** ```json theme={null} // In .forge/config.json { "executors": { "my-custom-agent": { "enabled": true, "type": "http", "endpoint": "http://localhost:8887/api/execute", "headers": { "Authorization": "Bearer ${CUSTOM_AGENT_TOKEN}" }, "timeout": 600000 } } } ``` Your custom agent must accept Forge's execution API format. See [Custom Executors](/forge/advanced/custom-executors) for details. **Forge is open source!** Contributions welcome. **Ways to contribute:** 1. **Report bugs:** * [https://github.com/namastexlabs/automagik-forge/issues](https://github.com/namastexlabs/automagik-forge/issues) 2. **Suggest features:** * GitHub Discussions or Discord 3. **Submit pull requests:** * Fork the repo * Create feature branch * Submit PR 4. **Improve documentation:** * Docs are in `/docs` directory * Submit PR with improvements 5. **Join community:** * Discord: [https://discord.gg/xcW8c7fF3R](https://discord.gg/xcW8c7fF3R) * Help other users * Share templates and patterns See [CONTRIBUTING.md](https://github.com/namastexlabs/automagik-forge/blob/main/CONTRIBUTING.md) **Upcoming features:** ### Q4 2024 * Template marketplace * Task dependencies visualization * UI revamp * Analytics dashboard * Spark integration (scheduled tasks) ### Q1-Q2 2025 * Cross-Forge sync (share tasks) * Hive executor (proprietary agent) * Non-code workflows (docs, PPTs) * Enterprise features * Mobile companion app ### Future * AI intelligence layer * Global template marketplace * Industry verticals * Cloud offering (optional SaaS) See full roadmap: [https://github.com/orgs/namastexlabs/projects/9](https://github.com/orgs/namastexlabs/projects/9) **Local storage:** * All data stored locally in `.forge/` directory * SQLite database (unencrypted) * GitHub OAuth tokens encrypted **No cloud sync** (by default): * Your code never leaves your machine * Tasks stored locally only * No telemetry (except optional PostHog) **Security recommendations:** 1. **Never commit `.forge/` to git:** ```gitignore theme={null} .forge/ .env ``` 2. **Restrict file permissions:** ```bash theme={null} chmod 600 .forge/config.json chmod 700 .forge/ ``` 3. **Use environment variables for secrets:** ```bash theme={null} export ANTHROPIC_API_KEY=... # Not in config files ``` 4. **Backup important data:** ```bash theme={null} cp -r .forge .forge-backup ``` Forge is 100% self-hosted. You control your data. *** ## Getting Help Join our Discord for real-time help and discussion Report bugs and request features Browse complete documentation Follow for updates and tips *** **Still have questions?** Ask in [Discord](https://discord.gg/xcW8c7fF3R) or open a [GitHub Discussion](https://github.com/namastexlabs/automagik-forge/discussions)! # Git Worktree Errors Source: https://docs.namastex.ai/forge/troubleshooting/git-worktree-errors Troubleshooting git worktree issues in Forge ## Overview Forge uses **git worktrees** to isolate task execution. Each task runs in its own worktree, preventing conflicts and allowing parallel development. However, this can occasionally cause issues. *** ## Common Worktree Errors ### Worktree Creation Failed **Problem**: `fatal: could not create worktree` **Causes & Solutions**: ```bash theme={null} # Verify you're in a git repo git status # If not, initialize git init # Add remote if needed git remote add origin https://github.com/owner/repo.git # Make initial commit git add . git commit -m "Initial commit" ``` ```bash theme={null} # Stash uncommitted changes git stash # Or commit them git add . git commit -m "WIP: save changes" # Try task again ``` ```bash theme={null} # Check available space df -h # Clean up old worktrees rm -rf .forge/worktrees/* # Or via Forge UI # Settings → Cleanup → Remove Old Worktrees ``` ```bash theme={null} # Check permissions on .forge directory ls -la .forge # Fix permissions chmod -R 755 .forge/worktrees # Ensure you own the directory sudo chown -R $USER .forge ``` *** ### Worktree Already Exists **Problem**: `fatal: worktree already exists` **Solution**: ```bash theme={null} # List existing worktrees git worktree list # Remove stale worktree git worktree remove .forge/worktrees/task-123-attempt-1 # Or force remove if it's corrupted git worktree remove --force .forge/worktrees/task-123-attempt-1 # Prune worktree references git worktree prune # Try creating task again ``` *** ### Cannot Remove Worktree **Problem**: `fatal: worktree contains modified or untracked files` **Solution**: ```bash theme={null} # Navigate to worktree cd .forge/worktrees/task-123-attempt-1 # See what's modified git status # Option 1: Stash changes git stash # Option 2: Discard changes git reset --hard HEAD git clean -fd # Option 3: Force remove (loses changes) cd ../.. git worktree remove --force .forge/worktrees/task-123-attempt-1 ``` *** ### Orphaned Worktrees **Problem**: Worktree directories exist but git doesn't know about them **Symptoms**: * `.forge/worktrees/` has directories * `git worktree list` doesn't show them * Disk space consumed **Solution**: ```bash theme={null} # List git's known worktrees git worktree list # List filesystem worktrees ls -la .forge/worktrees/ # Clean up orphans manually rm -rf .forge/worktrees/task-* # Prune git worktree references git worktree prune # Or use Forge's cleanup # Settings → Cleanup → Remove Orphaned Worktrees ``` **Automatic Cleanup**: ```json theme={null} // Enable in .forge/config.json { "worktrees": { "cleanup_on_exit": true, "auto_delete_merged": true } } ``` *** ## Branch Issues ### Branch Already Exists **Problem**: `fatal: a branch named 'forge/task-123' already exists` **Solution**: ```bash theme={null} # Delete the old branch git branch -D forge/task-123 # Or delete from both local and remote git branch -D forge/task-123 git push origin --delete forge/task-123 # Retry task creation ``` *** ### Detached HEAD State **Problem**: Worktree is in detached HEAD state **Solution**: ```bash theme={null} # Navigate to worktree cd .forge/worktrees/task-123-attempt-1 # Check current state git status # Create and checkout branch git checkout -b forge/task-123 # Or checkout existing branch git checkout main git checkout -b forge/task-123 ``` *** ### Cannot Switch Branches **Problem**: `error: you need to resolve your current index first` **Solution**: ```bash theme={null} cd .forge/worktrees/task-123-attempt-1 # Reset index git reset # Or discard all changes git reset --hard HEAD # Clean untracked files git clean -fd ``` *** ## Merge Conflicts ### Conflicts After Task Completion **Problem**: Merge conflicts when merging worktree back to main **Solution**: ```bash theme={null} cd .forge/worktrees/task-123-attempt-1 # Check for conflicts git status # View conflicted files git diff --name-only --diff-filter=U ``` ```bash theme={null} # Open conflicted files in editor # Look for conflict markers: # <<<<<<< HEAD # ======= # >>>>>>> branch # Edit files to resolve vim conflicted-file.ts # Or use merge tool git mergetool ``` ```bash theme={null} # Add resolved files git add conflicted-file.ts # Complete merge git commit ``` ```bash theme={null} # Return to main repo cd ../../.. # Merge the worktree branch git merge forge/task-123 # Or via Forge UI # Review → Approve → Merge ``` *** ### Preventing Merge Conflicts **Best Practices**: 1. **Keep main branch updated**: ```bash theme={null} git checkout main git pull origin main ``` 2. **Rebase before merging**: ```bash theme={null} cd .forge/worktrees/task-123-attempt-1 git fetch origin git rebase origin/main ``` 3. **Use small, focused tasks**: * Smaller changes = fewer conflicts * Complete tasks quickly 4. **Coordinate with team**: * Avoid working on same files simultaneously * Use task dependencies in Forge *** ## Performance Issues ### Too Many Worktrees **Problem**: Hundreds of worktrees consuming disk space **Solution**: ```bash theme={null} # Check worktree count ls .forge/worktrees/ | wc -l # List worktrees with sizes du -sh .forge/worktrees/* # Clean up completed tasks # Via Forge UI: Settings → Cleanup # Or manually remove old worktrees find .forge/worktrees -type d -mtime +7 -exec rm -rf {} + # Prune git references git worktree prune ``` **Configure Auto-cleanup**: ```json theme={null} { "worktrees": { "auto_delete_merged": true, "cleanup_on_exit": true, "max_concurrent": 5 } } ``` *** ### Slow Worktree Creation **Problem**: Creating worktrees takes very long **Causes & Solutions**: ```bash theme={null} # Check repo size du -sh .git # Use shallow clone for worktrees git config worktree.guessRemote true # Clean up old refs git gc --aggressive --prune=now ``` ```bash theme={null} # Skip submodule initialization in worktrees git config worktree.submodules false # Or update submodules only when needed ``` ```bash theme={null} # Move worktrees to faster disk { "worktrees": { "base_path": "/mnt/fast-ssd/forge-worktrees" } } ``` *** ## Debug Mode Enable worktree debugging to diagnose issues: ```bash theme={null} # Disable automatic cleanup export DISABLE_WORKTREE_ORPHAN_CLEANUP=1 # Enable detailed logging export RUST_LOG=debug # Run Forge automagik-forge # Check logs for worktree operations # Look for "worktree" in output ``` *** ## Manual Worktree Management If Forge's automatic worktree management fails, use git directly: ### Create Worktree Manually ```bash theme={null} # Create worktree for task git worktree add .forge/worktrees/task-123-attempt-1 -b forge/task-123 # Do work in worktree cd .forge/worktrees/task-123-attempt-1 # ... make changes ... # Commit git add . git commit -m "Implement feature" # Return to main repo cd ../../.. # Merge git merge forge/task-123 # Remove worktree git worktree remove .forge/worktrees/task-123-attempt-1 ``` ### List All Worktrees ```bash theme={null} # Show all worktrees git worktree list # Example output: # /path/to/repo a1b2c3d [main] # /path/to/repo/.forge/worktrees/task-1 d4e5f6g [forge/task-1] # /path/to/repo/.forge/worktrees/task-2 h7i8j9k [forge/task-2] ``` ### Remove All Worktrees ```bash theme={null} # Get list of worktree paths git worktree list --porcelain | grep worktree | cut -d' ' -f2 # Remove each worktree git worktree list --porcelain | grep worktree | cut -d' ' -f2 | while read dir; do [[ "$dir" != *"/.forge/worktrees/"* ]] || git worktree remove "$dir" done # Prune references git worktree prune ``` *** ## Recovery Procedures ### Corrupted Worktree **Problem**: Worktree is corrupted and won't work **Solution**: ```bash theme={null} # Force remove corrupted worktree git worktree remove --force .forge/worktrees/task-123-attempt-1 # Delete directory if still exists rm -rf .forge/worktrees/task-123-attempt-1 # Delete branch git branch -D forge/task-123 # Prune references git worktree prune # Recreate task in Forge UI ``` ### Complete Reset **Problem**: Worktree system completely broken **Solution**: ```bash theme={null} # BACKUP FIRST cp -r .forge .forge-backup # Remove all worktrees rm -rf .forge/worktrees/* # Prune all worktree references git worktree prune # Delete all forge branches git branch | grep 'forge/' | xargs git branch -D # Reset Forge database rm .forge/db.sqlite # Restart Forge automagik-forge ``` *** ## Next Steps General troubleshooting guide API connection problems Learn how git worktrees work in Forge Get help from the community # Bug Fixing Workflow Source: https://docs.namastex.ai/forge/workflows/bug-fixing Systematic approach to finding and fixing bugs with AI agents ## Overview Bug fixing with Forge combines human debugging intuition with AI agent execution power. You identify and reproduce the bug, AI agents help fix it, and you verify the solution actually works. *** ## The Bug Fixing Cycle ```mermaid theme={null} graph LR A[Report Bug] --> B[Reproduce] B --> C[Diagnose Root Cause] C --> D[Create Fix Task] D --> E[Try Multiple Approaches] E --> F[Verify Fix] F --> G[Add Regression Test] G --> H[Document] ``` *** ## Step 1: Capture the Bug Report Start with clear bug documentation. ### Bug Report Template Create a detailed task card with: ```yaml theme={null} Title: "API returns 500 on malformed JSON input" Description: Environment: Production API v2.3.1 Endpoint: POST /api/users Steps to Reproduce: 1. Send POST request with malformed JSON 2. Missing closing brace in request body Expected: 400 Bad Request with error message Actual: 500 Internal Server Error Impact: High - crashes API server Frequency: ~50 requests/day Example Request: { "name": "John Doe", "email": "john@example.com" # Missing closing brace Labels: bug, backend, priority:high, security ``` ```bash theme={null} forge task create \ --title "API returns 500 on malformed JSON input" \ --type bug \ --priority high \ --labels "backend,security" \ --description "$(cat < ```plaintext theme={null} "I found a bug in production. Create a bug task: Title: API returns 500 on malformed JSON input Type: bug Priority: high Labels: backend, security The POST /api/users endpoint crashes with 500 when receiving malformed JSON. It should return 400 Bad Request instead. This happens about 50 times per day and crashes the API server. High priority security issue." ``` *** ## Step 2: Reproduce the Bug Before fixing, ensure you can reliably reproduce it. ### Create Reproduction Task ```bash theme={null} # Create a task specifically for reproduction forge task create \ --title "Reproduce: API 500 on malformed JSON" \ --description "Write failing test that demonstrates the bug" \ --labels "bug,reproduction" \ --agent claude-code ``` ### Why Reproduction Matters ✅ **Confirms the bug exists** ✅ **Provides regression test** ✅ **Documents exact conditions** ✅ **Verifies fix actually works** ### Example Reproduction Test The AI agent might create: ```typescript theme={null} // test/api/users.test.ts describe('POST /api/users - Error Handling', () => { it('should return 400 for malformed JSON', async () => { const malformedJson = '{"name":"John","email":"john@example.com"'; // Missing } const response = await request(app) .post('/api/users') .set('Content-Type', 'application/json') .send(malformedJson); expect(response.status).toBe(400); // Currently fails with 500 expect(response.body).toHaveProperty('error'); expect(response.body.error).toContain('Invalid JSON'); }); }); ``` *** ## Step 3: Diagnose Root Cause Use AI agents to help analyze the problem. ### Diagnostic Approaches ```bash theme={null} # Let agent analyze the codebase forge task create \ --title "Analyze root cause: API 500 error" \ --description "Review error handling middleware and JSON parsing logic" \ --agent claude-code \ --labels "analysis,bug" ``` Agent might find: ```typescript theme={null} // Missing error handling in middleware app.use(express.json()); // ❌ No error handler ``` ```bash theme={null} # Provide logs to agent for analysis forge task create \ --title "Analyze error logs for JSON parsing bug" \ --description "Review last 100 error logs from production" \ --agent gemini \ --attach-file logs/error-2024-10-31.log ``` ```bash theme={null} # Analyze stack trace forge task create \ --title "Trace error: SyntaxError in JSON.parse" \ --description "Follow stack trace to find unhandled exception" \ --agent claude-code ``` *** ## Step 4: Create Fix Tasks Break down the fix into focused tasks. ### Example: JSON Parsing Bug Fix ```bash theme={null} # Task 1: Add error handling middleware forge task create \ --title "Add JSON parsing error handler" \ --description "Catch SyntaxError from express.json() and return 400" \ --agent claude-code \ --labels "bug,fix" # Task 2: Add validation forge task create \ --title "Add request validation middleware" \ --description "Validate request body structure before processing" \ --agent cursor-cli \ --labels "bug,validation" # Task 3: Improve error messages forge task create \ --title "Add detailed error messages for malformed JSON" \ --description "Return helpful error messages indicating what's wrong" \ --agent gemini \ --labels "bug,ux" ``` *** ## Step 5: Try Multiple Approaches Use Forge's multi-attempt feature to explore different solutions. ### Approach Comparison ```typescript theme={null} // Add error handling middleware app.use((err, req, res, next) => { if (err instanceof SyntaxError && err.status === 400 && 'body' in err) { return res.status(400).json({ error: 'Invalid JSON', message: err.message }); } next(); }); ``` **Pros**: Standard Express pattern **Cons**: Only handles middleware errors ```typescript theme={null} // Replace express.json() with custom parser app.use((req, res, next) => { try { req.body = JSON.parse(req.body); next(); } catch (err) { return res.status(400).json({ error: 'Malformed JSON', details: err.message }); } }); ``` **Pros**: Full control over parsing **Cons**: Reinventing the wheel ```typescript theme={null} // Use express-json-validator-middleware import { Validator } from 'express-json-validator-middleware'; const validator = new Validator({}); app.use(express.json({ verify: (req, res, buf) => { try { JSON.parse(buf); } catch (err) { throw new SyntaxError('Invalid JSON format'); } } })); ``` **Pros**: Validates before parsing **Cons**: Additional dependency ### Compare Attempts ```bash theme={null} # Run all three approaches forge task start task-1 --agent claude-code forge task fork task-1 --agent gemini forge task fork task-1 --agent cursor-cli # Compare results forge task compare task-1 # Test each approach forge task test task-1-attempt-1 forge task test task-1-attempt-2 forge task test task-1-attempt-3 ``` **Decision Matrix:** | Criterion | Claude (Middleware) | Gemini (Custom) | Cursor (Validation) | | --------------- | ------------------- | --------------- | ------------------- | | Code Quality | ⭐⭐⭐⭐⭐ | ⭐⭐⭐ | ⭐⭐⭐⭐ | | Performance | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐ | ⭐⭐⭐⭐ | | Maintainability | ⭐⭐⭐⭐⭐ | ⭐⭐ | ⭐⭐⭐⭐ | | Security | ⭐⭐⭐⭐ | ⭐⭐⭐ | ⭐⭐⭐⭐⭐ | | **Winner** | ✅ **Best overall** | ❌ | ⚠️ Good alternative | *** ## Step 6: Verify the Fix Never trust a fix without verification. ### Verification Checklist ```bash theme={null} # Run the original failing test forge task test task-reproduction # Should now pass ✅ ``` ```bash theme={null} # Create additional test task forge task create \ --title "Test edge cases for JSON parsing fix" \ --description "Test various malformed JSON scenarios" \ --agent claude-code ``` Tests should cover: * Missing closing bracket * Extra commas * Invalid escape sequences * Empty request body * Non-JSON content type ```bash theme={null} # Run full test suite forge task create \ --title "Run full test suite" \ --agent cursor-cli ``` Ensure the fix didn't break existing functionality. ```bash theme={null} # Benchmark before and after forge task create \ --title "Benchmark JSON parsing performance" \ --description "Compare performance before and after fix" \ --agent gemini ``` *** ## Step 7: Add Regression Test Prevent the bug from coming back. ```bash theme={null} # Create comprehensive test task forge task create \ --title "Add regression test suite for JSON parsing" \ --description "Cover all malformed JSON scenarios found in production" \ --agent claude-code \ --labels "testing,regression" ``` ### Example Regression Test Suite ```typescript theme={null} describe('JSON Parsing - Regression Tests', () => { test.each([ ['missing closing brace', '{"name":"John"'], ['extra comma', '{"name":"John",}'], ['invalid escape', '{"name":"John\\x"}'], ['trailing text', '{"name":"John"}extra'], ['leading text', 'extra{"name":"John"}'], ])('should return 400 for: %s', async (scenario, malformed) => { const response = await request(app) .post('/api/users') .send(malformed); expect(response.status).toBe(400); expect(response.body.error).toBeDefined(); }); }); ``` *** ## Step 8: Document the Fix Update documentation to help prevent similar bugs. ```typescript theme={null} // ⚠️ IMPORTANT: JSON parsing error handler // This middleware catches SyntaxError from malformed JSON // and returns 400 instead of crashing with 500. // See: https://github.com/yourorg/repo/issues/123 app.use((err, req, res, next) => { if (err instanceof SyntaxError && 'body' in err) { return res.status(400).json({ error: 'Invalid JSON', message: 'Request body contains malformed JSON' }); } next(); }); ``` ```markdown theme={null} ## [2.3.2] - 2024-10-31 ### Fixed - API now returns 400 Bad Request instead of 500 when receiving malformed JSON - Added comprehensive error messages for JSON parsing errors - Added regression test suite for JSON validation ### Security - Fixed crash vulnerability when processing malformed JSON input ``` **Error Response Documentation:** ### 400 Bad Request - Invalid JSON Returned when request body contains malformed JSON. **Example Response:** ```json theme={null} { "error": "Invalid JSON", "message": "Unexpected token } in JSON at position 42" } ``` **Common Causes:** * Missing closing braces or brackets * Trailing commas * Invalid escape sequences *** ## Real-World Example: Memory Leak Bug Here's a complete bug fix workflow for a production memory leak: ```bash theme={null} # Create investigation tasks forge task create --title "Analyze memory usage patterns" --agent claude-code forge task create --title "Review event listener registrations" --agent gemini forge task create --title "Check for unclosed connections" --agent cursor-cli # Run parallel analysis forge task start-batch task-1 task-2 task-3 # Finding: WebSocket connections not cleaned up on disconnect ``` ```bash theme={null} # Try different fix approaches forge task create --title "Add connection cleanup on disconnect" --agent claude-code forge task fork task-4 --agent gemini # Alternative approach # Compare solutions forge task compare task-4 # Claude's approach wins - more comprehensive ``` ```bash theme={null} # Add monitoring and tests forge task create --title "Add memory leak regression tests" --agent claude-code forge task create --title "Add connection pool monitoring" --agent gemini # Verify fix in staging forge task create --title "Load test in staging environment" --agent cursor-cli # All passed - merge and deploy forge task merge-all-approved ``` *** ## Bug Severity & Agent Strategy Choose your approach based on bug severity: **Characteristics**: Production down, data loss, security breach **Strategy**: ```bash theme={null} # Use fastest, most reliable agent forge task create --title "URGENT: Fix auth bypass" --agent claude-code # No time for multiple attempts - go with proven agent # Document and refactor later if needed ``` **Characteristics**: Feature broken, bad UX, performance issue **Strategy**: ```bash theme={null} # Try 2-3 approaches, choose best forge task create --title "Fix slow API response" --agent claude-code forge task fork task-1 --agent gemini # Compare and pick winner forge task compare task-1 ``` **Characteristics**: Minor issue, edge case, cosmetic **Strategy**: ```bash theme={null} # Experiment with different agents forge task create --title "Fix button alignment" --agent cursor-cli forge task fork task-1 --agent gemini forge task fork task-1 --agent claude-code # Good opportunity to learn which agent handles CSS best ``` **Characteristics**: Nice-to-have, typos, cleanup **Strategy**: ```bash theme={null} # Use fastest agent, batch with other low-priority tasks forge task create --title "Fix typo in error message" --agent gemini --batch-id cleanup-sprint ``` *** ## Pro Tips for Bug Fixing Never start fixing until you have a failing test: ```bash theme={null} # ✅ Correct order 1. Write failing test 2. Run test (confirms it fails) 3. Fix the bug 4. Run test (confirms it passes) # ❌ Wrong order 1. Make changes hoping to fix bug 2. Deploy and pray ``` ```bash theme={null} # Create bisect task forge task create \ --title "Bisect: Find commit that introduced bug" \ --description "Use git bisect to find regression commit" \ --agent claude-code ``` Good labels help with prioritization and analytics: ```bash theme={null} --labels "bug,security,database,priority:high,customer-reported" ``` ```bash theme={null} forge task create \ --title "Fix #123: API timeout" \ --github-issue 123 \ --related-pr 456 ``` *** ## Common Bug Patterns **Best Agent**: Claude Code (thorough type checking) ```bash theme={null} forge task create \ --title "Add null checks to user profile" \ --agent claude-code ``` **Best Agent**: Claude Code (complex async logic) ```bash theme={null} forge task create \ --title "Fix race condition in payment processing" \ --agent claude-code ``` **Best Agent**: Claude Code or Cursor CLI ```bash theme={null} forge task create \ --title "Fix memory leak in event listeners" \ --agent claude-code ``` **Best Agent**: Try multiple, compare benchmarks ```bash theme={null} forge task create \ --title "Optimize slow database query" \ --agent claude-code forge task fork task-1 --agent gemini ``` *** ## Next Steps Build new features with confidence Safe code improvements with AI Multi-agent PR review process Comprehensive testing strategies *** **Remember**: Bugs are opportunities to improve. With Forge, you can experiment with multiple fix approaches in isolation, choose the best solution, and ensure it never happens again. # Code Review Workflow Source: https://docs.namastex.ai/forge/workflows/code-review Multi-agent PR review for comprehensive code quality ## Overview Code review with Forge uses multiple AI agents as additional reviewers, each bringing different perspectives. Combine human judgment with AI analysis to catch more issues and ship higher quality code. *** ## The Multi-Agent Review Process ```mermaid theme={null} graph LR A[Create PR] --> B[Auto-Review Task] B --> C[Multiple Agent Reviews] C --> D[Aggregate Feedback] D --> E[Human Review] E --> F{Approve?} F -->|Yes| G[Merge] F -->|No| H[Address Feedback] H --> B ``` *** ## Step 1: Prepare for Review Before requesting review, ensure your PR is review-ready. \###Pre-Review Checklist ```bash theme={null} # Create pre-review task forge task create \ --title "Pre-review checklist for PR #123" \ --description "$(cat < ```bash theme={null} forge task create \ --title "Security review: PR #123 authentication changes" \ --description "Review for: SQL injection, XSS, auth bypasses, secret exposure" \ --agent claude-code \ --labels "review,security" \ --attach-pr 123 ``` **Claude excels at:** * Security vulnerabilities * Logic errors * Edge cases * Complex algorithms ```bash theme={null} forge task create \ --title "Performance review: PR #123" \ --description "Check for: N+1 queries, memory leaks, inefficient algorithms" \ --agent gemini \ --labels "review,performance" \ --attach-pr 123 ``` **Gemini excels at:** * Performance issues * Resource usage * Scalability concerns * Quick scans ```bash theme={null} forge task create \ --title "Best practices review: PR #123" \ --description "Check: Code style, patterns, naming, structure" \ --agent cursor-cli \ --labels "review,quality" \ --attach-pr 123 ``` **Cursor excels at:** * Modern patterns * Framework best practices * Code organization * TypeScript idioms ```bash theme={null} forge task create \ --title "Test coverage review: PR #123" \ --description "Verify: Test coverage, edge cases, integration tests" \ --agent claude-code \ --specialized-agent "test-reviewer" \ --labels "review,testing" \ --attach-pr 123 ``` **Test reviewer checks:** * Test coverage percentage * Missing edge cases * Test quality * Integration test gaps *** ## Step 3: Run Reviews in Parallel Execute all reviews simultaneously for faster feedback. ```bash theme={null} # Launch all review tasks at once forge task start-batch \ task-security \ task-performance \ task-best-practices \ task-testing \ --parallel # Monitor progress forge task watch-batch --all-reviews # Results ready in ~5-10 minutes ``` *** ## Step 4: Aggregate Feedback Collect and organize feedback from all agents. ### Example Review Aggregation ```bash theme={null} forge task create \ --title "Aggregate all PR #123 reviews" \ --description "Combine feedback from all agents into single report" \ --agent gemini \ --depends-on task-security,task-performance,task-best-practices,task-testing ``` **Aggregated Report Structure:** ```markdown theme={null} # PR #123 Review Summary ## 🔴 Critical Issues (3) 1. **[Security]** SQL injection vulnerability in user search - Agent: Claude Code - File: `src/api/users.ts:45` - Fix: Use parameterized queries 2. **[Performance]** N+1 query in order list endpoint - Agent: Gemini - File: `src/api/orders.ts:120` - Fix: Use eager loading with joins 3. **[Testing]** Missing tests for error scenarios - Agent: Test Reviewer - Coverage: 45% (target: 80%) - Fix: Add error case tests ## 🟡 Medium Issues (7) ... ## 🟢 Minor Issues (12) ... ## ✅ Positive Feedback - Good separation of concerns - Clear naming conventions - Comprehensive error handling ``` *** ## Step 5: Address Feedback Create tasks to address review feedback. ```bash theme={null} # Critical issues - fix immediately forge task create \ --title "Fix SQL injection in user search" \ --description "Use parameterized queries, validate input" \ --priority critical \ --agent claude-code \ --labels "bugfix,security" # Medium issues - fix before merge forge task create \ --title "Optimize order list query" \ --description "Replace N+1 with JOIN query" \ --priority high \ --agent gemini # Minor issues - address or defer forge task create \ --title "Improve variable naming in auth module" \ --priority low \ --agent cursor-cli \ --labels "refactor,nice-to-have" ``` *** ## Review Patterns for Different PR Types ```bash theme={null} # Comprehensive multi-agent review forge review create \ --pr 123 \ --agents claude-code,gemini,cursor-cli \ --focus security,performance,best-practices,testing \ --parallel ``` **Review Focus:** * Feature completeness * Test coverage * Security implications * Performance impact * Documentation ```bash theme={null} # Focus on regression prevention forge review create \ --pr 124 \ --agents claude-code,gemini \ --focus security,testing,regression \ --specialized-agent "bug-fix-reviewer" ``` **Review Focus:** * Root cause addressed * Regression tests added * No new bugs introduced * Similar bugs elsewhere ```bash theme={null} # Ensure no behavior changes forge review create \ --pr 125 \ --agents cursor-cli,claude-code \ --focus behavior-preservation,testing \ --require-benchmark ``` **Review Focus:** * All tests still pass * No behavior changes * Code quality improved * Performance not degraded ```bash theme={null} # Fast security/critical review only forge review create \ --pr 126 \ --agents claude-code \ --focus security,correctness \ --fast-track ``` **Review Focus:** * Fixes the critical issue * No new vulnerabilities * Minimal scope * Can be rolled back *** ## Specialized Review Agents Create custom review agents for specific needs. ### Creating a Custom Reviewer ```yaml theme={null} # .forge/agents/security-reviewer.yml name: security-reviewer description: "Security-focused code reviewer" base_agent: claude-code system_prompt: | You are a security-focused code reviewer. Review code for: OWASP Top 10 vulnerabilities: - SQL Injection - XSS (Cross-Site Scripting) - CSRF - Authentication/Authorization flaws - Security misconfigurations - Sensitive data exposure - Insufficient logging - XML External Entities (XXE) - Broken access control - Using components with known vulnerabilities Also check for: - Hardcoded secrets - Weak cryptography - Insecure dependencies - Input validation - Output encoding - Rate limiting - Error message information leakage Provide specific, actionable feedback with: - Severity (Critical/High/Medium/Low) - Exact file and line number - Vulnerability explanation - Remediation steps - Example secure code checklist: - SQL injection prevention - XSS prevention - Authentication checks - Authorization checks - Input validation - Output encoding - Secret management - Dependency security ``` ### Using Custom Reviewers ```bash theme={null} forge task create \ --title "Deep security review: Payment processing PR" \ --agent claude-code \ --specialized-agent "security-reviewer" \ --attach-pr 127 ``` *** ## Review Automation ### Auto-Review on PR Creation ```yaml theme={null} # .forge/workflows/auto-review.yml name: Auto-Review PR on: pull_request: types: [opened, synchronize] jobs: multi-agent-review: runs-on: forge-server steps: - name: Security Review run: | forge task create \ --title "Security review: PR ${{ github.event.number }}" \ --agent claude-code \ --specialized-agent "security-reviewer" \ --attach-pr ${{ github.event.number }} \ --auto-comment - name: Performance Review run: | forge task create \ --title "Performance review: PR ${{ github.event.number }}" \ --agent gemini \ --specialized-agent "performance-reviewer" \ --attach-pr ${{ github.event.number }} \ --auto-comment - name: Best Practices Review run: | forge task create \ --title "Best practices review: PR ${{ github.event.number }}" \ --agent cursor-cli \ --attach-pr ${{ github.event.number }} \ --auto-comment - name: Aggregate Results run: | forge review aggregate \ --pr ${{ github.event.number }} \ --post-summary ``` ### GitHub Integration ```bash theme={null} # Configure Forge to comment on PRs forge config set github.auto_comment true forge config set github.review_threshold "critical,high" # Agents will automatically post comments ``` **Example Auto-Comment:** ````markdown theme={null} ## 🤖 Forge Security Review **Agent:** Claude Code (security-reviewer) **Status:** ⚠️ Issues Found ### 🔴 Critical Issues (1) **SQL Injection in User Search** - **File:** `src/api/users.ts` - **Line:** 45 - **Severity:** Critical **Current Code:** ```typescript const query = `SELECT * FROM users WHERE name = '${searchTerm}'`; ```` **Issue:** User input is directly interpolated into SQL query. **Fix:** ```typescript theme={null} const query = 'SELECT * FROM users WHERE name = ?'; const results = await db.query(query, [searchTerm]); ``` *** *Reviewed by Automagik Forge • [View Full Report](https://forge.example.com/reviews/123)* ```` --- ## Measuring Review Quality Track metrics to improve review process. ### Issue Detection Rate **Measure effectiveness:** ```bash forge analytics review-effectiveness --period last-30-days ```` **Metrics tracked:** * Issues caught by AI vs humans * False positive rate * Severity distribution * Time to fix ### Agent Performance **Compare agent effectiveness:** ```bash theme={null} forge analytics agent-review-performance ``` **Comparison:** * Claude: Best at security, logic * Gemini: Best at performance * Cursor: Best at patterns ### Review Coverage **Track review metrics:** ```bash theme={null} forge analytics review-coverage ``` **Metrics:** * Files reviewed per PR * Lines of code reviewed * Review time per PR * Issues found per KLOC *** ## Real-World Example: Complete PR Review ### Large Feature PR Review Workflow ```bash theme={null} # PR #150: Add payment processing with Stripe # Files changed: 25 # Lines: +1,200 -150 # Launch parallel reviews forge review create \ --pr 150 \ --agents claude-code,gemini,cursor-cli \ --specialized-agents security-reviewer,payment-specialist \ --parallel # Results: 45 minutes # - 2 critical security issues # - 8 high priority issues # - 15 medium issues # - 23 minor suggestions ``` ```bash theme={null} # Create fix tasks forge task create \ --title "Fix: Validate webhook signatures" \ --agent claude-code \ --priority critical forge task create \ --title "Fix: Add idempotency keys" \ --agent claude-code \ --priority critical # Push fixes # Re-run security review forge review rerun --pr 150 --agent security-reviewer # ✅ Critical issues resolved ``` ```markdown theme={null} # Human reviewer sees: - AI found 2 critical issues (now fixed) - 8 high priority items addressed - AI review notes on 15 medium items - Human focuses on: - Business logic correctness - UX considerations - Edge cases AI might miss - Overall architecture # Human review time: 30 minutes (vs 2 hours without AI) ``` ```bash theme={null} # All reviews passed # Human approved # Merge PR forge review complete --pr 150 --approved ``` *** ## Pro Tips Let AI catch the obvious issues first: ```bash theme={null} # ✅ Good workflow 1. Push PR 2. AI review runs automatically 3. Fix critical/high issues 4. Request human review 5. Human focuses on nuanced issues # ❌ Bad workflow 1. Push PR 2. Request human review immediately 3. Human finds obvious issues 4. Waste reviewer time ``` ```bash theme={null} # Only block merge on critical/high forge config set review.block_on "critical,high" # Auto-approve if only minor issues forge config set review.auto_approve_threshold "minor" ``` ```bash theme={null} # Stage 1: Quick scan (Gemini - 2 mins) # Stage 2: Deep dive (Claude - 10 mins) # Stage 3: Specialized (Custom agents - 15 mins) forge review create --pr 151 --staged \ --stage-1 gemini \ --stage-2 claude-code \ --stage-3 security-reviewer ``` ```bash theme={null} # Analyze what agents catch most often forge analytics common-issues --by-agent # Improve specialized agents based on patterns forge agent improve security-reviewer \ --based-on-history last-50-reviews ``` *** ## Next Steps Coordinate reviews across teams Automate reviews in your pipeline Create specialized review agents Set up GitHub PR integration *** **Remember**: AI agents are additional reviewers, not replacements for human judgment. They catch common issues quickly, freeing humans to focus on architecture, business logic, and user experience. # Feature Development Workflow Source: https://docs.namastex.ai/forge/workflows/feature-development End-to-end workflow for building new features with Forge ## Overview Feature development with Forge follows the **Vibe Coding++™** approach: you plan and orchestrate, AI agents execute, you review and ship. This workflow ensures you ship production-ready code that you understand and can maintain. *** ## The Feature Development Cycle ```mermaid theme={null} graph LR A[Plan Feature] --> B[Break Down Tasks] B --> C[Create Task Cards] C --> D[Choose Agents] D --> E[Experiment & Iterate] E --> F[Review Results] F --> G[Merge & Ship] G --> H[Document & Test] ``` *** ## Step 1: Plan Your Feature Before jumping into code, plan your feature at a high level. ### Example: Building a Real-Time Notification System **Feature Goal**: Add real-time notifications with WebSocket support, browser notifications, and notification history. **Initial Planning Questions:** * What are the core components needed? * What are the technical dependencies? * What's the order of implementation? * Are there any risks or unknowns? *** ## Step 2: Break Down Into Tasks Decompose your feature into small, focused tasks. Each task should be completable in 15-30 minutes of AI execution. **Golden Rule**: If you can't describe a task in 1-2 sentences, it's too big. Break it down further. ### Example Task Breakdown ```yaml theme={null} Epic: Real-Time Notification System Tasks: 1. Design notification data model and database schema 2. Create WebSocket server with Socket.io 3. Build notification API endpoints (CRUD) 4. Implement browser notification permissions 5. Create notification UI component 6. Add notification history view 7. Write integration tests for WebSocket 8. Add notification settings panel 9. Document notification API ``` *** ## Step 3: Create Task Cards in Forge Open Forge and create your task cards: ```bash theme={null} # Start Forge UI npx automagik-forge # Open http://localhost:3000 # Click "New Task" button # Fill in task details ``` **Task Card Template:** * **Title**: Short, action-oriented (e.g., "Create WebSocket server") * **Description**: Detailed requirements and acceptance criteria * **Labels**: Type (feature, refactor, etc.) and priority * **Dependencies**: Link related tasks ```bash theme={null} # Create task via CLI forge task create \ --title "Create WebSocket server with Socket.io" \ --description "Set up Socket.io server, handle connections, implement room-based notifications" \ --labels "feature,backend,notifications" \ --priority high ``` ```plaintext theme={null} # From Claude Code or any MCP client "Create a new task: - Title: Create WebSocket server with Socket.io - Description: Set up Socket.io server, handle connections, implement room-based notifications - Labels: feature, backend, notifications - Priority: high" ``` *** ## Step 4: Choose Your Agents Strategically Different AI agents have different strengths. Choose based on the task type: **Best Agents:** * **Claude Code**: Excellent for complex logic * **Cursor CLI**: Great for boilerplate * **Gemini**: Fast iterations **Best Agents:** * **Cursor CLI**: Modern React patterns * **Claude Code**: Accessible UI * **Gemini**: Quick prototypes **Best Agents:** * **Claude Code**: Complex migrations * **GPT-4 Codex**: SQL optimization * **Gemini**: Schema design **Best Agents:** * **Claude Code**: Comprehensive tests * **Cursor CLI**: Integration tests * **Specialized "test-writer" agent** ### Example: WebSocket Server Task ```bash theme={null} # Try multiple agents to compare approaches forge task create \ --title "Create WebSocket server" \ --agent claude-code # Create alternative attempt with different agent forge task fork task-123 --agent gemini ``` *** ## Step 5: Experiment & Iterate Forge's git worktree isolation lets you experiment fearlessly. ### Running Multiple Attempts ```bash theme={null} # Claude Code attempts the task forge task start task-123 --agent claude-code # Forge creates: .forge/worktrees/task-123-attempt-1/ ``` ```bash theme={null} # Try Gemini's approach forge task fork task-123 --agent gemini # Forge creates: .forge/worktrees/task-123-attempt-2/ ``` ```bash theme={null} # Watch real-time execution forge task watch task-123 # Or check status forge task status task-123 ``` ### When to Create Multiple Attempts ✅ **Use multiple attempts when:** * Task is complex or critical * You want to compare different approaches * Previous attempt didn't meet requirements * Learning which agent works best for task type ❌ **Single attempt is fine when:** * Task is straightforward * You trust the chosen agent for this task type * Time is constrained *** ## Step 6: Review and Compare Results Never merge without understanding what changed. ### Review Checklist * Does the code follow project conventions? * Are there any code smells or anti-patterns? * Is error handling comprehensive? * Are edge cases covered? * Does it meet all acceptance criteria? * Are there any missing features? * Does it handle the happy path AND edge cases? * Are there any security concerns? * Are there tests for new functionality? * Do existing tests still pass? * Is test coverage adequate? * Are tests meaningful (not just for coverage)? * Is the code self-documenting? * Are complex parts commented? * Is API documentation updated? * Are there usage examples? ### Comparing Multiple Attempts ```bash theme={null} # Side-by-side comparison forge task compare task-123 # See detailed diff between attempts forge diff \ .forge/worktrees/task-123-attempt-1 \ .forge/worktrees/task-123-attempt-2 # Run tests on both attempts forge task test task-123-attempt-1 forge task test task-123-attempt-2 ``` **Example Comparison:** | Aspect | Claude Code Attempt | Gemini Attempt | Winner | | ------------- | --------------------------------- | -------------------- | -------- | | Code Quality | Comprehensive, well-structured | Simple, concise | Claude ✅ | | Performance | Optimized with connection pooling | Basic implementation | Claude ✅ | | Testing | Full test suite | Basic tests | Claude ✅ | | Documentation | Extensive JSDoc | Minimal comments | Claude ✅ | | Time Taken | 8 minutes | 4 minutes | Gemini ⚡ | **Decision**: Choose Claude's approach for production quality. *** ## Step 7: Merge & Ship Once you're satisfied with an attempt, merge it to your main branch. ```bash theme={null} # Review one final time forge task review task-123-attempt-1 # Merge to main forge task merge task-123-attempt-1 # Clean up other attempts forge task cleanup task-123 ``` ### Merge Best Practices **Before merging, always:** 1. Run the full test suite 2. Check for conflicts with main branch 3. Verify no secrets or sensitive data committed 4. Update CHANGELOG if applicable *** ## Step 8: Document & Test Integration After merging individual tasks, test how they work together. ### Integration Testing ```bash theme={null} # Create integration test task forge task create \ --title "Integration test: Notification system end-to-end" \ --description "Test full flow: send notification → WebSocket → browser → history" \ --labels "testing,integration" \ --agent claude-code ``` ### Documentation Task ```bash theme={null} # Document the feature forge task create \ --title "Document notification API and usage" \ --description "Update API docs, add usage examples, create user guide" \ --labels "documentation" \ --agent gemini # Gemini is fast for docs ``` *** ## Real-World Example: Complete Feature Here's a complete workflow for building a user dashboard: ```bash theme={null} # Morning: Plan and create tasks forge task create --title "Design dashboard data model" --agent claude-code forge task create --title "Create dashboard API endpoints" --agent claude-code forge task create --title "Add caching layer with Redis" --agent gemini # Afternoon: Execute and review forge task start-batch task-1 task-2 task-3 forge task review-all forge task merge-selected task-1 task-2 # Merge what's ready ``` ```bash theme={null} # Morning: UI components forge task create --title "Build dashboard layout component" --agent cursor-cli forge task create --title "Create chart components" --agent cursor-cli forge task create --title "Add real-time data updates" --agent claude-code # Try multiple approaches for charts forge task fork task-5 --agent gemini # Compare approaches ``` ```bash theme={null} # Morning: Testing and docs forge task create --title "Write dashboard integration tests" --agent claude-code forge task create --title "Add dashboard user guide" --agent gemini # Afternoon: Final review and ship forge task review-all forge task merge-all-approved # Create PR git checkout -b feature/user-dashboard git push origin feature/user-dashboard gh pr create --title "Add user dashboard with real-time charts" ``` *** ## Pro Tips for Feature Development Build the simplest version first, then enhance: ```bash theme={null} # Iteration 1: Basic functionality forge task create --title "Basic dashboard - static data" # Iteration 2: Add real-time forge task create --title "Add real-time data updates" # Iteration 3: Polish forge task create --title "Add animations and loading states" ``` Link tasks that must be completed in order: ```bash theme={null} forge task create --title "Create API" --id api-task forge task create --title "Build UI" --depends-on api-task ``` Good labeling makes filtering and tracking easier: ```bash theme={null} --labels "feature,frontend,priority:high,sprint-12" ``` Never merge half-finished work. Use Forge's isolation: * Each task in its own worktree * Only merge when tests pass * Review every change before merging *** ## Common Pitfalls to Avoid ### Don't Do This: 1. **Creating Tasks That Are Too Big** * ❌ "Build entire authentication system" * ✅ "Create user registration endpoint" 2. **Not Reviewing Before Merging** * ❌ Blindly merging AI-generated code * ✅ Understanding every change 3. **Using Only One Agent** * ❌ Always using the same agent * ✅ Experimenting to find best fit 4. **Forgetting Tests** * ❌ "I'll add tests later" * ✅ Tests are part of the feature 5. **Poor Task Descriptions** * ❌ "Fix the thing" * ✅ "Add validation to email field in signup form" *** ## Next Steps Learn how to squash bugs with multiple AI agents Safe refactoring with isolated experiments Multi-agent PR review process Coordinating AI-assisted development across teams *** **Remember**: Vibe Coding++™ means you're always in control. The AI agents are powerful tools, but you're the maestro orchestrating them to create production-ready features. # Refactoring Workflow Source: https://docs.namastex.ai/forge/workflows/refactoring Safe code improvements with AI-assisted refactoring ## Overview Refactoring with Forge lets you improve code structure without fear. Git worktree isolation means you can experiment boldly, compare different refactoring approaches, and only merge when you're certain the code is better. *** ## The Refactoring Cycle ```mermaid theme={null} graph LR A[Identify Code Smell] --> B[Define Goal] B --> C[Write Tests First] C --> D[Try Multiple Approaches] D --> E[Compare Results] E --> F[Verify Tests Pass] F --> G[Measure Improvement] G --> H[Merge Best Approach] ``` *** ## When to Refactor * Duplicated code * Long functions (>50 lines) * Complex conditions * Poor naming * God objects/classes * Before adding new features * After fixing bugs * During code review * When tests are green * NOT under pressure **Never refactor:** * Without tests * Under deadline pressure * Multiple things at once * Based on guesswork *** ## Step 1: Safety First - Write Tests Before refactoring, ensure comprehensive test coverage. ```bash theme={null} # Check current test coverage forge task create \ --title "Measure test coverage for auth module" \ --description "Generate coverage report, identify gaps" \ --agent claude-code \ --labels "testing,refactor-prep" # Add missing tests forge task create \ --title "Add tests for auth edge cases" \ --description "Ensure 100% coverage before refactoring" \ --agent claude-code \ --labels "testing" ``` **Golden Rule**: All tests must be green before starting refactoring. If tests fail, fix them first. *** ## Step 2: Define Clear Goals Know exactly what you're improving and how you'll measure it. ### Example Goals **Before**: "Clean up the code" **Better**: "Split 300-line UserService into 3 focused classes, each under 100 lines" ```bash theme={null} forge task create \ --title "Refactor: Split UserService into focused modules" \ --description "Create AuthService, ProfileService, PreferencesService" \ --agent claude-code ``` **Before**: "Make it faster" **Better**: "Reduce API response time from 500ms to under 200ms by optimizing database queries" ```bash theme={null} forge task create \ --title "Refactor: Optimize user lookup queries" \ --description "Add indexes, use eager loading, cache results" \ --agent claude-code \ --attach-benchmark baseline-performance.json ``` **Before**: "Improve the structure" **Better**: "Extract business logic from controllers into service layer" ```bash theme={null} forge task create \ --title "Refactor: Extract business logic from UserController" \ --description "Move all business logic to UserService" \ --agent cursor-cli ``` **Before**: "Remove duplication" **Better**: "Extract 5 duplicate validation functions into shared ValidationUtils" ```bash theme={null} forge task create \ --title "Refactor: Create shared validation utilities" \ --description "Extract email, phone, date, credit card, zip validation" \ --agent gemini ``` *** ## Step 3: Experiment with Multiple Approaches Try different refactoring strategies using different agents. ### Example: Refactoring Large Function ```typescript theme={null} // Original: 150-line processOrder function // Claude's approach: Extract small, focused methods class OrderProcessor { processOrder(order: Order) { this.validateOrder(order); this.calculateTotal(order); this.applyDiscounts(order); this.processPayment(order); this.updateInventory(order); this.sendConfirmation(order); } private validateOrder(order: Order) { /* ... */ } private calculateTotal(order: Order) { /* ... */ } // etc. } ``` **Pros**: Clear, testable methods **Cons**: Many small methods ```typescript theme={null} // Gemini's approach: Functional pipeline const processOrder = pipe( validateOrder, calculateTotal, applyDiscounts, processPayment, updateInventory, sendConfirmation ); ``` **Pros**: Functional, composable **Cons**: Requires pipeline utility ```typescript theme={null} // Cursor's approach: Strategy objects class OrderProcessor { constructor( private validator: OrderValidator, private calculator: PriceCalculator, private payment: PaymentProcessor, private inventory: InventoryManager, private notifications: NotificationService ) {} processOrder(order: Order) { this.validator.validate(order); const total = this.calculator.calculate(order); this.payment.process(order, total); this.inventory.update(order); this.notifications.sendConfirmation(order); } } ``` **Pros**: Highly testable, SOLID **Cons**: More boilerplate ### Compare Approaches ```bash theme={null} # Create all three attempts forge task create --title "Refactor processOrder" --agent claude-code forge task fork task-1 --agent gemini forge task fork task-1 --agent cursor-cli # Compare results forge task compare task-1 # Metrics to compare forge task metrics task-1-attempt-1 \ --measure "lines-of-code,cyclomatic-complexity,test-coverage" ``` **Comparison Matrix:** | Metric | Claude (Methods) | Gemini (Pipeline) | Cursor (Strategy) | | --------------------- | ---------------- | ------------------ | ----------------- | | Lines of Code | 180 | 120 | 220 | | Cyclomatic Complexity | 8 | 3 | 5 | | Test Coverage | 95% | 90% | 98% | | Readability Score | ⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ | ⭐⭐⭐ | | Testability | ⭐⭐⭐⭐ | ⭐⭐⭐ | ⭐⭐⭐⭐⭐ | | **Winner** | Good | ✅ **Best balance** | Overengineered | *** ## Step 4: Verify Everything Still Works After refactoring, run comprehensive verification. ```bash theme={null} # Run full test suite in refactored worktree forge task test task-1-attempt-2 # Compare test results with main branch forge task test-diff main task-1-attempt-2 ``` All tests must pass. No exceptions. ```bash theme={null} # Benchmark before and after forge task create \ --title "Benchmark refactored code vs original" \ --description "Compare memory usage, execution time, throughput" \ --agent gemini # Results should show improvement or no regression ``` ```bash theme={null} # Integration tests forge task create \ --title "Run integration tests for order processing" \ --agent claude-code # Manual smoke tests forge task create \ --title "Manual testing checklist for order flow" \ --description "Test happy path, edge cases, error scenarios" \ --agent gemini ``` ```bash theme={null} # Linting forge task run "npm run lint" task-1-attempt-2 # Type checking forge task run "npm run typecheck" task-1-attempt-2 # Code complexity analysis forge task run "npm run complexity" task-1-attempt-2 ``` *** ## Common Refactoring Patterns ### 1. Extract Function/Method **When**: Function is too long or has multiple responsibilities ```bash theme={null} forge task create \ --title "Refactor: Extract calculateShipping from processOrder" \ --description "Move shipping calculation to separate function" \ --agent gemini # Gemini is fast for simple extractions ``` ### 2. Extract Class **When**: Class has too many responsibilities ```bash theme={null} forge task create \ --title "Refactor: Extract EmailService from UserService" \ --description "Move all email-related logic to EmailService" \ --agent claude-code # Claude handles complex extractions well ``` ### 3. Rename for Clarity **When**: Names are unclear or misleading ```bash theme={null} forge task create \ --title "Refactor: Rename ambiguous variables in auth module" \ --description "data->userData, temp->sessionToken, flag->isAuthenticated" \ --agent cursor-cli # Cursor's LSP integration helps with safe renames ``` ### 4. Introduce Parameter Object **When**: Function has too many parameters ```bash theme={null} forge task create \ --title "Refactor: Replace parameters with UserCreateDTO" \ --description "Combine name, email, phone, address into single object" \ --agent claude-code ``` ### 5. Replace Conditional with Polymorphism **When**: Complex if/switch statements ```bash theme={null} forge task create \ --title "Refactor: Replace payment type switch with strategy pattern" \ --description "Create PaymentStrategy interface with CreditCard, PayPal, Crypto implementations" \ --agent cursor-cli ``` ### 6. Remove Duplication **When**: Same code appears in multiple places ```bash theme={null} forge task create \ --title "Refactor: Extract duplicate validation logic" \ --description "DRY principle - create shared validator utilities" \ --agent gemini ``` *** ## Real-World Example: Legacy Code Modernization Complete refactoring of a legacy authentication module: ```bash theme={null} # Day 1-2: Understand current code forge task create --title "Document legacy auth flow" --agent claude-code forge task create --title "Map dependencies and touch points" --agent gemini # Day 3-5: Add tests forge task create --title "Add unit tests (target 80% coverage)" --agent claude-code forge task create --title "Add integration tests" --agent cursor-cli forge task create --title "Create performance baseline" --agent gemini ``` ```bash theme={null} # Day 1: Extract services forge task create --title "Extract AuthService from monolithic auth.js" --agent claude-code # Day 2: Modernize syntax forge task create --title "Convert callbacks to async/await" --agent gemini # Day 3: Improve error handling forge task create --title "Add proper error handling and logging" --agent claude-code # Day 4: Type safety forge task create --title "Add TypeScript types to auth module" --agent cursor-cli # Day 5: Testing forge task create --title "Verify all tests pass with refactored code" --agent claude-code ``` ```bash theme={null} # Day 1-2: Performance optimization forge task create --title "Optimize token validation" --agent claude-code forge task create --title "Add caching layer" --agent gemini # Day 3-4: Security audit forge task create --title "Security review of auth refactoring" --agent claude-code # Day 5: Documentation forge task create --title "Update auth documentation" --agent gemini # Ship it! forge task merge-all-approved ``` *** ## Refactoring Anti-Patterns to Avoid ### Don't Do This: 1. **Big Bang Refactoring** * ❌ "Rewrite everything at once" * ✅ Small, incremental changes 2. **Refactoring Without Tests** * ❌ "Tests are old, we'll add them later" * ✅ Tests first, then refactor 3. **Changing Behavior** * ❌ "While I'm here, I'll also fix this bug" * ✅ Refactor OR fix bugs, not both 4. **Premature Optimization** * ❌ "This might be slow someday" * ✅ Profile first, optimize only if needed 5. **Over-Engineering** * ❌ "Let's use 5 design patterns here" * ✅ Simplest solution that works *** ## Measuring Refactoring Success Track these metrics to ensure refactoring improved the code: ```bash theme={null} # Before and after comparison forge task create \ --title "Generate code metrics report" \ --agent gemini # Compare: # - Lines of code (should decrease) # - Cyclomatic complexity (should decrease) # - Code duplication (should decrease) # - Test coverage (should increase) ``` ```bash theme={null} # Benchmark comparison forge task create \ --title "Performance comparison" \ --agent claude-code # Metrics: # - Execution time # - Memory usage # - Database queries # - API response time ``` ```bash theme={null} # SonarQube or similar forge task create \ --title "Code quality analysis" \ --agent cursor-cli # Scores: # - Maintainability index # - Technical debt ratio # - Code smells count ``` * Time to understand code (ask team) * Time to add new feature * Bugs introduced per month * Code review feedback *** ## Pro Tips Each commit should pass all tests: ```bash theme={null} # ✅ Good: One refactoring per task forge task create --title "Extract calculateTax method" forge task create --title "Extract calculateShipping method" forge task create --title "Extract applyDiscounts method" # ❌ Bad: Everything at once forge task create --title "Refactor entire order processing" ``` ```typescript theme={null} // Deploy refactored code behind feature flag const orderProcessor = featureFlags.isEnabled('new-order-processor') ? new RefactoredOrderProcessor() : new LegacyOrderProcessor(); // Gradually roll out, monitor for issues ``` ```bash theme={null} forge task create \ --title "Document refactoring decisions" \ --description "ADR: Why we chose pipeline pattern over strategy pattern" \ --agent gemini ``` ```bash theme={null} # One agent refactors, another reviews forge task create --title "Refactor auth module" --agent gemini forge task create --title "Review auth refactoring" --agent claude-code ``` *** ## Next Steps Multi-agent PR review process Comprehensive testing with AI Build features the Vibe Coding++™ way Coordinate refactoring across teams *** **Remember**: Refactoring is not about making code "perfect". It's about making it better, safer, and easier to maintain. With Forge's isolation, you can experiment freely and choose the approach that truly improves your codebase. # Team Collaboration Workflow Source: https://docs.namastex.ai/forge/workflows/team-collaboration Coordinating AI-assisted development across teams ## Overview Team collaboration with Forge means everyone has their own AI-powered workflow, but tasks, decisions, and knowledge are shared. Scale Vibe Coding++™ across your entire team without losing the human orchestration that makes it work. *** ## Team Collaboration Model ```mermaid theme={null} graph TB A[Shared Project Board] --> B[Team Member 1] A --> C[Team Member 2] A --> D[Team Member 3] B --> E[Individual Tasks] C --> F[Individual Tasks] D --> G[Individual Tasks] E --> H[Shared Knowledge Base] F --> H G --> H H --> A ``` *** ## Setup: Team Instance vs Individual **Best for:** Small co-located teams (2-5 people) ```bash theme={null} # One Forge instance, shared database # Central server: forge.company.com # Team members connect to shared instance FORGE_URL=https://forge.company.com forge connect ``` **Pros:** * Single source of truth * Real-time collaboration * Shared task board **Cons:** * Requires server setup * Network dependency * Potential conflicts **Best for:** Distributed teams, async work ```bash theme={null} # Each team member runs local Forge npx automagik-forge # Sync via GitHub/GitLab issues forge config set sync.enabled true forge config set sync.provider github forge config set sync.repo org/project ``` **Pros:** * Work offline * No server needed * Personal workflows **Cons:** * Sync latency * Potential conflicts * More setup **Best for:** Large teams with sub-teams ```bash theme={null} # Shared project, individual worktrees # Team A: forge-team-a.company.com # Team B: forge-team-b.company.com # Cross-team sync forge sync configure \ --teams team-a,team-b \ --sync-frequency 1h ``` **Pros:** * Team autonomy * Cross-team visibility * Scalable **Cons:** * Complex setup * Sync overhead *** ## Workflow 1: Sprint Planning Use Forge for structured sprint planning with AI assistance. ### Step 1: Epic Breakdown ```bash theme={null} # Product manager creates epic forge task create \ --title "EPIC: User notification system" \ --type epic \ --description "Real-time notifications with WebSocket, email, push" \ --assignee team \ --labels "epic,q4-2024" # Use AI to help break down epic forge task create \ --title "Break down notification epic into stories" \ --agent claude-code \ --description "Analyze epic, suggest user stories and technical tasks" ``` **AI Output:** ```markdown theme={null} ## Suggested User Stories 1. **As a user**, I want to receive real-time notifications so I stay updated - Subtasks: WebSocket server, client connection, notification UI 2. **As a user**, I want to configure notification preferences - Subtasks: Settings UI, preferences API, email opt-out 3. **As a user**, I want notification history so I can review past alerts - Subtasks: History table, API endpoints, history UI ## Technical Tasks - Design notification database schema - Set up WebSocket server infrastructure - Create notification service - Build notification UI components - Write integration tests ``` ### Step 2: Team Estimation ```bash theme={null} # Create estimation task forge task create \ --title "Team estimation: Notification system" \ --description "Estimate all subtasks, identify dependencies" \ --assignee team \ --labels "planning" # Individual estimates via MCP # Each team member adds estimates: # "Update task NOTIF-01 estimate: 5 points, depends on NOTIF-00" ``` ### Step 3: Assignment ```bash theme={null} # Assign based on expertise forge task assign NOTIF-01 --to alice # Backend expert forge task assign NOTIF-02 --to bob # Frontend expert forge task assign NOTIF-03 --to carol # Full-stack # AI suggests assignments forge task auto-assign \ --based-on expertise,workload,velocity \ --sprint sprint-24 ``` *** ## Workflow 2: Parallel Development Multiple developers working on related features simultaneously. ### Example: Building Dashboard Feature ```bash theme={null} # Tech lead creates structure forge task create --title "Design dashboard architecture" --agent claude-code forge task create --title "Set up shared types and interfaces" --agent cursor-cli # All team members review architecture forge task review DASH-00 --reviewers alice,bob,carol ``` ```bash theme={null} # Alice: Backend API forge task create \ --title "Build dashboard API endpoints" \ --assignee alice \ --agent claude-code \ --labels "backend,api" # Bob: Frontend components forge task create \ --title "Create dashboard UI components" \ --assignee bob \ --agent cursor-cli \ --labels "frontend,ui" # Carol: Data layer forge task create \ --title "Implement dashboard data aggregation" \ --assignee carol \ --agent gemini \ --labels "backend,data" # All work in isolated worktrees, no conflicts ``` ```bash theme={null} # Integration task forge task create \ --title "Integrate dashboard components" \ --assignee team \ --depends-on DASH-01,DASH-02,DASH-03 \ --labels "integration" # Test integration forge task create \ --title "End-to-end dashboard tests" \ --assignee carol \ --agent claude-code \ --labels "testing" ``` ### Handling Dependencies ```yaml theme={null} # Task dependency tree DASH-00: Design architecture ├─ DASH-01: API endpoints (Alice) │ └─ DASH-04: API tests (Alice) │ ├─ DASH-02: UI components (Bob) │ ├─ DASH-05: Component tests (Bob) │ └─ DASH-06: Storybook stories (Bob) │ └─ DASH-03: Data aggregation (Carol) └─ DASH-07: Performance tests (Carol) DASH-08: Integration (All, after DASH-01,02,03 complete) DASH-09: E2E tests (After DASH-08) ``` ```bash theme={null} # Forge automatically tracks dependencies forge task status --show-blockers # Output: # ✅ DASH-00: Complete # 🔄 DASH-01: In progress (Alice) # 🔄 DASH-02: In progress (Bob) # ⏸️ DASH-08: Blocked by DASH-01, DASH-02, DASH-03 ``` *** ## Workflow 3: Knowledge Sharing Share learnings, patterns, and agent strategies across the team. ### Agent Performance Tracking ```bash theme={null} # Track which agents work best for each task type forge analytics agent-performance --team # Share findings forge knowledge create \ --title "Best agents for our stack" \ --content "$(cat <80% coverage - Integration tests Technical details: - Express router - Async/await - TypeScript types - Swagger annotations EOF )" # Team members use template forge task create --from-template api-endpoint \ --title "Add user profile endpoint" ``` ### Code Review Guidelines ```yaml theme={null} # .forge/team/review-guidelines.yml security: - Check OWASP Top 10 - Review authentication/authorization - Scan for secret exposure - Validate input sanitization performance: - No N+1 queries - Efficient algorithms (< O(n²) for large data) - Proper caching - Lazy loading where appropriate testing: - Minimum 80% coverage - Tests for edge cases - Integration tests for new endpoints - E2E tests for user flows documentation: - JSDoc for public APIs - README updated - CHANGELOG entry - OpenAPI specs updated ``` *** ## Workflow 4: Pair Programming with AI Combine human pair programming with AI agents. ### Traditional Pairing + AI ```mermaid theme={null} graph LR A[Driver Developer] --> B[Navigator Developer] A --> C[AI Agent Helper] B --> D[AI Agent Reviewer] C --> E[Code Implementation] D --> E E --> F[Human Review] ``` ### Example Session ```bash theme={null} # Alice (driver) and Bob (navigator) pair on auth feature # Alice creates task forge task create \ --title "Implement OAuth2 login flow" \ --assignee alice,bob \ --agent claude-code # Alice codes with AI agent help # Bob reviews in real-time # AI agent (Claude) implements based on conversation # Bob creates parallel security review task forge task create \ --title "Security review: OAuth implementation" \ --agent security-reviewer \ --depends-on AUTH-01 # At end of session, both human review and AI review complete ``` ### Mob Programming with AI **Team of 4+ developers + multiple AI agents** ```bash theme={null} # Rotate driver every 15 minutes # All developers contribute to prompt # Multiple agents work on different aspects # Agent 1: Implementation (Claude) forge task start AUTH-01 --agent claude-code # Agent 2: Test generation (Cursor) forge task create --title "Tests for AUTH-01" --agent cursor-cli # Agent 3: Documentation (Gemini) forge task create --title "Document AUTH-01" --agent gemini # Team reviews all outputs together ``` *** ## Workflow 5: Async Collaboration Distributed team across timezones. ### Handoff Protocol ```bash theme={null} # End of day: Alice (US West Coast) forge task update AUTH-01 --status in-progress \ --note "Completed login endpoint, starting logout. DB schema in schema.sql" # AI summary for next shift forge task summarize AUTH-01 --for-handoff # Output: # "Alice implemented OAuth login endpoint with JWT tokens. # Completed: Login endpoint, JWT generation, token validation # Remaining: Logout endpoint, token refresh, cleanup # Blockers: None # Next steps: Implement logout, add refresh token logic # Files changed: auth.controller.ts, auth.service.ts, schema.sql" # Morning: Bob (Europe) forge task resume AUTH-01 --read-handoff # Bob sees context and continues work ``` ### Async Code Review ```bash theme={null} # Alice pushes PR before EOD gh pr create --title "OAuth login implementation" # Automated review starts forge review create --pr 200 \ --agents claude-code,gemini \ --post-results # Morning: Bob sees review results # Bob addresses issues # Alice reviews when back online # Async but efficient - no waiting ``` *** ## Team Dashboard & Metrics Monitor team velocity and agent effectiveness. ```bash theme={null} # Team dashboard forge dashboard team --sprint current # Shows: # - Tasks completed # - Agent usage by team member # - Blockers and dependencies # - Velocity trends # - Code review metrics ``` ### Example Team Metrics | Developer | Tasks | AI Agents Used | Avg Time | Quality Score | | --------- | ----- | ---------------------------------------- | -------- | ------------- | | Alice | 12 | Claude (70%), Gemini (30%) | 2.5h | 4.8/5 | | Bob | 15 | Cursor (80%), Claude (20%) | 1.8h | 4.6/5 | | Carol | 10 | Claude (50%), Gemini (40%), Cursor (10%) | 3.2h | 4.9/5 | **Insights:** * Bob is fastest (uses Cursor for frontend work) * Carol has highest quality (uses multiple agents for comparison) * Alice focuses on complex backend (Claude Code) *** ## Communication Patterns ### Daily Standup ```bash theme={null} # Generate standup update forge standup generate --developer alice --since yesterday # Output: # Alice - Yesterday: # ✅ Completed AUTH-01: OAuth login endpoint (2 attempts, Claude Code) # ✅ Reviewed PR #199 from Bob # 🔄 In Progress AUTH-02: Logout endpoint # # Today: # - Complete AUTH-02 # - Start AUTH-03: Token refresh # - Review Carol's PR #200 # # Blockers: None ``` ### Sprint Retrospective ```bash theme={null} # Generate retro insights forge retrospective --sprint 24 # AI-generated insights: # # ✅ What went well: # - 95% of tasks completed on time # - No production bugs from sprint # - Effective use of Claude for complex backend tasks # # ⚠️ What could improve: # - 3 tasks blocked by unclear requirements # - 2 merge conflicts (better coordination needed) # - Some agents underutilized (GPT-4 Codex only 5%) # # 💡 Action items: # - Define clearer acceptance criteria upfront # - Daily sync on overlapping work # - Experiment with GPT-4 Codex for specific tasks ``` *** ## Handling Conflicts ### Code Conflicts ```bash theme={null} # Forge's worktree isolation minimizes conflicts # But when merging to main: # Detect potential conflicts before merge forge task check-conflicts AUTH-01 # If conflicts detected forge task resolve-conflicts AUTH-01 \ --strategy ours|theirs|manual \ --agent claude-code # AI helps resolve # AI suggests resolution forge task suggest-resolution AUTH-01 ``` ### Task Conflicts (Multiple people on same task) ```bash theme={null} # Lock task when starting work forge task lock AUTH-01 --developer alice # If Bob tries to work on it: # ⚠️ Task AUTH-01 is locked by alice (started 2h ago) # Suggest: Coordinate with alice or pick different task # Unlock when done forge task unlock AUTH-01 ``` *** ## Best Practices ```yaml theme={null} # .forge/team/conventions.yml naming: tasks: "JIRA-123: Brief description" branches: "feature/JIRA-123-description" commits: "feat(module): description [JIRA-123]" agents: backend: claude-code (default) frontend: cursor-cli (default) security: security-reviewer (required for auth) performance: gemini (for optimization) review: required: 2 humans + 1 AI blocking_severity: critical, high auto_merge: false ``` ```bash theme={null} # Daily: Quick sync forge sync --type daily --duration 15min # Weekly: In-depth coordination forge sync --type weekly --review-blockers # Sprint: Planning and retro forge sync --type sprint --generate-reports ``` ```bash theme={null} # Document learnings forge knowledge add \ --title "How to fix N+1 queries in our ORM" \ --tags "performance,database,howto" # Share successful agent prompts forge template share "api-with-validation" \ --visibility team ``` ```bash theme={null} # Track and celebrate forge achievements --team --sprint 24 # 🏆 Sprint 24 Achievements: # - Alice: First time using multi-agent review (10 issues caught!) # - Bob: Fastest task completion (1.2h average) # - Carol: Highest quality score (4.9/5) # - Team: Zero production bugs 🎉 ``` *** ## Scaling to Larger Teams ### Department Level (20-50 developers) ```bash theme={null} # Multiple Forge instances per team # Cross-team board for dependencies forge config set org.structure "$(cat < Automate team workflows in CI/CD Create team-specific agents Team performance and insights Enterprise security features *** **Remember**: Vibe Coding++™ scales when teams maintain human orchestration. AI agents amplify each individual's productivity, but humans coordinate, decide, and own the architecture and outcomes. # Comparing Results Source: https://docs.namastex.ai/forge/working/comparing-results Compare outputs from different AI agents ## Overview One of Forge's most powerful features: **compare results from multiple AI agents** side-by-side. See which approach works best, cherry-pick the best parts, or combine solutions. *** ## Why Compare? Different AI agents have different strengths: | Agent | Strength | Weakness | | ----------------- | --------------------------- | ------------------------ | | **Claude Sonnet** | Complex logic, architecture | Can be verbose | | **Gemini Flash** | Fast, concise | May miss edge cases | | **Cursor** | UI/UX intuition | Less depth on algorithms | | **GPT-4** | Comprehensive | Expensive | **Solution**: Try multiple, compare results, choose the best! *** ## Quick Comparison ### Via CLI ```bash theme={null} # Compare all attempts for a task forge task compare 1 # Compare specific attempts forge diff task-1-claude task-1-gemini # Show only statistics forge task compare 1 --stats ``` ### Via Web UI Click on task card in Kanban board Click **Attempts** tab to see all attempts Check boxes next to 2+ attempts Opens split-view comparison interface *** ## Comparison Views ### File-by-File Diff ```bash theme={null} forge diff task-1-claude task-1-gemini --files ``` **Output**: ``` src/auth/login.ts Claude: 145 lines (+132, -13) Gemini: 98 lines (+89, -9) src/auth/signup.ts Claude: 178 lines (+165, -13) Gemini: 142 lines (+135, -7) src/utils/jwt.ts Claude: 67 lines (+67, new file) Gemini: 45 lines (+45, new file) ``` ### Side-by-Side Code Comparison ```bash theme={null} forge diff task-1-claude task-1-gemini \ --file src/auth/login.ts \ --side-by-side ``` **Output**: ```diff theme={null} Claude │ Gemini ────────────────────────────────────────┼─────────────────────────────────────── import bcrypt from 'bcryptjs'; │ import bcrypt from 'bcrypt'; import jwt from 'jsonwebtoken'; │ import jwt from 'jsonwebtoken'; import { validateEmail } from './util';│ │ export async function login(req, res) {│ export const login = async (req, res) => { const { email, password } = req.body;│ const { email, password } = req.body; │ if (!validateEmail(email)) { │ // Find user return res.status(400).json({ │ const user = await User.findOne({ email }); error: 'Invalid email format' │ }); │ } │ │ const user = await User.findOne(... │ if (!user || !await bcrypt.compare(... ``` ### Statistics Comparison ```bash theme={null} forge task compare 1 --stats ``` **Output**: ``` ╭───────────┬─────────┬─────────┬─────────╮ │ Metric │ Claude │ Gemini │ Cursor │ ├───────────┼─────────┼─────────┼─────────┤ │ Duration │ 5m 22s │ 2m 15s │ 4m 01s │ │ Files │ 8 │ 6 │ 7 │ │ Lines + │ 364 │ 269 │ 312 │ │ Lines - │ 33 │ 16 │ 28 │ │ Tests │ ✅ 24 │ ⚠️ 18 │ ✅ 22 │ │ Cost │ $0.234 │ $0.089 │ $0.187 │ ╰───────────┴─────────┴─────────┴─────────╯ ``` *** ## Detailed Comparison ### Test Results ```bash theme={null} forge task compare 1 --tests ``` **Output**: ``` Test Coverage Comparison: Claude (95% coverage): ✅ Login with valid credentials ✅ Login with invalid email ✅ Login with wrong password ✅ Login with missing fields ✅ JWT token generation ✅ Token expiry handling ⚠️ Missing: Rate limiting tests Gemini (78% coverage): ✅ Login with valid credentials ✅ Login with wrong password ⚠️ Missing: Email validation tests ⚠️ Missing: Edge case handling ⚠️ Missing: Token expiry tests Winner: Claude (more comprehensive) ``` ### Code Quality Metrics ```bash theme={null} forge task compare 1 --quality ``` **Output**: ``` Code Quality Analysis: Claude: Complexity: Medium (Cyclomatic: 8) Maintainability: A TypeScript coverage: 100% Comments: Comprehensive Error handling: Excellent Gemini: Complexity: Low (Cyclomatic: 4) Maintainability: A+ TypeScript coverage: 100% Comments: Minimal Error handling: Basic Winner: Tie (trade-off: Claude more robust, Gemini cleaner) ``` ### Performance Analysis ```bash theme={null} forge task compare 1 --benchmark ``` **Output**: ``` Performance Benchmarks: Login Endpoint (1000 requests): Claude: avg 45ms, p95 78ms, p99 125ms Gemini: avg 38ms, p95 65ms, p99 98ms Cursor: avg 42ms, p95 72ms, p99 110ms Winner: Gemini (fastest) Memory Usage: Claude: ~120MB Gemini: ~95MB Cursor: ~108MB Winner: Gemini (most efficient) ``` *** ## Visual Comparison (Web UI) The Forge UI provides rich visual comparisons: ### Split-Screen Editor * Left pane: Attempt 1 code * Right pane: Attempt 2 code * Synchronized scrolling * Inline diff highlighting ### Architecture Diagram Auto-generated comparison: ``` Claude's Approach: Gemini's Approach: ┌────────────────┐ ┌────────────────┐ │ Controller │ │ Handler │ └───────┬────────┘ └───────┬────────┘ │ │ ▼ ▼ ┌────────────────┐ ┌────────────────┐ │ Validator │ │ User Service │ └───────┬────────┘ └───────┬────────┘ │ │ ▼ ▼ ┌────────────────┐ ┌────────────────┐ │ Service │ │ Database │ └───────┬────────┘ └────────────────┘ │ ▼ ┌────────────────┐ │ Repository │ └────────────────┘ Claude: More layers, separation Gemini: Simpler, direct ``` *** ## Decision Matrix Build a decision matrix to choose systematically: ```bash theme={null} forge task compare 1 --matrix ``` **Output**: ``` ╭────────────────┬─────────┬─────────┬─────────╮ │ Criteria │ Claude │ Gemini │ Cursor │ ├────────────────┼─────────┼─────────┼─────────┤ │ Correctness │ ⭐⭐⭐⭐⭐ │ ⭐⭐⭐⭐ │ ⭐⭐⭐⭐ │ │ Performance │ ⭐⭐⭐⭐ │ ⭐⭐⭐⭐⭐ │ ⭐⭐⭐⭐ │ │ Maintainability│ ⭐⭐⭐⭐ │ ⭐⭐⭐⭐⭐ │ ⭐⭐⭐⭐ │ │ Test Coverage │ ⭐⭐⭐⭐⭐ │ ⭐⭐⭐ │ ⭐⭐⭐⭐ │ │ Documentation │ ⭐⭐⭐⭐⭐ │ ⭐⭐ │ ⭐⭐⭐ │ │ Cost │ ⭐⭐⭐ │ ⭐⭐⭐⭐⭐ │ ⭐⭐⭐⭐ │ ├────────────────┼─────────┼─────────┼─────────┤ │ Total Score │ 24/30 │ 23/30 │ 22/30 │ ╰────────────────┴─────────┴─────────┴─────────╯ Recommendation: Claude (best overall balance) ``` *** ## Cherry-Picking Best Parts Sometimes you want to combine approaches: ### Manual Cherry-Pick ```bash theme={null} # Start with Claude's attempt git checkout task-1-claude # Cherry-pick specific file from Gemini git checkout task-1-gemini -- src/utils/jwt.ts # Cherry-pick specific changes git show task-1-gemini:src/auth/login.ts | patch -p1 ``` ### Via Web UI 1. Open comparison view 2. Select blocks of code from different attempts 3. Click **"Create Combined Attempt"** 4. Forge creates new attempt merging selected parts *** ## Common Comparison Scenarios ### Feature Implementation **Question**: Which agent implemented the feature most completely? ```bash theme={null} # Check if all requirements met forge task compare 1 --requirements-checklist # Output: # Claude: ✅ All 8 requirements met # Gemini: ⚠️ 6/8 requirements met (missing: rate limiting, password reset) # Cursor: ⚠️ 7/8 requirements met (missing: email verification) ``` ### Bug Fix **Question**: Which fix actually solves the bug without breaking anything? ```bash theme={null} # Run tests for each attempt forge task compare 1 --run-tests # Output: # Claude: ✅ All tests pass (24/24) # Gemini: ⚠️ 2 tests fail (22/24) # Cursor: ✅ All tests pass (24/24) # Check if bug is fixed forge task compare 1 --validate-fix # Output: # Claude: ✅ Bug fixed, no regressions # Cursor: ✅ Bug fixed, no regressions # Gemini: ❌ Bug still present in edge case ``` ### Refactoring **Question**: Which refactor improves code without changing behavior? ```bash theme={null} # Verify behavior unchanged forge task compare 1 --behavior-test # Output: # Claude: ✅ All E2E tests pass # Gemini: ✅ All E2E tests pass # Cursor: ⚠️ 1 E2E test fails (regression) # Check code quality improvement forge task compare 1 --complexity # Output: # Original: Cyclomatic complexity 15 # Claude: Cyclomatic complexity 8 (-47%) # Gemini: Cyclomatic complexity 6 (-60%) ← Winner! # Cursor: Cyclomatic complexity 9 (-40%) ``` *** ## Export Comparison Reports ### Generate Report ```bash theme={null} # Full comparison report forge task compare 1 --report --output comparison-report.md # HTML report with charts forge task compare 1 --report --format html --output report.html # JSON for programmatic use forge task compare 1 --report --format json --output report.json ``` ### Share with Team ```bash theme={null} # Upload to GitHub Gist forge task compare 1 --share --gist # Output: # https://gist.github.com/user/abc123 # Or create PR description forge task compare 1 --pr-description > pr-description.md ``` *** ## Best Practices Don't just read code - run tests: ```bash theme={null} forge task test-all 1 ``` Code that looks good but fails tests is useless Specifically test edge cases: ```bash theme={null} # Test with invalid inputs # Test with empty data # Test error handling ``` Simple cases are easy; edges matter **Today**: All work **Six months from now**: Which will you understand? Prefer clear code over clever code ```bash theme={null} forge task annotate 1 \ --chosen claude \ --reason "Better test coverage and clearer error handling" ``` Future you will thank you *** ## Advanced: A/B Testing in Production For critical features, deploy multiple attempts for A/B testing: ```typescript theme={null} // Feature flag routing const implementation = featureFlags.get('auth-impl'); if (implementation === 'claude') { return claudeAuth(req, res); } else if (implementation === 'gemini') { return geminiAuth(req, res); } ``` Monitor metrics: * Response times * Error rates * User feedback Choose winner based on real-world data! *** ## Troubleshooting **Issue**: Comparing large attempts is slow **Solutions**: * Use `--files-only` to skip detailed diffs * Compare specific files: `--file src/auth/login.ts` * Increase timeout: `--timeout 300` **Issue**: Attempts look identical **Solutions**: * Check if comparing same attempt twice * Use `--ignore-whitespace` to see real changes * Try `--context 10` for more surrounding lines **Issue**: Can't run tests in worktrees **Solutions**: * Ensure dependencies installed in each worktree * Check test paths are correct * Use `--setup-cmd "npm install"` first *** ## Next Steps Merge your chosen attempt to main Learn more about working with attempts Create agents optimized for different tasks Run multiple attempts simultaneously # Creating Tasks Source: https://docs.namastex.ai/forge/working/creating-tasks Learn how to create and configure tasks in Forge ## Overview Tasks are the core unit of work in Forge. Each task represents a specific piece of work to be executed by AI coding agents in isolated environments. *** ## Creating Your First Task ### Via Web UI ```bash theme={null} forge start # Opens http://localhost:3000 ``` Click the **+ New Task** button in the Kanban board * **Title**: Clear, concise description * **Description**: Detailed requirements and context * **LLM**: Choose your AI agent (Claude, Gemini, etc.) * **Labels**: Add tags for organization Click **Create** - your task appears in the "To Do" column ### Via CLI ```bash theme={null} # Basic task creation forge task create \ --title "Add user authentication" \ --description "Implement JWT-based auth with login and signup" \ --llm claude # With additional options forge task create \ --title "Refactor API client" \ --description "Convert fetch calls to axios" \ --llm gemini \ --priority high \ --labels "refactor,backend" \ --assignee "claude" ``` ### Via MCP (from your coding agent) ``` You: "Create a task to add dark mode toggle with LocalStorage persistence" Claude Code: I'll create that task for you... [Uses MCP create_task tool] Task created: #42 "Add dark mode toggle" ``` *** ## Task Properties ### Required Fields Clear, action-oriented title **Good**: "Add JWT authentication endpoints" **Bad**: "Auth stuff" ```bash theme={null} forge task create --title "Add JWT authentication endpoints" ``` Detailed requirements, context, and acceptance criteria ```bash theme={null} forge task create \ --title "Add authentication" \ --description " Implement JWT-based authentication with: - POST /auth/login endpoint - POST /auth/signup endpoint - JWT token generation with 24h expiry - Password hashing with bcrypt - Input validation - Error handling " ``` ### Optional Fields AI coding agent to use Options: `claude`, `gemini`, `cursor`, `openai`, `opencode`, `qwen` ```bash theme={null} forge task create --title "Quick fix" --llm gemini ``` Task priority: `low`, `medium`, `high`, `critical` ```bash theme={null} forge task create --title "Security patch" --priority critical ``` Tags for organization and filtering ```bash theme={null} forge task create \ --title "Add tests" \ --labels "testing,backend,priority:high" ``` Specific agent profile or team member ```bash theme={null} forge task create --title "Security audit" --assignee "security-expert" ``` *** ## Task Types & Templates ### Feature Development ```bash theme={null} forge task create \ --title "Add export to CSV functionality" \ --type feature \ --description " Create CSV export feature: - Add download button to UI - Implement CSV generation logic - Handle large datasets (stream) - Add progress indicator - Include proper filename with timestamp " \ --labels "feature,ui,backend" ``` ### Bug Fix ```bash theme={null} forge task create \ --title "Fix memory leak in WebSocket connection" \ --type bugfix \ --priority high \ --description " Steps to reproduce: 1. Connect to WebSocket 2. Leave page open for 1 hour 3. Memory usage grows continuously Expected: Stable memory usage Actual: Memory grows by ~50MB/hour Stack trace: [attach if available] " \ --labels "bug,websocket,critical" ``` ### Refactoring ```bash theme={null} forge task create \ --title "Extract API client to separate module" \ --type refactor \ --description " Current state: API calls scattered across components Goal: Centralized API client with: - Axios instance with interceptors - Error handling middleware - Retry logic for failed requests - TypeScript types for all endpoints " \ --labels "refactor,architecture" ``` ### Documentation ```bash theme={null} forge task create \ --title "Document authentication flow" \ --type docs \ --description " Create comprehensive docs for: - How JWT tokens are generated - Token refresh flow - Password reset process - OAuth integration Include sequence diagrams " \ --labels "docs,auth" ``` ### Testing ```bash theme={null} forge task create \ --title "Add integration tests for payment flow" \ --type testing \ --description " Test scenarios: - Successful payment - Failed payment (card declined) - Network timeout during payment - Webhook handling - Refund flow Use Jest + Supertest Aim for 90%+ coverage " \ --labels "testing,payment" ``` *** ## Writing Effective Task Descriptions ### Bad Description ❌ ``` Add user stuff to the dashboard ``` ### Good Description ✅ ```markdown theme={null} ## Goal Add user management section to admin dashboard ## Requirements - Display paginated user list (20 per page) - Show: name, email, registration date, status - Add filters: status (active/inactive), role - Implement search by name or email - Add "Edit User" modal with: - Change role (user/admin) - Toggle active status - Reset password option ## Technical Notes - Use existing UserService API - Match design system components - Add loading states and error handling - Include unit tests for filtering logic ## Acceptance Criteria - [ ] User list loads and paginates correctly - [ ] Filters work as expected - [ ] Search returns accurate results - [ ] Edit modal saves changes successfully - [ ] All edge cases handled (empty state, API errors) ``` ### Tips for Great Descriptions **Bad**: "Make it faster" **Good**: "Reduce API response time from 2s to under 500ms by adding Redis caching" Why is this needed? What problem does it solve? "Users complain about slow dashboard load times. Profiling shows 80% time spent in database queries." Add acceptance criteria: * [ ] Dashboard loads in under 1 second * [ ] Cache hit rate over 70% * [ ] Tests pass Include: * Design mockups * API documentation * Similar implementations * Stack traces (for bugs) *** ## Task Organization ### Using Labels ```bash theme={null} # Category labels --labels "feature,bug,docs,refactor,testing" # Priority labels --labels "priority:high,priority:low" # Component labels --labels "frontend,backend,database,auth" # Status labels --labels "blocked,in-review,needs-testing" # Team labels --labels "team:mobile,team:api" # Combine multiple --labels "feature,backend,priority:high,team:api" ``` ### Filtering Tasks ```bash theme={null} # By label forge task list --labels "feature" forge task list --labels "priority:high" # By status forge task list --status pending forge task list --status in_progress # By assignee forge task list --assignee claude # Combine filters forge task list --labels "bug" --priority high --status pending ``` *** ## Attaching Context ### Code Snippets ```bash theme={null} forge task create \ --title "Optimize database query" \ --description " Current slow query: \`\`\`sql SELECT * FROM users WHERE created_at > NOW() - INTERVAL 30 DAY \`\`\` Takes 5 seconds on 1M users. Add index on created_at. " ``` ### Screenshots (Web UI) 1. Click **Attach Files** in task creation modal 2. Upload screenshots, diagrams, or mockups 3. Reference in description: "See attached mockup.png" ### Links ```markdown theme={null} ## References - Design: https://figma.com/file/xyz - API Docs: https://docs.example.com/api - Similar feature: https://github.com/user/repo/pull/123 ``` *** ## Advanced: Task Dependencies ```bash theme={null} # Create parent task forge task create \ --title "Build payment system" \ --id parent-task # Create dependent tasks forge task create \ --title "Stripe integration" \ --depends-on parent-task forge task create \ --title "Payment UI components" \ --depends-on parent-task forge task create \ --title "Webhook handling" \ --depends-on parent-task ``` Tasks with dependencies are blocked until parent completes. *** ## Batch Task Creation ### From File Create `tasks.yaml`: ```yaml theme={null} tasks: - title: "Setup database schema" description: "Create tables for users, posts, comments" priority: high labels: ["database", "setup"] - title: "Create API endpoints" description: "CRUD operations for posts" labels: ["backend", "api"] - title: "Build frontend components" description: "Post list, create post form" labels: ["frontend", "ui"] ``` Import: ```bash theme={null} forge task import tasks.yaml ``` ### Programmatic Creation ```typescript theme={null} import { ForgeClient } from 'automagik-forge-sdk'; const forge = new ForgeClient(); const tasks = [ { title: "Task 1", description: "..." }, { title: "Task 2", description: "..." }, { title: "Task 3", description: "..." }, ]; for (const task of tasks) { await forge.createTask(task); } ``` *** ## Best Practices **Bad**: "Build entire e-commerce platform" **Good**: "Add product listing page" Smaller tasks = better AI results **Bad**: "Add auth and refactor database" **Good**: Two separate tasks Focus improves quality Define done: * [ ] Feature works as described * [ ] Tests pass * [ ] Documentation updated Show, don't just tell: ```javascript theme={null} // Expected usage: const token = await auth.generateToken(user); ``` *** ## Troubleshooting **Error**: "Failed to create task" **Solutions**: * Check project is selected * Verify database is accessible * Ensure title is not empty * Check LLM is configured **Issue**: Task created but not visible **Solutions**: * Refresh the Kanban board * Check filters aren't hiding it * Use search: `forge task list --search "your title"` **Issue**: Same task created multiple times **Solutions**: * Check for button double-clicks * Use unique IDs if programmatic * Search before creating: `forge task list --search "similar"` *** ## Next Steps Run tasks with different AI agents Compare outputs from multiple agents Reusable patterns for common workflows Complete CLI command reference # Kanban Interface Source: https://docs.namastex.ai/forge/working/kanban-interface Master the Forge visual task board ## Overview Forge's Kanban board is your command center for AI-assisted development. Unlike lost chat histories, your tasks live here permanently - organized, trackable, and always accessible. *** ## Accessing the Interface ```bash theme={null} # Start Forge forge start # Opens automatically at: # http://localhost:3000 ``` **First time?** You'll need to sign in with GitHub to access your projects. *** ## Board Layout ``` ┌─────────────────────────────────────────────────────────┐ │ Forge - Project: My App [@username] │ ├─────────────────────────────────────────────────────────┤ │ [+ New Task] [Filters ▼] [Sort ▼] [View ▼] │ ├──────────┬──────────┬──────────┬──────────┬────────────┤ │ To Do │ In Prog │ Review │ Done │ Archived │ │ (5) │ (3) │ (2) │ (12) │ (45) │ ├──────────┼──────────┼──────────┼──────────┼────────────┤ │ ┌──────┐ │ ┌──────┐ │ ┌──────┐ │ ┌──────┐ │ ┌──────┐ │ │ │Task 1│ │ │Task 4│ │ │Task 7│ │ │Task 9│ │ │Task..│ │ │ └──────┘ │ └──────┘ │ └──────┘ │ └──────┘ │ └──────┘ │ │ │ │ │ │ │ │ ┌──────┐ │ ┌──────┐ │ ┌──────┐ │ │ │ │ │Task 2│ │ │Task 5│ │ │Task 8│ │ │ │ │ └──────┘ │ └──────┘ │ └──────┘ │ │ │ └──────────┴──────────┴──────────┴──────────┴────────────┘ ``` *** ## Columns Explained ### To Do **New tasks waiting to be started** * Tasks you just created * Tasks planned but not started * Backlog items **Actions**: * Start task (moves to In Progress) * Edit task details * Delete task * Move to other columns ### In Progress **Tasks currently being executed by AI** * Active attempts running * Tasks being worked on * Shows real-time progress **Visual Indicators**: * 🟢 Agent working * 📝 Files being edited * ⏱️ Time elapsed * 💰 Cost so far ### Review **Completed attempts awaiting your approval** * Attempts finished successfully * Ready for code review * Waiting for merge decision **Actions**: * View changes * Compare attempts * Approve and merge * Request changes * Reject ### Done **Completed and merged tasks** * Successfully merged to main * Shipped features * Fixed bugs * Completed work **Info Shown**: * Merge commit SHA * Completion date * Agent used * Final cost ### Archived **Old completed tasks** * Automatically archived after 30 days * Can be restored if needed * Keeps board clean *** ## Task Cards Each task card shows: ``` ┌─────────────────────────────────────┐ │ #42 🔒 Add user authentication │ ← Title + Lock icon (if blocked) │ by @username 2 hours ago │ ← Creator + Time │ │ │ "Implement JWT-based auth with..." │ ← Description preview │ │ │ 🤖 3 attempts │ ← Number of attempts │ ✅ 2 completed 🔄 1 running │ ← Status breakdown │ │ │ [feature] [backend] [priority:high] │ ← Labels │ │ │ 💰 $0.45 ⏱️ 12m 30s │ ← Cost + Duration └─────────────────────────────────────┘ ``` ### Card Colors Cards are color-coded by priority: * 🔴 **Critical**: Red border * 🟠 **High**: Orange border * 🟡 **Medium**: Yellow border (default) * 🟢 **Low**: Green border *** ## Drag & Drop ### Moving Tasks Between Columns Click on a task card and hold Drag the card to the target column Release to drop the card Task status updates automatically **Keyboard shortcut**: Select task, press `→` to move right, `←` to move left ### Reordering Within Columns Drag cards up/down within a column to prioritize: * Top = highest priority * Bottom = lowest priority *** ## Task Details View Click any task card to open the detail panel: ### Overview Tab ``` Task #42: Add user authentication Created by @username 3 hours ago Status: In Progress Description: ───────────────────────────────────── Implement JWT-based authentication: - Login endpoint with email/password - Signup endpoint with validation - JWT token generation (24h expiry) - Password hashing with bcrypt ... Labels: [feature] [backend] [priority:high] Assignee: claude-sonnet ``` ### Attempts Tab ``` ╭──────┬──────────┬──────────┬──────────╮ │ # │ Agent │ Status │ Duration │ ├──────┼──────────┼──────────┼──────────┤ │ 1 │ Claude │ ✅ Done │ 5m 22s │ │ 2 │ Gemini │ 🔄 Run │ 2m 15s │ │ 3 │ Cursor │ ❌ Fail │ 4m 01s │ ╰──────┴──────────┴──────────┴──────────╯ [View Logs] [Compare] [Start New Attempt] ``` ### Changes Tab View file changes for each attempt: ``` src/auth/login.ts +132 -13 src/auth/signup.ts +165 -13 src/utils/jwt.ts +67 (new) test/auth.test.ts +89 (new) [View Diff] [Download] [Apply to Main] ``` ### Activity Tab Timeline of all events: ``` 🟢 3 hours ago @username created task 🤖 2 hours ago Started attempt #1 with Claude ✅ 2 hours ago Attempt #1 completed successfully 🤖 1 hour ago Started attempt #2 with Gemini 💬 30 minutes ago @reviewer added comment: "Check error handling" 🔄 15 minutes ago Started attempt #3 with Cursor ``` *** ## Filters & Search ### Quick Filters ``` [All] [My Tasks] [High Priority] [In Progress] ``` Click to instantly filter the board. ### Advanced Filters Click **Filters ▼** to open: ``` ╭───────────────────────────────────╮ │ Filter Tasks │ ├───────────────────────────────────┤ │ Status: [All ▼] │ │ Priority: [All ▼] │ │ Assignee: [All ▼] │ │ Labels: [Select... ▼] │ │ Date: [Last 7 days ▼] │ │ │ │ [Clear] [Apply] │ ╰───────────────────────────────────╯ ``` ### Search ``` ┌─────────────────────────────────┐ │ 🔍 Search tasks... │ └─────────────────────────────────┘ ``` Search by: * Task title or description * Task ID (#42) * Labels (feature, bug, etc.) * Agent name (claude, gemini) *** ## Sorting Options Click **Sort ▼**: * **Priority** (High → Low) * **Created** (Newest → Oldest) * **Updated** (Recently modified first) * **Alphabetical** (A → Z) * **Cost** (Most expensive first) * **Duration** (Longest first) * **Custom** (Manual drag-drop order) *** ## View Modes ### Kanban View (Default) Classic column-based board - best for workflow visualization ### List View ``` ╭────┬─────────────────────┬──────────┬──────────┬──────╮ │ ID │ Title │ Status │ Assignee │ Cost │ ├────┼─────────────────────┼──────────┼──────────┼──────┤ │ 42 │ Add authentication │ Progress │ Claude │ $0.45│ │ 41 │ Fix memory leak │ Review │ Gemini │ $0.12│ │ 40 │ Refactor API │ Done │ Cursor │ $0.89│ ╰────┴─────────────────────┴──────────┴──────────┴──────╯ ``` Best for: Scanning many tasks quickly ### Timeline View ``` Jan 15 ●─────────● Jan 20 ●──────────● Jan 25 │ │ │ │ Task 42 Task 41 Task 40 Today Started Completed Merged ``` Best for: Understanding project timeline ### Calendar View ``` January 2024 Su Mo Tu We Th Fr Sa 1 2 3 4 5 6 7 8 [9] 10 11 12 13 [9] = 3 tasks 14 15 16 17 18 19 20 ``` Best for: Planning and scheduling *** ## Bulk Operations Select multiple tasks: 1. Click checkbox on first card 2. Shift+Click on last card 3. All cards between are selected **Available actions**: * Move to column * Add label * Change priority * Archive * Delete ``` ✓ 5 tasks selected [Move to ▼] [Add Label ▼] [Priority ▼] [Archive] [Delete] ``` *** ## Keyboard Shortcuts | Shortcut | Action | | -------------- | -------------------- | | `n` | New task | | `f` | Focus search | | `j` / `k` | Navigate down/up | | `←` / `→` | Move task left/right | | `Enter` | Open task details | | `Esc` | Close modal | | `Cmd/Ctrl + S` | Save changes | | `Cmd/Ctrl + K` | Command palette | | `?` | Show all shortcuts | *** ## Customization ### Column Configuration Add/remove/rename columns: ``` Settings → Columns Default columns: To Do, In Progress, Review, Done, Archived Custom columns: - Blocked - Testing - Staging - Deployed ``` ### Card Display Choose what to show on cards: ``` Settings → Card Display ☑ Show labels ☑ Show cost ☑ Show duration ☑ Show assignee ☑ Show attempt count ☐ Show description preview ``` ### Theme ``` Settings → Appearance ○ Light mode ● Dark mode ○ Auto (match system) Accent color: [Purple ▼] ``` *** ## Notifications Bell icon (🔔) shows: * Task completed * Attempt failed * Review requested * Comment added * Task assigned to you Configure in **Settings → Notifications**: ``` ☑ Desktop notifications ☑ Email notifications ☐ Slack notifications ☐ Discord notifications ``` *** ## Mobile View Forge UI is responsive: * **Mobile**: Single column, swipe gestures * **Tablet**: 2-3 columns, touch optimized * **Desktop**: Full Kanban board Use the mobile app for quick status checks and approvals while away from desk! *** ## Collaboration Features ### Comments Add comments to tasks: ``` 💬 @reviewer 5 minutes ago Have you considered edge case where... 💬 @username 2 minutes ago Good catch! I'll add that to attempt #3. ``` ### Mentions Use `@username` to notify team members: ``` @john Can you review the security aspects? @sarah FYI, this affects the mobile app ``` ### Assignments Assign tasks to team members: ``` Assignee: @john Due date: Jan 20, 2024 Labels: [needs-review] ``` *** ## Best Practices Don't let backlog grow too large: * Regularly archive old tasks * Move unlikely tasks to "Ideas" project * Aim for under 20 active To Do items Create label standards: * `feature`, `bug`, `docs`, `refactor` * `priority:high`, `priority:low` * `frontend`, `backend`, `database` Helps with filtering and reporting Don't let Review column fill up: * Check daily * Approve or request changes quickly * Merge when ready Stale reviews = blocked pipeline After 30 days, archive Done tasks: * Keeps board focused on active work * Historical data still accessible * Improves performance *** ## Troubleshooting **Solutions**: * Refresh page (Cmd/Ctrl + R) * Check network connection * Verify Forge backend is running * Clear browser cache **Solutions**: * Ensure JavaScript enabled * Try different browser * Disable browser extensions * Check for conflicting keyboard shortcuts **Solutions**: * Check WebSocket connection (dev tools) * Refresh page manually * Verify firewall allows WebSocket **Solutions**: * Verify project is selected * Check you have write permissions * Ensure not at task limit (if any) * Try via CLI as workaround *** ## Next Steps Master task creation Work with AI agent attempts End-to-end workflow examples Command-line alternative to UI # Managing Attempts Source: https://docs.namastex.ai/forge/working/managing-attempts Work with multiple task attempts and AI agents ## Overview Each Forge task can have **multiple attempts** - different executions with different AI agents, prompts, or approaches. This is Forge's superpower: experiment until you find what works! *** ## What Are Attempts? An **attempt** is a single execution of a task by an AI coding agent in an isolated Git worktree. ``` Task: "Add user authentication" ├── Attempt 1: Claude Sonnet → Too complex ├── Attempt 2: Gemini Flash → Missing edge cases ├── Attempt 3: Claude Haiku → Perfect! ✅ └── Result: You choose Attempt 3 to merge ``` Each attempt runs in complete isolation - no conflicts, no mess! *** ## Creating Attempts ### First Attempt (via UI) Create a task in Forge with title and description Click the task card → **Start Task** button Select your AI coding agent (Claude, Gemini, etc.) Watch real-time logs as the agent works ### Additional Attempts (via CLI) ```bash theme={null} # Try the same task with a different agent forge task fork 1 --llm gemini # Try with a specialized agent profile forge task fork 1 --llm claude --agent "test-writer" # Try with different context forge task fork 1 --llm cursor --description "Focus on performance" ``` ### Via MCP ``` You: "Try that authentication task again but with Gemini this time" Claude Code: I'll create a new attempt with Gemini... [Uses MCP to fork task] Attempt #2 started with Gemini ``` *** ## Attempt Lifecycle ```mermaid theme={null} graph LR A[Created] --> B[Running] B --> C{Success?} C -->|Yes| D[Completed] C -->|No| E[Failed] D --> F[Under Review] F --> G{Approved?} G -->|Yes| H[Merged] G -->|No| I[Rejected] E --> J[Retry] J --> B ``` ### Status Explained | Status | Meaning | Actions Available | | ---------------- | --------------------------- | ------------------------ | | **Created** | Attempt queued, not started | Start, Delete | | **Running** | Agent is working | Monitor, Cancel | | **Completed** | Finished successfully | Review, Merge, Fork | | **Failed** | Execution failed | Retry, View Logs | | **Under Review** | Awaiting your approval | Approve, Reject, Compare | | **Merged** | Changes merged to main | View, Rollback | | **Rejected** | You decided not to use it | Delete, Retry | *** ## Running Attempts ### Sequential Execution ```bash theme={null} # Run one at a time forge task start 1 --llm claude # Wait for completion... forge task start 1 --llm gemini # Wait for completion... ``` ### Parallel Execution ```bash theme={null} # Run multiple attempts simultaneously! forge task start 1 --llm claude & forge task start 1 --llm gemini & forge task start 1 --llm cursor & # All three run in isolated worktrees wait ``` **Parallel execution** is perfect for comparing approaches quickly! *** ## Monitoring Attempts ### View Attempt Status ```bash theme={null} # List all attempts for a task forge task attempts 1 # Output: # Attempt #1 (claude) [Completed] 5 minutes ago # Attempt #2 (gemini) [Running] Started 30s ago # Attempt #3 (cursor) [Failed] 2 minutes ago ``` ### Real-Time Logs ```bash theme={null} # Follow logs as agent works forge task logs 1 --follow # View specific attempt forge task logs 1 --attempt 2 --follow ``` ### Web UI Monitoring The Forge UI shows live progress: * Current file being edited * Lines added/removed * Test results (if running) * Agent's thinking process *** ## Comparing Attempts See [Comparing Results](/forge/working/comparing-results) for detailed guide. Quick comparison: ```bash theme={null} # Compare two attempts forge diff 1-claude 1-gemini # Compare all attempts forge task compare 1 # See just the stats forge task compare 1 --stats-only ``` *** ## Specialized Agent Profiles Use the same task with different "personas": ### Test Writer ```bash theme={null} forge task fork 1 \ --llm claude \ --agent "test-writer" \ --description "Focus on comprehensive test coverage" ``` ### Security Expert ```bash theme={null} forge task fork 1 \ --llm gemini \ --agent "security-expert" \ --description "Add input validation and sanitization" ``` ### Performance Optimizer ```bash theme={null} forge task fork 1 \ --llm cursor \ --agent "performance-optimizer" \ --description "Optimize for speed, add caching" ``` ### Documentation Writer ```bash theme={null} forge task fork 1 \ --llm claude \ --agent "docs-writer" \ --description "Add comprehensive documentation and examples" ``` Specialized agents are just different system prompts applied to the base LLM! *** ## Attempt Metadata Each attempt stores: ```json theme={null} { "id": "attempt-abc123", "taskId": "task-1", "llm": "claude", "agent": "default", "status": "completed", "worktreePath": ".forge/worktrees/task-1-claude", "startedAt": "2024-01-15T10:30:00Z", "completedAt": "2024-01-15T10:35:22Z", "duration": 322000, "filesChanged": 8, "linesAdded": 245, "linesRemoved": 12, "cost": { "inputTokens": 15420, "outputTokens": 3890, "totalCost": 0.23 } } ``` View metadata: ```bash theme={null} forge task attempt-info 1 --attempt 2 ``` *** ## Handling Failed Attempts ### View Failure Reason ```bash theme={null} # Check logs forge task logs 1 --attempt 3 # Get error summary forge task attempt-info 1 --attempt 3 --errors-only ``` ### Common Failure Reasons **Issue**: Agent generated invalid code **Solutions**: * Retry with more specific instructions * Try different agent * Add example code in task description **Issue**: Tests didn't pass **Solutions**: * Check test output in logs * Add "make tests pass" to description * Use `--agent "test-aware"` profile **Issue**: Agent took too long **Solutions**: * Increase timeout: `--timeout 600` * Break task into smaller pieces * Use faster agent (Haiku, Flash) **Issue**: LLM API failed **Solutions**: * Check API key is valid * Verify rate limits * Check network connectivity * Retry after a few minutes ### Retry Failed Attempt ```bash theme={null} # Retry with same configuration forge task retry 1 --attempt 3 # Retry with modifications forge task retry 1 --attempt 3 \ --llm gemini \ --description "Try simpler approach" ``` *** ## Cost Tracking ### View Attempt Costs ```bash theme={null} # Cost for specific attempt forge task cost 1 --attempt 2 # Output: # Input tokens: 15,420 ($0.046) # Output tokens: 3,890 ($0.058) # Total cost: $0.104 # Total cost for all attempts forge task cost 1 --all # Output: # Attempt 1 (claude): $0.234 # Attempt 2 (gemini): $0.104 # Attempt 3 (cursor): $0.187 # Total: $0.525 ``` ### Cost Optimization Strategies Use fast, cheap models first: * Gemini Flash (free tier!) * Claude Haiku * GPT-3.5 Turbo Save expensive models for complex tasks If agent is going wrong direction, cancel early: ```bash theme={null} forge task cancel 1 --attempt 2 ``` Saves tokens and money Once you find an approach that works, save it as a template: ```bash theme={null} forge template save 1 --attempt 2 \ --name "user-auth-pattern" ``` Monitor total costs: ```bash theme={null} forge cost summary --month january ``` Set budgets per project *** ## Attempt Best Practices Don't create 5 attempts immediately. Start with your preferred agent (Claude or Gemini) If first attempt is close but not perfect, fork it with specific feedback rather than starting fresh * Claude: Complex logic, architecture * Gemini: Fast iterations, simple tasks * Cursor: UI/UX focused work * Local models: Privacy-sensitive work ```bash theme={null} forge task cleanup 1 --remove-rejected ``` Keeps your workspace tidy *** ## Advanced: Attempt Hooks Run custom scripts on attempt events: ```yaml .forge/hooks.yaml theme={null} on_attempt_complete: - run: "npm test" - run: "npm run lint" - notify: "slack" on_attempt_fail: - run: "cat logs/error.log" - notify: "email" ``` *** ## Troubleshooting **Error**: "Maximum attempts reached for task" **Solution**: * Default limit is 10 attempts per task * Clean up old attempts: `forge task cleanup 1` * Or increase limit: `forge config set max-attempts 20` **Error**: "Worktree path already exists" **Solution**: ```bash theme={null} # Clean orphaned worktrees forge worktree cleanup # Or remove specific worktree git worktree remove .forge/worktrees/task-1-old ``` **Issue**: Attempt shows running but nothing happening **Solution**: ```bash theme={null} # Cancel the attempt forge task cancel 1 --attempt 2 # Check for zombie processes ps aux | grep forge # Restart Forge forge restart ``` *** ## Next Steps Learn to compare attempt outputs Merge approved attempts to main branch Create custom agent profiles Deep dive into isolation strategy # Merging & Cleanup Source: https://docs.namastex.ai/forge/working/merging-cleanup Merge approved changes and clean up worktrees ## Overview After comparing attempts and choosing the best approach, it's time to **merge** those changes into your main branch and **clean up** temporary worktrees. *** ## The Merge Process ```mermaid theme={null} graph LR A[Review Attempt] --> B{Approve?} B -->|Yes| C[Merge to Main] B -->|No| D[Reject] C --> E[Cleanup Worktree] D --> F[Try Again] E --> G[Task Complete] ``` *** ## Merging Attempts ### Via Web UI Open task details → Click on completed attempt Check all file changes carefully: * Files modified * Lines added/removed * Tests passing Click **"Approve & Merge"** button Confirm merge in dialog: ``` Merge attempt #2 (gemini) into main? Files changed: 8 Additions: +269 Deletions: -16 [Cancel] [Merge] ``` Task moves to "Done" column Worktree auto-cleaned ### Via CLI ```bash theme={null} # Basic merge forge task merge 1 --attempt 2 # Merge with message forge task merge 1 --attempt 2 \ --message "Add JWT authentication (Gemini implementation)" # Merge and close task forge task merge 1 --attempt 2 --close # Merge without cleanup (keep worktree) forge task merge 1 --attempt 2 --no-cleanup ``` *** ## Merge Strategies ### Fast-Forward Merge (Default) Clean, linear history: ```bash theme={null} forge task merge 1 --attempt 2 --ff # Git history: # * abc123 Add authentication (gemini) # * def456 Previous commit # * ... ``` **When to use**: Single-developer, clean history preferred ### Merge Commit Preserves attempt branch history: ```bash theme={null} forge task merge 1 --attempt 2 --no-ff # Git history: # * abc123 Merge task-1-gemini # |\ # | * def456 Implement JWT tokens # | * ghi789 Add login endpoint # |/ # * jkl012 Previous commit ``` **When to use**: Multiple developers, want to preserve attempt context ### Squash Merge Combine all commits into one: ```bash theme={null} forge task merge 1 --attempt 2 --squash # Git history: # * abc123 Add user authentication # - Implemented JWT tokens # - Added login/signup endpoints # - Added tests # * def456 Previous commit ``` **When to use**: Clean up messy attempt history, single commit per feature *** ## Pre-Merge Checks Forge runs automatic checks before merging: ### Test Suite ```bash theme={null} forge task merge 1 --attempt 2 # Automatic checks: Running pre-merge checks... ✓ All tests pass (24/24) ✓ Linting passed ✓ Type checking passed ✓ No merge conflicts ✓ Branch up to date with main Ready to merge! ``` ### Custom Pre-Merge Hooks Configure in `.forge/hooks.yaml`: ```yaml theme={null} pre_merge: - run: "npm test" required: true - run: "npm run lint" required: true - run: "npm run build" required: true - run: "npm audit" required: false # Warn but don't block ``` If any required check fails, merge is blocked: ``` ❌ Pre-merge checks failed ✓ Tests passed ✓ Linting passed ❌ Build failed: TypeScript errors in src/auth/login.ts Merge blocked. Fix errors and try again. [View Errors] [Override] [Cancel] ``` *** ## Handling Merge Conflicts ### Detecting Conflicts ```bash theme={null} forge task merge 1 --attempt 2 # Output: ❌ Merge conflicts detected Conflicts in: - src/auth/login.ts (3 conflicts) - package.json (1 conflict) [Resolve Manually] [Use Ours] [Use Theirs] [Abort] ``` ### Resolving Conflicts ```bash theme={null} # Open conflicted files forge task conflicts 1 --attempt 2 # Edit conflicts in your editor: <<<<<<< HEAD (main) const PORT = 3000; ======= const PORT = 8080; >>>>>>> task-1-gemini # Choose one or combine: const PORT = process.env.PORT || 3000; # Mark as resolved git add src/auth/login.ts # Continue merge forge task merge 1 --attempt 2 --continue ``` ```bash theme={null} # Launch merge tool forge task resolve 1 --attempt 2 --tool # Opens visual diff tool: # - Left: Current (main) # - Middle: Result # - Right: Incoming (attempt) # Click to choose sections # Save when done ``` ```bash theme={null} # Keep main version forge task merge 1 --attempt 2 --strategy ours # Keep attempt version forge task merge 1 --attempt 2 --strategy theirs # Smart merge (prefer new code) forge task merge 1 --attempt 2 --strategy theirs-if-newer ``` *** ## Post-Merge Actions ### Automatic Actions After successful merge, Forge can: ```yaml .forge/hooks.yaml theme={null} post_merge: - run: "npm run build" - run: "git push origin main" - notify: slack: "#engineering" message: "Task #{{task.id}} merged by {{user.name}}" - create_pr: # If feature branch title: "{{task.title}}" body: "Closes #{{task.id}}" ``` ### Manual Post-Merge Steps Common things you might do: ```bash theme={null} # Push to remote git push origin main # Tag release git tag -a v1.2.0 -m "Add authentication" git push origin v1.2.0 # Deploy npm run deploy # Notify team forge task comment 1 \ --message "@team Authentication is live in production!" ``` *** ## Cleanup ### Automatic Cleanup (Default) Forge automatically cleans up after merge: ```bash theme={null} forge task merge 1 --attempt 2 # Automatic cleanup: ✓ Merged to main ✓ Removed git worktree ✓ Cleaned up temporary files ✓ Archived attempt logs ✓ Updated task status Done! 🎉 ``` ### Manual Cleanup Sometimes you want to keep the worktree: ```bash theme={null} # Merge without cleanup forge task merge 1 --attempt 2 --no-cleanup # Later, clean up manually forge worktree remove task-1-gemini # Or clean all merged worktrees forge worktree cleanup --merged ``` ### Cleanup Rejected Attempts ```bash theme={null} # Remove specific attempt forge task remove-attempt 1 --attempt 1 # Remove all rejected attempts forge task cleanup 1 --rejected-only # Remove all attempts except winner forge task cleanup 1 --keep-merged ``` *** ## Worktree Management ### List Worktrees ```bash theme={null} # List all worktrees forge worktree list # Output: /Users/you/project abc123 [main] .forge/worktrees/task-1 def456 [task-1-claude] .forge/worktrees/task-2 ghi789 [task-2-gemini] # Git's native command git worktree list ``` ### Remove Worktrees ```bash theme={null} # Remove specific worktree forge worktree remove task-1-claude # Or use git directly git worktree remove .forge/worktrees/task-1-claude # Force remove (if needed) git worktree remove --force .forge/worktrees/task-1-claude ``` ### Clean Orphaned Worktrees Sometimes worktrees get orphaned (branch deleted but directory remains): ```bash theme={null} # Detect and remove orphaned worktrees forge worktree cleanup # Output: Found 3 orphaned worktrees: - .forge/worktrees/task-old-1 - .forge/worktrees/task-old-2 - .forge/worktrees/temp-experiment Remove all? [y/N] y ✓ Cleaned 3 orphaned worktrees Freed 156 MB of disk space ``` Forge runs this automatically, but you can trigger it manually if needed *** ## Rolling Back Merges Made a mistake? Undo the merge: ### Immediate Rollback ```bash theme={null} # If you just merged git reset --hard HEAD~1 # Via Forge forge task rollback 1 ``` ### Revert Merge After pushing to remote: ```bash theme={null} # Create revert commit git revert -m 1 abc123 # Via Forge forge task revert 1 --create-issue ``` This creates a new commit that undoes the merge, preserving history. *** ## Merge Best Practices Never merge without reviewing: ```bash theme={null} # Good workflow forge task review 1 --attempt 2 forge task test 1 --attempt 2 forge task merge 1 --attempt 2 # Bad workflow forge task merge 1 --attempt 2 --force ``` Main branch should always work: * All tests must pass * No known bugs * Builds successfully * Deployed confidently ```bash theme={null} # Good forge task merge 1 --message \ "Add JWT authentication with refresh tokens - Implemented login/signup endpoints - Added bcrypt password hashing - Configured JWT with 24h expiry - Added comprehensive tests (95% coverage)" # Bad forge task merge 1 --message "auth stuff" ``` Don't let worktrees accumulate: ```bash theme={null} # Weekly cleanup forge worktree cleanup # Check disk usage du -sh .forge/worktrees ``` Old worktrees waste disk space *** ## Advanced: Partial Merges Sometimes you want only specific files from an attempt: ```bash theme={null} # Merge only specific files forge task cherry-pick 1 --attempt 2 \ --files "src/auth/*.ts" # Or manually git checkout task-1-gemini -- src/auth/login.ts git commit -m "Cherry-pick login from attempt #2" ``` *** ## Integration with CI/CD ### Trigger Builds on Merge ```yaml .github/workflows/forge-merge.yml theme={null} name: Forge Merge on: push: branches: [ main ] # Only when Forge merges paths: - '!.forge/**' jobs: deploy: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Deploy run: npm run deploy ``` ### Merge Gates Require CI checks before merge: ```yaml .forge/config.json theme={null} { "mergeGates": { "requireCI": true, "requireReview": true, "requireTests": true, "minCoverage": 80 } } ``` *** ## Troubleshooting **Error**: "Cannot merge: worktree is in detached HEAD state" **Solution**: ```bash theme={null} # Checkout proper branch in worktree cd .forge/worktrees/task-1-attempt git checkout task-1-claude # Retry merge forge task merge 1 --attempt 1 ``` **Error**: "Cannot remove worktree: directory is locked" **Solution**: ```bash theme={null} # Check for running processes lsof | grep ".forge/worktrees/task-1" # Kill processes if needed pkill -f task-1 # Force remove git worktree remove --force .forge/worktrees/task-1 ``` **Issue**: Merge commit contains unintended files **Solution**: * Check `.gitignore` is proper * Ensure `node_modules/` not committed * Review files before merge: ```bash theme={null} forge task files 1 --attempt 2 ``` * Abort and fix: ```bash theme={null} git merge --abort # Fix .gitignore git add .gitignore git commit -m "Update .gitignore" # Retry merge ``` **Error**: "Updates were rejected because the remote contains work that you do not have locally" **Solution**: ```bash theme={null} # Pull and rebase git pull --rebase origin main # Resolve conflicts if any git add . git rebase --continue # Push git push origin main ``` *** ## Cleanup Schedule Recommended cleanup schedule: | Frequency | Action | Command | | ------------- | ----------------------- | ------------------------------------- | | **Daily** | Remove merged worktrees | `forge worktree cleanup --merged` | | **Weekly** | Remove old attempt logs | `find .forge/logs -mtime +7 -delete` | | **Monthly** | Archive old tasks | `forge task archive --older-than 30d` | | **Quarterly** | Compact database | `sqlite3 .forge/forge.db "VACUUM;"` | *** ## Next Steps Understand isolation strategy Complete development workflows Automate deployments Fix common issues # Automagik Forge Source: https://docs.namastex.ai/index AI Orchestration Kanban - Where Vibe Coding Meets Structure
Automagik Automagik

Forge

AI Orchestration Kanban

Run any AI task. Compare 8+ LLMs side-by-side. Ship code you understand.

npx @automagik/forge

No installation required - runs instantly

*** ## ✨ What Makes Forge Different **Drag-and-drop task management** Organize AI work visually. Track progress from idea to production. **8+ AI models at your fingertips** Run Claude, GPT-4, Gemini, and more on the same task. Compare results side-by-side. **Safe experimentation** Every AI attempt runs in isolated Git worktree. Never worry about breaking your main branch. **Understand every change** Review AI-generated code before merging. You stay in control, always. *** ## 🎯 Perfect For Get an AI pair programmer that never sleeps. Experiment with multiple AI models without switching tools. Standardize AI workflows across your team. Compare which AI works best for different types of tasks. Benchmark LLM performance on real coding tasks. Track which models excel at what. See how different AIs approach the same problem. Learn by comparing their solutions. *** ## 🚀 Get Started in 3 Steps ```bash theme={null} npx @automagik/forge ``` Opens at `http://localhost:8887` Click **"New Task"** and describe what you want to build Select your LLM, start the attempt, review the code, and merge when ready ## Why Forge Exists **The Problem:** AI coding tools today lock you into one model, one workflow, one approach. You can't compare. You can't experiment. You just... trust. **Our Solution:** Forge gives you a visual workspace to run any AI on any task, compare results, and ship code you actually understand. AI suggests, you decide. Review every change before it touches your codebase. Switch between Claude, GPT-4, Gemini freely. Compare. Choose what works. MIT licensed. Run it anywhere. Modify it however you want. We use Forge to build Forge. That's the ultimate dogfooding. *** ## 🔗 Learn More Deep dive into concepts, workflows, and advanced features Get help, share tips, connect with other Forge users Star the repo, report issues, contribute code See what we're building next ***

Made with ❤️ by Namastex Labs

Part of the Automagik Suite - AI that elevates human potential

# Quick Start Source: https://docs.namastex.ai/quickstart Get started with Automagik Forge in 2 minutes

Start Building with Forge

AI Orchestration Kanban - Run it instantly with npx

*** ## Run Forge Instantly No installation required. Just run: ```bash theme={null} npx @automagik/forge ``` That's it! Forge will start and open in your browser at `http://localhost:8887` **No `npm install -g` needed** - `npx` downloads and runs Forge on-demand *** ## What You Get Drag-and-drop task management for AI-powered development Compare Claude, Gemini, GPT-4, and more on the same task Every AI attempt runs in isolated worktree - experiment safely Compare AI outputs side-by-side before merging *** ## 3-Minute Tutorial ```bash theme={null} npx @automagik/forge ``` Opens at `http://localhost:8887` Click **"New Task"** in the web interface or use CLI: ```bash theme={null} npx @automagik/forge task create "Add dark mode toggle" ``` * Select your preferred LLM (Claude, Gemini, etc.) * Click **"Start Attempt"** * Watch AI work in isolated Git worktree * Review the code changes in the web UI * Compare with other LLMs if you want * Merge when satisfied ✅ **You just built a feature with AI!** *** ## CLI Quick Reference ```bash theme={null} # Start Forge npx @automagik/forge # Create task npx @automagik/forge task create "Task description" # List tasks npx @automagik/forge task list # Compare AI results npx @automagik/forge task compare ``` ## Requirements * Node.js v18+ * Git installed * Any OS (Mac, Linux, Windows) Get keys for LLMs you want to use: * [Claude (Anthropic)](https://console.anthropic.com) * [GPT-4 (OpenAI)](https://platform.openai.com) * [Gemini (Google)](https://makersuite.google.com) Forge works without API keys - you can explore the interface and features. Add keys later when you're ready to run AI tasks. *** ## Next Steps Deep dive into Forge concepts and features Get help and share your experience Contribute or report issues What's coming next # Forge Source: https://docs.namastex.ai/suite/forge AI Orchestration Kanban - Where Vibe Coding Meets Structure **AI Orchestration Kanban** Multi-agent orchestrator with Git worktree isolation. Experiment with 8+ LLMs (Claude, Gemini, Cursor), compare results, ship code you understand. ### Key Features * **Multi-LLM Support**: Work with 8+ different LLMs simultaneously * **Git Worktree Isolation**: Experiment safely without affecting your main codebase * **Visual Kanban Board**: Track AI-driven tasks with an intuitive interface * **Result Comparison**: Compare outputs from different AI models side-by-side * **Production-Ready**: Ship code you actually understand and can maintain ### Quick Links View source code and contribute Install via NPM ### Quick Start ```bash theme={null} npx @automagik/forge ``` No installation required - runs instantly! ### Get Started Learn about Forge Get up and running