### Start(firstTimeSetup bool) Source: https://github.com/smtg-ai/claude-squad/blob/main/_autodocs/04-instance-lifecycle.md Starts the instance by creating a tmux session and git worktree. ```APIDOC ## Start(firstTimeSetup bool) ### Description Starts the instance. If firstTimeSetup is true, it creates a git worktree and tmux session. If false, it restores an existing tmux session. ### Signature `func (i *Instance) Start(firstTimeSetup bool) error` ### Parameters - **firstTimeSetup** (bool) - Required - True for new instances, false when resuming paused instances. ### Returns - `error` - Returns an error if git setup, tmux creation, or program start fails. ``` -------------------------------- ### LaunchDaemon CLI Example Source: https://github.com/smtg-ai/claude-squad/blob/main/_autodocs/09-daemon-and-background-operations.md Example command showing how the daemon process is invoked. ```bash # If main process is /usr/local/bin/claude-squad: /usr/local/bin/claude-squad --daemon ``` -------------------------------- ### Example configuration JSON Source: https://github.com/smtg-ai/claude-squad/blob/main/_autodocs/03-config-state.md A sample JSON representation of the configuration file. ```json { "default_program": "claude", "auto_yes": false, "daemon_poll_interval": 1000, "branch_prefix": "john/", "profiles": [ { "name": "claude", "program": "claude" }, { "name": "aider", "program": "aider --model ollama_chat/gemma3:1b" }, { "name": "codex", "program": "codex" } ] } ``` -------------------------------- ### Install dependencies Source: https://github.com/smtg-ai/claude-squad/blob/main/CONTRIBUTING.md Downloads the necessary Go modules for the project. ```bash go mod download ``` -------------------------------- ### Start the development server Source: https://github.com/smtg-ai/claude-squad/blob/main/web/README.md Run the development server using your preferred package manager. ```bash npm run dev # or yarn dev # or pnpm dev # or bun dev ``` -------------------------------- ### Start a new tmux session Source: https://github.com/smtg-ai/claude-squad/blob/main/_autodocs/06-tmux-sessions.md Defines the signature for initializing a new session and provides a usage example. ```go func (t *TmuxSession) Start(workDir string) error ``` ```go session := tmux.NewTmuxSession("my-task", "claude") err := session.Start("/path/to/repo") // Session is now running with claude ``` -------------------------------- ### Start and Resume Instance Execution Source: https://github.com/smtg-ai/claude-squad/blob/main/_autodocs/04-instance-lifecycle.md Starts a new instance or resumes a previously paused one by managing tmux sessions and git worktrees. ```go func (i *Instance) Start(firstTimeSetup bool) error ``` ```go instance, _ := session.NewInstance(opts) err := instance.Start(true) // First time starting // ... later ... err := instance.Start(false) // Resuming from pause ``` -------------------------------- ### Start Background Instance Source: https://github.com/smtg-ai/claude-squad/blob/main/_autodocs/07-ui-components.md Executes instance startup in a background goroutine and returns a completion message. ```go func (m *home) runInstanceStartCmd(instance *session.Instance) tea.Cmd ``` -------------------------------- ### Started() Source: https://github.com/smtg-ai/claude-squad/blob/main/_autodocs/04-instance-lifecycle.md Checks if the tmux session and git worktree are initialized. ```APIDOC ### func (i *Instance) Started() bool Returns true if tmux session and git worktree are initialized. ``` -------------------------------- ### NewTmuxSession Usage Example Source: https://github.com/smtg-ai/claude-squad/blob/main/_autodocs/06-tmux-sessions.md Demonstrates initializing a session and the resulting name sanitization. ```go session := tmux.NewTmuxSession("My Task", "claude") // sanitizedName becomes: "claudesquad_MyTask" ``` -------------------------------- ### Start(workDir string) Source: https://github.com/smtg-ai/claude-squad/blob/main/_autodocs/06-tmux-sessions.md Creates and starts a new detached tmux session in the specified working directory. ```APIDOC ## Start(workDir string) ### Description Creates and starts a new detached tmux session. It validates the session, configures settings like history-limit and mouse scrolling, and attaches a PTY monitor. ### Parameters - **workDir** (string) - Required - Working directory for the session ### Returns - **error** - Returns an error if session creation or restore fails ``` -------------------------------- ### Setup From Existing Branch Source: https://github.com/smtg-ai/claude-squad/blob/main/_autodocs/05-git-operations.md Creates a worktree from a branch that already exists locally or on the remote. ```go func (g *GitWorktree) setupFromExistingBranch() error ``` -------------------------------- ### Example Daemon Log Output Source: https://github.com/smtg-ai/claude-squad/blob/main/_autodocs/09-daemon-and-background-operations.md Sample log entries showing startup, instance loading, and polling activity. ```text 2024-07-10 10:30:45 INFO Daemon started with poll interval 1000ms 2024-07-10 10:30:45 INFO Loaded 2 instances from storage 2024-07-10 10:30:46 INFO Started instance "task-1" 2024-07-10 10:30:47 INFO Starting polling loop 2024-07-10 10:31:47 INFO Detected and dismissed trust prompt for "task-1" 2024-07-10 10:32:47 INFO Instance "task-1" running ``` -------------------------------- ### Worktree Path Example Source: https://github.com/smtg-ai/claude-squad/blob/main/_autodocs/05-git-operations.md An example of a generated worktree path with a timestamp suffix. ```text ~/.claude-squad/worktrees/john_my_task_1625945823123456789 ``` -------------------------------- ### Define Instance Options and Initialization Source: https://github.com/smtg-ai/claude-squad/blob/main/_autodocs/04-instance-lifecycle.md Defines the structure for instance configuration and demonstrates how to initialize a new instance without starting it. ```go func NewInstance(opts InstanceOptions) (*Instance, error) type InstanceOptions struct { Title string Path string Program string AutoYes bool Branch string // Existing branch to start on (empty = new) } ``` ```go instance, err := session.NewInstance(session.InstanceOptions{ Title: "my-task", Path: ".", Program: "claude", Branch: "", // Create new branch }) ``` -------------------------------- ### Version Command Output Source: https://github.com/smtg-ai/claude-squad/blob/main/_autodocs/02-cli-commands.md Example output displayed when running the version command. ```text claude-squad version 1.0.19 https://github.com/smtg-ai/claude-squad/releases/tag/v1.0.19 ``` -------------------------------- ### Handle Instance Start Failures Source: https://github.com/smtg-ai/claude-squad/blob/main/_autodocs/09-daemon-and-background-operations.md Logs errors during instance startup without crashing the daemon process. ```go if err := instance.Start(false) { log.ErrorLog.Printf("failed to start instance: %v", err) // Continue with next instance } ``` -------------------------------- ### Time Handling Example Source: https://github.com/smtg-ai/claude-squad/blob/main/_autodocs/10-storage-and-serialization.md Demonstrates the progression of CreatedAt and UpdatedAt timestamps during instance lifecycle events. ```text Instance created: CreatedAt = 2024-07-10T10:00:00Z Instance updated: UpdatedAt = 2024-07-10T10:05:00Z Instance paused: UpdatedAt = 2024-07-10T10:10:00Z ``` -------------------------------- ### Manage Instance Lifecycle in Go Source: https://github.com/smtg-ai/claude-squad/blob/main/_autodocs/QUICK-REFERENCE.md Initialize, start, interact with, and terminate a session instance. ```go // Step 1: Create instance (not started yet) instance, err := session.NewInstance(session.InstanceOptions{ Title: "my-task", Path: ".", Program: "claude", }) // Step 2: Start instance (creates worktree and tmux session) err := instance.Start(true) // Step 3: Send prompt (optional) err := instance.SendPrompt("Implement feature X") // Step 4: Attach interactively (optional) done, err := instance.Attach() // User interactive terminal <-done // Returns when user detaches ``` -------------------------------- ### Install Claude Squad via Homebrew Source: https://github.com/smtg-ai/claude-squad/blob/main/README.md Installs the binary and creates a symbolic link for the 'cs' command. ```bash brew install claude-squad ln -s "$(brew --prefix)/bin/claude-squad" "$(brew --prefix)/bin/cs" ``` -------------------------------- ### Example Profile JSON Source: https://github.com/smtg-ai/claude-squad/blob/main/_autodocs/08-types-and-data-structures.md A sample JSON object representing a configured profile. ```json { "name": "aider", "program": "aider --model ollama_chat/gemma3:1b" } ``` -------------------------------- ### Cleanup Instance on Setup Failure Source: https://github.com/smtg-ai/claude-squad/blob/main/_autodocs/11-error-handling.md Uses a deferred function to ensure instance cleanup if an error occurs during startup. ```go defer func() { if setupErr != nil { if cleanupErr := i.Kill(); cleanupErr != nil { setupErr = fmt.Errorf("%v (cleanup error: %v)", setupErr, cleanupErr) } } }() ``` -------------------------------- ### StopDaemon CLI Example Source: https://github.com/smtg-ai/claude-squad/blob/main/_autodocs/09-daemon-and-background-operations.md Example commands to identify and terminate the daemon process manually. ```bash ps aux | grep "claude-squad --daemon" kill -TERM {pid} ``` -------------------------------- ### Restore() Source: https://github.com/smtg-ai/claude-squad/blob/main/_autodocs/06-tmux-sessions.md Attaches a PTY to an existing session and starts monitoring. ```APIDOC ## Restore() ### Description Attaches a PTY to an existing session and starts the status monitor goroutine. This is typically used after creating a session or resuming a paused instance. ### Returns - **error** - Returns an error if PTY creation or attach fails ``` -------------------------------- ### Debug Command Output Source: https://github.com/smtg-ai/claude-squad/blob/main/_autodocs/02-cli-commands.md Example output showing configuration paths and JSON settings. ```json Config: /home/user/.claude-squad/config.json { "default_program": "claude", "auto_yes": false, "daemon_poll_interval": 1000, "branch_prefix": "username/", "profiles": [...] } ``` -------------------------------- ### CLI Command Usage Source: https://github.com/smtg-ai/claude-squad/blob/main/_autodocs/02-cli-commands.md Examples of invoking the root command with various flags. ```bash cs cs -p "aider --model ollama_chat/gemma3:1b" cs -y # enable auto-yes mode ``` -------------------------------- ### Install Claude Squad Manually Source: https://github.com/smtg-ai/claude-squad/blob/main/README.md Downloads and installs the binary to ~/.local/bin. An optional name flag can be provided to customize the binary name. ```bash curl -fsSL https://raw.githubusercontent.com/smtg-ai/claude-squad/main/install.sh | bash ``` ```bash curl -fsSL https://raw.githubusercontent.com/smtg-ai/claude-squad/main/install.sh | bash -s -- --name ``` -------------------------------- ### Setup Git Worktree Source: https://github.com/smtg-ai/claude-squad/blob/main/_autodocs/05-git-operations.md Initializes the worktree directory and branch based on existing state or new branch creation. ```go func (g *GitWorktree) Setup() error ``` -------------------------------- ### Set Selected Branch Source: https://github.com/smtg-ai/claude-squad/blob/main/_autodocs/04-instance-lifecycle.md Sets the branch to use before starting the instance. ```go func (i *Instance) SetSelectedBranch(branch string) ``` -------------------------------- ### NewInstance(opts InstanceOptions) Source: https://github.com/smtg-ai/claude-squad/blob/main/_autodocs/04-instance-lifecycle.md Creates a new instance object without starting it, setting the initial state to Ready. ```APIDOC ## NewInstance(opts InstanceOptions) ### Description Creates a new instance without starting it. It converts the path to an absolute path, sets the status to Ready, and records the creation timestamp. ### Signature `func NewInstance(opts InstanceOptions) (*Instance, error)` ### Parameters - **opts** (InstanceOptions) - Required - Configuration options including Title, Path, Program, AutoYes, and Branch. ### Returns - `(*Instance, error)` - The instance in Ready state or an error if creation fails. ``` -------------------------------- ### Set Instance Title Source: https://github.com/smtg-ai/claude-squad/blob/main/_autodocs/04-instance-lifecycle.md Sets the instance title. Cannot be changed after the instance has started. ```go func (i *Instance) SetTitle(title string) error ``` -------------------------------- ### Get configuration directory Source: https://github.com/smtg-ai/claude-squad/blob/main/_autodocs/03-config-state.md Returns the absolute path to the application's configuration directory. ```go func GetConfigDir() (string, error) ``` -------------------------------- ### Daemon Auto-Yes Startup Flow Source: https://github.com/smtg-ai/claude-squad/blob/main/_autodocs/12-integration-examples.md The initialization sequence when starting the application with the auto-yes flag enabled. ```text cs -y ↓ main.go: rootCmd.RunE: autoYes = true app.Run(ctx, program, autoYes) ↓ newHome creates app with autoYes=true ↓ Loads instances from storage ↓ Sets AutoYes on all loaded instances ↓ Starts TUI (Bubble Tea event loop) ↓ Main function continues: defer daemon.LaunchDaemon() daemon.StopDaemon() // Kill any existing app.Run(...) ↓ TUI exits (user presses 'q') ↓ Defer: daemon.LaunchDaemon() executes ↓ Spawns background daemon process {exe} --daemon ↓ Returns immediately ↓ Main function exits ↓ Daemon continues running in background ``` -------------------------------- ### Instance Lifecycle Workflow Source: https://github.com/smtg-ai/claude-squad/blob/main/_autodocs/06-tmux-sessions.md Visualizes the sequence of operations for creating, starting, attaching, detaching, pausing, and resuming tmux-backed instances. ```text // Create instance instance, _ := session.NewInstance(opts) // Start calls: instance.Start(true) ↓ Creates GitWorktree ↓ Creates TmuxSession ↓ Calls TmuxSession.Start(worktreePath) ↓ Session is running // User attaches instance.Attach() ↓ TmuxSession.Attach() ↓ Terminal shows claude // User detaches (Ctrl+D) ↓ Channel closes ↓ UI resumes control // Pause instance instance.Pause() ↓ TmuxSession.DetachSafely() ↓ Session preserved in tmux ↓ TmuxSession object deleted // Resume instance instance.Resume() ↓ Creates new TmuxSession ↓ TmuxSession.Restore() ↓ Reconnects to preserved session ``` -------------------------------- ### Process Instance Title and Start Background Task Source: https://github.com/smtg-ai/claude-squad/blob/main/_autodocs/12-integration-examples.md Handles the submission of an instance title, triggers the background startup process, and updates the UI state upon completion. ```go stateNew handles key input ↓ Case KeyEnter: instance.Title = "my-task" instance.SetStatus(Loading) m.newInstanceFinalizer() // Register in list // Return background command to start startCmd := func() tea.Msg { err := instance.Start(true) return instanceStartedMsg{ instance: instance, err: err, promptAfterName: false, } } ↓ Background goroutine runs: instance.Start(true) ↓ git.NewGitWorktree(i.Path, i.Title) ↓ Creates GitWorktree (no disk ops yet) branchName = "john/my-task" ↓ i.gitWorktree.Setup() ↓ Creates ~/.claude-squad/worktrees/john_my_task_{timestamp}/ Runs: git worktree add -b john/my-task {path} HEAD ↓ Worktree created, branch checked out ↓ i.tmuxSession = tmux.NewTmuxSession(i.Title, i.Program) ↓ i.tmuxSession.Start(worktreePath) ↓ Runs: tmux new-session -d -s claudesquad_my-task -c {path} claude Polls for session creation Configures history-limit, mouse Calls Restore() to attach PTY ↓ tmux session running with claude inside ↓ i.SetStatus(Running) i.started = true ↓ instanceStartedMsg sent to event loop ↓ case instanceStartedMsg: m.storage.SaveInstances(m.list.GetInstances()) ↓ Saves all instances to ~/.claude-squad/state.json m.menu.SetState(StateDefault) m.showHelpScreen(helpStart(instance), nil) ↓ Shows help overlay about what user can do next ↓ UI back to normal, instance ready ``` -------------------------------- ### Daemon Management Commands Source: https://github.com/smtg-ai/claude-squad/blob/main/_autodocs/QUICK-REFERENCE.md Commands for starting, stopping, and verifying the background daemon process. ```bash # Start with daemon cs -y # Daemon runs in background # Automatically accepts prompts for all instances # Stop daemon (next TUI start stops it) cs # Check if daemon running ps aux | grep "claude-squad --daemon" # Manual daemon start claude-squad --daemon ``` -------------------------------- ### NewGitWorktree Constructor Source: https://github.com/smtg-ai/claude-squad/blob/main/_autodocs/05-git-operations.md Initializes a new GitWorktree instance with a fresh branch. Setup() must be called subsequently to create the physical directories. ```go func NewGitWorktree(repoPath string, sessionName string) ( tree *GitWorktree, branchName string, err error, ) ``` ```go tree, branchName, err := git.NewGitWorktree(".", "my-task") // branchName might be "john/my-task" // tree.worktreePath will be something like: // ~/.claude-squad/worktrees/john_my-task_1234567890 ``` -------------------------------- ### Save instances to disk Source: https://github.com/smtg-ai/claude-squad/blob/main/_autodocs/10-storage-and-serialization.md Persists started instances to the state file. Unstarted instances are automatically filtered out. ```go func (s *Storage) SaveInstances(instances []*Instance) error ``` ```go instances := m.list.GetInstances() err := storage.SaveInstances(instances) ``` -------------------------------- ### Get program command Source: https://github.com/smtg-ai/claude-squad/blob/main/_autodocs/03-config-state.md Retrieves the program command based on the current configuration and profiles. ```go func (c *Config) GetProgram() string ``` -------------------------------- ### Get profiles list Source: https://github.com/smtg-ai/claude-squad/blob/main/_autodocs/03-config-state.md Returns a unified list of profiles, ensuring the default profile is prioritized. ```go func (c *Config) GetProfiles() []Profile ``` -------------------------------- ### Configure Daemon Poll Interval Source: https://github.com/smtg-ai/claude-squad/blob/main/_autodocs/09-daemon-and-background-operations.md Example JSON configuration for setting the daemon polling interval. ```json { "daemon_poll_interval": 500 // Poll every 500ms (more responsive) } ``` -------------------------------- ### Debug and Manage Daemon via CLI Source: https://github.com/smtg-ai/claude-squad/blob/main/_autodocs/09-daemon-and-background-operations.md Commands for starting, monitoring, and terminating the daemon process manually. ```bash # Start daemon directly claude-squad --daemon # Monitor log file tail -f ~/.claude-squad/claude-squad.log # Check if daemon running ps aux | grep "claude-squad --daemon" # Kill daemon killall claude-squad --daemon ``` -------------------------------- ### Handle New Instance Key Press Source: https://github.com/smtg-ai/claude-squad/blob/main/_autodocs/12-integration-examples.md Initializes a new instance object when the user triggers the creation action. ```go User presses 'n' in default state ↓ m.handleKeyPress(KeyMsg) ↓ case keys.KeyNew: instance, err := session.NewInstance(session.InstanceOptions{ Title: "", Path: ".", Program: m.program, }) ↓ Instance created (not yet started) ↓ m.newInstanceFinalizer = m.list.AddInstance(instance) m.state = stateNew ↓ UI enters stateNew mode Menu shows "Enter name" prompt List shows new empty-titled instance ``` -------------------------------- ### Full Instance Workflow Source: https://github.com/smtg-ai/claude-squad/blob/main/_autodocs/QUICK-REFERENCE.md Demonstrates the complete lifecycle of a Claude instance from creation and prompting to reviewing changes and persisting state. ```go // 1. Create instance instance, err := session.NewInstance(session.InstanceOptions{ Title: "feature-x", Path: ".", Program: "claude", }) // 2. Start instance err = instance.Start(true) // 3. Send initial prompt err = instance.SendPrompt("Implement feature X") // 4. Later: get status if instance.HasUpdated() { fmt.Println("Claude finished working") } // 5. Review changes worktree, _ := instance.GetGitWorktree() diff := instance.ComputeDiff() fmt.Printf("Changes: +%d -%d\n", diff.Added, diff.Removed) // 6. Push changes err = worktree.PushChanges("[done] feature X", false) // 7. Save to storage storage, _ := session.NewStorage(appState) err = storage.SaveInstances([]*session.Instance{instance}) ``` -------------------------------- ### Handle Configuration Source: https://github.com/smtg-ai/claude-squad/blob/main/_autodocs/QUICK-REFERENCE.md Load, retrieve, and persist application configuration settings. ```go // Load configuration from disk config := config.LoadConfig() // Get the program to run program := config.GetProgram() // Get available profiles profiles := config.GetProfiles() // Save configuration err := config.SaveConfig(config) ``` -------------------------------- ### Initialize Instances in Daemon Source: https://github.com/smtg-ai/claude-squad/blob/main/_autodocs/09-daemon-and-background-operations.md Loads and resumes instances upon daemon startup without blocking on slow operations. ```go instances, err := storage.LoadInstances() for _, instance := range instances { instance.AutoYes = true if !instance.Started() { err := instance.Start(false) // Resume mode if err != nil { log.ErrorLog.Printf("failed to start instance: %v", err) } } } ``` -------------------------------- ### Load configuration Source: https://github.com/smtg-ai/claude-squad/blob/main/_autodocs/03-config-state.md Loads application configuration from disk or creates a default one if missing. ```go func LoadConfig() *Config ``` -------------------------------- ### Initialize Storage Source: https://github.com/smtg-ai/claude-squad/blob/main/_autodocs/10-storage-and-serialization.md Constructor for the Storage system, requiring a configuration state backend. ```go func NewStorage(state config.InstanceStorage) (*Storage, error) ``` ```go appState := config.LoadState() storage, err := session.NewStorage(appState) ``` -------------------------------- ### Show Help Screen Source: https://github.com/smtg-ai/claude-squad/blob/main/_autodocs/07-ui-components.md Displays a help overlay using TextOverlay with a specific help type and callback function. ```go m.showHelpScreen(helpStart(instance), callback) ``` -------------------------------- ### Instance Persistence Cycle Source: https://github.com/smtg-ai/claude-squad/blob/main/_autodocs/10-storage-and-serialization.md Illustrates the lifecycle of an instance from creation and saving to disk, through to restoration upon restart. ```go // 1. User creates instance in TUI instance, _ := session.NewInstance(opts) m.list.AddInstance(instance) // 2. User presses Enter to start _ = instance.Start(true) m.storage.SaveInstances(m.list.GetInstances()) // 3. Instance has a title "my-task" // 4. Saved to disk as: { "title": "my-task", "path": "/home/user/repo", "branch": "user/my-task", "status": 1, // Ready "program": "claude", "worktree": { "repo_path": "/home/user/repo", "worktree_path": "~/.claude-squad/worktrees/...", "branch_name": "user/my-task", ... }, ... } // 5. User quits TUI // Instances remain in ~/.claude-squad/state.json // 6. User restarts TUI // LoadInstances reconstructs instance // instance.Start(false) restores tmux session // Instance continues from where it was paused ``` -------------------------------- ### Tmux Session Naming Convention Source: https://github.com/smtg-ai/claude-squad/blob/main/_autodocs/06-tmux-sessions.md Example of how session names are sanitized using the claudesquad_ prefix. ```text Input: "My Task" Sanitized: "claudesquad_MyTask" ``` -------------------------------- ### Manage Daemon Lifecycle in Main Application Source: https://github.com/smtg-ai/claude-squad/blob/main/_autodocs/09-daemon-and-background-operations.md Handles daemon cleanup and background launch during application startup. ```go if autoYes { defer func() { if err := daemon.LaunchDaemon(); err != nil { log.ErrorLog.Printf("failed to launch daemon: %v", err) } }() } // Kill any daemon that's running if err := daemon.StopDaemon(); err != nil { log.ErrorLog.Printf("failed to stop daemon: %v", err) } return app.Run(ctx, program, autoYes) ``` -------------------------------- ### Define InstanceOptions struct Source: https://github.com/smtg-ai/claude-squad/blob/main/_autodocs/08-types-and-data-structures.md Configuration parameters required for initializing a new instance. ```go type InstanceOptions struct { Title string Path string Program string AutoYes bool Branch string } ``` -------------------------------- ### Load Configuration with Default Fallback Source: https://github.com/smtg-ai/claude-squad/blob/main/_autodocs/11-error-handling.md Creates and saves a default configuration if the existing configuration file is missing. ```go func LoadConfig() *Config { // If file missing, create default if os.IsNotExist(err) { defaultCfg := DefaultConfig() if saveErr := saveConfig(defaultCfg); saveErr != nil { log.WarningLog.Printf("failed to save default config: %v", saveErr) } return defaultCfg } } ``` -------------------------------- ### Instance Management Source: https://github.com/smtg-ai/claude-squad/blob/main/_autodocs/QUICK-REFERENCE.md Methods for creating, starting, pausing, resuming, and terminating Claude Squad instances. ```APIDOC ## session.NewInstance ### Description Creates a new instance object with the specified options. ### Parameters - **options** (session.InstanceOptions) - Required - Configuration including Title, Path, and Program. ## instance.Start ### Description Starts the instance, creating the worktree and tmux session. ### Parameters - **interactive** (bool) - Required - Whether to start in interactive mode. ## instance.SendPrompt ### Description Sends a prompt to the running instance. ### Parameters - **prompt** (string) - Required - The prompt text to send. ## instance.Attach ### Description Attaches the user to the instance interactively. ## instance.Pause ### Description Pauses the instance, removing the worktree while preserving the branch and tmux session. ## instance.Resume ### Description Resumes a paused instance, recreating the worktree and restoring the tmux session. ## instance.Kill ### Description Terminates the instance and removes all associated resources. ``` -------------------------------- ### Instance Options Schema Source: https://github.com/smtg-ai/claude-squad/blob/main/_autodocs/QUICK-REFERENCE.md Structure for defining individual instance parameters. ```go type InstanceOptions struct { Title string // Instance name (max 32 chars) Path string // Git repo path (relative or absolute) Program string // Program command: "claude", "aider", etc. AutoYes bool // Auto-accept prompts Branch string // Existing branch to start on (empty = new) } ``` -------------------------------- ### Configuration Data Structures Source: https://github.com/smtg-ai/claude-squad/blob/main/_autodocs/QUICK-REFERENCE.md Definitions for global configuration and named program profiles. ```go type Config struct { DefaultProgram string // Program to run: "claude", "aider", etc. AutoYes bool // Automatically accept prompts DaemonPollInterval int // Daemon poll interval in ms (default 1000) BranchPrefix string // Git branch prefix (default: "{username}/") Profiles []Profile // Named program profiles } type Profile struct { Name string // Profile name Program string // Full command } ``` -------------------------------- ### SaveInstances(instances []*Instance) Source: https://github.com/smtg-ai/claude-squad/blob/main/_autodocs/10-storage-and-serialization.md Persists a list of instances to disk, filtering for only started instances and saving them as a JSON array. ```APIDOC ## SaveInstances(instances []*Instance) ### Description Persists all instances to disk. The method filters out unstarted instances, converts them to JSON, and saves the resulting array to `~/.claude-squad/state.json`. ### Parameters - **instances** ([]*Instance) - Required - A slice of instance objects to be persisted. ### Returns - **error** - Returns an error if marshaling or state persistence fails. ### Example ```go instances := m.list.GetInstances() err := storage.SaveInstances(instances) ``` ``` -------------------------------- ### Initialize Tmux Session with Mocks Source: https://github.com/smtg-ai/claude-squad/blob/main/_autodocs/QUICK-REFERENCE.md Use these mocks to instantiate a tmux session for unit testing without requiring a real terminal environment. ```go // Mock executor mockExec := &TestExecutor{ Output: []byte("branch1\nbranch2"), } // Mock PTY factory mockPty := &TestPtyFactory{ PTY: os.Stdout, } // Create with dependencies session := tmux.NewTmuxSessionWithDeps( "test-session", "test-program", mockPty, mockExec, ) ``` -------------------------------- ### Retrieve Branch and Commit Information Source: https://github.com/smtg-ai/claude-squad/blob/main/_autodocs/05-git-operations.md Methods to get the current branch name and the base commit SHA of the worktree. ```go func (g *GitWorktree) GetBranchName() string ``` ```go func (g *GitWorktree) GetBaseCommitSHA() string ``` -------------------------------- ### Multi-Instance Lifecycle Scenario Source: https://github.com/smtg-ai/claude-squad/blob/main/_autodocs/09-daemon-and-background-operations.md A sequence diagram illustrating how multiple TUI windows interact with the daemon lifecycle. ```text Window 1 starts: cs ↓ TUI 1 kills daemon ↓ TUI 1 launches daemon(autoYes=false) ↓ Daemon exits (no autoYes mode) Window 2 starts: cs -y ↓ TUI 2 kills existing daemon ↓ TUI 2 launches daemon(autoYes=true) ↓ Daemon loads all instances, sets autoYes=true ↓ Daemon polling loop running ↓ Both TUI 1 and TUI 2 benefit from daemon auto-yes ↓ User quits TUI 2 ↓ Next TUI start (Window 3) kills daemon ↓ Daemon polling stops ``` -------------------------------- ### Clone the repository Source: https://github.com/smtg-ai/claude-squad/blob/main/CONTRIBUTING.md Initial step to create a local copy of the forked repository. ```bash git clone https://github.com/YOUR-USERNAME/claude-squad.git ``` -------------------------------- ### Set Preview Size Source: https://github.com/smtg-ai/claude-squad/blob/main/_autodocs/04-instance-lifecycle.md Updates tmux pane dimensions for UI rendering. Returns an error if the instance is not started or paused. ```go func (i *Instance) SetPreviewSize(width, height int) error ``` -------------------------------- ### Manage Storage Operations in Go Source: https://github.com/smtg-ai/claude-squad/blob/main/_autodocs/QUICK-REFERENCE.md Use these methods to persist and retrieve instance data from disk. Ensure appState is initialized before creating the storage session. ```go // Create storage storage, err := session.NewStorage(appState) // Save instances to disk err := storage.SaveInstances(instances) // Load instances from disk instances, err := storage.LoadInstances() // Delete specific instance err := storage.DeleteInstance("instance-title") // Delete all instances err := storage.DeleteAllInstances() ``` -------------------------------- ### Keyboard Commands Reference Source: https://github.com/smtg-ai/claude-squad/blob/main/_autodocs/QUICK-REFERENCE.md List of keybindings for navigating and managing instances within the TUI. ```text n Create new instance N (Shift+N) Create instance with prompt and branch selection d Delete instance ↑/j Navigate up ↓/k Navigate down Shift+↑/↓ Scroll in preview/diff Tab Switch between preview/diff/terminal tabs o/↵ (Enter) Attach to instance s Commit and push changes c Pause instance (checkout) r Resume paused instance D (Shift+D) Kill instance (delete) ? Show help q Quit Ctrl+C Cancel current operation Ctrl+D Detach from interactive session ``` -------------------------------- ### View Configuration File Paths for Windows Source: https://github.com/smtg-ai/claude-squad/blob/main/_autodocs/03-config-state.md Displays the standard directory structure for configuration and state files on Windows systems. ```text C:\Users\{username}\.claude-squad\config.json C:\Users\{username}\.claude-squad\state.json C:\Users\{username}\.claude-squad\worktrees\ ``` -------------------------------- ### Control Tmux Sessions in Go Source: https://github.com/smtg-ai/claude-squad/blob/main/_autodocs/QUICK-REFERENCE.md Methods for lifecycle management of tmux sessions, including starting, attaching, and sending input. Use DetachSafely to preserve the session state. ```go // Create session session := tmux.NewTmuxSession("my-task", "claude") // Start session (creates tmux, starts program) err := session.Start("/path/to/repo") // Check if session exists alive := session.DoesSessionExist() // Capture terminal output content, err := session.CapturePaneContent() // Attach interactively done, err := session.Attach() <-done // Send input err := session.SendInput("some text") err := session.TapEnter() // Detach safely (preserves session) err := session.DetachSafely() // Close session (kills it) err := session.Close() ``` -------------------------------- ### Initialize Tmux Session with Dependencies Source: https://github.com/smtg-ai/claude-squad/blob/main/_autodocs/06-tmux-sessions.md Uses dependency injection to provide mock PTY and command executors for unit testing without requiring real tmux or git environments. ```go session := tmux.NewTmuxSessionWithDeps( name, program, mockPtyFactory, // Can return fake PTY mockCmdExecutor, // Can mock git commands ) ``` -------------------------------- ### New Instance Creation with Daemon Source: https://github.com/smtg-ai/claude-squad/blob/main/_autodocs/12-integration-examples.md The process of handling a new instance request while a daemon is already active. ```text User runs: cs -y ↓ Another TUI window starts ↓ Kills existing daemon ↓ Launches new daemon with same config ↓ New daemon loads instances (includes new one) ↓ Polling resumes ↓ Both TUI windows can now see daemon managing instances ``` -------------------------------- ### View Configuration File Paths for macOS and Linux Source: https://github.com/smtg-ai/claude-squad/blob/main/_autodocs/03-config-state.md Displays the standard directory structure for configuration and state files on Unix-based systems. ```text ~/.claude-squad/config.json ~/.claude-squad/state.json ~/.claude-squad/worktrees/ (git worktrees) ``` -------------------------------- ### Validate Git Repository Initialization Source: https://github.com/smtg-ai/claude-squad/blob/main/_autodocs/11-error-handling.md Ensures the application is executed within a valid Git repository during startup. ```go if !git.IsGitRepo(currentDir) { return fmt.Errorf("error: %s must be run from within a git repository", binName) } ``` -------------------------------- ### cs (Root Command) Source: https://github.com/smtg-ai/claude-squad/blob/main/_autodocs/02-cli-commands.md The root command initializes the session, validates the git repository, and launches the Bubble Tea TUI application. ```APIDOC ## cs ### Description Initializes the application, loads configuration, and starts the TUI. It requires the current directory to be a git repository. ### Flags - **--program / -p** (string) - Optional - Program to run in new instances (e.g., aider --model ollama_chat/gemma3:1b) - **--autoyes / -y** (bool) - Optional - Automatically accept prompts for Claude Code & Aider ### Example Usage cs -p "aider --model ollama_chat/gemma3:1b" ``` -------------------------------- ### LoadInstances() Source: https://github.com/smtg-ai/claude-squad/blob/main/_autodocs/10-storage-and-serialization.md Loads and initializes all instances from the persisted JSON file on disk. ```APIDOC ## LoadInstances() ### Description Loads all instances from disk by reading the state file, unmarshaling the JSON array, and converting the data back into initialized instance objects. ### Returns - **[]*Instance** - A slice of fully initialized instances. - **error** - Returns an error if the JSON is invalid, corrupted, or if instance initialization fails. ### Example ```go instances, err := storage.LoadInstances() for _, instance := range instances { // instance is ready to use } ``` ``` -------------------------------- ### Define Config and Profile structs Source: https://github.com/smtg-ai/claude-squad/blob/main/_autodocs/08-types-and-data-structures.md Config holds the application state, while Profile defines specific program configurations. ```go type Config struct { DefaultProgram string `json:"default_program"` AutoYes bool `json:"auto_yes"` DaemonPollInterval int `json:"daemon_poll_interval"` BranchPrefix string `json:"branch_prefix"` Profiles []Profile `json:"profiles,omitempty"` } ``` ```go type Profile struct { Name string `json:"name"` Program string `json:"program"` } ``` -------------------------------- ### Logging Configuration and Usage Source: https://github.com/smtg-ai/claude-squad/blob/main/_autodocs/QUICK-REFERENCE.md Utilize the provided log levels for error, warning, and info reporting. Log files are stored in the user's home directory when running in daemon mode. ```go // Available log levels log.ErrorLog.Printf("error: %v", err) log.WarningLog.Printf("warning: %v", err) log.InfoLog.Printf("info: %v", err) // Log file location (daemon mode) ~/.claude-squad/claude-squad.log ``` -------------------------------- ### Reconstruct Partial Instance Data Source: https://github.com/smtg-ai/claude-squad/blob/main/_autodocs/10-storage-and-serialization.md Illustrates manual reconstruction of an instance from potentially incomplete data fields. ```go instance := &Instance{ Title: data.Title, Path: data.Path, // Might be empty Branch: data.Branch, // ... } ``` -------------------------------- ### Load instances from disk Source: https://github.com/smtg-ai/claude-squad/blob/main/_autodocs/10-storage-and-serialization.md Retrieves and unmarshals instance data from the state file into initialized objects. ```go func (s *Storage) LoadInstances() ([]*Instance, error) ``` ```go instances, err := storage.LoadInstances() for _, instance := range instances { // instance is ready to use } ``` -------------------------------- ### Load Application State Source: https://github.com/smtg-ai/claude-squad/blob/main/_autodocs/03-config-state.md Loads state from disk or initializes a default state if the file is missing or corrupted. ```go func LoadState() *State ``` -------------------------------- ### Recover from Partial Instance Loading Source: https://github.com/smtg-ai/claude-squad/blob/main/_autodocs/11-error-handling.md Iterates through instance data and returns an error if any individual instance fails to initialize. ```go instances := make([]*Instance, len(instancesData)) for i, data := range instancesData { instance, err := FromInstanceData(data) if err != nil { return nil, fmt.Errorf("failed to create instance %s: %w", data.Title, err) } instances[i] = instance } ``` -------------------------------- ### Profile Configuration and Selection Workflow Source: https://github.com/smtg-ai/claude-squad/blob/main/_autodocs/12-integration-examples.md Defines the JSON structure for program profiles and the logic flow for selecting and launching a specific profile instance. ```json ~/.claude-squad/config.json: { "default_program": "claude", "profiles": [ { "name": "claude", "program": "claude" }, { "name": "aider", "program": "aider --model ollama_chat/gemma3:1b" }, { "name": "codex", "program": "codex" } ] } ↓ User presses 'n' to create new instance ↓ stateNew with overlay showing profile picker ↓ Profiles displayed (default first): [1] claude [2] aider [3] codex ↓ User presses right arrow to select "aider" ↓ textInputOverlay.selectedProgram = "aider" ↓ After entering name and pressing Enter: selected.Program = textInputOverlay.GetSelectedProgram() # Program is now "aider --model ollama_chat/gemma3:1b" ↓ instance.Start(true) ↓ Runs: tmux new-session ... aider --model ollama_chat/gemma3:1b ↓ Aider starts instead of Claude ``` -------------------------------- ### Safe and Unsafe Storage Patterns Source: https://github.com/smtg-ai/claude-squad/blob/main/_autodocs/10-storage-and-serialization.md Demonstrates the required single-threaded access pattern for storage operations versus the unsafe concurrent approach. ```go // In TUI Update() method (single-threaded) instances := m.list.GetInstances() err := m.storage.SaveInstances(instances) ``` ```go // Two goroutines calling simultaneously go storage.SaveInstances(instances1) go storage.SaveInstances(instances2) // Can corrupt state file ``` -------------------------------- ### Preview() Source: https://github.com/smtg-ai/claude-squad/blob/main/_autodocs/04-instance-lifecycle.md Captures the current terminal output from the tmux pane. ```APIDOC ### func (i *Instance) Preview() (string, error) Captures current terminal output from tmux pane. Returns rendered content as a string, or an error if capture fails. ``` -------------------------------- ### Save configuration Source: https://github.com/smtg-ai/claude-squad/blob/main/_autodocs/03-config-state.md Persists the configuration object to disk as JSON. ```go func SaveConfig(config *Config) error ``` -------------------------------- ### Render View Source: https://github.com/smtg-ai/claude-squad/blob/main/_autodocs/07-ui-components.md Generates the current UI state as an ANSI string. ```go func (m *home) View() string ``` -------------------------------- ### Resume() Source: https://github.com/smtg-ai/claude-squad/blob/main/_autodocs/04-instance-lifecycle.md Resumes a previously paused instance. ```APIDOC ## Resume() ### Description Resumes a paused instance by recreating the git worktree and restoring or recreating the tmux session. ### Signature `func (i *Instance) Resume() error` ### Returns - `error` - Returns an error if branch checkout validation or worktree setup fails. ``` -------------------------------- ### Prompt Initiation Workflow Logic Source: https://github.com/smtg-ai/claude-squad/blob/main/_autodocs/12-integration-examples.md This pseudo-code represents the state transitions and background command execution triggered when a user initiates a prompt-based instance. ```text User presses Shift+N ↓ case keys.KeyPrompt: instance = NewInstance(...) m.newInstanceFinalizer = m.list.AddInstance(instance) m.state = statePrompt m.promptAfterName = true m.textInputOverlay = overlay.NewTextInputOverlay(...) ↓ Overlay shown: "Enter title" field ↓ User types title and presses Tab ↓ Overlay switches to branch picker Branches loaded from git ↓ User selects branch or creates new one ↓ statePrompt handles key input ↓ case KeyEnter (submit): selectedBranch = m.textInputOverlay.GetSelectedBranch() prompt = m.textInputOverlay.GetValue() if instance not started: instance.SetSelectedBranch(selectedBranch) instance.Prompt = prompt // Save for later instance.SetStatus(Loading) m.newInstanceFinalizer() // Background start with prompt startCmd := func() tea.Msg { err := instance.Start(true) return instanceStartedMsg{...} } ↓ Background: instance.Start(true) Same as Example 1, creates worktree and tmux ↓ case instanceStartedMsg: if instance.Prompt != "": instance.SendPrompt(instance.Prompt) ↓ tmux sends: "Claude, implement feature X" tmux sends: Enter key ↓ Claude receives prompt and starts working instance.Prompt = "" // Clear prompt ↓ UI shows instance running with prompt sent ``` -------------------------------- ### Query Instance State Source: https://github.com/smtg-ai/claude-squad/blob/main/_autodocs/04-instance-lifecycle.md Methods to check the current status of the instance, including tmux and git initialization. ```go func (i *Instance) Started() bool ``` ```go func (i *Instance) Paused() bool ``` ```go func (i *Instance) TmuxAlive() bool ``` -------------------------------- ### Define Key Name Constants Source: https://github.com/smtg-ai/claude-squad/blob/main/_autodocs/08-types-and-data-structures.md String constants representing keyboard or command inputs. ```go KeyHelp = "help" KeyNew = "new" KeyPrompt = "prompt" KeyEnter = "enter" KeyUp = "up" KeyDown = "down" KeyShiftUp = "shift-up" KeyShiftDown = "shift-down" KeyTab = "tab" KeyKill = "kill" KeySubmit = "submit" KeyCheckout = "checkout" KeyMoveUp = "move-up" KeyMoveDown = "move-down" KeyResume = "resume" ``` -------------------------------- ### LoadState() Source: https://github.com/smtg-ai/claude-squad/blob/main/_autodocs/03-config-state.md Loads the application state from disk, creating a default state if the file is missing or corrupted. ```APIDOC ## LoadState() ### Description Loads application state from disk. If the state file does not exist, it creates and saves a default state. ### Signature `func LoadState() *State` ### Returns - ***State** - The loaded or default state object (never nil). ``` -------------------------------- ### Configuration Source: https://github.com/smtg-ai/claude-squad/blob/main/_autodocs/QUICK-REFERENCE.md Methods for loading, accessing, and saving application configuration. ```APIDOC ## config.LoadConfig ### Description Loads the configuration from disk. ## config.GetProgram ### Description Retrieves the configured program name. ## config.GetProfiles ### Description Retrieves the list of available profiles. ## config.SaveConfig ### Description Persists the current configuration to disk. ### Parameters - **config** (Config) - Required - The configuration object to save. ``` -------------------------------- ### Configure Profiles Source: https://github.com/smtg-ai/claude-squad/blob/main/README.md Defines multiple named program configurations in the config.json file. ```json { "default_program": "claude", "profiles": [ { "name": "claude", "program": "claude" }, { "name": "codex", "program": "codex" }, { "name": "aider", "program": "aider --model ollama_chat/gemma3:1b" } ] } ``` -------------------------------- ### Define Application States Source: https://github.com/smtg-ai/claude-squad/blob/main/_autodocs/07-ui-components.md Enumerates the possible states for the application lifecycle. ```go type state int const ( stateDefault state = iota stateNew // Creating new instance statePrompt // Entering prompt/branch stateHelp // Help screen displayed stateConfirm // Confirmation modal ) ``` -------------------------------- ### Define configuration structure Source: https://github.com/smtg-ai/claude-squad/blob/main/_autodocs/03-config-state.md The main configuration struct defining application settings and profiles. ```go type Config struct { DefaultProgram string `json:"default_program"` AutoYes bool `json:"auto_yes"` DaemonPollInterval int `json:"daemon_poll_interval"` BranchPrefix string `json:"branch_prefix"` Profiles []Profile `json:"profiles,omitempty"` } ``` -------------------------------- ### Claude Squad CLI Help Source: https://github.com/smtg-ai/claude-squad/blob/main/README.md Displays the available commands and flags for the cs utility. ```text Usage: cs [flags] cs [command] Available Commands: completion Generate the autocompletion script for the specified shell debug Print debug information like config paths help Help about any command reset Reset all stored instances version Print the version number of claude-squad Flags: -y, --autoyes [experimental] If enabled, all instances will automatically accept prompts for claude code & aider -h, --help help for claude-squad -p, --program string Program to run in new instances (e.g. 'aider --model ollama_chat/gemma3:1b') ``` -------------------------------- ### Root Command Run Function Source: https://github.com/smtg-ai/claude-squad/blob/main/_autodocs/02-cli-commands.md The primary entry point function for the CLI application. ```go func Run(ctx context.Context, program string, autoYes bool) error ``` -------------------------------- ### Apply Branch Prefix Configuration Source: https://github.com/smtg-ai/claude-squad/blob/main/_autodocs/05-git-operations.md Constructs a branch name using the configured prefix from the application settings. ```go cfg := config.LoadConfig() branchName := fmt.Sprintf("%s%s", cfg.BranchPrefix, sessionName) ``` -------------------------------- ### Define Instance serialization methods and structures Source: https://github.com/smtg-ai/claude-squad/blob/main/_autodocs/10-storage-and-serialization.md Methods for converting between runtime instances and serializable data, along with the InstanceData structure definition. ```go func (i *Instance) ToInstanceData() InstanceData ``` ```go type InstanceData struct { Title string `json:"title"` Path string `json:"path"` Branch string `json:"branch"` Status Status `json:"status"` Height int `json:"height"` Width int `json:"width"` CreatedAt time.Time `json:"created_at"` UpdatedAt time.Time `json:"updated_at"` AutoYes bool `json:"auto_yes"` Program string `json:"program"` Worktree GitWorktreeData `json:"worktree"` DiffStats DiffStatsData `json:"diff_stats"` } ``` ```go func FromInstanceData(data InstanceData) (*Instance, error) ``` ```go data := InstanceData{ /* from JSON */ } instance, err := FromInstanceData(data) // instance is ready to use ``` -------------------------------- ### Instance Resume Workflow Source: https://github.com/smtg-ai/claude-squad/blob/main/_autodocs/12-integration-examples.md Triggered by the 'r' key, this process restores the git worktree and reconnects or restarts the tmux session. ```text User presses 'r' on paused instance ↓ case keys.KeyResume: selected.Resume() ↓ Validates branch is not checked out elsewhere ↓ Recreates git worktree instance.gitWorktree.Setup() ↓ Finds existing branch git worktree add {path} {branch} ↓ Worktree restored with branch checked out ↓ Checks if tmux session still exists If yes: Restore() to reconnect If no: Start() to create new session ↓ Sets status = Running ↓ tea.WindowSize() // Refresh UI ↓ Instance resumed, preview shows live output ``` -------------------------------- ### Define application configuration Source: https://github.com/smtg-ai/claude-squad/blob/main/_autodocs/08-types-and-data-structures.md Specifies global settings and available profiles for different programs. ```json { "default_program": "claude", "auto_yes": false, "daemon_poll_interval": 1000, "branch_prefix": "john/", "profiles": [ { "name": "claude", "program": "claude" }, { "name": "aider", "program": "aider --model ollama_chat/gemma3:1b" } ] } ``` -------------------------------- ### Define Instance Structure Source: https://github.com/smtg-ai/claude-squad/blob/main/_autodocs/04-instance-lifecycle.md Represents the configuration and state of a session instance, including repository metadata and tmux integration. ```go type Instance struct { Title string Path string Branch string Status Status Program string Height int Width int CreatedAt time.Time UpdatedAt time.Time AutoYes bool Prompt string // Private fields diffStats *git.DiffStats selectedBranch string started bool tmuxSession *tmux.TmuxSession gitWorktree *git.GitWorktree } ``` -------------------------------- ### Generate default configuration Source: https://github.com/smtg-ai/claude-squad/blob/main/_autodocs/03-config-state.md Creates a new configuration object with default values. ```go func DefaultConfig() *Config ```