second-brain-core 0.13.5

Core library for second-brain: SQLite storage with vector and lexical indexes, BGE embeddings, and hybrid retrieval
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
use std::collections::{BTreeMap, BTreeSet};
use std::fs;
use std::io::ErrorKind;
use std::path::{Path, PathBuf};
use std::time::Duration;

use anyhow::{Context, Result};

use super::storage::run_bounded;
use super::store_key::{remove_if_present, replace_private_file};

pub const HARDWARE_BINDING_FILE: &str = "device.hardware";

/// A disk's sysfs serial and its hardware by-id names are readings of the
/// same disk, so they are one kind and match when either does.
const DISK: &str = "disk";
const DEVICETREE: &str = "devicetree";
const PLATFORM: &str = "platform";

/// By-id names that carry a disk's own serial or WWN. `dm-uuid-*`,
/// `lvm-pv-uuid-*` and filesystem ids are written on the disk, so an image
/// copies them.
const HARDWARE_BY_ID_PREFIXES: &[&str] = &["nvme-", "ata-", "wwn-"];
const MAX_STACK_DEPTH: usize = 8;
const IOREG: &str = "/usr/sbin/ioreg";
const IOREG_TIMEOUT: Duration = Duration::from_secs(10);

/// Hardware ids by kind. Two ids of one kind match when they share any
/// value, so a disk array matches while one member is still in place.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct HardwareId(BTreeMap<String, BTreeSet<String>>);

impl HardwareId {
    /// Reads `kind:value` lines, skipping any that are not.
    pub fn parse(text: &str) -> Self {
        let mut id = Self::default();
        for line in text.lines() {
            if let Some((kind, value)) = line.split_once(':') {
                id.insert(kind, value);
            }
        }
        id
    }

    pub fn insert(&mut self, kind: &str, value: &str) {
        let kind = kind.trim();
        let value = value.trim_matches(|c: char| c.is_whitespace() || c == '\0');
        if kind.is_empty() || value.is_empty() || kind.contains(':') {
            return;
        }
        if kind.chars().chain(value.chars()).any(char::is_control) {
            return;
        }
        self.0
            .entry(kind.to_string())
            .or_default()
            .insert(value.to_string());
    }

    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    pub fn to_text(&self) -> String {
        let mut text = String::new();
        for (kind, values) in &self.0 {
            for value in values {
                text.push_str(kind);
                text.push(':');
                text.push_str(value);
                text.push('\n');
            }
        }
        text
    }

    /// Whether `current` is the hardware these ids were recorded on: false
    /// when a kind read on both sides shares no value, None when no kind
    /// was read on both sides, so nothing can be compared.
    pub fn matches(&self, current: &HardwareId) -> Option<bool> {
        let mut compared = false;
        for (kind, recorded) in &self.0 {
            let Some(now) = current.0.get(kind) else {
                continue;
            };
            if recorded.is_disjoint(now) {
                return Some(false);
            }
            compared = true;
        }
        compared.then_some(true)
    }

    /// These ids with every kind `current` holds replaced by its values,
    /// so a binding follows disks that are swapped one at a time.
    pub fn refreshed(&self, current: &HardwareId) -> HardwareId {
        let mut refreshed = self.clone();
        for (kind, values) in &current.0 {
            refreshed.0.insert(kind.clone(), values.clone());
        }
        refreshed
    }
}

pub trait HardwareSource: Send + Sync {
    /// Empty when no id can be read here.
    fn read(&self, data_dir: &Path) -> HardwareId;
}

/// `IOPlatformUUID` on macOS; on Linux the serials of the physical disks
/// under the data dir and the devicetree serial number. DMI `product_uuid`
/// is readable only by root and `/etc/machine-id` travels with an image, so
/// neither is used.
#[derive(Debug, Clone, Copy, Default)]
pub struct SystemHardware;

impl HardwareSource for SystemHardware {
    fn read(&self, data_dir: &Path) -> HardwareId {
        if cfg!(target_os = "macos") {
            mac_platform_id()
        } else if cfg!(target_os = "linux") {
            LinuxHardware::system().read(data_dir)
        } else {
            HardwareId::default()
        }
    }
}

fn mac_platform_id() -> HardwareId {
    let mut id = HardwareId::default();
    let args = ["-rd1", "-c", "IOPlatformExpertDevice"];
    match run_bounded(Path::new(IOREG), &args, &[], IOREG_TIMEOUT) {
        Ok(out) => {
            if let Some(uuid) = parse_ioreg(&String::from_utf8_lossy(&out)) {
                id.insert(PLATFORM, &uuid);
            }
        }
        Err(e) => tracing::warn!("cannot read this Mac's platform UUID: {e:#}"),
    }
    id
}

fn parse_ioreg(text: &str) -> Option<String> {
    text.lines().find_map(|line| {
        let (key, value) = line.split_once('=')?;
        if key.trim() != "\"IOPlatformUUID\"" {
            return None;
        }
        let value = value.trim().trim_matches('"').trim();
        (!value.is_empty()).then(|| value.to_string())
    })
}

pub(crate) struct LinuxHardware {
    sys: PathBuf,
    by_id: PathBuf,
    devicetree_serial: PathBuf,
    mountinfo: PathBuf,
}

impl LinuxHardware {
    fn system() -> Self {
        Self {
            sys: PathBuf::from("/sys"),
            by_id: PathBuf::from("/dev/disk/by-id"),
            devicetree_serial: PathBuf::from("/sys/firmware/devicetree/base/serial-number"),
            mountinfo: PathBuf::from("/proc/self/mountinfo"),
        }
    }

    fn read(&self, data_dir: &Path) -> HardwareId {
        let mut id = self
            .block_dir(data_dir)
            .map(|block| self.block_ids(&block))
            .unwrap_or_default();
        if let Some(serial) = read_text(&self.devicetree_serial) {
            id.insert(DEVICETREE, &serial);
        }
        id
    }

    /// The sysfs block device under `data_dir`, found by its device number,
    /// or through the mount table where the filesystem reports a device
    /// number sysfs lacks (btrfs subvolumes).
    fn block_dir(&self, data_dir: &Path) -> Option<PathBuf> {
        if let Some((major, minor)) = device_number(data_dir) {
            let dir = self.sys.join("dev/block").join(format!("{major}:{minor}"));
            if dir.exists() {
                return Some(dir);
            }
        }
        let table = fs::read_to_string(&self.mountinfo).ok()?;
        let source = mount_source(&table, &fs::canonicalize(data_dir).ok()?)?;
        if !source.is_absolute() {
            return None;
        }
        let name = fs::canonicalize(source).ok()?.file_name()?.to_owned();
        let dir = self.sys.join("class/block").join(name);
        dir.exists().then_some(dir)
    }

    fn block_ids(&self, block: &Path) -> HardwareId {
        let mut disks = BTreeSet::new();
        self.collect_disks(block, 0, &mut disks);
        let mut id = HardwareId::default();
        for disk in &disks {
            self.disk_ids(disk, &mut id);
        }
        id
    }

    fn collect_disks(&self, block: &Path, depth: usize, disks: &mut BTreeSet<PathBuf>) {
        if depth > MAX_STACK_DEPTH {
            return;
        }
        let Ok(block) = fs::canonicalize(block) else {
            return;
        };
        if block.join("partition").is_file() {
            if let Some(disk) = block.parent() {
                self.collect_disks(disk, depth + 1, disks);
            }
            return;
        }
        let slaves = entry_names(&block.join("slaves"));
        if slaves.is_empty() {
            disks.insert(block);
            return;
        }
        for slave in slaves {
            let slave = self.sys.join("class/block").join(slave);
            self.collect_disks(&slave, depth + 1, disks);
        }
    }

    fn disk_ids(&self, disk: &Path, id: &mut HardwareId) {
        if let Some(serial) = read_text(&disk.join("device/serial")) {
            id.insert(DISK, &serial);
        }
        let Some(name) = disk.file_name() else {
            return;
        };
        for link in entry_names(&self.by_id) {
            let Some(link_name) = link.to_str() else {
                continue;
            };
            if !HARDWARE_BY_ID_PREFIXES
                .iter()
                .any(|prefix| link_name.starts_with(prefix))
            {
                continue;
            }
            if fs::read_link(self.by_id.join(&link))
                .is_ok_and(|target| target.file_name() == Some(name))
            {
                id.insert(DISK, link_name);
            }
        }
    }
}

#[cfg(unix)]
fn device_number(path: &Path) -> Option<(u64, u64)> {
    use std::os::unix::fs::MetadataExt;

    let dev = fs::metadata(path).ok()?.dev();
    let major = ((dev >> 32) & 0xffff_f000) | ((dev >> 8) & 0x0fff);
    let minor = ((dev >> 12) & 0xffff_ff00) | (dev & 0xff);
    Some((major, minor))
}

#[cfg(not(unix))]
fn device_number(_path: &Path) -> Option<(u64, u64)> {
    None
}

/// The source of the mount that holds `path`: the deepest mount point over
/// it, and of those the one mounted last, which hides the others.
fn mount_source(mountinfo: &str, path: &Path) -> Option<PathBuf> {
    let mut best: Option<(usize, PathBuf)> = None;
    for line in mountinfo.lines() {
        let fields: Vec<&str> = line.split(' ').collect();
        let Some(separator) = fields.iter().position(|f| *f == "-") else {
            continue;
        };
        let (Some(mount_point), Some(source)) = (fields.get(4), fields.get(separator + 2)) else {
            continue;
        };
        if separator < 6 {
            continue;
        }
        let mount_point = PathBuf::from(unescape_mount_field(mount_point));
        if !path.starts_with(&mount_point) {
            continue;
        }
        let depth = mount_point.components().count();
        if best.as_ref().is_none_or(|(deepest, _)| depth >= *deepest) {
            best = Some((depth, PathBuf::from(unescape_mount_field(source))));
        }
    }
    best.map(|(_, source)| source)
}

/// The kernel writes space, tab, newline and backslash in mount fields as
/// three-digit octal escapes.
fn unescape_mount_field(field: &str) -> String {
    let bytes = field.as_bytes();
    let mut out = Vec::with_capacity(bytes.len());
    let mut i = 0;
    while i < bytes.len() {
        let octal = bytes
            .get(i + 1..i + 4)
            .filter(|d| bytes[i] == b'\\' && d.iter().all(|b| (b'0'..=b'7').contains(b)));
        match octal.and_then(|d| u8::from_str_radix(std::str::from_utf8(d).ok()?, 8).ok()) {
            Some(byte) => {
                out.push(byte);
                i += 4;
            }
            None => {
                out.push(bytes[i]);
                i += 1;
            }
        }
    }
    String::from_utf8_lossy(&out).into_owned()
}

fn read_text(path: &Path) -> Option<String> {
    let bytes = fs::read(path).ok()?;
    let text = String::from_utf8_lossy(&bytes);
    let text = text.trim_matches(|c: char| c.is_whitespace() || c == '\0');
    (!text.is_empty()).then(|| text.to_string())
}

fn entry_names(dir: &Path) -> Vec<std::ffi::OsString> {
    let Ok(entries) = fs::read_dir(dir) else {
        return Vec::new();
    };
    let mut names: Vec<_> = entries.flatten().map(|e| e.file_name()).collect();
    names.sort();
    names
}

/// None when `data_dir` holds no binding.
pub fn read_binding(data_dir: &Path) -> Result<Option<HardwareId>> {
    let path = data_dir.join(HARDWARE_BINDING_FILE);
    match fs::read_to_string(&path) {
        Ok(text) => Ok(Some(HardwareId::parse(&text))),
        Err(e) if e.kind() == ErrorKind::NotFound => Ok(None),
        Err(e) => Err(e).with_context(|| format!("reading {}", path.display())),
    }
}

/// Replaces the binding; an empty id removes it.
pub fn write_binding(data_dir: &Path, id: &HardwareId) -> Result<()> {
    if id.is_empty() {
        return remove_if_present(&data_dir.join(HARDWARE_BINDING_FILE));
    }
    replace_private_file(data_dir, HARDWARE_BINDING_FILE, id.to_text().as_bytes())
}

#[cfg(test)]
mod tests {
    use std::os::unix::fs::symlink;

    use super::*;

    fn id(lines: &[&str]) -> HardwareId {
        HardwareId::parse(&lines.join("\n"))
    }

    struct Tree {
        root: tempfile::TempDir,
    }

    impl Tree {
        fn new() -> Self {
            let tree = Self {
                root: tempfile::tempdir().unwrap(),
            };
            for dir in ["sys/class/block", "sys/dev/block", "by-id", "dt", "dev"] {
                fs::create_dir_all(tree.path(dir)).unwrap();
            }
            tree
        }

        fn path(&self, rel: &str) -> PathBuf {
            self.root.path().join(rel)
        }

        fn hardware(&self) -> LinuxHardware {
            LinuxHardware {
                sys: self.path("sys"),
                by_id: self.path("by-id"),
                devicetree_serial: self.path("dt/serial-number"),
                mountinfo: self.path("mountinfo"),
            }
        }

        fn class_link(&self, name: &str, target: &Path) {
            symlink(target, self.path("sys/class/block").join(name)).unwrap();
        }

        fn disk(&self, name: &str, serial: Option<&str>) -> PathBuf {
            let dir = self.path("sys/devices/pci0000:00/block").join(name);
            fs::create_dir_all(dir.join("device")).unwrap();
            if let Some(serial) = serial {
                fs::write(dir.join("device/serial"), format!("{serial}\n")).unwrap();
            }
            self.class_link(name, &dir);
            dir
        }

        fn partition(&self, disk: &Path, name: &str) -> PathBuf {
            let dir = disk.join(name);
            fs::create_dir_all(&dir).unwrap();
            fs::write(dir.join("partition"), "1\n").unwrap();
            self.class_link(name, &dir);
            dir
        }

        fn stacked(&self, name: &str, slaves: &[&str]) -> PathBuf {
            let dir = self.path("sys/devices/virtual/block").join(name);
            fs::create_dir_all(dir.join("slaves")).unwrap();
            for slave in slaves {
                symlink(
                    self.path("sys/class/block").join(slave),
                    dir.join("slaves").join(slave),
                )
                .unwrap();
            }
            self.class_link(name, &dir);
            dir
        }

        fn by_id(&self, name: &str, target: &str) {
            symlink(format!("../../{target}"), self.path("by-id").join(name)).unwrap();
        }

        fn block(&self, name: &str) -> PathBuf {
            self.path("sys/class/block").join(name)
        }
    }

    #[test]
    fn a_partition_resolves_to_its_disks_serial_and_hardware_names() {
        let tree = Tree::new();
        let disk = tree.disk("nvme0n1", Some("S4EWNX0R123456"));
        tree.partition(&disk, "nvme0n1p2");
        tree.by_id("nvme-Example_SSD_S4EWNX0R123456", "nvme0n1");
        tree.by_id("nvme-Example_SSD_S4EWNX0R123456-part2", "nvme0n1p2");
        tree.by_id("nvme-eui.0025385b91b0f1aa", "nvme0n1");
        tree.by_id("wwn-0x5002538e40a1b2c3", "nvme0n1");

        assert_eq!(
            tree.hardware().block_ids(&tree.block("nvme0n1p2")),
            id(&[
                "disk:S4EWNX0R123456",
                "disk:nvme-Example_SSD_S4EWNX0R123456",
                "disk:nvme-eui.0025385b91b0f1aa",
                "disk:wwn-0x5002538e40a1b2c3",
            ])
        );
    }

    #[test]
    fn a_dm_device_resolves_through_its_slaves_to_the_physical_disk() {
        let tree = Tree::new();
        let disk = tree.disk("sda", None);
        tree.partition(&disk, "sda3");
        tree.stacked("dm-0", &["sda3"]);
        tree.stacked("dm-1", &["dm-0"]);
        tree.by_id("ata-Example_HDD_WD-WCC4E1234567", "sda");
        tree.by_id("dm-uuid-CRYPT-LUKS2-0123abcd-luks", "dm-0");
        tree.by_id("dm-uuid-LVM-abcdef0123456789", "dm-1");
        tree.by_id("lvm-pv-uuid-Ab12Cd-34Ef", "dm-0");
        tree.by_id("dm-name-vg-root", "dm-1");

        assert_eq!(
            tree.hardware().block_ids(&tree.block("dm-1")),
            id(&["disk:ata-Example_HDD_WD-WCC4E1234567"])
        );
    }

    #[test]
    fn an_md_array_binds_the_set_of_member_serials() {
        let tree = Tree::new();
        let a = tree.disk("nvme0n1", Some("SERIAL-A"));
        let b = tree.disk("nvme1n1", Some("SERIAL-B"));
        tree.partition(&a, "nvme0n1p1");
        tree.partition(&b, "nvme1n1p1");
        tree.stacked("md0", &["nvme0n1p1", "nvme1n1p1"]);

        assert_eq!(
            tree.hardware().block_ids(&tree.block("md0")),
            id(&["disk:SERIAL-A", "disk:SERIAL-B"])
        );
    }

    #[test]
    fn image_copied_names_alone_give_no_id() {
        let tree = Tree::new();
        tree.stacked("dm-0", &[]);
        tree.disk("loop0", None);
        tree.by_id("dm-uuid-CRYPT-LUKS2-0123abcd-luks", "dm-0");
        tree.by_id("lvm-pv-uuid-Ab12Cd-34Ef", "dm-0");
        tree.by_id("dm-name-luks", "dm-0");

        let hardware = tree.hardware();
        assert!(hardware.block_ids(&tree.block("dm-0")).is_empty());
        assert!(hardware.block_ids(&tree.block("loop0")).is_empty());
    }

    #[test]
    fn a_stacking_loop_ends_without_an_id() {
        let tree = Tree::new();
        tree.stacked("dm-0", &["dm-1"]);
        tree.stacked("dm-1", &["dm-0"]);
        assert!(tree.hardware().block_ids(&tree.block("dm-0")).is_empty());
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn the_data_dir_is_found_by_its_device_number() {
        let tree = Tree::new();
        let disk = tree.disk("mmcblk0", Some("0x1234abcd"));
        let part = tree.partition(&disk, "mmcblk0p2");
        let (major, minor) = device_number(tree.root.path()).unwrap();
        symlink(&part, tree.path(&format!("sys/dev/block/{major}:{minor}"))).unwrap();
        fs::write(tree.path("dt/serial-number"), "10000000abcdef01\0").unwrap();

        assert_eq!(
            tree.hardware().read(tree.root.path()),
            id(&["disk:0x1234abcd", "devicetree:10000000abcdef01"])
        );
    }

    #[test]
    fn a_device_number_sysfs_lacks_falls_back_to_the_mount_source() {
        let tree = Tree::new();
        let disk = tree.disk("nvme0n1", Some("S4EW"));
        tree.partition(&disk, "nvme0n1p2");
        fs::write(tree.path("dev/nvme0n1p2"), "").unwrap();
        let data_dir = tree.path("home/user/.second-brain");
        fs::create_dir_all(&data_dir).unwrap();
        let mount = fs::canonicalize(tree.path("home")).unwrap();
        let source = tree.path("dev/nvme0n1p2");
        fs::write(
            tree.path("mountinfo"),
            format!(
                "22 1 0:21 / / rw shared:1 - tmpfs tmpfs rw\n\
                 36 22 0:31 /@home {} rw,relatime shared:2 - btrfs {} rw,subvol=/@home\n",
                mount.display(),
                source.display()
            ),
        )
        .unwrap();

        assert_eq!(tree.hardware().read(&data_dir), id(&["disk:S4EW"]));
    }

    #[test]
    fn the_mount_source_is_the_longest_mount_point_over_the_path_and_the_last_mounted() {
        let table = "22 1 0:21 / / rw - ext4 /dev/sda1 rw\n\
                     30 22 0:30 / /home rw - ext4 /dev/sdb1 rw\n\
                     31 22 0:31 / /home/us rw - ext4 /dev/sdc1 rw\n\
                     32 30 0:32 / /home/user\\040name rw shared:3 - ext4 /dev/sdd1 rw\n\
                     33 30 0:33 / /home/user\\040name rw - ext4 /dev/sde1 rw\n";
        let source = |path: &str| mount_source(table, Path::new(path));
        assert_eq!(
            source("/home/user name/.second-brain"),
            Some(PathBuf::from("/dev/sde1"))
        );
        assert_eq!(source("/home/user/x"), Some(PathBuf::from("/dev/sdb1")));
        assert_eq!(source("/var/lib"), Some(PathBuf::from("/dev/sda1")));
        assert_eq!(mount_source("garbage line\n", Path::new("/x")), None);
    }

    #[test]
    fn hardware_ids_compare_per_kind() {
        let disk_a = id(&["disk:A"]);
        let cases = [
            ("same disk", disk_a.clone(), id(&["disk:A"]), Some(true)),
            ("other disk", disk_a.clone(), id(&["disk:B"]), Some(false)),
            (
                "one array member left",
                id(&["disk:A", "disk:B"]),
                id(&["disk:B", "disk:C"]),
                Some(true),
            ),
            (
                "every array member replaced",
                id(&["disk:A", "disk:B"]),
                id(&["disk:C", "disk:D"]),
                Some(false),
            ),
            ("nothing read now", disk_a.clone(), id(&[]), None),
            (
                "no kind in common",
                disk_a.clone(),
                id(&["devicetree:P"]),
                None,
            ),
            (
                "the disk moved to another board",
                id(&["disk:A", "devicetree:P"]),
                id(&["disk:A", "devicetree:Q"]),
                Some(false),
            ),
            (
                "by-id links renamed under the same serial",
                id(&["disk:S4EW", "disk:nvme-Old_Name_S4EW"]),
                id(&["disk:S4EW", "disk:nvme-New_Name_S4EW"]),
                Some(true),
            ),
            (
                "a kind read only now",
                disk_a.clone(),
                id(&["disk:A", "devicetree:Q"]),
                Some(true),
            ),
        ];
        for (name, recorded, current, expected) in cases {
            assert_eq!(recorded.matches(&current), expected, "{name}");
        }
    }

    #[test]
    fn a_refreshed_binding_takes_the_kinds_read_now_and_keeps_the_rest() {
        let recorded = id(&["disk:A", "disk:B", "devicetree:P"]);
        assert_eq!(
            recorded.refreshed(&id(&["disk:B", "disk:C"])),
            id(&["disk:B", "disk:C", "devicetree:P"])
        );
    }

    #[test]
    fn ids_parse_strictly_and_round_trip_through_text() {
        let parsed =
            HardwareId::parse("disk: A1 \nnot an id\n:empty-kind\nby-id:\nserial:B\u{7}\n");
        assert_eq!(parsed.to_text(), "disk:A1\n");
        assert_eq!(HardwareId::parse(&parsed.to_text()), parsed);
    }

    #[test]
    fn the_binding_file_round_trips_and_an_empty_id_removes_it() {
        let dir = tempfile::tempdir().unwrap();
        assert_eq!(read_binding(dir.path()).unwrap(), None);
        let bound = id(&["disk:A", "disk:ata-X"]);
        write_binding(dir.path(), &bound).unwrap();
        assert_eq!(read_binding(dir.path()).unwrap(), Some(bound));
        write_binding(dir.path(), &HardwareId::default()).unwrap();
        assert!(!dir.path().join(HARDWARE_BINDING_FILE).exists());
        write_binding(dir.path(), &HardwareId::default()).unwrap();
    }

    #[test]
    fn ioreg_output_yields_the_platform_uuid() {
        let text = "+-o J314sAP  <class IOPlatformExpertDevice, id 0x100000110>\n\
                    {\n\
                    \x20 \"IOPlatformSerialNumber\" = \"C02ABCDEF\"\n\
                    \x20 \"IOPlatformUUID\" = \"1A2B3C4D-0000-1111-2222-333344445555\"\n\
                    }\n";
        assert_eq!(
            parse_ioreg(text).as_deref(),
            Some("1A2B3C4D-0000-1111-2222-333344445555")
        );
        assert_eq!(parse_ioreg("no uuid here"), None);
        assert_eq!(parse_ioreg("  \"IOPlatformUUID\" = \"\"\n"), None);
    }
}