Command Processor Enhancements
All enhancements are backward compatible: - Existing code continues to work - `process_text()` still returns `bool` - Default parameters match original behavior - Optional features can be disabled
Full Public Reader
Command Processor Enhancements
The `CommandProcessor` has been significantly enhanced with a full-featured implementation.
New Features
### 1. Advanced Matching System
- Confidence Scoring: Every match includes a confidence score (0.0-1.0)
- Match Types: EXACT, WORD_BOUNDARY, FUZZY, ALIAS, PARTIAL
- Multi-strategy Matching: Tries multiple matching strategies in order of preference
- SequenceMatcher: Uses advanced similarity algorithms for fuzzy matching
### 2. Command Aliases & Synonyms
- Built-in Aliases: Common shortcuts like "go" → "play", "cut" → "censor"
- Custom Aliases: Add your own with `add_alias()`
- Synonyms: Automatic synonym generation for deck-specific commands
- Alias Expansion: Automatically expands aliases before matching
### 3. Command History
- Execution History: Tracks last 100 commands with full details
- History Entry: Includes phrase, key combo, execution time, success status, match type, confidence
- History Access: `get_history(limit=10)` to retrieve recent commands
- History Clearing: `clear_history()` to reset
### 4. Statistics & Metrics
- Comprehensive Stats: Total commands, success rate, match type distribution
- Performance Metrics: Average match time, execution time, min/max times
- Confidence Tracking: Average confidence across all matches
- Statistics Access: `get_statistics()` returns full stats dictionary
- Statistics Reset: `reset_statistics()` to clear all stats
### 5. Enhanced Command Buffer
- Buffer History: Keeps last 50 buffer states
- Max Size: Configurable maximum buffer size (default: 10 words)
- Timeout Checking: `has_timeout_elapsed()` method
- Word Access: `get_words()`, `get_last_n_words()` methods
- Better State Management: Improved buffer clearing and task cancellation
### 6. Command Suggestions
- Prefix Matching: Finds commands starting with partial text
- Fuzzy Suggestions: Uses fuzzy matching for suggestions
- Limit Control: Configurable suggestion limit
- Usage: `get_suggestions("play", limit=5)`
### 7. Error Handling
- Comprehensive Logging: Uses Python logging module
- Exception Handling: Graceful error handling with fallbacks
- Error Tracking: Failed commands tracked in statistics
- Debug Logging: Detailed debug logs for troubleshooting
### 8. Performance Optimizations
- Match Time Tracking: Records time taken for matching
- Execution Time Tracking: Records command execution time
- Efficient Data Structures: Uses `deque` for O(1) operations
- Lazy Evaluation: Only processes when needed
### 9. Deck State Management
- Automatic Deck Detection: Updates deck from command text
- Deck Validation: Validates deck names ("left" or "right")
- Deck Tracking: Maintains current deck state
### 10. Configuration Options
- Configurable Timeouts: Buffer timeout and command cooldown
- Fuzzy Cutoff: Configurable minimum similarity threshold
- Feature Flags: Enable/disable history and statistics
- Flexible Initialization: Many optional parameters
New Classes & Types
`MatchType` (Enum)
MatchType.EXACT # Exact phrase match
MatchType.WORD_BOUNDARY # Word-boundary match
MatchType.FUZZY # Fuzzy similarity match
MatchType.ALIAS # Alias expansion match
MatchType.PARTIAL # Partial phrase match`CommandMatch` (Dataclass)
@dataclass
class CommandMatch:
phrase: str # Matched command phrase
key_combo: str # Keyboard shortcut or special marker
match_type: MatchType # Type of match
confidence: float # Confidence score (0.0-1.0)
original_text: str # Original input text
matched_at: float # Timestamp`CommandHistory` (Dataclass)
@dataclass
class CommandHistory:
phrase: str # Command phrase
key_combo: str # Keyboard shortcut
executed_at: float # Execution timestamp
success: bool # Whether execution succeeded
execution_time: float # Time taken to execute
match_type: MatchType # Type of match
confidence: float # Match confidenceEnhanced Methods
### `process_text(text: str) -> bool`
- Now includes alias expansion
- Better deck detection
- Performance timing
- Improved logging
### `_try_match_command()` → Returns `Optional[CommandMatch]`
- Returns `CommandMatch` object instead of just bool
- Includes confidence scoring
- Multiple matching strategies
- Better error handling
### New Methods
- `get_statistics()` - Get comprehensive statistics
- `get_history(limit)` - Get command history
- `clear_history()` - Clear history
- `add_alias(alias, command)` - Add custom alias
- `add_synonym(command, synonym)` - Add synonym
- `get_suggestions(text, limit)` - Get command suggestions
- `reset_statistics()` - Reset all statistics
Usage Examples
Get Statistics
stats = processor.get_statistics()
print(f"Success rate: {stats['success_rate']:.1%}")
print(f"Average confidence: {stats['average_confidence']:.2f}")
print(f"Total commands: {stats['total_commands']}")Get Command History
history = processor.get_history(limit=10)
for entry in history:
print(f"{entry.phrase} ({entry.match_type.value}, {entry.confidence:.2f})")Add Custom Alias
processor.add_alias("fire", "censor")
# Now "fire left" will match "censor left"Get Suggestions
suggestions = processor.get_suggestions("play", limit=5)
# Returns: ["play left", "play right", "play both", ...]Configure Processor
processor = CommandProcessor(
command_map=commands,
buffer_timeout=2.0, # Longer buffer timeout
command_cooldown=2.0, # Longer cooldown
fuzzy_cutoff=0.8, # Higher fuzzy threshold
enable_history=True, # Enable history
enable_statistics=True # Enable statistics
)Backward Compatibility
All enhancements are backward compatible:
- Existing code continues to work
- `process_text()` still returns `bool`
- Default parameters match original behavior
- Optional features can be disabled
Performance
- Match Time: Typically < 10ms
- Memory: Efficient deque-based structures
- Scalability: Handles large command maps efficiently
- History: Limited to prevent memory growth
Logging
The processor uses Python's `logging` module:
- `logger.debug()` - Detailed matching information
- `logger.info()` - Command execution
- `logger.warning()` - Warnings (invalid deck, etc.)
- `logger.error()` - Errors during execution
Set logging level to control verbosity:
import logging
logging.basicConfig(level=logging.DEBUG) # See all debug infoPromotion Decision
Attach run IDs, datasets, metrics, and reproduction commands.
Source Anchor
Comp-Core/apps/web/cc-studio/docs/dj_agent/core/command_processor.md
Detected Structure
Method · Evaluation · Figures