allot-cli 0.5.0

CLI for Allot: status, leases, history, daemon control, install, and the PreToolUse hook
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
//! Runs the built `allot install` and `allot uninstall` against a temporary `HOME` on Linux and
//! macOS. Stand-ins for `systemctl` and `launchctl` come first on `PATH`: they log their
//! arguments and keep a marker file for the enabled or loaded state, so no test touches the
//! runner's own user manager or launchd.

#![cfg(unix)]

use std::{
    env, fs,
    net::{Ipv4Addr, TcpListener},
    os::unix::fs::{PermissionsExt, symlink},
    path::{Path, PathBuf},
    process::{self, Command, Output, Stdio},
};

const BINARIES: [&str; 3] = ["allot", "allotd", "allot-mcp"];

/// A home directory with a build output to install from, a config that points at a port nothing
/// listens on, a `~/.local/bin`, and the stand-ins for the service managers.
struct Home(PathBuf);

impl Home {
    fn new(name: &str) -> Self {
        Self::with_managers(name, true)
    }

    /// `working` false: every `systemctl` and `launchctl` call fails, as without a user manager
    /// or a GUI login.
    fn with_managers(name: &str, working: bool) -> Self {
        let root = env::temp_dir().join(format!("allot-install-unix-{}-{name}", process::id()));
        let _ = fs::remove_dir_all(&root);
        let app = root.join(".allot");
        fs::create_dir_all(&app).unwrap();
        let port = TcpListener::bind((Ipv4Addr::LOCALHOST, 0))
            .unwrap()
            .local_addr()
            .unwrap()
            .port();
        fs::write(
            app.join("config.toml"),
            format!("[daemon]\nport = {port}\n"),
        )
        .unwrap();
        fs::create_dir_all(root.join(".local").join("bin")).unwrap();

        // Only allot has to run; the other two are never started by these tests.
        let build = root.join("build");
        fs::create_dir_all(&build).unwrap();
        fs::copy(env!("CARGO_BIN_EXE_allot"), build.join("allot")).unwrap();
        fs::write(build.join("allotd"), "allotd").unwrap();
        fs::write(build.join("allot-mcp"), "allot-mcp").unwrap();

        let home = Self(root);
        home.write_managers(working);
        home
    }

    fn write_managers(&self, working: bool) {
        let fakes = self.fakes();
        let state = self.0.join("state");
        fs::create_dir_all(&fakes).unwrap();
        fs::create_dir_all(&state).unwrap();
        let log = self.log();
        let (log, state) = (log.display(), state.display());
        let fail = if working {
            ""
        } else {
            "echo 'not available here' >&2; exit 1\n"
        };
        let systemctl = format!(
            "#!/bin/sh\necho \"systemctl $*\" >> '{log}'\n{fail}\
             case \"$2\" in\n\
             is-enabled) if [ -e '{state}/enabled' ]; then echo enabled; exit 0; fi; \
             echo disabled; exit 1;;\n\
             enable) touch '{state}/enabled';;\n\
             disable) rm -f '{state}/enabled';;\n\
             esac\nexit 0\n"
        );
        let launchctl = format!(
            "#!/bin/sh\necho \"launchctl $*\" >> '{log}'\n{fail}\
             case \"$1\" in\n\
             print) if [ -e '{state}/loaded' ]; then exit 0; fi; exit 113;;\n\
             bootstrap) touch '{state}/loaded';;\n\
             bootout) rm -f '{state}/loaded';;\n\
             esac\nexit 0\n"
        );
        for (name, script) in [("systemctl", systemctl), ("launchctl", launchctl)] {
            let path = fakes.join(name);
            fs::write(&path, script).unwrap();
            fs::set_permissions(&path, fs::Permissions::from_mode(0o755)).unwrap();
        }
    }

    fn fakes(&self) -> PathBuf {
        self.0.join("fakes")
    }

    fn log(&self) -> PathBuf {
        self.0.join("calls.log")
    }

    /// The service manager calls so far, one per line.
    fn calls(&self) -> Vec<String> {
        fs::read_to_string(self.log())
            .unwrap_or_default()
            .lines()
            .map(str::to_owned)
            .collect()
    }

    fn app(&self) -> PathBuf {
        self.0.join(".allot")
    }

    fn bin(&self) -> PathBuf {
        self.app().join("bin")
    }

    fn build(&self) -> PathBuf {
        self.0.join("build")
    }

    fn link(&self) -> PathBuf {
        self.0.join(".local").join("bin").join("allot")
    }

    fn claude(&self, name: &str) -> PathBuf {
        self.0.join(".claude").join(name)
    }

    /// The autostart file this OS uses.
    fn autostart(&self) -> PathBuf {
        if cfg!(target_os = "macos") {
            self.0.join("Library/LaunchAgents/tech.mehran.allotd.plist")
        } else {
            self.0.join(".config/systemd/user/allotd.service")
        }
    }

    /// Runs the built `allot` in this home. `claude` points nowhere, so no test registers the
    /// MCP server with the real Claude Code.
    fn allot(&self, args: &[&str]) -> Output {
        self.allot_on_desktop(args, "")
    }

    /// As [`Self::allot`], with `$XDG_CURRENT_DESKTOP` set to `desktop`.
    fn allot_on_desktop(&self, args: &[&str], desktop: &str) -> Output {
        self.run(Path::new(env!("CARGO_BIN_EXE_allot")), args, desktop)
    }

    fn run(&self, exe: &Path, args: &[&str], desktop: &str) -> Output {
        let path = format!(
            "{}:{}",
            self.fakes().display(),
            env::var("PATH").unwrap_or_default()
        );
        Command::new(exe)
            .args(args)
            .env("HOME", &self.0)
            .env("XDG_CONFIG_HOME", self.0.join(".config"))
            .env("XDG_DATA_HOME", self.0.join(".local/share"))
            .env_remove("BASH_COMPLETION_USER_DIR")
            .env("XDG_CURRENT_DESKTOP", desktop)
            .env("ALLOT_CLAUDE", self.0.join("no-claude"))
            .env("PATH", path)
            .stdin(Stdio::null())
            .output()
            .unwrap()
    }

    fn install_with(&self, extra: &[&str]) -> String {
        let build = self.build();
        let mut args = vec!["install", "--from", build.to_str().unwrap()];
        args.extend(extra);
        let output = self.allot(&args);
        assert!(output.status.success(), "{output:?}");
        String::from_utf8(output.stdout).unwrap()
    }

    fn install(&self) -> String {
        self.install_with(&[])
    }

    fn uninstall(&self) -> String {
        let output = self.allot(&["uninstall"]);
        assert!(output.status.success(), "{output:?}");
        String::from_utf8(output.stdout).unwrap()
    }
}

impl Drop for Home {
    fn drop(&mut self) {
        let _ = fs::remove_dir_all(&self.0);
    }
}

fn uid() -> u32 {
    // SAFETY: getuid has no preconditions and cannot fail.
    unsafe { libc::getuid() }
}

fn bin_names(bin: &Path) -> Vec<String> {
    let mut names: Vec<_> = fs::read_dir(bin)
        .unwrap()
        .map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned())
        .collect();
    names.sort();
    names
}

#[test]
fn test_install_through_a_link_takes_the_binaries_beside_the_real_file() {
    let home = Home::new("through-link");
    let links = home.0.join("links");
    fs::create_dir_all(&links).unwrap();
    let link = links.join("allot");
    symlink(home.build().join("allot"), &link).unwrap();

    let output = home.run(&link, &["install"], "");

    assert!(output.status.success(), "{output:?}");
    for name in BINARIES {
        assert!(home.bin().join(name).is_file(), "{name}");
    }
}

#[test]
fn test_install_copies_binaries_links_allot_and_registers_hooks() {
    let home = Home::new("fresh");
    let stdout = home.install();

    for name in BINARIES {
        let installed = home.bin().join(name);
        assert_eq!(
            fs::read(&installed).unwrap(),
            fs::read(home.build().join(name)).unwrap(),
            "{name}"
        );
        let mode = fs::metadata(&installed).unwrap().permissions().mode();
        assert_eq!(mode & 0o777, 0o755, "{name}");
    }
    assert_eq!(bin_names(&home.bin()), ["allot", "allot-mcp", "allotd"]);
    assert_eq!(
        fs::read_link(home.link()).unwrap(),
        home.bin().join("allot")
    );
    assert!(stdout.contains("linked "), "{stdout}");

    let config: serde_json::Value =
        serde_json::from_str(&fs::read_to_string(home.0.join(".claude.json")).unwrap()).unwrap();
    assert_eq!(
        config["mcpServers"]["allot"]["command"],
        home.bin().join("allot-mcp").to_str().unwrap()
    );
    let settings: serde_json::Value =
        serde_json::from_str(&fs::read_to_string(home.claude("settings.json")).unwrap()).unwrap();
    assert_eq!(
        settings["hooks"]["PreToolUse"][0]["hooks"][0]["command"],
        home.bin().join("allot").to_str().unwrap()
    );
    assert_eq!(
        fs::read_to_string(home.claude("CLAUDE.md")).unwrap(),
        "@allot.md\n"
    );
    assert!(
        home.claude("skills/resource-guard/SKILL.md").is_file(),
        "{stdout}"
    );
    // The autostart started allotd, so nothing says it is not running.
    assert!(!stdout.contains("allotd is not running"), "{stdout}");
}

#[test]
fn test_install_sets_up_autostart_once() {
    let home = Home::new("autostart");
    let stdout = home.install();
    let allotd = home.bin().join("allotd");
    let file = home.autostart();
    let text = fs::read_to_string(&file).unwrap();
    let calls = home.calls();
    assert!(
        stdout.contains(&format!(
            "4. [done] allotd at login, {} {} (registered and started)",
            if cfg!(target_os = "macos") {
                "LaunchAgent"
            } else {
                "systemd user unit"
            },
            file.display()
        )),
        "{stdout}"
    );
    if cfg!(target_os = "macos") {
        assert!(
            text.contains(&format!("<string>{}</string>", allotd.display())),
            "{text}"
        );
        assert!(
            calls.contains(&format!(
                "launchctl bootstrap gui/{} {}",
                uid(),
                file.display()
            )),
            "{calls:?}"
        );
    } else {
        assert!(
            text.contains(&format!("ExecStart=\"{}\"", allotd.display())),
            "{text}"
        );
        assert!(text.contains("WantedBy=default.target"), "{text}");
        assert!(
            calls.contains(&"systemctl --user daemon-reload".to_owned()),
            "{calls:?}"
        );
        assert!(
            calls.contains(&"systemctl --user enable --now allotd.service".to_owned()),
            "{calls:?}"
        );
    }

    let before = calls.len();
    let stdout = home.install();
    assert!(
        stdout.contains("4. [done] allotd at login") && !stdout.contains("started)"),
        "{stdout}"
    );
    let again = &home.calls()[before..];
    assert!(
        !again
            .iter()
            .any(|call| call.contains("daemon-reload") || call.contains("bootstrap")),
        "{again:?}"
    );
}

#[test]
fn test_install_replaces_a_unit_or_agent_for_another_allotd() {
    let home = Home::new("other-allotd");
    let file = home.autostart();
    fs::create_dir_all(file.parent().unwrap()).unwrap();
    let old = if cfg!(target_os = "macos") {
        allot_shared::autostart::launch_agent(Path::new("/dev/allotd"))
    } else {
        allot_shared::autostart::systemd_unit(Path::new("/dev/allotd"))
    };
    fs::write(&file, old).unwrap();

    let stdout = home.install();

    assert!(
        stdout.contains("(updated and started; it started /dev/allotd before)"),
        "{stdout}"
    );
    assert!(
        fs::read_to_string(&file)
            .unwrap()
            .contains(home.bin().join("allotd").to_str().unwrap())
    );
}

#[test]
fn test_install_without_a_service_manager_prints_the_steps() {
    let home = Home::with_managers("no-manager", false);
    let stdout = home.install();

    assert!(stdout.contains("4. [todo] allotd at login"), "{stdout}");
    if cfg!(target_os = "macos") {
        assert!(
            stdout.contains(&format!("launchctl bootstrap gui/{} \"", uid())),
            "{stdout}"
        );
    } else {
        assert!(
            stdout.contains("systemctl --user enable --now allotd.service"),
            "{stdout}"
        );
    }
    // Nothing set up allotd's start, so the first session starts it.
    assert!(
        stdout.contains("allotd is not running; the first session starts it"),
        "{stdout}"
    );
}

#[test]
fn test_install_no_autostart_touches_no_service_manager() {
    let home = Home::new("no-autostart");
    let stdout = home.install_with(&["--no-autostart"]);

    assert!(!home.autostart().exists());
    assert!(home.calls().is_empty(), "{:?}", home.calls());
    assert!(!stdout.contains("allotd at login"), "{stdout}");
    assert!(
        stdout.contains("allotd is not running; the first session starts it"),
        "{stdout}"
    );
}

#[test]
fn test_install_leaves_another_allot_on_path_alone() {
    let home = Home::new("foreign-link");
    fs::write(home.link(), "someone else's").unwrap();

    let stdout = home.install();

    assert!(
        stdout.contains("left ") && stdout.contains(" alone"),
        "{stdout}"
    );
    assert_eq!(fs::read_to_string(home.link()).unwrap(), "someone else's");
    home.uninstall();
    assert!(home.link().is_file(), "uninstall keeps what is not ours");
}

#[test]
fn test_install_without_local_bin_says_how_to_add_path() {
    let home = Home::new("no-local-bin");
    fs::remove_dir_all(home.0.join(".local")).unwrap();

    let stdout = home.install();

    assert!(
        stdout.contains(&format!(
            "add {} to PATH to run allot from anywhere",
            home.bin().display()
        )),
        "{stdout}"
    );
}

#[test]
fn test_install_replaces_a_running_allot() {
    let home = Home::new("running");
    home.install();
    let mut running = Command::new(home.bin().join("allot"))
        .args(["hook", "pre-tool"])
        .env("HOME", &home.0)
        .stdin(Stdio::piped())
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn()
        .unwrap();
    fs::write(home.build().join("allot-mcp"), "a newer allot-mcp").unwrap();

    home.install();

    assert_eq!(
        fs::read_to_string(home.bin().join("allot-mcp")).unwrap(),
        "a newer allot-mcp"
    );
    assert_eq!(bin_names(&home.bin()), ["allot", "allot-mcp", "allotd"]);
    drop(running.stdin.take());
    running.wait().unwrap();
}

#[test]
fn test_uninstall_removes_autostart_binaries_link_and_registrations() {
    let home = Home::new("uninstall");
    home.install();
    let before = home.calls().len();

    let stdout = home.uninstall();

    assert!(!home.autostart().exists(), "{stdout}");
    let calls = &home.calls()[before..];
    if cfg!(target_os = "macos") {
        assert!(
            calls.contains(&format!(
                "launchctl bootout gui/{}/tech.mehran.allotd",
                uid()
            )),
            "{calls:?}"
        );
        assert!(stdout.contains("removed the LaunchAgent"), "{stdout}");
    } else {
        assert!(
            calls.contains(&"systemctl --user disable --now allotd.service".to_owned()),
            "{calls:?}"
        );
        assert!(stdout.contains("removed the systemd user unit"), "{stdout}");
    }
    assert!(!home.bin().exists());
    assert!(fs::symlink_metadata(home.link()).is_err(), "{stdout}");
    assert!(!home.claude("skills/resource-guard/SKILL.md").exists());
    let settings = fs::read_to_string(home.claude("settings.json")).unwrap();
    assert!(!settings.contains("allot"), "{settings}");
    assert!(home.app().join("config.toml").is_file(), "data is kept");
}

#[test]
fn test_install_writes_bash_and_fish_completions_and_uninstall_removes_only_those() {
    let home = Home::new("completions");
    let bash = home
        .0
        .join(".local/share/bash-completion/completions/allot");
    let fish = home.0.join(".config/fish/completions/allot.fish");
    fs::create_dir_all(fish.parent().unwrap()).unwrap();
    fs::write(&fish, "# my own\n").unwrap();

    let stdout = home.install();

    let script = fs::read_to_string(&bash).unwrap();
    assert!(
        script.starts_with("# Written by `allot install`"),
        "{script}"
    );
    assert!(script.contains("_allot()"), "{script}");
    assert_eq!(fs::read_to_string(&fish).unwrap(), "# my own\n", "{stdout}");
    assert!(
        stdout.contains("zsh completions: run `allot completions zsh"),
        "{stdout}"
    );

    fs::remove_file(&fish).unwrap();
    home.install();
    assert!(
        fs::read_to_string(&fish)
            .unwrap()
            .contains("complete -c allot")
    );

    let stdout = home.uninstall();
    assert!(!bash.exists(), "{stdout}");
    assert!(!fish.exists(), "{stdout}");
}

#[test]
fn test_uninstall_purge_removes_the_data_dir_with_its_logs() {
    let home = Home::new("purge");
    home.install();
    let logs = home.app().join("logs");
    fs::create_dir_all(&logs).unwrap();
    fs::write(logs.join("allotd.log"), "a log").unwrap();
    fs::write(home.app().join("token"), "secret").unwrap();

    let output = home.allot(&["uninstall", "--purge"]);

    assert!(output.status.success(), "{output:?}");
    assert!(!home.app().exists());
}

#[test]
fn test_uninstall_keeps_a_unit_or_agent_for_another_allotd() {
    let home = Home::new("keep-other");
    let file = home.autostart();
    fs::create_dir_all(file.parent().unwrap()).unwrap();
    let other = if cfg!(target_os = "macos") {
        allot_shared::autostart::launch_agent(Path::new("/dev/allotd"))
    } else {
        allot_shared::autostart::systemd_unit(Path::new("/dev/allotd"))
    };
    fs::write(&file, &other).unwrap();
    // A link of the same name to another build is not ours either.
    symlink("/dev/allot", home.link()).unwrap();

    home.uninstall();

    assert_eq!(fs::read_to_string(&file).unwrap(), other);
    assert!(home.calls().is_empty(), "{:?}", home.calls());
    assert_eq!(fs::read_link(home.link()).unwrap(), Path::new("/dev/allot"));
}

#[cfg(target_os = "linux")]
#[test]
fn test_install_writes_the_icon_and_uninstall_removes_it_and_the_notifyrc() {
    let home = Home::new("icon");
    let data = home.0.join(".local/share");
    let icon = data.join("icons/hicolor/scalable/apps/allot.svg");
    let notify_rc = data.join("knotifications6/allot.notifyrc");

    let stdout = home.install();
    assert!(icon.is_file(), "{stdout}");
    assert!(stdout.contains("installed the allot icon"), "{stdout}");

    fs::create_dir_all(notify_rc.parent().unwrap()).unwrap();
    fs::write(&notify_rc, "[Global]\n").unwrap();
    let choices = home.0.join(".config/allot.notifyrc");
    fs::write(&choices, "[Event/notification]\n").unwrap();
    home.uninstall();

    assert!(!icon.exists());
    assert!(!notify_rc.exists());
    assert!(choices.is_file(), "only a purge removes the user's choices");
}

#[cfg(target_os = "linux")]
#[test]
fn test_uninstall_purge_removes_the_notification_choices() {
    let home = Home::new("purge-choices");
    home.install();
    let choices = home.0.join(".config/allot.notifyrc");
    fs::write(&choices, "[Event/notification]\n").unwrap();

    let output = home.allot(&["uninstall", "--purge"]);

    assert!(output.status.success(), "{output:?}");
    assert!(!choices.exists());
}

#[cfg(target_os = "linux")]
#[test]
fn test_install_hints_at_the_panel_package_until_it_is_installed() {
    let home = Home::new("panel-hint");
    let build = home.build();
    let args = ["install", "--from", build.to_str().unwrap()];
    let stdout = |desktop| {
        let output = home.allot_on_desktop(&args, desktop);
        assert!(output.status.success(), "{output:?}");
        String::from_utf8(output.stdout).unwrap()
    };

    assert!(stdout("KDE").contains("kpackagetool6"));
    assert!(stdout("ubuntu:GNOME").contains("gnome-extensions install"));
    assert!(!stdout("XFCE").contains("for the panel"));

    fs::create_dir_all(
        home.0
            .join(".local/share/plasma/plasmoids/tech.mehran.allot"),
    )
    .unwrap();
    assert!(!stdout("KDE").contains("kpackagetool6"));
}

#[test]
fn test_install_help_names_unix_paths() {
    let home = Home::new("help");
    let output = home.allot(&["install", "--help"]);
    let help = String::from_utf8(output.stdout).unwrap();

    for expected in [
        "~/.allot/bin",
        "target/release",
        "--no-autostart",
        "LaunchAgent",
    ] {
        assert!(help.contains(expected), "{expected}: {help}");
    }
    for unexpected in [
        "%USERPROFILE%",
        ".exe",
        r"target\release",
        "--tray",
        "--no-logon-task",
    ] {
        assert!(!help.contains(unexpected), "{unexpected}: {help}");
    }
}

#[test]
fn test_install_from_the_bin_dir_is_refused_with_a_unix_example() {
    let home = Home::new("from-bin");
    home.install();
    let bin = home.bin();

    let output = home.allot(&["install", "--from", bin.to_str().unwrap()]);

    assert!(!output.status.success());
    let stderr = String::from_utf8(output.stderr).unwrap();
    assert!(
        stderr.contains("such as target/release/allot install"),
        "{stderr}"
    );
}