### Enterprise Setup Configuration Example Source: https://github.com/vasoyaprince14/dev-crew/blob/main/_autodocs/configuration.md A comprehensive `.dev-crew/config.yml` for an enterprise setup, detailing project specifics, advanced settings, and detailed configurations for review, security, test, and performance agents. ```yaml project: name: enterprise-platform stack: typescript database: postgresql orm: prisma test_framework: jest settings: max_tokens_per_request: 16384 show_token_usage: true auto_include_schema: true auto_include_env_example: true default_review_depth: deep confirm_before_apply: true output_format: markdown agents: review: severity: strict rules: - "require JSDoc for all exports" - "require unit tests" focus: - src/** ignore: - src/**/*.test.ts - src/**/__mocks__/** security: severity: strict rules: - "check for SQL injection" - "validate all user input" - "use parameterized queries" - "never log secrets" test: coverage_target: 85 performance: rules: - "identify n+1 queries" - "check bundle size" feedback: all-agents: - "we use TypeScript strict mode" - "all async operations must have error handling" ``` -------------------------------- ### Full Project Setup Example Source: https://github.com/vasoyaprince14/dev-crew/blob/main/_autodocs/api-reference/configuration-and-detection.md Demonstrates initializing a project's configuration, detecting project details, and setting agent-specific configurations using ConfigManager and ProjectDetector. ```typescript import { ConfigManager, ProjectDetector } from 'dev-crew'; async function setupProject() { const detector = new ProjectDetector(); const info = await detector.detect(); const config = new ConfigManager(); let cfg = config.load(); // Initialize project section cfg.project = { name: info.name, stack: info.language, database: info.database[0] || undefined, orm: info.orm || undefined, test_framework: info.testFramework || undefined }; // Set strictness based on project cfg.agents = cfg.agents || {}; cfg.agents.review = { severity: 'strict', focus: ['src/api/**'] }; // Add custom feedback config.save(cfg); config.addFeedback('review', 'require unit tests'); config.addFeedback('security', 'validate all inputs'); } ``` -------------------------------- ### Install Dev-Crew and Check Setup Source: https://github.com/vasoyaprince14/dev-crew/blob/main/README.md Install Dev-Crew globally using npm and verify the installation with the `doctor` command. This is a quick start for using the tool. ```bash npm install -g dev-crew # Check your setup dev-crew doctor # Scan your project (zero AI, runs instantly) dev-crew scan # Start interactive mode dev-crew ``` -------------------------------- ### Project Configuration Example Source: https://github.com/vasoyaprince14/dev-crew/blob/main/_autodocs/configuration.md Example of a project-level configuration file (`.dev-crew/config.yml`) defining project metadata, settings, and agent rules. ```yaml # .dev-crew/config.yml project: name: my-app stack: typescript database: postgresql orm: prisma test_framework: vitest settings: max_tokens_per_request: 8192 show_token_usage: true auto_include_schema: true auto_include_env_example: true default_review_depth: normal confirm_before_apply: false output_format: pretty agents: review: severity: strict rules: - "require JSDoc for all exports" - "no console.log in production" focus: - "src/api/**" ignore: - "**/*.test.ts" security: severity: strict rules: - "check for SQL injection" - "validate all user input" feedback: review: - "always check for potential null reference errors" - "check error handling in async functions" ``` -------------------------------- ### Execute Agent using AgentRegistry Source: https://github.com/vasoyaprince14/dev-crew/blob/main/_autodocs/api-reference/agents.md Example of how to get an agent from the registry and execute it with specific input, including handling streaming output and logging results. ```typescript const agent = await registry.get('review'); const result = await agent.execute({ files: ['src/api/routes.ts'], query: 'check for security issues', streaming: true, onStream: (chunk) => console.log(chunk) }); console.log(`Issues found: ${result.parsed.issues?.length || 0}`); console.log(`Tokens: ${result.tokensUsed}`); console.log(`Time: ${result.duration}ms`); ``` -------------------------------- ### Usage Example: Review Diff Source: https://github.com/vasoyaprince14/dev-crew/blob/main/_autodocs/api-reference/utilities-and-features.md An example demonstrating how to use DiffContext to get uncommitted changes and pass them to an agent for review. ```typescript async function reviewDiff() { const diff = new DiffContext(); const changes = await diff.getUncommittedChanges(); if (!changes) { console.log('No uncommitted changes'); return; } // Use changes as context for code review const agent = await AgentRegistry.get('review'); const result = await agent.execute({ context: changes, query: 'Review these changes for security and quality' }); console.log(result.parsed.summary); } ``` -------------------------------- ### Add Feedback via CLI Source: https://github.com/vasoyaprince14/dev-crew/blob/main/_autodocs/configuration.md Command-line examples for adding feedback to specific agents at runtime. ```bash dev-crew feedback review "always check for potential null reference errors" dev-crew feedback security "validate all user inputs before using them" dev-crew feedback test "use 'describe.skip' instead of 'describe.only'" ``` -------------------------------- ### ProjectDetector Usage Example Source: https://github.com/vasoyaprince14/dev-crew/blob/main/_autodocs/api-reference/configuration-and-detection.md Demonstrates how to use ProjectDetector to detect project characteristics and then configure DevCrew settings. ```APIDOC ## ProjectDetector and ConfigManager Usage Example ### Description Demonstrates how to use ProjectDetector to detect project characteristics and then configure DevCrew settings. ### Request Example ```typescript import { ConfigManager, ProjectDetector } from 'dev-crew'; async function setupProject() { const detector = new ProjectDetector(); const info = await detector.detect(); const config = new ConfigManager(); let cfg = config.load(); // Initialize project section cfg.project = { name: info.name, stack: info.language, database: info.database[0] || undefined, orm: info.orm || undefined, test_framework: info.testFramework || undefined }; // Set strictness based on project cfg.agents = cfg.agents || {}; cfg.agents.review = { severity: 'strict', focus: ['src/api/**'] }; // Add custom feedback config.save(cfg); config.addFeedback('review', 'require unit tests'); config.addFeedback('security', 'validate all inputs'); } ``` ``` -------------------------------- ### BaseAgent buildPrompt Implementation Source: https://github.com/vasoyaprince14/dev-crew/blob/main/_autodocs/api-reference/agents.md Example implementation of buildPrompt for a BaseAgent, constructing the user prompt with code context and static findings. ```typescript buildPrompt(input: AgentInput): string { const codeContext = this.gatheredContext; const staticFindings = this.staticAnalysis; return `Review this code: ${codeContext} ${staticFindings}`; } ``` -------------------------------- ### Full TokenOptimizer Usage Example Source: https://github.com/vasoyaprince14/dev-crew/blob/main/_autodocs/api-reference/optimization-and-parsing.md Demonstrates a complete workflow using TokenOptimizer, including estimating, compressing, selecting files, and reporting costs. ```typescript import { TokenOptimizer } from 'dev-crew'; const optimizer = new TokenOptimizer(); // 1. Estimate const codeSize = optimizer.estimate(codeContent); console.log(`Code is ~${codeSize} tokens`); // 2. Compress for token savings const compressed = optimizer.compress(codeContent); const savedTokens = optimizer.estimate(codeContent) - optimizer.estimate(compressed); console.log(`Saved ${savedTokens} tokens (${Math.round(savedTokens / optimizer.estimate(codeContent) * 100)}%)`); // 3. Select files within budget const files = ['auth.ts', 'database.ts', 'api.ts', 'utils.ts']; const selected = optimizer.selectRelevantFiles(files, 'auth.ts', 4000); console.log(`Including: ${selected.join(', ')}`); // 4. Report costs const report = optimizer.report(prompt, response); console.log(`Cost: $${report.cost.toFixed(4)}`); ``` -------------------------------- ### Execute the Explain Agent Source: https://github.com/vasoyaprince14/dev-crew/blob/main/_autodocs/agent-registry.md Shows how to get the 'explain' agent and execute it with a file and query to receive a detailed explanation of the code. ```typescript const agent = await AgentRegistry.get('explain'); const result = await agent.execute({ files: ['src/algorithm.ts'], query: 'Explain this sorting algorithm' }); console.log(result.parsed.summary); ``` -------------------------------- ### Full Debt Tracking Workflow Example Source: https://github.com/vasoyaprince14/dev-crew/blob/main/_autodocs/api-reference/utilities-and-features.md Demonstrates a complete workflow for tracking technical debt, from agent execution to report generation and trend analysis. ```typescript async function trackDebt() { const tracker = new DebtTracker(); const agent = await AgentRegistry.get('review'); const result = await agent.execute({ files: ['src/**/*.ts'] }); // Record debt from issues tracker.updateFromReview(result.parsed.issues || []); // Generate report const report = tracker.generateReport(); console.log(` 📊 Debt Report`); console.log(`Total: ${report.totalPoints} points`); console.log(`Items: ${report.itemCount}`); if (report.trend > 0) { console.log(`⚠️ Debt increasing by ${report.trend}%`); } else { console.log(`✓ Debt decreasing by ${Math.abs(report.trend)}%`); } } ``` -------------------------------- ### Track Agent Runs and Get Insights Source: https://github.com/vasoyaprince14/dev-crew/blob/main/_autodocs/api-reference/optimization-and-parsing.md A comprehensive usage example demonstrating how to track agent runs by recording token usage for each agent and then retrieving session summaries and optimization recommendations. ```typescript const intelligence = new TokenIntelligence(); // Record agent runs for (const result of agentResults) { intelligence.track(result.agent, result.prompt.tokens, result.response.tokens); } // Get insights const summary = intelligence.getSummary(); console.log(`Session tokens: ${summary.totalTokens}`); const recs = intelligence.getRecommendations(); if (recs.length > 0) { console.log('Optimization opportunities:'); recs.forEach(rec => console.log(` - ${rec}`)); } ``` -------------------------------- ### Install and Run Dev-Crew Commands Source: https://github.com/vasoyaprince14/dev-crew/blob/main/README.md Install Dev-Crew globally and execute common commands for project analysis and AI-assisted tasks. Use `scan` for instant analysis without AI. ```bash npx dev-crew scan # Instant project analysis (no AI needed) npx dev-crew review @src/api.ts # AI code review with graph context npx dev-crew security @src/ # OWASP security audit ``` -------------------------------- ### Feedback Configuration Example Source: https://github.com/vasoyaprince14/dev-crew/blob/main/_autodocs/configuration.md Template for providing custom feedback to agents, allowing up to 30 items per agent with the most recent having the highest priority. ```yaml feedback: {agent_name}: - "instruction 1" - "instruction 2" - "instruction 3" ``` -------------------------------- ### Execute the Tech-Lead Agent Source: https://github.com/vasoyaprince14/dev-crew/blob/main/_autodocs/agent-registry.md Demonstrates getting the 'tech-lead' agent and executing it with a query to receive architectural guidance. ```typescript const agent = await AgentRegistry.get('tech-lead'); const result = await agent.execute({ query: 'Should we refactor this monolith into microservices?' }); ``` -------------------------------- ### Development Team Configuration Example Source: https://github.com/vasoyaprince14/dev-crew/blob/main/_autodocs/configuration.md An example `.dev-crew/config.yml` for a development team, specifying project details, settings, and agent configurations for review, fix, and security. ```yaml project: name: acme-api stack: typescript database: postgresql orm: prisma test_framework: vitest settings: show_token_usage: true auto_include_schema: true default_review_depth: normal confirm_before_apply: false agents: review: severity: strict focus: - src/api/** - src/core/** fix: auto_apply: true create_backup: true security: severity: strict feedback: review: - "require JSDoc for all exports" - "check for unguarded process.env access" security: - "validate all user input" - "never log sensitive data" ``` -------------------------------- ### Deploy projects with automatic framework detection Source: https://github.com/vasoyaprince14/dev-crew/blob/main/CHANGELOG.md This command handles project deployment by auto-detecting the framework and recommending a platform. It performs pre-deployment checks and can install necessary CLIs. ```bash dev-crew deploy ``` -------------------------------- ### Integrate Project Detection, Config, and Analysis Source: https://github.com/vasoyaprince14/dev-crew/blob/main/_autodocs/api-reference/configuration-and-detection.md A complete example showing the integration of ProjectDetector, ConfigManager, ProjectCache, CodeGraph, DependencyGraph, and ContextEngine for comprehensive project analysis. ```typescript import { ProjectDetector, ConfigManager, ProjectCache, CodeGraph, DependencyGraph, ContextEngine } from 'dev-crew'; async function analyzeProject() { const cache = new ProjectCache(); // 1. Detect project let projectInfo = cache.get('projectInfo'); if (!projectInfo) { const detector = new ProjectDetector(); projectInfo = await detector.detect(); cache.set('projectInfo', projectInfo); } // 2. Load config const configMgr = new ConfigManager(); const config = configMgr.load(); // 3. Build code graph let codeGraph = cache.get('codeGraph'); if (!codeGraph) { codeGraph = new CodeGraph(); codeGraph.buildFromDirectory('./src', 500); cache.set('codeGraph', codeGraph); } // 4. Compute blast radius const blast = codeGraph.getBlastRadius(['src/api/routes.ts'], 2); // 5. Get dependencies const depGraph = new DependencyGraph(); const deps = await depGraph.build('src/api/routes.ts', 2); // 6. Gather context const engine = new ContextEngine(); const context = await engine.gather({ files: deps.map(d => d.file), projectInfo, includeSchema: projectInfo.orm !== null, includeConfig: true, maxDepth: 2, maxTokenBudget: 6000 }); return { projectInfo, config, blast, context }; } ``` -------------------------------- ### Get Claude Code CLI Version Source: https://github.com/vasoyaprince14/dev-crew/blob/main/_autodocs/api-reference/ai-providers-and-context.md Retrieve and log the installed version of the Claude Code CLI. ```typescript const bridge = new ClaudeBridge(); const version = await bridge.getVersion(); console.log(`Claude Code: ${version}`); ``` -------------------------------- ### Execute the Review Agent Source: https://github.com/vasoyaprince14/dev-crew/blob/main/_autodocs/agent-registry.md Demonstrates how to get the 'review' agent and execute it with specific files and a query for code quality and security assessment. ```typescript const agent = await AgentRegistry.get('review'); const result = await agent.execute({ files: ['src/api.ts'], query: 'Review for quality and security' }); console.log(`Score: ${result.parsed.score}/10`); console.log(`Issues: ${result.parsed.issues?.length}`); ``` -------------------------------- ### Example Feedback Configuration Source: https://github.com/vasoyaprince14/dev-crew/blob/main/_autodocs/configuration.md This YAML snippet shows how to define feedback for different agents like review and security within a Dev-Crew configuration. ```yaml feedback: review: - "we use async/await, not callbacks" - "require error handling in async functions" - "check for n+1 queries in loops" security: - "we use bcrypt for password hashing, not bcryptjs" - "all API responses must sanitize user input" - "never log API keys or tokens" test: - "test files should be colocated with source files" - "use meaningful test descriptions" ``` -------------------------------- ### Example Usage of ProjectDetector Source: https://github.com/vasoyaprince14/dev-crew/blob/main/_autodocs/api-reference/configuration-and-detection.md Demonstrates how to use the ProjectDetector to detect project information and perform conditional logic based on the detected language and framework, or ORM and database. ```typescript import { ProjectDetector } from 'dev-crew'; const detector = new ProjectDetector(); const info = await detector.detect(); if (info.language === 'typescript' && info.framework === 'nextjs') { console.log('Next.js TypeScript project detected'); } if (info.orm === 'prisma') { console.log(`Database: ${info.database.join(', ')}`); console.log('Will include Prisma schema in context'); } ``` -------------------------------- ### DevCrewError Usage Example Source: https://github.com/vasoyaprince14/dev-crew/blob/main/_autodocs/errors.md Demonstrates how to catch and inspect DevCrewError instances, checking for specific codes and hints. ```typescript import { DevCrewError } from 'dev-crew'; try { // some operation } catch (error) { if (error instanceof DevCrewError) { console.error(`Error [${error.code}]: ${error.message}`); if (error.hint) console.error(`Help: ${error.hint}`); } } ``` -------------------------------- ### Test Generation Configuration Source: https://github.com/vasoyaprince14/dev-crew/blob/main/_autodocs/configuration.md Example configuration for the test agent, specifying a coverage target and file patterns for focus and ignore. ```yaml agents: test: coverage_target: 85 focus: - "src/core/**" ignore: - "**/*.mock.ts" ``` -------------------------------- ### ClaudeBridge.verify Source: https://github.com/vasoyaprince14/dev-crew/blob/main/_autodocs/api-reference/ai-providers-and-context.md Checks if the Claude Code CLI is installed and functioning correctly. ```APIDOC ## ClaudeBridge.verify ### Description Checks if the Claude Code CLI is installed and functioning correctly. ### Method `async verify(): Promise` ### Example ```typescript const bridge = new ClaudeBridge(); if (await bridge.verify()) { console.log('✓ Claude Code available'); } else { console.log('✗ Claude Code not found'); } ``` ``` -------------------------------- ### ResponseParser Usage Example Source: https://github.com/vasoyaprince14/dev-crew/blob/main/_autodocs/api-reference/optimization-and-parsing.md Demonstrates how to instantiate and use the ResponseParser to parse an AI review response. It checks the score and logs issues if the score is below a threshold. ```typescript import { ResponseParser } from 'dev-crew'; const parser = new ResponseParser(); // From AI response const aiResponse = ` { "summary": "Code looks good overall", "score": 8, "issues": [ { "severity": "warning", "file": "src/api.ts", "line": 42, "message": "Missing error handling", "suggestion": "Add try-catch block" } ] } `; const parsed = parser.parseReview(aiResponse); if (parsed.score && parsed.score < 7) { console.log('⚠️ Score below threshold'); parsed.issues?.forEach(issue => { console.log(`${issue.file}:${issue.line} ${issue.message}`); }); } ``` -------------------------------- ### Comprehensive Feature Integration Example Source: https://github.com/vasoyaprince14/dev-crew/blob/main/_autodocs/api-reference/utilities-and-features.md Demonstrates the end-to-end usage of multiple library features, including diff analysis, agent execution, analytics tracking, debt management, pattern detection, and Git hotspot analysis. ```typescript import { AgentRegistry, DiffContext, GitIntelligence, DebtTracker, PatternLibrary, Analytics } from 'dev-crew'; async function comprehensiveAnalysis() { const analytics = new Analytics(); const debt = new DebtTracker(); const git = new GitIntelligence(); const patterns = new PatternLibrary(); const diff = new DiffContext(); // 1. Get diff const changes = await diff.getUncommittedChanges(); // 2. Run review const agent = await AgentRegistry.get('review'); const start = Date.now(); const result = await agent.execute({ context: changes }); const duration = Date.now() - start; // 3. Track usage analytics.recordAgent('review', duration, result.tokensUsed || 0); // 4. Update debt debt.updateFromReview(result.parsed.issues || []); // 5. Analyze patterns const foundPatterns = patterns.detectPatterns(changes, 'typescript'); // 6. Git analysis const hotspots = await git.getHotspots('src'); // 7. Report console.log(` 📊 Analysis Complete`); console.log(`Issues: ${result.parsed.issues?.length || 0}`); console.log(`Patterns: ${foundPatterns.length}`); console.log(`Hotspots: ${hotspots.length}`); const debtReport = debt.generateReport(); console.log(`Debt points: ${debtReport.totalPoints}`); } ``` -------------------------------- ### SecurityAgent System Prompt Source: https://github.com/vasoyaprince14/dev-crew/blob/main/_autodocs/api-reference/agents.md Example implementation of getSystemPrompt for a SecurityAgent, defining its role as a security expert focusing on OWASP top 10. ```typescript class SecurityAgent extends BaseAgent { getSystemPrompt(): string { return `You are a security expert. Focus on OWASP top 10...`; } } ``` -------------------------------- ### ConfigError Usage Example Source: https://github.com/vasoyaprince14/dev-crew/blob/main/_autodocs/errors.md Illustrates catching ConfigError to handle invalid or missing configuration, providing specific error messages and hints for the user. ```typescript import { ConfigError, ConfigManager } from 'dev-crew'; try { const config = new ConfigManager(); const agentConfig = config.load(); } catch (error) { if (error instanceof ConfigError) { console.error(`Config problem: ${error.message}`); console.error(`Fix it: ${error.hint}`); } } ``` -------------------------------- ### BaseAgent preProcess Implementation Source: https://github.com/vasoyaprince14/dev-crew/blob/main/_autodocs/api-reference/agents.md Example implementation of the protected preProcess method for a BaseAgent, used for input normalization and validation. ```typescript protected preProcess(input: AgentInput): AgentInput { // Normalize file paths, validate inputs, etc. return input; } ``` -------------------------------- ### Full Usage Example: Code Review Workflow Source: https://github.com/vasoyaprince14/dev-crew/blob/main/_autodocs/api-reference/ai-providers-and-context.md Demonstrates a complete workflow using ProviderBridge for code review. It includes initializing the bridge, auto-selecting a provider, gathering context from files, and sending the context for review. ```typescript import { ProviderBridge } from 'dev-crew'; async function runCodeReview(files: string[]) { const bridge = new ProviderBridge(); // Auto-select best available provider bridge.autoSelect(); const provider = bridge.selectedProvider(); console.log(`Using AI provider: ${provider.name}`); // Prepare context const context = await gatherContext(files); // Send to AI const response = await bridge.send( `Review this code:\n${context}`, { maxTokens: 8192 } ); console.log(response.content); } ``` -------------------------------- ### Analyze a File Example Source: https://github.com/vasoyaprince14/dev-crew/blob/main/_autodocs/README.md Demonstrates a common pattern for analyzing a specific file using Dev-Crew's library, involving project detection, code graph building, context gathering, and agent execution. ```APIDOC ## Pattern 1: Analyze a File Demonstrates a common pattern for analyzing a specific file using Dev-Crew's library, involving project detection, code graph building, context gathering, and agent execution. ```typescript import { ProjectDetector, CodeGraph, ContextEngine, AgentRegistry } from 'dev-crew'; async function analyzeFile(filePath: string) { // 1. Detect project const detector = new ProjectDetector(); const projectInfo = await detector.detect(); // 2. Build code graph for blast radius const graph = new CodeGraph(); graph.buildFromDirectory('./src'); const blast = graph.getBlastRadius([filePath], 2); // 3. Gather context const engine = new ContextEngine(); const context = await engine.gather({ files: [filePath], projectInfo, includeSchema: projectInfo.orm !== null }); // 4. Run agent const agent = await AgentRegistry.get('review'); const result = await agent.execute({ files: [filePath], context: `\nBlast radius: ${blast.impactedFiles.length} files affected` }); return result.parsed; } ``` ``` -------------------------------- ### Import and Use AgentRegistry Source: https://github.com/vasoyaprince14/dev-crew/blob/main/_autodocs/agent-registry.md Import the AgentRegistry class and demonstrate basic operations like getting an agent by name, listing all agents, and listing agents by tier. ```typescript import { AgentRegistry } from 'dev-crew'; // Get agent by name const agent = await AgentRegistry.get('review'); // List all agents const all = AgentRegistry.list(); // Get agents by tier const proAgents = AgentRegistry.listByTier('pro'); ``` -------------------------------- ### Example Static Analysis Workflow Source: https://github.com/vasoyaprince14/dev-crew/blob/main/_autodocs/api-reference/code-graph-and-analysis.md Demonstrates a typical workflow for using the StaticAnalyzer: analyzing files, checking for errors, and exiting if errors are found. This is useful for integrating static analysis into CI/CD pipelines or pre-commit hooks. ```typescript import { StaticAnalyzer } from 'dev-crew'; const analyzer = new StaticAnalyzer(); const findings = analyzer.analyze(['src/auth.ts', 'src/api.ts']); if (findings.some(f => f.type === 'error')) { console.log('❌ Errors found:'); findings .filter(f => f.type === 'error') .forEach(f => console.log(` ${f.file}:${f.line} ${f.message}`)); process.exit(1); } console.log('✓ No errors'); ``` -------------------------------- ### Dev-Crew Project Configuration Source: https://github.com/vasoyaprince14/dev-crew/blob/main/_autodocs/README.md Example YAML configuration for a Dev-Crew project, specifying project details, settings, and agent configurations. ```yaml project: name: my-app stack: typescript database: postgresql orm: prisma test_framework: vitest settings: max_tokens_per_request: 8192 show_token_usage: true auto_include_schema: true default_review_depth: normal agents: review: severity: strict rules: - "require JSDoc for exports" security: severity: strict feedback: review: - "validate user input carefully" - "check for n+1 queries" ``` -------------------------------- ### Get Token Optimization Recommendations Source: https://github.com/vasoyaprince14/dev-crew/blob/main/_autodocs/api-reference/optimization-and-parsing.md Retrieves an array of actionable recommendations for optimizing token usage. Useful for identifying areas to reduce costs or improve efficiency. ```typescript const recs = intelligence.getRecommendations(); // ['Consider using quick review depth', 'Cache graphs to save tokens', ...] recs.forEach(rec => console.log(`💡 ${rec}`)); ``` -------------------------------- ### BaseAgent postProcess Implementation Source: https://github.com/vasoyaprince14/dev-crew/blob/main/_autodocs/api-reference/agents.md Example implementation of the protected postProcess method for a BaseAgent, used for filtering results and adding metadata. ```typescript protected postProcess(parsed: ParsedResponse): ParsedResponse { // Filter results, add metadata, etc. return parsed; } ``` -------------------------------- ### Configure Review Agent Rules Source: https://github.com/vasoyaprince14/dev-crew/blob/main/_autodocs/api-reference/agents.md Example YAML configuration for the 'review' agent, specifying strictness levels and custom rules for code quality checks. ```yaml # .dev-crew/config.yml agents: review: severity: strict rules: - "require JSDoc for exports" - "no console.log in production" focus: - "src/api/**" ``` -------------------------------- ### Agent Execution with Input Sanitization Source: https://github.com/vasoyaprince14/dev-crew/blob/main/_autodocs/api-reference/optimization-and-parsing.md Example of safely executing an agent by sanitizing file paths, validating queries, and sanitizing context before processing. ```typescript import { InputSanitizer } from 'dev-crew'; async function executeAgentSafely(input: AgentInput) { // Sanitize file paths if (input.files) { input.files = input.files.map(f => InputSanitizer.sanitizePath(f)); } // Validate query if (!InputSanitizer.validateQuery(input.query || '')) { throw new Error('Invalid query'); } // Sanitize context if (input.context) { input.context = InputSanitizer.sanitizeQuery(input.context); } return await agent.execute(input); } ``` -------------------------------- ### ProviderError Usage Example Source: https://github.com/vasoyaprince14/dev-crew/blob/main/_autodocs/errors.md Shows how to catch ProviderError, useful for handling AI provider communication failures and implementing fallback mechanisms. ```typescript import { ProviderError } from 'dev-crew'; try { await bridge.send(prompt); } catch (error) { if (error instanceof ProviderError) { console.error(`Provider failed: ${error.message}`); // Fallback to simulation mode or manual review } } ``` -------------------------------- ### Get Context Files for Operation Source: https://github.com/vasoyaprince14/dev-crew/blob/main/_autodocs/api-reference/code-graph-and-analysis.md Retrieves a list of recommended files to include for a specific operation (review, fix, debug, test) based on the target file and its dependencies. Helps in providing relevant context for AI operations. ```typescript const deps = await depGraph.build('src/utils/parser.ts', 2); const reviewFiles = depGraph.getContextFiles('src/utils/parser.ts', 'review'); // Includes parser.ts + directly imported files ``` -------------------------------- ### Analyze a File with Dev-Crew Source: https://github.com/vasoyaprince14/dev-crew/blob/main/_autodocs/README.md Demonstrates how to analyze a specific file within a project using dev-crew. This example covers project detection, code graph building, context gathering, and agent execution. ```typescript import { ProjectDetector, CodeGraph, ContextEngine, AgentRegistry } from 'dev-crew'; async function analyzeFile(filePath: string) { // 1. Detect project const detector = new ProjectDetector(); const projectInfo = await detector.detect(); // 2. Build code graph for blast radius const graph = new CodeGraph(); graph.buildFromDirectory('./src'); const blast = graph.getBlastRadius([filePath], 2); // 3. Gather context const engine = new ContextEngine(); const context = await engine.gather({ files: [filePath], projectInfo, includeSchema: projectInfo.orm !== null }); // 4. Run agent const agent = await AgentRegistry.get('review'); const result = await agent.execute({ files: [filePath], context: `\nBlast radius: ${blast.impactedFiles.length} files affected` }); return result.parsed; } ``` -------------------------------- ### Run Dev-Crew CLI Commands Source: https://github.com/vasoyaprince14/dev-crew/blob/main/_autodocs/README.md Execute dev-crew commands from the command line. Includes examples for interactive mode, project scanning, agent execution, and configuration management. ```bash npx dev-crew [command] [options] # No args: interactive REPL npx dev-crew # Scan: instant project analysis (no AI) npx dev-crew scan # Agents npx dev-crew review src/api.ts npx dev-crew security src/ npx dev-crew fix src/bug.ts npx dev-crew test src/utils.ts npx dev-crew tech-lead "should we use microservices?" # Config npx dev-crew init # Create .dev-crew/config.yml npx dev-crew doctor # Check setup npx dev-crew config set ... # Edit config npx dev-crew feedback review "new rule" # Full list in package.json bin/dev-crew.ts ``` -------------------------------- ### Error Recovery Pattern with Fallback Source: https://github.com/vasoyaprince14/dev-crew/blob/main/_autodocs/errors.md Demonstrates an error recovery strategy where specific ProviderErrors, like a missing AI provider, trigger an automatic installation and retry mechanism. ```typescript import { ProviderError } from 'dev-crew'; async function executeWithFallback(agent, input) { try { return await agent.execute(input); } catch (error) { if (error instanceof ProviderError && error.message.includes('not found')) { console.log('Installing AI provider...'); await installProvider(); return await agent.execute(input); // Retry } throw error; } } ``` -------------------------------- ### ContextEngine Constructor Source: https://github.com/vasoyaprince14/dev-crew/blob/main/_autodocs/api-reference/ai-providers-and-context.md Initializes the ContextEngine. No parameters are required. ```APIDOC ## ContextEngine Constructor ### Description Initializes the ContextEngine. No parameters are required. ### Constructor ```typescript constructor() ``` ### Example ```typescript const engine = new ContextEngine(); ``` ``` -------------------------------- ### Verify Claude Code CLI Installation Source: https://github.com/vasoyaprince14/dev-crew/blob/main/_autodocs/api-reference/ai-providers-and-context.md Check if the Claude Code CLI is installed and functioning correctly. Logs a success or failure message to the console. ```typescript const bridge = new ClaudeBridge(); if (await bridge.verify()) { console.log('✓ Claude Code available'); } else { console.log('✗ Claude Code not found'); } ``` -------------------------------- ### Get Project Config File Path Source: https://github.com/vasoyaprince14/dev-crew/blob/main/_autodocs/api-reference/configuration-and-detection.md Use the `configPath` property to get the full path to the project's main configuration file (`.dev-crew/config.yml`). ```typescript console.log(config.configPath); // /path/to/project/.dev-crew/config.yml ``` -------------------------------- ### Get Nested Configuration Value Source: https://github.com/vasoyaprince14/dev-crew/blob/main/_autodocs/api-reference/configuration-and-detection.md Retrieve a specific configuration value using its dot-separated key with the generic `get()` method. Returns `undefined` if the key is not found. ```typescript const maxTokens = config.get('settings.max_tokens_per_request'); const framework = config.get('project.framework'); const rules = config.get('agents.review.rules'); ``` -------------------------------- ### ClaudeBridge.getVersion Source: https://github.com/vasoyaprince14/dev-crew/blob/main/_autodocs/api-reference/ai-providers-and-context.md Retrieves the installed version of the Claude Code CLI. ```APIDOC ## ClaudeBridge.getVersion ### Description Retrieves the installed version of the Claude Code CLI. ### Method `async getVersion(): Promise` ### Example ```typescript const version = await bridge.getVersion(); console.log(`Claude Code: ${version}`); ``` ``` -------------------------------- ### Initialize and Configure Dev Crew Source: https://github.com/vasoyaprince14/dev-crew/blob/main/README.md Commands to initialize the configuration file, set the AI provider, and teach agents by providing feedback. ```bash dev-crew init # Create .dev-crew.yml config dev-crew config set provider claude # Set AI provider dev-crew feedback review "always check for SQL injection" # Teach agents ``` -------------------------------- ### DebtTracker Constructor Source: https://github.com/vasoyaprince14/dev-crew/blob/main/_autodocs/api-reference/utilities-and-features.md Initializes a new instance of the DebtTracker. Optionally accepts a project root directory. ```APIDOC ## DebtTracker Constructor ### Description Initializes a new instance of the DebtTracker. Optionally accepts a project root directory. ### Parameters #### Path Parameters * **projectRoot** (string) - Optional - The root directory of the project. Defaults to `process.cwd()`. ### Request Example ```typescript const tracker = new DebtTracker('./my-project'); ``` ``` -------------------------------- ### Initialize DebtTracker Source: https://github.com/vasoyaprince14/dev-crew/blob/main/_autodocs/api-reference/utilities-and-features.md Instantiates the DebtTracker with an optional project root directory. ```typescript const tracker = new DebtTracker('./my-project'); ``` -------------------------------- ### Get Agent Feedback Source: https://github.com/vasoyaprince14/dev-crew/blob/main/_autodocs/api-reference/configuration-and-detection.md Retrieve an array of custom feedback strings associated with a specific agent using `getFeedback()`. ```typescript const feedback = config.getFeedback('review'); // ['rule 1', 'rule 2', ...] ``` -------------------------------- ### Get Agent-Specific Configuration Source: https://github.com/vasoyaprince14/dev-crew/blob/main/_autodocs/api-reference/configuration-and-detection.md Retrieve configuration overrides specific to an agent by providing the agent's name to `getAgentConfig()`. ```typescript const reviewConfig = config.getAgentConfig('review'); const severity = reviewConfig.severity; // 'normal' | 'strict' | 'relaxed' const rules = reviewConfig.rules; // string[] ``` -------------------------------- ### Get Global Config File Path Source: https://github.com/vasoyaprince14/dev-crew/blob/main/_autodocs/api-reference/configuration-and-detection.md Retrieve the path to the global configuration file using the `globalConfigPath` property. ```typescript console.log(config.globalConfigPath); // ~/.dev-crew/config.yml ``` -------------------------------- ### Get Feedback for an Agent Source: https://github.com/vasoyaprince14/dev-crew/blob/main/_autodocs/configuration.md Retrieve the list of feedback messages associated with a specific agent, like the 'review' agent. ```typescript const reviewFeedback = config.getFeedback('review'); // ['always check for null refs', ...] ``` -------------------------------- ### BaseAgent parseResponse Implementation Source: https://github.com/vasoyaprince14/dev-crew/blob/main/_autodocs/api-reference/agents.md Example implementation of parseResponse for a BaseAgent, extracting issues and fixes from the AI's raw response. ```typescript parseResponse(raw: string): ParsedResponse { // Extract issues, fixes, etc. from raw text/JSON return { type: 'review', summary: extracted.summary, issues: extracted.issues, raw }; } ``` -------------------------------- ### Set Up Shared Provider Bridge for Agents Source: https://github.com/vasoyaprince14/dev-crew/blob/main/_autodocs/api-reference/agents.md Demonstrates how to initialize and set a shared `ProviderBridge` instance, ensuring all subsequent agents use the same provider for consistency and token tracking. ```typescript import { setSharedProvider, getSharedProvider } from 'dev-crew'; const provider = new ProviderBridge(); provider.autoSelect(); setSharedProvider(provider); // Now all agents created after this use the same provider const review = await AgentRegistry.get('review'); const security = await AgentRegistry.get('security'); // Both use same ProviderBridge instance ``` -------------------------------- ### Get Staged Changes Source: https://github.com/vasoyaprince14/dev-crew/blob/main/_autodocs/api-reference/utilities-and-features.md Retrieves the diff of staged changes in a git repository. This shows only the changes that have been added to the staging area. ```typescript const staged = await diff.getStagedChanges(); console.log(staged); // Shows git add'ed changes only ``` -------------------------------- ### Instantiate ConfigManager Source: https://github.com/vasoyaprince14/dev-crew/blob/main/_autodocs/api-reference/configuration-and-detection.md Create a new ConfigManager instance. Specify the project root directory if it's not the current working directory. ```typescript const config = new ConfigManager('./src'); // Specific project const config = new ConfigManager(); // Current directory ``` -------------------------------- ### Get Uncommitted Changes Source: https://github.com/vasoyaprince14/dev-crew/blob/main/_autodocs/api-reference/utilities-and-features.md Retrieves the diff of uncommitted changes in a git repository. Useful for reviewing current modifications before staging. ```typescript const diff = new DiffContext(); const changes = await diff.getUncommittedChanges(); console.log(changes); // Shows all uncommitted modifications ``` -------------------------------- ### BaseAgent validate Implementation Source: https://github.com/vasoyaprince14/dev-crew/blob/main/_autodocs/api-reference/agents.md Example implementation of the protected validate method for a BaseAgent, returning an array of warning strings if no files are specified. ```typescript protected validate(input: AgentInput): string[] { const warnings: string[] = []; if (!input.files || input.files.length === 0) { warnings.push('No files specified'); } return warnings; } ``` -------------------------------- ### Initialize ContextEngine Source: https://github.com/vasoyaprince14/dev-crew/blob/main/_autodocs/api-reference/ai-providers-and-context.md Instantiate the ContextEngine without any parameters. This engine is used for gathering and formatting code context for AI prompts. ```typescript const engine = new ContextEngine(); ``` -------------------------------- ### Strict Security Auditing Configuration Source: https://github.com/vasoyaprince14/dev-crew/blob/main/_autodocs/configuration.md Example configuration for the security agent, setting strict severity and defining specific security rules. ```yaml agents: security: severity: strict rules: - "check for SQL injection" - "validate all user inputs" - "use parameterized queries" - "never log sensitive data" ``` -------------------------------- ### Execute the Ask Agent Source: https://github.com/vasoyaprince14/dev-crew/blob/main/_autodocs/agent-registry.md Illustrates retrieving the 'ask' agent and executing it with a query to ask general questions about the codebase. ```typescript const agent = await AgentRegistry.get('ask'); const result = await agent.execute({ query: 'How do I use the auth module?' }); console.log(result.parsed.summary); ``` -------------------------------- ### Load, Access, and Modify Configuration Source: https://github.com/vasoyaprince14/dev-crew/blob/main/_autodocs/configuration.md Demonstrates loading configuration, accessing nested values, modifying settings, and retrieving agent-specific configurations and feedback. ```typescript import { ConfigManager } from 'dev-crew'; const config = new ConfigManager('/path/to/project'); // Load config const cfg = config.load(); // Access nested values const maxTokens = config.get('settings.max_tokens_per_request'); const dbType = config.get('project.database'); // Modify and save config.set('settings.show_token_usage', true); // Agent-specific const reviewRules = config.getAgentConfig('review').rules; const securityFeedback = config.getFeedback('security'); // Add feedback config.addFeedback('review', 'new feedback rule'); ``` -------------------------------- ### Get Most Used Agent Source: https://github.com/vasoyaprince14/dev-crew/blob/main/_autodocs/api-reference/utilities-and-features.md Identify and retrieve the name of the agent that has been used most frequently. This helps in understanding user preferences and agent utilization. ```typescript const favorite = analytics.getMostUsedAgent(); console.log(`You use '${favorite}' the most`); ``` -------------------------------- ### Initialize and Load Configuration Source: https://github.com/vasoyaprince14/dev-crew/blob/main/_autodocs/configuration.md Instantiate the ConfigManager and load the merged global and project configurations. The loaded configuration object contains project, settings, agents, and feedback details. ```typescript const config = new ConfigManager(); const merged = config.load(); // {project, settings, agents, feedback} ``` -------------------------------- ### Get Known Anti-Patterns Source: https://github.com/vasoyaprince14/dev-crew/blob/main/_autodocs/api-reference/utilities-and-features.md Retrieve a list of predefined anti-patterns that the library recognizes. Each anti-pattern object includes its name and a description of why it should be avoided. ```typescript const antiPatterns = library.getAntiPatterns(); antiPatterns.forEach(ap => { console.log(`Anti-pattern: ${ap.name}`); console.log(`Why avoid: ${ap.description}`); }); ``` -------------------------------- ### Get an Agent Instance Source: https://github.com/vasoyaprince14/dev-crew/blob/main/_autodocs/api-reference/agents.md Retrieves an agent instance by its name using AgentRegistry.get. This is useful for programmatically accessing specific agent functionalities. ```typescript import { AgentRegistry } from 'dev-crew'; const reviewAgent = await AgentRegistry.get('review'); const result = await reviewAgent.execute({ files: ['src/api.ts'] }); ``` -------------------------------- ### Get Config Directory Path Source: https://github.com/vasoyaprince14/dev-crew/blob/main/_autodocs/api-reference/configuration-and-detection.md Access the `configDir` property to retrieve the path to the project's configuration directory, typically '.dev-crew'. ```typescript console.log(config.configDir); // /path/to/project/.dev-crew ``` -------------------------------- ### Initialize GitIntelligence with Repository Path Source: https://github.com/vasoyaprince14/dev-crew/blob/main/_autodocs/api-reference/utilities-and-features.md Constructs a new GitIntelligence instance, optionally specifying the path to the git repository. Defaults to the current working directory. ```typescript const git = new GitIntelligence('./my-repo'); ``` -------------------------------- ### Get Agent-Specific Configuration Overrides Source: https://github.com/vasoyaprince14/dev-crew/blob/main/_autodocs/configuration.md Retrieve configuration settings specific to an agent, such as overrides for the 'review' agent's severity and rules. ```typescript const reviewConfig = config.getAgentConfig('review'); // { severity: 'strict', rules: [...], ... } ``` -------------------------------- ### Comprehensive Project Analysis Workflow Source: https://github.com/vasoyaprince14/dev-crew/blob/main/_autodocs/api-reference/utilities-and-features.md This snippet demonstrates a typical workflow integrating multiple utilities for project detection, git intelligence gathering, code analysis, agent execution for review, and debt tracking. ```typescript // Detect project const detector = new ProjectDetector(); const projectInfo = await detector.detect(); // Get git intelligence const git = new GitIntelligence(); const hotspots = await git.getHotspots('src'); // Analyze code const graph = new CodeGraph(); graph.buildFromDirectory('./src'); // Run agent with context const agent = await AgentRegistry.get('review'); const result = await agent.execute({ files: ['src/api.ts'], context: hotspots.map(h => h.file).join(', ') }); // Track debt const debt = new DebtTracker(); debt.updateFromReview(result.parsed.issues || []); // Report const report = debt.generateReport(); console.log(`Debt: ${report.totalPoints} points`); ``` -------------------------------- ### Deploy projects to specific platforms Source: https://github.com/vasoyaprince14/dev-crew/blob/main/CHANGELOG.md Deploy your project to a specific platform like Vercel, Railway, or Netlify using dedicated commands. These commands ensure the necessary pre-deployment checks are performed. ```bash dev-crew deploy vercel ``` ```bash dev-crew deploy railway ``` ```bash dev-crew deploy netlify ``` -------------------------------- ### buildFromDirectory Source: https://github.com/vasoyaprince14/dev-crew/blob/main/_autodocs/api-reference/code-graph-and-analysis.md Recursively indexes all source files within a specified directory. An optional `maxFiles` parameter limits the number of files indexed. ```APIDOC ## buildFromDirectory ### Description Recursively index all source files in a directory. ### Method ```typescript buildFromDirectory(root: string, maxFiles?: number): void ``` ### Parameters #### Path Parameters - **root** (string) - Required - Directory to scan - **maxFiles** (number) - Optional - Default: 500 - Stop after N files (prevents memory bloat) ### Request Example ```typescript const graph = new CodeGraph(); graph.buildFromDirectory('./src', 500); ``` Skips standard dirs: `node_modules`, `dist`, `build`, `.git`, `coverage`, `.next`, `venv`, etc. ``` -------------------------------- ### StaticAnalyzer.formatForPrompt Source: https://github.com/vasoyaprince14/dev-crew/blob/main/_autodocs/api-reference/code-graph-and-analysis.md Formats an array of StaticFinding objects into a markdown string suitable for inclusion in an AI prompt. ```APIDOC ## StaticAnalyzer.formatForPrompt ### Description Format findings as markdown for inclusion in AI prompt. ### Method `formatForPrompt(findings: StaticFinding[]): string` ### Parameters #### Path Parameters - **findings** (StaticFinding[]) - Required - Analysis results ### Response #### Success Response - **string** - Markdown string of findings. ### Request Example ```typescript const findings = analyzer.analyze(files); const context = analyzer.formatForPrompt(findings); const prompt = ` Here is the code to review: ${codeContext} ${context} // <- Static findings included here `; ``` ``` -------------------------------- ### ConfigManager Constructor Source: https://github.com/vasoyaprince14/dev-crew/blob/main/_autodocs/api-reference/configuration-and-detection.md Initializes a new ConfigManager instance. It can be pointed to a specific project root or default to the current working directory. ```APIDOC ## Constructor ConfigManager ### Description Initializes a new ConfigManager instance. It can be pointed to a specific project root or default to the current working directory. ### Parameters #### Path Parameters - **projectRoot** (string) - Optional - Project root directory. Defaults to `process.cwd()`. ### Request Example ```typescript const config = new ConfigManager('./src'); // Specific project const config = new ConfigManager(); // Current directory ``` ``` -------------------------------- ### DependencyGraph.getContextFiles Source: https://github.com/vasoyaprince14/dev-crew/blob/main/_autodocs/api-reference/code-graph-and-analysis.md Retrieves a list of recommended files to include based on the specified operation type (review, fix, debug, test). ```APIDOC ## DependencyGraph.getContextFiles ### Description Get recommended files to include based on operation type. ### Method `getContextFiles(target: string, operation: 'review' | 'fix' | 'debug' | 'test'): string[]` ### Parameters #### Path Parameters - **target** (string) - Required - Target file - **operation** (string) - Required - Type of analysis (review, fix, debug, test) ### Response #### Success Response - **string[]** - Array of recommended file paths. ### Request Example ```typescript const deps = await depGraph.build('src/utils/parser.ts', 2); const reviewFiles = depGraph.getContextFiles('src/utils/parser.ts', 'review'); // Includes parser.ts + directly imported files ``` ``` -------------------------------- ### Get File Changes Source: https://github.com/vasoyaprince14/dev-crew/blob/main/_autodocs/api-reference/utilities-and-features.md Retrieves the diff for a specific file, parsing it into hunks and lines. Useful for detailed analysis of changes within a single file. ```typescript const changes = await diff.getFileChanges('src/api.ts'); changes.hunks.forEach(hunk => { console.log(`Lines ${hunk.oldStart}-${hunk.newStart}:`); console.log(` Removed: ${hunk.oldLines.length} lines`); console.log(` Added: ${hunk.newLines.length} lines`); }); ``` -------------------------------- ### Execute the Test Agent Source: https://github.com/vasoyaprince14/dev-crew/blob/main/_autodocs/agent-registry.md Demonstrates obtaining the 'test' agent and using it to generate comprehensive tests for a given file. ```typescript const agent = await AgentRegistry.get('test'); const result = await agent.execute({ files: ['src/utils.ts'], query: 'Generate comprehensive tests' }); console.log(result.parsed.raw); // Test file content ```