memstead-engine 0.7.0

Full engine extension for Memstead — multi-mem policy, mem management, cross-mem-link resolution, lifecycle. Depends on memstead-base. Internal library surface consumed by the memstead binaries — pre-1.0, experimental, 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
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
//! Mem-lifecycle orchestrator — full home for the multi-mem create
//! and delete pipelines. The matcher primitives
//! ([`memstead_base::CreateRuleSet`], [`memstead_base::DeleteRuleSet`],
//! [`memstead_base::MatcherSet`]) stay in lean because the lean engine's
//! `cross_mem_link_allowed` synthesises a [`memstead_base::CreateRuleSet`]
//! on multi-folder workspaces. Only the lifecycle orchestrators —
//! `create_mem`, `delete_mem`, their param/response types, the
//! shared `NOTE_MAX_LEN` cap, and the `validate_mem_path` helper —
//! live here.
//!
//! Functions take `&mut memstead_base::Engine` directly rather than going
//! through a `FullEngine` wrapper struct: the lean engine is a single
//! polymorphic `Engine` parameterised by `Box<dyn MemBackend>` and
//! already carries every state field the orchestrators need
//! (`mem_router`, `settings`, `backend_factory`, `workspace_root`,
//! `git_branch_ops`). Full contributes lifecycle as free functions over
//! that engine; no separate engine type, no policy-provider trait.
//!
//! Return type is `Result<_, crate::FullEngineError>`. Lean-side
//! failures (`InvalidInput`, `UnknownMem`, `SchemaResolverInit`,
//! `SchemaNotFound`, `MemNameCollision`, `Mem(_)`, `Backend(_)`)
//! propagate verbatim through `FullEngineError::Lean(_)` via the
//! `#[from] memstead_base::EngineError` conversion — the `?` operator on
//! `engine.persist_state()?` and similar lean calls does the wrap
//! automatically. The four lifecycle-only variants
//! (`MemPathNotAllowed`, `MemReferencedByPolicy`, `MemSchemaNotAllowed`,
//! `ConfigAlreadyExists`) are constructed as `FullEngineError::*`
//! directly; they no longer live in `memstead_base::EngineError`.

use memstead_base::mem_management::{CreateRuleSet, DeleteRuleSet};

use crate::FullEngineError;

/// Note-length cap shared with `memstead_create` / `memstead_update` / full's
/// lifecycle orchestrators. Mirrors `memstead_git_branch::NOTE_MAX_LEN`.
pub const NOTE_MAX_LEN: usize = 280;

/// Compose an ISO-8601 UTC timestamp (`YYYY-MM-DDTHH:MM:SSZ`) for the
/// current wall clock. Used to stamp the `unregistered_at` tombstone
/// on `memstead mem unregister`. Hand-rolled to avoid a
/// chrono / time dependency — the codebase already calculates the
/// date portion in `memstead_base::entity::generator` via the same
/// epoch-day algorithm; this adds the time-of-day suffix.
fn now_iso_utc() -> String {
    let dur = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap_or_default();
    let total_secs = dur.as_secs();
    let days = total_secs / 86_400;
    let rem = total_secs - days * 86_400;
    let hours = rem / 3_600;
    let mins = (rem % 3_600) / 60;
    let secs = rem % 60;
    let (year, month, day) = days_to_ymd(days);
    format!("{year:04}-{month:02}-{day:02}T{hours:02}:{mins:02}:{secs:02}Z")
}

/// Result shape of the storage-residue probe
/// `residue_probe_for_workspace` performs at Step 2b of
/// `create_mem`. `Present` carries the diagnostic payload the
/// `MEM_STORAGE_RESIDUE_DETECTED` error envelope renders, plus the
/// parsed existing config (for tombstone + reattach branches).
enum ResidueProbe {
    None,
    Present {
        branch_ref: String,
        config_blob: Option<String>,
        existing_config: Option<Box<memstead_schema::config::MemConfig>>,
    },
}

/// Probe the workspace's mem-repo for pre-existing storage at the
/// composed `branch_full_path`. Returns `None` when the workspace
/// lacks a mem-repo (folder-only) or when nothing exists at the
/// path; otherwise returns the residue payload the create-side
/// orchestrator routes against `(recovery, tombstone)` to pick a
/// path.
///
/// Implementation routes through the engine's installed backend
/// factory rather than calling `memstead-git-branch` directly — that
/// keeps `memstead-engine` decoupled from the git-branch crate (the
/// layer-above-backend posture matches the rest of `mem_management`,
/// which delegates backend instantiation through the same factory).
/// `backend.read_mem_config()` for a git-branch mount lifts
/// `__MEMSTEAD:mems/<branch_full_path>/config.json`'s bytes — present
/// iff residue exists at this exact path. Folder backends return
/// `None` here (their residue is `<location>/.memstead/config.json`
/// which Step 4 below catches separately via `ConfigAlreadyExists`).
/// Failures from the probe collapse to `None` so the create flow
/// falls through to its prior behaviour (the seed-commit step's
/// existing `HashMismatch` is the fallback safety net).
fn residue_probe_for_workspace(
    engine: &memstead_base::Engine,
    workspace_root: Option<&std::path::Path>,
    branch_full_path: &str,
    mem_name: &str,
    canonical_schema_ref: &memstead_schema::SchemaRef,
) -> ResidueProbe {
    let Some(root) = workspace_root else {
        return ResidueProbe::None;
    };
    let gitdir = root.join("mem-repo").join(".git");
    if !gitdir.is_dir() {
        return ResidueProbe::None;
    }
    let canonical_gitdir = gitdir.canonicalize().unwrap_or(gitdir);
    let probe_mount = memstead_base::workspace::Mount {
        migration_target: None,
        mem: mem_name.to_string(),
        schema: Some(canonical_schema_ref.clone()),
        storage: memstead_base::workspace::MountStorage::GitBranch {
            gitdir: canonical_gitdir,
            branch: format!("refs/heads/{branch_full_path}"),
        },
        capability: memstead_base::workspace::MountCapability::Write,
        lifecycle: memstead_base::workspace::MountLifecycle::Eager,
        cross_linkable: true,
    };
    let factory = engine.backend_factory();
    let backend = match factory(&probe_mount) {
        Ok(b) => b,
        Err(_) => return ResidueProbe::None,
    };
    let bytes = match backend.read_mem_config() {
        Ok(Some(b)) => b,
        Ok(None) | Err(_) => return ResidueProbe::None,
    };
    let existing_config = serde_json::from_slice::<memstead_schema::config::MemConfig>(&bytes)
        .ok()
        .map(Box::new);
    ResidueProbe::Present {
        branch_ref: format!("refs/heads/{branch_full_path}"),
        config_blob: Some(format!("__MEMSTEAD:mems/{branch_full_path}/config.json")),
        existing_config,
    }
}

/// Days-since-epoch → (Y, M, D). Algorithm from
/// http://howardhinnant.github.io/date_algorithms.html — same one
/// `memstead_base::entity::generator::days_to_ymd` uses; replicated here
/// to keep the function private to the orchestrator without
/// re-exporting from lean.
fn days_to_ymd(days: u64) -> (u64, u64, u64) {
    let z = days + 719_468;
    let era = z / 146_097;
    let doe = z - era * 146_097;
    let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
    let y = yoe + era * 400;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
    let mp = (5 * doy + 2) / 153;
    let d = doy - (153 * mp + 2) / 5 + 1;
    let m = if mp < 10 { mp + 3 } else { mp - 9 };
    let y = if m <= 2 { y + 1 } else { y };
    (y, m, d)
}

// ---------------------------------------------------------------------------
// `memstead_mem_delete` orchestration
// ---------------------------------------------------------------------------

/// Parameters for [`delete_mem`]. Mirrors the `memstead_mem_delete`
/// MCP tool's wire shape 1:1, plus a transport-side `operator_mode`
/// flag the wire shape does not expose.
#[derive(Debug, Clone)]
pub struct MemDeleteParams {
    /// Name of the mem to unregister. Must resolve in the current
    /// snapshot — unknown names surface as `UnknownMem`.
    pub name: String,
    /// When `true`, remove the mem's on-disk directory (folder
    /// backends only) after unregistering. Default `false` —
    /// unregister-only.
    pub delete_files: bool,
    /// Agent-authored provenance note (≤[`NOTE_MAX_LEN`] chars).
    pub note: Option<String>,
    /// Process-scoped operator-mode posture. When `true`, the
    /// orchestrator skips the `[[mem_management.delete]]` allowlist
    /// gate. Every other check (input validation, name resolution,
    /// `MEM_REFERENCED_BY_POLICY`, backend cleanup) runs
    /// identically — the policy safeguard is now gated by
    /// `delete_files: true` instead of `!operator_mode`, so the
    /// CLI's `mem delete` (operator-mode) still hits the refusal
    /// when cross-mem grants point at the target. Set only by
    /// transports that established operator intent at boot
    /// (`memstead-mcp --operator-mode`); never accepted as a wire-shape
    /// input from agents. Defaults to `false` — agent-mode.
    pub operator_mode: bool,
    /// Mem-replacement affordance. When `true`, incoming cross-mem
    /// edges from surviving Write-Mems do not refuse the delete
    /// (`MEM_HAS_INCOMING_REFS` is skipped): the referrers' files
    /// stay untouched, their edges degrade to unresolved stub
    /// targets in the in-memory index, and a later same-name
    /// re-creation re-adopts them — the intended flow when a mem is
    /// re-homed (backend or location change) under a stable name.
    /// The detached referrers are reported on
    /// [`MemDeleteResponse::detached_referrers`] so the caller can
    /// verify re-adoption after the successor mem mounts. Default
    /// `false` — the refusal stands.
    pub detach_incoming: bool,
}

/// Response shape from [`delete_mem`].
#[derive(Debug, Clone)]
pub struct MemDeleteResponse {
    pub name: String,
    /// Always `true` on successful return — the snapshot swap
    /// happened.
    pub deleted_from_router: bool,
    /// `true` when `delete_files` was `true` AND the directory was
    /// removed cleanly; `false` otherwise (delete_files false, or
    /// removal errored, or backend has no on-disk directory).
    pub files_deleted: bool,
    /// Non-fatal findings emitted during the disk-cleanup step.
    /// Populated when `delete_files: true` was requested but
    /// [`Self::files_deleted`] ended `false` — distinguishes the
    /// mem-db-no-op case from the rmdir-failure case so an agent
    /// reading `files_deleted: false` doesn't trigger redundant
    /// cleanup attempts. Empty when nothing surprised the operation
    /// (e.g. `delete_files: false`, or `delete_files: true` and rmdir
    /// succeeded).
    pub warnings: Vec<memstead_base::ops::WarningHint>,
    /// Dangling `[cross_mem_links]` grants scrubbed from
    /// `.memstead/workspace.toml` on a destructive delete. Surfacing
    /// the scrub here gives the agent a one-round-trip view of every
    /// policy side effect. Only dangling cross-link grants are scrubbed
    /// (and reported here); the `[[mem_management.*]]` allowlist rules
    /// are preserved, so a later re-create of the same name needs no
    /// fresh `allow-create`. Empty `[]` when no cross-link grant named
    /// the deleted mem.
    pub allowlist_entries_removed: Vec<AllowlistEntryRemoved>,
    /// Write-Mem referrers whose cross-mem edges into the deleted mem
    /// were deliberately left dangling under
    /// [`MemDeleteParams::detach_incoming`] — one entry per source
    /// entity, `rel_types` aggregating every detached edge type. The
    /// referrers' files are untouched; their edges resolve to stubs
    /// until a same-name re-creation re-adopts them. Always empty
    /// when `detach_incoming` was `false` (the refusal fires
    /// instead).
    pub detached_referrers: Vec<memstead_base::ReferrerInfo>,
}

/// One scrubbed `.memstead/workspace.toml` entry surfaced on
/// [`MemDeleteResponse::allowlist_entries_removed`]. Only dangling
/// `[cross_mem_links]` grants are scrubbed, so `table` is always
/// `"cross_mem_links"` and `from` / `to` name the directionality the
/// grant established (`from` is the table key, `to` is the array
/// element or wildcard). The `pattern` field is retained on the stable
/// response shape but is no longer populated — the
/// `[[mem_management.*]]` allowlist rules are preserved across a
/// delete and therefore never reported here.
#[derive(Debug, Clone, serde::Serialize, PartialEq, Eq)]
pub struct AllowlistEntryRemoved {
    /// Section in `.memstead/workspace.toml` the scrubbed entry came
    /// from. Always `"cross_mem_links"` — the only class scrubbed on
    /// delete.
    pub table: String,
    /// Retained on the response shape for stability but never
    /// populated since the `[[mem_management.*]]` allowlist rules
    /// are preserved across a delete. Always `None`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub pattern: Option<String>,
    /// Cross-link source mem — the grant's table key.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub from: Option<String>,
    /// Cross-link target — the deleted mem when scrubbed from a
    /// peer's list, or `"*"` when a wildcard grant got dropped.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub to: Option<String>,
}

/// Unregister a writable mem at runtime. The unified-engine
/// counterpart to full's `memstead_git_branch::mem_management::delete_mem`.
///
/// Ordering guarantees mirror full's:
/// 1. Pre-mutation checks (input validation, name resolution,
///    allowlist match). Any failure here leaves the engine untouched
///    and performs zero filesystem writes.
/// 2. Router unregister (snapshot swap via
///    [`memstead_base::Engine::unregister_writable_mem`]). After this the
///    mem is no longer visible to readers. The unregister hands
///    back the backend handle so step 3 can drive backend-side
///    cleanup without re-resolving the mount.
/// 3. Optional disk delete. A failure here is non-fatal: the mem
///    is already unregistered, the leftover artifacts are a
///    follow-up concern, and the response reports `files_deleted: false`
///    with a typed `MEM_FILES_NOT_DELETED` warning naming what
///    survived.
///    - Folder mount: `remove_dir_all(location)` removes the mem
///      directory. `backend.delete_artifacts()` is a no-op (folder
///      backends keep the default impl).
///    - Mem-db-backed (git-branch) mount: `backend.delete_artifacts()`
///      drops `refs/heads/<branch_leaf>` and prunes
///      `__MEMSTEAD:mems/<branch_leaf>/config.json`. There is no
///      on-disk directory to rmdir.
///
///    `files_deleted: true` reflects "every backend-visible artifact
///    for this mem has been removed" — the wire shape is unchanged
///    but the semantic now covers both backends symmetrically.
///
/// Operator-mode bypass. When [`MemDeleteParams::operator_mode`] is
/// `true`, Step 2 (`[[mem_management.delete]]` allowlist match) is
/// skipped. All other steps run identically — including input
/// validation, name resolution, the policy safeguard, router
/// unregister, backend cleanup, and persistence. The flag is set by
/// the transport that established operator intent at boot (today,
/// `memstead-mcp --operator-mode`) and is not exposed as a wire-shape
/// input.
///
/// Policy safeguard. Step 3 (`MEM_REFERENCED_BY_POLICY`) fires when
/// `delete_files: true` AND another writable mem has a
/// `cross_mem_links` grant pointing into the target. The gating is
/// independent of `operator_mode`: storage destruction would orphan
/// the grant, so the refusal is a hard stop until the grant is
/// revoked. When `delete_files: false` (router-only unregister), the
/// storage survives and the grant remains valid against it — the
/// check is skipped. This matches the verb split exposed at the CLI
/// layer (`mem unregister` is the verb that produces `delete_files:
/// false`; `mem delete` is the verb that produces `delete_files:
/// true`).
///
/// Hierarchical candidate composition is symmetric with
/// `create_mem`: the router records the create-time `path` on
/// each writable entry, and Step 2 below reads it back via
/// [`memstead_base::MemRouterSnapshot::mem_path_for_mem`] to assemble
/// the same `<mem_path>/<name>` (or bare `<name>`) string the
/// create-side composer matched against.
pub fn delete_mem(
    engine: &mut memstead_base::Engine,
    params: MemDeleteParams,
) -> Result<MemDeleteResponse, FullEngineError> {
    // ---- Step 0: input validation ----
    if let Some(note) = params.note.as_deref()
        && note.chars().count() > NOTE_MAX_LEN
    {
        return Err(memstead_base::EngineError::InvalidInput(format!(
            "note exceeds {NOTE_MAX_LEN} characters"
        ))
        .into());
    }

    // Populated only under `detach_incoming: true` — see Step 3a.
    let mut detached_referrers: Vec<memstead_base::ReferrerInfo> = Vec::new();

    // ---- Step 1: resolve name ----
    if !engine.mem_router().is_writable(&params.name) {
        return Err(memstead_base::EngineError::UnknownMem(params.name.clone()).into());
    }

    // ---- Step 2: allowlist match ----
    // Snapshot the on-disk dir (folder mounts only) and the
    // create-time hierarchical `mem_path`. The lifecycle candidate
    // composes as `<mem_path>/<name>` when a path was recorded at
    // registration, falling back to the bare `<name>` for flat-layout
    // mems — the same shape `create_mem` matched against the rule
    // list. Symmetric on the engine side; closes the asymmetry that
    // previously left hierarchical runtime mems un-deletable.
    //
    // Operator-mode skips the allowlist match entirely. The mem_dir
    // is still resolved because Step 5 needs it for the rmdir step.
    let mem_dir: Option<std::path::PathBuf> = engine
        .mem_router()
        .dir_for_mem(&params.name)
        .map(|p| p.to_path_buf());

    if !params.operator_mode {
        // Hierarchical paths are first-class mem identifiers.
        // `params.name` is already the full path (e.g.
        // `team/sub-mem`) — no separate `mem_path` composition
        // step needed. The delete-side lifecycle candidate IS the
        // mem name.
        let attempted = mem_dir
            .clone()
            .unwrap_or_else(|| std::path::PathBuf::from(format!("(mem: {})", params.name)));
        let candidate: String = params.name.clone();

        let delete_rule_set = DeleteRuleSet::new(engine.settings().mem_delete_rules.clone())
            .map_err(|e| {
                memstead_base::EngineError::InvalidInput(format!("mem_delete_rules: {e}"))
            })?;
        let patterns_for_errors: Vec<String> = delete_rule_set.patterns();

        if delete_rule_set.is_empty() {
            return Err(FullEngineError::MemPathNotAllowed {
                attempted,
                candidate,
                patterns: patterns_for_errors,
                reason: "no_allowlist_configured",
                policy_table: "mem_management.delete",
            });
        }
        if delete_rule_set
            .first_match(std::path::Path::new(&candidate))
            .is_none()
        {
            return Err(FullEngineError::MemPathNotAllowed {
                attempted,
                candidate,
                patterns: patterns_for_errors,
                reason: "no_match",
                policy_table: "mem_management.delete",
            });
        }
    }

    // ---- Step 3: MEM_REFERENCED_BY_POLICY check ----
    // Walk the workspace's `cross_mem_links` setting and refuse to
    // delete a mem that any other visible writable mem is
    // permitted to link into. Reads the workspace-level policy
    // directly rather than per-mem `effective_cross_links` (the
    // per-mem projection that composes workspace policy with
    // create-rule defaults) — for workspaces that only configure
    // links via the workspace-level `[cross_mem_links]` section
    // (the common case), the two are equivalent.
    //
    // The check gates on `delete_files: true` rather than
    // `!operator_mode`. The
    // safeguard protects against orphaning a grant by destroying the
    // storage it relies on; when `delete_files: false` (router-only
    // unregister), the storage survives so grants remain valid and
    // re-activate on re-init. The new CLI verb `memstead mem
    // unregister` maps to this branch unconditionally; the CLI verb
    // `memstead mem delete` maps to the storage-destruction branch
    // where the check fires regardless of `operator_mode` (the
    // operator is presumed to have surveyed the link graph, but a
    // hard stop forces an explicit revoke-first flow).
    if params.delete_files {
        use memstead_schema::workspace_config::CrossLinkValue;
        let mut referring_mems: Vec<String> = engine
            .settings()
            .cross_mem_links
            .iter()
            .filter_map(|(referring, policy)| {
                if referring == &params.name {
                    return None;
                }
                match policy {
                    CrossLinkValue::List(targets) => {
                        if targets.iter().any(|t| t == &params.name) {
                            Some(referring.clone())
                        } else {
                            None
                        }
                    }
                    _ => None,
                }
            })
            .collect();
        referring_mems.sort();
        referring_mems.dedup();
        if !referring_mems.is_empty() {
            return Err(FullEngineError::MemReferencedByPolicy {
                name: params.name,
                referring_mems,
            });
        }
    }

    // ---- Step 3a: MEM_HAS_INCOMING_REFS check ----
    // The policy check above closes the workspace-policy axis ("is this
    // mem still grant-pointed-at?") but not the edge-graph axis
    // ("does any actual entity still point at this mem's entities?").
    // Revoking a grant is independent of removing the edges. Without
    // this step, a mem whose grant was revoked but whose surviving
    // Write-Mem peers still carry `DEPENDS_ON → target_mem--*`
    // edges deletes cleanly, leaving dangling cross-mem edges that
    // resolve to nothing.
    //
    // The scan walks every entity in the doomed mem, collects each
    // entity's incoming edges, partitions out same-mem and ReadOnly-
    // mount referrers, and groups the remaining Write-Mem referrers
    // by source-entity id (one [`memstead_base::ReferrerInfo`] per source,
    // `rel_types` aggregating every offending edge type). Same shape
    // as entity-level `HasIncomingRefs` — see [`memstead_base::EngineError::MemHasIncomingRefs`]
    // for the refusal-with-recovery contract. Fires regardless of
    // `delete_files` because a router-only unregister with stale edges
    // is just as broken as a storage-destruction with stale edges —
    // either way, surviving entities point at a mem the engine no
    // longer routes to.
    {
        use std::collections::BTreeSet;

        // Source-id is grouped via a `Vec` of `(EntityId, BTreeSet<rel_type>)`
        // pairs keyed by the id's string form — EntityId itself isn't
        // `Ord` (no full lexical ordering defined), but its string
        // form sorts deterministically and is what the wire envelope
        // serialises anyway.
        let store = engine.store();
        let mut by_source: std::collections::BTreeMap<
            String,
            (memstead_base::EntityId, BTreeSet<String>),
        > = std::collections::BTreeMap::new();
        let doomed_mem = params.name.as_str();
        for entity in store.all_entities() {
            if entity.mem != doomed_mem {
                continue;
            }
            for in_edge in store.incoming(&entity.id) {
                if in_edge.from.mem() == doomed_mem {
                    continue;
                }
                // ReadOnly-mount referrers are partitioned out — they
                // route through the residual-stub demotion path on
                // the destructive mutation, same as entity-level
                // HasIncomingRefs. Use the router's capability lookup
                // to decide; mounts the router doesn't know about
                // (shouldn't happen post-construction) are treated as
                // Write to be conservative.
                let is_writable = engine.mem_router().is_writable(in_edge.from.mem());
                if !is_writable {
                    continue;
                }
                by_source
                    .entry(in_edge.from.to_string())
                    .or_insert_with(|| (in_edge.from.clone(), BTreeSet::new()))
                    .1
                    .insert(in_edge.rel_type.clone());
            }
        }

        if !by_source.is_empty() {
            let referrers: Vec<memstead_base::ReferrerInfo> = by_source
                .into_values()
                .map(|(from, rel_types)| memstead_base::ReferrerInfo {
                    from_id: from.to_string(),
                    rel_types: rel_types.into_iter().collect(),
                    mem: from.mem().to_string(),
                })
                .collect();
            if params.detach_incoming {
                // Mem-replacement affordance: the caller intends a
                // same-name re-creation, so the referrers' edges stay
                // in their files and degrade to stubs until the
                // successor mem re-adopts them. Report the detached
                // set so the caller can verify re-adoption.
                detached_referrers = referrers;
            } else {
                return Err(memstead_base::EngineError::MemHasIncomingRefs {
                    mem: params.name,
                    referrers,
                }
                .into());
            }
        }
    }

    // ---- Step 4: router unregister ----
    // Returns the backend handle so step 5 can drive backend-side
    // cleanup without re-resolving the mount through the router
    // (which has already lost the entry by the time we get here).
    let removed_backend = engine.unregister_writable_mem(&params.name)?;
    let backend =
        removed_backend.expect("mem_router().is_writable check above guarantees a present mount");

    // ---- Step 4b: tombstone write (unregister-only path) ----
    // When the operator asked for
    // router-only removal (`delete_files: false`), stamp the surviving
    // config blob with an `unregistered_at` ISO-8601 marker so a
    // subsequent `memstead mem init <same-name>` can recognize the
    // residue as deliberate operator state (zero-friction reattach
    // path) versus crash residue (refuse with
    // `MEM_STORAGE_RESIDUE_DETECTED`).
    //
    // Failures here are non-fatal — the unregister has already
    // committed, and a missing tombstone only downgrades the
    // re-init flow (operator must pass `--reattach` explicitly).
    // The warning surfaces the missed write so the operator can
    // intervene if needed.
    if !params.delete_files {
        match backend.read_mem_config() {
            Ok(Some(bytes)) => {
                match serde_json::from_slice::<memstead_schema::config::MemConfig>(&bytes) {
                    Ok(mut cfg) => {
                        cfg.unregistered_at = Some(now_iso_utc());
                        match serde_json::to_vec_pretty(&cfg) {
                            Ok(mut new_bytes) => {
                                new_bytes.push(b'\n');
                                if let Err(e) = backend.write_mem_config(&new_bytes) {
                                    tracing::warn!(
                                        mem = %params.name,
                                        error = %e,
                                        "delete_mem: unregister succeeded but tombstone \
                                         write failed — re-init will require an explicit \
                                         --reattach flag"
                                    );
                                }
                            }
                            Err(e) => tracing::warn!(
                                mem = %params.name,
                                error = %e,
                                "delete_mem: tombstone serialize failed",
                            ),
                        }
                    }
                    Err(e) => tracing::warn!(
                        mem = %params.name,
                        error = %e,
                        "delete_mem: tombstone-write skipped — config blob did not \
                         parse as MemConfig",
                    ),
                }
            }
            Ok(None) => {
                // No on-disk config blob (folder backend with no
                // `.memstead/config.json`, or git-branch mount whose
                // `__MEMSTEAD:mems/.../config.json` was never written).
                // Nothing to stamp.
            }
            Err(e) => tracing::warn!(
                mem = %params.name,
                error = %e,
                "delete_mem: tombstone-read skipped — backend read_mem_config errored",
            ),
        }
    }

    // ---- Step 5: optional disk delete ----
    // `delete_files: true` runs BOTH halves of the symmetric cleanup:
    //   1. Backend-side `delete_artifacts()`. Folder + archive
    //      backends keep the default no-op. The git-branch backend
    //      drops `refs/heads/<branch_leaf>` and prunes
    //      `__MEMSTEAD:mems/<branch_leaf>/config.json` in a single
    //      ref-edit transaction.
    //   2. Folder-direct `remove_dir_all(location)` when the mount
    //      registered an on-disk directory (folder backends only).
    //      Git-branch backends register `dir: None` so this branch
    //      is skipped — the backend step above handled their state.
    // Any sub-step failing leaves the operation in a documented
    // partial state: the mem is already unregistered, `files_deleted`
    // ends `false`, and per-failure `MEM_FILES_NOT_DELETED` warnings
    // name the surviving artifact(s). `delete_files: false` returns
    // `files_deleted: false` silently (the archive-workflow contract).
    let mut warnings: Vec<memstead_base::ops::WarningHint> = Vec::new();
    let files_deleted = if params.delete_files {
        let backend_ok = match backend.delete_artifacts() {
            Ok(()) => true,
            Err(e) => {
                tracing::warn!(
                    mem = %params.name,
                    error = %e,
                    "delete_mem: unregister succeeded but backend artifact \
                     cleanup failed — leaving leftover refs / tree entries \
                     for explicit cleanup"
                );
                warnings.push(memstead_base::ops::WarningHint::MemFilesNotDeleted {
                    mem: params.name.clone(),
                    reason: "backend_prune_failed".into(),
                    path: None,
                    error: Some(e.to_string()),
                });
                false
            }
        };
        let dir_ok = match mem_dir.as_ref() {
            Some(dir) => match std::fs::remove_dir_all(dir) {
                Ok(()) => true,
                Err(e) => {
                    tracing::warn!(
                        mem = %params.name,
                        path = %dir.display(),
                        error = %e,
                        "delete_mem: unregister succeeded but rmdir failed — \
                         leaving leftover files for explicit cleanup"
                    );
                    warnings.push(memstead_base::ops::WarningHint::MemFilesNotDeleted {
                        mem: params.name.clone(),
                        reason: "rmdir_failed".into(),
                        path: Some(dir.display().to_string()),
                        error: Some(e.to_string()),
                    });
                    false
                }
            },
            // No on-disk directory to rmdir — mem-db-backed mount.
            // The backend step above carried the cleanup; no warning
            // here since the absence of a directory is the documented
            // shape, not a partial-state signal.
            None => true,
        };
        backend_ok && dir_ok
    } else {
        false
    };

    // Symmetric persistence with `create_mem`: write the post-
    // unregister mount manifest so a sibling process boots without
    // the deleted mem. If the workspace_root is unset (tests /
    // ad-hoc consumers) the call is a no-op.
    engine.persist_state()?;

    // ---- Step 6: policy scrub on destructive delete ----
    // When both refusal gates admitted and the destructive delete
    // committed, scrub
    // `.memstead/workspace.toml` of the now-dangling `[cross_mem_links]`
    // grants naming the deleted mem — its own key plus every peer's
    // allowlist value. The `[[mem_management.create|delete]]`
    // allowlist rules are deliberately preserved (forward-looking
    // permissions for the name, not references to the gone instance),
    // so a later `mem init <same name>` needs no fresh allow-create.
    // Refresh the engine's in-memory settings from the freshly-edited
    // workspace.toml so a follow-up `memstead_mem_create` against the
    // same name doesn't trip a stale grant, and `workspace show`
    // agrees with the on-disk file. Skipped for router-only unregister
    // (`delete_files: false`): the storage and grants survive
    // together, set to re-activate on a future reattach.
    let mut allowlist_entries_removed: Vec<AllowlistEntryRemoved> = Vec::new();
    if params.delete_files
        && let Some(root) = engine.workspace_root().map(|p| p.to_path_buf())
    {
        // Scrub failures are non-fatal but surfaced as warnings —
        // the delete itself committed, and dangling policy entries
        // would only cost reload-time `UNKNOWN_MEM` checks. Wrap
        // the typed enum in a warning code the agent can branch on.
        match crate::workspace_config_edit::scrub_policy_for_deleted_mem(&root, &params.name) {
            Err(e) => {
                tracing::warn!(
                    mem = %params.name,
                    error = %e,
                    "delete_mem: destructive delete committed but policy \
                     scrub failed — `.memstead/workspace.toml` may still \
                     reference the deleted mem"
                );
            }
            Ok(scrubbed) => {
                // Lift scrubbed entries into the response envelope
                // so the agent doesn't have to re-read
                // `workspace show` to learn the side effects of
                // the delete.
                allowlist_entries_removed = scrubbed
                    .into_iter()
                    .map(|e| match e {
                        crate::workspace_config_edit::ScrubbedEntry::CrossLink { from, to } => {
                            AllowlistEntryRemoved {
                                table: "cross_mem_links".to_string(),
                                pattern: None,
                                from: Some(from),
                                to: Some(to),
                            }
                        }
                    })
                    .collect();
                // Refresh the in-memory settings so the scrub takes
                // effect without a full reload. Best-effort: missing or
                // unparseable file leaves the existing in-memory
                // settings untouched (the scrub already succeeded; the
                // pre-scrub settings were strictly more permissive).
                let store = memstead_base::workspace_store::FileWorkspaceStore::new();
                if let Ok(ws) = <memstead_base::workspace_store::FileWorkspaceStore as memstead_base::workspace_store::WorkspaceStoreAdapter>::load(
                        &store,
                        &root,
                    ) {
                        engine.set_settings(ws.settings);
                    }
            }
        }
    }

    // `require_notes` provenance nudge — inherited from the engine's
    // single enforcement point (see `create_mem`).
    if let Some(w) = engine.note_missing_warning("delete_mem", params.note.as_deref()) {
        warnings.push(w);
    }

    Ok(MemDeleteResponse {
        name: params.name,
        deleted_from_router: true,
        files_deleted,
        warnings,
        allowlist_entries_removed,
        detached_referrers,
    })
}

// ---------------------------------------------------------------------------
// `memstead_mem_create` orchestration
// ---------------------------------------------------------------------------

/// Explicit storage-backend override for [`create_mem`]. The default
/// (`MemCreateParams.storage: None`) keeps the workspace-shape
/// heuristic: git-branch when `<workspace_root>/mem-repo/.git/`
/// exists, folder otherwise. Passing `Some(_)` pins the backend
/// regardless of workspace shape — the mount loader and runtime
/// already handle mixed-backend workspaces (per-mount backend
/// dispatch), so a folder mem can live beside git-branch mems.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StorageKind {
    /// Plain-markdown folder mount — the mem's files live at
    /// `location`, visible in the outer tree.
    Folder,
    /// Per-mem branch in the workspace's `mem-repo/.git/`. Requires
    /// a mem-repo workspace; refused with `InvalidInput` otherwise.
    GitBranch,
}

/// Parameters for [`create_mem`]. Mirrors the `memstead_mem_create`
/// MCP tool's wire shape 1:1.
///
/// Hierarchical paths are first-class mem identifiers — there is no
/// separate `path` field; `name` carries the full path
/// (e.g. `"team/sub-mem"`) directly, validated via
/// [`memstead_base::entity::id::validate_mem_name_grammar`]. The
/// branch ref composes as `refs/heads/<name>` and the `__MEMSTEAD`
/// config blob as `__MEMSTEAD:mems/<name>/config.json` with no extra
/// composition step.
#[derive(Debug, Clone)]
pub struct MemCreateParams {
    /// Name of the new mem — the full hierarchical identifier
    /// (e.g. `"sub-mem"` for flat layouts or `"team/sub-mem"`
    /// for hierarchical layouts). Must be unique across every
    /// visible mem in the current snapshot, match the basename of
    /// `location` (folder backend identity invariant on the
    /// trailing path segment), and satisfy the mem-name grammar
    /// (`[a-z0-9-]+(/[a-z0-9-]+)*`).
    pub name: String,
    /// Target location. Absolute or workspace-relative.
    /// Canonicalized inside the orchestrator before the allowlist
    /// check.
    pub location: std::path::PathBuf,
    /// Schema pin for the new mem (`name@x.y.z`).
    pub schema_ref: memstead_schema::SchemaRef,
    /// Optional vcs config override (signing keys, identity hints).
    /// Persisted into the per-mem config blob alongside `schema`
    /// and `name`. Most callers pass `None` — defaults come from
    /// the workspace's `.memstead/workspace.toml`. Mirrors full's
    /// `memstead_git_branch::MemCreateParams.vcs`.
    pub vcs: Option<memstead_schema::VcsConfig>,
    /// Agent-authored provenance note (≤[`NOTE_MAX_LEN`] chars).
    pub note: Option<String>,
    /// Process-scoped operator-mode posture. When `true`, the
    /// orchestrator skips the `[[mem_management.create]]` allowlist
    /// gate and the matched-rule schema gate it derives — every other
    /// check (input validation, schema canonicalisation, basename
    /// invariant, name collision, backend instantiation) runs
    /// identically. Set only by transports that established operator
    /// intent at boot (`memstead-mcp --operator-mode`); never accepted as
    /// a wire-shape input from agents. Defaults to `false` —
    /// agent-mode.
    pub operator_mode: bool,
    /// Explicit recovery action for
    /// the case where the storage already carries residue for the
    /// composed branch path. `None` is the default — the engine
    /// then routes by tombstone presence: residue with an
    /// `unregistered_at` tombstone (deliberate operator state from
    /// `memstead mem unregister`) defaults to [`RecoveryAction::Reattach`],
    /// residue without a tombstone refuses with
    /// `MEM_STORAGE_RESIDUE_DETECTED`. Setting an explicit value
    /// overrides the tombstone-driven default. A bare `mem init`
    /// against a name with no residue at all ignores this field
    /// (the happy path is unchanged).
    pub recovery: Option<crate::RecoveryAction>,
    /// Optional opaque per-instance writing guidance, persisted
    /// verbatim into the new mem's config (`writeGuidance`) in the
    /// seed commit. The engine never inspects the map's contents
    /// (schema-strictness D8 — `writeGuidance` is client-owned
    /// vocabulary); a client that read a schema package's
    /// `mem-template.json` fills the instance keys and passes them
    /// here. Empty map (the default) seeds no guidance, identical to
    /// pre-parameter behaviour.
    pub write_guidance: std::collections::HashMap<String, serde_json::Value>,
    /// Explicit storage-backend override. `None` (default) keeps the
    /// workspace-shape heuristic — git-branch when
    /// `<workspace_root>/mem-repo/.git/` exists, folder otherwise.
    /// `Some(StorageKind::Folder)` forces a folder mount even in a
    /// mem-repo workspace: the mem's markdown files live at
    /// `location`, visible in the outer tree.
    /// `Some(StorageKind::GitBranch)` in a workspace WITHOUT
    /// `mem-repo/.git/` refuses with `EngineError::InvalidInput` —
    /// there is no gitdir to host the branch.
    pub storage: Option<StorageKind>,
    /// Caller category for the seed commit's provenance trailer.
    /// Transports pass their own: MCP `Actor::Agent`, the CLI
    /// `Actor::Cli`, application embedders (UniFFI, HTTP) `Actor::App`.
    /// Pre-parameter behaviour hardcoded `Agent` for every transport —
    /// the macOS app's mem creations were misattributed as agent
    /// writes.
    pub actor: memstead_base::vcs::Actor,
    /// Client identity paired with `actor` — renders `name@version`
    /// in the seed commit's `Client:` trailer and derives its author,
    /// exactly as entity mutations do.
    pub client: Option<memstead_base::vcs::ClientId>,
}

/// Response shape from [`create_mem`].
#[derive(Debug, Clone)]
pub struct MemCreateResponse {
    pub name: String,
    pub location: std::path::PathBuf,
    pub schema_ref: memstead_schema::SchemaRef,
    /// Seed-commit cursor. Folder backends produce a synthetic id
    /// (UNIX-nanos + counter, hex per the trait's contract);
    /// git-branch backends produce a real 40-char hex sha. Either
    /// way, the cursor is non-empty — agents poll
    /// `memstead_changes_since` against it without branching on
    /// backend type. Empty string (`""`) signals the reattach branch
    /// was taken — pair with the `MEM_REATTACHED_AFTER_UNREGISTER`
    /// warning surfaced via [`Self::warnings`] for full context.
    pub seed_commit_sha: String,
    /// Non-fatal findings emitted during the create / reattach
    /// pipeline. Today populated only by the reattach branch with a
    /// `MEM_REATTACHED_AFTER_UNREGISTER` warning carrying
    /// `{mem, unregistered_at}`. Fresh-create
    /// (residue absent or force-overwrite branch taken) leaves this
    /// empty.
    pub warnings: Vec<memstead_base::ops::WarningHint>,
}

/// Classify a structurally-invalid mem name into the typed
/// `FullEngineError::InvalidMemName.reason` discriminator. Returns
/// `None` when the name passes the structural check and the caller
/// should proceed to the regex-level grammar check + allowlist gate.
///
/// Discriminator vocabulary:
/// - `empty` — `params.name == ""`.
/// - `whitespace` — input contains any ASCII whitespace, or is non-
///   empty but trims to empty.
/// - `reserved_prefix` — any path segment starts with `__` (the
///   reserved prefix the engine uses for `__MEMSTEAD` registry refs and
///   similar). Caught early so the operator sees the intent rather
///   than a regex no-match.
/// - `invalid_char` — fallback for anything else the grammar rejects
///   (non-printable, non-ASCII letters, reserved characters).
fn classify_invalid_mem_name(name: &str) -> Option<&'static str> {
    if name.is_empty() {
        return Some("empty");
    }
    if name.chars().any(char::is_whitespace) {
        return Some("whitespace");
    }
    if name.split('/').any(|seg| seg.starts_with("__")) {
        return Some("reserved_prefix");
    }
    None
}

/// Create a new writable mem at runtime. Unified counterpart to
/// full's `memstead_git_branch::mem_management::create_mem`. Routes
/// through the engine's installed [`memstead_base::BackendFactory`] so the
/// same call site materialises folder, archive, or git-branch
/// backends transparently — production full consumers install
/// `memstead_git_branch::storage::instantiate_full_backend` at boot via
/// `engine_from_workspace_root`.
///
/// Pipeline:
/// 0. Input validation (note length, optional `path` segments).
///    - 0b. Schema canonicalization against the built-in catalogue.
///      Workspace-authored schemas are resolved by the workspace's
///      schemas_dir, not yet here.
/// 1. Canonicalize location against `engine.workspace_root()`
///    (relative paths) or take absolute paths as-is.
///    - 1a. Allowlist match against the composed candidate
///      (`<path>/<name>` when `path` is `Some`, else `<name>`).
///    - 1b. Schema gate against matched rule's `schemas` list. `["*"]`
///      wildcard admits any schema.
///    - 1c. Basename invariant: `params.name` MUST equal the canonical
///      location's basename.
/// 2. Name collision probe against the current mem_router
///    snapshot. The rich tree-walk collision detector (with
///    `colliding_paths` envelope payload) is full-only; unified
///    surfaces collisions through the snapshot probe with the
///    same `EngineError::MemNameCollision` discriminant.
/// 3. Build [`memstead_schema::config::MemConfig`] bytes.
///    - 3b. Pick the storage variant: `params.storage` when set
///      (explicit [`StorageKind`] override — folder mems beside
///      git-branch mems in one workspace), else by workspace shape
///      (git-branch when `<workspace_root>/mem-repo/.git/` exists,
///      folder otherwise). The branch leaf composes as
///      `<path>/<name>`.
/// 4. Write `<location>/.memstead/config.json` for folder mounts
///    only. Git-branch mounts skip the on-disk write — the
///    per-mem config travels in the workspace's `__MEMSTEAD` registry
///    ref.
/// 5. Materialise the backend via the engine's
///    [`memstead_base::BackendFactory`], commit the seed (real sha for
///    git-branch, synthetic id for folder), and register via
///    [`memstead_base::Engine::register_writable_mem`] with
///    [`memstead_base::MemOrigin::RuntimeCreated`].
pub fn create_mem(
    engine: &mut memstead_base::Engine,
    mut params: MemCreateParams,
) -> Result<MemCreateResponse, FullEngineError> {
    use std::path::Path;

    // ---- Step 0: input validation ----
    if let Some(note) = params.note.as_deref()
        && note.chars().count() > NOTE_MAX_LEN
    {
        return Err(memstead_base::EngineError::InvalidInput(format!(
            "note exceeds {NOTE_MAX_LEN} characters"
        ))
        .into());
    }
    // Hierarchical paths are first-class. `params.name` carries the
    // full path (e.g. `"team/sub-mem"`); the grammar validator
    // accepts both flat and hierarchical forms and refuses
    // malformations (leading / trailing / double slashes, segments
    // outside `[a-z0-9-]+`).
    //
    // Structural-failure modes get typed reasons before the allowlist
    // check fires, so the four distinct shapes (empty / whitespace /
    // invalid-char / reserved-prefix) stay distinguishable from a
    // legitimate authorisation refusal rather than collapsing into the
    // post-allowlist `MEM_PATH_NOT_ALLOWED (no_match)` envelope.
    if let Some(reason) = classify_invalid_mem_name(&params.name) {
        return Err(FullEngineError::InvalidMemName {
            name: params.name.clone(),
            reason,
        });
    }
    // Grammar check (regex-level shape) for anything the structural
    // classifier did not catch. The grammar refusals shouldn't fire
    // here in practice — `classify_invalid_mem_name` already covers
    // every concrete malformation. But keep the call as a defense in
    // depth in case the grammar tightens later; route through the
    // typed `invalid_char` reason so the wire shape stays consistent.
    if memstead_base::entity::id::validate_mem_name_grammar(&params.name).is_err() {
        return Err(FullEngineError::InvalidMemName {
            name: params.name.clone(),
            reason: "invalid_char",
        });
    }

    // ---- Step 0b: schema canonicalization ----
    // Resolve the agent-supplied schema pin against the engine's full
    // loaded catalogue: workspace-authored schemas from the backend's
    // local storage (folder `.memstead/schemas/` or the git-branch
    // `__MEMSTEAD:schemas/` ref) layered over the built-ins. A mem can
    // therefore pin a schema installed onto the backend via
    // `memstead schema install`, not just a built-in.
    let mut builtin_schemas: Vec<std::sync::Arc<memstead_schema::Schema>> =
        engine.workspace_schemas().to_vec();
    builtin_schemas.extend_from_slice(engine.builtin_schemas());
    let resolved_schema = memstead_base::engine::SchemaResolver::new(&builtin_schemas)
        .resolve(&params.schema_ref)
        .map_err(|sources| {
            memstead_base::EngineError::SchemaNotFound {
                mem: params.name.clone(),
                pin: params.schema_ref.to_string(),
                sources,
                install_hint: None,
            }
            .with_schema_install_probe(engine.workspace_root())
        })?;
    let canonical_schema_ref = memstead_schema::SchemaRef::new(
        resolved_schema.manifest.name.clone(),
        resolved_schema.version.clone(),
    );
    params.schema_ref = canonical_schema_ref.clone();

    // ---- Step 1: canonicalize location ----
    let workspace_root = engine.workspace_root().map(|p| p.to_path_buf());
    let absolute = if params.location.is_absolute() {
        params.location.clone()
    } else if let Some(root) = workspace_root.as_ref() {
        root.join(&params.location)
    } else {
        // No workspace_root set (tests, ad-hoc consumers). Treat
        // relative as relative-to-CWD by canonicalising directly;
        // the basename invariant + allowlist still apply.
        params.location.clone()
    };
    let canonical = canonicalize_maybe_missing(&absolute);
    // The mount record keeps the caller's *expressed* anchoring: a
    // relative `location` stays the lexical workspace-root join (no
    // `..` resolution, no symlink normalisation), so
    // `relativize_mount_path`'s lexical strip_prefix recovers the
    // same relative form at serialisation time — an out-of-root
    // location like `../public/engineering` lands in `mounts.json`
    // as that relative path and survives cloning the tree to a
    // different absolute prefix. An absolute `location` stays
    // absolute — machine-pinned by expression. Every validation
    // below (basename invariant, outside-workspace check, residue
    // probes) still runs on `canonical`. Without a workspace_root
    // there is nothing to anchor portability against, so the
    // canonical form is the honest record.
    let mount_path = if workspace_root.is_some() {
        absolute.clone()
    } else {
        canonical.clone()
    };

    // ---- Step 1a: allowlist match ----
    // Compose the allowlist candidate from the optional `<path>`
    // plus `<name>`. Flat layout (path = None) candidate is just
    // `<name>`; hierarchical layout candidate is `<path>/<name>`
    // (used by the rule lookup and surfaced in the
    // `MEM_PATH_NOT_ALLOWED` envelope's `details.candidate` field).
    //
    // Operator-mode bypasses Step 1a and Step 1b entirely. The
    // outside-workspace check below also folds in — operators
    // typically rebuild from scratch and may place a mem outside
    // any allowlist'd region. Every safety-shaped check (schema
    // canonicalisation, basename invariant, name collision) stays
    // unconditional.
    // Hierarchical paths are first-class. The allowlist candidate IS
    // the mem name (no `<path>/<name>` composition step —
    // `params.name` already carries the full path).
    let candidate: String = params.name.clone();

    if !params.operator_mode {
        let create_rule_set = CreateRuleSet::new(engine.settings().mem_create_rules.clone())
            .map_err(|e| {
                memstead_base::EngineError::InvalidInput(format!("mem_create_rules: {e}"))
            })?;
        let patterns_for_errors: Vec<String> = create_rule_set.patterns();

        if create_rule_set.is_empty() {
            return Err(FullEngineError::MemPathNotAllowed {
                attempted: canonical.clone(),
                candidate,
                patterns: patterns_for_errors,
                reason: "no_allowlist_configured",
                policy_table: "mem_management.create",
            });
        }
        let matched_rule = match create_rule_set.first_match(Path::new(&candidate)) {
            Some(r) => r.clone(),
            None => {
                return Err(FullEngineError::MemPathNotAllowed {
                    attempted: canonical.clone(),
                    candidate,
                    patterns: patterns_for_errors,
                    reason: "no_match",
                    policy_table: "mem_management.create",
                });
            }
        };

        // Outside-workspace check (skipped when no workspace_root is
        // set — tests / ad-hoc).
        if let Some(root) = workspace_root.as_ref()
            && canonical.strip_prefix(root).is_err()
        {
            return Err(FullEngineError::MemPathNotAllowed {
                attempted: canonical.clone(),
                candidate,
                patterns: patterns_for_errors,
                reason: "outside_workspace",
                policy_table: "mem_management.create",
            });
        }

        // ---- Step 1b: schema gate ----
        let schema_wildcard = matched_rule
            .schemas
            .iter()
            .any(|s| s == memstead_base::SCHEMA_WILDCARD);
        if !schema_wildcard {
            let requested_canonical = canonical_schema_ref.to_string();
            let mut allowed_canonical: Vec<String> = Vec::with_capacity(matched_rule.schemas.len());
            let mut allowed = false;
            for raw in &matched_rule.schemas {
                let parsed: memstead_schema::SchemaRef = match raw.parse() {
                    Ok(r) => r,
                    Err(_) => {
                        return Err(memstead_base::EngineError::InvalidInput(format!(
                            "[mem_management] rule {:?}: schema entry {:?} is not a valid `name@version` pin",
                            matched_rule.pattern, raw,
                        ))
                        .into());
                    }
                };
                let resolved = memstead_base::engine::SchemaResolver::new(&builtin_schemas)
                    .resolve(&parsed)
                    .map_err(|sources| {
                        memstead_base::EngineError::SchemaNotFound {
                            mem: params.name.clone(),
                            pin: parsed.to_string(),
                            sources,
                            install_hint: None,
                        }
                        .with_schema_install_probe(engine.workspace_root())
                    })?;
                let canon_str = memstead_schema::SchemaRef::new(
                    resolved.manifest.name.clone(),
                    resolved.version.clone(),
                )
                .to_string();
                if canon_str == requested_canonical {
                    allowed = true;
                }
                allowed_canonical.push(canon_str);
            }
            if !allowed {
                return Err(FullEngineError::MemSchemaNotAllowed {
                    candidate,
                    matched_pattern: matched_rule.pattern.clone(),
                    requested_schema: requested_canonical,
                    allowed_schemas: allowed_canonical,
                });
            }
        }
    }

    // ---- Step 1c: basename invariant ----
    // Enforced for folder creates only, because the equivalent
    // invariant is implicit on the git-branch path: `params.name` IS
    // the branch identifier, and `params.location` is ignored at
    // runtime (the mem has no on-disk identity beyond the gitdir).
    //
    // Mem names accept hierarchical paths (`team/sub-mem`). The
    // on-disk basename matches the LAST segment of the path —
    // folder-backed
    // hierarchical mems register under `<location>/sub-mem`
    // even when their identity is `team/sub-mem`.
    let workspace_has_mem_repo = workspace_root
        .as_ref()
        .map(|root| root.join("mem-repo").join(".git").is_dir())
        .unwrap_or(false);
    // Resolve the effective storage kind once: the explicit override
    // wins; `None` keeps the workspace-shape heuristic (behaviour-
    // preserving for existing callers). An explicit git-branch
    // request without a mem-repo has no gitdir to host the branch —
    // typed refusal rather than a downstream instantiate failure.
    let storage_kind = match params.storage {
        Some(k) => k,
        None => {
            if workspace_has_mem_repo {
                StorageKind::GitBranch
            } else {
                StorageKind::Folder
            }
        }
    };
    if storage_kind == StorageKind::GitBranch && !workspace_has_mem_repo {
        return Err(memstead_base::EngineError::InvalidInput(
            "storage: git-branch requires a mem-repo workspace \
             (<workspace_root>/mem-repo/.git/ not found) — omit the \
             override or pass storage: folder"
                .to_string(),
        )
        .into());
    }
    if storage_kind == StorageKind::Folder {
        let target_basename = canonical
            .file_name()
            .and_then(|n| n.to_str())
            .unwrap_or("")
            .to_string();
        let name_leaf = params
            .name
            .rsplit('/')
            .next()
            .unwrap_or(params.name.as_str());
        if target_basename != name_leaf {
            return Err(memstead_base::EngineError::InvalidInput(format!(
                "mem name '{}' (leaf '{}') does not match the basename '{}' of the canonical location '{}' \
                 — rename either side so the registered identity's leaf matches the on-disk basename",
                params.name,
                name_leaf,
                target_basename,
                canonical.display()
            ))
            .into());
        }
    }

    // ---- Step 2: name collision probe (snapshot only) ----
    if let Some(existing) = engine.mem_router().origin_for_mem(&params.name) {
        return Err(memstead_base::EngineError::MemNameCollision {
            name: params.name,
            source_origin: existing.render_source(),
        }
        .into());
    }
    if engine
        .mem_router()
        .archive_path_for_mem(&params.name)
        .is_some()
    {
        return Err(memstead_base::EngineError::MemNameCollision {
            name: params.name,
            source_origin: "attached read mem".to_string(),
        }
        .into());
    }

    // ---- Step 2b: storage residue probe (mem-repo only) ----
    // A name absent from the in-memory router can still have storage
    // residue — a per-mem content branch +
    // `__MEMSTEAD:mems/<branch_leaf>/config.json` blob surviving a
    // `memstead mem unregister` (deliberate operator state), a crash
    // mid-create, or a partially-failed delete. Without this probe the
    // seed-commit step would silently re-attach (resurrecting deleted
    // entities) or fail with a low-level `HashMismatch` carrying no
    // useful recovery context. The probe here is path-aware: the
    // composed `branch_leaf`
    // (`<mem_path>/<name>` for hierarchical, bare `<name>` for
    // flat) is the exact branch ref to inspect — `find_branches_by_leaf`
    // is too permissive (would match `other-team/<name>` for
    // `team/<name>`).
    //
    // Folder creates don't have a branch-residue concept (even in a
    // mem-repo workspace where the explicit override forces folder);
    // their analogous probe is "does `<location>/.memstead/config.json`
    // already exist?" — which Step 4 below already enforces via
    // `ConfigAlreadyExists`. The residue refusal is git-branch-only.
    // Hierarchical paths are first-class: the composed branch path IS
    // the mem name
    // (`params.name` carries the full `team/sub-mem` form
    // directly). Bound to a local for readability and to match the
    // reattach + force-overwrite arm shapes that still need a
    // `&str` reference.
    let composed_branch_leaf = params.name.clone();
    let residue_probe = if storage_kind == StorageKind::Folder {
        ResidueProbe::None
    } else {
        residue_probe_for_workspace(
            engine,
            workspace_root.as_deref(),
            &composed_branch_leaf,
            &params.name,
            &canonical_schema_ref,
        )
    };
    // The match discriminates the residue routes: `None` / fresh-create
    // and `ForceOverwrite` fall through to Step 3 below; `Reattach`
    // early-returns with the warning surfaced via the response's
    // `warnings` field. The match value itself is unused once those
    // branches have taken effect — the warning emission lives on the
    // response, not the discarded binding.
    let _: Option<memstead_base::ops::WarningHint> = match residue_probe {
        ResidueProbe::None => None,
        ResidueProbe::Present {
            branch_ref,
            config_blob,
            existing_config,
        } => {
            let tombstone = existing_config
                .as_ref()
                .and_then(|c| c.unregistered_at.clone());
            let effective_action = params
                .recovery
                .or_else(|| tombstone.as_ref().map(|_| crate::RecoveryAction::Reattach));
            match effective_action {
                None => {
                    return Err(FullEngineError::MemStorageResidueDetected {
                        branch_ref,
                        config_blob,
                        entity_count: 0,
                    });
                }
                Some(crate::RecoveryAction::HardCleanupFirst) => {
                    return Err(FullEngineError::MemStorageResidueDetected {
                        branch_ref,
                        config_blob,
                        entity_count: 0,
                    });
                }
                Some(crate::RecoveryAction::ForceOverwrite) => {
                    // Force-overwrite — prune the residual branch and
                    // `__MEMSTEAD` config blob in one ref-edit
                    // transaction, then fall through to Steps 3-5
                    // (normal create path). The match arm yields
                    // `None` so no warning rides on the response;
                    // the prior entities are gone by design.
                    let workspace_root_ref = workspace_root.as_ref().ok_or_else(|| {
                        memstead_base::EngineError::InvalidInput(
                            "force_overwrite requires a workspace_root \
                                 to locate mem-repo/.git/"
                                .to_string(),
                        )
                    })?;
                    let gitdir = workspace_root_ref.join("mem-repo").join(".git");
                    let canonical_gitdir = gitdir.canonicalize().unwrap_or(gitdir);
                    let ops = engine.git_branch_ops().ok_or_else(|| {
                        memstead_base::EngineError::InvalidInput(
                            "force_overwrite requires the git-branch ops \
                             bundle (full boot only) — folder workspaces \
                             have no branch residue to prune"
                                .to_string(),
                        )
                    })?;
                    (ops.prune_residue)(&canonical_gitdir, &composed_branch_leaf).map_err(|e| {
                        memstead_base::EngineError::Mem(format!("force_overwrite prune: {e}"))
                    })?;
                    // Fall through to Step 3 — the residue is gone,
                    // create proceeds normally and the fresh seed
                    // commit is the new branch tip.
                    None
                }
                Some(crate::RecoveryAction::Reattach) => {
                    // Reattach path — register the existing branch
                    // as a fresh writable mount, skip the seed
                    // commit (the branch already carries history),
                    // clear the tombstone if present, surface the
                    // audit warning. Falls out below via early
                    // return so steps 3-5 stay aligned with the
                    // fresh-create path.
                    let workspace_root_ref = workspace_root.as_ref().ok_or_else(|| {
                        memstead_base::EngineError::InvalidInput(
                            "reattach requires a workspace_root \
                                 to locate mem-repo/.git/"
                                .to_string(),
                        )
                    })?;
                    let gitdir = workspace_root_ref.join("mem-repo").join(".git");
                    let canonical_gitdir = gitdir.canonicalize().unwrap_or(gitdir);
                    let mount = memstead_base::workspace::Mount {
                        migration_target: None,
                        mem: params.name.clone(),
                        schema: Some(canonical_schema_ref.clone()),
                        storage: memstead_base::workspace::MountStorage::GitBranch {
                            gitdir: canonical_gitdir,
                            branch: format!("refs/heads/{composed_branch_leaf}"),
                        },
                        capability: memstead_base::workspace::MountCapability::Write,
                        lifecycle: memstead_base::workspace::MountLifecycle::Eager,
                        cross_linkable: true,
                    };
                    let factory = engine.backend_factory();
                    let backend = factory(&mount).map_err(|e| {
                        memstead_base::EngineError::Mem(format!(
                            "reattach backend instantiate: {e}"
                        ))
                    })?;
                    // Clear the tombstone if one was present, so a
                    // future drift probe doesn't re-trigger the
                    // reattach branch.
                    if let Some(cfg) = existing_config.as_ref()
                        && cfg.unregistered_at.is_some()
                    {
                        let mut updated = cfg.clone();
                        updated.unregistered_at = None;
                        if let Ok(mut bytes) = serde_json::to_vec_pretty(&updated) {
                            bytes.push(b'\n');
                            if let Err(e) = backend.write_mem_config(&bytes) {
                                tracing::warn!(
                                    mem = %params.name,
                                    error = %e,
                                    "reattach: tombstone clear failed — \
                                     the marker survives; a re-unregister will \
                                     overwrite it",
                                );
                            }
                        }
                    }
                    let origin = memstead_base::MemOrigin::RuntimeCreated {
                        at: std::time::SystemTime::now(),
                        by_tool: "memstead_mem_create (reattach)",
                    };
                    engine.register_writable_mem(mount, backend, origin)?;
                    engine.persist_state()?;
                    // Re-derive every writable mem's incoming-edge slice
                    // so other mems' relationships pointing at the
                    // reattaching mem land in the in-memory edge index.
                    // Rebuilding only from the reattaching mem's own
                    // outgoing edges would leave `memstead_health`
                    // undercounting cross-mem edges visible via
                    // `memstead_entity` on the on-disk markdown.
                    // Reuses the existing workspace-wide reload path
                    // (`memstead_reload` no-arg) — schema rebuild + per-mem
                    // bodies + read-mem re-attach + workspace.toml
                    // re-read. Reports are dropped; the side effect is
                    // the edge index re-derivation.
                    let _ = engine.reload_each_writable_mem_reports()?;
                    let mut warnings: Vec<memstead_base::ops::WarningHint> = Vec::new();
                    if let Some(ts) = tombstone {
                        warnings.push(
                            memstead_base::ops::WarningHint::MemReattachedAfterUnregister {
                                mem: params.name.clone(),
                                unregistered_at: ts,
                            },
                        );
                    }
                    // Early return — the reattach path has no seed
                    // commit, no .memstead/config.json write. The branch
                    // tip stays as the prior session left it.
                    return Ok(MemCreateResponse {
                        name: params.name,
                        location: canonical,
                        schema_ref: canonical_schema_ref,
                        seed_commit_sha: String::new(),
                        warnings,
                    });
                }
            }
        }
    };
    // ---- Step 3: build MemConfig bytes ----
    // F1: every mem carries a populated `version` from creation
    // onward — `0.1.0` is the engine default; operators bump via
    // `memstead mem set-version` before publishing. Without this seed,
    // the export path hits the residual `MEM_CONFIG_INCOMPLETE` /
    // pre-fix `INTERNAL` collapse on the first archive attempt.
    let mem_config = memstead_schema::config::MemConfig {
        review_mark: None,
        mutation_stamp: None,
        name: None,
        title: None,
        subject: None,
        version: Some(semver::Version::new(0, 1, 0)),
        description: None,
        authors: None,
        schema: Some(canonical_schema_ref.clone()),
        write_guidance: params.write_guidance.clone(),
        process_mem: None,
        rules: None,
        publish: None,
        language: None,
        read_mems: Default::default(),
        community: None,
        vcs: params.vcs.clone(),
        unregistered_at: None,
        sync_state: Default::default(),
        extra: Default::default(),
    };
    let config_bytes = serde_json::to_vec_pretty(&mem_config).map_err(|e| {
        memstead_base::EngineError::InvalidInput(format!("could not serialize mem config: {e}"))
    })?;

    // ---- Step 3b: pick storage variant ----
    // `storage_kind` was resolved at Step 1c: the explicit
    // `params.storage` override when set, else the workspace-shape
    // heuristic (git-branch when `<workspace_root>/mem-repo/.git/`
    // exists, folder otherwise — gix-free, so the heuristic works in
    // lean builds, which never have a mem-repo).
    //
    // The git-branch storage requires the engine to have the full
    // backend factory installed (`engine_from_workspace_root` does
    // this at boot). When the factory is the default lean one, the
    // factory call below returns
    // [`memstead_base::workspace_store::InstantiateError::GitBranchRequiresMemRepoFeature`]
    // — wrapped as `EngineError::Mem` in the seed-commit step.
    // The branch leaf IS `params.name` — no separate composition step.
    // Hierarchical identity lives directly in the mem name.
    let branch_leaf = params.name.clone();
    let storage = match storage_kind {
        StorageKind::GitBranch => {
            // Step 1c refused git-branch without a mem-repo, and the
            // mem-repo probe requires a workspace_root — this arm
            // always has one. The `ok_or_else` is defence in depth.
            let root = workspace_root.as_ref().ok_or_else(|| {
                memstead_base::EngineError::InvalidInput(
                    "storage: git-branch requires a workspace_root \
                     to locate mem-repo/.git/"
                        .to_string(),
                )
            })?;
            let probe = root.join("mem-repo").join(".git");
            let gitdir = probe.canonicalize().unwrap_or(probe);
            memstead_base::workspace::MountStorage::GitBranch {
                gitdir,
                branch: format!("refs/heads/{branch_leaf}"),
            }
        }
        StorageKind::Folder => memstead_base::workspace::MountStorage::Folder {
            path: mount_path.clone(),
        },
    };
    let is_git_branch = matches!(
        storage,
        memstead_base::workspace::MountStorage::GitBranch { .. }
    );

    // ---- Step 4: write .memstead/config.json ----
    // Folder path: write the config blob to disk before instantiating
    // the backend so the post-register `read_mem_config()` sees it.
    // Git-branch path: skip the on-disk write — the per-mem config
    // travels in the workspace's `__MEMSTEAD` registry ref, not on disk.
    // The seed commit on the per-mem branch may also include a
    // `.memstead/config.json` blob for parity with folder backends; this
    // can be added later as an additive piece without changing the
    // wire shape.
    if !is_git_branch {
        std::fs::create_dir_all(&canonical).map_err(|e| {
            memstead_base::EngineError::Mem(format!("create_dir_all {}: {e}", canonical.display()))
        })?;
        let memstead_dir = canonical.join(memstead_base::MEM_META_DIR);
        std::fs::create_dir_all(&memstead_dir).map_err(|e| {
            memstead_base::EngineError::Mem(format!(
                "create_dir_all {}: {e}",
                memstead_dir.display()
            ))
        })?;
        let config_path = memstead_dir.join("config.json");
        if config_path.exists() {
            return Err(FullEngineError::ConfigAlreadyExists { path: config_path });
        }
        std::fs::write(&config_path, &config_bytes).map_err(|e| {
            memstead_base::EngineError::Mem(format!("write {}: {e}", config_path.display()))
        })?;
    }

    // ---- Step 5: instantiate backend + seed commit + register ----
    // Backend instantiation routes through `engine.backend_factory()`.
    // Full consumers install
    // `memstead_git_branch::storage::instantiate_full_backend` at boot so
    // the same call site produces git-branch backends when the mount
    // declares one (Step 3b above picks the variant by workspace
    // shape).
    //
    // Produce a real seed commit via the backend's commit method
    // before registering. Folder backends emit a synthetic id
    // (UNIX-nanos + counter, hex per the trait's contract);
    // git-branch backends produce real 40-char shas. Either way the
    // response carries a non-empty cursor.
    let mount = memstead_base::workspace::Mount {
        mem: params.name.clone(),
        schema: Some(canonical_schema_ref.clone()),
        storage,
        capability: memstead_base::workspace::MountCapability::Write,
        lifecycle: memstead_base::workspace::MountLifecycle::Eager,
        cross_linkable: true,
        migration_target: None,
    };
    let factory = engine.backend_factory();
    let backend = factory(&mount)
        .map_err(|e| memstead_base::EngineError::Mem(format!("instantiate backend: {e}")))?;
    let seed_ctx = memstead_base::vcs::CommitContext {
        actor: params.actor,
        client: params.client.clone(),
        tool: Some("memstead_mem_create"),
        note: params.note.clone(),
        role: Default::default(),
        logical_operation_id: None,
        entity_ids: None,
    };
    // For git-branch mounts, write the per-mem config blob to the
    // workspace's `__MEMSTEAD` ref before sealing the per-mem branch.
    // Folder mounts already wrote the config to disk in Step 4;
    // calling `write_mem_config` again would be redundant for
    // folder.
    if is_git_branch {
        backend
            .write_mem_config(&config_bytes)
            .map_err(|e| memstead_base::EngineError::Mem(format!("write mem config: {e}")))?;
    }
    let seed_commit_sha = backend
        .commit(&format!("memstead: create mem {}", params.name), &seed_ctx)
        .map_err(|e| memstead_base::EngineError::Mem(format!("seed commit: {e}")))?;
    let origin = memstead_base::MemOrigin::RuntimeCreated {
        at: std::time::SystemTime::now(),
        by_tool: "memstead_mem_create",
    };
    // Hierarchical identity lives in `mount.mem` directly — there is
    // exactly one identifier (the full path), with no separate
    // `params.path` plumbed into the router.
    engine.register_writable_mem(mount, backend, origin)?;

    // Persist the updated mount list to the workspace store. Without
    // this, the per-mem branch + `__MEMSTEAD` config (or folder +
    // `.memstead/config.json`) lives on disk but the next CLI / MCP
    // process boots with an empty mount manifest — `unknown mem`
    // on every follow-up call. Engine-side rather than orchestrator-
    // side so every caller (MCP, UniFFI, in-process embedding)
    // inherits persistence by construction.
    engine.persist_state()?;

    // `require_notes` provenance nudge — inherited from the engine's
    // single enforcement point so mem lifecycle matches entity
    // mutations (no second, drift-prone implementation on the MCP
    // transport). The seed commit landed above; a noteless create
    // surfaces the warning without blocking.
    let note_warning = engine.note_missing_warning("create_mem", params.note.as_deref());
    let mut warnings: Vec<memstead_base::ops::WarningHint> = note_warning.into_iter().collect();
    // Folder storage has no version control: say at creation what
    // provenance means there (changelog ledger, placeholder SHAs,
    // durability tied to the surrounding repo). A warning, never a
    // refusal — folder mems are a supported storage class. Git-branch
    // mounts carry real commits and get no notice.
    if storage_kind == StorageKind::Folder {
        warnings.push(memstead_base::ops::WarningHint::FolderMemProvenance {
            mem: params.name.clone(),
        });
    }
    Ok(MemCreateResponse {
        name: params.name,
        location: canonical,
        schema_ref: canonical_schema_ref,
        seed_commit_sha,
        warnings,
    })
}

/// Canonicalize a path that may or may not yet exist. Walks up
/// until the first existing ancestor, canonicalizes that, and
/// appends the tail — preserving the original segment order. Falls
/// back to the input when every ancestor is unavailable.
///
/// Mirrors full's `canonicalize_maybe_missing` in
/// `memstead_git_branch::mem_management::create`. Lifted into memstead-engine
/// so the unified create orchestrator doesn't reach back to
/// memstead-git-branch.
fn canonicalize_maybe_missing(path: &std::path::Path) -> std::path::PathBuf {
    if let Ok(c) = path.canonicalize() {
        return c;
    }
    let mut tail: Vec<std::ffi::OsString> = Vec::new();
    let mut cursor: &std::path::Path = path;
    loop {
        if let Ok(c) = cursor.canonicalize() {
            let mut out = c;
            for seg in tail.iter().rev() {
                out.push(seg);
            }
            return out;
        }
        match cursor.file_name() {
            Some(name) => {
                tail.push(name.to_os_string());
                match cursor.parent() {
                    Some(parent) => cursor = parent,
                    None => return path.to_path_buf(),
                }
            }
            None => return path.to_path_buf(),
        }
    }
}

// ---------------------------------------------------------------------------
// Mem rename
// ---------------------------------------------------------------------------

/// Parameters for [`rename_mem`].
#[derive(Debug, Clone)]
pub struct MemRenameParams {
    /// Current mem name (full hierarchical identifier).
    pub old: String,
    /// Target mem name. Must satisfy the mem-name grammar and not be
    /// registered.
    pub new: String,
    /// When `true`, both allowlist gates (delete for `old`, create for
    /// `new`) are skipped — same posture as `create_mem` / `delete_mem`.
    pub operator_mode: bool,
    /// Agent-authored provenance note (≤[`NOTE_MAX_LEN`] chars),
    /// carried on every commit the rename produces.
    pub note: Option<String>,
}

/// Response of [`rename_mem`].
#[derive(Debug, Clone)]
pub struct MemRenameResponse {
    pub old: String,
    pub new: String,
    /// Mems whose entity files were rewritten by the reference sweep,
    /// in commit order.
    pub rewritten_mems: Vec<String>,
    /// `true` when the call completed a previously interrupted rename
    /// (the old name was already gone, the new mount present): only
    /// the idempotent halves ran (reference sweep, grants, binding /
    /// findings relocation).
    pub resumed: bool,
    pub warnings: Vec<memstead_base::ops::WarningHint>,
}

/// Rename a mem: `old` → `new`, complete across every surface that
/// carries the name.
///
/// Entity ids are derived from `(mount name, file path)`, so the mem's
/// own entities re-id automatically once the mount is renamed; the
/// orchestrator's job is everything textual and structural around
/// that:
///
/// 1. **Reference sweep** ([`memstead_base::Engine::rewrite_mem_references`]):
///    every `<old>--<slug>` / `<old>:<slug>` wiki-link and
///    Relationships entry in every writable mem (peers and the renamed
///    mem's own full-id self-references), plus the anchors-sidecar
///    keys — one commit per affected mem, all tagged with one
///    `logical_operation_id`.
/// 2. **Sync-state keys** in the mem's config
///    (`<old>/<binding>/<source>#…` → `<new>/…`), written to the
///    backend before the identity flip so the updated blob travels
///    with it.
/// 3. **Storage identity flip**: git-branch mounts move
///    `refs/heads/<old>` to `refs/heads/<new>` at the same tip
///    (history preserved) and relocate the `__MEMSTEAD:mems/` config
///    blob in one ref transaction; folder mounts keep their directory
///    (the mount name, not the path, is the identity).
/// 4. **Router / mounts**: the mount re-registers under the new name
///    and `mounts.json` is persisted.
/// 5. **Workspace grants**: `[cross_mem_links]` keys and named values
///    carrying `old` are rewritten to `new` in `workspace.toml`.
/// 6. **Binding + findings stores**:
///    `.memstead/projections/<old>/` and
///    `.memstead/state/findings/<old>/` move to `<new>/`, and each
///    relocated binding's `destination_mem` field is rewritten.
///
/// **Refusal atomicity:** every refusal (unknown mem, read-only mount,
/// grammar, collision, allowlists) fires before the first write — a
/// refused call leaves the workspace byte-identical.
///
/// **Interruption:** the sweep commits per-mem; a crash mid-sweep
/// leaves stale `<old>--` references that surface as stubs in health,
/// and re-issuing the same `rename_mem` completes the operation. When
/// the identity flip has already happened (old gone, new present) the
/// call runs in *resumption mode*: only the idempotent halves execute.
///
/// **In-process caveat:** grants rewritten on disk (step 5) are not
/// reflected into the already-loaded engine's settings — the CLI's
/// one-shot process model makes this invisible; a long-lived embedder
/// must re-boot after a rename.
pub fn rename_mem(
    engine: &mut memstead_base::Engine,
    params: MemRenameParams,
) -> Result<MemRenameResponse, FullEngineError> {
    // ---- Step 0: input validation (no writes past this block) ----
    if let Some(note) = params.note.as_deref()
        && note.chars().count() > NOTE_MAX_LEN
    {
        return Err(memstead_base::EngineError::InvalidInput(format!(
            "note exceeds {NOTE_MAX_LEN} characters"
        ))
        .into());
    }
    if params.old == params.new {
        return Err(memstead_base::EngineError::InvalidInput(
            "rename source and target are the same name".to_string(),
        )
        .into());
    }
    if let Some(reason) = classify_invalid_mem_name(&params.new) {
        return Err(FullEngineError::InvalidMemName {
            name: params.new.clone(),
            reason,
        });
    }
    if memstead_base::entity::id::validate_mem_name_grammar(&params.new).is_err() {
        return Err(FullEngineError::InvalidMemName {
            name: params.new.clone(),
            reason: "invalid_char",
        });
    }

    // ---- Step 1: mode resolution ----
    let old_mount = engine.mount(&params.old).cloned();
    let new_mount_present = engine.mount(&params.new).is_some();
    let resumed = match (&old_mount, new_mount_present) {
        (Some(_), true) => {
            return Err(memstead_base::EngineError::MemNameCollision {
                name: params.new.clone(),
                source_origin: "registered mount".to_string(),
            }
            .into());
        }
        (Some(m), false) => {
            if m.capability != memstead_base::MountCapability::Write {
                return Err(memstead_base::EngineError::ReadOnlyMount(params.old.clone()).into());
            }
            false
        }
        (None, true) => {
            // The identity flip already happened — resumption mode.
            // The new mount must be writable (a rename never produces
            // a read-only mount, so anything else is a name clash
            // with an installed read mem, not a resumable rename).
            if !engine.mem_router().is_writable(&params.new) {
                return Err(memstead_base::EngineError::UnknownMem(params.old.clone()).into());
            }
            true
        }
        (None, false) => {
            return Err(memstead_base::EngineError::UnknownMem(params.old.clone()).into());
        }
    };

    // ---- Step 2: allowlist gates (normal mode, agent posture) ----
    // Resumption mode skips them: the flip that created the current
    // state already passed both gates, and the old name can no longer
    // match anything.
    if !resumed && !params.operator_mode {
        let attempted = std::path::PathBuf::from(format!("(mem: {})", params.old));

        let delete_rule_set = DeleteRuleSet::new(engine.settings().mem_delete_rules.clone())
            .map_err(|e| {
                memstead_base::EngineError::InvalidInput(format!("mem_delete_rules: {e}"))
            })?;
        let delete_patterns: Vec<String> = delete_rule_set.patterns();
        if delete_rule_set.is_empty()
            || delete_rule_set
                .first_match(std::path::Path::new(&params.old))
                .is_none()
        {
            let reason = if delete_rule_set.is_empty() {
                "no_allowlist_configured"
            } else {
                "no_match"
            };
            return Err(FullEngineError::MemPathNotAllowed {
                attempted,
                candidate: params.old.clone(),
                patterns: delete_patterns,
                reason,
                policy_table: "mem_management.delete",
            });
        }

        let create_rule_set = CreateRuleSet::new(engine.settings().mem_create_rules.clone())
            .map_err(|e| {
                memstead_base::EngineError::InvalidInput(format!("mem_create_rules: {e}"))
            })?;
        let create_patterns: Vec<String> = create_rule_set.patterns();
        let matched_rule = if create_rule_set.is_empty() {
            None
        } else {
            create_rule_set
                .first_match(std::path::Path::new(&params.new))
                .cloned()
        };
        let Some(matched_rule) = matched_rule else {
            let reason = if create_rule_set.is_empty() {
                "no_allowlist_configured"
            } else {
                "no_match"
            };
            return Err(FullEngineError::MemPathNotAllowed {
                attempted: std::path::PathBuf::from(format!("(mem: {})", params.new)),
                candidate: params.new.clone(),
                patterns: create_patterns,
                reason,
                policy_table: "mem_management.create",
            });
        };

        // Schema gate: the pin is unchanged by a rename, so the
        // matched create rule's schema list is checked against the
        // mem's EXISTING pin (config pin first, mount assertion as
        // fallback). A mem with no discoverable pin passes only a
        // wildcard rule — refusing there would make unpinned mems
        // unrenamable for a reason the operator can't see.
        let schema_wildcard = matched_rule
            .schemas
            .iter()
            .any(|s| s == memstead_base::SCHEMA_WILDCARD);
        if !schema_wildcard {
            let existing_pin: Option<String> = engine
                .mem_configs_named()
                .find(|(name, _)| *name == params.old)
                .and_then(|(_, c)| c.schema.as_ref().map(|s| s.to_string()))
                .or_else(|| {
                    old_mount
                        .as_ref()
                        .and_then(|m| m.schema.as_ref().map(|s| s.to_string()))
                });
            let allowed = existing_pin
                .as_deref()
                .is_some_and(|pin| matched_rule.schemas.iter().any(|s| s == pin));
            if !allowed {
                return Err(FullEngineError::MemSchemaNotAllowed {
                    candidate: params.new.clone(),
                    matched_pattern: matched_rule.pattern.clone(),
                    requested_schema: existing_pin.unwrap_or_else(|| "(no pin)".to_string()),
                    allowed_schemas: matched_rule.schemas.clone(),
                });
            }
        }
    }

    // ---- Step 3: reference sweep (idempotent; both modes) ----
    let sweep = engine
        .rewrite_mem_references(&params.old, &params.new, params.note.as_deref())
        .map_err(FullEngineError::from)?;

    // ---- Steps 4-6: identity flip (normal mode only) ----
    if !resumed {
        let mount = old_mount.expect("normal mode implies the old mount is present");

        // Step 4: sync-state keys embed the mem name
        // (`<mem>/<binding>/<source>#…`) — rewrite them on the old
        // backend so the updated config blob travels with the flip.
        {
            // No public live-backend accessor exists; a throwaway
            // backend handle from the factory reads and writes the
            // same storage the mounted one does (git-branch handles
            // are cheap ref wrappers, folder handles are paths).
            let factory = engine.backend_factory();
            let backend_ref = factory(&mount).map_err(|e| {
                memstead_base::EngineError::Mem(format!("instantiate backend: {e}"))
            })?;
            let config_bytes = backend_ref
                .read_mem_config()
                .map_err(|e| memstead_base::EngineError::Mem(format!("read mem config: {e}")))?;
            if let Some(bytes) = config_bytes
                && let Ok(mut cfg) =
                    serde_json::from_slice::<memstead_schema::config::MemConfig>(&bytes)
            {
                let old_prefix = format!("{}/", params.old);
                let new_prefix = format!("{}/", params.new);
                let mut changed = false;
                let rewritten: std::collections::BTreeMap<String, String> = cfg
                    .sync_state
                    .into_iter()
                    .map(|(k, v)| match k.strip_prefix(&old_prefix) {
                        Some(rest) => {
                            changed = true;
                            (format!("{new_prefix}{rest}"), v)
                        }
                        None => (k, v),
                    })
                    .collect();
                cfg.sync_state = rewritten;
                if changed {
                    let mut out = serde_json::to_vec_pretty(&cfg).map_err(|e| {
                        memstead_base::EngineError::Mem(format!("serialise mem config: {e}"))
                    })?;
                    out.push(b'\n');
                    backend_ref.write_mem_config(&out).map_err(|e| {
                        memstead_base::EngineError::Mem(format!("write mem config: {e}"))
                    })?;
                }
            }
        }

        // Step 5: storage identity flip.
        let new_storage = match &mount.storage {
            memstead_base::MountStorage::GitBranch { gitdir, branch } => {
                let ops = engine.git_branch_ops().ok_or_else(|| {
                    memstead_base::EngineError::InvalidInput(
                        "mem rename on a git-branch mount requires the git-branch ops \
                         bundle (full boot only)"
                            .to_string(),
                    )
                })?;
                let canonical_gitdir = gitdir.canonicalize().unwrap_or_else(|_| gitdir.clone());
                // Mount records may carry the branch as a bare leaf or
                // as the full `refs/heads/<leaf>` form — the backend
                // instantiation tolerates both. Normalise to the leaf
                // for the storage call and write the new record in the
                // same form the old one used.
                let had_prefix = branch.starts_with("refs/heads/");
                let old_leaf = branch.strip_prefix("refs/heads/").unwrap_or(branch);
                (ops.rename_mem_storage)(&canonical_gitdir, old_leaf, &params.new)
                    .map_err(|e| memstead_base::EngineError::Mem(format!("storage rename: {e}")))?;
                let new_branch = if had_prefix {
                    format!("refs/heads/{}", params.new)
                } else {
                    params.new.clone()
                };
                memstead_base::MountStorage::GitBranch {
                    gitdir: gitdir.clone(),
                    branch: new_branch,
                }
            }
            other => other.clone(),
        };

        // Step 6: re-register under the new name and persist.
        engine
            .unregister_writable_mem(&params.old)
            .map_err(FullEngineError::from)?;
        let new_mount = memstead_base::Mount {
            mem: params.new.clone(),
            schema: mount.schema.clone(),
            storage: new_storage,
            capability: mount.capability,
            lifecycle: mount.lifecycle,
            cross_linkable: mount.cross_linkable,
            migration_target: mount.migration_target.clone(),
        };
        let factory = engine.backend_factory();
        let backend = factory(&new_mount)
            .map_err(|e| memstead_base::EngineError::Mem(format!("instantiate backend: {e}")))?;
        let origin = memstead_base::MemOrigin::RuntimeCreated {
            at: std::time::SystemTime::now(),
            by_tool: "memstead mem rename",
        };
        engine
            .register_writable_mem(new_mount, backend, origin)
            .map_err(FullEngineError::from)?;
        engine.persist_state().map_err(FullEngineError::from)?;
    }

    // ---- Step 7: workspace grants (idempotent; both modes) ----
    if let Some(root) = engine.workspace_root().map(|p| p.to_path_buf()) {
        crate::workspace_config_edit::rename_mem_in_cross_links(&root, &params.old, &params.new)
            .map_err(|e| memstead_base::EngineError::Mem(format!("grants rewrite: {e}")))?;

        // ---- Step 8: binding + findings stores (idempotent) ----
        let store_dir = root.join(memstead_base::WORKSPACE_STORE_DIR);
        let projections_old = store_dir.join("projections").join(&params.old);
        let projections_new = store_dir.join("projections").join(&params.new);
        if projections_old.is_dir() && !projections_new.exists() {
            std::fs::rename(&projections_old, &projections_new).map_err(|e| {
                memstead_base::EngineError::Mem(format!("move projections dir: {e}"))
            })?;
        }
        if projections_new.is_dir() {
            for entry in std::fs::read_dir(&projections_new)
                .map_err(|e| memstead_base::EngineError::Mem(format!("read projections: {e}")))?
            {
                let path = entry
                    .map_err(|e| memstead_base::EngineError::Mem(format!("read projections: {e}")))?
                    .path();
                if path.extension().and_then(|e| e.to_str()) != Some("json") {
                    continue;
                }
                let Ok(text) = std::fs::read_to_string(&path) else {
                    continue;
                };
                let Ok(mut doc) = serde_json::from_str::<serde_json::Value>(&text) else {
                    continue;
                };
                if doc.get("destination_mem").and_then(|v| v.as_str()) == Some(params.old.as_str())
                {
                    doc["destination_mem"] = serde_json::Value::String(params.new.clone());
                    let mut out = serde_json::to_string_pretty(&doc).unwrap_or(text);
                    out.push('\n');
                    std::fs::write(&path, out).map_err(|e| {
                        memstead_base::EngineError::Mem(format!("rewrite binding: {e}"))
                    })?;
                }
            }
        }
        let findings_old = store_dir.join("state").join("findings").join(&params.old);
        let findings_new = store_dir.join("state").join("findings").join(&params.new);
        if findings_old.is_dir() && !findings_new.exists() {
            std::fs::rename(&findings_old, &findings_new)
                .map_err(|e| memstead_base::EngineError::Mem(format!("move findings dir: {e}")))?;
        }
    }

    let note_warning = engine.note_missing_warning("rename_mem", params.note.as_deref());
    Ok(MemRenameResponse {
        old: params.old,
        new: params.new,
        rewritten_mems: sweep.rewritten_mems,
        resumed,
        warnings: note_warning.into_iter().collect(),
    })
}