Orchestrata Ultimate / Specs / 050-cheetahclaws-integration
050-cheetahclaws-integration: CheetahClaws Integration
Integration of CheetahClaws v3.05.6 into Orchestrata as the primary terminal interface and file editing system. This brings CheetahClaws' rich TUI, 40+ slash commands, checkpoint system, and multi-provider model support into the Ultimate Hybrid architecture.
At a glance
| Item | Value |
|---|---|
| Spec directory | specs/050-cheetahclaws-integration/ |
| Status line in the spec | Complete |
| Requirement IDs defined | 5 |
With a @traces citation in src/ |
4 (80.0%) |
With a @traces citation in tests/ |
0 (0.0%) |
| Tracked files | 3 |
| RTM page | 050-cheetahclaws-integration |
Reading this spec
This spec brings CheetahClaws v3.05.6 into Orchestrata as the primary terminal interface and file-editing system. CheetahClaws contributes a rich terminal UI, more than 40 slash commands, a checkpoint system and multi-provider model support, and the spec describes how these fit into the Ultimate Hybrid architecture. The problem it addresses is that file edits made by a single agent have no coordination, no policy check and no safe way back; the spec adds all three.
Its three user stories cover multi-agent collaborative file editing, checkpoint-based safe experimentation and multi-provider model selection. Five requirements are recorded. REQ-050-FR1 has the Cd, Qa, Ar and Ux agents review a proposed file edit in parallel and requires approval from all of them before a change is committed. REQ-050-FR2 enforces PAM++ governance policies before any file operation and blocks violations. REQ-050-FR8 supports Anthropic, OpenAI, Google Gemini and local Ollama models with automatic fallback when a provider fails. REQ-050-FR9 routes all slash commands through the Orchestrata kernel with agent dispatch. A code-derived requirement, REQ-050-001, describes dispatching a CXP packet for a proposed edit and collecting each agent's verdict (approve, block, suggest, timeout or error).
The key design decisions are stated plainly. All four agents run at the same time to keep latency low. Governance is checked first, before any modification. A checkpoint captures files, conversation and knowledge graph state in one atomic operation. Failures fall back from the model to an alternate provider, then to single-agent mode, then to an error with a retry option. File paths are validated against traversal patterns at the entry point. The governance section also requires extra review for edits touching files that hold secrets and for bulk operations over ten files.
In the code, the work is concentrated in the CheetahClaws integration package, with supporting citations in the TUI gateway handler and in the QA volk, the architect volk and the code director volk. The requirements traceability matrix lists each ID.
The spec's own status line reads Complete, and it tracks 3 files. Measured coverage is 4 of 5 requirements cited by at least one @traces in src/ (80.0%), spread over 5 modules; the module citing the most of them is orchestrata_ultimate/integrations/cheetahclaws/__init__ (4 requirements). In tests/, 0 requirements are cited by a test-side @traces. The one gap is REQ-050-FR8 (provider support and fallback), which no @traces names; the behaviour may still exist in code that was never annotated.
Requirements
Checkbox is the state recorded in the requirements checklist; Traced by is the count of src/ symbols whose @traces names the ID.
| ID | Done | Requirement | Traced by |
|---|---|---|---|
REQ-050-FR1-001 |
no | The system SHALL coordinate file edits across Cd, Qa, Ar, and Ux agents in parallel, requiring approval from all agents before committing changes. | 18 |
REQ-050-FR2-001 |
no | The system SHALL enforce PAM++ governance policies before any file operation, blocking operations that violate security or policy rules. | 5 |
REQ-050-FR8-001 |
no | The system SHALL support Anthropic, OpenAI, Google Gemini, and local Ollama models with automatic fallback on provider failure. | none |
REQ-050-FR9-001 |
no | The system SHALL route all 40+ CheetahClaws slash commands through Orchestrata kernel with appropriate agent dispatch. | 8 |
REQ-050-001 |
no | <!-- code-derived --> Dispatch a CXP packet describing a proposed edit to a set of agents (U:Cd, U:Qa, U:Ar, optionally U:Ux) in parallel and collect each agent's structured verdict (APPROVE/BLOCK/SUGGEST/TIMEOUT/ERROR) as AgentFeedback, per MultiAgentCoordinator's docstring in orchestrata_ultimate/integrations/cheetahclaws/__init__.py. This overlaps FR-001's multi-agent coordination requirement but is tagged as a separate component-level id in code — confirm with the spec owner whether it should be merged into REQ-050-FR1-001 or kept as a distinct requirement. |
4 |
Code that traces this spec
Checklists
checklists/requirements.md
The requirement list above comes from this file; 0 of 5 checkbox items are ticked.
Other tracked files
specs/050-cheetahclaws-integration/compliance-audit.md
Full spec text
Verbatim from specs/050-cheetahclaws-integration/spec.md; headings are pushed down two levels.
SPEC-050: CheetahClaws Integration
Metadata
- Spec ID: 050-cheetahclaws-integration
- Title: CheetahClaws Integration - Rich TUI and File Tools
- Author: Mohamed
- Status: Complete
- Created: 2026-04-08
- Last Updated: 2026-04-09
- Priority: P0
- Components: Rich TUI, File Editing Tools, Checkpoint System, Command Palette
- Version: 1.0.1
Overview
What
Integration of CheetahClaws v3.05.6 into Orchestrata as the primary terminal interface and file editing system. This brings CheetahClaws' rich TUI, 40+ slash commands, checkpoint system, and multi-provider model support into the Ultimate Hybrid architecture.
Why
- Leverage CheetahClaws' mature terminal interface (460 stars, production-ready)
- Provide rich file editing with diff rendering and rollback
- Enable checkpoint system for safe experimentation
- Support multi-provider models (Claude, OpenAI, Gemini, local)
- Combine with Orchestrata's multi-agent coordination
How
- Import CheetahClaws Rich TUI as the terminal interface
- Adapt file tools for multi-agent coordination
- Integrate checkpoint system with Orchestrata sessions
- Route slash commands through Orchestrata kernel
- Enhance with knowledge graph and governance
User Scenarios
US-001: Multi-Agent Collaborative File Editing
- As a Developer
- I want to edit files with coordinated feedback from multiple specialized agents
- So that I can ensure code quality, security, architecture, and UX are all considered in every change
- Acceptance Criteria:
- Edit command triggers parallel review by Cd, Qa, Ar, and Ux agents
- All agents provide approval or feedback before changes are committed
- Diff display shows changes with agent annotations
- Edit is rejected if any agent blocks it
US-002: Checkpoint-Based Safe Experimentation
- As a Developer
- I want to create checkpoints before risky changes and rollback if needed
- So that I can experiment freely without fear of losing working code
- Acceptance Criteria:
- Checkpoint captures files, conversation history, and knowledge graph state
- Rollback restores all three layers to checkpoint state
- Rollback completes within 1 second
- Failed rollback provides clear error and recovery options
US-003: Multi-Provider Model Selection
- As a Developer
- I want to switch between different LLM providers for different tasks
- So that I can optimize for cost, speed, or quality based on task requirements
- Acceptance Criteria:
- Support for Anthropic, OpenAI, Google, and local Ollama models
- Model switch completes within 50ms
- Routing suggestions based on agent type and task
- Fallback to alternate provider on API failure
Terminology
| Term | Definition |
|---|---|
| CheetahClaws | Rich TUI framework providing terminal interface with 40+ slash commands |
| Checkpoint | Snapshot of files, conversation, and knowledge graph state for rollback |
| UltimateTUI | Orchestrata-adapted version of CheetahClaws TUI |
| Multi-Agent Coordination | Simultaneous collaboration of Cd, Qa, Ar, and Ux agents on edits |
| PAM++ | Policy Automation and Management Plus Plus - governance framework |
| CXP Packet | Coordination Exchange Protocol packet for inter-agent messaging |
| Knowledge Graph (KG) | Graph database tracking code relationships and agent decisions |
| Rollback | Process of restoring system state to a previous checkpoint |
Data Models (JSON Schemas)
EditRequest
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"required": ["file_path", "old_string", "new_string"],
"properties": {
"file_path": {
"type": "string",
"pattern": "^(?!.*(\\.\\.|/\\.\\.)).*$",
"description": "Path to file to edit (no path traversal)"
},
"old_string": {
"type": "string",
"description": "Text to replace"
},
"new_string": {
"type": "string",
"description": "Replacement text"
},
"strict": {
"type": "boolean",
"default": true,
"description": "Whether old_string must match exactly"
}
}
}
EditResult
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"required": ["success", "file_path"],
"properties": {
"success": {
"type": "boolean"
},
"file_path": {
"type": "string"
},
"diff": {
"type": "string",
"description": "Unified diff of changes"
},
"bytes_changed": {
"type": "integer"
},
"agents_responded": {
"type": "array",
"items": {"type": "string"}
}
}
}
Checkpoint
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"required": ["id", "name", "created_at"],
"properties": {
"id": {
"type": "string",
"pattern": "^CP:[0-9]+$"
},
"name": {
"type": "string",
"minLength": 1,
"maxLength": 100
},
"description": {
"type": "string",
"maxLength": 500
},
"created_at": {
"type": "string",
"format": "date-time"
},
"size_mb": {
"type": "number",
"minimum": 0
},
"tags": {
"type": "array",
"items": {"type": "string"}
},
"parents": {
"type": "array",
"items": {"type": "string"}
}
}
}
AgentResponse
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"required": ["agent_id", "timestamp", "status"],
"properties": {
"agent_id": {
"type": "string",
"pattern": "^U:[A-Za-z]+$"
},
"timestamp": {
"type": "string",
"format": "date-time"
},
"status": {
"type": "string",
"enum": ["success", "failed", "timeout", "governance_blocked"]
},
"content": {
"type": "string"
},
"tools_used": {
"type": "array",
"items": {"type": "string"}
},
"errors": {
"type": "array",
"items": {"type": "string"}
}
}
}
Technical Design
System Architecture
The CheetahClaws integration follows a layered architecture:
┌─────────────────────────────────────────────────────────────┐
│ UltimateTUI Layer │
│ (Command Palette, Rich Display, Live Diff, Syntax Highlight)│
└─────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────┐
│ Command Router Layer │
│ (40+ Slash Commands → Orchestrata Kernel → Agent Dispatch) │
└─────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────┐
│ Multi-Agent Coordination Layer │
│ (CXP Packets, Parallel Agent Execution) │
│ ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐ │
│ │ U:Cd │ │ U:Qa │ │ U:Ar │ │ U:Ux │ │
│ │(Create) │ │(Review) │ │(Architect)│ │(UX) │ │
│ └─────────┘ └─────────┘ └─────────┘ └─────────┘ │
└─────────────────────────────────────────────────────────────┘
│
┌───────────────┼───────────────┐
▼ ▼ ▼
┌─────────────────┐ ┌───────────────┐ ┌──────────────┐
│ CheetahClaws │ │ Knowledge │ │ PAM++ │
│ File Tools │ │ Graph │ │ Governance │
│ (Edit/Read/ │ │ (Neo4j) │ │ (Policy │
│ Write/Bash) │ │ │ │ Enforcement│
└─────────────────┘ └───────────────┘ └──────────────┘
Component Responsibilities
| Component | Responsibility |
|---|---|
UltimateTUI |
Terminal interface, command parsing, rich display |
CommandRouter |
Route slash commands to appropriate handlers |
UltimateEditTool |
Multi-agent coordination for file edits |
CheckpointManager |
Snapshot and restore system state |
ModelProvider |
Multi-provider LLM routing and fallback |
GovernanceBridge |
PAM++ policy enforcement integration |
KnowledgeGraphBridge |
Event logging and context queries |
Data Flow
- Edit Flow: User command → TUI → Command Router → Multi-Agent Coordination → Governance Check → CheetahClaws Edit Tool → Knowledge Graph Log → Checkpoint
- Query Flow: User command → TUI → Knowledge Graph Bridge → Neo4j Query → Rich Display
- Checkpoint Flow: User command → TUI → Checkpoint Manager → File Snapshot + Session Snapshot + KG Snapshot → Restore on demand
Key Design Decisions
- Parallel Agent Execution: All 4 agents execute simultaneously for each edit to minimize latency
- Governance-First: PAM++ checks occur before any file modification
- Atomic Checkpoints: Files, conversation, and KG state captured in single atomic operation
- Fallback Hierarchy: Model failure → Alternate provider → Single-agent mode → Error with retry option
- Path Validation: All file paths validated against traversal patterns at entry point
Security Requirements
Authentication
- System SHALL validate user identity before any file operation
- System SHALL support API key and OAuth2 authentication
- System SHALL expire sessions after 24 hours of inactivity
Authorization
- System SHALL enforce PAM++ policies for file operations
- System SHALL check file ownership and permissions before edit
- System SHALL block operations on files outside allowed directories
Input Validation
- System SHALL validate file paths against path traversal attacks
- System SHALL reject files larger than 10MB
- System SHALL detect and reject binary file edits
- System SHALL sanitize user input in command arguments
Audit Logging
- System SHALL log all file operations with user, file, timestamp
- System SHALL log all governance blocks with policy details
- System SHALL retain logs for 90 days minimum
Governance Requirements (PAM++)
File Operation Policies
- All edit operations MUST pass governance check before execution
- File deletion in system directories MUST require elevated approval
- Bulk operations (>10 files) MUST be logged and may require approval
- Operations on files with secrets MUST trigger additional review
Policy Enforcement Points
- Pre-edit: Check if file contains secrets (prevent accidental exposure)
- Pre-delete: Check if file is part of critical system
- Pre-bulk: Check if operation rate exceeds threshold
- Post-execution: Log operation for audit trail
CheetahClaws Architecture
TUI Interface
from cheetahclaws import TUI
from cheetahclaws.tools import Read, Write, Edit, Bash, Grep
from cheetahclaws.checkpoint import CheckpointManager
class UltimateTUI:
"""CheetahClaws TUI adapted for Orchestrata."""
def __init__(self, orchestrator):
self.orchestrator = orchestrator
self.tui = TUI()
self.checkpoint_manager = CheckpointManager()
self.command_handlers = self._setup_command_handlers()
def _setup_command_handlers(self):
"""Map CheetahClaws commands to Orchestrata actions."""
return {
'/edit': self.handle_edit,
'/read': self.handle_read,
'/write': self.handle_write,
'/bash': self.handle_bash,
'/grep': self.handle_grep,
'/checkpoint': self.handle_checkpoint,
'/rewind': self.handle_rewind,
'/memory': self.handle_memory,
'/agents': self.handle_agents,
'/model': self.handle_model,
'/config': self.handle_config,
'/audit': self.handle_audit,
}
Available Commands (40+)
CHEETAHCLAWS_COMMANDS = {
# File Operations
'/read': 'Read file contents',
'/write': 'Write new file',
'/edit': 'Edit file content',
'/insert': 'Insert text at position',
'/delete': 'Delete text range',
'/move': 'Move/rename file',
'/copy': 'Copy file',
'/remove': 'Remove file',
# Search and Navigation
'/grep': 'Search file contents',
'/find': 'Find files',
'/cd': 'Change directory',
'/ls': 'List directory',
'/tree': 'Show directory tree',
# Shell Operations
'/bash': 'Execute shell command',
'/python': 'Execute Python code',
'/node': 'Execute Node.js code',
# Git Operations
'/git': 'Git command',
'/commit': 'Git commit',
'/diff': 'Show git diff',
'/status': 'Git status',
# Checkpoint System
'/checkpoint': 'Create checkpoint',
'/rewind': 'Rollback to checkpoint',
'/list': 'List checkpoints',
'/restore': 'Restore checkpoint',
# Agent Coordination
'/agents': 'List active agents',
'/assign': 'Assign task to agent',
'/review': 'Request agent review',
'/approve': 'Approve agent work',
# Model and Configuration
'/model': 'Switch models',
'/config': 'Configuration',
'/settings': 'User settings',
# Knowledge and Context
'/memory': 'Query knowledge graph',
'/context': 'Show context',
'/history': 'Show command history',
# Audit and Governance
'/audit': 'View audit trail',
'/governance': 'Check policies',
'/verify': 'Verify changes',
# Help and Documentation
'/help': 'Show help',
'/docs': 'Open documentation',
'/examples': 'Show examples',
# Workflow
'/workflow': 'Start workflow',
'/task': 'Manage tasks',
'/deploy': 'Deploy application',
'/test': 'Run tests',
}
Integration with Orchestrata
Multi-Agent File Editing
class UltimateEditTool(Edit):
"""Enhanced EditTool with multi-agent coordination."""
async def execute(
self,
file_path: str,
old_string: str,
new_string: str
) -> EditResult:
# 1. Governance check via PAM++
if not await self.orchestrator.governance.check(
action="edit_file",
context={
"path": file_path,
"change": new_string,
"user": self.tui.current_user
}
):
return EditResult(
success=False,
error="Blocked by governance policy"
)
# 2. Create CXP packet for multi-agent coordination
packet = self.orchestrator.cxp.create_packet(
from_agent="U:TUI",
to_agent="U:Cd",
subject="multi_agent_edit",
payload={
"file_path": file_path,
"old_string": old_string,
"new_string": new_string,
"context": await self._get_file_context(file_path)
}
)
# 3. Route to multiple agents in parallel
parallel_tasks = [
("U:Cd", self.orchestrator.agents["U:Cd"].execute_edit),
("U:Qa", self.orchestrator.agents["U:Qa"].review_edit),
("U:Ar", self.orchestrator.agents["U:Ar"].analyze_impact),
("U:Ux", self.orchestrator.agents["U:Ux"].review_ux)
]
results = {}
for agent_name, agent_func in parallel_tasks:
try:
results[agent_name] = await agent_func(packet)
except Exception as e:
results[agent_name] = {"error": str(e)}
# 4. Aggregate results
if all(r.get("approved", False) for r in results.values()):
# Execute the actual edit via CheetahClaws
edit_result = await super().execute(file_path, old_string, new_string)
# 5. Log to knowledge graph
await self.orchestrator.kg.log_edit_event(
file=file_path,
change=new_string,
agents=results,
timestamp=datetime.now()
)
# 6. Create checkpoint
await self.checkpoint_manager.create_checkpoint(
description=f"Edit: {file_path}"
)
return EditResult(
success=True,
result=edit_result.result,
multi_agent_feedback=results
)
else:
return EditResult(
success=False,
error="Edit rejected by agent review",
multi_agent_feedback=results
)
Checkpoint System Integration
class UltimateCheckpointManager(CheckpointManager):
"""Enhanced checkpoint system with Orchestrata integration."""
async def create_checkpoint(
self,
description: str,
scope: str = "all" # all, files, conversation, kg
) -> str:
checkpoint_id = await super().create_checkpoint(description)
if scope in ["all", "files"]:
# Snapshot files (already handled by parent)
pass
if scope in ["all", "conversation"]:
# Snapshot Orchestrata session
await self.orchestrator.session.create_snapshot(checkpoint_id)
if scope in ["all", "kg"]:
# Snapshot knowledge graph events
await self.orchestrator.kg.create_snapshot(checkpoint_id)
# Log checkpoint creation
await self.orchestrator.kg.log_checkpoint_event(
checkpoint_id=checkpoint_id,
description=description,
scope=scope,
timestamp=datetime.now()
)
return checkpoint_id
async def restore_checkpoint(self, checkpoint_id: str) -> RestoreResult:
# Get checkpoint metadata
checkpoint = await super().get_checkpoint(checkpoint_id)
# Restore files
file_result = await super().restore_checkpoint(checkpoint_id)
# Restore Orchestrata session if needed
if checkpoint.scope in ["all", "conversation"]:
await self.orchestrator.session.restore_snapshot(checkpoint_id)
# Restore knowledge graph if needed
if checkpoint.scope in ["all", "kg"]:
await self.orchestrator.kg.restore_snapshot(checkpoint_id)
# Log restoration
await self.orchestrator.kg.log_restoration_event(
checkpoint_id=checkpoint_id,
timestamp=datetime.now()
)
return RestoreResult(
success=file_result.success,
files_restored=file_result.files_restored,
session_restored=checkpoint.scope in ["all", "conversation"],
kg_restored=checkpoint.scope in ["all", "kg"]
)
Command Handler Implementation
class UltimateTUI:
"""Complete TUI implementation."""
async def handle_edit(self, args: list[str]) -> None:
"""Handle /edit command with multi-agent coordination."""
if len(args) < 2:
self.tui.print_error("Usage: /edit <file> <old_string> -> <new_string>")
return
file_path = args[0]
old_new = " ".join(args[1:])
if "->" not in old_new:
self.tui.print_error("Usage: /edit <file> <old_string> -> <new_string>")
return
old_string, new_string = old_new.split("->", 1)
old_string = old_string.strip()
new_string = new_string.strip()
self.tui.print(f"Editing {file_path}...")
# Execute via UltimateEditTool
result = await self.ultimate_edit_tool.execute(
file_path, old_string, new_string
)
if result.success:
self.tui.print("✅ Edit completed")
# Show multi-agent feedback
if result.multi_agent_feedback:
self.tui.print("\nAgent Feedback:")
for agent, feedback in result.multi_agent_feedback.items():
if "error" in feedback:
self.tui.print(f" ❌ {agent}: {feedback['error']}")
else:
status = "✅ APPROVED" if feedback.get("approved") else "⚠️ REVIEW"
self.tui.print(f" {agent}: {status}")
if feedback.get("notes"):
self.tui.print(f" {feedback['notes']}")
# Show diff if requested
if self.tui.should_show_diff():
diff = self.generate_diff(file_path, old_string, new_string)
self.tui.display_diff(diff)
else:
self.tui.print_error(f"Edit failed: {result.error}")
async def handle_checkpoint(self, args: list[str]) -> None:
"""Handle /checkpoint command."""
description = " ".join(args) if args else "Manual checkpoint"
checkpoint_id = await self.checkpoint_manager.create_checkpoint(description)
# Get checkpoint stats
stats = await self.checkpoint_manager.get_stats(checkpoint_id)
self.tui.print(f"✓ Checkpoint {checkpoint_id} created")
self.tui.print(f" Description: {description}")
self.tui.print(f" Files: {stats.files_changed}")
self.tui.print(f" Conversation: {stats.messages}")
self.tui.print(f" Knowledge Graph: {stats.kg_events}")
async def handle_rewind(self, args: list[str]) -> None:
"""Handle /rewind command."""
if not args:
self.tui.print_error("Usage: /rewind <checkpoint_id>")
return
checkpoint_id = args[0]
self.tui.print(f"⏪ Rolling back to checkpoint {checkpoint_id}...")
result = await self.checkpoint_manager.restore_checkpoint(checkpoint_id)
if result.success:
self.tui.print("✓ Rollback completed")
self.tui.print(f" Files restored: {result.files_restored}")
if result.session_restored:
self.tui.print(" Session restored")
if result.kg_restored:
self.tui.print(" Knowledge graph restored")
else:
self.tui.print_error("Rollback failed")
async def handle_memory(self, args: list[str]) -> None:
"""Handle /memory command - query knowledge graph."""
query = " ".join(args) if args else ""
if not query:
self.tui.print_error("Usage: /memory <query>")
return
# Query knowledge graph
results = await self.orchestrator.kg.query(query)
if results:
self.tui.print(f"\n📚 Knowledge Graph Results for: {query}")
for result in results[:10]: # Limit to 10 results
self.tui.print(f" • {result.summary}")
self.tui.print(f" {result.detail}")
else:
self.tui.print("No relevant context found")
async def handle_agents(self, args: list[str]) -> None:
"""Handle /agents command - show active agents."""
agents = await self.orchestrator.get_agent_status()
self.tui.print("\n🤖 Active Agents:")
for agent in agents:
status_emoji = "●" if agent.status == "active" else "○"
self.tui.print(f" {status_emoji} {agent.alias}: {agent.role}")
self.tui.print(f" Model: {agent.model}")
self.tui.print(f" Status: {agent.status}")
async def handle_model(self, args: list[str]) -> None:
"""Handle /model command - manage models."""
if not args:
# Show current models
agents = await self.orchestrator.get_agent_status()
self.tui.print("\n🧠 Current Model Configuration:")
for agent in agents:
self.tui.print(f" {agent.alias}: {agent.model}")
return
subcommand = args[0]
if subcommand == "show":
# Detailed model info
await self._show_model_details(args[1] if len(args) > 1 else None)
elif subcommand == "switch":
# Switch model
if len(args) < 3:
self.tui.print_error("Usage: /model switch <agent> <model>")
return
agent = args[1]
model = args[2]
await self.orchestrator.switch_model(agent, model)
self.tui.print(f"✅ {agent} model switched to {model}")
elif subcommand == "list":
# List available models
models = await self.orchestrator.list_available_models()
self.tui.print("\n📋 Available Models:")
for category, model_list in models.items():
self.tui.print(f" {category}:")
for model in model_list:
self.tui.print(f" • {model}")
async def handle_audit(self, args: list[str]) -> None:
"""Handle /audit command - view audit trail."""
file_path = args[0] if args else None
events = await self.orchestrator.audit.get_events(
file_path=file_path,
limit=20
)
if file_path:
self.tui.print(f"\n📋 Audit Trail for: {file_path}")
else:
self.tui.print("\n📋 Recent Audit Events")
for event in events:
self.tui.print(f" {event.timestamp}: {event.agent} - {event.action}")
self.tui.print(f" {event.details}")
Model Support
Multi-Provider Models
class CheetahClawsModelProvider:
"""Model provider supporting multiple LLM services."""
PROVIDERS = {
"anthropic": {
"models": [
"claude-3-5-sonnet",
"claude-3-opus",
"claude-3-haiku"
],
"best_for": ["reasoning", "planning", "architecture"]
},
"openai": {
"models": [
"gpt-4o",
"gpt-4o-mini",
"gpt-3.5-turbo"
],
"best_for": ["coding", "testing", "refactoring"]
},
"google": {
"models": [
"gemini-1.5-pro",
"gemini-1.5-flash"
],
"best_for": ["context", "analysis"]
},
"local": {
"models": [
"ollama/llama2",
"ollama/codellama",
"ollama/mistral"
],
"best_for": ["privacy", "offline", "experimentation"]
}
}
@classmethod
def get_best_model(cls, agent_type: str, task_type: str) -> str:
"""Get best model for agent and task type."""
routing = {
"U:Cd": {
"code_generation": "claude-3-5-sonnet",
"refactoring": "gpt-4o",
"debugging": "claude-3-opus"
},
"U:Qa": {
"code_review": "gpt-4o",
"testing": "gpt-4o",
"security": "claude-3-opus"
},
"U:Ar": {
"architecture": "claude-3-opus",
"design": "claude-3-5-sonnet",
"patterns": "gemini-1.5-pro"
},
"U:Ux": {
"ux_review": "gpt-4o",
"design": "claude-3-5-sonnet",
"accessibility": "gpt-4o"
}
}
return routing.get(agent_type, {}).get(task_type, "claude-3-5-sonnet")
Rich UI Features
Syntax Highlighting
from rich.syntax import Syntax
from rich.panel import Panel
class UltimateSyntaxViewer:
"""Enhanced syntax viewer with agent context."""
def display_file(self, file_path: str, line_range: tuple[int, int] = None):
"""Display file with syntax highlighting and agent annotations."""
with open(file_path) as f:
code = f.read()
# Get syntax language
language = self._get_language(file_path)
# Create syntax highlighted code
syntax = Syntax(
code,
language,
theme="monokai",
line_numbers=True,
highlight_lines=set(), # Will be populated by agents
)
# Get agent annotations
annotations = self.orchestrator.kg.get_file_annotations(file_path)
# Create panel with annotations
panel = Panel(
syntax,
title=f"[bold blue]{file_path}[/bold blue]",
subtitle=f"[dim]{', '.join(annotations)}[/dim]" if annotations else ""
)
self.tui.console.print(panel)
def display_diff(self, diff: str, file_path: str):
"""Display diff with agent context."""
# Parse diff
additions, deletions = self._parse_diff(diff)
# Add agent feedback
feedback = self._get_agent_feedback(file_path)
# Create rich diff display
diff_display = Syntax(
diff,
"diff",
theme="monokai",
line_numbers=True
)
# Display with agent feedback
self.tui.console.print(Panel(diff_display, title=f"Changes to {file_path}"))
if feedback:
self.tui.console.print("\n[bold]Agent Feedback:[/bold]")
for agent, comments in feedback.items():
self.tui.console.print(f"[cyan]{agent}:[/cyan]")
for comment in comments:
self.tui.console.print(f" • {comment}")
Live Diff Rendering
class UltimateDiffViewer:
"""Real-time diff viewer with agent updates."""
def __init__(self, tui):
self.tui = tui
self.live_display = None
async def watch_edit(self, file_path: str, agent: str):
"""Watch file edit in real-time."""
with Live(self._create_layout(file_path), refresh_per_second=10) as live:
self.live_display = live
# Monitor file changes
while self._is_editing(agent):
await self._update_display(file_path, agent)
await asyncio.sleep(0.1)
def _create_layout(self, file_path: str) -> Layout:
"""Create layout for live diff display."""
layout = Layout()
layout.split(
Layout(name="main", ratio=3),
Layout(name="feedback", ratio=1)
)
return layout
def _create_progress_display(self, file_path: str, agent: str) -> Panel:
"""Create progress display."""
progress = Progress(
SpinnerColumn(),
TextColumn("[progress.description]{task.description}"),
BarColumn(),
TextColumn("[progress.percentage]{task.percentage:>3.0f}%"),
)
task = progress.add_task(f"[cyan]{agent}[/cyan]", total=100)
return Panel(progress, title=f"Editing {file_path}")
Integration Examples
Example 1: Multi-Agent File Edit
Terminal Session:
[webapp] ❯ /edit auth.py - add OAuth2 support
U:Cd (CheetahClaws): Writing OAuth2 implementation...
└─ Using model: claude-3-5-sonnet
U:Qa (Review): Running security scan...
└─ Using model: gpt-4o
✓ No vulnerabilities found
U:Ar (Architect): Checking architecture...
└─ Using model: claude-3-opus
✓ Follows established patterns
U:Ux (UX): Reviewing user experience...
└─ Using model: gpt-4o
⚠️ Consider adding loading states
✅ Edit completed successfully
--- a/auth.py
+++ b/auth.py
@@ -10,6 +10,8 @@
+def oauth2_login():
+ """OAuth2 authentication."""
+ # Implementation here
+ pass
Example 2: Checkpoint and Rollback
Terminal Session:
[webapp] ❯ /checkpoint Implementing OAuth2
✓ Checkpoint c1 created
Files: 3 changed (auth.py, settings.py, templates/login.html)
Conversation: 12 messages with agents
Knowledge Graph: 8 events logged
[webapp] ❯ /edit models.py - add UserProfile
UserProfile added successfully
U:Cd: Created UserProfile model
U:Qa: Added validation tests
U:Ar: Verified database schema compatibility
[webapp] ❯ /rewind c1
⏪ Rolling back to checkpoint c1...
Restored: auth.py, settings.py, templates/login.html
Restored: conversation context
Restored: Knowledge Graph events
⚠️ UserProfile changes will be lost
Example 3: Knowledge Graph Query
Terminal Session:
[webapp] ❯ /memory authentication patterns
📚 Knowledge Graph Results for: authentication patterns
• OAuth2 implementation patterns
Applied in auth.py using established patterns
Agents: U:Ar (review), U:Cd (implementation)
• Security considerations
No vulnerabilities found in OAuth2 flow
Agent: U:Qa (security review)
• Previous authentication approaches
Basic JWT auth (removed in checkpoint c1)
Multi-factor auth pattern (planned)
[webapp] ❯ /memory user profile requirements
• Database schema for UserProfile
Model created with validation
Agent: U:Cd (implementation), U:Qa (testing)
• UX requirements for profile page
Loading states recommended
Agent: U:Ux (ux review)
Example 4: Model Switching
Terminal Session:
[webapp] ❯ /model show
🧠 Current Model Configuration:
U:Cd (CheetahClaws): claude-3-5-sonnet (reasoning)
U:Qa (Review): gpt-4o (testing)
U:Ar (Architect): claude-3-opus (architecture)
U:Ux (UX): gpt-4o (ux_review)
[webapp] ❯ /model switch U:Cd gpt-4o-turbo
⚠️ Model switched for U:Cd: claude-3-5-sonnet → gpt-4o-turbo
💰 Cost impact: -$0.02 per request
📊 Performance impact: +10% speed, -5% quality
[webapp] ❯ /model list
📋 Available Models:
Anthropic:
• claude-3-5-sonnet (best for reasoning)
• claude-3-opus (best for architecture)
• claude-3-haiku (fast, cost-effective)
OpenAI:
• gpt-4o (best for coding)
• gpt-4o-mini (fast, economical)
• gpt-3.5-turbo (basic tasks)
Google:
• gemini-1.5-pro (best for context)
• gemini-1.5-flash (fast responses)
Local (Ollama):
• ollama/llama2 (general purpose)
• ollama/codellama (coding focused)
• ollama/mistral (lightweight)
Examples
Basic File Editing
Create a simple file edit with multi-agent review:
# Edit a Python file
/edit main.py "def hello():" -> "def hello_world():"
# Output:
# ✅ Multi-agent review started
# U:Cd: Implementing function rename
# U:Qa: ✓ Code looks good, tests passing
# U:Ar: ✓ Architecture intact
# U:Ux: ✓ Clear naming convention
# Edit completed successfully
Working with Checkpoints
Create checkpoints before risky changes and rollback if needed:
# Create checkpoint before major refactoring
/checkpoint "Refactor authentication module"
# Output:
# ✓ Checkpoint CP:42 created
# Description: Refactor authentication module
# Files: 8 changed
# Conversation: 15 messages
# Knowledge Graph: 12 events
# Make changes
/edit auth.py "old_auth()" -> "new_oauth2()"
# Realize the changes didn't work? Rollback!
/rewind CP:42
# Output:
# ⏪ Rolling back to checkpoint CP:42...
# ✓ Rollback completed
# Files restored: auth.py, models.py, views.py
# Session restored
# Knowledge graph restored
Multi-Agent File Editing
Collaborative editing with specialized agents:
# Complex edit requiring architecture review
/edit services/payment.py "process_payment(amount):" -> "async process_payment(amount, user_id):"
# Output:
# U:Cd (Claude 3.5 Sonnet): Adding async support and user context
# U:Qa (GPT-4o): ✓ Added payment validation tests
# U:Ar (Claude 3 Opus): ✓ Verified against microservice patterns
# U:Ux (GPT-4o): ⚠️ Consider adding user feedback for async operations
# ✅ Edit completed with UX suggestions
Querying Knowledge Graph
Find context from previous work:
# Search for authentication patterns
/memory "OAuth2 implementation patterns"
# Output:
# 📚 Knowledge Graph Results for: OAuth2 implementation patterns
#
# • OAuth2 implementation in auth.py
# Applied 2026-04-09 by U:Cd with U:Qa review
# Status: Active (checkpoint CP:45)
#
# • JWT authentication (deprecated)
# Removed 2026-04-08 during OAuth2 migration
# Replaced with OAuth2 for better security
#
# • Security best practices
# Validated by U:Qa: No vulnerabilities found
# Agent: U:Qa (security audit)
# Find all edits by a specific agent
/memory "edits by U:Ar"
# Output:
# 📚 Knowledge Graph Results for: edits by U:Ar
#
# • Architecture refactor in services/
# Migrated to microservice patterns
# Agent: U:Ar (architecture review)
#
# • Database schema design
# Optimized for scale
# Agent: U:Ar (architectural guidance)
Model Management
Switch between different models based on task:
# Check current model configuration
/model
# Output:
# 🧠 Current Model Configuration:
# U:Cd (CheetahClaws): claude-3-5-sonnet (coding)
# U:Qa (Review): gpt-4o (testing & security)
# U:Ar (Architect): claude-3-opus (architecture)
# U:Ux (UX): gpt-4o (ux review)
# Switch to faster model for U:Cd (code generation)
/model switch U:Cd gpt-4o-mini
# Output:
# ⚠️ Model switched for U:Cd: claude-3-5-sonnet → gpt-4o-mini
# 💰 Cost impact: -$0.03 per request
# 📊 Performance impact: +25% speed, -10% quality
# List all available models
/model list
# Output:
# 📋 Available Models:
# Anthropic:
# • claude-3-5-sonnet (best for reasoning)
# • claude-3-opus (best for architecture)
# • claude-3-haiku (fast, cost-effective)
#
# OpenAI:
# • gpt-4o (best for coding)
# • gpt-4o-mini (fast, economical)
# • gpt-3.5-turbo (basic tasks)
#
# Google:
# • gemini-1.5-pro (context-heavy tasks)
# • gemini-1.5-flash (quick responses)
#
# Local (Ollama):
# • ollama/llama2 (private, general)
# • ollama/codellama (coding focused)
Agent Status and Coordination
View active agents and their work:
# Check all active agents
/agents
# Output:
# 🤖 Active Agents:
# ● U:Cd: CheetahClaws Agent (claude-3-5-sonnet)
# Status: Active
# Current task: Implementing new feature
#
# ● U:Qa: Quality Assurance (gpt-4o)
# Status: Active
# Current task: Reviewing security
#
# ● U:Ar: Architect (claude-3-opus)
# Status: Active
# Current task: Architecture planning
#
# ● U:Ux: User Experience (gpt-4o)
# Status: Active
# Current task: UX review
# Request agent to review specific file
/review auth.py
# Output:
# 📋 Review request sent for auth.py
# U:Cd: Will implement changes
# U:Qa: Will review security
# U:Ar: Will check architecture
# U:Ux: Will review user experience
Audit Trail
Track all operations for compliance:
# View recent audit events
/audit
# Output:
# 📋 Recent Audit Events
#
# 2026-04-09 14:32:15 U:Cd - file_edit
# auth.py: Added OAuth2 support
# Governance: Policy approved (AUTH_OAUTH2_ENABLED)
#
# 2026-04-09 14:30:42 U:TUI - checkpoint_create
# CP:47 created: OAuth2 migration
# Scope: files, conversation, knowledge_graph
#
# 2026-04-09 14:28:09 U:Qa - security_review
# No vulnerabilities found in auth.py
# Policy: SEC_SCAN_REQUIRED ✓
# View audit for specific file
/audit auth.py
# Output:
# 📋 Audit Trail for: auth.py
#
# 2026-04-09 14:32:15 - Edit: Added OAuth2 support
# Agents: U:Cd (implementation), U:Qa (review)
# Result: Success
#
# 2026-04-09 12:15:33 - Edit: Added JWT authentication
# Agents: U:Cd (implementation), U:Qa (review)
# Result: Replaced (OAuth2 migration)
Common Command Combinations
Workflow: Safe Feature Development
# 1. Create checkpoint
/checkpoint "Start new feature: user profiles"
# 2. Make changes with multi-agent review
/edit models.py "class User():" -> "class User():"
# 3. Check knowledge graph for similar patterns
/memory "User model patterns"
# 4. If something goes wrong, rollback
/rewind latest
# 5. Review audit trail
/audit models.py
Workflow: Architecture Review
# 1. Check current model configuration
/model show
# 2. Switch to architecture-focused model
/model switch U:Ar claude-3-opus
# 3. Request architectural review
/review services/database.py
# 4. Query knowledge graph for architecture decisions
/memory "database architecture decisions"
# 5. View audit for compliance
/audit services/database.py
File Operations
Read a file with syntax highlighting:
/read main.py
# Rich formatted output with:
# - Syntax highlighting
# - Line numbers
# - Agent annotations (if available)
Write a new file:
/write utils.py "def helper_function():\\n pass"
# Output:
# ✅ File created: utils.py
# U:Cd: Implementation approved
# U:Qa: No security issues
# Checkpoint created: CP:48
Search file contents:
/grep "oauth" *.py
# Output:
# auth.py:45:def oauth2_login():
# auth.py:67:oauth2_enabled = True
# settings.py:123:OAUTH2_CONFIG = {
Functional Requirements
FR-001: Multi-Agent Edit Coordination
The system SHALL coordinate file edits across Cd, Qa, Ar, and Ux agents in parallel, requiring approval from all agents before committing changes.
FR-002: Governance Policy Enforcement
The system SHALL enforce PAM++ governance policies before any file operation, blocking operations that violate security or policy rules.
FR-003: Checkpoint Creation
The system SHALL create checkpoints that capture file state, conversation history, and knowledge graph events in a single atomic operation.
FR-004: Checkpoint Restoration
The system SHALL restore files, conversation state, and knowledge graph to checkpoint state within 1 second.
FR-005: Path Traversal Prevention
The system SHALL reject any file operation with path traversal patterns (../ or ..) to prevent directory escape attacks.
FR-006: Binary File Detection
The system SHALL detect binary files and reject edit operations on them with appropriate error messaging.
FR-007: File Size Limits
The system SHALL reject files larger than 10MB for read operations and 1MB for edit operations.
FR-008: Multi-Provider Model Support
The system SHALL support Anthropic, OpenAI, Google Gemini, and local Ollama models with automatic fallback on provider failure.
FR-009: Command Routing
The system SHALL route all 40+ CheetahClaws slash commands through Orchestrata kernel with appropriate agent dispatch.
FR-010: Audit Logging
The system SHALL log all file operations, governance decisions, and agent actions with timestamp, user, file, and outcome.
FR-011: Knowledge Graph Integration
The system SHALL log all edit events to the knowledge graph with file path, change summary, participating agents, and timestamp.
FR-012: Live Diff Rendering
The system SHALL display real-time diff updates during multi-agent edits with agent feedback annotations.
FR-013: Session Expiration
The system SHALL expire user sessions after 24 hours of inactivity, requiring re-authentication.
FR-014: Model Routing
The system SHALL suggest optimal model selection based on agent type and task characteristics.
FR-015: Graceful Degradation
The system SHALL fall back to single-agent mode when multi-agent coordination fails, logging the degradation event.
API Contracts
UltimateEditTool.execute()
async def execute(
self,
file_path: str,
old_string: str,
new_string: str,
strict: bool = True
) -> EditResult:
"""
Execute file edit with multi-agent coordination.
Args:
file_path: Path to file (must not contain path traversal)
old_string: Text to replace (must match exactly if strict=True)
new_string: Replacement text
strict: Whether to enforce exact old_string match
Returns:
EditResult with success status, diff, and agent feedback
Raises:
PathTraversalError: If file_path contains ../
FileTooLargeError: If file exceeds 10MB
BinaryFileError: If file is binary
GovernanceError: If PAM++ policy blocks edit
AgentTimeoutError: If agents exceed timeout
"""
CheckpointManager.create_checkpoint()
async def create_checkpoint(
self,
description: str,
scope: str = "all"
) -> str:
"""
Create checkpoint capturing system state.
Args:
description: Human-readable description
scope: "all", "files", "conversation", or "kg"
Returns:
Checkpoint ID in format CP:[0-9]+
Raises:
CheckpointError: If checkpoint creation fails
InsufficientSpaceError: If disk space insufficient
"""
CheckpointManager.restore_checkpoint()
async def restore_checkpoint(
self,
checkpoint_id: str
) -> RestoreResult:
"""
Restore system to checkpoint state.
Args:
checkpoint_id: Checkpoint to restore
Returns:
RestoreResult with restoration status
Raises:
CheckpointNotFoundError: If checkpoint doesn't exist
CheckpointCorruptError: If checkpoint file corrupted
RestoreError: If restoration fails
"""
UltimateTUI.handle_edit()
async def handle_edit(self, args: list[str]) -> None:
"""
Handle /edit slash command.
Args:
args: [file_path, old_string, "->", new_string]
Returns:
None (prints output to TUI)
Raises:
CommandError: If arguments invalid
EditFailedError: If edit rejected by agents
"""
ModelProvider.switch_model()
async def switch_model(
self,
agent: str,
model: str
) -> None:
"""
Switch agent to different model.
Args:
agent: Agent alias (e.g., "U:Cd")
model: Model identifier (e.g., "gpt-4o")
Raises:
ModelNotFoundError: If model unavailable
AgentNotFoundError: If agent doesn't exist
"""
KnowledgeGraph.log_edit_event()
async def log_edit_event(
self,
file: str,
change: str,
agents: dict,
timestamp: datetime
) -> None:
"""
Log edit event to knowledge graph.
Args:
file: File path that was edited
change: Description of changes made
agents: Dictionary of agent feedback
timestamp: When edit occurred
"""
Non-Functional Requirements
Performance
- Command Execution: 85ms (target: <100ms)
- Multi-Agent Coordination: 1.5s (target: <2s)
- Checkpoint Creation: 350ms (target: <500ms)
- Checkpoint Rollback: 750ms (target: <1s)
- Model Switch: 35ms (target: <50ms)
- Knowledge Graph Query: 150ms (target: <200ms)
Scalability
- Support 100+ concurrent users
- Handle 10,000+ checkpoints per session
- Process files up to 10MB
- Support 40+ slash commands simultaneously
Reliability
- 99.9% uptime for TUI interface
- 99.5% checkpoint creation success rate
- Automatic fallback on single agent failure
- Retry with exponential backoff on network errors
Security
- No path traversal vulnerabilities
- All file operations governed by PAM++
- 24-hour session expiration
- Complete audit trail for all operations
- Detection and rejection of binary files
Usability
- Rich syntax highlighting for 50+ languages
- Live diff rendering during edits
- Colored terminal output
- Keyboard shortcuts for all commands
- Context-sensitive help system
Error Handling
Error Conditions
| ID | Condition | Trigger | Handling | Exit Code |
|---|---|---|---|---|
| ERR-001 | File not found | Read/edit non-existent file | Return error with suggestion | 1 |
| ERR-002 | Permission denied | File without read/write permissions | Show permission error with chmod suggestion | 1 |
| ERR-003 | Path traversal | Path contains ../ | Reject with security warning | 1 |
| ERR-004 | File too large | File >10MB | Reject with size limit info | 1 |
| ERR-005 | Binary file | Attempt to edit binary file | Reject with binary detection | 1 |
| ERR-006 | Governance block | PAM++ policy blocks operation | Show policy reason and appeal process | 1 |
| ERR-007 | Agent timeout | Agent exceeds timeout | Fallback to single-agent, log warning | 1 |
| ERR-008 | Model unavailable | Requested model not available | Auto-switch to fallback model | 1 |
| ERR-009 | Multi-agent conflict | Agents produce conflicting edits | Show conflicts, require manual resolution | 1 |
| ERR-010 | Checkpoint corrupt | Checkpoint file corrupted | Reject rollback, suggest new checkpoint | 1 |
| ERR-011 | Network failure | External API unavailable | Queue operation, retry with backoff | 1 |
| ERR-012 | Invalid edit | old_string doesn't match file | Show actual content, suggest correct match | 1 |
Graceful Degradation
class UltimateTUIErrorHandler:
"""Comprehensive error handling for CheetahClaws integration."""
async def handle_edit_error(self, error: Exception, context: dict) -> None:
"""Handle edit operation errors."""
if isinstance(error, GovernanceError):
self.tui.print_error(f"🚫 Edit blocked: {error.reason}")
self.tui.print(f"Policy: {error.policy}")
self.tui.print(f"Article: {error.article}")
elif isinstance(error, AgentTimeoutError):
self.tui.print_error(f"⏰ Agent timeout: {error.agent}")
self.tui.print("Attempting fallback...")
await self._attempt_fallback(context)
elif isinstance(error, FilePermissionError):
self.tui.print_error(f"🔒 Permission denied: {context['file_path']}")
self.tui.print("Try: sudo, or change file permissions")
else:
self.tui.print_error(f"❌ Unexpected error: {str(error)}")
self.tui.print("Check logs for details: /audit")
async def _attempt_fallback(self, context: dict) -> None:
"""Attempt fallback strategies for failed operations."""
# Try alternate model
if context.get("agent") and context.get("model"):
fallback_model = self._get_fallback_model(context["model"])
await self.orchestrator.switch_model(
context["agent"],
fallback_model
)
self.tui.print(f"Switched to fallback model: {fallback_model}")
# Try single-agent mode
self.tui.print("Falling back to single-agent mode...")
# Continue with U:Cd only
Testing Strategy
Integration Tests
class TestCheetahClawsIntegration:
"""Test suite for CheetahClaws integration."""
async def test_multi_agent_edit(self):
"""Test multi-agent coordination for file edit."""
# Create test file
test_file = "test_integration.py"
# Execute edit
result = await self.tui.handle_edit([
test_file,
"def old_function():",
"->",
"def new_function():"
])
# Verify all agents participated
assert len(result.multi_agent_feedback) == 4
assert "U:Cd" in result.multi_agent_feedback
assert "U:Qa" in result.multi_agent_feedback
assert "U:Ar" in result.multi_agent_feedback
assert "U:Ux" in result.multi_agent_feedback
async def test_checkpoint_rollback(self):
"""Test checkpoint creation and rollback."""
# Create checkpoint
checkpoint_id = await self.tui.handle_checkpoint([
"Test checkpoint"
])
# Modify file
await self.tui.handle_edit([
"test.txt",
"old",
"->",
"new"
])
# Rollback
await self.tui.handle_rewind([checkpoint_id])
# Verify rollback
with open("test.txt") as f:
assert "old" in f.read()
async def test_model_switching(self):
"""Test dynamic model switching."""
# Switch model
await self.tui.handle_model([
"switch", "U:Cd", "gpt-4o"
])
# Verify switch
agents = await self.orchestrator.get_agent_status()
cd_agent = [a for a in agents if a.alias == "U:Cd"][0]
assert cd_agent.model == "gpt-4o"
Performance Metrics
| Operation | Target | Current |
|---|---|---|
| Command execution | < 100ms | 85ms |
| Multi-agent coordination | < 2s | 1.5s |
| Checkpoint creation | < 500ms | 350ms |
| Rollback execution | < 1s | 750ms |
| Model switch | < 50ms | 35ms |
| Knowledge graph query | < 200ms | 150ms |
Visual Architecture
Class Diagram
Diagram source shown as text: Mermaid could not parse it (Error: Parse error on line 36:).
classDiagram-direction LR
class CheetahClawsTUI {
+__init__()
#_load_commands(): dict[str, Any]
+async create_checkpoint(name: str): dict[str, Any]
+async rewind(steps: int = 1): dict[str, Any]
+async query_memory(query: str, depth: int = 1): dict[str, Any]
+async edit_file(file_path: str, old_string: str, new_string: str): dict[str, Any]
+async search_files(pattern: str, path: str = '.'): list[str]
+async execute_command(command: str, args: list[str] | None = None): dict[str, Any]
}
class OpenRouterProvider {
+__init__(api_key: str | None = None)
+async chat_completion(model: str, messages: list[dict[str, str]], **kwargs): dict[str, Any]
+get_available_models(): list[str]
+get_model_cost(model: str): float
}
class TodoistIntegration {
+__init__(api_key: str | None = None)
+is_configured(): bool
+async create_project(name: str): str
+async create_task(project_id: str, title: str, **kwargs): str
+async sync_tasks(project_id: str): list[dict[str, Any]]
+async close()
}
class VizIntWebUI {
+__init__(host: str = 'localhost', port: int = 8765)
+async start()
+async shutdown()
+async add_project(project_data: dict[str, Any])
+async broadcast_edit_complete(file_path: str, result: dict[str, Any])
+async update_task_status(task_id: str, status: str)
+async get_projects(): list[dict[str, Any]]
}
Knowledge Graph Integration
- Edit events logged to KG with agent feedback
- Checkpoint events tracked in KG
- Queryable history of all file changes
Governance Integration
- Pre-edit policy checks via PAM++
- Pre-delete elevated approval workflow
- Audit logging of all governance decisions
Session Management Integration
- Checkpoints include session state
- Rollback restores active session context
- Session expiration tied to auth system
Multi-Agent Coordination Integration
- CXP packet routing for edit coordination
- Agent feedback aggregation
- Conflict resolution workflows
Success Criteria
Core Functionality
- [ ] All 40+ CheetahClaws commands functional
- [ ] Multi-agent edit coordination working with 4 agents
- [ ] Checkpoint creation capturing files, conversation, KG
- [ ] Rollback restoring all three layers
- [ ] Model switching across 4 providers
Security
- [ ] Path traversal attacks blocked
- [ ] Binary files detected and rejected
- [ ] PAM++ governance policies enforced
- [ ] 24-hour session expiration implemented
- [ ] Complete audit trail available
Performance
- [ ] Command execution under 100ms
- [ ] Multi-agent coordination under 2s
- [ ] Checkpoint creation under 500ms
- [ ] Rollback under 1 second
- [ ] Model switch under 50ms
Quality
- [ ] All 15 functional requirements met
- [ ] 12 error conditions handled gracefully
- [ ] Live diff rendering functional
- [ ] Syntax highlighting for 50+ languages
Observability
Logging Requirements
- Component Logging
- Log all major operations with appropriate log levels
- Include correlation IDs for request tracing
- Log performance metrics for critical operations
- Log errors with full context for debugging
Metrics Requirements
- Performance Metrics
- Operation duration histograms
- Request/error rate counters
- Resource utilization gauges
- Business metrics relevant to domain
Tracing Requirements
- Distributed Tracing
- Trace propagation across component boundaries
- Span attributes for domain-specific context
- Trace sampling based on operational needs
Alerting Requirements
- Critical Alerts
- Error rate spikes
- Performance degradation
- Resource exhaustion
- Business metric anomalies
Dashboard Requirements
- Operational Dashboard
- Real-time system health
- Performance trends
- Error analysis
- Resource monitoring
Revision History
| Version | Date | Author | Changes |
|---|---|---|---|
| 1.0.0 | 2026-04-08 | Mohamed | Initial specification |
| 1.0.1 | 2026-04-09 | Mohamed | Added User Scenarios, Functional Requirements (FR-001 to FR-015), API Contracts, Non-Functional Requirements, Dependencies, Integration Points, Success Criteria, Revision History. Updated error IDs to ERR-001 to ERR-012 format. |
Conclusion
The CheetahClaws integration brings a mature, production-ready terminal interface to the Ultimate Hybrid system. With 40+ commands, rich diff rendering, checkpoint system, and multi-provider model support, it provides an excellent developer experience while leveraging Orchestrata's enterprise-grade multi-agent coordination.
The integration maintains CheetahClaws' strengths (usability, file editing, checkpoints) while enhancing it with multi-agent collaboration, knowledge graph integration, and governance policies.