episteme 0.3.1

Knowledge graph for software engineering — design patterns, refactorings, and laws for AI agents
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
//! Daemon management: start / stop / status helpers for MCP HTTP and API servers.
//!
//! Ported from Python `cli/service.py`. Supports dual PID files via
//! [`ServiceKind`] and cross-platform OS service registration (macOS launchd,
//! Linux systemd).

use std::fs;
#[cfg(any(target_os = "macos", target_os = "linux"))]
use std::path::PathBuf;
use std::process::{Command, Stdio};
use std::time::{Duration, Instant};

use crate::adapters::paths;

// ---------------------------------------------------------------------------
// ServiceKind
// ---------------------------------------------------------------------------

/// Discriminates between the two background daemon types Episteme manages.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ServiceKind {
    Mcp,
    Api,
}

/// Return the PID file path for the given service kind.
pub fn pid_file_for(kind: ServiceKind) -> PathBuf {
    let name = match kind {
        ServiceKind::Mcp => "mcp.pid",
        ServiceKind::Api => "api.pid",
    };
    paths::episteme_home().join(name)
}

// ---------------------------------------------------------------------------
// PID file helpers (ServiceKind-aware)
// ---------------------------------------------------------------------------

/// Read the PID from the kind-specific PID file, if present and valid.
pub fn read_pid_for(kind: ServiceKind) -> Option<u32> {
    let path = pid_file_for(kind);
    fs::read_to_string(&path)
        .ok()
        .and_then(|s| s.trim().parse().ok())
}

/// Write `pid` to the kind-specific PID file.
pub fn write_pid_for(kind: ServiceKind, pid: u32) -> std::io::Result<()> {
    let path = pid_file_for(kind);
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent)?;
    }
    fs::write(path, pid.to_string())
}

/// Remove the kind-specific PID file (idempotent).
pub fn clear_pid_for(kind: ServiceKind) -> std::io::Result<()> {
    let path = pid_file_for(kind);
    if path.exists() {
        fs::remove_file(path)
    } else {
        Ok(())
    }
}

// ---------------------------------------------------------------------------
// PID file helpers (backward-compat wrappers defaulting to Mcp)
// ---------------------------------------------------------------------------

/// Read the PID from the MCP PID file. Backward-compatible wrapper.
pub fn read_pid() -> Option<u32> {
    read_pid_for(ServiceKind::Mcp)
}

/// Write `pid` to the MCP PID file. Backward-compatible wrapper.
pub fn write_pid(pid: u32) -> std::io::Result<()> {
    write_pid_for(ServiceKind::Mcp, pid)
}

/// Remove the MCP PID file. Backward-compatible wrapper.
pub fn clear_pid() -> std::io::Result<()> {
    clear_pid_for(ServiceKind::Mcp)
}

// ---------------------------------------------------------------------------
// Process helpers
// ---------------------------------------------------------------------------

/// Check whether a process with the given PID is still alive.
///
/// On non-Unix targets this always returns `false`.
pub fn is_running(pid: u32) -> bool {
    #[cfg(unix)]
    {
        // SAFETY: `kill` with signal 0 performs no action; it only checks
        // process existence and permissions. No state is mutated.
        unsafe { libc::kill(pid as libc::pid_t, 0) == 0 }
    }
    #[cfg(not(unix))]
    {
        let _ = pid;
        false
    }
}

/// Find the PID of the process listening on `port` using `lsof`.
pub fn find_pid_by_port(port: u16) -> Option<u32> {
    let output = Command::new("lsof")
        .args(["-ti", &format!(":{port}")])
        .output()
        .ok()?;
    if output.status.success() {
        String::from_utf8_lossy(&output.stdout).trim().parse().ok()
    } else {
        None
    }
}

// ---------------------------------------------------------------------------
// Port helpers
// ---------------------------------------------------------------------------

/// Returns `true` when something is listening on `127.0.0.1:port`.
///
/// Uses a TCP connect rather than a bind attempt: on macOS, binding
/// `127.0.0.1:PORT` succeeds even when a server holds `0.0.0.0:PORT`,
/// so the bind approach produces false negatives.
pub fn is_port_in_use(port: u16) -> bool {
    std::net::TcpStream::connect(("127.0.0.1", port)).is_ok()
}

/// Poll until the port is free, up to `timeout_secs`.
/// Returns `true` if the port became free within the deadline.
pub fn wait_port_free(port: u16, timeout_secs: u64) -> bool {
    let start = Instant::now();
    let deadline = Duration::from_secs(timeout_secs);
    while start.elapsed() < deadline {
        if !is_port_in_use(port) {
            return true;
        }
        std::thread::sleep(Duration::from_millis(200));
    }
    false
}

/// Poll until something is listening on `port`, up to `timeout_secs`.
/// Returns `true` if the port came up within the deadline.
pub fn wait_port_open(port: u16, timeout_secs: u64) -> bool {
    let start = Instant::now();
    let deadline = Duration::from_secs(timeout_secs);
    while start.elapsed() < deadline {
        if is_port_in_use(port) {
            return true;
        }
        std::thread::sleep(Duration::from_millis(200));
    }
    false
}

// ---------------------------------------------------------------------------
// Config helpers per ServiceKind
// ---------------------------------------------------------------------------

/// Resolve the configured host and port for the given service kind.
/// Loads config once.
fn get_host_port(kind: ServiceKind) -> (String, u16) {
    let cfg = crate::adapters::config::EpistemeConfig::load().ok();
    match kind {
        ServiceKind::Mcp => {
            let host = cfg
                .as_ref()
                .map(|c| c.mcp_host.clone())
                .unwrap_or_else(|| "127.0.0.1".to_owned());
            let port = cfg.as_ref().map(|c| c.mcp_port).unwrap_or(43175);
            (host, port)
        }
        ServiceKind::Api => {
            let host = cfg
                .as_ref()
                .map(|c| c.api_host.clone())
                .unwrap_or_else(|| "0.0.0.0".to_owned());
            let port = cfg.as_ref().map(|c| c.api_port).unwrap_or(58302);
            (host, port)
        }
    }
}

/// Resolve the configured port for the given service kind.
fn get_port(kind: ServiceKind) -> u16 {
    get_host_port(kind).1
}

/// Resolve the configured access token/key for the given service kind.
fn get_token(kind: ServiceKind) -> Option<String> {
    let cfg = crate::adapters::config::EpistemeConfig::load().ok()?;
    match kind {
        ServiceKind::Mcp => {
            if cfg.mcp_token.is_empty() {
                None
            } else {
                Some(cfg.mcp_token)
            }
        }
        ServiceKind::Api => {
            if cfg.api_keys.is_empty() {
                None
            } else {
                Some(cfg.api_keys)
            }
        }
    }
}

/// Return a human-readable label for the service kind.
pub fn kind_label(kind: ServiceKind) -> &'static str {
    match kind {
        ServiceKind::Mcp => "MCP",
        ServiceKind::Api => "API",
    }
}

// ---------------------------------------------------------------------------
// High-level service commands (ServiceKind-aware)
// ---------------------------------------------------------------------------

/// Spawn the server in the background for the given `kind`.
///
/// Outcome of a start attempt: newly spawned, or already running.
pub enum StartOutcome {
    Started(u32),
    AlreadyRunning(u32),
}

/// Spawn the server in the background for the given `kind`.
///
/// Returns [`StartOutcome::Started`] with the child PID on success, or
/// [`StartOutcome::AlreadyRunning`] when our own server is still listening.
pub fn cmd_start(kind: ServiceKind, host: &str, port: u16) -> Result<StartOutcome, String> {
    if is_port_in_use(port) {
        if let Some(existing) = find_pid_by_port(port) {
            let expected = read_pid_for(kind);
            if expected.is_some_and(|p| p == existing) && is_running(existing) {
                return Ok(StartOutcome::AlreadyRunning(existing));
            }
            return Err(format!("Port {port} is already in use (PID {existing})"));
        }
        return Err(format!("Port {port} is already in use"));
    }

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

    let log_dir = paths::log_dir();
    fs::create_dir_all(&log_dir).map_err(|e| format!("cannot create log dir: {e}"))?;

    let (log_name, err_name) = match kind {
        ServiceKind::Mcp => ("mcp.log", "mcp.err"),
        ServiceKind::Api => ("api.log", "api.err"),
    };
    let stdout_path = log_dir.join(log_name);
    let stderr_path = log_dir.join(err_name);

    let stdout = fs::File::create(&stdout_path)
        .map_err(|e| format!("cannot create {}: {e}", stdout_path.display()))?;
    let stderr = fs::File::create(&stderr_path)
        .map_err(|e| format!("cannot create {}: {e}", stderr_path.display()))?;

    let args: Vec<String> = match kind {
        ServiceKind::Mcp => vec![
            "mcp".into(),
            "serve".into(),
            "--host".into(),
            host.into(),
            "--port".into(),
            port.to_string(),
        ],
        ServiceKind::Api => vec![
            "api".into(),
            "serve".into(),
            "--host".into(),
            host.into(),
            "--port".into(),
            port.to_string(),
        ],
    };

    let child = Command::new(&exe)
        .args(&args)
        .stdout(Stdio::from(stdout))
        .stderr(Stdio::from(stderr))
        .spawn()
        .map_err(|e| format!("failed to spawn server: {e}"))?;

    let pid = child.id();
    write_pid_for(kind, pid).map_err(|e| format!("failed to write PID file: {e}"))?;

    if wait_port_open(port, 10) {
        Ok(StartOutcome::Started(pid))
    } else {
        // Best-effort cleanup.
        let _ = clear_pid_for(kind);
        Err("Server failed to start within 10 seconds".to_owned())
    }
}

/// Stop the running server for the given `kind` (SIGTERM, then SIGKILL on timeout).
///
/// When a launchd agent is loaded for this service kind, unloads it first so that
/// macOS does not immediately re-spawn the process.
///
/// Works even without a PID file by discovering the process via the port it binds.
pub fn cmd_stop(kind: ServiceKind) -> Result<(), String> {
    let port = get_port(kind);

    // Unload launchd agent first to prevent immediate re-spawn.
    #[cfg(target_os = "macos")]
    {
        let label = launch_agent_label(kind);
        let loaded = Command::new("launchctl")
            .args(["list", label])
            .output()
            .map(|o| o.status.success())
            .unwrap_or(false);
        if loaded {
            let uid = Command::new("id")
                .arg("-u")
                .output()
                .ok()
                .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_owned())
                .unwrap_or_default();
            let _ = Command::new("launchctl")
                .args(["bootout", &format!("gui/{uid}/{label}")])
                .status();
        }
    }

    // Resolve PID: prefer PID file, fall back to port-based discovery.
    let pid = match read_pid_for(kind) {
        Some(p) => p,
        None => match find_pid_by_port(port) {
            Some(p) => p,
            None => {
                // Nothing running — just clean up stale PID file.
                clear_pid_for(kind).ok();
                return Ok(());
            }
        },
    };

    if !is_running(pid) {
        clear_pid_for(kind).ok();
        return Ok(());
    }

    // Graceful SIGTERM.
    #[cfg(unix)]
    {
        // SAFETY: Sending SIGTERM is a standard POSIX signal delivery. The
        // kernel validates `pid`; no memory-safety invariants are violated.
        unsafe {
            libc::kill(pid as libc::pid_t, libc::SIGTERM);
        }
    }
    #[cfg(not(unix))]
    {
        // On non-Unix, try to kill via the OS command.
        let _ = Command::new("kill").arg(pid.to_string()).output();
    }

    if wait_port_free(port, 5) {
        clear_pid_for(kind).ok();
        return Ok(());
    }

    // Force SIGKILL.
    #[cfg(unix)]
    {
        // SAFETY: SIGKILL is immediate process termination. Same reasoning as
        // SIGTERM above.
        unsafe {
            libc::kill(pid as libc::pid_t, libc::SIGKILL);
        }
    }
    #[cfg(windows)]
    {
        let _ = Command::new("taskkill")
            .args(["/F", "/PID", &pid.to_string()])
            .output();
    }
    #[cfg(all(not(unix), not(windows)))]
    {
        let _ = Command::new("kill").args(["-9", &pid.to_string()]).output();
    }

    // Give it a moment, then clean up PID file regardless.
    std::thread::sleep(Duration::from_millis(500));
    clear_pid_for(kind).ok();
    Ok(())
}

/// Print a human-readable status line for `kind` and return `true` if up.
pub fn cmd_status(kind: ServiceKind) -> bool {
    let port = get_port(kind);
    let label = kind_label(kind);

    match read_pid_for(kind) {
        Some(pid) => {
            if is_running(pid) {
                let port_status = if is_port_in_use(port) {
                    format!("listening on port {port}")
                } else {
                    format!("not yet listening on port {port}")
                };
                println!("{label} server is running (PID {pid}, {port_status})");
                true
            } else {
                println!("{label} server is NOT running (stale PID {pid})");
                clear_pid_for(kind).ok();
                false
            }
        }
        None => {
            // No PID file -- but maybe the server is running from another source.
            if is_port_in_use(port)
                && let Some(pid) = find_pid_by_port(port)
            {
                println!(
                    "{label} server appears to be running (PID {pid} on port {port}), but no PID file"
                );
                return true;
            }
            println!("{label} server is stopped");
            false
        }
    }
}

// ---------------------------------------------------------------------------
// Backward-compat wrappers (no ServiceKind arg)
// ---------------------------------------------------------------------------

/// Spawn the MCP HTTP server in the background. Backward-compatible wrapper.
pub fn cmd_start_mcp(host: &str, port: u16) -> Result<u32, String> {
    match cmd_start(ServiceKind::Mcp, host, port)? {
        StartOutcome::Started(pid) | StartOutcome::AlreadyRunning(pid) => Ok(pid),
    }
}

/// Stop the running MCP server. Backward-compatible wrapper.
pub fn cmd_stop_mcp() -> Result<(), String> {
    cmd_stop(ServiceKind::Mcp)
}

/// Print MCP status. Backward-compatible wrapper.
pub fn cmd_status_mcp() -> bool {
    cmd_status(ServiceKind::Mcp)
}

// ---------------------------------------------------------------------------
// macOS launchd integration
// ---------------------------------------------------------------------------

#[cfg(target_os = "macos")]
fn launch_agent_label(kind: ServiceKind) -> &'static str {
    match kind {
        ServiceKind::Mcp => "io.episteme.mcp",
        ServiceKind::Api => "io.episteme.api",
    }
}

#[cfg(target_os = "macos")]
fn launch_agent_plist_path(kind: ServiceKind) -> PathBuf {
    let home = paths::episteme_home()
        .parent()
        .map(PathBuf::from)
        .unwrap_or_else(|| PathBuf::from("/tmp"));
    home.join("Library")
        .join("LaunchAgents")
        .join(format!("{}.plist", launch_agent_label(kind)))
}

/// Install a launchd plist for the given service kind (macOS only).
pub fn install_launchd_agent_for(
    kind: ServiceKind,
    host: &str,
    port: u16,
    token: Option<&str>,
) -> Result<String, String> {
    validate_host_port(host, port)?;
    #[cfg(not(target_os = "macos"))]
    {
        let _ = (kind, host, port, token);
        Err("launchd integration is only supported on macOS".to_owned())
    }
    #[cfg(target_os = "macos")]
    {
        let exe = std::env::current_exe().map_err(|e| e.to_string())?;
        let plist_path = launch_agent_plist_path(kind);
        if let Some(parent) = plist_path.parent() {
            fs::create_dir_all(parent).map_err(|e| e.to_string())?;
        }

        let label = launch_agent_label(kind);
        let (log_name, err_name) = match kind {
            ServiceKind::Mcp => ("launchd-mcp.log", "launchd-mcp.err"),
            ServiceKind::Api => ("launchd-api.log", "launchd-api.err"),
        };
        let log_dir = paths::log_dir();
        let stdout_log = log_dir.join(log_name);
        let stderr_log = log_dir.join(err_name);

        let exec_args = match kind {
            ServiceKind::Mcp => format!(
                r#"<string>{exe}</string>
    <string>mcp</string>
    <string>serve</string>
    <string>--host</string>
    <string>{host}</string>
    <string>--port</string>
    <string>{port}</string>"#,
                exe = exe.display(),
            ),
            ServiceKind::Api => format!(
                r#"<string>{exe}</string>
    <string>api</string>
    <string>serve</string>
    <string>--host</string>
    <string>{host}</string>
    <string>--port</string>
    <string>{port}</string>"#,
                exe = exe.display(),
            ),
        };

        let env_key = match kind {
            ServiceKind::Mcp => "EPISTEME_MCP_TOKEN",
            ServiceKind::Api => "EPISTEME_API_KEYS",
        };
        let env_vars_section = match token {
            Some(t) => format!(
                r#"  <key>EnvironmentVariables</key>
  <dict>
    <key>{env_key}</key>
    <string>{t}</string>
  </dict>
"#
            ),
            None => String::new(),
        };

        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>{label}</string>
  <key>ProgramArguments</key>
  <array>
    {exec_args}
  </array>
  <key>RunAtLoad</key><true/>
  <key>KeepAlive</key><true/>
  {env_vars_section}<key>StandardOutPath</key><string>{stdout}</string>
  <key>StandardErrorPath</key><string>{stderr}</string>
</dict>
</plist>"#,
            label = label,
            stdout = stdout_log.display(),
            stderr = stderr_log.display(),
        );
        let uid = Command::new("id")
            .arg("-u")
            .output()
            .ok()
            .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_owned())
            .unwrap_or_else(|| "501".to_owned());

        // Check if the agent is already loaded — if so, bootout first so we can
        // re-bootstrap with the updated plist.
        let already_loaded = Command::new("launchctl")
            .args(["list", label])
            .output()
            .map(|o| o.status.success())
            .unwrap_or(false);

        if already_loaded {
            let _ = Command::new("launchctl")
                .args(["bootout", &format!("gui/{uid}/{label}")])
                .status();
        }

        fs::write(&plist_path, plist).map_err(|e| e.to_string())?;

        let st = Command::new("launchctl")
            .args([
                "bootstrap",
                &format!("gui/{uid}"),
                plist_path.to_string_lossy().as_ref(),
            ])
            .status()
            .map_err(|e| e.to_string())?;
        if !st.success() {
            return Err("failed to bootstrap launchd agent".to_owned());
        }

        if already_loaded {
            Ok(format!(
                "{kind} launchd agent reloaded: {path}",
                kind = kind_label(kind),
                path = plist_path.display(),
            ))
        } else {
            Ok(format!(
                "{kind} launchd agent installed: {path}",
                kind = kind_label(kind),
                path = plist_path.display(),
            ))
        }
    }
}

/// Uninstall the launchd plist for the given service kind (macOS only).
pub fn uninstall_launchd_agent_for(kind: ServiceKind) -> Result<String, String> {
    #[cfg(not(target_os = "macos"))]
    {
        let _ = kind;
        Err("launchd integration is only supported on macOS".to_owned())
    }
    #[cfg(target_os = "macos")]
    {
        let plist_path = launch_agent_plist_path(kind);
        let uid = Command::new("id")
            .arg("-u")
            .output()
            .ok()
            .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_owned())
            .unwrap_or_default();
        let _ = Command::new("launchctl")
            .args([
                "bootout",
                &format!("gui/{uid}"),
                plist_path.to_string_lossy().as_ref(),
            ])
            .status();
        if plist_path.exists() {
            fs::remove_file(&plist_path).map_err(|e| e.to_string())?;
        }
        Ok(format!(
            "{kind} launchd agent removed: {path}",
            kind = kind_label(kind),
            path = plist_path.display(),
        ))
    }
}

/// Return the launchd status for the given service kind (macOS only).
pub fn launchd_status_for(kind: ServiceKind) -> Result<String, String> {
    #[cfg(not(target_os = "macos"))]
    {
        let _ = kind;
        Err("launchd integration is only supported on macOS".to_owned())
    }
    #[cfg(target_os = "macos")]
    {
        let label = launch_agent_label(kind);
        let output = Command::new("launchctl")
            .args(["list", label])
            .output()
            .map_err(|e| e.to_string())?;
        if output.status.success() {
            Ok(format!(
                "{kind} launchd active: {detail}",
                kind = kind_label(kind),
                detail = String::from_utf8_lossy(&output.stdout).trim(),
            ))
        } else {
            Ok(format!(
                "{kind} launchd agent not loaded",
                kind = kind_label(kind),
            ))
        }
    }
}

// ---------------------------------------------------------------------------
// macOS launchd backward-compat wrappers (default to Mcp)
// ---------------------------------------------------------------------------

/// Install the MCP launchd agent. Backward-compatible wrapper.
pub fn install_launchd_agent(host: &str, port: u16) -> Result<String, String> {
    install_launchd_agent_for(ServiceKind::Mcp, host, port, None)
}

/// Uninstall the MCP launchd agent. Backward-compatible wrapper.
pub fn uninstall_launchd_agent() -> Result<String, String> {
    uninstall_launchd_agent_for(ServiceKind::Mcp)
}

/// Return MCP launchd status. Backward-compatible wrapper.
pub fn launchd_status() -> Result<String, String> {
    launchd_status_for(ServiceKind::Mcp)
}

/// Enable the MCP launchd agent. Backward-compatible wrapper.
pub fn enable_launchd(now: bool) -> Result<String, String> {
    enable_service(ServiceKind::Mcp, now)
}

/// Disable the MCP launchd agent. Backward-compatible wrapper.
pub fn disable_launchd(now: bool) -> Result<String, String> {
    disable_service(ServiceKind::Mcp, now)
}

// ---------------------------------------------------------------------------
// Linux systemd integration
// ---------------------------------------------------------------------------

#[cfg(target_os = "linux")]
fn systemd_unit_path(kind: ServiceKind) -> Result<PathBuf, String> {
    let home = std::env::var("HOME").map_err(|_| {
        "HOME environment variable not set; cannot determine systemd user unit path".to_owned()
    })?;
    Ok(PathBuf::from(home)
        .join(".config")
        .join("systemd")
        .join("user")
        .join(format!("{}.service", systemd_unit_label(kind))))
}

#[cfg(target_os = "linux")]
fn systemd_unit_label(kind: ServiceKind) -> &'static str {
    match kind {
        ServiceKind::Mcp => "episteme-mcp",
        ServiceKind::Api => "episteme-api",
    }
}

/// Install a systemd user unit for the given service kind (Linux only).
#[cfg(target_os = "linux")]
pub fn install_systemd_unit(
    kind: ServiceKind,
    host: &str,
    port: u16,
    token: Option<&str>,
) -> Result<String, String> {
    validate_host_port(host, port)?;
    let exe = std::env::current_exe().map_err(|e| e.to_string())?;
    let unit_path = systemd_unit_path(kind)?;
    if let Some(parent) = unit_path.parent() {
        fs::create_dir_all(parent).map_err(|e| e.to_string())?;
    }

    let cmd = match kind {
        ServiceKind::Mcp => "mcp",
        ServiceKind::Api => "api",
    };

    let log_dir = paths::log_dir();
    let stdout_log = log_dir.join(format!("systemd-{}.log", cmd));
    let stderr_log = log_dir.join(format!("systemd-{}.err", cmd));

    // Ensure log directory exists.
    fs::create_dir_all(&log_dir).map_err(|e| e.to_string())?;

    let description = kind_label(kind);

    let env_line = match token {
        Some(t) => format!("Environment=\"EPISTEME_MCP_TOKEN={t}\"\n"),
        None => String::new(),
    };

    let unit = format!(
        "[Unit]\n\
Description=Episteme {description} Server\n\
After=network.target\n\
\n\
[Service]\n\
Type=simple\n\
ExecStart=\"{exe}\" {cmd} serve --host \"{host}\" --port {port}\n\
{env_line}Restart=on-failure\n\
RestartSec=5\n\
StandardOutput=append:{stdout}\n\
StandardError=append:{stderr}\n\
\n\
[Install]\n\
WantedBy=default.target\n",
        exe = exe.display(),
        cmd = cmd,
        host = host,
        port = port,
        env_line = env_line,
        stdout = stdout_log.display(),
        stderr = stderr_log.display(),
    );

    fs::write(&unit_path, unit).map_err(|e| e.to_string())?;

    // Reload systemd user daemon.
    let reload_st = Command::new("systemctl")
        .args(["--user", "daemon-reload"])
        .status()
        .map_err(|e| format!("failed to run systemctl daemon-reload: {e}"))?;
    if !reload_st.success() {
        return Err("systemctl --user daemon-reload failed".to_owned());
    }

    // Enable the unit so it starts automatically on login.
    let label = systemd_unit_label(kind);
    let enable_st = Command::new("systemctl")
        .args(["--user", "enable", &format!("{label}.service")])
        .status()
        .map_err(|e| format!("failed to enable systemd unit: {e}"))?;
    if !enable_st.success() {
        return Err(format!("failed to enable {label}.service"));
    }

    Ok(format!(
        "{kind} systemd unit installed: {path}",
        kind = kind_label(kind),
        path = unit_path.display(),
    ))
}

/// Uninstall the systemd user unit for the given service kind (Linux only).
#[cfg(target_os = "linux")]
pub fn uninstall_systemd_unit(kind: ServiceKind) -> Result<String, String> {
    let label = systemd_unit_label(kind);
    let _ = Command::new("systemctl")
        .args(["--user", "stop", &format!("{label}.service")])
        .status();
    let _ = Command::new("systemctl")
        .args(["--user", "disable", &format!("{label}.service")])
        .status();

    let unit_path = systemd_unit_path(kind)?;
    if unit_path.exists() {
        fs::remove_file(&unit_path).map_err(|e| e.to_string())?;
    }

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

    Ok(format!(
        "{kind} systemd unit removed: {path}",
        kind = kind_label(kind),
        path = unit_path.display(),
    ))
}

// Stubs for non-Linux targets so callers can compile unconditionally.
#[cfg(not(target_os = "linux"))]
pub fn install_systemd_unit(
    kind: ServiceKind,
    host: &str,
    port: u16,
    token: Option<&str>,
) -> Result<String, String> {
    let _ = (kind, host, port, token);
    Err("systemd integration is only supported on Linux".to_owned())
}

#[cfg(not(target_os = "linux"))]
pub fn uninstall_systemd_unit(kind: ServiceKind) -> Result<String, String> {
    let _ = kind;
    Err("systemd integration is only supported on Linux".to_owned())
}

// ---------------------------------------------------------------------------
// Cross-platform enable / disable
// ---------------------------------------------------------------------------

/// Validate host and port for security and correctness.
fn validate_host_port(host: &str, port: u16) -> Result<(), String> {
    if host.contains(|c: char| !c.is_alphanumeric() && c != '.' && c != ':' && c != '-') {
        return Err(format!("invalid host: {}", host));
    }
    if port == 0 {
        return Err("port cannot be 0".to_owned());
    }
    Ok(())
}

/// Enable (install OS service unit and optionally start) the given service.
pub fn enable_service(kind: ServiceKind, now: bool) -> Result<String, String> {
    let (host, port) = get_host_port(kind);
    let token = get_token(kind);
    validate_host_port(&host, port)?;

    let mut msg = String::new();

    #[cfg(target_os = "macos")]
    {
        let install_msg = install_launchd_agent_for(kind, &host, port, token.as_deref())?;
        msg.push_str(&install_msg);
    }
    #[cfg(target_os = "linux")]
    {
        let install_msg = install_systemd_unit(kind, &host, port, token.as_deref())?;
        msg.push_str(&install_msg);
    }
    #[cfg(not(any(target_os = "macos", target_os = "linux")))]
    {
        msg.push_str("OS service registration (persistence) is not supported on this platform.");
    }

    if now {
        // On macOS, launchctl bootstrap (called inside install_launchd_agent_for) already
        // starts the daemon via RunAtLoad. Calling cmd_stop + cmd_start on top of that
        // creates a race: cmd_stop unloads the agent, launchd KeepAlive re-spawns it, and
        // cmd_start spawns a second process — both compete for the same port.
        // Instead, just wait for launchd to bring the port up.
        #[cfg(target_os = "macos")]
        {
            let label = kind_label(kind);
            if wait_port_open(port, 10) {
                let pid = find_pid_by_port(port).unwrap_or(0);
                let _ = write_pid_for(kind, pid);
                msg.push_str(&format!("\n{label} started via launchd (PID {pid})"));
            } else {
                return Err(format!(
                    "{label} launchd agent registered but server did not open port {port} within 10 seconds. \
                     Check logs: ~/.episteme/logs/launchd-api.err"
                ));
            }
        }
        // On Linux / other platforms there is no service manager yet — fall back to direct spawn.
        #[cfg(not(target_os = "macos"))]
        {
            let label = kind_label(kind);
            match cmd_start(kind, &host, port) {
                Ok(StartOutcome::Started(pid)) => {
                    msg.push_str(&format!("\n{label} started (PID {pid})"));
                }
                Ok(StartOutcome::AlreadyRunning(pid)) => {
                    msg.push_str(&format!("\n{label} already running (PID {pid})"));
                }
                Err(e) => return Err(e),
            }
        }
    }
    Ok(msg)
}

/// Disable (stop and uninstall OS service unit) the given service.
pub fn disable_service(kind: ServiceKind, now: bool) -> Result<String, String> {
    let mut msg = String::new();
    if now {
        let _ = cmd_stop(kind);
        msg.push_str(&format!("{} stopped.\n", kind_label(kind)));
    }

    #[cfg(target_os = "macos")]
    {
        let uninstall_msg = uninstall_launchd_agent_for(kind)?;
        msg.push_str(&uninstall_msg);
    }
    #[cfg(target_os = "linux")]
    {
        let uninstall_msg = uninstall_systemd_unit(kind)?;
        msg.push_str(&uninstall_msg);
    }

    Ok(msg)
}