-
Notifications
You must be signed in to change notification settings - Fork 54
Expand file tree
/
Copy pathcli.go
More file actions
5580 lines (4791 loc) · 160 KB
/
Copy pathcli.go
File metadata and controls
5580 lines (4791 loc) · 160 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package cli
import (
"bufio"
"context"
"encoding/json"
"fmt"
"os"
"os/exec"
"path/filepath"
"runtime/debug"
"strconv"
"strings"
"syscall"
"time"
"github.com/dlorenc/multiclaude/internal/agents"
"github.com/dlorenc/multiclaude/internal/bugreport"
"github.com/dlorenc/multiclaude/internal/daemon"
"github.com/dlorenc/multiclaude/internal/errors"
"github.com/dlorenc/multiclaude/internal/fork"
"github.com/dlorenc/multiclaude/internal/format"
"github.com/dlorenc/multiclaude/internal/hooks"
"github.com/dlorenc/multiclaude/internal/messages"
"github.com/dlorenc/multiclaude/internal/names"
"github.com/dlorenc/multiclaude/internal/prompts"
"github.com/dlorenc/multiclaude/internal/socket"
"github.com/dlorenc/multiclaude/internal/state"
"github.com/dlorenc/multiclaude/internal/templates"
"github.com/dlorenc/multiclaude/internal/worktree"
"github.com/dlorenc/multiclaude/pkg/claude"
"github.com/dlorenc/multiclaude/pkg/config"
"github.com/dlorenc/multiclaude/pkg/tmux"
)
// Version is the current version of multiclaude (set at build time via ldflags)
var Version = "dev"
// GetVersion returns the semver-formatted version string
func GetVersion() string {
if Version != "dev" {
return Version
}
// Try to get VCS info embedded by Go at build time
info, ok := debug.ReadBuildInfo()
if !ok {
return "0.0.0-dev"
}
var commit string
for _, setting := range info.Settings {
if setting.Key == "vcs.revision" {
commit = setting.Value
if len(commit) > 7 {
commit = commit[:7] // Short commit hash
}
break
}
}
if commit == "" {
return "0.0.0-dev"
}
return fmt.Sprintf("0.0.0+%s-dev", commit)
}
// IsDevVersion returns true if running a development build (not set via ldflags)
func IsDevVersion() bool {
return Version == "dev"
}
// Command represents a CLI command
type Command struct {
Name string
Description string
Usage string
Run func(args []string) error
Subcommands map[string]*Command
}
// CLI manages the command-line interface
type CLI struct {
rootCmd *Command
paths *config.Paths
documentation string // Auto-generated CLI documentation for prompts
}
// New creates a new CLI
func New() (*CLI, error) {
paths, err := config.DefaultPaths()
if err != nil {
return nil, err
}
cli := &CLI{
paths: paths,
rootCmd: &Command{
Name: "multiclaude",
Description: "repo-centric orchestrator for Claude Code",
Subcommands: make(map[string]*Command),
},
}
cli.registerCommands()
// Generate documentation after commands are registered
cli.documentation = cli.GenerateDocumentation()
return cli, nil
}
// NewWithPaths creates a CLI with custom paths (for testing)
func NewWithPaths(paths *config.Paths) *CLI {
cli := &CLI{
paths: paths,
rootCmd: &Command{
Name: "multiclaude",
Description: "repo-centric orchestrator for Claude Code",
Subcommands: make(map[string]*Command),
},
}
cli.registerCommands()
// Generate documentation after commands are registered
cli.documentation = cli.GenerateDocumentation()
return cli
}
// getClaudeBinary resolves the claude binary path
func (c *CLI) getClaudeBinary() (string, error) {
binaryPath, err := exec.LookPath("claude")
if err != nil {
return "", errors.ClaudeNotFound(err)
}
return binaryPath, nil
}
// loadState loads the state file, wrapping errors with context
func (c *CLI) loadState() (*state.State, error) {
st, err := state.Load(c.paths.StateFile)
if err != nil {
return nil, fmt.Errorf("failed to load state: %w", err)
}
return st, nil
}
// sendDaemonRequest sends a request to the daemon and handles common error cases.
// It returns the response if successful, or an error if communication fails or the daemon returns an error.
func (c *CLI) sendDaemonRequest(command string, args map[string]interface{}) (*socket.Response, error) {
client := socket.NewClient(c.paths.DaemonSock)
resp, err := client.Send(socket.Request{
Command: command,
Args: args,
})
if err != nil {
return nil, errors.DaemonCommunicationFailed(command, err)
}
if !resp.Success {
return nil, fmt.Errorf("%s failed: %s", command, resp.Error)
}
return resp, nil
}
// removeDirectoryIfExists removes a directory and prints status messages.
// It prints a warning if removal fails, or a success message if it succeeds.
// If the directory doesn't exist, it does nothing.
func removeDirectoryIfExists(path, description string) {
if _, err := os.Stat(path); err == nil {
if err := os.RemoveAll(path); err != nil {
fmt.Printf(" Warning: failed to remove %s: %v\n", description, err)
} else {
fmt.Printf(" Removed %s\n", path)
}
}
}
// tmuxSanitizer replaces problematic characters with hyphens for tmux session names.
// tmux has issues with dots, colons, spaces, and forward slashes in session names.
var tmuxSanitizer = strings.NewReplacer(
".", "-",
":", "-",
" ", "-",
"/", "-",
)
// sanitizeTmuxSessionName creates a tmux-safe session name from a repo name.
// tmux has issues with certain characters like dots, so we replace them.
func sanitizeTmuxSessionName(repoName string) string {
// Strip control characters (ASCII 0-31) for safety
sanitized := strings.Map(func(r rune) rune {
if r < 32 {
return -1 // drop the character
}
return r
}, repoName)
return fmt.Sprintf("mc-%s", tmuxSanitizer.Replace(sanitized))
}
// Execute executes the CLI with the given arguments
func (c *CLI) Execute(args []string) error {
if len(args) == 0 {
return c.showHelp()
}
// Check for --version or -v flag at top level
if args[0] == "--version" || args[0] == "-v" {
return c.showVersion()
}
return c.executeCommand(c.rootCmd, args)
}
// showVersion displays the version information
func (c *CLI) showVersion() error {
fmt.Printf("multiclaude %s\n", GetVersion())
return nil
}
// versionCommand displays version information with optional JSON output
func (c *CLI) versionCommand(args []string) error {
flags, _ := ParseFlags(args)
outputJSON := flags["json"] == "true"
version := GetVersion()
if outputJSON {
output := map[string]interface{}{
"version": version,
"isDev": IsDevVersion(),
"rawVersion": Version,
}
encoder := json.NewEncoder(os.Stdout)
encoder.SetIndent("", " ")
return encoder.Encode(output)
}
fmt.Printf("multiclaude %s\n", version)
return nil
}
// executeCommand recursively executes commands and subcommands
func (c *CLI) executeCommand(cmd *Command, args []string) error {
if len(args) == 0 {
if cmd.Run != nil {
return cmd.Run([]string{})
}
return c.showCommandHelp(cmd)
}
// Check for --help or -h flag
if args[0] == "--help" || args[0] == "-h" {
return c.showCommandHelp(cmd)
}
// Check for subcommands
if subcmd, exists := cmd.Subcommands[args[0]]; exists {
return c.executeCommand(subcmd, args[1:])
}
// No subcommand found, run this command with args
if cmd.Run != nil {
return cmd.Run(args)
}
return errors.UnknownCommand(args[0])
}
// showHelp shows the main help message
func (c *CLI) showHelp() error {
fmt.Println("multiclaude - repo-centric orchestrator for Claude Code")
fmt.Println()
fmt.Println("Usage: multiclaude <command> [options]")
fmt.Println()
fmt.Println("Commands:")
for name, cmd := range c.rootCmd.Subcommands {
fmt.Printf(" %-15s %s\n", name, cmd.Description)
}
fmt.Println()
fmt.Println("Use 'multiclaude <command> --help' for more information about a command.")
return nil
}
// showCommandHelp shows help for a specific command
func (c *CLI) showCommandHelp(cmd *Command) error {
fmt.Printf("%s - %s\n", cmd.Name, cmd.Description)
fmt.Println()
if cmd.Usage != "" {
fmt.Printf("Usage: %s\n", cmd.Usage)
fmt.Println()
}
if len(cmd.Subcommands) > 0 {
fmt.Println("Subcommands:")
for name, subcmd := range cmd.Subcommands {
// Skip internal commands (prefixed with _)
if strings.HasPrefix(name, "_") {
continue
}
fmt.Printf(" %-15s %s\n", name, subcmd.Description)
}
fmt.Println()
}
return nil
}
// registerCommands registers all CLI commands
func (c *CLI) registerCommands() {
// Daemon commands
// Root-level 'start' is kept as alias for backward compatibility
c.rootCmd.Subcommands["start"] = &Command{
Name: "start",
Description: "Start the daemon (alias for 'daemon start')",
Usage: "multiclaude start",
Run: c.startDaemon,
}
daemonCmd := &Command{
Name: "daemon",
Description: "Manage the multiclaude daemon",
Subcommands: make(map[string]*Command),
}
daemonCmd.Subcommands["start"] = &Command{
Name: "start",
Description: "Start the daemon",
Usage: "multiclaude daemon start",
Run: c.startDaemon,
}
daemonCmd.Subcommands["stop"] = &Command{
Name: "stop",
Description: "Stop the daemon",
Usage: "multiclaude daemon stop",
Run: c.stopDaemon,
}
daemonCmd.Subcommands["status"] = &Command{
Name: "status",
Description: "Show daemon status",
Usage: "multiclaude daemon status",
Run: c.daemonStatus,
}
daemonCmd.Subcommands["logs"] = &Command{
Name: "logs",
Description: "View daemon logs",
Usage: "multiclaude daemon logs [-f|--follow] [-n <lines>]",
Run: c.daemonLogs,
}
daemonCmd.Subcommands["_run"] = &Command{
Name: "_run",
Description: "Internal: run daemon in foreground (used by daemon start)",
Run: c.runDaemon,
}
c.rootCmd.Subcommands["daemon"] = daemonCmd
// Stop-all command (convenience for stopping everything)
c.rootCmd.Subcommands["stop-all"] = &Command{
Name: "stop-all",
Description: "Stop daemon and kill all multiclaude tmux sessions",
Usage: "multiclaude stop-all [--clean] [--yes]",
Run: c.stopAll,
}
// Repository commands (repo subcommand)
repoCmd := &Command{
Name: "repo",
Description: "Manage repositories",
Subcommands: make(map[string]*Command),
}
repoCmd.Subcommands["init"] = &Command{
Name: "init",
Description: "Initialize a repository",
Usage: "multiclaude repo init <github-url> [name] [--no-merge-queue] [--mq-track=all|author|assigned]",
Run: c.initRepo,
}
repoCmd.Subcommands["list"] = &Command{
Name: "list",
Description: "List tracked repositories",
Usage: "multiclaude repo list",
Run: c.listRepos,
}
repoCmd.Subcommands["rm"] = &Command{
Name: "rm",
Description: "Remove a tracked repository",
Usage: "multiclaude repo rm <name>",
Run: c.removeRepo,
}
repoCmd.Subcommands["use"] = &Command{
Name: "use",
Description: "Set the default repository",
Usage: "multiclaude repo use <name>",
Run: c.setCurrentRepo,
}
repoCmd.Subcommands["current"] = &Command{
Name: "current",
Description: "Show the default repository",
Usage: "multiclaude repo current",
Run: c.getCurrentRepo,
}
repoCmd.Subcommands["unset"] = &Command{
Name: "unset",
Description: "Clear the default repository",
Usage: "multiclaude repo unset",
Run: c.clearCurrentRepo,
}
repoCmd.Subcommands["history"] = &Command{
Name: "history",
Description: "Show task history for a repository",
Usage: "multiclaude repo history [--repo <repo>] [-n <count>] [--status <status>] [--search <query>] [--full]",
Run: c.showHistory,
}
c.rootCmd.Subcommands["repo"] = repoCmd
// Backward compatibility aliases for root-level repo commands
c.rootCmd.Subcommands["init"] = repoCmd.Subcommands["init"]
c.rootCmd.Subcommands["list"] = repoCmd.Subcommands["list"]
c.rootCmd.Subcommands["history"] = repoCmd.Subcommands["history"]
// Worker commands
workerCmd := &Command{
Name: "worker",
Description: "Manage worker agents",
Usage: "multiclaude worker [<task>] [--repo <repo>] [--branch <branch>] [--push-to <branch>]",
Subcommands: make(map[string]*Command),
}
workerCmd.Run = c.createWorker // Default action for 'worker' command (same as 'worker create')
workerCmd.Subcommands["create"] = &Command{
Name: "create",
Description: "Create a new worker agent",
Usage: "multiclaude worker create <task> [--repo <repo>] [--branch <branch>] [--push-to <branch>]",
Run: c.createWorker,
}
workerCmd.Subcommands["list"] = &Command{
Name: "list",
Description: "List active workers",
Usage: "multiclaude worker list [--repo <repo>]",
Run: c.listWorkers,
}
workerCmd.Subcommands["rm"] = &Command{
Name: "rm",
Description: "Remove a worker",
Usage: "multiclaude worker rm <worker-name>",
Run: c.removeWorker,
}
c.rootCmd.Subcommands["worker"] = workerCmd
// 'work' is an alias for 'worker' (backward compatibility)
c.rootCmd.Subcommands["work"] = workerCmd
// Workspace commands
workspaceCmd := &Command{
Name: "workspace",
Description: "Manage workspaces",
Usage: "multiclaude workspace [<name>]",
Subcommands: make(map[string]*Command),
}
workspaceCmd.Run = c.workspaceDefault // Default action: list or connect
workspaceCmd.Subcommands["add"] = &Command{
Name: "add",
Description: "Add a new workspace",
Usage: "multiclaude workspace add <name> [--branch <branch>]",
Run: c.addWorkspace,
}
workspaceCmd.Subcommands["rm"] = &Command{
Name: "rm",
Description: "Remove a workspace",
Usage: "multiclaude workspace rm <name>",
Run: c.removeWorkspace,
}
workspaceCmd.Subcommands["list"] = &Command{
Name: "list",
Description: "List workspaces",
Usage: "multiclaude workspace list",
Run: c.listWorkspaces,
}
workspaceCmd.Subcommands["connect"] = &Command{
Name: "connect",
Description: "Connect to a workspace",
Usage: "multiclaude workspace connect <name>",
Run: c.connectWorkspace,
}
c.rootCmd.Subcommands["workspace"] = workspaceCmd
// Agent commands (run from within Claude)
agentCmd := &Command{
Name: "agent",
Description: "Agent communication commands",
Subcommands: make(map[string]*Command),
}
// Legacy message commands (aliases for backward compatibility)
// Prefer: multiclaude message send/list/read/ack
agentCmd.Subcommands["send-message"] = &Command{
Name: "send-message",
Description: "Send a message to another agent (alias for 'message send')",
Usage: "multiclaude agent send-message <recipient> <message>",
Run: c.sendMessage,
}
agentCmd.Subcommands["list-messages"] = &Command{
Name: "list-messages",
Description: "List pending messages (alias for 'message list')",
Usage: "multiclaude agent list-messages",
Run: c.listMessages,
}
agentCmd.Subcommands["read-message"] = &Command{
Name: "read-message",
Description: "Read a specific message (alias for 'message read')",
Usage: "multiclaude agent read-message <message-id>",
Run: c.readMessage,
}
agentCmd.Subcommands["ack-message"] = &Command{
Name: "ack-message",
Description: "Acknowledge a message (alias for 'message ack')",
Usage: "multiclaude agent ack-message <message-id>",
Run: c.ackMessage,
}
agentCmd.Subcommands["complete"] = &Command{
Name: "complete",
Description: "Signal worker completion",
Usage: "multiclaude agent complete [--summary <text>] [--failure <reason>]",
Run: c.completeWorker,
}
agentCmd.Subcommands["restart"] = &Command{
Name: "restart",
Description: "Restart a crashed or exited agent",
Usage: "multiclaude agent restart <name> [--repo <repo>] [--force]",
Run: c.restartAgentCmd,
}
agentCmd.Subcommands["attach"] = &Command{
Name: "attach",
Description: "Attach to an agent's tmux window",
Usage: "multiclaude agent attach <agent-name> [--read-only]",
Run: c.attachAgent,
}
c.rootCmd.Subcommands["agent"] = agentCmd
// Message commands (new noun group for message operations)
// These are the preferred commands; agent *-message commands are kept as aliases
messageCmd := &Command{
Name: "message",
Description: "Manage inter-agent messages",
Subcommands: make(map[string]*Command),
}
messageCmd.Subcommands["send"] = &Command{
Name: "send",
Description: "Send a message to another agent",
Usage: "multiclaude message send <recipient> <message>",
Run: c.sendMessage,
}
messageCmd.Subcommands["list"] = &Command{
Name: "list",
Description: "List pending messages",
Usage: "multiclaude message list",
Run: c.listMessages,
}
messageCmd.Subcommands["read"] = &Command{
Name: "read",
Description: "Read a specific message",
Usage: "multiclaude message read <message-id>",
Run: c.readMessage,
}
messageCmd.Subcommands["ack"] = &Command{
Name: "ack",
Description: "Acknowledge a message",
Usage: "multiclaude message ack <message-id>",
Run: c.ackMessage,
}
c.rootCmd.Subcommands["message"] = messageCmd
// 'attach' is an alias for 'agent attach' (backward compatibility)
c.rootCmd.Subcommands["attach"] = agentCmd.Subcommands["attach"]
// Maintenance commands
c.rootCmd.Subcommands["cleanup"] = &Command{
Name: "cleanup",
Description: "Clean up orphaned resources",
Usage: "multiclaude cleanup [--dry-run] [--verbose] [--merged]",
Run: c.cleanup,
}
c.rootCmd.Subcommands["repair"] = &Command{
Name: "repair",
Description: "Repair state after crash",
Usage: "multiclaude repair [--verbose]",
Run: c.repair,
}
// Claude restart command - for resuming Claude after exit
c.rootCmd.Subcommands["claude"] = &Command{
Name: "claude",
Description: "Restart Claude in current agent context",
Usage: "multiclaude claude",
Run: c.restartClaude,
}
// Debug command
c.rootCmd.Subcommands["docs"] = &Command{
Name: "docs",
Description: "Show generated CLI documentation",
Usage: "multiclaude docs",
Run: c.showDocs,
}
// Review command
c.rootCmd.Subcommands["review"] = &Command{
Name: "review",
Description: "Spawn a review agent for a PR",
Usage: "multiclaude review <pr-url>",
Run: c.reviewPR,
}
// Logs commands
logsCmd := &Command{
Name: "logs",
Description: "View and manage agent output logs",
Usage: "multiclaude logs [<agent-name>] [-f|--follow]",
Subcommands: make(map[string]*Command),
}
logsCmd.Run = c.viewLogs // Default action: view logs for an agent
logsCmd.Subcommands["list"] = &Command{
Name: "list",
Description: "List log files",
Usage: "multiclaude logs list [--repo <repo>]",
Run: c.listLogs,
}
logsCmd.Subcommands["search"] = &Command{
Name: "search",
Description: "Search across logs",
Usage: "multiclaude logs search <pattern> [--repo <repo>]",
Run: c.searchLogs,
}
logsCmd.Subcommands["clean"] = &Command{
Name: "clean",
Description: "Remove old logs",
Usage: "multiclaude logs clean --older-than <duration>",
Run: c.cleanLogs,
}
c.rootCmd.Subcommands["logs"] = logsCmd
// Config command
c.rootCmd.Subcommands["config"] = &Command{
Name: "config",
Description: "View or modify repository configuration",
Usage: "multiclaude config [repo] [--mq-enabled=true|false] [--mq-track=all|author|assigned] [--ps-enabled=true|false] [--ps-track=all|author|assigned]",
Run: c.configRepo,
}
// Bug report command
c.rootCmd.Subcommands["bug"] = &Command{
Name: "bug",
Description: "Generate a diagnostic bug report",
Usage: "multiclaude bug [--output <file>] [--verbose] [description]",
Run: c.bugReport,
}
// Version command
c.rootCmd.Subcommands["version"] = &Command{
Name: "version",
Description: "Show version information",
Usage: "multiclaude version [--json]",
Run: c.versionCommand,
}
// Agents command - for managing agent definitions
agentsCmd := &Command{
Name: "agents",
Description: "Manage agent definitions",
Subcommands: make(map[string]*Command),
}
agentsCmd.Subcommands["list"] = &Command{
Name: "list",
Description: "List available agent definitions for a repository",
Usage: "multiclaude agents list [--repo <repo>]",
Run: c.listAgentDefinitions,
}
agentsCmd.Subcommands["spawn"] = &Command{
Name: "spawn",
Description: "Spawn an agent from a prompt file",
Usage: "multiclaude agents spawn --name <name> --class <class> --prompt-file <file> [--repo <repo>] [--task <task>]",
Run: c.spawnAgentFromFile,
}
agentsCmd.Subcommands["reset"] = &Command{
Name: "reset",
Description: "Reset agent definitions to defaults (re-copy from templates)",
Usage: "multiclaude agents reset [--repo <repo>]",
Run: c.resetAgentDefinitions,
}
c.rootCmd.Subcommands["agents"] = agentsCmd
}
// Daemon command implementations
func (c *CLI) startDaemon(args []string) error {
return daemon.RunDetached()
}
func (c *CLI) runDaemon(args []string) error {
return daemon.Run()
}
func (c *CLI) stopDaemon(args []string) error {
_, err := c.sendDaemonRequest("stop", nil)
if err != nil {
return err
}
fmt.Println("Daemon stopped successfully")
return nil
}
func (c *CLI) daemonStatus(args []string) error {
// Check PID file first
pidFile := daemon.NewPIDFile(c.paths.DaemonPID)
running, pid, err := pidFile.IsRunning()
if err != nil {
return fmt.Errorf("failed to check daemon status: %w", err)
}
if !running {
fmt.Println("Daemon is not running")
return nil
}
// Try to connect to daemon
client := socket.NewClient(c.paths.DaemonSock)
resp, err := client.Send(socket.Request{
Command: "status",
})
if err != nil {
fmt.Printf("Daemon PID file exists (PID: %d) but daemon is not responding\n", pid)
return nil
}
if !resp.Success {
return fmt.Errorf("status check failed: %s", resp.Error)
}
// Pretty print status
fmt.Println("Daemon Status:")
if statusMap, ok := resp.Data.(map[string]interface{}); ok {
fmt.Printf(" Running: %v\n", statusMap["running"])
fmt.Printf(" PID: %v\n", statusMap["pid"])
fmt.Printf(" Repos: %v\n", statusMap["repos"])
fmt.Printf(" Agents: %v\n", statusMap["agents"])
fmt.Printf(" Socket: %v\n", statusMap["socket_path"])
} else {
// Fallback: print as JSON
jsonData, _ := json.MarshalIndent(resp.Data, " ", " ")
fmt.Println(string(jsonData))
}
return nil
}
func (c *CLI) daemonLogs(args []string) error {
flags, _ := ParseFlags(args)
// Check if we should follow logs
follow := flags["follow"] == "true" || flags["f"] == "true"
if follow {
// Use tail -f to follow logs
cmd := exec.Command("tail", "-f", c.paths.DaemonLog)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
return cmd.Run()
}
// Show last 50 lines
lines := "50"
if n, ok := flags["n"]; ok {
lines = n
}
cmd := exec.Command("tail", "-n", lines, c.paths.DaemonLog)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
return cmd.Run()
}
func (c *CLI) stopAll(args []string) error {
flags, _ := ParseFlags(args)
clean := flags["clean"] == "true"
skipConfirm := flags["yes"] == "true"
// Get list of repos (try daemon first, then state file)
var repos []string
client := socket.NewClient(c.paths.DaemonSock)
resp, err := client.Send(socket.Request{Command: "list_repos"})
if err == nil && resp.Success {
// Daemon is running, get repos from it
if repoList, ok := resp.Data.([]interface{}); ok {
for _, repo := range repoList {
if repoStr, ok := repo.(string); ok {
repos = append(repos, repoStr)
}
}
}
} else {
// Daemon not running, try to load from state file
st, err := state.Load(c.paths.StateFile)
if err == nil {
repos = st.ListRepos()
}
}
// If --clean is specified, require confirmation
if clean {
fmt.Println("WARNING: This will permanently delete:")
fmt.Println(" - All worktrees (~/.multiclaude/wts/)")
fmt.Println(" - All agent state (state.json agents section)")
fmt.Println(" - All message queues (~/.multiclaude/messages/)")
fmt.Println(" - All output logs (~/.multiclaude/output/)")
fmt.Println(" - All agent configs (~/.multiclaude/claude-config/)")
fmt.Println(" - All prompts (~/.multiclaude/prompts/)")
fmt.Println(" - Local branches (work/*, multiclaude/*)")
fmt.Println()
fmt.Println("The following will be PRESERVED:")
fmt.Println(" - Cloned repositories (~/.multiclaude/repos/)")
fmt.Println(" - Git credentials")
fmt.Println()
if !skipConfirm {
fmt.Print("Type 'NUKE' to confirm: ")
reader := bufio.NewReader(os.Stdin)
input, err := reader.ReadString('\n')
if err != nil {
return fmt.Errorf("failed to read input: %w", err)
}
input = strings.TrimSpace(input)
if input != "NUKE" {
fmt.Println("Aborted.")
return nil
}
fmt.Println()
}
}
fmt.Println("Stopping all multiclaude sessions...")
// Kill all multiclaude tmux sessions
tmuxClient := tmux.NewClient()
if tmuxClient.IsTmuxAvailable() {
for _, repo := range repos {
sessionName := fmt.Sprintf("mc-%s", repo)
exists, err := tmuxClient.HasSession(context.Background(), sessionName)
if err == nil && exists {
fmt.Printf("Killing tmux session: %s\n", sessionName)
if err := tmuxClient.KillSession(context.Background(), sessionName); err != nil {
fmt.Printf("Warning: failed to kill session %s: %v\n", sessionName, err)
}
}
}
// Also check for any mc-* sessions we might have missed
sessions, err := tmuxClient.ListSessions(context.Background())
if err == nil {
for _, session := range sessions {
if strings.HasPrefix(session, "mc-") {
exists := false
for _, repo := range repos {
if fmt.Sprintf("mc-%s", repo) == session {
exists = true
break
}
}
if !exists {
fmt.Printf("Killing orphaned tmux session: %s\n", session)
if err := tmuxClient.KillSession(context.Background(), session); err != nil {
fmt.Printf("Warning: failed to kill session %s: %v\n", session, err)
}
}
}
}
}
}
// Stop the daemon
fmt.Println("Stopping daemon...")
resp, err = client.Send(socket.Request{Command: "stop"})
if err != nil {
fmt.Printf("Daemon already stopped or not responding\n")
} else if resp.Success {
fmt.Println("Daemon stopped")
}
// Full cleanup if --clean is specified
if clean {
// Remove worktrees directory
fmt.Println("\nRemoving worktrees...")
removeDirectoryIfExists(c.paths.WorktreesDir, "worktrees")
// Remove messages directory
fmt.Println("Removing messages...")
removeDirectoryIfExists(c.paths.MessagesDir, "messages")
// Remove output logs
fmt.Println("Removing output logs...")
removeDirectoryIfExists(c.paths.OutputDir, "output logs")
// Remove claude config (per-agent settings)
fmt.Println("Removing agent configs...")
removeDirectoryIfExists(c.paths.ClaudeConfigDir, "agent configs")
// Remove prompts directory
fmt.Println("Removing prompts...")
promptsDir := filepath.Join(c.paths.Root, "prompts")
removeDirectoryIfExists(promptsDir, "prompts")
// Clean up local branches in each repository
fmt.Println("\nCleaning up local branches...")
for _, repoName := range repos {
repoPath := c.paths.RepoDir(repoName)
if _, err := os.Stat(repoPath); os.IsNotExist(err) {
continue
}
fmt.Printf(" Repository: %s\n", repoName)
// Delete work/* and multiclaude/* branches
wt := worktree.NewManager(repoPath)
for _, prefix := range []string{"work/", "multiclaude/"} {
branches, err := c.listBranchesWithPrefix(repoPath, prefix)
if err != nil {
fmt.Printf(" Warning: failed to list %s branches: %v\n", prefix, err)
continue
}
for _, branch := range branches {
// First remove any worktree associated with this branch
if err := wt.Remove(branch, true); err != nil {
// Ignore errors - worktree may not exist
}
// Delete the branch
if err := c.deleteBranch(repoPath, branch); err != nil {
fmt.Printf(" Warning: failed to delete branch %s: %v\n", branch, err)
} else {
fmt.Printf(" Deleted branch: %s\n", branch)
}
}
}
// Prune worktrees
if err := wt.Prune(); err != nil {
fmt.Printf(" Warning: failed to prune worktrees: %v\n", err)
}
}
// Clear agent state but preserve repository entries
fmt.Println("\nClearing agent state...")
st, err := state.Load(c.paths.StateFile)