vex-cli 0.7.13

AI-native version control workflow engine
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
mod agent;
mod daemon_client;
mod doctor;
mod github;
mod project;
mod prompts;
mod shell;
mod workstream;

use clap::{CommandFactory, Parser, Subcommand};
use clap_complete::Shell;
use serde_json::json;
use vex_config::ConnectionEntry;

#[derive(Parser)]
#[command(
    name = "vex",
    about = "Parallel workstream manager for software developers"
)]
#[command(version)]
struct Cli {
    /// Target a specific host (required for mutations when multiple hosts are connected)
    #[arg(long, global = true)]
    host: Option<String>,

    #[command(subcommand)]
    command: Commands,
}

#[derive(Subcommand)]
enum Commands {
    /// Run health checks on your system
    Doctor,

    /// Manage projects
    Project {
        #[command(subcommand)]
        action: ProjectAction,
    },

    /// Manage workstreams
    Ws {
        #[command(subcommand)]
        action: WsAction,
    },

    /// Open a shell in a workstream
    Shell {
        #[command(subcommand)]
        action: ShellAction,
    },

    /// Manage AI agents
    Agent {
        #[command(subcommand)]
        action: AgentAction,
    },

    /// Manage the Vex daemon
    Daemon {
        #[command(subcommand)]
        action: DaemonAction,
    },

    /// Manage hub connections
    Hub {
        #[command(subcommand)]
        action: HubAction,
    },

    /// GitHub integration
    Gh {
        #[command(subcommand)]
        action: GhAction,
    },

    /// Manage saved prompts
    Prompt {
        #[command(subcommand)]
        action: PromptAction,
    },

    /// Generate shell completions
    Completions {
        /// Shell to generate completions for
        shell: Shell,
    },
}

#[derive(Subcommand)]
enum ProjectAction {
    /// Register a git repository as a project
    Add {
        /// Path to the git repository
        path: String,
    },
    /// List registered projects
    List,
    /// Remove a project registration
    Remove {
        /// Project name
        name: String,
    },
}

#[derive(Subcommand)]
enum WsAction {
    /// Create a new workstream
    Create {
        /// Project name
        project: String,
        /// Workstream name
        name: Option<String>,
        /// Git branch name (defaults to task/<name>)
        #[arg(long)]
        branch: Option<String>,
        /// Create from a GitHub PR URL
        #[arg(long)]
        pr: Option<String>,
    },
    /// List workstreams for a project
    List {
        /// Project name
        project: String,
    },
    /// Rename a workstream (updates branch if it follows task/<name> convention)
    Rename {
        /// Project name
        project: String,
        /// Current workstream name
        name: String,
        /// New workstream name
        new_name: String,
    },
    /// Delete a workstream (removes worktree and metadata)
    Delete {
        /// Project name
        project: String,
        /// Workstream name
        name: String,
    },
    /// Get or set markdown notes for a workstream
    Notes {
        #[command(subcommand)]
        action: WsNotesAction,
    },
}

#[derive(Subcommand)]
enum WsNotesAction {
    /// Show the notes for a workstream
    Get {
        /// Project name
        project: String,
        /// Workstream name
        ws: String,
    },
    /// Set the notes for a workstream (reads from stdin if content is "-")
    Set {
        /// Project name
        project: String,
        /// Workstream name
        ws: String,
        /// Markdown content (use "-" to read from stdin)
        content: String,
    },
}

#[derive(Subcommand)]
enum ShellAction {
    /// Open a new interactive shell (in a workstream worktree, or project root)
    Open {
        /// Project name
        project: String,
        /// Workstream name (omit to use project root)
        ws: Option<String>,
    },
    /// Attach to an existing shell
    Attach {
        /// Shell ID (e.g. shell-1)
        shell_id: String,
    },
    /// List active shells
    List,
    /// Kill a shell
    Kill {
        /// Shell ID (e.g. shell-1)
        shell_id: String,
    },
}

#[derive(Subcommand)]
enum AgentAction {
    /// Spawn an AI agent (in a workstream, or project root)
    Spawn {
        /// Project name
        project: String,
        /// Workstream name (omit to use project root)
        ws: Option<String>,
        /// Agent type (claude or codex)
        #[arg(long, value_name = "TYPE")]
        r#type: Option<String>,
    },
    /// Send a prompt to a running agent
    Prompt {
        /// Agent ID
        agent_id: String,
        /// Prompt text
        text: String,
    },
    /// List agents (optionally filter by project and workstream)
    List {
        /// Project name
        project: Option<String>,
        /// Workstream name
        ws: Option<String>,
    },
    /// Kill an agent and its underlying shell
    Kill {
        /// Agent ID
        agent_id: String,
    },
    /// Attach to an agent's shell (view/interact with agent terminal)
    AttachShell {
        /// Agent ID
        agent_id: String,
    },
    /// Show agent conversation (parsed JSONL session)
    Conversation {
        /// Agent ID
        agent_id: String,
        /// Keep watching for new messages
        #[arg(long)]
        watch: bool,
        /// Show inner work (thinking, tool calls, tool results)
        #[arg(long, short)]
        verbose: bool,
    },
    /// Show detailed agent status
    Status {
        /// Agent ID
        agent_id: String,
    },
}

#[derive(Subcommand)]
enum DaemonAction {
    /// Start the daemon
    Start {
        /// Run in foreground (don't daemonize)
        #[arg(long)]
        foreground: bool,
    },
    /// Stop the daemon
    Stop,
    /// Tail daemon logs
    Logs,
}

#[derive(Subcommand)]
enum HubAction {
    /// Register a daemon connection (e.g. local, 192.168.0.5, ssh-host)
    Connect {
        /// Daemon host (e.g. local, 192.168.0.5, ssh-host)
        host: String,
        /// Daemon port
        #[arg(long, default_value = "9800")]
        port: u16,
    },
    /// Start the hub
    Start {
        /// Run in foreground (don't daemonize)
        #[arg(long)]
        foreground: bool,
    },
    /// Stop the hub
    Stop,
    /// Tail hub logs
    Logs,
}

#[derive(Subcommand)]
enum GhAction {
    /// Auto-detect and link a PR for a workstream's branch
    DetectPr {
        /// Project name
        project: String,
        /// Workstream name
        #[arg(long)]
        ws: String,
    },
    /// Manually link a PR by number
    LinkPr {
        /// Project name
        project: String,
        /// Workstream name
        #[arg(long)]
        ws: String,
        /// PR number
        pr_number: u64,
    },
    /// Unlink the PR from a workstream
    UnlinkPr {
        /// Project name
        project: String,
        /// Workstream name
        #[arg(long)]
        ws: String,
    },
    /// Link a GitHub issue to a workstream
    LinkIssue {
        /// Project name
        project: String,
        /// Workstream name
        #[arg(long)]
        ws: String,
        /// Issue number
        issue_number: u64,
    },
    /// Unlink a GitHub issue from a workstream
    UnlinkIssue {
        /// Project name
        project: String,
        /// Workstream name
        #[arg(long)]
        ws: String,
        /// Issue number
        issue_number: u64,
    },
    /// Show GitHub link status for a workstream
    Status {
        /// Project name
        project: String,
        /// Workstream name
        #[arg(long)]
        ws: String,
    },
}

#[derive(Subcommand)]
enum PromptAction {
    /// List all saved prompts
    List,
    /// Create a saved prompt
    Create {
        /// Prompt display name
        name: String,
        /// The prompt text
        prompt: String,
    },
    /// Update a saved prompt
    Update {
        /// Prompt ID
        id: String,
        /// New name
        #[arg(long)]
        name: Option<String>,
        /// New prompt text
        #[arg(long)]
        prompt: Option<String>,
    },
    /// Delete a saved prompt
    Delete {
        /// Prompt ID
        id: String,
    },
}

fn main() {
    let cli = Cli::parse();
    let host = cli.host.as_deref();

    match cli.command {
        Commands::Doctor => doctor::run(),
        Commands::Project { action } => match action {
            ProjectAction::Add { path } => project::add(&path, host),
            ProjectAction::List => project::list(host),
            ProjectAction::Remove { name } => project::remove(&name, host),
        },
        Commands::Ws { action } => match action {
            WsAction::Create {
                project,
                name,
                branch,
                pr,
            } => {
                workstream::create(
                    &project,
                    name.as_deref(),
                    branch.as_deref(),
                    pr.as_deref(),
                    host,
                );
            }
            WsAction::Rename {
                project,
                name,
                new_name,
            } => {
                workstream::rename(&project, &name, &new_name, host);
            }
            WsAction::List { project } => workstream::list(&project, host),
            WsAction::Delete { project, name } => workstream::delete(&project, &name, host),
            WsAction::Notes { action } => match action {
                WsNotesAction::Get { project, ws } => workstream::notes_get(&project, &ws, host),
                WsNotesAction::Set {
                    project,
                    ws,
                    content,
                } => workstream::notes_set(&project, &ws, &content, host),
            },
        },
        Commands::Shell { action } => match action {
            ShellAction::Open { project, ws } => shell::open(&project, ws.as_deref(), host),
            ShellAction::Attach { shell_id } => shell::attach(&shell_id, host),
            ShellAction::List => shell::list(host),
            ShellAction::Kill { shell_id } => shell::kill(&shell_id, host),
        },
        Commands::Agent { action } => match action {
            AgentAction::Spawn {
                project,
                ws,
                r#type,
            } => agent::spawn(&project, ws.as_deref(), r#type.as_deref(), host),
            AgentAction::Prompt { agent_id, text } => agent::prompt(&agent_id, &text, host),
            AgentAction::Kill { agent_id } => agent::kill(&agent_id, host),
            AgentAction::AttachShell { agent_id } => agent::attach_shell(&agent_id, host),
            AgentAction::Conversation {
                agent_id,
                watch,
                verbose,
            } => {
                agent::conversation(&agent_id, watch, verbose, host);
            }
            AgentAction::List { project, ws } => {
                agent::list(project.as_deref(), ws.as_deref(), host);
            }
            AgentAction::Status { agent_id } => agent::status(&agent_id, host),
        },
        Commands::Daemon { action } => match action {
            DaemonAction::Start { foreground } => {
                daemon_start(foreground);
            }
            DaemonAction::Stop => {
                daemon_stop();
            }
            DaemonAction::Logs => {
                daemon_logs();
            }
        },
        Commands::Gh { action } => match action {
            GhAction::DetectPr { project, ws } => github::detect_pr(&project, &ws, host),
            GhAction::LinkPr {
                project,
                ws,
                pr_number,
            } => github::link_pr(&project, &ws, pr_number, host),
            GhAction::UnlinkPr { project, ws } => github::unlink_pr(&project, &ws, host),
            GhAction::LinkIssue {
                project,
                ws,
                issue_number,
            } => github::link_issue(&project, &ws, issue_number, host),
            GhAction::UnlinkIssue {
                project,
                ws,
                issue_number,
            } => github::unlink_issue(&project, &ws, issue_number, host),
            GhAction::Status { project, ws } => github::status(&project, &ws, host),
        },
        Commands::Prompt { action } => match action {
            PromptAction::List => prompts::list(host),
            PromptAction::Create { name, prompt } => prompts::create(&name, &prompt, host),
            PromptAction::Update { id, name, prompt } => {
                prompts::update(&id, name.as_deref(), prompt.as_deref(), host);
            }
            PromptAction::Delete { id } => prompts::delete(&id, host),
        },
        Commands::Completions { shell } => {
            clap_complete::generate(shell, &mut Cli::command(), "vex", &mut std::io::stdout());
        }
        Commands::Hub { action } => match action {
            HubAction::Connect { host, port } => {
                hub_connect(&host, port);
            }
            HubAction::Start { foreground } => {
                hub_start(foreground);
            }
            HubAction::Stop => {
                hub_stop();
            }
            HubAction::Logs => {
                hub_logs();
            }
        },
    }
}

fn load_vex_home() -> vex_app::VexHome {
    match vex_app::VexHome::new(None) {
        Ok(h) => h,
        Err(e) => {
            eprintln!("Error: {e}");
            std::process::exit(1);
        }
    }
}

fn daemon_start(foreground: bool) {
    let vex_home = load_vex_home();
    let config = vex_home.load_config().unwrap_or_default();
    let port = config.daemon_port;

    if std::net::TcpStream::connect_timeout(
        &std::net::SocketAddr::from(([127, 0, 0, 1], port)),
        std::time::Duration::from_millis(200),
    )
    .is_ok()
    {
        eprintln!("Daemon is already running on port {port}");
        std::process::exit(1);
    }

    if foreground {
        let rt = tokio::runtime::Runtime::new().unwrap();
        rt.block_on(async {
            if let Err(e) = vex_daemon::run(vex_home).await {
                eprintln!("Daemon error: {e}");
                std::process::exit(1);
            }
        });
    } else {
        let exe = match std::env::current_exe() {
            Ok(e) => e,
            Err(e) => {
                eprintln!("Error finding executable: {e}");
                std::process::exit(1);
            }
        };
        let log_path = vex_home.root().join("daemon.log");
        let log_file = match std::fs::File::create(&log_path) {
            Ok(f) => f,
            Err(e) => {
                eprintln!("Error creating daemon log: {e}");
                std::process::exit(1);
            }
        };
        let log_file2 = log_file.try_clone().unwrap();
        match std::process::Command::new(exe)
            .args(["daemon", "start", "--foreground"])
            .stdout(std::process::Stdio::from(log_file))
            .stderr(std::process::Stdio::from(log_file2))
            .spawn()
        {
            Ok(child) => {
                std::thread::sleep(std::time::Duration::from_millis(500));
                println!("Daemon started (PID: {})", child.id());
            }
            Err(e) => {
                eprintln!("Error starting daemon: {e}");
                std::process::exit(1);
            }
        }
    }
}

fn daemon_logs() {
    let vex_home = load_vex_home();
    let log_path = vex_home.root().join("daemon.log");
    if !log_path.exists() {
        eprintln!("No daemon log file found. Start the daemon first.");
        std::process::exit(1);
    }
    let _ = std::process::Command::new("tail")
        .args(["-f", &log_path.to_string_lossy()])
        .status();
}

fn daemon_stop() {
    let vex_home = load_vex_home();

    // Try clean shutdown via local token
    let token = vex_home.load_or_create_token().ok();
    let config = vex_home.load_config().unwrap_or_default();
    let url = format!("ws://127.0.0.1:{}/ws", config.daemon_port);

    if let Some(token) = token
        && let Ok(mut client) = daemon_client::DaemonClient::connect(&url, &token)
    {
        match client.request("daemon.shutdown", json!({})) {
            Ok(_) => {
                println!("Daemon stopped");
                return;
            }
            Err(e) => {
                eprintln!("Warning: shutdown RPC failed: {e}");
            }
        }
    }

    // Fallback: PID file
    let pid_path = vex_home.root().join("daemon.pid");
    if pid_path.exists()
        && let Ok(pid_str) = std::fs::read_to_string(&pid_path)
        && let Ok(pid) = pid_str.trim().parse::<i32>()
    {
        #[cfg(unix)]
        unsafe {
            libc::kill(pid, libc::SIGTERM);
        }
        let _ = std::fs::remove_file(&pid_path);
        println!("Daemon stopped (via PID)");
        return;
    }

    eprintln!("Could not stop daemon: not running or unreachable");
    std::process::exit(1);
}

fn hub_connect(host: &str, port: u16) {
    let vex_home = load_vex_home();

    let is_local = host == "local" || host == "localhost" || host == "127.0.0.1";
    let is_ssh = !is_local && vex_app::ssh::is_ssh_host(host);

    // Determine the WebSocket URL and SSH metadata
    let (url, ssh_host, remote_port) = if is_ssh {
        let local_port = vex_app::ssh::find_free_port();
        eprintln!("Setting up SSH tunnel to {host} ({local_port} -> localhost:{port})...");
        if let Err(e) = vex_app::ssh::setup_tunnel(host, local_port, port) {
            eprintln!("Error: {e}");
            std::process::exit(1);
        }
        (
            format!("ws://127.0.0.1:{local_port}/ws"),
            Some(host.to_string()),
            Some(port),
        )
    } else {
        let resolved_host = if host == "local" { "127.0.0.1" } else { host };
        (format!("ws://{resolved_host}:{port}/ws"), None, None)
    };

    // Get token: auto-read for local, prompt interactively for remote
    let token = if is_local {
        match vex_home.load_or_create_token() {
            Ok(t) => t,
            Err(e) => {
                eprintln!("Error reading local token: {e}");
                std::process::exit(1);
            }
        }
    } else {
        prompt_token()
    };

    // Verify connection works
    match daemon_client::DaemonClient::connect(&url, &token) {
        Ok(_) => {}
        Err(e) => {
            eprintln!("Error connecting to daemon at {url}: {e}");
            std::process::exit(1);
        }
    }

    let mut connections = vex_home.load_connections().unwrap_or_default();
    connections.insert(
        host.to_string(),
        ConnectionEntry {
            url: url.clone(),
            token,
            ssh_host,
            remote_port,
        },
    );

    if let Err(e) = vex_home.save_connections(&connections) {
        eprintln!("Error saving connections: {e}");
        std::process::exit(1);
    }

    if is_ssh {
        println!("Connected to daemon at {host} via SSH tunnel ({url})");
    } else {
        println!("Connected to daemon at {url}");
    }
}

fn prompt_token() -> String {
    eprint!("Enter daemon token: ");
    std::io::Write::flush(&mut std::io::stderr()).expect("failed to flush stderr");
    let mut token = String::new();
    std::io::stdin()
        .read_line(&mut token)
        .expect("failed to read token");
    let token = token.trim().to_string();
    if token.is_empty() {
        eprintln!("Token cannot be empty");
        std::process::exit(1);
    }
    token
}

fn hub_start(foreground: bool) {
    let vex_home = load_vex_home();
    let hub_config = vex_home.load_hub_config().unwrap_or_default();
    let port = hub_config.web_port;

    if std::net::TcpStream::connect_timeout(
        &std::net::SocketAddr::from(([127, 0, 0, 1], port)),
        std::time::Duration::from_millis(200),
    )
    .is_ok()
    {
        eprintln!("Hub is already running on port {port}");
        std::process::exit(1);
    }

    if foreground {
        let rt = tokio::runtime::Runtime::new().unwrap();
        rt.block_on(async {
            if let Err(e) = vex_hub::run(vex_home).await {
                eprintln!("Hub error: {e}");
                std::process::exit(1);
            }
        });
    } else {
        let exe = match std::env::current_exe() {
            Ok(e) => e,
            Err(e) => {
                eprintln!("Error finding executable: {e}");
                std::process::exit(1);
            }
        };
        let log_path = vex_home.root().join("hub.log");
        let log_file = match std::fs::File::create(&log_path) {
            Ok(f) => f,
            Err(e) => {
                eprintln!("Error creating hub log: {e}");
                std::process::exit(1);
            }
        };
        let log_file2 = log_file.try_clone().unwrap();
        match std::process::Command::new(exe)
            .args(["hub", "start", "--foreground"])
            .stdout(std::process::Stdio::from(log_file))
            .stderr(std::process::Stdio::from(log_file2))
            .spawn()
        {
            Ok(child) => {
                std::thread::sleep(std::time::Duration::from_millis(500));
                println!("Hub started (PID: {})", child.id());
                println!("Web UI available at http://localhost:{port}");
            }
            Err(e) => {
                eprintln!("Error starting hub: {e}");
                std::process::exit(1);
            }
        }
    }
}

fn hub_stop() {
    let vex_home = load_vex_home();
    let pid_path = vex_home.root().join("hub.pid");
    if !pid_path.exists() {
        eprintln!("Hub is not running (no PID file)");
        std::process::exit(1);
    }
    let pid_str = match std::fs::read_to_string(&pid_path) {
        Ok(s) => s.trim().to_string(),
        Err(e) => {
            eprintln!("Error reading hub PID: {e}");
            std::process::exit(1);
        }
    };
    let pid: i32 = match pid_str.parse() {
        Ok(p) => p,
        Err(e) => {
            eprintln!("Invalid hub PID: {e}");
            std::process::exit(1);
        }
    };

    #[cfg(unix)]
    {
        unsafe {
            libc::kill(pid, libc::SIGTERM);
        }
    }
    let _ = std::fs::remove_file(&pid_path);
    println!("Hub stopped");
}

fn hub_logs() {
    let vex_home = load_vex_home();
    let log_path = vex_home.root().join("hub.log");
    if !log_path.exists() {
        eprintln!("No hub log file found. Start the hub first.");
        std::process::exit(1);
    }
    let _ = std::process::Command::new("tail")
        .args(["-f", &log_path.to_string_lossy()])
        .status();
}