ai-ipc 0.3.1

API server for inter-process communication between AI agents.
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
use clap::{Parser, Subcommand};
use anyhow::Result;
use serde::Deserialize;
use std::path::PathBuf;

mod client;
mod init;
mod worker;
mod lifecycle;
#[cfg(feature = "monitor")]
mod monitor;
#[cfg(feature = "monitor")]
mod wizard;

use client::CollabClient;

#[derive(Debug, Deserialize, Default)]
struct Config {
    host: Option<String>,
    instance: Option<String>,
    token: Option<String>,
}

fn load_config() -> Config {
    let local = local_config_path().and_then(|p| read_config(&p));
    let global = config_path().and_then(|p| read_config(&p));

    match (local, global) {
        (Some(l), Some(g)) => Config {
            host: l.host.or(g.host),
            instance: l.instance.or(g.instance),
            token: l.token.or(g.token),
        },
        (Some(c), None) | (None, Some(c)) => c,
        (None, None) => Config::default(),
    }
}

fn read_config(path: &PathBuf) -> Option<Config> {
    let contents = std::fs::read_to_string(path).ok()?;
    toml::from_str::<Config>(&contents).ok()
}

/// Walk up from CWD looking for a local .collab.toml (stops before home dir).
fn local_config_path() -> Option<PathBuf> {
    let home = home_dir()?;
    let mut dir = std::env::current_dir().ok()?;
    loop {
        let candidate = dir.join(".collab.toml");
        if candidate.exists() {
            return Some(candidate);
        }
        // Don't read the global ~/.collab.toml as a local config
        if dir == home {
            return None;
        }
        if !dir.pop() {
            return None;
        }
    }
}

fn config_path() -> Option<PathBuf> {
    home_dir().map(|h| h.join(".collab.toml"))
}

fn home_dir() -> Option<PathBuf> {
    #[cfg(windows)]
    {
        std::env::var("USERPROFILE").ok().map(PathBuf::from).or_else(|| {
            let drive = std::env::var("HOMEDRIVE").ok()?;
            let path = std::env::var("HOMEPATH").ok()?;
            Some(PathBuf::from(format!("{}{}", drive, path)))
        })
    }
    #[cfg(not(windows))]
    {
        std::env::var("HOME").ok().map(PathBuf::from)
    }
}

/// Load a .env file by walking up from cwd (same search as .collab.toml).
/// Sets values as real environment variables so std::env::var picks them up.
fn load_dotenv() {
    let home = home_dir();
    let mut dir = match std::env::current_dir() {
        Ok(d) => d,
        Err(_) => return,
    };
    loop {
        let candidate = dir.join(".env");
        if candidate.is_file() {
            if let Ok(contents) = std::fs::read_to_string(&candidate) {
                for line in contents.lines() {
                    let line = line.trim();
                    if line.is_empty() || line.starts_with('#') {
                        continue;
                    }
                    if let Some((key, val)) = line.split_once('=') {
                        let key = key.trim();
                        let val = val.trim().trim_matches('"').trim_matches('\'');
                        // Don't overwrite values already in the environment
                        if std::env::var(key).is_err() {
                            std::env::set_var(key, val);
                        }
                    }
                }
            }
            return;
        }
        if home.as_ref().map_or(false, |h| &dir == h) {
            return;
        }
        if !dir.pop() {
            return;
        }
    }
}

/// CLI for inter-instance communication between Claude Code workers
#[derive(Parser)]
#[command(name = "collab", version)]
#[command(about = "Collaboration tool for Claude Code instances", long_about = None)]
#[command(args_conflicts_with_subcommands = false)]
struct Cli {
    /// Server URL (overrides $COLLAB_SERVER and ~/.collab.toml)
    #[arg(long, global = true)]
    server: Option<String>,

    /// Instance identifier (overrides $COLLAB_INSTANCE and ~/.collab.toml)
    #[arg(short, long, global = true)]
    instance: Option<String>,

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

#[derive(Subcommand)]
enum TodoAction {
    /// Assign a task to an instance
    Add {
        /// Target instance (e.g., @worker or worker)
        #[arg(value_name = "@INSTANCE")]
        instance: String,

        /// Task description
        #[arg(value_name = "DESCRIPTION")]
        description: String,
    },

    /// List pending tasks (defaults to your own instance)
    List {
        /// Show tasks for a specific instance instead of yourself
        #[arg(value_name = "@INSTANCE")]
        instance: Option<String>,

        /// Alias: show tasks for a specific instance (e.g., --for @d4-stats)
        #[arg(long = "for", value_name = "INSTANCE")]
        for_instance: Option<String>,
    },

    /// Mark a task complete
    Done {
        /// Hash prefix of the task (at least 4 chars)
        #[arg(value_name = "HASH")]
        hash: String,
    },
}

#[derive(Subcommand)]
enum Commands {
    /// List messages intended for this instance (unread by default)
    List {
        /// Show all messages from the last hour, not just unread
        #[arg(short, long)]
        all: bool,

        /// Only show messages from a specific sender (e.g., @kali)
        #[arg(short, long, value_name = "@INSTANCE")]
        from: Option<String>,

        /// Only show messages after the message with this hash prefix
        #[arg(long, value_name = "HASH")]
        since: Option<String>,
    },

    /// Reply to the most recent message from a sender (auto-fills --refs)
    Reply {
        /// Sender to reply to (e.g., @kali)
        #[arg(value_name = "@INSTANCE")]
        sender: String,

        /// Message content
        #[arg(value_name = "MESSAGE")]
        message: String,
    },

    /// Show a single message by hash prefix
    Show {
        /// Hash prefix of the message to display (at least 4 chars)
        #[arg(value_name = "HASH")]
        hash: String,
    },

    /// Show unread messages and roster in one command (recommended cold-start)
    Status,

    /// Send a message to another instance
    Add {
        /// Target instance (e.g., @other_instance or other_instance)
        #[arg(value_name = "@INSTANCE")]
        recipient: String,

        /// Message content
        #[arg(value_name = "MESSAGE")]
        message: String,

        /// Reference message hash(es) - comma-separated
        #[arg(short, long, value_name = "HASH1,HASH2")]
        refs: Option<String>,
    },

    /// Send a message to all currently active workers (everyone in the roster except you)
    Broadcast {
        /// Message content
        #[arg(value_name = "MESSAGE")]
        message: String,

        /// Reference message hash(es) - comma-separated
        #[arg(short, long, value_name = "HASH1,HASH2")]
        refs: Option<String>,
    },

    /// Stream messages in real-time via SSE (zero-poll, instant delivery)
    Stream {
        /// Describe what you're working on (shown in roster)
        #[arg(short, long, value_name = "DESCRIPTION")]
        role: Option<String>,
    },

    /// View message history including sent and received messages
    History {
        /// Filter by conversation partner (e.g., @other_instance)
        #[arg(value_name = "@INSTANCE")]
        filter: Option<String>,
    },

    /// Show active workers (who's heartbeating or has sent messages recently)
    Roster,

    /// Live TUI monitor showing roster and message activity (requires --features monitor)
    #[cfg(feature = "monitor")]
    Monitor {
        /// Refresh interval in seconds (default: 2)
        #[arg(short, long, default_value = "2")]
        interval: u64,
    },

    /// Print the path to the config file
    ConfigPath,

    /// Show token usage from worker invocations
    Usage,

    /// Manage persistent task queue (survives context resets)
    Todo {
        #[command(subcommand)]
        action: TodoAction,
    },

    /// Set up worker environments from a YAML config (or interactive wizard)
    ///
    /// Example YAML:
    ///
    ///   server: http://localhost:8000
    ///   output_dir: ./workers     # optional
    ///   workers:
    ///     - name: frontend
    ///       role: "Build the React UI and manage component state"
    ///     - name: backend
    ///       role: "Implement REST API endpoints and database queries"
    Init {
        /// Path to workers YAML file (omit to launch interactive wizard)
        #[arg(value_name = "FILE")]
        file: Option<PathBuf>,

        /// Override the output directory from the YAML
        #[arg(short, long, value_name = "DIR")]
        output: Option<String>,
    },

    /// Event-driven headless worker (replaces polling)
    Worker {
        /// Project directory to run claude in (default: cwd)
        #[arg(long, value_name = "PATH")]
        workdir: Option<PathBuf>,

        /// Model to pass to claude (default: haiku)
        #[arg(long, value_name = "MODEL")]
        model: Option<String>,

        /// CLI command template with {prompt}, {model}, {workdir} placeholders
        /// (default: "claude -p {prompt} --model {model} --allowedTools Bash,Read,Write,Edit")
        #[arg(long, value_name = "TEMPLATE")]
        cli_template: Option<String>,

        /// Enable trivial message auto-reply (default: true)
        #[arg(long)]
        auto_reply: Option<bool>,

        /// Wait this long (ms) after first message before spawning (default: 2000)
        #[arg(long, value_name = "MS")]
        batch_wait: Option<u64>,
    },

    /// Start worker process(es) in background
    Start {
        /// Which worker(s) to start: 'all' or '@name'
        #[arg(value_name = "TARGET")]
        target: String,
    },

    /// Stop running worker process(es)
    Stop {
        /// Which worker(s) to stop: 'all' or '@name'
        #[arg(value_name = "TARGET")]
        target: String,
    },

    /// Stop and restart worker process(es)
    Restart {
        /// Which worker(s) to restart: 'all' or '@name'
        #[arg(value_name = "TARGET")]
        target: String,
    },

    /// Show running worker processes
    LifecycleStatus,
}

#[tokio::main]
async fn main() -> Result<()> {
    // Load .env file if present (walk up from cwd, stop before home)
    load_dotenv();

    let cli = Cli::parse();
    let file_config = load_config();

    // Priority: CLI flag > env var > .env file (already loaded) > config file > default
    let server = cli.server
        .or_else(|| std::env::var("COLLAB_SERVER").ok())
        .or(file_config.host.clone())
        .unwrap_or_else(|| "http://localhost:8000".to_string());

    let instance = cli.instance
        .or_else(|| std::env::var("COLLAB_INSTANCE").ok())
        .or(file_config.instance.clone());

    let token = std::env::var("COLLAB_TOKEN").ok().or(file_config.token.clone());

    if let Commands::Init { file, output } = cli.command {
        match file {
            Some(path) => {
                init::run_from_yaml(&path, output.as_deref())?;
            }
            None => {
                #[cfg(feature = "monitor")]
                {
                    match wizard::run()? {
                        Some(config) => init::generate(&config, output.as_deref())?,
                        None => println!("Wizard cancelled."),
                    }
                }
                #[cfg(not(feature = "monitor"))]
                {
                    anyhow::bail!(
                        "Interactive wizard requires the 'monitor' feature.\n\
                         Provide a YAML file instead: collab init workers.yaml"
                    );
                }
            }
        }
        return Ok(());
    }

    if let Commands::Worker { workdir, model, cli_template, auto_reply, batch_wait } = cli.command {
        let workdir = workdir.unwrap_or_else(|| std::env::current_dir().unwrap_or_default());
        let model = model.unwrap_or_default();
        let auto_reply = auto_reply.unwrap_or(true);
        let batch_wait = batch_wait.unwrap_or(2000);

        let instance_id = instance.ok_or_else(|| {
            anyhow::anyhow!(
                "Instance ID required. Set via --instance, $COLLAB_INSTANCE, or ~/.collab.toml"
            )
        })?;

        // Load manifest for pipeline config, teammate info, and cli_template fallback
        let (hands_off_to, teammates, manifest_cli_template, manifest_cli_template_light) = match find_manifest() {
            Ok(manifest_path) => {
                match lifecycle::read_manifest(&manifest_path) {
                    Ok(manifest) => {
                        let entry = manifest.iter().find(|w| w.name == instance_id);
                        let hands_off = entry
                            .map(|w| w.hands_off_to.clone())
                            .unwrap_or_default();
                        let tmpl = entry
                            .and_then(|w| w.cli_template.clone());
                        let tmpl_light = entry
                            .and_then(|w| w.cli_template_light.clone());
                        let team: Vec<(String, String)> = manifest.iter()
                            .map(|w| (w.name.clone(), w.role.clone()))
                            .collect();
                        (hands_off, team, tmpl, tmpl_light)
                    }
                    Err(_) => (vec![], vec![], None, None),
                }
            }
            Err(_) => (vec![], vec![], None, None),
        };

        // Priority: CLI flag > manifest > default
        let resolved_cli_template = cli_template.or(manifest_cli_template);

        let harness = worker::WorkerHarness::new(
            CollabClient::new(&server, &instance_id, token.as_deref()),
            instance_id,
            workdir,
            model,
            resolved_cli_template,
            manifest_cli_template_light,
            auto_reply,
            batch_wait,
            hands_off_to,
            teammates,
        );
        harness.run().await?;
        return Ok(());
    }

    if let Commands::Start { target } = cli.command {
        return lifecycle_start(&target, &server, token.as_deref()).await;
    }

    if let Commands::Stop { target } = cli.command {
        return lifecycle_stop(&target, &server, token.as_deref()).await;
    }

    if let Commands::Restart { target } = cli.command {
        return lifecycle_restart(&target, &server, token.as_deref()).await;
    }

    if matches!(cli.command, Commands::LifecycleStatus) {
        return lifecycle_status().await;
    }

    if matches!(cli.command, Commands::Roster) {
        let client = CollabClient::new(&server, "", token.as_deref());
        client.show_roster().await?;
        return Ok(());
    }

    if matches!(cli.command, Commands::ConfigPath) {
        if let Some(local) = local_config_path() {
            println!("local:  {}", local.display());
        }
        match config_path() {
            Some(path) => println!("global: {}", path.display()),
            None => println!("Could not determine home directory"),
        }
        return Ok(());
    }

    if matches!(cli.command, Commands::Usage) {
        let log_path = find_manifest()
            .map(|p| p.parent().unwrap().join("usage.log"))
            .unwrap_or_else(|_| std::path::PathBuf::from(".collab/usage.log"));

        if !log_path.exists() {
            println!("No usage data yet. Workers log to {} after each invocation.", log_path.display());
            return Ok(());
        }

        let content = std::fs::read_to_string(&log_path)?;
        // (input_tokens, output_tokens, duration_secs, call_count, cli_name, light_calls, full_calls, cost_usd)
        let mut per_worker: std::collections::HashMap<String, (u64, u64, u64, u32, String, u32, u32, f64)> = std::collections::HashMap::new();
        let mut total_input: u64 = 0;
        let mut total_output: u64 = 0;
        let mut total_duration: u64 = 0;
        let mut total_calls: u32 = 0;
        let mut total_light: u32 = 0;
        let mut total_full: u32 = 0;
        let mut total_cost: f64 = 0.0;
        let mut any_cost = false;

        for line in content.lines() {
            if line.len() > 1024 || line.is_empty() { continue; }
            let cols: Vec<&str> = line.split('\t').collect();
            if cols.len() >= 5 {
                let worker = cols[1];
                if worker.len() > 64 || !worker.chars().all(|c| c.is_alphanumeric() || c == '-' || c == '_') {
                    continue;
                }
                let worker = worker.to_string();
                let dur: u64 = cols[2].parse().unwrap_or(0);
                let inp: u64 = cols[3].parse().unwrap_or(0);
                let out: u64 = cols[4].parse().unwrap_or(0);
                let model = if cols.len() >= 6 { cols[5].to_string() } else { "?".to_string() };
                let tier = if cols.len() >= 7 { cols[6] } else { "full" };
                let cost: f64 = if cols.len() >= 8 { cols[7].parse().unwrap_or(0.0) } else { 0.0 };
                if cost > 0.0 { any_cost = true; }

                total_input += inp;
                total_output += out;
                total_duration += dur;
                total_calls += 1;
                total_cost += cost;
                if tier == "light" { total_light += 1; } else { total_full += 1; }

                let entry = per_worker.entry(worker).or_insert((0, 0, 0, 0, model.clone(), 0, 0, 0.0));
                entry.0 += inp;
                entry.1 += out;
                entry.2 += dur;
                entry.3 += 1;
                entry.4 = model;
                if tier == "light" { entry.5 += 1; } else { entry.6 += 1; }
                entry.7 += cost;
            }
        }

        let fmt_time = |secs: u64| -> String {
            let h = secs / 3600;
            let m = (secs % 3600) / 60;
            let s = secs % 60;
            if h > 0 { format!("{:>2}:{:02}:{:02}", h, m, s) }
            else { format!("   {:02}:{:02}", m, s) }
        };

        let header = if any_cost { "Token usage (actual)\n" } else { "Token usage (estimated ~4 chars/token)\n" };
        println!("{}", header);

        // Fetch todo counts per worker from server
        let client = CollabClient::new(&server, "", token.as_deref());
        let mut todo_counts: std::collections::HashMap<String, usize> = std::collections::HashMap::new();
        for worker_name in per_worker.keys() {
            if let Ok(todos) = client.fetch_todos(worker_name).await {
                todo_counts.insert(worker_name.clone(), todos.len());
            }
        }
        let total_todos: usize = todo_counts.values().sum();

        let mut workers: Vec<_> = per_worker.iter().collect();
        workers.sort_by(|a, b| (b.1.0 + b.1.1).cmp(&(a.1.0 + a.1.1)));

        let cost_col = if any_cost { "  Cost" } else { "" };
        println!("{:<20} {:>8} {:>8} {:>6} {:>8}  {:<10} {:<10} {:<6}{}", "Worker", "Input", "Output", "Calls", "Time", "CLI", "Tiers", "Todos", cost_col);
        println!("{}", "".repeat(if any_cost { 96 } else { 88 }));

        for (name, (inp, out, dur, calls, model, light, full, cost)) in &workers {
            let tier_str = format!("{}F/{}L", full, light);
            let todo_str = match todo_counts.get(*name) {
                Some(0) => "".to_string(),
                Some(n) => format!("{}", n),
                None => "?".to_string(),
            };
            let cost_str = if any_cost { format!("  ${:.4}", cost) } else { String::new() };
            println!("{:<20} {:>7}K {:>7}K {:>6} {:>8}  {:<10} {:<10} {:<6}{}", name, inp / 1000, out / 1000, calls, fmt_time(*dur), model, tier_str, todo_str, cost_str);
        }

        println!("{}", "".repeat(if any_cost { 96 } else { 88 }));
        let total_tier_str = format!("{}F/{}L", total_full, total_light);
        let total_todo_str = if total_todos > 0 { format!("{}", total_todos) } else { "".to_string() };
        let total_cost_str = if any_cost { format!("  ${:.4}", total_cost) } else { String::new() };
        println!("{:<20} {:>7}K {:>7}K {:>6} {:>8}  {:<10} {:<10} {:<6}{}", "TOTAL", total_input / 1000, total_output / 1000, total_calls, fmt_time(total_duration), "", total_tier_str, total_todo_str, total_cost_str);

        return Ok(());
    }

    let instance_id = instance.ok_or_else(|| {
        anyhow::anyhow!(
            "Instance ID required. Set via --instance, $COLLAB_INSTANCE, or ~/.collab.toml\n\
             \n\
             Example ~/.collab.toml:\n\
             host = \"http://localhost:8000\"\n\
             instance = \"worker1\""
        )
    })?;

    let client = CollabClient::new(&server, &instance_id, token.as_deref());

    // Update presence on every command so the roster stays current even without `watch`.
    // Ignore errors — if the server is unreachable the command itself will surface that.
    let _ = client.heartbeat(None).await;

    match cli.command {
        Commands::List { all, from, since } => {
            client.list_messages(!all, from.as_deref(), since.as_deref()).await?;
        }
        Commands::Reply { sender, message } => {
            client.reply_to_latest(&sender, &message).await?;
        }
        Commands::Show { hash } => {
            client.show_message(&hash).await?;
        }
        Commands::Status => {
            client.show_status().await?;
        }
        Commands::Add { recipient, message, refs } => {
            let recipient = recipient.trim_start_matches('@');
            let ref_hashes = refs.map(|r| {
                r.split(',').map(|s| s.trim().to_string()).collect()
            });
            client.add_message(recipient, &message, ref_hashes).await?;
        }
        Commands::Stream { role } => {
            client.stream_messages(role).await?;
        }
        Commands::Broadcast { message, refs } => {
            let ref_hashes = refs.map(|r| {
                r.split(',').map(|s| s.trim().to_string()).collect()
            });
            client.broadcast(&message, ref_hashes).await?;
        }
        Commands::History { filter } => {
            let filter_id = filter.as_deref().map(|s| s.trim_start_matches('@'));
            client.show_history(filter_id).await?;
        }
        Commands::Todo { action } => match action {
            TodoAction::Add { instance, description } => {
                let instance = instance.trim_start_matches('@');
                client.todo_add(instance, &description).await?;
            }
            TodoAction::List { instance, for_instance } => {
                let target = for_instance.as_deref().or(instance.as_deref());
                let target = target.map(|s| s.trim_start_matches('@'));
                client.todo_list(target).await?;
            }
            TodoAction::Done { hash } => {
                client.todo_done(&hash).await?;
            }
        },
        #[cfg(feature = "monitor")]
        Commands::Monitor { interval } => {
            let server2 = server.clone();
            let instance2 = instance_id.clone();
            let token2 = token.clone();
            std::thread::spawn(move || {
                monitor::run(&server2, &instance2, interval, token2.as_deref())
            })
            .join()
            .unwrap_or_else(|_| Err(anyhow::anyhow!("monitor panicked")))?;
        }
        Commands::Roster | Commands::ConfigPath | Commands::Usage | Commands::Init { .. } | Commands::Start { .. } | Commands::Stop { .. } | Commands::Restart { .. } | Commands::LifecycleStatus => unreachable!(),
        #[allow(unreachable_patterns)]
        #[allow(unreachable_patterns)]
        _ => unreachable!(),
    }

    Ok(())
}

/// SECURITY: Parse target string, preventing injection
fn parse_target(target: &str) -> Result<Vec<String>> {
    let target = target.trim();
    if target == "all" {
        // Will be expanded using manifest
        Ok(vec!["all".to_string()])
    } else if target.starts_with('@') {
        // Single instance
        let name = &target[1..];
        if name.chars().all(|c| c.is_alphanumeric() || c == '-' || c == '_') {
            Ok(vec![name.to_string()])
        } else {
            Err(anyhow::anyhow!("Invalid instance name: {}", name))
        }
    } else if target.chars().all(|c| c.is_alphanumeric() || c == '-' || c == '_') {
        // Instance name without @
        Ok(vec![target.to_string()])
    } else {
        Err(anyhow::anyhow!("Invalid target: {}", target))
    }
}

async fn lifecycle_start(target: &str, server: &str, token: Option<&str>) -> Result<()> {
    let targets = parse_target(target)?;
    let manifest_path = find_manifest()?;
    let manifest = lifecycle::read_manifest(&manifest_path)?;

    let pids_file = manifest_path.parent().unwrap().join("workers.pids");

    // Clean up stale PIDs — remove entries for processes that are no longer alive
    if pids_file.exists() {
        let content = std::fs::read_to_string(&pids_file)?;
        let state: std::collections::HashMap<String, lifecycle::WorkerState> =
            serde_json::from_str(&content).unwrap_or_default();
        for (name, ws) in &state {
            if !lifecycle::process_exists(ws.pid) {
                println!("⚠ Cleaning up stale PID for {} (PID {} no longer running)", name, ws.pid);
                lifecycle::remove_worker_pid(&pids_file, name)?;
            }
        }
    }

    // Determine which workers to start
    let workers = if targets[0] == "all" {
        manifest.clone()
    } else {
        manifest.into_iter()
            .filter(|w| targets.contains(&w.name))
            .collect()
    };

    if workers.is_empty() {
        println!("No matching workers found");
        return Ok(());
    }

    for worker in workers {
        let workdir = std::path::PathBuf::from(&worker.output_dir);
        let child = lifecycle::spawn_worker(
            &worker.name,
            &workdir,
            &worker.model,
            &worker.name,
            server,
            token,
            worker.cli_template.as_deref(),
        )?;

        let pid = child.id();
        let mut cmd = format!("collab worker --workdir {} --model {}", worker.output_dir, worker.model);
        if let Some(tmpl) = &worker.cli_template {
            cmd.push_str(&format!(" --cli-template {:?}", tmpl));
        }
        lifecycle::save_worker_pid(&pids_file, &worker.name, pid, &cmd)?;

        // Detach the child process
        std::mem::drop(child);
    }

    println!("✓ Workers started. Check status with: collab lifecycle-status");
    Ok(())
}

async fn lifecycle_stop(target: &str, server: &str, token: Option<&str>) -> Result<()> {
    let targets = parse_target(target)?;
    let manifest_path = find_manifest()?;
    let _manifest = lifecycle::read_manifest(&manifest_path)?;

    let pids_file = manifest_path.parent().unwrap().join("workers.pids");

    // Read current PIDs
    let mut state: std::collections::HashMap<String, lifecycle::WorkerState> = if pids_file.exists() {
        let content = std::fs::read_to_string(&pids_file)?;
        serde_json::from_str(&content).unwrap_or_default()
    } else {
        println!("No running workers found");
        return Ok(());
    };

    // Determine which workers to stop
    let workers_to_stop: Vec<String> = if targets[0] == "all" {
        state.keys().cloned().collect()
    } else {
        targets.iter()
            .filter(|t| state.contains_key(*t))
            .cloned()
            .collect()
    };

    if workers_to_stop.is_empty() {
        println!("No matching running workers found");
        return Ok(());
    }

    for name in &workers_to_stop {
        if let Some(worker_state) = state.remove(name) {
            lifecycle::kill_process(worker_state.pid, name)?;
            lifecycle::remove_worker_pid(&pids_file, name)?;
        }
    }

    println!("✓ Workers stopped");
    Ok(())
}

async fn lifecycle_restart(target: &str, server: &str, token: Option<&str>) -> Result<()> {
    lifecycle_stop(target, server, token).await?;
    std::thread::sleep(std::time::Duration::from_millis(500));
    lifecycle_start(target, server, token).await?;
    Ok(())
}

async fn lifecycle_status() -> Result<()> {
    let manifest_path = find_manifest()?;
    let pids_file = manifest_path.parent().unwrap().join("workers.pids");

    if !pids_file.exists() {
        println!("No workers running");
        return Ok(());
    }

    let content = std::fs::read_to_string(&pids_file)?;
    let state: std::collections::HashMap<String, lifecycle::WorkerState> = serde_json::from_str(&content)?;

    println!("Running workers:");
    for (name, worker_state) in &state {
        println!("  {} (PID: {})", name, worker_state.pid);
        println!("    Started: {}", worker_state.started_at);
        println!("    Command: {}", worker_state.command);
    }

    Ok(())
}

fn find_manifest() -> Result<std::path::PathBuf> {
    // Look for .collab/workers.json in current dir or parents
    let mut current = std::env::current_dir()?;
    loop {
        let manifest = current.join(".collab/workers.json");
        if manifest.exists() {
            return Ok(manifest);
        }
        if !current.pop() {
            break;
        }
    }
    Err(anyhow::anyhow!(
        "Manifest not found. Run 'collab init workers.yml' in your project directory"
    ))
}