pulpod 0.0.41

Pulpo daemon — manages agent sessions via tmux/Docker
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
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
pub mod api;
pub mod auth_info;
pub mod backend;
pub mod config;
pub mod discovery;

pub mod mcp;
pub mod notifications;
pub mod peers;
pub mod platform;
pub mod scheduler;
pub mod session;
pub mod store;
pub mod watchdog;

use std::path::Path;
use std::sync::Arc;

use anyhow::Result;
use clap::Parser;
use pulpo_common::event::PulpoEvent;
use tokio::sync::{broadcast, watch};
use tracing::info;
use tracing_subscriber::EnvFilter;
use tracing_subscriber::layer::SubscriberExt;
use tracing_subscriber::util::SubscriberInitExt;

#[cfg(all(not(coverage), not(target_os = "windows")))]
use backend::tmux::TmuxBackend;
use session::manager::SessionManager;

/// No-op backend used only during coverage builds (where TmuxBackend doesn't impl Backend).
#[cfg(coverage)]
struct CoverageBackend;

#[cfg(coverage)]
impl backend::Backend for CoverageBackend {
    fn session_id(&self, name: &str) -> String {
        name.to_owned()
    }
    fn create_session(&self, _: &str, _: &str, _: &str) -> anyhow::Result<()> {
        Ok(())
    }
    fn kill_session(&self, _: &str) -> anyhow::Result<()> {
        Ok(())
    }
    fn is_alive(&self, _: &str) -> anyhow::Result<bool> {
        Ok(true)
    }
    fn capture_output(&self, _: &str, _: usize) -> anyhow::Result<String> {
        Ok(String::new())
    }
    fn send_input(&self, _: &str, _: &str) -> anyhow::Result<()> {
        Ok(())
    }
    fn setup_logging(&self, _: &str, _: &str) -> anyhow::Result<()> {
        Ok(())
    }
    fn list_sessions(&self) -> anyhow::Result<Vec<(String, String)>> {
        Ok(Vec::new())
    }
    fn pane_info(&self, _: &str) -> anyhow::Result<(String, String)> {
        Ok(("bash".into(), "/tmp".into()))
    }
}

/// Stub backend for platforms where tmux is not available (Windows).
/// Sessions require --runtime docker on these platforms.
#[cfg(target_os = "windows")]
struct WindowsStubBackend;

#[cfg(target_os = "windows")]
impl backend::Backend for WindowsStubBackend {
    fn create_session(&self, _: &str, _: &str, _: &str) -> anyhow::Result<()> {
        anyhow::bail!("tmux is not available on Windows — use --runtime docker for Docker sessions")
    }
    fn kill_session(&self, _: &str) -> anyhow::Result<()> {
        Ok(())
    }
    fn is_alive(&self, _: &str) -> anyhow::Result<bool> {
        Ok(false)
    }
    fn capture_output(&self, _: &str, _: usize) -> anyhow::Result<String> {
        Ok(String::new())
    }
    fn send_input(&self, _: &str, _: &str) -> anyhow::Result<()> {
        Ok(())
    }
    fn setup_logging(&self, _: &str, _: &str) -> anyhow::Result<()> {
        Ok(())
    }
}

/// Holds shutdown senders for all background loops.
///
/// Calling `shutdown()` signals all loops to exit gracefully. Also holds owned
/// resources (like mDNS registration) that should be dropped on shutdown.
pub struct ShutdownHandle {
    senders: Vec<watch::Sender<bool>>,
    /// mDNS registration kept alive until shutdown (behind cfg so coverage builds compile).
    #[cfg(not(coverage))]
    mdns_registration: Option<discovery::mdns::MdnsRegistration>,
    /// Whether `tailscale serve` was started and needs cleanup on shutdown.
    tailscale_serve_active: bool,
}

impl ShutdownHandle {
    const fn new() -> Self {
        Self {
            senders: Vec::new(),
            #[cfg(not(coverage))]
            mdns_registration: None,
            tailscale_serve_active: false,
        }
    }

    fn add_sender(&mut self, tx: watch::Sender<bool>) {
        self.senders.push(tx);
    }

    #[cfg(not(coverage))]
    fn set_mdns_registration(&mut self, reg: discovery::mdns::MdnsRegistration) {
        self.mdns_registration = Some(reg);
    }

    /// Signal all background loops to shut down and clean up resources.
    pub fn shutdown(&self) {
        for tx in &self.senders {
            let _ = tx.send(true);
        }
        if self.tailscale_serve_active {
            tailscale_serve_cleanup();
        }
    }
}

#[derive(Parser, Debug)]
#[command(
    name = "pulpod",
    about = "Pulpo daemon — agent session orchestrator",
    version = env!("PULPO_VERSION")
)]
pub struct Cli {
    /// Config file path
    #[arg(long, default_value = "~/.pulpo/config.toml")]
    pub config: String,

    /// Port to listen on (overrides config)
    #[arg(short, long)]
    pub port: Option<u16>,

    #[command(subcommand)]
    pub command: Option<CliCommand>,
}

#[derive(clap::Subcommand, Debug, Clone, PartialEq, Eq)]
pub enum CliCommand {
    /// Start the MCP server over STDIO (for use by AI agents)
    Mcp,
}

/// Initialize tracing subscriber for logging.
///
/// When `log_dir` is `Some`, logs are written to hourly-rotated files under
/// `{log_dir}/logs/` using a non-blocking writer. The `retain_days` parameter
/// controls how many days of log files to keep (converted to `days * 24` hourly
/// files for `max_log_files`). If the log directory cannot be created, falls back
/// to console-only logging instead of failing.
///
/// The console layer is included only when stdout is a terminal (i.e., not when
/// running under systemd/launchd), to avoid double-logging to both journald and
/// the log file.
///
/// When `log_dir` is `None`, only console output is used (useful for tests).
///
/// Returns an optional guard that must be held for the lifetime of the program
/// to ensure buffered log writes are flushed.
pub fn init_tracing(
    log_dir: Option<&Path>,
    retain_days: u32,
) -> Result<Option<tracing_appender::non_blocking::WorkerGuard>> {
    use std::io::IsTerminal;
    use tracing_appender::rolling::{RollingFileAppender, Rotation};

    let env_filter = EnvFilter::from_default_env().add_directive("pulpod=info".parse()?);
    let is_tty = std::io::stdout().is_terminal();

    if let Some(dir) = log_dir {
        let log_path = dir.join("logs");
        match std::fs::create_dir_all(&log_path) {
            Ok(()) => {
                let max_files = retain_days.max(1) as usize * 24;
                let file_appender = RollingFileAppender::builder()
                    .rotation(Rotation::HOURLY)
                    .filename_prefix("pulpod.log")
                    .max_log_files(max_files)
                    .build(&log_path)
                    .map_err(|e| anyhow::anyhow!("Failed to create log appender: {e}"))?;
                let (non_blocking, guard) = tracing_appender::non_blocking(file_appender);
                let file_layer = tracing_subscriber::fmt::layer()
                    .with_ansi(false)
                    .with_writer(non_blocking);

                // Include console layer only when running interactively (TTY).
                // Under systemd/launchd, stdout goes to journald/syslog already.
                let console_layer = is_tty.then(tracing_subscriber::fmt::layer);

                tracing_subscriber::registry()
                    .with(env_filter)
                    .with(console_layer)
                    .with(file_layer)
                    .try_init()
                    .ok();

                return Ok(Some(guard));
            }
            Err(e) => {
                eprintln!(
                    "Warning: could not create log directory {}: {e}. Logging to console only.",
                    log_path.display()
                );
            }
        }
    }

    let console_layer = tracing_subscriber::fmt::layer();
    tracing_subscriber::registry()
        .with(env_filter)
        .with(console_layer)
        .try_init()
        .ok();

    Ok(None)
}

/// Upgrade name-based backend session IDs to tmux `$N` IDs for live sessions.
/// Best-effort: skips sessions whose tmux session is dead or already upgraded.
#[cfg(all(not(coverage), not(target_os = "windows")))]
async fn upgrade_backend_ids(manager: &SessionManager, store: &store::Store) {
    let upgrade_backend = manager.backend();
    let Ok(sessions) = store.list_sessions().await else {
        return;
    };
    for session in sessions {
        let is_live = matches!(
            session.status,
            pulpo_common::session::SessionStatus::Active
                | pulpo_common::session::SessionStatus::Idle
                | pulpo_common::session::SessionStatus::Ready
        );
        if !is_live {
            continue;
        }
        if session
            .backend_session_id
            .as_ref()
            .is_some_and(|id| id.starts_with('$') || id.starts_with("docker:"))
        {
            continue;
        }
        if let Ok(tmux_id) = upgrade_backend.query_backend_id(&session.name) {
            let _ = store
                .update_backend_session_id(&session.id.to_string(), &tmux_id)
                .await;
        }
    }
}

/// Build the application from config — returns the router, listener address, and shutdown handle.
#[allow(clippy::too_many_lines)]
pub async fn build_app(cli: &Cli) -> Result<(axum::Router, String, ShutdownHandle)> {
    let mut config = config::load(&cli.config)?;
    let port = cli.port.unwrap_or(config.node.port);

    // Resolve config path for saving later
    let expanded = shellexpand::tilde(&cli.config);
    let config_path = std::path::PathBuf::from(expanded.as_ref());

    // Auto-generate auth token on first run
    let mut config_changed = config::ensure_auth_token(&mut config);
    if config_changed {
        info!("Generated new auth token");
    }

    // Auto-generate VAPID keys on first run
    if config::ensure_vapid_keys(&mut config) {
        info!("Generated new VAPID keys for Web Push");
        config_changed = true;
    }

    if config_changed {
        config::save(&config, &config_path)?;
    }

    let store = store::Store::new(&config.data_dir()).await?;
    store.migrate().await?;

    #[cfg(all(not(coverage), not(target_os = "windows")))]
    let backend: Arc<dyn backend::Backend> = Arc::new(TmuxBackend::new());

    #[cfg(all(not(coverage), not(target_os = "windows")))]
    {
        let version = backend.check_version()?;
        info!("Using {version}");
    }

    #[cfg(all(not(coverage), target_os = "windows"))]
    let backend: Arc<dyn backend::Backend> = Arc::new(WindowsStubBackend);

    #[cfg(coverage)]
    let backend: Arc<dyn backend::Backend> = Arc::new(CoverageBackend);
    #[cfg(not(coverage))]
    let watchdog_backend = backend.clone();
    #[cfg(not(coverage))]
    let watchdog_store = store.clone();

    let node_name = config.node.name.clone();
    let (event_tx, _) = broadcast::channel::<PulpoEvent>(256);

    let docker_backend: Option<Arc<dyn backend::Backend>> = if config.docker.image.is_empty() {
        None
    } else {
        #[cfg(not(coverage))]
        {
            Some(Arc::new(backend::docker::DockerBackend::new(
                &config.docker.image,
                config.docker.volumes.clone(),
            )))
        }
        #[cfg(coverage)]
        {
            None
        }
    };

    let mut manager = SessionManager::new(
        backend,
        store.clone(),
        config.inks.clone(),
        config.node.default_command.clone(),
    )
    .with_event_tx(event_tx.clone(), node_name.clone());
    if let Some(ref db) = docker_backend {
        manager = manager.with_docker_backend(db.clone());
    }

    // Auto-resume sessions that were active before a restart
    match manager.resume_lost_sessions().await {
        Ok(0) => {}
        Ok(n) => info!("Auto-resumed {n} session(s) from previous run"),
        Err(e) => tracing::warn!("Failed to auto-resume sessions: {e}"),
    }

    // Upgrade name-based backend_session_ids to tmux $N IDs (best-effort)
    #[cfg(all(not(coverage), not(target_os = "windows")))]
    upgrade_backend_ids(&manager, &store).await;

    let peer_registry = peers::PeerRegistry::new(&config.peers);

    let mut shutdown_handle = ShutdownHandle::new();

    // Start built-in scheduler
    #[cfg(not(coverage))]
    {
        let sched_manager = manager.clone();
        let sched_store = store.clone();
        let sched_event_tx = Some(event_tx.clone());
        let (sched_shutdown_tx, sched_shutdown_rx) = watch::channel(false);
        tokio::spawn(scheduler::run_scheduler_loop(
            sched_manager,
            sched_store,
            sched_event_tx,
            sched_shutdown_rx,
        ));
        shutdown_handle.add_sender(sched_shutdown_tx);
        info!("Scheduler enabled");
    }

    #[cfg(not(coverage))]
    let watchdog_config_tx = {
        if config.watchdog.enabled {
            let reader = watchdog::memory::SystemMemoryReader;
            let wd_runtime = watchdog::WatchdogRuntimeConfig {
                threshold: config.watchdog.memory_threshold,
                interval: std::time::Duration::from_secs(config.watchdog.check_interval_secs),
                breach_count: config.watchdog.breach_count,
                idle: watchdog::IdleConfig {
                    enabled: config.watchdog.idle_timeout_secs > 0,
                    timeout_secs: config.watchdog.idle_timeout_secs,
                    action: if config.watchdog.idle_action == "kill" {
                        watchdog::IdleAction::Kill
                    } else {
                        watchdog::IdleAction::Alert
                    },
                    threshold_secs: config.watchdog.idle_threshold_secs,
                },
                ready_ttl_secs: config.watchdog.ready_ttl_secs,
                adopt_tmux: config.watchdog.adopt_tmux,
                extra_waiting_patterns: config.watchdog.waiting_patterns.clone(),
            };
            let (wd_config_tx, wd_config_rx) = watch::channel(wd_runtime.clone());
            let (wd_shutdown_tx, wd_shutdown_rx) = watch::channel(false);
            info!(
                threshold = wd_runtime.threshold,
                interval_secs = wd_runtime.interval.as_secs(),
                breach_count = wd_runtime.breach_count,
                "Starting memory watchdog"
            );
            let ready_ctx = watchdog::ReadyContext {
                event_tx: Some(event_tx.clone()),
                node_name,
            };
            tokio::spawn(watchdog::run_watchdog_loop(
                watchdog_backend,
                watchdog_store,
                Box::new(reader),
                wd_config_rx,
                wd_shutdown_rx,
                ready_ctx,
            ));
            shutdown_handle.add_sender(wd_shutdown_tx);
            Some(wd_config_tx)
        } else {
            None
        }
    };

    let bind_mode = config.node.bind;

    // Start peer discovery based on bind mode
    #[cfg(not(coverage))]
    match bind_mode {
        pulpo_common::auth::BindMode::Tailscale => {
            let ts_registry = peer_registry.clone();
            let own_name = config.node.name.clone();
            let ts_tag = config.node.tag.clone();
            let ts_interval = std::time::Duration::from_secs(config.node.discovery_interval_secs);
            let (ts_shutdown_tx, ts_shutdown_rx) = watch::channel(false);
            tokio::spawn(discovery::tailscale::run_tailscale_discovery(
                ts_registry,
                own_name,
                ts_tag,
                ts_interval,
                ts_shutdown_rx,
            ));
            shutdown_handle.add_sender(ts_shutdown_tx);
            info!("Tailscale discovery enabled");
        }
        pulpo_common::auth::BindMode::Public => {
            if let Some(seed_address) = config.node.seed.clone() {
                // Seed discovery (explicit seed peer)
                let seed_registry = peer_registry.clone();
                let own_name = config.node.name.clone();
                let seed_interval =
                    std::time::Duration::from_secs(config.node.discovery_interval_secs);
                let (seed_shutdown_tx, seed_shutdown_rx) = watch::channel(false);
                tokio::spawn(discovery::seed::run_seed_discovery(
                    seed_registry,
                    own_name,
                    port,
                    seed_address,
                    seed_interval,
                    seed_shutdown_rx,
                ));
                shutdown_handle.add_sender(seed_shutdown_tx);
                info!("Seed discovery enabled");
            } else {
                // mDNS discovery (default for public)
                let reg = discovery::ServiceRegistration {
                    node_name: config.node.name.clone(),
                    port,
                };
                match discovery::mdns::MdnsRegistration::register(&reg) {
                    Ok(registration) => {
                        shutdown_handle.set_mdns_registration(registration);
                    }
                    Err(e) => {
                        tracing::warn!("mDNS registration failed (discovery disabled): {e}");
                    }
                }

                let browser_registry = peer_registry.clone();
                let own_name = config.node.name.clone();
                let (browser_shutdown_tx, browser_shutdown_rx) = watch::channel(false);
                tokio::spawn(discovery::mdns::run_mdns_browser(
                    browser_registry,
                    own_name,
                    browser_shutdown_rx,
                ));
                shutdown_handle.add_sender(browser_shutdown_tx);
            }
        }
        // Local and Container: no discovery
        pulpo_common::auth::BindMode::Local | pulpo_common::auth::BindMode::Container => {}
    }

    // Start Discord notification loop if configured
    if let Some(discord_config) = config.notifications.discord.clone() {
        let notifier = notifications::discord::DiscordNotifier::new(discord_config);
        let discord_rx = event_tx.subscribe();
        let (discord_shutdown_tx, discord_shutdown_rx) = watch::channel(false);
        tokio::spawn(notifications::discord::run_notification_loop(
            notifier,
            discord_rx,
            discord_shutdown_rx,
        ));
        shutdown_handle.add_sender(discord_shutdown_tx);
        info!("Discord notifications enabled");
    }

    // Start generic webhook notification loops
    for webhook_config in &config.notifications.webhooks {
        let notifier = notifications::webhook::WebhookNotifier::new(webhook_config.clone());
        let webhook_rx = event_tx.subscribe();
        let (webhook_shutdown_tx, webhook_shutdown_rx) = watch::channel(false);
        let name = webhook_config.name.clone();
        tokio::spawn(notifications::webhook::run_notification_loop(
            notifier,
            webhook_rx,
            webhook_shutdown_rx,
        ));
        shutdown_handle.add_sender(webhook_shutdown_tx);
        info!(webhook = %name, "Webhook notifications enabled");
    }

    // Start Web Push notification loop (always enabled when VAPID keys are present)
    if !config.notifications.vapid.private_key.is_empty()
        && !config.notifications.vapid.public_key.is_empty()
    {
        let notifier = notifications::web_push::WebPushNotifier::new(
            store.clone(),
            config.notifications.vapid.private_key.clone(),
        );
        let push_rx = event_tx.subscribe();
        let (push_shutdown_tx, push_shutdown_rx) = watch::channel(false);
        tokio::spawn(notifications::web_push::run_notification_loop(
            notifier,
            push_rx,
            push_shutdown_rx,
        ));
        shutdown_handle.add_sender(push_shutdown_tx);
        info!("Web Push notifications enabled");
    }

    #[cfg(not(coverage))]
    let wd_tx = watchdog_config_tx;
    #[cfg(coverage)]
    let wd_tx: Option<tokio::sync::watch::Sender<watchdog::WatchdogRuntimeConfig>> = None;

    let state = api::AppState::with_watchdog_tx(
        config,
        config_path,
        manager,
        peer_registry,
        event_tx,
        wd_tx,
        store.clone(),
    );

    let app = api::router(state);

    let bind_ip: String = match bind_mode {
        pulpo_common::auth::BindMode::Local | pulpo_common::auth::BindMode::Tailscale => {
            "127.0.0.1".into()
        }
        pulpo_common::auth::BindMode::Public | pulpo_common::auth::BindMode::Container => {
            "0.0.0.0".into()
        }
    };

    // Set up tailscale serve for HTTPS access over tailnet
    if bind_mode == pulpo_common::auth::BindMode::Tailscale {
        match tailscale_serve_start(port) {
            Ok(()) => {
                shutdown_handle.tailscale_serve_active = true;
            }
            Err(e) => {
                tracing::warn!(
                    "Tailscale serve unavailable ({e}). \
                     Dashboard will only be accessible locally at http://localhost:{port}. \
                     Start Tailscale to enable HTTPS access over your tailnet."
                );
            }
        }
    }

    let addr = format!("{bind_ip}:{port}");
    info!("pulpod v{} starting", env!("CARGO_PKG_VERSION"));
    if bind_mode == pulpo_common::auth::BindMode::Tailscale
        && shutdown_handle.tailscale_serve_active
    {
        let ts_name = resolve_tailscale_name().unwrap_or_else(|_| "your-machine".into());
        info!("Dashboard: https://{ts_name}");
    } else {
        info!("Dashboard: http://localhost:{port}");
    }
    info!("Listening on {addr} (bind={bind_mode})");

    Ok((app, addr, shutdown_handle))
}

/// Start `tailscale serve` to proxy the local port over HTTPS on the tailnet.
///
/// Cleans up any stale serve rules first (e.g., from a previous crash), then
/// registers `https / http://127.0.0.1:{port}` so the dashboard is available at
/// `https://<machine-name>.<tailnet>.ts.net`.
#[cfg(not(coverage))]
fn tailscale_serve_start(port: u16) -> Result<()> {
    // Clean up stale rules from a previous crash
    let _ = std::process::Command::new("tailscale")
        .args(["serve", "--https=443", "off"])
        .output();

    let output = std::process::Command::new("tailscale")
        .args([
            "serve",
            "--bg",
            "--https=443",
            &format!("http://127.0.0.1:{port}"),
        ])
        .output()
        .map_err(|e| anyhow::anyhow!("Failed to run `tailscale serve`: {e}"))?;
    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        anyhow::bail!("tailscale serve failed: {stderr}");
    }
    info!("tailscale serve started (proxying port {port} over HTTPS)");
    Ok(())
}

/// Stub for coverage builds.
#[cfg(coverage)]
fn tailscale_serve_start(_port: u16) -> Result<()> {
    Ok(())
}

/// Clean up `tailscale serve` on shutdown, logging any errors.
#[cfg(not(coverage))]
fn tailscale_serve_cleanup() {
    if let Err(e) = tailscale_serve_stop() {
        tracing::warn!("Failed to stop tailscale serve: {e}");
    }
}

/// Stub for coverage builds.
#[cfg(coverage)]
fn tailscale_serve_cleanup() {}

/// Stop `tailscale serve` and remove the HTTPS proxy rule.
#[cfg(not(coverage))]
fn tailscale_serve_stop() -> Result<()> {
    let output = std::process::Command::new("tailscale")
        .args(["serve", "--https=443", "off"])
        .output()
        .map_err(|e| anyhow::anyhow!("Failed to run `tailscale serve off`: {e}"))?;
    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        anyhow::bail!("tailscale serve off failed: {stderr}");
    }
    tracing::info!("tailscale serve stopped");
    Ok(())
}

/// Stub for coverage builds.
#[cfg(coverage)]
#[cfg_attr(coverage, allow(dead_code))]
fn tailscale_serve_stop() -> Result<()> {
    Ok(())
}

/// Resolve the Tailscale HTTPS hostname (e.g., `raven.tailnet-name.ts.net`).
#[cfg(not(coverage))]
fn resolve_tailscale_name() -> Result<String> {
    let output = std::process::Command::new("tailscale")
        .args(["status", "--json"])
        .output()
        .map_err(|e| anyhow::anyhow!("Failed to run `tailscale status`: {e}"))?;
    if !output.status.success() {
        anyhow::bail!("tailscale status failed");
    }
    let json: serde_json::Value = serde_json::from_slice(&output.stdout)?;
    let dns_name = json["Self"]["DNSName"]
        .as_str()
        .unwrap_or("")
        .trim_end_matches('.')
        .to_owned();
    if dns_name.is_empty() {
        anyhow::bail!("Could not resolve Tailscale DNS name");
    }
    Ok(dns_name)
}

/// Stub for coverage builds.
#[cfg(coverage)]
fn resolve_tailscale_name() -> Result<String> {
    Ok("test-node.tailnet.ts.net".into())
}

/// Build the MCP server from config — same init as `build_app` but returns `PulpoMcp`
/// instead of a router. No HTTP server, no tracing to stdout (would corrupt STDIO protocol).
pub async fn build_mcp_server(cli: &Cli) -> Result<mcp::PulpoMcp> {
    let mut config = config::load(&cli.config)?;

    // Resolve config path for saving later
    let expanded = shellexpand::tilde(&cli.config);
    let config_path = std::path::PathBuf::from(expanded.as_ref());

    // Auto-generate auth token on first run
    if config::ensure_auth_token(&mut config) {
        config::save(&config, &config_path)?;
    }

    let store = store::Store::new(&config.data_dir()).await?;
    store.migrate().await?;

    #[cfg(all(not(coverage), not(target_os = "windows")))]
    let backend: Arc<dyn backend::Backend> = Arc::new(backend::tmux::TmuxBackend::new());

    #[cfg(all(not(coverage), target_os = "windows"))]
    let backend: Arc<dyn backend::Backend> = Arc::new(WindowsStubBackend);

    #[cfg(coverage)]
    let backend: Arc<dyn backend::Backend> = Arc::new(CoverageBackend);

    let manager = session::manager::SessionManager::new(
        backend,
        store.clone(),
        config.inks.clone(),
        config.node.default_command.clone(),
    );
    let peer_registry = peers::PeerRegistry::new(&config.peers);

    Ok(mcp::PulpoMcp::new(manager, peer_registry, config))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_shutdown_handle_signals_loops() {
        let mut handle = ShutdownHandle::new();
        let (tx1, mut rx1) = watch::channel(false);
        let (tx2, mut rx2) = watch::channel(false);
        handle.add_sender(tx1);
        handle.add_sender(tx2);

        assert!(!*rx1.borrow());
        assert!(!*rx2.borrow());

        handle.shutdown();

        assert!(rx1.has_changed().unwrap());
        assert!(*rx1.borrow_and_update());
        assert!(rx2.has_changed().unwrap());
        assert!(*rx2.borrow_and_update());
    }

    #[test]
    fn test_shutdown_handle_empty() {
        let handle = ShutdownHandle::new();
        // Should not panic with no senders
        handle.shutdown();
    }

    #[test]
    fn test_shutdown_handle_dropped_receiver() {
        let mut handle = ShutdownHandle::new();
        let (tx, rx) = watch::channel(false);
        handle.add_sender(tx);
        drop(rx);
        // Should not panic when receiver is already dropped
        handle.shutdown();
    }

    #[tokio::test]
    async fn test_build_app_with_defaults() {
        let tmpdir = tempfile::tempdir().unwrap();
        let config_path = tmpdir.path().join("config.toml");

        // Write a config that uses a temp data dir
        let data_dir = tmpdir.path().join("data");
        std::fs::write(
            &config_path,
            format!(
                r#"
[node]
name = "test"
port = 0
data_dir = "{}"
"#,
                data_dir.display()
            ),
        )
        .unwrap();

        let cli = Cli {
            config: config_path.to_str().unwrap().into(),
            port: Some(0),
            command: None,
        };

        let (app, addr, handle) = build_app(&cli).await.unwrap();
        assert_eq!(addr, "127.0.0.1:0");
        // Verify app and handle can be used (doesn't panic)
        handle.shutdown();
        drop(app);

        // Token should have been auto-generated and saved
        let saved = config::load(config_path.to_str().unwrap()).unwrap();
        assert!(!saved.auth.token.is_empty());
        assert_eq!(saved.auth.token.len(), 43);
    }

    #[test]
    fn test_cli_version() {
        let result = Cli::try_parse_from(["pulpod", "--version"]);
        let err = result.unwrap_err();
        assert_eq!(err.kind(), clap::error::ErrorKind::DisplayVersion);
    }

    #[test]
    fn test_cli_parse() {
        // Test default parsing
        let cli = Cli::try_parse_from(["pulpod"]).unwrap();
        assert_eq!(cli.config, "~/.pulpo/config.toml");
        assert!(cli.port.is_none());
        assert!(cli.command.is_none());
    }

    #[test]
    fn test_cli_parse_with_args() {
        let cli =
            Cli::try_parse_from(["pulpod", "--config", "/custom/path", "--port", "8080"]).unwrap();
        assert_eq!(cli.config, "/custom/path");
        assert_eq!(cli.port, Some(8080));
        assert!(cli.command.is_none());
    }

    #[test]
    fn test_cli_parse_mcp_subcommand() {
        let cli = Cli::try_parse_from(["pulpod", "mcp"]).unwrap();
        assert_eq!(cli.command, Some(CliCommand::Mcp));
    }

    #[test]
    fn test_cli_parse_mcp_with_config() {
        let cli = Cli::try_parse_from(["pulpod", "--config", "/custom/path", "mcp"]).unwrap();
        assert_eq!(cli.config, "/custom/path");
        assert_eq!(cli.command, Some(CliCommand::Mcp));
    }

    #[test]
    fn test_cli_command_debug() {
        let cmd = CliCommand::Mcp;
        let debug = format!("{cmd:?}");
        assert!(debug.contains("Mcp"));
    }

    #[test]
    fn test_cli_command_clone() {
        let cmd = CliCommand::Mcp;
        #[allow(clippy::clone_on_copy)]
        let cloned = cmd.clone();
        assert_eq!(cmd, cloned);
    }

    #[test]
    fn test_init_tracing_console_only() {
        // Should not panic even if called multiple times (uses try_init)
        let result = init_tracing(None, 7);
        assert!(result.is_ok());
        assert!(result.unwrap().is_none());
    }

    #[test]
    fn test_init_tracing_with_log_dir() {
        let tmpdir = tempfile::tempdir().unwrap();
        let result = init_tracing(Some(tmpdir.path()), 7);
        assert!(result.is_ok());
        assert!(tmpdir.path().join("logs").is_dir());
    }

    #[test]
    fn test_init_tracing_degrades_on_bad_dir() {
        // Read-only path that can't be created — should fall back to console-only
        let result = init_tracing(Some(Path::new("/proc/nonexistent")), 7);
        assert!(result.is_ok());
        assert!(result.unwrap().is_none());
    }

    #[cfg(coverage)]
    #[test]
    fn test_coverage_backend_methods() {
        use crate::backend::Backend;
        let b = CoverageBackend;
        assert!(b.create_session("n", "d", "c").is_ok());
        assert!(b.kill_session("n").is_ok());
        assert!(b.is_alive("n").unwrap());
        assert!(b.capture_output("n", 10).unwrap().is_empty());
        assert!(b.send_input("n", "t").is_ok());
        assert!(b.setup_logging("n", "p").is_ok());
    }

    #[tokio::test]
    async fn test_build_app_uses_config_port() {
        let tmpdir = tempfile::tempdir().unwrap();
        let config_path = tmpdir.path().join("config.toml");

        let data_dir = tmpdir.path().join("data");
        std::fs::write(
            &config_path,
            format!(
                r#"
[node]
name = "test"
port = 9876
data_dir = "{}"
"#,
                data_dir.display()
            ),
        )
        .unwrap();

        // No port override — should use config's port
        let cli = Cli {
            config: config_path.to_str().unwrap().into(),
            port: None,
            command: None,
        };

        let (_app, addr, _handle) = build_app(&cli).await.unwrap();
        assert_eq!(addr, "127.0.0.1:9876");
    }

    #[tokio::test]
    async fn test_build_mcp_server() {
        let tmpdir = tempfile::tempdir().unwrap();
        let config_path = tmpdir.path().join("config.toml");
        let data_dir = tmpdir.path().join("data");
        std::fs::write(
            &config_path,
            format!(
                r#"
[node]
name = "mcp-test"
port = 0
data_dir = "{}"
"#,
                data_dir.display()
            ),
        )
        .unwrap();

        let cli = Cli {
            config: config_path.to_str().unwrap().into(),
            port: None,
            command: Some(CliCommand::Mcp),
        };

        let mcp = build_mcp_server(&cli).await.unwrap();
        let info = <mcp::PulpoMcp as rmcp::ServerHandler>::get_info(&mcp);
        assert_eq!(info.server_info.name, "pulpo");
    }

    #[tokio::test]
    async fn test_build_mcp_server_existing_token() {
        let tmpdir = tempfile::tempdir().unwrap();
        let config_path = tmpdir.path().join("config.toml");
        let data_dir = tmpdir.path().join("data");
        std::fs::write(
            &config_path,
            format!(
                r#"
[node]
name = "mcp-token-test"
port = 0
data_dir = "{}"

[auth]
token = "already-existing-token"
"#,
                data_dir.display()
            ),
        )
        .unwrap();

        let cli = Cli {
            config: config_path.to_str().unwrap().into(),
            port: None,
            command: Some(CliCommand::Mcp),
        };

        let mcp = build_mcp_server(&cli).await.unwrap();
        let info = <mcp::PulpoMcp as rmcp::ServerHandler>::get_info(&mcp);
        assert_eq!(info.server_info.name, "pulpo");

        // Token should NOT have been overwritten
        let saved = config::load(config_path.to_str().unwrap()).unwrap();
        assert_eq!(saved.auth.token, "already-existing-token");
    }

    #[tokio::test]
    async fn test_build_app_with_discord_notifications() {
        let tmpdir = tempfile::tempdir().unwrap();
        let config_path = tmpdir.path().join("config.toml");
        let data_dir = tmpdir.path().join("data");
        std::fs::write(
            &config_path,
            format!(
                r#"
[node]
name = "test"
port = 0
data_dir = "{}"

[notifications.discord]
webhook_url = "https://discord.com/api/webhooks/123/abc"
events = ["ready", "killed"]
"#,
                data_dir.display()
            ),
        )
        .unwrap();

        let cli = Cli {
            config: config_path.to_str().unwrap().into(),
            port: Some(0),
            command: None,
        };

        let (_app, addr, handle) = build_app(&cli).await.unwrap();
        assert_eq!(addr, "127.0.0.1:0");
        // Shutdown should signal the discord notification loop too
        handle.shutdown();
    }

    #[tokio::test]
    async fn test_build_app_generates_vapid_keys() {
        let tmpdir = tempfile::tempdir().unwrap();
        let config_path = tmpdir.path().join("config.toml");
        let data_dir = tmpdir.path().join("data");
        std::fs::write(
            &config_path,
            format!(
                r#"
[node]
name = "test"
port = 0
data_dir = "{}"
"#,
                data_dir.display()
            ),
        )
        .unwrap();

        let cli = Cli {
            config: config_path.to_str().unwrap().into(),
            port: Some(0),
            command: None,
        };

        let (_app, _addr, handle) = build_app(&cli).await.unwrap();

        // VAPID keys should have been auto-generated and saved
        let saved = config::load(config_path.to_str().unwrap()).unwrap();
        assert!(!saved.notifications.vapid.private_key.is_empty());
        assert!(!saved.notifications.vapid.public_key.is_empty());
        assert_eq!(saved.notifications.vapid.private_key.len(), 43);
        assert_eq!(saved.notifications.vapid.public_key.len(), 87);

        handle.shutdown();
    }

    #[tokio::test]
    async fn test_build_app_preserves_existing_vapid_keys() {
        let tmpdir = tempfile::tempdir().unwrap();
        let config_path = tmpdir.path().join("config.toml");
        let data_dir = tmpdir.path().join("data");
        std::fs::write(
            &config_path,
            format!(
                r#"
[node]
name = "test"
port = 0
data_dir = "{}"

[auth]
token = "existing-token"

[notifications.vapid]
private_key = "existing-priv"
public_key = "existing-pub"
"#,
                data_dir.display()
            ),
        )
        .unwrap();

        let cli = Cli {
            config: config_path.to_str().unwrap().into(),
            port: Some(0),
            command: None,
        };

        let (_app, _addr, handle) = build_app(&cli).await.unwrap();

        // Existing keys should be preserved
        let saved = config::load(config_path.to_str().unwrap()).unwrap();
        assert_eq!(saved.notifications.vapid.private_key, "existing-priv");
        assert_eq!(saved.notifications.vapid.public_key, "existing-pub");
        assert_eq!(saved.auth.token, "existing-token");

        handle.shutdown();
    }

    #[tokio::test]
    async fn test_build_app_bind_public() {
        let tmpdir = tempfile::tempdir().unwrap();
        let config_path = tmpdir.path().join("config.toml");
        let data_dir = tmpdir.path().join("data");
        std::fs::write(
            &config_path,
            format!(
                r#"
[node]
name = "test"
port = 0
data_dir = "{}"
bind = "public"

[auth]
token = "existing-token-value"
"#,
                data_dir.display()
            ),
        )
        .unwrap();

        let cli = Cli {
            config: config_path.to_str().unwrap().into(),
            port: Some(0),
            command: None,
        };
        let (_app, addr, _handle) = build_app(&cli).await.unwrap();
        assert_eq!(addr, "0.0.0.0:0");

        // Existing token should be preserved
        let saved = config::load(config_path.to_str().unwrap()).unwrap();
        assert_eq!(saved.auth.token, "existing-token-value");
    }

    #[tokio::test]
    async fn test_build_app_bind_container() {
        let tmpdir = tempfile::tempdir().unwrap();
        let config_path = tmpdir.path().join("config.toml");
        let data_dir = tmpdir.path().join("data");
        std::fs::write(
            &config_path,
            format!(
                r#"
[node]
name = "test"
port = 0
data_dir = "{}"
bind = "container"
"#,
                data_dir.display()
            ),
        )
        .unwrap();

        let cli = Cli {
            config: config_path.to_str().unwrap().into(),
            port: Some(0),
            command: None,
        };
        let (_app, addr, _handle) = build_app(&cli).await.unwrap();
        assert_eq!(addr, "0.0.0.0:0");
    }

    #[cfg(coverage)]
    #[tokio::test]
    async fn test_build_app_bind_tailscale() {
        let tmpdir = tempfile::tempdir().unwrap();
        let config_path = tmpdir.path().join("config.toml");
        let data_dir = tmpdir.path().join("data");
        std::fs::write(
            &config_path,
            format!(
                r#"
[node]
name = "test"
port = 0
data_dir = "{}"
bind = "tailscale"
tag = "pulpo"
discovery_interval_secs = 60
"#,
                data_dir.display()
            ),
        )
        .unwrap();

        let cli = Cli {
            config: config_path.to_str().unwrap().into(),
            port: Some(0),
            command: None,
        };
        let (_app, addr, handle) = build_app(&cli).await.unwrap();
        // Tailscale bind uses 127.0.0.1 (tailscale serve proxies over HTTPS)
        assert_eq!(addr, "127.0.0.1:0");
        assert!(handle.tailscale_serve_active);
        handle.shutdown();
    }

    #[tokio::test]
    async fn test_build_app_bind_public_with_seed() {
        let tmpdir = tempfile::tempdir().unwrap();
        let config_path = tmpdir.path().join("config.toml");
        let data_dir = tmpdir.path().join("data");
        std::fs::write(
            &config_path,
            format!(
                r#"
[node]
name = "test"
port = 0
data_dir = "{}"
bind = "public"
seed = "10.0.0.5:7433"
"#,
                data_dir.display()
            ),
        )
        .unwrap();

        let cli = Cli {
            config: config_path.to_str().unwrap().into(),
            port: Some(0),
            command: None,
        };
        let (_app, addr, handle) = build_app(&cli).await.unwrap();
        assert_eq!(addr, "0.0.0.0:0");
        handle.shutdown();
    }

    #[tokio::test]
    async fn test_build_app_bind_public_mdns() {
        let tmpdir = tempfile::tempdir().unwrap();
        let config_path = tmpdir.path().join("config.toml");
        let data_dir = tmpdir.path().join("data");
        std::fs::write(
            &config_path,
            format!(
                r#"
[node]
name = "test"
port = 0
data_dir = "{}"
bind = "public"
"#,
                data_dir.display()
            ),
        )
        .unwrap();

        let cli = Cli {
            config: config_path.to_str().unwrap().into(),
            port: Some(0),
            command: None,
        };
        let (_app, addr, handle) = build_app(&cli).await.unwrap();
        assert_eq!(addr, "0.0.0.0:0");
        handle.shutdown();
    }

    #[test]
    fn test_shutdown_handle_tailscale_serve_cleanup() {
        let mut handle = ShutdownHandle::new();
        assert!(!handle.tailscale_serve_active);
        handle.tailscale_serve_active = true;
        // Should not panic — coverage stub is a no-op
        handle.shutdown();
    }

    #[cfg(coverage)]
    #[test]
    fn test_tailscale_serve_stubs() {
        assert!(tailscale_serve_start(7433).is_ok());
        assert!(tailscale_serve_stop().is_ok());
        tailscale_serve_cleanup();
        assert_eq!(
            resolve_tailscale_name().unwrap(),
            "test-node.tailnet.ts.net"
        );
    }

    #[cfg(coverage)]
    #[test]
    fn test_coverage_backend_session_id() {
        use backend::Backend;
        let b = CoverageBackend;
        assert_eq!(b.session_id("my-session"), "my-session");
    }

    #[tokio::test]
    async fn test_build_app_with_webhooks() {
        let tmpdir = tempfile::tempdir().unwrap();
        let config_path = tmpdir.path().join("config.toml");
        let data_dir = tmpdir.path().join("data");
        std::fs::write(
            &config_path,
            format!(
                r#"
[node]
name = "test"
port = 0
data_dir = "{}"

[[notifications.webhooks]]
name = "test-hook"
url = "http://127.0.0.1:1/hook"
events = ["killed"]
"#,
                data_dir.display()
            ),
        )
        .unwrap();

        let cli = Cli {
            config: config_path.to_str().unwrap().into(),
            port: Some(0),
            command: None,
        };
        let (_app, addr, handle) = build_app(&cli).await.unwrap();
        assert_eq!(addr, "127.0.0.1:0");
        handle.shutdown();
    }
}