memstead-base 0.26.1

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
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
//! Schema gates on the write path: declared constraints, required
//! outgoing edges (plain and conditional), acyclic sets, labelling,
//! signals, and the no-self-loop refusal.

use super::*;

/// Fixture for the declared-constraints vertical: type `task`
/// declares `requires_when` (checked → checked_by) at the given
/// severity, plus a `required_outgoing` block at the given
/// severity — so one schema exercises form 1 and form 4 at either
/// tier.
fn engine_with_constraints_schema(
    tmp: &TempDir,
    requires_when_severity: &str,
    required_outgoing_severity: &str,
) -> Engine {
    let schemas_dir = tmp.path().join("schemas");
    let pkg = schemas_dir.join("constr");
    std::fs::create_dir_all(pkg.join("types")).unwrap();
    std::fs::write(
        pkg.join("schema.yaml"),
        r#"name: constr
version: 0.1.0
description: constraint fixture
when_to_use: tests
types:
  - task
relationships:
  mode: strict
  definitions:
    - name: PART_OF
      description: hier
      default_weight: 3.0
    - name: _default
      description: fallback
      default_weight: 1.0
community:
  resolution: 1.0
  seed: 42
"#,
    )
    .unwrap();
    std::fs::write(
        pkg.join("types").join("task.yaml"),
        format!(
            r#"name: task
description: t
when_to_use: tests
sections:
  - key: body
    heading: Body
    required: true
    search_weight: 10.0
    catch_all: true
    write_rules: []
metadata_fields:
  - key: status
    description: workflow state
    field_type: string
    enum_values: [open, checked]
  - key: checked_by
    description: who checked
    field_type: string
title_weight: 100.0
text_fields:
  - body
hierarchy_relationship: PART_OF
no_self_loop_relationships: [PART_OF]
updatable_fields:
  - title
  - body
  - status
  - checked_by
health_required_fields:
  - body
staleness_threshold_days: 90
required_outgoing:
  - relationships: [PART_OF]
    cardinality: at_least_one
    severity: {required_outgoing_severity}
constraints:
  - kind: requires_when
    field: checked_by
    when_field: status
    when_value: checked
    severity: {requires_when_severity}
write_rules: []
"#
        ),
    )
    .unwrap();
    let mem_dir = tmp.path().join("mem");
    std::fs::create_dir_all(&mem_dir).unwrap();
    let writer = FilesystemBackend::new(mem_dir.clone());
    let mount = crate::workspace::Mount {
        mem: "tasks".to_string(),
        schema: Some(memstead_schema::SchemaRef::new(
            "constr",
            semver::Version::new(0, 1, 0),
        )),
        storage: crate::workspace::MountStorage::Folder { path: mem_dir },
        capability: crate::workspace::MountCapability::Write,
        lifecycle: crate::workspace::MountLifecycle::Eager,
        cross_linkable: true,
        migration_target: None,
    };
    Engine::from_mounts_with_schemas_dir(
        vec![(mount, Box::new(writer) as Box<dyn MemBackend>)],
        Some(&schemas_dir),
    )
    .unwrap()
}

fn checked_task_args(title: &str, relations: Vec<crate::ops::RelateArg>) -> CreateEntityArgs {
    let mut args = task_create_args(title, relations);
    args.metadata
        .insert("status".to_string(), "checked".to_string());
    args
}

/// Form 1 at warn: a create violating `requires_when` warns
/// `CONSTRAINT_UNSATISFIED` and still commits; the health sweep
/// reports the same violation (shared evaluation); a create
/// satisfying the constraint emits neither.
#[test]
fn create_warns_requires_when_and_still_commits() {
    let tmp = TempDir::new().unwrap();
    let mut engine = engine_with_constraints_schema(&tmp, "warn", "warn");
    let (actor, client) = cli_actor();

    let outcome = engine
        .create_entity(
            checked_task_args("Unbacked Judgment", vec![]),
            actor,
            Some(&client),
            None,
        )
        .unwrap();
    assert!(!outcome.write_id.is_empty(), "warn tier never blocks");
    let violation = outcome
        .warnings
        .iter()
        .find_map(|w| match w {
            WarningHint::ConstraintUnsatisfied { violations, .. } => Some(violations.clone()),
            _ => None,
        })
        .expect("CONSTRAINT_UNSATISFIED warning present");
    assert_eq!(violation.len(), 1);
    let crate::ops::health::UnsatisfiedConstraint::RequiresWhen {
        field,
        when_field,
        when_value,
        ..
    } = &violation[0]
    else {
        panic!("expected requires_when violation");
    };
    assert_eq!(field, "checked_by");
    assert_eq!(when_field, "status");
    assert_eq!(when_value, "checked");

    // Health parity — same single evaluation.
    let reports = crate::ops::health::collect_constraint_findings(
        engine.store(),
        None,
        engine.schemas(),
        None,
    );
    assert_eq!(reports.len(), 1);
    assert_eq!(reports[0].id, outcome.id);
    assert_eq!(reports[0].violations.len(), 1);
    let crate::ops::health::UnsatisfiedConstraint::RequiresWhen { field, .. } =
        &reports[0].violations[0]
    else {
        panic!("expected requires_when finding");
    };
    assert_eq!(field, "checked_by");

    // Complement 1: satisfying the constraint in the same create
    // emits no warning and no finding.
    let mut satisfied_args = checked_task_args("Backed Judgment", vec![]);
    satisfied_args
        .metadata
        .insert("checked_by".to_string(), "reviewer-a".to_string());
    let satisfied = engine
        .create_entity(satisfied_args, actor, Some(&client), None)
        .unwrap();
    assert!(
        !satisfied
            .warnings
            .iter()
            .any(|w| matches!(w, WarningHint::ConstraintUnsatisfied { .. })),
        "satisfied constraint emits no warning: {:?}",
        satisfied.warnings
    );

    // Complement 2: an untriggered constraint (status != checked)
    // emits nothing even with checked_by unset.
    let untriggered = engine
        .create_entity(
            task_create_args("Open Task", vec![]),
            actor,
            Some(&client),
            None,
        )
        .unwrap();
    assert!(
        !untriggered
            .warnings
            .iter()
            .any(|w| matches!(w, WarningHint::ConstraintUnsatisfied { .. })),
        "untriggered constraint emits no warning"
    );
}

/// Form 1 at block: the same violation refuses the create with
/// `CONSTRAINT_UNSATISFIED`, leaves nothing behind, and the
/// refusal payload restates the declaration.
#[test]
fn create_refuses_block_tier_requires_when() {
    let tmp = TempDir::new().unwrap();
    let mut engine = engine_with_constraints_schema(&tmp, "block", "warn");
    let (actor, client) = cli_actor();

    let err = engine
        .create_entity(
            checked_task_args("Unbacked Judgment", vec![]),
            actor,
            Some(&client),
            None,
        )
        .unwrap_err();
    assert_eq!(err.code(), "CONSTRAINT_UNSATISFIED");
    let details = err.details();
    assert_eq!(details["violations"][0]["field"], "checked_by");
    assert_eq!(details["violations"][0]["severity"], "block");
    assert_eq!(
        engine.store().all_entities().count(),
        0,
        "refused create leaves nothing behind"
    );

    // The satisfying create passes under the same schema.
    let mut ok_args = checked_task_args("Backed Judgment", vec![]);
    ok_args
        .metadata
        .insert("checked_by".to_string(), "reviewer-a".to_string());
    engine
        .create_entity(ok_args, actor, Some(&client), None)
        .unwrap();
}

/// Form 4 at block: a create leaving a `severity: block`
/// `required_outgoing` block unsatisfied refuses with
/// `MISSING_REQUIRED_OUTGOING` (the same code the warn tier
/// warns with — one condition, one vocabulary); an inline
/// relation satisfying the block lets the create pass.
#[test]
fn create_refuses_block_tier_required_outgoing() {
    let tmp = TempDir::new().unwrap();
    let mut engine = engine_with_constraints_schema(&tmp, "warn", "block");
    let (actor, client) = cli_actor();

    let err = engine
        .create_entity(
            task_create_args("Orphan Task", vec![]),
            actor,
            Some(&client),
            None,
        )
        .unwrap_err();
    assert_eq!(err.code(), "MISSING_REQUIRED_OUTGOING");
    let details = err.details();
    assert_eq!(details["missing"][0]["relationships"][0], "PART_OF");
    assert_eq!(details["missing"][0]["severity"], "block");
    assert_eq!(engine.store().all_entities().count(), 0);

    // A create satisfying the block via an inline relation to an
    // auto-stubbed target passes — the stub itself has no type
    // definition under this schema's `task`-only vocabulary, so
    // wire the edge from the real entity.
    let outcome = engine.create_entity(
        task_create_args(
            "Child Task",
            vec![crate::ops::RelateArg {
                target: crate::entity::EntityId("tasks--parent".to_string()),
                rel_type: "PART_OF".to_string(),
                description: None,
            }],
        ),
        actor,
        Some(&client),
        None,
    );
    assert!(
        outcome.is_ok(),
        "satisfied block-tier create passes: {:?}",
        outcome.err()
    );
}

/// Update-side severity mirror for form 1: at warn, an update
/// that makes the constraint trigger warns and commits; at block,
/// the same update refuses and the entity keeps its prior state.
#[test]
fn update_enforces_requires_when_by_severity() {
    let (actor, client) = cli_actor();
    let set_checked = |engine: &mut Engine, id: &crate::entity::EntityId| {
        let current = engine.get_entity(id).unwrap().content_hash.clone();
        let mut metadata = IndexMap::new();
        metadata.insert("status".to_string(), "checked".to_string());
        engine.update_entity(
            crate::engine::UpdateEntityArgs {
                anchors: Vec::new(),
                id: id.clone(),
                expected_hash: crate::ExpectedHash::Current(current),
                sections: IndexMap::new(),
                append_sections: IndexMap::new(),
                patch_sections: IndexMap::new(),
                sections_unset: Vec::new(),
                metadata,
                metadata_unset: Vec::new(),
                declare_relations: vec![],
                dry_run: false,
                relations_unset: Vec::new(),
                anchors_unset: Vec::new(),
            },
            actor,
            Some(&client),
            None,
        )
    };

    // Warn tier: the update commits with the typed warning.
    let tmp = TempDir::new().unwrap();
    let mut engine = engine_with_constraints_schema(&tmp, "warn", "warn");
    let a = engine
        .create_entity(
            task_create_args("Task A", vec![]),
            actor,
            Some(&client),
            None,
        )
        .unwrap();
    let outcome = set_checked(&mut engine, &a.id).unwrap();
    assert!(!outcome.write_id.is_empty());
    assert!(
        outcome
            .warnings
            .iter()
            .any(|w| matches!(w, WarningHint::ConstraintUnsatisfied { .. })),
        "warn-tier update carries the warning: {:?}",
        outcome.warnings
    );

    // Block tier: the same update refuses; the entity keeps its
    // prior metadata.
    let tmp = TempDir::new().unwrap();
    let mut engine = engine_with_constraints_schema(&tmp, "block", "warn");
    let b = engine
        .create_entity(
            task_create_args("Task B", vec![]),
            actor,
            Some(&client),
            None,
        )
        .unwrap();
    let err = set_checked(&mut engine, &b.id).unwrap_err();
    assert_eq!(err.code(), "CONSTRAINT_UNSATISFIED");
    assert!(
        !engine
            .get_entity(&b.id)
            .unwrap()
            .metadata
            .contains_key("status"),
        "refused update leaves the entity unchanged"
    );
}

/// Form 4 at block on the relate surface: removing the edge that
/// satisfies a `severity: block` `required_outgoing` block refuses
/// with `MISSING_REQUIRED_OUTGOING`; the edge survives.
#[test]
fn relate_remove_refuses_block_tier_required_outgoing() {
    let tmp = TempDir::new().unwrap();
    let mut engine = engine_with_constraints_schema(&tmp, "warn", "block");
    let (actor, client) = cli_actor();
    let parent_id = crate::entity::EntityId("tasks--parent".to_string());
    let child = engine
        .create_entity(
            task_create_args(
                "Child Task",
                vec![crate::ops::RelateArg {
                    target: parent_id.clone(),
                    rel_type: "PART_OF".to_string(),
                    description: None,
                }],
            ),
            actor,
            Some(&client),
            None,
        )
        .unwrap();

    let err = engine
        .relate_entity(
            crate::engine::RelateEntityArgs {
                source: child.id.clone(),
                target: parent_id.clone(),
                rel_type: "PART_OF".to_string(),
                description: None,
                remove: true,
                expected_hash: None,
                dry_run: false,
            },
            actor,
            Some(&client),
            None,
        )
        .unwrap_err();
    assert_eq!(err.code(), "MISSING_REQUIRED_OUTGOING");
    assert!(
        engine
            .get_entity(&child.id)
            .unwrap()
            .relationships
            .iter()
            .any(|r| r.rel_type == "PART_OF" && r.target == parent_id),
        "refused remove leaves the edge in place"
    );
}

/// Fixture for the conditional `required_outgoing` form: type
/// `task` requires a PART_OF edge only while `status` holds
/// `checked`, at the given severity. No unconditional blocks, no
/// `constraints` — the conditional block is the only obligation.
fn engine_with_conditional_ro_schema(tmp: &TempDir, severity: &str) -> Engine {
    let schemas_dir = tmp.path().join("schemas");
    let pkg = schemas_dir.join("condro");
    std::fs::create_dir_all(pkg.join("types")).unwrap();
    std::fs::write(
        pkg.join("schema.yaml"),
        r#"name: condro
version: 0.1.0
description: conditional required_outgoing fixture
when_to_use: tests
types:
  - task
relationships:
  mode: strict
  definitions:
    - name: PART_OF
      description: hier
      default_weight: 3.0
    - name: _default
      description: fallback
      default_weight: 1.0
community:
  resolution: 1.0
  seed: 42
"#,
    )
    .unwrap();
    std::fs::write(
        pkg.join("types").join("task.yaml"),
        format!(
            r#"name: task
description: t
when_to_use: tests
sections:
  - key: body
    heading: Body
    required: true
    search_weight: 10.0
    catch_all: true
    write_rules: []
metadata_fields:
  - key: status
    description: workflow state
    field_type: string
    enum_values: [open, checked]
title_weight: 100.0
text_fields:
  - body
hierarchy_relationship: PART_OF
no_self_loop_relationships: []
updatable_fields:
  - title
  - body
  - status
health_required_fields:
  - body
staleness_threshold_days: 90
required_outgoing:
  - relationships: [PART_OF]
    cardinality: at_least_one
    severity: {severity}
    when_field: status
    when_value: checked
write_rules: []
"#
        ),
    )
    .unwrap();
    let mem_dir = tmp.path().join("mem");
    std::fs::create_dir_all(&mem_dir).unwrap();
    let writer = FilesystemBackend::new(mem_dir.clone());
    let mount = crate::workspace::Mount {
        mem: "tasks".to_string(),
        schema: Some(memstead_schema::SchemaRef::new(
            "condro",
            semver::Version::new(0, 1, 0),
        )),
        storage: crate::workspace::MountStorage::Folder { path: mem_dir },
        capability: crate::workspace::MountCapability::Write,
        lifecycle: crate::workspace::MountLifecycle::Eager,
        cross_linkable: true,
        migration_target: None,
    };
    Engine::from_mounts_with_schemas_dir(
        vec![(mount, Box::new(writer) as Box<dyn MemBackend>)],
        Some(&schemas_dir),
    )
    .unwrap()
}

/// An unarmed conditional block never fires: entities whose
/// trigger field is unset or holds another enum value create
/// cleanly without the edge, with no `MISSING_REQUIRED_OUTGOING`
/// warning, even at block tier.
#[test]
fn create_ignores_conditional_required_outgoing_when_unarmed() {
    let tmp = TempDir::new().unwrap();
    let mut engine = engine_with_conditional_ro_schema(&tmp, "block");
    let (actor, client) = cli_actor();

    let unset = engine
        .create_entity(
            task_create_args("Unset Status", vec![]),
            actor,
            Some(&client),
            None,
        )
        .expect("unset trigger field must create");
    let mut open_args = task_create_args("Open Task", vec![]);
    open_args
        .metadata
        .insert("status".to_string(), "open".to_string());
    let open = engine
        .create_entity(open_args, actor, Some(&client), None)
        .expect("non-trigger value must create");
    for outcome in [&unset, &open] {
        assert!(
            !outcome
                .warnings
                .iter()
                .any(|w| matches!(w, WarningHint::MissingRequiredOutgoing { .. })),
            "unarmed block emits no warning: {:?}",
            outcome.warnings
        );
    }
}

/// Armed at block tier: a create whose trigger field holds the
/// trigger value and lacks the edge refuses with
/// `MISSING_REQUIRED_OUTGOING`, and the payload names the trigger
/// (`when_field` / `when_value`); an inline relation satisfying
/// the armed block lets the same create pass.
#[test]
fn create_refuses_block_tier_conditional_required_outgoing() {
    let tmp = TempDir::new().unwrap();
    let mut engine = engine_with_conditional_ro_schema(&tmp, "block");
    let (actor, client) = cli_actor();

    let err = engine
        .create_entity(
            checked_task_args("Checked Orphan", vec![]),
            actor,
            Some(&client),
            None,
        )
        .unwrap_err();
    assert_eq!(err.code(), "MISSING_REQUIRED_OUTGOING");
    let details = err.details();
    assert_eq!(details["missing"][0]["relationships"][0], "PART_OF");
    assert_eq!(details["missing"][0]["when_field"], "status");
    assert_eq!(details["missing"][0]["when_value"], "checked");
    assert_eq!(engine.store().all_entities().count(), 0);

    let outcome = engine.create_entity(
        checked_task_args(
            "Checked Child",
            vec![crate::ops::RelateArg {
                target: crate::entity::EntityId("tasks--parent".to_string()),
                rel_type: "PART_OF".to_string(),
                description: None,
            }],
        ),
        actor,
        Some(&client),
        None,
    );
    assert!(
        outcome.is_ok(),
        "satisfied armed block passes: {:?}",
        outcome.err()
    );
}

/// Armed at warn tier: the create lands and carries the
/// `MISSING_REQUIRED_OUTGOING` warning whose block entry names
/// the trigger.
#[test]
fn create_warns_conditional_required_outgoing_at_warn_tier() {
    let tmp = TempDir::new().unwrap();
    let mut engine = engine_with_conditional_ro_schema(&tmp, "warn");
    let (actor, client) = cli_actor();

    let outcome = engine
        .create_entity(
            checked_task_args("Checked Orphan", vec![]),
            actor,
            Some(&client),
            None,
        )
        .expect("warn tier lands the write");
    assert!(!outcome.write_id.is_empty());
    let block = outcome
        .warnings
        .iter()
        .find_map(|w| match w {
            WarningHint::MissingRequiredOutgoing { missing, .. } => missing.first(),
            _ => None,
        })
        .expect("warning carries the unsatisfied block");
    assert_eq!(block.relationships, vec!["PART_OF".to_string()]);
    assert_eq!(block.when_field.as_deref(), Some("status"));
    assert_eq!(block.when_value.as_deref(), Some("checked"));
}

/// The metadata flip that arms the block is caught on update: at
/// block tier the update refuses and the entity keeps its prior
/// value; at warn tier the same flip commits with the warning.
#[test]
fn update_flip_to_trigger_value_enforces_conditional_block() {
    let (actor, client) = cli_actor();
    let flip_to_checked = |engine: &mut Engine, id: &crate::entity::EntityId| {
        let current = engine.get_entity(id).unwrap().content_hash.clone();
        let mut metadata = IndexMap::new();
        metadata.insert("status".to_string(), "checked".to_string());
        engine.update_entity(
            crate::engine::UpdateEntityArgs {
                anchors: Vec::new(),
                id: id.clone(),
                expected_hash: crate::ExpectedHash::Current(current),
                sections: IndexMap::new(),
                append_sections: IndexMap::new(),
                patch_sections: IndexMap::new(),
                sections_unset: Vec::new(),
                metadata,
                metadata_unset: Vec::new(),
                declare_relations: vec![],
                dry_run: false,
                relations_unset: Vec::new(),
                anchors_unset: Vec::new(),
            },
            actor,
            Some(&client),
            None,
        )
    };

    // Block tier: the flip refuses; the entity keeps `open`.
    let tmp = TempDir::new().unwrap();
    let mut engine = engine_with_conditional_ro_schema(&tmp, "block");
    let mut open_args = task_create_args("Task A", vec![]);
    open_args
        .metadata
        .insert("status".to_string(), "open".to_string());
    let a = engine
        .create_entity(open_args, actor, Some(&client), None)
        .unwrap();
    let err = flip_to_checked(&mut engine, &a.id).unwrap_err();
    assert_eq!(err.code(), "MISSING_REQUIRED_OUTGOING");
    assert_eq!(
        engine.get_entity(&a.id).unwrap().metadata["status"].to_frontmatter_string(),
        "open",
        "refused update leaves the entity unchanged"
    );

    // Warn tier: the same flip commits with the typed warning.
    let tmp = TempDir::new().unwrap();
    let mut engine = engine_with_conditional_ro_schema(&tmp, "warn");
    let b = engine
        .create_entity(
            task_create_args("Task B", vec![]),
            actor,
            Some(&client),
            None,
        )
        .unwrap();
    let outcome = flip_to_checked(&mut engine, &b.id).unwrap();
    assert!(!outcome.write_id.is_empty());
    assert!(
        outcome
            .warnings
            .iter()
            .any(|w| matches!(w, WarningHint::MissingRequiredOutgoing { .. })),
        "warn-tier flip carries the warning: {:?}",
        outcome.warnings
    );
}

/// Fixture for declared acyclicity sets: one `claim` type over
/// GROUNDS / CONCLUDES, with `acyclic_sets: [[GROUNDS, CONCLUDES]]`
/// when `with_set` (neither rel-type carries the per-definition
/// `acyclic` flag, so without the set every cycle is legal).
fn engine_with_acyclic_set_schema(tmp: &TempDir, with_set: bool) -> Engine {
    let schemas_dir = tmp.path().join("schemas");
    let pkg = schemas_dir.join("argchain");
    std::fs::create_dir_all(pkg.join("types")).unwrap();
    let sets = if with_set {
        "  acyclic_sets:\n    - [GROUNDS, CONCLUDES]\n"
    } else {
        ""
    };
    std::fs::write(
        pkg.join("schema.yaml"),
        format!(
            r#"name: argchain
version: 0.1.0
description: acyclicity-set fixture
when_to_use: tests
types:
  - claim
relationships:
  mode: strict
{sets}  definitions:
    - name: GROUNDS
      description: g
      default_weight: 3.0
    - name: CONCLUDES
      description: c
      default_weight: 3.0
    - name: PART_OF
      description: hier
      default_weight: 1.0
    - name: _default
      description: fallback
      default_weight: 1.0
community:
  resolution: 1.0
  seed: 42
"#
        ),
    )
    .unwrap();
    std::fs::write(
        pkg.join("types").join("claim.yaml"),
        r#"name: claim
description: t
when_to_use: tests
sections:
  - key: body
    heading: Body
    required: true
    search_weight: 10.0
    catch_all: true
    write_rules: []
metadata_fields: []
title_weight: 100.0
text_fields:
  - body
hierarchy_relationship: PART_OF
no_self_loop_relationships: []
updatable_fields:
  - title
  - body
health_required_fields:
  - body
staleness_threshold_days: 90
write_rules: []
"#,
    )
    .unwrap();
    let mem_dir = tmp.path().join("mem");
    std::fs::create_dir_all(&mem_dir).unwrap();
    let writer = FilesystemBackend::new(mem_dir.clone());
    let mount = crate::workspace::Mount {
        mem: "arg".to_string(),
        schema: Some(memstead_schema::SchemaRef::new(
            "argchain",
            semver::Version::new(0, 1, 0),
        )),
        storage: crate::workspace::MountStorage::Folder { path: mem_dir },
        capability: crate::workspace::MountCapability::Write,
        lifecycle: crate::workspace::MountLifecycle::Eager,
        cross_linkable: true,
        migration_target: None,
    };
    Engine::from_mounts_with_schemas_dir(
        vec![(mount, Box::new(writer) as Box<dyn MemBackend>)],
        Some(&schemas_dir),
    )
    .unwrap()
}

fn claim_args(title: &str, relations: Vec<crate::ops::RelateArg>) -> CreateEntityArgs {
    let mut sections = IndexMap::new();
    sections.insert("body".to_string(), "a claim body.".to_string());
    CreateEntityArgs {
        anchors: Vec::new(),
        mem: "arg".to_string(),
        title: title.to_string(),
        entity_type: "claim".to_string(),
        sections,
        metadata: IndexMap::new(),
        relations,
        dry_run: false,
    }
}

/// The experiment's alternating cycle: with `[GROUNDS, CONCLUDES]`
/// declared as one acyclicity set, the relate that closes a cycle
/// mixing both rel-types refuses with `RELATIONSHIP_CYCLE`; the
/// payload echoes the set and names each hop's rel-type. The same
/// graph WITHOUT the set declaration accepts the cycle (no
/// implicit derivation from anything else).
#[test]
fn relate_refuses_mixed_type_cycle_in_declared_set() {
    let tmp = TempDir::new().unwrap();
    let mut engine = engine_with_acyclic_set_schema(&tmp, true);
    let (actor, client) = cli_actor();
    for t in ["A", "B", "C"] {
        engine
            .create_entity(claim_args(t, vec![]), actor, Some(&client), None)
            .unwrap();
    }
    relate(&mut engine, "arg--a", "GROUNDS", "arg--b").unwrap();
    relate(&mut engine, "arg--b", "CONCLUDES", "arg--c").unwrap();

    let err = relate(&mut engine, "arg--c", "GROUNDS", "arg--a").unwrap_err();
    assert_eq!(err.code(), "RELATIONSHIP_CYCLE", "{err:?}");
    let details = err.details();
    assert_eq!(
        details["acyclic_set"],
        serde_json::json!(["GROUNDS", "CONCLUDES"])
    );
    assert_eq!(
        details["existing_path"],
        serde_json::json!(["arg--a", "arg--b", "arg--c"])
    );
    assert_eq!(
        details["existing_path_rel_types"],
        serde_json::json!(["GROUNDS", "CONCLUDES"]),
        "one rel-type per hop, mixing both members"
    );

    // Complement: the identical graph without the declaration
    // accepts the cycle.
    let tmp = TempDir::new().unwrap();
    let mut engine = engine_with_acyclic_set_schema(&tmp, false);
    for t in ["A", "B", "C"] {
        engine
            .create_entity(claim_args(t, vec![]), actor, Some(&client), None)
            .unwrap();
    }
    relate(&mut engine, "arg--a", "GROUNDS", "arg--b").unwrap();
    relate(&mut engine, "arg--b", "CONCLUDES", "arg--c").unwrap();
    relate(&mut engine, "arg--c", "GROUNDS", "arg--a")
        .expect("without the set declaration the cycle is legal");
}

/// The set refusal fires identically for inline relations on
/// create (through a promoted stub) and declared relations on
/// update.
#[test]
fn create_inline_and_update_declared_refuse_set_cycle() {
    let tmp = TempDir::new().unwrap();
    let mut engine = engine_with_acyclic_set_schema(&tmp, true);
    let (actor, client) = cli_actor();

    // create.relations[]: A → GROUNDS → ghost auto-stubs `ghost`;
    // promoting the stub with a CONCLUDES back-edge closes a
    // mixed-type cycle.
    engine
        .create_entity(
            claim_args(
                "Alpha",
                vec![crate::ops::RelateArg {
                    target: crate::entity::EntityId("arg--ghost".to_string()),
                    rel_type: "GROUNDS".to_string(),
                    description: None,
                }],
            ),
            actor,
            Some(&client),
            None,
        )
        .unwrap();
    let err = engine
        .create_entity(
            claim_args(
                "Ghost",
                vec![crate::ops::RelateArg {
                    target: crate::entity::EntityId("arg--alpha".to_string()),
                    rel_type: "CONCLUDES".to_string(),
                    description: None,
                }],
            ),
            actor,
            Some(&client),
            None,
        )
        .expect_err("cycle-closing create.relations[] must refuse");
    assert_eq!(err.code(), "RELATIONSHIP_CYCLE", "{err:?}");
    assert_eq!(
        err.details()["acyclic_set"],
        serde_json::json!(["GROUNDS", "CONCLUDES"])
    );

    // update.declare_relations: D → GROUNDS → E exists; updating E
    // with CONCLUDES → D closes the mixed cycle.
    for t in ["D", "E"] {
        engine
            .create_entity(claim_args(t, vec![]), actor, Some(&client), None)
            .unwrap();
    }
    relate(&mut engine, "arg--d", "GROUNDS", "arg--e").unwrap();
    let e_id = crate::entity::EntityId("arg--e".to_string());
    let current = engine.get_entity(&e_id).unwrap().content_hash.clone();
    let err = engine
        .update_entity(
            crate::engine::UpdateEntityArgs {
                anchors: Vec::new(),
                id: e_id,
                expected_hash: crate::ExpectedHash::Current(current),
                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![crate::ops::RelateArg {
                    target: crate::entity::EntityId("arg--d".to_string()),
                    rel_type: "CONCLUDES".to_string(),
                    description: None,
                }],
                dry_run: false,
                relations_unset: Vec::new(),
                anchors_unset: Vec::new(),
            },
            actor,
            Some(&client),
            None,
        )
        .expect_err("cycle-closing declare_relations must refuse");
    assert_eq!(err.code(), "RELATIONSHIP_CYCLE", "{err:?}");
    assert_eq!(
        err.details()["acyclic_set"],
        serde_json::json!(["GROUNDS", "CONCLUDES"])
    );
}

/// A package whose on-disk edges already close a mixed-type cycle
/// boots with one cycle-closing edge dropped and warned, exactly
/// as the single-type sweep does.
#[test]
fn boot_drops_cycle_closing_edge_in_declared_acyclic_set() {
    let tmp = TempDir::new().unwrap();
    // Write the schema and two claim files closing a GROUNDS /
    // CONCLUDES cycle BEFORE boot, then reuse the fixture builder
    // (same schemas dir and mem dir layout).
    let mem_dir = tmp.path().join("mem");
    std::fs::create_dir_all(&mem_dir).unwrap();
    std::fs::write(
            mem_dir.join("a.md"),
            "---\ntype: claim\n---\n# A\n\n## Body\n\nfirst.\n\n## Relationships\n\n- **GROUNDS**: [[arg--b]]\n",
        )
        .unwrap();
    std::fs::write(
            mem_dir.join("b.md"),
            "---\ntype: claim\n---\n# B\n\n## Body\n\nsecond.\n\n## Relationships\n\n- **CONCLUDES**: [[arg--a]]\n",
        )
        .unwrap();
    let engine = engine_with_acyclic_set_schema(&tmp, true);

    let surviving: usize = engine
        .store()
        .all_entities()
        .map(|e| {
            engine
                .store()
                .outgoing(&e.id)
                .iter()
                .filter(|edge| edge.rel_type == "GROUNDS" || edge.rel_type == "CONCLUDES")
                .count()
        })
        .sum();
    assert_eq!(surviving, 1, "exactly one edge survives the cycle break");
    let cycle_warnings: Vec<_> = engine
        .load_warnings()
        .iter()
        .filter(|w| {
            matches!(
                w,
                WarningHint::ParsedRelationInvalid { reason, .. } if reason == "cycle"
            )
        })
        .cloned()
        .collect();
    assert_eq!(
        cycle_warnings.len(),
        1,
        "exactly one cycle warning fires: {cycle_warnings:?}"
    );
}

/// Fixture for aggregate signals: `claim` declares `attack_load`
/// (in-REBUTS count, notice at 1, warn at 3) and
/// `open_objections` (same set, counterpart `state: open` only,
/// notice at 1); `objection` declares the `state` enum.
/// Fixture for the grounded labelling: `arglab` declares
/// `labelling.attack: [REBUTS]` and a support walk over GROUNDS
/// (direction out, terminal `evidence`); mem `arg` (and, when the
/// test mounts it, mem `other`) pin it.
fn engine_with_labelling_schema(tmp: &TempDir, with_other_mem: bool) -> Engine {
    engine_with_labelling_schema_support(tmp, with_other_mem, true)
}

fn engine_with_labelling_schema_support(
    tmp: &TempDir,
    with_other_mem: bool,
    with_support: bool,
) -> Engine {
    let schemas_dir = tmp.path().join("schemas");
    let pkg = schemas_dir.join("arglab");
    std::fs::create_dir_all(pkg.join("types")).unwrap();
    std::fs::write(
            pkg.join("schema.yaml"),
            format!(
                r#"name: arglab
version: 0.1.0
description: grounded-labelling fixture
when_to_use: tests
types:
  - claim
  - evidence
relationships:
  mode: strict
  labelling:
    attack: [REBUTS]
{support}  definitions:
    - name: REBUTS
      description: attack
      default_weight: 3.0
    - name: GROUNDS
      description: support
      default_weight: 3.0
    - name: PART_OF
      description: hier
      default_weight: 1.0
    - name: _default
      description: fallback
      default_weight: 1.0
community:
  resolution: 1.0
  seed: 42
cross_mem_relationships:
  - to_schema: arglab
    definitions:
      - name: REBUTS
        description: cross-mem attack
        default_weight: 3.0
"#,
                support = if with_support {
                    "    support:\n      relationships: [GROUNDS]\n      direction: out\n      terminal_types: [evidence]\n"
                } else {
                    ""
                },
            ),
        )
        .unwrap();
    let body = "sections:\n  - key: body\n    heading: Body\n    required: true\n    search_weight: 10.0\n    catch_all: true\n    write_rules: []\nmetadata_fields: []\ntitle_weight: 100.0\ntext_fields:\n  - body\nhierarchy_relationship: PART_OF\nno_self_loop_relationships: []\nupdatable_fields:\n  - title\n  - body\nhealth_required_fields:\n  - body\nstaleness_threshold_days: 90\nwrite_rules: []\n";
    for t in ["claim", "evidence"] {
        std::fs::write(
            pkg.join("types").join(format!("{t}.yaml")),
            format!("name: {t}\ndescription: t\nwhen_to_use: tests\n{body}"),
        )
        .unwrap();
    }
    let mut mounts: Vec<(crate::workspace::Mount, Box<dyn MemBackend>)> = Vec::new();
    for mem in std::iter::once("arg").chain(with_other_mem.then_some("other")) {
        let mem_dir = tmp.path().join(format!("mem-{mem}"));
        std::fs::create_dir_all(&mem_dir).unwrap();
        let writer = FilesystemBackend::new(mem_dir.clone());
        mounts.push((
            crate::workspace::Mount {
                mem: mem.to_string(),
                schema: Some(memstead_schema::SchemaRef::new(
                    "arglab",
                    semver::Version::new(0, 1, 0),
                )),
                storage: crate::workspace::MountStorage::Folder { path: mem_dir },
                capability: crate::workspace::MountCapability::Write,
                lifecycle: crate::workspace::MountLifecycle::Eager,
                cross_linkable: true,
                migration_target: None,
            },
            Box::new(writer) as Box<dyn MemBackend>,
        ));
    }
    Engine::from_mounts_with_schemas_dir(mounts, Some(&schemas_dir)).unwrap()
}

fn lab_create(engine: &mut Engine, mem: &str, title: &str, entity_type: &str) {
    let (actor, client) = cli_actor();
    let mut sections = IndexMap::new();
    sections.insert("body".to_string(), "a body.".to_string());
    engine
        .create_entity(
            CreateEntityArgs {
                anchors: Vec::new(),
                mem: mem.to_string(),
                title: title.to_string(),
                entity_type: entity_type.to_string(),
                sections,
                metadata: IndexMap::new(),
                relations: vec![],
                dry_run: false,
            },
            actor,
            Some(&client),
            None,
        )
        .unwrap();
}

fn lab_relate(engine: &mut Engine, from: &str, rel: &str, to: &str) {
    let (actor, client) = cli_actor();
    engine
        .relate_entity(
            crate::engine::RelateEntityArgs {
                source: crate::entity::EntityId(from.to_string()),
                target: crate::entity::EntityId(to.to_string()),
                rel_type: rel.to_string(),
                description: None,
                remove: false,
                expected_hash: None,
                dry_run: false,
            },
            actor,
            Some(&client),
            None,
        )
        .unwrap();
}

fn label_of(engine: &Engine, id: &str) -> (String, Vec<String>, Vec<String>) {
    let entity = engine
        .get_entity(&crate::entity::EntityId(id.to_string()))
        .unwrap()
        .clone();
    let view = engine.computed_labelling(&entity).unwrap();
    (
        view.label.wire().to_string(),
        view.defeated_by.clone(),
        view.undecided_by.clone(),
    )
}

/// The hand-computed grounded extension: an unattacked claim is
/// accepted, a chain defeats, a defeated attacker reinstates, a
/// cycle stays undecided (and keeps its victims undecided); the
/// evidence names the accepted / undecided direct attackers; two
/// instances serve identical labels; the memo invalidates on the
/// in-process mutation path AND the reload path; labels never
/// gate writes; the health axis serves counts with evidence.
#[test]
fn grounded_labelling_extension_evidence_and_invalidation() {
    let tmp = TempDir::new().unwrap();
    let mut engine = engine_with_labelling_schema(&tmp, false);
    for t in ["A", "B", "C", "D", "E", "F"] {
        lab_create(&mut engine, "arg", t, "claim");
    }
    lab_relate(&mut engine, "arg--a", "REBUTS", "arg--b");
    lab_relate(&mut engine, "arg--b", "REBUTS", "arg--c");
    lab_relate(&mut engine, "arg--d", "REBUTS", "arg--e");
    lab_relate(&mut engine, "arg--e", "REBUTS", "arg--d");
    lab_relate(&mut engine, "arg--d", "REBUTS", "arg--f");

    assert_eq!(label_of(&engine, "arg--a").0, "accepted", "unattacked");
    let (label, defeated_by, _) = label_of(&engine, "arg--b");
    assert_eq!(label, "defeated");
    assert_eq!(defeated_by, vec!["arg--a".to_string()], "evidence ships");
    assert_eq!(
        label_of(&engine, "arg--c").0,
        "accepted",
        "reinstatement: the only attacker is itself defeated"
    );
    let (label, _, undecided_by) = label_of(&engine, "arg--d");
    assert_eq!(label, "undecided", "cycle member");
    assert_eq!(undecided_by, vec!["arg--e".to_string()]);
    let (label, _, undecided_by) = label_of(&engine, "arg--f");
    assert_eq!(label, "undecided", "victim of an undecided attacker");
    assert_eq!(undecided_by, vec!["arg--d".to_string()]);

    // Determinism: a second instance over the same on-disk state.
    let engine_b = engine_with_labelling_schema(&tmp, false);
    for id in ["arg--a", "arg--b", "arg--c", "arg--d", "arg--e", "arg--f"] {
        assert_eq!(label_of(&engine, id), label_of(&engine_b, id));
    }

    // Health axis: counts per label, evidence on the lists.
    let axis = engine.health_labelling_axis(None);
    assert_eq!(axis["arg"]["counts"]["accepted"], 2);
    assert_eq!(axis["arg"]["counts"]["defeated"], 1);
    assert_eq!(axis["arg"]["counts"]["undecided"], 3);
    assert_eq!(axis["arg"]["defeated"][0]["id"], "arg--b");
    assert_eq!(axis["arg"]["defeated"][0]["defeated_by"][0], "arg--a");

    // Labels never gate writes: updating a defeated entity and
    // adding an edge into it both succeed with the normal shapes.
    let (actor, client) = cli_actor();
    let b_id = crate::entity::EntityId("arg--b".to_string());
    let current = engine.get_entity(&b_id).unwrap().content_hash.clone();
    let mut sections = IndexMap::new();
    sections.insert("body".to_string(), "updated body.".to_string());
    let outcome = engine
        .update_entity(
            crate::engine::UpdateEntityArgs {
                anchors: Vec::new(),
                id: b_id,
                expected_hash: crate::ExpectedHash::Current(current),
                sections,
                append_sections: IndexMap::new(),
                patch_sections: IndexMap::new(),
                sections_unset: Vec::new(),
                metadata: IndexMap::new(),
                metadata_unset: Vec::new(),
                declare_relations: vec![],
                dry_run: false,
                relations_unset: Vec::new(),
                anchors_unset: Vec::new(),
            },
            actor,
            Some(&client),
            None,
        )
        .expect("updating a defeated entity succeeds");
    assert!(!outcome.write_id.is_empty());
    lab_relate(&mut engine, "arg--f", "REBUTS", "arg--b");

    // In-process invalidation: a fresh unattacked attacker flips
    // A on the next read.
    lab_create(&mut engine, "arg", "H", "claim");
    lab_relate(&mut engine, "arg--h", "REBUTS", "arg--a");
    let (label, defeated_by, _) = label_of(&engine, "arg--a");
    assert_eq!(
        label, "defeated",
        "memo invalidated by the in-process mutation"
    );
    assert_eq!(defeated_by, vec!["arg--h".to_string()]);

    // Reload-path invalidation: an out-of-band file change plus an
    // explicit mem reload serves the new labelling.
    let g_path = tmp.path().join("mem-arg").join("g.md");
    std::fs::write(
            &g_path,
            "---\ntype: claim\n---\n# G\n\n## Body\n\nout of band.\n\n## Relationships\n\n- **REBUTS**: [[arg--c]]\n",
        )
        .unwrap();
    engine.reload_one_mem("arg").expect("reload succeeds");
    let (label, defeated_by, _) = label_of(&engine, "arg--c");
    assert_eq!(label, "defeated", "reload invalidated the memo");
    assert!(defeated_by.contains(&"arg--g".to_string()));
}

/// Support-blindness, chain shape, cross-mem exclusion, and the
/// no-declaration complement.
#[test]
fn labelling_support_blindness_shape_and_cross_mem() {
    let tmp = TempDir::new().unwrap();
    let mut engine = engine_with_labelling_schema(&tmp, true);
    // Support chain: conclusion → inference → evidence; an
    // undercutter defeats the inference.
    for (t, ty) in [
        ("Conclusion", "claim"),
        ("Inference", "claim"),
        ("Undercutter", "claim"),
    ] {
        lab_create(&mut engine, "arg", t, ty);
    }
    lab_create(&mut engine, "arg", "Ev One", "evidence");
    lab_relate(&mut engine, "arg--conclusion", "GROUNDS", "arg--inference");
    lab_relate(&mut engine, "arg--inference", "GROUNDS", "arg--ev-one");
    lab_relate(&mut engine, "arg--undercutter", "REBUTS", "arg--inference");

    // Support-blindness: the defeated inference leaves its
    // conclusion accepted; the defeat shows in the shape count.
    let conclusion = engine
        .get_entity(&crate::entity::EntityId("arg--conclusion".to_string()))
        .unwrap()
        .clone();
    let view = engine.computed_labelling(&conclusion).unwrap();
    assert_eq!(view.label.wire(), "accepted", "support-blind by design");
    let shape = view.shape.expect("support declared, shape served");
    assert_eq!(shape.depth, 2);
    assert!((shape.branching - 1.0).abs() < 1e-9);
    assert_eq!(shape.terminal_share, Some(1.0));
    assert_eq!(shape.defeated_in_support, 1, "the defeated inference");
    assert_eq!(shape.undecided_in_support, 0);

    // Isolated entity: zeros and a null share.
    lab_create(&mut engine, "arg", "Loner", "claim");
    let loner = engine
        .get_entity(&crate::entity::EntityId("arg--loner".to_string()))
        .unwrap()
        .clone();
    let view = engine.computed_labelling(&loner).unwrap();
    let shape = view.shape.unwrap();
    assert_eq!(
        (shape.depth, shape.branching, shape.terminal_share),
        (0, 0.0, None)
    );
    assert_eq!(
        (shape.defeated_in_support, shape.undecided_in_support),
        (0, 0)
    );

    // Cross-mem: an attack edge from `other` into `arg` (granted
    // by workspace policy) is excluded from the computation and
    // counted; the target stays accepted.
    let mut settings = engine.settings().clone();
    settings.cross_mem_links.insert(
        "other".to_string(),
        memstead_schema::workspace_config::CrossLinkValue::Wildcard,
    );
    engine.set_settings(settings);
    lab_create(&mut engine, "other", "Foreign", "claim");
    lab_relate(&mut engine, "other--foreign", "REBUTS", "arg--conclusion");
    let conclusion = engine
        .get_entity(&crate::entity::EntityId("arg--conclusion".to_string()))
        .unwrap()
        .clone();
    let view = engine.computed_labelling(&conclusion).unwrap();
    assert_eq!(
        view.label.wire(),
        "accepted",
        "the cross-mem attack is excluded, never guessed"
    );
    let axis = engine.health_labelling_axis(Some("arg"));
    assert_eq!(axis["arg"]["cross_mem_edges_excluded"], 1);
    assert!(axis.get("other").is_none(), "mem filter narrows");

    // Serving channels: envelope `_labelling` and the text
    // channel's `_label` + `## Labelling`; the canonical form
    // stays projection-free.
    let inference = engine
        .get_entity(&crate::entity::EntityId("arg--inference".to_string()))
        .unwrap()
        .clone();
    let view = engine.computed_labelling(&inference).unwrap();
    let md = crate::render::render_entity_markdown_with_signals(
        &inference,
        None,
        None,
        Some(&view),
        None,
    );
    assert!(md.contains("_label: defeated"), "{md}");
    assert!(md.contains("## Labelling"), "{md}");
    assert!(md.contains("defeated_by: arg--undercutter"), "{md}");
    let env = crate::render::build_entity_envelope(
        &inference,
        0,
        None,
        None,
        None,
        crate::render::OriginClass::FirstParty,
        engine
            .store()
            .outgoing(&crate::entity::EntityId("arg--inference".to_string())),
        None,
        None,
        Some(&view),
    );
    assert_eq!(env["_labelling"]["label"], "defeated");
    assert_eq!(env["_labelling"]["defeated_by"][0], "arg--undercutter");
    assert!(env["_labelling"]["shape"].is_object());
    let canonical = crate::render::render_entity_markdown(&inference, None);
    assert!(
        !canonical.contains("_label") && !canonical.contains("## Labelling"),
        "canonical form is projection-free"
    );

    // No-declaration complement: a signals-fixture entity (schema
    // without labelling) serves no labelling view at all.
    let tmp2 = TempDir::new().unwrap();
    let mut plain = engine_with_signals_schema(&tmp2);
    let (actor, client) = cli_actor();
    let mut sections = IndexMap::new();
    sections.insert("body".to_string(), "a claim body.".to_string());
    plain
        .create_entity(
            CreateEntityArgs {
                anchors: Vec::new(),
                mem: "arg".to_string(),
                title: "Plain".to_string(),
                entity_type: "claim".to_string(),
                sections,
                metadata: IndexMap::new(),
                relations: vec![],
                dry_run: false,
            },
            actor,
            Some(&client),
            None,
        )
        .unwrap();
    let plain_entity = plain
        .get_entity(&crate::entity::EntityId("arg--plain".to_string()))
        .unwrap()
        .clone();
    assert!(plain.computed_labelling(&plain_entity).is_none());
}

/// An attack-only declaration (no `support` walk) serves labels
/// but nothing shape-shaped on any channel.
#[test]
fn labelling_without_support_serves_no_shape() {
    let tmp = TempDir::new().unwrap();
    let mut engine = engine_with_labelling_schema_support(&tmp, false, false);
    lab_create(&mut engine, "arg", "Solo", "claim");
    let entity = engine
        .get_entity(&crate::entity::EntityId("arg--solo".to_string()))
        .unwrap()
        .clone();
    let view = engine.computed_labelling(&entity).expect("labels served");
    assert_eq!(view.label.wire(), "accepted");
    assert!(view.shape.is_none(), "no support declaration, no shape");
    assert!(view.to_json().get("shape").is_none());
    let md =
        crate::render::render_entity_markdown_with_signals(&entity, None, None, Some(&view), None);
    assert!(!md.contains("- shape:"), "{md}");
}

fn engine_with_signals_schema(tmp: &TempDir) -> Engine {
    let schemas_dir = tmp.path().join("schemas");
    let pkg = schemas_dir.join("argsig");
    std::fs::create_dir_all(pkg.join("types")).unwrap();
    std::fs::write(
        pkg.join("schema.yaml"),
        r#"name: argsig
version: 0.1.0
description: aggregate-signal fixture
when_to_use: tests
types:
  - claim
  - objection
relationships:
  mode: strict
  definitions:
    - name: REBUTS
      description: r
      default_weight: 3.0
    - name: PART_OF
      description: hier
      default_weight: 1.0
    - name: _default
      description: fallback
      default_weight: 1.0
community:
  resolution: 1.0
  seed: 42
"#,
    )
    .unwrap();
    let body = "sections:\n  - key: body\n    heading: Body\n    required: true\n    search_weight: 10.0\n    catch_all: true\n    write_rules: []\ntitle_weight: 100.0\ntext_fields:\n  - body\nhierarchy_relationship: PART_OF\nno_self_loop_relationships: []\nhealth_required_fields:\n  - body\nstaleness_threshold_days: 90\nwrite_rules: []\n";
    std::fs::write(
            pkg.join("types").join("claim.yaml"),
            format!(
                "name: claim\ndescription: t\nwhen_to_use: tests\nmetadata_fields: []\nupdatable_fields:\n  - title\n  - body\n{body}signals:\n  - name: attack_load\n    kind: edge_load\n    relationships: [REBUTS]\n    direction: in\n    thresholds:\n      - at_least: 1\n        level: notice\n      - at_least: 3\n        level: warn\n  - name: open_objections\n    kind: edge_load\n    relationships: [REBUTS]\n    direction: in\n    neighbour_field: state\n    neighbour_value: open\n    thresholds:\n      - at_least: 1\n        level: notice\n"
            ),
        )
        .unwrap();
    std::fs::write(
            pkg.join("types").join("objection.yaml"),
            format!(
                "name: objection\ndescription: t\nwhen_to_use: tests\nmetadata_fields:\n  - key: state\n    description: objection lifecycle\n    field_type: string\n    enum_values: [open, closed]\nupdatable_fields:\n  - title\n  - body\n  - state\n{body}"
            ),
        )
        .unwrap();
    let mem_dir = tmp.path().join("mem");
    std::fs::create_dir_all(&mem_dir).unwrap();
    let writer = FilesystemBackend::new(mem_dir.clone());
    let mount = crate::workspace::Mount {
        mem: "arg".to_string(),
        schema: Some(memstead_schema::SchemaRef::new(
            "argsig",
            semver::Version::new(0, 1, 0),
        )),
        storage: crate::workspace::MountStorage::Folder { path: mem_dir },
        capability: crate::workspace::MountCapability::Write,
        lifecycle: crate::workspace::MountLifecycle::Eager,
        cross_linkable: true,
        migration_target: None,
    };
    Engine::from_mounts_with_schemas_dir(
        vec![(mount, Box::new(writer) as Box<dyn MemBackend>)],
        Some(&schemas_dir),
    )
    .unwrap()
}

fn objection_args(title: &str, state: Option<&str>, rebuts: Option<&str>) -> CreateEntityArgs {
    let mut sections = IndexMap::new();
    sections.insert("body".to_string(), "an objection body.".to_string());
    let mut metadata = IndexMap::new();
    if let Some(s) = state {
        metadata.insert("state".to_string(), s.to_string());
    }
    let relations = rebuts
        .map(|to| {
            vec![crate::ops::RelateArg {
                target: crate::entity::EntityId(to.to_string()),
                rel_type: "REBUTS".to_string(),
                description: None,
            }]
        })
        .unwrap_or_default();
    CreateEntityArgs {
        anchors: Vec::new(),
        mem: "arg".to_string(),
        title: title.to_string(),
        entity_type: "objection".to_string(),
        sections,
        metadata,
        relations,
        dry_run: false,
    }
}

fn crossing_warnings_of(warnings: &[WarningHint]) -> Vec<(String, String, u64, String, String)> {
    warnings
        .iter()
        .filter_map(|w| match w {
            WarningHint::SignalThresholdCrossed {
                entity_id,
                signal,
                value,
                old_level,
                new_level,
            } => Some((
                entity_id.to_string(),
                signal.clone(),
                *value,
                old_level.clone(),
                new_level.clone(),
            )),
            _ => None,
        })
        .collect()
}

/// Signals on reads: thresholds map boundary counts to levels, the
/// neighbour filter counts only qualifying counterparts, the two
/// serving channels carry headline + contributors, a flip of the
/// counterpart's field changes the count on the next read, and two
/// engine instances over the same on-disk state serve identical
/// payloads.
#[test]
fn signals_reads_thresholds_neighbour_filter_and_determinism() {
    let tmp = TempDir::new().unwrap();
    let mut engine = engine_with_signals_schema(&tmp);
    let (actor, client) = cli_actor();

    let mut claim_sections = IndexMap::new();
    claim_sections.insert("body".to_string(), "a claim body.".to_string());
    engine
        .create_entity(
            CreateEntityArgs {
                anchors: Vec::new(),
                mem: "arg".to_string(),
                title: "Claim".to_string(),
                entity_type: "claim".to_string(),
                sections: claim_sections,
                metadata: IndexMap::new(),
                relations: vec![],
                dry_run: false,
            },
            actor,
            Some(&client),
            None,
        )
        .unwrap();
    let claim_id = crate::entity::EntityId("arg--claim".to_string());
    let sig_of = |engine: &Engine, name: &str| {
        let entity = engine.get_entity(&claim_id).unwrap().clone();
        engine
            .computed_signals(&entity)
            .unwrap()
            .into_iter()
            .find(|s| s.name == name)
            .unwrap()
    };

    // Below the first threshold: value 0, level none.
    let s = sig_of(&engine, "attack_load");
    assert_eq!((s.value, s.level_wire()), (0, "none"));

    // First objection (open, inline REBUTS): the create's crossing
    // warnings name BOTH signals moving none → notice on the claim.
    let outcome = engine
        .create_entity(
            objection_args("Obj One", Some("open"), Some("arg--claim")),
            actor,
            Some(&client),
            None,
        )
        .unwrap();
    let crossings = crossing_warnings_of(&outcome.warnings);
    assert!(
        crossings.contains(&(
            "arg--claim".to_string(),
            "attack_load".to_string(),
            1,
            "none".to_string(),
            "notice".to_string()
        )),
        "create with inline relation crosses attack_load: {crossings:?}"
    );
    assert!(
        crossings.iter().any(|c| c.1 == "open_objections"),
        "open counterpart crosses open_objections too: {crossings:?}"
    );

    // Closed and field-less counterparts count for attack_load,
    // never for open_objections.
    engine
        .create_entity(
            objection_args("Obj Two", Some("closed"), Some("arg--claim")),
            actor,
            Some(&client),
            None,
        )
        .unwrap();
    engine
        .create_entity(
            objection_args("Obj Three", None, Some("arg--claim")),
            actor,
            Some(&client),
            None,
        )
        .unwrap();
    let attack = sig_of(&engine, "attack_load");
    assert_eq!((attack.value, attack.level_wire()), (3, "warn"));
    assert_eq!(attack.contributors.len(), 3);
    let open = sig_of(&engine, "open_objections");
    assert_eq!((open.value, open.level_wire()), (1, "notice"));
    assert_eq!(open.contributors[0].0, "arg--obj-one");

    // Both serving channels: frontmatter headline + `## Signals`
    // contributors on the text channel; `_signals` on the envelope.
    let entity = engine.get_entity(&claim_id).unwrap().clone();
    let signals = engine.computed_signals(&entity).unwrap();
    let md = crate::render::render_entity_markdown_with_signals(
        &entity,
        None,
        Some(&signals),
        None,
        None,
    );
    assert!(
        md.contains("_signals: [attack_load: 3 (warn), open_objections: 1 (notice)]"),
        "frontmatter headline: {md}"
    );
    assert!(md.contains("## Signals"), "contributors section: {md}");
    assert!(md.contains("arg--obj-one"), "evidence ships: {md}");
    let env = crate::render::build_entity_envelope(
        &entity,
        0,
        None,
        None,
        None,
        crate::render::OriginClass::FirstParty,
        engine.store().outgoing(&claim_id),
        None,
        Some(&signals),
        None,
    );
    assert_eq!(env["_signals"][0]["name"], "attack_load");
    assert_eq!(env["_signals"][0]["value"], 3);
    assert_eq!(env["_signals"][0]["level"], "warn");
    assert_eq!(
        env["_signals"][0]["contributors"].as_array().unwrap().len(),
        3
    );
    // The canonical form stays signal-free.
    let canonical = crate::render::render_entity_markdown(&entity, None);
    assert!(
        !canonical.contains("_signals"),
        "canonical form is signal-free"
    );

    // Flipping the counterpart's field changes the count on the
    // next read, and the update carries the crossing for the CLAIM.
    let obj_one = crate::entity::EntityId("arg--obj-one".to_string());
    let current = engine.get_entity(&obj_one).unwrap().content_hash.clone();
    let mut metadata = IndexMap::new();
    metadata.insert("state".to_string(), "closed".to_string());
    let outcome = engine
        .update_entity(
            crate::engine::UpdateEntityArgs {
                anchors: Vec::new(),
                id: obj_one,
                expected_hash: crate::ExpectedHash::Current(current),
                sections: IndexMap::new(),
                append_sections: IndexMap::new(),
                patch_sections: IndexMap::new(),
                sections_unset: Vec::new(),
                metadata,
                metadata_unset: Vec::new(),
                declare_relations: vec![],
                dry_run: false,
                relations_unset: Vec::new(),
                anchors_unset: Vec::new(),
            },
            actor,
            Some(&client),
            None,
        )
        .unwrap();
    assert!(!outcome.write_id.is_empty(), "success shape kept");
    let crossings = crossing_warnings_of(&outcome.warnings);
    assert!(
        crossings.contains(&(
            "arg--claim".to_string(),
            "open_objections".to_string(),
            0,
            "notice".to_string(),
            "none".to_string()
        )),
        "the neighbour flip crosses the claim's filtered signal: {crossings:?}"
    );
    let open = sig_of(&engine, "open_objections");
    assert_eq!((open.value, open.level_wire()), (0, "none"));

    // Determinism: a second instance over the same on-disk state
    // serves an identical payload.
    let engine_b = engine_with_signals_schema(&tmp);
    let entity_b = engine_b.get_entity(&claim_id).unwrap().clone();
    let signals_b = engine_b.computed_signals(&entity_b).unwrap();
    let entity_a = engine.get_entity(&claim_id).unwrap().clone();
    let signals_a = engine.computed_signals(&entity_a).unwrap();
    assert_eq!(
        crate::ops::signals::signals_json(&signals_a),
        crate::ops::signals::signals_json(&signals_b),
        "two instances over the same mem state serve identical signals"
    );
}

/// Crossings on the relate surface: upward and downward crossings
/// warn with the full detail set; a write that crosses nothing
/// carries nothing signal-shaped; the mutation stays the success
/// shape throughout. The `signals` health axis serves only
/// above-`none` entities, with per-level counts and a mem filter.
#[test]
fn signal_crossings_on_relate_and_health_axis() {
    let tmp = TempDir::new().unwrap();
    let mut engine = engine_with_signals_schema(&tmp);
    let (actor, client) = cli_actor();

    let mut claim_sections = IndexMap::new();
    claim_sections.insert("body".to_string(), "a claim body.".to_string());
    engine
        .create_entity(
            CreateEntityArgs {
                anchors: Vec::new(),
                mem: "arg".to_string(),
                title: "Claim".to_string(),
                entity_type: "claim".to_string(),
                sections: claim_sections,
                metadata: IndexMap::new(),
                relations: vec![],
                dry_run: false,
            },
            actor,
            Some(&client),
            None,
        )
        .unwrap();
    for (t, s) in [("Obj A", "open"), ("Obj B", "closed"), ("Obj C", "closed")] {
        engine
            .create_entity(objection_args(t, Some(s), None), actor, Some(&client), None)
            .unwrap();
    }
    let relate = |engine: &mut Engine, from: &str, remove: bool| {
        engine
            .relate_entity(
                crate::engine::RelateEntityArgs {
                    source: crate::entity::EntityId(from.to_string()),
                    target: crate::entity::EntityId("arg--claim".to_string()),
                    rel_type: "REBUTS".to_string(),
                    description: None,
                    remove,
                    expected_hash: None,
                    dry_run: false,
                },
                actor,
                Some(&client),
                None,
            )
            .unwrap()
    };

    // 0 → 1: none → notice (upward), on the TARGET of the edge.
    let outcome = relate(&mut engine, "arg--obj-a", false);
    assert!(!outcome.write_id.is_empty());
    let crossings = crossing_warnings_of(&outcome.warnings);
    assert!(
        crossings.contains(&(
            "arg--claim".to_string(),
            "attack_load".to_string(),
            1,
            "none".to_string(),
            "notice".to_string()
        )),
        "{crossings:?}"
    );

    // 1 → 2: notice → notice — nothing signal-shaped rides.
    let outcome = relate(&mut engine, "arg--obj-b", false);
    assert!(
        crossing_warnings_of(&outcome.warnings).is_empty(),
        "no threshold crossed, no warning: {:?}",
        outcome.warnings
    );

    // 2 → 3: notice → warn.
    let outcome = relate(&mut engine, "arg--obj-c", false);
    let crossings = crossing_warnings_of(&outcome.warnings);
    assert!(
        crossings.contains(&(
            "arg--claim".to_string(),
            "attack_load".to_string(),
            3,
            "notice".to_string(),
            "warn".to_string()
        )),
        "{crossings:?}"
    );

    // Health axis at warn: the claim is the one above-`none`
    // entity; counts split per level; a mem filter narrows.
    let axis = engine.health_signals_axis(None);
    assert_eq!(axis["entities"].as_array().unwrap().len(), 1);
    assert_eq!(axis["entities"][0]["id"], "arg--claim");
    assert_eq!(axis["counts"]["warn"], 1, "attack_load at warn: {axis}");
    assert_eq!(axis["counts"]["notice"], 1, "open_objections at notice");
    let filtered = engine.health_signals_axis(Some("other"));
    assert!(filtered["entities"].as_array().unwrap().is_empty());

    // 3 → 2: warn → notice (downward crossing warns too).
    let outcome = relate(&mut engine, "arg--obj-c", true);
    let crossings = crossing_warnings_of(&outcome.warnings);
    assert!(
        crossings.contains(&(
            "arg--claim".to_string(),
            "attack_load".to_string(),
            2,
            "warn".to_string(),
            "notice".to_string()
        )),
        "{crossings:?}"
    );
}

/// Regression pin for `no_self_loop_relationships`' single
/// functional behavior: a self-loop (`from == to`) on a rel-type
/// the source type lists there refuses with `RELATIONSHIP_CYCLE`.
/// The constraint vocabulary settles the field's semantics — the
/// new propagation declaration gets a distinct name, and this pin
/// guards that the old field keeps exactly this effect.
#[test]
fn no_self_loop_rel_type_self_loop_refusal_is_pinned() {
    let tmp = TempDir::new().unwrap();
    // The `constr` fixture declares `no_self_loop_relationships:
    // [PART_OF]` on `task`.
    let mut engine = engine_with_constraints_schema(&tmp, "warn", "warn");
    let (actor, client) = cli_actor();
    let a = engine
        .create_entity(
            task_create_args("Task A", vec![]),
            actor,
            Some(&client),
            None,
        )
        .unwrap();
    let err = engine
        .relate_entity(
            crate::engine::RelateEntityArgs {
                source: a.id.clone(),
                target: a.id.clone(),
                rel_type: "PART_OF".to_string(),
                description: None,
                remove: false,
                expected_hash: None,
                dry_run: false,
            },
            actor,
            Some(&client),
            None,
        )
        .unwrap_err();
    assert_eq!(err.code(), "RELATIONSHIP_CYCLE");
}

/// A write whose schema declares aggregate signals reads every mem for
/// its crossing warnings, so it holds every mem's lock, as a write under
/// an acyclicity law does: it waits for a writer holding another mem's
/// lock, where it read that mem without its lock and could warn from a
/// view the other writer was changing.
#[test]
fn a_write_with_aggregate_signals_waits_for_every_mems_lock() {
    let tmp = TempDir::new().unwrap();
    drop(engine_with_signals_schema(&tmp));
    let schemas_dir = tmp.path().join("schemas");
    let mount = |mem: &str, pin: memstead_schema::SchemaRef| {
        let dir = tmp.path().join(mem);
        std::fs::create_dir_all(&dir).unwrap();
        (
            crate::workspace::Mount {
                mem: mem.to_string(),
                schema: Some(pin),
                storage: crate::workspace::MountStorage::Folder { path: dir.clone() },
                capability: crate::workspace::MountCapability::Write,
                lifecycle: crate::workspace::MountLifecycle::Eager,
                cross_linkable: true,
                migration_target: None,
            },
            Box::new(FilesystemBackend::new(dir)) as Box<dyn MemBackend>,
        )
    };
    let mut engine = Engine::from_mounts_with_schemas_dir(
        vec![
            mount(
                "mem",
                memstead_schema::SchemaRef::new("argsig", semver::Version::new(0, 1, 0)),
            ),
            mount(
                "other",
                memstead_schema::SchemaRef::new("default", semver::Version::new(1, 0, 0)),
            ),
        ],
        Some(&schemas_dir),
    )
    .unwrap();
    let other_lock = std::fs::canonicalize(tmp.path().join("other"))
        .unwrap()
        .join(".memstead/locks/write.lock");
    std::fs::create_dir_all(other_lock.parent().unwrap()).unwrap();

    let (held_tx, held_rx) = std::sync::mpsc::channel();
    let holder = std::thread::spawn(move || {
        let f = std::fs::OpenOptions::new()
            .read(true)
            .write(true)
            .create(true)
            .truncate(false)
            .open(&other_lock)
            .unwrap();
        f.lock().unwrap();
        held_tx.send(()).unwrap();
        std::thread::sleep(std::time::Duration::from_millis(1500));
        f.unlock().unwrap();
    });
    held_rx.recv().unwrap();

    let started = std::time::Instant::now();
    let (actor, client) = cli_actor();
    let mut args = objection_args("Waits", Some("open"), None);
    args.mem = "mem".to_string();
    engine
        .create_entity(args, actor, Some(&client), None)
        .expect("the write lands once the other lock is free");
    let waited = started.elapsed();
    holder.join().unwrap();
    assert!(
        waited >= std::time::Duration::from_millis(1000),
        "the write did not wait for the other mem's lock ({waited:?})"
    );
}