memstead-base 0.7.0

Engine internals for Memstead — store, parser, validators, filesystem-mem engine. 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
//! Source-cursor driver — assemble a [`SourceCursor`] from live workspace
//! state, so the brief's changed-slice preface can steer a pass at what moved.
//!
//! Engine-side port of the plugin's `computeSourceCursor` (`inject.mjs`). For
//! each of a binding's source facets it resolves the change-detection
//! strategy, reads the durable baseline from the **destination** mem's
//! `sync_state` (keyed `"<binding-id>/<facet-or-refmem>#synced"`, D4), computes
//! the changed slice against the source's current state, and unions the
//! per-facet slices.
//!
//! Strategies:
//!   - **git** — diff the stored commit id against the source tree's current
//!     `HEAD` (subprocess `git rev-parse` / `git diff --name-status`), with
//!     the facet scope + ingest `deny_paths` pushed down as `:(glob)` /
//!     `:(glob,exclude)` pathspecs.
//!   - **graph** — diff the source mem's snapshot token via the engine's own
//!     [`Engine::changes_since`]; reference mems are graph-detected too.
//!   - **mtime** — enumerate the facet's files (minus the facet scope's own
//!     denies *and* the ingest `deny_paths`, applied identically to the git
//!     strategy's exclude pathspecs — see [`enumerate_facet_files`]), compute a
//!     stat-map digest, memoise it under `.memstead.cache/ingest/source-cursor/`,
//!     and diff the current digest against the memoised baseline via the pure
//!     [`super::slice::mtime_slice_outcome`] core (precise, incl. deletions).
//!
//! **Deny invariance.** Ingest `deny_paths` are enforced identically by every
//! strategy that reads a file tree — git, mtime, and refinement's enumeration,
//! plus both token computations (`current_primary_token` / [`source_moved`]).
//! A file matching a `deny_paths` entry appears in no changed slice, no
//! refinement batch, and never influences the mtime digest or the
//! `source_moved` token. The **graph** strategy is exempt *by definition*:
//! `deny_paths` entries are file-path globs, but a graph source's artifacts are
//! entities (entity-granular), so a file-path glob can never select one. This
//! exemption is designed, not an omission.
//!
//! **One deny dialect.** A `deny_paths` entry is a **workspace-relative glob**
//! — the exact grammar and resolution root as a facet-scope entry, resolved by
//! the same [`build_glob_set`] / `:(glob,exclude)` machinery. The plugin's
//! PreToolUse deny hook enforces the *identical* dialect against the ingest
//! agent's Read/Glob/Grep, reading the active list from an engine-written cache
//! file. [`write_active_deny_file`] publishes that file during brief rendering
//! (remove-then-write, overwrite-always), so hook enforcement tracks the last
//! rendered ingest and is never stale. A deny entry that selects **no file** in
//! the project tree is surfaced as a rendered brief warning
//! ([`SourceCursor::dead_denies`]) rather than silently no-op'ing — catching
//! typos and un-migrated legacy bare names, never a hard error.
//!
//! **One empty-scope semantic.** A facet with **no allow patterns** is
//! *unscoped* — and that is a **typed refusal**, identical on every file-tree
//! strategy: git, mtime, and refinement all decline to diff or enumerate the
//! whole medium (a `facet_unscoped` check gates it). No strategy silently emits an
//! empty slice, enumeration, or batch for an unscoped facet; instead the source
//! contributes [`NoSignalReason::Unscoped`], which renders in the brief. A
//! facet that genuinely wants the whole medium writes `**/*`. This is a
//! different field from the ingest's `deny_paths`: an **empty `deny_paths`**
//! list is valid and means "no denies" — it never trips the unscoped refusal.
//!
//! **Visible no-signal.** Every source contributes a per-source outcome. A
//! genuinely-unchanged source (baseline present, nothing moved) stays silent —
//! the only documented silence, preserving the "brief is byte-identical to a
//! plain roam when nothing moved" property. Every other no-signal condition —
//! unscoped facet, `signal:none`, git failure / unknown baseline, missing graph
//! snapshot — is collected as a [`NoSignalNote`] and rendered distinguishably.
//!
//! Load-bearing invariant: the new baseline `token` is only *collected* here
//! (into `write_commands` / `reseed`); it is recorded by the engine's
//! `set_mem_sync_state` writer when `projection advance` completes a full pass
//! (D7). The driver never writes it.

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

use globset::{Glob, GlobSet, GlobSetBuilder};

use crate::Engine;
use crate::pipeline::{MediumType, PatternMode};

use super::brief::{NoSignalNote, SourceCursor, SyncCommand};
use super::change_detection::{
    StatMap, compute_stat_map, digest_stat_map, parse_digest_token, serialize_digest_token,
};
use super::resolve::{
    ChangeStrategy, ResolvedIngest, ResolvedSource, find_git_root, resolve_change_strategy,
};
use super::slice::{
    NoSignalReason, Slice, SliceOutcome, graph_slice_outcome, is_git_token, mtime_slice_outcome,
};
use crate::pipeline::Source;

/// Lexically normalize a path — resolve `.` and `..` without touching the
/// filesystem (no symlink resolution), matching Node's `path.resolve` on an
/// already-absolute path.
fn normalize_lexical(path: &Path) -> PathBuf {
    let mut out: Vec<Component> = Vec::new();
    for comp in path.components() {
        match comp {
            Component::CurDir => {}
            Component::ParentDir => match out.last() {
                Some(Component::Normal(_)) => {
                    out.pop();
                }
                Some(Component::RootDir | Component::Prefix(_)) => {}
                _ => out.push(comp),
            },
            other => out.push(other),
        }
    }
    out.iter().collect()
}

/// The relative path from `from` to `to` (both normalized), matching Node's
/// `path.relative`.
fn relative_path(from: &Path, to: &Path) -> PathBuf {
    let from = normalize_lexical(from);
    let to = normalize_lexical(to);
    let from_comps: Vec<Component> = from.components().collect();
    let to_comps: Vec<Component> = to.components().collect();
    let mut common = 0;
    while common < from_comps.len()
        && common < to_comps.len()
        && from_comps[common] == to_comps[common]
    {
        common += 1;
    }
    let mut result = PathBuf::new();
    for _ in common..from_comps.len() {
        result.push("..");
    }
    for comp in &to_comps[common..] {
        result.push(comp.as_os_str());
    }
    result
}

/// The medium pointer resolved to an absolute base directory. Public
/// so init-time surfaces (CLI `projection init`) can resolve a medium
/// base exactly as the strategies do — e.g. to warn when it falls
/// outside the workspace root.
pub fn medium_base(pointer: &str, workspace_root: &Path) -> PathBuf {
    if pointer.is_empty() {
        workspace_root.to_path_buf()
    } else {
        normalize_lexical(&workspace_root.join(pointer))
    }
}

/// Workspace-relative deny globs excluding the engine's own state from
/// every strategy's input set. Unconditional and non-configurable: a
/// binding can never legitimately model `.memstead/`,
/// `.memstead.cache/`, or a mount's resolved storage location as
/// source artifacts — an allow glob covering them does not admit them.
/// The dot-directories key on their *names* (the names are the
/// contract, and a foreign workspace's `.memstead/` is still engine
/// state); the mount storage locations key on their *resolved* paths
/// because their directory names are configurable. Fail-open on an
/// unreadable mount list: the name-based excludes stay in force.
fn engine_state_denies(workspace_root: &Path) -> Vec<String> {
    use crate::workspace_store::{FileWorkspaceStore, WorkspaceStoreAdapter};

    let mut denies: Vec<String> = vec![
        ".memstead/**".to_string(),
        ".memstead.cache/**".to_string(),
        "**/.memstead/**".to_string(),
        "**/.memstead.cache/**".to_string(),
    ];
    if let Ok(ws) = FileWorkspaceStore.load(workspace_root) {
        for mount in &ws.mounts {
            let dir: Option<PathBuf> = match &mount.storage {
                crate::workspace::MountStorage::GitBranch { gitdir, .. } => {
                    gitdir.parent().map(Path::to_path_buf)
                }
                crate::workspace::MountStorage::Folder { path } => Some(path.clone()),
                crate::workspace::MountStorage::Archive { path, .. } => {
                    // A sealed archive is one file, not a tree.
                    let rel = relative_path(workspace_root, &normalize_lexical(path));
                    denies.push(rel.to_string_lossy().to_string());
                    None
                }
                // No on-disk footprint to exclude.
                crate::workspace::MountStorage::InMemory => None,
            };
            if let Some(dir) = dir {
                let rel = relative_path(workspace_root, &normalize_lexical(&dir));
                // A collapsed single-mem folder workspace stores the mem
                // AT the workspace root — excluding `**` there would
                // empty every denominator; skip it.
                if !rel.as_os_str().is_empty() {
                    denies.push(format!("{}/**", rel.to_string_lossy()));
                }
            }
        }
    }
    denies
}

/// `git rev-parse HEAD` in `git_root`, or `None` on any failure.
fn git_head(git_root: &Path) -> Option<String> {
    let out = Command::new("git")
        .args(["rev-parse", "HEAD"])
        .current_dir(git_root)
        .output()
        .ok()?;
    if !out.status.success() {
        return None;
    }
    let sha = String::from_utf8_lossy(&out.stdout).trim().to_string();
    (!sha.is_empty()).then_some(sha)
}

/// Translate a workspace-relative facet pattern into a git pathspec relative
/// to `git_root`, with `:(glob)` magic (or `:(glob,exclude)` for a deny).
///
/// A `**`-prefixed pattern is prefix-free — it matches under any directory,
/// in particular the medium subtree — so it is emitted verbatim as a
/// git-root-relative glob. Lexically re-rooting it (join + relativize) would
/// produce `../**/…` for any non-root medium pointer, and git *fatals* on an
/// out-of-tree pathspec, sinking the whole diff into a no-signal degrade.
fn to_git_pathspec(pattern: &str, git_root: &Path, workspace_root: &Path, exclude: bool) -> String {
    let magic = if exclude {
        ":(glob,exclude)"
    } else {
        ":(glob)"
    };
    if pattern.starts_with("**") {
        return format!("{magic}{pattern}");
    }
    let resolved = normalize_lexical(&workspace_root.join(pattern));
    let git_rel = relative_path(git_root, &resolved);
    format!("{magic}{}", git_rel.to_string_lossy())
}

/// Like [`to_git_pathspec`], but `None` when the pattern resolves *outside*
/// `git_root` (its git-relative path escapes with a leading `..`). Git fatals
/// on an out-of-tree pathspec, so a cross-repo deny must be dropped from the
/// diff rather than pushed — it can match nothing in this repo regardless.
fn in_repo_pathspec(
    pattern: &str,
    git_root: &Path,
    workspace_root: &Path,
    exclude: bool,
) -> Option<String> {
    // Prefix-free glob — same verbatim re-anchoring as `to_git_pathspec`.
    if pattern.starts_with("**") {
        return Some(to_git_pathspec(pattern, git_root, workspace_root, exclude));
    }
    let resolved = normalize_lexical(&workspace_root.join(pattern));
    let git_rel = relative_path(git_root, &resolved);
    if git_rel
        .components()
        .next()
        .is_some_and(|c| c == Component::ParentDir)
    {
        return None;
    }
    let magic = if exclude {
        ":(glob,exclude)"
    } else {
        ":(glob)"
    };
    Some(format!("{magic}{}", git_rel.to_string_lossy()))
}

/// Build a [`GlobSet`] from workspace-relative glob patterns, or `None` if
/// any pattern is malformed.
fn build_glob_set(patterns: &[&str]) -> Option<GlobSet> {
    let mut builder = GlobSetBuilder::new();
    for pattern in patterns {
        builder.add(Glob::new(pattern).ok()?);
    }
    builder.build().ok()
}

/// Whether a primary source's facet declares **no allow patterns** — an
/// *unscoped* facet. This is the single condition behind the uniform
/// empty-scope refusal ([`NoSignalReason::Unscoped`]): neither git nor mtime
/// diffs or enumerates the whole medium for such a facet, and refinement emits
/// no batch for it. It is orthogonal to the ingest's `deny_paths` — an empty
/// deny list is not an unscoped facet.
fn facet_unscoped(source: &Source) -> bool {
    !source.scope.iter().any(|r| r.mode == PatternMode::Allow)
}

/// Enumerate the workspace-relative file paths a primary source's facet scope
/// selects — the `mtime` strategy's input set. Mirrors the plugin's
/// `enumerateFacetFiles`: only `codebase`/`filesystem` mediums; the facet's
/// allow globs minus its deny globs, evaluated over the medium's directory
/// tree. Returns a sorted, de-duplicated list. An unscoped facet (no allows)
/// yields an empty list here — but callers must not treat that as signal: the
/// strategy layer (`compute_mtime_slice` / `current_primary_token`) refuses
/// an unscoped facet via `facet_unscoped` *before* enumerating, so the empty
/// list is only ever reached for a genuinely-empty scoped enumeration.
///
/// `deny_paths` are the ingest-level denies (`ResolvedIngest::deny_paths`),
/// applied on top of the facet's own scope denies with the *same*
/// workspace-relative glob grammar the git strategy pushes down as
/// `:(glob,exclude)` pathspecs — so a denied file is excluded from the mtime
/// input set exactly as it is from the git diff. Passing `&[]` yields the
/// facet-scope-only behaviour.
pub fn enumerate_facet_files(
    source: &Source,
    deny_paths: &[String],
    workspace_root: &Path,
) -> Vec<String> {
    if !matches!(
        source.medium_type,
        MediumType::Codebase | MediumType::Filesystem
    ) {
        return Vec::new();
    }
    let mut allows: Vec<&str> = Vec::new();
    let mut denies: Vec<&str> = Vec::new();
    for rule in &source.scope {
        match rule.mode {
            PatternMode::Allow => allows.push(&rule.path),
            PatternMode::Deny => denies.push(&rule.path),
        }
    }
    // Ingest deny_paths deny on top of the facet's own denies, sharing the
    // facet-scope glob grammar (workspace-relative, matched against each
    // candidate's workspace-relative path) — the same entries the git strategy
    // resolves as exclude pathspecs, so deny enforcement is strategy-invariant.
    for dp in deny_paths {
        denies.push(dp);
    }
    // Engine self-exclusion — unconditional, below configuration; the
    // git strategy pushes the same set as exclude pathspecs so the
    // denominator stays strategy-invariant.
    let forced = engine_state_denies(workspace_root);
    for f in &forced {
        denies.push(f);
    }
    if allows.is_empty() {
        return Vec::new();
    }
    let Some(allow_set) = build_glob_set(&allows) else {
        return Vec::new();
    };
    let deny_set = if denies.is_empty() {
        None
    } else {
        build_glob_set(&denies)
    };

    // Walk the medium's directory tree; the facet patterns are
    // workspace-relative, so each candidate is matched by its
    // workspace-relative path. VCS internals are never source artifacts —
    // they are pruned here so `.git/**` plumbing cannot enter `S(D)`,
    // matching the git strategy (whose diffs never name `.git` files).
    let base = medium_base(&source.pointer, workspace_root);
    let mut out: Vec<String> = Vec::new();
    let mut stack = vec![base];
    while let Some(dir) = stack.pop() {
        let Ok(entries) = std::fs::read_dir(&dir) else {
            continue;
        };
        for entry in entries.flatten() {
            let Ok(file_type) = entry.file_type() else {
                continue;
            };
            let path = entry.path();
            if file_type.is_dir() {
                let skip = path.file_name().and_then(|n| n.to_str()).is_some_and(|n| {
                    // VCS internals and engine state are never source
                    // artifacts — pruning here saves the walk; the
                    // forced deny globs enforce the same exclusion for
                    // anything that still slips into a candidate list.
                    VCS_INTERNAL_DIRS.contains(&n) || n == ".memstead" || n == ".memstead.cache"
                });
                if !skip {
                    stack.push(path);
                }
            } else if file_type.is_file() {
                let rel = relative_path(workspace_root, &normalize_lexical(&path))
                    .to_string_lossy()
                    .to_string();
                let denied = deny_set.as_ref().is_some_and(|d| d.is_match(&rel));
                if allow_set.is_match(&rel) && !denied {
                    out.push(rel);
                }
            }
        }
    }
    out.sort();
    out.dedup();
    out
}

/// Compute the git changed slice for one primary source between its stored
/// baseline commit and the tree's current `HEAD`. Mirrors `computeGitSlice`.
fn compute_git_slice(
    source: &Source,
    deny_paths: &[String],
    workspace_root: &Path,
    baseline: Option<&str>,
) -> SliceOutcome {
    let base = medium_base(&source.pointer, workspace_root);
    let Some(git_root) = find_git_root(&base) else {
        return SliceOutcome::NoSignal {
            reason: NoSignalReason::GitUnavailable,
        };
    };
    let Some(head) = git_head(&git_root) else {
        return SliceOutcome::NoSignal {
            reason: NoSignalReason::GitUnavailable,
        };
    };

    let baseline = match baseline {
        Some(b) if is_git_token(b) => b,
        // No usable commit baseline — seed at HEAD, present no slice.
        _ => return SliceOutcome::Reseed { token: head },
    };
    if baseline == head {
        return SliceOutcome::Unchanged { token: head };
    }

    // Pathspecs from the facet scope + the ingest's deny_paths.
    let mut allows: Vec<&str> = Vec::new();
    let mut denies: Vec<&str> = Vec::new();
    for rule in &source.scope {
        match rule.mode {
            PatternMode::Allow => allows.push(&rule.path),
            PatternMode::Deny => denies.push(&rule.path),
        }
    }
    if allows.is_empty() {
        // Unscoped facet — the uniform typed refusal (never diff the whole
        // repo); renders in the brief rather than degrading silently.
        return SliceOutcome::NoSignal {
            reason: NoSignalReason::Unscoped,
        };
    }
    for dp in deny_paths {
        denies.push(dp);
    }
    // Engine self-exclusion — same forced set the mtime strategy's
    // enumeration applies, pushed down as exclude pathspecs so the
    // slice never names engine state either.
    let forced = engine_state_denies(workspace_root);
    for f in &forced {
        denies.push(f);
    }
    let mut specs: Vec<String> = Vec::with_capacity(allows.len() + denies.len());
    for a in &allows {
        specs.push(to_git_pathspec(a, &git_root, workspace_root, false));
    }
    for d in &denies {
        // A deny may target a path OUTSIDE this medium's git repo — a
        // cross-medium workspace-relative glob such as `../dev/**`, whose tree
        // lives in a sibling repo. Git *fatals* on an out-of-tree pathspec
        // (`'../dev/**' is outside repository`), which would sink the entire
        // diff into a no-signal degrade. Such a deny can exclude nothing here
        // anyway (the files simply aren't in this repo), so drop it: the plugin
        // hook still enforces it agent-side (workspace-relative, cross-repo),
        // and a genuinely-dead entry is still surfaced by the brief warning.
        if let Some(spec) = in_repo_pathspec(d, &git_root, workspace_root, true) {
            specs.push(spec);
        }
    }

    let mut cmd = Command::new("git");
    cmd.args([
        "diff",
        "--no-renames",
        "--name-status",
        baseline,
        &head,
        "--",
    ]);
    cmd.args(&specs);
    cmd.current_dir(&git_root);
    let out = match cmd.output() {
        Ok(o) if o.status.success() => o,
        // Unknown baseline (gc'd / rewritten), an out-of-repo pathspec, or a
        // git failure — degrade to a whole re-roam (the plugin does the same).
        _ => {
            return SliceOutcome::NoSignal {
                reason: NoSignalReason::GitUnavailable,
            };
        }
    };
    let text = String::from_utf8_lossy(&out.stdout);

    let mut slice = Slice::default();
    for line in text.lines() {
        if line.trim().is_empty() {
            continue;
        }
        let Some(tab) = line.find('\t') else { continue };
        let status = line[..tab].trim();
        let git_path = line[tab + 1..].trim();
        let ws_path = relative_path(workspace_root, &normalize_lexical(&git_root.join(git_path)))
            .to_string_lossy()
            .to_string();
        match status.chars().next() {
            Some('A') => slice.added.push(ws_path),
            Some('D') => slice.deleted.push(ws_path),
            // M, T (type change), C, and the rest.
            _ => slice.modified.push(ws_path),
        }
    }
    slice.added.sort();
    slice.modified.sort();
    slice.deleted.sort();
    SliceOutcome::Changed {
        token: head,
        slice,
        degraded: false,
    }
}

/// Compute the graph changed slice for a source mem between its stored
/// baseline snapshot token and the mem's current head. Mirrors
/// `computeGraphSlice`, using the engine's own change history.
fn compute_graph_slice(engine: &Engine, source_mem: &str, baseline: Option<&str>) -> SliceOutcome {
    let current = match engine.mem_head_sha(source_mem) {
        Ok(Some(sha)) => sha,
        // Source has no snapshot signal, or is unknown — degrade.
        _ => {
            return SliceOutcome::NoSignal {
                reason: NoSignalReason::GraphSnapshotMissing,
            };
        }
    };
    // Fetch the entity delta only when the source actually moved.
    let changed = matches!(baseline, Some(b) if is_git_token(b) && b != current);
    if changed {
        let baseline = baseline.expect("changed implies a baseline");
        match engine.changes_since(source_mem, baseline, None) {
            Ok(report) => graph_slice_outcome(Some(baseline), &current, &report.changes),
            // Unknown baseline / engine error — degrade.
            Err(_) => SliceOutcome::NoSignal {
                reason: NoSignalReason::GraphSnapshotMissing,
            },
        }
    } else {
        graph_slice_outcome(baseline, &current, &[])
    }
}

// ── mtime source-cursor memo ────────────────────────────────────────────────
//
// The `mtime` strategy's durable baseline is a small digest token (in the
// destination mem's `sync_state`), which cannot by itself say *which* files
// changed. The engine keeps a rebuildable memo — the full stat map keyed by
// its digest aggregate — so a run whose baseline matches a memoised aggregate
// diffs precisely (incl. deletions) instead of degrading to a full scan.
//
// The memo lives engine-side under `<workspace>/.memstead.cache/ingest/` in
// the plugin's format (`{aggregate: {relpath: {mtime, size}}}`), so the engine
// and the transition-era skill share it. It is pure engine-internal cache —
// not mem-repo, not the graph — so writing it during brief rendering is not a
// tracked mutation. A write failure only costs the next run's precision.

/// The `<cache_root>/source-cursor/<ingest>/<facet>.json` memo path.
fn cursor_memo_path(cache_root: &Path, ingest_name: &str, facet_ref: &str) -> PathBuf {
    let safe: String = facet_ref
        .chars()
        .map(|c| {
            if c.is_ascii_alphanumeric() || matches!(c, '_' | '.' | '-') {
                c
            } else {
                '_'
            }
        })
        .collect();
    cache_root
        .join("source-cursor")
        .join(ingest_name)
        .join(format!("{safe}.json"))
}

/// Read the stat map memoised under `aggregate` for a facet, or `None` on miss.
fn read_cursor_memo(
    cache_root: &Path,
    ingest: &str,
    facet: &str,
    aggregate: &str,
) -> Option<StatMap> {
    let bytes = std::fs::read(cursor_memo_path(cache_root, ingest, facet)).ok()?;
    let memo: BTreeMap<String, StatMap> = serde_json::from_slice(&bytes).ok()?;
    memo.get(aggregate).cloned()
}

/// Memoise the current stat map under its aggregate, bounding the file to the
/// 3 most-recent aggregates. Best-effort.
fn write_cursor_memo(cache_root: &Path, ingest: &str, facet: &str, aggregate: &str, map: &StatMap) {
    let path = cursor_memo_path(cache_root, ingest, facet);
    let mut memo: BTreeMap<String, StatMap> = std::fs::read(&path)
        .ok()
        .and_then(|b| serde_json::from_slice(&b).ok())
        .unwrap_or_default();
    memo.insert(aggregate.to_string(), map.clone());
    if memo.len() > 3 {
        // Keep the just-written aggregate plus up to two others.
        let drop: Vec<String> = memo
            .keys()
            .filter(|k| k.as_str() != aggregate)
            .skip(2)
            .cloned()
            .collect();
        for key in drop {
            memo.remove(&key);
        }
    }
    if let Some(parent) = path.parent() {
        let _ = std::fs::create_dir_all(parent);
    }
    if let Ok(bytes) = serde_json::to_vec(&memo) {
        let _ = std::fs::write(&path, bytes);
    }
}

// ── active-deny hook channel & dead-deny detection ──────────────────────────
//
// The plugin's PreToolUse deny hook (`deny-meta-files.mjs`) blocks the ingest
// agent from Read/Glob/Grep against the *active* ingest's `deny_paths`. It
// reads the list from an engine-written cache file; the engine writes that file
// during brief rendering (below), so the hook always enforces the list of the
// ingest whose brief was last rendered — never a stale one. Same
// workspace-relative glob dialect the engine resolves here.

/// The hook's active-deny cache path:
/// `<workspace>/.memstead.cache/projection/active-deny-paths.json`.
fn active_deny_path(workspace_root: &Path) -> PathBuf {
    workspace_root
        .join(".memstead.cache")
        .join("projection")
        .join("active-deny-paths.json")
}

/// Write the active ingest's deny list for the plugin hook, **stale-safe**.
///
/// Rendering a brief for ingest X publishes X's name and X's (dialect-normalized)
/// deny entries here; a later render for Y overwrites it. An ingest with an
/// empty `deny_paths` writes an explicit empty list (so the hook enforces
/// *nothing*, rather than inheriting a previous ingest's list).
///
/// **Remove-then-write:** the previous file is unlinked *before* the new write,
/// so a failed write can never leave X's list in place to be enforced against
/// Y. Best-effort like the mtime memo (engine-internal cache, not a tracked
/// mutation) — but the failure mode is fail-*closed* (no file ⇒ the hook
/// blocks nothing), never fail-stale.
pub fn write_active_deny_file(workspace_root: &Path, ingest_name: &str, deny_paths: &[String]) {
    let path = active_deny_path(workspace_root);
    // Unlink first: a subsequent write failure then leaves *no* file rather
    // than a stale previous-ingest file the hook would keep enforcing.
    let _ = std::fs::remove_file(&path);
    if let Some(parent) = path.parent() {
        let _ = std::fs::create_dir_all(parent);
    }
    let payload = serde_json::json!({
        "ingest": ingest_name,
        "deny_paths": deny_paths,
    });
    if let Ok(bytes) = serde_json::to_vec(&payload) {
        let _ = std::fs::write(&path, bytes);
    }
}

/// VCS metadata directories — never source artifacts. Pruned from source
/// enumeration (`S(D)`, mtime slices, advance) and from the dead-deny scan.
const VCS_INTERNAL_DIRS: &[&str] = &[".git", ".svn", ".hg"];

/// Directory names never worth walking for the dead-deny scan — build output,
/// VCS metadata ([`VCS_INTERNAL_DIRS`]), dependency caches, and the engine's
/// own cache.
const DEAD_DENY_SKIP_DIRS: &[&str] = &[
    ".git",
    "node_modules",
    "target",
    "dist",
    ".memstead.cache",
    ".sqlx",
    ".svn",
    ".hg",
];

/// Bounded, pruned walk of `base` collecting every file's **workspace-relative**
/// path (the same string space the deny globs match). Skips heavy directories
/// ([`DEAD_DENY_SKIP_DIRS`]) and gives up (returns `None`) past `cap` files, so
/// the dead-deny scan degrades to "can't tell" rather than warning falsely or
/// walking an unbounded tree. Best-effort: unreadable directories are skipped.
fn walk_tree_bounded(base: &Path, workspace_root: &Path, cap: usize) -> Option<Vec<String>> {
    let mut out: Vec<String> = Vec::new();
    let mut stack = vec![base.to_path_buf()];
    while let Some(dir) = stack.pop() {
        let Ok(entries) = std::fs::read_dir(&dir) else {
            continue;
        };
        for entry in entries.flatten() {
            let Ok(file_type) = entry.file_type() else {
                continue;
            };
            let path = entry.path();
            if file_type.is_dir() {
                let skip = path
                    .file_name()
                    .and_then(|n| n.to_str())
                    .is_some_and(|n| DEAD_DENY_SKIP_DIRS.contains(&n));
                if !skip {
                    stack.push(path);
                }
            } else if file_type.is_file() {
                if out.len() >= cap {
                    return None;
                }
                out.push(
                    relative_path(workspace_root, &normalize_lexical(&path))
                        .to_string_lossy()
                        .to_string(),
                );
            }
        }
    }
    Some(out)
}

/// The ingest `deny_paths` entries that select **no file** in the project tree
/// — surfaced as a rendered brief warning (AC 6 refusal leg) so a zero-matching
/// deny is never a silent no-op. Resolution base is the medium's git project
/// root (so a cross-medium workspace-relative deny like `../dev/**`, whose
/// target lives outside a sub-medium, still resolves against real files),
/// falling back to the workspace root. Uses the *same* [`build_glob_set`]
/// matcher the strategies use, so "does this deny select anything" is answered
/// with the identical dialect. Best-effort: if the tree can't be enumerated
/// (walk cap hit, no readable base) nothing is reported — a warning is only
/// ever raised on a confirmed zero-match.
fn dead_deny_entries(resolved: &ResolvedIngest, workspace_root: &Path) -> Vec<String> {
    if resolved.deny_paths.is_empty() {
        return Vec::new();
    }
    let base = find_git_root(workspace_root).unwrap_or_else(|| workspace_root.to_path_buf());
    let Some(files) = walk_tree_bounded(&base, workspace_root, 100_000) else {
        return Vec::new();
    };
    let mut dead: Vec<String> = Vec::new();
    for entry in &resolved.deny_paths {
        let Some(set) = build_glob_set(&[entry.as_str()]) else {
            // A malformed glob can't be resolved either way — not a confirmed
            // zero-match, so it is not reported here.
            continue;
        };
        if !files.iter().any(|f| set.is_match(f)) {
            dead.push(entry.clone());
        }
    }
    dead
}

/// Compute the `mtime` changed slice for one primary source: enumerate the
/// facet files, stat them, memoise the current map, and diff against the
/// baseline digest's memoised map (precise) or degrade to a full scan on memo
/// miss. Mirrors the mtime branch of the plugin's `computeSourceCursor`.
fn compute_mtime_slice(
    source: &Source,
    ingest_name: &str,
    deny_paths: &[String],
    workspace_root: &Path,
    cache_root: &Path,
    baseline: Option<&str>,
) -> SliceOutcome {
    if facet_unscoped(source) {
        // Unscoped facet — the same typed refusal git raises, so the mtime
        // strategy never enumerates the whole medium nor emits an empty slice.
        return SliceOutcome::NoSignal {
            reason: NoSignalReason::Unscoped,
        };
    }
    let files = enumerate_facet_files(source, deny_paths, workspace_root);
    let now_map = compute_stat_map(&files, workspace_root);
    let now_digest = digest_stat_map(&now_map);
    write_cursor_memo(
        cache_root,
        ingest_name,
        &source.name,
        &now_digest.aggregate,
        &now_map,
    );
    let prev_map = baseline
        .and_then(parse_digest_token)
        .and_then(|base| read_cursor_memo(cache_root, ingest_name, &source.name, &base.aggregate));
    mtime_slice_outcome(baseline, prev_map.as_ref(), &now_map)
}

/// The current change-detection token for a primary source, per its resolved
/// strategy: git `HEAD`, the graph mem's snapshot, or the freshly-computed
/// mtime digest. `None` when there is no signal.
fn current_primary_token(
    engine: &Engine,
    source: &Source,
    deny_paths: &[String],
    workspace_root: &Path,
) -> Option<String> {
    match resolve_change_strategy(source, workspace_root) {
        ChangeStrategy::Git => git_head(&find_git_root(&medium_base(
            &source.pointer,
            workspace_root,
        ))?),
        ChangeStrategy::Graph => engine.mem_head_sha(&source.pointer).ok().flatten(),
        ChangeStrategy::Mtime => {
            if facet_unscoped(source) {
                // Unscoped facet has no signal — not an empty-set digest posing
                // as one, so the source can never register as "moved".
                None
            } else {
                let files = enumerate_facet_files(source, deny_paths, workspace_root);
                Some(serialize_digest_token(&digest_stat_map(&compute_stat_map(
                    &files,
                    workspace_root,
                ))))
            }
        }
        ChangeStrategy::None => None,
    }
}

/// Whether any of an ingest's sources moved since its last synced pass — the
/// cheap, slice-free predicate the backoff uses as its additive second
/// trigger. Compares each source's current token to the baseline stored in the
/// destination mem's `sync_state`; a source with no baseline is not "moved"
/// (a first sync does not by itself defeat backoff). Mirrors the plugin's
/// `sourceChangedSince`.
pub fn source_moved(engine: &Engine, resolved: &ResolvedIngest, workspace_root: &Path) -> bool {
    source_moved_since(engine, resolved, workspace_root, "synced", false)
}

/// The generalized form of [`source_moved`]: compare each source's current
/// change-detection token against the baseline stored under
/// `"<binding>/<facet>#<state>"` in the destination mem's `sync_state`. The
/// `state` suffix selects the baseline family — `"synced"` (the build/sync
/// baseline [`source_moved`] reads) or `"verified"` (the verify baseline).
///
/// `missing_baseline_is_moved` decides the never-recorded case: `false`
/// preserves [`source_moved`]'s posture (no baseline ⇒ not "moved" — a first
/// sync does not by itself defeat backoff); `true` treats a source with a live
/// current token but no recorded baseline as moved — the verify due-check's
/// posture, where "never verified" means the first verify is due.
pub fn source_moved_since(
    engine: &Engine,
    resolved: &ResolvedIngest,
    workspace_root: &Path,
    state: &str,
    missing_baseline_is_moved: bool,
) -> bool {
    let dest = &resolved.destination_mem;
    let baseline_map = engine
        .mem_config_for(dest)
        .map(|c| c.sync_state.clone())
        .unwrap_or_default();

    for source in &resolved.sources {
        let (facet_ref, current) = match source {
            ResolvedSource::Primary(p) => (
                p.name.clone(),
                current_primary_token(engine, p, &resolved.deny_paths, workspace_root),
            ),
            ResolvedSource::Reference { mem } => {
                (mem.clone(), engine.mem_head_sha(mem).ok().flatten())
            }
        };
        let key = format!("{}/{}#{state}", resolved.name, facet_ref);
        let Some(baseline) = baseline_map.get(&key) else {
            // No baseline recorded for this state family.
            if missing_baseline_is_moved && current.as_deref().is_some_and(|c| !c.is_empty()) {
                return true;
            }
            continue;
        };
        if let Some(current) = current
            && !current.is_empty()
            && current != *baseline
        {
            return true;
        }
    }
    false
}

/// Assemble the combined [`SourceCursor`] for an ingest from live state: the
/// destination mem's `sync_state` baselines and each source's current state.
pub fn compute_source_cursor(
    engine: &Engine,
    resolved: &ResolvedIngest,
    workspace_root: &Path,
) -> SourceCursor {
    let dest = &resolved.destination_mem;
    let baseline_map = engine
        .mem_config_for(dest)
        .map(|c| c.sync_state.clone())
        .unwrap_or_default();

    let cache_root = workspace_root.join(".memstead.cache").join("ingest");
    let mut union = Slice::default();
    let mut write_commands: Vec<SyncCommand> = Vec::new();
    let mut reseed: Vec<SyncCommand> = Vec::new();
    let mut no_signal: Vec<NoSignalNote> = Vec::new();
    let mut degraded = false;

    for source in &resolved.sources {
        // Key: "<ingest>/<facet_ref>" for primaries, "<ingest>/<mem>" for
        // reference sources — matching the plugin's sync_state keying.
        let (facet_ref, outcome) = match source {
            ResolvedSource::Primary(p) => {
                let key = format!("{}/{}#synced", resolved.name, p.name);
                let baseline = baseline_map.get(&key).map(String::as_str);
                let outcome = match resolve_change_strategy(p, workspace_root) {
                    ChangeStrategy::Git => {
                        compute_git_slice(p, &resolved.deny_paths, workspace_root, baseline)
                    }
                    // A graph-typed primary's medium pointer is the source mem id.
                    ChangeStrategy::Graph => compute_graph_slice(engine, &p.pointer, baseline),
                    ChangeStrategy::Mtime => compute_mtime_slice(
                        p,
                        &resolved.name,
                        &resolved.deny_paths,
                        workspace_root,
                        &cache_root,
                        baseline,
                    ),
                    // `none` is inert — a rendered `signal:none` state, no slice.
                    ChangeStrategy::None => SliceOutcome::NoSignal {
                        reason: NoSignalReason::DetectionNone,
                    },
                };
                (p.name.clone(), outcome)
            }
            ResolvedSource::Reference { mem } => {
                let key = format!("{}/{}#synced", resolved.name, mem);
                let baseline = baseline_map.get(&key).map(String::as_str);
                (mem.clone(), compute_graph_slice(engine, mem, baseline))
            }
        };

        let key = format!("{}/{}#synced", resolved.name, facet_ref);
        match outcome {
            // Genuinely unchanged (baseline present, nothing moved) is the only
            // documented silence — it renders nothing, keeping an all-unchanged
            // brief byte-identical to a plain roam.
            SliceOutcome::Unchanged { .. } => {}
            // Every no-signal reason is a visible per-source note.
            SliceOutcome::NoSignal { reason } => no_signal.push(NoSignalNote {
                source: facet_ref.clone(),
                reason,
            }),
            SliceOutcome::Reseed { token } => reseed.push(SyncCommand { key, token }),
            SliceOutcome::Changed {
                token,
                slice,
                degraded: d,
            } => {
                union.added.extend(slice.added);
                union.modified.extend(slice.modified);
                union.deleted.extend(slice.deleted);
                degraded |= d;
                write_commands.push(SyncCommand { key, token });
            }
        }
    }

    dedupe_sort(&mut union.added);
    dedupe_sort(&mut union.modified);
    dedupe_sort(&mut union.deleted);
    let any_changes =
        !union.added.is_empty() || !union.modified.is_empty() || !union.deleted.is_empty();

    SourceCursor {
        union,
        write_commands,
        reseed,
        no_signal,
        any_changes,
        degraded,
        dead_denies: dead_deny_entries(resolved, workspace_root),
        dest_mem: dest.clone(),
        // The resolved ingest's `name` is the canonical binding id `<mem>/<stem>`
        // (via `resolve_binding_run`) — the id the `projection advance` line the
        // brief renders (D4/D7) is keyed on.
        binding_id: resolved.name.clone(),
    }
}

fn dedupe_sort(v: &mut Vec<String>) {
    v.sort();
    v.dedup();
}

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

    #[test]
    fn normalize_resolves_dot_and_dotdot() {
        assert_eq!(
            normalize_lexical(Path::new("/a/b/../c/./d")),
            PathBuf::from("/a/c/d")
        );
        assert_eq!(
            normalize_lexical(Path::new("/a/../../b")),
            PathBuf::from("/b"),
            "dotdot past root is clamped"
        );
    }

    #[test]
    fn relative_computes_updowns() {
        assert_eq!(
            relative_path(Path::new("/a/b"), Path::new("/a/b/c/d")),
            PathBuf::from("c/d")
        );
        assert_eq!(
            relative_path(Path::new("/a/b/c"), Path::new("/a/x")),
            PathBuf::from("../../x")
        );
        // A workspace whose medium is a sibling repository.
        assert_eq!(
            relative_path(Path::new("/m/public"), Path::new("/m/public/crates/x.rs")),
            PathBuf::from("crates/x.rs")
        );
        assert_eq!(
            relative_path(Path::new("/m/graph"), Path::new("/m/public/crates/x.rs")),
            PathBuf::from("../public/crates/x.rs")
        );
    }

    #[test]
    fn pathspec_builds_glob_magic_relative_to_git_root() {
        let ws = Path::new("/m/graph");
        let git_root = Path::new("/m/public");
        assert_eq!(
            to_git_pathspec("../public/**/*.rs", git_root, ws, false),
            ":(glob)**/*.rs"
        );
        assert_eq!(
            to_git_pathspec("../public/target/**", git_root, ws, true),
            ":(glob,exclude)target/**"
        );
    }

    /// A `**`-prefixed pattern (the scaffolded facet default `**/*`) is
    /// prefix-free and re-anchors verbatim onto the git root. Lexical
    /// re-rooting would yield `:(glob)../**/*` for any sub-medium — an
    /// out-of-tree pathspec git fatals on, degrading every diff to
    /// no-signal.
    #[test]
    fn wildcard_prefixed_pathspec_reanchors_verbatim() {
        let ws = Path::new("/m/ws");
        let git_root = Path::new("/m/ws/src");
        assert_eq!(to_git_pathspec("**/*", git_root, ws, false), ":(glob)**/*");
        assert_eq!(
            in_repo_pathspec("**/__pycache__/**", git_root, ws, true).as_deref(),
            Some(":(glob,exclude)**/__pycache__/**")
        );
    }

    use crate::ingest::resolve::Source;
    use crate::pipeline::{MediumType, PatternEntry};

    fn git(repo: &Path, args: &[&str]) {
        let status = std::process::Command::new("git")
            .args(args)
            .current_dir(repo)
            .env("GIT_AUTHOR_NAME", "t")
            .env("GIT_AUTHOR_EMAIL", "t@t")
            .env("GIT_COMMITTER_NAME", "t")
            .env("GIT_COMMITTER_EMAIL", "t@t")
            .output()
            .unwrap();
        assert!(
            status.status.success(),
            "git {args:?}: {}",
            String::from_utf8_lossy(&status.stderr)
        );
    }

    fn primary(scope: Vec<PatternEntry>) -> Source {
        Source {
            name: "src".to_string(),
            medium_type: MediumType::Codebase,
            pointer: String::new(),
            change_detection: Some("git".to_string()),
            scope,
            engagement: None,
            preparation: None,
        }
    }

    /// Shared deny-dialect fixture: the SAME entry list must exclude the SAME
    /// files from an engine slice as it blocks in the plugin hook
    /// (`deny-meta-files.test.js` asserts the hook half against this file).
    /// Proven here by materialising every `blocked` + `allowed` path into a
    /// temp workspace, scoping a facet to `**` (everything), applying the
    /// fixture `entries` as the ingest `deny_paths`, and asserting
    /// `enumerate_facet_files` yields exactly `allowed`.
    #[test]
    fn deny_dialect_fixture_matches_engine_slice() {
        let fixture_path = Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("../../plugins/claude-code/hooks/deny-dialect-fixture.json");
        let raw = std::fs::read(&fixture_path)
            .unwrap_or_else(|e| panic!("read fixture {}: {e}", fixture_path.display()));
        let fixture: serde_json::Value = serde_json::from_slice(&raw).unwrap();
        let strs = |key: &str| -> Vec<String> {
            fixture[key]
                .as_array()
                .unwrap()
                .iter()
                .map(|v| v.as_str().unwrap().to_string())
                .collect()
        };
        let entries = strs("entries");
        let blocked = strs("blocked");
        let allowed = strs("allowed");

        let ws = tempfile::tempdir().unwrap();
        for rel in blocked.iter().chain(allowed.iter()) {
            let path = ws.path().join(rel);
            std::fs::create_dir_all(path.parent().unwrap()).unwrap();
            std::fs::write(&path, "x").unwrap();
        }

        // Scope = everything; the ONLY exclusions are the ingest deny_paths.
        let source = primary(vec![PatternEntry {
            path: "**".to_string(),
            mode: PatternMode::Allow,
        }]);
        let mut got = enumerate_facet_files(&source, &entries, ws.path());
        got.sort();
        let mut want = allowed.clone();
        want.sort();
        assert_eq!(
            got, want,
            "engine slice must equal the fixture `allowed` set"
        );

        for b in &blocked {
            assert!(
                !got.contains(b),
                "denied `{b}` leaked into the engine slice"
            );
        }
        for a in &allowed {
            assert!(
                got.contains(a),
                "allowed `{a}` missing from the engine slice"
            );
        }
    }

    /// The active-deny hook channel: a render for ingest X publishes X's list;
    /// a render for Y overwrites it (never a stale X); an empty deny list writes
    /// an explicit empty array (so the hook enforces nothing, not a leftover).
    #[test]
    fn active_deny_file_overwrites_and_writes_empty() {
        let ws = tempfile::tempdir().unwrap();
        let path = active_deny_path(ws.path());

        write_active_deny_file(ws.path(), "x-graph", &["dev/**".to_string()]);
        let v: serde_json::Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();
        assert_eq!(v["ingest"], "x-graph");
        assert_eq!(v["deny_paths"], serde_json::json!(["dev/**"]));

        // A later render for Y overwrites — nothing from X survives.
        write_active_deny_file(ws.path(), "y-graph", &["**/VISION.md".to_string()]);
        let v: serde_json::Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();
        assert_eq!(v["ingest"], "y-graph");
        assert_eq!(v["deny_paths"], serde_json::json!(["**/VISION.md"]));

        // An empty-deny ingest writes an explicit empty list.
        write_active_deny_file(ws.path(), "z-graph", &[]);
        let v: serde_json::Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();
        assert_eq!(v["ingest"], "z-graph");
        assert_eq!(v["deny_paths"], serde_json::json!([]));
    }

    /// A cross-repo deny (its target sibling to the medium's git repo)
    /// resolves outside `git_root` and is dropped from the pathspecs — pushing
    /// it would make git fatal on the whole diff. An in-repo deny is kept.
    #[test]
    fn out_of_repo_deny_pathspec_is_dropped() {
        let ws = Path::new("/m/graph");
        let git_root = Path::new("/m/public");
        // `../dev/**` (workspace-relative) → /m/dev/** — outside /m/public.
        assert_eq!(in_repo_pathspec("../dev/**", git_root, ws, true), None);
        assert_eq!(in_repo_pathspec("../CLAUDE.md", git_root, ws, true), None);
        // An in-repo deny is preserved as a normal exclude pathspec.
        assert_eq!(
            in_repo_pathspec("../public/target/**", git_root, ws, true),
            Some(":(glob,exclude)target/**".to_string())
        );
    }

    /// A real git diff with a cross-repo deny present must still succeed (the
    /// out-of-repo pathspec is dropped, not fataled), and the in-repo scope is
    /// honoured. Regression for the dogfood dialect (`../dev/**` under a
    /// sub-medium): git must not degrade the whole slice.
    #[test]
    fn git_slice_survives_cross_repo_deny() {
        let repo = tempfile::tempdir().unwrap();
        let root = repo.path();
        std::fs::write(root.join("keep.rs"), "one").unwrap();
        git(root, &["init", "-q"]);
        git(root, &["add", "-A"]);
        git(root, &["commit", "-qm", "seed"]);
        let baseline = String::from_utf8(
            std::process::Command::new("git")
                .args(["rev-parse", "HEAD"])
                .current_dir(root)
                .output()
                .unwrap()
                .stdout,
        )
        .unwrap()
        .trim()
        .to_string();
        std::fs::write(root.join("keep.rs"), "two").unwrap();
        git(root, &["add", "-A"]);
        git(root, &["commit", "-qm", "move"]);

        let source = primary(vec![PatternEntry {
            path: "**/*.rs".to_string(),
            mode: PatternMode::Allow,
        }]);
        // `../dev/**` resolves outside this repo — must be dropped, not fatal.
        let outcome = compute_git_slice(&source, &["../dev/**".to_string()], root, Some(&baseline));
        match outcome {
            SliceOutcome::Changed { slice, .. } => {
                assert_eq!(slice.modified, vec!["keep.rs"]);
            }
            other => panic!("expected Changed (deny dropped), got {other:?}"),
        }
    }

    /// A real git diff: baseline commit → HEAD produces the changed slice,
    /// classifying added / modified / deleted and honouring the scope.
    #[test]
    fn git_slice_diffs_baseline_to_head() {
        let repo = tempfile::tempdir().unwrap();
        let root = repo.path();
        git(root, &["init", "-q"]);
        std::fs::write(root.join("keep.rs"), "one").unwrap();
        std::fs::write(root.join("gone.rs"), "bye").unwrap();
        std::fs::write(root.join("note.md"), "ignored-by-scope").unwrap();
        git(root, &["add", "-A"]);
        git(root, &["commit", "-qm", "base"]);
        let baseline = String::from_utf8(
            std::process::Command::new("git")
                .args(["rev-parse", "HEAD"])
                .current_dir(root)
                .output()
                .unwrap()
                .stdout,
        )
        .unwrap()
        .trim()
        .to_string();

        // Move: modify keep.rs, delete gone.rs, add new.rs, touch note.md.
        std::fs::write(root.join("keep.rs"), "two").unwrap();
        std::fs::remove_file(root.join("gone.rs")).unwrap();
        std::fs::write(root.join("new.rs"), "hi").unwrap();
        std::fs::write(root.join("note.md"), "still ignored").unwrap();
        git(root, &["add", "-A"]);
        git(root, &["commit", "-qm", "move"]);

        // Scope to *.rs only — note.md must not appear.
        let source = primary(vec![PatternEntry {
            path: "**/*.rs".to_string(),
            mode: PatternMode::Allow,
        }]);
        let outcome = compute_git_slice(&source, &[], root, Some(&baseline));
        match outcome {
            SliceOutcome::Changed {
                slice, degraded, ..
            } => {
                assert!(!degraded);
                assert_eq!(slice.added, vec!["new.rs"]);
                assert_eq!(slice.modified, vec!["keep.rs"]);
                assert_eq!(slice.deleted, vec!["gone.rs"]);
            }
            other => panic!("expected Changed, got {other:?}"),
        }

        // Same baseline == HEAD → Unchanged.
        let head = String::from_utf8(
            std::process::Command::new("git")
                .args(["rev-parse", "HEAD"])
                .current_dir(root)
                .output()
                .unwrap()
                .stdout,
        )
        .unwrap()
        .trim()
        .to_string();
        assert!(matches!(
            compute_git_slice(&source, &[], root, Some(&head)),
            SliceOutcome::Unchanged { .. }
        ));

        // A non-commit baseline → Reseed at HEAD.
        assert!(matches!(
            compute_git_slice(&source, &[], root, None),
            SliceOutcome::Reseed { .. }
        ));
    }

    /// Facet-file enumeration honours allow globs, deny globs, and the
    /// codebase/filesystem medium-type gate.
    #[test]
    fn enumerate_honours_allow_and_deny() {
        let ws = tempfile::tempdir().unwrap();
        let root = ws.path();
        std::fs::create_dir_all(root.join("sub")).unwrap();
        std::fs::write(root.join("a.rs"), "").unwrap();
        std::fs::write(root.join("sub/b.rs"), "").unwrap();
        std::fs::write(root.join("c.md"), "").unwrap();

        // medium_pointer "" → base is the workspace root; allow **/*.rs,
        // deny sub/** (so sub/b.rs is excluded, c.md never matched).
        let source = primary(vec![
            PatternEntry {
                path: "**/*.rs".to_string(),
                mode: PatternMode::Allow,
            },
            PatternEntry {
                path: "sub/**".to_string(),
                mode: PatternMode::Deny,
            },
        ]);
        assert_eq!(enumerate_facet_files(&source, &[], root), vec!["a.rs"]);

        // A graph medium enumerates nothing (not a file tree).
        let mut graph_source = source.clone();
        graph_source.medium_type = MediumType::Graph;
        assert!(enumerate_facet_files(&graph_source, &[], root).is_empty());
    }

    /// The mtime driver reseeds on the first pass (writing the memo), then
    /// diffs precisely against the memoised map — including deletions.
    #[test]
    fn mtime_driver_reseeds_then_diffs_precisely() {
        let ws = tempfile::tempdir().unwrap();
        let root = ws.path();
        let cache = root.join(".memstead.cache").join("ingest");
        std::fs::write(root.join("a.rs"), "one").unwrap();
        std::fs::write(root.join("gone.rs"), "bye").unwrap();
        let source = primary(vec![PatternEntry {
            path: "**/*.rs".to_string(),
            mode: PatternMode::Allow,
        }]);

        // First pass: no baseline → reseed at the current digest, memo written.
        let token = match compute_mtime_slice(&source, "ing", &[], root, &cache, None) {
            SliceOutcome::Reseed { token } => token,
            other => panic!("expected Reseed, got {other:?}"),
        };

        // Move the source: modify a.rs (size change), delete gone.rs, add new.rs.
        std::fs::write(root.join("a.rs"), "one-longer").unwrap();
        std::fs::remove_file(root.join("gone.rs")).unwrap();
        std::fs::write(root.join("new.rs"), "x").unwrap();

        // Second pass with the reseed token → precise diff from the memo.
        match compute_mtime_slice(&source, "ing", &[], root, &cache, Some(&token)) {
            SliceOutcome::Changed {
                slice, degraded, ..
            } => {
                assert!(
                    !degraded,
                    "memo present → precise, not a degraded full scan"
                );
                assert_eq!(slice.added, vec!["new.rs"]);
                assert_eq!(slice.modified, vec!["a.rs"]);
                assert_eq!(
                    slice.deleted,
                    vec!["gone.rs"],
                    "deletions come from the memo"
                );
            }
            other => panic!("expected Changed, got {other:?}"),
        }

        // A run whose baseline aggregate is not memoised degrades to a full
        // scan (every current file as added, no deletions).
        let stale = super::super::change_detection::serialize_digest_token(
            &super::super::change_detection::digest_stat_map(&stat_map_for(&["absent.rs"])),
        );
        match compute_mtime_slice(&source, "ing", &[], root, &cache, Some(&stale)) {
            SliceOutcome::Changed { degraded, .. } => assert!(degraded, "memo miss → degraded"),
            other => panic!("expected degraded Changed, got {other:?}"),
        }
    }

    fn head_sha(repo: &Path) -> String {
        String::from_utf8(
            std::process::Command::new("git")
                .args(["rev-parse", "HEAD"])
                .current_dir(repo)
                .output()
                .unwrap()
                .stdout,
        )
        .unwrap()
        .trim()
        .to_string()
    }

    fn slice_contains(slice: &Slice, path: &str) -> bool {
        let p = path.to_string();
        slice.added.contains(&p) || slice.modified.contains(&p) || slice.deleted.contains(&p)
    }

    /// The mtime `source_moved` / `current_primary_token` value: the digest
    /// token over the deny-filtered enumeration — exactly what the mtime branch
    /// of `current_primary_token` computes.
    fn mtime_token(source: &Source, deny: &[String], root: &Path) -> String {
        let files = enumerate_facet_files(source, deny, root);
        serialize_digest_token(&digest_stat_map(&compute_stat_map(&files, root)))
    }

    /// AC1 (deny invariance): a file matching an ingest `deny_paths` entry
    /// appears in **no** changed slice (git, mtime), **no** refinement batch,
    /// and does **not** influence the mtime digest / `source_moved` token —
    /// exercising the *same* denied file across every strategy that reads a
    /// file tree.
    #[test]
    fn deny_paths_excluded_from_every_strategy_and_token() {
        use crate::binding::BuildMode;
        use crate::ingest::refinement::next_batch;
        use crate::pipeline::IngestTrigger;

        let repo = tempfile::tempdir().unwrap();
        let root = repo.path();
        let cache = root.join(".memstead.cache").join("ingest");

        // One tree that is both the git work tree and the mtime/refinement
        // workspace root (medium_pointer "" → base == root).
        git(root, &["init", "-q"]);
        std::fs::write(root.join("keep.rs"), "one").unwrap();
        std::fs::write(root.join("denied.rs"), "secret-one").unwrap();
        git(root, &["add", "-A"]);
        git(root, &["commit", "-qm", "base"]);
        let baseline = head_sha(root);

        // Both files genuinely move — denied.rs must never surface anywhere.
        std::fs::write(root.join("keep.rs"), "two").unwrap();
        std::fs::write(root.join("denied.rs"), "secret-two").unwrap();
        git(root, &["add", "-A"]);
        git(root, &["commit", "-qm", "move"]);

        // Scope allows every .rs; the ingest denies denied.rs by the same
        // workspace-relative glob grammar the git strategy uses.
        let source = primary(vec![PatternEntry {
            path: "**/*.rs".to_string(),
            mode: PatternMode::Allow,
        }]);
        let deny = vec!["denied.rs".to_string()];

        // (1) git slice — with the deny, only keep.rs.
        match compute_git_slice(&source, &deny, root, Some(&baseline)) {
            SliceOutcome::Changed { slice, .. } => {
                assert_eq!(slice.modified, vec!["keep.rs"]);
                assert!(!slice_contains(&slice, "denied.rs"), "git deny leak");
            }
            other => panic!("git: expected Changed, got {other:?}"),
        }
        // Control: without the deny, denied.rs *is* a real change — proving the
        // deny (not the scope) is what excludes it above.
        match compute_git_slice(&source, &[], root, Some(&baseline)) {
            SliceOutcome::Changed { slice, .. } => {
                assert!(
                    slice_contains(&slice, "denied.rs"),
                    "un-denied, denied.rs is a genuine git change"
                );
            }
            other => panic!("git(no-deny): expected Changed, got {other:?}"),
        }

        // (2) enumeration (mtime input set + refinement source set).
        assert_eq!(enumerate_facet_files(&source, &deny, root), vec!["keep.rs"]);
        assert!(
            enumerate_facet_files(&source, &[], root).contains(&"denied.rs".to_string()),
            "un-denied, denied.rs is enumerated"
        );

        // (2b) mtime slice — reseed, then move both files; only keep.rs surfaces.
        let token = match compute_mtime_slice(&source, "ing", &deny, root, &cache, None) {
            SliceOutcome::Reseed { token } => token,
            other => panic!("mtime reseed expected, got {other:?}"),
        };
        std::fs::write(root.join("keep.rs"), "three-longer").unwrap();
        std::fs::write(root.join("denied.rs"), "secret-three-longer").unwrap();
        match compute_mtime_slice(&source, "ing", &deny, root, &cache, Some(&token)) {
            SliceOutcome::Changed { slice, .. } => {
                assert_eq!(slice.modified, vec!["keep.rs"]);
                assert!(!slice_contains(&slice, "denied.rs"), "mtime deny leak");
            }
            other => panic!("mtime: expected Changed, got {other:?}"),
        }

        // (3) mtime digest / source_moved token — invariant to denied.rs, since
        // the token is the digest over the deny-filtered enumeration. Removing
        // denied.rs from disk leaves the token unchanged; a leak would show it
        // as a deletion and shift the digest.
        let token_present = mtime_token(&source, &deny, root);
        std::fs::remove_file(root.join("denied.rs")).unwrap();
        let token_absent = mtime_token(&source, &deny, root);
        assert_eq!(
            token_present, token_absent,
            "denied.rs must not influence the mtime digest / source_moved token"
        );
        std::fs::write(root.join("denied.rs"), "secret-restored").unwrap();

        // (4) refinement batch — the denied file is never batched.
        let resolved = ResolvedIngest {
            name: "ing".to_string(),
            mode: BuildMode::Discovery,
            trigger: IngestTrigger::Loop,
            batch_size: 50,
            deny_paths: deny.clone(),
            projection_ref: "m/p".to_string(),
            projection_mem: "m".to_string(),
            projection_name: "p".to_string(),
            intent: None,
            sources: vec![ResolvedSource::Primary(source.clone())],
            destination_mem: "m".to_string(),
            rules: None,
            post_actions: None,
        };
        let batch = next_batch(&resolved, root, &cache, 20).unwrap();
        assert!(
            batch.files.contains(&"keep.rs".to_string()),
            "keep.rs batched"
        );
        assert!(
            !batch.files.contains(&"denied.rs".to_string()),
            "denied.rs must never enter a refinement batch"
        );
    }

    /// AC2 (one empty-scope semantic): an **unscoped** facet (no allow
    /// patterns) is the same typed refusal — `NoSignal { Unscoped }` — on git
    /// AND mtime, never a silent empty slice. AC2 complement: an empty
    /// `deny_paths` list does NOT trip that refusal — a *scoped* facet still
    /// classifies normally (empty scope and empty deny_paths are different
    /// fields with different semantics).
    #[test]
    fn unscoped_facet_refuses_uniformly_and_empty_deny_is_distinct() {
        let repo = tempfile::tempdir().unwrap();
        let root = repo.path();
        let cache = root.join(".memstead.cache").join("ingest");
        git(root, &["init", "-q"]);
        std::fs::write(root.join("a.rs"), "one").unwrap();
        git(root, &["add", "-A"]);
        git(root, &["commit", "-qm", "base"]);
        let baseline = head_sha(root);
        std::fs::write(root.join("a.rs"), "two").unwrap();
        git(root, &["add", "-A"]);
        git(root, &["commit", "-qm", "move"]);

        // Unscoped: a deny pattern but no allow. `deny_paths` is empty here —
        // so the refusal comes from the empty *scope*, not from denies.
        let unscoped = primary(vec![PatternEntry {
            path: "target/**".to_string(),
            mode: PatternMode::Deny,
        }]);
        assert_eq!(
            compute_git_slice(&unscoped, &[], root, Some(&baseline)),
            SliceOutcome::NoSignal {
                reason: NoSignalReason::Unscoped
            },
            "git refuses an unscoped facet"
        );
        assert_eq!(
            compute_mtime_slice(&unscoped, "ing", &[], root, &cache, None),
            SliceOutcome::NoSignal {
                reason: NoSignalReason::Unscoped
            },
            "mtime refuses an unscoped facet identically"
        );
        // A fully empty scope is unscoped too.
        let empty_scope = primary(vec![]);
        assert_eq!(
            compute_git_slice(&empty_scope, &[], root, Some(&baseline)),
            SliceOutcome::NoSignal {
                reason: NoSignalReason::Unscoped
            }
        );

        // Complement: a SCOPED facet with an empty `deny_paths` classifies
        // normally — empty deny_paths (no denies) must not trip the refusal.
        let scoped = primary(vec![PatternEntry {
            path: "**/*.rs".to_string(),
            mode: PatternMode::Allow,
        }]);
        assert!(
            matches!(
                compute_git_slice(&scoped, &[], root, Some(&baseline)),
                SliceOutcome::Changed { .. }
            ),
            "scoped facet + empty deny_paths → normal git slice, not a refusal"
        );
        assert!(
            matches!(
                compute_mtime_slice(&scoped, "ing", &[], root, &cache, None),
                SliceOutcome::Reseed { .. }
            ),
            "scoped facet + empty deny_paths → normal mtime reseed, not a refusal"
        );
    }

    /// AC2 refinement leg: an ingest whose only source is unscoped emits no
    /// refinement batch — the refusal, not a silent empty batch.
    #[test]
    fn unscoped_facet_emits_no_refinement_batch() {
        use crate::binding::BuildMode;
        use crate::ingest::refinement::next_batch;
        use crate::pipeline::IngestTrigger;

        let ws = tempfile::tempdir().unwrap();
        let root = ws.path();
        let cache = root.join(".memstead.cache").join("ingest");
        std::fs::write(root.join("a.rs"), "x").unwrap();

        let resolved = ResolvedIngest {
            name: "ing".to_string(),
            mode: BuildMode::Discovery,
            trigger: IngestTrigger::Loop,
            batch_size: 50,
            deny_paths: vec![],
            projection_ref: "m/p".to_string(),
            projection_mem: "m".to_string(),
            projection_name: "p".to_string(),
            intent: None,
            // Only source: an unscoped facet (no allow patterns).
            sources: vec![ResolvedSource::Primary(primary(vec![]))],
            destination_mem: "m".to_string(),
            rules: None,
            post_actions: None,
        };
        assert!(
            next_batch(&resolved, root, &cache, 20).is_none(),
            "an all-unscoped ingest emits no refinement batch"
        );
    }

    /// AC3 (visible NoSignal) end-to-end through the cursor: a `signal:none`
    /// source and an unscoped source each contribute a distinct no-signal note;
    /// a first-seen (reseed) source does NOT — only no-signal reasons are
    /// noted. The rendered preface names `signal:none` explicitly and the
    /// unscoped reason distinctly.
    #[test]
    fn compute_source_cursor_notes_no_signal_reasons() {
        use crate::binding::BuildMode;
        use crate::pipeline::IngestTrigger;

        let engine = crate::Engine::from_mounts(Vec::new()).unwrap();
        // No `.git` over the workspace → mtime strategy for `auto`/`mtime`.
        let ws = tempfile::tempdir().unwrap();
        let root = ws.path();
        std::fs::write(root.join("a.rs"), "x").unwrap();

        let allow_rs = || {
            vec![PatternEntry {
                path: "**/*.rs".to_string(),
                mode: PatternMode::Allow,
            }]
        };
        let src = |facet: &str, declared: &str, scope: Vec<PatternEntry>| {
            ResolvedSource::Primary(Source {
                name: facet.to_string(),
                medium_type: MediumType::Filesystem,
                pointer: String::new(),
                change_detection: Some(declared.to_string()),
                scope,
                engagement: None,
                preparation: None,
            })
        };

        let resolved = ResolvedIngest {
            name: "ing".to_string(),
            mode: BuildMode::Discovery,
            trigger: IngestTrigger::Loop,
            batch_size: 20,
            deny_paths: vec![],
            projection_ref: "m/p".to_string(),
            projection_mem: "m".to_string(),
            projection_name: "p".to_string(),
            intent: None,
            sources: vec![
                // signal:none → DetectionNone note (even though it is scoped).
                src("plan", "none", allow_rs()),
                // mtime + no allows → Unscoped note.
                src("blind", "mtime", vec![]),
                // mtime + allows, first-seen → Reseed, NOT a no-signal note.
                src("watched", "mtime", allow_rs()),
            ],
            destination_mem: "m".to_string(),
            rules: None,
            post_actions: None,
        };

        let cursor = compute_source_cursor(&engine, &resolved, root);
        let reasons: BTreeMap<&str, NoSignalReason> = cursor
            .no_signal
            .iter()
            .map(|n| (n.source.as_str(), n.reason))
            .collect();
        assert_eq!(reasons.get("plan"), Some(&NoSignalReason::DetectionNone));
        assert_eq!(reasons.get("blind"), Some(&NoSignalReason::Unscoped));
        assert!(
            !reasons.contains_key("watched"),
            "a first-seen (reseed) source is not a no-signal note"
        );
        assert_eq!(cursor.no_signal.len(), 2);
        // The reseed source still produced a reseed command.
        assert!(cursor.reseed.iter().any(|c| c.key == "ing/watched#synced"));

        // The rendered preface names signal:none and the unscoped reason.
        let out = crate::ingest::brief::render_changed_slice(&cursor);
        assert!(out.contains("- `plan`: `signal:none`"));
        assert!(out.contains("- `blind`: unscoped facet"));
    }

    fn stat_map_for(paths: &[&str]) -> super::super::change_detection::StatMap {
        paths
            .iter()
            .map(|p| {
                (
                    (*p).to_string(),
                    super::super::change_detection::StatEntry { mtime: 1, size: 1 },
                )
            })
            .collect()
    }

    /// Engine self-exclusion: `.memstead/**`, `.memstead.cache/**`, and
    /// every mount's resolved storage location (here a mem-repo at a
    /// NON-default directory name) are absent from the enumeration
    /// regardless of configuration — explicit allow globs covering them
    /// do not admit them.
    #[test]
    fn engine_state_never_enumerates_even_when_allowed() {
        let ws = tempfile::tempdir().unwrap();
        let root = ws.path();
        for rel in [
            ".memstead/state/findings/muehle/f.json",
            ".memstead/projections/muehle/f.json",
            ".memstead.cache/ingest/source-cursor/muehle/f/f.json",
            "custom-repo/README.md",
            "Allgemein/Protokoll.md",
            "Allgemein/Vertrag.md",
        ] {
            let path = root.join(rel);
            std::fs::create_dir_all(path.parent().unwrap()).unwrap();
            std::fs::write(&path, "x").unwrap();
        }
        // Engine-managed workspace state resolving the mem-repo at
        // `custom-repo/` — the exclusion must key on this resolved
        // location, not on the literal default name `mem-repo/`.
        std::fs::write(
            root.join(".memstead/workspace.toml"),
            "format = \"memstead-git-branch-2\"\n\n[persistence_adapter]\nname = \"file-two-layer\"\n",
        )
        .unwrap();
        std::fs::write(
            root.join(".memstead/state/mounts.json"),
            serde_json::json!({
                "format": "memstead-mounts-3",
                "mounts": [{
                    "mem": "muehle",
                    "schema": "default@1.0.0",
                    "storage": {
                        "type": "git-branch",
                        "gitdir": "custom-repo/.git",
                        "branch": "refs/heads/muehle"
                    },
                    "capability": "write",
                    "lifecycle": "eager",
                    "cross_linkable": true
                }]
            })
            .to_string(),
        )
        .unwrap();

        // Allow everything AND explicitly try to admit engine state.
        let source = primary(vec![
            PatternEntry {
                path: "**/*".to_string(),
                mode: PatternMode::Allow,
            },
            PatternEntry {
                path: ".memstead/**".to_string(),
                mode: PatternMode::Allow,
            },
            PatternEntry {
                path: "custom-repo/**".to_string(),
                mode: PatternMode::Allow,
            },
        ]);
        let got = enumerate_facet_files(&source, &[], root);
        assert_eq!(
            got,
            vec!["Allgemein/Protokoll.md", "Allgemein/Vertrag.md"],
            "only source artifacts may enter the denominator"
        );
    }

    /// The git strategy pushes the same engine-state excludes as
    /// pathspecs: a diff touching `.memstead/**` and the resolved
    /// mem-repo path yields a slice naming neither — denominator and
    /// slice stay strategy-invariant.
    #[test]
    fn git_slice_excludes_engine_state() {
        let repo = tempfile::tempdir().unwrap();
        let root = repo.path();
        git(root, &["init", "-q"]);
        std::fs::write(
            root.join("workspace.rs"), // placeholder so base commit is non-empty
            "x",
        )
        .unwrap();
        std::fs::create_dir_all(root.join(".memstead/state")).unwrap();
        std::fs::write(
            root.join(".memstead/workspace.toml"),
            "format = \"memstead-git-branch-2\"\n\n[persistence_adapter]\nname = \"file-two-layer\"\n",
        )
        .unwrap();
        std::fs::write(
            root.join(".memstead/state/mounts.json"),
            serde_json::json!({
                "format": "memstead-mounts-3",
                "mounts": [{
                    "mem": "muehle",
                    "schema": "default@1.0.0",
                    "storage": {
                        "type": "git-branch",
                        "gitdir": "custom-repo/.git",
                        "branch": "refs/heads/muehle"
                    },
                    "capability": "write",
                    "lifecycle": "eager",
                    "cross_linkable": true
                }]
            })
            .to_string(),
        )
        .unwrap();
        git(root, &["add", "-A"]);
        git(root, &["commit", "-qm", "base"]);
        let baseline = String::from_utf8(
            std::process::Command::new("git")
                .args(["rev-parse", "HEAD"])
                .current_dir(root)
                .output()
                .unwrap()
                .stdout,
        )
        .unwrap()
        .trim()
        .to_string();

        // Move: one real file, one engine-state file, one mem-repo file.
        std::fs::write(root.join("real.md"), "signal").unwrap();
        std::fs::write(root.join(".memstead/state/findings.json"), "self").unwrap();
        std::fs::create_dir_all(root.join("custom-repo")).unwrap();
        std::fs::write(root.join("custom-repo/README.md"), "repo").unwrap();
        git(root, &["add", "-A"]);
        git(root, &["commit", "-qm", "move"]);

        let source = primary(vec![PatternEntry {
            path: "**/*".to_string(),
            mode: PatternMode::Allow,
        }]);
        match compute_git_slice(&source, &[], root, Some(&baseline)) {
            SliceOutcome::Changed { slice, .. } => {
                assert_eq!(
                    slice.added,
                    vec!["real.md"],
                    "engine state leaked: {slice:?}"
                );
                assert!(slice.modified.is_empty(), "{slice:?}");
            }
            other => panic!("expected Changed, got {other:?}"),
        }
    }
}