second-brain-core 0.13.2

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
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
use std::fmt;
use std::path::Path;

use anyhow::{Context, Result};

use super::hardware::{HardwareId, HardwareSource, SystemHardware, read_binding, write_binding};
use super::storage::{has_device_key, replace_device_keys};
use super::store_key::write_store_key_to;
use super::{
    DEVICE_PUB_FILE, DeviceKeys, KeyStorage, NEXT_STORE_KEY_FILE, STORE_KEY_FILE,
    load_device_keys_in, publish_device_pub, read_store_key,
};
use crate::machine::MachineIdentity;
use crate::write_queue;

#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum HardwareCheck {
    /// No device keys yet; they are bound when they are created.
    NoKeys,
    Bound,
    /// The keys predate the binding, so this hardware was recorded now.
    Recorded,
    /// No hardware id can be compared here, so the check is off. Never a
    /// mismatch.
    Unreadable,
    /// The data dir was made on other hardware (a clone, or a copy restored
    /// by hand), so this device now has a new machine id and new device keys
    /// and has to be paired.
    Reminted {
        previous_machine_id: Option<String>,
        machine_id: String,
    },
}

impl HardwareCheck {
    pub fn name(&self) -> &'static str {
        match self {
            Self::NoKeys => "no-keys",
            Self::Bound => "bound",
            Self::Recorded => "recorded",
            Self::Unreadable => "unreadable",
            Self::Reminted { .. } => "reminted",
        }
    }
}

/// Marks an error from a remint that had begun: the data dir is known to
/// come from other hardware, so the daemon must not run under the machine
/// id it carries. The next start redoes the remint.
#[derive(Debug)]
pub struct RemintFailed;

impl fmt::Display for RemintFailed {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("the device keys were made on other hardware and replacing them failed")
    }
}

/// Compares the hardware the device keys in `data_dir` were made on with
/// this hardware. On a mismatch it mints new device keys, re-wraps the
/// store key to them and writes a new machine id into `config_dir`; the
/// daemon must run it before it opens the store or reads the machine id.
pub fn check_hardware(
    data_dir: &Path,
    config_dir: &Path,
    storage: &KeyStorage,
) -> Result<HardwareCheck> {
    check_hardware_with(data_dir, config_dir, storage, &SystemHardware)
}

pub fn check_hardware_with(
    data_dir: &Path,
    config_dir: &Path,
    storage: &KeyStorage,
    source: &dyn HardwareSource,
) -> Result<HardwareCheck> {
    let Some(device) = load_device_keys_in(data_dir, storage)? else {
        return Ok(HardwareCheck::NoKeys);
    };
    let current = source.read(data_dir);
    let Some(recorded) = read_binding(data_dir)? else {
        if current.is_empty() {
            return Ok(HardwareCheck::Unreadable);
        }
        write_binding(data_dir, &current)?;
        return Ok(HardwareCheck::Recorded);
    };
    match recorded.matches(&current) {
        None => Ok(HardwareCheck::Unreadable),
        Some(true) => {
            let refreshed = recorded.refreshed(&current);
            if refreshed != recorded {
                write_binding(data_dir, &refreshed)?;
            }
            Ok(HardwareCheck::Bound)
        }
        Some(false) => {
            remint(data_dir, config_dir, storage, &device, &current).context(RemintFailed)
        }
    }
}

/// For a start whose `check_hardware` found no keys and that then made them:
/// creation bound the keys to this hardware, so this only reads that binding
/// and never compares or remints after the machine id is in use.
pub fn binding_after_creation(data_dir: &Path) -> Result<HardwareCheck> {
    if !has_device_key(data_dir) {
        return Ok(HardwareCheck::NoKeys);
    }
    Ok(match read_binding(data_dir)? {
        Some(id) if !id.is_empty() => HardwareCheck::Recorded,
        _ => HardwareCheck::Unreadable,
    })
}

/// The binding is written last: until it is, every start finds the
/// mismatch again and redoes the remint from whatever key is in place.
fn remint(
    data_dir: &Path,
    config_dir: &Path,
    storage: &KeyStorage,
    device: &DeviceKeys,
    current: &HardwareId,
) -> Result<HardwareCheck> {
    let previous_machine_id = match MachineIdentity::load(config_dir) {
        Ok(machine) => machine.map(|m| m.id),
        Err(e) => {
            tracing::warn!("cannot read the machine id being replaced: {e:#}");
            None
        }
    };
    swap_device_keys(data_dir, storage, device)?;
    let machine = MachineIdentity::mint(config_dir)?;
    write_binding(data_dir, current)?;
    Ok(HardwareCheck::Reminted {
        previous_machine_id,
        machine_id: machine.id,
    })
}

/// The store key and queued writes open with the device key on disk after
/// every step, so a swap cut short anywhere leaves them readable.
fn swap_device_keys(data_dir: &Path, storage: &KeyStorage, old: &DeviceKeys) -> Result<DeviceKeys> {
    let fresh = DeviceKeys::generate()?;
    seal_to_both(data_dir, old, &fresh)?;
    replace_device_keys(data_dir, storage, &fresh)?;
    settle_on(data_dir, old, &fresh)?;
    Ok(fresh)
}

/// `device.pub` is withdrawn first, so writes queued during the swap stay
/// plaintext rather than sealed to a key about to go.
fn seal_to_both(data_dir: &Path, old: &DeviceKeys, fresh: &DeviceKeys) -> Result<()> {
    match std::fs::remove_file(data_dir.join(DEVICE_PUB_FILE)) {
        Ok(()) => {}
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
        Err(e) => return Err(e).context("withdrawing the device recipient"),
    }
    rewrap_store_keys(data_dir, old, &[old, fresh])?;
    write_queue::reseal_dir(
        &data_dir.join(write_queue::DIR_NAME),
        old.age_identity(),
        &[old.age_recipient(), fresh.age_recipient()],
    )?;
    Ok(())
}

/// The last reseal catches a write sealed to the old `device.pub` by a
/// writer that read it before it was withdrawn.
fn settle_on(data_dir: &Path, old: &DeviceKeys, fresh: &DeviceKeys) -> Result<()> {
    rewrap_store_keys(data_dir, fresh, &[fresh])?;
    publish_device_pub(data_dir, fresh)?;
    write_queue::reseal_dir(
        &data_dir.join(write_queue::DIR_NAME),
        old.age_identity(),
        &[fresh.age_recipient()],
    )?;
    Ok(())
}

fn rewrap_store_keys(data_dir: &Path, reader: &DeviceKeys, devices: &[&DeviceKeys]) -> Result<()> {
    for name in [STORE_KEY_FILE, NEXT_STORE_KEY_FILE] {
        if let Some(key) = read_store_key(&data_dir.join(name), reader)? {
            write_store_key_to(data_dir, name, &key, devices)?;
        }
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use std::fs;
    use std::sync::Arc;

    use anyhow::anyhow;

    use super::*;
    use crate::keys::hardware::{HARDWARE_BINDING_FILE, HardwareId, read_binding, write_binding};
    use crate::keys::storage::create_device_keys_with;
    use crate::keys::{
        CredentialSealer, DEVICE_KEY_FILE, DeviceKeys, DeviceRecord, KeyGuard, NEXT_STORE_KEY_FILE,
        SEALED_DEVICE_KEY_FILE, STORE_KEY_FILE, StoreKey, admit_device, found_identity,
        load_device_keys_in, read_store_key, write_store_key,
    };
    use crate::machine::MachineIdentity;
    use crate::sqlite_store::SqliteStore;

    const NOW: i64 = 1_793_600_000_000_000;

    struct Fixed(HardwareId);

    impl HardwareSource for Fixed {
        fn read(&self, _data_dir: &Path) -> HardwareId {
            self.0.clone()
        }
    }

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

    struct Device {
        dir: tempfile::TempDir,
        machine: MachineIdentity,
        keys: DeviceKeys,
        store_key: StoreKey,
    }

    impl Device {
        fn path(&self) -> &Path {
            self.dir.path()
        }

        fn check(&self, source: &Fixed) -> HardwareCheck {
            check_hardware_with(self.path(), self.path(), &KeyStorage::File, source).unwrap()
        }

        fn machine_id(&self) -> String {
            MachineIdentity::load_or_create(self.path()).unwrap().id
        }

        fn keys_now(&self) -> DeviceKeys {
            load_device_keys_in(self.path(), &KeyStorage::File)
                .unwrap()
                .unwrap()
        }
    }

    fn device_on(source: &Fixed) -> Device {
        let dir = tempfile::tempdir().unwrap();
        let machine = MachineIdentity::load_or_create(dir.path()).unwrap();
        let keys = create_device_keys_with(dir.path(), &KeyStorage::File, source).unwrap();
        let store_key = StoreKey::generate().unwrap();
        write_store_key(dir.path(), STORE_KEY_FILE, &store_key, &keys).unwrap();
        Device {
            dir,
            machine,
            keys,
            store_key,
        }
    }

    fn same_keys(a: &DeviceKeys, b: &DeviceKeys) -> bool {
        a.verifying_key() == b.verifying_key()
            && a.age_recipient().to_string() == b.age_recipient().to_string()
            && a.ssh_public_key() == b.ssh_public_key()
    }

    fn record_for(machine_id: &str, keys: &DeviceKeys, tag: &str) -> DeviceRecord {
        DeviceRecord {
            machine_id: machine_id.to_string(),
            identity_tag: tag.to_string(),
            version: 1,
            name: "laptop".into(),
            age_recipient: keys.age_recipient().to_string(),
            ssh_public_key: keys.ssh_public_key(),
            signing_public_key: keys.verifying_key().to_bytes(),
            recovery_fingerprints: Vec::new(),
            ssh_login: Some("user".into()),
            ssh_port: Some(22),
            ssh_host_key: None,
        }
    }

    #[test]
    fn keys_made_during_this_start_report_the_hardware_they_were_bound_to() {
        let none = tempfile::tempdir().unwrap();
        assert_eq!(
            binding_after_creation(none.path()).unwrap(),
            HardwareCheck::NoKeys
        );

        let left_behind = tempfile::tempdir().unwrap();
        write_binding(left_behind.path(), &HardwareId::parse("disk:A")).unwrap();
        assert_eq!(
            binding_after_creation(left_behind.path()).unwrap(),
            HardwareCheck::NoKeys
        );

        let device = device_on(&hw(&["disk:A"]));
        assert_eq!(
            binding_after_creation(device.path()).unwrap(),
            HardwareCheck::Recorded
        );

        let unreadable = tempfile::tempdir().unwrap();
        create_device_keys_with(unreadable.path(), &KeyStorage::File, &hw(&[])).unwrap();
        assert_eq!(
            binding_after_creation(unreadable.path()).unwrap(),
            HardwareCheck::Unreadable
        );
    }

    #[test]
    fn device_keys_record_the_hardware_id_at_creation() {
        let device = device_on(&hw(&["disk:A", "by-id:nvme-X"]));
        assert_eq!(
            read_binding(device.path()).unwrap(),
            Some(HardwareId::parse("disk:A\nby-id:nvme-X"))
        );

        let dir = tempfile::tempdir().unwrap();
        write_binding(dir.path(), &HardwareId::parse("disk:left-behind")).unwrap();
        create_device_keys_with(dir.path(), &KeyStorage::File, &hw(&[])).unwrap();
        assert_eq!(
            read_binding(dir.path()).unwrap(),
            None,
            "keys made where no id reads carry no stale binding"
        );
    }

    #[test]
    fn a_start_on_the_same_hardware_keeps_the_keys_and_machine_id() {
        let device = device_on(&hw(&["disk:A"]));
        let key_file = fs::read(device.path().join(DEVICE_KEY_FILE)).unwrap();
        assert_eq!(device.check(&hw(&["disk:A"])), HardwareCheck::Bound);
        assert_eq!(device.machine_id(), device.machine.id);
        assert_eq!(
            fs::read(device.path().join(DEVICE_KEY_FILE)).unwrap(),
            key_file
        );
    }

    #[test]
    fn a_binding_follows_array_members_replaced_one_at_a_time() {
        let device = device_on(&hw(&["disk:A", "disk:B"]));
        assert_eq!(
            device.check(&hw(&["disk:B", "disk:C"])),
            HardwareCheck::Bound
        );
        assert_eq!(
            device.check(&hw(&["disk:C", "disk:D"])),
            HardwareCheck::Bound
        );
        assert_eq!(device.machine_id(), device.machine.id);
    }

    #[test]
    fn keys_made_before_the_binding_record_this_hardware_at_their_next_start() {
        let dir = tempfile::tempdir().unwrap();
        let machine = MachineIdentity::load_or_create(dir.path()).unwrap();
        DeviceKeys::load_or_create(&dir.path().join(DEVICE_KEY_FILE)).unwrap();
        let check = |source: &Fixed| {
            check_hardware_with(dir.path(), dir.path(), &KeyStorage::File, source).unwrap()
        };
        assert_eq!(check(&hw(&[])), HardwareCheck::Unreadable);
        assert!(!dir.path().join(HARDWARE_BINDING_FILE).exists());
        assert_eq!(check(&hw(&["disk:A"])), HardwareCheck::Recorded);
        assert_eq!(check(&hw(&["disk:A"])), HardwareCheck::Bound);
        assert_eq!(
            MachineIdentity::load_or_create(dir.path()).unwrap().id,
            machine.id
        );
    }

    #[test]
    fn without_device_keys_there_is_nothing_to_check() {
        let dir = tempfile::tempdir().unwrap();
        let check =
            check_hardware_with(dir.path(), dir.path(), &KeyStorage::File, &hw(&["disk:A"]));
        assert_eq!(check.unwrap(), HardwareCheck::NoKeys);
        assert_eq!(fs::read_dir(dir.path()).unwrap().count(), 0);
    }

    #[test]
    fn an_unreadable_id_disables_the_check_and_is_never_a_mismatch() {
        let device = device_on(&hw(&["disk:A"]));
        let key_file = fs::read(device.path().join(DEVICE_KEY_FILE)).unwrap();
        for source in [hw(&[]), hw(&["devicetree:P"]), hw(&["platform:U"])] {
            assert_eq!(device.check(&source), HardwareCheck::Unreadable);
        }
        assert_eq!(device.machine_id(), device.machine.id);
        assert_eq!(
            fs::read(device.path().join(DEVICE_KEY_FILE)).unwrap(),
            key_file
        );
        assert_eq!(
            read_binding(device.path()).unwrap(),
            Some(HardwareId::parse("disk:A"))
        );
    }

    #[test]
    fn a_mismatch_mints_a_new_machine_id_and_device_keys_and_keeps_the_store_key() {
        let device = device_on(&hw(&["disk:A"]));
        let check = device.check(&hw(&["disk:B"]));

        let now = device.machine_id();
        assert_ne!(now, device.machine.id);
        assert_eq!(
            check,
            HardwareCheck::Reminted {
                previous_machine_id: Some(device.machine.id.clone()),
                machine_id: now.clone(),
            }
        );
        let keys = device.keys_now();
        assert!(!same_keys(&keys, &device.keys));
        let store_key = read_store_key(&device.path().join(STORE_KEY_FILE), &keys)
            .unwrap()
            .unwrap();
        assert_eq!(store_key.expose(), device.store_key.expose());
        assert!(
            read_store_key(&device.path().join(STORE_KEY_FILE), &device.keys).is_err(),
            "the original's device key no longer opens the copy's store key"
        );
        assert_eq!(
            read_binding(device.path()).unwrap(),
            Some(HardwareId::parse("disk:B"))
        );
        assert_eq!(device.check(&hw(&["disk:B"])), HardwareCheck::Bound);
        assert_eq!(device.machine_id(), now);
    }

    #[test]
    fn a_reminted_copy_has_no_identity_and_pairs_where_the_copy_was_refused() {
        let device = device_on(&hw(&["disk:A"]));
        let original = SqliteStore::in_memory(device.machine.id.clone()).unwrap();
        let tag = found_identity(&original, &device.keys, "desk", &[], NOW)
            .unwrap()
            .tag;
        let db = device.path().join("brain.db");
        let copy = SqliteStore::open(&db, device.machine.id.clone()).unwrap();
        found_identity(&copy, &device.keys, "desk", &[], NOW).unwrap();
        drop(copy);

        let refused = admit_device(
            &original,
            &device.keys,
            record_for(&device.machine.id, &device.keys, tag.as_str()),
        );
        assert!(
            format!("{:#}", refused.unwrap_err()).contains("is a copy"),
            "an unreminted copy is the original to its peers"
        );

        let HardwareCheck::Reminted { machine_id, .. } = device.check(&hw(&["disk:B"])) else {
            panic!("a copy on other hardware is reminted");
        };
        let copy = SqliteStore::open(&db, machine_id.clone()).unwrap();
        assert!(copy.envelopes_for_machine(&machine_id).unwrap().is_empty());
        assert!(copy.device_record(&machine_id).unwrap().is_none());
        assert!(
            copy.device_record(&device.machine.id).unwrap().is_some(),
            "the copy keeps what it held"
        );

        let keys = device.keys_now();
        admit_device(
            &original,
            &device.keys,
            record_for(&machine_id, &keys, tag.as_str()),
        )
        .unwrap();
    }

    fn queued_forget() -> write_queue::Entry {
        write_queue::Entry {
            tool: "forget".to_string(),
            method: "DELETE".to_string(),
            path: "/v1/memory/m-1".to_string(),
            query: Some("hard=false&reason=wrong".to_string()),
            body: None,
        }
    }

    /// Queues `entry` sealed to the device's current key; returns its path.
    fn queue_sealed(device: &Device, entry: &write_queue::Entry) -> std::path::PathBuf {
        let queue = device.path().join(write_queue::DIR_NAME);
        fs::create_dir_all(&queue).unwrap();
        let path = queue.join(write_queue::entry_name(1, true));
        let sealed = entry
            .to_sealed_file(&[device.keys.age_recipient()])
            .unwrap();
        fs::write(&path, sealed).unwrap();
        publish_device_pub(device.path(), &device.keys).unwrap();
        path
    }

    #[test]
    fn a_remint_stopped_right_after_the_key_swap_leaves_queued_writes_readable() {
        let device = device_on(&hw(&["disk:A"]));
        let entry = queued_forget();
        let path = queue_sealed(&device, &entry);
        let fresh = DeviceKeys::generate().unwrap();

        super::seal_to_both(device.path(), &device.keys, &fresh).unwrap();
        assert!(!device.path().join(DEVICE_PUB_FILE).exists());
        replace_device_keys(device.path(), &KeyStorage::File, &fresh).unwrap();
        let keys = device.keys_now();
        assert!(same_keys(&keys, &fresh));
        let opened = write_queue::open(&fs::read(&path).unwrap(), Some(keys.age_identity()));
        assert_eq!(opened.unwrap(), entry);

        assert!(matches!(
            device.check(&hw(&["disk:B"])),
            HardwareCheck::Reminted { .. }
        ));
        let keys = device.keys_now();
        let opened = write_queue::open(&fs::read(&path).unwrap(), Some(keys.age_identity()));
        assert_eq!(opened.unwrap(), entry);
    }

    #[test]
    fn a_write_sealed_to_the_old_key_during_the_swap_is_resealed_when_it_settles() {
        let device = device_on(&hw(&["disk:A"]));
        let fresh = DeviceKeys::generate().unwrap();
        super::seal_to_both(device.path(), &device.keys, &fresh).unwrap();
        replace_device_keys(device.path(), &KeyStorage::File, &fresh).unwrap();
        let entry = queued_forget();
        let late = queue_sealed(&device, &entry);

        super::settle_on(device.path(), &device.keys, &fresh).unwrap();
        let bytes = fs::read(&late).unwrap();
        let opened = write_queue::open(&bytes, Some(fresh.age_identity()));
        assert_eq!(opened.unwrap(), entry);
        assert!(write_queue::open(&bytes, Some(device.keys.age_identity())).is_err());
        assert_eq!(
            fs::read_to_string(device.path().join(DEVICE_PUB_FILE)).unwrap(),
            format!("{}\n", fresh.age_recipient())
        );
    }

    #[test]
    fn writes_queued_under_the_old_key_replay_with_the_reminted_one() {
        let device = device_on(&hw(&["disk:A"]));
        let entry = queued_forget();
        let path = queue_sealed(&device, &entry);

        assert!(matches!(
            device.check(&hw(&["disk:B"])),
            HardwareCheck::Reminted { .. }
        ));
        let keys = device.keys_now();
        let bytes = fs::read(&path).unwrap();
        let opened = write_queue::open(&bytes, Some(keys.age_identity())).unwrap();
        assert_eq!(opened, entry);
        assert!(write_queue::open(&bytes, Some(device.keys.age_identity())).is_err());
        assert_eq!(
            fs::read_to_string(device.path().join(DEVICE_PUB_FILE)).unwrap(),
            format!("{}\n", keys.age_recipient())
        );
    }

    #[test]
    fn a_remint_cut_short_after_the_key_swap_finishes_at_the_next_start() {
        let device = device_on(&hw(&["disk:A"]));
        super::swap_device_keys(device.path(), &KeyStorage::File, &device.keys).unwrap();
        assert_eq!(device.machine_id(), device.machine.id);

        assert!(matches!(
            device.check(&hw(&["disk:B"])),
            HardwareCheck::Reminted { .. }
        ));
        assert_ne!(device.machine_id(), device.machine.id);
        let store_key = read_store_key(&device.path().join(STORE_KEY_FILE), &device.keys_now())
            .unwrap()
            .unwrap();
        assert_eq!(store_key.expose(), device.store_key.expose());
    }

    #[test]
    fn a_remint_that_fails_is_marked_so_the_daemon_stops_and_the_next_start_finishes_it() {
        let device = device_on(&hw(&["disk:A"]));
        let blocker = device.path().join("not-a-dir");
        fs::write(&blocker, "").unwrap();
        let err = check_hardware_with(
            device.path(),
            &blocker.join("config"),
            &KeyStorage::File,
            &hw(&["disk:B"]),
        )
        .unwrap_err();
        assert!(err.downcast_ref::<RemintFailed>().is_some(), "{err:#}");
        assert_eq!(
            read_binding(device.path()).unwrap(),
            Some(HardwareId::parse("disk:A"))
        );

        assert!(matches!(
            device.check(&hw(&["disk:B"])),
            HardwareCheck::Reminted { .. }
        ));
        assert_ne!(device.machine_id(), device.machine.id);
        let store_key = read_store_key(&device.path().join(STORE_KEY_FILE), &device.keys_now())
            .unwrap()
            .unwrap();
        assert_eq!(store_key.expose(), device.store_key.expose());
    }

    #[test]
    fn a_pending_rotation_key_is_rewrapped_with_the_store_key() {
        let device = device_on(&hw(&["disk:A"]));
        let next = StoreKey::generate().unwrap();
        write_store_key(device.path(), NEXT_STORE_KEY_FILE, &next, &device.keys).unwrap();
        assert!(matches!(
            device.check(&hw(&["disk:B"])),
            HardwareCheck::Reminted { .. }
        ));
        let keys = device.keys_now();
        let opened = read_store_key(&device.path().join(NEXT_STORE_KEY_FILE), &keys)
            .unwrap()
            .unwrap();
        assert_eq!(opened.expose(), next.expose());
        assert!(read_store_key(&device.path().join(NEXT_STORE_KEY_FILE), &device.keys).is_err());
    }

    #[test]
    fn a_sealed_copy_that_does_not_open_beside_the_plain_key_is_replaced_by_a_plain_key() {
        let device = device_on(&hw(&["disk:A"]));
        fs::write(
            device.path().join(SEALED_DEVICE_KEY_FILE),
            b"sealed on the original",
        )
        .unwrap();
        let storage = KeyStorage::Sealed(Arc::new(XorSealer));
        let check =
            check_hardware_with(device.path(), device.path(), &storage, &hw(&["disk:B"])).unwrap();
        assert!(matches!(check, HardwareCheck::Reminted { .. }));
        assert!(!device.path().join(SEALED_DEVICE_KEY_FILE).exists());
        let keys = load_device_keys_in(device.path(), &storage)
            .unwrap()
            .unwrap();
        assert!(!same_keys(&keys, &device.keys));
        let store_key = read_store_key(&device.path().join(STORE_KEY_FILE), &keys)
            .unwrap()
            .unwrap();
        assert_eq!(store_key.expose(), device.store_key.expose());
    }

    const FAKE_MAGIC: &[u8] = b"XOR";

    struct XorSealer;

    impl CredentialSealer for XorSealer {
        fn seal(&self, plaintext: &[u8]) -> Result<Vec<u8>> {
            let mut out = FAKE_MAGIC.to_vec();
            out.extend(plaintext.iter().map(|b| b ^ 0x5a));
            Ok(out)
        }

        fn unseal(&self, sealed: &[u8]) -> Result<KeyGuard<Vec<u8>>> {
            let body = sealed
                .strip_prefix(FAKE_MAGIC)
                .ok_or_else(|| anyhow!("not sealed by the fake"))?;
            Ok(KeyGuard::new(body.iter().map(|b| b ^ 0x5a).collect()))
        }
    }

    #[test]
    fn a_sealed_device_key_is_replaced_in_sealed_storage() {
        let dir = tempfile::tempdir().unwrap();
        let storage = KeyStorage::Sealed(Arc::new(XorSealer));
        let old = create_device_keys_with(dir.path(), &storage, &hw(&["disk:A"])).unwrap();
        assert!(dir.path().join(SEALED_DEVICE_KEY_FILE).exists());

        let check = check_hardware_with(dir.path(), dir.path(), &storage, &hw(&["disk:B"]));
        assert!(matches!(check.unwrap(), HardwareCheck::Reminted { .. }));
        assert!(dir.path().join(SEALED_DEVICE_KEY_FILE).exists());
        assert!(!dir.path().join(DEVICE_KEY_FILE).exists());
        let keys = load_device_keys_in(dir.path(), &storage).unwrap().unwrap();
        assert!(!same_keys(&keys, &old));
    }

    #[cfg(feature = "encryption")]
    #[test]
    fn an_encrypted_copy_opens_its_store_under_the_new_keys() {
        use crate::keys::open_device_store;
        use crate::schema::{Memory, MemoryType};
        use crate::store::Store;

        let dir = tempfile::tempdir().unwrap();
        let db = dir.path().join("brain.db");
        let machine = MachineIdentity::load_or_create(dir.path()).unwrap();
        let opened =
            open_device_store(&db, dir.path(), machine.id.clone(), &KeyStorage::File).unwrap();
        let memory = Memory::new(
            "kept across the remint".to_string(),
            MemoryType::Semantic,
            "test".to_string(),
            String::new(),
        );
        opened.store.store_memory(&memory).unwrap();
        drop(opened);
        write_binding(dir.path(), &HardwareId::parse("disk:A")).unwrap();

        let check =
            check_hardware_with(dir.path(), dir.path(), &KeyStorage::File, &hw(&["disk:B"]));
        let HardwareCheck::Reminted { machine_id, .. } = check.unwrap() else {
            panic!("expected a remint");
        };
        let reopened = open_device_store(&db, dir.path(), machine_id, &KeyStorage::File).unwrap();
        assert!(reopened.store.get_memory(memory.id).unwrap().is_some());
    }
}