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
//! Declared relations and alias synthesis on update, the dry-run
//! preview, the full CRUD round trip of REFERENCES edges, the outcome
//! shape, and the no-op family.

use super::*;

#[test]
fn update_entity_pointer_schema_auto_synthesises_references_from_body_link() {
    // Under the default schema's `alias_target_rel_type: REFERENCES`
    // pointer, a body wiki-link no longer trips the strict validator
    // — the alias-synthesis pass emits the REFERENCES relation
    // first, the validator finds the link backed, the body lands.
    // (Schemas without the pointer continue to refuse with
    // `WIKILINK_WITHOUT_RELATION`; that path is covered by the
    // dedicated no-pointer fixture test elsewhere.)
    use crate::EntityId;
    use crate::engine::UpdateEntityArgs;
    use indexmap::IndexMap;
    use tempfile::TempDir;

    let tmp = TempDir::new().unwrap();
    let mem_dir = tmp.path().to_path_buf();
    let writer = FilesystemBackend::new(mem_dir.clone());
    let mut engine = Engine::from_mounts(vec![(
        folder_mount("specs", mem_dir.clone()),
        Box::new(writer) as Box<dyn MemBackend>,
    )])
    .unwrap();
    engine.set_workspace_root(mem_dir.clone());
    let (actor, client) = cli_actor();

    let target = engine
        .create_entity(
            empty_create_args("specs", "Target"),
            actor,
            Some(&client),
            None,
        )
        .unwrap();
    let source = engine
        .create_entity(
            empty_create_args("specs", "Source"),
            actor,
            Some(&client),
            None,
        )
        .unwrap();

    let mut sections: IndexMap<String, String> = IndexMap::new();
    sections.insert(
        "purpose".to_string(),
        "see [[target]] for context".to_string(),
    );
    let outcome = engine
        .update_entity(
            UpdateEntityArgs {
                anchors: Vec::new(),
                id: source.id.clone(),
                expected_hash: crate::ExpectedHash::Current(source.content_hash.clone()),
                sections,
                append_sections: IndexMap::new(),
                patch_sections: IndexMap::new(),
                sections_unset: Vec::new(),
                metadata: IndexMap::new(),
                metadata_unset: Vec::new(),
                declare_relations: Vec::new(),
                dry_run: false,
                relations_unset: Vec::new(),
                anchors_unset: Vec::new(),
            },
            actor,
            Some(&client),
            None,
        )
        .expect("auto-synthesis must satisfy the alias-existence invariant");
    // Body landed.
    assert!(
        outcome
            .modified_sections
            .replaced
            .iter()
            .any(|s| s == "purpose"),
    );
    let in_mem = engine.get_entity(&source.id).unwrap();
    assert_eq!(
        in_mem
            .sections
            .get("purpose")
            .map(String::as_str)
            .unwrap_or(""),
        "see [[target]] for context",
    );
    // REFERENCES relation synthesised from the body wiki-link.
    assert!(
        in_mem
            .relationships
            .iter()
            .any(|r| r.rel_type == "REFERENCES" && r.target == target.id),
        "synthesis must emit REFERENCES → target; relationships: {:?}",
        in_mem.relationships,
    );
    // Defeat unused-import warnings for the helper imports.
    let _ = EntityId::new("specs", "x");
}

#[test]
fn update_entity_declare_relations_passes_strict_validator_in_one_call() {
    // The agent declares the relation + adds the body wiki-link
    // in a single `memstead_update` call. Without
    // `declare_relations`, the strict validator would refuse
    // (no backing relation yet); with the batched declaration,
    // the relation lands *before* the strict validator runs so
    // the body link passes the gate.
    use crate::engine::UpdateEntityArgs;
    use crate::ops::RelateArg;
    use indexmap::IndexMap;
    use tempfile::TempDir;

    let tmp = TempDir::new().unwrap();
    let mem_dir = tmp.path().to_path_buf();
    let writer = FilesystemBackend::new(mem_dir.clone());
    let mut engine = Engine::from_mounts(vec![(
        folder_mount("specs", mem_dir.clone()),
        Box::new(writer) as Box<dyn MemBackend>,
    )])
    .unwrap();
    engine.set_workspace_root(mem_dir.clone());
    let (actor, client) = cli_actor();

    let target = engine
        .create_entity(
            empty_create_args("specs", "Target"),
            actor,
            Some(&client),
            None,
        )
        .unwrap();
    let source = engine
        .create_entity(
            empty_create_args("specs", "Source"),
            actor,
            Some(&client),
            None,
        )
        .unwrap();

    // Atomic declare + body update. USES (not REFERENCES) — under
    // the default schema's `alias_target_rel_type: REFERENCES`
    // pointer, explicit declare_relations type=REFERENCES is
    // refused; the body wiki-link is auto-emitted via synthesis.
    // The test's intent — that declare_relations atomically lands
    // alongside body changes — holds for any rel-type that admits
    // explicit authoring.
    let mut sections: IndexMap<String, String> = IndexMap::new();
    sections.insert(
        "purpose".to_string(),
        "see [[target]] for context".to_string(),
    );
    let outcome = engine
        .update_entity(
            UpdateEntityArgs {
                anchors: Vec::new(),
                relations_unset: Vec::new(),
                anchors_unset: Vec::new(),
                id: source.id.clone(),
                expected_hash: crate::ExpectedHash::Current(source.content_hash.clone()),
                sections,
                append_sections: IndexMap::new(),
                patch_sections: IndexMap::new(),
                sections_unset: Vec::new(),
                metadata: IndexMap::new(),
                metadata_unset: Vec::new(),
                dry_run: false,
                declare_relations: vec![RelateArg {
                    rel_type: "USES".to_string(),
                    target: target.id.clone(),
                    description: None,
                }],
            },
            actor,
            Some(&client),
            None,
        )
        .expect("declare_relations + body update must succeed in one call");

    assert_eq!(outcome.relations_declared.len(), 1);
    assert_eq!(outcome.relations_declared[0].rel_type, "USES");
    assert_eq!(outcome.relations_declared[0].target, target.id);
    assert!(
        !outcome.relations_declared[0].target_was_stubbed,
        "target was already present in store; target_was_stubbed must be false"
    );

    let in_mem = engine.get_entity(&source.id).unwrap();
    assert!(
        in_mem.relationships.iter().any(|r| r.target == target.id),
        "declared relation must land in entity.relationships; got {:?}",
        in_mem.relationships
    );
}

#[test]
fn update_entity_declare_relations_auto_stubs_absent_target() {
    // When the declared target doesn't exist yet, the engine
    // auto-stubs it (same mechanic as `memstead_relate`) and flags
    // `target_was_stubbed: true` in the outcome.
    use crate::EntityId;
    use crate::engine::UpdateEntityArgs;
    use crate::ops::RelateArg;
    use indexmap::IndexMap;

    let tmp = TempDir::new().unwrap();
    let (mut engine, source) = engine_with_seed(&tmp, "Source");
    let (actor, client) = cli_actor();
    let absent_target = EntityId::new("specs", "not-yet-existing");
    assert!(!engine.store().contains(&absent_target));

    let outcome = engine
        .update_entity(
            UpdateEntityArgs {
                anchors: Vec::new(),
                relations_unset: Vec::new(),
                anchors_unset: Vec::new(),
                id: source.id.clone(),
                expected_hash: crate::ExpectedHash::Current(source.content_hash.clone()),
                sections: IndexMap::new(),
                append_sections: IndexMap::new(),
                patch_sections: IndexMap::new(),
                sections_unset: Vec::new(),
                metadata: IndexMap::new(),
                metadata_unset: Vec::new(),
                dry_run: false,
                declare_relations: vec![RelateArg {
                    rel_type: "USES".to_string(),
                    target: absent_target.clone(),
                    description: None,
                }],
            },
            actor,
            Some(&client),
            None,
        )
        .unwrap();

    assert_eq!(outcome.relations_declared.len(), 1);
    assert!(
        outcome.relations_declared[0].target_was_stubbed,
        "absent target must be auto-stubbed; got target_was_stubbed=false"
    );
    // Stub now exists in the store.
    assert!(engine.store().contains(&absent_target));
    let stub = engine.get_entity(&absent_target).unwrap();
    assert!(stub.stub);
}

#[test]
fn update_entity_alias_synthesis_runs_unconditionally_for_pointer_schemas() {
    // Under the alias model with a pointer-set schema (default
    // schema's `alias_target_rel_type: REFERENCES`), a fresh
    // workspace's first body-wiki-link write triggers the
    // alias-synthesis pass and the mutation lands with the
    // REFERENCES relation auto-emitted.
    use crate::engine::UpdateEntityArgs;
    use indexmap::IndexMap;
    use tempfile::TempDir;

    let tmp = TempDir::new().unwrap();
    let mem_dir = tmp.path().to_path_buf();
    let writer = FilesystemBackend::new(mem_dir.clone());
    let mut engine = Engine::from_mounts(vec![(
        folder_mount("specs", mem_dir.clone()),
        Box::new(writer) as Box<dyn MemBackend>,
    )])
    .unwrap();
    engine.set_workspace_root(mem_dir.clone());
    let (actor, client) = cli_actor();
    let target = engine
        .create_entity(
            empty_create_args("specs", "Target"),
            actor,
            Some(&client),
            None,
        )
        .unwrap();
    let source = engine
        .create_entity(
            empty_create_args("specs", "Source"),
            actor,
            Some(&client),
            None,
        )
        .unwrap();

    let mut sections: IndexMap<String, String> = IndexMap::new();
    sections.insert(
        "purpose".to_string(),
        "see [[target]] for context".to_string(),
    );
    engine
        .update_entity(
            UpdateEntityArgs {
                anchors: Vec::new(),
                id: source.id.clone(),
                expected_hash: crate::ExpectedHash::Current(source.content_hash.clone()),
                sections,
                append_sections: IndexMap::new(),
                patch_sections: IndexMap::new(),
                sections_unset: Vec::new(),
                metadata: IndexMap::new(),
                metadata_unset: Vec::new(),
                declare_relations: Vec::new(),
                dry_run: false,
                relations_unset: Vec::new(),
                anchors_unset: Vec::new(),
            },
            actor,
            Some(&client),
            None,
        )
        .expect("synthesis must back the wiki-link and let the body land");
    let in_mem = engine.get_entity(&source.id).unwrap();
    assert!(
        in_mem
            .relationships
            .iter()
            .any(|r| r.rel_type == "REFERENCES" && r.target == target.id),
        "synthesis must emit REFERENCES → target; relationships: {:?}",
        in_mem.relationships,
    );
}

#[test]
fn update_entity_dry_run_returns_prospective_hash_without_writing() {
    let tmp = TempDir::new().unwrap();
    let (mut engine, seeded) = engine_with_seed(&tmp, "Preview Subject");
    let (actor, client) = cli_actor();
    let original_hash = seeded.content_hash.clone();

    let mut sections = IndexMap::new();
    sections.insert("identity".to_string(), "preview body".to_string());

    let outcome = engine
        .update_entity(
            UpdateEntityArgs {
                anchors: Vec::new(),
                id: seeded.id.clone(),
                // Stale-hash recovery path — dry_run skips the
                // hash check, so a wrong expected_hash is OK.
                expected_hash: crate::ExpectedHash::Current("wrong-hash".to_string()),
                sections,
                append_sections: IndexMap::new(),
                patch_sections: IndexMap::new(),
                sections_unset: Vec::new(),
                metadata: IndexMap::new(),
                metadata_unset: Vec::new(),
                declare_relations: Vec::new(),
                dry_run: true,
                relations_unset: Vec::new(),
                anchors_unset: Vec::new(),
            },
            actor,
            Some(&client),
            None,
        )
        .unwrap();

    // Wire shape: content_hash = current; prospective_hash =
    // what the write would produce; write_id empty.
    assert_eq!(outcome.content_hash, original_hash);
    let prospective = outcome
        .prospective_hash
        .expect("prospective_hash populated on dry_run");
    assert_ne!(prospective, original_hash);
    assert!(outcome.write_id.is_empty());
    // Store entity unchanged.
    let store_entity = engine.get_entity(&seeded.id).unwrap();
    assert_eq!(store_entity.content_hash, original_hash);
}

/// Edge-count round-trip lock. Captures the REFERENCES-drift
/// finding:
/// a mutation cycle (create body wiki-links → relate → update
/// body → rename → delete) must return both `total_edges` and the
/// REFERENCES counter to the pre-cycle values exactly. The bug
/// was in `push_entities_into_store`: `upsert` preserved the
/// entity's pre-existing out-edges, so `add_edge` (idempotent on
/// `(from, to, rel_type)`) couldn't remove edges that the new
/// parse no longer emits. Dropping a wiki-link from a body or
/// absorbing one into an explicit relationship leaked the stale
/// REFERENCES edge.
///
/// Under the alias model the leak is structurally impossible —
/// body wiki-links no longer emit edges, so the cleanup-on-reparse
/// path the original test exercised has no premise. The test
/// keeps the CRUD cycle but routes edges through atomic
/// `relations:` declarations and explicit `memstead_relate`, which is
/// what the model now treats as the only edge source.
#[test]
fn references_edges_round_trip_across_full_crud_cycle() {
    let tmp = TempDir::new().unwrap();
    let mem_dir = tmp.path().to_path_buf();
    let writer = FilesystemBackend::new(mem_dir.clone());
    let mut engine = Engine::from_mounts(vec![(
        folder_mount("specs", mem_dir),
        Box::new(writer) as Box<dyn MemBackend>,
    )])
    .unwrap();
    let (actor, client) = cli_actor();

    // Seed two link targets so the wiki-links inside the
    // probe entity's body resolve to real entities (not auto-
    // stubs we'd then have to GC).
    let foo = engine
        .create_entity(
            empty_create_args("specs", "Foo"),
            actor,
            Some(&client),
            None,
        )
        .unwrap();
    let bar = engine
        .create_entity(
            empty_create_args("specs", "Bar"),
            actor,
            Some(&client),
            None,
        )
        .unwrap();

    let count_references = |engine: &Engine| -> usize {
        engine
            .store()
            .all_ids()
            .flat_map(|id| engine.store().outgoing(id))
            .filter(|e| e.rel_type == "REFERENCES")
            .count()
    };

    let baseline_edges = engine.store().edge_count();
    let baseline_refs = count_references(&engine);

    // Step 1: create entity with body wiki-links — the
    // alias-synthesis pass auto-emits one REFERENCES per body
    // wiki-link (default schema's `alias_target_rel_type` →
    // REFERENCES), so the explicit `relations:` slot stays
    // empty. Net: 2 REFERENCES.
    let mut sections = IndexMap::new();
    sections.insert(
        "identity".to_string(),
        "See [[foo]] and [[bar]] inline.".to_string(),
    );
    sections.insert("purpose".to_string(), "probe purpose".to_string());
    let probe = engine
        .create_entity(
            CreateEntityArgs {
                anchors: Vec::new(),
                mem: "specs".to_string(),
                title: "Probe".to_string(),
                entity_type: "spec".to_string(),
                sections,
                metadata: IndexMap::new(),
                relations: Vec::new(),
                dry_run: false,
            },
            actor,
            Some(&client),
            None,
        )
        .unwrap();
    assert_eq!(count_references(&engine), baseline_refs + 2);

    // Step 2: relate INFORMED_BY → foo as a second relation to the
    // same target. The body wiki-link `[[foo]]` aliases the set of
    // relations to foo, so adding INFORMED_BY does not affect the
    // REFERENCES count — both relations coexist.
    let relate1 = engine
        .relate_entity(
            RelateEntityArgs {
                source: probe.id.clone(),
                expected_hash: Some(probe.content_hash.clone()),
                rel_type: "INFORMED_BY".to_string(),
                target: foo.id.clone(),
                remove: false,
                description: None,
                dry_run: false,
            },
            actor,
            Some(&client),
            None,
        )
        .unwrap();
    assert_eq!(
        count_references(&engine),
        baseline_refs + 2,
        "set-membership aliasing — adding INFORMED_BY does not \
             absorb the REFERENCES relation"
    );

    // Step 3: drop the [[bar]] body link. The alias-synthesis pass
    // GCs the synthesised REFERENCES → bar atomically with the
    // body update — no second `memstead_relate --remove` needed.
    let mut sections = IndexMap::new();
    sections.insert("identity".to_string(), "See [[foo]] inline.".to_string());
    let updated = engine
        .update_entity(
            UpdateEntityArgs {
                anchors: Vec::new(),
                id: probe.id.clone(),
                expected_hash: crate::ExpectedHash::Current(relate1.content_hash.clone()),
                sections,
                append_sections: IndexMap::new(),
                patch_sections: IndexMap::new(),
                sections_unset: Vec::new(),
                metadata: IndexMap::new(),
                metadata_unset: Vec::new(),
                declare_relations: Vec::new(),
                dry_run: false,
                relations_unset: Vec::new(),
                anchors_unset: Vec::new(),
            },
            actor,
            Some(&client),
            None,
        )
        .unwrap();
    assert_eq!(
        count_references(&engine),
        baseline_refs + 1,
        "REFERENCES → bar must be auto-GC'd when its body link drops"
    );

    // Step 4: rename the entity. Edges follow via remove + push.
    let renamed = engine
        .rename_entity(
            crate::engine::RenameEntityArgs {
                id: probe.id.clone(),
                expected_hash: crate::ExpectedHash::Current(updated.content_hash.clone()),
                new_title: "Probe Renamed".to_string(),
            },
            actor,
            Some(&client),
            None,
        )
        .unwrap();
    assert_eq!(count_references(&engine), baseline_refs + 1);

    // Step 5: delete the renamed entity. The INFORMED_BY → foo
    // edge cascades; REFERENCES count unchanged.
    engine
        .delete_entity(
            crate::engine::DeleteEntityArgs {
                id: renamed.new_id.clone(),
                expected_hash: crate::ExpectedHash::Current(renamed.content_hash.clone()),
            },
            actor,
            Some(&client),
            None,
        )
        .unwrap();

    // Final assertion: every counter back to baseline.
    assert_eq!(
        engine.store().edge_count(),
        baseline_edges,
        "total edges must round-trip to baseline"
    );
    assert_eq!(
        count_references(&engine),
        baseline_refs,
        "REFERENCES counter must round-trip to baseline"
    );

    // Cross-check: a full reload of the mem produces the same
    // post-cycle counts. If the in-memory store and the on-disk
    // bytes drift, reload uncovers it.
    engine.reload_one_mem("specs").unwrap();
    assert_eq!(
        engine.store().edge_count(),
        baseline_edges,
        "total edges must match disk after reload"
    );
    assert_eq!(
        count_references(&engine),
        baseline_refs,
        "REFERENCES must match disk after reload"
    );
    // Sanity: foo + bar still in the store (they were not deleted).
    assert!(engine.store().contains(&foo.id));
    assert!(engine.store().contains(&bar.id));
}

#[test]
fn update_entity_returns_write_id_title_modified_date_warnings_shape() {
    let tmp = TempDir::new().unwrap();
    let (mut engine, seeded) = engine_with_seed(&tmp, "Subject");
    let (actor, client) = cli_actor();

    let mut sections = IndexMap::new();
    sections.insert("identity".to_string(), "edited body".to_string());

    let outcome = engine
        .update_entity(
            UpdateEntityArgs {
                anchors: Vec::new(),
                id: seeded.id.clone(),
                expected_hash: crate::ExpectedHash::Current(seeded.content_hash.clone()),
                sections,
                append_sections: IndexMap::new(),
                patch_sections: IndexMap::new(),
                sections_unset: Vec::new(),
                metadata: IndexMap::new(),
                metadata_unset: Vec::new(),
                declare_relations: Vec::new(),
                dry_run: false,
                relations_unset: Vec::new(),
                anchors_unset: Vec::new(),
            },
            actor,
            Some(&client),
            None,
        )
        .unwrap();

    // Folder backend produces a synthetic CommitId.
    assert!(
        !outcome.write_id.is_empty(),
        "write_id must be populated on a real update"
    );
    // Title echoed from the parsed entity post-write.
    assert_eq!(outcome.title, "Subject");
    // The default `spec` schema declares `modified_date` with
    // `auto_timestamp: true`; the unified update path
    // auto-stamps it. Asserting non-empty pins the
    // wire-shape parity with full's UpdateResult.modified_date.
    assert!(
        !outcome.modified_date.is_empty(),
        "modified_date must be auto-stamped on update for the default spec schema",
    );
    // V1: warnings always empty (typed warning surfaces are
    // separate session work). The vec is present on the outcome
    // so the wire shape parity with full's UpdateResult holds.
    assert!(outcome.warnings.is_empty());
    // Section was modified (existing behaviour, sanity check).
    assert_eq!(
        outcome.modified_sections.replaced,
        vec!["identity".to_string()]
    );
}

// ---- Engine::update_entity no-op detection ---------------------

/// Re-setting a
/// section to its current on-disk value short-circuits to
/// `UPDATE_NOOP` and preserves `last_modified` at its pre-call
/// value. Pre-fix the auto-timestamp stamped `last_modified` to
/// `today_iso()` before the bytes-compare ran; the stamp
/// synthesised a delta and the no-op never matched.
#[test]
fn update_entity_noop_resetting_section_to_current_value_preserves_last_modified() {
    let tmp = TempDir::new().unwrap();
    let (mut engine, seeded) = engine_with_seed(&tmp, "Section Resetter");
    let (actor, client) = cli_actor();

    // Read the pre-update `last_modified` so we can assert it
    // survives the no-op.
    let pre_last_modified = engine
        .get_entity(&seeded.id)
        .and_then(|e| e.metadata.get("last_modified"))
        .map(|v| v.to_frontmatter_string())
        .expect("seeded entity has last_modified");

    // Re-set `identity` to its current on-disk body. The seed
    // helper writes "fixture identity body" — passing the same
    // string back must be a no-op.
    let mut sections = IndexMap::new();
    sections.insert("identity".to_string(), "fixture identity body".to_string());
    let outcome = engine
        .update_entity(
            UpdateEntityArgs {
                anchors: Vec::new(),
                id: seeded.id.clone(),
                expected_hash: crate::ExpectedHash::Current(seeded.content_hash.clone()),
                sections,
                append_sections: IndexMap::new(),
                patch_sections: IndexMap::new(),
                sections_unset: Vec::new(),
                metadata: IndexMap::new(),
                metadata_unset: Vec::new(),
                declare_relations: Vec::new(),
                dry_run: false,
                relations_unset: Vec::new(),
                anchors_unset: Vec::new(),
            },
            actor,
            Some(&client),
            None,
        )
        .unwrap();

    assert_eq!(outcome.write_id, "", "no-op must not commit");
    assert_eq!(
        outcome.content_hash, seeded.content_hash,
        "no-op must not advance content_hash",
    );
    assert!(
        outcome.warnings.iter().any(|w| w.code() == "UPDATE_NOOP"),
        "UPDATE_NOOP must fire on bytes-identical re-set",
    );
    assert_eq!(
        outcome.modified_date, pre_last_modified,
        "no-op must preserve last_modified at the pre-call value",
    );
    // The applied delta is empty on a
    // no-op — `modified_sections` must not claim `identity` was
    // replaced when nothing landed (matching the empty write_id
    // and unchanged hash above).
    assert!(
        outcome.modified_sections.replaced.is_empty()
            && outcome.modified_sections.appended.is_empty()
            && outcome.modified_sections.patched.is_empty(),
        "no-op must report an empty section delta, got {:?}",
        outcome.modified_sections,
    );

    // The on-disk entity also still carries the pre-update
    // last_modified — the no-op didn't bump it through some
    // other path.
    let post_last_modified = engine
        .get_entity(&seeded.id)
        .and_then(|e| e.metadata.get("last_modified"))
        .map(|v| v.to_frontmatter_string())
        .expect("entity still in store");
    assert_eq!(post_last_modified, pre_last_modified);
}

/// A payload with no
/// recognised mutation content refuses with `EMPTY_UPDATE` BEFORE
/// any engine work runs. Previously this same input short-
/// circuited as a success-with-`UPDATE_NOOP`-warning, which
/// hid a boundary-discipline failure mode (a
/// misspelled mutation key deserialises to empty defaults and
/// looks like a no-op success on the wire). The new refusal
/// makes "no mutation content provided" structurally distinct
/// from "mutation content provided but matched current state"
/// (which still surfaces `UPDATE_NOOP` — see
/// `update_entity_noop_same_content_surfaces_warning` below).
#[test]
fn update_entity_empty_payload_refuses_with_typed_code() {
    let tmp = TempDir::new().unwrap();
    let (mut engine, seeded) = engine_with_seed(&tmp, "Empty Payload");
    let (actor, client) = cli_actor();

    let err = engine
        .update_entity(
            UpdateEntityArgs {
                anchors: Vec::new(),
                id: seeded.id.clone(),
                expected_hash: crate::ExpectedHash::Current(seeded.content_hash.clone()),
                sections: IndexMap::new(),
                append_sections: IndexMap::new(),
                patch_sections: IndexMap::new(),
                sections_unset: Vec::new(),
                metadata: IndexMap::new(),
                metadata_unset: Vec::new(),
                declare_relations: Vec::new(),
                dry_run: false,
                relations_unset: Vec::new(),
                anchors_unset: Vec::new(),
            },
            actor,
            Some(&client),
            None,
        )
        .unwrap_err();
    match err {
        EngineError::EmptyUpdate { id } => {
            assert_eq!(id, seeded.id.to_string());
        }
        other => panic!("expected EMPTY_UPDATE, got {other:?}"),
    }
    // No provenance row landed — the refusal preempts any write.
    let log_path = tmp.path().join(".memstead/changes.jsonl");
    if let Ok(log) = std::fs::read_to_string(&log_path) {
        let updates = log.matches("\"kind\":\"update\"").count();
        assert_eq!(updates, 0, "EMPTY_UPDATE refusal must not log an update");
    }
}

/// Complement: a
/// payload with mutation content that matches the current entity
/// state continues to land as success-with-`UPDATE_NOOP`-warning.
/// The new `EMPTY_UPDATE` refusal applies only when no mutation
/// content was provided; this path is structurally distinct.
#[test]
fn update_entity_noop_same_content_surfaces_warning() {
    let tmp = TempDir::new().unwrap();
    let (mut engine, seeded) = engine_with_seed(&tmp, "Same Content Noop");
    let (actor, client) = cli_actor();

    // `empty_create_args` seeds `identity` with this exact body.
    let mut sections = IndexMap::new();
    sections.insert("identity".to_string(), "fixture identity body".to_string());

    let outcome = engine
        .update_entity(
            UpdateEntityArgs {
                anchors: Vec::new(),
                id: seeded.id.clone(),
                expected_hash: crate::ExpectedHash::Current(seeded.content_hash.clone()),
                sections,
                append_sections: IndexMap::new(),
                patch_sections: IndexMap::new(),
                sections_unset: Vec::new(),
                metadata: IndexMap::new(),
                metadata_unset: Vec::new(),
                declare_relations: Vec::new(),
                dry_run: false,
                relations_unset: Vec::new(),
                anchors_unset: Vec::new(),
            },
            actor,
            Some(&client),
            None,
        )
        .unwrap();

    assert_eq!(outcome.write_id, "");
    assert_eq!(outcome.content_hash, seeded.content_hash);
    let codes: Vec<&str> = outcome.warnings.iter().map(|w| w.code()).collect();
    assert!(
        codes.contains(&"UPDATE_NOOP"),
        "same-content update must surface UPDATE_NOOP; got {codes:?}",
    );
}

#[test]
fn update_entity_noop_metadata_unset_on_absent_key() {
    // `metadata_unset=["never-set-key"]`
    // where the key was never set is a no-op — no field actually
    // changed, no commit advances, follow-up calls can chain
    // `expected_hash` without `HASH_MISMATCH`.
    let tmp = TempDir::new().unwrap();
    let (mut engine, seeded) = engine_with_seed(&tmp, "Absent Key Noop");
    let (actor, client) = cli_actor();

    let outcome = engine
        .update_entity(
            UpdateEntityArgs {
                anchors: Vec::new(),
                id: seeded.id.clone(),
                expected_hash: crate::ExpectedHash::Current(seeded.content_hash.clone()),
                sections: IndexMap::new(),
                append_sections: IndexMap::new(),
                patch_sections: IndexMap::new(),
                sections_unset: Vec::new(),
                metadata: IndexMap::new(),
                // `tags` is declared on the `spec` schema but
                // unset on the seeded entity. Unsetting it should
                // be a no-op rather than producing a fresh commit.
                metadata_unset: vec!["tags".to_string()],
                declare_relations: Vec::new(),
                dry_run: false,
                relations_unset: Vec::new(),
                anchors_unset: Vec::new(),
            },
            actor,
            Some(&client),
            None,
        )
        .unwrap();

    assert_eq!(outcome.write_id, "");
    assert_eq!(outcome.content_hash, seeded.content_hash);
    assert!(
        outcome.warnings.iter().any(|w| w.code() == "UPDATE_NOOP"),
        "absent-key metadata_unset must surface UPDATE_NOOP",
    );
    // Empty applied delta on the no-op —
    // `unset` must not claim `tags` was removed when nothing landed.
    assert!(
        outcome.modified_metadata.set.is_empty() && outcome.modified_metadata.unset.is_empty(),
        "no-op must report an empty metadata delta, got {:?}",
        outcome.modified_metadata,
    );

    // Follow-up real change against the unchanged hash succeeds —
    // no HASH_MISMATCH cascade from a phantom advance.
    let mut sections = IndexMap::new();
    sections.insert("identity".to_string(), "real change".to_string());
    let real = engine
        .update_entity(
            UpdateEntityArgs {
                anchors: Vec::new(),
                id: seeded.id.clone(),
                expected_hash: crate::ExpectedHash::Current(seeded.content_hash.clone()),
                sections,
                append_sections: IndexMap::new(),
                patch_sections: IndexMap::new(),
                sections_unset: Vec::new(),
                metadata: IndexMap::new(),
                metadata_unset: Vec::new(),
                declare_relations: Vec::new(),
                dry_run: false,
                relations_unset: Vec::new(),
                anchors_unset: Vec::new(),
            },
            actor,
            Some(&client),
            None,
        )
        .unwrap();
    assert!(!real.write_id.is_empty());
    assert_ne!(real.content_hash, seeded.content_hash);
}

/// The exact MCP repro — re-setting a
/// metadata key to its current value no-ops, and the response's
/// `modified_metadata` reports the applied delta (empty), not the
/// requested key. Pre-fix the no-op short-circuit echoed
/// `set: ["level"]` while `write_id` was empty and the hash
/// unchanged — a self-contradictory response.
#[test]
fn update_entity_noop_setting_metadata_to_current_value_reports_empty_delta() {
    let tmp = TempDir::new().unwrap();
    let (mut engine, seeded) = engine_with_seed(&tmp, "Stability Resetter");
    let (actor, client) = cli_actor();

    // `level` defaults to "M0" on the spec schema, so the seed
    // carries it. Re-setting it to "M0" changes nothing.
    let mut metadata = IndexMap::new();
    metadata.insert("level".to_string(), "M0".to_string());
    let outcome = engine
        .update_entity(
            UpdateEntityArgs {
                anchors: Vec::new(),
                id: seeded.id.clone(),
                expected_hash: crate::ExpectedHash::Current(seeded.content_hash.clone()),
                sections: IndexMap::new(),
                append_sections: IndexMap::new(),
                patch_sections: IndexMap::new(),
                sections_unset: Vec::new(),
                metadata,
                metadata_unset: Vec::new(),
                declare_relations: Vec::new(),
                dry_run: false,
                relations_unset: Vec::new(),
                anchors_unset: Vec::new(),
            },
            actor,
            Some(&client),
            None,
        )
        .unwrap();

    assert_eq!(outcome.write_id, "", "no-op must not commit");
    assert_eq!(
        outcome.content_hash, seeded.content_hash,
        "no-op must not advance hash"
    );
    assert!(
        outcome.warnings.iter().any(|w| w.code() == "UPDATE_NOOP"),
        "re-set to current value must surface UPDATE_NOOP",
    );
    assert!(
        outcome.modified_metadata.set.is_empty() && outcome.modified_metadata.unset.is_empty(),
        "no-op must not claim `level` was set — applied delta is empty, got {:?}",
        outcome.modified_metadata,
    );
}

#[test]
fn update_entity_noop_declare_already_related_edge() {
    // Re-declare an already-related edge
    // via `declare_relations` — no field, section, metadata or
    // relations list actually changes, so the bytes are identical
    // and the call no-ops.
    use crate::ops::RelateArg;
    let tmp = TempDir::new().unwrap();
    let mem_dir = tmp.path().to_path_buf();
    let writer = FilesystemBackend::new(mem_dir.clone());
    let mut engine = Engine::from_mounts(vec![(
        folder_mount("specs", mem_dir),
        Box::new(writer) as Box<dyn MemBackend>,
    )])
    .unwrap();
    let (actor, client) = cli_actor();
    let target = engine
        .create_entity(
            empty_create_args("specs", "Target Already Related"),
            actor,
            Some(&client),
            None,
        )
        .unwrap();
    let source = engine
        .create_entity(
            empty_create_args("specs", "Source Already Related"),
            actor,
            Some(&client),
            None,
        )
        .unwrap();
    let after_relate = engine
        .relate_entity(
            RelateEntityArgs {
                source: source.id.clone(),
                expected_hash: Some(source.content_hash.clone()),
                rel_type: "USES".to_string(),
                target: target.id.clone(),
                remove: false,
                description: None,
                dry_run: false,
            },
            actor,
            Some(&client),
            None,
        )
        .unwrap();
    // Now re-declare the same edge via update.declare_relations.
    let outcome = engine
        .update_entity(
            UpdateEntityArgs {
                anchors: Vec::new(),
                relations_unset: Vec::new(),
                anchors_unset: Vec::new(),
                id: source.id.clone(),
                expected_hash: crate::ExpectedHash::Current(after_relate.content_hash.clone()),
                sections: IndexMap::new(),
                append_sections: IndexMap::new(),
                patch_sections: IndexMap::new(),
                sections_unset: Vec::new(),
                metadata: IndexMap::new(),
                metadata_unset: Vec::new(),
                declare_relations: vec![RelateArg {
                    rel_type: "USES".to_string(),
                    target: target.id.clone(),
                    description: None,
                }],
                dry_run: false,
            },
            actor,
            Some(&client),
            None,
        )
        .unwrap();

    assert_eq!(outcome.write_id, "");
    assert_eq!(outcome.content_hash, after_relate.content_hash);
    assert!(
        outcome.warnings.iter().any(|w| w.code() == "UPDATE_NOOP"),
        "duplicate declare must surface UPDATE_NOOP",
    );
    // `relations_declared` still records the entry — the per-
    // relation outcome is part of the surface, even for no-ops.
    assert_eq!(outcome.relations_declared.len(), 1);
    assert_eq!(outcome.relations_declared[0].rel_type, "USES");
    assert_eq!(outcome.relations_declared[0].target, target.id);
    assert!(!outcome.relations_declared[0].target_was_stubbed);
}

#[test]
fn update_entity_real_change_still_commits_and_advances_hash() {
    // Regression: the no-op short-circuit must not short-circuit
    // real changes. A section replacement still produces a
    // non-empty `write_id`, advances `content_hash`, and does
    // NOT surface UPDATE_NOOP.
    let tmp = TempDir::new().unwrap();
    let (mut engine, seeded) = engine_with_seed(&tmp, "Real Change Subject");
    let (actor, client) = cli_actor();

    let mut sections = IndexMap::new();
    sections.insert("identity".to_string(), "definitely new body".to_string());

    let outcome = engine
        .update_entity(
            UpdateEntityArgs {
                anchors: Vec::new(),
                id: seeded.id.clone(),
                expected_hash: crate::ExpectedHash::Current(seeded.content_hash.clone()),
                sections,
                append_sections: IndexMap::new(),
                patch_sections: IndexMap::new(),
                sections_unset: Vec::new(),
                metadata: IndexMap::new(),
                metadata_unset: Vec::new(),
                declare_relations: Vec::new(),
                dry_run: false,
                relations_unset: Vec::new(),
                anchors_unset: Vec::new(),
            },
            actor,
            Some(&client),
            None,
        )
        .unwrap();

    assert!(!outcome.write_id.is_empty(), "real change must commit");
    assert_ne!(
        outcome.content_hash, seeded.content_hash,
        "real change must advance content_hash",
    );
    assert!(
        !outcome.warnings.iter().any(|w| w.code() == "UPDATE_NOOP"),
        "real change must not surface UPDATE_NOOP",
    );
}

#[test]
fn update_entity_noop_preserves_expected_hash_across_chain() {
    // A follow-up update with the original
    // hash after one or more no-ops succeeds because the hash
    // never advanced. Demonstrates the `expected_hash`-caching
    // posture the agent surface relies on.
    let tmp = TempDir::new().unwrap();
    let (mut engine, seeded) = engine_with_seed(&tmp, "Chained Noops Subject");
    let (actor, client) = cli_actor();

    // Two no-op calls in a row — both must return the same hash.
    // Pass same-content mutation
    // so UPDATE_NOOP fires (rather than EMPTY_UPDATE) and the
    // hash-chain invariant is exercised on the warning path.
    let mut noop_sections = IndexMap::new();
    noop_sections.insert("identity".to_string(), "fixture identity body".to_string());
    for _ in 0..2 {
        let outcome = engine
            .update_entity(
                UpdateEntityArgs {
                    anchors: Vec::new(),
                    id: seeded.id.clone(),
                    expected_hash: crate::ExpectedHash::Current(seeded.content_hash.clone()),
                    sections: noop_sections.clone(),
                    append_sections: IndexMap::new(),
                    patch_sections: IndexMap::new(),
                    sections_unset: Vec::new(),
                    metadata: IndexMap::new(),
                    metadata_unset: Vec::new(),
                    declare_relations: Vec::new(),
                    dry_run: false,
                    relations_unset: Vec::new(),
                    anchors_unset: Vec::new(),
                },
                actor,
                Some(&client),
                None,
            )
            .unwrap();
        assert_eq!(outcome.write_id, "");
        assert_eq!(outcome.content_hash, seeded.content_hash);
    }

    // Real follow-up with the original hash still works — no
    // HASH_MISMATCH cascade because the hash never advanced.
    let mut sections = IndexMap::new();
    sections.insert(
        "identity".to_string(),
        "third call: real change".to_string(),
    );
    let real = engine
        .update_entity(
            UpdateEntityArgs {
                anchors: Vec::new(),
                id: seeded.id.clone(),
                expected_hash: crate::ExpectedHash::Current(seeded.content_hash.clone()),
                sections,
                append_sections: IndexMap::new(),
                patch_sections: IndexMap::new(),
                sections_unset: Vec::new(),
                metadata: IndexMap::new(),
                metadata_unset: Vec::new(),
                declare_relations: Vec::new(),
                dry_run: false,
                relations_unset: Vec::new(),
                anchors_unset: Vec::new(),
            },
            actor,
            Some(&client),
            None,
        )
        .unwrap();
    assert!(!real.write_id.is_empty());
    assert_ne!(real.content_hash, seeded.content_hash);
}

/// A refused update leaves the store as it found it: the target stub a
/// declared relation created during composition goes with the refusal.
#[test]
fn a_refused_update_leaves_no_stub_for_its_declared_target() {
    let tmp = TempDir::new().unwrap();
    let (mut engine, seeded) = engine_with_seed(&tmp, "Stub Source");
    let (actor, client) = cli_actor();
    let ghost = EntityId("specs--ghost".to_string());
    assert!(engine.get_entity(&ghost).is_none());

    let mut patches = IndexMap::new();
    patches.insert(
        "identity".to_string(),
        vec![crate::ops::PatchArg {
            old: "text that is not there".to_string(),
            new: "anything".to_string(),
            all: false,
        }],
    );
    let err = engine
        .update_entity(
            UpdateEntityArgs {
                anchors: Vec::new(),
                relations_unset: Vec::new(),
                anchors_unset: Vec::new(),
                id: seeded.id.clone(),
                expected_hash: crate::ExpectedHash::Current(seeded.content_hash.clone()),
                sections: IndexMap::new(),
                append_sections: IndexMap::new(),
                patch_sections: patches,
                sections_unset: Vec::new(),
                metadata: IndexMap::new(),
                metadata_unset: Vec::new(),
                dry_run: false,
                declare_relations: vec![crate::ops::RelateArg {
                    rel_type: "USES".to_string(),
                    target: ghost.clone(),
                    description: None,
                }],
            },
            actor,
            Some(&client),
            None,
        )
        .unwrap_err();
    assert_eq!(err.code(), "PATCH_OLD_NOT_FOUND", "{err:?}");
    assert!(
        engine.get_entity(&ghost).is_none(),
        "the refused update left a stub for its declared target"
    );
}