semlith 0.33.0

A fast local vector store for AI agents — index files once, keep it current as you save, and answer questions across all of it in milliseconds without leaving the machine.
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
//! The daemon as a login service, so semlith is answering before a client asks.
//!
//! A server that is silently absent does not exist. Until 0.21.0 the daemon ran
//! only while somebody held a terminal open for it: a client that started first
//! found nothing, and nothing said why. This installs it as the thing each
//! platform already has for "run this when I log in, and keep it running" — a
//! launchd user agent on macOS, a systemd user unit on Linux, a logon task on
//! Windows.
//!
//! One public surface, three `#[cfg]` bodies and a fallback, which is the shape
//! `system.rs` already uses for the same reason: the callers — `semlith start
//! --service`, `semlith setup`, `semlith doctor` and the portal's Agents page —
//! ask the same four questions on every platform and none of them should know
//! which mechanism answered.
//!
//! **The three are not equally strong, and this module does not pretend they
//! are.** launchd's `KeepAlive` and systemd's `Restart=always` restart a daemon
//! that exits, within seconds, with no user present. A Windows logon task is
//! registered with a restart count and interval, which covers a task that
//! *fails*; it is a weaker guarantee than the other two and [`Status::restarts`]
//! says so rather than letting a caller assume parity.

use anyhow::{Context, Result};
use std::path::{Path, PathBuf};

/// What this platform calls the service, in its own registry.
pub const LABEL: &str = "com.semlith.daemon";

/// Whether the login service is installed, and where to look when it misbehaves.
#[derive(Debug, Clone, serde::Serialize)]
pub struct Status {
    /// Whether a service is registered for this user.
    pub installed: bool,
    /// The mechanism that answered — `launchd`, `systemd`, `schtasks`, or
    /// `none` on a platform semlith has no login service for. Named rather
    /// than inferred from the operating system, because a caller that has to
    /// guess is a caller that will guess wrong on the next platform.
    pub mechanism: &'static str,
    /// The unit, plist or task definition, when the mechanism has a file.
    pub definition: Option<PathBuf>,
    /// Where this service's own output goes, so a failing service is readable
    /// without knowing launchd, systemd or Task Scheduler.
    pub log: Option<PathBuf>,
    /// Whether the mechanism restarts a daemon that exits without a person
    /// present. False on Windows, where a logon task restarts a task that
    /// failed but does not supervise one that ended cleanly.
    pub restarts: bool,
    /// Whether this install started a daemon now, as opposed to only
    /// registering one for the next login because something was already
    /// listening on the port.
    pub started_now: bool,
}

impl Status {
    /// A service that is not there, and the base every platform body builds on.
    ///
    /// The three bodies are each compiled on one operating system only, so a
    /// field added to `Status` and filled in on two of them breaks the third on
    /// a machine the author cannot run — which is exactly how a Windows-only
    /// compile error reached CI during this release. Each body now overrides
    /// what it knows and takes the rest from here, so a new field is additive
    /// on every platform by construction rather than by remembering.
    fn absent(mechanism: &'static str) -> Self {
        Self {
            installed: false,
            mechanism,
            definition: None,
            log: None,
            restarts: false,
            started_now: false,
        }
    }
}

/// Where the service's output goes.
///
/// Under the semlith home rather than the platform's own log directory, so one
/// path is right on all three and `doctor` can print it without a `cfg`.
pub fn log_path() -> Result<PathBuf> {
    let dir = crate::home::home_or_error()?.join("logs");
    std::fs::create_dir_all(&dir).with_context(|| format!("creating {}", dir.display()))?;
    crate::home::tighten_dir(&dir);
    Ok(dir.join("daemon.log"))
}

/// The binary a service definition should name.
///
/// Resolved, never the bare command: a service manager starts a process with
/// its own environment, and the PATH a login shell builds is not the PATH
/// launchd, systemd or Task Scheduler hands a job. That is the same mistake
/// registration made until 0.21.0, and it is worth making only once.
pub fn exe() -> Result<PathBuf> {
    let exe = std::env::current_exe().context("finding this binary")?;
    Ok(plain(exe.canonicalize().unwrap_or(exe)))
}

/// A path in the spelling a person and a service manager both accept.
///
/// `canonicalize` on Windows returns the verbatim form, `\\?\C:\…`, which is a
/// legal path for the API and an illegal-looking one everywhere a human reads
/// it — and which several tools refuse outright. Compare canonical, emit plain.
fn plain(path: PathBuf) -> PathBuf {
    let text = path.to_string_lossy();
    match text.strip_prefix(r"\\?\UNC\") {
        Some(rest) => PathBuf::from(format!(r"\\{rest}")),
        None => match text.strip_prefix(r"\\?\") {
            Some(rest) => PathBuf::from(rest),
            None => path,
        },
    }
}

// ------------------------------------------------------------------- macOS

#[cfg(target_os = "macos")]
mod platform {
    use super::*;

    pub const MECHANISM: &str = "launchd";

    /// What the plist asks launchd for. See `install`.
    pub const PROCESS_TYPE: &str = "Standard";

    /// Whether an installed plist still asks for the efficiency cores, which
    /// every release before 0.28.0 wrote. `setup` and `upgrade` rewrite it;
    /// `doctor` names it until they have.
    pub fn stale_definition() -> Option<String> {
        let path = plist_path().ok()?;
        let text = std::fs::read_to_string(&path).ok()?;
        text.contains("<string>Background</string>").then(|| {
            format!(
                "{} asks launchd for ProcessType Background, which holds the daemon on the \
                 efficiency cores; run `semlith setup` (or `semlith start --service`) to rewrite it",
                path.display()
            )
        })
    }

    fn plist_path() -> Result<PathBuf> {
        Ok(crate::home::user_home()?
            .join("Library")
            .join("LaunchAgents")
            .join(format!("{LABEL}.plist")))
    }

    pub fn status() -> Status {
        let Ok(path) = plist_path() else {
            return Status::absent(MECHANISM);
        };
        // The file is the definition; whether launchd knows the job is whether
        // anything is supervising it. A headless session — a CI runner, a
        // machine reached only over ssh — has no `gui/<uid>` domain, so
        // `bootstrap` fails, the `load -w` fallback starts the daemon once, and
        // nothing restarts it when it dies. The plist is still on disk, and
        // reporting that as an installed login service is the same claim
        // without the thing it claims. Measured on a GitHub macOS runner, where
        // the daemon ran, was killed, and never came back.
        let known = path.is_file()
            && run(
                "launchctl",
                &[
                    "print",
                    &format!("gui/{}/{LABEL}", unsafe { libc::getuid() }),
                ],
            )
            .is_ok();
        Status {
            installed: known,
            definition: path.is_file().then_some(path),
            log: log_path().ok(),
            restarts: true,
            ..Status::absent(MECHANISM)
        }
    }

    pub fn install(exe: &Path, port: Option<u16>) -> Result<Status> {
        let path = plist_path()?;
        let dir = path
            .parent()
            .expect("a plist has a directory")
            .to_path_buf();
        std::fs::create_dir_all(&dir).with_context(|| format!("creating {}", dir.display()))?;
        let log = log_path()?;

        let mut args = vec![exe.display().to_string(), "start".to_string()];
        if let Some(port) = port {
            args.push("--port".to_string());
            args.push(port.to_string());
        }
        let program: String = args
            .iter()
            .map(|a| format!("    <string>{}</string>\n", escape(a)))
            .collect();

        // KeepAlive, not RunAtLoad alone: the whole claim is that a daemon
        // which exits comes back without a person present.
        //
        // `Standard`, not `Background`. A job launchd starts as `Background`
        // is held on the efficiency cores and cannot lift itself out: on the
        // reference M1 it indexed at 3.3 chunks/s against 28 in a terminal,
        // and `setpriority` from inside it returned 0 and changed nothing.
        // The daemon puts itself in background state while it is idle
        // instead (`priority::manage`), which it can undo in microseconds.
        let plist = format!(
            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\
             <!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \
             \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n\
             <plist version=\"1.0\">\n\
             <dict>\n\
             <key>Label</key>\n  <string>{label}</string>\n\
             <key>ProgramArguments</key>\n  <array>\n{program}  </array>\n\
             <key>RunAtLoad</key>\n  <true/>\n\
             <key>KeepAlive</key>\n  <true/>\n\
             <key>ProcessType</key>\n  <string>{process_type}</string>\n\
             <key>StandardOutPath</key>\n  <string>{log}</string>\n\
             <key>StandardErrorPath</key>\n  <string>{log}</string>\n\
             </dict>\n\
             </plist>\n",
            label = LABEL,
            process_type = PROCESS_TYPE,
            log = escape(&log.display().to_string()),
        );
        std::fs::write(&path, plist).with_context(|| format!("writing {}", path.display()))?;

        // Unload first so a re-install replaces the definition rather than
        // leaving the old one running against the new file. Both are allowed
        // to fail: the first because there may be nothing loaded, the second
        // because `bootstrap` is the modern spelling and `load` the one that
        // works on older systems.
        let domain = format!("gui/{}", unsafe { libc::getuid() });
        let _ = run("launchctl", &["bootout", &format!("{domain}/{LABEL}")]);
        if run(
            "launchctl",
            &["bootstrap", &domain, &path.display().to_string()],
        )
        .is_err()
        {
            run("launchctl", &["load", "-w", &path.display().to_string()])
                .context("loading the launchd agent")?;
        }
        Ok(status())
    }

    pub fn remove() -> Result<bool> {
        let path = plist_path()?;
        let domain = format!("gui/{}", unsafe { libc::getuid() });
        let _ = run("launchctl", &["bootout", &format!("{domain}/{LABEL}")]);
        let _ = run("launchctl", &["unload", "-w", &path.display().to_string()]);
        if !path.exists() {
            return Ok(false);
        }
        std::fs::remove_file(&path).with_context(|| format!("removing {}", path.display()))?;
        Ok(true)
    }

    /// XML, not a shell. A home directory with an ampersand in it is rare and
    /// a plist that silently fails to parse is not worth the odds.
    fn escape(value: &str) -> String {
        value
            .replace('&', "&amp;")
            .replace('<', "&lt;")
            .replace('>', "&gt;")
    }
}

// ------------------------------------------------------------------- Linux

#[cfg(target_os = "linux")]
mod platform {
    use super::*;

    pub const MECHANISM: &str = "systemd";
    const UNIT: &str = "semlith.service";

    /// A unit written before 0.32.0 has no `Nice`, `CPUWeight` or `IOWeight`,
    /// so a bulk index competes with the person at the keyboard as an equal.
    pub fn stale_definition() -> Option<String> {
        let path = unit_path().ok()?;
        let text = std::fs::read_to_string(&path).ok()?;
        (!text.contains("CPUWeight=")).then(|| {
            format!(
                "{} predates the daemon's lower scheduling weight (Nice, CPUWeight, IOWeight); \
                 run `semlith setup` (or `semlith start --service`) to rewrite it",
                path.display()
            )
        })
    }

    fn unit_path() -> Result<PathBuf> {
        Ok(crate::home::user_home()?
            .join(".config")
            .join("systemd")
            .join("user")
            .join(UNIT))
    }

    pub fn status() -> Status {
        let Ok(path) = unit_path() else {
            return Status::absent(MECHANISM);
        };
        // The file is the definition; `is-enabled` is whether systemd agreed to
        // it. A unit file present and not enabled is a half-install, and
        // reporting it as installed is how a user ends up with no daemon and a
        // green row.
        let enabled = run("systemctl", &["--user", "is-enabled", UNIT])
            .map(|out| out.trim() == "enabled")
            .unwrap_or(false);
        Status {
            installed: path.is_file() && enabled,
            definition: path.is_file().then_some(path),
            log: log_path().ok(),
            restarts: true,
            ..Status::absent(MECHANISM)
        }
    }

    pub fn install(exe: &Path, port: Option<u16>) -> Result<Status> {
        let path = unit_path()?;
        let dir = path.parent().expect("a unit has a directory").to_path_buf();
        std::fs::create_dir_all(&dir).with_context(|| format!("creating {}", dir.display()))?;

        let port = port.map(|p| format!(" --port {p}")).unwrap_or_default();
        let unit = format!(
            "[Unit]\n\
             Description=semlith — local semantic index for agent clients\n\
             Documentation=https://github.com/semlith/semlith\n\
             \n\
             [Service]\n\
             Type=simple\n\
             ExecStart={exe}{port}\n\
             Restart=always\n\
             RestartSec=2\n\
             Nice=5\n\
             CPUWeight=50\n\
             IOWeight=50\n\
             \n\
             [Install]\n\
             WantedBy=default.target\n",
            exe = exe.display(),
        );
        std::fs::write(&path, unit).with_context(|| format!("writing {}", path.display()))?;

        run("systemctl", &["--user", "daemon-reload"]).context("reloading systemd --user")?;
        run("systemctl", &["--user", "enable", "--now", UNIT])
            .context("enabling the systemd user unit")?;
        Ok(status())
    }

    pub fn remove() -> Result<bool> {
        let path = unit_path()?;
        let _ = run("systemctl", &["--user", "disable", "--now", UNIT]);
        let existed = path.exists();
        if existed {
            std::fs::remove_file(&path).with_context(|| format!("removing {}", path.display()))?;
        }
        let _ = run("systemctl", &["--user", "daemon-reload"]);
        Ok(existed)
    }
}

// ----------------------------------------------------------------- Windows

#[cfg(windows)]
mod platform {
    use super::*;

    pub const MECHANISM: &str = "schtasks";
    const TASK: &str = "semlith";

    /// Whether the logon task still runs at Task Scheduler's default of 7
    /// (below normal), which every release before 0.28.0 registered, and at
    /// which Windows 11 may apply EcoQoS to the whole process.
    pub fn stale_definition() -> Option<String> {
        let priority = powershell(&format!(
            "(Get-ScheduledTask -TaskName '{TASK}' -ErrorAction Stop).Settings.Priority"
        ))
        .ok()?;
        let priority = priority.trim();
        (priority != "5").then(|| {
            format!(
                "the {TASK} logon task runs at priority {priority} (below normal); run \
                 `semlith setup` (or `semlith start --service`) to register it at 5"
            )
        })
    }

    pub fn status() -> Status {
        let installed = run("schtasks", &["/Query", "/TN", TASK]).is_ok();
        Status {
            installed,
            log: log_path().ok(),
            // `restarts` and `started_now` are both false here and both come
            // from `absent`. A logon task restarts a task that *failed*; it
            // does not supervise one that ended cleanly, the way launchd's
            // KeepAlive and systemd's Restart=always do — said rather than
            // left for a caller to assume parity it does not have.
            ..Status::absent(MECHANISM)
        }
    }

    pub fn install(exe: &Path, port: Option<u16>) -> Result<Status> {
        let port = port.map(|p| format!(" --port {p}")).unwrap_or_default();
        // `-Priority 5` is normal. Without it Task Scheduler starts the task at
        // 7, below normal, and Windows 11 may then apply EcoQoS, which on a
        // hybrid CPU means the efficiency cores. The daemon lowers itself while
        // idle (`priority::manage`), so asking for normal here costs nothing.
        //
        // PowerShell rather than `schtasks /Create`, for one reason: the
        // restart settings. `schtasks` has no flag for "try again if this
        // fails", and a logon task without one is a service that gives up the
        // first time the port is busy.
        let script = format!(
            "$ErrorActionPreference='Stop'; \
             $action = New-ScheduledTaskAction -Execute '{exe}' -Argument 'start{port}'; \
             $trigger = New-ScheduledTaskTrigger -AtLogOn -User $env:USERNAME; \
             $settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries \
             -DontStopIfGoingOnBatteries -Priority 5 -RestartCount 3 \
             -RestartInterval (New-TimeSpan -Minutes 1) \
             -ExecutionTimeLimit (New-TimeSpan -Seconds 0); \
             Register-ScheduledTask -TaskName '{task}' -Action $action -Trigger $trigger \
             -Settings $settings -Force | Out-Null; \
             Start-ScheduledTask -TaskName '{task}'",
            exe = exe.display(),
            task = TASK,
        );
        powershell(&script).context("registering the logon task")?;
        Ok(status())
    }

    pub fn remove() -> Result<bool> {
        if run("schtasks", &["/Query", "/TN", TASK]).is_err() {
            return Ok(false);
        }
        run("schtasks", &["/Delete", "/TN", TASK, "/F"]).context("deleting the logon task")?;
        Ok(true)
    }

    fn powershell(script: &str) -> Result<String> {
        // `powershell` rather than `pwsh`: Windows Server and a stock Windows
        // 11 have the first and may not have the second, and this has to work
        // on the machine as it is rather than on a developer's.
        run(
            "powershell",
            &["-NoProfile", "-NonInteractive", "-Command", script],
        )
    }
}

// ------------------------------------------------------- every other target

#[cfg(not(any(target_os = "macos", target_os = "linux", windows)))]
mod platform {
    use super::*;

    pub const MECHANISM: &str = "none";

    pub fn stale_definition() -> Option<String> {
        None
    }

    pub fn status() -> Status {
        Status::absent(MECHANISM)
    }

    pub fn install(_exe: &Path, _port: Option<u16>) -> Result<Status> {
        anyhow::bail!(
            "semlith has no login service for this platform — \
             run `semlith start` from whatever this system uses to start a user service"
        )
    }

    pub fn remove() -> Result<bool> {
        Ok(false)
    }
}

/// Run a command and return its stdout, or an error carrying what it said.
///
/// Service managers report the interesting half on stderr and exit non-zero,
/// so a caller that only looked at the status gets "it failed" and nothing a
/// person can act on.
fn run(program: &str, args: &[&str]) -> Result<String> {
    let out = std::process::Command::new(program)
        .args(args)
        .output()
        .with_context(|| format!("running {program}"))?;
    if !out.status.success() {
        let said = String::from_utf8_lossy(&out.stderr);
        let said = if said.trim().is_empty() {
            String::from_utf8_lossy(&out.stdout).trim().to_string()
        } else {
            said.trim().to_string()
        };
        anyhow::bail!("{program} {}: {said}", args.join(" "));
    }
    Ok(String::from_utf8_lossy(&out.stdout).to_string())
}

/// Why the installed login service needs rewriting, if it does.
///
/// Every release before 0.28.0 asked for background priority — launchd's
/// `ProcessType Background` on macOS, Task Scheduler's default of 7 on
/// Windows — and a daemon started that way runs its whole index on the
/// efficiency cores. `setup` and `upgrade` rewrite such a definition, and
/// `doctor` names it until one of them has.
pub fn stale_definition() -> Option<String> {
    platform::stale_definition()
}

/// Whether a login service is installed for this user, and where to look.
pub fn status() -> Status {
    platform::status()
}

/// Install the daemon as a login service and start it now.
///
/// Installing twice is safe: each platform's body replaces its own definition
/// rather than adding a second one.
pub fn install(binary: Option<&Path>, port: Option<u16>) -> Result<Status> {
    // `setup` names the binary it just installed, which is not the one running
    // this code: a service pointing at the downloaded installer, or at a
    // checkout someone is about to delete, is a service that stops working
    // without saying so.
    let exe = match binary {
        Some(path) => plain(path.canonicalize().unwrap_or_else(|_| path.to_path_buf())),
        None => exe()?,
    };
    // A service pointing into the temp directory is one the next cleanup
    // breaks, and it is what a test that forgot `--no-service` produces: HOME
    // is redirected, but launchd and systemd register into the real session,
    // and on 2026-09-23 a test run replaced the developer's own login service
    // with a binary under /var/folders.
    if under_temp(&exe) {
        anyhow::bail!(
            "{} is under the temporary directory, and a login service pointing there stops \
             working when it is cleaned up. Install semlith first (`semlith setup`) and \
             register the installed binary.",
            exe.display()
        );
    }
    if let Some(guarded) = tcc_guarded(&exe) {
        anyhow::bail!(
            "this binary is at {} — macOS gates {} for a background login agent, and a launchd job pointing there hangs inside the dynamic linker before it can write a word to its own log. Install semlith outside that directory and run `semlith start --service` from there; `semlith setup` puts it in {}.",
            exe.display(),
            guarded.display(),
            crate::home::bin_dir()
                .map(|d| d.display().to_string())
                .unwrap_or_else(|_| "the semlith home's bin directory".to_string()),
        );
    }
    // A daemon may already be running — started by hand, or by an earlier
    // install. Registering the service is still right, because the point is
    // the next login; starting a second one now is not. It would lose the bind
    // and exit, and launchd's `KeepAlive` and systemd's `Restart=always` would
    // start it again, and again: an install that means "semlith is always
    // there" turning into a process respawning every ten seconds into a log
    // nobody is reading.
    let answering = crate::daemon::port_of(port);
    if already_answering(answering) {
        let mut status = platform::install(&exe, port)?;
        status.started_now = false;
        return Ok(status);
    }
    let mut status = platform::install(&exe, port)?;
    // Whether a daemon actually came up, asked rather than assumed. On Linux
    // `systemctl --user enable --now` reports success and leaves the unit
    // enabled-but-not-running wherever the user session cannot run one — a
    // container, a CI runner, a machine with no lingering — and "enabled" is a
    // statement about the next login, not about now. Reporting that as running
    // is how a page comes to say semlith is there while nothing answers, which
    // is the whole of what this release is about.
    status.started_now = status.installed && waits_for(answering);
    Ok(status)
}

/// The commands that restart an installed login service in place, per
/// mechanism.
///
/// Pure, so all three are pinned by a test on any runner: no CI runner can
/// supervise a user service, so the command is what can be checked there.
/// `enable --now` (systemd) and `bootstrap` (launchd) leave a running daemon
/// running, which is how every client stayed on a 0.30.0 daemon through two
/// upgrades. A logon task has no restart verb, so it is ended and run again.
pub fn restart_commands(mechanism: &str, uid: u32) -> Vec<Vec<String>> {
    let owned = |args: &[&str]| args.iter().map(|a| a.to_string()).collect::<Vec<_>>();
    match mechanism {
        "launchd" => vec![owned(&[
            "launchctl",
            "kickstart",
            "-k",
            &format!("gui/{uid}/{LABEL}"),
        ])],
        "systemd" => vec![owned(&[
            "systemctl",
            "--user",
            "restart",
            "semlith.service",
        ])],
        "schtasks" => vec![
            owned(&["schtasks", "/End", "/TN", "semlith"]),
            owned(&["schtasks", "/Run", "/TN", "semlith"]),
        ],
        _ => Vec::new(),
    }
}

/// Whether a daemon serving `running` has to be restarted for this binary.
/// A daemon at this binary's own version never is.
pub fn is_stale(running: Option<&str>) -> bool {
    running.is_some_and(|v| v != env!("CARGO_PKG_VERSION"))
}

/// Restart the login service when the daemon it runs serves another version.
///
/// `Ok(None)` when nothing had to happen: no daemon, or one at this version.
/// `Ok(Some(previous))` once the new daemon answers at this version, within ten
/// seconds. A daemon started by hand rather than by the service is not this
/// function's to kill; that is an error naming what to do.
pub fn restart_if_stale() -> Result<Option<String>> {
    let running = running_version();
    if !is_stale(running.as_deref()) {
        return Ok(None);
    }
    let previous = running.unwrap_or_default();
    let status = status();
    if !status.installed {
        anyhow::bail!(
            "a semlith {previous} daemon is running, not started by the login service; \
             stop it and run `semlith start` so clients reach {}",
            env!("CARGO_PKG_VERSION")
        );
    }
    #[cfg(unix)]
    let uid = unsafe { libc::getuid() };
    #[cfg(not(unix))]
    let uid = 0;
    for command in restart_commands(status.mechanism, uid) {
        let args: Vec<&str> = command[1..].iter().map(String::as_str).collect();
        // `/End` on a task that already stopped fails and is fine.
        let result = run(&command[0], &args);
        if command.get(1).map(String::as_str) != Some("/End") {
            result.with_context(|| format!("restarting the {} service", status.mechanism))?;
        }
    }
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
    while std::time::Instant::now() < deadline {
        if running_version().as_deref() == Some(env!("CARGO_PKG_VERSION")) {
            return Ok(Some(previous));
        }
        std::thread::sleep(std::time::Duration::from_millis(250));
    }
    anyhow::bail!(
        "restarted the {} service, and no daemon answered at {} within 10 s; see {}",
        status.mechanism,
        env!("CARGO_PKG_VERSION"),
        status
            .log
            .map(|p| p.display().to_string())
            .unwrap_or_else(|| "the service log".into())
    )
}

/// Whether a binary lives under the system's temporary directory.
fn under_temp(exe: &Path) -> bool {
    let temp = std::env::temp_dir();
    let temp = temp.canonicalize().unwrap_or(temp);
    let exe = exe.canonicalize().unwrap_or_else(|_| exe.to_path_buf());
    exe.starts_with(&temp)
        || exe.starts_with("/private/var/folders")
        || exe.starts_with("/var/folders")
}

/// Whether something answers on the port within a few seconds of being asked to.
///
/// A service manager returns as soon as it has accepted the job, not when the
/// job is listening, so a single immediate check would answer "no" on a machine
/// where everything is fine.
fn waits_for(port: u16) -> bool {
    for _ in 0..20 {
        if already_answering(port) {
            return true;
        }
        std::thread::sleep(std::time::Duration::from_millis(250));
    }
    false
}

/// Whether something is already listening on the daemon's port.
///
/// A connect, not a request: this asks whether the bind would fail, which is
/// the only thing the caller is about to care about. Whatever is there may not
/// even be semlith — and if it is not, starting a daemon that cannot bind is
/// still the wrong thing to do.
fn already_answering(port: u16) -> bool {
    std::net::TcpStream::connect_timeout(
        &std::net::SocketAddr::from(([127, 0, 0, 1], port)),
        std::time::Duration::from_millis(300),
    )
    .is_ok()
}

/// The privacy-gated directory this path is inside, if it is inside one.
///
/// Found by running it. `semlith start --service` from a development checkout
/// under `~/Documents` installed cleanly, `launchctl` reported the job running
/// with a live pid — and nothing ever listened on the port, the log stayed
/// zero bytes, and a sample showed the process stopped in `dyld`'s `__open`.
/// It had not finished loading itself. macOS asks a foreground process for
/// consent to read these directories and simply blocks a background agent, so
/// the failure has no error, no log line and no timeout: exactly the silent
/// absence this release exists to remove, reached through the feature that was
/// meant to remove it.
///
/// macOS only. Linux and Windows have no equivalent gate, and a check that
/// refused there would be refusing something that works.
#[allow(unused_variables)]
fn tcc_guarded(exe: &Path) -> Option<PathBuf> {
    #[cfg(target_os = "macos")]
    {
        let home = crate::home::user_home().ok()?;
        [
            "Documents",
            "Desktop",
            "Downloads",
            "Library/Mobile Documents",
        ]
        .iter()
        .map(|name| home.join(name))
        .find(|dir| exe.starts_with(dir))
    }
    #[cfg(not(target_os = "macos"))]
    {
        None
    }
}

/// Remove the login service. `false` when there was nothing to remove, which
/// is not an error — `--no-service` on a machine that never had one is a
/// statement about the end state, not a request that can fail.
pub fn remove() -> Result<bool> {
    platform::remove()
}

/// When the daemon last started, as a unix second.
///
/// Read from the `started` field of any store's discovery file (0.33.0). A file
/// an older daemon wrote has none, and its mtime is the fallback — which is
/// what this function read until then, and which every store open and key
/// rotation moves.
pub fn last_started() -> Option<i64> {
    let registry = crate::home::Registry::load().ok()?;
    registry
        .stores
        .keys()
        .filter_map(|name| crate::home::Registry::dir_of(name).ok())
        .filter_map(|dir| started_from(&dir.join(crate::daemon::DISCOVERY_FILE)))
        .max()
}

fn started_from(path: &Path) -> Option<i64> {
    let text = std::fs::read_to_string(path).ok()?;
    let found: crate::daemon::Discovery = serde_json::from_str(&text).ok()?;
    if found.started > 0 {
        return Some(found.started as i64);
    }
    let at = std::fs::metadata(path).ok()?.modified().ok()?;
    Some(at.duration_since(std::time::UNIX_EPOCH).ok()?.as_secs() as i64)
}

/// The version the running daemon serves, when one is running.
///
/// Through `Discovery::read`, so only a live daemon this user wrote the file
/// for counts. The upgrade path left every client on a 0.30.0 daemon through
/// two releases because nothing compared this with the binary's own.
pub fn running_version() -> Option<String> {
    let registry = crate::home::Registry::load().ok()?;
    registry
        .stores
        .keys()
        .filter_map(|name| crate::home::Registry::dir_of(name).ok())
        .find_map(|dir| crate::daemon::Discovery::read(&dir))
        .map(|found| found.version)
}

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

    /// F1: each mechanism's restart, as the exact argv. `enable --now` and
    /// `bootstrap` would leave the old daemon running.
    #[test]
    fn a_restart_is_the_command_each_mechanism_restarts_with() {
        assert_eq!(
            restart_commands("launchd", 501),
            [["launchctl", "kickstart", "-k", "gui/501/com.semlith.daemon"]]
        );
        assert_eq!(
            restart_commands("systemd", 1000),
            [["systemctl", "--user", "restart", "semlith.service"]]
        );
        assert_eq!(
            restart_commands("schtasks", 0),
            [
                ["schtasks", "/End", "/TN", "semlith"],
                ["schtasks", "/Run", "/TN", "semlith"]
            ]
        );
        assert!(restart_commands("none", 0).is_empty());
    }

    #[test]
    fn a_daemon_at_this_version_is_never_restarted() {
        assert!(!is_stale(None));
        assert!(!is_stale(Some(env!("CARGO_PKG_VERSION"))));
        assert!(is_stale(Some("0.0.1")));
    }

    /// A verbatim path in a service definition is a path a person cannot read
    /// and several tools refuse. Windows produces one from `canonicalize`.
    #[test]
    fn a_verbatim_path_is_written_in_its_plain_spelling() {
        assert_eq!(
            plain(PathBuf::from(r"\\?\C:\Users\me\semlith.exe")),
            PathBuf::from(r"C:\Users\me\semlith.exe"),
        );
        assert_eq!(
            plain(PathBuf::from(r"\\?\UNC\server\share\semlith.exe")),
            PathBuf::from(r"\\server\share\semlith.exe"),
        );
        // A path that is already plain is left exactly as it is.
        assert_eq!(
            plain(PathBuf::from("/usr/local/bin/semlith")),
            PathBuf::from("/usr/local/bin/semlith"),
        );
    }

    /// A launchd agent pointing into a privacy-gated directory does not fail.
    /// It hangs in the dynamic linker with an empty log and a live pid, which
    /// is the one failure mode this release must not ship.
    #[test]
    #[cfg(target_os = "macos")]
    fn a_binary_in_a_privacy_gated_directory_is_refused_rather_than_hung() {
        let home = crate::home::user_home().expect("a home");
        assert_eq!(
            tcc_guarded(&home.join("Documents/code/semlith/target/release/semlith")),
            Some(home.join("Documents")),
        );
        assert_eq!(
            tcc_guarded(&home.join("Desktop/semlith")),
            Some(home.join("Desktop")),
        );
        // The directory semlith installs itself into is not gated, which is
        // what makes the refusal actionable rather than a dead end.
        assert_eq!(tcc_guarded(&home.join(".semlith/bin/semlith")), None);
        assert_eq!(tcc_guarded(Path::new("/usr/local/bin/semlith")), None);
    }

    /// Installing must not start a second daemon onto a port something already
    /// holds. It would lose the bind and exit, and `KeepAlive` would start it
    /// again — an install that means "semlith is always there" becoming a
    /// process respawning into a log nobody reads.
    #[test]
    fn a_port_something_already_holds_is_seen_as_held() {
        let held = std::net::TcpListener::bind(("127.0.0.1", 0)).expect("a port");
        let port = held.local_addr().expect("an address").port();
        assert!(
            already_answering(port),
            "a bound port was not seen as bound"
        );
        drop(held);
        // The negative half against a port this test has just proved free by
        // binding it itself (#141). Checking the port it had held raced every
        // other test in the binary: one that bound an ephemeral port in the
        // gap made "a freed port" answer. A port some other test takes between
        // our bind and our check is retried, within a bound, never excused.
        let free = (0..20).any(|_| {
            let probe = std::net::TcpListener::bind(("127.0.0.1", 0)).expect("a port");
            let port = probe.local_addr().expect("an address").port();
            drop(probe);
            !already_answering(port)
        });
        assert!(
            free,
            "a freed port was still seen as bound, twenty times over"
        );
    }

    /// `remove` on a machine that never had a service is an end state, not a
    /// failure — `semlith start --no-service` has to be safe to run twice.
    #[test]
    fn removing_a_service_that_is_not_installed_is_not_an_error() {
        // This reads `HOME` twice, through `status` and through `remove`, and
        // another test repointing it between the two is what made this fail in
        // a full run and pass on its own.
        let _guard = crate::home::ENV_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        if status().installed {
            // The developer's own machine has one installed; removing it here
            // would be this test deciding something it was not asked to.
            return;
        }
        assert!(matches!(remove(), Ok(false)), "removing nothing failed");
    }
}