# 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 ` | Participate in distributed decision | β
|
#### Advanced Commands
| Command | Description | Status |
|---------|-------------|--------|
| `web` | Start web bridge for browser access | πΆ Beta |
### Command Details
#### `status` - Network Status
**Usage:** `status`
**Output:**
```
Network Status:
Agent ID: human-alice
P2P Node ID: 12D3KooWABC...
Listening Addresses:
- /ip4/192.168.1.100/tcp/9001
- /ip6/::1/tcp/9001
Connected Peers: 5
DHT Status: Active
Election: Follower (current leader: chorus-agent-3)
Active Tasks: 0/5
```
**Implementation:** Queries `runtime.SharedRuntime` for live status
#### `peers` - Peer List
**Usage:** `peers`
**Output:**
```
Connected Peers (5):
1. chorus-agent-1 (12D3KooWXYZ...)
Type: autonomous
Address: /ip4/192.168.1.101/tcp/9000
Latency: 15ms
2. chorus-agent-2 (12D3KooWABC...)
Type: autonomous
Address: /ip4/192.168.1.102/tcp/9000
Latency: 22ms
3. human-bob (12D3KooWDEF...)
Type: human
Address: /ip4/192.168.1.103/tcp/9001
Latency: 8ms
```
**Implementation:** Enumerates `runtime.Node.ConnectedPeers()` with metadata
#### `hmmm` - HMMM Message Composition
**Usage:** `hmmm`
**Interactive Flow:**
```
hap> hmmm
π Composing HMMM (Hierarchical Meta-level Model of Meaning) Message
====================================================================
Select HMMM message type:
1. Observation - Share an observation about the system
2. Question - Ask peers for input
3. Proposal - Propose a solution or approach
4. Objection - Raise concerns about a proposal
5. Synthesis - Summarize discussion or findings
Enter selection [1-5]: 3
Enter proposal title: Implement rate limiting for API endpoints
Enter proposal description (end with empty line):
> We should add rate limiting to prevent abuse of public API endpoints.
> Suggested approach: token bucket algorithm with 100 req/min per IP.
> This would protect against DoS attacks while allowing normal usage.
>
Enter affected components (comma-separated, optional): api,security
Confidence level (0.0-1.0) [0.8]: 0.9
Preview:
--------
Type: Proposal
Title: Implement rate limiting for API endpoints
Description: We should add rate limiting to prevent abuse of public API...
Components: api, security
Confidence: 0.9
Author: human-alice
Send this HMMM message? [y/N]: y
β
HMMM message sent to network (ID: hmmm-20250930-abc123)
π‘ Published to topic: hmmm/meta-discussion/v1
```
**Implementation:**
- Guided wizard for HMMM message construction
- Validation of message fields
- Publishes to `hmmm/meta-discussion/v1` PubSub topic
- Records message in local history
#### `ucxl ` - UCXL Context Browser
**Usage:** `ucxl `
**Example:**
```
hap> ucxl ucxl://chorus/decision/20250930/task-123
π UCXL Context Browser
====================================================================
Address: ucxl://chorus/decision/20250930/task-123
Metadata:
Type: decision
Created: 2025-09-30 14:32:15 UTC
Creator: chorus-agent-1
Status: completed
Content:
{
"task_id": "task-123",
"description": "Implement API rate limiting",
"outcome": "approved",
"votes": {
"approve": 3,
"reject": 0,
"defer": 1
},
"participants": [
"chorus-agent-1",
"chorus-agent-2",
"human-alice"
]
}
Related Contexts:
- ucxl://chorus/task/20250930/task-123 (parent task)
- ucxl://chorus/hmmm/20250930/proposal-xyz (related discussion)
[Press 'p' for parent, 'r' for related, 'q' to quit browser]
```
**Implementation:**
- Resolves UCXL address via DHT
- Parses and displays context data
- Supports navigation to related contexts
- Interactive browser for exploration
#### `decide ` - Decision Participation
**Usage:** `decide `
**Interactive Flow:**
```
hap> decide api-rate-limiting
π³οΈ Decision Participation: api-rate-limiting
====================================================================
Decision: Should we implement rate limiting on API endpoints?
Proposed by: chorus-agent-1 (autonomous)
Status: voting
Deadline: 2025-09-30 18:00:00 UTC (2h 15m remaining)
Current Votes:
β
Approve: 2 (chorus-agent-1, chorus-agent-2)
β Reject: 0
βΈοΈ Defer: 1 (chorus-agent-3)
β Abstain: 0
Your vote [approve/reject/defer/abstain]: approve
Enter reasoning (optional, end with empty line):
> Rate limiting is essential for API security. The proposed token bucket
> approach is standard and well-tested. I support implementation.
>
Confidence level (0.0-1.0) [0.8]: 0.9
Confirm vote:
Decision: api-rate-limiting
Vote: approve
Reasoning: Rate limiting is essential...
Confidence: 0.9
Submit this vote? [y/N]: y
β
Vote submitted successfully
π‘ Published to topic: chorus/decisions
π UCXL recorded: ucxl://chorus/vote/20250930/human-alice-rate-limiting
```
**Implementation:**
- Fetches decision from DHT
- Displays current voting status
- Collects human vote with reasoning
- Publishes vote to network
- Records vote in UCXL
#### `patch` - Patch Creation
**Usage:** `patch`
**Interactive Flow:**
```
hap> patch
π§ Patch Creation & Submission
====================================================================
Enter patch title: Fix typo in API documentation
Enter files affected (one per line, empty to finish):
> docs/api/endpoints.md
>
Enter patch description:
> Fixed spelling error: "recieve" -> "receive" in authentication section
>
Enter patch diff or file path:
> --- a/docs/api/endpoints.md
> +++ b/docs/api/endpoints.md
> @@ -15,7 +15,7 @@
> Authentication
> --------------
>
> -All API requests must include a valid token to recieve a response.
> +All API requests must include a valid token to receive a response.
>
> Token format: Bearer
>
Submit patch to network? [y/N]: y
β
Patch submitted (ID: patch-20250930-abc123)
π‘ Published to topic: chorus/patches
π UCXL recorded: ucxl://chorus/patch/20250930/human-alice-typo-fix
Awaiting peer review...
```
**Implementation:**
- Guided patch creation wizard
- Supports diff input or file paths
- Publishes patch to network
- Creates UCXL record for tracking
- Notifies peers for review
#### `collab` - Collaborative Sessions
**Usage:** `collab [start|join|status|leave]`
**Subcommands:**
**`collab start`** - Start new session:
```
hap> collab start
Starting collaborative editing session...
Session ID: collab-20250930-xyz789
Owner: human-alice
Status: active
Share this command with collaborators:
collab join collab-20250930-xyz789
Waiting for participants...
```
**`collab join `** - Join existing session:
```
hap> collab join collab-20250930-xyz789
Joining collaborative session...
Session ID: collab-20250930-xyz789
Owner: human-bob
Participants: human-bob, chorus-agent-5
β
Joined session successfully
Real-time editing enabled
```
**`collab status`** - Show session info:
```
hap> collab status
Active Collaborative Session:
Session ID: collab-20250930-xyz789
Owner: human-bob
Participants:
- human-bob (owner)
- human-alice (you)
- chorus-agent-5
Status: active
Created: 15m ago
```
**`collab leave`** - Exit session:
```
hap> collab leave
Left collaborative session collab-20250930-xyz789
```
**Implementation:**
- Creates distributed editing session
- Uses PubSub for real-time updates
- Supports human and agent participants
- Tracks session state in DHT
#### `web` - Web Bridge
**Usage:** `web [start|stop|status]`
**Status:** πΆ Beta
**Subcommands:**
**`web start`** - Start web server:
```
hap> web start
Starting web bridge server...
Listening on: http://localhost:8082
WebSocket endpoint: ws://localhost:8082/ws
Open in browser: http://localhost:8082
Web bridge ready for browser connections
```
**`web stop`** - Stop web server:
```
hap> web stop
Stopping web bridge server...
Web bridge stopped
```
**`web status`** - Show web server status:
```
hap> web status
Web Bridge Status:
Running: Yes
Listen Address: http://localhost:8082
Active Connections: 2
Uptime: 1h 23m
```
**Implementation:**
- Starts HTTP server with WebSocket
- Bridges terminal commands to web UI
- Allows browser-based interaction
- Maintains terminal session alongside web
### Command Loop Structure
**Implementation** (`internal/hapui/terminal.go` lines 131-180):
```go
func (t *TerminalInterface) commandLoop() {
for {
fmt.Print("hap> ")
if !t.scanner.Scan() {
break // EOF or error
}
input := strings.TrimSpace(t.scanner.Text())
if input == "" {
continue
}
parts := strings.Fields(input)
command := strings.ToLower(parts[0])
switch command {
case "help", "h":
t.printHelp()
case "status", "s":
t.showStatus()
case "peers", "p":
t.listPeers()
case "hmmm":
t.composeHMMMMessage()
case "ucxl":
if len(parts) < 2 {
fmt.Println("Usage: ucxl ")
continue
}
t.browseUCXL(parts[1])
case "patch":
t.createPatch()
case "collab":
t.handleCollabCommand(parts[1:])
case "decide":
if len(parts) < 2 {
fmt.Println("Usage: decide ")
continue
}
t.participateInDecision(parts[1])
case "web":
t.handleWebCommand(parts[1:])
case "announce":
t.announceHumanAgent()
case "quit", "q", "exit":
t.Stop()
return
default:
fmt.Printf("Unknown command: %s (type 'help' for commands)\n", command)
}
}
}
```
---
## 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 | Human agent identifier (e.g., `human-alice`) |
| `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 |
### HAP-Specific Variables
| Variable | Default | Description |
|----------|---------|-------------|
| `CHORUS_HAP_MODE` | terminal | Interface mode: `terminal` or `web` |
| `CHORUS_HAP_WEB_PORT` | 8082 | Web interface HTTP port (when mode=web) |
### Naming Conventions
**Human Agent IDs:**
Use human-recognizable names to distinguish from autonomous agents:
```bash
# Good examples
CHORUS_AGENT_ID=human-alice
CHORUS_AGENT_ID=human-bob-reviewer
CHORUS_AGENT_ID=human-ops-team
# Less clear (looks like autonomous agent)
CHORUS_AGENT_ID=agent-123
CHORUS_AGENT_ID=chorus-worker-1
```
---
## Runtime Behavior
### Startup Sequence
```
1. Parse CLI arguments
βββ --help β print help, exit 0
βββ --version β print version, exit 0
βββ (none) β continue
2. 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
3. Determine HAP mode
βββ Read CHORUS_HAP_MODE
βββ Default to "terminal"
βββ Validate mode (terminal or web)
4. Start appropriate interface
βββ TERMINAL:
β βββ Create TerminalInterface
β βββ Print welcome message
β βββ Show help
β βββ Announce human agent to network
β βββ Start command loop (blocking)
β
βββ WEB (currently stubbed):
βββ Log web mode request
βββ Log stub status warning
βββ Fall back to terminal mode
βββ TODO: Start HTTP server with WebSocket
5. Run until quit command or signal
βββ Terminal: wait for 'quit' command
βββ Web: wait for SIGINT/SIGTERM
6. Cleanup on shutdown
βββ Close active collaborative sessions
βββ Unsubscribe from PubSub topics
βββ Close P2P connections
βββ Stop HTTP servers
βββ Exit gracefully
```
### Signal Handling
| Signal | Behavior |
|--------|----------|
| SIGINT (Ctrl+C) | Graceful shutdown, close sessions |
| SIGTERM | Graceful shutdown |
| SIGHUP | Reload configuration (if applicable) |
### Human Participation Model
**Differences from Autonomous Agents:**
| Aspect | chorus-agent | chorus-hap |
|--------|--------------|------------|
| **Task Assignment** | Accepts automatically | Prompts human for approval |
| **HMMM Messages** | AI-generated reasoning | Human-composed reasoning |
| **Decision Voting** | Autonomous voting | Interactive voting prompts |
| **Code Execution** | Automatic in sandbox | Manual approval required |
| **Availability** | 24/7 operation | Human working hours |
| **Network Role** | Autonomous peer | Human oversight peer |
**Announcement to Network:**
On startup, HAP announces human presence:
```json
{
"type": "peer_announcement",
"agent_id": "human-alice",
"agent_type": "human",
"capabilities": [
"hmmm_composition",
"decision_participation",
"code_review",
"collaborative_editing"
],
"availability": "interactive",
"timestamp": "2025-09-30T14:30:00Z"
}
```
Published to: `chorus/coordination/v1` topic
**Purpose:**
- Helps autonomous agents identify human peers
- Adjusts interaction patterns (e.g., wait for human responses)
- Enables mixed human-agent collaboration
---
## P2P Networking
### Peer Discovery
**Same as chorus-agent:**
**mDNS (Local):**
- Discovers peers on local network
- Service name: `chorus-peer-discovery`
- Automatic peer connection
**DHT (Global):**
- Discovers peers across networks
- Requires bootstrap peers
- Content-addressed routing
### Topics Subscribed
| Topic | Purpose |
|-------|---------|
| `chorus/coordination/v1` | Task coordination messages |
| `hmmm/meta-discussion/v1` | Collaborative reasoning (human participates here) |
| `chorus/election/v1` | Leader election heartbeats |
| `chorus/decisions` | Decision announcements (voting) |
| `chorus/patches` | Patch submission and review |
| `chorus/collaborative` | Collaborative editing sessions |
| `chorus/health` | Health status broadcasts |
### Human-Specific Behaviors
**Slower Response Times:**
HAP doesn't auto-respond to messages. Autonomous agents should:
- Wait longer for human responses
- Include timeout considerations
- Provide clear prompts/context
**Interactive Approval:**
Tasks requiring human execution trigger interactive prompts:
```
hap>
π Task Assignment Request
====================================================================
Task ID: task-123
From: chorus-agent-2
Description: Review security patch for API endpoints
Priority: high
Estimated Time: 30 minutes
Accept this task? [y/N]: _
```
---
## Health Checks
### HTTP Endpoints
**Liveness Probe:**
```bash
curl http://localhost:8081/healthz
# Returns: 200 OK if HAP is alive
```
**Readiness Probe:**
```bash
curl http://localhost:8081/ready
# Returns: 200 OK if HAP is ready (human available)
# Returns: 503 if human is away/unavailable
```
**Health Details:**
```bash
curl http://localhost:8081/health
# Returns JSON with:
# - P2P connectivity status
# - Interface mode (terminal/web)
# - Active sessions
# - Human availability status
```
### Availability Indicators
HAP reports human availability status:
| Status | Meaning |
|--------|---------|
| `available` | Human actively using terminal |
| `idle` | Terminal open but no recent activity |
| `away` | Extended idle period |
| `offline` | HAP closed |
**Implementation:**
- Tracks last command timestamp
- Idle timeout: 15 minutes β `idle`
- Away timeout: 1 hour β `away`
---
## Integration Points
### HMMM Protocol
**Human Participation in Meta-Discussion:**
HAP enables humans to compose HMMM messages:
1. **Observation**: Share insights about system behavior
2. **Question**: Ask network for input
3. **Proposal**: Suggest solutions
4. **Objection**: Raise concerns
5. **Synthesis**: Summarize findings
**Message Format:**
```json
{
"type": "hmmm/proposal",
"id": "hmmm-20250930-abc123",
"author": "human-alice",
"author_type": "human",
"title": "Implement rate limiting",
"description": "...",
"confidence": 0.9,
"timestamp": "2025-09-30T14:30:00Z"
}
```
**See:** [HMMM Protocol](../protocols/hmmm.md)
### UCXL Context Addressing
**Browser Support:**
HAP provides UCXL browser for exploring contexts:
- Navigate context tree
- View related contexts
- Follow links between decisions/tasks
- Export context data
**Example Navigation:**
```
ucxl://chorus/task/20250930/task-123
βββ ucxl://chorus/decision/20250930/decision-abc
βββ ucxl://chorus/hmmm/20250930/proposal-xyz
βββ ucxl://chorus/patch/20250930/patch-def
```
**See:** [UCXL Specification](../protocols/ucxl.md)
### Decision Voting
**Democratic Participation:**
Humans vote on network decisions:
- Approve/Reject/Defer/Abstain
- Provide reasoning
- Express confidence level
- Track voting history
**Vote Weight:**
Configurable per deployment:
- Equal weight (1 human = 1 agent)
- Expert weight (humans have higher weight)
- Role-based weight
**See:** [Decision System](../packages/decisions.md)
---
## Example Deployments
### Local Development
```bash
#!/bin/bash
# Run HAP for local development
export CHORUS_LICENSE_ID=dev-local-123
export CHORUS_AGENT_ID=human-developer
export CHORUS_P2P_PORT=9001
export CHORUS_API_PORT=8080
export CHORUS_HEALTH_PORT=8081
export CHORUS_HAP_MODE=terminal
export OLLAMA_ENDPOINT=http://localhost:11434
./chorus-hap
```
### Docker Container
```dockerfile
FROM debian:bookworm-slim
# Install runtime dependencies
RUN apt-get update && apt-get install -y \
ca-certificates \
&& rm -rf /var/lib/apt/lists/*
# Copy binary
COPY chorus-hap /usr/local/bin/chorus-hap
# Expose ports
EXPOSE 9000 8080 8081 8082
# HAP typically runs interactively, but can be daemonized
ENTRYPOINT ["/usr/local/bin/chorus-hap"]
```
```bash
docker run -it \
--name chorus-hap-alice \
-e CHORUS_LICENSE_ID=dev-123 \
-e CHORUS_AGENT_ID=human-alice \
-e CHORUS_HAP_MODE=terminal \
-p 9001:9000 \
-p 8080:8080 \
-p 8081:8081 \
chorus-hap:latest
```
**Note:** Interactive terminal requires `-it` flags for stdin/stdout
### Web Mode Deployment (Future)
```bash
# When web interface is implemented:
export CHORUS_HAP_MODE=web
export CHORUS_HAP_WEB_PORT=8082
./chorus-hap
# Access via http://localhost:8082
```
### Multi-User Setup
```bash
# Multiple humans can join network with different agent IDs
# Human 1 (Alice)
CHORUS_AGENT_ID=human-alice CHORUS_P2P_PORT=9001 ./chorus-hap &
# Human 2 (Bob)
CHORUS_AGENT_ID=human-bob CHORUS_P2P_PORT=9002 ./chorus-hap &
# Both connect to same network via mDNS/DHT
# Both can collaborate on same decisions/tasks
```
---
## Troubleshooting
### HAP Won't Start
**Symptom:** HAP exits immediately with error
**Possible Causes:**
1. **Invalid or missing license**
```
β Failed to initialize CHORUS HAP: license validation failed
```
**Fix:** Check `CHORUS_LICENSE_ID` and KACHING server connectivity
2. **Port already in use**
```
β Failed to initialize: bind: address already in use
```
**Fix:** Change `CHORUS_P2P_PORT` or kill process on port
3. **P2P node creation failed**
```
β Failed to create P2P node: ...
```
**Fix:** Check network connectivity and firewall rules
### Terminal Not Accepting Input
**Symptom:** `hap>` prompt doesn't respond to keyboard
**Possible Causes:**
1. **Running without TTY**
**Fix:** Use `-it` flags if running in Docker: `docker run -it ...`
2. **STDIN redirected**
**Fix:** Ensure terminal has direct stdin access
3. **Terminal encoding issues**
**Fix:** Set `LANG=en_US.UTF-8` or appropriate locale
### No Peers Discovered
**Symptom:** HAP shows 0 connected peers
**Possible Causes:**
1. **mDNS blocked by firewall**
**Fix:** Allow UDP port 5353, or use bootstrap peers
2. **No other agents running**
**Fix:** Start at least one chorus-agent on network
3. **Network isolation**
**Fix:** Ensure HAP can reach other peers on P2P ports
### Web Mode Falls Back to Terminal
**Symptom:** Web mode requested but terminal interface starts
**Expected Behavior:** This is normal! Web interface is currently stubbed (Phase 3).
**Log Output:**
```
π Starting web interface for human interaction
β οΈ Web interface not yet implemented
π HAP running in stub mode - P2P connectivity established
π» Starting terminal interface for human interaction
```
**Workaround:** Use terminal interface until Phase 3 implementation
### HMMM Messages Not Received
**Symptom:** Compose HMMM message but peers don't see it
**Possible Causes:**
1. **Not subscribed to topic**
**Check:** Verify PubSub subscription status
**Fix:** Restart HAP to re-subscribe
2. **PubSub not enabled**
**Check:** `status` command shows PubSub status
**Fix:** Ensure DHT is enabled
3. **Message formatting error**
**Check:** HAP logs for publish errors
**Fix:** Report issue with message details
### Commands Don't Work
**Symptom:** Type command but nothing happens
**Possible Causes:**
1. **Typo in command name**
**Fix:** Type `help` to see valid commands
2. **Missing required arguments**
```
Usage: ucxl
```
**Fix:** Provide required arguments
3. **Backend error (silent failure)**
**Fix:** Check HAP logs for error messages
---
## Related Documentation
- [chorus-agent](chorus-agent.md) - Autonomous agent binary
- [chorus](chorus.md) - Deprecated compatibility wrapper
- [internal/runtime](../internal/runtime.md) - Shared runtime initialization
- [internal/hapui](../internal/hapui.md) - Terminal and web interface implementations
- [HMMM Protocol](../protocols/hmmm.md) - Meta-discussion protocol
- [UCXL Specification](../protocols/ucxl.md) - Context addressing
- [Decision System](../packages/decisions.md) - Democratic voting
- [Configuration](../deployment/configuration.md) - Environment variables
---
## Implementation Status
| Feature | Status | Notes |
|---------|--------|-------|
| **Terminal Interface** | β
Production | Full interactive REPL |
| **Web Interface** | β³ Stubbed | Phase 3 implementation pending |
| **P2P Networking** | β
Production | Same as chorus-agent |
| **HMMM Composition** | β
Production | Guided wizard with templates |
| **UCXL Browser** | β
Production | Interactive context navigation |
| **Decision Voting** | β
Production | Full voting workflow |
| **Collaborative Sessions** | β
Production | Multi-party editing |
| **Patch Creation** | β
Production | Diff-based submission |
| **Web Bridge** | πΆ Beta | Experimental browser access |
| **Task Approval** | β
Production | Interactive task acceptance |
| **Peer Management** | β
Production | List and monitor peers |
| **Health Checks** | β
Production | Liveness & readiness |
| **Availability Tracking** | β
Production | Idle/away detection |
| **License Validation** | β
Production | KACHING integration |
### Phase 3 Roadmap: Web Interface
**Planned Components:**
1. **HTTP Server with WebSocket**
- Real-time bidirectional communication
- Server-sent events for notifications
- WebSocket for collaborative sessions
2. **Web Forms for HMMM**
- Rich text editor for message composition
- Template selection dropdown
- Preview before submission
3. **Visual Context Browser**
- Tree view of UCXL contexts
- Graph visualization of relationships
- Search and filter capabilities
4. **Decision Voting UI**
- Card-based decision display
- Interactive voting buttons
- Real-time vote tallies
- Voting history timeline
5. **Dashboard**
- Network status overview
- Connected peers visualization
- Active sessions monitoring
- Personal activity feed
6. **Multi-User Support**
- Authentication for web users
- Session management
- User presence indicators
**Implementation Estimate:** 2-3 development sprints
**See:** `cmd/hap/main.go` lines 114-126 for TODO details
---
## Best Practices
### Agent ID Naming
**Recommended Format:**
```bash
# Human agents: prefix with "human-"
CHORUS_AGENT_ID=human-alice
CHORUS_AGENT_ID=human-bob-ops
CHORUS_AGENT_ID=human-security-team
# Makes it clear in network views who is human vs autonomous
```
### Working Hours Configuration
**Availability Signaling:**
HAP automatically signals availability based on activity. For scheduled availability:
```bash
# Set custom idle/away timeouts via configuration
# (Future enhancement)
CHORUS_HAP_IDLE_TIMEOUT=900 # 15 minutes
CHORUS_HAP_AWAY_TIMEOUT=3600 # 1 hour
```
### Collaborative Workflow
**Best Practice for Human-Agent Collaboration:**
1. **Start HAP at beginning of work session**
2. **Announce presence**: `announce` command
3. **Monitor network status**: Use `status` and `peers` regularly
4. **Participate in decisions**: Check for pending votes with `decide`
5. **Collaborate actively**: Join collaborative sessions when invited
6. **Review agent work**: Use UCXL browser to audit agent decisions
7. **Clean exit**: Use `quit` command (not Ctrl+C) for graceful shutdown
### Security Considerations
**Sensitive Operations:**
Humans can override agent decisions for sensitive operations:
- Production deployments
- Database schema changes
- Security policy updates
- API versioning changes
**Recommended Setup:**
- Use separate license for HAP (human-authorized)
- Grant HAP elevated permissions for overrides
- Require human approval for sensitive task categories
---
**Last Updated:** 2025-09-30