memstead-base 0.26.0

Engine internals for Memstead — store, parser, validators, mem lifecycle, workspace policy. Published as a dependency of the memstead-cli and memstead-mcp products, not as a supported library — pre-1.0, no API stability promise.
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
#![cfg(test)]

use super::*;
use crate::vcs::{Actor, ClientId, CommitContext};
use tempfile::TempDir;

fn ctx_for_test<'a>() -> CommitContext<'a> {
    CommitContext {
        actor: Actor::Cli,
        client: Some(ClientId {
            name: "claude-code".to_string(),
            version: "0.1.0".to_string(),
        }),
        tool: Some("test"),
        note: None,
        role: Default::default(),
        identity: None,
        logical_operation_id: None,
        entity_ids: None,
        proposal: None,
    }
}

/// `entity_exists` observes the same pending-buffer precedence as
/// `read_entity`: staged upsert → true before any commit, staged
/// delete → false while the file still sits on disk, and the
/// committed state answers between transactions — all without
/// reading bytes (the write-time cross-mem target check's primitive).
#[test]
fn entity_exists_metadata_probe_and_pending_precedence() {
    use crate::backend::MemBackend;
    let tmp = TempDir::new().unwrap();
    let writer = FilesystemBackend::new(tmp.path().to_path_buf());

    assert!(!MemBackend::entity_exists(&writer, Path::new("notes/a.md")).unwrap());

    MemBackend::write_entity(
        &writer,
        Path::new("notes/a.md"),
        b"# a
",
    )
    .unwrap();
    assert!(
        MemBackend::entity_exists(&writer, Path::new("notes/a.md")).unwrap(),
        "staged upsert answers true before commit"
    );

    MemBackend::commit(&writer, "land a", &ctx_for_test()).unwrap();
    assert!(MemBackend::entity_exists(&writer, Path::new("notes/a.md")).unwrap());

    MemBackend::delete_entity(&writer, Path::new("notes/a.md")).unwrap();
    assert!(
        !MemBackend::entity_exists(&writer, Path::new("notes/a.md")).unwrap(),
        "staged delete answers false while the file is still on disk"
    );
}

#[test]
fn write_then_commit_round_trip() {
    let tmp = TempDir::new().unwrap();
    let writer = FilesystemBackend::new(tmp.path().to_path_buf());

    writer
        .write_entity(Path::new("notes/hello.md"), b"# hi\n")
        .unwrap();
    let id = writer.commit("first commit", &ctx_for_test()).unwrap();
    assert!(!id.is_empty());

    let bytes = std::fs::read(tmp.path().join("notes/hello.md")).unwrap();
    assert_eq!(bytes, b"# hi\n");
}

#[test]
fn delete_removes_path() {
    let tmp = TempDir::new().unwrap();
    let writer = FilesystemBackend::new(tmp.path().to_path_buf());

    writer.write_entity(Path::new("a.md"), b"a").unwrap();
    writer.write_entity(Path::new("b.md"), b"b").unwrap();
    writer.commit("seed", &ctx_for_test()).unwrap();

    writer.delete_entity(Path::new("a.md")).unwrap();
    writer.commit("drop a", &ctx_for_test()).unwrap();

    assert!(!tmp.path().join("a.md").exists());
    assert!(tmp.path().join("b.md").exists());
}

#[test]
fn delete_of_missing_path_is_idempotent() {
    let tmp = TempDir::new().unwrap();
    let writer = FilesystemBackend::new(tmp.path().to_path_buf());

    writer.delete_entity(Path::new("never-existed.md")).unwrap();
    writer.commit("noop delete", &ctx_for_test()).unwrap();
}

#[test]
fn move_renames_path() {
    let tmp = TempDir::new().unwrap();
    let writer = FilesystemBackend::new(tmp.path().to_path_buf());

    writer
        .write_entity(Path::new("from.md"), b"payload")
        .unwrap();
    writer.commit("seed", &ctx_for_test()).unwrap();

    writer
        .move_entity(Path::new("from.md"), Path::new("nested/to.md"))
        .unwrap();
    writer.commit("rename", &ctx_for_test()).unwrap();

    assert!(!tmp.path().join("from.md").exists());
    let moved = std::fs::read(tmp.path().join("nested/to.md")).unwrap();
    assert_eq!(moved, b"payload");
}

#[test]
fn move_with_pending_upsert_carries_bytes() {
    let tmp = TempDir::new().unwrap();
    let writer = FilesystemBackend::new(tmp.path().to_path_buf());

    writer.write_entity(Path::new("a.md"), b"alpha").unwrap();
    writer
        .move_entity(Path::new("a.md"), Path::new("b.md"))
        .unwrap();
    writer.commit("write+move", &ctx_for_test()).unwrap();

    assert!(!tmp.path().join("a.md").exists());
    assert_eq!(std::fs::read(tmp.path().join("b.md")).unwrap(), b"alpha");
}

#[test]
fn move_missing_source_errors() {
    let tmp = TempDir::new().unwrap();
    let writer = FilesystemBackend::new(tmp.path().to_path_buf());

    let err = writer
        .move_entity(Path::new("ghost.md"), Path::new("here.md"))
        .unwrap_err();
    assert!(matches!(err, BackendError::Path(_)));
}

#[test]
fn move_with_pending_target_upsert_errors() {
    let tmp = TempDir::new().unwrap();
    let writer = FilesystemBackend::new(tmp.path().to_path_buf());

    writer.write_entity(Path::new("from.md"), b"x").unwrap();
    writer.write_entity(Path::new("to.md"), b"y").unwrap();
    let err = writer
        .move_entity(Path::new("from.md"), Path::new("to.md"))
        .unwrap_err();
    assert!(matches!(err, BackendError::Path(_)));
}

#[test]
fn move_onto_a_committed_target_refuses_and_keeps_both_files() {
    let tmp = TempDir::new().unwrap();
    let writer = FilesystemBackend::new(tmp.path().to_path_buf());

    writer
        .write_entity(Path::new("from.md"), b"source")
        .unwrap();
    writer.write_entity(Path::new("to.md"), b"target").unwrap();
    writer.commit("seed", &ctx_for_test()).unwrap();

    let err = writer
        .move_entity(Path::new("from.md"), Path::new("to.md"))
        .unwrap_err();
    assert!(matches!(err, BackendError::Path(_)));
    writer
        .commit("after refused move", &ctx_for_test())
        .unwrap();
    assert_eq!(
        std::fs::read(tmp.path().join("from.md")).unwrap(),
        b"source"
    );
    assert_eq!(std::fs::read(tmp.path().join("to.md")).unwrap(), b"target");
}

#[test]
fn a_refused_move_keeps_the_source_staged_bytes() {
    let tmp = TempDir::new().unwrap();
    let writer = FilesystemBackend::new(tmp.path().to_path_buf());

    writer.write_entity(Path::new("from.md"), b"new").unwrap();
    writer.write_entity(Path::new("to.md"), b"other").unwrap();
    writer
        .move_entity(Path::new("from.md"), Path::new("to.md"))
        .unwrap_err();
    assert_eq!(
        writer.read_entity(Path::new("from.md")).unwrap(),
        Some(b"new".to_vec())
    );
    writer
        .commit("after refused move", &ctx_for_test())
        .unwrap();
    assert_eq!(std::fs::read(tmp.path().join("from.md")).unwrap(), b"new");
}

#[test]
fn multi_op_commit() {
    let tmp = TempDir::new().unwrap();
    let writer = FilesystemBackend::new(tmp.path().to_path_buf());

    writer.write_entity(Path::new("doomed.md"), b"x").unwrap();
    writer.commit("seed", &ctx_for_test()).unwrap();

    writer.write_entity(Path::new("a.md"), b"alpha").unwrap();
    writer
        .write_entity(Path::new("nested/b.md"), b"beta")
        .unwrap();
    writer.delete_entity(Path::new("doomed.md")).unwrap();
    writer.commit("multi-op", &ctx_for_test()).unwrap();

    assert!(!tmp.path().join("doomed.md").exists());
    assert_eq!(std::fs::read(tmp.path().join("a.md")).unwrap(), b"alpha");
    assert_eq!(
        std::fs::read(tmp.path().join("nested/b.md")).unwrap(),
        b"beta"
    );
}

#[test]
fn rejects_path_traversal() {
    let tmp = TempDir::new().unwrap();
    let writer = FilesystemBackend::new(tmp.path().to_path_buf());

    let err = writer
        .write_entity(Path::new("../escape.md"), b"x")
        .unwrap_err();
    assert!(matches!(err, BackendError::Path(_)));
}

#[test]
fn rejects_absolute_path() {
    let tmp = TempDir::new().unwrap();
    let writer = FilesystemBackend::new(tmp.path().to_path_buf());

    let err = writer
        .write_entity(Path::new("/etc/passwd"), b"x")
        .unwrap_err();
    assert!(matches!(err, BackendError::Path(_)));
}

#[test]
fn rejects_empty_path() {
    let tmp = TempDir::new().unwrap();
    let writer = FilesystemBackend::new(tmp.path().to_path_buf());

    let err = writer.write_entity(Path::new(""), b"x").unwrap_err();
    assert!(matches!(err, BackendError::Path(_)));
}

#[test]
fn write_overwrites_existing_file() {
    let tmp = TempDir::new().unwrap();
    let writer = FilesystemBackend::new(tmp.path().to_path_buf());

    writer.write_entity(Path::new("a.md"), b"first").unwrap();
    writer.commit("c1", &ctx_for_test()).unwrap();
    writer.write_entity(Path::new("a.md"), b"second").unwrap();
    writer.commit("c2", &ctx_for_test()).unwrap();

    assert_eq!(std::fs::read(tmp.path().join("a.md")).unwrap(), b"second");
}

#[test]
fn no_temp_files_left_after_commit() {
    let tmp = TempDir::new().unwrap();
    let writer = FilesystemBackend::new(tmp.path().to_path_buf());

    writer.write_entity(Path::new("a.md"), b"a").unwrap();
    writer.write_entity(Path::new("nested/b.md"), b"b").unwrap();
    writer.commit("c", &ctx_for_test()).unwrap();

    // Walk the tree and ensure no `.tmp.` artefacts survived.
    fn walk(dir: &Path, out: &mut Vec<PathBuf>) {
        for entry in std::fs::read_dir(dir).unwrap() {
            let p = entry.unwrap().path();
            if p.is_dir() {
                walk(&p, out);
            } else {
                out.push(p);
            }
        }
    }
    let mut files = Vec::new();
    walk(tmp.path(), &mut files);
    for f in &files {
        let name = f.file_name().unwrap().to_string_lossy();
        assert!(
            !name.contains(".tmp."),
            "stray temp file after commit: {}",
            f.display()
        );
    }
}

#[test]
fn commit_id_is_unique_across_calls() {
    let tmp = TempDir::new().unwrap();
    let writer = FilesystemBackend::new(tmp.path().to_path_buf());

    writer.write_entity(Path::new("a.md"), b"a").unwrap();
    let id1 = writer.commit("c1", &ctx_for_test()).unwrap();
    writer.write_entity(Path::new("b.md"), b"b").unwrap();
    let id2 = writer.commit("c2", &ctx_for_test()).unwrap();

    assert_ne!(id1, id2);
}

#[test]
fn pending_buffer_clears_on_commit() {
    let tmp = TempDir::new().unwrap();
    let writer = FilesystemBackend::new(tmp.path().to_path_buf());

    writer.write_entity(Path::new("a.md"), b"a").unwrap();
    writer.commit("c1", &ctx_for_test()).unwrap();
    // A second commit with no mutations writes nothing new but
    // still returns a fresh id.
    let id2 = writer.commit("noop", &ctx_for_test()).unwrap();
    assert!(!id2.is_empty());
    // a.md still has its original content (no zombie pending op).
    assert_eq!(std::fs::read(tmp.path().join("a.md")).unwrap(), b"a");
}

/// A commit that fails partway ends its transaction: nothing staged
/// stays readable, nothing staged is on disk, and the next commit
/// carries only what was staged after the failure. The failure is a
/// real one: a file sits where the second write needs a directory.
#[test]
fn a_failed_commit_leaves_no_staged_write_readable() {
    let tmp = TempDir::new().unwrap();
    let writer = FilesystemBackend::new(tmp.path().to_path_buf());
    std::fs::write(tmp.path().join("blocker"), b"a file, not a directory").unwrap();

    writer.write_entity(Path::new("a.md"), b"staged").unwrap();
    writer
        .write_entity(Path::new("blocker/child.md"), b"staged")
        .unwrap();
    assert!(writer.commit("fails", &ctx_for_test()).is_err());

    assert_eq!(
        writer.read_entity(Path::new("a.md")).unwrap(),
        None,
        "a write that never landed is not served"
    );
    assert!(!tmp.path().join("a.md").exists());

    writer.write_entity(Path::new("b.md"), b"b").unwrap();
    writer.commit("next", &ctx_for_test()).unwrap();
    assert_eq!(std::fs::read(tmp.path().join("b.md")).unwrap(), b"b");
    assert!(
        !tmp.path().join("a.md").exists(),
        "the failed commit's write does not ride the next commit"
    );
    let names: Vec<String> = std::fs::read_dir(tmp.path())
        .unwrap()
        .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
        .collect();
    assert!(
        names.iter().all(|n| !n.contains(".tmp.")),
        "no temp of the failed commit remains: {names:?}"
    );
}

// --- MemBackend impl ----------------------------------------

/// Folder backend's `write_mem_config` writes
/// `<root>/.memstead/config.json`, creating the umbrella directory
/// if needed. The subsequent `read_mem_config` round-trips the
/// bytes.
#[test]
fn backend_write_mem_config_round_trips_via_read() {
    use crate::backend::MemBackend;

    let tmp = TempDir::new().unwrap();
    let writer = FilesystemBackend::new(tmp.path().to_path_buf());
    let backend: &dyn MemBackend = &writer;

    // No config yet — read returns None.
    assert!(backend.read_mem_config().unwrap().is_none());

    // Write — creates `.memstead/` umbrella + the config blob.
    let bytes = br#"{"version":"0.1.0","schema":"default@1.0.0"}"#.to_vec();
    backend
        .write_mem_config(
            &bytes,
            &crate::vcs::CommitContext::new(
                Some("test"),
                crate::vcs::Actor::Cli,
                None,
                None,
                crate::vcs::Role::Unspecified,
                None,
            ),
        )
        .unwrap();

    // Read returns the same bytes.
    let read_back = backend.read_mem_config().unwrap();
    assert_eq!(read_back, Some(bytes.clone()));
    // Config file lands at `<root>/.memstead/config.json`.
    let on_disk = std::fs::read(tmp.path().join(".memstead/config.json")).unwrap();
    assert_eq!(on_disk, bytes);
}

#[test]
fn backend_list_entities_returns_only_md_outside_meta_dirs() {
    use crate::backend::MemBackend;

    let tmp = TempDir::new().unwrap();
    let writer = FilesystemBackend::new(tmp.path().to_path_buf());

    // With both traits in scope, dot-syntax `writer.foo(...)`
    // is ambiguous — seed via fully-qualified MemBackend calls.
    <FilesystemBackend as MemBackend>::write_entity(&writer, Path::new("a.md"), b"a").unwrap();
    <FilesystemBackend as MemBackend>::write_entity(&writer, Path::new("nested/b.md"), b"b")
        .unwrap();
    <FilesystemBackend as MemBackend>::write_entity(&writer, Path::new("notes.json"), b"{}")
        .unwrap();
    <FilesystemBackend as MemBackend>::commit(&writer, "seed", &ctx_for_test()).unwrap();
    // The current `.memstead/` meta dir is skipped by the walker.
    // An ordinary dot-dir (`.other/`) is not special, so markdown
    // under it is walked like any other non-meta path.
    std::fs::create_dir_all(tmp.path().join(".memstead")).unwrap();
    std::fs::write(tmp.path().join(".memstead/config.json"), b"{}").unwrap();
    std::fs::write(tmp.path().join(".memstead/notes.md"), b"#").unwrap();
    std::fs::create_dir_all(tmp.path().join(".other")).unwrap();
    std::fs::write(tmp.path().join(".other/notes.md"), b"#").unwrap();

    let backend: &dyn MemBackend = &writer;
    let mut paths: Vec<String> = backend
        .list_entities()
        .unwrap()
        .into_iter()
        .map(|p| p.to_string_lossy().into_owned())
        .collect();
    paths.sort();
    assert_eq!(
        paths,
        vec![
            ".other/notes.md".to_string(),
            "a.md".to_string(),
            "nested/b.md".to_string(),
        ]
    );
}

#[test]
fn backend_read_entity_consults_pending_then_disk() {
    let tmp = TempDir::new().unwrap();
    let writer = FilesystemBackend::new(tmp.path().to_path_buf());

    // Seed via fully-qualified MemBackend calls — the trait exposes
    // `write_entity`; importing `MemBackend` later in the test
    // makes the dot-syntax ambiguous, so we route the seed
    // through the trait that's still implicitly in scope here.
    <FilesystemBackend as MemBackend>::write_entity(&writer, Path::new("on_disk.md"), b"disk")
        .unwrap();
    <FilesystemBackend as MemBackend>::commit(&writer, "seed", &ctx_for_test()).unwrap();

    use crate::backend::MemBackend;
    let backend: &dyn MemBackend = &writer;
    // Disk path → reads from disk.
    assert_eq!(
        backend.read_entity(Path::new("on_disk.md")).unwrap(),
        Some(b"disk".to_vec())
    );
    // Buffered upsert wins over disk.
    backend
        .write_entity(Path::new("on_disk.md"), b"buffered")
        .unwrap();
    assert_eq!(
        backend.read_entity(Path::new("on_disk.md")).unwrap(),
        Some(b"buffered".to_vec())
    );
    // Buffered delete masks disk.
    backend.delete_entity(Path::new("on_disk.md")).unwrap();
    assert_eq!(backend.read_entity(Path::new("on_disk.md")).unwrap(), None);
    // Unknown path → None (idempotent).
    assert_eq!(backend.read_entity(Path::new("never.md")).unwrap(), None);
}

#[test]
fn backend_provenance_round_trips_through_jsonl() {
    let tmp = TempDir::new().unwrap();
    let writer = FilesystemBackend::new(tmp.path().to_path_buf());
    use crate::backend::MemBackend;
    let backend: &dyn MemBackend = &writer;

    let client = ClientId {
        name: "claude-code".into(),
        version: "2.1.0".into(),
    };
    let earlier = std::time::UNIX_EPOCH + std::time::Duration::from_secs(1_700_000_000);
    let later = std::time::UNIX_EPOCH + std::time::Duration::from_secs(1_777_077_296);

    backend
        .append_provenance(&Provenance::new(
            earlier,
            ProvenanceKind::Create,
            Some("v:e1".into()),
            Actor::Agent,
            Some(client.clone()),
            Some("first".into()),
        ))
        .unwrap();
    backend
        .append_provenance(&Provenance::new(
            later,
            ProvenanceKind::Update,
            Some("v:e1".into()),
            Actor::Cli,
            None,
            None,
        ))
        .unwrap();

    let all = backend.read_provenance(None).unwrap();
    assert_eq!(all.len(), 2);
    assert_eq!(all[0].kind, ProvenanceKind::Create);
    assert_eq!(all[0].entity.as_deref(), Some("v:e1"));
    assert_eq!(all[0].actor, Actor::Agent);
    assert_eq!(all[0].note.as_deref(), Some("first"));
    assert_eq!(
        all[0]
            .client
            .as_ref()
            .map(|c| (c.name.as_str(), c.version.as_str())),
        Some(("claude-code", "2.1.0"))
    );
    assert_eq!(all[0].timestamp, earlier);
    assert_eq!(all[1].kind, ProvenanceKind::Update);
    assert_eq!(all[1].timestamp, later);
    assert!(all[1].note.is_none());
    assert!(all[1].client.is_none());
}

#[test]
fn backend_provenance_cursor_filters_by_timestamp() {
    let tmp = TempDir::new().unwrap();
    let writer = FilesystemBackend::new(tmp.path().to_path_buf());
    use crate::backend::MemBackend;
    let backend: &dyn MemBackend = &writer;

    for (secs, label) in [
        (1_700_000_000u64, "first"),
        (1_750_000_000, "middle"),
        (1_800_000_000, "last"),
    ] {
        backend
            .append_provenance(&Provenance::new(
                std::time::UNIX_EPOCH + std::time::Duration::from_secs(secs),
                ProvenanceKind::Create,
                Some(format!("v:{label}")),
                Actor::Cli,
                None,
                None,
            ))
            .unwrap();
    }
    // Cursor between first and middle should drop the first entry.
    let cursor = changelog::format_rfc3339_utc(
        std::time::UNIX_EPOCH + std::time::Duration::from_secs(1_725_000_000),
    );
    let after = backend.read_provenance(Some(&cursor)).unwrap();
    let entities: Vec<_> = after.iter().filter_map(|p| p.entity.clone()).collect();
    assert_eq!(entities, vec!["v:middle".to_string(), "v:last".to_string()]);
}

#[test]
fn backend_read_provenance_handles_missing_log() {
    let tmp = TempDir::new().unwrap();
    let writer = FilesystemBackend::new(tmp.path().to_path_buf());
    use crate::backend::MemBackend;
    let backend: &dyn MemBackend = &writer;
    // No mutations yet → no `.memstead/changes.jsonl` → empty result, no error.
    assert!(backend.read_provenance(None).unwrap().is_empty());
}

// ---- folder JSONL synthesis (memstead_base::ops::folder_changes_since) ----

/// Helper: append a single Provenance event with an explicit
/// timestamp, so tests get deterministic JSONL ordering.
fn append_at(
    backend: &dyn crate::backend::MemBackend,
    secs: u64,
    kind: ProvenanceKind,
    entity: &str,
) {
    backend
        .append_provenance(&Provenance::new(
            std::time::UNIX_EPOCH + std::time::Duration::from_secs(secs),
            kind,
            Some(entity.to_string()),
            Actor::Cli,
            None,
            None,
        ))
        .unwrap();
}

#[test]
fn folder_changes_since_no_log_returns_empty_at_cursor() {
    // Fresh mem, no `.memstead/changes.jsonl` → empty BackendChanges
    // with `head` echoing the cursor.
    let tmp = TempDir::new().unwrap();
    let result =
        crate::ops::folder_changes_since(tmp.path(), "specs", crate::ops::EMPTY_TREE_SHA, None)
            .unwrap();
    assert_eq!(result.since, crate::ops::EMPTY_TREE_SHA);
    assert_eq!(result.head, crate::ops::EMPTY_TREE_SHA);
    assert!(result.changes.is_empty());
}

/// A rename row names only the id the entity now carries; with the
/// store's view the replay pairs it with the id that vanished. Added
/// and renamed inside one window: one `added` under the final id.
/// Rename alone in the window: one `renamed` with both ids. An
/// entity created in the window that still exists keeps its `added`.
#[test]
fn folder_changes_since_pairs_a_rename_row_with_the_vanished_id() {
    let tmp = TempDir::new().unwrap();
    let writer = FilesystemBackend::new(tmp.path().to_path_buf());
    append_at(
        &writer,
        1_700_000_000,
        ProvenanceKind::Create,
        "specs--alpha",
    );
    append_at(
        &writer,
        1_700_000_100,
        ProvenanceKind::Create,
        "specs--keeper",
    );
    append_at(
        &writer,
        1_700_000_200,
        ProvenanceKind::Rename,
        "specs--alpha-two",
    );
    // The store after the rename: alpha is gone, alpha-two carries
    // alpha's creation instant, keeper is untouched.
    let store = |id: &crate::EntityId| -> Option<String> {
        match id.0.as_str() {
            "specs--alpha-two" => Some("2023-11-14T22:13:20Z".to_string()),
            "specs--keeper" => Some("2023-11-14T22:15:00Z".to_string()),
            _ => None,
        }
    };

    let whole = crate::ops::folder_changes_since(
        tmp.path(),
        "specs",
        crate::ops::EMPTY_TREE_SHA,
        Some(&store),
    )
    .unwrap();
    let kinds: Vec<(&str, &str)> = whole
        .changes
        .iter()
        .map(|c| (c.action(), c.primary_id()))
        .collect();
    assert_eq!(
        kinds,
        vec![("added", "specs--alpha-two"), ("added", "specs--keeper")],
        "add-then-rename folds to one added under the final id: {:?}",
        whole.changes
    );

    // Window opens after the add and before the rename.
    let mid = crate::filesystem::changelog::format_rfc3339_utc(
        std::time::UNIX_EPOCH + std::time::Duration::from_secs(1_700_000_150),
    );
    let later = crate::ops::folder_changes_since(tmp.path(), "specs", &mid, Some(&store)).unwrap();
    match later.changes.as_slice() {
        [crate::ops::ChangeEnvelope::Renamed { from_id, to_id, .. }] => {
            assert_eq!(from_id.0, "specs--alpha");
            assert_eq!(to_id.0, "specs--alpha-two");
        }
        other => panic!("expected the renamed event alone, got {other:?}"),
    }

    // Without the store's view the rename row reads as updated.
    let bare = crate::ops::folder_changes_since(tmp.path(), "specs", &mid, None).unwrap();
    assert_eq!(bare.changes.len(), 1);
    assert_eq!(bare.changes[0].action(), "updated");

    // A chain: alpha-two -> alpha-three -> alpha-four. Only the
    // final name exists now. The whole window folds to one added
    // under it; a reader holding alpha-two gets one renamed from
    // alpha-two to alpha-four; a reader holding alpha-three gets
    // one renamed from alpha-three; the intermediates surface
    // nowhere.
    append_at(
        &writer,
        1_700_000_300,
        ProvenanceKind::Rename,
        "specs--alpha-three",
    );
    append_at(
        &writer,
        1_700_000_400,
        ProvenanceKind::Rename,
        "specs--alpha-four",
    );
    let store = |id: &crate::EntityId| -> Option<String> {
        match id.0.as_str() {
            "specs--alpha-four" => Some("2023-11-14T22:13:20Z".to_string()),
            "specs--keeper" => Some("2023-11-14T22:15:00Z".to_string()),
            _ => None,
        }
    };
    let at = |secs: u64| {
        crate::filesystem::changelog::format_rfc3339_utc(
            std::time::UNIX_EPOCH + std::time::Duration::from_secs(secs),
        )
    };
    let whole = crate::ops::folder_changes_since(
        tmp.path(),
        "specs",
        crate::ops::EMPTY_TREE_SHA,
        Some(&store),
    )
    .unwrap();
    let kinds: Vec<(&str, &str)> = whole
        .changes
        .iter()
        .map(|c| (c.action(), c.primary_id()))
        .collect();
    assert_eq!(
        kinds,
        vec![("added", "specs--alpha-four"), ("added", "specs--keeper")],
        "{:?}",
        whole.changes
    );
    for (cursor, from) in [
        (1_700_000_250, "specs--alpha-two"),
        (1_700_000_350, "specs--alpha-three"),
    ] {
        let part = crate::ops::folder_changes_since(tmp.path(), "specs", &at(cursor), Some(&store))
            .unwrap();
        match part.changes.as_slice() {
            [crate::ops::ChangeEnvelope::Renamed { from_id, to_id, .. }] => {
                assert_eq!(from_id.0, from);
                assert_eq!(to_id.0, "specs--alpha-four");
            }
            other => panic!("expected one renamed from {from}, got {other:?}"),
        }
    }
}

#[test]
fn folder_changes_since_create_only_yields_added_envelope() {
    let tmp = TempDir::new().unwrap();
    let writer = FilesystemBackend::new(tmp.path().to_path_buf());
    append_at(
        &writer,
        1_700_000_000,
        ProvenanceKind::Create,
        "specs--alpha",
    );

    let result =
        crate::ops::folder_changes_since(tmp.path(), "specs", crate::ops::EMPTY_TREE_SHA, None)
            .unwrap();
    assert_eq!(result.changes.len(), 1);
    match &result.changes[0] {
        crate::ops::ChangeEnvelope::Added {
            id,
            title,
            entity_type,
        } => {
            assert_eq!(id.0, "specs--alpha");
            assert!(title.is_none(), "id-only contract");
            assert!(entity_type.is_none(), "id-only contract");
        }
        other => panic!("expected Added, got {other:?}"),
    }
    // head advances to the event's timestamp.
    assert_ne!(result.head, crate::ops::EMPTY_TREE_SHA);
}

#[test]
fn folder_changes_since_create_then_delete_cancels_to_no_envelope() {
    // Within the cursor window, an entity that was created and then
    // deleted nets out to Removed (final state wins for Delete).
    let tmp = TempDir::new().unwrap();
    let writer = FilesystemBackend::new(tmp.path().to_path_buf());
    append_at(
        &writer,
        1_700_000_000,
        ProvenanceKind::Create,
        "specs--ephemeral",
    );
    append_at(
        &writer,
        1_700_000_001,
        ProvenanceKind::Delete,
        "specs--ephemeral",
    );

    let result =
        crate::ops::folder_changes_since(tmp.path(), "specs", crate::ops::EMPTY_TREE_SHA, None)
            .unwrap();
    assert_eq!(result.changes.len(), 1);
    match &result.changes[0] {
        crate::ops::ChangeEnvelope::Removed { id, .. } => {
            assert_eq!(id.0, "specs--ephemeral");
        }
        other => panic!("expected Removed (Delete wins), got {other:?}"),
    }
}

#[test]
fn folder_changes_since_update_only_yields_updated_envelope() {
    let tmp = TempDir::new().unwrap();
    let writer = FilesystemBackend::new(tmp.path().to_path_buf());
    append_at(
        &writer,
        1_700_000_000,
        ProvenanceKind::Update,
        "specs--alpha",
    );

    let result =
        crate::ops::folder_changes_since(tmp.path(), "specs", crate::ops::EMPTY_TREE_SHA, None)
            .unwrap();
    assert_eq!(result.changes.len(), 1);
    assert!(matches!(
        result.changes[0],
        crate::ops::ChangeEnvelope::Updated { .. }
    ));
}

/// The exact confusion the guard exists for: a mutation's
/// `write_id` (fixed-width hex, sorts below every timestamp)
/// passed back as `since` must refuse, never silently replay the
/// whole history. Garbage refuses on the same rule; the empty
/// string and the empty-tree sentinel stay "from the beginning".
#[test]
fn folder_changes_since_refuses_non_timestamp_cursor() {
    let tmp = TempDir::new().unwrap();
    let writer = FilesystemBackend::new(tmp.path().to_path_buf());
    append_at(
        &writer,
        1_700_000_000,
        ProvenanceKind::Create,
        "specs--alpha",
    );

    let write_token = make_commit_id();
    for bad in [write_token.as_str(), "not-a-timestamp"] {
        let err = crate::ops::folder_changes_since(tmp.path(), "specs", bad, None).unwrap_err();
        match err {
            BackendError::Other(msg) => {
                assert_eq!(msg, format!("INVALID_TS_CURSOR:{bad}"));
            }
            other => panic!("expected typed marker, got {other:?}"),
        }
    }
    for from_start in ["", crate::ops::EMPTY_TREE_SHA] {
        let ok = crate::ops::folder_changes_since(tmp.path(), "specs", from_start, None).unwrap();
        assert_eq!(ok.changes.len(), 1, "sentinel '{from_start}' reads all");
    }
}

#[test]
fn folder_changes_since_cursor_filters_to_window() {
    // Three events at three timestamps; cursor between first and
    // second drops the first event from the window.
    let tmp = TempDir::new().unwrap();
    let writer = FilesystemBackend::new(tmp.path().to_path_buf());
    append_at(
        &writer,
        1_700_000_000,
        ProvenanceKind::Create,
        "specs--first",
    );
    append_at(
        &writer,
        1_750_000_000,
        ProvenanceKind::Create,
        "specs--middle",
    );
    append_at(
        &writer,
        1_800_000_000,
        ProvenanceKind::Create,
        "specs--last",
    );

    let cursor = changelog::format_rfc3339_utc(
        std::time::UNIX_EPOCH + std::time::Duration::from_secs(1_725_000_000),
    );
    let result = crate::ops::folder_changes_since(tmp.path(), "specs", &cursor, None).unwrap();
    assert_eq!(result.changes.len(), 2);
    let ids: Vec<_> = result
        .changes
        .iter()
        .map(|e| match e {
            crate::ops::ChangeEnvelope::Added { id, .. } => id.0.clone(),
            _ => panic!("expected Added"),
        })
        .collect();
    // BTreeMap iteration order — ids sort lexicographically.
    assert_eq!(
        ids,
        vec!["specs--last".to_string(), "specs--middle".to_string()]
    );
}

#[test]
fn folder_changes_since_skips_events_for_other_mems() {
    // Defensive: changelog drift could carry events for another
    // mem prefix; the impl filters them out so envelopes only
    // surface for the queried mem.
    let tmp = TempDir::new().unwrap();
    let writer = FilesystemBackend::new(tmp.path().to_path_buf());
    append_at(
        &writer,
        1_700_000_000,
        ProvenanceKind::Create,
        "specs--mine",
    );
    append_at(
        &writer,
        1_700_000_001,
        ProvenanceKind::Create,
        "other--theirs",
    );

    let result =
        crate::ops::folder_changes_since(tmp.path(), "specs", crate::ops::EMPTY_TREE_SHA, None)
            .unwrap();
    assert_eq!(result.changes.len(), 1);
    match &result.changes[0] {
        crate::ops::ChangeEnvelope::Added { id, .. } => {
            assert_eq!(id.0, "specs--mine");
        }
        other => panic!("expected Added, got {other:?}"),
    }
}

#[test]
fn folder_changes_since_skips_batch_events_with_no_entity() {
    // Batch events have entity=null. They don't surface as
    // envelopes (no per-entity id to attach to).
    let tmp = TempDir::new().unwrap();
    let writer = FilesystemBackend::new(tmp.path().to_path_buf());
    use crate::backend::MemBackend;
    // append_at requires an entity; use append_provenance directly
    // for the batch-with-no-entity case.
    writer
        .append_provenance(&Provenance::new(
            std::time::UNIX_EPOCH + std::time::Duration::from_secs(1_700_000_000),
            ProvenanceKind::Batch,
            None,
            Actor::Cli,
            None,
            None,
        ))
        .unwrap();
    append_at(
        &writer,
        1_700_000_001,
        ProvenanceKind::Create,
        "specs--real",
    );

    let result =
        crate::ops::folder_changes_since(tmp.path(), "specs", crate::ops::EMPTY_TREE_SHA, None)
            .unwrap();
    // Only the Create-Real event surfaces; the batch is dropped.
    assert_eq!(result.changes.len(), 1);
    match &result.changes[0] {
        crate::ops::ChangeEnvelope::Added { id, .. } => {
            assert_eq!(id.0, "specs--real");
        }
        other => panic!("expected Added, got {other:?}"),
    }
}

#[test]
fn folder_changes_since_head_echoes_cursor_when_no_events_in_window() {
    // Events exist but all before the cursor → head echoes cursor.
    let tmp = TempDir::new().unwrap();
    let writer = FilesystemBackend::new(tmp.path().to_path_buf());
    append_at(&writer, 1_700_000_000, ProvenanceKind::Create, "specs--old");

    let cursor = changelog::format_rfc3339_utc(
        std::time::UNIX_EPOCH + std::time::Duration::from_secs(1_900_000_000),
    );
    let result = crate::ops::folder_changes_since(tmp.path(), "specs", &cursor, None).unwrap();
    assert!(result.changes.is_empty());
    assert_eq!(result.head, cursor);
}

#[test]
fn backend_writes_delegate_to_memwriter() {
    let tmp = TempDir::new().unwrap();
    let writer = FilesystemBackend::new(tmp.path().to_path_buf());
    use crate::backend::MemBackend;
    let backend: &dyn MemBackend = &writer;

    backend.write_entity(Path::new("a.md"), b"alpha").unwrap();
    backend.commit("seed", &ctx_for_test()).unwrap();
    assert_eq!(std::fs::read(tmp.path().join("a.md")).unwrap(), b"alpha");

    backend.delete_entity(Path::new("a.md")).unwrap();
    backend.commit("drop", &ctx_for_test()).unwrap();
    assert!(!tmp.path().join("a.md").exists());
}

#[test]
fn parse_client_id_splits_on_last_at() {
    let c = parse_client_id("claude-code@2.1.0").unwrap();
    assert_eq!(c.name, "claude-code");
    assert_eq!(c.version, "2.1.0");
    // Edge: name with `.`
    let c = parse_client_id("foo.bar@1.0").unwrap();
    assert_eq!(c.name, "foo.bar");
    // Bare strings without `@` → None (forward-compat: tolerant
    // readers ignore rather than mis-construct).
    assert!(parse_client_id("naked").is_none());
    assert!(parse_client_id("@1.0").is_none());
    assert!(parse_client_id("name@").is_none());
}

/// A config write replaces the file rather than rewriting it in place: a
/// second name for the old file keeps the old bytes, which only holds when
/// the new bytes went to a new file that was renamed over the old name. An
/// in-place write would truncate the one inode both names share, and a
/// crash in that window leaves the config empty.
#[test]
fn config_writes_replace_the_file_instead_of_truncating_it() {
    let tmp = TempDir::new().unwrap();
    let backend = FilesystemBackend::new(tmp.path().to_path_buf());
    let config = tmp
        .path()
        .join(crate::mem::MEM_META_DIR)
        .join("config.json");
    let witness = tmp.path().join("witness.json");

    backend
        .write_mem_config(b"{\"v\":1}", &ctx_for_test())
        .unwrap();
    std::fs::hard_link(&config, &witness).unwrap();
    backend
        .write_mem_config(b"{\"v\":2}", &ctx_for_test())
        .unwrap();
    assert_eq!(std::fs::read(&config).unwrap(), b"{\"v\":2}");
    assert_eq!(std::fs::read(&witness).unwrap(), b"{\"v\":1}");

    std::fs::remove_file(&witness).unwrap();
    std::fs::hard_link(&config, &witness).unwrap();
    assert!(
        backend
            .write_mem_config_cas(Some(b"{\"v\":2}"), b"{\"v\":3}", &ctx_for_test())
            .unwrap()
    );
    assert_eq!(std::fs::read(&config).unwrap(), b"{\"v\":3}");
    assert_eq!(std::fs::read(&witness).unwrap(), b"{\"v\":2}");

    let leftovers: Vec<_> = std::fs::read_dir(config.parent().unwrap())
        .unwrap()
        .map(|e| e.unwrap().file_name().into_string().unwrap())
        .filter(|n| n != "config.json" && n != "locks")
        .collect();
    assert!(leftovers.is_empty(), "{leftovers:?}");
}

/// A config write, plain or compare-and-set, waits for the writer holding
/// the config lock however long that writer takes, and the compare then
/// sees what the holder wrote. A writer that dies holds nothing: the
/// operating system releases its lock.
#[test]
fn config_writes_wait_for_the_holder_of_the_config_lock() {
    use std::io::Write as _;
    let tmp = TempDir::new().unwrap();
    let backend = FilesystemBackend::new(tmp.path().to_path_buf());
    backend
        .write_mem_config(b"{\"v\":1}", &ctx_for_test())
        .unwrap();
    let root = std::fs::canonicalize(tmp.path()).unwrap();
    let lock = root.join(".memstead/locks/config.lock");
    let config = root.join(".memstead/config.json");

    // A holder that stalls well past any wait a writer might give up after.
    let (held_tx, held_rx) = std::sync::mpsc::channel();
    let holder = std::thread::spawn({
        let lock = lock.clone();
        let config = config.clone();
        move || {
            std::fs::create_dir_all(lock.parent().unwrap()).unwrap();
            let f = std::fs::OpenOptions::new()
                .read(true)
                .write(true)
                .create(true)
                .truncate(false)
                .open(&lock)
                .unwrap();
            f.lock().unwrap();
            held_tx.send(()).unwrap();
            std::thread::sleep(std::time::Duration::from_secs(4));
            let mut c = std::fs::File::create(&config).unwrap();
            c.write_all(b"{\"v\":\"holder\"}").unwrap();
            drop(c);
            f.unlock().unwrap();
        }
    });
    held_rx.recv().unwrap();

    let started = std::time::Instant::now();
    let landed = backend
        .write_mem_config_cas(Some(b"{\"v\":1}"), b"{\"v\":2}", &ctx_for_test())
        .unwrap();
    let waited = started.elapsed();
    holder.join().unwrap();
    assert!(
        waited >= std::time::Duration::from_secs(3),
        "the CAS did not wait"
    );
    assert!(!landed, "the compare must see the holder's write");
    assert_eq!(std::fs::read(&config).unwrap(), b"{\"v\":\"holder\"}");

    // The plain write takes the same lock.
    let f = std::fs::OpenOptions::new()
        .read(true)
        .write(true)
        .open(&lock)
        .unwrap();
    f.lock().unwrap();
    let writer = std::thread::spawn({
        let root = root.clone();
        move || {
            FilesystemBackend::new(root)
                .write_mem_config(b"{\"v\":3}", &ctx_for_test())
                .unwrap();
        }
    });
    std::thread::sleep(std::time::Duration::from_millis(300));
    assert_eq!(
        std::fs::read(&config).unwrap(),
        b"{\"v\":\"holder\"}",
        "the plain write did not wait"
    );
    f.unlock().unwrap();
    writer.join().unwrap();
    assert_eq!(std::fs::read(&config).unwrap(), b"{\"v\":3}");
}

/// A path through a symbolic link inside the mem is refused at staging, so
/// no write lands in the directory the link points at.
#[cfg(unix)]
#[test]
fn a_write_through_a_symlinked_directory_is_refused() {
    let tmp = TempDir::new().unwrap();
    let root = tmp.path().join("mem");
    let outside = tmp.path().join("outside");
    std::fs::create_dir_all(&root).unwrap();
    std::fs::create_dir_all(&outside).unwrap();
    std::os::unix::fs::symlink(&outside, root.join("link")).unwrap();
    let writer = FilesystemBackend::new(root.clone());

    assert!(matches!(
        writer.write_entity(Path::new("link/secret.md"), b"x"),
        Err(BackendError::Path(_))
    ));
    assert!(writer.delete_entity(Path::new("link/secret.md")).is_err());
    writer
        .commit("after refused write", &ctx_for_test())
        .unwrap();
    assert!(std::fs::read_dir(&outside).unwrap().next().is_none());
}

/// A link that appears between staging and commit refuses the commit, and
/// nothing reaches the link's target.
#[cfg(unix)]
#[test]
fn a_symlink_created_after_staging_refuses_the_commit() {
    let tmp = TempDir::new().unwrap();
    let root = tmp.path().join("mem");
    let outside = tmp.path().join("outside");
    std::fs::create_dir_all(&root).unwrap();
    std::fs::create_dir_all(&outside).unwrap();
    let writer = FilesystemBackend::new(root.clone());

    writer.write_entity(Path::new("sub/x.md"), b"x").unwrap();
    std::os::unix::fs::symlink(&outside, root.join("sub")).unwrap();
    assert!(writer.commit("through a link", &ctx_for_test()).is_err());
    assert!(std::fs::read_dir(&outside).unwrap().next().is_none());
}

/// Under `.memstead/` an entity-path write reaches only the declared
/// sidecars: the commit record, the ledger, the config and the locks are
/// the backend's own, and a staged write over one of them would destroy it.
#[test]
fn an_entity_path_write_cannot_reach_the_backends_own_files() {
    let tmp = TempDir::new().unwrap();
    let writer = FilesystemBackend::new(tmp.path().to_path_buf());
    for reserved in [
        ".memstead/commit.json",
        ".memstead/changes.jsonl",
        ".memstead/config.json",
        ".memstead/locks/write.lock",
        ".memstead/anything-else.json",
    ] {
        assert!(
            matches!(
                writer.write_entity(Path::new(reserved), b"x"),
                Err(BackendError::Path(_))
            ),
            "{reserved}"
        );
        assert!(
            writer.delete_entity(Path::new(reserved)).is_err(),
            "{reserved}"
        );
    }
    for sidecar in [
        crate::anchor::ANCHOR_SIDECAR_PATH,
        crate::derivation::DERIVATION_SIDECAR_PATH,
        crate::ops::proposal::PROPOSAL_RECORD_PATH,
    ] {
        writer.write_entity(Path::new(sidecar), b"{}").unwrap();
    }
    writer.commit("sidecars", &ctx_for_test()).unwrap();
}

/// A `.memstead` that is a symbolic link is refused for the config, the
/// commit record and the ledger, so none of them lands outside the mem.
#[cfg(unix)]
#[test]
fn a_symlinked_meta_directory_is_refused() {
    let tmp = TempDir::new().unwrap();
    let root = tmp.path().join("mem");
    let outside = tmp.path().join("outside");
    std::fs::create_dir_all(&root).unwrap();
    std::fs::create_dir_all(&outside).unwrap();
    std::os::unix::fs::symlink(&outside, root.join(".memstead")).unwrap();
    let writer = FilesystemBackend::new(root.clone());

    assert!(writer.write_mem_config(b"{}", &ctx_for_test()).is_err());
    assert!(
        writer
            .write_mem_config_cas(None, b"{}", &ctx_for_test())
            .is_err()
    );
    writer.write_entity(Path::new("a.md"), b"a").unwrap();
    assert!(
        writer
            .commit("through a meta link", &ctx_for_test())
            .is_err()
    );
    let left: Vec<_> = std::fs::read_dir(&outside).unwrap().collect();
    assert!(left.is_empty(), "{left:?}");
}