trusty-common 0.51.1

Shared utilities and provider-agnostic streaming chat (ChatProvider, OllamaProvider, OpenRouter, tool-use) for trusty-* projects
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
//! macOS launchd LaunchAgent generation and lifecycle management.
//!
//! Why: trusty-search, trusty-analyze, and trusty-memory each hand-rolled
//! launchd plist XML and shelled out to `launchctl` to install their daemons
//! as login agents. The three copies disagreed on how to obtain the user's
//! UID (one used the `nix` crate, one used `libc`, one parsed `id -u` output)
//! and on `KeepAlive` semantics. This module is the single shared
//! implementation.
//!
//! What: a [`LaunchdConfig`] struct that renders plist XML, installs it under
//! `~/Library/LaunchAgents`, and bootstraps/bootouts it via `launchctl`.
//! macOS-only — the whole module is gated behind `#[cfg(target_os = "macos")]`.
//!
//! Test: `render_plist` output is asserted in unit tests (pure string
//! generation). `install`/`bootstrap`/`bootout` shell out and are exercised
//! manually by downstream `setup` commands.
//!
//! [`LaunchdConfig`]: crate::launchd::LaunchdConfig
#![cfg(target_os = "macos")]

use std::path::PathBuf;
use std::process::Command;

use anyhow::{Context, Result};

/// Restart policy for a launchd agent.
///
/// Why: trusty-* daemons want to be restarted automatically, but the two
/// useful policies differ — "always keep alive" versus "restart only when the
/// process exits non-zero". Encoding the choice as an enum prevents callers
/// from hand-writing the wrong `KeepAlive` plist fragment.
/// What: [`KeepAlive::Always`] renders `<key>KeepAlive</key><true/>`;
/// [`KeepAlive::OnSuccess`] renders a dictionary with `SuccessfulExit` set to
/// `false`, telling launchd to restart unless the process exited 0.
/// Test: both variants are covered by `render_plist_*` unit tests.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum KeepAlive {
    /// Keep the process running at all times; restart immediately on exit.
    Always,
    /// Restart only when the process exits non-zero (`SuccessfulExit: false`).
    OnSuccess,
}

/// File-descriptor ceiling emitted into every generated LaunchAgent plist.
///
/// Why: macOS launchd's default soft fd limit for user agents is 256. The
/// trusty-memory daemon opens ~3 redb files per palace (data, KG, vector
/// index) plus sockets, log descriptors, and reqwest connection pools.
/// At 82 palaces that is ~246 fds — right at the ceiling. When the limit is
/// exhausted, `open()` returns EMFILE, palace handles become non-functional,
/// and launchd's `KeepAlive` respawns each crashing instance into a zombie
/// herd (69 observed in the wild) because each new instance fails to bind
/// on the already-occupied port and exits non-zero. 8192 provides headroom
/// for thousands of palaces and matches the `ulimit -n 8192` hand-patch that
/// mitigated the live incident; setting both soft and hard to the same value
/// avoids any unexpected launchd-imposed ceiling below the hard limit.
/// What: the integer rendered into both `SoftResourceLimits` and
/// `HardResourceLimits` dictionaries' `NumberOfFiles` key.
/// Test: `render_plist_includes_resource_limits` asserts both dicts are present
/// with this value.
pub const LAUNCHD_FD_LIMIT: u32 = 8192;

/// Declarative description of a launchd LaunchAgent.
///
/// Why: assembling a plist by hand is error-prone (XML escaping, key ordering,
/// log-path wiring). A struct with a `render_plist` method makes the agent
/// definition data, not code, so every trusty-* setup command produces an
/// identical, correct plist.
/// What: holds the agent label, executable path and args, log directory,
/// restart policy, throttle interval, environment variables, and the optional
/// fd-limit override (defaults to [`LAUNCHD_FD_LIMIT`] for new agents).
/// Methods turn it into XML and drive `launchctl`.
/// Test: `render_plist` output asserted in unit tests; `plist_path` checked
/// against the expected `~/Library/LaunchAgents/<label>.plist` layout.
#[derive(Debug, Clone)]
pub struct LaunchdConfig {
    /// Reverse-DNS-style agent label, e.g. `com.trusty.search`. Also the
    /// plist file's base name.
    pub label: String,
    /// Absolute path to the daemon executable.
    pub exe_path: PathBuf,
    /// Arguments passed to the executable (after `argv[0]`).
    pub args: Vec<String>,
    /// Directory for log files: stdout → `<log_dir>/stdout.log`,
    /// stderr → `<log_dir>/stderr.log`.
    pub log_dir: PathBuf,
    /// Restart policy.
    pub keep_alive: KeepAlive,
    /// Minimum seconds between successive launches (launchd `ThrottleInterval`).
    pub throttle_interval: u32,
    /// Extra environment variables for the daemon process.
    pub env_vars: Vec<(String, String)>,
    /// `NumberOfFiles` written into both `SoftResourceLimits` and
    /// `HardResourceLimits` plist dicts. `None` suppresses both dicts
    /// (useful for agents that do not open many files). New agents should
    /// leave this as `Some(LAUNCHD_FD_LIMIT)` (the default via
    /// `LaunchdConfig::new`).
    pub fd_limit: Option<u32>,
    /// `WorkingDirectory`, when the agent needs one. `None` omits the key.
    ///
    /// #4919: exists so a regenerated unit can carry forward a
    /// `WorkingDirectory` the installed one had. Before install started
    /// overwriting the live plist this was invisible; now dropping it would be
    /// a silent behaviour change on every upgrade.
    pub working_directory: Option<String>,
}

impl LaunchdConfig {
    /// Ensure the agent's environment exports a full `PATH` covering Homebrew
    /// and user bin dirs, returning `self` for builder-style chaining.
    ///
    /// Why: macOS launchd relaunches LaunchAgents with a minimal `PATH`
    /// (`/usr/bin:/bin:/usr/sbin:/sbin`). Daemons that shell out to Homebrew or
    /// user-installed tools (`tmux` at `/opt/homebrew/bin`, `claude` at
    /// `~/.local/bin`) then fail before reaching application logic, and every
    /// daemon restart re-breaks them until the plist is hand-patched (#1298).
    /// Seeding `PATH` into the generated plist makes the fix survive restarts.
    /// What: if the caller has not already supplied a `PATH` env var, pushes a
    /// `("PATH", `[`crate::bin_resolve::daemon_path_env`]`())` entry. A
    /// caller-provided `PATH` is left untouched so explicit overrides win.
    /// Test: `with_daemon_path_seeds_full_path`,
    /// `with_daemon_path_preserves_explicit_path`.
    #[must_use]
    pub fn with_daemon_path(mut self) -> Self {
        let has_path = self.env_vars.iter().any(|(k, _)| k == "PATH");
        if !has_path {
            self.env_vars
                .push(("PATH".to_string(), crate::bin_resolve::daemon_path_env()));
        }
        self
    }

    /// Render the launchd plist XML for this agent.
    ///
    /// Why: launchd consumes a property-list XML document; generating it in one
    /// audited place avoids the escaping and key-ordering bugs that plagued the
    /// three sibling implementations.
    /// What: returns a complete plist `String` with `Label`, `ProgramArguments`
    /// (exe + args), `KeepAlive` (per [`KeepAlive`]), `ThrottleInterval`,
    /// `RunAtLoad`, `StandardOutPath`/`StandardErrorPath` under `log_dir`,
    /// `SoftResourceLimits` + `HardResourceLimits` dicts (when `fd_limit` is
    /// `Some`), `ExitTimeOut` (#4393, from
    /// [`crate::shutdown::TERMINATION_GRACE_SECS`]), and an
    /// `EnvironmentVariables` dictionary when `env_vars` is non-empty. All
    /// string values are XML-escaped.
    /// Test: `render_plist_contains_core_keys`, `render_plist_keepalive_*`,
    /// `render_plist_escapes_xml`, `render_plist_includes_resource_limits`,
    /// `render_plist_declares_exit_timeout`.
    pub fn render_plist(&self) -> Result<String> {
        let exe = self
            .exe_path
            .to_str()
            .context("exe_path is not valid UTF-8")?;
        let stdout = self.log_dir.join("stdout.log");
        let stderr = self.log_dir.join("stderr.log");
        let stdout = stdout
            .to_str()
            .context("stdout log path is not valid UTF-8")?;
        let stderr = stderr
            .to_str()
            .context("stderr log path is not valid UTF-8")?;

        let mut s = String::new();
        s.push_str("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
        s.push_str(
            "<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \
             \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n",
        );
        s.push_str("<plist version=\"1.0\">\n");
        s.push_str("<dict>\n");

        s.push_str("  <key>Label</key>\n");
        s.push_str(&format!("  <string>{}</string>\n", xml_escape(&self.label)));

        s.push_str("  <key>ProgramArguments</key>\n");
        s.push_str("  <array>\n");
        s.push_str(&format!("    <string>{}</string>\n", xml_escape(exe)));
        for arg in &self.args {
            s.push_str(&format!("    <string>{}</string>\n", xml_escape(arg)));
        }
        s.push_str("  </array>\n");

        s.push_str("  <key>KeepAlive</key>\n");
        match self.keep_alive {
            KeepAlive::Always => s.push_str("  <true/>\n"),
            KeepAlive::OnSuccess => {
                s.push_str("  <dict>\n");
                s.push_str("    <key>SuccessfulExit</key>\n");
                s.push_str("    <false/>\n");
                s.push_str("  </dict>\n");
            }
        }

        s.push_str("  <key>RunAtLoad</key>\n");
        s.push_str("  <true/>\n");

        s.push_str("  <key>ThrottleInterval</key>\n");
        s.push_str(&format!(
            "  <integer>{}</integer>\n",
            self.throttle_interval
        ));

        // #4393: without this key launchd applies its "system-defined" default,
        // measured at 5 s on macOS — SIGTERM, then SIGKILL 5 s later. Every
        // termination path routes through it: `launchctl bootout`, `launchctl
        // kickstart -k` (measured: SIGTERM first, SIGKILL at exactly the
        // ExitTimeOut boundary), and logout/reboot. trusty-search's shutdown
        // flush floors each index at 30 s, so it was cut off mid-write on all of
        // them. Rendered from the shared constant rather than a per-agent field
        // so the window a daemon PLANS for and the window launchd GRANTS cannot
        // disagree.
        s.push_str("  <key>ExitTimeOut</key>\n");
        s.push_str(&format!(
            "  <integer>{}</integer>\n",
            crate::shutdown::TERMINATION_GRACE_SECS
        ));

        // #4919: carried forward from the installed unit when it had one.
        if let Some(wd) = &self.working_directory {
            s.push_str("  <key>WorkingDirectory</key>\n");
            s.push_str(&format!("  <string>{}</string>\n", xml_escape(wd)));
        }

        s.push_str("  <key>StandardOutPath</key>\n");
        s.push_str(&format!("  <string>{}</string>\n", xml_escape(stdout)));
        s.push_str("  <key>StandardErrorPath</key>\n");
        s.push_str(&format!("  <string>{}</string>\n", xml_escape(stderr)));

        // Soft + hard fd limits — both dicts must be present so the hard
        // ceiling matches the soft request and launchd cannot silently clamp
        // the soft limit below what we asked for.
        if let Some(fd) = self.fd_limit {
            for key in &["SoftResourceLimits", "HardResourceLimits"] {
                s.push_str(&format!("  <key>{key}</key>\n"));
                s.push_str("  <dict>\n");
                s.push_str("    <key>NumberOfFiles</key>\n");
                s.push_str(&format!("    <integer>{fd}</integer>\n"));
                s.push_str("  </dict>\n");
            }
        }

        if !self.env_vars.is_empty() {
            s.push_str("  <key>EnvironmentVariables</key>\n");
            s.push_str("  <dict>\n");
            for (k, v) in &self.env_vars {
                s.push_str(&format!("    <key>{}</key>\n", xml_escape(k)));
                s.push_str(&format!("    <string>{}</string>\n", xml_escape(v)));
            }
            s.push_str("  </dict>\n");
        }

        s.push_str("</dict>\n");
        s.push_str("</plist>\n");
        Ok(s)
    }

    /// Return the install path for this agent's plist:
    /// `~/Library/LaunchAgents/<label>.plist`.
    ///
    /// Why: launchd discovers per-user agents in `~/Library/LaunchAgents`.
    /// Centralising the path keeps install and uninstall in agreement.
    /// What: joins the user's home directory with
    /// `Library/LaunchAgents/<label>.plist`. Errors if the home directory
    /// cannot be resolved.
    /// Test: `plist_path_layout`.
    pub fn plist_path(&self) -> Result<PathBuf> {
        plist_path_for_label(&self.label).context("could not resolve home directory")
    }

    /// Install the agent: write the plist and ensure the log directory exists.
    ///
    /// Why: `launchctl bootstrap` fails if the plist file or the log directory
    /// it references is missing. Doing both in one call removes a footgun.
    /// What: creates `~/Library/LaunchAgents` and `log_dir` if absent, then
    /// writes the rendered plist to [`plist_path`](Self::plist_path). Does not
    /// load the agent — call [`bootstrap`](Self::bootstrap) for that.
    /// Test: side-effecting filesystem write; exercised by downstream `setup`.
    pub fn install(&self) -> Result<()> {
        let plist = self.plist_path()?;
        if let Some(parent) = plist.parent() {
            std::fs::create_dir_all(parent)
                .with_context(|| format!("create LaunchAgents dir {}", parent.display()))?;
        }
        std::fs::create_dir_all(&self.log_dir)
            .with_context(|| format!("create log dir {}", self.log_dir.display()))?;
        let xml = self.render_plist()?;
        std::fs::write(&plist, xml).with_context(|| format!("write plist {}", plist.display()))?;
        Ok(())
    }

    /// Bootstrap (load and start) the agent via `launchctl`, idempotently.
    ///
    /// Why: `launchctl bootstrap` errors if the agent is already loaded.
    /// Re-running a `setup` command must not fail for that reason, so we
    /// bootout first and ignore the "not loaded" error.
    /// What: calls [`bootout`](Self::bootout) (ignoring its result), then runs
    /// `launchctl bootstrap gui/<uid> <plist_path>`. Requires the plist to
    /// already be installed via [`install`](Self::install).
    /// Test: side-effecting `launchctl` call; exercised manually.
    pub fn bootstrap(&self) -> Result<()> {
        // Best-effort unload first so bootstrap doesn't trip on an existing
        // registration.
        let _ = self.bootout();

        let plist = self.plist_path()?;
        let domain = format!("gui/{}", current_uid());
        let output = Command::new("launchctl")
            .arg("bootstrap")
            .arg(&domain)
            .arg(&plist)
            .output()
            .context("spawn launchctl bootstrap")?;
        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            anyhow::bail!(
                "launchctl bootstrap {} {} failed: {}",
                domain,
                plist.display(),
                stderr.trim()
            );
        }
        Ok(())
    }

    /// Report whether the agent is currently loaded in the GUI domain.
    ///
    /// Why: `tctl start` right after `tctl install` (#2556) would otherwise
    /// unconditionally call [`bootstrap`](Self::bootstrap) — which itself
    /// boots the agent OUT first — bouncing a daemon that the install's own
    /// service-bootstrap step just started seconds earlier. A cheap
    /// `launchctl print` check lets the caller skip that redundant restart
    /// when the agent is already loaded and running (#2566 review, item 4).
    /// What: runs `launchctl print gui/<uid>/<label>` and returns whether it
    /// exited successfully (launchctl exits non-zero when the label is not
    /// loaded). Never errors — an inability to query is treated as "not
    /// loaded" so the caller falls back to the safe (bootstrap) path.
    /// Test: side-effecting `launchctl` call; exercised manually (mirrors the
    /// `service status` subcommands' identical `launchctl print` check).
    pub fn is_loaded(&self) -> bool {
        label_is_loaded(&self.label)
    }

    /// Bootout (stop and unload) the agent via `launchctl`.
    ///
    /// Why: uninstalling or re-bootstrapping an agent requires removing the
    /// existing registration. A not-loaded agent is not an error condition for
    /// callers, so that case returns `Ok(())`.
    /// What: runs `launchctl bootout gui/<uid>/<label>`. Returns `Ok(())` on
    /// success or when `launchctl` reports the agent is not loaded; any other
    /// failure propagates as `Err`.
    /// Test: side-effecting `launchctl` call; exercised manually.
    pub fn bootout(&self) -> Result<()> {
        let domain_target = format!("gui/{}/{}", current_uid(), self.label);
        let output = Command::new("launchctl")
            .arg("bootout")
            .arg(&domain_target)
            .output()
            .context("spawn launchctl bootout")?;
        if output.status.success() {
            return Ok(());
        }
        let stderr = String::from_utf8_lossy(&output.stderr).to_lowercase();
        // launchctl reports a not-loaded agent in a few phrasings / exit codes.
        if stderr.contains("no such process")
            || stderr.contains("not find")
            || stderr.contains("not loaded")
            || stderr.contains("could not find specified service")
        {
            return Ok(());
        }
        anyhow::bail!(
            "launchctl bootout {} failed: {}",
            domain_target,
            stderr.trim()
        );
    }
}

/// Where launchd looks for the per-user agent named `label`.
///
/// Why (#6619): a caller that has only a label — the on-demand spawn guard
/// asking whether a unit is installed for the socket it is about to bind — would
/// otherwise assemble this path itself, and a second spelling of
/// `~/Library/LaunchAgents/<label>.plist` is exactly the drift the
/// common-entry-point rule exists to prevent.
/// What: `~/Library/LaunchAgents/<label>.plist`. `None` when the home directory
/// cannot be resolved. [`LaunchdConfig::plist_path`] is this over its own label.
/// Test: `plist_path_layout` covers the layout through the method;
/// `plist_path_for_label_matches_the_config_method` keeps the two in step.
#[must_use]
pub fn plist_path_for_label(label: &str) -> Option<PathBuf> {
    Some(
        dirs::home_dir()?
            .join("Library")
            .join("LaunchAgents")
            .join(format!("{label}.plist")),
    )
}

/// Whether launchd currently has `label` loaded in the GUI domain.
///
/// Why (#6619): same reason as [`plist_path_for_label`] — a label-only caller
/// must reach launchd through the one `launchctl print` this crate owns rather
/// than spawning its own.
/// What: runs `launchctl print gui/<uid>/<label>` and reports whether it exited
/// successfully; launchctl exits non-zero for a label it does not have. Never
/// errors — an inability to query reads as "not loaded", so callers fall back to
/// their safe path. [`LaunchdConfig::is_loaded`] is this over its own label.
/// Test: side-effecting `launchctl` call; exercised manually.
#[must_use]
pub fn label_is_loaded(label: &str) -> bool {
    let target = format!("gui/{}/{label}", current_uid());
    Command::new("launchctl")
        .args(["print", &target])
        .output()
        .map(|o| o.status.success())
        .unwrap_or(false)
}

/// Return the current process's real user ID.
///
/// Why: launchd's per-user GUI domain is addressed as `gui/<uid>`. The three
/// sibling projects each resolved the UID differently (`nix`, `libc`, shelling
/// out to `id -u`); this is the single shared, dependency-light answer.
/// What: returns `libc::getuid()`. The call is always safe — `getuid` cannot
/// fail and has no preconditions.
/// Test: `current_uid_is_nonzero_for_normal_user` sanity-checks the value is
/// plausible (developers don't run the test suite as root).
pub fn current_uid() -> u32 {
    // SAFETY: getuid() is a POSIX call with no arguments and no failure mode.
    unsafe { libc::getuid() }
}

/// Escape a string for safe inclusion in plist XML text content.
fn xml_escape(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for c in s.chars() {
        match c {
            '&' => out.push_str("&amp;"),
            '<' => out.push_str("&lt;"),
            '>' => out.push_str("&gt;"),
            '"' => out.push_str("&quot;"),
            '\'' => out.push_str("&apos;"),
            other => out.push(other),
        }
    }
    out
}

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

    fn sample(keep_alive: KeepAlive) -> LaunchdConfig {
        LaunchdConfig {
            label: "com.trusty.search".to_string(),
            exe_path: PathBuf::from("/usr/local/bin/trusty-search"),
            args: vec![
                "daemon".to_string(),
                "--port".to_string(),
                "7777".to_string(),
            ],
            log_dir: PathBuf::from("/Users/test/Library/Logs/trusty-search"),
            keep_alive,
            throttle_interval: 10,
            env_vars: vec![],
            fd_limit: Some(LAUNCHD_FD_LIMIT),
            working_directory: None,
        }
    }

    #[test]
    fn render_plist_contains_core_keys() {
        let xml = sample(KeepAlive::Always).render_plist().unwrap();
        assert!(xml.contains("<key>Label</key>"));
        assert!(xml.contains("<string>com.trusty.search</string>"));
        assert!(xml.contains("<string>/usr/local/bin/trusty-search</string>"));
        assert!(xml.contains("<string>daemon</string>"));
        assert!(xml.contains("<key>ThrottleInterval</key>"));
        assert!(xml.contains("<integer>10</integer>"));
        assert!(xml.contains("<key>RunAtLoad</key>"));
        assert!(xml.contains("stdout.log"));
        assert!(xml.contains("stderr.log"));
        assert!(xml.trim_end().ends_with("</plist>"));
    }

    #[test]
    fn render_plist_keepalive_always() {
        let xml = sample(KeepAlive::Always).render_plist().unwrap();
        assert!(xml.contains("<key>KeepAlive</key>\n  <true/>"));
        assert!(!xml.contains("SuccessfulExit"));
    }

    #[test]
    fn render_plist_keepalive_on_success() {
        let xml = sample(KeepAlive::OnSuccess).render_plist().unwrap();
        assert!(xml.contains("<key>SuccessfulExit</key>"));
        assert!(xml.contains("<false/>"));
    }

    #[test]
    fn render_plist_includes_env_vars() {
        let mut cfg = sample(KeepAlive::Always);
        cfg.env_vars = vec![("RUST_LOG".to_string(), "info".to_string())];
        let xml = cfg.render_plist().unwrap();
        assert!(xml.contains("<key>EnvironmentVariables</key>"));
        assert!(xml.contains("<key>RUST_LOG</key>"));
        assert!(xml.contains("<string>info</string>"));
    }

    /// Why: #1298 — every generated launchd plist for a daemon that spawns
    /// `tmux`/`claude` must export a `PATH` covering Homebrew and the expanded
    /// user bin dirs, or the daemon fails after each restart under launchd's
    /// minimal `PATH`. This asserts the rendered plist carries that `PATH`.
    /// What: builds a config with `with_daemon_path`, renders, and checks the
    /// `EnvironmentVariables` `PATH` string contains `/opt/homebrew/bin`, the
    /// expanded `~/.local/bin`, and the expanded `~/.cargo/bin`.
    /// Test: itself.
    #[test]
    fn with_daemon_path_seeds_full_path() {
        let home = dirs::home_dir().expect("home dir resolvable in test env");
        let xml = sample(KeepAlive::Always)
            .with_daemon_path()
            .render_plist()
            .unwrap();
        assert!(xml.contains("<key>EnvironmentVariables</key>"));
        assert!(xml.contains("<key>PATH</key>"));
        assert!(
            xml.contains("/opt/homebrew/bin"),
            "plist PATH must include Homebrew bin dir"
        );
        assert!(
            xml.contains(home.join(".local/bin").to_str().unwrap()),
            "plist PATH must include expanded ~/.local/bin"
        );
        assert!(
            xml.contains(home.join(".cargo/bin").to_str().unwrap()),
            "plist PATH must include expanded ~/.cargo/bin"
        );
    }

    #[test]
    fn with_daemon_path_preserves_explicit_path() {
        let mut cfg = sample(KeepAlive::Always);
        cfg.env_vars = vec![("PATH".to_string(), "/custom/only".to_string())];
        let cfg = cfg.with_daemon_path();
        let path_entries: Vec<&(String, String)> =
            cfg.env_vars.iter().filter(|(k, _)| k == "PATH").collect();
        assert_eq!(path_entries.len(), 1, "must not duplicate an explicit PATH");
        assert_eq!(path_entries[0].1, "/custom/only");
    }

    #[test]
    fn render_plist_omits_env_block_when_empty() {
        let xml = sample(KeepAlive::Always).render_plist().unwrap();
        assert!(!xml.contains("EnvironmentVariables"));
    }

    /// Why: The fd-exhaustion bug (246 open fds for 82 palaces against a 256
    /// soft limit) required a manual plist hand-patch to survive. This test
    /// asserts that every generated plist carries both `SoftResourceLimits`
    /// and `HardResourceLimits` with the canonical value so the fix survives
    /// refactors and `service start` / `service install` regenerations.
    /// What: renders a plist with `fd_limit = Some(LAUNCHD_FD_LIMIT)` and
    /// asserts both resource-limit dicts and the integer value appear. Also
    /// asserts that `fd_limit = None` suppresses both dicts.
    /// Test: itself.
    #[test]
    fn render_plist_includes_resource_limits() {
        let xml = sample(KeepAlive::OnSuccess).render_plist().unwrap();
        assert!(
            xml.contains("<key>SoftResourceLimits</key>"),
            "SoftResourceLimits must be present"
        );
        assert!(
            xml.contains("<key>HardResourceLimits</key>"),
            "HardResourceLimits must be present"
        );
        assert!(
            xml.contains(&format!("<integer>{LAUNCHD_FD_LIMIT}</integer>")),
            "NumberOfFiles must equal LAUNCHD_FD_LIMIT ({LAUNCHD_FD_LIMIT})"
        );

        // When fd_limit is None, neither dict should appear.
        let mut cfg = sample(KeepAlive::Always);
        cfg.fd_limit = None;
        let xml_no_limits = cfg.render_plist().unwrap();
        assert!(
            !xml_no_limits.contains("SoftResourceLimits"),
            "fd_limit=None must suppress SoftResourceLimits"
        );
        assert!(
            !xml_no_limits.contains("HardResourceLimits"),
            "fd_limit=None must suppress HardResourceLimits"
        );
    }

    /// Why (#4393 — the regression this test exists for): the renderer emitted
    /// no `ExitTimeOut` key at all, so launchd applied its "system-defined"
    /// default, measured at 5 s on this host. A daemon whose shutdown flush
    /// floors at 30 s per index was therefore SIGKILLed mid-write on every
    /// launchd-mediated termination — `bootout`, `kickstart -k`, logout.
    /// What: asserts the key is present, carries
    /// [`crate::shutdown::TERMINATION_GRACE_SECS`], and that the rendered
    /// window clears the measured 5 s default it replaces.
    /// Test: itself.
    #[test]
    fn render_plist_declares_exit_timeout() {
        let xml = sample(KeepAlive::Always).render_plist().unwrap();
        assert!(
            xml.contains("<key>ExitTimeOut</key>"),
            "plist must declare ExitTimeOut or launchd applies its 5 s default (#4393)"
        );
        assert!(
            xml.contains(&format!(
                "<key>ExitTimeOut</key>\n  <integer>{}</integer>",
                crate::shutdown::TERMINATION_GRACE_SECS
            )),
            "ExitTimeOut must carry the shared termination grace, got:\n{xml}"
        );
        // `const` block: the operands are compile-time constants, so a later
        // edit that shortens the window back toward launchd's default fails the
        // build rather than a test run.
        const {
            assert!(
                crate::shutdown::TERMINATION_GRACE_SECS > 5,
                "rendering the measured system default would leave #4393 unfixed"
            );
        }
    }

    #[test]
    fn render_plist_escapes_xml() {
        let mut cfg = sample(KeepAlive::Always);
        cfg.args = vec!["--name".to_string(), "a&b<c>\"d\"".to_string()];
        let xml = cfg.render_plist().unwrap();
        assert!(xml.contains("a&amp;b&lt;c&gt;&quot;d&quot;"));
        assert!(!xml.contains("a&b<c>"));
    }

    #[test]
    fn plist_path_layout() {
        let p = sample(KeepAlive::Always).plist_path().unwrap();
        assert!(p.ends_with("Library/LaunchAgents/com.trusty.search.plist"));
    }

    /// Why (#6621): a label-only caller must resolve the SAME path an install
    /// wrote, or a staleness check reads a file launchd never had. The method
    /// delegates to the free function, and this is what keeps that true.
    /// Test: this is the test.
    #[test]
    fn plist_path_for_label_matches_the_config_method() {
        let cfg = sample(KeepAlive::Always);
        assert_eq!(
            plist_path_for_label(&cfg.label).unwrap(),
            cfg.plist_path().unwrap()
        );
    }

    #[test]
    fn current_uid_is_nonzero_for_normal_user() {
        // CI and developer machines do not run tests as root.
        assert_ne!(current_uid(), 0, "test suite should not run as root");
    }

    #[test]
    fn xml_escape_handles_all_entities() {
        assert_eq!(xml_escape("&<>\"'"), "&amp;&lt;&gt;&quot;&apos;");
        assert_eq!(xml_escape("plain"), "plain");
    }
}