mnemo-engine 0.16.1

Encrypted, single-file, portable agent memory engine with multi-signal recall, sessions, snapshots, and an IVF+PQ index
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
//! Maintenance: export, rekey, verify, stats, and compaction (which also upgrades v8 files to v9).

use super::*;

impl Mnemo {
    /// Return the KDF (Argon2id) parameters this file currently uses to
    /// wrap its DEK. Needed by callers that want to [`rekey`] while
    /// keeping the file's original protection level (e.g. the Python
    /// binding's `rekey(fast=False)`, whose docstring promises exactly
    /// that). FIX-1 R-001.5.
    pub fn kdf_params(&self) -> KdfParams {
        self.kdf
    }

    /// Flush any pending writes, then stream the (encrypted) file to
    /// `dest` atomically: writes to a sibling temp file in `dest`'s
    /// parent directory, `sync_all`s it, renames onto `dest`, and
    /// fsyncs the parent directory on Unix so a crash never leaves a
    /// partial export.
    ///
    /// Refuses when `dest` resolves to the file this handle has open
    /// — that case would otherwise `File::create`-truncate the live
    /// database to 0 bytes (`fs::copy` on Unix reads *after* the
    /// `O_TRUNC`, so a naive export-to-self destroys the source).
    /// Unix: compares `(dev, ino)` of both paths via `MetadataExt`,
    /// catching symlinks and hard links. Windows: compares
    /// canonicalized paths. (The rename is no second line of defense:
    /// renaming over a file another handle holds open and locked
    /// succeeds on Windows too, as a 2026-11-13 CI probe showed.)
    ///
    /// Reads the bytes from the already-open file handle, not by
    /// `fs::copy`. On Windows that matters: `LockFileEx` locks are
    /// mandatory, so a second handle opened by `fs::copy` would fail
    /// while this writer still holds the lock.
    ///
    /// FIX-1 R-001.5 + R-002.2 part 3.
    pub fn export_encrypted(&mut self, dest: impl AsRef<Path>) -> Result<()> {
        let dest = dest.as_ref();

        // Step 1 — refuse export to the open file itself. We compare
        // by identity, not string, so symlinks and hard links to
        // `self.path` are caught too. The check runs before any flush
        // so a self-targeted export is a pure no-op.
        if paths_refer_to_same_file(&self.path, dest).unwrap_or(false) {
            return Err(MnemoError::Invalid(format!(
                "export_encrypted refuses to overwrite the open database at {}",
                dest.display()
            )));
        }

        // Step 2 — flush, so on-disk bytes match the live state.
        if !self.read_only {
            self.flush()?;
        }

        // Step 3 — stream from the open handle into a sibling temp.
        // Using the open handle (instead of a second open on `self.path`)
        // means a Windows mandatory lock can't block the copy.
        let parent = dest.parent().ok_or_else(|| {
            MnemoError::Invalid(format!(
                "export_encrypted: dest {} has no parent directory",
                dest.display()
            ))
        })?;
        // A new file under a fresh name: `create_new` refuses anything
        // already there, a symlink included, and a taken name gets another.
        let (tmp, mut out) = {
            let mut attempt = 0;
            loop {
                let tmp = temp_sibling(dest, "export");
                match owner_only(OpenOptions::new().write(true).create_new(true)).open(&tmp) {
                    Ok(out) => break (tmp, out),
                    Err(e)
                        if e.kind() == std::io::ErrorKind::AlreadyExists
                            && attempt + 1 < TEMP_NAME_ATTEMPTS =>
                    {
                        attempt += 1;
                    }
                    Err(e) => return Err(MnemoError::Io(e)),
                }
            }
        };
        // Scope the temp handle so it closes before the rename on
        // Windows (which refuses to rename a file this process has open).
        {
            let src = self.pager.file_mut();
            src.seek(SeekFrom::Start(0))?;
            let mut buf = vec![0u8; 1 << 20]; // 1 MiB
            loop {
                let n = src.read(&mut buf)?;
                if n == 0 {
                    break;
                }
                out.write_all(&buf[..n])?;
            }
            out.sync_all()?;
            crate::bump_fsync();
            drop(out);
        }

        // Step 4 — atomic rename onto `dest`.
        if let Err(e) = std::fs::rename(&tmp, dest) {
            // Best-effort cleanup; propagate the rename error.
            let _ = std::fs::remove_file(&tmp);
            return Err(MnemoError::Io(e));
        }

        // Step 5 — fsync the parent directory on Unix so the rename
        // itself is durable. On Windows directory syncs aren't
        // supported; the rename above is atomic enough on NTFS.
        #[cfg(unix)]
        {
            if let Ok(dir) = File::open(parent) {
                let _ = dir.sync_all();
                crate::bump_fsync();
            }
        }
        #[cfg(not(unix))]
        {
            let _ = parent;
        }

        Ok(())
    }

    /// Change the passphrase. Cheap: re-derives the KEK and re-wraps the DEK;
    /// the encrypted pages are never rewritten.
    ///
    /// **This changes the secret that opens this file from now on; anyone who
    /// had the file and the old secret can still read it and later writes.**
    /// The data key stays the same, so an earlier copy of the file (or of
    /// just its header) and the old passphrase still unlock it. The old wrap
    /// is scrubbed from this file (the previous WAL region is zeroed, and any
    /// stale copy of the old header's key wrap is overwritten); that's
    /// hygiene, not revocation. **To revoke, rotate:** rekey, then
    /// [`Mnemo::compact_file`] (`mnemo rekey --rotate`), which rewrites the
    /// file under a fresh data key. Rotation can't erase old ciphertext the storage hardware still holds: flash keeps rewritten blocks until it reuses them, and that's out of the engine's hands.
    ///
    /// **An error means the old secret is still in force,** for this handle
    /// and for the file, including after later writes and a close (REKEY-1).
    /// The one exception is when the new header's write fails and putting
    /// the old one back fails too: the error then says so, and the file may
    /// open with either secret.
    ///
    /// `Ok` means the new secret is in force. Scrubbing the old wrap
    /// afterwards is hygiene; if part of it fails, the rekey still succeeds
    /// and [`Mnemo::rekey_cleanup_error`] says what was left.
    pub fn rekey(&mut self, new_passphrase: &str, kdf: KdfParams) -> Result<()> {
        self.rekey_secret(new_passphrase.as_bytes(), SecretKind::Passphrase, kdf)
    }

    /// PERF-1 step 7: switch to (or rotate) a raw 256-bit key, recording
    /// [`KdfParams::raw_key`] in the header. Like [`Mnemo::rekey`], only the
    /// wrapped DEK changes; pages aren't rewritten, and it doesn't revoke
    /// the old key (see [`Mnemo::rekey`]).
    ///
    /// Errors and the cleanup report work as in [`Mnemo::rekey`].
    pub fn rekey_with_key(&mut self, new_key: &[u8; crypto::KEY_LEN]) -> Result<()> {
        self.rekey_secret(new_key, SecretKind::Key, KdfParams::raw_key())
    }

    pub(super) fn rekey_secret(
        &mut self,
        secret: &[u8],
        kind: SecretKind,
        kdf: KdfParams,
    ) -> Result<()> {
        if self.shared {
            // RB-007.2: the shared handle would keep the old secret, and
            // fail at the next compaction or recovery.
            return Err(MnemoError::Unsupported(
                "inside a shared-mode window, change the passphrase with SharedMnemo::rekey, \
                 which also updates the secret the handle keeps. Nothing was changed"
                    .into(),
            ));
        }
        self.rekey_unchecked(secret, kind, kdf, None)
    }

    /// 12.3 (the keys note, section 4): [`Mnemo::rekey`] or
    /// [`Mnemo::rekey_with_key`], with `before_commit` run once the new salt
    /// is drawn and before anything is written, so a caller can store the new
    /// secret under that salt first. An error from it stops the rekey with
    /// nothing changed. Used by [`crate::keys::rekey_stored`].
    pub(crate) fn rekey_staged(
        &mut self,
        secret: &[u8],
        kind: SecretKind,
        kdf: KdfParams,
        before_commit: &mut crypto::SaltHook<'_>,
    ) -> Result<()> {
        if self.shared {
            return Err(MnemoError::Unsupported(
                "a staged rekey runs on a plain handle only".into(),
            ));
        }
        self.rekey_unchecked(secret, kind, kdf, Some(before_commit))
    }

    /// The rekey itself; [`SharedMnemo::rekey`] calls it in its window. 12.3:
    /// where every rekey meets, so a passphrase with raw-key parameters is
    /// refused here (the keys note, section 1, rule 2).
    pub(super) fn rekey_unchecked(
        &mut self,
        secret: &[u8],
        kind: SecretKind,
        kdf: KdfParams,
        before_commit: Option<&mut crypto::SaltHook<'_>>,
    ) -> Result<()> {
        if self.read_only {
            return Err(MnemoError::ReadOnly);
        }
        crypto::check_kdf_for(kind, kdf)?;
        self.rekey_cleanup = None;
        self.flush()?;
        // v0.14.0 step 1: `flush` checks only when it has something to
        // write; the rekey writes either way.
        self.ensure_not_replaced()?;
        let new_salt = crypto::random_salt();
        let new_kek = crypto::derive_kek(secret, &new_salt, kdf)?;
        let new_nonce = crypto::random_nonce();
        let wrapped = crypto::wrap_dek(&new_kek, &new_nonce, self.pager.dek())?;
        if wrapped.len() != WRAPPED_DEK_LEN {
            return Err(MnemoError::Crypto("unexpected wrapped DEK length".into()));
        }
        let mut wrapped_dek = [0u8; WRAPPED_DEK_LEN];
        wrapped_dek.copy_from_slice(&wrapped);
        // 12.3: the caller stores the new secret under `new_salt` before
        // anything is written.
        if let Some(hook) = before_commit {
            hook(&new_salt)?;
        }

        // SEC-2: the old header's key wrap (salt, DEK nonce, wrapped DEK, as
        // laid out at header bytes 86..162), to scrub once the new header
        // is committed.
        let mut old_wrap =
            Vec::with_capacity(crypto::SALT_LEN + crypto::NONCE_LEN + WRAPPED_DEK_LEN);
        old_wrap.extend_from_slice(&self.header.salt);
        old_wrap.extend_from_slice(&self.header.dek_nonce);
        old_wrap.extend_from_slice(&self.header.wrapped_dek);

        // REKEY-1 (RB-004.2): until the new page 0 is on disk, a failure puts
        // these back, so an `Err` means "still the old secret".
        let before = self.header.clone();
        let before_kdf = self.kdf;

        self.header.salt = new_salt;
        self.header.dek_nonce = new_nonce;
        self.header.wrapped_dek = wrapped_dek;
        self.header.m_cost = kdf.m_cost;
        self.header.t_cost = kdf.t_cost;
        self.header.p_cost = kdf.p_cost;
        self.kdf = kdf;

        // DUR-1 (R-002.1): WAL-log the new page 0 before touching it.
        // Allocate a fresh WAL region at the tail so that a crash during
        // the rekey leaves either the old region (old passphrase works)
        // or the new region (new passphrase works) fully committed —
        // overwriting the existing region would risk destroying both.
        let old_wal_start = self.header.wal_start;
        let new_pages = self.header.wal_pages;
        let new_start = self.header.next_page;
        self.header.next_page += new_pages;
        self.header.wal_start = new_start;
        self.header.wal_pages = new_pages;
        self.header.wal_seq += 1;

        // The steps of `relocate_header_through_wal`, apart, so a failure
        // can be told from one before page 0 and one after it.
        self.header.write_counter = self.pager.write_counter;
        let mut page = self.header.to_page();
        if let Err(e) = self.header.apply_seal(&mut page, self.pager.dek()) {
            return Err(self.undo_rekey(before, before_kdf, None, false, e));
        }
        let frames = vec![(0u64, page.to_vec())];
        let txn_id = self.header.wal_seq;
        if let Err(e) = wal::commit(self.pager.file_mut(), new_start, new_pages, txn_id, &frames) {
            let region = Some((new_start, new_pages));
            return Err(self.undo_rekey(before, before_kdf, region, false, e));
        }
        if let Err(e) = self
            .pager
            .write_raw(0, &page)
            .and_then(|_| self.pager.sync())
        {
            let region = Some((new_start, new_pages));
            return Err(self.undo_rekey(before, before_kdf, region, true, e));
        }

        // The new page 0 is on disk: the new secret is in force, and nothing
        // below fails the rekey. SEC-2 (RB-001.30): zero the old region's
        // first frame header (so no scan reads it as a WAL), then all of it
        // (its frames hold page-0 images with the old wrap), then any other
        // stale copy of the old wrap in the file (an earlier, grown or
        // relocated region). Each step runs even if the one before failed.
        // Hygiene only: a copy of the file taken before the rekey still
        // opens with the old secret (see `rekey`).
        let mut left = Vec::new();
        if let Err(e) = wal::invalidate_region(self.pager.file_mut(), old_wal_start) {
            left.push(format!("clearing the old WAL region's first frame: {e}"));
        }
        if let Err(e) = wal::scrub_region(self.pager.file_mut(), old_wal_start, new_pages) {
            left.push(format!("zeroing the old WAL region: {e}"));
        }
        if let Err(e) = scrub_bytes(self.pager.file_mut(), &old_wrap) {
            left.push(format!("overwriting other copies of the old key wrap: {e}"));
        }
        self.rekey_cleanup = (!left.is_empty()).then(|| left.join("; "));
        // FMT-9 (a): the old region is freed by the next commit (see
        // `ensure_wal_capacity`).
        self.release_pages(old_wal_start, new_pages);
        Ok(())
    }

    /// REKEY-1: a rekey failed before its new page 0 was on disk. Put the
    /// header and the KDF back, so the handle (and every later write) uses
    /// the old secret. Then, best effort: zero the new WAL region, whose
    /// commit wraps the data key under the new secret, so a later
    /// torn-header scan can't find it; and, if page 0 may have been
    /// written, write the old one back.
    fn undo_rekey(
        &mut self,
        before: crate::format::Header,
        before_kdf: KdfParams,
        new_region: Option<(u64, u64)>,
        page0_written: bool,
        err: MnemoError,
    ) -> MnemoError {
        self.header = before;
        self.kdf = before_kdf;
        // RB-005.2: a failed zeroing is reported, not dropped. The old
        // secret is still in force either way; what's left is a committed
        // copy of the new key wrap in the region past the file's end,
        // which a torn-header scan could use with the new secret until a
        // compaction clears it (a later write over those pages also does).
        let scrub_failed = new_region.and_then(|(start, pages)| {
            wal::scrub_region(self.pager.file_mut(), start, pages).err()
        });
        let with_scrub_note = |err: MnemoError| match &scrub_failed {
            None => err,
            Some(e) => MnemoError::Io(std::io::Error::other(format!(
                "{err}; the old secret is still in force, but zeroing the new key wrap's \
                 copy failed ({e}), so a copy may be left in the file until `mnemo compact` \
                 clears it (a later write over those pages also does)"
            ))),
        };
        if !page0_written {
            return with_scrub_note(err);
        }
        self.header.write_counter = self.pager.write_counter;
        let mut page = self.header.to_page();
        let put_back = self
            .header
            .apply_seal(&mut page, self.pager.dek())
            .and_then(|_| self.pager.write_raw(0, &page))
            .and_then(|_| self.pager.sync());
        match put_back {
            Ok(()) => with_scrub_note(err),
            // `mnemo rekey` looks for "may open with either secret" to leave
            // out its "the passphrase was not changed": keep the phrase.
            Err(again) => MnemoError::Io(std::io::Error::other(format!(
                "rekey failed writing the new header ({err}), and the old header \
                 couldn't be written back ({again}): the file {EITHER_SECRET}; close it \
                 without writing and try both"
            ))),
        }
    }

    /// 12.3: whether `e` is REKEY-1's one exception, the error that says the
    /// file may open with either secret. Kept beside the message it reads.
    pub(crate) fn rekey_left_either_secret(e: &MnemoError) -> bool {
        e.to_string().contains(EITHER_SECRET)
    }

    /// REKEY-1 (RB-004.2): after a successful [`Mnemo::rekey`] or
    /// [`Mnemo::rekey_with_key`], what couldn't be scrubbed of the old key
    /// wrap, or `None` if it all was. The rekey took effect either way; what
    /// is left is plaintext key-wrap bytes the old secret could still use, so
    /// to be sure, rotate (`compact_file`) as [`Mnemo::rekey`] describes.
    /// Each rekey resets it.
    pub fn rekey_cleanup_error(&self) -> Option<&str> {
        self.rekey_cleanup.as_deref()
    }

    /// SEC-2 (RB-001.30): write a copy of this database at `dest` under a
    /// **fresh data key**, protected by `passphrase` through `kdf`. It goes
    /// through the compaction path (live memories, the result cache and
    /// the index, no history), so the copy shares no key material with
    /// this file: neither this file's passphrase nor its data key opens
    /// it, and its passphrase opens nothing here. This file is flushed
    /// first (unless read-only) and is otherwise unchanged; `dest` must not
    /// exist. The copy is v9.
    pub fn export_rekeyed(
        &mut self,
        dest: impl AsRef<Path>,
        passphrase: &str,
        kdf: KdfParams,
    ) -> Result<CompactReport> {
        self.export_rekeyed_secret(
            dest.as_ref(),
            passphrase.as_bytes(),
            SecretKind::Passphrase,
            kdf,
        )
    }

    /// [`Mnemo::export_rekeyed`] protected by a raw 256-bit key (no KDF).
    pub fn export_rekeyed_with_key(
        &mut self,
        dest: impl AsRef<Path>,
        key: &[u8; crypto::KEY_LEN],
    ) -> Result<CompactReport> {
        self.export_rekeyed_secret(dest.as_ref(), key, SecretKind::Key, KdfParams::raw_key())
    }

    pub(super) fn export_rekeyed_secret(
        &mut self,
        dest: &Path,
        secret: &[u8],
        kind: SecretKind,
        kdf: KdfParams,
    ) -> Result<CompactReport> {
        crypto::check_kdf_for(kind, kdf)?;
        if paths_refer_to_same_file(&self.path, dest).unwrap_or(false) {
            return Err(MnemoError::Invalid(format!(
                "export_rekeyed refuses to overwrite the open database at {}",
                dest.display()
            )));
        }
        if dest.exists() {
            return Err(MnemoError::Invalid(format!(
                "{} already exists",
                dest.display()
            )));
        }
        if !self.read_only {
            self.flush()?;
        }
        let config = MnemoConfig {
            dimensions: self.dimensions,
            kdf,
            store_float_vectors: self.float_vectors(),
            ..Default::default()
        };
        let (tmp, mut new) = create_temp(dest, "export", secret, kind, config, None)?;
        let result = (|| {
            let report = self.copy_live_into(&mut new)?;
            new.flush()?;
            drop(new);
            std::fs::rename(&tmp, dest)?;
            Ok(report)
        })();
        if result.is_err() {
            let _ = std::fs::remove_file(&tmp);
        }
        result
    }

    /// The compaction copy: every live, unexpired memory and cache entry of
    /// `self` into `new` (a freshly created file), and the index if `self`
    /// has one. Counts as [`CompactReport`].
    pub(super) fn copy_live_into(&mut self, new: &mut Mnemo) -> Result<CompactReport> {
        // FMT-9e: compaction rewrites everything, so it compresses every
        // thread turn, recent or not.
        new.turn_compress_after = 0;
        // ANN-1.1: compaction is "re-tune for the current size" by
        // default. Pass IndexConfig::default() so partitions,
        // subspaces, n_probe and n_rerank are all re-derived from the
        // compacted vector count. Previously we froze the pre-compact
        // (n_probe, n_rerank), which left the new index on stale
        // numbers for the smaller post-compact corpus.
        let want_index = self.has_index();
        let now = memory::now_secs();
        let all = self.memories()?;
        let before = all.len();
        let mut after = 0;
        let mut zero_vector_manifests = 0;
        let mut zero_vector_memories = 0;
        for mut m in all {
            if m.is_expired(now) {
                continue;
            }
            // A file from before the zero-vector rule (Phase 3 PR 10a) can
            // hold all-zero vectors. A legacy onboarding or manifest memory
            // gets the sentinel unit vector a current manifest has, so it
            // behaves like a new one; any other is carried unchanged.
            if embed::is_zero_vector(&m.vector) {
                if crud::is_onboarding(&m) || is_manifest(&m) {
                    m.vector = Memory::scaffold_manifest(self.dimensions).vector;
                    zero_vector_manifests += 1;
                } else {
                    zero_vector_memories += 1;
                }
            }
            // The engine's own copy: `_mnemo.*` keys come through as they
            // are, and the write-time zero-vector check doesn't apply.
            new.put_existing(m)?;
            after += 1;
        }
        if want_index && after > 0 {
            new.build_index_with(IndexConfig::default())?;
        }

        // Count + copy cache entries. We walk `self.cache_dir` by index
        // so each hop reads the directory's live `accessed_at` /
        // `access_count` directly rather than going through
        // `cache_get` (which would also treat read-only semantics,
        // tombstones, etc. — we want the raw, authoritative values).
        let mut cache_before = 0usize;
        let mut cache_after = 0usize;
        let positions: Vec<usize> = (0..self.cache_dir.len()).collect();
        for pos in positions {
            let (keep, reserved) = {
                let e = &self.cache_dir[pos];
                (
                    !e.deleted && !e.is_expired(now),
                    embed::is_reserved_namespace(&e.namespace),
                )
            };
            if keep {
                // EMBED-ID-1: the engine's own entries (the embedder
                // identity) are copied but not counted.
                new.copy_cache_entry_from(self, pos)?;
                if !reserved {
                    cache_before += 1;
                    cache_after += 1;
                }
            }
        }
        Ok(CompactReport {
            before,
            after,
            cache_before,
            cache_after,
            zero_vector_manifests,
            zero_vector_memories,
        })
    }

    /// Decrypt and validate every live record. Returns the count verified
    /// across memories **and** cache entries (FIX-1 R-001.1: now that the
    /// cache survives compaction, `verify()` has to walk it too — the
    /// pre-FIX-1 implementation only checked `self.catalog`, so a
    /// corrupted cache record went unnoticed).
    pub fn verify(&mut self) -> Result<usize> {
        Ok(self.verify_report()?.records)
    }

    /// [`Mnemo::verify`], also counting the memories whose vector is all
    /// zeros. A file written before the zero-vector rule (Phase 3 PR 10a)
    /// can hold them; they decode fine but score 0.0 on every vector query.
    /// `mnemo verify` warns about them, and compaction carries them
    /// (giving a legacy manifest the sentinel vector).
    pub fn verify_report(&mut self) -> Result<VerifyReport> {
        let entries: Vec<CatalogEntry> = self
            .catalog
            .iter()
            .filter(|e| !e.deleted)
            .cloned()
            .collect();
        let mut n = entries.len();
        let mut zero_vector_memories = 0;
        for e in &entries {
            let bytes = self.read_record(e)?;
            let m: Memory = self.decode_memory(&bytes)?;
            // FMT-9b: and the row's vector column entry.
            let zero = if e.v9.is_some() {
                let (h, _) = self.column_entry(e)?;
                if h.len() != self.dimensions {
                    return Err(MnemoError::Invalid(
                        "vector entry has the wrong width".into(),
                    ));
                }
                // fp16 +0.0 and -0.0.
                !h.is_empty() && h.iter().all(|b| b & 0x7fff == 0)
            } else {
                embed::is_zero_vector(&m.vector)
            };
            if zero {
                zero_vector_memories += 1;
            }
        }

        // Also decode every live cache entry. Tombstoned entries are
        // skipped — their pages are orphan ciphertext awaiting
        // `compact_file`, same as deleted memories. Expired entries
        // are *still* on disk until compaction, so we verify them too.
        let cache_positions: Vec<(u64, u32, u32, u64, bool)> = self
            .cache_dir
            .iter()
            .filter(|e| !e.deleted)
            .map(|e| {
                let reserved = embed::is_reserved_namespace(&e.namespace);
                (e.start_page, e.page_count, e.len, e.gen, reserved)
            })
            .collect();
        for (start_page, page_count, len, gen, reserved) in cache_positions {
            let buf = self.read_record_run(start_page, page_count, len, gen)?;
            let _c: CacheEntry = rmp_serde::from_slice(&buf)
                .map_err(|err| MnemoError::Serialize(err.to_string()))?;
            // EMBED-ID-1: the engine's own entries are checked, not counted.
            if !reserved {
                n += 1;
            }
        }
        // FMT-9 (a): no free run may overlap a page the committed state
        // references (records, cache entries, control runs, the WAL).
        if self.is_v9() {
            self.check_free_list_disjoint()?;
        }
        Ok(VerifyReport {
            records: n,
            zero_vector_memories,
            keyword_tokenizer: self.keyword_tokenizer()?,
        })
    }

    /// FMT-9 (a): fail if the free list (or a pending free) overlaps any
    /// page the current state references.
    pub(super) fn check_free_list_disjoint(&self) -> Result<()> {
        let h = &self.header;
        let mut live: Vec<(u64, u64, &str)> = vec![
            (h.wal_start, h.wal_pages, "WAL region"),
            (h.catalog_start, h.catalog_pages, "catalog run"),
            (h.index_start, h.index_pages, "index run"),
            (h.manifest_start, h.manifest_pages, "manifest run"),
            (h.cache_start, h.cache_pages, "cache directory run"),
            (h.free.start, h.free.pages, "free-list run"),
            (h.keys.start, h.keys.pages, "key-slot run"),
        ];
        live.extend(
            self.catalog
                .iter()
                .filter(|e| !e.deleted)
                .map(|e| (e.start_page, e.page_count as u64, "record")),
        );
        live.extend(
            self.cache_dir
                .iter()
                .filter(|e| !e.deleted)
                .map(|e| (e.start_page, e.page_count as u64, "cache entry")),
        );
        live.extend(self.col.page_rows.keys().map(|&p| (p, 1, "vector page")));
        live.extend(
            self.delta_chain
                .iter()
                .map(|r| (r.start, r.pages, "catalog delta run")),
        );
        live.extend(
            self.index_chain
                .iter()
                .map(|r| (r.start, r.pages, "index delta run")),
        );
        live.push((
            self.header.bm25.start,
            self.header.bm25.pages,
            "BM25 manifest",
        ));
        live.extend(
            self.bm25
                .manifest
                .segments
                .iter()
                .map(|t| (t.0, t.1, "BM25 segment")),
        );
        for (p, c, what) in live {
            if c == 0 {
                continue;
            }
            if self.free.overlaps(p, c) {
                return Err(MnemoError::Invalid(format!(
                    "free list overlaps a live {what} at page {p} (+{c})"
                )));
            }
            if self
                .pending_free
                .iter()
                .any(|&(q, n)| q < p + c && p < q + n)
            {
                return Err(MnemoError::Invalid(format!(
                    "a pending free overlaps a live {what} at page {p} (+{c})"
                )));
            }
        }
        Ok(())
    }

    /// The statistics that need no record decrypts and no index load
    /// (v0.12.2, RB-002.3): counts, sizes, the format, whether an index
    /// exists, the recall mode and the bytes the vector column needs. The
    /// first [`Mnemo::stats`] on a handle decrypts every record (for its
    /// agent list) and loads a persisted index; this is what a phone app
    /// polling the recall mode should call.
    pub fn stats_summary(&self) -> StatsSummary {
        let deleted = self.catalog.iter().filter(|e| e.deleted).count();
        let v9 = self.is_v9();
        let column = if v9 {
            (self.scored_rows() * crate::veccol::entry_len(self.dimensions)) as u64
        } else {
            0
        };
        let recall_mode = if self.has_index() {
            RecallMode::Indexed
        } else if v9 && column <= self.vector_cache_budget as u64 {
            RecallMode::ExactResident
        } else {
            RecallMode::ExactPaged
        };
        let rp = self.restore_points();
        StatsSummary {
            memories: self.len(),
            deleted,
            dimensions: self.dimensions,
            file_bytes: self.header.next_page * PAGE_SIZE as u64,
            format_version: self.header.version,
            wal_pages: self.header.wal_pages,
            has_index: self.has_index(),
            recall_mode,
            vector_column_bytes: column,
            snapshots_retained: rp.retained,
            oldest_restorable_at: rp.oldest_at,
            snapshot_pinned_bytes: rp.pinned_bytes,
        }
    }

    /// Summary statistics for the open database. The first call on a
    /// handle decrypts every record (to list the agents) and loads a
    /// persisted index; [`Mnemo::stats_summary`] does neither.
    pub fn stats(&mut self) -> Result<Stats> {
        let deleted = self.catalog.iter().filter(|e| e.deleted).count();
        // FIX-1 R-001.8 part 2: build the agent set lazily on first
        // call per handle, then maintain in `put` / invalidate in
        // `delete`. Pre-FIX-1 every `stats()` call decrypted every
        // live memory (O(N) AES-GCM decrypts just to list a usually-
        // tiny set of distinct agent IDs). On a 1M-memory database
        // this was in the multi-second range on hardware AES.
        if self.agent_set.is_none() {
            let built: std::collections::BTreeSet<String> =
                self.memories()?.into_iter().map(|m| m.agent_id).collect();
            self.agent_set = Some(built);
        }
        let agents: Vec<String> = self
            .agent_set
            .as_ref()
            .expect("agent_set just filled above")
            .iter()
            .cloned()
            .collect();
        let file_bytes = self.header.next_page * PAGE_SIZE as u64;
        let recall_mode = self.recall_mode()?;
        let rp = self.restore_points();
        Ok(Stats {
            memories: self.len(),
            deleted,
            dimensions: self.dimensions,
            file_bytes,
            agents,
            encrypted: self.header.flags & FLAG_ENCRYPTED != 0,
            created_at: self.header.created_at,
            index: {
                self.ensure_ann()?;
                self.ann.as_ref().map(|a| a.info())
            },
            wal_pages: self.header.wal_pages,
            fsyncs_last_flush: self.fsyncs_last_flush,
            format_version: self.header.version,
            recall_mode,
            snapshots_retained: rp.retained,
            oldest_restorable_at: rp.oldest_at,
            snapshot_pinned_bytes: rp.pinned_bytes,
            keyword_tokenizer: self.keyword_tokenizer()?,
        })
    }

    /// Rewrite the file, dropping tombstoned and expired memories and
    /// reclaiming stale pages left by updates. Done out-of-place via a temp
    /// file and an atomic rename.
    ///
    /// FIX-1 R-001.1 + R-002.2 part 2: the result cache now survives
    /// compaction. Every live, non-expired directory entry is copied
    /// into the new file verbatim — `created_at`, `ttl_secs`,
    /// `cost_hint_ms`, `key_preview`, `size_bytes`, `content_type`,
    /// `vector` and `model` come from the record body; `accessed_at`
    /// and `access_count` come from the *directory* (the record body
    /// only holds the insert-time snapshot — the directory is the
    /// source of truth for the live counts, as of v5's recall trick).
    /// Tombstoned and TTL-expired entries are dropped. Pre-FIX-1
    /// compaction kept only the memory catalog and silently emptied
    /// the cache; the Planner's interim README caveat (c417d2e) called
    /// that out — this PR removes the surprise.
    ///
    /// The output is always v9, so this is also how a v4–v8 file is
    /// converted: the only read-write open that accepts one (the v8
    /// sunset, v0.13). It keeps every live memory.
    pub fn compact_file(path: &str, passphrase: &str) -> Result<CompactReport> {
        Self::compact_file_secret(
            path,
            passphrase.as_bytes(),
            SecretKind::Passphrase,
            0,
            &crate::SharedOptions::default(),
        )
    }

    /// PERF-1 step 7: [`Mnemo::compact_file`] for a raw-key database.
    pub fn compact_file_with_key(path: &str, key: &[u8; crypto::KEY_LEN]) -> Result<CompactReport> {
        Self::compact_file_secret(
            path,
            key,
            SecretKind::Key,
            0,
            &crate::SharedOptions::default(),
        )
    }

    /// [`Mnemo::compact_file`] with the lock layer's options: how long to
    /// wait for the file's lock (`opts.deadline`; `compact_file` waits 10 s),
    /// a cancel, and `allow_network_fs`. `mnemo compact --wait` uses it.
    pub fn compact_file_waiting(
        path: &str,
        passphrase: &str,
        opts: crate::SharedOptions,
    ) -> Result<CompactReport> {
        Self::compact_file_secret(
            path,
            passphrase.as_bytes(),
            SecretKind::Passphrase,
            0,
            &opts,
        )
    }

    /// [`Mnemo::compact_file_waiting`] for a raw-key database.
    pub fn compact_file_waiting_with_key(
        path: &str,
        key: &[u8; crypto::KEY_LEN],
        opts: crate::SharedOptions,
    ) -> Result<CompactReport> {
        Self::compact_file_secret(path, key, SecretKind::Key, 0, &opts)
    }

    pub(super) fn compact_file_secret(
        path: &str,
        secret: &[u8],
        kind: SecretKind,
        format_version: u16,
        opts: &crate::SharedOptions,
    ) -> Result<CompactReport> {
        // RB-007.3: compact the file the path names, through any symlink,
        // and rename over that file, so a link stays a link and every path
        // to the brain names the new file.
        let real = std::fs::canonicalize(path)?;
        // The one read-write open that takes a v4–v8 file (the v8 sunset).
        // RB-007.4: through the lock layer, so shared handles' busy reads
        // can't keep it out, and a shared caller that times out reads
        // "compact" in the lock-info note.
        let old = Mnemo::open_exclusive_secret(&real, secret, "compact", opts, true)?;
        // RB-007.8 item 8: with the exclusive lock held no compaction of
        // this file is running, so temp files left by dead ones can go.
        remove_dead_compaction_temps(&real);
        let dims = old.dimensions;
        // 12.3 (the keys note, section 1, rule 6): never lower the
        // parameters, and raise a passphrase file that's below the floor.
        let kdf = if kind == SecretKind::Passphrase && old.kdf.below_passphrase_floor() {
            old.kdf.for_passphrase()
        } else {
            old.kdf
        };
        // 12.3 (the salt rule): the new file keeps the salt, so whatever
        // found the secret for the old file (a keychain entry) finds it.
        let salt = old.header.salt;
        let config = MnemoConfig {
            dimensions: dims,
            kdf,
            // FMT-9f: compaction writes v9 (upgrading a v8 file),
            // unless `compact_file_to` asked for v8. A v9 file that
            // keeps float vectors keeps them.
            format_version,
            store_float_vectors: old.float_vectors(),
            ..Default::default()
        };
        // v0.14.0 step 1: a new file under a name no other compaction shares.
        let (tmp, new) = create_temp(&real, "compact", secret, kind, config, Some(salt))?;
        // Created owner-only; it keeps the old file's mode.
        if let Err(e) = copy_mode(old.pager.file(), new.pager.file()) {
            drop(new);
            let _ = std::fs::remove_file(&tmp);
            return Err(e);
        }
        // `compact_into` releases the old file's lock only after the rename.
        let result = Self::compact_into(old, new, &real, &tmp, |old, new| old.copy_live_into(new));
        if result.is_err() {
            let _ = std::fs::remove_file(&tmp);
        }
        result
    }

    /// Write the compacted copy of `old` to `tmp`, then rename it over
    /// `path`, all while `old` holds the old file's exclusive lock.
    ///
    /// v0.14.0 step 1 (12.4's design note, "Gaps in today's code"): the lock
    /// used to be released before the rename. A process that opened the
    /// path in that window locked the old file and wrote to it, and the
    /// rename then replaced it, losing those writes. Holding the lock
    /// through the rename and the directory sync means a process either
    /// waits on the old file's lock (and then finds, by `open_with_lock`'s
    /// identity check, that the path names the new file) or opens the new
    /// file.
    ///
    /// **Windows and the toolchain.** Renaming over a file another handle
    /// holds open and locked works on Linux and macOS with every toolchain,
    /// and on Windows when the engine is built with Rust 1.85 or later,
    /// whose `std::fs::rename` uses POSIX semantics. Built with 1.75 to 1.84
    /// (the MSRV is 1.75), Windows refuses it with "Access is denied" (os
    /// error 5) while the old file is open, so the rename is retried once
    /// after the old handle is closed, as before v0.14.0. That leaves the
    /// old window open for those builds; each commit's identity check
    /// (`ensure_not_replaced`) then turns nearly every write that would have
    /// been lost into `Replaced`. (Probed on CI, 2026-11-13: 1.75 to 1.84
    /// refuse, 1.85 to 1.100 succeed; the released binaries are built with
    /// stable.)
    fn compact_into<R>(
        mut old: Mnemo,
        mut new: Mnemo,
        path: &Path,
        tmp: &Path,
        copy: impl FnOnce(&mut Mnemo, &mut Mnemo) -> Result<R>,
    ) -> Result<R> {
        let report = copy(&mut old, &mut new)?;

        new.flush()?;
        // The new file is closed before the rename: Windows won't rename a
        // file this process still has open.
        drop(new);

        match std::fs::rename(tmp, path) {
            Ok(()) => {}
            #[cfg(windows)]
            Err(e) if e.kind() == std::io::ErrorKind::PermissionDenied => {
                // A toolchain before 1.85: see above.
                drop(old);
                std::fs::rename(tmp, path)?;
                return Ok(report);
            }
            Err(e) => return Err(MnemoError::Io(e)),
        }
        // Make the rename durable before the old file's lock goes.
        #[cfg(unix)]
        if let Some(parent) = path.parent() {
            let parent = if parent.as_os_str().is_empty() {
                Path::new(".")
            } else {
                parent
            };
            if let Ok(dir) = File::open(parent) {
                let _ = dir.sync_all();
                crate::bump_fsync();
            }
        }
        // Only now does the old file's lock go.
        drop(old);
        Ok(report)
    }

    /// 12.3 step 4 (v0.15): **embed every live memory again with
    /// `embedder`** and record its identity, so a file moves to a new model
    /// (or a new query convention, or a new width) in one step.
    ///
    /// It's a compaction with new vectors: it runs under the file's
    /// exclusive lock (waiting 10 s for it, like [`Mnemo::compact_file`]),
    /// writes a temp file beside the brain with the same salt and KDF
    /// parameters, and renames it over the brain while the lock is held. An
    /// interrupted run leaves the old file whole (and a temp file the next
    /// compaction or reembed removes), so the file never opens with two
    /// identities or mixed vectors.
    ///
    /// - Every live memory is embedded with [`Embedder::embed`] (the
    ///   document side), in batches of 64: facts, superseded versions (so
    ///   history reads stay consistent), essence items and thread turns.
    ///   A manifest and a thread link (`_mnemo.kind = "thread_link"`) keep
    ///   their sentinel vector, at the new width, and aren't embedded.
    /// - The new identity is recorded in the `_mnemo.embedder` entry and in
    ///   the manifest's `metadata.embedder`.
    /// - The result cache is copied as compaction copies it; a semantic
    ///   entry whose vector has the old width is dropped.
    /// - The ANN index is rebuilt if there was one, and the keyword index
    ///   with the current tokenizer (TOK-1). Snapshot history is dropped,
    ///   as by compaction.
    pub fn reembed_file(
        path: &str,
        passphrase: &str,
        embedder: &dyn Embedder,
    ) -> Result<ReembedReport> {
        Self::reembed_file_secret(
            path,
            passphrase.as_bytes(),
            SecretKind::Passphrase,
            embedder,
            &crate::SharedOptions::default(),
        )
    }

    /// [`Mnemo::reembed_file`] for a raw-key database.
    pub fn reembed_file_with_key(
        path: &str,
        key: &[u8; crypto::KEY_LEN],
        embedder: &dyn Embedder,
    ) -> Result<ReembedReport> {
        Self::reembed_file_secret(
            path,
            key,
            SecretKind::Key,
            embedder,
            &crate::SharedOptions::default(),
        )
    }

    /// [`Mnemo::reembed_file`] with the lock layer's options (how long to
    /// wait for the lock, a cancel), as [`Mnemo::compact_file_waiting`].
    pub fn reembed_file_waiting(
        path: &str,
        passphrase: &str,
        embedder: &dyn Embedder,
        opts: crate::SharedOptions,
    ) -> Result<ReembedReport> {
        Self::reembed_file_secret(
            path,
            passphrase.as_bytes(),
            SecretKind::Passphrase,
            embedder,
            &opts,
        )
    }

    /// [`Mnemo::reembed_file_waiting`] for a raw-key database.
    pub fn reembed_file_waiting_with_key(
        path: &str,
        key: &[u8; crypto::KEY_LEN],
        embedder: &dyn Embedder,
        opts: crate::SharedOptions,
    ) -> Result<ReembedReport> {
        Self::reembed_file_secret(path, key, SecretKind::Key, embedder, &opts)
    }

    fn reembed_file_secret(
        path: &str,
        secret: &[u8],
        kind: SecretKind,
        embedder: &dyn Embedder,
        opts: &crate::SharedOptions,
    ) -> Result<ReembedReport> {
        let to = embedder.identity();
        if to.dimensions == 0 {
            return Err(MnemoError::Invalid(
                "reembed: the embedder's identity has 0 dimensions".into(),
            ));
        }
        let real = std::fs::canonicalize(path)?;
        let mut old = Mnemo::open_exclusive_secret(&real, secret, "reembed", opts, true)?;
        remove_dead_temps(&real, "reembed");
        let from = old.recorded_identity()?;
        let kdf = if kind == SecretKind::Passphrase && old.kdf.below_passphrase_floor() {
            old.kdf.for_passphrase()
        } else {
            old.kdf
        };
        let salt = old.header.salt;
        let config = MnemoConfig {
            dimensions: to.dimensions,
            kdf,
            format_version: 0,
            store_float_vectors: old.float_vectors(),
            ..Default::default()
        };
        let (tmp, new) = create_temp(&real, "reembed", secret, kind, config, Some(salt))?;
        if let Err(e) = copy_mode(old.pager.file(), new.pager.file()) {
            drop(new);
            let _ = std::fs::remove_file(&tmp);
            return Err(e);
        }
        let result = Self::compact_into(old, new, &real, &tmp, |old, new| {
            old.copy_reembedded_into(new, embedder, from.clone(), to.clone())
        });
        if result.is_err() {
            let _ = std::fs::remove_file(&tmp);
        }
        result
    }

    /// [`Mnemo::reembed_file`]'s copy: every live memory with a new vector,
    /// the new identity, and the cache.
    fn copy_reembedded_into(
        &mut self,
        new: &mut Mnemo,
        embedder: &dyn Embedder,
        from: Option<embed::EmbedderIdentity>,
        to: embed::EmbedderIdentity,
    ) -> Result<ReembedReport> {
        const BATCH: usize = 64;
        new.turn_compress_after = 0;
        let want_index = self.has_index();
        let now = memory::now_secs();
        let dims = to.dimensions;
        let mut live: Vec<Memory> = self
            .memories()?
            .into_iter()
            .filter(|m| !m.is_expired(now))
            .collect();
        let mut manifests = 0;
        let mut thread_links = 0;
        for m in live.iter_mut() {
            if embed::read_identity_from_metadata(&m.metadata).is_some() {
                embed::write_identity_into_metadata(&mut m.metadata, &to);
            }
        }
        // R-008.3: a manifest and a thread link carry a sentinel vector, not
        // an embedding of their text.
        let is_link = |m: &Memory| {
            m.metadata.get(MNEMO_META_KIND).and_then(|v| v.as_str())
                == Some(MNEMO_META_KIND_THREAD_LINK)
        };
        let to_embed: Vec<usize> = (0..live.len())
            .filter(|&i| !is_manifest(&live[i]) && !is_link(&live[i]))
            .collect();
        for chunk in to_embed.chunks(BATCH) {
            let texts: Vec<&str> = chunk.iter().map(|&i| live[i].content.as_str()).collect();
            let vectors = embedder.embed(&texts)?;
            if vectors.len() != texts.len() {
                return Err(MnemoError::Invalid(format!(
                    "reembed: the embedder returned {} vectors for {} texts",
                    vectors.len(),
                    texts.len()
                )));
            }
            for (&i, v) in chunk.iter().zip(vectors) {
                if v.len() != dims {
                    return Err(MnemoError::DimensionMismatch {
                        expected: dims,
                        got: v.len(),
                    });
                }
                if embed::is_zero_vector(&v) {
                    return Err(MnemoError::Invalid(format!(
                        "reembed: the embedder returned an all-zero vector for memory {}",
                        live[i].id
                    )));
                }
                live[i].vector = v;
            }
        }
        let memories = live.len();
        for mut m in live {
            if is_manifest(&m) {
                m.vector = Memory::scaffold_manifest(dims).vector;
                manifests += 1;
            } else if is_link(&m) {
                m.vector = new.sentinel_vector();
                thread_links += 1;
            }
            new.put_existing(m)?;
        }
        if want_index && memories > 0 {
            new.build_index_with(IndexConfig::default())?;
        }
        let mut cache_entries = 0;
        let mut cache_dropped = 0;
        for pos in 0..self.cache_dir.len() {
            let (keep, reserved, wrong_width) = {
                let e = &self.cache_dir[pos];
                (
                    !e.deleted && !e.is_expired(now),
                    embed::is_reserved_namespace(&e.namespace),
                    e.vector.as_ref().is_some_and(|v| v.len() != dims),
                )
            };
            if !keep || (reserved && self.cache_dir[pos].namespace == embed::IDENTITY_NAMESPACE) {
                continue;
            }
            if wrong_width {
                cache_dropped += 1;
                continue;
            }
            new.copy_cache_entry_from(self, pos)?;
            if !reserved {
                cache_entries += 1;
            }
        }
        new.record_identity(&to)?;
        Ok(ReembedReport {
            memories: memories - manifests - thread_links,
            manifests,
            thread_links,
            cache_entries,
            cache_dropped,
            from,
            to,
        })
    }

    /// Copy one live cache entry from `old` at directory position
    /// `pos` into `self` (a freshly-created compaction target).
    /// Decrypts the old record body, substitutes the old *directory*'s
    /// `accessed_at` + `access_count` (the record body's copies are
    /// stale as of v5's directory-only hit path), re-encodes, writes
    /// a fresh record run, and pushes a matching directory entry.
    ///
    /// Caller is expected to have already filtered out tombstoned /
    /// expired entries and to call this on a read-write handle.
    pub(crate) fn copy_cache_entry_from(&mut self, old: &mut Mnemo, pos: usize) -> Result<()> {
        if self.read_only {
            return Err(MnemoError::ReadOnly);
        }
        // Snapshot the directory fields we need, so the borrow on
        // `old.cache_dir` ends before we touch `old.pager`.
        let (start_page, page_count, len, dir_accessed_at, dir_access_count, old_gen) = {
            let e = &old.cache_dir[pos];
            (
                e.start_page,
                e.page_count,
                e.len,
                e.accessed_at,
                e.access_count,
                e.gen,
            )
        };

        // Read + decrypt the old record body.
        let buf = old.read_record_run(start_page, page_count, len, old_gen)?;
        let mut entry: CacheEntry =
            rmp_serde::from_slice(&buf).map_err(|e| MnemoError::Serialize(e.to_string()))?;

        // Overwrite the stale body copies with the directory's live
        // values before persisting. Everything else — `created_at`,
        // `ttl_secs`, `cost_hint_ms`, `key_preview`, `size_bytes`,
        // `content_type`, `value`, `vector`, `model` — stays as the
        // body already recorded it.
        entry.accessed_at = dir_accessed_at;
        entry.access_count = dir_access_count;

        let bytes =
            rmp_serde::to_vec(&entry).map_err(|err| MnemoError::Serialize(err.to_string()))?;
        let (new_start_page, new_page_count, gen) = self.write_record(&bytes)?;

        let dir_entry = CacheDirectoryEntry {
            namespace: entry.namespace.clone(),
            key_hash: entry.key_hash,
            start_page: new_start_page,
            page_count: new_page_count,
            len: bytes.len() as u32,
            deleted: false,
            accessed_at: dir_accessed_at,
            access_count: dir_access_count,
            size_bytes: entry.size_bytes,
            ttl_secs: entry.ttl_secs,
            created_at: entry.created_at,
            vector: entry.vector.clone(),
            model: entry.model.clone(),
            gen,
        };
        let new_pos = self.cache_dir.len();
        self.cache_idx
            .insert(&entry.namespace, entry.key_hash, new_pos);
        self.cache_dir.push(dir_entry);
        self.dirty_cache = true;
        Ok(())
    }
}

/// SEC-2 (RB-001.30): overwrite every occurrence of `needle` in the file
/// with zeros, then sync. Rekey uses it for stale copies of the old header's
/// key wrap: they're plaintext (page 0 is sealed, not encrypted) and can sit
/// in WAL regions that were grown, relocated or freed. Every other page is
/// AES-GCM ciphertext, where a 76-byte random match doesn't happen.
pub(super) fn scrub_bytes(file: &mut std::fs::File, needle: &[u8]) -> Result<usize> {
    if needle.is_empty() {
        return Ok(0);
    }
    let len = file.seek(SeekFrom::End(0))?;
    let chunk = 1 << 20;
    let overlap = needle.len() - 1;
    let mut hits: Vec<u64> = Vec::new();
    let mut buf = vec![0u8; chunk + overlap];
    let mut pos: u64 = 0;
    while pos < len {
        let want = (chunk as u64 + overlap as u64).min(len - pos) as usize;
        file.seek(SeekFrom::Start(pos))?;
        file.read_exact(&mut buf[..want])?;
        let mut i = 0;
        while i + needle.len() <= want {
            if buf[i..i + needle.len()] == *needle {
                hits.push(pos + i as u64);
                i += needle.len();
            } else {
                i += 1;
            }
        }
        pos += chunk as u64;
    }
    hits.dedup();
    let zeros = vec![0u8; needle.len()];
    for off in &hits {
        file.seek(SeekFrom::Start(*off))?;
        file.write_all(&zeros)?;
    }
    if !hits.is_empty() {
        file.sync_all()?;
        crate::bump_fsync();
    }
    Ok(hits.len())
}

/// RB-007.8 item 8: remove the temp files that compactions of `brain` left
/// when their process died: in `brain`'s directory, regular files named
/// exactly `<brain's name>.compact-<pid>-<n>-<8 hex digits>.tmp` (the
/// pattern [`temp_sibling`] makes) whose pid isn't this process and no
/// longer runs, and, on Unix, that this user owns: in a shared directory
/// another user's file of the same name is left alone. Nothing else is
/// touched. Best effort; returns how many went.
///
/// Call it only with `brain`'s exclusive lock held: a live compaction holds
/// that lock for as long as its temp file exists. Off Unix no process
/// check is available, so nothing is removed.
pub(crate) fn remove_dead_compaction_temps(brain: &Path) -> usize {
    remove_dead_temps(brain, "compact")
}

/// [`remove_dead_compaction_temps`] for the temps of another operation
/// (`what`, as [`temp_sibling`] names them): 12.3's `init` uses "init".
pub(crate) fn remove_dead_temps(brain: &Path, what: &str) -> usize {
    let (Some(dir), Some(name)) = (brain.parent(), brain.file_name()) else {
        return 0;
    };
    let prefix = format!("{}.{what}-", name.to_string_lossy());
    let Ok(entries) = std::fs::read_dir(dir) else {
        return 0;
    };
    let mut removed = 0;
    for entry in entries.flatten() {
        let file_name = entry.file_name();
        let Some(pid) = file_name.to_str().and_then(|n| dead_temp_pid(n, &prefix)) else {
            continue;
        };
        if pid == std::process::id() || crate::shared::pid_alive(pid) {
            continue;
        }
        let path = entry.path();
        let Ok(meta) = std::fs::symlink_metadata(&path) else {
            continue;
        };
        if !meta.file_type().is_file() || !owned_by_us(&meta) {
            continue;
        }
        if std::fs::remove_file(&path).is_ok() {
            removed += 1;
        }
    }
    removed
}

/// Whether this process's user owns the file (Unix). Elsewhere, true: the
/// caller removes nothing off Unix anyway.
#[cfg(unix)]
fn owned_by_us(meta: &std::fs::Metadata) -> bool {
    use std::os::unix::fs::MetadataExt;
    #[cfg(any(test, feature = "failpoints"))]
    if let Some(uid) = crate::__failpoints::euid_override() {
        return meta.uid() == uid;
    }
    meta.uid() == rustix::process::geteuid().as_raw()
}

#[cfg(not(unix))]
fn owned_by_us(_meta: &std::fs::Metadata) -> bool {
    true
}

/// The pid in a compaction temp name `<prefix><pid>-<n>-<8 hex>.tmp`, if the
/// name is exactly that.
fn dead_temp_pid(name: &str, prefix: &str) -> Option<u32> {
    let rest = name.strip_prefix(prefix)?.strip_suffix(".tmp")?;
    let mut parts = rest.split('-');
    let (pid, n, nanos) = (parts.next()?, parts.next()?, parts.next()?);
    let digits = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit());
    let hex8 = nanos.len() == 8 && nanos.bytes().all(|b| b.is_ascii_hexdigit());
    if parts.next().is_some() || !digits(pid) || !digits(n) || !hex8 {
        return None;
    }
    pid.parse().ok()
}

/// The phrase REKEY-1's one exception carries; `mnemo rekey` and
/// [`crate::keys::rekey_stored`] look for it.
const EITHER_SECRET: &str = "may open with either secret";

/// A new, locked temp file next to `dest` (`Create::New`, so nothing already
/// at the name, a symlink included, is ever written through), under a fresh
/// name for each attempt while names are taken. RB-006.10.
pub(crate) fn create_temp(
    dest: &Path,
    what: &str,
    secret: &[u8],
    kind: SecretKind,
    config: MnemoConfig,
    salt: Option<[u8; crypto::SALT_LEN]>,
) -> Result<(PathBuf, Mnemo)> {
    let mut attempt = 0;
    loop {
        let tmp = temp_sibling(dest, what);
        match Mnemo::create_secret_new(&tmp, secret, kind, config, salt) {
            Ok(new) => return Ok((tmp, new)),
            Err(e) if is_name_taken(&e) && attempt + 1 < TEMP_NAME_ATTEMPTS => attempt += 1,
            Err(e) => return Err(e),
        }
    }
}