# CHORUS Internal Package: hapui **Package:** `chorus/internal/hapui` **Purpose:** Human Agent Portal (HAP) Terminal Interface for CHORUS **Lines of Code:** 3,985 lines (terminal.go) ## Overview The `hapui` package provides a comprehensive interactive terminal interface that allows human operators to participate in the CHORUS P2P agent network on equal footing with autonomous agents. It implements a full-featured command-line interface with support for HMMM reasoning, UCXL context browsing, decision voting, collaborative editing, patch management, and an embedded web bridge. This package enables humans to: - Communicate with autonomous agents using the same protocols - Participate in distributed decision-making processes - Browse and navigate UCXL-addressed contexts - Collaborate on code and content in real-time - Manage patches with temporal navigation - Access all functionality via terminal or web browser ## Architecture ### Core Types #### TerminalInterface The main interface for human agent interaction. ```go type TerminalInterface struct { runtime *runtime.SharedRuntime scanner *bufio.Scanner quit chan bool collaborativeSession *CollaborativeSession hmmmMessageCount int webServer *http.Server } ``` **Responsibilities:** - Command processing and routing - User input/output management - Session lifecycle management - Integration with SharedRuntime - Web server hosting #### CollaborativeSession Represents an active collaborative editing session. ```go type CollaborativeSession struct { SessionID string Owner string Participants []string Status string CreatedAt time.Time } ``` **Use Cases:** - Multi-agent code collaboration - Real-time content editing - Session state tracking - Participant management #### Decision Represents a network decision awaiting votes. ```go type Decision struct { ID string `json:"id"` Title string `json:"title"` Description string `json:"description"` Type string `json:"type"` Proposer string `json:"proposer"` ProposerType string `json:"proposer_type"` CreatedAt time.Time `json:"created_at"` Deadline time.Time `json:"deadline"` Status string `json:"status"` Votes map[string]DecisionVote `json:"votes"` Metadata map[string]interface{} `json:"metadata"` Version int `json:"version"` } ``` **Decision Types:** - `technical` - Architecture, code, infrastructure decisions - `operational` - Process, resource allocation - `policy` - Network rules, governance - `emergency` - Urgent security/stability issues (2-hour deadline) #### DecisionVote Represents a single vote on a decision. ```go type DecisionVote struct { VoterID string `json:"voter_id"` VoterType string `json:"voter_type"` Vote string `json:"vote"` // approve, reject, defer, abstain Reasoning string `json:"reasoning"` Timestamp time.Time `json:"timestamp"` Confidence float64 `json:"confidence"` // 0.0-1.0 confidence in vote } ``` **Vote Options:** - `approve` - Support this decision - `reject` - Oppose this decision - `defer` - Need more information - `abstain` - Acknowledge but not participate ## Terminal Commands ### Main Commands #### help Show available commands and help information. ```bash hap> help ``` **Output:** Complete list of terminal commands with descriptions. #### status Display current network and agent status. ```bash hap> status ``` **Shows:** - Agent ID, role, and type (Human/HAP) - P2P Node ID and connected peer count - Active task count and limits - DHT connection status - BACKBEAT integration status - Last updated timestamp **Example Output:** ``` πŸ“Š HAP Status Report ---------------------------------------- Agent ID: human-alice Agent Role: developer Agent Type: Human (HAP) Node ID: 12D3KooWAbc... Connected Peers: 5 Active Tasks: 2/10 DHT: βœ… Connected BACKBEAT: βœ… Connected ---------------------------------------- Last Updated: 14:32:15 ``` #### peers List connected P2P peers in the network. ```bash hap> peers ``` **Shows:** - Total peer count - Connection status - Guidance for peer discovery #### announce Re-announce human agent presence to the network. ```bash hap> announce ``` **Broadcasts:** - Agent ID and node ID - Agent type: "human" - Interface: "terminal" - Capabilities: hmmm_reasoning, decision_making, context_browsing, collaborative_editing - Current status: "online" **Published to:** `CapabilityBcast` topic via PubSub #### quit / exit Exit the HAP terminal interface. ```bash hap> quit ``` **Actions:** - Graceful shutdown - Network disconnection - Session cleanup #### clear / cls Clear the terminal screen and redisplay welcome message. ```bash hap> clear ``` ### HMMM Commands **Access:** `hap> hmmm` The HMMM (Human-Machine-Machine-Machine) command provides a sub-menu for collaborative reasoning messages. #### HMMM Sub-Commands ##### new Compose a new reasoning message. ```bash hmmm> new ``` **Interactive Wizard:** 1. Topic (e.g., engineering, planning, architecture) 2. Issue ID (numeric identifier for the problem) 3. Subject/Title (concise summary) 4. Reasoning content (press Enter twice to finish) **Message Structure:** - **Topic:** `CHORUS/hmmm/{topic}` - **Type:** `reasoning_start` - **Thread ID:** Auto-generated from topic and issue ID - **Message ID:** Unique identifier with timestamp **Example Flow:** ``` πŸ“ New HMMM Reasoning Message ---------------------------------------- Topic (e.g., engineering, planning, architecture): architecture Issue ID (number for this specific problem): 42 Subject/Title: Service mesh migration strategy Your reasoning (press Enter twice when done): We should migrate to a service mesh architecture to improve observability and resilience. Key considerations: 1. Gradual rollout across services 2. Training for ops team 3. Performance impact assessment [Enter] [Enter] βœ… HMMM reasoning message sent to network Topic: architecture Issue: #42 Thread: thread- Message ID: hap-1234567890-123456 ``` ##### reply Reply to an existing HMMM thread. ```bash hmmm> reply ``` **Interactive Wizard:** 1. Thread ID to reply to 2. Issue ID 3. Reasoning/response content **Use Cases:** - Build on previous reasoning - Add counterpoints - Request clarification - Provide additional context ##### query Ask the network for reasoning help. ```bash hmmm> query ``` **Interactive Wizard:** 1. Query topic 2. Issue ID (optional, auto-generated if not provided) 3. Question/problem statement 4. Additional context (optional) **Message Structure:** - **Topic:** `CHORUS/hmmm/query/{topic}` - **Type:** `reasoning_query` - **Urgency:** normal (default) **Example:** ``` ❓ HMMM Network Query ------------------------- Query topic: technical Issue ID: [Enter for new] Your question/problem: How should we handle backpressure in the task queue? Additional context: Current queue size averages 1000 tasks Agents process 10-50 tasks/minute Peak load reaches 5000+ tasks [Enter] [Enter] βœ… HMMM query sent to network Waiting for agent responses on issue #7834 Thread: thread- Message ID: hap-1234567890-123456 ``` ##### decide Propose a decision requiring network consensus. ```bash hmmm> decide ``` **Interactive Wizard:** 1. Decision topic 2. Decision title 3. Decision rationale 4. Voting options (comma-separated, defaults to approve/reject) **Creates:** - HMMM message with type `decision_proposal` - Decision object in DHT storage - Network announcement - 24-hour voting deadline (default) ##### help Show detailed HMMM system information. ```bash hmmm> help ``` **Displays:** - HMMM overview and purpose - Message types explained - Message structure details - Best practices for effective reasoning ##### back Return to main HAP menu. ### UCXL Commands **Access:** `hap> ucxl
` The UCXL command provides context browsing and navigation. **Address Format:** ``` ucxl://agent:role@project:task/path*temporal/ ``` **Components:** - `agent` - Agent ID or '*' for wildcard - `role` - Agent role (dev, admin, user, etc.) - `project` - Project identifier - `task` - Task or issue identifier - `path` - Optional resource path - `temporal` - Optional time navigation **Example:** ```bash hap> ucxl ucxl://alice:dev@webapp:frontend/src/components/ ``` **Display:** ``` πŸ”— UCXL Context Browser -------------------------------------------------- πŸ“ Address: ucxl://alice:dev@webapp:frontend/src/components/ πŸ€– Agent: alice 🎭 Role: dev πŸ“ Project: webapp πŸ“ Task: frontend πŸ“„ Path: src/components/ πŸ“¦ Content Found: ------------------------------ πŸ“„ Type: directory πŸ‘€ Creator: developer πŸ“… Created: 2025-09-30 10:15:23 πŸ“ Size: 2048 bytes πŸ“– Content: [directory listing or file content] ``` #### UCXL Sub-Commands ##### search Search for related UCXL content. ```bash ucxl> search ``` **Interactive Wizard:** 1. Search agent (current or custom) 2. Search role (current or custom) 3. Search project (current or custom) 4. Content type filter (optional) **Returns:** List of matching UCXL addresses with metadata. ##### related Find content related to the current address. ```bash ucxl> related ``` **Searches:** Same project and task, different agents/roles **Use Cases:** - Find parallel work by other agents - Discover related contexts - Understand project structure ##### history View address version history (stub). ```bash ucxl> history ``` **Status:** Not yet fully implemented **Planned Features:** - Temporal version listing - Change tracking - Rollback capabilities ##### create Create new content at this address. ```bash ucxl> create ``` **Interactive Wizard:** 1. Content type selection 2. Content input 3. Metadata configuration 4. Storage and announcement ##### help Show UCXL help information. ```bash ucxl> help ``` **Displays:** - Address format specification - Component descriptions - Temporal navigation syntax - Examples **Temporal Navigation Syntax:** - `*^/` - Latest version - `*~/` - Earliest version - `*@1234/` - Specific timestamp - `*~5/` - 5 versions back - `*^3/` - 3 versions forward ##### back Return to main menu. ### Decision Commands **Access:** `hap> decide ` The decide command provides distributed decision participation. #### Decision Sub-Commands ##### list List all active decisions. ```bash decision> list ``` **Output:** ``` πŸ—³οΈ Active Decisions Requiring Your Vote -------------------------------------------------- 1. DEC-A1B2C3 | Emergency: Database quarantine Type: emergency | Proposer: agent-42 (autonomous) Deadline: 45 minutes | Votes: 4 (75% approval) 2. DEC-D4E5F6 | Technical: Upgrade to libp2p v0.30 Type: technical | Proposer: alice (human) Deadline: 6 hours | Votes: 8 (62% approval) 3. DEC-G7H8I9 | Operational: Task timeout adjustment Type: operational | Proposer: agent-15 (autonomous) Deadline: 12 hours | Votes: 3 (33% approval) ``` ##### view View decision details. ```bash decision> view DEC-A1B2C3 ``` **Output:** ``` πŸ” Decision Details: DEC-A1B2C3 ---------------------------------------- πŸ“‹ Title: Emergency: Database quarantine 🏷️ Type: Emergency πŸ‘€ Proposer: agent-42 (autonomous) πŸ“… Proposed: 2025-09-30 14:15:30 ⏰ Deadline: 2025-09-30 16:00:00 (45 minutes remaining) πŸ“– Description: Database instance db-prod-03 is showing signs of corruption. Recommend immediate quarantine and failover to standby instance db-prod-04 to prevent data loss. Impact: 2-3 minute service interruption Risk if delayed: Potential data corruption spread πŸ—³οΈ Current Voting Status (4 total votes): βœ… Approve: 3 votes ❌ Reject: 0 votes ⏸️ Defer: 1 votes ⚠️ Abstain: 0 votes πŸ’­ Recent Reasoning: agent-42 (approve): "Data integrity is critical priority" agent-15 (approve): "Standby instance is healthy and ready" alice (defer): "Need more info on corruption extent" 🎯 Status: 75.0% approval (Passing) To vote on this decision, use: vote DEC-A1B2C3 ``` ##### vote Cast a vote on a decision. ```bash decision> vote DEC-A1B2C3 ``` **Interactive Wizard:** 1. Vote selection (1-4: approve, reject, defer, abstain) 2. Reasoning/justification input (required) 3. Confirmation **Example:** ``` πŸ—³οΈ Cast Vote on DEC-A1B2C3 ------------------------------ Vote Options: 1. βœ… approve - Support this decision 2. ❌ reject - Oppose this decision 3. ⏸️ defer - Need more information 4. ⚠️ abstain - Acknowledge but not participate Your vote (1-4): 1 You selected: approve Reasoning/Justification (required for transparency): Explain why you are voting this way (press Enter twice when done): Data integrity is our highest priority. The corruption is confirmed and contained to one instance. Failover plan is sound. [Enter] [Enter] πŸ“‹ Vote Summary: Decision: DEC-A1B2C3 Your Vote: approve Reasoning: Data integrity is our highest priority... Submit this vote? (y/n): y πŸ”„ Submitting vote... βœ… Your approve vote on DEC-A1B2C3 has been recorded πŸ“’ Vote announced via HMMM reasoning network πŸ’Œ Vote reasoning published to network for transparency πŸ”” Other network members will be notified of your participation ``` **Vote Storage:** - Saved to DHT with decision object - Versioned (decision.Version++) - Broadcast via HMMM on topic `CHORUS/decisions/vote/{decisionID}` ##### propose Propose a new decision. ```bash decision> propose ``` **Interactive Wizard:** 1. Decision type (1-4: technical, operational, policy, emergency) 2. Title (concise summary) 3. Detailed rationale 4. Custom voting options (optional, defaults to approve/reject/defer/abstain) 5. Voting deadline (hours, default: 24, emergency: 2) **Example:** ``` πŸ“ Propose New Network Decision ----------------------------------- Decision Types: 1. technical - Architecture, code, infrastructure 2. operational - Process, resource allocation 3. policy - Network rules, governance 4. emergency - Urgent security/stability issue Decision type (1-4): 1 Decision title (concise summary): Adopt gRPC for inter-agent communication Detailed rationale (press Enter twice when done): Current JSON-over-HTTP adds latency and parsing overhead. gRPC with Protocol Buffers would provide: - Type-safe communication - Bidirectional streaming - Better performance - Native load balancing [Enter] [Enter] Custom voting options (comma-separated, or press Enter for default): [Enter] Voting deadline in hours (default: 24): [Enter] πŸ“‹ Decision Proposal Summary: Type: technical Title: Adopt gRPC for inter-agent communication Options: approve, reject, defer, abstain Deadline: 24h from now Rationale: Current JSON-over-HTTP adds latency... Submit this decision proposal? (y/n): y πŸ”„ Creating decision proposal... βœ… Decision DEC-J1K2L3 proposed successfully πŸ“’ Decision announced to all network members ⏰ Voting closes in 24h πŸ—³οΈ Network members can now cast their votes ``` **Decision Creation:** - Generates unique ID: `DEC-{randomID}` - Stores in DHT - Announces via HMMM on topic `CHORUS/decisions/proposal/{type}` - Sets appropriate priority metadata ##### status Show decision system status. ```bash decision> status ``` **Mock Status (development):** ``` πŸ“Š Decision System Status ------------------------------ πŸ—³οΈ Active Decisions: 3 ⏰ Urgent Decisions: 1 (emergency timeout) πŸ‘₯ Network Members: 12 (8 active, 4 idle) πŸ“Š Participation Rate: 67% (last 7 days) βœ… Consensus Success Rate: 89% βš–οΈ Decision Types: Technical: 45%, Operational: 30% Policy: 20%, Emergency: 5% πŸ”” Recent Activity: β€’ DEC-003: Emergency quarantine decision (45m left) β€’ DEC-002: Task timeout adjustment (6h 30m left) β€’ DEC-001: libp2p upgrade (2h 15m left) β€’ DEC-055: Completed - Storage encryption (βœ… approved) ``` ##### help Show decision help information. ##### back Return to main menu. ### Patch Commands **Access:** `hap> patch` The patch command provides patch creation, review, and submission. #### Patch Sub-Commands ##### create Create a new patch. **Interactive Wizard:** 1. Patch type (context, code, config, docs) 2. Base UCXL address (what you're modifying) 3. Patch title 4. Patch description 5. Content changes **Patch Types:** - **context** - UCXL context content changes - **code** - Traditional diff-based code changes - **config** - Configuration changes - **docs** - Documentation updates **Example:** ``` πŸ“ Create New Patch ------------------------- Patch Types: 1. context - UCXL context content changes 2. code - Traditional code diff 3. config - Configuration changes 4. docs - Documentation updates Patch type (1-4): 2 Base UCXL address (what you're modifying): ucxl://alice:dev@webapp:bug-123/src/main.go Patch title: Fix nil pointer dereference in request handler πŸ“– Fetching current content... πŸ“„ Current Content: [shows current file content] [Content editing workflow continues...] ``` ##### diff Review changes with temporal comparison (stub). ##### submit Submit patch for peer review via HMMM network. **Workflow:** 1. Validate patch completeness 2. Generate patch ID 3. Store in DHT 4. Announce via HMMM on `CHORUS/patches/submit` topic 5. Notify network members ##### list List active patches (stub). ##### review Participate in patch review process (stub). ##### status Show patch system status (stub). ##### help Show patch help information. **Displays:** - Patch types explained - Temporal navigation syntax - Workflow stages - Integration points (HMMM, UCXL, DHT, Decision System) ##### back Return to main menu. ### Collaborative Editing Commands **Access:** `hap> collab` The collab command provides collaborative session management (stub implementation). #### Collab Sub-Commands ##### start Start a new collaborative session. ##### join Join an existing session. ##### list List active collaborative sessions. ##### status Show collaborative session status. ##### leave Leave current session. ##### help Show collaborative editing help. ##### back Return to main menu. ### Web Bridge Commands **Access:** `hap> web` Start the HAP web bridge for browser access. **Features:** - HTTP server on port 8090 - HTML interface for all HAP features - REST API endpoints - WebSocket support for real-time updates (stub) **Endpoints:** **Static UI:** - `/` - Home dashboard - `/status` - Agent status - `/decisions` - Decision list - `/decisions/{id}` - Decision details - `/collab` - Collaborative editing (stub) - `/patches` - Patch management (stub) - `/hmmm` - HMMM messages (stub) **API:** - `/api/status` - JSON status - `/api/decisions` - JSON decision list - `/api/decisions/vote` - POST vote submission - `/api/decisions/propose` - POST decision proposal (stub) - `/api/collab/sessions` - JSON session list (stub) - `/api/hmmm/send` - POST HMMM message (stub) **WebSocket:** - `/ws` - Real-time updates (stub) **Example:** ```bash hap> web ``` **Output:** ``` 🌐 Starting HAP Web Bridge ------------------------------ πŸ”Œ Starting web server on port 8090 βœ… Web interface available at: http://localhost:8090 πŸ“± Browser HAP interface ready πŸ”— API endpoints available at: /api/* ⚑ Real-time updates via WebSocket: /ws πŸ’‘ Press Enter to return to terminal... ``` **Web Interface Features:** - Dashboard with quick access cards - Decision voting interface with JavaScript - Real-time status updates - Responsive design - Dark mode support (status page) ## Integration Points ### SharedRuntime Integration The TerminalInterface depends on `runtime.SharedRuntime` for: - **Config:** Agent ID, role, configuration - **Node:** P2P node ID, peer connections - **TaskTracker:** Active task monitoring - **DHTNode:** Distributed storage access - **BackbeatIntegration:** Timing system status - **PubSub:** Message publishing - **EncryptedStorage:** UCXL content retrieval - **Logger:** Logging interface ### HMMM Integration HMMM messages are published using: ```go router := hmmm.NewRouter(t.runtime.PubSub) router.Publish(ctx, message) ``` **Message Structure:** ```go hmmm.Message{ Topic: "CHORUS/hmmm/{category}", Type: "reasoning_start|reasoning_reply|reasoning_query|decision_proposal", Payload: map[string]interface{}{...}, Version: "1.0", IssueID: issueID, ThreadID: threadID, MsgID: msgID, NodeID: nodeID, HopCount: 0, Timestamp: time.Now().Unix(), Message: "Human-readable summary", } ``` ### UCXL Integration UCXL addresses are parsed and resolved using: ```go parsed, err := ucxl.ParseUCXLAddress(address) content, metadata, err := t.runtime.EncryptedStorage.RetrieveUCXLContent(address) ``` ### Decision Storage Decisions are stored in DHT using the storage interface: ```go func (t *TerminalInterface) saveDecision(decision *Decision) error func (t *TerminalInterface) getDecisionByID(decisionID string) (*Decision, error) func (t *TerminalInterface) getActiveDecisions() ([]Decision, error) ``` ### PubSub Topics **Published Topics:** - `CapabilityBcast` - Agent presence announcements - `CHORUS/hmmm/{topic}` - HMMM reasoning messages - `CHORUS/hmmm/query/{topic}` - HMMM queries - `CHORUS/hmmm/decision/{topic}` - Decision proposals - `CHORUS/decisions/vote/{decisionID}` - Vote announcements - `CHORUS/decisions/proposal/{type}` - Decision proposals - `CHORUS/patches/submit` - Patch submissions - `CHORUS/collab/{event}` - Collaborative events ## User Experience Features ### Interactive Wizards All complex operations use multi-step interactive wizards: - Clear prompts with examples - Input validation - Confirmation steps - Progress feedback - Error handling with guidance ### Visual Feedback Rich terminal output with: - Emoji indicators (βœ… ❌ πŸ”„ πŸ“Š πŸ—³οΈ etc.) - Color support (via ANSI codes in web interface) - Progress indicators - Status summaries - Formatted tables and lists ### Help System Comprehensive help at every level: - Main help menu - Sub-command help - Inline examples - Best practices - Troubleshooting guidance ### Error Handling User-friendly error messages: - Clear problem description - Suggested solutions - Alternative actions - Non-blocking errors with warnings ## Web Interface ### Home Dashboard Provides quick access to all HAP features with cards: - Decision Management - Collaborative Editing - Patch Management - HMMM Network - Network Status - Live Updates ### Decision Voting Interface Full-featured web UI for decisions: - Decision list with vote counts - Inline voting with prompts - JavaScript-based vote submission - Real-time status updates - Color-coded vote indicators ### API Design RESTful JSON API: - Standard HTTP methods - JSON request/response - Error handling with HTTP status codes - Authentication ready (not yet implemented) ### Real-time Updates WebSocket endpoint for: - Decision updates - Vote notifications - Collaborative session events - Network status changes **Status:** Stub implementation, connection established but no event streaming yet. ## Development Status ### Fully Implemented - βœ… Terminal command processing - βœ… HMMM message composition (all types) - βœ… UCXL address parsing and browsing - βœ… Decision voting and proposal - βœ… Status reporting - βœ… Peer listing - βœ… Web bridge with basic UI - βœ… Decision voting API - βœ… Agent presence announcements ### Partially Implemented - ⚠️ UCXL content retrieval (depends on storage backend) - ⚠️ Decision storage (DHT integration) - ⚠️ Patch creation (wizard complete, submission pending) - ⚠️ Web decision proposal API - ⚠️ WebSocket real-time updates ### Stub / TODO - πŸ”œ Collaborative editing sessions - πŸ”œ Patch review workflow - πŸ”œ UCXL history tracking - πŸ”œ Web HMMM message interface - πŸ”œ Web collaborative editing interface - πŸ”œ Web patch management interface - πŸ”œ Authentication and authorization - πŸ”œ Session persistence ## Best Practices ### For Developers **Adding New Commands:** 1. Add case to `commandLoop()` switch statement 2. Implement handler function `handle{Command}Command()` 3. Add help text to `printHelp()` 4. Document in this file **Adding Web Endpoints:** 1. Add route in `startWebBridge()` 2. Implement handler function `web{Feature}()` or `api{Feature}()` 3. Follow existing HTML/JSON patterns 4. Add API documentation **Error Handling:** ```go if err != nil { fmt.Printf("❌ Operation failed: %v\n", err) fmt.Println("πŸ’‘ Try: [suggestion]") return } ``` **User Feedback:** ```go fmt.Println("πŸ”„ Processing...") // operation fmt.Println("βœ… Operation successful") ``` ### For Users **Effective HMMM Usage:** - Be specific and clear in reasoning - Include relevant context and background - Ask follow-up questions to guide discussion - Build on previous messages in threads - Avoid vague or overly broad statements **Decision Voting:** - Always provide detailed reasoning - Consider impact on all network members - Vote promptly on urgent decisions - Use defer when more information is needed - Abstain when lacking relevant expertise **UCXL Navigation:** - Use wildcards (*) for broad searches - Use temporal navigation to track changes - Include full context in addresses - Follow project naming conventions ## Security Considerations ### Current Implementation - No authentication required (trusted network assumption) - No authorization checks - No input sanitization (trusted users) - No rate limiting - No session security ### Future Enhancements - Agent identity verification - Role-based access control - Input validation and sanitization - Rate limiting on votes and proposals - Encrypted web sessions - Audit logging ## Testing ### Manual Testing Start HAP and exercise all commands: ```bash make build-hap ./build/chorus-hap ``` Test each command category: - status, peers, announce - hmmm (new, reply, query, decide) - ucxl (search, related, history, create) - decide (list, view, vote, propose) - patch (create, submit) - collab (start, join, list) - web (access all endpoints) ### Integration Testing Test with multiple agents: 1. Start autonomous agents 2. Start HAP 3. Verify presence announcement 4. Send HMMM messages 5. Propose and vote on decisions 6. Monitor network activity ### Web Interface Testing Test browser functionality: 1. Start web bridge: `hap> web` 2. Open http://localhost:8090 3. Test decision voting 4. Verify WebSocket connection 5. Test API endpoints with curl ## Performance Considerations ### Resource Usage - **Memory:** Minimal, single-threaded scanner - **CPU:** Low, blocking I/O on user input - **Network:** Burst traffic on message sends - **Storage:** DHT operations on demand ### Scalability - Supports hundreds of concurrent agents - DHT lookups may slow with large decision sets - Web server limited by single Go routine per connection - WebSocket scaling depends on implementation ## Troubleshooting ### Common Issues **"Failed to announce human agent presence"** - Check PubSub connection - Verify network connectivity - Ensure runtime is initialized **"Storage system not available"** - DHT not configured - EncryptedStorage not initialized - Network partition **"Decision not found"** - Decision not yet propagated - DHT lookup failure - Invalid decision ID **"Web server error"** - Port 8090 already in use - Permission denied (use port >1024) - Network interface not available ### Debug Mode Enable verbose logging in SharedRuntime: ```go runtime.Logger.SetLevel(slog.LevelDebug) ``` Monitor network traffic: ```bash # Watch HMMM messages # Watch decision announcements # Check peer connections ``` ## Future Enhancements ### Phase 2 (Planned) - Full collaborative editing implementation - Complete patch review workflow - UCXL history with temporal navigation - Enhanced web interface with real-time updates - Mobile-responsive design improvements ### Phase 3 (Future) - Rich text editor in web interface - Visual diff tools - Decision analytics dashboard - Agent reputation system - Notification system (email, webhooks) - Plugin architecture for custom commands ## Related Documentation - `/docs/comprehensive/internal/runtime.md` - SharedRuntime integration - `/docs/comprehensive/pkg/hmmm.md` - HMMM protocol details - `/docs/comprehensive/pkg/ucxl.md` - UCXL addressing system - `/docs/comprehensive/pkg/storage.md` - DHT storage backend - `/docs/comprehensive/pkg/p2p.md` - P2P networking layer ## Summary The `hapui` package is the primary interface for human participation in the CHORUS network. It provides: - **3,985 lines** of comprehensive terminal interface - **9 main command categories** with rich sub-menus - **HMMM integration** for collaborative reasoning - **UCXL browsing** for context navigation - **Decision voting** with transparency and reasoning - **Patch management** with temporal navigation - **Web bridge** for browser-based access - **RESTful API** for external integrations The interface treats humans as first-class network members, providing the same capabilities as autonomous agents while adding human-friendly wizards, help systems, and visual feedback. **Current Status:** Production-ready for terminal interface, web interface in active development with core features functional and advanced features planned for upcoming phases.