Skip to content

Ethical-AI-Syndicate/chroma-coder

Repository files navigation

ChromaCoder

TypeScript Tests Coverage License Node.js

The Deterministic AI Engineering Interface (DAEI) for the Agentic Era. Chroma-Coder is a high-performance terminal CLI for precise AI code generation, featuring auditable execution traces, composable pipes, and strict type safety across multi-model providers.

Why ChromaCoder?

The Problem: AI coding tools often lack precision, auditability, and enterprise-grade reliability. Engineers need deterministic outputs, not black-box magic.

Our Solution: ChromaCoder provides:

  • Deterministic AI Engineering - Type-safe, predictable code generation
  • Auditable Execution - Complete traces of every AI interaction
  • Production Resilience - Circuit breakers, retries, graceful degradation
  • Multi-Provider Support - Works with Anthropic Claude and OpenRouter models

Real-World Applications

✅ Use Case: Enterprise Code Generation

# Generate with full audit trail
chromacoder "Create a TypeScript API for user authentication"
# Output: Complete, type-safe code with execution trace

# Verify what was generated
chromacoder --trace last
# Shows: Prompt, model used, tokens consumed, and generated code hash

Result: Enterprise-grade code generation with full provenance and reproducibility.

✅ Use Case: Batch Processing

# Process multiple files with consistency
chromacoder --batch "refactor/*.ts" --template enterprise-pattern
# Applies consistent refactoring across codebase

# Generate verification report
chromacoder --report refactor-results.json

Result: Scalable code transformations with guaranteed consistency and reporting.

✅ Use Case: CI/CD Integration

# As part of your pipeline
name: AI Code Review
on: [push]
jobs:
  review:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - name: ChromaCoder Review
        run: |
          chromacoder --review ./src --output review.json
          chromacoder --verify-review review.json

Result: Automated code review with deterministic, verifiable AI analysis.

Key Features

🎯 Deterministic AI Engineering

  • Type-Safe Generation - All outputs validated with Zod schemas
  • Composable Pipes - Chain multiple AI operations predictably
  • Hash Verification - Verify code integrity with SHA-256 fingerprints
  • Execution Traces - Complete audit trail of all AI interactions

🛡️ Enterprise Resilience

  • Circuit Breakers - Prevent cascade failures during outages
  • Exponential Backoff - Intelligent retry with 1s→2s→4s→8s progression
  • Graceful Degradation - System continues operating during partial failures
  • Structured Logging - Component-level logs with JSON/text output

🔄 Multi-Provider Architecture

  • Anthropic Claude - Native support for Claude models
  • OpenRouter - Access to 100+ models including GPT-4, Llama, Mixtral
  • Auto-Detection - Intelligent provider selection based on availability
  • Model Switching - Change models mid-session without losing context

📊 Production Monitoring

  • 92.83% Test Coverage - Comprehensive test suite with 256 passing tests
  • Performance Metrics - Token usage, latency, success rates
  • Error Tracking - Structured error reporting with context
  • Session Analytics - Track patterns and optimize usage

Quick Start

Prerequisites: Node.js 18+, pnpm 8+

See Installation below for setup instructions.

# Start a conversation
pnpm start

# Or use headless mode for scripting
pnpm start --headless "Create a REST API with TypeScript and Express"

# With specific model and parameters
pnpm start --headless "Build a React component" \
  --model claude-3-5-sonnet-20241022 \
  --max-tokens 2000 \
  --temperature 0.1

Installation

# Clone and install
git clone https://github.com/Ethical-AI-Syndicate/chroma-coder
cd chroma-coder
pnpm install

# Configure your API keys
cp .env.example .env
# Edit .env with your preferred provider

# Build and run
pnpm build
pnpm start

Prerequisites

  • Node.js 18+
  • pnpm 8+
  • API key for Anthropic or OpenRouter

Environment Configuration

# Copy example environment file
cp .env.example .env

Edit .env with your API keys:

# Anthropic API Key (https://console.anthropic.com/)
ANTHROPIC_API_KEY=sk-ant-...

# OR OpenRouter API Key (https://openrouter.ai/)
OPENROUTER_API_KEY=sk-or-...

# Optional: Specify model
CHROMA_MODEL=claude-3-5-sonnet-20241022

# Optional: Configure logging
LOG_LEVEL=info  # debug | info | warn | error
LOG_FORMAT=text # text | json

Architecture Overview

┌─────────────────┐    ┌──────────────────┐    ┌─────────────────┐
│   Terminal UI  │    │   Core Engine   │    │  AI Providers   │
│               │    │                  │    │                 │
│ • Ink React   │───▶│ • Sessions      │───▶│ • Anthropic     │
│ • History     │    │ • Validation    │    │ • OpenRouter   │
│ • Shortcuts   │    │ • Retry Logic   │    │ • Custom APIs   │
└─────────────────┘    └──────────────────┘    └─────────────────┘
         │                       │                       │
         ▼                       ▼                       ▼
┌─────────────────┐    ┌──────────────────┐    ┌─────────────────┐
│   State Mgmt   │    │   Persistence   │    │   Monitoring    │
│               │    │                  │    │                 │
│ • Redux-like  │    │ • File Storage  │    │ • Structured    │
│ • Immutable   │    │ • History      │    │   Logging      │
│ • Traceable   │    │ • Snapshots    │    │ • Metrics      │
└─────────────────┘    └──────────────────┘    └─────────────────┘

Configuration

Environment Variables

Variable Required Default Description
ANTHROPIC_API_KEY No* - Anthropic API key for Claude models
OPENROUTER_API_KEY No* - OpenRouter API key for various models
CHROMA_MODEL No Auto-detected Model to use (e.g., claude-3-5-sonnet-20241022)
LOG_LEVEL No info Logging level: debug, info, warn, error
LOG_FORMAT No text Log output format: text or json
NO_COLOR No - Set to 1 to disable colored output

*At least one API key is required

Model Selection

The application automatically detects which LLM provider to use:

# Prefer Anthropic if available
ANTHROPIC_API_KEY=sk-ant-... pnpm start

# Fall back to OpenRouter
OPENROUTER_API_KEY=sk-or-... pnpm start

# Override with specific model
CHROMA_MODEL=anthropic/claude-3-opus-20240229 pnpm start

Advanced Usage

Composable Pipes

Chain multiple AI operations:

import { chromacoder } from 'chroma-coder';

const pipeline = chromacoder
  .pipe('analyze-code', { language: 'typescript' })
  .pipe('generate-tests', { coverage: '90%' })
  .pipe('optimize-performance', { target: 'sub-100ms' });

await pipeline.execute('./src/component.ts');

Execution Traces

Verify and audit AI interactions:

# View last execution trace
pnpm chromacoder --trace last

# Export trace for compliance
pnpm chromacoder --export-trace audit-2024-Q1.json

# Verify code integrity
pnpm chromacoder --verify ./src --algorithm sha256

Batch Processing

Process multiple files with consistency:

# Refactor entire directory
pnpm chromacoder --batch refactor ./src --pattern "*.ts" \
  --template enterprise-pattern --output ./refactored

# Generate documentation
pnpm chromacoder --batch docs ./src --format markdown \
  --output ./documentation

Production Features

Error Handling & Resilience

Circuit Breaker Pattern

  • Opens after 5 consecutive failures
  • Prevents thundering herd during outages
  • Automatic recovery after 60-second timeout
  • Half-open state for testing recovery

Retry with Exponential Backoff

  • Automatic retry on network failures and 5xx errors
  • Exponential backoff: 1s → 2s → 4s → 8s (max 10s)
  • Configurable max attempts (default: 3)
  • Structured logging of all retry attempts

Graceful Degradation

  • API failures don't crash the application
  • User-friendly error messages with troubleshooting tips
  • Conversation state preserved across failures
  • Errors added to conversation history for debugging

Validation & Type Safety

Runtime Type Validation with Zod

  • All API requests validated before sending
  • All API responses validated before processing
  • Clear validation error messages with context
  • Type-safe data flows throughout application

Validated Components

  • LLM completion requests (messages, tokens, temperature)
  • API responses (content, usage, model)
  • Configuration (provider, API keys, model names)
  • Generated code (syntax, type checking)

Monitoring & Observability

Structured Logging System

  • Multiple log levels: debug, info, warn, error
  • Component-specific loggers with context
  • Nested logger support for complex workflows
  • Configurable output formats (colored console, JSON)
  • Environment-aware configuration

Performance Metrics

  • Token usage tracking per model and session
  • Latency measurements with percentiles
  • Success/failure rates by operation type
  • Resource utilization (memory, CPU)

Testing

Test Coverage: 92.83%

Component Coverage Tests
Core Conversation 100% 15 tests
Session Processor 98.87% 23 tests
Retry Utility 96.99% 32 tests
Logger 100% 43 tests
LLM Clients 95%+ 45 tests
UI State 97.98% 45 tests
Overall 92.83% 256 tests

Running Tests

# Run all tests
pnpm test

# Run with coverage report
pnpm test:coverage

# Run specific test file
pnpm test retry.test.ts

# Watch mode for development
pnpm test:watch

Development

Project Structure

chroma-coder/
├── src/
│   ├── adapters/           # External adapters
│   │   ├── env/           # Environment configuration
│   │   ├── filesystem/    # File I/O operations
│   │   └── network/       # LLM client implementations
│   ├── cli/               # Command-line interface
│   ├── core/              # Core business logic
│   │   ├── conversation/  # Conversation management
│   │   ├── session/       # Session processing
│   │   ├── utils/         # Utilities (retry, logger)
│   │   └── validation/    # Zod schemas
│   ├── tui/               # Terminal UI components (Ink/React)
│   ├── ui-state/          # State management
│   └── domain/            # Domain types
├── tests/
│   └── unit/              # Unit tests
├── docs/                  # Additional documentation
└── dist/                  # Compiled output

Development Scripts

# Development mode with auto-reload
pnpm dev

# Run tests
pnpm test

# Run tests with coverage
pnpm test:coverage

# Run tests in watch mode
pnpm test:watch

# Build for production
pnpm build

# Type checking
pnpm type-check

# Lint code
pnpm lint

# Format code
pnpm format

Architecture

ChromaCoder follows clean architecture principles:

  1. Domain Layer - Pure business logic and types
  2. Core Layer - Application logic (conversation, session management)
  3. Adapters Layer - External integrations (LLM clients, file I/O)
  4. UI Layer - Terminal interface (Ink components)

Key patterns:

  • Dependency Injection - LLM clients injected into session processor
  • Adapter Pattern - Unified interface for multiple LLM providers
  • Factory Pattern - LLM client factory for provider selection
  • State Management - Redux-like reducer pattern for UI state

What ChromaCoder is NOT

  • Not a Web IDE - Terminal-first design for developer efficiency
  • Not a Magic Tool - Deterministic, verifiable code generation
  • Not Language Specific - Works with any programming language
  • Not Closed Source - MIT license with full transparency

Contributing

Development Setup

# Fork and clone
git clone https://github.com/your-username/chroma-coder
cd chroma-coder

# Install dependencies
pnpm install

# Start development
pnpm dev

# Run tests
pnpm test

# Build for production
pnpm build

Contribution Guidelines

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Write tests for new functionality
  4. Ensure tests pass (pnpm test)
  5. Check code coverage (pnpm test:coverage)
  6. Format code (pnpm format)
  7. Commit changes (git commit -m 'Add amazing feature')
  8. Push to branch (git push origin feature/amazing-feature)
  9. Open a Pull Request

Code Standards

  • TypeScript - Strict mode enabled
  • Test Coverage - Maintain >90% coverage
  • ESLint - Follow existing linting rules
  • Prettier - Use project formatting config
  • Conventional Commits - Use semantic commit messages

Testing Requirements

  • Unit tests for all new features
  • Minimum 80% coverage for new code
  • All existing tests must pass
  • Integration tests for API interactions (when applicable)

Troubleshooting

Common Issues

API Key Not Found

Error: OpenRouter client not configured

Solution: Ensure API key is set in .env file or environment variable

Network Timeouts

  • Application automatically retries with exponential backoff
  • Check internet connection
  • Verify API service status

Model Not Found

Error: Model 'xyz' not found

Solution: Check model name is correct for your provider

  • Anthropic: claude-3-5-sonnet-20241022, claude-3-opus-20240229
  • OpenRouter: anthropic/claude-3-5-sonnet, openai/gpt-4

Import Errors

Error: Cannot find module

Solution: Run pnpm install and pnpm build

Debug Mode

Enable debug logging to troubleshoot issues:

LOG_LEVEL=debug pnpm start

This outputs detailed information about:

  • API requests and responses
  • Retry attempts
  • Validation errors
  • Internal state changes

Roadmap

  • Integration tests for LLM providers
  • End-to-end tests for user workflows
  • Transactional session storage with rollback
  • Multi-turn conversation optimization
  • Streaming response support in TUI
  • Plugin system for custom commands
  • Configuration file support (.chromacoderrc)
  • Session export/import functionality

License

MIT License - see LICENSE file for details

Support & Community


Built by Ethical AI Syndicate - Creating deterministic, auditable AI engineering tools.

About

The Deterministic AI Engineering Interface (DAEI) for the Agentic Era. Chroma-Coder is a high-performance terminal CLI for precise AI code generation, featuring auditable execution traces, composable pipes, and strict type safety across multi-model providers. Built by engineers, for engineers.

Resources

License

Contributing

Security policy

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors