collet 0.1.1

Relentless agentic coding orchestrator with zero-drop agent loops
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
/// Remote gateway management commands.
use anyhow::Result;
use fs2::FileExt;

/// PID file path for the running gateway process.
pub fn remote_pid_path() -> std::path::PathBuf {
    crate::config::collet_home(None).join("remote.pid")
}

/// Lock file path used as an exclusive daemon guard (separate from the PID file).
pub fn remote_lock_path() -> std::path::PathBuf {
    crate::config::collet_home(None).join("remote.lock")
}

/// Log file path for the remote gateway.
pub fn remote_log_path() -> std::path::PathBuf {
    crate::config::logs_dir().join("remote.log")
}

/// `collet remote add [platform]` — interactive adapter setup.
pub fn remote_add(platform: Option<&str>) -> Result<()> {
    use crate::config::wizard_style as s;

    let platforms = ["telegram", "slack", "discord"];
    let choice = if let Some(p) = platform {
        if !platforms.contains(&p) {
            eprintln!("Unknown platform: {p}");
            eprintln!("Available: {}", platforms.join(", "));
            std::process::exit(1);
        }
        p.to_string()
    } else {
        eprintln!("{}Select platform:{}", s::BOLD, s::RESET);
        for (i, p) in platforms.iter().enumerate() {
            eprintln!("  {}[{}]{} {}", s::CYAN, i + 1, s::RESET, p);
        }
        eprint!("  {}Choice [1]: {}", s::DIM, s::RESET);
        let mut line = String::new();
        std::io::stdin().read_line(&mut line)?;
        let idx: usize = line.trim().parse().unwrap_or(1);
        if idx == 0 || idx > platforms.len() {
            eprintln!("Invalid choice.");
            std::process::exit(1);
        }
        platforms[idx - 1].to_string()
    };

    let path = crate::config::config_file_path();
    let mut cf = crate::config::load_config_file().unwrap_or_default();

    // Collect non-secret config.toml patches: (section, key, toml_value).
    // Secrets (tokens) are saved to .secrets separately via save_config_secrets.
    let mut patches: Vec<(String, String, String)> = Vec::new();

    match choice.as_str() {
        "telegram" => {
            eprintln!();
            eprintln!("{}Telegram Setup{}", s::BOLD, s::RESET);
            eprintln!(
                "  Get a bot token from {}@BotFather{} on Telegram.",
                s::CYAN,
                s::RESET
            );
            eprintln!();
            eprint!("  {}Bot token: {}", s::BOLD, s::RESET);
            let token = super::util::read_password_line()?;
            if token.is_empty() {
                eprintln!("Token is required.");
                std::process::exit(1);
            }
            cf.telegram.token_enc = Some(crate::config::encrypt_key(&token)?);
            cf.telegram.token = None;

            eprintln!(
                "  {}Tip:{} Send a message to {}@userinfobot{} on Telegram to find your numeric user ID.",
                s::DIM,
                s::RESET,
                s::CYAN,
                s::RESET
            );
            eprint!(
                "  {}Allowed user IDs (comma-separated, empty=none): {}",
                s::DIM,
                s::RESET
            );
            let mut users_line = String::new();
            std::io::stdin().read_line(&mut users_line)?;
            let raw_parts: Vec<&str> = users_line
                .trim()
                .split(',')
                .map(|s| s.trim())
                .filter(|s| !s.is_empty())
                .collect();
            let mut users: Vec<i64> = Vec::new();
            for part in &raw_parts {
                match part.parse::<i64>() {
                    Ok(id) => users.push(id),
                    Err(_) => {
                        eprintln!(
                            "  {}⚠ Skipping '{}' — Telegram user IDs must be numeric.{}",
                            s::YELLOW,
                            part,
                            s::RESET
                        );
                    }
                }
            }
            if !users.is_empty() {
                let ids = users
                    .iter()
                    .map(|u| u.to_string())
                    .collect::<Vec<_>>()
                    .join(", ");
                patches.push((
                    "telegram".into(),
                    "allowed_users".into(),
                    format!("[{ids}]"),
                ));
            } else if !raw_parts.is_empty() {
                eprintln!(
                    "  {}⚠ No valid user IDs provided. All users will be denied.{}",
                    s::YELLOW,
                    s::RESET
                );
            }

            eprintln!("  {}✓ Telegram configured{}", s::GREEN, s::RESET);
        }
        "slack" => {
            eprintln!();
            eprintln!("{}Slack Setup{}", s::BOLD, s::RESET);
            eprintln!("  You need a Bot User OAuth Token (xoxb-...) and");
            eprintln!("  a Socket Mode App Token (xapp-...).");
            eprintln!();
            eprint!("  {}Bot token (xoxb-...): {}", s::BOLD, s::RESET);
            let bot = super::util::read_password_line()?;
            eprint!("  {}App token (xapp-...): {}", s::BOLD, s::RESET);
            let app = super::util::read_password_line()?;
            if bot.is_empty() || app.is_empty() {
                eprintln!("Both tokens are required.");
                std::process::exit(1);
            }
            cf.slack.bot_token_enc = Some(crate::config::encrypt_key(&bot)?);
            cf.slack.app_token_enc = Some(crate::config::encrypt_key(&app)?);
            cf.slack.bot_token = None;
            cf.slack.app_token = None;

            eprint!(
                "  {}Allowed user IDs (comma-separated, empty=none): {}",
                s::DIM,
                s::RESET
            );
            let mut users_line = String::new();
            std::io::stdin().read_line(&mut users_line)?;
            let users: Vec<String> = users_line
                .trim()
                .split(',')
                .map(|s| s.trim().to_string())
                .filter(|s| !s.is_empty())
                .collect();
            if !users.is_empty() {
                let ids = users
                    .iter()
                    .map(|u| format!("{u:?}"))
                    .collect::<Vec<_>>()
                    .join(", ");
                patches.push(("slack".into(), "allowed_users".into(), format!("[{ids}]")));
            }

            eprintln!("  {}✓ Slack configured{}", s::GREEN, s::RESET);
        }
        "discord" => {
            eprintln!();
            eprintln!("{}Discord Setup{}", s::BOLD, s::RESET);
            eprintln!("  Get a bot token from the Discord Developer Portal.");
            eprintln!();
            eprint!("  {}Bot token: {}", s::BOLD, s::RESET);
            let token = super::util::read_password_line()?;
            if token.is_empty() {
                eprintln!("Token is required.");
                std::process::exit(1);
            }
            cf.discord.token_enc = Some(crate::config::encrypt_key(&token)?);
            cf.discord.token = None;

            eprint!(
                "  {}Allowed user IDs (comma-separated, empty=none): {}",
                s::DIM,
                s::RESET
            );
            let mut users_line = String::new();
            std::io::stdin().read_line(&mut users_line)?;
            let users: Vec<u64> = users_line
                .trim()
                .split(',')
                .filter_map(|s| s.trim().parse().ok())
                .collect();
            if !users.is_empty() {
                let ids = users
                    .iter()
                    .map(|u| u.to_string())
                    .collect::<Vec<_>>()
                    .join(", ");
                patches.push(("discord".into(), "allowed_users".into(), format!("[{ids}]")));
            }

            eprint!(
                "  {}Guild IDs (comma-separated, empty=all): {}",
                s::DIM,
                s::RESET
            );
            let mut guilds_line = String::new();
            std::io::stdin().read_line(&mut guilds_line)?;
            let guilds: Vec<u64> = guilds_line
                .trim()
                .split(',')
                .filter_map(|s| s.trim().parse().ok())
                .collect();
            if !guilds.is_empty() {
                let ids = guilds
                    .iter()
                    .map(|u| u.to_string())
                    .collect::<Vec<_>>()
                    .join(", ");
                patches.push(("discord".into(), "guild_ids".into(), format!("[{ids}]")));
            }

            eprintln!("  {}✓ Discord configured{}", s::GREEN, s::RESET);
        }
        _ => unreachable!(),
    }

    // Auto-enable remote if not already set in the file.
    let existing_remote_enabled = crate::config::load_config_file()
        .ok()
        .and_then(|c| c.remote.enabled)
        .unwrap_or(false);
    if !existing_remote_enabled {
        patches.push(("remote".into(), "enabled".into(), "true".into()));
        eprintln!("  {}[remote] enabled = true{}", s::DIM, s::RESET);
    }

    // 1. Save secrets to .secrets (token_enc fields) — never written to config.toml.
    crate::config::save_config_secrets(&cf)?;

    // 2. Surgically patch config.toml — only the fields changed above.
    let patch_refs: Vec<(&str, &str, &str)> = patches
        .iter()
        .map(|(s, k, v)| (s.as_str(), k.as_str(), v.as_str()))
        .collect();
    crate::config::patch_config_toml(&path, &patch_refs)?;

    eprintln!();
    eprintln!("Saved to {}", path.display());
    Ok(())
}

/// `collet remote rm <platform>` — remove platform config.
pub fn remote_rm(platform: Option<&str>) -> Result<()> {
    let platform = platform.unwrap_or_else(|| {
        eprintln!("Usage: collet remote rm <telegram|slack|discord>");
        std::process::exit(1);
    });

    let path = crate::config::config_file_path();
    let mut cf = crate::config::load_config_file().unwrap_or_default();

    match platform {
        "telegram" => {
            cf.telegram = crate::config::TelegramSection::default();
            eprintln!("Removed Telegram configuration.");
        }
        "slack" => {
            cf.slack = crate::config::SlackSection::default();
            eprintln!("Removed Slack configuration.");
        }
        "discord" => {
            cf.discord = crate::config::DiscordSection::default();
            eprintln!("Removed Discord configuration.");
        }
        other => {
            eprintln!("Unknown platform: {other}");
            std::process::exit(1);
        }
    }

    crate::config::write_config_public(&path, &cf)?;
    Ok(())
}

/// `collet remote ls` — list configured platforms.
pub fn remote_ls() -> Result<()> {
    let file = crate::config::load_config_file().unwrap_or_default();
    let enabled = file.remote.enabled.unwrap_or(false);

    eprintln!(
        "Remote gateway: {}",
        if enabled { "enabled" } else { "disabled" }
    );
    eprintln!();

    // Check running status
    let running = is_remote_running();
    if running {
        eprintln!(
            "Status: running (PID {})",
            std::fs::read_to_string(remote_pid_path())
                .unwrap_or_default()
                .trim()
        );
    } else {
        eprintln!("Status: stopped");
    }
    eprintln!();

    // Telegram
    let tg_configured = file.telegram.token.is_some()
        || file.telegram.token_enc.is_some()
        || std::env::var("COLLET_TELEGRAM_TOKEN").is_ok();
    eprintln!(
        "  {} telegram  users: {}",
        if tg_configured { "" } else { "·" },
        if file.telegram.allowed_users.is_empty() {
            "(none)".to_string()
        } else {
            format!("{:?}", file.telegram.allowed_users)
        },
    );

    // Slack
    let sl_configured = file.slack.bot_token.is_some()
        || file.slack.bot_token_enc.is_some()
        || std::env::var("COLLET_SLACK_BOT_TOKEN").is_ok();
    eprintln!(
        "  {} slack     users: {}",
        if sl_configured { "" } else { "·" },
        if file.slack.allowed_users.is_empty() {
            "(none)".to_string()
        } else {
            format!("{:?}", file.slack.allowed_users)
        },
    );

    // Discord
    let dc_configured = file.discord.token.is_some()
        || file.discord.token_enc.is_some()
        || std::env::var("COLLET_DISCORD_TOKEN").is_ok();
    eprintln!(
        "  {} discord   users: {}  guilds: {}",
        if dc_configured { "" } else { "·" },
        if file.discord.allowed_users.is_empty() {
            "(none)".to_string()
        } else {
            format!("{:?}", file.discord.allowed_users)
        },
        if file.discord.guild_ids.is_empty() {
            "(all)".to_string()
        } else {
            format!("{:?}", file.discord.guild_ids)
        },
    );

    // Channel mappings
    if !file.channel_map.is_empty() {
        eprintln!();
        eprintln!("Channel mappings:");
        for m in &file.channel_map {
            eprintln!(
                "  {} #{}{} ({})",
                m.platform,
                m.channel,
                m.project.as_deref().unwrap_or("(default)"),
                if m.name.is_empty() { "-" } else { &m.name }
            );
        }
    }

    Ok(())
}

/// `collet remote start` — start the gateway (foreground).
pub async fn remote_start() -> Result<()> {
    use crate::remote::adapter::{StreamingLevel, WorkspaceScope};
    use std::sync::Arc;

    let config = crate::config::Config::load()?;
    let file = crate::config::load_config_file().unwrap_or_default();

    if !file.remote.enabled.unwrap_or(false) {
        eprintln!("Remote gateway is disabled. Enable it first:");
        eprintln!("  collet remote add <platform>");
        eprintln!("  or set [remote] enabled = true in config.toml");
        std::process::exit(1);
    }

    let auth = crate::remote::auth::AuthConfig::new(
        file.telegram.allowed_users.clone(),
        file.slack.allowed_users.clone(),
        file.discord.allowed_users.clone(),
    );

    let channel_map = crate::remote::channel_map::ChannelMap::new(file.channel_map.clone());

    let default_streaming = file
        .remote
        .default_streaming
        .as_deref()
        .and_then(StreamingLevel::parse)
        .unwrap_or(StreamingLevel::Compact);

    let default_workspace = file
        .remote
        .default_workspace
        .as_deref()
        .and_then(WorkspaceScope::parse)
        .unwrap_or(WorkspaceScope::Project);

    let default_workspace_dir = file.remote.workspace.clone();
    let approval_mode = file.remote.approval_mode.clone();
    let permissions = file.remote.permissions.clone();

    let mut adapters: Vec<Arc<dyn crate::remote::adapter::PlatformAdapter>> = Vec::new();

    #[cfg(feature = "telegram")]
    {
        let token = file
            .telegram
            .token
            .clone()
            .or_else(|| {
                file.telegram
                    .token_enc
                    .as_ref()
                    .and_then(|e| crate::config::decrypt_key(e).ok())
            })
            .or_else(|| std::env::var("COLLET_TELEGRAM_TOKEN").ok());
        if let Some(token) = token {
            adapters.push(Arc::new(crate::remote::telegram::TelegramAdapter::new(
                token,
            )));
            eprintln!("  ✓ Telegram adapter enabled");
        }
    }

    #[cfg(feature = "slack")]
    {
        let bot_token = file
            .slack
            .bot_token
            .clone()
            .or_else(|| {
                file.slack
                    .bot_token_enc
                    .as_ref()
                    .and_then(|e| crate::config::decrypt_key(e).ok())
            })
            .or_else(|| std::env::var("COLLET_SLACK_BOT_TOKEN").ok());
        let app_token = file
            .slack
            .app_token
            .clone()
            .or_else(|| {
                file.slack
                    .app_token_enc
                    .as_ref()
                    .and_then(|e| crate::config::decrypt_key(e).ok())
            })
            .or_else(|| std::env::var("COLLET_SLACK_APP_TOKEN").ok());
        if let (Some(bot), Some(app)) = (bot_token, app_token) {
            adapters.push(Arc::new(crate::remote::slack::SlackAdapter::new(bot, app)));
            eprintln!("  ✓ Slack adapter enabled");
        }
    }

    #[cfg(feature = "discord")]
    {
        let token = file
            .discord
            .token
            .clone()
            .or_else(|| {
                file.discord
                    .token_enc
                    .as_ref()
                    .and_then(|e| crate::config::decrypt_key(e).ok())
            })
            .or_else(|| std::env::var("COLLET_DISCORD_TOKEN").ok());
        if let Some(token) = token {
            adapters.push(Arc::new(crate::remote::discord::DiscordAdapter::new(token)));
            eprintln!("  ✓ Discord adapter enabled");
        }
    }

    if adapters.is_empty() {
        eprintln!("No platform adapters configured.");
        eprintln!("  Run: collet remote add");
        std::process::exit(1);
    }

    // Write PID file
    let pid_path = remote_pid_path();
    let _ = tokio::fs::create_dir_all(pid_path.parent().unwrap()).await;
    let _ = tokio::fs::write(&pid_path, std::process::id().to_string()).await;

    eprintln!(
        "Starting remote gateway with {} adapter(s)...",
        adapters.len()
    );

    let gateway = crate::remote::gateway::RemoteGateway::new(
        config,
        channel_map,
        auth,
        adapters,
        default_streaming,
        default_workspace,
        default_workspace_dir,
        approval_mode,
        permissions,
    );

    // Run gateway with graceful Ctrl+C shutdown
    let result = tokio::select! {
        res = gateway.run() => res,
        _ = tokio::signal::ctrl_c() => {
            eprintln!("\nShutting down remote gateway...");
            Ok(())
        }
    };
    let _ = std::fs::remove_file(&pid_path);
    result
}

/// `collet remote start` — start the gateway.
///
/// Delegates to the system service manager when `remote enable` has been run,
/// otherwise spawns a background daemon directly.
pub fn remote_start_daemon() -> Result<()> {
    #[cfg(target_os = "macos")]
    {
        let plist_path = super::util::launchd_plist_path();
        if plist_path.exists() {
            let uid = get_uid();
            let status = std::process::Command::new("launchctl")
                .args([
                    "bootstrap",
                    &format!("gui/{uid}"),
                    &plist_path.to_string_lossy(),
                ])
                .status();
            match status {
                Ok(s) if s.success() => eprintln!("Started gateway (launchd)."),
                _ => eprintln!("Failed to start gateway via launchd. Is it already running?"),
            }
            return Ok(());
        }
    }

    #[cfg(target_os = "linux")]
    {
        let unit_path = super::util::systemd_unit_path();
        if unit_path.exists() {
            let _ = std::process::Command::new("systemctl")
                .args(["--user", "start", "collet-remote"])
                .status();
            eprintln!("Started gateway (systemd).");
            return Ok(());
        }
    }

    remote_start_daemon_direct()
}

/// Spawn the gateway as a background daemon directly (no service manager).
fn remote_start_daemon_direct() -> Result<()> {
    // Use an exclusive lock on the lock file to prevent two concurrent
    // `collet remote start` invocations from both deciding "not running"
    // and both spawning a daemon (TOCTOU guard).
    let lock_path = remote_lock_path();
    let _ = std::fs::create_dir_all(lock_path.parent().unwrap_or(std::path::Path::new(".")));
    let lock_file = std::fs::OpenOptions::new()
        .create(true)
        .truncate(false)
        .write(true)
        .open(&lock_path)
        .map_err(|e| anyhow::anyhow!("cannot open daemon lock file: {e}"))?;
    if lock_file.try_lock_exclusive().is_err() {
        eprintln!("Remote gateway is already running (or another start is in progress).");
        eprintln!("  Use: collet remote stop");
        return Ok(());
    }

    // Check PID file as a secondary signal (foreground daemon holds the lock
    // while running; if the lock was available but PID exists, it's a stale file).
    let pid_path = remote_pid_path();
    if let Ok(pid_str) = std::fs::read_to_string(&pid_path) {
        let pid: u32 = pid_str.trim().parse().unwrap_or(0);
        if pid > 0 && is_process_running(pid) {
            eprintln!("Remote gateway is already running (PID {pid}).");
            eprintln!("  Use: collet remote stop");
            return Ok(());
        }
    }

    let exe = std::env::current_exe()
        .map_err(|e| anyhow::anyhow!("cannot find current executable: {e}"))?;

    let log_dir = crate::config::collet_home(None).join("logs");
    let _ = std::fs::create_dir_all(&log_dir);
    let log_path = crate::config::dated_log_path(&log_dir, "remote", 7);

    let log_file = std::fs::OpenOptions::new()
        .create(true)
        .append(true)
        .open(&log_path)
        .map_err(|e| anyhow::anyhow!("cannot open log file: {e}"))?;

    let log_err = log_file
        .try_clone()
        .map_err(|e| anyhow::anyhow!("cannot clone log file handle: {e}"))?;

    let child = std::process::Command::new(exe)
        .args(["remote", "start", "--fg"])
        .stdout(log_file)
        .stderr(log_err)
        .stdin(std::process::Stdio::null())
        .spawn()
        .map_err(|e| anyhow::anyhow!("failed to spawn daemon: {e}"))?;

    eprintln!("Remote gateway started (PID {}).", child.id());
    eprintln!("  Logs: {}", log_path.display());
    eprintln!("  Stop: collet remote stop");
    Ok(())
}

/// Check if a process is still running.
fn is_process_running(pid: u32) -> bool {
    #[cfg(unix)]
    {
        // kill(pid, 0) checks existence without sending a signal
        unsafe { libc::kill(pid as i32, 0) == 0 }
    }
    #[cfg(not(unix))]
    {
        let _ = pid;
        false
    }
}

/// Get the current user's numeric UID (for launchd service targets).
#[cfg(target_os = "macos")]
fn get_uid() -> String {
    std::process::Command::new("id")
        .arg("-u")
        .output()
        .ok()
        .and_then(|o| String::from_utf8(o.stdout).ok())
        .map(|s| s.trim().to_string())
        .unwrap_or_else(|| "501".to_string())
}

/// Returns the launchd service target string (e.g. `gui/501/com.collet.remote`).
#[cfg(target_os = "macos")]
fn launchd_target() -> String {
    format!("gui/{}/com.collet.remote", get_uid())
}

/// `collet remote stop` — stop the running gateway.
///
/// Delegates to the system service manager (launchctl / systemctl) when
/// `remote enable` has been run, otherwise falls back to PID-file kill.
pub fn remote_stop() -> Result<()> {
    #[cfg(target_os = "macos")]
    {
        let plist_path = super::util::launchd_plist_path();
        if plist_path.exists() {
            let target = launchd_target();
            let status = std::process::Command::new("launchctl")
                .args(["bootout", &target])
                .status();
            match status {
                Ok(s) if s.success() => eprintln!("Stopped gateway (launchd)."),
                _ => eprintln!("Gateway may not be running (launchd)."),
            }
            return Ok(());
        }
    }

    #[cfg(target_os = "linux")]
    {
        let unit_path = super::util::systemd_unit_path();
        if unit_path.exists() {
            let _ = std::process::Command::new("systemctl")
                .args(["--user", "stop", "collet-remote"])
                .status();
            eprintln!("Stopped gateway (systemd).");
            return Ok(());
        }
    }

    remote_stop_by_pid()
}

/// Stop a running gateway by reading the PID file and sending SIGTERM.
fn remote_stop_by_pid() -> Result<()> {
    let pid_path = remote_pid_path();
    let pid_str = match std::fs::read_to_string(&pid_path) {
        Ok(s) => s,
        Err(_) => {
            eprintln!("No running gateway found (no PID file).");
            return Ok(());
        }
    };

    let pid: u32 = pid_str.trim().parse().unwrap_or(0);
    if pid == 0 {
        eprintln!("Invalid PID file. Removing.");
        let _ = std::fs::remove_file(&pid_path);
        return Ok(());
    }

    #[cfg(unix)]
    {
        let status = std::process::Command::new("kill")
            .arg(pid.to_string())
            .status();
        match status {
            Ok(s) if s.success() => {
                eprintln!("Stopped gateway (PID {pid}).");
                let _ = std::fs::remove_file(&pid_path);
            }
            _ => {
                eprintln!("Failed to stop PID {pid}. Process may have already exited.");
                let _ = std::fs::remove_file(&pid_path);
            }
        }
    }

    #[cfg(not(unix))]
    {
        eprintln!("Stop is not supported on this platform. Kill PID {pid} manually.");
    }

    Ok(())
}

/// `collet remote restart` — restart the running gateway.
///
/// Delegates to the system service manager when `remote enable` has been run,
/// otherwise falls back to stop + start.
pub fn remote_restart() -> Result<()> {
    #[cfg(target_os = "macos")]
    {
        let plist_path = super::util::launchd_plist_path();
        if plist_path.exists() {
            let target = launchd_target();
            // kickstart -k kills the current instance and relaunches immediately.
            let status = std::process::Command::new("launchctl")
                .args(["kickstart", "-k", &target])
                .status();
            if status.map(|s| s.success()).unwrap_or(false) {
                eprintln!("Restarted gateway (launchd).");
                return Ok(());
            }
            // Fallback: bootout then bootstrap (service not loaded yet, etc.)
            let _ = std::process::Command::new("launchctl")
                .args(["bootout", &target])
                .status();
            std::thread::sleep(std::time::Duration::from_secs(1));
            let uid = get_uid();
            let _ = std::process::Command::new("launchctl")
                .args([
                    "bootstrap",
                    &format!("gui/{uid}"),
                    &plist_path.to_string_lossy(),
                ])
                .status();
            eprintln!("Restarted gateway (launchd).");
            return Ok(());
        }
    }

    #[cfg(target_os = "linux")]
    {
        let unit_path = super::util::systemd_unit_path();
        if unit_path.exists() {
            let _ = std::process::Command::new("systemctl")
                .args(["--user", "restart", "collet-remote"])
                .status();
            eprintln!("Restarted gateway (systemd).");
            return Ok(());
        }
    }

    // No service manager — direct PID stop + daemon spawn.
    let _ = remote_stop_by_pid();
    std::thread::sleep(std::time::Duration::from_secs(1));
    remote_start_daemon()
}

fn is_remote_running() -> bool {
    let pid_path = remote_pid_path();
    let pid_str = match std::fs::read_to_string(&pid_path) {
        Ok(s) => s,
        Err(_) => return false,
    };
    let pid: u32 = pid_str.trim().parse().unwrap_or(0);
    if pid == 0 {
        return false;
    }

    // Check if process exists
    #[cfg(unix)]
    {
        // kill -0 checks existence without sending a signal
        std::process::Command::new("kill")
            .args(["-0", &pid.to_string()])
            .output()
            .map(|o| o.status.success())
            .unwrap_or(false)
    }
    #[cfg(not(unix))]
    {
        false
    }
}

/// `collet remote status` — show gateway status.
pub fn remote_status() -> Result<()> {
    let file = crate::config::load_config_file().unwrap_or_default();
    let enabled = file.remote.enabled.unwrap_or(false);

    eprintln!(
        "Remote gateway: {}",
        if enabled { "enabled" } else { "disabled" }
    );

    if is_remote_running() {
        let pid = std::fs::read_to_string(remote_pid_path()).unwrap_or_default();
        eprintln!("Status: running (PID {})", pid.trim());
    } else {
        eprintln!("Status: stopped");
    }

    // Check login item
    let plist = super::util::launchd_plist_path();
    if plist.exists() {
        eprintln!("Auto-start: enabled ({})", plist.display());
    } else {
        eprintln!("Auto-start: disabled");
    }

    Ok(())
}

/// `collet remote enable` — register launchd plist (macOS) or systemd unit (Linux).
pub fn remote_enable() -> Result<()> {
    #[cfg(target_os = "macos")]
    {
        let plist_path = super::util::launchd_plist_path();
        if plist_path.exists() {
            eprintln!("Already enabled: {}", plist_path.display());
            return Ok(());
        }

        let exe = std::env::current_exe().map_err(|e| {
            crate::common::AgentError::Config(format!("Cannot find executable: {e}"))
        })?;
        let log = remote_log_path();
        let _ = std::fs::create_dir_all(log.parent().unwrap());

        let plist = format!(
            r#"<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>com.collet.remote</string>
    <key>ProgramArguments</key>
    <array>
        <string>{}</string>
        <string>remote</string>
        <string>start</string>
        <string>--fg</string>
    </array>
    <key>RunAtLoad</key>
    <true/>
    <key>KeepAlive</key>
    <true/>
    <key>StandardOutPath</key>
    <string>{}</string>
    <key>StandardErrorPath</key>
    <string>{}</string>
</dict>
</plist>
"#,
            exe.display(),
            log.display(),
            log.display()
        );

        let _ = std::fs::create_dir_all(plist_path.parent().unwrap());
        std::fs::write(&plist_path, plist).map_err(|e| {
            crate::common::AgentError::Config(format!("Failed to write plist: {e}"))
        })?;

        // Load the plist
        let _ = std::process::Command::new("launchctl")
            .args(["load", &plist_path.to_string_lossy()])
            .status();

        eprintln!("Enabled auto-start: {}", plist_path.display());
        eprintln!("Logs: {}", log.display());
    }

    #[cfg(target_os = "linux")]
    {
        let unit_path = super::util::systemd_unit_path();
        if unit_path.exists() {
            eprintln!("Already enabled: {}", unit_path.display());
            return Ok(());
        }

        let exe = std::env::current_exe().map_err(|e| {
            crate::common::AgentError::Config(format!("Cannot find executable: {e}"))
        })?;

        let unit = format!(
            r#"[Unit]
Description=Collet Remote Gateway
After=network.target

[Service]
ExecStart={} remote start --fg
Restart=on-failure
RestartSec=5

[Install]
WantedBy=default.target
"#,
            exe.display()
        );

        let _ = std::fs::create_dir_all(unit_path.parent().unwrap());
        std::fs::write(&unit_path, unit).map_err(|e| {
            crate::common::AgentError::Config(format!("Failed to write systemd unit: {e}"))
        })?;

        let _ = std::process::Command::new("systemctl")
            .args(["--user", "daemon-reload"])
            .status();
        let _ = std::process::Command::new("systemctl")
            .args(["--user", "enable", "collet-remote"])
            .status();

        eprintln!("Enabled auto-start: {}", unit_path.display());
    }

    #[cfg(not(any(target_os = "macos", target_os = "linux")))]
    {
        eprintln!("Auto-start is not supported on this platform.");
    }

    Ok(())
}

/// `collet remote disable` — unregister login item.
pub fn remote_disable() -> Result<()> {
    #[cfg(target_os = "macos")]
    {
        let plist_path = super::util::launchd_plist_path();
        if !plist_path.exists() {
            eprintln!("Not enabled.");
            return Ok(());
        }
        let _ = std::process::Command::new("launchctl")
            .args(["unload", &plist_path.to_string_lossy()])
            .status();
        let _ = std::fs::remove_file(&plist_path);
        eprintln!("Disabled auto-start.");
    }

    #[cfg(target_os = "linux")]
    {
        let unit_path = super::util::systemd_unit_path();
        if !unit_path.exists() {
            eprintln!("Not enabled.");
            return Ok(());
        }
        let _ = std::process::Command::new("systemctl")
            .args(["--user", "disable", "collet-remote"])
            .status();
        let _ = std::fs::remove_file(&unit_path);
        let _ = std::process::Command::new("systemctl")
            .args(["--user", "daemon-reload"])
            .status();
        eprintln!("Disabled auto-start.");
    }

    #[cfg(not(any(target_os = "macos", target_os = "linux")))]
    {
        eprintln!("Auto-start is not supported on this platform.");
    }

    Ok(())
}

/// Find the most recently modified `{prefix}.*.log` file in `dir`.
fn find_latest_log(dir: &std::path::Path, prefix: &str) -> Option<std::path::PathBuf> {
    let mut best: Option<(std::time::SystemTime, std::path::PathBuf)> = None;
    if let Ok(entries) = std::fs::read_dir(dir) {
        for entry in entries.flatten() {
            let name = entry.file_name();
            let name = name.to_string_lossy();
            if name.starts_with(&format!("{prefix}."))
                && name.ends_with(".log")
                && let Ok(modified) = entry.metadata().and_then(|m| m.modified())
                && best.as_ref().map(|(t, _)| modified > *t).unwrap_or(true)
            {
                best = Some((modified, entry.path()));
            }
        }
    }
    best.map(|(_, p)| p)
}

/// `collet remote logs [-f]` — show gateway logs.
pub fn remote_logs(follow: bool) -> Result<()> {
    let log_dir = crate::config::logs_dir();
    let log = find_latest_log(&log_dir, "remote").unwrap_or_else(remote_log_path);
    if !log.exists() {
        eprintln!("No log file found.");
        return Ok(());
    }

    if follow {
        // tail -f
        let status = std::process::Command::new("tail")
            .args(["-f", &log.to_string_lossy()])
            .status()
            .map_err(|e| crate::common::AgentError::Config(format!("Failed to tail log: {e}")))?;
        if !status.success() {
            std::process::exit(status.code().unwrap_or(1));
        }
    } else {
        // Last 50 lines
        let output = std::process::Command::new("tail")
            .args(["-50", &log.to_string_lossy()])
            .output()
            .map_err(|e| crate::common::AgentError::Config(format!("Failed to read log: {e}")))?;
        eprint!("{}", String::from_utf8_lossy(&output.stdout));
        eprint!("{}", String::from_utf8_lossy(&output.stderr));
    }

    Ok(())
}