second-brain-cli 0.13.4

Memory layer for AI coding agents: ingest, recall, and sync across machines
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
use std::ffi::OsString;
use std::net::{SocketAddr, TcpStream};
use std::os::unix::fs::PermissionsExt;
use std::path::{Path, PathBuf};
use std::process::{Command, Output};
use std::time::Duration;

use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};

use crate::launchd;

pub const DEFAULT_UNIT: &str = "second-brain.service";
pub const DEFAULT_BIND: &str = "127.0.0.1:7200";

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Manager {
    Systemd,
    Launchd,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Os {
    Linux,
    MacOs,
}

impl Os {
    pub fn current() -> Self {
        if cfg!(target_os = "macos") {
            Os::MacOs
        } else {
            Os::Linux
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Action {
    Start,
    Stop,
    Restart,
}

impl Action {
    fn as_str(self) -> &'static str {
        match self {
            Action::Start => "start",
            Action::Stop => "stop",
            Action::Restart => "restart",
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Scope {
    User,
    System,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ServiceRecord {
    pub manager: Manager,
    pub unit: String,
    pub scope: Scope,
}

impl ServiceRecord {
    pub fn user_default() -> Self {
        Self {
            manager: Manager::Systemd,
            unit: DEFAULT_UNIT.to_string(),
            scope: Scope::User,
        }
    }

    pub fn launchd(label: &str) -> Self {
        Self {
            manager: Manager::Launchd,
            unit: label.to_string(),
            scope: Scope::System,
        }
    }

    fn default_for(os: Os) -> Self {
        match os {
            Os::Linux => Self::user_default(),
            Os::MacOs => Self::launchd(launchd::DEFAULT_LABEL),
        }
    }
}

pub fn select(os: Os, recorded: Option<ServiceRecord>) -> ServiceRecord {
    recorded.unwrap_or_else(|| ServiceRecord::default_for(os))
}

pub fn check_setup_caller(os: Os, uid: u32) -> Result<()> {
    if os == Os::MacOs && uid == 0 {
        anyhow::bail!(
            "run `sb setup` as the user who will own the daemon, not as root; \
             it calls sudo itself to install the LaunchDaemon"
        );
    }
    Ok(())
}

pub fn status_hint(record: &ServiceRecord) -> String {
    match (&record.manager, &record.scope) {
        (Manager::Systemd, Scope::User) => format!("systemctl --user status {}", record.unit),
        (Manager::Systemd, Scope::System) => format!("systemctl status {}", record.unit),
        (Manager::Launchd, _) => format!("launchctl print system/{}", record.unit),
    }
}

pub struct Caller {
    pub uid: u32,
    runtime_dir: Option<OsString>,
}

impl Caller {
    pub fn current() -> Self {
        Self {
            uid: unsafe { libc::getuid() },
            runtime_dir: std::env::var_os("XDG_RUNTIME_DIR"),
        }
    }

    #[cfg(test)]
    pub fn with_uid(uid: u32) -> Self {
        Self {
            uid,
            runtime_dir: None,
        }
    }
}

/// `StartLimitIntervalSec=0` belongs in `[Unit]`: systemd ignores it in
/// `[Service]`, and without it a crash loop eventually stops restarting.
pub fn unit_file(api_bin: &Path, db_path: &Path) -> String {
    format!(
        "[Unit]\n\
         Description=second-brain memory daemon (SQLite store, embedder, transcript watcher)\n\
         After=network.target\n\
         StartLimitIntervalSec=0\n\
         \n\
         [Service]\n\
         Type=simple\n\
         ExecStart={api}\n\
         Environment=SECOND_BRAIN_DB={db}\n\
         Environment=SECOND_BRAIN_BIND={bind}\n\
         Restart=on-failure\n\
         RestartSec=5\n\
         TimeoutStartSec=60\n\
         \n\
         [Install]\n\
         WantedBy=default.target\n",
        api = api_bin.display(),
        db = db_path.display(),
        bind = DEFAULT_BIND,
    )
}

/// systemd accepts the prefixes `-@:+!` before the program path.
pub(crate) fn unit_exec_start(unit: &str) -> Option<PathBuf> {
    let value = unit
        .lines()
        .find_map(|line| line.trim().strip_prefix("ExecStart="))?;
    value
        .trim_start_matches(['-', '@', ':', '+', '!'])
        .split_whitespace()
        .next()
        .map(PathBuf::from)
}

/// On failure, returns what is wrong as a predicate that follows the path
/// in a sentence, such as "does not exist".
pub(crate) fn program_usable(program: &Path) -> std::result::Result<(), String> {
    match std::fs::metadata(program) {
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Err("does not exist".to_string()),
        Err(e) => Err(format!("cannot be read ({e})")),
        Ok(meta) if !meta.is_file() => Err("is not a file".to_string()),
        Ok(meta) if meta.permissions().mode() & 0o111 == 0 => Err("is not executable".to_string()),
        Ok(_) => Ok(()),
    }
}

pub(crate) fn user_unit_dir(home: &Path) -> PathBuf {
    home.join(".config/systemd/user")
}

pub fn record_path() -> Result<PathBuf> {
    Ok(second_brain_core::machine::data_dir()?.join("service.json"))
}

pub fn save_record(path: &Path, record: &ServiceRecord) -> Result<()> {
    if let Some(dir) = path.parent() {
        std::fs::create_dir_all(dir).with_context(|| format!("creating {}", dir.display()))?;
    }
    let json = serde_json::to_string_pretty(record)?;
    std::fs::write(path, json + "\n").with_context(|| format!("writing {}", path.display()))
}

pub(crate) fn load_record(path: &Path) -> Result<Option<ServiceRecord>> {
    let content = match std::fs::read_to_string(path) {
        Ok(content) => content,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
        Err(e) => return Err(e).with_context(|| format!("reading {}", path.display())),
    };
    serde_json::from_str(&content)
        .map(Some)
        .with_context(|| format!("parsing {}", path.display()))
}

pub fn control(action: Action) -> Result<()> {
    let path = record_path()?;
    let recorded = load_record(&path)?;
    let from_record = recorded.is_some();
    let record = select(Os::current(), recorded);
    let caller = Caller::current();
    match record.manager {
        Manager::Systemd => systemd_control(
            &record,
            from_record.then_some(path.as_path()),
            action,
            &caller,
        ),
        Manager::Launchd => launchd::control(
            action,
            &launchd::Daemon::new(&record.unit),
            &caller,
            &mut launchd::System,
        ),
    }
}

fn systemd_control(
    record: &ServiceRecord,
    recorded_in: Option<&Path>,
    action: Action,
    caller: &Caller,
) -> Result<()> {
    let probe = load_state_command(record, caller)
        .output()
        .context("failed to run systemctl")?;
    check_loaded(record, recorded_in, &probe)?;

    let mut cmd = action_command(record, action.as_str(), caller);
    let shown = render(&cmd);
    let status = cmd
        .status()
        .with_context(|| format!("failed to run {shown}"))?;
    if !status.success() {
        anyhow::bail!("{shown} failed");
    }
    Ok(())
}

/// `systemctl --user` finds the user bus through XDG_RUNTIME_DIR, which ssh,
/// sudo and agent shells often leave unset even though the bus is running;
/// without it systemctl fails with "Failed to connect to bus: No medium found".
fn systemctl(scope: &Scope, caller: &Caller) -> Command {
    let mut cmd = Command::new("systemctl");
    if *scope == Scope::User {
        cmd.arg("--user");
        if caller.runtime_dir.as_ref().is_none_or(|d| d.is_empty()) {
            cmd.env("XDG_RUNTIME_DIR", format!("/run/user/{}", caller.uid));
        }
    }
    cmd
}

fn load_state_command(record: &ServiceRecord, caller: &Caller) -> Command {
    let mut cmd = systemctl(&record.scope, caller);
    cmd.args(["show", "--property=LoadState", "--value", &record.unit]);
    cmd
}

fn action_command(record: &ServiceRecord, action: &str, caller: &Caller) -> Command {
    let mut cmd = if record.scope == Scope::System && caller.uid != 0 {
        let mut sudo = Command::new("sudo");
        sudo.arg("systemctl");
        sudo
    } else {
        systemctl(&record.scope, caller)
    };
    cmd.args([action, &record.unit]);
    cmd
}

fn check_loaded(record: &ServiceRecord, recorded_in: Option<&Path>, probe: &Output) -> Result<()> {
    let scope = match record.scope {
        Scope::User => "user",
        Scope::System => "system",
    };
    let unit = &record.unit;
    if !probe.status.success() {
        anyhow::bail!(
            "could not query the {scope} unit {unit}: {}",
            String::from_utf8_lossy(&probe.stderr).trim()
        );
    }
    let state = String::from_utf8_lossy(&probe.stdout);
    let state = state.trim();
    if state == "loaded" {
        return Ok(());
    }
    match recorded_in {
        Some(path) => anyhow::bail!(
            "the {scope} unit {unit} recorded in {} is not loaded (LoadState={state}); \
             reinstall that service or remove the record",
            path.display()
        ),
        None => anyhow::bail!(
            "the {scope} unit {unit} is not loaded (LoadState={state}); \
             install it with `sb setup`"
        ),
    }
}

pub trait Exec {
    fn output(&mut self, cmd: Command) -> Result<Output>;
}

pub(crate) fn is_not_found(err: &anyhow::Error) -> bool {
    err.chain().any(|cause| {
        cause
            .downcast_ref::<std::io::Error>()
            .is_some_and(|io| io.kind() == std::io::ErrorKind::NotFound)
    })
}

pub struct SystemExec;

impl Exec for SystemExec {
    fn output(&mut self, mut cmd: Command) -> Result<Output> {
        cmd.output()
            .with_context(|| format!("failed to run {}", render(&cmd)))
    }
}

const CONNECT_TIMEOUT: Duration = Duration::from_millis(500);

/// Refuses when `bind` accepts connections and the daemon setup manages is
/// not what is running there; a second daemon would lose the port and
/// crash-loop while setup's health check saw the old one answer.
pub fn check_bind_free(
    bind: &str,
    our_service_running: impl FnOnce() -> Result<bool>,
    holder: impl FnOnce(u16) -> Option<String>,
) -> Result<()> {
    let addr: SocketAddr = bind
        .parse()
        .with_context(|| format!("parsing bind address {bind}"))?;
    if TcpStream::connect_timeout(&addr, CONNECT_TIMEOUT).is_err() || our_service_running()? {
        return Ok(());
    }
    let lookup = render(&holder_command(addr.port()));
    let found = match holder(addr.port()) {
        Some(listing) => format!(":\n{listing}\n"),
        None => format!(" (find it with `{lookup}`)"),
    };
    anyhow::bail!(
        "{bind} is already in use by a process that is not the daemon `sb setup` manages{found}\
         stop it (and disable its service so it does not start again), then rerun `sb setup`; \
         `{lookup}` shows what holds the port"
    )
}

pub fn holder_command(port: u16) -> Command {
    let mut cmd = Command::new("lsof");
    cmd.args(["-nP", &format!("-iTCP:{port}"), "-sTCP:LISTEN"]);
    cmd
}

pub fn port_holder(port: u16, exec: &mut dyn Exec) -> Option<String> {
    let out = exec.output(holder_command(port)).ok()?;
    let listing = String::from_utf8_lossy(&out.stdout).trim().to_string();
    (out.status.success() && !listing.is_empty()).then_some(listing)
}

pub fn user_unit_active(caller: &Caller, exec: &mut dyn Exec) -> bool {
    let cmd = is_active_command(&ServiceRecord::user_default(), caller);
    exec.output(cmd).is_ok_and(|out| out.status.success())
}

pub(crate) fn is_active_command(record: &ServiceRecord, caller: &Caller) -> Command {
    let mut cmd = systemctl(&record.scope, caller);
    cmd.args(["is-active", &record.unit]);
    cmd
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Start {
    Started,
    Restarted,
    Failed { command: String, detail: String },
}

fn start_steps(active: bool) -> Vec<Vec<&'static str>> {
    if active {
        vec![
            vec!["daemon-reload"],
            vec!["enable", DEFAULT_UNIT],
            vec!["restart", DEFAULT_UNIT],
        ]
    } else {
        vec![vec!["daemon-reload"], vec!["enable", "--now", DEFAULT_UNIT]]
    }
}

/// A unit that was already running must be restarted, since `enable --now`
/// leaves it on the binary it started with.
pub fn start_user_unit(active: bool, caller: &Caller, exec: &mut dyn Exec) -> Start {
    for args in start_steps(active) {
        let mut cmd = systemctl(&Scope::User, caller);
        cmd.args(&args);
        if let Err(detail) = run_checked(exec, cmd) {
            return Start::Failed {
                command: format!("systemctl --user {}", args.join(" ")),
                detail,
            };
        }
    }
    if active {
        Start::Restarted
    } else {
        Start::Started
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Linger {
    AlreadyOn,
    Enabled,
    Failed(String),
}

/// `show-user` fails for a user with no session and no linger, so only an
/// explicit `Linger=yes` skips enabling it.
pub fn ensure_linger(user: &str, exec: &mut dyn Exec) -> Linger {
    let mut probe = Command::new("loginctl");
    probe.args(["show-user", user, "-p", "Linger"]);
    if exec
        .output(probe)
        .is_ok_and(|out| String::from_utf8_lossy(&out.stdout).trim() == "Linger=yes")
    {
        return Linger::AlreadyOn;
    }
    let mut enable = Command::new("loginctl");
    enable.args(["enable-linger", user]);
    let shown = render(&enable);
    match run_checked(exec, enable) {
        Ok(()) => Linger::Enabled,
        Err(detail) => Linger::Failed(format!(
            "could not enable linger ({detail}), so the daemon stops when you log out; \
             run `{shown}` to keep it running"
        )),
    }
}

pub(crate) fn run_checked(exec: &mut dyn Exec, cmd: Command) -> std::result::Result<(), String> {
    match exec.output(cmd) {
        Ok(out) if out.status.success() => Ok(()),
        Ok(out) => {
            let stderr = String::from_utf8_lossy(&out.stderr).trim().to_string();
            Err(if stderr.is_empty() {
                out.status.to_string()
            } else {
                stderr
            })
        }
        Err(e) => Err(format!("{e:#}")),
    }
}

pub(crate) fn render(cmd: &Command) -> String {
    std::iter::once(cmd.get_program())
        .chain(cmd.get_args())
        .map(|a| shell_word(&a.to_string_lossy()))
        .collect::<Vec<_>>()
        .join(" ")
}

pub(crate) fn shell_word(arg: &str) -> String {
    let plain = |c: char| c.is_ascii_alphanumeric() || "_-./=:@,+%".contains(c);
    if !arg.is_empty() && arg.chars().all(plain) {
        arg.to_string()
    } else {
        format!("'{}'", arg.replace('\'', r"'\''"))
    }
}

#[cfg(test)]
mod tests {
    use std::os::unix::process::ExitStatusExt;
    use std::process::ExitStatus;

    use super::*;

    fn caller(uid: u32, runtime_dir: Option<&str>) -> Caller {
        Caller {
            uid,
            runtime_dir: runtime_dir.map(OsString::from),
        }
    }

    fn system_record() -> ServiceRecord {
        ServiceRecord {
            manager: Manager::Systemd,
            unit: "custom-brain.service".to_string(),
            scope: Scope::System,
        }
    }

    fn argv(cmd: &Command) -> Vec<String> {
        std::iter::once(cmd.get_program())
            .chain(cmd.get_args())
            .map(|a| a.to_string_lossy().into_owned())
            .collect()
    }

    fn runtime_env(cmd: &Command) -> Option<Option<OsString>> {
        cmd.get_envs()
            .find(|(k, _)| *k == "XDG_RUNTIME_DIR")
            .map(|(_, v)| v.map(OsString::from))
    }

    fn probe(code: i32, stdout: &str, stderr: &str) -> Output {
        Output {
            status: ExitStatus::from_raw(code << 8),
            stdout: stdout.as_bytes().to_vec(),
            stderr: stderr.as_bytes().to_vec(),
        }
    }

    #[test]
    fn missing_record_means_no_record() {
        let dir = tempfile::tempdir().unwrap();
        assert_eq!(load_record(&dir.path().join("service.json")).unwrap(), None);
    }

    #[test]
    fn saved_record_loads_back() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("nested/service.json");
        save_record(&path, &system_record()).unwrap();
        assert_eq!(load_record(&path).unwrap(), Some(system_record()));
    }

    #[test]
    fn record_file_uses_plain_lowercase_names() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("service.json");
        std::fs::write(
            &path,
            r#"{"manager":"systemd","unit":"second-brain-api.service","scope":"system"}"#,
        )
        .unwrap();
        assert_eq!(
            load_record(&path).unwrap(),
            Some(ServiceRecord {
                manager: Manager::Systemd,
                unit: "second-brain-api.service".to_string(),
                scope: Scope::System,
            })
        );
    }

    #[test]
    fn malformed_record_is_an_error_naming_the_file() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("service.json");
        std::fs::write(&path, "{").unwrap();
        let err = format!("{:#}", load_record(&path).unwrap_err());
        assert!(err.contains("service.json"), "{err}");
    }

    #[test]
    fn default_record_is_the_user_unit_setup_installs() {
        assert_eq!(
            ServiceRecord::user_default(),
            ServiceRecord {
                manager: Manager::Systemd,
                unit: DEFAULT_UNIT.to_string(),
                scope: Scope::User,
            }
        );
    }

    #[test]
    fn user_systemctl_fills_runtime_dir_when_unset_or_empty() {
        for unset in [None, Some("")] {
            let cmd = systemctl(&Scope::User, &caller(1000, unset));
            assert_eq!(argv(&cmd), ["systemctl", "--user"]);
            assert_eq!(
                runtime_env(&cmd),
                Some(Some(OsString::from("/run/user/1000")))
            );
        }
    }

    #[test]
    fn user_systemctl_keeps_an_existing_runtime_dir() {
        let cmd = systemctl(&Scope::User, &caller(1000, Some("/custom")));
        assert_eq!(runtime_env(&cmd), None);
    }

    #[test]
    fn system_systemctl_never_touches_the_runtime_dir() {
        let cmd = systemctl(&Scope::System, &caller(1000, None));
        assert_eq!(argv(&cmd), ["systemctl"]);
        assert_eq!(runtime_env(&cmd), None);
    }

    #[test]
    fn user_action_targets_the_recorded_unit() {
        let record = ServiceRecord {
            scope: Scope::User,
            ..system_record()
        };
        let cmd = action_command(&record, "stop", &caller(1000, None));
        assert_eq!(
            argv(&cmd),
            ["systemctl", "--user", "stop", "custom-brain.service"]
        );
        assert_eq!(
            runtime_env(&cmd),
            Some(Some(OsString::from("/run/user/1000")))
        );
    }

    #[test]
    fn render_quotes_arguments_a_shell_would_split_or_expand() {
        let mut cmd = Command::new("claude");
        cmd.args([
            "add",
            "SECOND_BRAIN_API=http://127.0.0.1:7200",
            "--",
            "/Users/a b/bin/mcp",
            "it's",
            "~/x",
            "$HOME",
            "",
        ]);
        assert_eq!(
            render(&cmd),
            "claude add SECOND_BRAIN_API=http://127.0.0.1:7200 -- '/Users/a b/bin/mcp' \
             'it'\\''s' '~/x' '$HOME' ''"
        );
    }

    #[test]
    fn system_action_goes_through_sudo_unless_root() {
        let record = system_record();
        assert_eq!(
            argv(&action_command(&record, "restart", &caller(1000, None))),
            ["sudo", "systemctl", "restart", "custom-brain.service"]
        );
        assert_eq!(
            argv(&action_command(&record, "restart", &caller(0, None))),
            ["systemctl", "restart", "custom-brain.service"]
        );
    }

    #[test]
    fn load_state_probe_asks_the_recorded_manager_scope() {
        let record = system_record();
        assert_eq!(
            argv(&load_state_command(&record, &caller(1000, None))),
            [
                "systemctl",
                "show",
                "--property=LoadState",
                "--value",
                "custom-brain.service"
            ]
        );
        let user = ServiceRecord::user_default();
        assert_eq!(
            argv(&load_state_command(&user, &caller(1000, None)))[..2],
            ["systemctl", "--user"]
        );
    }

    #[test]
    fn loaded_unit_passes() {
        check_loaded(&system_record(), None, &probe(0, "loaded\n", "")).unwrap();
    }

    #[test]
    fn unloaded_recorded_unit_names_the_unit_state_and_record() {
        let err = check_loaded(
            &system_record(),
            Some(Path::new("/data/service.json")),
            &probe(0, "not-found\n", ""),
        )
        .unwrap_err()
        .to_string();
        assert!(err.contains("custom-brain.service"), "{err}");
        assert!(err.contains("not-found"), "{err}");
        assert!(err.contains("/data/service.json"), "{err}");
    }

    #[test]
    fn unloaded_default_unit_points_at_setup() {
        let err = check_loaded(
            &ServiceRecord::user_default(),
            None,
            &probe(0, "not-found\n", ""),
        )
        .unwrap_err()
        .to_string();
        assert!(err.contains(DEFAULT_UNIT), "{err}");
        assert!(err.contains("sb setup"), "{err}");
    }

    #[test]
    fn failed_probe_reports_systemctl_stderr() {
        let err = check_loaded(
            &ServiceRecord::user_default(),
            None,
            &probe(1, "", "Failed to connect to bus: No medium found\n"),
        )
        .unwrap_err()
        .to_string();
        assert!(err.contains("No medium found"), "{err}");
    }

    fn launchd_record() -> ServiceRecord {
        ServiceRecord::launchd("custom-brain.api")
    }

    #[test]
    fn launchd_record_round_trips_as_plain_lowercase_names() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("service.json");
        save_record(&path, &launchd_record()).unwrap();
        let text = std::fs::read_to_string(&path).unwrap();
        let json: serde_json::Value = serde_json::from_str(&text).unwrap();
        assert_eq!(
            json,
            serde_json::json!({"manager": "launchd", "unit": "custom-brain.api", "scope": "system"})
        );
        assert_eq!(load_record(&path).unwrap(), Some(launchd_record()));
    }

    #[test]
    fn linux_without_a_record_uses_the_user_unit() {
        assert_eq!(select(Os::Linux, None), ServiceRecord::user_default());
    }

    #[test]
    fn macos_without_a_record_uses_the_launchd_daemon() {
        assert_eq!(
            select(Os::MacOs, None),
            ServiceRecord {
                manager: Manager::Launchd,
                unit: launchd::DEFAULT_LABEL.to_string(),
                scope: Scope::System,
            }
        );
    }

    #[test]
    fn a_record_wins_on_linux() {
        assert_eq!(select(Os::Linux, Some(launchd_record())), launchd_record());
    }

    #[test]
    fn a_record_wins_on_macos() {
        assert_eq!(select(Os::MacOs, Some(system_record())), system_record());
    }

    #[test]
    fn macos_setup_refuses_root() {
        let err = check_setup_caller(Os::MacOs, 0).unwrap_err().to_string();
        assert!(err.contains("sudo"), "{err}");
        check_setup_caller(Os::MacOs, 501).unwrap();
    }

    #[test]
    fn linux_setup_allows_any_uid() {
        check_setup_caller(Os::Linux, 0).unwrap();
        check_setup_caller(Os::Linux, 1000).unwrap();
    }

    #[test]
    fn status_hint_names_the_manager_setup_used() {
        assert_eq!(
            status_hint(&ServiceRecord::user_default()),
            "systemctl --user status second-brain.service"
        );
        assert_eq!(
            status_hint(&system_record()),
            "systemctl status custom-brain.service"
        );
        assert_eq!(
            status_hint(&launchd_record()),
            "launchctl print system/custom-brain.api"
        );
    }

    #[test]
    fn caller_uid_is_the_real_uid() {
        assert_eq!(Caller::current().uid, unsafe { libc::getuid() });
    }

    fn section<'a>(unit: &'a str, name: &str) -> Vec<&'a str> {
        unit.lines()
            .skip_while(|l| *l != format!("[{name}]"))
            .skip(1)
            .take_while(|l| !l.starts_with('['))
            .collect()
    }

    #[test]
    fn the_unit_never_stops_restarting_and_names_the_real_store() {
        let unit = unit_file(
            Path::new("/opt/sb/second-brain-api"),
            Path::new("/h/brain.db"),
        );
        assert!(
            section(&unit, "Unit").contains(&"StartLimitIntervalSec=0"),
            "{unit}"
        );
        assert!(
            section(&unit, "Service").contains(&"Restart=on-failure"),
            "{unit}"
        );
        assert!(
            section(&unit, "Service").contains(&"ExecStart=/opt/sb/second-brain-api"),
            "{unit}"
        );
        assert!(
            section(&unit, "Service").contains(&"Environment=SECOND_BRAIN_DB=/h/brain.db"),
            "{unit}"
        );
        assert!(!unit.to_lowercase().contains("kuzu"), "{unit}");
    }

    #[test]
    fn exec_start_reads_back_the_binary_the_unit_runs() {
        let unit = unit_file(
            Path::new("/opt/sb/second-brain-api"),
            Path::new("/h/brain.db"),
        );
        assert_eq!(
            unit_exec_start(&unit),
            Some(PathBuf::from("/opt/sb/second-brain-api"))
        );
        assert_eq!(
            unit_exec_start("[Service]\nExecStart=-/usr/bin/api --flag\n"),
            Some(PathBuf::from("/usr/bin/api"))
        );
        assert_eq!(unit_exec_start("[Service]\nType=simple\n"), None);
    }

    #[test]
    fn is_active_probe_asks_the_recorded_scope_without_sudo() {
        assert_eq!(
            argv(&is_active_command(&system_record(), &caller(1000, None))),
            ["systemctl", "is-active", "custom-brain.service"]
        );
    }

    type Reply = Box<dyn FnMut(&[String]) -> Result<Output>>;

    struct FakeExec {
        calls: Vec<Vec<String>>,
        reply: Reply,
    }

    impl FakeExec {
        fn new(reply: impl FnMut(&[String]) -> Result<Output> + 'static) -> Self {
            Self {
                calls: Vec::new(),
                reply: Box::new(reply),
            }
        }
    }

    impl Exec for FakeExec {
        fn output(&mut self, cmd: Command) -> Result<Output> {
            let argv = argv(&cmd);
            let out = (self.reply)(&argv);
            self.calls.push(argv);
            out
        }
    }

    fn ok(stdout: &str) -> Result<Output> {
        Ok(probe(0, stdout, ""))
    }

    fn held_port() -> (std::net::TcpListener, String) {
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let bind = listener.local_addr().unwrap().to_string();
        (listener, bind)
    }

    fn free_port() -> String {
        let (listener, bind) = held_port();
        drop(listener);
        bind
    }

    #[test]
    fn a_held_port_without_our_running_service_is_refused_naming_the_holder() {
        let (_listener, bind) = held_port();
        let port = bind.rsplit(':').next().unwrap().to_string();
        let mut asked = None;
        let err = check_bind_free(
            &bind,
            || Ok(false),
            |p| {
                asked = Some(p);
                Some("other-daemon 4242 me 9u IPv4 TCP 127.0.0.1:7200 (LISTEN)".to_string())
            },
        )
        .unwrap_err()
        .to_string();
        assert_eq!(asked.map(|p| p.to_string()), Some(port.clone()));
        assert!(err.contains(&bind), "{err}");
        assert!(err.contains("other-daemon 4242"), "{err}");
        assert!(
            err.contains(&format!("lsof -nP -iTCP:{port} -sTCP:LISTEN")),
            "{err}"
        );
        assert!(err.contains("stop it"), "{err}");
    }

    #[test]
    fn a_refusal_without_lsof_output_still_says_where_to_look() {
        let (_listener, bind) = held_port();
        let port = bind.rsplit(':').next().unwrap();
        let err = check_bind_free(&bind, || Ok(false), |_| None)
            .unwrap_err()
            .to_string();
        assert!(
            err.contains(&format!("lsof -nP -iTCP:{port} -sTCP:LISTEN")),
            "{err}"
        );
    }

    #[test]
    fn a_held_port_passes_when_our_service_is_running_there() {
        let (_listener, bind) = held_port();
        check_bind_free(&bind, || Ok(true), |_| panic!("no lookup")).unwrap();
    }

    #[test]
    fn a_free_port_passes_without_probing_the_service() {
        let bind = free_port();
        check_bind_free(&bind, || panic!("no probe"), |_| panic!("no lookup")).unwrap();
    }

    #[test]
    fn holder_lookup_lists_tcp_listeners_on_the_port() {
        assert_eq!(
            argv(&holder_command(7200)),
            ["lsof", "-nP", "-iTCP:7200", "-sTCP:LISTEN"]
        );
    }

    #[test]
    fn is_active_probe_asks_the_user_manager() {
        let mut exec = FakeExec::new(|_| ok("active\n"));
        assert!(user_unit_active(&caller(1000, None), &mut exec));
        assert_eq!(
            exec.calls,
            [["systemctl", "--user", "is-active", DEFAULT_UNIT]]
        );
    }

    #[test]
    fn an_inactive_or_unreachable_unit_is_not_active() {
        let mut inactive = FakeExec::new(|_| Ok(probe(3, "inactive\n", "")));
        assert!(!user_unit_active(&caller(1000, None), &mut inactive));
        let mut missing = FakeExec::new(|_| Err(anyhow::anyhow!("no systemctl")));
        assert!(!user_unit_active(&caller(1000, None), &mut missing));
    }

    fn user(args: &[&str]) -> Vec<String> {
        ["systemctl", "--user"]
            .iter()
            .chain(args)
            .map(|s| s.to_string())
            .collect()
    }

    #[test]
    fn a_fresh_install_enables_and_starts_the_unit() {
        let mut exec = FakeExec::new(|_| ok(""));
        let outcome = start_user_unit(false, &caller(1000, None), &mut exec);
        assert_eq!(outcome, Start::Started);
        assert_eq!(
            exec.calls,
            [
                user(&["daemon-reload"]),
                user(&["enable", "--now", DEFAULT_UNIT])
            ]
        );
    }

    #[test]
    fn a_reinstall_over_a_running_unit_restarts_it_on_the_new_binary() {
        let mut exec = FakeExec::new(|_| ok(""));
        let outcome = start_user_unit(true, &caller(1000, None), &mut exec);
        assert_eq!(outcome, Start::Restarted);
        assert_eq!(
            exec.calls,
            [
                user(&["daemon-reload"]),
                user(&["enable", DEFAULT_UNIT]),
                user(&["restart", DEFAULT_UNIT]),
            ]
        );
    }

    #[test]
    fn a_failing_restart_is_reported_like_a_failing_enable() {
        let failing = |verb: &'static str| {
            move |argv: &[String]| {
                if argv.iter().any(|a| a == verb) {
                    Ok(probe(1, "", "Unit failed\n"))
                } else {
                    ok("")
                }
            }
        };
        let mut exec = FakeExec::new(failing("restart"));
        let restart = start_user_unit(true, &caller(1000, None), &mut exec);
        let mut exec = FakeExec::new(failing("enable"));
        let enable = start_user_unit(false, &caller(1000, None), &mut exec);
        for (outcome, verb) in [(restart, "restart"), (enable, "enable")] {
            match outcome {
                Start::Failed { command, detail } => {
                    assert!(command.contains(verb), "{command}");
                    assert!(detail.contains("Unit failed"), "{detail}");
                }
                other => panic!("{verb}: {other:?}"),
            }
        }
    }

    #[test]
    fn a_failing_daemon_reload_stops_before_enable() {
        let mut exec = FakeExec::new(|_| Err(anyhow::anyhow!("systemctl not found")));
        let outcome = start_user_unit(true, &caller(1000, None), &mut exec);
        assert!(
            matches!(&outcome, Start::Failed { command, detail }
                if command.contains("daemon-reload") && detail.contains("not found")),
            "{outcome:?}"
        );
        assert_eq!(exec.calls.len(), 1);
    }

    #[test]
    fn linger_already_on_is_left_alone() {
        let mut exec = FakeExec::new(|_| ok("Linger=yes\n"));
        assert_eq!(ensure_linger("alice", &mut exec), Linger::AlreadyOn);
        assert_eq!(
            exec.calls,
            [["loginctl", "show-user", "alice", "-p", "Linger"]]
        );
    }

    #[test]
    fn linger_off_is_enabled_without_sudo() {
        let mut exec = FakeExec::new(|argv| {
            ok(if argv[1] == "show-user" {
                "Linger=no\n"
            } else {
                ""
            })
        });
        assert_eq!(ensure_linger("alice", &mut exec), Linger::Enabled);
        assert_eq!(
            exec.calls,
            [
                vec!["loginctl", "show-user", "alice", "-p", "Linger"],
                vec!["loginctl", "enable-linger", "alice"],
            ]
        );
    }

    #[test]
    fn a_failed_linger_probe_still_tries_to_enable_it() {
        let mut exec = FakeExec::new(|argv| {
            if argv[1] == "show-user" {
                Ok(probe(1, "", "User alice is not logged in or lingering\n"))
            } else {
                ok("")
            }
        });
        assert_eq!(ensure_linger("alice", &mut exec), Linger::Enabled);
        assert_eq!(exec.calls.len(), 2);
    }

    #[test]
    fn a_failing_enable_linger_warns_with_the_exact_command() {
        let mut exec = FakeExec::new(|argv| {
            if argv[1] == "show-user" {
                ok("Linger=no\n")
            } else {
                Ok(probe(1, "", "Access denied\n"))
            }
        });
        match ensure_linger("alice", &mut exec) {
            Linger::Failed(warning) => {
                assert!(
                    warning.contains("loginctl enable-linger alice"),
                    "{warning}"
                );
                assert!(warning.contains("Access denied"), "{warning}");
            }
            other => panic!("{other:?}"),
        }
    }

    #[test]
    fn is_not_found_matches_a_missing_program_anywhere_in_the_chain() {
        let missing = anyhow::Error::new(std::io::Error::from(std::io::ErrorKind::NotFound))
            .context("failed to run systemctl --user is-active second-brain.service");
        assert!(is_not_found(&missing), "{missing:#}");
        let wrapped = missing.context("doctor could not query the service");
        assert!(is_not_found(&wrapped), "{wrapped:#}");
    }

    #[test]
    fn is_not_found_rejects_other_spawn_errors() {
        let denied = anyhow::Error::new(std::io::Error::from(std::io::ErrorKind::PermissionDenied))
            .context("failed to run claude mcp get second-brain");
        assert!(!is_not_found(&denied), "{denied:#}");
        let plain = anyhow::anyhow!("No such file or directory");
        assert!(!is_not_found(&plain), "{plain:#}");
    }
}