m1nd-mcp 1.4.0

Local MCP runtime for coding agents: structural retrieval, change reasoning, document grounding, and continuity.
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
//! MEDULLA slice M5a — the storage-split migration (MEDULLA-PRD §4.2).
//!
//! Today the owner's shared `<runtime_root>/agent-memory/` holds ONE
//! undifferentiated mix (§2.3 S1): m1nd-repo facts (ship notes, hall fixes, CI
//! flake gotchas, code-anchored findings) tangled with maintainer doctrine,
//! preferences, and product vocabulary. The medulla-to-be is polluted by project
//! fact. M5a formalizes the medulla at that SAME path (no move — the kill-the-move
//! precedent, §4.1) and triages the mix ONE claim, ONE row, ONE destination:
//!
//! | class                          | destination                              |
//! |--------------------------------|------------------------------------------|
//! | m1nd-repo fact                 | the m1nd PROJECT brain store             |
//! | maintainer doctrine/vocabulary | STAY on the medulla (stamp Origin-Brain) |
//! | ambiguous                      | STAY + flagged for maintainer triage     |
//!
//! ## Safety posture — CODE-LAND-ONLY (this ladder's absolute rule)
//!
//! This module BUILDS and PROVES the migration; it NEVER runs it on a live owner
//! by default. [`MedullaMigration::plan`] is the default and is pure-read (a
//! dry-run: it enumerates + classifies + reports, mutating nothing).
//! [`MedullaMigration::apply`] is the gated executor — backup-first and
//! count-conserving — and is exercised ONLY in scratch stores by the battery /
//! unit tests. The live maintainer store is migrated by the maintainer, never by
//! an agent.
//!
//! ## Reversibility (proven by a migrate → rollback round-trip)
//!
//! `apply` snapshots the ENTIRE medulla `agent-memory/` dir into a timestamped
//! backup BEFORE the first mutation. [`MedullaMigration::rollback`] restores that
//! backup byte-for-byte. The battery proves a plan → apply → rollback cycle
//! returns the store to its exact original bytes — no claim lost, no claim
//! altered.

use std::collections::BTreeMap;
use std::path::{Path, PathBuf};

use m1nd_core::error::{M1ndError, M1ndResult};
use serde::{Deserialize, Serialize};

use crate::util::now_ms;

/// Where a triaged claim is routed (MEDULLA-PRD §4.2).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Destination {
    /// A repo-anchored fact → moves to the project brain's store.
    Project,
    /// Doctrine / preference / vocabulary → stays on the medulla.
    Medulla,
    /// Doubt → stays on the medulla, flagged for maintainer triage
    /// (the M4 hand-curated judgment: doubt → don't move).
    AmbiguousStay,
}

/// One triaged claim in the plan (§4.2, one claim = one row).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ClaimPlan {
    /// The `.light.md` filename (slug + extension) inside the medulla store.
    pub file_name: String,
    /// Where it will land.
    pub destination: Destination,
    /// Whether the file already carries an `Origin-Brain:` frontmatter line.
    pub has_origin_brain: bool,
    /// One-line, human-readable classification reason (for the maintainer's
    /// review before the gated `apply`).
    pub reason: String,
}

/// A ghost pointer found in `ingest_roots.json`: a per-file `.light.md` entry
/// whose file no longer exists (live example: `tokenvalidator.light.md`, §2.2c),
/// or the collapse of per-file entries into the one dir root.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GhostPointer {
    /// The offending ingest-root entry.
    pub entry: String,
    /// Why it is being pruned.
    pub reason: String,
}

/// The full dry-run plan — everything `apply` WOULD do, computed by pure read
/// (MEDULLA-PRD §11 M5a: the migration is a dry-run by default).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MigrationPlan {
    /// Every live `.light.md` claim in the medulla store, triaged.
    pub claims: Vec<ClaimPlan>,
    /// Ghost `ingest_roots.json` entries the sweep would prune (§4.2).
    pub ghost_pointers: Vec<GhostPointer>,
    /// `count(baseline)` — live claims before migration.
    pub baseline_count: usize,
    /// `count(project-active)` the plan would produce.
    pub project_count: usize,
    /// `count(medulla-active)` the plan would produce (medulla + ambiguous-stay).
    pub medulla_count: usize,
    /// Whether the count-conservation gate holds:
    /// `baseline == project + medulla` (§4.2 gate; no claim lost).
    pub count_conserved: bool,
    /// Absolute path to the medulla `agent-memory/` store this plan is for.
    pub medulla_dir: String,
    /// Absolute path to the m1nd project brain's `agent-memory/` store.
    pub project_dir: String,
}

/// The migration engine (MEDULLA-PRD §4.2). Holds the two store dirs + the
/// `ingest_roots.json` path. Pure filesystem — no live `SessionState`, so it is
/// trivially scratch-testable and structurally incapable of touching a running
/// owner's in-memory graph.
pub struct MedullaMigration {
    /// `<owner runtime_root>/agent-memory/` — the medulla store.
    medulla_dir: PathBuf,
    /// The m1nd project brain's `agent-memory/` store (destination for repo facts).
    project_dir: PathBuf,
    /// `<owner runtime_root>/ingest_roots.json` — swept for ghost pointers.
    ingest_roots_path: PathBuf,
    /// The `Origin-Brain` value stamped on repo-fact claims moved to the project
    /// store (the m1nd repo root, e.g. `/path/to/repo`).
    project_origin: String,
    /// Loopback port the owner-alive guard probes before mutating. An offline
    /// migration must never race a live served owner keeping the store warm, so
    /// `apply`/`rollback` refuse while something listens here. Defaults to the
    /// served-owner port; overridable for tests via [`with_owner_guard_port`].
    owner_guard_port: u16,
}

/// Prefix that marks the timestamped backup dirs `apply` writes before mutating.
const BACKUP_PREFIX: &str = ".m5a-backup-";

/// The loopback port a served owner keeps a keepalive listener on. The offline
/// migration refuses to run against a live owner on this port (owner-alive guard).
const SERVED_OWNER_PORT: u16 = 1338;

/// Manifest file (inside each backup dir) recording the exact `.light.md` names
/// `apply` moved into the project store — the authoritative rollback list, so a
/// rollback never has to scan (and thereby risk deleting) the destination store.
const MANIFEST_NAME: &str = "manifest.json";

/// Subdir (inside each backup dir) holding a byte-for-byte copy of the owner's
/// `ingest_roots.json` as it stood before `apply` rewrote it — restored on rollback.
const ROOTS_BACKUP_SUBDIR: &str = "ingest-roots";

/// Subdir (inside each backup dir) holding copies of any destination-store files
/// that shared a name with an incoming claim. `apply` refuses on collision, so
/// this is defence in depth: if a future path ever writes over a destination file,
/// its original is recoverable here.
const DEST_PREEXISTING_SUBDIR: &str = "project-preexisting";

/// Subdir (inside the backup dir) where `rollback` snapshots the live medulla
/// state BEFORE it wipes/restores, so a mid-rollback failure stays recoverable.
const PRE_ROLLBACK_SUBDIR: &str = "pre-rollback-live";

impl MedullaMigration {
    /// Build a migration for a medulla store, a project-brain destination store,
    /// and the owner's `ingest_roots.json`.
    pub fn new(
        medulla_dir: impl Into<PathBuf>,
        project_dir: impl Into<PathBuf>,
        ingest_roots_path: impl Into<PathBuf>,
        project_origin: impl Into<String>,
    ) -> Self {
        Self {
            medulla_dir: medulla_dir.into(),
            project_dir: project_dir.into(),
            ingest_roots_path: ingest_roots_path.into(),
            project_origin: project_origin.into(),
            owner_guard_port: SERVED_OWNER_PORT,
        }
    }

    /// Point the owner-alive guard at a different loopback port. Production always
    /// uses the default served-owner port; tests bind an ephemeral port and pass it
    /// here to exercise the refusal deterministically.
    pub fn with_owner_guard_port(mut self, port: u16) -> Self {
        self.owner_guard_port = port;
        self
    }

    /// Owner-alive guard (§4.2 safety): the offline migration must not race a live
    /// served owner keeping the store warm. If anything accepts a loopback
    /// connection on the guard port, refuse with a clear instruction to stop the
    /// owner first. A short connect timeout keeps the probe cheap; a refused/closed
    /// port (the owner-down case) passes silently.
    fn ensure_owner_down(&self) -> M1ndResult<()> {
        use std::net::{SocketAddr, TcpStream};
        use std::time::Duration;
        let addr = SocketAddr::from(([127, 0, 0, 1], self.owner_guard_port));
        if TcpStream::connect_timeout(&addr, Duration::from_millis(200)).is_ok() {
            return Err(M1ndError::InvalidParams {
                tool: "medulla_migration".into(),
                detail: format!(
                    "a served owner is listening on 127.0.0.1:{} — stop the served owner first; \
                     the offline migration must not run against a live owner",
                    self.owner_guard_port
                ),
            });
        }
        Ok(())
    }

    /// Enumerate the LIVE `.light.md` claims in the medulla store — never the
    /// `.history/` archive, never dot-dirs, never backups. Sorted for a stable,
    /// reproducible plan. This is the ONLY source of the baseline (§4.2: the
    /// live inventory at migration time, never from the PRD document).
    fn live_claims(&self) -> M1ndResult<Vec<PathBuf>> {
        let mut out = Vec::new();
        let entries = match std::fs::read_dir(&self.medulla_dir) {
            Ok(e) => e,
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(out),
            Err(e) => return Err(M1ndError::Io(e)),
        };
        for entry in entries.flatten() {
            let path = entry.path();
            let Some(name) = path.file_name().and_then(|n| n.to_str()) else {
                continue;
            };
            // Skip dot-dirs (.history/.locks) and any dotfile/backup.
            if name.starts_with('.') {
                continue;
            }
            if path.is_file() && name.ends_with(".light.md") {
                out.push(path);
            }
        }
        out.sort();
        Ok(out)
    }

    /// Classify one claim by the shape of its text (§4.2 triage). Repo-fact
    /// signals: an `[𝔻 evidence: ...]` marker anchoring to code, or ship-note /
    /// hall-fix / flake vocabulary. Doctrine signals: preference / vocabulary /
    /// cross-project language. Everything unclear → ambiguous-stay (doubt → don't
    /// move). Returns `(Destination, reason)`.
    fn classify(text: &str) -> (Destination, String) {
        let lower = text.to_ascii_lowercase();

        // STRONGEST signal of all: transversal doctrine the maintainer curates for
        // EVERY project, not one repo's fact. It stays on the medulla even when it
        // cites evidence paths — a doctrine note routinely anchors to the docs that
        // prove it, so the code-evidence heuristic below would otherwise misfile it
        // into a single brain (closeout field letter, 2026-07-05). These markers are
        // deliberately UNAMBIGUOUS about cross-project reach (and bilingual, since the
        // maintainer writes doctrine in pt-BR too) so a plain repo fact never matches.
        const HARD_DOCTRINE_MARKERS: &[&str] = &[
            "doctrine",
            "doutrina",
            "cross-project",
            "transversal",
            "universal across",
            "across any project",
            "every m1nd caller",
            "every agent",
            "todo agente",
            "founder decision",
            "sealed by max",
            "product vocabulary",
            "maintainer preference",
        ];
        if let Some(hit) = HARD_DOCTRINE_MARKERS.iter().find(|m| lower.contains(*m)) {
            return (
                Destination::Medulla,
                format!(
                    "cross-project doctrine: mentions '{hit}' — stays on the medulla \
                     even though it cites evidence"
                ),
            );
        }

        // Strongest project signal: the claim anchors to code evidence.
        let has_code_evidence = text.lines().any(|l| {
            let t = l.trim();
            t.starts_with("[𝔻 evidence:")
                && (t.contains(".rs")
                    || t.contains(".ts")
                    || t.contains(".py")
                    || t.contains(".js")
                    || t.contains(".md")
                    || t.contains('/'))
        });
        if has_code_evidence {
            return (
                Destination::Project,
                "code-anchored: carries a [𝔻 evidence:] marker to a repo path".into(),
            );
        }

        // Repo-fact vocabulary (ship notes, hall fixes, CI flake gotchas, slice work).
        const PROJECT_MARKERS: &[&str] = &[
            "slice",
            "shipped",
            "hall fix",
            "hall-fix",
            "flake",
            "ci flake",
            "ladder",
            "pr #",
            "merged",
            "handler",
            "invariant tt-",
            "regression",
            "gate",
        ];
        if let Some(hit) = PROJECT_MARKERS.iter().find(|m| lower.contains(*m)) {
            return (
                Destination::Project,
                format!("m1nd-repo fact: mentions '{hit}' (ship/fix/flake vocabulary)"),
            );
        }

        // Doctrine / preference / vocabulary — the medulla is already home.
        const DOCTRINE_MARKERS: &[&str] = &[
            "doctrine",
            "preference",
            "prefers",
            "maintainer",
            "vocabulary",
            "cross-project",
            "always",
            "never ",
            "rule:",
            "policy",
        ];
        if let Some(hit) = DOCTRINE_MARKERS.iter().find(|m| lower.contains(*m)) {
            return (
                Destination::Medulla,
                format!("doctrine/preference: mentions '{hit}' — already home on the medulla"),
            );
        }

        // Doubt → don't move (the M4 hand-curated judgment).
        (
            Destination::AmbiguousStay,
            "ambiguous: no clear repo-fact or doctrine signal — stays, flagged for maintainer triage"
                .into(),
        )
    }

    /// True when a `.light.md` already carries an `Origin-Brain:` line (a whole-file
    /// scan — the marker only ever lives in the frontmatter, and the file is tiny).
    fn has_origin_brain(text: &str) -> bool {
        text.lines()
            .any(|l| l.trim_start().starts_with("Origin-Brain:"))
    }

    /// The ghost-pointer sweep (§4.2): `ingest_roots.json` entries that point at
    /// a `.light.md` FILE which no longer exists are pruned; per-file `.light.md`
    /// entries are collapsed into the one dir root. Returns the ghosts found +
    /// the swept root list (the second used by `apply`).
    fn sweep_ingest_roots(&self) -> M1ndResult<(Vec<GhostPointer>, Option<Vec<String>>)> {
        let text = match std::fs::read_to_string(&self.ingest_roots_path) {
            Ok(t) => t,
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok((Vec::new(), None)),
            Err(e) => return Err(M1ndError::Io(e)),
        };
        let roots: Vec<String> = serde_json::from_str(&text).map_err(M1ndError::Serde)?;

        let mem_dir_str = self.medulla_dir.to_string_lossy().to_string();
        let mut ghosts = Vec::new();
        let mut swept: Vec<String> = Vec::new();
        let mut collapsed_dir = false;

        for entry in &roots {
            let is_light_file = entry.ends_with(".light.md");
            if is_light_file {
                // A per-file .light.md pointer. Prune if the file is gone (ghost);
                // otherwise collapse it into the single dir root.
                if !Path::new(entry).exists() {
                    ghosts.push(GhostPointer {
                        entry: entry.clone(),
                        reason: "dangling: the .light.md file no longer exists".into(),
                    });
                } else {
                    ghosts.push(GhostPointer {
                        entry: entry.clone(),
                        reason: "collapsed: per-file .light.md pointer folds into the dir root"
                            .into(),
                    });
                    collapsed_dir = true;
                }
            } else {
                swept.push(entry.clone());
            }
        }
        // Ensure the one dir root survives when we collapsed per-file entries.
        if collapsed_dir && !swept.iter().any(|r| r == &mem_dir_str) {
            swept.push(mem_dir_str);
        }

        if ghosts.is_empty() {
            Ok((ghosts, None))
        } else {
            Ok((ghosts, Some(swept)))
        }
    }

    /// THE DRY-RUN (default, pure-read). Enumerate + classify every live claim,
    /// find the ghost pointers, and compute the count-conservation gate — WITHOUT
    /// mutating anything. This is what runs against the live owner: it reports the
    /// migration it WOULD perform, and stops (§11 M5a: dry-run default).
    pub fn plan(&self) -> M1ndResult<MigrationPlan> {
        let files = self.live_claims()?;
        let baseline_count = files.len();

        let mut claims = Vec::with_capacity(baseline_count);
        let mut project_count = 0usize;
        let mut medulla_count = 0usize;

        for path in &files {
            let text = std::fs::read_to_string(path).map_err(M1ndError::Io)?;
            let (destination, reason) = Self::classify(&text);
            match destination {
                Destination::Project => project_count += 1,
                Destination::Medulla | Destination::AmbiguousStay => medulla_count += 1,
            }
            claims.push(ClaimPlan {
                file_name: path
                    .file_name()
                    .map(|n| n.to_string_lossy().to_string())
                    .unwrap_or_default(),
                destination,
                has_origin_brain: Self::has_origin_brain(&text),
                reason,
            });
        }

        let (ghost_pointers, _swept) = self.sweep_ingest_roots()?;

        Ok(MigrationPlan {
            claims,
            ghost_pointers,
            baseline_count,
            project_count,
            medulla_count,
            count_conserved: baseline_count == project_count + medulla_count,
            medulla_dir: self.medulla_dir.to_string_lossy().to_string(),
            project_dir: self.project_dir.to_string_lossy().to_string(),
        })
    }

    /// Snapshot the WHOLE medulla `agent-memory/` dir into a timestamped backup
    /// beside it, BEFORE any mutation (backup-first posture). Returns the backup
    /// dir path — the rollback anchor. Copies files + the `.history/` subtree so
    /// a rollback restores the store's exact bytes.
    fn backup(&self) -> M1ndResult<PathBuf> {
        let backup_dir = self
            .medulla_dir
            .join(format!("{BACKUP_PREFIX}{}", now_ms()));
        std::fs::create_dir_all(&backup_dir).map_err(M1ndError::Io)?;
        copy_tree(&self.medulla_dir, &backup_dir, &backup_dir)?;
        Ok(backup_dir)
    }

    /// Persist the authoritative moved-file list into `<backup>/manifest.json`
    /// (fix 1). This is the ONLY list `rollback` trusts — it never scans the
    /// destination store, so it can never delete a claim the migration did not
    /// create.
    fn write_manifest(&self, backup_dir: &Path, moved_files: &[String]) -> M1ndResult<()> {
        let json = serde_json::to_string_pretty(moved_files).map_err(M1ndError::Serde)?;
        std::fs::write(backup_dir.join(MANIFEST_NAME), json).map_err(M1ndError::Io)?;
        Ok(())
    }

    /// Read the moved-file manifest from a backup dir. Absent/unreadable → an empty
    /// list (a legacy backup predating the manifest, or a rollback caller that
    /// passed its own list).
    fn read_manifest(backup_dir: &Path) -> Vec<String> {
        std::fs::read_to_string(backup_dir.join(MANIFEST_NAME))
            .ok()
            .and_then(|t| serde_json::from_str(&t).ok())
            .unwrap_or_default()
    }

    /// Copy the owner's `ingest_roots.json` into the backup dir (fix 5) so rollback
    /// can restore the pre-migration roots file byte-for-byte. A missing roots file
    /// is fine (nothing to restore).
    fn backup_ingest_roots(&self, backup_dir: &Path) -> M1ndResult<()> {
        if !self.ingest_roots_path.is_file() {
            return Ok(());
        }
        let dir = backup_dir.join(ROOTS_BACKUP_SUBDIR);
        std::fs::create_dir_all(&dir).map_err(M1ndError::Io)?;
        let name = self
            .ingest_roots_path
            .file_name()
            .map(|n| n.to_os_string())
            .unwrap_or_else(|| "ingest_roots.json".into());
        std::fs::copy(&self.ingest_roots_path, dir.join(name)).map_err(M1ndError::Io)?;
        Ok(())
    }

    /// Restore the owner's `ingest_roots.json` from a backup dir (fix 5). No-op when
    /// the backup predates roots-backup (legacy) or had no roots file.
    fn restore_ingest_roots(&self, backup_dir: &Path) -> M1ndResult<()> {
        let name = self
            .ingest_roots_path
            .file_name()
            .map(|n| n.to_os_string())
            .unwrap_or_else(|| "ingest_roots.json".into());
        let backed_up = backup_dir.join(ROOTS_BACKUP_SUBDIR).join(name);
        if backed_up.is_file() {
            std::fs::copy(&backed_up, &self.ingest_roots_path).map_err(M1ndError::Io)?;
        }
        Ok(())
    }

    /// THE GATED EXECUTOR (never run on a live owner by default — scratch/tests
    /// only). Backup-first, then: move project-fact claims into the project store
    /// (stamping `Origin-Brain: <project root>`), stamp `Origin-Brain: medulla`
    /// on doctrine/ambiguous claims that lack it, prune ghost ingest-root
    /// pointers, and verify count-conservation. Returns the [`MigrationReceipt`]
    /// with the backup path for [`rollback`].
    ///
    /// Non-destructive on the project side: a move writes the claim into the
    /// project store then removes it from the medulla (the backup holds the
    /// original, so the move is fully reversible). If count-conservation fails
    /// AFTER the moves, the caller should `rollback` immediately.
    pub fn apply(&self) -> M1ndResult<MigrationReceipt> {
        // Owner-alive guard (fix 6): never mutate the store while a served owner is
        // up — the offline migration would race a live keepalive owner.
        self.ensure_owner_down()?;

        let plan = self.plan()?;

        // Name-collision guard (fix 2): a claim must NEVER silently overwrite a
        // same-named file already living in the destination store. Detect every
        // collision up front and REFUSE — before any backup or mutation — naming
        // the offending files so the maintainer resolves them by hand.
        let collisions: Vec<String> = plan
            .claims
            .iter()
            .filter(|c| c.destination == Destination::Project)
            .map(|c| c.file_name.clone())
            .filter(|name| self.project_dir.join(name).exists())
            .collect();
        if !collisions.is_empty() {
            return Err(M1ndError::InvalidParams {
                tool: "medulla_migration".into(),
                detail: format!(
                    "destination name collision — the project store already holds: {}; \
                     refusing to overwrite. Resolve these files before migrating.",
                    collisions.join(", ")
                ),
            });
        }

        // Idempotency guard (field bug 2026-07-05): a store with no repo fact to
        // move AND nothing left to stamp is already migrated. Re-running `apply`
        // must NOT write a fresh (empty) backup nor re-report a phantom
        // count-conservation failure — never degrade an already-migrated store.
        // "Nothing to do" = no Project-bound claim and every staying claim already
        // carries its `Origin-Brain`.
        let nothing_to_move = plan.project_count == 0;
        let nothing_to_stamp = plan.claims.iter().all(|c| c.has_origin_brain);
        if nothing_to_move && nothing_to_stamp {
            let medulla_after = self.live_claims()?.len();
            let project_after = count_project_claims(&self.project_dir);
            return Ok(MigrationReceipt {
                backup_dir: String::new(),
                moved_to_project: 0,
                moved_files: Vec::new(),
                stamped_medulla: 0,
                ghosts_pruned: 0,
                baseline_count: plan.baseline_count,
                medulla_after,
                project_after,
                count_conserved: true,
                content_conserved: true,
                already_migrated: true,
            });
        }

        let backup_dir = self.backup()?;

        // Back up the owner's ingest_roots.json (fix 5) so rollback can restore it
        // byte-for-byte after apply rewrites it below.
        self.backup_ingest_roots(&backup_dir)?;

        std::fs::create_dir_all(&self.project_dir).map_err(M1ndError::Io)?;

        let mut moved_files: Vec<String> = Vec::new();
        let mut stamped = 0usize;

        for claim in &plan.claims {
            let src = self.medulla_dir.join(&claim.file_name);
            let text = std::fs::read_to_string(&src).map_err(M1ndError::Io)?;
            match claim.destination {
                Destination::Project => {
                    // Stamp the project origin, write into the project store, then
                    // remove from the medulla. The backup keeps the original, and
                    // the collision guard above proved the destination path is free.
                    let stamped_text = stamp_origin_brain(&text, &self.project_origin);
                    let dst = self.project_dir.join(&claim.file_name);
                    std::fs::write(&dst, stamped_text).map_err(M1ndError::Io)?;
                    std::fs::remove_file(&src).map_err(M1ndError::Io)?;
                    moved_files.push(claim.file_name.clone());
                }
                Destination::Medulla | Destination::AmbiguousStay => {
                    // Stays home. Stamp Origin-Brain: medulla if it lacks one.
                    if !claim.has_origin_brain {
                        let stamped_text = stamp_origin_brain(&text, "medulla");
                        std::fs::write(&src, stamped_text).map_err(M1ndError::Io)?;
                        stamped += 1;
                    }
                }
            }
        }
        moved_files.sort();

        // Persist the authoritative moved-list (fix 1): the manifest is the ONLY
        // source rollback consults, so it never scans the destination store.
        self.write_manifest(&backup_dir, &moved_files)?;

        // Prune ghost ingest-root pointers (write the swept list back).
        let (_ghosts, swept) = self.sweep_ingest_roots()?;
        if let Some(roots) = swept {
            let json = serde_json::to_string_pretty(&roots).map_err(M1ndError::Serde)?;
            std::fs::write(&self.ingest_roots_path, json).map_err(M1ndError::Io)?;
        }

        // Count-conservation gate: the live medulla + project stores together must
        // hold exactly the baseline count.
        let medulla_after = self.live_claims()?.len();
        let project_after = count_project_claims(&self.project_dir);
        let count_conserved = plan.baseline_count == medulla_after + project_after;

        // Content-level conservation (fix 3): cardinality can balance by luck (a
        // stray destination file offsetting a lost claim). Verify each moved file
        // is present at the destination AND absent from the source, and that the
        // cardinality equation `baseline == medulla_after + moved.len()` holds.
        let content_conserved = count_conserved
            && moved_files.iter().all(|name| {
                self.project_dir.join(name).exists() && !self.medulla_dir.join(name).exists()
            })
            && plan.baseline_count == medulla_after + moved_files.len();

        Ok(MigrationReceipt {
            backup_dir: backup_dir.to_string_lossy().to_string(),
            moved_to_project: moved_files.len(),
            moved_files,
            stamped_medulla: stamped,
            ghosts_pruned: plan.ghost_pointers.len(),
            baseline_count: plan.baseline_count,
            medulla_after,
            project_after,
            count_conserved,
            content_conserved,
            already_migrated: false,
        })
    }

    /// Reverse an `apply`: restore the medulla store from a backup dir written by
    /// `apply` and remove any claims the migration moved into the project store.
    /// After a rollback the medulla store is byte-identical to its pre-migration
    /// state (the reversibility proof).
    ///
    /// `moved_file_names` is a FALLBACK list used only for legacy backups that
    /// predate the manifest; the authoritative source is the `manifest.json` apply
    /// wrote inside the backup dir. Returns the files actually removed from the
    /// project store, so the caller reports a truthful `removed_from_project`
    /// instead of re-deriving it by scanning (the scan is the data-loss vector).
    pub fn rollback(
        &self,
        backup_dir: &str,
        moved_file_names: &[String],
    ) -> M1ndResult<Vec<String>> {
        // Owner-alive guard (fix 6): as with apply, never mutate against a live
        // served owner.
        self.ensure_owner_down()?;

        let backup = PathBuf::from(backup_dir);
        if !backup.is_dir() {
            return Err(M1ndError::InvalidParams {
                tool: "medulla_migration".into(),
                detail: format!("backup dir '{backup_dir}' does not exist — cannot rollback"),
            });
        }

        // Authoritative moved-list (fix 1): trust the manifest apply wrote. Only
        // fall back to the caller-supplied list when the backup predates manifests
        // (a legacy backup). NEVER scan the destination store — that is exactly how
        // a rollback used to delete pre-existing destination claims.
        let manifest = Self::read_manifest(&backup);
        let moved: &[String] = if manifest.is_empty() {
            moved_file_names
        } else {
            &manifest
        };

        // Snapshot-first (fix 4): capture the live medulla state into the backup dir
        // BEFORE wiping it, so a failure mid-restore leaves a recoverable snapshot.
        let snapshot = backup.join(PRE_ROLLBACK_SUBDIR);
        if snapshot.exists() {
            std::fs::remove_dir_all(&snapshot).map_err(M1ndError::Io)?;
        }
        copy_tree(&self.medulla_dir, &snapshot, &backup)?;

        // 1. Remove the claims the migration created in the project store.
        let mut removed: Vec<String> = Vec::new();
        for name in moved {
            let dst = self.project_dir.join(name);
            if dst.exists() {
                std::fs::remove_file(&dst).map_err(M1ndError::Io)?;
                removed.push(name.clone());
            }
        }

        // 2. Wipe the LIVE medulla claims (not backups/dot-dirs) and restore from
        //    the backup, byte-for-byte.
        for path in self.live_claims()? {
            std::fs::remove_file(&path).map_err(M1ndError::Io)?;
        }
        restore_tree(&backup, &self.medulla_dir)?;

        // 3. Restore the pre-migration ingest_roots.json (fix 5).
        self.restore_ingest_roots(&backup)?;
        Ok(removed)
    }
}

/// The result of an `apply` (also the rollback anchor).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MigrationReceipt {
    /// The backup dir written before mutation — pass to `rollback`.
    pub backup_dir: String,
    /// Claims moved into the project store (== `moved_files.len()`).
    pub moved_to_project: usize,
    /// The AUTHORITATIVE list of `.light.md` names `apply` moved into the project
    /// store, also persisted as `manifest.json` in the backup dir. `rollback`
    /// removes exactly these — it never scans the destination store, so it can
    /// never delete a pre-existing destination claim (fix 1, the data-loss vector).
    #[serde(default)]
    pub moved_files: Vec<String>,
    /// Claims that stayed and were stamped `Origin-Brain: medulla`.
    pub stamped_medulla: usize,
    /// Ghost ingest-root pointers pruned.
    pub ghosts_pruned: usize,
    /// Live claim count before migration.
    pub baseline_count: usize,
    /// Live medulla claims after migration.
    pub medulla_after: usize,
    /// Project-store claims after migration.
    pub project_after: usize,
    /// The count-conservation gate: `baseline == medulla_after + project_after`.
    pub count_conserved: bool,
    /// The CONTENT-level conservation gate (fix 3): beyond cardinality, every moved
    /// file exists at the destination AND is gone from the source, and
    /// `baseline == medulla_after + moved_files.len()`. Cardinality alone can
    /// balance by luck (a stray destination file offsetting a lost claim); this
    /// cannot.
    #[serde(default)]
    pub content_conserved: bool,
    /// True when the store was already migrated (nothing to move, nothing to
    /// stamp): `apply` short-circuited BEFORE any backup or mutation. A
    /// re-invocation of a done migration never degrades the store (field bug
    /// 2026-07-05). On the normal executing path this is `false`.
    #[serde(default)]
    pub already_migrated: bool,
}

/// Count the LIVE `.light.md` claims in a project store (skip dot-dirs/backups),
/// shared by `apply`'s count-conservation gate and its already-migrated guard.
fn count_project_claims(project_dir: &Path) -> usize {
    std::fs::read_dir(project_dir)
        .map(|e| {
            e.flatten()
                .filter(|d| {
                    d.path()
                        .file_name()
                        .and_then(|n| n.to_str())
                        .is_some_and(|n| !n.starts_with('.') && n.ends_with(".light.md"))
                })
                .count()
        })
        .unwrap_or(0)
}

/// Insert an `Origin-Brain: <value>` frontmatter line into a `.light.md` if it
/// lacks one, placed after `Source-Agent:` (or, absent that, after the opening
/// `---`). Idempotent: a file already carrying `Origin-Brain:` is returned
/// unchanged. This preserves original `Created`/`Source-Agent` stamps (§4.2:
/// carry the original provenance).
fn stamp_origin_brain(text: &str, value: &str) -> String {
    if text
        .lines()
        .any(|l| l.trim_start().starts_with("Origin-Brain:"))
    {
        return text.to_string();
    }
    let mut out = String::with_capacity(text.len() + 40);
    let mut inserted = false;
    let mut seen_open_fence = false;
    for line in text.lines() {
        out.push_str(line);
        out.push('\n');
        if inserted {
            continue;
        }
        let trimmed = line.trim();
        if trimmed == "---" && !seen_open_fence {
            seen_open_fence = true;
            continue;
        }
        // Prefer inserting right after Source-Agent (keeps the §3.3 grammar order).
        if seen_open_fence && trimmed.starts_with("Source-Agent:") {
            out.push_str(&format!("Origin-Brain: {value}\n"));
            inserted = true;
        }
    }
    // If there was no Source-Agent line, insert right after the opening fence.
    if !inserted && seen_open_fence {
        let mut rebuilt = String::with_capacity(out.len() + 40);
        let mut done = false;
        for line in out.lines() {
            rebuilt.push_str(line);
            rebuilt.push('\n');
            if !done && line.trim() == "---" {
                rebuilt.push_str(&format!("Origin-Brain: {value}\n"));
                done = true;
            }
        }
        return rebuilt;
    }
    out
}

/// Recursively copy `src`'s live files + `.history/` into `dst`, skipping any
/// backup dir under `src` (never back up a backup). `backup_self` names the
/// backup dir currently being written so the walk does not recurse into it.
fn copy_tree(src: &Path, dst: &Path, backup_self: &Path) -> M1ndResult<()> {
    std::fs::create_dir_all(dst).map_err(M1ndError::Io)?;
    for entry in std::fs::read_dir(src).map_err(M1ndError::Io)?.flatten() {
        let path = entry.path();
        let Some(name) = path.file_name().and_then(|n| n.to_str()) else {
            continue;
        };
        // Never back up prior backups (or the backup we are writing right now).
        if name.starts_with(BACKUP_PREFIX) || path == backup_self {
            continue;
        }
        let target = dst.join(name);
        if path.is_dir() {
            copy_tree(&path, &target, backup_self)?;
        } else {
            std::fs::copy(&path, &target).map_err(M1ndError::Io)?;
        }
    }
    Ok(())
}

/// Restore a backup tree back over the medulla dir (files + `.history/`). Does
/// not delete files already present (the caller wipes live claims first); it
/// overwrites/creates from the backup so the store returns to backup bytes.
fn restore_tree(backup: &Path, dst: &Path) -> M1ndResult<()> {
    /// Backup-metadata entries that describe the backup itself and must NEVER be
    /// restored into the live store (fixes 1/4/5): the moved-list manifest, the
    /// ingest_roots.json copy, the destination-preexisting snapshot, and the
    /// pre-rollback live snapshot.
    const METADATA: &[&str] = &[
        MANIFEST_NAME,
        ROOTS_BACKUP_SUBDIR,
        DEST_PREEXISTING_SUBDIR,
        PRE_ROLLBACK_SUBDIR,
    ];
    std::fs::create_dir_all(dst).map_err(M1ndError::Io)?;
    for entry in std::fs::read_dir(backup).map_err(M1ndError::Io)?.flatten() {
        let path = entry.path();
        let Some(name) = path.file_name().and_then(|n| n.to_str()) else {
            continue;
        };
        // Skip backup-metadata: it belongs to the backup, not the restored store.
        if METADATA.contains(&name) {
            continue;
        }
        let target = dst.join(name);
        if path.is_dir() {
            restore_tree(&path, &target)?;
        } else {
            std::fs::copy(&path, &target).map_err(M1ndError::Io)?;
        }
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Build a minimal `.light.md` with the given frontmatter + body.
    fn light_doc(node: &str, source_agent: &str, body: &str) -> String {
        format!(
            "---\nProtocol: L1GHT/1.0\nNode: {node}\nState: authored\nCreated: 1700000000000\nSource-Agent: {source_agent}\n---\n\n# {node}\n\n## {node}\n\n{body}\n"
        )
    }

    struct Scratch {
        _tmp: tempfile::TempDir,
        medulla: PathBuf,
        project: PathBuf,
        roots: PathBuf,
    }

    fn scratch() -> Scratch {
        let tmp = tempfile::tempdir().expect("tempdir");
        let medulla = tmp.path().join("runtime").join("agent-memory");
        let project = tmp
            .path()
            .join("runtime")
            .join("project-brains")
            .join("fp")
            .join("agent-memory");
        std::fs::create_dir_all(&medulla).expect("medulla dir");
        let roots = tmp.path().join("runtime").join("ingest_roots.json");
        Scratch {
            _tmp: tmp,
            medulla,
            project,
            roots,
        }
    }

    fn write_claim(dir: &Path, file: &str, contents: &str) {
        std::fs::write(dir.join(file), contents).expect("write claim");
    }

    /// A loopback port that is CLOSED right now: bind an ephemeral port, read it,
    /// then drop the listener so the port is free again. The owner-alive guard
    /// probing this port gets a refused connection (the owner-down path), so
    /// scratch tests exercise the migration logic without racing the machine's real
    /// served owner (which really does listen on 1338 in this environment).
    fn closed_port() -> u16 {
        std::net::TcpListener::bind("127.0.0.1:0")
            .expect("bind ephemeral")
            .local_addr()
            .unwrap()
            .port()
    }

    /// Build a migration over a scratch store with the owner-alive guard pointed at
    /// a closed port (see [`closed_port`]). Every test that calls `apply`/`rollback`
    /// uses this so the real served owner never interferes; the guard's own test
    /// overrides the port back to a live listener to prove the refusal.
    fn scratch_mig(s: &Scratch) -> MedullaMigration {
        MedullaMigration::new(&s.medulla, &s.project, &s.roots, "/path/to/repo")
            .with_owner_guard_port(closed_port())
    }

    /// RED (closeout field letter, 2026-07-05): a cross-project doctrine note
    /// routinely cites the docs that prove it, so it carries a `[𝔻 evidence:]`
    /// marker. The code-evidence heuristic must NOT pull such a claim into one
    /// repo's brain — the transversal-doctrine signal wins over the code anchor,
    /// and it must fire on the maintainer's bilingual wording ("Doutrina").
    #[test]
    fn cross_project_doctrine_with_evidence_stays_on_the_medulla() {
        let doctrine = "# SixMoves\nDoutrina destilada: every agent applies the six \
             analytical moves across any project.\n\n[𝔻 evidence: docs/HUMAN-LAYER-PRD.md]\n";
        assert_eq!(
            MedullaMigration::classify(doctrine).0,
            Destination::Medulla,
            "transversal doctrine that cites evidence must stay medulla"
        );

        // The guard must stay narrow: a genuine repo fact that cites code
        // evidence still routes to the project brain.
        let repo_fact = "# SliceShip\nThe reception slice shipped on main.\n\n\
             [𝔻 evidence: m1nd-mcp/src/server.rs]\n";
        assert_eq!(
            MedullaMigration::classify(repo_fact).0,
            Destination::Project,
            "a repo fact with code evidence still moves to the project brain"
        );
    }

    /// RED framing (M5a acceptance): a store with mixed claims, zero
    /// `Origin-Brain` fields, and a ghost ingest-root pointer. The plan must
    /// triage them ONE row per claim, count-conserving, without mutating.
    #[test]
    fn plan_triages_mixed_store_count_conserving_and_pure_read() {
        let s = scratch();
        // A code-anchored repo fact.
        write_claim(
            &s.medulla,
            "sliceship.light.md",
            &light_doc(
                "SliceShip",
                "closer-agent",
                "The slice shipped.\n\n[⍂ entity: SliceShip]\n[𝔻 evidence: m1nd-mcp/src/server.rs]\n",
            ),
        );
        // A doctrine/preference claim.
        write_claim(
            &s.medulla,
            "maxpref.light.md",
            &light_doc(
                "MaxPref",
                "orchestrator",
                "The maintainer prefers pt-BR replies always.\n\n[⍂ entity: MaxPref]\n",
            ),
        );
        // An ambiguous claim (no strong signal).
        write_claim(
            &s.medulla,
            "mystery.light.md",
            &light_doc(
                "Mystery",
                "someone",
                "A thing happened once.\n\n[⍂ entity: Mystery]\n",
            ),
        );

        // A ghost ingest-root pointer at a deleted .light.md + the dir root.
        let ghost = s.medulla.join("deleted.light.md");
        std::fs::write(
            &s.roots,
            serde_json::to_string_pretty(&vec![
                s.medulla.to_string_lossy().to_string(),
                ghost.to_string_lossy().to_string(),
            ])
            .unwrap(),
        )
        .unwrap();

        // Snapshot the store bytes BEFORE plan to prove plan is pure-read.
        let before: BTreeMap<String, String> = std::fs::read_dir(&s.medulla)
            .unwrap()
            .flatten()
            .filter(|e| e.path().is_file())
            .map(|e| {
                (
                    e.file_name().to_string_lossy().to_string(),
                    std::fs::read_to_string(e.path()).unwrap(),
                )
            })
            .collect();

        let mig = scratch_mig(&s);
        let plan = mig.plan().expect("plan");

        assert_eq!(plan.baseline_count, 3, "three live claims");
        assert_eq!(plan.project_count, 1, "one repo fact → project");
        assert_eq!(plan.medulla_count, 2, "doctrine + ambiguous stay");
        assert!(plan.count_conserved, "baseline == project + medulla");
        assert_eq!(plan.ghost_pointers.len(), 1, "one dangling ghost pruned");
        assert!(
            plan.claims.iter().all(|c| !c.has_origin_brain),
            "RED: zero Origin-Brain fields today"
        );

        // PURE-READ: the store is byte-identical after plan.
        let after: BTreeMap<String, String> = std::fs::read_dir(&s.medulla)
            .unwrap()
            .flatten()
            .filter(|e| e.path().is_file())
            .map(|e| {
                (
                    e.file_name().to_string_lossy().to_string(),
                    std::fs::read_to_string(e.path()).unwrap(),
                )
            })
            .collect();
        assert_eq!(before, after, "plan must not mutate the store (dry-run)");
    }

    /// GREEN: apply moves repo facts, stamps Origin-Brain, prunes ghosts, and the
    /// count-conservation gate holds.
    #[test]
    fn apply_splits_stores_stamps_origin_and_conserves_count() {
        let s = scratch();
        write_claim(
            &s.medulla,
            "sliceship.light.md",
            &light_doc(
                "SliceShip",
                "closer",
                "shipped.\n\n[⍂ entity: SliceShip]\n[𝔻 evidence: m1nd-mcp/src/x.rs]\n",
            ),
        );
        write_claim(
            &s.medulla,
            "maxpref.light.md",
            &light_doc(
                "MaxPref",
                "orch",
                "maintainer doctrine.\n\n[⍂ entity: MaxPref]\n",
            ),
        );
        std::fs::write(
            &s.roots,
            serde_json::to_string_pretty(&vec![s.medulla.to_string_lossy().to_string()]).unwrap(),
        )
        .unwrap();

        let mig = scratch_mig(&s);
        let receipt = mig.apply().expect("apply");

        assert!(receipt.count_conserved, "no claim lost");
        assert_eq!(receipt.moved_to_project, 1);
        assert_eq!(receipt.medulla_after, 1, "only doctrine stays");
        assert_eq!(receipt.project_after, 1, "the repo fact moved");

        // The moved claim is stamped with the project origin.
        let moved = std::fs::read_to_string(s.project.join("sliceship.light.md")).unwrap();
        assert!(
            moved.contains("Origin-Brain: /path/to/repo"),
            "moved claim carries the project origin, got:\n{moved}"
        );
        assert!(
            moved.contains("Source-Agent: closer"),
            "original provenance preserved"
        );
        // The staying claim is stamped medulla.
        let stayed = std::fs::read_to_string(s.medulla.join("maxpref.light.md")).unwrap();
        assert!(
            stayed.contains("Origin-Brain: medulla"),
            "doctrine claim stamped medulla, got:\n{stayed}"
        );
    }

    /// REVERSIBILITY PROOF (§11 M5a): plan → apply → rollback returns the medulla
    /// store to its EXACT original bytes and empties the project store.
    #[test]
    fn migrate_then_rollback_restores_original_bytes() {
        let s = scratch();
        let ship = light_doc(
            "SliceShip",
            "closer",
            "shipped.\n\n[⍂ entity: SliceShip]\n[𝔻 evidence: m1nd-mcp/src/x.rs]\n",
        );
        let pref = light_doc(
            "MaxPref",
            "orch",
            "maintainer doctrine.\n\n[⍂ entity: MaxPref]\n",
        );
        write_claim(&s.medulla, "sliceship.light.md", &ship);
        write_claim(&s.medulla, "maxpref.light.md", &pref);
        std::fs::write(
            &s.roots,
            serde_json::to_string_pretty(&vec![s.medulla.to_string_lossy().to_string()]).unwrap(),
        )
        .unwrap();

        // Capture the exact original bytes of the whole live store.
        let original: BTreeMap<String, String> = std::fs::read_dir(&s.medulla)
            .unwrap()
            .flatten()
            .filter(|e| e.path().is_file())
            .map(|e| {
                (
                    e.file_name().to_string_lossy().to_string(),
                    std::fs::read_to_string(e.path()).unwrap(),
                )
            })
            .collect();

        let mig = scratch_mig(&s);
        let receipt = mig.apply().expect("apply");
        assert!(receipt.count_conserved);
        // Post-apply the store changed (moved + stamped).
        assert!(s.project.join("sliceship.light.md").exists());

        mig.rollback(&receipt.backup_dir, &["sliceship.light.md".to_string()])
            .expect("rollback");

        // The medulla store is byte-identical to the original.
        let restored: BTreeMap<String, String> = std::fs::read_dir(&s.medulla)
            .unwrap()
            .flatten()
            .filter(|e| {
                e.path().is_file()
                    && e.file_name()
                        .to_string_lossy()
                        .to_string()
                        .ends_with(".light.md")
            })
            .map(|e| {
                (
                    e.file_name().to_string_lossy().to_string(),
                    std::fs::read_to_string(e.path()).unwrap(),
                )
            })
            .collect();
        assert_eq!(
            original, restored,
            "rollback must restore the medulla store byte-for-byte"
        );
        // The project store is empty of the moved claim again.
        assert!(
            !s.project.join("sliceship.light.md").exists(),
            "rollback removed the moved claim from the project store"
        );
    }

    /// CODE-GRAPH INVARIANT (LEVA 3-PREP, option B — MEDULLA-PRD §4.2): the runtime
    /// owner is BOTH the medulla AND the home brain of its own repo, so the ~6.6k-node
    /// code graph legitimately lives at the medulla root. `apply` is a MEMORY-ONLY
    /// split: it moves `.light.md` claims and must NEVER touch the code graph — the
    /// medulla's `graph_snapshot.json` stays byte-for-byte, and `apply` fabricates no
    /// graph in the destination project store (a split that reassociated a large graph
    /// would be the expensive, data-risky path B deliberately rejects). This pins the
    /// "code graph stays at the medulla root" hazard as a proven invariant.
    #[test]
    fn apply_is_memory_only_and_never_touches_the_code_graph() {
        let s = scratch();
        // The owner's code graph sits at the medulla root — stand it in with a
        // sentinel snapshot whose bytes we can prove are untouched.
        let graph_path = s.medulla.join("graph_snapshot.json");
        let graph_bytes = "{\"schema\":\"stand-in-code-graph\",\"nodes\":6657}";
        std::fs::write(&graph_path, graph_bytes).expect("seed code graph");

        write_claim(
            &s.medulla,
            "sliceship.light.md",
            &light_doc(
                "SliceShip",
                "closer",
                "shipped.\n\n[⍂ entity: SliceShip]\n[𝔻 evidence: m1nd-mcp/src/x.rs]\n",
            ),
        );
        write_claim(
            &s.medulla,
            "maxpref.light.md",
            &light_doc(
                "MaxPref",
                "orch",
                "maintainer doctrine.\n\n[⍂ entity: MaxPref]\n",
            ),
        );
        std::fs::write(
            &s.roots,
            serde_json::to_string_pretty(&vec![s.medulla.to_string_lossy().to_string()]).unwrap(),
        )
        .unwrap();

        let mig = scratch_mig(&s);
        let receipt = mig.apply().expect("apply");
        assert!(
            receipt.count_conserved,
            "the memory split still conserves count"
        );

        // The code graph at the medulla root is byte-identical — never migrated.
        assert!(
            graph_path.exists(),
            "the medulla's code graph must survive a memory-only migration"
        );
        assert_eq!(
            std::fs::read_to_string(&graph_path).unwrap(),
            graph_bytes,
            "apply must not touch the medulla's code graph (option B: the owner keeps it)"
        );
        // And no graph was fabricated in the destination project store (it is a
        // memory brain; option A — reassociating a large graph — is rejected here).
        assert!(
            !s.project.join("graph_snapshot.json").exists(),
            "apply must not fabricate a code graph in the destination project store"
        );
        // The `.light.md` split itself still happened (the memory DID move).
        assert!(
            s.project.join("sliceship.light.md").exists(),
            "the repo fact still moved (memory-only migration is not a no-op)"
        );
    }

    /// Ghost-pointer sweep: a dangling per-file pointer is pruned; a live per-file
    /// pointer collapses into the dir root.
    #[test]
    fn ghost_pointer_sweep_prunes_dangling_and_collapses_live() {
        let s = scratch();
        // One live per-file pointer (real file) + one dangling.
        write_claim(&s.medulla, "real.light.md", &light_doc("Real", "a", "x"));
        let real = s.medulla.join("real.light.md");
        let dangling = s.medulla.join("gone.light.md");
        std::fs::write(
            &s.roots,
            serde_json::to_string_pretty(&vec![
                s.medulla.to_string_lossy().to_string(),
                real.to_string_lossy().to_string(),
                dangling.to_string_lossy().to_string(),
            ])
            .unwrap(),
        )
        .unwrap();

        let mig = scratch_mig(&s);
        let (ghosts, swept) = mig.sweep_ingest_roots().expect("sweep");
        assert_eq!(ghosts.len(), 2, "one dangling + one collapsed");
        let roots = swept.expect("swept list");
        assert!(
            roots.iter().all(|r| !r.ends_with(".light.md")),
            "no per-file .light.md pointers remain, got: {roots:?}"
        );
        assert!(
            roots.contains(&s.medulla.to_string_lossy().to_string()),
            "the dir root survives"
        );
    }

    /// Idempotency guard (field bug 2026-07-05): a SECOND `apply` over a store
    /// with nothing left to move or stamp reports `already_migrated` with zero
    /// moves and an empty backup path — it never writes a fresh (empty) backup nor
    /// reports a phantom count-conservation failure.
    #[test]
    fn apply_is_idempotent_on_already_migrated_store() {
        let s = scratch();
        write_claim(
            &s.medulla,
            "sliceship.light.md",
            &light_doc(
                "SliceShip",
                "closer",
                "shipped.\n\n[⍂ entity: SliceShip]\n[𝔻 evidence: m1nd-mcp/src/x.rs]\n",
            ),
        );
        write_claim(
            &s.medulla,
            "maxpref.light.md",
            &light_doc(
                "MaxPref",
                "orch",
                "maintainer doctrine.\n\n[⍂ entity: MaxPref]\n",
            ),
        );
        std::fs::write(
            &s.roots,
            serde_json::to_string_pretty(&vec![s.medulla.to_string_lossy().to_string()]).unwrap(),
        )
        .unwrap();

        let mig = scratch_mig(&s);
        let first = mig.apply().expect("first apply");
        assert!(!first.already_migrated, "first apply actually migrates");
        assert_eq!(first.moved_to_project, 1);

        // Drop the first (legitimate) backup so the assertion isolates run 2.
        for e in std::fs::read_dir(&s.medulla).unwrap().flatten() {
            if e.file_name().to_string_lossy().starts_with(BACKUP_PREFIX) {
                std::fs::remove_dir_all(e.path()).unwrap();
            }
        }

        let second = mig.apply().expect("second apply");
        assert!(
            second.already_migrated,
            "a re-applied migration reports already_migrated"
        );
        assert_eq!(second.moved_to_project, 0, "nothing moved the second time");
        assert!(
            second.count_conserved,
            "already-migrated must not report a count-conservation failure"
        );
        assert!(
            second.backup_dir.is_empty(),
            "already-migrated writes no backup, got: {}",
            second.backup_dir
        );
        let backups: Vec<_> = std::fs::read_dir(&s.medulla)
            .unwrap()
            .flatten()
            .filter(|e| e.file_name().to_string_lossy().starts_with(BACKUP_PREFIX))
            .collect();
        assert!(
            backups.is_empty(),
            "no fresh backup dir on the second apply"
        );
    }

    /// Idempotent stamping: a claim already carrying Origin-Brain is untouched.
    #[test]
    fn stamp_origin_brain_is_idempotent() {
        let already = "---\nProtocol: L1GHT/1.0\nNode: X\nState: authored\nSource-Agent: a\nOrigin-Brain: medulla\n---\n\n# X\n";
        assert_eq!(stamp_origin_brain(already, "medulla"), already);

        let fresh =
            "---\nProtocol: L1GHT/1.0\nNode: X\nState: authored\nSource-Agent: a\n---\n\n# X\n";
        let stamped = stamp_origin_brain(fresh, "/path/to/repo");
        assert!(stamped.contains("Origin-Brain: /path/to/repo"));
        assert!(
            stamped.find("Origin-Brain:").unwrap() > stamped.find("Source-Agent:").unwrap(),
            "Origin-Brain lands after Source-Agent"
        );
    }

    // ---------------------------------------------------------------------
    // DATA-SAFETY CLUSTER (M5a) — one RED per data-loss vector.
    // ---------------------------------------------------------------------

    /// Fixture-neutral helper: a repo-fact claim (code-anchored → Project).
    fn repo_fact(name: &str) -> String {
        light_doc(
            name,
            "closer",
            &format!("shipped.\n\n[⍂ entity: {name}]\n[𝔻 evidence: repo-alpha/src/x.rs]\n"),
        )
    }
    /// Fixture-neutral helper: a doctrine claim (stays on the medulla).
    fn doctrine(name: &str) -> String {
        light_doc(
            name,
            "orch",
            &format!("maintainer doctrine holds.\n\n[⍂ entity: {name}]\n"),
        )
    }

    /// RED (fix 1 — authoritative moved-list): `apply` must report the exact
    /// files it moved, and that list must survive in a `manifest.json` inside the
    /// backup dir. A rollback driven by that authoritative list never has to scan
    /// the destination store (where it would delete claims it never created).
    #[test]
    fn apply_receipt_carries_authoritative_moved_files_and_manifest() {
        let s = scratch();
        write_claim(&s.medulla, "alpha.light.md", &repo_fact("Alpha"));
        write_claim(&s.medulla, "keepdoc.light.md", &doctrine("KeepDoc"));
        std::fs::write(
            &s.roots,
            serde_json::to_string_pretty(&vec![s.medulla.to_string_lossy().to_string()]).unwrap(),
        )
        .unwrap();

        let mig = scratch_mig(&s);
        let receipt = mig.apply().expect("apply");

        assert_eq!(
            receipt.moved_files,
            vec!["alpha.light.md".to_string()],
            "receipt must name exactly the moved files"
        );
        // The manifest persisted beside the backup is the rollback's source of truth.
        let manifest = PathBuf::from(&receipt.backup_dir).join("manifest.json");
        assert!(manifest.is_file(), "backup dir carries a manifest.json");
        let names: Vec<String> =
            serde_json::from_str(&std::fs::read_to_string(&manifest).unwrap()).unwrap();
        assert_eq!(names, vec!["alpha.light.md".to_string()]);
    }

    /// RED (fix 1 — rollback must NOT wipe pre-existing destination claims): the
    /// project store already holds a claim BEFORE the migration. `apply` moves one
    /// claim in; a rollback driven by the receipt's `moved_files` removes ONLY the
    /// moved claim and leaves the pre-existing destination claim untouched.
    /// (Today `main.rs` rollback scans the whole project store → it would delete
    /// the pre-existing claim. This proves the authoritative-list contract.)
    #[test]
    fn rollback_with_moved_files_spares_preexisting_destination_claims() {
        let s = scratch();
        std::fs::create_dir_all(&s.project).unwrap();
        // A claim that already lived in the destination brain BEFORE any migration.
        write_claim(&s.project, "preexisting.light.md", &doctrine("Preexisting"));
        write_claim(&s.medulla, "alpha.light.md", &repo_fact("Alpha"));
        std::fs::write(
            &s.roots,
            serde_json::to_string_pretty(&vec![s.medulla.to_string_lossy().to_string()]).unwrap(),
        )
        .unwrap();

        let mig = scratch_mig(&s);
        let receipt = mig.apply().expect("apply");
        assert!(
            s.project.join("alpha.light.md").exists(),
            "moved claim landed"
        );

        mig.rollback(&receipt.backup_dir, &receipt.moved_files)
            .expect("rollback");

        assert!(
            s.project.join("preexisting.light.md").exists(),
            "rollback must NOT delete a claim it never created"
        );
        assert!(
            !s.project.join("alpha.light.md").exists(),
            "rollback removed exactly the moved claim"
        );
    }

    /// RED (fix 2 — name collision is a hard refusal, never a silent overwrite):
    /// the destination store already holds a file with the SAME name a repo-fact
    /// claim would move to. `apply` must REFUSE with an error that names the
    /// colliding file, and must not have mutated either store.
    #[test]
    fn apply_refuses_on_destination_name_collision() {
        let s = scratch();
        std::fs::create_dir_all(&s.project).unwrap();
        // Destination already has `alpha.light.md` with DISTINCT bytes.
        let preexisting_bytes = doctrine("DestinationAlpha");
        write_claim(&s.project, "alpha.light.md", &preexisting_bytes);
        // The medulla has a repo-fact that would move to `alpha.light.md`.
        write_claim(&s.medulla, "alpha.light.md", &repo_fact("Alpha"));
        std::fs::write(
            &s.roots,
            serde_json::to_string_pretty(&vec![s.medulla.to_string_lossy().to_string()]).unwrap(),
        )
        .unwrap();

        let mig = scratch_mig(&s);
        let err = mig.apply().expect_err("collision must refuse");
        let msg = err.to_string();
        assert!(
            msg.contains("alpha.light.md") && msg.to_ascii_lowercase().contains("collision"),
            "refusal names the colliding file, got: {msg}"
        );
        // Neither store was mutated: destination bytes intact, source still present.
        assert_eq!(
            std::fs::read_to_string(s.project.join("alpha.light.md")).unwrap(),
            preexisting_bytes,
            "pre-existing destination claim untouched by a refused apply"
        );
        assert!(
            s.medulla.join("alpha.light.md").exists(),
            "source claim still present after a refused apply"
        );
    }

    /// RED (fix 3 — content-level conservation, not just cardinality): a stray,
    /// unrelated `.light.md` sitting in the destination store before migration
    /// keeps the post-apply cardinality equation balanced by luck, yet the moved
    /// claim's content must be verified present at the destination and absent from
    /// the source. `verify_conservation` performs the content-level check and must
    /// hold on a clean apply.
    #[test]
    fn apply_verifies_content_level_conservation() {
        let s = scratch();
        std::fs::create_dir_all(&s.project).unwrap();
        write_claim(&s.medulla, "alpha.light.md", &repo_fact("Alpha"));
        write_claim(&s.medulla, "keepdoc.light.md", &doctrine("KeepDoc"));
        std::fs::write(
            &s.roots,
            serde_json::to_string_pretty(&vec![s.medulla.to_string_lossy().to_string()]).unwrap(),
        )
        .unwrap();

        let mig = scratch_mig(&s);
        let receipt = mig.apply().expect("apply");
        assert!(receipt.count_conserved, "cardinality gate holds");
        assert!(
            receipt.content_conserved,
            "content-level gate: every moved file present at dest + gone from source"
        );
        // The moved claim exists at the destination and is gone from the source.
        assert!(s.project.join("alpha.light.md").exists());
        assert!(!s.medulla.join("alpha.light.md").exists());
    }

    /// RED (fix 4 — rollback is snapshot-first): rollback must snapshot the live
    /// state into the backup dir BEFORE it wipes/restores, so a failure mid-way
    /// leaves a recoverable snapshot. We assert the snapshot dir materialises.
    #[test]
    fn rollback_snapshots_live_state_before_restoring() {
        let s = scratch();
        write_claim(&s.medulla, "alpha.light.md", &repo_fact("Alpha"));
        write_claim(&s.medulla, "keepdoc.light.md", &doctrine("KeepDoc"));
        std::fs::write(
            &s.roots,
            serde_json::to_string_pretty(&vec![s.medulla.to_string_lossy().to_string()]).unwrap(),
        )
        .unwrap();

        let mig = scratch_mig(&s);
        let receipt = mig.apply().expect("apply");
        mig.rollback(&receipt.backup_dir, &receipt.moved_files)
            .expect("rollback");

        // A pre-rollback snapshot of the live medulla state exists under the backup.
        let snap = PathBuf::from(&receipt.backup_dir).join("pre-rollback-live");
        assert!(
            snap.is_dir(),
            "rollback snapshots the live medulla state before wiping it"
        );
        assert!(
            snap.join("alpha.light.md").exists() || snap.join("keepdoc.light.md").exists(),
            "the pre-rollback snapshot captured the live claims"
        );
    }

    /// RED (fix 5 — ingest_roots.json is backed up and restored): `apply` prunes
    /// ghost pointers by rewriting `ingest_roots.json`; a rollback must restore the
    /// PRE-migration roots file byte-for-byte.
    #[test]
    fn rollback_restores_ingest_roots_json() {
        let s = scratch();
        write_claim(&s.medulla, "alpha.light.md", &repo_fact("Alpha"));
        let dangling = s.medulla.join("gone.light.md");
        // Original roots: dir root + a dangling per-file pointer (a ghost).
        let original_roots = serde_json::to_string_pretty(&vec![
            s.medulla.to_string_lossy().to_string(),
            dangling.to_string_lossy().to_string(),
        ])
        .unwrap();
        std::fs::write(&s.roots, &original_roots).unwrap();

        let mig = scratch_mig(&s);
        let receipt = mig.apply().expect("apply");
        // apply rewrote the roots file (pruned the ghost).
        assert_ne!(
            std::fs::read_to_string(&s.roots).unwrap(),
            original_roots,
            "apply pruned the ghost pointer from ingest_roots.json"
        );

        mig.rollback(&receipt.backup_dir, &receipt.moved_files)
            .expect("rollback");
        assert_eq!(
            std::fs::read_to_string(&s.roots).unwrap(),
            original_roots,
            "rollback restores the pre-migration ingest_roots.json byte-for-byte"
        );
    }

    /// RED (fix 6 — owner-alive guard): a live listener on the served-owner port
    /// means an offline migration would race a keepalive owner. `apply`/`rollback`
    /// must refuse with a clear "stop the served owner first" message while a
    /// listener is up.
    #[test]
    fn apply_and_rollback_refuse_while_owner_listener_is_up() {
        use std::net::TcpListener;
        let s = scratch();
        write_claim(&s.medulla, "alpha.light.md", &repo_fact("Alpha"));
        std::fs::write(
            &s.roots,
            serde_json::to_string_pretty(&vec![s.medulla.to_string_lossy().to_string()]).unwrap(),
        )
        .unwrap();

        // Bind an ephemeral port to stand in for a live served owner, and point the
        // migration's guard at it.
        let listener = TcpListener::bind("127.0.0.1:0").expect("bind stand-in owner");
        let port = listener.local_addr().unwrap().port();

        let mig = MedullaMigration::new(&s.medulla, &s.project, &s.roots, "/path/to/repo")
            .with_owner_guard_port(port);

        let err = mig
            .apply()
            .expect_err("apply must refuse while a listener is up");
        assert!(
            err.to_string()
                .to_ascii_lowercase()
                .contains("stop the served owner"),
            "refusal tells the maintainer to stop the served owner, got: {err}"
        );
        let err = mig
            .rollback("unused", &[])
            .expect_err("rollback must refuse while a listener is up");
        assert!(
            err.to_string()
                .to_ascii_lowercase()
                .contains("stop the served owner"),
            "rollback refusal is the same guard, got: {err}"
        );
    }
}