Skip to content

Add CLI Init Command with AI-Powered Config Generation#28

Merged
JeremyDev87 merged 1 commit into
masterfrom
feat/22
Dec 19, 2025
Merged

Add CLI Init Command with AI-Powered Config Generation#28
JeremyDev87 merged 1 commit into
masterfrom
feat/22

Conversation

@JeremyDev87

Copy link
Copy Markdown
Owner

Add CLI Init Command with AI-Powered Config Generation

📋 Summary

Implements the codingbuddy init CLI command that automatically generates codingbuddy.config.js from project analysis using AI. This provides a simple, one-command solution for developers to configure CodingBuddy for their projects.

Closes #22

🎯 Problem

Manual Configuration Barrier

Even with project analysis capabilities (TICKET-003), developers still need to:

  1. Understand the analysis results
  2. Manually convert analysis into config format
  3. Write the config file themselves

This creates friction and reduces adoption. Developers want a single command that does everything.

Missing Developer Interface

The previous PRs built the infrastructure:

  • ✅ Config schema (TICKET-001)
  • ✅ Config loader (TICKET-002)
  • ✅ Project analyzer (TICKET-003)

But there was no way for developers to actually use it. They needed a CLI command.

✨ Solution

CLI Init Command

A complete CLI implementation that:

  1. Analyzes the project using AnalyzerService
  2. Generates config using AI (Anthropic Claude API)
  3. Writes the config file in JS or JSON format
  4. Provides clear progress feedback and error handling

1. CLI Entry Point (cli.ts)

Features:

  • Command parsing (init, help, version)
  • Option parsing (--format, --force, --api-key)
  • Usage and version display
  • Main entry point for CLI execution

Commands:

  • codingbuddy init [path] - Initialize configuration
  • codingbuddy --help - Show usage
  • codingbuddy --version - Show version

Options:

  • --format <js|json> - Output format (default: js)
  • --force, -f - Overwrite existing config
  • --api-key <key> - Anthropic API key (or use ANTHROPIC_API_KEY env)

2. Init Command (init.command.ts)

Features:

  • Orchestrates the entire init flow:
    1. Check for API key (options or environment)
    2. Check for existing config (prompt if found)
    3. Analyze project with AnalyzerService
    4. Generate config with ConfigGenerator
    5. Write config file with ConfigWriter
  • Progress indication with spinner
  • Error handling and user-friendly messages
  • Returns InitResult with success status

Key Functions:

  • runInit(options): Main init command execution
  • getApiKey(options): Get API key from options or environment

3. Config Generator (config.generator.ts)

Features:

  • Uses Anthropic Claude API to generate config from analysis
  • Default model: claude-sonnet-4-20250514
  • Extracts JSON from markdown code blocks or raw JSON
  • Validates generated config against schema
  • Handles API errors gracefully

Key Functions:

  • ConfigGenerator.generate(analysis): Generate config from analysis
  • extractJsonFromResponse(response): Extract JSON from AI response
  • parseJsonResponse(response): Parse and validate JSON response

AI Prompt:

  • System prompt explains CodingBuddy config schema
  • User prompt includes formatted project analysis
  • AI generates appropriate config based on project characteristics

4. Config Writer (config.writer.ts)

Features:

  • Writes config in two formats:
    • JavaScript: CommonJS module with JSDoc type annotation
    • JSON: Pretty-printed JSON with indentation
  • Checks for existing config files
  • Handles file write errors

Key Functions:

  • writeConfig(projectRoot, config, options): Write config file
  • findExistingConfig(projectRoot): Find existing config
  • formatConfigAsJs(config): Format as JS module
  • formatConfigAsJson(config): Format as JSON

Output Formats:

JavaScript (codingbuddy.config.js):

/** @type {import('codingbuddy').CodingBuddyConfig} */
module.exports = {
  "projectName": "my-app",
  "language": "ko",
  "techStack": {
    "frontend": ["React", "TypeScript"]
  }
};

JSON (codingbuddy.config.json):

{
  "projectName": "my-app",
  "language": "ko",
  "techStack": {
    "frontend": ["React", "TypeScript"]
  }
}

5. Prompt Builder (prompt.builder.ts)

Features:

  • Builds system prompt explaining config schema
  • Formats project analysis for AI consumption
  • Includes examples and guidelines
  • Structures prompts for optimal AI understanding

Key Functions:

  • buildSystemPrompt(): Build system prompt
  • buildAnalysisPrompt(analysis): Format analysis as user prompt

6. Console Utilities (utils/console.ts)

Features:

  • Colored output (info, success, warn, error)
  • Spinner animation for progress indication
  • Step-by-step logging
  • Config formatting for display

Key Functions:

  • log.info/success/warn/error(message): Colored logging
  • spinner.start/succeed/fail/stop(message): Spinner control
  • formatConfig(config): Format config for display

7. MCP Service Integration (mcp.service.ts)

Features:

  • Integrates ConfigService into MCP service
  • Adds config://project resource
  • Adds get_project_config tool
  • Includes project context in activate_agent prompt
  • Includes language setting in parse_mode response

New Resources:

  • config://project - Project configuration as JSON resource

New Tools:

  • get_project_config - Get project configuration

Enhanced Prompts:

  • activate_agent - Now includes project context (tech stack, architecture, conventions)
  • parse_mode - Now includes language setting from config

🧪 Testing

Test Coverage

  • CLI: 10 tests covering argument parsing, help, version
  • Init Command: 12 tests covering full init flow, error handling
  • Config Generator: 10 tests covering AI integration, JSON extraction
  • Config Writer: 8 tests covering file writing, formatting
  • Prompt Builder: 10 tests covering prompt construction
  • Console Utils: 8 tests covering logging, spinner
  • MCP Service: 20+ tests covering config integration

Total: 70+ tests, all passing ✅

Test Scenarios

CLI:

  • ✅ Parse init command with options
  • ✅ Parse help and version commands
  • ✅ Handle unknown commands
  • ✅ Default to current directory

Init Command:

  • ✅ Full init flow (analyze → generate → write)
  • ✅ API key validation
  • ✅ Existing config handling
  • ✅ Error handling (analysis failure, generation failure, write failure)

Config Generator:

  • ✅ Extract JSON from markdown code blocks
  • ✅ Extract JSON from raw response
  • ✅ Validate generated config
  • ✅ Handle API errors

Config Writer:

  • ✅ Write JS format with JSDoc
  • ✅ Write JSON format
  • ✅ Find existing config files
  • ✅ Handle write errors

MCP Service:

  • ✅ Config resource reading
  • ✅ Get project config tool
  • ✅ Project context in prompts
  • ✅ Language setting in parse_mode

🎯 Benefits

1. Low Barrier to Entry

Single command (npx codingbuddy init) to get started. No manual configuration needed.

2. Intelligent Configuration

AI understands project characteristics and generates appropriate settings based on actual project state.

3. Transparency

Clear progress indication and error messages. Users can see what's happening at each step.

4. Customization

Generated config can be manually edited after generation. Users have full control.

5. MCP Integration

Config is automatically used by MCP server to improve AI responses with project context.

📖 Usage Example

# Initialize config in current directory
$ npx codingbuddy init

🔍 Analyzing project...
  ✓ package.json found
  ✓ TypeScript project detected
  ✓ React + Next.js stack confirmed
  ✓ Next.js App Router pattern identified

🤖 AI is generating configuration...

✅ codingbuddy.config.js created!

Please review the generated configuration.
# Initialize with JSON format
$ npx codingbuddy init --format json

# Initialize in specific directory
$ npx codingbuddy init ./my-project

# Overwrite existing config
$ npx codingbuddy init --force

# Use custom API key
$ npx codingbuddy init --api-key sk-...

🔗 Related Documentation

📝 Design Decisions

Why Anthropic Claude API?

  • High Quality: Claude generates well-structured, accurate configs
  • Schema Understanding: Better at following complex schemas
  • Reliability: Consistent output format

Why Two Output Formats?

  • JavaScript: More flexible (can use dynamic values, comments)
  • JSON: Simpler, more portable, easier to parse programmatically

Why Separate Modules?

  • Separation of Concerns: Each module has a single responsibility
  • Testability: Easy to test each component independently
  • Reusability: Components can be used outside CLI if needed

Why Console Utilities?

  • User Experience: Clear progress indication reduces anxiety
  • Debugging: Colored output helps identify issues quickly
  • Professional: Polished CLI experience encourages adoption

Why MCP Integration?

  • Immediate Value: Config is used right away by MCP server
  • Context Awareness: AI responses include project context
  • Language Support: Response language matches project setting

✅ Acceptance Criteria

  • npx codingbuddy init command works
  • Project analysis results sent to AI
  • AI response converted to config file
  • Progress indication (spinner, logs)
  • Handle existing config file (overwrite confirmation)
  • Support JS and JSON output formats
  • Comprehensive test coverage
  • MCP service integration

@JeremyDev87 JeremyDev87 self-assigned this Dec 19, 2025
- Add CLI with init command for automatic config generation
- Use Anthropic Claude API to generate config from project analysis
- Support JS and JSON output formats
- Integrate ConfigService into MCP service (resources, tools, prompts)
- Add console utilities and comprehensive tests

Enables  to auto-generate codingbuddy.config.js

close #22
@JeremyDev87 JeremyDev87 marked this pull request as ready for review December 19, 2025 02:04
@JeremyDev87 JeremyDev87 merged commit 5f0fa81 into master Dec 19, 2025
2 checks passed
@JeremyDev87 JeremyDev87 deleted the feat/22 branch December 21, 2025 15:31
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

CLI Init Command

2 participants