fallow-cli 3.2.0

CLI for fallow, codebase intelligence for TypeScript and JavaScript
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
use std::path::{Path, PathBuf};

use toml::{Table, Value};

#[test]
fn repo_architecture_north_star_stays_documented() {
    let migration_doc =
        std::fs::read_to_string(workspace_root().join("docs/fallow-core-migration.md"))
            .expect("read core migration doc");
    for required in [
        "Architecture north star",
        "deterministic repo-intelligence engine",
        "Engine-first",
        "Contracts-first",
        "Session reuse before broad persistence",
        "Repo-policy as code",
        "Core stays backend-only",
    ] {
        assert!(
            migration_doc.contains(required),
            "core migration doc must keep the architecture north star: {required}"
        );
    }
    assert!(
        !migration_doc.contains("ADR-008"),
        "public core migration doc must stay self-contained instead of requiring private ADR context"
    );
}

#[test]
fn api_consumers_depend_on_api_not_engine_cli_or_core() {
    for manifest in [
        "crates/lsp/Cargo.toml",
        "crates/mcp/Cargo.toml",
        "crates/napi/Cargo.toml",
    ] {
        assert_no_deps(manifest, &["fallow-engine", "fallow-cli", "fallow-core"]);
    }
}

#[test]
fn cli_does_not_depend_on_core() {
    let manifest = read_manifest("crates/cli/Cargo.toml");
    assert!(
        !section_has_dep(&manifest, "dependencies", "fallow-core"),
        "fallow-cli must not depend on fallow-core in production dependencies"
    );
    assert!(
        !section_has_dep(&manifest, "dev-dependencies", "fallow-core"),
        "fallow-cli tests must use public contract crates instead of fallow-core"
    );
}

#[test]
fn root_envelope_compatibility_debt_stays_removed() {
    let root_envelopes =
        std::fs::read_to_string(workspace_root().join("crates/output/src/root_envelopes.rs"))
            .expect("read root envelopes");
    assert!(
        !root_envelopes.contains("RootEnvelopeMode::Legacy"),
        "legacy root envelope mode must not be reintroduced"
    );
    assert!(
        !root_envelopes.contains("remove_root_kind"),
        "root kind stripping must not be reintroduced"
    );
    let compat_docs =
        std::fs::read_to_string(workspace_root().join("docs/backwards-compatibility.md"))
            .expect("read compatibility docs");
    for required in ["top-level `kind` discriminator", "Tagged root envelopes"] {
        assert!(
            compat_docs.contains(required),
            "compatibility docs must keep tagged-envelope guidance: {required}"
        );
    }
}

#[test]
fn lower_contract_crates_do_not_depend_upward() {
    assert_no_deps(
        "crates/types/Cargo.toml",
        &[
            "fallow-config",
            "fallow-output",
            "fallow-api",
            "fallow-engine",
            "fallow-cli",
            "fallow-core",
        ],
    );
    assert_no_deps(
        "crates/config/Cargo.toml",
        &[
            "fallow-output",
            "fallow-api",
            "fallow-engine",
            "fallow-cli",
            "fallow-core",
        ],
    );
    assert_no_deps(
        "crates/security/Cargo.toml",
        &[
            "fallow-output",
            "fallow-api",
            "fallow-engine",
            "fallow-cli",
            "fallow-core",
        ],
    );
    assert_no_deps(
        "crates/output/Cargo.toml",
        &["fallow-api", "fallow-engine", "fallow-cli", "fallow-core"],
    );
}

#[test]
fn api_and_engine_do_not_depend_on_cli() {
    assert_no_deps("crates/api/Cargo.toml", &["fallow-cli"]);
    assert_no_deps("crates/engine/Cargo.toml", &["fallow-api", "fallow-cli"]);
}

#[test]
fn core_publish_status_matches_engine_dependency() {
    let manifest = read_manifest("crates/core/Cargo.toml");
    let engine = read_manifest("crates/engine/Cargo.toml");
    let engine_depends_on_core = section_has_dep(&engine, "dependencies", "fallow-core");
    let core_publish_disabled = manifest
        .get("package")
        .and_then(Value::as_table)
        .and_then(|package| package.get("publish"))
        == Some(&Value::Boolean(false));
    assert!(
        !engine_depends_on_core || !core_publish_disabled,
        "fallow-core cannot be publish=false while fallow-engine has a normal dependency on it"
    );

    let release_workflow =
        std::fs::read_to_string(workspace_root().join(".github/workflows/release.yml"))
            .expect("read release workflow");
    assert!(
        !engine_depends_on_core || release_workflow.contains("fallow-core fallow-engine"),
        "release workflow must publish fallow-core before fallow-engine until engine no longer depends on it"
    );
}

#[test]
fn engine_owns_parse_cache_size_policy() {
    let project_config = read_source_without_line_comments("crates/engine/src/project_config.rs")
        .expect("read engine project config");
    let core_backend = read_source_without_line_comments("crates/engine/src/core_backend.rs")
        .expect("read core backend adapter");
    assert!(
        project_config.contains("fallow_extract::cache::DEFAULT_CACHE_MAX_SIZE"),
        "engine project config must own parse-cache max-size fallback policy"
    );
    assert!(
        !core_backend.contains("resolve_cache_max_size_bytes"),
        "parse-cache size policy must not round-trip through the fallow-core adapter"
    );
    assert!(
        !core_backend.contains("collect_file_hashes"),
        "session-owned artifact metadata must not live in the fallow-core adapter"
    );
}

#[test]
fn api_does_not_depend_on_core_or_cli() {
    assert_no_deps("crates/api/Cargo.toml", &["fallow-core", "fallow-cli"]);
    for source_path in rust_sources_under(["crates/api/src"]) {
        let source = read_source_without_line_comments(&source_path)
            .unwrap_or_else(|error| panic!("read {source_path}: {error}"));
        for forbidden in [
            "fallow_core::",
            "use fallow_core",
            "fallow_cli::",
            "use fallow_cli",
        ] {
            assert!(
                !source.contains(forbidden),
                "{source_path} must consume fallow-engine or API-owned helpers instead of {forbidden}"
            );
        }
    }
}

#[test]
fn public_boundaries_do_not_wildcard_reexport_internal_type_crates() {
    for source_path in [
        "crates/engine/src/source.rs",
        "crates/engine/src/results.rs",
        "crates/api/src/editor.rs",
    ] {
        let source =
            std::fs::read_to_string(workspace_root().join(source_path)).expect("read source");
        for forbidden in [
            concat!("pub use fallow_types::extract::", "*"),
            concat!("pub use fallow_types::results::", "*"),
            concat!("pub use fallow_types::output_dead_code::", "*"),
        ] {
            assert!(
                !source.contains(forbidden),
                "{source_path} must keep public boundary reexports explicit"
            );
        }
    }
}

#[test]
fn api_editor_contracts_do_not_route_type_contracts_through_engine_facade() {
    let source_path = "crates/api/src/editor.rs";
    let source = std::fs::read_to_string(workspace_root().join(source_path)).expect("read source");
    for forbidden in [
        "pub use fallow_engine::",
        "pub use fallow_engine::source::",
        "pub use fallow_engine::results::",
        "pub type EditorCloneFamily = fallow_engine::",
        "pub type EditorCloneGroup = fallow_engine::",
        "pub type EditorCloneInstance = fallow_engine::",
        "pub type EditorDuplicationReport = fallow_engine::",
        "pub type EditorDuplicationStats = fallow_engine::",
        "pub type EditorMirroredDirectory = fallow_engine::",
        "pub type EditorRefactoringKind = fallow_engine::",
        "pub type EditorRefactoringSuggestion = fallow_engine::",
        "pub type EditorDeadCodeAnalysisOutput = fallow_engine::",
        "pub type EditorProjectAnalysisOutput = fallow_engine::",
    ] {
        assert!(
            !source.contains(forbidden),
            "{source_path} must re-export editor type contracts from fallow-types directly"
        );
    }
}

#[test]
fn api_programmatic_health_runner_does_not_expose_engine_results() {
    let source_path = "crates/api/src/runtime/mod.rs";
    let source = std::fs::read_to_string(workspace_root().join(source_path)).expect("read source");
    for forbidden in [
        "pub analysis: fallow_engine::results::HealthAnalysisResult",
        "pub type ProgrammaticHealthAnalysis = fallow_engine::",
        "pub type ProgrammaticHealthRun = fallow_engine::",
        "pub fn derive_programmatic_health_execution_options",
    ] {
        assert!(
            !source.contains(forbidden),
            "{source_path} must expose API-owned programmatic health runner contracts"
        );
    }

    let lib_path = "crates/api/src/lib.rs";
    let lib = std::fs::read_to_string(workspace_root().join(lib_path)).expect("read source");
    for forbidden in [
        "pub use fallow_engine::{",
        "ComplexityRunOptions, ComplexitySectionOptions, DerivedComplexityOptions",
        "DerivedHealthSections, HealthSectionOptions, derive_complexity_sections",
        "derive_programmatic_health_execution_options",
    ] {
        assert!(
            !lib.contains(forbidden),
            "{lib_path} must expose API-owned health option contracts"
        );
    }
}

#[test]
fn engine_does_not_publish_legacy_graph_cache_resolve_modules() {
    let lib = std::fs::read_to_string(workspace_root().join("crates/engine/src/lib.rs"))
        .expect("read engine lib");
    for forbidden in ["pub mod cache;", "pub mod graph;", "pub mod resolve;"] {
        assert!(
            !lib.contains(forbidden),
            "fallow-engine must keep legacy {forbidden} wrapper modules private or removed"
        );
    }

    for removed in [
        "crates/engine/src/cache.rs",
        "crates/engine/src/graph.rs",
        "crates/engine/src/resolve.rs",
    ] {
        assert!(
            !workspace_root().join(removed).exists(),
            "{removed} must not return as a compatibility wrapper"
        );
    }
}

#[test]
fn api_and_cli_use_duplicate_output_contracts_from_types() {
    let duplicate_contract_types = [
        "CloneFamily",
        "CloneGroup",
        "CloneInstance",
        "DefaultIgnoreSkips",
        "DuplicationReport",
        "DuplicationStats",
        "MirroredDirectory",
        "RefactoringKind",
        "RefactoringSuggestion",
    ];
    for source_path in rust_sources_under(["crates/api/src", "crates/cli/src"]) {
        if source_path == "crates/cli/src/architecture_boundaries.rs" {
            continue;
        }
        let source = read_source_without_line_comments(&source_path)
            .unwrap_or_else(|error| panic!("read {source_path}: {error}"));
        for ty in duplicate_contract_types {
            let forbidden = format!("fallow_engine::{ty}");
            assert!(
                !source.contains(&forbidden),
                "{source_path} must import duplicate output contracts from fallow-types, not fallow-engine"
            );
        }
    }
}

#[test]
fn api_and_cli_use_trace_output_contracts_from_types() {
    let trace_contract_types = [
        "CloneTrace",
        "DependencyTrace",
        "ExportReference",
        "ExportTrace",
        "FileTrace",
        "ImpactClosureGap",
        "ImpactClosureTrace",
        "PipelineTimings",
        "ReExportChain",
        "TracedCloneGroup",
        "TracedExport",
        "TracedReExport",
    ];
    for source_path in rust_sources_under(["crates/api/src", "crates/cli/src"]) {
        if source_path == "crates/cli/src/architecture_boundaries.rs" {
            continue;
        }
        let source = read_source_without_line_comments(&source_path)
            .unwrap_or_else(|error| panic!("read {source_path}: {error}"));
        for ty in trace_contract_types {
            let forbidden = format!("fallow_engine::{ty}");
            assert!(
                !source.contains(&forbidden),
                "{source_path} must import trace output contracts from fallow-types, not fallow-engine"
            );
        }
    }
}

#[test]
fn engine_adapter_modules_are_explicit_public_boundaries() {
    let engine_lib = std::fs::read_to_string(workspace_root().join("crates/engine/src/lib.rs"))
        .expect("read engine lib");
    for required in [
        "pub mod changed_files;",
        "pub mod churn;",
        "pub mod cross_reference;",
        "pub mod dead_code;",
        "pub mod discover;",
        "pub mod duplicates;",
        "pub mod health;",
        "pub mod module_graph;",
        "pub mod plugins;",
        "pub mod project_analysis;",
        "pub mod project_config;",
        "pub mod session;",
        "pub mod source;",
        "pub mod trace;",
        "pub mod trace_chain;",
    ] {
        assert!(
            engine_lib.contains(required),
            "engine module boundary must stay explicit: {required}"
        );
    }

    for private in [
        "pub mod core_backend;",
        "pub mod error;",
        "pub mod git_env;",
        "pub mod public_api;",
        "pub mod results;",
        "pub mod security;",
    ] {
        assert!(
            !engine_lib.contains(private),
            "engine private adapter module must not become a public catch-all boundary: {private}"
        );
    }
}

#[test]
fn api_and_cli_do_not_use_removed_engine_root_adapter_exports() {
    for source_path in rust_sources_under(["crates/api/src", "crates/cli/src"]) {
        if source_path == "crates/cli/src/architecture_boundaries.rs" {
            continue;
        }
        let source = read_source_without_line_comments(&source_path)
            .unwrap_or_else(|error| panic!("read {source_path}: {error}"));
        for forbidden in [
            "fallow_engine::AnalysisSession",
            "fallow_engine::AnalysisSessionArtifacts",
            "fallow_engine::ProjectAnalysisArtifactOptions",
            "fallow_engine::ProjectAnalysisOutput",
            "fallow_engine::ProjectAnalysisArtifacts",
            "fallow_engine::ProjectConfig",
            "fallow_engine::ProjectConfigOptions",
            "fallow_engine::results::",
            "fallow_engine::ChangedFilesError",
            "fallow_engine::changed_files(",
            "fallow_engine::config_for_project(",
            "fallow_engine::config_for_project_analysis(",
            "fallow_engine::discover_entry_points(",
            "fallow_engine::discover_files",
            "fallow_engine::filter_results_by_changed_files",
            "fallow_engine::get_changed_files(",
            "fallow_engine::resolve_cache_max_size_bytes(",
            "fallow_engine::try_get_changed_files",
            "fallow_engine::ChurnResult",
            "fallow_engine::ChurnTrend",
            "fallow_engine::FileChurn",
            "fallow_engine::SinceDuration",
            "fallow_engine::analyze_churn",
            "fallow_engine::is_git_repo(",
            "fallow_engine::parse_since(",
            "fallow_engine::RetainedModuleGraph",
            "fallow_engine::ImpactClosurePaths",
            "fallow_engine::PartitionOrderPaths",
            "fallow_engine::FocusFileFactsPaths",
            "fallow_engine::CoordinationGapPaths",
            "fallow_engine::module_value_exports(",
            "fallow_engine::CrossReferenceResult",
            "fallow_engine::cross_reference(",
            "fallow_engine::trace_clone(",
            "fallow_engine::trace_dependency(",
            "fallow_engine::trace_export(",
            "fallow_engine::trace_file(",
            "fallow_engine::trace_symbol_chain(",
        ] {
            assert!(
                !source.contains(forbidden),
                "{source_path} must use the typed fallow-engine module path instead of removed root export {forbidden}"
            );
        }
    }
}

#[test]
fn cli_json_root_outputs_use_runtime_envelope_mode() {
    let allowed = [
        "crates/cli/src/architecture_boundaries.rs",
        "crates/cli/src/output_runtime.rs",
        "crates/cli/src/output_envelope.rs",
    ];
    for source_path in rust_sources_under(["crates/cli/src"]) {
        if allowed.contains(&source_path.as_str()) {
            continue;
        }
        let source = read_source_without_line_comments(&source_path)
            .unwrap_or_else(|error| panic!("read {source_path}: {error}"));
        let forbidden = "RootEnvelopeMode::Tagged";
        assert!(
            !source.contains(forbidden),
            "{source_path} must use output_runtime::current_root_envelope_mode() for root JSON output"
        );
    }
}

#[test]
fn include_dupes_reuses_dead_code_discovery_artifacts() {
    let check = read_source_without_line_comments("crates/cli/src/check/mod.rs")
        .expect("read check module");
    let output = read_source_without_line_comments("crates/cli/src/check/output.rs")
        .expect("read check output module");
    assert!(
        check.contains("opts.include_dupes")
            && check.contains("AnalysisSession::from_resolved_config")
            && check.contains(".analyze_dead_code_retaining_files"),
        "check --include-dupes must retain discovered files from the shared AnalysisSession dead-code run"
    );
    assert!(
        check.contains("result.retained_files.as_deref()")
            || check.contains("result\n            .retained_files\n            .as_deref()"),
        "check --include-dupes must pass retained discovered files into cross-reference"
    );
    assert!(
        !output.contains("discover_files_with_plugin_scopes"),
        "check cross-reference output must not rediscover files after dead-code analysis"
    );
}

#[test]
fn check_command_dead_code_routes_through_analysis_session() {
    let check = read_source_without_line_comments("crates/cli/src/check/mod.rs")
        .expect("read check module");
    assert!(
        check.contains("AnalysisSession::from_resolved_config"),
        "check must build an AnalysisSession before dead-code variants"
    );
    for forbidden in [
        "fallow_engine::dead_code::analyze(",
        "fallow_engine::dead_code::analyze_with_trace",
        "fallow_engine::dead_code::analyze_retaining_files",
        "fallow_engine::dead_code::analyze_retaining_modules",
    ] {
        assert!(
            !check.contains(forbidden),
            "check must route dead-code analysis through AnalysisSession instead of {forbidden}"
        );
    }
}

#[test]
fn security_command_dead_code_routes_through_analysis_session() {
    let security = read_source_without_line_comments("crates/cli/src/security.rs")
        .expect("read security module");
    assert!(
        security.contains("AnalysisSession::from_resolved_config"),
        "security must build an AnalysisSession before dead-code variants"
    );
    for forbidden in [
        "fallow_engine::dead_code::analyze(",
        "fallow_engine::dead_code::analyze_retaining_modules",
    ] {
        assert!(
            !security.contains(forbidden),
            "security must route dead-code analysis through AnalysisSession instead of {forbidden}"
        );
    }
}

#[test]
fn fix_command_dead_code_routes_through_analysis_session() {
    let fix =
        read_source_without_line_comments("crates/cli/src/fix/mod.rs").expect("read fix module");
    assert!(
        fix.contains("AnalysisSession::from_resolved_config"),
        "fix must build an AnalysisSession before dead-code analysis"
    );
    assert!(
        !fix.contains("fallow_engine::dead_code::analyze_with_file_hashes"),
        "fix must collect file hashes through AnalysisSession artifacts"
    );
}

#[test]
fn coverage_upload_dead_code_routes_through_analysis_session() {
    for source_path in [
        "crates/cli/src/coverage/upload_static_findings.rs",
        "crates/cli/src/coverage/upload_inventory.rs",
    ] {
        let source =
            read_source_without_line_comments(source_path).expect("read coverage upload module");
        assert!(
            source.contains("AnalysisSession::from_resolved_config"),
            "{source_path} must build an AnalysisSession before dead-code analysis"
        );
        for forbidden in [
            "fallow_engine::dead_code::analyze(",
            "fallow_engine::dead_code::analyze_retaining_modules",
        ] {
            assert!(
                !source.contains(forbidden),
                "{source_path} must route dead-code analysis through AnalysisSession instead of {forbidden}"
            );
        }
    }
}

#[test]
fn watch_command_dead_code_routes_through_analysis_session() {
    let watch =
        read_source_without_line_comments("crates/cli/src/watch.rs").expect("read watch module");
    assert!(
        watch.contains("AnalysisSession::from_resolved_config"),
        "watch must build an AnalysisSession before dead-code analysis"
    );
    assert!(
        !watch.contains("fallow_engine::dead_code::analyze("),
        "watch must route dead-code analysis through AnalysisSession"
    );
}

#[test]
fn feature_flags_reuse_session_parse_and_discovery() {
    let flags = read_source_without_line_comments("crates/engine/src/flags.rs")
        .expect("read engine flags module");
    assert!(
        flags.contains("analyze_feature_flags_with_session"),
        "feature flags must expose the session-backed runner"
    );
    for forbidden in [
        "discover_files_with_plugin_scopes",
        "parse_files_for_config",
        "analyze_with_parse_result",
    ] {
        assert!(
            !flags.contains(forbidden),
            "feature flags must reuse AnalysisSession parse/discovery instead of {forbidden}"
        );
    }
}

#[test]
fn list_surfaces_reuse_session_discovery() {
    for source_path in ["crates/cli/src/list.rs", "crates/api/src/list_runtime.rs"] {
        let source = read_source_without_line_comments(source_path).expect("read source");
        assert!(
            source.contains("AnalysisSession::from_"),
            "{source_path} must build an AnalysisSession before collecting discovered files"
        );
        assert!(
            !source.contains("discover_files_with_plugin_scopes"),
            "{source_path} must reuse AnalysisSession discovery instead of direct discovery"
        );
        if source_path == "crates/cli/src/list.rs" {
            assert!(
                source.contains("session.workspaces()")
                    && source.contains("session.workspace_diagnostics()"),
                "{source_path} must reuse AnalysisSession workspace metadata when a session already exists"
            );
        }
    }
}

#[test]
fn list_surfaces_delegate_inventory_composition_to_engine() {
    for source_path in ["crates/cli/src/list.rs", "crates/api/src/list_runtime.rs"] {
        let source = read_source_without_line_comments(source_path).expect("read source");
        assert!(
            source.contains("fallow_engine::list_inventory"),
            "{source_path} must use engine-owned list inventory helpers"
        );
        for forbidden in [
            "discover_entry_points(",
            "discover_workspace_entry_points(",
            "discover_plugin_entry_points(",
            "PluginRegistry::new",
            "PackageJson::load",
            "merge_active_plugins_from",
        ] {
            assert!(
                !source.contains(forbidden),
                "{source_path} must not own list inventory composition helper `{forbidden}`"
            );
        }
    }
}

#[test]
fn coverage_inventory_reuses_session_discovery() {
    let source = read_source_without_line_comments("crates/cli/src/coverage/upload_inventory.rs")
        .expect("read coverage upload inventory");
    assert!(
        source.contains("AnalysisSession::from_resolved_config"),
        "coverage upload-inventory must create one AnalysisSession for inventory discovery"
    );
    assert!(
        source.contains("fn collect_inventory(\n    session: &AnalysisSession"),
        "coverage inventory collection must receive the shared AnalysisSession"
    );
    assert!(
        source.contains("fn collect_caller_edges(\n    session: &AnalysisSession"),
        "caller-edge collection must reuse the inventory AnalysisSession"
    );
    assert!(
        !source.contains("discover_files_with_plugin_scopes"),
        "coverage upload-inventory must reuse AnalysisSession discovery instead of direct discovery"
    );
}

#[test]
fn decision_surface_reuses_session_workspace_metadata() {
    let source = read_source_without_line_comments("crates/api/src/runtime/decision_surface.rs")
        .expect("read decision surface runtime");
    assert!(
        source.contains("session.workspaces()"),
        "decision surface must reuse workspace metadata captured by AnalysisSession"
    );
    assert!(
        !source.contains("discover_workspaces("),
        "decision surface must not rediscover workspaces after building an AnalysisSession"
    );
    assert!(
        !source.contains("PackageJson::load"),
        "decision surface must not own root package metadata reads after building an AnalysisSession"
    );

    let review_deltas =
        read_source_without_line_comments("crates/api/src/review_deltas.rs").expect("read deltas");
    assert!(
        review_deltas.contains("fallow_engine::project_analysis::public_export_keys_for_graph"),
        "review deltas must use engine-owned public API graph policy"
    );
    assert!(
        !review_deltas.contains("fallow_config::PackageJson"),
        "review deltas must not own package metadata policy"
    );

    let audit = read_source_without_line_comments("crates/cli/src/audit.rs").expect("read audit");
    assert!(
        audit.contains(
            "review_deltas::public_export_keys_for(graph, &check.config, &check.workspaces, root)"
        ),
        "audit brief must route public API key selection through review deltas"
    );
    assert!(
        !audit.contains("PackageJson::load"),
        "audit brief must not own public API package metadata reads"
    );
}

#[test]
fn project_info_reuses_session_workspace_metadata() {
    let source = read_source_without_line_comments("crates/api/src/list_runtime.rs")
        .expect("read list runtime");
    assert!(
        source.contains("let workspaces = session.workspaces();"),
        "project info must read workspace metadata from the shared AnalysisSession"
    );
    assert!(
        !source.contains("discover_workspaces(")
            && !source.contains("discover_workspaces_with_diagnostics("),
        "project info must not rediscover workspaces after building an AnalysisSession"
    );
}

#[test]
fn session_backed_api_runtimes_defer_workspace_scope_to_session() {
    for source_path in [
        "crates/api/src/runtime/combined.rs",
        "crates/api/src/runtime/dead_code.rs",
        "crates/api/src/runtime/duplication.rs",
        "crates/api/src/runtime/feature_flags.rs",
        "crates/api/src/runtime/decision_surface.rs",
    ] {
        let source = read_source_without_line_comments(source_path).expect("read runtime source");
        assert!(
            source.contains("resolve_programmatic_analysis_context_deferred_workspace"),
            "{source_path} must defer workspace scope until an AnalysisSession has workspace metadata"
        );
    }

    for source_path in [
        "crates/api/src/runtime/dead_code.rs",
        "crates/api/src/runtime/duplication.rs",
        "crates/api/src/runtime/feature_flags.rs",
        "crates/api/src/runtime/decision_surface.rs",
        "crates/api/src/runtime/mod.rs",
    ] {
        let source = read_source_without_line_comments(source_path).expect("read runtime source");
        assert!(
            source.contains("workspace_roots_for_session("),
            "{source_path} must resolve workspace filters from session.workspaces()"
        );
        assert!(
            !source.contains("resolved.workspace_roots.as_ref()"),
            "{source_path} must not apply eager workspace roots in session-backed analysis"
        );
    }
}

#[test]
fn session_backed_api_next_steps_reuse_session_workspaces() {
    let dead_code = read_source_without_line_comments("crates/api/src/runtime/dead_code.rs")
        .expect("read dead-code runtime source");
    assert!(
        dead_code.contains("default_workspace_ref_for_workspaces(root, session.workspaces())"),
        "dead-code next steps must reuse AnalysisSession workspace metadata"
    );
    assert!(
        !dead_code.contains("default_workspace_ref(root)"),
        "dead-code next steps must not rediscover workspaces after building an AnalysisSession"
    );

    let combined = read_source_without_line_comments("crates/api/src/runtime/combined.rs")
        .expect("read combined runtime source");
    assert!(
        combined.contains("workspaces: Some(session.workspaces().to_vec())")
            && combined.contains("default_workspace_ref_for_workspaces(root, workspaces)"),
        "combined next steps must carry session workspace metadata into shared-session output"
    );
}

#[test]
fn next_step_workspace_ref_probing_routes_through_engine() {
    for source_path in [
        "crates/api/src/next_steps.rs",
        "crates/cli/src/report/suggestions.rs",
    ] {
        let source = read_source_without_line_comments(source_path).expect("read source");
        assert!(
            source.contains("fallow_engine::repo_refs::default_workspace_ref"),
            "{source_path} must use engine-owned repo-ref probing"
        );
        for forbidden in [
            "Command::new(\"git\")",
            "std::process::Command::new(\"git\")",
            "fn git_ref_exists",
            "fn run_git",
            "symbolic-ref",
            "origin/master",
        ] {
            assert!(
                !source.contains(forbidden),
                "{source_path} must not own git-ref probing helper `{forbidden}`"
            );
        }
    }
}

#[test]
fn routing_self_identity_probe_routes_through_engine() {
    let source_path = "crates/api/src/routing.rs";
    let source = read_source_without_line_comments(source_path).expect("read routing source");
    assert!(
        source.contains("fallow_engine::repo_refs::current_user_identities"),
        "routing must use engine-owned git identity probing"
    );
    for forbidden in [
        "Command::new(\"git\")",
        "std::process::Command::new(\"git\")",
        "fn current_user_identities",
        "user.email",
        "user.name",
    ] {
        assert!(
            !source.contains(forbidden),
            "{source_path} must not own git identity probing helper `{forbidden}`"
        );
    }
}

#[test]
fn audit_repo_ref_orchestration_routes_through_engine() {
    let source_path = "crates/api/src/runtime/audit.rs";
    let source = read_source_without_line_comments(source_path).expect("read audit source");
    let production_source = source
        .split("\n#[cfg(test)]")
        .next()
        .expect("audit source before tests");
    assert!(
        production_source.contains("repo_refs::{self, ResolvedAuditBase, TemporaryBaseWorktree}"),
        "audit runtime must use engine-owned repo-ref and base-worktree helpers"
    );
    for forbidden in [
        "Command::new(\"git\")",
        "std::process::Command::new(\"git\")",
        "clear_ambient_git_env",
        "fn git_stdout",
        "fn git_ref_exists",
        "fn git_upstream_ref",
        "fn git_merge_base",
        "fn detect_remote_default_ref",
        "fn get_head_sha",
        "struct BaseWorktree",
    ] {
        assert!(
            !production_source.contains(forbidden),
            "{source_path} must not own audit git orchestration helper `{forbidden}`"
        );
    }

    let decision_surface_path = "crates/api/src/runtime/decision_surface.rs";
    let decision_surface =
        read_source_without_line_comments(decision_surface_path).expect("read decision surface");
    assert!(
        decision_surface.contains("fallow_engine::repo_refs::{self, TemporaryBaseWorktree}"),
        "decision surface must use engine-owned base-worktree helpers"
    );
    assert!(
        !decision_surface.contains("super::audit::BaseWorktree")
            && !decision_surface.contains("super::audit::base_analysis_root"),
        "{decision_surface_path} must not depend on audit-internal base-worktree helpers"
    );
}

#[test]
fn combined_and_audit_share_project_analysis_artifacts() {
    for source_path in [
        "crates/api/src/runtime/combined.rs",
        "crates/api/src/runtime/audit.rs",
    ] {
        let source = read_source_without_line_comments(source_path).expect("read runtime source");
        assert!(
            source.contains("analyze_project_with_artifacts"),
            "{source_path} must reuse one engine-owned project artifact run for shared dead-code and duplication paths"
        );
        assert!(
            source.contains("run_dead_code_from_artifacts")
                && source.contains("run_duplication_report_with_session"),
            "{source_path} must build API outputs from retained artifacts instead of rerunning dead-code or duplication"
        );
        assert!(
            source.contains("health_may_consume_duplication_report")
                && source.contains("project.duplication.clone()")
                && (source.contains("pre_computed_duplication")
                    || source.contains("duplication_artifacts")),
            "{source_path} must pass the already computed project duplication report into health when score or targets need it"
        );
    }
}

#[test]
fn grouped_health_reuses_project_duplication_artifacts() {
    let output_build =
        read_source_without_line_comments("crates/engine/src/health/output_build.rs")
            .expect("read health output build");
    let grouping = read_source_without_line_comments("crates/engine/src/health/grouping.rs")
        .expect("read health grouping");
    assert!(
        output_build.contains("derived_sections.dupes_report.as_ref()"),
        "health grouping must receive the already computed project duplication report"
    );
    assert!(
        grouping.contains("dupes_report: Option<&'a DuplicationReport>"),
        "health grouping must model duplication as an artifact input"
    );
    assert!(
        !grouping.contains("find_duplicates(")
            && !grouping.contains("find_duplicates_cached(")
            && !grouping.contains("duplicates::find_duplicates"),
        "health grouping must not run an additional duplicate analysis per group"
    );
}

#[test]
fn standalone_health_parse_precompute_does_not_fill_session_cache() {
    for source_path in [
        "crates/cli/src/health/mod.rs",
        "crates/engine/src/health/runner.rs",
    ] {
        let source = read_source_without_line_comments(source_path).expect("read health source");
        assert!(
            source.contains("parsed_parts_uncached(true)"),
            "{source_path} must avoid retaining an extra full module vector for one-shot health precompute"
        );
    }
}

#[test]
fn framework_health_reuses_pipeline_workspaces() {
    let framework_health =
        read_source_without_line_comments("crates/engine/src/health/framework_health.rs")
            .expect("read framework health source");
    assert!(
        !framework_health.contains("discover_workspaces("),
        "framework health diagnostics must use HealthPipelineInputs workspaces instead of rediscovering"
    );
    let execute = read_source_without_line_comments("crates/engine/src/health/execute.rs")
        .expect("read health execute source");
    assert!(
        execute.contains("workspaces,") && execute.contains("workspaces: &workspaces"),
        "health execute must thread pipeline workspaces into output assembly"
    );
}

#[test]
fn explain_dead_code_aliases_route_through_issue_registry() {
    let source = read_source_without_line_comments("crates/api/src/explain.rs")
        .expect("read explain source");
    assert!(
        source.contains("issue_meta_for_contract_token"),
        "fallow explain must resolve dead-code tokens through IssueKindMeta"
    );
    assert!(
        source.contains("rule_result_meta(rule).map_or(rule.name, |meta| meta.meta_name)")
            && source.contains(
                "rule_result_meta(rule).map_or(rule.short, |meta| meta.sarif_description)"
            )
            && source.contains(
                "rule_result_meta(rule).map_or(rule.docs_path, |meta| meta.meta_docs_path)"
            ),
        "standalone explain output must derive shared contract fields from IssueResultMeta"
    );
    assert!(
        !source.contains("dead_code_alias_id(") && !source.contains("catalog_alias_id("),
        "dead-code and catalog explain aliases must not be mirrored outside IssueKindMeta"
    );
}

#[test]
fn sarif_rule_descriptions_live_in_issue_result_registry() {
    let source = read_source_without_line_comments("crates/types/src/issue_meta.rs")
        .expect("read issue metadata source");
    assert!(
        source.contains("pub sarif_description: &'static str"),
        "IssueResultMeta must own SARIF short descriptions"
    );
    assert!(
        source.contains("issue_result_meta_by_code(code).map(|meta| meta.sarif_description)"),
        "SARIF rule descriptions must resolve from IssueResultMeta"
    );
    assert!(
        !source.contains("\"unused-file\" => Some(")
            && !source.contains("\"unused-export\" => Some(")
            && !source.contains("\"unresolved-import\" => Some("),
        "SARIF descriptions must not be mirrored in a per-issue match"
    );
}

#[test]
fn typescript_alias_policy_routes_through_issue_registry() {
    let source = read_source_without_line_comments("crates/types/src/issue_meta.rs")
        .expect("read issue metadata source");
    assert!(
        source.contains("pub const ISSUE_TS_ALIAS_META"),
        "TypeScript alias policy must live in registry data"
    );
    assert!(
        source.contains("ISSUE_TS_ALIAS_META")
            && source.contains(".find(|meta| meta.code == code)")
            && source.contains(".map(|meta| meta.alias)"),
        "issue_ts_alias must resolve from ISSUE_TS_ALIAS_META"
    );
    assert!(
        !source.contains("\"unused-file\" => TsAliasMeta")
            && !source.contains("\"unused-export\" => TsAliasMeta")
            && !source.contains("\"unresolved-import\" => TsAliasMeta"),
        "TypeScript aliases must not be mirrored in a per-issue match"
    );
}

#[test]
fn vscode_tree_labels_route_through_generated_issue_registry() {
    let source = std::fs::read_to_string(workspace_root().join("editors/vscode/src/labels.ts"))
        .expect("read vscode labels");
    assert!(
        source.contains("DIAGNOSTIC_CATEGORIES"),
        "VS Code tree labels must read labels from the generated IssueKindMeta surface"
    );
    assert!(
        !source.contains("\"Unused Files\"")
            && !source.contains("\"Unused Exports\"")
            && !source.contains("\"Code Duplication\""),
        "VS Code tree labels must not mirror issue labels as a hand-maintained string table"
    );
}

#[test]
fn lsp_changed_since_scopes_editor_project_analysis_before_duplication() {
    let source =
        read_source_without_line_comments("crates/lsp/src/analysis.rs").expect("read lsp analysis");
    assert!(
        source.contains("resolve_changed_since_scope("),
        "LSP must resolve changedSince before per-root analysis so shared project artifacts can receive the scope"
    );
    assert!(
        source.contains("analyze_project_with_changed_files"),
        "LSP editor analysis must pass changed files into the typed editor API before duplication runs"
    );
    assert!(
        source.contains("analysis.filter_by_changed_files"),
        "LSP must keep the existing post-analysis changedSince filter for dead-code and inline complexity semantics"
    );
}

#[test]
fn engine_session_and_dead_code_route_core_calls_through_backend_adapter() {
    assert_engine_modules_do_not_call_core_directly();
    assert_engine_session_owns_parse_orchestration();
    assert_engine_dead_code_facade_has_no_analysis_bypasses();
    assert_engine_discovery_exposes_session_oriented_surface();
    assert_engine_changed_files_owns_git_orchestration();
}

fn assert_engine_modules_do_not_call_core_directly() {
    for source_path in [
        "crates/engine/src/session.rs",
        "crates/engine/src/dead_code.rs",
        "crates/engine/src/trace.rs",
        "crates/engine/src/trace_chain.rs",
    ] {
        let source =
            std::fs::read_to_string(workspace_root().join(source_path)).expect("read source");
        assert!(
            !source.contains("fallow_core::"),
            "{source_path} must use engine::core_backend instead of direct fallow_core calls"
        );
    }
}

fn assert_engine_session_owns_parse_orchestration() {
    let session = read_source_without_line_comments("crates/engine/src/session.rs")
        .expect("read engine session source");
    for forbidden in [
        "analyze_with_usages_from_discovery",
        "analyze_with_usages_and_complexity_from_discovery",
        "analyze_retaining_modules_from_discovery",
        "pub fn analyze_dead_code_from_config",
        "pub fn analyze_dead_code_with_complexity_from_config",
        "pub fn analyze_dead_code_with_artifacts_from_config",
        "pub fn analyze_dead_code_retaining_files_from_config",
        "pub fn analyze_dead_code_with_parse_result_from_config",
    ] {
        assert!(
            !session.contains(forbidden),
            "engine session must own dead-code parse orchestration instead of calling {forbidden}"
        );
    }
}

fn assert_engine_dead_code_facade_has_no_analysis_bypasses() {
    let core_backend = read_source_without_line_comments("crates/engine/src/core_backend.rs")
        .expect("read engine core backend source");
    assert!(
        !core_backend.contains("fallow_core::analyze_with_parse_result"),
        "engine reused-parse analysis must use the engine-owned dead-code phase pipeline"
    );
    assert!(
        !core_backend.contains("fallow_core::analyze::derive_security_severity"),
        "engine security severity policy must stay in fallow-engine, not the core analyze namespace"
    );
    assert!(
        !core_backend.contains("fallow_core::analyze::public_api_package_entry_points"),
        "engine public API entry-point selection must stay in fallow-engine, not the core analyze namespace"
    );
    assert!(
        !core_backend.contains("fallow_core::config_for_project"),
        "engine project config resolution must stay owned by fallow-engine, not the old core monolith"
    );

    let dead_code =
        read_source_without_line_comments("crates/engine/src/dead_code.rs").expect("read source");
    assert!(
        !dead_code.contains("core_backend::analyze_with_parse_result"),
        "engine dead-code facade must not delegate reused-parse analysis to the old core monolith"
    );
    for forbidden in [
        "pub fn analyze(",
        "pub fn analyze_with_usages(",
        "pub fn analyze_with_file_hashes(",
        "pub fn analyze_with_trace(",
        "pub fn analyze_retaining_modules(",
        "pub fn analyze_retaining_files(",
        "pub fn analyze_with_parse_result(",
        "pub fn analyze_with_usages_and_complexity(",
    ] {
        assert!(
            !dead_code.contains(forbidden),
            "engine dead-code facade must not expose direct analysis bypass {forbidden}; use AnalysisSession"
        );
    }

    let cli_dupes =
        read_source_without_line_comments("crates/cli/src/dupes.rs").expect("read cli dupes");
    assert!(
        !cli_dupes.contains("discover_files_with_plugin_scopes"),
        "standalone dupes must use AnalysisSession discovery instead of direct discovery"
    );

    let project_config = read_source_without_line_comments("crates/engine/src/project_config.rs")
        .expect("read engine project config source");
    assert!(
        !project_config.contains("core_backend::config_for_project"),
        "engine project config must not route through the core backend adapter"
    );
}

fn assert_engine_discovery_exposes_session_oriented_surface() {
    let engine_discover = read_source_without_line_comments("crates/engine/src/discover.rs")
        .expect("read engine discover");
    for forbidden in [
        "pub fn discover_files(",
        "pub fn discover_files_with_additional_hidden_dirs(",
        "pub fn discover_files_with_plugin_scopes(",
    ] {
        assert!(
            !engine_discover.contains(forbidden),
            "engine discovery must expose session-oriented discovery instead of leftover direct helper {forbidden}"
        );
    }
}

fn assert_engine_changed_files_owns_git_orchestration() {
    let changed_files = read_source_without_line_comments("crates/engine/src/changed_files.rs")
        .expect("read source");
    for forbidden in [
        "core_backend::set_changed_files_spawn_hook",
        "core_backend::validate_git_ref",
        "core_backend::resolve_git_toplevel",
        "core_backend::resolve_git_common_dir",
        "core_backend::try_get_changed_files",
        "core_backend::try_get_changed_diff",
        "core_backend::get_changed_files",
    ] {
        assert!(
            !changed_files.contains(forbidden),
            "engine changed-files git orchestration must be owned by changed_files.rs, not {forbidden}"
        );
    }

    let core_backend = read_source_without_line_comments("crates/engine/src/core_backend.rs")
        .expect("read engine core backend source");
    for forbidden in [
        "fallow_core::changed_files::set_spawn_hook",
        "fallow_core::changed_files::validate_git_ref",
        "fallow_core::changed_files::resolve_git_toplevel",
        "fallow_core::changed_files::resolve_git_common_dir",
        "fallow_core::changed_files::try_get_changed_files",
        "fallow_core::changed_files::try_get_changed_diff",
        "fallow_core::changed_files::get_changed_files",
        "fallow_core::changed_files::filter_results_by_changed_files",
        "fallow_core::changed_files::filter_duplication_by_changed_files",
    ] {
        assert!(
            !core_backend.contains(forbidden),
            "engine core_backend must not re-introduce changed-files orchestration through {forbidden}"
        );
    }

    let core_lib =
        read_source_without_line_comments("crates/core/src/lib.rs").expect("read core lib source");
    assert!(
        !core_lib.contains("pub mod changed_files"),
        "fallow-core must not re-publish changed-file orchestration after it moved to fallow-engine"
    );
}

#[test]
fn core_legacy_orchestration_is_hidden_from_public_docs() {
    let source = std::fs::read_to_string(workspace_root().join("crates/core/src/lib.rs"))
        .expect("read core lib");
    for item in [
        "pub struct AnalysisOutput",
        "pub struct AnalysisParseMetrics",
        "pub struct AnalysisDiscovery",
        "pub struct DeadCodePreludeTimings",
        "pub struct DeadCodeBackendPrelude",
        "pub struct DeadCodeEntryPoints",
        "pub struct DeadCodeResolvedModules",
        "pub struct DeadCodeGraphRun",
        "pub struct DeadCodeDetectorRun",
        "pub fn analyze(",
        "pub fn analyze_with_usages(",
        "pub fn analyze_with_trace(",
        "pub fn analyze_retaining_modules(",
    ] {
        assert_doc_hidden_before(&source, item);
    }
    assert!(
        !source.contains("pub fn config_for_project("),
        "fallow-core config_for_project must stay crate-private now that fallow-engine owns project config resolution"
    );
    assert!(
        !source.contains("pub fn analyze_project("),
        "fallow-core analyze_project must stay crate-private now that fallow-api owns the public project analysis surface"
    );
    assert!(
        !source.contains("pub fn analyze_with_usages_and_complexity("),
        "fallow-core analyze_with_usages_and_complexity must stay removed; LSP now composes typed API and health artifacts"
    );
    assert!(
        !source.contains("pub fn analyze_with_file_hashes("),
        "fallow-core analyze_with_file_hashes must stay removed; fix and CLI callers use AnalysisSession artifacts"
    );
    assert!(
        !source.contains("pub fn analyze_with_parse_result("),
        "fallow-core analyze_with_parse_result must stay removed; pre-parsed reuse stays behind fallow-engine AnalysisSession"
    );
    assert!(
        !source.contains("pub fn public_api_package_entry_points("),
        "fallow-core public_api_package_entry_points must stay private; engine owns the public API entrypoint surface"
    );
    assert!(
        !source.contains("pub use entry_points::resolve_entry_path"),
        "fallow-core resolve_entry_path must not be externally re-exported; engine owns public API entrypoint resolution"
    );
}

#[test]
fn core_legacy_orchestration_wrappers_stay_out_of_production_call_paths() {
    for source_path in rust_sources_under([
        "crates/api/src",
        "crates/cli/src",
        "crates/engine/src",
        "crates/lsp/src",
        "crates/mcp/src",
        "crates/napi/src",
    ]) {
        if source_path == "crates/cli/src/architecture_boundaries.rs" {
            continue;
        }
        let source = read_source_without_line_comments(&source_path)
            .unwrap_or_else(|error| panic!("read {source_path}: {error}"));
        for forbidden in [
            "fallow_core::analyze(",
            "fallow_core::analyze_with_usages(",
            "fallow_core::analyze_with_trace(",
            "fallow_core::analyze_retaining_modules(",
            "fallow_core::analyze_with_parse_result(",
        ] {
            assert!(
                !source.contains(forbidden),
                "{source_path} must not call legacy fallow-core orchestration wrapper {forbidden}"
            );
        }
    }
}

#[test]
fn api_consumers_do_not_reference_engine_core_or_cli_sources() {
    for source_path in rust_sources_under(["crates/lsp/src", "crates/mcp/src", "crates/napi/src"]) {
        let source = read_source_without_line_comments(&source_path)
            .unwrap_or_else(|error| panic!("read {source_path}: {error}"));
        for forbidden in [
            "fallow_engine::",
            "use fallow_engine",
            "fallow_core::",
            "use fallow_core",
            "fallow_cli::",
            "use fallow_cli",
        ] {
            assert!(
                !source.contains(forbidden),
                "{source_path} must consume fallow-api instead of {forbidden}"
            );
        }
    }
}

#[test]
fn mcp_api_routes_honor_ambient_changed_since_scope() {
    for source_path in [
        "crates/mcp/src/tools/analyze.rs",
        "crates/mcp/src/tools/audit.rs",
        "crates/mcp/src/tools/code_mode_tools.rs",
        "crates/mcp/src/tools/decision_surface.rs",
        "crates/mcp/src/tools/dupes.rs",
        "crates/mcp/src/tools/flags.rs",
        "crates/mcp/src/tools/health.rs",
        "crates/mcp/src/tools/list_boundaries.rs",
        "crates/mcp/src/tools/project_info.rs",
        "crates/mcp/src/tools/trace.rs",
    ] {
        let source = read_source_without_line_comments(source_path)
            .unwrap_or_else(|error| panic!("read {source_path}: {error}"));
        assert!(
            source.contains("changed_since_from_param("),
            "{source_path} must apply FALLOW_CHANGED_SINCE when tool params omit changed_since"
        );
    }
}

#[test]
fn engine_root_facade_does_not_reexport_private_adapter_helpers() {
    let source_path = "crates/engine/src/lib.rs";
    let source = read_source_without_line_comments(source_path)
        .unwrap_or_else(|error| panic!("read {source_path}: {error}"));
    for forbidden in [
        "ChangedFilesSpawnHook",
        "ChurnSpawnHook",
        "analyze_churn_from_file",
        "collect_hidden_dir_scopes",
        "compile_glob_set",
        "discover_dynamically_loaded_entry_points",
        "discover_files_and_config_candidates",
        "discover_infrastructure_entry_points",
        "discover_plugin_entry_point_sets",
        "AnalysisSessionParts",
        "pub use health::",
        "health_scoring",
        "health_ownership",
        "pub use dead_code::",
        "analyze_retaining_modules",
        "analyze_with_file_hashes",
        "filter_to_workspaces",
        "pub use duplicates::",
        "pub use changed_files::",
        "pub use churn::",
        "pub use cross_reference::",
        "pub use discover::",
        "pub use module_graph::",
        "pub use plugins::",
        "pub use project_config::",
        "pub use session::",
        "pub use source::inventory",
        "pub use trace::",
        "pub use trace_chain::",
        "InventoryComplexity",
        "InventoryEntry",
        "walk_source_with_complexity",
    ] {
        assert!(
            !source.contains(forbidden),
            "fallow-engine root facade must not re-export private adapter helper {forbidden}"
        );
    }
}

#[test]
fn engine_core_references_stay_inside_adapter_modules() {
    let allowed = ["crates/engine/src/core_backend.rs"];
    for source_path in rust_sources_under(["crates/engine/src"]) {
        let source = read_source_without_line_comments(&source_path)
            .unwrap_or_else(|error| panic!("read {source_path}: {error}"));
        if source.contains("fallow_core::") || source.contains("use fallow_core") {
            assert!(
                allowed.contains(&source_path.as_str()),
                "{source_path} must route fallow_core access through core_backend or an approved typed adapter still awaiting containment"
            );
        }
    }
}

#[test]
fn public_core_migration_messages_stay_self_contained() {
    for source_path in rust_sources_under(["crates/core/src", "crates/core/benches"]) {
        let source = read_source_without_line_comments(&source_path)
            .unwrap_or_else(|error| panic!("read {source_path}: {error}"));
        assert!(
            !source.contains("ADR-008"),
            "{source_path} must not require private ADR context for public fallow-core migration messaging"
        );
    }
}

#[test]
fn api_and_cli_workspace_discovery_routes_through_engine() {
    for source_path in rust_sources_under(["crates/api/src", "crates/cli/src"]) {
        if source_path == "crates/cli/src/architecture_boundaries.rs" {
            continue;
        }
        let source = read_source_without_line_comments(&source_path)
            .unwrap_or_else(|error| panic!("read {source_path}: {error}"));
        for forbidden in [
            "fallow_config::discover_workspaces(",
            "fallow_config::discover_workspaces_with_diagnostics(",
            "use fallow_config::{discover_workspaces",
            "use fallow_config::discover_workspaces",
        ] {
            assert!(
                !source.contains(forbidden),
                "{source_path} must route workspace discovery through fallow_engine::discover or AnalysisSession"
            );
        }
    }
}

#[test]
fn engine_source_inventory_owns_public_contracts() {
    let source_path = "crates/engine/src/source.rs";
    let source = std::fs::read_to_string(workspace_root().join(source_path)).expect("read source");
    for forbidden in [
        "pub use fallow_extract::cache::CacheStore",
        "pub use fallow_extract::inventory::",
        "pub type InventoryEntry = fallow_extract::",
        "pub type CacheStore = fallow_extract::",
    ] {
        assert!(
            !source.contains(forbidden),
            "{source_path} must wrap extractor inventory output in engine-owned contracts"
        );
    }

    let lib = std::fs::read_to_string(workspace_root().join("crates/engine/src/lib.rs"))
        .expect("read engine lib");
    assert!(
        !lib.contains("pub use source::CacheStore"),
        "engine root must not publish extractor parse-cache internals"
    );
}

#[test]
fn engine_root_does_not_publish_graph_node_internals() {
    let lib_path = "crates/engine/src/lib.rs";
    let lib = std::fs::read_to_string(workspace_root().join(lib_path)).expect("read engine lib");
    for forbidden in [
        " ModuleGraph,",
        "ModuleNode",
        "ExportSymbol",
        "ResolvedModule",
        "pub use module_graph::{ ModuleNode",
    ] {
        assert!(
            !lib.contains(forbidden),
            "{lib_path} must expose graph snapshots and query helpers, not graph internals"
        );
    }
    for line in lib.lines() {
        assert!(
            !line.contains("ModuleGraph") || line.contains("RetainedModuleGraph"),
            "{lib_path} must expose RetainedModuleGraph, not concrete ModuleGraph"
        );
    }

    let coverage_path = "crates/cli/src/health/coverage.rs";
    let coverage =
        std::fs::read_to_string(workspace_root().join(coverage_path)).expect("read coverage");
    for forbidden in ["fallow_engine::ModuleNode", ".is_test_reachable"] {
        assert!(
            !coverage.contains(forbidden),
            "{coverage_path} must use engine-owned graph export snapshots"
        );
    }

    let module_graph_path = "crates/engine/src/module_graph.rs";
    let module_graph = std::fs::read_to_string(workspace_root().join(module_graph_path))
        .expect("read engine module graph");
    for forbidden in [
        "pub use fallow_graph::",
        "pub type ModuleGraph = fallow_graph::",
        "pub type ModuleNode = fallow_graph::",
        "pub type ExportSymbol = fallow_graph::",
        "pub type ResolvedModule = fallow_graph::",
    ] {
        assert!(
            !module_graph.contains(forbidden),
            "{module_graph_path} must wrap graph internals in engine-owned contracts"
        );
    }
}

#[test]
fn cli_audit_uses_engine_graph_fact_helpers() {
    let source_path = "crates/cli/src/audit.rs";
    let source = std::fs::read_to_string(workspace_root().join(source_path)).expect("read audit");
    for forbidden in [
        "graph.modules",
        ".impact_closure(&changed_ids)",
        ".partition_order(&changed_ids)",
        ".focus_file_facts(&changed_ids)",
    ] {
        assert!(
            !source.contains(forbidden),
            "{source_path} must ask fallow-engine for path-resolved graph facts"
        );
    }
}

#[test]
fn api_and_cli_workspace_scope_resolution_routes_through_engine() {
    for source_path in [
        "crates/api/src/analysis_context.rs",
        "crates/cli/src/check/filtering.rs",
    ] {
        let source = read_source_without_line_comments(source_path)
            .unwrap_or_else(|error| panic!("read {source_path}: {error}"));
        assert!(
            source.contains("fallow_engine::workspace_scope"),
            "{source_path} must route workspace-scope resolution through fallow-engine"
        );
        if source_path == "crates/api/src/analysis_context.rs" {
            assert!(
                source.contains("resolve_workspace_scope_roots_for_project"),
                "{source_path} must use the engine-owned project workspace-scope helper"
            );
            assert!(
                !source.contains("discover_workspace_packages(root)"),
                "{source_path} must not rediscover workspaces outside the engine workspace-scope helper"
            );
        }
        for forbidden in [
            "globset::Glob",
            "fn split_workspace_patterns",
            "fn split_patterns",
            "fn find_workspace_matches",
            "fn find_matches",
            "fn match_positive_workspace_patterns",
            "fn match_positive_patterns",
            "fn relative_workspace_path",
            "fn format_available_workspaces",
            "fn workspaces_containing_any",
        ] {
            assert!(
                !source.contains(forbidden),
                "{source_path} must not own workspace-scope matching helper `{forbidden}`"
            );
        }
    }
}

fn read_source_without_line_comments(path: &str) -> std::io::Result<String> {
    let source = std::fs::read_to_string(workspace_root().join(path))?;
    Ok(source
        .lines()
        .filter(|line| !line.trim_start().starts_with("//"))
        .collect::<Vec<_>>()
        .join("\n"))
}

fn assert_doc_hidden_before(source: &str, item: &str) {
    let index = source
        .find(item)
        .unwrap_or_else(|| panic!("expected to find {item}"));
    let prefix = &source[..index];
    let recent_attributes = prefix
        .rsplit_once("\n\n")
        .map_or(prefix, |(_, recent)| recent);
    assert!(
        recent_attributes.contains("#[doc(hidden)]"),
        "{item} must stay hidden from fallow-core rustdoc; expose engine/api wrappers instead"
    );
}

fn assert_no_deps(manifest_path: &str, forbidden: &[&str]) {
    let manifest = read_manifest(manifest_path);
    for section in ["dependencies", "dev-dependencies", "build-dependencies"] {
        for dep in forbidden {
            assert!(
                !section_has_dep(&manifest, section, dep),
                "{manifest_path} must not list {dep} under {section}"
            );
        }
    }
}

fn rust_sources_under<const N: usize>(roots: [&str; N]) -> Vec<String> {
    let mut sources = Vec::new();
    for root in roots {
        collect_rust_sources(&workspace_root().join(root), root, &mut sources);
    }
    sources.sort();
    sources
}

fn collect_rust_sources(dir: &Path, relative_dir: &str, out: &mut Vec<String>) {
    for entry in
        std::fs::read_dir(dir).unwrap_or_else(|error| panic!("read {relative_dir}: {error}"))
    {
        let entry = entry.unwrap_or_else(|error| panic!("read entry in {relative_dir}: {error}"));
        let path = entry.path();
        let file_name = entry.file_name();
        let file_name = file_name.to_string_lossy();
        let relative_path = format!("{relative_dir}/{file_name}");
        if path.is_dir() {
            collect_rust_sources(&path, &relative_path, out);
        } else if path.extension().is_some_and(|extension| extension == "rs") {
            out.push(relative_path);
        }
    }
}

fn section_has_dep(manifest: &Value, section: &str, dep: &str) -> bool {
    manifest
        .get(section)
        .and_then(Value::as_table)
        .is_some_and(|deps| deps.contains_key(dep))
}

fn read_manifest(path: &str) -> Value {
    let text = std::fs::read_to_string(workspace_root().join(path)).expect("read Cargo.toml");
    Value::Table(text.parse::<Table>().expect("parse Cargo.toml"))
}

fn workspace_root() -> PathBuf {
    Path::new(env!("CARGO_MANIFEST_DIR"))
        .parent()
        .and_then(Path::parent)
        .expect("workspace root")
        .to_path_buf()
}