npm package: @orchestrator-cli/core
Description: Sistema de Orquestracao Autonomo - Clean Architecture + Claude Code 2.0
Author: Cmac
Latest version: 1.3.0
Deprecated: Migrate to @orchestrator-claude/cli. See https://github.com/orchestrator/orchestrator/blob/main/docs/migration-v1.4.md

# Orchestrator

[![Build Status](https://img.shields.io/badge/build-passing-brightgreen)](.)
[![Tests](https://img.shields.io/badge/tests-4200%2B%20passing-brightgreen)](.)
[![Coverage](https://img.shields.io/badge/coverage-88%25-brightgreen)](.)
[![Version](https://img.shields.io/badge/version-0.9.0-blue)](.)
[![TypeScript](https://img.shields.io/badge/TypeScript-5.9-blue)](https://www.typescriptlang.org/)
[![License](https://img.shields.io/badge/license-MIT-blue)](LICENSE)
[![Docker](https://img.shields.io/badge/docker-ready-blue)](https://www.docker.com/)

Sistema de Orquestração Autônomo para desenvolvimento de software com Claude Code 2.0 e Perplexity AI.

## Overview

O Orchestrator é um sistema que coordena workflows de desenvolvimento de software usando agentes de IA. Ele implementa uma arquitetura limpa (Clean Architecture) com 5 camadas e suporta múltiplos tipos de workflows:

- **Feature Development** - Desenvolvimento completo de novas funcionalidades
- **Bug Fix** - Correção de bugs com análise e solução
- **Refactoring** - Refatoração de código existente
- **Emergency Debug** - Debug urgente de problemas críticos

## Features

- **🎯 Ping-Pong Híbrido Pattern (v0.6.0)** - Resolução de LIM-001 (context window bloat)
  - Orchestrator como dispatcher (cria pendingActions)
  - Múltiplas invocações com contexto isolado (< 12k tokens por agent)
  - **40%+ token savings** em features complexas
  - Workflow resumable após crashes
  - [📖 Ver Guia Completo](./docs/ping-pong-guide.md)
- **Orchestrator v2 (v0.7.0)** - Arquitetura Determinística com State Machine
  - Workflows configuráveis via JSON (feature-development, bug-fix, refactoring)
  - State machine baseada em configuração (WorkflowStateMachineV2)
  - Quality gates dinâmicos
  - Transições validadas
  - MCP Tools v2 determinísticos
  - [📖 Ver Guia Rápido](./docs/orchestrator-v2-quickstart.md)
- **🚀 REST API Ecosystem (v0.9.0 - RFC-001)** - Complete HTTP API
  - Local-first mode (Model A) - File-based storage, API key auth
  - Projects, Workflows, Agents, Artifacts REST endpoints
  - OpenAPI/Swagger documentation
  - Docker deployment ready
  - [📖 API Documentation](./docs/api/README.md)
- **🛡️ Governance Hooks (v0.12.0 - RFC-002 Phase 3)** - Automatic quality enforcement
  - **Gate Enforcement** - Blocks file modifications until phase gates pass
  - **Human-in-the-Loop** - Requires approval before IMPLEMENT phase
  - **Artifact Validation** - Validates spec.md, plan.md, tasks.md against schemas
  - SDK-First architecture with ClaudeHook integration
  - Domain-driven hook handlers (IHookHandler)
  - [📖 See Code Example](#governance-hooks-example)
- **Workflow Orchestration** - Coordenação automática de fases de desenvolvimento
- **Workflow Customization** - Define custom workflows via JSON configuration
  - Custom phases and gates
  - Custom agent mapping
  - Tier-based priority system (custom > user > built-in)
  - Hot-reload support
- **Knowledge Base** - Base de conhecimento integrada com SOLID, Clean Architecture, Clean Code
- **Perplexity Integration** - Pesquisa de informações técnicas em tempo real
- **Git Integration** - Checkpoints automáticos e controle de versão
- **MCP Servers** - Integração com Claude Code via Model Context Protocol
  - **MCP Thin Client (v1.0.0 - RFC-001 Phase 3)** - Lightweight MCP server forwarding to REST API
  - Zero business logic in MCP layer (thin client pattern)
  - 18 tools available for Claude Code integration
  - [📖 MCP Server Documentation](./packages/mcp-server/README.md)
- **Artifact Validation** - Validação automática de artefatos gerados
- **Phase Gates** - Controle de qualidade entre fases

## Installation

### Using NPM (Recommended)

```bash
# Install globally for CLI access
npm install -g @orchestrator/cli

# Or as project dependency
npm install @orchestrator/cli
```

### Using Docker (For REST API)

```bash
# Option 1: Docker Compose (recommended)
docker-compose up -d

# Option 2: Direct docker run
docker pull orchestrator/api:latest
docker run -d -p 3001:3001 -v $(pwd):/workspace orchestrator/api:latest

# Check API health
curl http://localhost:3001/api/v1/health

# Access Swagger UI
open http://localhost:3001/documentation
```

### From Source (Development)

```bash
git clone https://github.com/orchestratorAII/orchestrator.git
cd orchestrator
npm install
npm run build
npm link  # Makes 'orchestrator' command available globally
```

Add to your `package.json`:

```json
{
  "dependencies": {
    "@orchestrator/cli": "^0.9.0"
  }
}
```

For detailed installation instructions, see [docs/INSTALLATION.md](./docs/INSTALLATION.md).

For detailed installation instructions, see [docs/INSTALLATION.md](./docs/INSTALLATION.md).

## Getting Started

### Prerequisites

- Node.js >= 18.0.0
- npm >= 9.0.0
- Git
- Docker + Docker Compose (optional, for REST API)

### Quick Start

```bash
# Install globally
npm install -g @orchestrator/cli

# Initialize a new project
orchestrator init my-project --template api

# Navigate to project
cd my-project

# Start developing with Claude Code
claude "Create a REST API for user management"
```

### REST API Quick Start

```bash
# Start API server
docker-compose up -d

# Register a project
curl -X POST http://localhost:3001/api/v1/projects \
  -H "Content-Type: application/json" \
  -d '{"name": "my-project", "rootPath": "/workspace/my-project"}'

# Create a workflow
curl -X POST http://localhost:3001/api/v1/workflows \
  -H "Content-Type: application/json" \
  -d '{"type": "feature_development", "prompt": "Create auth API"}'
```

### Creating a New Project

```bash
# Basic initialization
orchestrator init my-project

# With a specific template
orchestrator init my-api --template api
orchestrator init my-app --template frontend
orchestrator init my-cli --template cli

# Skip git and npm install
orchestrator init my-project --skip-git --skip-install

# Interactive wizard mode
orchestrator init my-project --interactive

# Navigate to your project
cd my-project

# Install dependencies and build
npm install
npm run build

# Run tests
npm test
```

### Migrating Existing Projects

To add Orchestrator to an existing project:

```bash
# Navigate to your project
cd my-existing-project

# Run migration (preview mode)
orchestrator migrate --dry-run

# Apply migration
orchestrator migrate

# With backup and force
orchestrator migrate --backup --force
```

### Configuration

1. **Environment Variables**

Create a `.env` file in the project root:

```bash
# Perplexity API (required for research integration)
PERPLEXITY_API_KEY=your-api-key-here

# Node Environment
NODE_ENV=development

# Logging Level (debug, info, warn, error)
LOG_LEVEL=info
```

2. **MCP Configuration**

The `.mcp.json` file configures the MCP servers:

```json
{
  "mcpServers": {
    "orchestrator-tools": {
      "command": "node",
      "args": ["dist/mcp/orchestrator-server.js"]
    },
    "perplexity": {
      "command": "node",
      "args": ["dist/mcp/perplexity-server.js"]
    },
    "knowledge-base": {
      "command": "node",
      "args": ["dist/mcp/kb-server.js"]
    }
  }
}
```

## Prerequisites

**IMPORTANT:** The CLI is a thin client that requires the REST API server to be running.

### Starting the API Server

```bash
# Terminal 1: Start API server
npm run api:start

# Or using Docker
docker-compose up -d
```

Once the API server is running, you can use the CLI commands below.

## Usage

### CLI Commands

#### Project Initialization

```bash
# Initialize new project (minimal template)
orchestrator init my-project

# Initialize with specific template
orchestrator init my-api --template api

# Initialize with preset
orchestrator init my-project --template frontend --preset strict

# Interactive wizard mode
orchestrator init --interactive

# Skip optional steps
orchestrator init my-project --skip-git --skip-install

# View all options
orchestrator init --help
```

**Available Templates:**
- `minimal` - Basic TypeScript project with minimal setup
- `api` - REST API project with routing and controllers
- `frontend` - Frontend project with modern build tools
- `cli` - CLI application template
- `monorepo` - Monorepo structure with workspaces

**Available Presets:**
- `strict` - Maximum governance and quality rules
- `moderate` - Balanced rules (recommended)
- `minimal` - Minimal rules for maximum flexibility

#### Project Migration

```bash
# Migrate existing project
orchestrator migrate

# Preview changes (dry-run)
orchestrator migrate --dry-run

# Create backup before migration
orchestrator migrate --backup

# Force overwrite existing files
orchestrator migrate --force

# Migrate with specific preset
orchestrator migrate --preset strict

# Verbose output
orchestrator migrate --verbose
```

### Workflow Management (via MCP)

Workflow orchestration is managed through **MCP servers** integrated with Claude Code, not via CLI commands. This enables autonomous workflow execution within your AI-assisted development environment.

**Available MCP Tools:**

```bash
# In Claude Code, use MCP tools directly:
mcp__orchestrator-tools__detectWorkflow    # Detect workflow type
mcp__orchestrator-tools__advancePhase      # Advance to next phase
mcp__orchestrator-tools__evaluateGate      # Evaluate phase gates
mcp__orchestrator-tools__validateArtifact  # Validate artifacts
mcp__orchestrator-tools__createCheckpoint  # Create checkpoints
mcp__orchestrator-tools__getStatus         # Get workflow status

mcp__knowledge-base__search                # Search knowledge base
mcp__knowledge-base__getDocument           # Get specific document
mcp__knowledge-base__getConstitution       # Get project constitution

mcp__perplexity__search                    # Research with Perplexity AI
```

See [CLAUDE.md](./CLAUDE.md) for detailed workflow instructions.

### REST API Usage

```bash
# Register a project
curl -X POST http://localhost:3000/api/v1/projects \
  -H "Content-Type: application/json" \
  -d '{
    "name": "my-app",
    "path": "/path/to/project",
    "description": "My awesome project"
  }'

# Create a feature development workflow
curl -X POST http://localhost:3000/api/v1/workflows \
  -H "Content-Type: application/json" \
  -d '{
    "type": "feature-development",
    "prompt": "Implement user authentication with JWT",
    "projectId": "proj_123"
  }'

# Check workflow status
curl http://localhost:3000/api/v1/workflows/wf_123

# List artifacts
curl http://localhost:3000/api/v1/artifacts?workflowId=wf_123
```

See [API Documentation](./docs/api/README.md) for complete REST API reference.

### Programmatic Usage

```typescript
import { CompositionRoot } from '@orchestrator/core';

// Create the orchestrator with all dependencies
const { orchestrator } = await CompositionRoot.create();

// Start a new workflow
const result = await orchestrator.start('Implement user login feature');

if (result.isOk()) {
  console.log('Workflow started:', result.value.id);

  // Get current status
  const status = await orchestrator.getStatus();
  console.log('Current phase:', status?.currentPhase);

  // Advance to next phase
  const advanceResult = await orchestrator.advance();
}
```

### Common Use Cases

#### Starting a New Project

```bash
# Interactive setup (recommended for first-time users)
orchestrator init --interactive

# Quick setup with defaults
orchestrator init my-app --template minimal --yes

# Full-featured API project
orchestrator init my-api --template api --preset moderate

# Frontend project with strict quality rules
orchestrator init my-frontend --template frontend --preset strict
```

#### Adding Orchestrator to Existing Project

```bash
# Step 1: Preview what will change
orchestrator migrate --dry-run

# Step 2: Create backup before migrating
orchestrator migrate --backup

# Step 3: Apply migration
# (or combine: orchestrator migrate --backup --verbose)
```

#### Working with Templates

```bash
# Browse available templates
orchestrator templates list

# Learn about a specific template
orchestrator templates info api

# Initialize project with that template
orchestrator init my-api-project --template api
```

### Workflow Phases

Each workflow type has specific phases:

| Workflow | Phases |
|----------|--------|
| Feature Development | research → specify → plan → implement → validate |
| Bug Fix | specify → plan → implement → validate |
| Refactoring | plan → implement → validate |
| Emergency Debug | implement → validate |

### Artifacts

The system generates artifacts in `.orchestrator/artifacts/`:

```
.orchestrator/
├── artifacts/
│   ├── specify/      # Specifications
│   ├── plan/         # Plans and architecture
│   ├── implement/    # Implementation details
│   ├── validate/     # Validation reports
│   └── research/     # Research results
├── workflows/        # Workflow state
├── checkpoints/      # Git checkpoints
└── memory/
    └── knowledge-base/  # KB documents
```

## Architecture

The project follows Clean Architecture with 5 layers:

```
┌─────────────────────────────────────────────┐
│           Presentation Layer                │
│     (CLI, Hooks, Skills, Entry Points)      │
├─────────────────────────────────────────────┤
│           Orchestration Layer               │
│  (OrchestratorEngine, WorkflowExecutor)     │
├─────────────────────────────────────────────┤
│           Application Layer                 │
│      (Use Cases, DTOs, Ports)               │
├─────────────────────────────────────────────┤
│           Infrastructure Layer              │
│  (Repositories, Adapters, MCP Servers)      │
├─────────────────────────────────────────────┤
│             Domain Layer                    │
│   (Entities, Value Objects, Services)       │
└─────────────────────────────────────────────┘
```

### Key Components

- **Domain**: Core business logic (Workflow, Artifact, Phase, Agent)
- **Application**: Use cases and ports (StartWorkflow, ValidateArtifact)
- **Infrastructure**: Technical implementations (FileRepository, GitAdapter, PerplexityClient)
- **Presentation**: User interfaces (CLI commands, Hook handlers, Skill handlers)
- **Orchestration**: Workflow coordination (OrchestratorEngine, WorkflowExecutor, AgentInvoker)

## Development

### Running Tests

```bash
# Run all tests
npm test

# Run tests in watch mode
npm run test:watch

# Run with coverage
npm run test:coverage

# Run specific test file
npm test -- tests/domain/entities/Workflow.test.ts
```

### Code Quality

```bash
# Type checking
npm run typecheck

# Linting
npm run lint
npm run lint:fix

# Formatting
npm run format
npm run format:check
```

### Project Structure

```
src/
├── domain/           # Domain layer
│   ├── entities/     # Business entities
│   ├── value-objects/# Value objects
│   ├── services/     # Domain services
│   └── repositories/ # Repository interfaces
├── application/      # Application layer
│   ├── use-cases/    # Use case implementations
│   ├── ports/        # Port interfaces
│   └── dtos/         # Data transfer objects
├── infrastructure/   # Infrastructure layer
│   ├── persistence/  # File-based repositories
│   ├── adapters/     # External adapters
│   ├── external/     # External services
│   ├── mcp/          # MCP servers
│   └── di/           # Dependency injection
├── presentation/     # Presentation layer
│   ├── cli/          # CLI commands
│   ├── hooks/        # Hook handlers
│   └── skills/       # Skill handlers
├── orchestration/    # Orchestration layer
│   ├── OrchestratorEngine.ts
│   ├── WorkflowExecutor.ts
│   └── AgentInvoker.ts
└── shared/           # Shared utilities
    └── types/        # Common types
```

## API Reference

### OrchestratorEngine

```typescript
class OrchestratorEngine {
  // Start a new workflow
  start(prompt: string): Promise<Result<Workflow, OrchestratorError>>;

  // Advance to the next phase
  advance(): Promise<Result<PhaseResult, OrchestratorError>>;

  // Abort the current workflow
  abort(reason: string): Promise<Result<void, OrchestratorError>>;

  // Get current workflow status
  getStatus(): Promise<WorkflowStatus | null>;
}
```

### PerplexityClient

```typescript
class PerplexityClient {
  // Search for information
  search(query: string, options?: SearchOptions): Promise<Result<SearchResult, PerplexityError>>;

  // Get content about a topic
  getTopicContent(topic: string): Promise<Result<TopicContent, PerplexityError>>;

  // Check API availability
  isAvailable(): Promise<boolean>;
}
```

### FileArtifactRepository

```typescript
class FileArtifactRepository implements IArtifactRepository {
  save(artifact: Artifact, workflowId?: string): Promise<void>;
  findById(id: string): Promise<Artifact | null>;
  findByType(type: ArtifactType): Promise<Artifact[]>;
  findByPhase(phase: string): Promise<Artifact[]>;
  exists(id: string): Promise<boolean>;
  delete(id: string): Promise<void>;
}
```

## Governance Hooks Example

The Orchestrator includes governance hooks that automatically enforce quality gates, require human approval before code generation, and validate artifacts.

### What are Governance Hooks?

Governance hooks are automatic quality enforcement mechanisms that intercept agent actions (like Write, Edit, Bash) and ensure:
1. **Gate Enforcement** - Phase requirements are met before file modifications
2. **Human Approval** - User reviews artifacts before IMPLEMENT phase
3. **Artifact Validation** - Generated artifacts meet schema requirements

### Architecture

```
SDKAgentExecutor (Application)
    ↓ registers
HookAdapter (Application)
    ↓ converts
IHookHandler (Domain)
    ├─ GateHookHandler
    ├─ ApprovalHookHandler
    └─ ArtifactValidatorHookHandler
```

### Example: Registering Custom Hooks

```typescript
import { SDKAgentExecutor } from '@orchestrator-cli/core';
import { HookAdapter } from '@orchestrator-cli/core/adapters';
import { GateHookHandler, ApprovalHookHandler } from '@orchestrator-cli/core/domain';

// 1. Create hook handlers
const gateHandler = new GateHookHandler(gateEvaluatorService);
const approvalHandler = new ApprovalHookHandler(workflowStateService);

// 2. Register handlers with adapter
const hookAdapter = new HookAdapter();
hookAdapter.register(gateHandler);
hookAdapter.register(approvalHandler);

// 3. Pass adapter to executor
const executor = new SDKAgentExecutor(
  apiKey,
  agentDefinitionAdapter,
  hookAdapter // <-- Hooks enabled
);

// 4. Execute agent with automatic governance
const result = await executor.execute(agent, workflow, prompt, options);
// Hooks will automatically:
// - Block Write/Edit if gates fail
// - Ask for approval during IMPLEMENT phase
// - Validate artifacts after creation
```

### How Hooks Work

#### Gate Enforcement (GateHookHandler)

Prevents file modifications until phase gates pass:

```typescript
// Before this hook:
// Agent tries: Write to /src/feature.ts
// Gate status: SPECIFY phase incomplete

// GateHookHandler intercepts:
{
  decision: 'deny',
  reason: 'Gate not passed: Missing acceptance criteria, Incomplete specification'
}

// After fixing issues:
// Gate status: SPECIFY phase complete ✅
// GateHookHandler allows Write ✅
```

#### Human Approval (ApprovalHookHandler)

Requires user approval before IMPLEMENT phase:

```typescript
// Before this hook:
// Agent tries: Write to /src/index.ts during IMPLEMENT
// Approval status: Not approved

// ApprovalHookHandler intercepts:
{
  decision: 'ask',
  reason: 'Implementation requires human approval. Review spec.md, plan.md, and tasks.md before proceeding.'
}

// User reviews artifacts and approves
// ApprovalHookHandler allows Write ✅
```

#### Artifact Validation (ArtifactValidatorHookHandler)

Validates generated artifacts against schemas:

```typescript
// After this hook:
// Agent executed: Write to /.orchestrator/artifacts/specify/spec.md

// ArtifactValidatorHookHandler validates:
const artifact = Artifact.create({ type: 'specification', content: '...' });
const result = await artifactValidator.validate(artifact);

// If invalid:
{
  decision: 'deny',
  reason: 'Artifact validation failed: Missing metadata section, Invalid frontmatter format'
}

// If valid: { decision: 'allow' } ✅
```

### Creating Custom Hooks

Implement the `IHookHandler` interface:

```typescript
import type { IHookHandler, HookContext, HookDecision } from '@orchestrator-cli/core/domain';

export class CustomSecurityHook implements IHookHandler {
  readonly name = 'security-check';
  readonly hookTypes = ['PreToolUse'] as const;
  readonly toolPatterns = ['Write', 'Edit', 'Bash'];

  async evaluate(context: HookContext): Promise<HookDecision> {
    // Custom logic
    if (context.input.file_path?.includes('password')) {
      return {
        decision: 'deny',
        reason: 'Cannot modify password files'
      };
    }

    return { decision: 'allow' };
  }
}

// Register your custom hook
hookAdapter.register(new CustomSecurityHook());
```

### Hook Execution Order

Hooks execute in registration order and short-circuit on first deny/ask:

```typescript
// Registration order:
hookAdapter.register(gateHandler);       // 1. Gate check
hookAdapter.register(approvalHandler);   // 2. Approval check (if gate passes)
hookAdapter.register(validatorHandler);  // 3. Validation (PostToolUse)

// Execution:
// If gateHandler denies → stop, don't run approvalHandler
// If approvalHandler asks → stop, don't allow action
// If both allow → action proceeds → validatorHandler validates result
```

### Files Reference

- **Domain Interfaces**: `src/domain/interfaces/IHookHandler.ts`
- **Hook Handlers**:
  - `src/domain/services/GateHookHandler.ts`
  - `src/domain/services/ApprovalHookHandler.ts`
  - `src/domain/services/ArtifactValidatorHookHandler.ts`
- **Adapter**: `src/application/adapters/HookAdapter.ts`
- **Integration**: `src/application/services/SDKAgentExecutor.ts`

### Benefits

- **Automatic Quality Enforcement** - No manual gate checks needed
- **Fail-Safe** - Prevents invalid implementations before they start
- **Human-in-the-Loop** - User control over expensive IMPLEMENT phase
- **Extensible** - Add custom hooks for project-specific rules
- **Testable** - All hooks are unit-tested with 90%+ coverage

## Contributing

1. Fork the repository
2. Create a feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request

### Coding Standards

- Follow TypeScript strict mode
- Write tests for all new code
- Maintain >80% code coverage
- Follow Clean Architecture principles
- Use Result types for error handling

## License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

## Acknowledgments

- [Clean Architecture](https://blog.cleancoder.com/uncle-bob/2012/08/13/the-clean-architecture.html) by Robert C. Martin
- [Claude Code](https://claude.ai) by Anthropic
- [Perplexity AI](https://www.perplexity.ai) for research integration