diff --git a/docs/comprehensive/README.md b/docs/comprehensive/README.md new file mode 100644 index 0000000..afb4c06 --- /dev/null +++ b/docs/comprehensive/README.md @@ -0,0 +1,226 @@ +# CHORUS Complete Documentation + +**Version:** 1.0.0 +**Generated:** 2025-09-30 +**Status:** Complete comprehensive documentation of CHORUS system + +--- + +## Table of Contents + +### 1. [Architecture Overview](architecture/README.md) +High-level system architecture, design principles, and component relationships + +- [System Architecture](architecture/system-architecture.md) +- [Component Map](architecture/component-map.md) +- [Data Flow](architecture/data-flow.md) +- [Security Architecture](architecture/security.md) +- [Deployment Architecture](architecture/deployment.md) + +### 2. [Command-Line Tools](commands/README.md) +Entry points and command-line interfaces + +- [chorus-agent](commands/chorus-agent.md) - Autonomous agent binary +- [chorus-hap](commands/chorus-hap.md) - Human Agent Portal +- [chorus](commands/chorus.md) - Compatibility wrapper (deprecated) + +### 3. [Core Packages](packages/README.md) +Public API packages in `pkg/` + +#### Execution & AI +- [pkg/execution](packages/execution.md) - Task execution engine and Docker sandboxing +- [pkg/ai](packages/ai.md) - AI provider interfaces and abstractions +- [pkg/providers](packages/providers.md) - Concrete AI provider implementations + +#### Coordination & Distribution +- [pkg/slurp](packages/slurp/README.md) - Distributed coordination system + - [alignment](packages/slurp/alignment.md) - Goal alignment + - [context](packages/slurp/context.md) - Context management + - [distribution](packages/slurp/distribution.md) - Work distribution + - [intelligence](packages/slurp/intelligence.md) - Intelligence layer + - [leader](packages/slurp/leader.md) - Leadership coordination + - [roles](packages/slurp/roles.md) - Role assignments + - [storage](packages/slurp/storage.md) - Distributed storage + - [temporal](packages/slurp/temporal.md) - Time-based coordination +- [pkg/coordination](packages/coordination.md) - Task coordination primitives +- [pkg/election](packages/election.md) - Leader election algorithms +- [pkg/dht](packages/dht.md) - Distributed hash table + +#### Security & Cryptography +- [pkg/crypto](packages/crypto.md) - Encryption and cryptographic primitives +- [pkg/shhh](packages/shhh.md) - Secrets management system +- [pkg/security](packages/security.md) - Security policies and validation + +#### Validation & Compliance +- [pkg/ucxl](packages/ucxl.md) - UCXL validation and enforcement +- [pkg/ucxi](packages/ucxi.md) - UCXI integration + +#### Infrastructure +- [pkg/mcp](packages/mcp.md) - Model Context Protocol implementation +- [pkg/repository](packages/repository.md) - Git repository operations +- [pkg/metrics](packages/metrics.md) - Monitoring and telemetry +- [pkg/health](packages/health.md) - Health check system +- [pkg/config](packages/config.md) - Configuration management +- [pkg/bootstrap](packages/bootstrap.md) - System bootstrapping +- [pkg/pubsub](packages/pubsub.md) - Pub/sub messaging +- [pkg/storage](packages/storage.md) - Storage abstractions +- [pkg/types](packages/types.md) - Common type definitions +- [pkg/version](packages/version.md) - Version information +- [pkg/web](packages/web.md) - Web server and static assets +- [pkg/agentid](packages/agentid.md) - Agent identity management +- [pkg/prompt](packages/prompt.md) - Prompt management +- [pkg/shutdown](packages/shutdown.md) - Graceful shutdown coordination +- [pkg/hmmm](packages/hmmm.md) - HMMM integration +- [pkg/hmmm_adapter](packages/hmmm_adapter.md) - HMMM adapter +- [pkg/integration](packages/integration.md) - Integration utilities +- [pkg/protocol](packages/protocol.md) - Protocol definitions + +### 4. [Internal Packages](internal/README.md) +Private implementation packages in `internal/` + +- [internal/agent](internal/agent.md) - Agent core implementation +- [internal/hapui](internal/hapui.md) - Human Agent Portal UI +- [internal/licensing](internal/licensing.md) - License validation and enforcement +- [internal/logging](internal/logging.md) - Logging infrastructure +- [internal/config](internal/config.md) - Internal configuration +- [internal/runtime](internal/runtime.md) - Runtime environment +- [internal/backbeat](internal/backbeat.md) - Background processing +- [internal/p2p](internal/p2p.md) - Peer-to-peer networking + +### 5. [API Layer](api/README.md) +HTTP API and external interfaces + +- [API Overview](api/overview.md) +- [HTTP Server](api/http-server.md) +- [Setup Manager](api/setup-manager.md) +- [Authentication](api/authentication.md) +- [API Reference](api/reference.md) + +### 6. [Deployment](deployment/README.md) +Deployment configurations and procedures + +- [Docker Setup](deployment/docker.md) +- [Configuration Files](deployment/configuration.md) +- [Environment Variables](deployment/environment.md) +- [Production Deployment](deployment/production.md) +- [Development Setup](deployment/development.md) + +### 7. [Diagrams](diagrams/README.md) +Visual documentation and architecture diagrams + +- [System Overview](diagrams/system-overview.md) +- [Component Interactions](diagrams/component-interactions.md) +- [Sequence Diagrams](diagrams/sequences.md) +- [Data Flow Diagrams](diagrams/data-flow.md) + +--- + +## Quick Reference + +### Key Components + +| Component | Purpose | Status | Location | +|-----------|---------|--------|----------| +| chorus-agent | Autonomous AI agent | Production | cmd/agent | +| Task Execution Engine | Sandboxed code execution | Production | pkg/execution | +| SLURP | Distributed coordination | Production | pkg/slurp | +| UCXL Validation | Compliance enforcement | Production | pkg/ucxl | +| Crypto/SHHH | Security & secrets | Production | pkg/crypto, pkg/shhh | +| HAP | Human Agent Portal | Beta | cmd/hap, internal/hapui | +| MCP Integration | Model Context Protocol | Beta | pkg/mcp | +| DHT | Distributed hash table | Alpha | pkg/dht | +| AI Providers | Multi-provider AI | Production | pkg/ai, pkg/providers | + +### Implementation Status Legend + +- β **Production**: Fully implemented, tested, and production-ready +- πΆ **Beta**: Implemented with core features, undergoing testing +- π· **Alpha**: Basic implementation, experimental +- π΄ **Stubbed**: Interface defined, implementation incomplete +- βͺ **Mocked**: Mock/simulation for development + +### File Statistics + +- **Total Go files**: 221 (excluding vendor) +- **Packages**: 30+ public packages in `pkg/` +- **Internal packages**: 8 in `internal/` +- **Entry points**: 3 in `cmd/` +- **Lines of code**: ~50,000+ (estimated, excluding vendor) + +--- + +## How to Use This Documentation + +### For New Developers +1. Start with [Architecture Overview](architecture/README.md) +2. Read [System Architecture](architecture/system-architecture.md) +3. Explore [Command-Line Tools](commands/README.md) +4. Deep dive into specific [packages](packages/README.md) as needed + +### For Understanding a Specific Feature +1. Check the [Component Map](architecture/component-map.md) +2. Read the specific package documentation +3. Review relevant [diagrams](diagrams/README.md) +4. See [API Reference](api/reference.md) if applicable + +### For Deployment +1. Read [Deployment Overview](deployment/README.md) +2. Follow [Docker Setup](deployment/docker.md) +3. Configure using [Configuration Files](deployment/configuration.md) +4. Review [Production Deployment](deployment/production.md) + +### For Contributing +1. Understand [Architecture Overview](architecture/README.md) +2. Review relevant package documentation +3. Check implementation status in component tables +4. Follow coding patterns shown in examples + +--- + +## Documentation Conventions + +### Code References +- File paths are shown relative to repository root: `pkg/execution/engine.go` +- Line numbers included when specific: `pkg/execution/engine.go:125-150` +- Functions referenced with parentheses: `ExecuteTask()`, `NewEngine()` +- Types referenced without parentheses: `TaskExecutionRequest`, `Engine` + +### Status Indicators +- **[PRODUCTION]** - Fully implemented and tested +- **[BETA]** - Core features complete, testing in progress +- **[ALPHA]** - Basic implementation, experimental +- **[STUB]** - Interface defined, implementation incomplete +- **[MOCK]** - Simulated/mocked for development +- **[DEPRECATED]** - Scheduled for removal + +### Cross-References +- Internal links use relative paths: [See execution engine](packages/execution.md) +- External links use full URLs: [Docker Documentation](https://docs.docker.com/) +- Code references link to specific sections: [TaskExecutionEngine](packages/execution.md#taskexecutionengine) + +### Diagrams +- ASCII diagrams for simple flows +- Mermaid diagrams for complex relationships (convert to SVG with pandoc) +- Sequence diagrams for interactions +- Component diagrams for architecture + +--- + +## Maintenance + +This documentation was generated through comprehensive code analysis and should be updated when: +- New packages are added +- Significant architectural changes occur +- Implementation status changes (stub β alpha β beta β production) +- APIs change or are deprecated + +To regenerate specific sections, see [Documentation Generation Guide](maintenance.md). + +--- + +## Contact & Support + +For questions about this documentation or the CHORUS system: +- Repository: https://gitea.chorus.services/tony/CHORUS +- Issues: https://gitea.chorus.services/tony/CHORUS/issues +- Documentation issues: Tag with `documentation` label \ No newline at end of file diff --git a/docs/comprehensive/architecture/README.md b/docs/comprehensive/architecture/README.md new file mode 100644 index 0000000..6bfbb11 --- /dev/null +++ b/docs/comprehensive/architecture/README.md @@ -0,0 +1,590 @@ +# CHORUS Architecture Overview + +**System:** CHORUS - Container-First P2P Task Coordination +**Version:** 0.5.0-dev +**Architecture Type:** Distributed, Peer-to-Peer, Event-Driven + +--- + +## Table of Contents + +1. [System Overview](#system-overview) +2. [Core Principles](#core-principles) +3. [Architecture Layers](#architecture-layers) +4. [Key Components](#key-components) +5. [Data Flow](#data-flow) +6. [Deployment Models](#deployment-models) +7. [Related Documents](#related-documents) + +--- + +## System Overview + +CHORUS is a **distributed task coordination system** that enables both autonomous AI agents and human operators to collaborate on software development tasks through a peer-to-peer network. The system provides: + +### Primary Capabilities + +- **Autonomous Agent Execution**: AI agents that can execute code tasks in isolated Docker sandboxes +- **Human-Agent Collaboration**: Human Agent Portal (HAP) for human participation in agent networks +- **Distributed Coordination**: P2P mesh networking with democratic leader election +- **Context Addressing**: UCXL (Universal Context Addressing) for immutable decision tracking +- **Secure Execution**: Multi-layer sandboxing with Docker containers and security policies +- **Collaborative Reasoning**: HMMM protocol for meta-discussion and consensus building +- **Encrypted Storage**: DHT-based encrypted storage for sensitive data + +### System Philosophy + +CHORUS follows these key principles: + +1. **Container-First**: All configuration via environment variables, no file-based config +2. **P2P by Default**: No central server; agents form democratic mesh networks +3. **Zero-Trust Security**: Every operation validated, credentials never stored in containers +4. **Immutable Decisions**: All agent decisions recorded in content-addressed storage +5. **Human-in-the-Loop**: Humans as first-class peers in the agent network + +--- + +## Core Principles + +### 1. Container-Native Architecture + +``` +βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ +β CHORUS Container β +β β +β Environment Variables β Runtime Configuration β +β Volume Mounts β Prompts & Secrets β +β Network Policies β Zero-Egress by Default β +β Signal Handling β Dynamic Reconfiguration (SIGHUP) β +βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ +``` + +**Key Features:** +- No config files inside containers +- All settings via environment variables +- Secrets injected via secure volumes +- Dynamic assignment loading from WHOOSH +- SIGHUP-triggered reconfiguration + +### 2. Peer-to-Peer Mesh Network + +``` + Agent-1 (Alice) + /|\ + / | \ + / | \ + / | \ + Agent-2 | Agent-4 + (Bob) | (Dave) + \ | / + \ | / + \ | / + \|/ + Agent-3 (Carol) + +All agents are equal peers +No central coordinator +Democratic leader election +mDNS local discovery +DHT global discovery +``` + +### 3. Multi-Layer Security + +``` +Layer 1: License Validation (KACHING) + β +Layer 2: P2P Encryption (libp2p TLS) + β +Layer 3: DHT Encryption (age encryption) + β +Layer 4: Docker Sandboxing (namespaces, cgroups) + β +Layer 5: Network Isolation (zero-egress) + β +Layer 6: SHHH Secrets Detection (scan & redact) + β +Layer 7: UCXL Validation (immutable audit trail) + β +Layer 8: Credential Mediation (agent uploads, not container) +``` + +--- + +## Architecture Layers + +CHORUS is organized into distinct architectural layers: + +### Layer 1: P2P Infrastructure + +**Components:** +- libp2p Host (networking) +- mDNS Discovery (local peers) +- DHT (global peer discovery) +- PubSub (message broadcasting) + +**Responsibilities:** +- Peer discovery and connection management +- Encrypted peer-to-peer communication +- Message routing and delivery +- Network resilience and failover + +**See:** [P2P Infrastructure](../internal/p2p.md) + +### Layer 2: Coordination & Consensus + +**Components:** +- Election Manager (leader election) +- Task Coordinator (work distribution) +- HMMM Router (meta-discussion) +- SLURP (distributed orchestration) + +**Responsibilities:** +- Democratic leader election +- Task assignment and tracking +- Collaborative reasoning protocols +- Work distribution algorithms + +**See:** [Coordination](../packages/coordination.md), [SLURP](../packages/slurp/README.md) + +### Layer 3: Execution Engine + +**Components:** +- Task Execution Engine +- Docker Sandbox +- Image Selector +- Command Executor + +**Responsibilities:** +- Isolated code execution in Docker containers +- Language-specific environment selection +- Resource limits and monitoring +- Result capture and validation + +**See:** [Execution Engine](../packages/execution.md), [Task Execution Engine Module](../../Modules/TaskExecutionEngine.md) + +### Layer 4: AI Integration + +**Components:** +- AI Provider Interface +- Provider Implementations (Ollama, ResetData) +- Model Selection Logic +- Prompt Management + +**Responsibilities:** +- Abstract AI provider differences +- Route requests to appropriate models +- Manage system prompts and context +- Handle AI provider failover + +**See:** [AI Providers](../packages/ai.md), [Providers](../packages/providers.md) + +### Layer 5: Storage & State + +**Components:** +- DHT Storage (distributed) +- Encrypted Storage (age encryption) +- UCXL Decision Publisher +- Hypercore Log (append-only) + +**Responsibilities:** +- Distributed data storage +- Encryption and key management +- Immutable decision recording +- Event log persistence + +**See:** [DHT](../packages/dht.md), [UCXL](../packages/ucxl.md) + +### Layer 6: Security & Validation + +**Components:** +- License Validator (KACHING) +- SHHH Sentinel (secrets detection) +- Crypto Layer (encryption) +- Security Policies + +**Responsibilities:** +- License enforcement +- Secrets scanning and redaction +- Cryptographic operations +- Security policy enforcement + +**See:** [Crypto](../packages/crypto.md), [SHHH](../packages/shhh.md), [Licensing](../internal/licensing.md) + +### Layer 7: Observability + +**Components:** +- Metrics Collector (CHORUS Metrics) +- Health Checks (liveness, readiness) +- BACKBEAT Integration (P2P telemetry) +- Hypercore Log (coordination events) + +**Responsibilities:** +- System metrics collection +- Health monitoring +- P2P operation tracking +- Event logging and audit trails + +**See:** [Metrics](../packages/metrics.md), [Health](../packages/health.md) + +### Layer 8: External Interfaces + +**Components:** +- HTTP API Server +- UCXI Server (content resolution) +- HAP Terminal Interface +- HAP Web Interface [STUB] + +**Responsibilities:** +- REST API endpoints +- UCXL content resolution +- Human interaction interfaces +- External system integration + +**See:** [API](../api/README.md), [UCXI](../packages/ucxi.md), [HAP UI](../internal/hapui.md) + +--- + +## Key Components + +### Runtime Architecture + +``` +ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ +β main.go (cmd/agent or cmd/hap) β +β β β +β βββ internal/runtime.Initialize() β +β β β +β βββ Config Loading (environment) β +β βββ License Validation (KACHING) β +β βββ AI Provider Setup (Ollama/ResetData) β +β βββ P2P Node Creation (libp2p) β +β βββ PubSub Initialization β +β βββ DHT Setup (optional) β +β βββ Election Manager β +β βββ Task Coordinator β +β βββ HTTP API Server β +β βββ UCXI Server (optional) β +β βββ Health & Metrics β +β β +β SharedRuntime β +β βββ Context & Cancellation β +β βββ Logger (SimpleLogger) β +β βββ Config (*config.Config) β +β βββ RuntimeConfig (dynamic assignments) β +β βββ P2P Node (*p2p.Node) β +β βββ PubSub (*pubsub.PubSub) β +β βββ DHT (*dht.LibP2PDHT) β +β βββ Encrypted Storage (*dht.EncryptedDHTStorage) β +β βββ Election Manager (*election.ElectionManager) β +β βββ Task Coordinator (*coordinator.TaskCoordinator) β +β βββ HTTP Server (*api.HTTPServer) β +β βββ UCXI Server (*ucxi.Server) β +β βββ Health Manager (*health.Manager) β +β βββ Metrics (*metrics.CHORUSMetrics) β +β βββ SHHH Sentinel (*shhh.Sentinel) β +β βββ BACKBEAT Integration (*backbeat.Integration) β +β βββ Decision Publisher (*ucxl.DecisionPublisher) β +ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ +``` + +### Binary Separation + +CHORUS provides three binaries with shared infrastructure: + +| Binary | Purpose | Mode | Status | +|--------|---------|------|--------| +| **chorus-agent** | Autonomous AI agent | Agent Mode | β Production | +| **chorus-hap** | Human Agent Portal | HAP Mode | πΆ Beta | +| **chorus** | Compatibility wrapper | N/A | π΄ Deprecated | + +All binaries share: +- P2P infrastructure (libp2p, PubSub, DHT) +- Election and coordination systems +- Security and encryption layers +- Configuration and licensing + +Differences: +- **Agent**: Automatic task execution, autonomous reasoning +- **HAP**: Terminal/web UI for human interaction, manual task approval + +**See:** [Commands](../commands/README.md) + +--- + +## Data Flow + +### Task Execution Flow + +``` +1. Task Request Arrives + β + βββ Via PubSub (from another agent) + βββ Via HTTP API (from external system) + βββ Via HAP (from human operator) + β + β +2. Task Coordinator Receives Task + β + βββ Check agent availability + βββ Validate task structure + βββ Assign to execution engine + β + β +3. Execution Engine Processes + β + βββ Detect language (Go, Rust, Python, etc.) + βββ Select Docker image + βββ Create sandbox configuration + βββ Start container + β β + β βββ Mount /workspace/input (read-only source) + β βββ Mount /workspace/data (working directory) + β βββ Mount /workspace/output (deliverables) + β + βββ Execute commands via Docker Exec API + βββ Stream stdout/stderr + βββ Monitor resource usage + βββ Capture exit codes + β + β +4. Result Processing + β + βββ Collect artifacts from /workspace/output + βββ Generate task summary + βββ Create UCXL decision record + βββ Publish to DHT (encrypted) + β + β +5. Result Distribution + β + βββ Broadcast completion via PubSub + βββ Update task tracker (availability) + βββ Notify requester (if HTTP API) + βββ Log to Hypercore (audit trail) +``` + +### Decision Publishing Flow + +``` +Agent Decision Made + β + β +Generate UCXL Context Address + β + βββ Hash decision content (SHA-256) + βββ Create ucxl:// URI + βββ Add metadata (agent ID, timestamp) + β + β +Encrypt Decision Data + β + βββ Use age encryption + βββ Derive key from shared secret + βββ Create encrypted blob + β + β +Store in DHT + β + βββ Key: UCXL hash + βββ Value: Encrypted decision + βββ TTL: Configured expiration + β + β +Announce on PubSub + β + βββ Topic: "chorus/decisions" + βββ Payload: UCXL address only + βββ Interested peers can fetch from DHT +``` + +### Election Flow + +``` +Agent Startup + β + β +Join Election Topic + β + βββ Subscribe to "chorus/election/v1" + βββ Announce presence + βββ Share capabilities + β + β +Send Heartbeats + β + βββ Every 5 seconds + βββ Include: Node ID, Uptime, Load + βββ Track other peers' heartbeats + β + β +Monitor Admin Status + β + βββ Track last admin heartbeat + βββ Timeout: 15 seconds + βββ If timeout β Trigger election + β + β +Election Triggered + β + βββ All agents propose themselves + βββ Vote for highest uptime + βββ Consensus on winner + βββ Winner becomes admin + β + β +Admin Elected + β + βββ Winner assumes admin role + βββ Applies admin configuration + βββ Enables SLURP coordination + βββ Continues heartbeat at higher frequency +``` + +--- + +## Deployment Models + +### Model 1: Local Development + +``` +βββββββββββββββββββββββββββββββββββββββββββ +β Developer Laptop β +β β +β ββββββββββββββββ ββββββββββββββββ β +β β chorus-agent β β chorus-hap β β +β β (Alice) β β (Human) β β +β ββββββββ¬ββββββββ ββββββββ¬ββββββββ β +β β β β +β ββββββββββ¬ββββββββββ β +β β β +β mDNS Discovery β +β P2P Mesh (local) β +β β +β Ollama: localhost:11434 β +β Docker: /var/run/docker.sock β +βββββββββββββββββββββββββββββββββββββββββββ +``` + +**Characteristics:** +- Single machine deployment +- mDNS for peer discovery +- Local Ollama instance +- Shared Docker socket +- No DHT required + +**Use Cases:** +- Local testing +- Development workflows +- Single-user tasks + +### Model 2: Docker Swarm Cluster + +``` +ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ +β Docker Swarm Cluster β +β β +β Manager Node 1 Manager Node 2 Worker 1 β +β ββββββββββββββββ ββββββββββββββββ βββββββββββ β +β β chorus-agent βββββββββ chorus-agent βββββββββ chorus β β +β β (Leader) β β (Follower) β β -agent β β +β ββββββββββββββββ ββββββββββββββββ βββββββββββ β +β β β β β +β β β β β +β βββββββββββββββββββββββββ΄ββββββββββββββββββββββ β +β Docker Swarm Overlay Network β +β P2P Mesh + DHT β +β β +β Shared Services: β +β - Docker Registry (private) β +β - Ollama Distributed (5 nodes) β +β - NFS Storage (/rust) β +β - WHOOSH (assignment server) β +β - KACHING (license server) β +ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ +``` + +**Characteristics:** +- Multi-node cluster +- DHT for global discovery +- Bootstrap peers for network joining +- Overlay networking +- Shared storage via NFS +- Centralized license validation + +**Use Cases:** +- Production deployments +- Team collaboration +- High availability +- Scalable workloads + +### Model 3: Hybrid (Agent + HAP) + +``` +ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ +β Production Environment β +β β +β Docker Swarm Developer Workstation β +β ββββββββββββββββ ββββββββββββββββ β +β β chorus-agent β β chorus-hap β β +β β (Alice) βββββββP2Pβββββββ (Human-Bob) β β +β ββββββββ¬ββββββββ ββββββββββββββββ β +β β β +β ββββββββ΄ββββββββ β +β β chorus-agent β β +β β (Carol) β β +β ββββββββββββββββ β +β β +β Autonomous agents run in swarm β +β Human operator joins via HAP (local or remote) β +β Same P2P protocol, equal participants β +ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ +``` + +**Characteristics:** +- Autonomous agents in production +- Human operators join as needed +- Collaborative decision-making +- HMMM meta-discussion +- Humans can override or guide + +**Use Cases:** +- Supervised automation +- Human-in-the-loop workflows +- Critical decision points +- Training and oversight + +--- + +## Related Documents + +### Getting Started +- [Commands Overview](../commands/README.md) - Entry points and CLI tools +- [Deployment Guide](../deployment/README.md) - How to deploy CHORUS +- [Configuration](../deployment/configuration.md) - Environment variables and settings + +### Core Systems +- [Task Execution Engine](../../Modules/TaskExecutionEngine.md) - Complete execution engine documentation +- [P2P Infrastructure](../internal/p2p.md) - libp2p networking details +- [SLURP System](../packages/slurp/README.md) - Distributed coordination + +### Security +- [Security Architecture](security.md) - Security layers and threat model +- [Crypto Package](../packages/crypto.md) - Encryption and key management +- [SHHH](../packages/shhh.md) - Secrets detection and redaction +- [Licensing](../internal/licensing.md) - License validation + +### Integration +- [API Reference](../api/reference.md) - HTTP API endpoints +- [UCXL System](../packages/ucxl.md) - Context addressing +- [AI Providers](../packages/ai.md) - AI integration + +--- + +## Next Steps + +For detailed information on specific components: +1. **New to CHORUS?** Start with [System Architecture](system-architecture.md) +2. **Want to deploy?** See [Deployment Guide](../deployment/README.md) +3. **Developing features?** Review [Component Map](component-map.md) +4. **Understanding execution?** Read [Task Execution Engine](../../Modules/TaskExecutionEngine.md) \ No newline at end of file diff --git a/docs/comprehensive/commands/chorus-agent.md b/docs/comprehensive/commands/chorus-agent.md new file mode 100644 index 0000000..17c1025 --- /dev/null +++ b/docs/comprehensive/commands/chorus-agent.md @@ -0,0 +1,738 @@ +# chorus-agent - Autonomous Agent Binary + +**Binary:** `chorus-agent` +**Source:** `cmd/agent/main.go` +**Status:** β Production +**Purpose:** Autonomous AI agent for P2P task coordination + +--- + +## Overview + +`chorus-agent` is the primary executable for running autonomous AI agents in the CHORUS system. Agents participate in peer-to-peer networks, execute tasks in isolated Docker sandboxes, collaborate with other agents via HMMM protocol, and maintain distributed state through DHT storage. + +### Key Features + +- β **Autonomous Operation**: Executes tasks without human intervention +- β **P2P Networking**: Participates in distributed mesh network +- β **Docker Sandboxing**: Isolated code execution environments +- β **HMMM Reasoning**: Collaborative meta-discussion protocol +- β **DHT Storage**: Encrypted distributed data storage +- β **UCXL Publishing**: Immutable decision recording +- β **Democratic Elections**: Participates in leader election +- β **Health Monitoring**: Self-reporting health status + +--- + +## Usage + +### Basic Invocation + +```bash +# With required environment variables +CHORUS_LICENSE_ID=dev-123 \ +CHORUS_AGENT_ID=chorus-agent-1 \ +./chorus-agent +``` + +### Help Output + +```bash +$ ./chorus-agent --help +CHORUS-agent 0.5.0-dev (build: abc123, 2025-09-30) + +Usage: + chorus-agent [--help] [--version] + +CHORUS Autonomous Agent - P2P Task Coordination + +This binary runs autonomous AI agents that participate in P2P task coordination, +collaborative reasoning via HMMM, and distributed decision making. + +Environment (common): + CHORUS_LICENSE_ID (required) + CHORUS_AGENT_ID (optional; auto-generated if empty) + CHORUS_P2P_PORT (default 9000) + CHORUS_API_PORT (default 8080) + CHORUS_HEALTH_PORT (default 8081) + CHORUS_DHT_ENABLED (default true) + CHORUS_BOOTSTRAP_PEERS (comma-separated multiaddrs) + OLLAMA_ENDPOINT (default http://localhost:11434) + +Example: + CHORUS_LICENSE_ID=dev-123 \ + CHORUS_AGENT_ID=chorus-agent-1 \ + CHORUS_P2P_PORT=9000 CHORUS_API_PORT=8080 ./chorus-agent + +Agent Features: + - Autonomous task execution + - P2P mesh networking + - HMMM collaborative reasoning + - DHT encrypted storage + - UCXL context addressing + - Democratic leader election + - Health monitoring +``` + +### Version Information + +```bash +$ ./chorus-agent --version +CHORUS-agent 0.5.0-dev (build: abc123, 2025-09-30) +``` + +--- + +## Source Code Analysis + +### File: `cmd/agent/main.go` + +**Lines:** 79 +**Package:** main +**Imports:** +- `chorus/internal/runtime` - Shared P2P runtime infrastructure + +### Build-Time Variables + +```go +// Lines 11-16 +var ( + version = "0.5.0-dev" + commitHash = "unknown" + buildDate = "unknown" +) +``` + +**Set via ldflags:** +```bash +go build -ldflags "-X main.version=1.0.0 -X main.commitHash=$(git rev-parse --short HEAD) -X main.buildDate=$(date -u +%Y-%m-%d)" +``` + +### main() Function Flow + +```go +func main() { + // 1. CLI Argument Handling (lines 19-59) + // - Check for --help, -h, help + // - Check for --version, -v + // - Print usage and exit early if found + + // 2. Set Build Information (lines 61-64) + runtime.AppVersion = version + runtime.AppCommitHash = commitHash + runtime.AppBuildDate = buildDate + + // 3. Initialize Shared Runtime (lines 66-72) + sharedRuntime, err := runtime.Initialize("agent") + if err != nil { + // Fatal error, exit 1 + } + defer sharedRuntime.Cleanup() + + // 4. Start Agent Mode (lines 74-78) + if err := sharedRuntime.StartAgentMode(); err != nil { + // Fatal error, exit 1 + } +} +``` + +### Execution Phases + +#### Phase 1: Early CLI Handling (lines 19-59) + +**Purpose:** Handle help/version requests without loading configuration + +**Code:** +```go +for _, a := range os.Args[1:] { + switch a { + case "--help", "-h", "help": + // Print detailed help message + fmt.Printf("%s-agent %s (build: %s, %s)\n\n", runtime.AppName, version, commitHash, buildDate) + // ... usage information ... + return + case "--version", "-v": + fmt.Printf("%s-agent %s (build: %s, %s)\n", runtime.AppName, version, commitHash, buildDate) + return + } +} +``` + +**Why Important:** Allows users to get help without needing valid license or configuration. + +#### Phase 2: Runtime Initialization (line 67) + +**Function Call:** `runtime.Initialize("agent")` + +**What Happens:** +1. Load configuration from environment variables +2. Validate CHORUS license with KACHING server +3. Initialize AI provider (Ollama or ResetData) +4. Create P2P libp2p node +5. Start mDNS discovery +6. Initialize PubSub messaging +7. Setup DHT (if enabled) +8. Start election manager +9. Create task coordinator +10. Start HTTP API server +11. Start UCXI server (if enabled) +12. Initialize health checks +13. Setup SHHH sentinel (secrets detection) +14. Configure metrics collection + +**Returns:** `*runtime.SharedRuntime` containing all initialized components + +**See:** [internal/runtime Documentation](../internal/runtime.md) for complete initialization details + +#### Phase 3: Agent Mode Activation (line 75) + +**Function Call:** `sharedRuntime.StartAgentMode()` + +**What Happens:** +1. Agent registers itself as available for tasks +2. Begins listening for task assignments via PubSub +3. Starts autonomous task execution loops +4. Enables automatic decision making +5. Activates HMMM meta-discussion participation +6. Begins heartbeat broadcasting for election + +**Implementation:** See `internal/runtime/agent_support.go` + +**Behavior Differences from HAP:** +- **Agent**: Automatically accepts and executes tasks +- **HAP**: Prompts human for task approval + +--- + +## Configuration + +### Required Environment Variables + +| Variable | Description | Example | +|----------|-------------|---------| +| `CHORUS_LICENSE_ID` | License key from KACHING | `dev-123` | + +### Optional Environment Variables + +| Variable | Default | Description | +|----------|---------|-------------| +| `CHORUS_AGENT_ID` | Auto-generated | Unique agent identifier | +| `CHORUS_P2P_PORT` | 9000 | libp2p listening port | +| `CHORUS_API_PORT` | 8080 | HTTP API port | +| `CHORUS_HEALTH_PORT` | 8081 | Health check port | +| `CHORUS_DHT_ENABLED` | true | Enable distributed hash table | +| `CHORUS_BOOTSTRAP_PEERS` | "" | Comma-separated multiaddrs | +| `OLLAMA_ENDPOINT` | http://localhost:11434 | Ollama API endpoint | + +### Role-Based Configuration + +| Variable | Default | Description | +|----------|---------|-------------| +| `CHORUS_AGENT_ROLE` | "" | Agent role (admin, developer, reviewer) | +| `CHORUS_AGENT_EXPERTISE` | "" | Comma-separated expertise areas | +| `CHORUS_AGENT_REPORTS_TO` | "" | Supervisor agent ID | +| `CHORUS_AGENT_SPECIALIZATION` | "general" | Task specialization | +| `CHORUS_AGENT_MAX_TASKS` | 3 | Max concurrent tasks | + +### AI Provider Configuration + +#### Ollama (Default) + +```bash +export CHORUS_AI_PROVIDER=ollama +export OLLAMA_ENDPOINT=http://192.168.1.72:11434 +``` + +#### ResetData + +```bash +export CHORUS_AI_PROVIDER=resetdata +export RESETDATA_API_KEY=your-api-key-here +export RESETDATA_BASE_URL=https://api.resetdata.ai +export RESETDATA_MODEL=claude-3-5-sonnet-20250930 +``` + +### Assignment Loading + +Agents can load dynamic configuration from WHOOSH: + +```bash +export ASSIGN_URL=https://whoosh.example.com/api/assignments/agent-123.json +``` + +When configured, agents: +1. Fetch assignment JSON on startup +2. Merge with environment config +3. Listen for SIGHUP to reload +4. Update configuration without restart + +**See:** [Configuration Management](../packages/config.md) for assignment schema + +--- + +## Runtime Behavior + +### Startup Sequence + +``` +1. Parse CLI arguments + βββ --help β print help, exit 0 + βββ --version β print version, exit 0 + βββ (none) β continue + +2. Set build information in runtime package + +3. Initialize shared runtime + βββ Load environment configuration + βββ Validate license with KACHING + β βββ FAIL β print error, exit 1 + βββ Configure AI provider + βββ Create P2P node + βββ Start mDNS discovery + βββ Initialize PubSub + βββ Setup DHT (optional) + βββ Start election manager + βββ Create task coordinator + βββ Start HTTP API server + βββ Initialize health checks + +4. Start agent mode + βββ Register as available agent + βββ Join task coordination topics + βββ Begin heartbeat broadcasting + βββ Enable autonomous task execution + βββ Activate HMMM participation + +5. Run until signal (SIGINT, SIGTERM) + +6. Cleanup on shutdown + βββ Stop accepting new tasks + βββ Complete in-flight tasks + βββ Close P2P connections + βββ Flush DHT cache + βββ Stop HTTP servers + βββ Exit gracefully +``` + +### Signal Handling + +| Signal | Behavior | +|--------|----------| +| SIGINT | Graceful shutdown (complete current tasks) | +| SIGTERM | Graceful shutdown (complete current tasks) | +| SIGHUP | Reload configuration from ASSIGN_URL | + +### Task Execution Loop + +Once in agent mode: + +``` +Loop Forever: +β +βββ Listen for tasks on PubSub topic "chorus/tasks" +β +βββ Task received: +β βββ Check agent availability (< max tasks) +β βββ Check task matches specialization +β βββ Accept or decline +β +βββ Task accepted: +β βββ Increment active task count +β βββ Log task start to Hypercore +β βββ Invoke execution engine +β β βββ Select Docker image based on language +β β βββ Create sandbox container +β β βββ Execute commands via Docker Exec API +β β βββ Stream output +β β βββ Monitor resource usage +β β βββ Capture results +β βββ Generate task summary +β βββ Create UCXL decision record +β βββ Publish decision to DHT +β βββ Broadcast completion on PubSub +β βββ Decrement active task count +β βββ Log task completion to Hypercore +β +βββ Continue listening +``` + +**See:** [Task Execution Engine](../packages/execution.md) for execution details + +--- + +## P2P Networking + +### Peer Discovery + +**mDNS (Local):** +- Discovers peers on local network +- Service name: `chorus-peer-discovery` +- No configuration required +- Automatic peer connection + +**DHT (Global):** +- Discovers peers across networks +- Requires bootstrap peers +- Content-addressed routing +- Kademlia-based DHT + +**Bootstrap Peers:** +```bash +export CHORUS_BOOTSTRAP_PEERS="/ip4/192.168.1.100/tcp/9000/p2p/12D3KooWABC...,/ip4/192.168.1.101/tcp/9000/p2p/12D3KooWXYZ..." +``` + +### Topics Subscribed + +| Topic | Purpose | +|-------|---------| +| `chorus/coordination/v1` | Task coordination messages | +| `hmmm/meta-discussion/v1` | Collaborative reasoning | +| `chorus/election/v1` | Leader election heartbeats | +| `chorus/decisions` | Decision announcements | +| `chorus/health` | Health status broadcasts | + +### Role-Based Topics (Optional) + +If `CHORUS_AGENT_ROLE` is set, agent also joins: + +| Topic | Purpose | +|-------|---------| +| `chorus/role/{role}` | Role-specific coordination | +| `chorus/expertise/{expertise}` | Expertise-based routing | +| `chorus/reports/{supervisor}` | Reporting hierarchy | + +--- + +## Health Checks + +### HTTP Endpoints + +**Liveness Probe:** +```bash +curl http://localhost:8081/healthz +# Returns: 200 OK if agent is alive +``` + +**Readiness Probe:** +```bash +curl http://localhost:8081/ready +# Returns: 200 OK if agent is ready for tasks +# Returns: 503 Service Unavailable if at max capacity +``` + +**Health Details:** +```bash +curl http://localhost:8081/health +# Returns JSON with: +# - P2P connectivity status +# - DHT reachability +# - Active task count +# - Available capacity +# - Last heartbeat time +``` + +### Health Criteria + +Agent is **healthy** when: +- β License valid +- β P2P node connected +- β At least 1 peer discovered +- β Election manager running +- β Task coordinator active +- β HTTP API responding + +Agent is **ready** when: +- β All health checks pass +- β Active tasks < max tasks +- β Docker daemon reachable +- β AI provider accessible + +**See:** [Health Package](../packages/health.md) + +--- + +## Monitoring & Metrics + +### Prometheus Metrics + +Exposed on `http://localhost:8080/metrics`: + +**Task Metrics:** +- `chorus_tasks_active` - Current active tasks +- `chorus_tasks_completed_total` - Total completed tasks +- `chorus_tasks_failed_total` - Total failed tasks +- `chorus_task_duration_seconds` - Task execution duration histogram + +**P2P Metrics:** +- `chorus_peers_connected` - Number of connected peers +- `chorus_pubsub_messages_sent_total` - PubSub messages sent +- `chorus_pubsub_messages_received_total` - PubSub messages received +- `chorus_dht_queries_total` - DHT query count +- `chorus_dht_cache_hits_total` - DHT cache hits +- `chorus_dht_cache_misses_total` - DHT cache misses + +**Execution Metrics:** +- `chorus_sandbox_containers_active` - Active Docker containers +- `chorus_sandbox_cpu_usage` - Container CPU usage +- `chorus_sandbox_memory_usage_bytes` - Container memory usage + +**Security Metrics:** +- `chorus_shhh_findings_total` - Secrets detected by SHHH +- `chorus_license_checks_total` - License validation attempts +- `chorus_license_failures_total` - Failed license validations + +**See:** [Metrics Package](../packages/metrics.md) + +--- + +## Integration Points + +### WHOOSH Assignment System + +Agents can load dynamic assignments from WHOOSH: + +```bash +# Set assignment URL +export ASSIGN_URL=https://whoosh.example.com/api/assignments/agent-123.json + +# Agent fetches assignment on startup +# Assignment JSON structure: +{ + "agent_id": "agent-123", + "role": "developer", + "expertise": ["rust", "go"], + "reports_to": "agent-admin", + "max_tasks": 5, + "bootstrap_peers": [ + "/ip4/192.168.1.100/tcp/9000/p2p/12D3KooWABC..." + ], + "join_stagger_ms": 5000 +} + +# Reload with SIGHUP +kill -HUP $(pidof chorus-agent) +``` + +### KACHING License Server + +All agents validate licenses on startup: + +```bash +# License validation flow +1. Agent starts with CHORUS_LICENSE_ID +2. Connects to KACHING server (from config) +3. Validates license is: + - Valid and not expired + - Assigned to correct cluster + - Has required permissions +4. If invalid: agent exits with error +5. If valid: agent continues startup +``` + +**See:** [Licensing](../internal/licensing.md) + +### BACKBEAT Integration + +Optional telemetry system for P2P operations: + +```bash +export CHORUS_BACKBEAT_ENABLED=true +export CHORUS_BACKBEAT_ENDPOINT=http://backbeat.example.com + +# When enabled, agent tracks: +# - P2P operation phases +# - DHT bootstrap timing +# - Election progression +# - Task execution phases +``` + +**See:** [BACKBEAT Integration](../internal/backbeat.md) + +--- + +## Example Deployments + +### Local Development + +```bash +#!/bin/bash +# Run local agent for development + +export CHORUS_LICENSE_ID=dev-local-123 +export CHORUS_AGENT_ID=dev-agent-1 +export CHORUS_P2P_PORT=9000 +export CHORUS_API_PORT=8080 +export CHORUS_HEALTH_PORT=8081 +export OLLAMA_ENDPOINT=http://localhost:11434 +export CHORUS_DHT_ENABLED=false # Disable DHT for local dev + +./chorus-agent +``` + +### Docker Container + +```dockerfile +FROM debian:bookworm-slim + +# Install runtime dependencies +RUN apt-get update && apt-get install -y \ + ca-certificates \ + docker.io \ + && rm -rf /var/lib/apt/lists/* + +# Copy binary +COPY chorus-agent /usr/local/bin/chorus-agent + +# Expose ports +EXPOSE 9000 8080 8081 + +# Run as non-root +USER nobody + +ENTRYPOINT ["/usr/local/bin/chorus-agent"] +``` + +```bash +docker run -d \ + --name chorus-agent-1 \ + -e CHORUS_LICENSE_ID=prod-123 \ + -e CHORUS_AGENT_ID=agent-1 \ + -v /var/run/docker.sock:/var/run/docker.sock \ + -p 9000:9000 \ + -p 8080:8080 \ + -p 8081:8081 \ + chorus-agent:latest +``` + +### Docker Swarm Service + +```yaml +version: "3.8" +services: + chorus-agent: + image: registry.example.com/chorus-agent:1.0.0 + environment: + CHORUS_LICENSE_ID: ${CHORUS_LICENSE_ID} + CHORUS_P2P_PORT: 9000 + CHORUS_API_PORT: 8080 + CHORUS_DHT_ENABLED: "true" + CHORUS_BOOTSTRAP_PEERS: "/ip4/192.168.1.100/tcp/9000/p2p/12D3KooWABC..." + ASSIGN_URL: "https://whoosh.example.com/api/assignments/{{.Service.Name}}.{{.Task.Slot}}.json" + volumes: + - /var/run/docker.sock:/var/run/docker.sock:ro + - /rust/containers/WHOOSH/prompts:/prompts:ro + deploy: + replicas: 3 + placement: + constraints: + - node.role == worker + networks: + - chorus-mesh + ports: + - target: 9000 + published: 9000 + mode: host +``` + +--- + +## Troubleshooting + +### Agent Won't Start + +**Symptom:** Agent exits immediately with error + +**Possible Causes:** +1. Invalid or missing license + ``` + β Failed to initialize CHORUS agent: license validation failed + ``` + **Fix:** Check `CHORUS_LICENSE_ID` and KACHING server connectivity + +2. Docker socket not accessible + ``` + β Failed to create P2P node: failed to create Docker client + ``` + **Fix:** Mount `/var/run/docker.sock` or check Docker daemon + +3. Port already in use + ``` + β Failed to initialize: bind: address already in use + ``` + **Fix:** Change `CHORUS_P2P_PORT` or kill process on port + +### No Peer Discovery + +**Symptom:** Agent starts but shows 0 connected peers + +**Possible Causes:** +1. mDNS blocked by firewall + **Fix:** Allow UDP port 5353, or use bootstrap peers + +2. No bootstrap peers configured + **Fix:** Set `CHORUS_BOOTSTRAP_PEERS` with valid multiaddrs + +3. Network isolation + **Fix:** Ensure agents can reach each other on P2P ports + +### Tasks Not Executing + +**Symptom:** Agent receives tasks but doesn't execute + +**Possible Causes:** +1. Agent at max capacity + **Check:** `curl localhost:8080/metrics | grep chorus_tasks_active` + **Fix:** Increase `CHORUS_AGENT_MAX_TASKS` + +2. Docker images not available + **Check:** `docker images | grep chorus` + **Fix:** Pull images: `docker pull anthonyrawlins/chorus-rust-dev:latest` + +3. Wrong specialization + **Check:** Task language doesn't match agent expertise + **Fix:** Adjust `CHORUS_AGENT_EXPERTISE` or remove specialization + +### High Memory Usage + +**Symptom:** Agent consuming excessive memory + +**Possible Causes:** +1. DHT cache size too large + **Fix:** Reduce `CHORUS_DHT_CACHE_SIZE` (default 100MB) + +2. Too many concurrent tasks + **Fix:** Reduce `CHORUS_AGENT_MAX_TASKS` + +3. Memory leak in long-running containers + **Fix:** Restart agent periodically or investigate task code + +--- + +## Related Documentation + +- [chorus-hap](chorus-hap.md) - Human Agent Portal binary +- [chorus](chorus.md) - Deprecated compatibility wrapper +- [internal/runtime](../internal/runtime.md) - Shared runtime initialization +- [Task Execution Engine](../packages/execution.md) - Task execution details +- [Configuration](../deployment/configuration.md) - Environment variables reference +- [Deployment](../deployment/docker.md) - Docker deployment guide + +--- + +## Implementation Status + +| Feature | Status | Notes | +|---------|--------|-------| +| P2P Networking | β Production | libp2p, mDNS, DHT | +| Task Execution | β Production | Docker sandboxing | +| License Validation | β Production | KACHING integration | +| HMMM Reasoning | πΆ Beta | Collaborative meta-discussion | +| UCXL Publishing | β Production | Decision recording | +| Election | β Production | Democratic leader election | +| Health Checks | β Production | Liveness & readiness | +| Metrics | β Production | Prometheus format | +| Assignment Loading | β Production | WHOOSH integration | +| SIGHUP Reload | β Production | Dynamic reconfiguration | +| BACKBEAT Telemetry | πΆ Beta | Optional P2P tracking | + +**Last Updated:** 2025-09-30 \ No newline at end of file diff --git a/docs/comprehensive/commands/chorus-hap.md b/docs/comprehensive/commands/chorus-hap.md new file mode 100644 index 0000000..02a49b2 --- /dev/null +++ b/docs/comprehensive/commands/chorus-hap.md @@ -0,0 +1,1411 @@ +# chorus-hap - Human Agent Portal Binary + +**Binary:** `chorus-hap` +**Source:** `cmd/hap/main.go` +**Status:** πΆ Beta (Terminal interface: β Production, Web interface: β³ Stubbed) +**Purpose:** Human-friendly interface for participating in P2P agent networks + +--- + +## Overview + +`chorus-hap` (Human Agent Portal) is the executable that enables human users to participate in CHORUS P2P agent networks as first-class peers. Unlike autonomous agents, HAP provides interactive interfaces (terminal and web) for humans to collaborate with agents using the same protocols. + +### Key Features + +- β **Terminal Interface**: Full-featured command-line interaction (Production) +- β³ **Web Interface**: Browser-based UI (Stubbed, falls back to terminal) +- β **HMMM Composition**: Human-friendly reasoning message helpers +- β **UCXL Browsing**: Navigate and explore context addresses +- β **Decision Participation**: Vote on network decisions +- β **Collaborative Sessions**: Multi-party editing coordination +- β **Patch Creation**: Submit changes to codebase +- β **P2P Protocols**: Same networking as autonomous agents +- β **Peer Management**: View and interact with network peers + +### Human vs Agent Mode + +| Feature | chorus-agent | chorus-hap | +|---------|--------------|------------| +| **Task Execution** | Automatic | Manual approval required | +| **UI Mode** | Headless | Terminal or Web | +| **HMMM Messages** | AI-generated | Human-composed | +| **Decision Making** | Autonomous | Interactive prompts | +| **Network Role** | Autonomous peer | Human peer | +| **Use Case** | Batch processing | Oversight & collaboration | + +--- + +## Usage + +### Basic Invocation + +```bash +# With required environment variables +CHORUS_LICENSE_ID=dev-123 \ +CHORUS_AGENT_ID=human-alice \ +CHORUS_HAP_MODE=terminal \ +./chorus-hap +``` + +### Help Output + +```bash +$ ./chorus-hap --help +CHORUS-hap 0.5.0-dev + +Usage: + chorus-hap [--help] [--version] + +CHORUS Human Agent Portal - Human Interface to P2P Agent Networks + +This binary provides a human-friendly interface to participate in P2P agent +coordination networks. Humans can collaborate with autonomous agents using +the same protocols and appear as peers in the distributed network. + +Environment (common): + CHORUS_LICENSE_ID (required) + CHORUS_AGENT_ID (optional; auto-generated if empty) + CHORUS_P2P_PORT (default 9000) + CHORUS_API_PORT (default 8080) + CHORUS_HEALTH_PORT (default 8081) + CHORUS_DHT_ENABLED (default true) + CHORUS_BOOTSTRAP_PEERS (comma-separated multiaddrs) + OLLAMA_ENDPOINT (default http://localhost:11434) + +HAP-Specific Environment: + CHORUS_HAP_MODE (terminal|web, default terminal) + CHORUS_HAP_WEB_PORT (default 8082) + +Example: + CHORUS_LICENSE_ID=dev-123 \ + CHORUS_AGENT_ID=human-alice \ + CHORUS_HAP_MODE=terminal \ + CHORUS_P2P_PORT=9001 ./chorus-hap + +HAP Features: + - Human-friendly message composition + - HMMM reasoning template helpers + - UCXL context browsing + - Collaborative decision participation + - Terminal and web interface modes + - Same P2P protocols as autonomous agents +``` + +### Version Information + +```bash +$ ./chorus-hap --version +CHORUS-hap 0.5.0-dev +``` + +--- + +## Source Code Analysis + +### File: `cmd/hap/main.go` + +**Lines:** 126 +**Package:** main +**Imports:** +- `chorus/internal/hapui` - Terminal and web interface implementations +- `chorus/internal/runtime` - Shared P2P runtime infrastructure + +### main() Function Flow + +```go +func main() { + // 1. CLI Argument Handling (lines 14-58) + // - Check for --help, -h, help + // - Check for --version, -v + // - Print usage and exit early if found + + // 2. Initialize Shared Runtime (lines 60-66) + sharedRuntime, err := runtime.Initialize("hap") + if err != nil { + // Fatal error, exit 1 + } + defer sharedRuntime.Cleanup() + + // 3. Start HAP Mode (lines 68-72) + if err := startHAPMode(sharedRuntime); err != nil { + // Fatal error, exit 1 + } +} +``` + +### Execution Phases + +#### Phase 1: Early CLI Handling (lines 14-58) + +**Purpose:** Handle help/version requests without loading configuration + +**Code:** +```go +for _, a := range os.Args[1:] { + switch a { + case "--help", "-h", "help": + // Print HAP-specific help with terminal/web mode info + fmt.Printf("%s-hap %s\n\n", runtime.AppName, runtime.AppVersion) + // ... detailed usage information ... + return + case "--version", "-v": + fmt.Printf("%s-hap %s\n", runtime.AppName, runtime.AppVersion) + return + } +} +``` + +**Help Output Details (lines 17-52):** +- Describes HAP purpose and human participation model +- Lists common environment variables (same as chorus-agent) +- Lists HAP-specific variables (mode, web port) +- Shows example invocation with human-focused agent ID +- Highlights features: HMMM helpers, UCXL browsing, decision participation + +**Why Important:** Users can explore HAP capabilities without needing valid license. + +#### Phase 2: Runtime Initialization (line 61) + +**Function Call:** `runtime.Initialize("hap")` + +**What Happens:** +1. Load configuration from environment variables +2. Validate CHORUS license with KACHING server +3. Initialize AI provider (Ollama or ResetData) +4. Create P2P libp2p node (same as agent) +5. Start mDNS discovery +6. Initialize PubSub messaging +7. Setup DHT (if enabled) +8. Start election manager +9. Create task coordinator +10. Start HTTP API server +11. Start UCXI server (if enabled) +12. Initialize health checks +13. Setup SHHH sentinel + +**Returns:** `*runtime.SharedRuntime` containing all initialized components + +**Key Difference from Agent:** Mode parameter is `"hap"` instead of `"agent"`, which configures runtime for human interaction patterns. + +**See:** [internal/runtime Documentation](../internal/runtime.md) for complete initialization details + +#### Phase 3: HAP Mode Selection (lines 75-95) + +**Function:** `startHAPMode(runtime *runtime.SharedRuntime) error` + +**What Happens:** +1. Reads `CHORUS_HAP_MODE` environment variable (default: "terminal") +2. Routes to appropriate interface: + - **"terminal"**: Starts interactive command-line interface + - **"web"**: Attempts web interface (falls back to terminal if stubbed) + - **Invalid**: Returns error + +**Code:** +```go +func startHAPMode(runtime *runtime.SharedRuntime) error { + runtime.Logger.Info("π€ Starting CHORUS Human Agent Portal (HAP)") + runtime.Logger.Info("π Connected to P2P network as human agent") + runtime.Logger.Info("π Ready for collaborative reasoning and decision making") + + hapMode := os.Getenv("CHORUS_HAP_MODE") + if hapMode == "" { + hapMode = "terminal" + } + + switch hapMode { + case "terminal": + return startTerminalInterface(runtime) + case "web": + return startWebInterface(runtime) + default: + return fmt.Errorf("unknown HAP mode: %s (valid: terminal, web)", hapMode) + } +} +``` + +#### Phase 4: Terminal Interface (lines 97-108) + +**Function:** `startTerminalInterface(runtime *runtime.SharedRuntime) error` + +**Implementation:** +```go +func startTerminalInterface(runtime *runtime.SharedRuntime) error { + runtime.Logger.Info("π» Starting terminal interface for human interaction") + + // Create and start the HAP terminal interface + terminal := hapui.NewTerminalInterface(runtime) + + runtime.Logger.Info("π― Human agent terminal interface ready") + + // Start the interactive terminal (blocks until quit) + return terminal.Start() +} +``` + +**Terminal Capabilities:** +- Interactive REPL with `hap>` prompt +- Command parsing and execution +- HMMM message composition with templates +- UCXL context browsing +- Network status monitoring +- Peer management +- Decision voting +- Collaborative session management +- Patch submission + +**See:** Terminal Interface Details section for full command reference + +#### Phase 5: Web Interface (lines 110-126) + +**Function:** `startWebInterface(runtime *runtime.SharedRuntime) error` + +**Current Status:** β³ **STUBBED** - Phase 3 Implementation + +**Code:** +```go +func startWebInterface(runtime *runtime.SharedRuntime) error { + runtime.Logger.Info("π Starting web interface for human interaction") + + // TODO Phase 3: Implement web interface + // - HTTP server with WebSocket for real-time updates + // - Web forms for HMMM message composition + // - Context browser UI + // - Decision voting interface + + runtime.Logger.Info("β οΈ Web interface not yet implemented") + runtime.Logger.Info("π HAP running in stub mode - P2P connectivity established") + runtime.Logger.Info("π Next: Implement Phase 3 web interface") + + // For now, fall back to terminal mode + return startTerminalInterface(runtime) +} +``` + +**Planned Features (Phase 3):** +- HTTP server with WebSocket for real-time updates +- Web forms for HMMM message composition +- Visual context browser UI +- Interactive decision voting interface +- Multi-user collaborative session views +- Real-time network status dashboard + +**Current Behavior:** Falls back to terminal interface with warning logs + +--- + +## Terminal Interface + +### Implementation Details + +**Source:** `internal/hapui/terminal.go` +**Lines:** ~3985 +**Status:** β Production + +### Welcome Screen + +When terminal interface starts: + +``` +================================================================================ +π CHORUS Human Agent Portal (HAP) - Terminal Interface +================================================================================ +Agent ID: human-alice +P2P Node: 12D3KooW...short +Connected to: 3 peers + +You are now connected to the CHORUS P2P agent network as a human participant. +You can collaborate with autonomous agents using the same protocols. +================================================================================ +``` + +### Available Commands + +#### Core Commands + +| Command | Description | Status | +|---------|-------------|--------| +| `help` | Show command reference | β | +| `status` | Show network and agent status | β | +| `peers` | List connected P2P peers | β | +| `quit` | Exit HAP terminal | β | +| `announce` | Re-announce human agent presence | β | + +#### Collaborative Commands + +| Command | Description | Status | +|---------|-------------|--------| +| `hmmm` | Compose and send HMMM reasoning message | β | +| `ucxl
` | Browse UCXL context address | β | +| `patch` | Create and submit patches | β | +| `collab` | Collaborative editing sessions | β | +| `decide