Skip to main content

sprite/utils/
help.rs

1//! Comprehensive help system for the Sprite multi-agent workflow toolkit.
2//!
3//! This module provides enhanced help functionality including command documentation,
4//! usage examples, troubleshooting guides, and contextual help suggestions.
5
6use anyhow::Result;
7use std::collections::HashMap;
8use std::fmt;
9
10/// Comprehensive help system for Sprite commands and features.
11#[derive(Debug, Clone)]
12pub struct HelpSystem {
13    /// Command documentation
14    pub commands: HashMap<String, CommandHelp>,
15    /// Common usage patterns
16    pub usage_patterns: Vec<UsagePattern>,
17    /// Troubleshooting guides
18    pub troubleshooting: Vec<TroubleshootingGuide>,
19    /// Quick reference
20    pub quick_reference: QuickReference,
21}
22
23/// Help information for a specific command.
24#[derive(Debug, Clone)]
25pub struct CommandHelp {
26    /// Command name
27    pub name: String,
28    /// Brief description
29    pub description: String,
30    /// Detailed usage information
31    pub usage: String,
32    /// Examples
33    pub examples: Vec<String>,
34    /// Common mistakes and solutions
35    pub common_mistakes: Vec<String>,
36    /// Related commands
37    pub related_commands: Vec<String>,
38    /// Prerequisites
39    pub prerequisites: Vec<String>,
40    /// Tips and tricks
41    pub tips: Vec<String>,
42}
43
44/// Usage pattern for common workflows.
45#[derive(Debug, Clone)]
46pub struct UsagePattern {
47    /// Pattern name
48    pub name: String,
49    /// Description
50    pub description: String,
51    /// Steps to follow
52    pub steps: Vec<String>,
53    /// Commands involved
54    pub commands: Vec<String>,
55    /// Use case category
56    pub category: UsageCategory,
57}
58
59/// Category of usage pattern.
60#[derive(Debug, Clone, PartialEq)]
61pub enum UsageCategory {
62    /// Getting started
63    GettingStarted,
64    /// Daily workflow
65    DailyWorkflow,
66    /// Troubleshooting
67    Troubleshooting,
68    /// Advanced usage
69    Advanced,
70    /// Collaboration
71    Collaboration,
72}
73
74/// Troubleshooting guide.
75#[derive(Debug, Clone)]
76pub struct TroubleshootingGuide {
77    /// Problem description
78    pub problem: String,
79    /// Symptoms
80    pub symptoms: Vec<String>,
81    /// Possible causes
82    pub causes: Vec<String>,
83    /// Solutions
84    pub solutions: Vec<String>,
85    /// Prevention tips
86    pub prevention: Vec<String>,
87    /// Related commands
88    pub related_commands: Vec<String>,
89}
90
91/// Quick reference information.
92#[derive(Debug, Clone)]
93pub struct QuickReference {
94    /// Most commonly used commands
95    pub common_commands: Vec<String>,
96    /// Keyboard shortcuts
97    pub shortcuts: Vec<KeyboardShortcut>,
98    /// Frequently asked questions
99    pub faq: Vec<Faq>,
100}
101
102/// Keyboard shortcut.
103#[derive(Debug, Clone)]
104pub struct KeyboardShortcut {
105    /// Key combination
106    pub keys: String,
107    /// Description
108    pub description: String,
109    /// Context where it applies
110    pub context: String,
111}
112
113/// Frequently asked question.
114#[derive(Debug, Clone)]
115pub struct Faq {
116    /// Question
117    pub question: String,
118    /// Answer
119    pub answer: String,
120    /// Related commands
121    pub related_commands: Vec<String>,
122}
123
124impl HelpSystem {
125    /// Create a new help system with all documentation.
126    pub fn new() -> Self {
127        let mut help_system = Self {
128            commands: HashMap::new(),
129            usage_patterns: Vec::new(),
130            troubleshooting: Vec::new(),
131            quick_reference: QuickReference {
132                common_commands: Vec::new(),
133                shortcuts: Vec::new(),
134                faq: Vec::new(),
135            },
136        };
137
138        help_system.load_command_help();
139        help_system.load_usage_patterns();
140        help_system.load_troubleshooting();
141        help_system.load_quick_reference();
142
143        help_system
144    }
145
146    /// Load command help documentation.
147    fn load_command_help(&mut self) {
148        // Core commands
149        self.commands.insert(
150            "init".to_string(),
151            CommandHelp {
152                name: "init".to_string(),
153                description: "Initialize a new multi-agent environment in the current directory"
154                    .to_string(),
155                usage: "sprite init [OPTIONS]".to_string(),
156                examples: vec![
157                    "sprite init                                    # Basic initialization"
158                        .to_string(),
159                    "sprite init --agents 5                        # Create 5 agents".to_string(),
160                    "sprite init --force                           # Overwrite existing config"
161                        .to_string(),
162                ],
163                common_mistakes: vec![
164                    "Running from outside a git repository - sprite requires a git repository"
165                        .to_string(),
166                    "Not having tmux installed - required for session management".to_string(),
167                ],
168                related_commands: vec![
169                    "config".to_string(),
170                    "agents".to_string(),
171                    "start".to_string(),
172                ],
173                prerequisites: vec![
174                    "Git repository initialized".to_string(),
175                    "Tmux installed and available".to_string(),
176                ],
177                tips: vec![
178                    "Use --force if you want to overwrite an existing configuration".to_string(),
179                    "The default creates 3 agents - adjust with --agents if needed".to_string(),
180                ],
181            },
182        );
183
184        self.commands.insert(
185            "start".to_string(),
186            CommandHelp {
187                name: "start".to_string(),
188                description: "Start a new multi-agent supervision session".to_string(),
189                usage: "sprite start [OPTIONS]".to_string(),
190                examples: vec![
191                    "sprite start                                    # Start with default settings"
192                        .to_string(),
193                    "sprite start --session-name my-session          # Custom session name"
194                        .to_string(),
195                    "sprite start --layout main-vertical            # Use vertical layout"
196                        .to_string(),
197                    "sprite start --detach                          # Start and detach immediately"
198                        .to_string(),
199                ],
200                common_mistakes: vec![
201                    "Starting without agent configuration - run 'sprite init' first".to_string(),
202                    "Session already exists - use 'sprite attach' or kill existing session"
203                        .to_string(),
204                ],
205                related_commands: vec![
206                    "attach".to_string(),
207                    "kill".to_string(),
208                    "agents".to_string(),
209                ],
210                prerequisites: vec![
211                    "Sprite configuration exists".to_string(),
212                    "Agent workspaces created".to_string(),
213                ],
214                tips: vec![
215                    "Use --detach to start in background and return to terminal".to_string(),
216                    "Different layouts work better for different screen sizes".to_string(),
217                ],
218            },
219        );
220
221        self.commands.insert(
222            "agents".to_string(),
223            CommandHelp {
224                name: "agents".to_string(),
225                description: "Manage agents (list, create, remove, show details)".to_string(),
226                usage: "sprite agents <SUBCOMMAND> [OPTIONS]".to_string(),
227                examples: vec![
228                    "sprite agents list                              # List all agents".to_string(),
229                    "sprite agents create 4                          # Create agent 4".to_string(),
230                    "sprite agents create 5 --branch feature/auth   # Custom branch".to_string(),
231                    "sprite agents show 1                           # Show agent 1 details"
232                        .to_string(),
233                    "sprite agents remove 2 --force                 # Remove agent 2".to_string(),
234                ],
235                common_mistakes: vec![
236                    "Creating agents with duplicate IDs - each agent must have unique ID"
237                        .to_string(),
238                    "Removing agents that are currently running - stop session first".to_string(),
239                ],
240                related_commands: vec![
241                    "remove".to_string(),
242                    "start".to_string(),
243                    "warp".to_string(),
244                ],
245                prerequisites: vec!["Sprite configuration exists".to_string()],
246                tips: vec![
247                    "Use 'show' to see detailed agent information".to_string(),
248                    "Agent IDs are typically numbers but can be any identifier".to_string(),
249                ],
250            },
251        );
252
253        self.commands.insert(
254            "warp".to_string(),
255            CommandHelp {
256                name: "warp".to_string(),
257                description: "Navigate between agent workspaces".to_string(),
258                usage: "sprite warp [WORKSPACE] [OPTIONS]".to_string(),
259                examples: vec![
260                    "sprite warp                                    # Show current workspace"
261                        .to_string(),
262                    "sprite warp --list                            # List all workspaces"
263                        .to_string(),
264                    "sprite warp 1                                 # Navigate to agent 1"
265                        .to_string(),
266                    "sprite warp main                              # Navigate to main directory"
267                        .to_string(),
268                    "sprite warp --print 2                         # Print path without changing"
269                        .to_string(),
270                ],
271                common_mistakes: vec![
272                    "Navigating to workspace that doesn't exist - check with --list first"
273                        .to_string(),
274                    "Forgetting that sprite warp doesn't actually change directory".to_string(),
275                ],
276                related_commands: vec!["agents".to_string(), "status".to_string()],
277                prerequisites: vec!["Git repository".to_string()],
278                tips: vec![
279                    "Use 'cd $(sprite warp --print <name>)' to actually change directory"
280                        .to_string(),
281                    "Workspace navigation works with relative paths and tab completion".to_string(),
282                ],
283            },
284        );
285
286        self.commands.insert(
287            "hey".to_string(),
288            CommandHelp {
289                name: "hey".to_string(),
290                description: "Send a command to a specific agent".to_string(),
291                usage: "sprite hey <AGENT> <COMMAND> [ARGS...] [OPTIONS]".to_string(),
292                examples: vec![
293                    "sprite hey 1 'npm test'                       # Run tests in agent 1"
294                        .to_string(),
295                    "sprite hey 2 'git status' --timeout 60       # Custom timeout".to_string(),
296                    "sprite hey 3 'npm run dev' --interactive      # Interactive mode".to_string(),
297                ],
298                common_mistakes: vec![
299                    "Sending commands to non-existent agent - check with 'sprite agents list'"
300                        .to_string(),
301                    "Commands not found - agents have different environments".to_string(),
302                    "Timeout too short for long-running operations".to_string(),
303                ],
304                related_commands: vec![
305                    "send".to_string(),
306                    "agents".to_string(),
307                    "start".to_string(),
308                ],
309                prerequisites: vec!["Active session with running agents".to_string()],
310                tips: vec![
311                    "Use --interactive for commands that require user input".to_string(),
312                    "Adjust timeout based on command complexity".to_string(),
313                    "Use 'send' to broadcast to all agents".to_string(),
314                ],
315            },
316        );
317
318        self.commands.insert(
319            "send".to_string(),
320            CommandHelp {
321                name: "send".to_string(),
322                description: "Send a command to all agents (broadcast)".to_string(),
323                usage: "sprite send <COMMAND> [ARGS...] [OPTIONS]".to_string(),
324                examples: vec![
325                    "sprite send 'git pull'                        # Pull changes in all agents"
326                        .to_string(),
327                    "sprite send 'npm install' --sequential        # Run one by one".to_string(),
328                    "sprite send 'cargo build' --timeout 120       # Longer timeout".to_string(),
329                ],
330                common_mistakes: vec![
331                    "Broadcasting expensive operations - consider using --sequential".to_string(),
332                    "Not setting appropriate timeout for complex commands".to_string(),
333                ],
334                related_commands: vec!["hey".to_string(), "sync".to_string()],
335                prerequisites: vec!["Active session with running agents".to_string()],
336                tips: vec![
337                    "Use --sequential for operations that shouldn't run in parallel".to_string(),
338                    "Broadcast is great for maintenance tasks across all agents".to_string(),
339                ],
340            },
341        );
342
343        self.commands.insert(
344            "sync".to_string(),
345            CommandHelp {
346                name: "sync".to_string(),
347                description: "Synchronize workspaces context-aware".to_string(),
348                usage: "sprite sync [OPTIONS]".to_string(),
349                examples: vec![
350                    "sprite sync                                    # Sync current context"
351                        .to_string(),
352                    "sprite sync --agent 2                          # Sync specific agent"
353                        .to_string(),
354                    "sprite sync --force                            # Force sync with conflicts"
355                        .to_string(),
356                    "sprite sync --dry-run                          # Preview changes".to_string(),
357                ],
358                common_mistakes: vec![
359                    "Syncing with uncommitted changes - commit or stash first".to_string(),
360                    "Merge conflicts - resolve manually or use --force strategy".to_string(),
361                ],
362                related_commands: vec!["hey".to_string(), "send".to_string(), "status".to_string()],
363                prerequisites: vec!["Git repository with changes to sync".to_string()],
364                tips: vec![
365                    "Use --dry-run to preview what will be synced".to_string(),
366                    "Different behavior in main vs agent workspaces".to_string(),
367                ],
368            },
369        );
370
371        self.commands.insert("remove".to_string(), CommandHelp {
372            name: "remove".to_string(),
373            description: "Remove agent workspace with comprehensive cleanup".to_string(),
374            usage: "sprite remove <AGENT> [OPTIONS]".to_string(),
375            examples: vec![
376                "sprite remove 1                               # Remove agent 1 (with confirmation)".to_string(),
377                "sprite remove 2 --force                      # Remove without confirmation".to_string(),
378                "sprite remove 3 --merge-branch               # Merge branch before removal".to_string(),
379                "sprite remove 4 --keep-workspace             # Keep workspace files".to_string(),
380            ],
381            common_mistakes: vec![
382                "Removing running agent - stop session first".to_string(),
383                "Losing work with uncommitted changes - commit first".to_string(),
384            ],
385            related_commands: vec!["agents".to_string(), "kill".to_string()],
386            prerequisites: vec![
387                "Agent not currently running".to_string(),
388            ],
389            tips: vec![
390                "Use --merge-branch to preserve agent work".to_string(),
391                "--force bypasses all safety checks - use with caution".to_string(),
392            ],
393        });
394
395        self.commands.insert(
396            "zoom".to_string(),
397            CommandHelp {
398                name: "zoom".to_string(),
399                description: "Focus on a specific agent pane in tmux".to_string(),
400                usage: "sprite zoom [AGENT] [OPTIONS]".to_string(),
401                examples: vec![
402                    "sprite zoom 1                                 # Zoom on agent 1".to_string(),
403                    "sprite zoom --unzoom                         # Return to normal layout"
404                        .to_string(),
405                    "sprite zoom --list                           # List available panes"
406                        .to_string(),
407                ],
408                common_mistakes: vec![
409                    "Zooming when no session is active - start session first".to_string(),
410                    "Agent not found in current session".to_string(),
411                ],
412                related_commands: vec![
413                    "start".to_string(),
414                    "attach".to_string(),
415                    "hey".to_string(),
416                ],
417                prerequisites: vec!["Active tmux session".to_string()],
418                tips: vec![
419                    "Use --unzoom or run again to return to normal layout".to_string(),
420                    "Great for focusing on a specific agent's work".to_string(),
421                ],
422            },
423        );
424
425        self.commands.insert(
426            "status".to_string(),
427            CommandHelp {
428                name: "status".to_string(),
429                description: "Check session status and health".to_string(),
430                usage: "sprite status [OPTIONS]".to_string(),
431                examples: vec![
432                    "sprite status                                    # Show status".to_string(),
433                    "sprite status --detailed                        # Detailed information"
434                        .to_string(),
435                    "sprite status --cleanup                         # Clean up old sessions"
436                        .to_string(),
437                    "sprite status --session-name my-session         # Check specific session"
438                        .to_string(),
439                ],
440                common_mistakes: vec![
441                    "Not understanding status indicators - check help for symbols".to_string(),
442                ],
443                related_commands: vec![
444                    "start".to_string(),
445                    "kill".to_string(),
446                    "attach".to_string(),
447                ],
448                prerequisites: vec!["None (works with or without active sessions)".to_string()],
449                tips: vec![
450                    "Use --detailed for comprehensive health information".to_string(),
451                    "Regular status checks help maintain system health".to_string(),
452                ],
453            },
454        );
455
456        self.commands.insert(
457            "config".to_string(),
458            CommandHelp {
459                name: "config".to_string(),
460                description: "Manage configuration settings".to_string(),
461                usage: "sprite config <SUBCOMMAND> [OPTIONS]".to_string(),
462                examples: vec![
463                    "sprite config show                              # Show current config"
464                        .to_string(),
465                    "sprite config validate                          # Validate configuration"
466                        .to_string(),
467                    "sprite config set timeout 60                   # Set configuration value"
468                        .to_string(),
469                    "sprite config edit                              # Open config in editor"
470                        .to_string(),
471                ],
472                common_mistakes: vec![
473                    "Invalid configuration values - check validation output".to_string(),
474                    "Editing config directly - use 'sprite config edit'".to_string(),
475                ],
476                related_commands: vec!["init".to_string(), "agents".to_string()],
477                prerequisites: vec!["Sprite configuration file exists".to_string()],
478                tips: vec![
479                    "Always validate config after making changes".to_string(),
480                    "Use 'show' to review current settings".to_string(),
481                ],
482            },
483        );
484    }
485
486    /// Load usage patterns.
487    fn load_usage_patterns(&mut self) {
488        self.usage_patterns = vec![
489            UsagePattern {
490                name: "First Time Setup".to_string(),
491                description: "Set up Sprite for a new project".to_string(),
492                steps: vec![
493                    "Initialize git repository if not already done".to_string(),
494                    "Run 'sprite init' to create initial configuration".to_string(),
495                    "Review agent configuration with 'sprite config show'".to_string(),
496                    "Start first session with 'sprite start'".to_string(),
497                    "Navigate workspaces with 'sprite warp --list'".to_string(),
498                ],
499                commands: vec![
500                    "init".to_string(),
501                    "config".to_string(),
502                    "start".to_string(),
503                    "warp".to_string(),
504                ],
505                category: UsageCategory::GettingStarted,
506            },
507            UsagePattern {
508                name: "Daily Workflow".to_string(),
509                description: "Typical daily work with Sprite agents".to_string(),
510                steps: vec![
511                    "Check current status with 'sprite status'".to_string(),
512                    "Start session if not running: 'sprite start'".to_string(),
513                    "Sync any changes: 'sprite sync'".to_string(),
514                    "Navigate to workspace: 'sprite warp <agent>'".to_string(),
515                    "Send commands to agents: 'sprite hey <agent> <command>'".to_string(),
516                    "Check progress and coordinate between agents".to_string(),
517                    "End session: 'sprite kill'".to_string(),
518                ],
519                commands: vec![
520                    "status".to_string(),
521                    "start".to_string(),
522                    "sync".to_string(),
523                    "warp".to_string(),
524                    "hey".to_string(),
525                    "kill".to_string(),
526                ],
527                category: UsageCategory::DailyWorkflow,
528            },
529            UsagePattern {
530                name: "Collaborative Development".to_string(),
531                description: "Working with multiple agents on the same codebase".to_string(),
532                steps: vec![
533                    "Ensure all agents are on latest code: 'sprite send git pull'".to_string(),
534                    "Assign tasks to different agents based on expertise".to_string(),
535                    "Coordinate changes to avoid conflicts".to_string(),
536                    "Regular sync to merge work: 'sprite sync'".to_string(),
537                    "Resolve conflicts if they arise".to_string(),
538                    "Review and test combined changes".to_string(),
539                ],
540                commands: vec![
541                    "send".to_string(),
542                    "sync".to_string(),
543                    "hey".to_string(),
544                    "status".to_string(),
545                ],
546                category: UsageCategory::Collaboration,
547            },
548        ];
549    }
550
551    /// Load troubleshooting guides.
552    fn load_troubleshooting(&mut self) {
553        self.troubleshooting = vec![
554            TroubleshootingGuide {
555                problem: "Session won't start".to_string(),
556                symptoms: vec![
557                    "'sprite start' fails with error".to_string(),
558                    "Tmux session not created".to_string(),
559                    "Agents don't appear in session".to_string(),
560                ],
561                causes: vec![
562                    "Tmux not installed or not in PATH".to_string(),
563                    "Configuration file is corrupted or invalid".to_string(),
564                    "Git repository issues".to_string(),
565                    "Agent workspace creation failed".to_string(),
566                ],
567                solutions: vec![
568                    "Check tmux installation: 'tmux -V'".to_string(),
569                    "Validate configuration: 'sprite config validate'".to_string(),
570                    "Check git status: 'git status'".to_string(),
571                    "Reinitialize: 'sprite init --force'".to_string(),
572                ],
573                prevention: vec![
574                    "Regularly validate configuration".to_string(),
575                    "Keep tmux updated".to_string(),
576                    "Maintain clean git repository".to_string(),
577                ],
578                related_commands: vec![
579                    "config".to_string(),
580                    "init".to_string(),
581                    "status".to_string(),
582                ],
583            },
584            TroubleshootingGuide {
585                problem: "Agent commands not working".to_string(),
586                symptoms: vec![
587                    "Commands sent with 'hey' fail".to_string(),
588                    "No output from agents".to_string(),
589                    "Timeout errors".to_string(),
590                ],
591                causes: vec![
592                    "Session not active".to_string(),
593                    "Agent pane not responding".to_string(),
594                    "Command not found in agent environment".to_string(),
595                    "Network or permission issues".to_string(),
596                ],
597                solutions: vec![
598                    "Check session status: 'sprite status'".to_string(),
599                    "Increase timeout: '--timeout 120'".to_string(),
600                    "Restart session: 'sprite kill && sprite start'".to_string(),
601                    "Check agent environment with simple commands".to_string(),
602                ],
603                prevention: vec![
604                    "Use appropriate timeouts for commands".to_string(),
605                    "Test agent environments regularly".to_string(),
606                    "Monitor agent health with status command".to_string(),
607                ],
608                related_commands: vec![
609                    "status".to_string(),
610                    "hey".to_string(),
611                    "start".to_string(),
612                ],
613            },
614            TroubleshootingGuide {
615                problem: "Sync conflicts".to_string(),
616                symptoms: vec![
617                    "'sprite sync' reports conflicts".to_string(),
618                    "Git merge conflicts appear".to_string(),
619                    "Agents can't share changes".to_string(),
620                ],
621                causes: vec![
622                    "Multiple agents modified same files".to_string(),
623                    "Uncommitted changes during sync".to_string(),
624                    "Branch divergence".to_string(),
625                ],
626                solutions: vec![
627                    "Commit changes before syncing".to_string(),
628                    "Use conflict resolution: --strategy auto-theirs".to_string(),
629                    "Manual conflict resolution in main workspace".to_string(),
630                    "Coordinate agent work to avoid overlap".to_string(),
631                ],
632                prevention: vec![
633                    "Regular syncs to prevent divergence".to_string(),
634                    "Coordinate agent tasks carefully".to_string(),
635                    "Commit frequently when working with agents".to_string(),
636                ],
637                related_commands: vec!["sync".to_string(), "hey".to_string(), "warp".to_string()],
638            },
639        ];
640    }
641
642    /// Load quick reference information.
643    fn load_quick_reference(&mut self) {
644        self.quick_reference.common_commands = vec![
645            "sprite init".to_string(),
646            "sprite start".to_string(),
647            "sprite agents list".to_string(),
648            "sprite warp --list".to_string(),
649            "sprite hey <agent> <command>".to_string(),
650            "sprite send <command>".to_string(),
651            "sprite sync".to_string(),
652            "sprite status".to_string(),
653            "sprite kill".to_string(),
654        ];
655
656        self.quick_reference.shortcuts = vec![
657            KeyboardShortcut {
658                keys: "Ctrl+C".to_string(),
659                description: "Cancel current command or operation".to_string(),
660                context: "All contexts".to_string(),
661            },
662            KeyboardShortcut {
663                keys: "Ctrl+D".to_string(),
664                description: "Exit current session or shell".to_string(),
665                context: "Tmux sessions".to_string(),
666            },
667            KeyboardShortcut {
668                keys: "Ctrl+B".to_string(),
669                description: "Tmux prefix key".to_string(),
670                context: "Tmux sessions".to_string(),
671            },
672            KeyboardShortcut {
673                keys: "Ctrl+B then d".to_string(),
674                description: "Detach from tmux session".to_string(),
675                context: "Tmux sessions".to_string(),
676            },
677        ];
678
679        self.quick_reference.faq = vec![
680            Faq {
681                question: "How do I get started with Sprite?".to_string(),
682                answer: "Run 'sprite init' in your git repository, then 'sprite start' to begin your first session. Use 'sprite warp --list' to see available workspaces.".to_string(),
683                related_commands: vec!["init".to_string(), "start".to_string(), "warp".to_string()],
684            },
685            Faq {
686                question: "Can I use Sprite without tmux?".to_string(),
687                answer: "No, Sprite requires tmux for session management and multi-agent coordination. Install tmux first, then use Sprite.".to_string(),
688                related_commands: vec![],
689            },
690            Faq {
691                question: "How do I actually change directories with warp?".to_string(),
692                answer: "Use 'cd $(sprite warp --print <name>)' to change directory. Sprite warp shows the path but doesn't change directories itself.".to_string(),
693                related_commands: vec!["warp".to_string()],
694            },
695            Faq {
696                question: "What's the difference between 'hey' and 'send'?".to_string(),
697                answer: "'hey' sends commands to a specific agent, while 'send' broadcasts to all agents. Use 'hey' for targeted tasks, 'send' for maintenance or coordination.".to_string(),
698                related_commands: vec!["hey".to_string(), "send".to_string()],
699            },
700        ];
701    }
702
703    /// Get help for a specific command.
704    pub fn get_command_help(&self, command: &str) -> Option<&CommandHelp> {
705        self.commands.get(command)
706    }
707
708    /// Get all available commands.
709    pub fn list_commands(&self) -> Vec<&str> {
710        self.commands.keys().map(|s| s.as_str()).collect()
711    }
712
713    /// Get usage patterns by category.
714    pub fn get_usage_patterns(&self, category: Option<UsageCategory>) -> Vec<&UsagePattern> {
715        match category {
716            Some(cat) => self
717                .usage_patterns
718                .iter()
719                .filter(|p| p.category == cat)
720                .collect(),
721            None => self.usage_patterns.iter().collect(),
722        }
723    }
724
725    /// Get troubleshooting guides.
726    pub fn get_troubleshooting(&self) -> &[TroubleshootingGuide] {
727        &self.troubleshooting
728    }
729
730    /// Get quick reference.
731    pub fn get_quick_reference(&self) -> &QuickReference {
732        &self.quick_reference
733    }
734
735    /// Search help content.
736    pub fn search(&self, query: &str) -> Vec<HelpResult> {
737        let mut results = Vec::new();
738        let query_lower = query.to_lowercase();
739
740        // Search commands
741        for (name, command) in &self.commands {
742            if name.contains(&query_lower)
743                || command.description.to_lowercase().contains(&query_lower)
744            {
745                results.push(HelpResult {
746                    result_type: HelpResultType::Command,
747                    title: format!("Command: {}", name),
748                    description: command.description.clone(),
749                    action: format!("sprite {} --help", name),
750                });
751            }
752
753            // Search examples
754            for example in &command.examples {
755                if example.to_lowercase().contains(&query_lower) {
756                    results.push(HelpResult {
757                        result_type: HelpResultType::Example,
758                        title: format!("Example: {}", name),
759                        description: example.clone(),
760                        action: example.clone(),
761                    });
762                }
763            }
764
765            // Search tips
766            for tip in &command.tips {
767                if tip.to_lowercase().contains(&query_lower) {
768                    results.push(HelpResult {
769                        result_type: HelpResultType::Tip,
770                        title: format!("Tip: {}", name),
771                        description: tip.clone(),
772                        action: format!("sprite {} --help", name),
773                    });
774                }
775            }
776        }
777
778        // Search troubleshooting
779        for guide in &self.troubleshooting {
780            if guide.problem.to_lowercase().contains(&query_lower) {
781                results.push(HelpResult {
782                    result_type: HelpResultType::Troubleshooting,
783                    title: format!("Problem: {}", guide.problem),
784                    description: guide.symptoms.join("; "),
785                    action: "Check troubleshooting guide".to_string(),
786                });
787            }
788        }
789
790        results
791    }
792
793    /// Format help output for display.
794    pub fn format_help(&self, command: Option<&str>) -> String {
795        match command {
796            Some(cmd) => {
797                if let Some(help) = self.get_command_help(cmd) {
798                    self.format_command_help(help)
799                } else {
800                    format!(
801                        "Command '{}' not found. Available commands:\n{}",
802                        cmd,
803                        self.list_commands().join(", ")
804                    )
805                }
806            }
807            None => self.format_general_help(),
808        }
809    }
810
811    /// Format command help.
812    fn format_command_help(&self, help: &CommandHelp) -> String {
813        let mut output = String::new();
814
815        output.push_str(&format!("šŸ”§ {} - {}\n\n", help.name, help.description));
816        output.push_str(&format!("Usage: {}\n\n", help.usage));
817
818        if !help.examples.is_empty() {
819            output.push_str("Examples:\n");
820            for example in &help.examples {
821                output.push_str(&format!("  {}\n", example));
822            }
823            output.push('\n');
824        }
825
826        if !help.prerequisites.is_empty() {
827            output.push_str("Prerequisites:\n");
828            for prereq in &help.prerequisites {
829                output.push_str(&format!("  • {}\n", prereq));
830            }
831            output.push('\n');
832        }
833
834        if !help.tips.is_empty() {
835            output.push_str("Tips:\n");
836            for tip in &help.tips {
837                output.push_str(&format!("  šŸ’” {}\n", tip));
838            }
839            output.push('\n');
840        }
841
842        if !help.common_mistakes.is_empty() {
843            output.push_str("Common Mistakes:\n");
844            for mistake in &help.common_mistakes {
845                output.push_str(&format!("  āš ļø  {}\n", mistake));
846            }
847            output.push('\n');
848        }
849
850        if !help.related_commands.is_empty() {
851            output.push_str(&format!(
852                "Related Commands: {}\n",
853                help.related_commands.join(", ")
854            ));
855        }
856
857        output
858    }
859
860    /// Format general help.
861    fn format_general_help(&self) -> String {
862        let mut output = String::new();
863
864        output.push_str("šŸš€ Sprite - Multi-Agent Workflow Toolkit\n\n");
865        output.push_str(
866            "Sprite helps you manage multiple AI coding agents in isolated tmux sessions\n",
867        );
868        output.push_str("with comprehensive workspace management and health monitoring.\n\n");
869
870        output.push_str("šŸ“‹ Quick Start:\n");
871        output.push_str("  1. sprite init          # Initialize project\n");
872        output.push_str("  2. sprite start         # Start session\n");
873        output.push_str("  3. sprite hey 1 <cmd>   # Send command to agent 1\n");
874        output.push_str("  4. sprite status        # Check status\n\n");
875
876        output.push_str("šŸ”§ Core Commands:\n");
877        for cmd in &[
878            "init", "start", "agents", "warp", "hey", "send", "sync", "status",
879        ] {
880            if let Some(help) = self.get_command_help(cmd) {
881                output.push_str(&format!("  {:12} - {}\n", cmd, help.description));
882            }
883        }
884
885        output.push_str("\nšŸ’” Get Help:\n");
886        output.push_str("  sprite help <command>  # Get detailed help for a command\n");
887        output.push_str("  sprite help --search  # Search help content\n");
888        output.push_str("  sprite help --patterns # Show usage patterns\n");
889
890        output
891    }
892
893    /// Generate accessible help output.
894    pub fn format_accessible_help(&self, command: Option<&str>) -> String {
895        // Similar to format_help but with enhanced accessibility features
896        let mut output = "SCREEN READER HELP FOR SPRITE\n\n".to_string();
897
898        if let Some(cmd) = command {
899            if let Some(help) = self.get_command_help(cmd) {
900                output.push_str(&format!("COMMAND: {}\n", help.name.to_uppercase()));
901                output.push_str(&format!("DESCRIPTION: {}\n", help.description));
902                output.push_str(&format!("USAGE: {}\n", help.usage));
903
904                output.push_str("\nEXAMPLES:\n");
905                for (i, example) in help.examples.iter().enumerate() {
906                    output.push_str(&format!("EXAMPLE {}: {}\n", i + 1, example));
907                }
908
909                if !help.prerequisites.is_empty() {
910                    output.push_str("\nPREREQUISITES:\n");
911                    for (i, prereq) in help.prerequisites.iter().enumerate() {
912                        output.push_str(&format!("{}. {}\n", i + 1, prereq));
913                    }
914                }
915
916                output.push_str("\nRELATED COMMANDS:\n");
917                output.push_str(&help.related_commands.join(", "));
918            } else {
919                output.push_str(&format!("COMMAND '{}' NOT FOUND\n", cmd.to_uppercase()));
920                output.push_str("AVAILABLE COMMANDS:\n");
921                for cmd_name in self.list_commands() {
922                    output.push_str(&format!("• {}\n", cmd_name));
923                }
924            }
925        } else {
926            output.push_str("SPRITE OVERVIEW\n");
927            output.push_str(
928                "Sprite is a command-line toolkit for managing multiple AI coding agents.\n\n",
929            );
930
931            output.push_str("AVAILABLE COMMANDS:\n");
932            for cmd_name in self.list_commands() {
933                if let Some(help) = self.get_command_help(cmd_name) {
934                    output.push_str(&format!("• {}: {}\n", cmd_name, help.description));
935                }
936            }
937
938            output.push_str("\nFor detailed help on any command, use: sprite help <command>\n");
939        }
940
941        output
942    }
943}
944
945impl Default for HelpSystem {
946    fn default() -> Self {
947        Self::new()
948    }
949}
950
951/// Result of a help search.
952#[derive(Debug, Clone)]
953pub struct HelpResult {
954    /// Type of result
955    pub result_type: HelpResultType,
956    /// Title
957    pub title: String,
958    /// Description
959    pub description: String,
960    /// Suggested action
961    pub action: String,
962}
963
964/// Type of help result.
965#[derive(Debug, Clone, PartialEq)]
966pub enum HelpResultType {
967    /// Command help
968    Command,
969    /// Usage example
970    Example,
971    /// Tip or trick
972    Tip,
973    /// Troubleshooting guide
974    Troubleshooting,
975}
976
977impl fmt::Display for HelpSystem {
978    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
979        write!(
980            f,
981            "Sprite Help System with {} commands",
982            self.commands.len()
983        )
984    }
985}
986
987/// Get the global help system instance.
988pub fn get_help_system() -> HelpSystem {
989    HelpSystem::new()
990}
991
992/// Show help for a specific command.
993pub fn show_help(command: Option<&str>) -> Result<()> {
994    let help_system = get_help_system();
995    let help_text = help_system.format_help(command);
996    println!("{}", help_text);
997    Ok(())
998}
999
1000/// Show accessible help.
1001pub fn show_accessible_help(command: Option<&str>) -> Result<()> {
1002    let help_system = get_help_system();
1003    let help_text = help_system.format_accessible_help(command);
1004    println!("{}", help_text);
1005    Ok(())
1006}
1007
1008/// Search help content.
1009pub fn search_help(query: &str) -> Result<()> {
1010    let help_system = get_help_system();
1011    let results = help_system.search(query);
1012
1013    if results.is_empty() {
1014        println!("No results found for: {}", query);
1015        return Ok(());
1016    }
1017
1018    println!("šŸ” Search Results for: {}\n", query);
1019    for result in results {
1020        match result.result_type {
1021            HelpResultType::Command => println!("šŸ“‹ Command:"),
1022            HelpResultType::Example => println!("šŸ’” Example:"),
1023            HelpResultType::Tip => println!("✨ Tip:"),
1024            HelpResultType::Troubleshooting => println!("šŸ”§ Troubleshooting:"),
1025        }
1026
1027        println!("  {}", result.title);
1028        println!("  {}", result.description);
1029
1030        if !result.action.is_empty() {
1031            println!("  Action: {}", result.action);
1032        }
1033
1034        println!();
1035    }
1036
1037    Ok(())
1038}
1039
1040/// Show usage patterns.
1041pub fn show_usage_patterns(category: Option<UsageCategory>) -> Result<()> {
1042    let help_system = get_help_system();
1043    let patterns = help_system.get_usage_patterns(category);
1044
1045    if patterns.is_empty() {
1046        println!("No usage patterns found.");
1047        return Ok(());
1048    }
1049
1050    println!("šŸ“š Usage Patterns\n");
1051    for pattern in patterns {
1052        println!("šŸŽÆ {}\n", pattern.name);
1053        println!("{}\n", pattern.description);
1054
1055        println!("Steps:");
1056        for (i, step) in pattern.steps.iter().enumerate() {
1057            println!("  {}. {}", i + 1, step);
1058        }
1059
1060        println!("Commands: {}\n", pattern.commands.join(", "));
1061    }
1062
1063    Ok(())
1064}
1065
1066#[cfg(test)]
1067mod tests {
1068    use super::*;
1069
1070    #[test]
1071    fn test_help_system_creation() {
1072        let help_system = HelpSystem::new();
1073        assert!(!help_system.commands.is_empty());
1074        assert!(help_system.get_command_help("init").is_some());
1075    }
1076
1077    #[test]
1078    fn test_command_help() {
1079        let help_system = HelpSystem::new();
1080        let init_help = help_system.get_command_help("init").unwrap();
1081        assert_eq!(init_help.name, "init");
1082        assert!(!init_help.description.is_empty());
1083        assert!(!init_help.examples.is_empty());
1084    }
1085
1086    #[test]
1087    fn test_search_functionality() {
1088        let help_system = HelpSystem::new();
1089        let results = help_system.search("init");
1090        assert!(!results.is_empty());
1091
1092        let results = help_system.search("nonexistent");
1093        assert!(results.is_empty());
1094    }
1095
1096    #[test]
1097    fn test_usage_patterns() {
1098        let help_system = HelpSystem::new();
1099        let patterns = help_system.get_usage_patterns(Some(UsageCategory::GettingStarted));
1100        assert!(!patterns.is_empty());
1101
1102        for pattern in patterns {
1103            assert_eq!(pattern.category, UsageCategory::GettingStarted);
1104        }
1105    }
1106}