nodus 0.17.0

Local-first CLI for managing project-scoped agent packages.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
mod doctor;
mod install_digest;
mod resolve;
mod support;

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

pub use self::doctor::{
    DoctorActionRecord, DoctorFinding, DoctorFindingKind, DoctorMode, DoctorStatus, DoctorSummary,
    doctor_in_dir_with_mode,
};
use self::install_digest::install_digest_from_disk;
use self::resolve::{ResolveProjectOptions, resolve_project};
use self::support::{
    build_sync_execution_plan, enforce_capabilities, execute_sync_plan, find_managed_collision,
    find_runtime_output_collision, find_unmanaged_collision, load_owned_paths,
    recover_runtime_owned_paths, recover_runtime_owned_paths_from_disk,
    unmanaged_collision_guidance,
};
#[cfg(test)]
use self::support::{prune_empty_parent_dirs, write_managed_files};
use crate::adapters::{
    Adapter, Adapters, ManagedFile, OutputPlan, OutputPlanOptions, PackageOwnedPaths,
    build_output_plan_with_options,
};
use crate::execution::ExecutionMode;
use crate::hashing::content_digest;
use crate::install_paths::{InstallPaths, InstallScope};
use crate::lockfile::{
    LOCKFILE_NAME, LockedPackage, LockedSource, Lockfile, compact_owned_runtime_adapter_ownership,
    locked_runtime_adapter_owned_paths,
};
use crate::manifest::{
    DependencyComponent, LoadedManifest, ManagedPlacement, Manifest, PackageRole,
    load_root_from_dir_allow_missing,
};
use crate::paths::display_path;
use crate::report::Reporter;
use crate::selection::{
    resolve_adapter_selection, resolve_global_adapter_selection, should_prompt_for_adapter,
};
use crate::store::{SnapshotSource, snapshot_packages};
use anyhow::{Result, bail};
#[cfg(test)]
use std::fs;

#[derive(Debug, Clone)]
pub struct Resolution {
    pub packages: Vec<ResolvedPackage>,
    pub warnings: Vec<String>,
    pub(crate) managed_migrations: Vec<ManagedMappingMigration>,
}

#[derive(Debug, Clone)]
pub struct ResolvedPackage {
    pub alias: String,
    pub root: PathBuf,
    pub manifest: LoadedManifest,
    pub source: PackageSource,
    pub digest: String,
    pub selected_components: Option<Vec<DependencyComponent>>,
    pub selected_workspace_members: Option<Vec<String>>,
    pub managed_paths: Vec<ResolvedManagedPath>,
    /// Set when this package is a workspace member resolved through an owning
    /// package (a git/path workspace dependency). It records the owner's source
    /// identity and namespace so every member of one repo + commit shares a
    /// stable plugin suffix (e.g. `+main`) and a namespaced plugin name.
    pub member_origin: Option<MemberOrigin>,
    extra_package_files: Vec<PathBuf>,
}

/// Identity of the package that owns a resolved workspace member. Members adopt
/// the owner's source-derived suffix so packages from the same git repo + commit
/// line up (`ena+main`, `ena-core+main`, `ena-rust+main`) instead of each member
/// falling back to its own digest hash.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MemberOrigin {
    /// Namespace declared by the owning workspace, if any (e.g. `ena`).
    pub namespace: Option<String>,
    /// Source of the owning package; members reuse its identity suffix.
    pub group_source: PackageSource,
    /// Owning package version, used as a suffix fallback for non-git groups.
    pub group_version: Option<String>,
    /// Owning package digest, used as the final suffix fallback.
    pub group_digest: String,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ResolvedManagedPath {
    pub source_root: PathBuf,
    pub target_root: PathBuf,
    pub ownership_root: PathBuf,
    pub files: Vec<ResolvedManagedFile>,
    pub origin: ResolvedManagedPathOrigin,
}

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct ResolvedManagedFile {
    pub source_relative: PathBuf,
    pub target_relative: PathBuf,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ResolvedManagedPathOrigin {
    LegacyDependencyMapping,
    PackageManagedExport { placement: ManagedPlacement },
}

#[derive(Debug, Clone)]
pub(crate) struct ManagedMappingMigration {
    alias: String,
    legacy_target_roots: Vec<PathBuf>,
    adds_additional_package_exports: bool,
}

#[derive(Debug, Clone)]
pub struct SyncSummary {
    pub package_count: usize,
    pub adapters: Vec<Adapter>,
    pub managed_file_count: usize,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PackageSource {
    Root,
    Path {
        path: PathBuf,
        tag: Option<String>,
    },
    Git {
        url: String,
        subpath: Option<PathBuf>,
        tag: Option<String>,
        branch: Option<String>,
        rev: String,
    },
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ResolveMode {
    Sync,
    Doctor,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum SyncMode {
    Normal,
    Locked,
    Frozen,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum DependencyFailureMode {
    Graceful,
    Strict,
}

#[derive(Clone)]
struct SyncExecutionOptions<'a> {
    allow_high_sensitivity: bool,
    force: bool,
    adapters: &'a [Adapter],
    sync_on_launch: bool,
    execution_mode: ExecutionMode,
    dependency_failure_mode: DependencyFailureMode,
    /// When true, skip the v10 `install_digest` drift fast-path even if all
    /// preconditions hold (lockfile is current schema, all pins are exact,
    /// every package has an `install_digest`). Slice 4 added the fast-path for
    /// the common "nothing changed on disk" case; this flag is the escape
    /// hatch for users who want to force a full re-render.
    force_rebuild: bool,
    /// CLI override for the Codex profile (`--codex-profile <name>`). Takes
    /// precedence over the manifest's `[adapters.codex] profile`. `None` means
    /// "no override"; fall back to the manifest.
    codex_profile: Option<String>,
}

impl<'a> SyncExecutionOptions<'a> {
    #[allow(clippy::too_many_arguments)]
    fn new(
        allow_high_sensitivity: bool,
        force: bool,
        adapters: &'a [Adapter],
        sync_on_launch: bool,
        execution_mode: ExecutionMode,
        dependency_failure_mode: DependencyFailureMode,
        force_rebuild: bool,
        codex_profile: Option<String>,
    ) -> Self {
        Self {
            allow_high_sensitivity,
            force,
            adapters,
            sync_on_launch,
            execution_mode,
            dependency_failure_mode,
            force_rebuild,
            codex_profile,
        }
    }
}

impl SyncMode {
    fn checks_lockfile(self) -> bool {
        matches!(self, Self::Locked | Self::Frozen)
    }

    fn installs_from_lockfile(self) -> bool {
        matches!(self, Self::Frozen)
    }

    fn flag(self) -> &'static str {
        match self {
            Self::Normal => "`nodus sync`",
            Self::Locked => "`nodus sync --locked`",
            Self::Frozen => "`nodus sync --frozen`",
        }
    }
}

/// Resolve the effective Codex profile for a sync or doctor run: the CLI
/// override when supplied, otherwise the manifest's `[adapters.codex] profile`.
/// The name is validated so nodus never writes the overlay outside `CODEX_HOME`.
pub(crate) fn resolve_codex_profile(
    manifest: &Manifest,
    override_profile: Option<&str>,
) -> Result<Option<String>> {
    let resolved = override_profile
        .map(str::trim)
        .filter(|name| !name.is_empty())
        .map(str::to_string)
        .or_else(|| manifest.codex_profile().map(str::to_string));
    if let Some(name) = resolved.as_deref() {
        validate_codex_profile_name(name)?;
    }
    Ok(resolved)
}

/// Codex resolves `--profile <name>` to `$CODEX_HOME/<name>.config.toml`, so the
/// profile name must be a single, benign path segment.
fn validate_codex_profile_name(name: &str) -> Result<()> {
    let unsafe_name = name.is_empty()
        || name == "."
        || name.contains("..")
        || name.contains('/')
        || name.contains('\\')
        || name.contains(std::path::MAIN_SEPARATOR)
        || name.chars().any(char::is_control);
    if unsafe_name {
        bail!(
            "invalid Codex profile `{name}`: use a simple profile name without path separators or `..`"
        );
    }
    Ok(())
}

fn lockfile_out_of_date_message() -> String {
    format!(
        "{LOCKFILE_NAME} is out of date; run `nodus sync` to regenerate the lockfile and managed outputs, then run `nodus doctor` to verify the project state"
    )
}

fn checked_sync_lockfile_out_of_date_message() -> String {
    format!(
        "{LOCKFILE_NAME} is out of date; run `nodus sync` without `--locked` or `--frozen` to regenerate the lockfile and managed outputs"
    )
}

#[derive(Debug, Clone)]
struct PlannedFileWrite {
    path: PathBuf,
    contents: Vec<u8>,
    create: bool,
}

#[derive(Debug, Clone)]
struct SyncExecutionPlan {
    runtime_root: PathBuf,
    manifest_write: Option<PlannedFileWrite>,
    removals: Vec<PathBuf>,
    managed_writes: Vec<ManagedFile>,
    external_writes: Vec<ManagedFile>,
    lockfile_write: Option<PlannedFileWrite>,
    warnings: Vec<String>,
    summary: SyncSummary,
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct UnmanagedCollision {
    path: PathBuf,
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct ManagedCollision {
    alias: String,
    ownership_root: PathBuf,
    collision_path: PathBuf,
    source: ManagedCollisionSource,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ManagedCollisionSource {
    LegacyDependencyMapping,
    PackageManagedExport,
    RuntimeOutput,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ManagedCollisionChoice {
    Adopt,
    RemoveMapping,
    Cancel,
}

trait ManagedCollisionResolver {
    fn resolve(
        &mut self,
        project_root: &Path,
        collision: &ManagedCollision,
    ) -> Result<ManagedCollisionChoice>;
}

struct TtyManagedCollisionResolver;

#[allow(clippy::too_many_arguments)]
pub fn sync_in_dir_with_adapters(
    cwd: &Path,
    cache_root: &Path,
    locked: bool,
    allow_high_sensitivity: bool,
    force: bool,
    adapters: &[Adapter],
    sync_on_launch: bool,
    reporter: &Reporter,
) -> Result<SyncSummary> {
    sync_in_dir_with_adapters_full(
        cwd,
        cache_root,
        locked,
        allow_high_sensitivity,
        force,
        adapters,
        sync_on_launch,
        false,
        None,
        reporter,
    )
}

/// `sync_in_dir_with_adapters` plus the v10 fast-path opt-out.
///
/// Slice 4 added the `install_digest` drift fast-path that lets `nodus sync`
/// exit early when the lockfile and disk agree. Pass `force_rebuild = true` to
/// skip that check and always run a full resolve + render. The CLI surfaces
/// this as `--no-fast-path`; library callers default to `false` so they keep
/// the speedup.
#[allow(clippy::too_many_arguments)]
pub fn sync_in_dir_with_adapters_full(
    cwd: &Path,
    cache_root: &Path,
    locked: bool,
    allow_high_sensitivity: bool,
    force: bool,
    adapters: &[Adapter],
    sync_on_launch: bool,
    force_rebuild: bool,
    codex_profile: Option<String>,
    reporter: &Reporter,
) -> Result<SyncSummary> {
    sync_in_dir_with_adapters_with_failure_mode(
        cwd,
        cache_root,
        locked,
        SyncExecutionOptions::new(
            allow_high_sensitivity,
            force,
            adapters,
            sync_on_launch,
            ExecutionMode::Apply,
            DependencyFailureMode::Graceful,
            force_rebuild,
            codex_profile,
        ),
        reporter,
    )
}

#[allow(clippy::too_many_arguments, dead_code)]
pub fn sync_in_dir_with_adapters_strict(
    cwd: &Path,
    cache_root: &Path,
    locked: bool,
    allow_high_sensitivity: bool,
    force: bool,
    adapters: &[Adapter],
    sync_on_launch: bool,
    reporter: &Reporter,
) -> Result<SyncSummary> {
    sync_in_dir_with_adapters_strict_full(
        cwd,
        cache_root,
        locked,
        allow_high_sensitivity,
        force,
        adapters,
        sync_on_launch,
        false,
        None,
        reporter,
    )
}

/// `sync_in_dir_with_adapters_strict` plus the v10 fast-path opt-out.
#[allow(clippy::too_many_arguments)]
pub fn sync_in_dir_with_adapters_strict_full(
    cwd: &Path,
    cache_root: &Path,
    locked: bool,
    allow_high_sensitivity: bool,
    force: bool,
    adapters: &[Adapter],
    sync_on_launch: bool,
    force_rebuild: bool,
    codex_profile: Option<String>,
    reporter: &Reporter,
) -> Result<SyncSummary> {
    sync_in_dir_with_adapters_with_failure_mode(
        cwd,
        cache_root,
        locked,
        SyncExecutionOptions::new(
            allow_high_sensitivity,
            force,
            adapters,
            sync_on_launch,
            ExecutionMode::Apply,
            DependencyFailureMode::Strict,
            force_rebuild,
            codex_profile,
        ),
        reporter,
    )
}

fn sync_in_dir_with_adapters_with_failure_mode(
    cwd: &Path,
    cache_root: &Path,
    locked: bool,
    options: SyncExecutionOptions<'_>,
    reporter: &Reporter,
) -> Result<SyncSummary> {
    let install_paths = InstallPaths::project(cwd);
    let codex_profile = options.codex_profile.clone();
    sync_in_dir_with_adapters_mode(
        &install_paths,
        cache_root,
        if locked {
            SyncMode::Locked
        } else {
            SyncMode::Normal
        },
        options.allow_high_sensitivity,
        options.force,
        options.adapters,
        options.sync_on_launch,
        options.execution_mode,
        None,
        options.dependency_failure_mode,
        options.force_rebuild,
        codex_profile,
        reporter,
    )
}

#[allow(dead_code)]
pub fn sync_in_dir_with_adapters_frozen(
    cwd: &Path,
    cache_root: &Path,
    allow_high_sensitivity: bool,
    force: bool,
    adapters: &[Adapter],
    sync_on_launch: bool,
    reporter: &Reporter,
) -> Result<SyncSummary> {
    sync_in_dir_with_adapters_frozen_full(
        cwd,
        cache_root,
        allow_high_sensitivity,
        force,
        adapters,
        sync_on_launch,
        false,
        None,
        reporter,
    )
}

/// `sync_in_dir_with_adapters_frozen` plus the v10 fast-path opt-out.
#[allow(clippy::too_many_arguments)]
pub fn sync_in_dir_with_adapters_frozen_full(
    cwd: &Path,
    cache_root: &Path,
    allow_high_sensitivity: bool,
    force: bool,
    adapters: &[Adapter],
    sync_on_launch: bool,
    force_rebuild: bool,
    codex_profile: Option<String>,
    reporter: &Reporter,
) -> Result<SyncSummary> {
    sync_in_dir_with_adapters_frozen_with_failure_mode(
        cwd,
        cache_root,
        SyncExecutionOptions::new(
            allow_high_sensitivity,
            force,
            adapters,
            sync_on_launch,
            ExecutionMode::Apply,
            DependencyFailureMode::Graceful,
            force_rebuild,
            codex_profile,
        ),
        reporter,
    )
}

#[allow(dead_code)]
pub fn sync_in_dir_with_adapters_frozen_strict(
    cwd: &Path,
    cache_root: &Path,
    allow_high_sensitivity: bool,
    force: bool,
    adapters: &[Adapter],
    sync_on_launch: bool,
    reporter: &Reporter,
) -> Result<SyncSummary> {
    sync_in_dir_with_adapters_frozen_strict_full(
        cwd,
        cache_root,
        allow_high_sensitivity,
        force,
        adapters,
        sync_on_launch,
        false,
        None,
        reporter,
    )
}

/// `sync_in_dir_with_adapters_frozen_strict` plus the v10 fast-path opt-out.
#[allow(clippy::too_many_arguments)]
pub fn sync_in_dir_with_adapters_frozen_strict_full(
    cwd: &Path,
    cache_root: &Path,
    allow_high_sensitivity: bool,
    force: bool,
    adapters: &[Adapter],
    sync_on_launch: bool,
    force_rebuild: bool,
    codex_profile: Option<String>,
    reporter: &Reporter,
) -> Result<SyncSummary> {
    sync_in_dir_with_adapters_frozen_with_failure_mode(
        cwd,
        cache_root,
        SyncExecutionOptions::new(
            allow_high_sensitivity,
            force,
            adapters,
            sync_on_launch,
            ExecutionMode::Apply,
            DependencyFailureMode::Strict,
            force_rebuild,
            codex_profile,
        ),
        reporter,
    )
}

fn sync_in_dir_with_adapters_frozen_with_failure_mode(
    cwd: &Path,
    cache_root: &Path,
    options: SyncExecutionOptions<'_>,
    reporter: &Reporter,
) -> Result<SyncSummary> {
    let install_paths = InstallPaths::project(cwd);
    let codex_profile = options.codex_profile.clone();
    sync_in_dir_with_adapters_mode(
        &install_paths,
        cache_root,
        SyncMode::Frozen,
        options.allow_high_sensitivity,
        options.force,
        options.adapters,
        options.sync_on_launch,
        options.execution_mode,
        None,
        options.dependency_failure_mode,
        options.force_rebuild,
        codex_profile,
        reporter,
    )
}

#[allow(clippy::too_many_arguments, dead_code)]
pub fn sync_in_dir_with_adapters_dry_run(
    cwd: &Path,
    cache_root: &Path,
    locked: bool,
    allow_high_sensitivity: bool,
    force: bool,
    adapters: &[Adapter],
    sync_on_launch: bool,
    reporter: &Reporter,
) -> Result<SyncSummary> {
    sync_in_dir_with_adapters_dry_run_full(
        cwd,
        cache_root,
        locked,
        allow_high_sensitivity,
        force,
        adapters,
        sync_on_launch,
        false,
        None,
        reporter,
    )
}

/// `sync_in_dir_with_adapters_dry_run` plus the v10 fast-path opt-out.
#[allow(clippy::too_many_arguments)]
pub fn sync_in_dir_with_adapters_dry_run_full(
    cwd: &Path,
    cache_root: &Path,
    locked: bool,
    allow_high_sensitivity: bool,
    force: bool,
    adapters: &[Adapter],
    sync_on_launch: bool,
    force_rebuild: bool,
    codex_profile: Option<String>,
    reporter: &Reporter,
) -> Result<SyncSummary> {
    sync_in_dir_with_adapters_with_failure_mode(
        cwd,
        cache_root,
        locked,
        SyncExecutionOptions::new(
            allow_high_sensitivity,
            force,
            adapters,
            sync_on_launch,
            ExecutionMode::DryRun,
            DependencyFailureMode::Graceful,
            force_rebuild,
            codex_profile,
        ),
        reporter,
    )
}

#[allow(clippy::too_many_arguments, dead_code)]
pub fn sync_in_dir_with_adapters_strict_dry_run(
    cwd: &Path,
    cache_root: &Path,
    locked: bool,
    allow_high_sensitivity: bool,
    force: bool,
    adapters: &[Adapter],
    sync_on_launch: bool,
    reporter: &Reporter,
) -> Result<SyncSummary> {
    sync_in_dir_with_adapters_strict_dry_run_full(
        cwd,
        cache_root,
        locked,
        allow_high_sensitivity,
        force,
        adapters,
        sync_on_launch,
        false,
        None,
        reporter,
    )
}

/// `sync_in_dir_with_adapters_strict_dry_run` plus the v10 fast-path opt-out.
#[allow(clippy::too_many_arguments)]
pub fn sync_in_dir_with_adapters_strict_dry_run_full(
    cwd: &Path,
    cache_root: &Path,
    locked: bool,
    allow_high_sensitivity: bool,
    force: bool,
    adapters: &[Adapter],
    sync_on_launch: bool,
    force_rebuild: bool,
    codex_profile: Option<String>,
    reporter: &Reporter,
) -> Result<SyncSummary> {
    sync_in_dir_with_adapters_with_failure_mode(
        cwd,
        cache_root,
        locked,
        SyncExecutionOptions::new(
            allow_high_sensitivity,
            force,
            adapters,
            sync_on_launch,
            ExecutionMode::DryRun,
            DependencyFailureMode::Strict,
            force_rebuild,
            codex_profile,
        ),
        reporter,
    )
}

#[allow(dead_code)]
pub fn sync_in_dir_with_adapters_frozen_dry_run(
    cwd: &Path,
    cache_root: &Path,
    allow_high_sensitivity: bool,
    force: bool,
    adapters: &[Adapter],
    sync_on_launch: bool,
    reporter: &Reporter,
) -> Result<SyncSummary> {
    sync_in_dir_with_adapters_frozen_dry_run_full(
        cwd,
        cache_root,
        allow_high_sensitivity,
        force,
        adapters,
        sync_on_launch,
        false,
        None,
        reporter,
    )
}

/// `sync_in_dir_with_adapters_frozen_dry_run` plus the v10 fast-path opt-out.
#[allow(clippy::too_many_arguments)]
pub fn sync_in_dir_with_adapters_frozen_dry_run_full(
    cwd: &Path,
    cache_root: &Path,
    allow_high_sensitivity: bool,
    force: bool,
    adapters: &[Adapter],
    sync_on_launch: bool,
    force_rebuild: bool,
    codex_profile: Option<String>,
    reporter: &Reporter,
) -> Result<SyncSummary> {
    sync_in_dir_with_adapters_frozen_with_failure_mode(
        cwd,
        cache_root,
        SyncExecutionOptions::new(
            allow_high_sensitivity,
            force,
            adapters,
            sync_on_launch,
            ExecutionMode::DryRun,
            DependencyFailureMode::Graceful,
            force_rebuild,
            codex_profile,
        ),
        reporter,
    )
}

#[allow(dead_code)]
pub fn sync_in_dir_with_adapters_frozen_strict_dry_run(
    cwd: &Path,
    cache_root: &Path,
    allow_high_sensitivity: bool,
    force: bool,
    adapters: &[Adapter],
    sync_on_launch: bool,
    reporter: &Reporter,
) -> Result<SyncSummary> {
    sync_in_dir_with_adapters_frozen_strict_dry_run_full(
        cwd,
        cache_root,
        allow_high_sensitivity,
        force,
        adapters,
        sync_on_launch,
        false,
        None,
        reporter,
    )
}

/// `sync_in_dir_with_adapters_frozen_strict_dry_run` plus the v10 fast-path
/// opt-out.
#[allow(clippy::too_many_arguments)]
pub fn sync_in_dir_with_adapters_frozen_strict_dry_run_full(
    cwd: &Path,
    cache_root: &Path,
    allow_high_sensitivity: bool,
    force: bool,
    adapters: &[Adapter],
    sync_on_launch: bool,
    force_rebuild: bool,
    codex_profile: Option<String>,
    reporter: &Reporter,
) -> Result<SyncSummary> {
    sync_in_dir_with_adapters_frozen_with_failure_mode(
        cwd,
        cache_root,
        SyncExecutionOptions::new(
            allow_high_sensitivity,
            force,
            adapters,
            sync_on_launch,
            ExecutionMode::DryRun,
            DependencyFailureMode::Strict,
            force_rebuild,
            codex_profile,
        ),
        reporter,
    )
}

#[allow(clippy::too_many_arguments)]
fn sync_in_dir_with_adapters_mode(
    install_paths: &InstallPaths,
    cache_root: &Path,
    sync_mode: SyncMode,
    allow_high_sensitivity: bool,
    force: bool,
    adapters: &[Adapter],
    sync_on_launch: bool,
    execution_mode: ExecutionMode,
    root_override: Option<LoadedManifest>,
    dependency_failure_mode: DependencyFailureMode,
    force_rebuild: bool,
    codex_profile_override: Option<String>,
    reporter: &Reporter,
) -> Result<SyncSummary> {
    let mut collision_resolver = TtyManagedCollisionResolver;
    sync_in_dir_with_adapters_mode_and_collision_resolution(
        install_paths,
        cache_root,
        sync_mode,
        allow_high_sensitivity,
        force,
        adapters,
        sync_on_launch,
        execution_mode,
        root_override,
        dependency_failure_mode,
        force_rebuild,
        codex_profile_override,
        if sync_mode.checks_lockfile() || !should_prompt_for_adapter() {
            None
        } else {
            Some(&mut collision_resolver)
        },
        reporter,
    )
}

#[allow(clippy::too_many_arguments)]
fn sync_in_dir_with_adapters_mode_and_collision_resolution(
    install_paths: &InstallPaths,
    cache_root: &Path,
    sync_mode: SyncMode,
    allow_high_sensitivity: bool,
    force: bool,
    adapters: &[Adapter],
    sync_on_launch: bool,
    execution_mode: ExecutionMode,
    root_override: Option<LoadedManifest>,
    dependency_failure_mode: DependencyFailureMode,
    force_rebuild: bool,
    codex_profile_override: Option<String>,
    mut collision_resolver: Option<&mut dyn ManagedCollisionResolver>,
    reporter: &Reporter,
) -> Result<SyncSummary> {
    if matches!(install_paths.scope, InstallScope::Project) {
        crate::relay::ensure_no_pending_relay_edits_in_dir(&install_paths.config_root, cache_root)?;
    }
    let has_root_override = root_override.is_some();
    let original_root = load_root_from_dir_allow_missing(&install_paths.config_root)?;
    let mut root = root_override.unwrap_or_else(|| original_root.clone());
    let mut adopted_owned_paths = HashSet::new();
    let selection = match install_paths.scope {
        InstallScope::Project => resolve_adapter_selection(
            &install_paths.adapter_detection_root,
            &root.manifest,
            adapters,
            !sync_mode.checks_lockfile() && should_prompt_for_adapter(),
        )?,
        InstallScope::Global => {
            if sync_on_launch {
                bail!("`nodus add --global` does not support `--sync-on-launch`");
            }
            resolve_global_adapter_selection(
                &install_paths.adapter_detection_root,
                &root.manifest,
                adapters,
            )?
        }
    };
    if selection.should_persist {
        if sync_mode.checks_lockfile() {
            bail!(
                "adapter selection must be persisted before running {}; rerun without `--locked` or `--frozen`, or set `[adapters] enabled = [...]` in nodus.toml",
                sync_mode.flag(),
            );
        }
        root.manifest.set_enabled_adapters(&selection.adapters);
    }
    if sync_on_launch {
        if sync_mode.checks_lockfile() {
            bail!(
                "launch hook configuration must be persisted before running {}; rerun without `--locked` or `--frozen`, or declare the `nodus.sync_on_startup` hook in [[hooks]]",
                sync_mode.flag(),
            );
        }
        root.manifest.set_sync_on_launch(true);
    }
    let legacy_launch_hook_config = root.manifest.uses_legacy_launch_hook_config();
    if legacy_launch_hook_config && sync_mode.checks_lockfile() {
        bail!(
            "legacy manifest field `launch_hooks.sync_on_startup` must be migrated before running {}; rerun plain `nodus sync` to rewrite `nodus.toml` with [[hooks]]",
            sync_mode.flag(),
        );
    }
    if legacy_launch_hook_config {
        reporter.note(
            "migrating legacy manifest field `launch_hooks.sync_on_startup` to `[[hooks]]`",
        )?;
    }
    if has_root_override || selection.should_persist || sync_on_launch || legacy_launch_hook_config
    {
        root = original_root.with_manifest(root.manifest.clone(), PackageRole::Root)?;
    }

    let lockfile_path = install_paths.config_root.join(LOCKFILE_NAME);
    let existing_lockfile = if lockfile_path.exists() {
        Some(if sync_mode.checks_lockfile() {
            Lockfile::read(&lockfile_path)?
        } else {
            Lockfile::read_for_sync(&lockfile_path)?
        })
    } else {
        None
    };
    if let Some(lockfile) = existing_lockfile.as_ref()
        && !lockfile.uses_current_schema()
    {
        reporter.note(format!(
            "upgrading {LOCKFILE_NAME} from version {} to {}",
            lockfile.version,
            Lockfile::current_version()
        ))?;
    }
    if sync_mode.installs_from_lockfile() && existing_lockfile.is_none() {
        bail!(
            "`--frozen` requires an existing {} in {}",
            LOCKFILE_NAME,
            install_paths.config_root.display()
        );
    }

    // The Codex profile that determines where managed MCP servers are written
    // (manifest `[adapters.codex] profile`, CLI override applied upstream), plus
    // the profile recorded by the previous sync so a change can be cleaned up.
    let codex_profile = resolve_codex_profile(&root.manifest, codex_profile_override.as_deref())?;
    let previous_codex_profile = existing_lockfile
        .as_ref()
        .and_then(|lockfile| lockfile.codex_profile.clone());

    // ---- v10 install_digest drift fast-path ----------------------------
    //
    // Slice 4: when the lockfile is v10, all packages are exactly pinned,
    // each package's `install_digest` is populated, and the on-disk state
    // matches every recorded digest, we can skip the full resolve + render
    // and return a synthetic `SyncSummary` immediately. This is the common
    // case at the start of an editor session ("`nodus sync` on a clean
    // repo") and shaves seconds off the wall time.
    //
    // The fast-path gate is intentionally conservative: any condition we
    // can't cheaply verify (branch-tracking deps, missing digests, root
    // manifest mutation in flight, opt-out flag) falls through to the
    // full sync loop below. `--frozen` is the one mode where a failing
    // gate becomes an error instead of a fallthrough, since the user has
    // explicitly opted into "trust the lockfile".
    let manifest_mutation_pending = has_root_override
        || selection.should_persist
        || sync_on_launch
        || legacy_launch_hook_config;
    let attempt_fast_path = !force_rebuild
        && !manifest_mutation_pending
        // A profile change moves managed servers between the project config and
        // the overlay (an external file outside the install_digest), so the
        // digests alone can't detect it — force a full render in that case.
        && codex_profile.as_deref() == previous_codex_profile.as_deref()
        && existing_lockfile
            .as_ref()
            .is_some_and(Lockfile::uses_current_schema);
    if attempt_fast_path {
        let lockfile = existing_lockfile
            .as_ref()
            .expect("attempt_fast_path implies existing_lockfile is Some");
        let selected_adapters = Adapters::from_slice(&selection.adapters);
        match evaluate_fast_path(
            lockfile,
            &install_paths.runtime_root,
            sync_mode,
            cache_root,
            selected_adapters,
        )? {
            FastPathOutcome::Hit => {
                reporter.note(format!("{LOCKFILE_NAME} is in sync; no work to do"))?;
                let summary = SyncSummary {
                    package_count: lockfile.packages.len(),
                    adapters: selection.adapters.clone(),
                    managed_file_count: count_owned_files(lockfile),
                };
                return Ok(summary);
            }
            FastPathOutcome::Miss(reason) => {
                if sync_mode.installs_from_lockfile() {
                    bail!(
                        "{LOCKFILE_NAME} is out of date for {}: {reason}. Rerun plain `nodus sync` to repair the lockfile and managed outputs.",
                        sync_mode.flag(),
                    );
                }
                // For non-frozen modes the miss reason is debug-level
                // information only — fall through to the full resolve
                // loop which will repair any drift.
            }
        }
    } else if sync_mode.installs_from_lockfile() && force_rebuild {
        // `--frozen` requires the lockfile to be trusted. An explicit
        // `--no-fast-path` (force_rebuild) flag contradicts that intent —
        // bail before doing any work rather than silently honoring one
        // flag and ignoring the other.
        bail!(
            "{} cannot be combined with `--no-fast-path`",
            sync_mode.flag(),
        );
    }

    loop {
        reporter.status(
            "Resolving",
            format!("package graph in {}", install_paths.config_root.display()),
        )?;
        let resolution = resolve_project(
            &install_paths.config_root,
            cache_root,
            ResolveMode::Sync,
            reporter,
            ResolveProjectOptions::new(
                existing_lockfile.as_ref(),
                existing_lockfile
                    .as_ref()
                    .filter(|_| sync_mode.installs_from_lockfile()),
                Some(&root),
                dependency_failure_mode,
            ),
        )?;
        if !resolution.managed_migrations().is_empty() {
            if sync_mode.checks_lockfile() {
                bail!(
                    "legacy dependency `managed` mappings must be migrated before running {}; rerun plain `nodus sync` to let Nodus adopt package-owned `managed_exports`",
                    sync_mode.flag(),
                );
            }
            for migration in resolution.managed_migrations() {
                for target_root in &migration.legacy_target_roots {
                    if !root
                        .manifest
                        .remove_managed_mapping(&migration.alias, target_root)?
                    {
                        bail!(
                            "failed to migrate legacy managed mapping for dependency `{}` targeting {}",
                            migration.alias,
                            target_root.display()
                        );
                    }
                }
                let mut message = format!(
                    "migrating dependency `{}` to package-owned `managed_exports`",
                    migration.alias
                );
                if migration.adds_additional_package_exports {
                    message.push_str(
                        "; package-declared exports include additional managed files beyond the legacy subset",
                    );
                }
                reporter.note(message)?;
            }
            root = root.with_manifest(root.manifest.clone(), PackageRole::Root)?;
            continue;
        }
        reporter.status("Checking", "declared capabilities")?;
        enforce_capabilities(&resolution, allow_high_sensitivity, reporter)?;
        reporter.status(
            "Snapshotting",
            format!("{} packages", resolution.packages.len()),
        )?;
        let stored_packages = snapshot_packages(cache_root, &resolution.packages)?;

        let snapshot_by_digest = stored_packages
            .into_iter()
            .map(|stored| (stored.digest, stored.snapshot_root))
            .collect::<HashMap<_, _>>();
        let package_snapshots = resolution
            .packages
            .iter()
            .map(|package| {
                let snapshot_root = snapshot_by_digest
                    .get(&package.digest)
                    .cloned()
                    .ok_or_else(|| anyhow::anyhow!("missing snapshot for {}", package.digest))?;
                Ok((package.clone(), snapshot_root))
            })
            .collect::<Result<Vec<_>>>()?;
        let selected_adapters = Adapters::from_slice(&selection.adapters);
        let codex_native_plugins_auto_enabled = selected_adapters.contains(Adapter::Codex);
        let output_plan = build_output_plan_with_options(
            &install_paths.runtime_root,
            &package_snapshots,
            selected_adapters,
            existing_lockfile.as_ref(),
            OutputPlanOptions {
                merge_existing_mcp: true,
                codex_native_plugins_auto_enabled,
                codex_user_config: install_paths.codex_user_config.clone(),
                codex_profile: codex_profile.clone(),
                codex_previous_profile: previous_codex_profile.clone(),
            },
        )?;
        let ownership_output_plan = build_output_plan_with_options(
            &install_paths.runtime_root,
            &package_snapshots,
            selected_adapters,
            None,
            OutputPlanOptions {
                merge_existing_mcp: false,
                codex_native_plugins_auto_enabled,
                codex_user_config: install_paths.codex_user_config.clone(),
                codex_profile: codex_profile.clone(),
                ..OutputPlanOptions::default()
            },
        )?;
        let planned_files = output_plan.files.clone();
        let external_files = output_plan.external_files.clone();
        let desired_paths = resolution
            .managed_paths_from_output_plan(&install_paths.runtime_root, &ownership_output_plan)?;
        let mut lockfile = resolution.to_lockfile_from_plans(
            &install_paths.runtime_root,
            &ownership_output_plan,
            &planned_files,
        )?;
        lockfile.codex_profile = codex_profile.clone();
        let mut owned_paths =
            load_owned_paths(&install_paths.runtime_root, existing_lockfile.as_ref())?;
        if existing_lockfile.is_none() {
            owned_paths.exact.extend(recover_runtime_owned_paths(
                &install_paths.runtime_root,
                &desired_paths,
            ));
        }
        owned_paths
            .exact
            .extend(recover_runtime_owned_paths_from_disk(
                &install_paths.runtime_root,
                &desired_paths,
                &planned_files,
            ));
        owned_paths
            .exact
            .extend(adopted_owned_paths.iter().cloned());

        if sync_mode.checks_lockfile() {
            let Some(existing) = existing_lockfile.as_ref() else {
                bail!(
                    "{} requires an existing {} in {}",
                    sync_mode.flag(),
                    LOCKFILE_NAME,
                    install_paths.config_root.display()
                );
            };
            if *existing != lockfile {
                bail!("{}", checked_sync_lockfile_out_of_date_message());
            }
        }

        if let Some(unmanaged_collision) =
            find_unmanaged_collision(&planned_files, &owned_paths, &install_paths.runtime_root)
        {
            if force {
                reporter.note(format!(
                    "forcing overwrite of unmanaged path {}",
                    display_path(&unmanaged_collision.path)
                ))?;
                adopted_owned_paths.insert(unmanaged_collision.path.clone());
                continue;
            }
            let Some(managed_collision) = find_managed_collision(
                &install_paths.runtime_root,
                &resolution,
                &unmanaged_collision,
            )
            .or_else(|| find_runtime_output_collision(&planned_files, &unmanaged_collision)) else {
                bail!(
                    "refusing to overwrite unmanaged file {}",
                    display_path(&unmanaged_collision.path)
                );
            };
            // Branch-tracked dependencies follow a moving ref: the branch
            // advances on every upstream commit, so a changed managed output is
            // the expected state, not a user-vs-package conflict. Adopt it
            // silently (even without a TTY, e.g. the sync-on-launch hook)
            // instead of prompting the user to reconcile every branch update.
            let branch_owned = lockfile.branch_tracked_owned_set(&install_paths.runtime_root)?;
            let choice = if branch_owned.contains(&unmanaged_collision.path) {
                reporter.note(format!(
                    "adopting {} from a branch-tracked dependency without prompting",
                    display_path(&unmanaged_collision.path)
                ))?;
                ManagedCollisionChoice::Adopt
            } else {
                let Some(resolver) = collision_resolver.as_deref_mut() else {
                    bail!(
                        "{}",
                        unmanaged_collision_guidance(
                            &install_paths.runtime_root,
                            &managed_collision,
                            sync_mode,
                        )
                    );
                };
                resolver.resolve(&install_paths.runtime_root, &managed_collision)?
            };
            match choice {
                ManagedCollisionChoice::Adopt => {
                    let adopted_path = match managed_collision.source {
                        ManagedCollisionSource::RuntimeOutput => {
                            reporter.note(format!(
                                "adopting managed runtime output {}",
                                display_path(&managed_collision.collision_path)
                            ))?;
                            managed_collision.collision_path.clone()
                        }
                        _ => {
                            let ownership_root = install_paths
                                .runtime_root
                                .join(&managed_collision.ownership_root);
                            reporter.note(format!(
                                "adopting managed target {}",
                                display_path(&ownership_root)
                            ))?;
                            ownership_root
                        }
                    };
                    adopted_owned_paths.insert(adopted_path);
                    continue;
                }
                ManagedCollisionChoice::RemoveMapping => {
                    if managed_collision.source != ManagedCollisionSource::LegacyDependencyMapping {
                        bail!(
                            "cannot remove package-owned managed export for dependency `{}` from the consumer manifest",
                            managed_collision.alias
                        );
                    }
                    if !root.manifest.remove_managed_mapping(
                        &managed_collision.alias,
                        &managed_collision.ownership_root,
                    )? {
                        bail!(
                            "failed to remove managed mapping for dependency `{}` targeting {}",
                            managed_collision.alias,
                            managed_collision.ownership_root.display()
                        );
                    }
                    reporter.note(format!(
                        "removing managed mapping for dependency `{}` targeting {}",
                        managed_collision.alias,
                        managed_collision.ownership_root.display()
                    ))?;
                    root = root.with_manifest(root.manifest.clone(), PackageRole::Root)?;
                    continue;
                }
                ManagedCollisionChoice::Cancel => {
                    let target = match managed_collision.source {
                        ManagedCollisionSource::RuntimeOutput => {
                            managed_collision.collision_path.clone()
                        }
                        _ => install_paths
                            .runtime_root
                            .join(&managed_collision.ownership_root),
                    };
                    bail!(
                        "cancelled {} because managed target {} collides with existing unmanaged path {}",
                        sync_mode.flag(),
                        display_path(&target),
                        display_path(&managed_collision.collision_path)
                    );
                }
            }
        }

        let plan = build_sync_execution_plan(
            &original_root,
            &root,
            &lockfile_path,
            &lockfile,
            &install_paths.runtime_root,
            &owned_paths,
            &desired_paths,
            &planned_files,
            external_files,
            resolution
                .warnings
                .iter()
                .chain(output_plan.warnings.iter())
                .cloned()
                .collect(),
            SyncSummary {
                package_count: resolution.packages.len(),
                adapters: selection.adapters,
                managed_file_count: planned_files.len(),
            },
            sync_mode,
        )?;
        execute_sync_plan(&plan, execution_mode, reporter)?;

        return Ok(plan.summary);
    }
}

#[allow(clippy::too_many_arguments)]
pub(crate) fn sync_in_dir_with_loaded_root(
    cwd: &Path,
    cache_root: &Path,
    locked: bool,
    allow_high_sensitivity: bool,
    force: bool,
    adapters: &[Adapter],
    sync_on_launch: bool,
    execution_mode: ExecutionMode,
    root: LoadedManifest,
    reporter: &Reporter,
) -> Result<SyncSummary> {
    let install_paths = InstallPaths::project(cwd);
    sync_with_loaded_root_at_paths(
        &install_paths,
        cache_root,
        locked,
        allow_high_sensitivity,
        force,
        adapters,
        sync_on_launch,
        execution_mode,
        root,
        reporter,
    )
}

#[allow(clippy::too_many_arguments)]
pub(crate) fn sync_with_loaded_root_at_paths(
    install_paths: &InstallPaths,
    cache_root: &Path,
    locked: bool,
    allow_high_sensitivity: bool,
    force: bool,
    adapters: &[Adapter],
    sync_on_launch: bool,
    execution_mode: ExecutionMode,
    root: LoadedManifest,
    reporter: &Reporter,
) -> Result<SyncSummary> {
    sync_in_dir_with_adapters_mode(
        install_paths,
        cache_root,
        if locked {
            SyncMode::Locked
        } else {
            SyncMode::Normal
        },
        allow_high_sensitivity,
        force,
        adapters,
        sync_on_launch,
        execution_mode,
        Some(root),
        DependencyFailureMode::Graceful,
        false,
        None,
        reporter,
    )
}

#[allow(clippy::too_many_arguments)]
#[cfg(test)]
pub fn resolve_project_for_sync(
    root: &Path,
    cache_root: &Path,
    reporter: &Reporter,
) -> Result<Resolution> {
    resolve_project(
        root,
        cache_root,
        ResolveMode::Sync,
        reporter,
        ResolveProjectOptions::new(None, None, None, DependencyFailureMode::Graceful),
    )
}

pub fn resolve_project_from_existing_lockfile_in_dir(
    cwd: &Path,
    cache_root: &Path,
    _selected_adapters: Adapters,
    reporter: &Reporter,
) -> Result<(Resolution, Lockfile)> {
    let lockfile_path = cwd.join(LOCKFILE_NAME);
    if !lockfile_path.exists() {
        bail!("missing {}", LOCKFILE_NAME);
    }

    let lockfile = Lockfile::read(&lockfile_path)?;
    let resolution = resolve_project(
        cwd,
        cache_root,
        ResolveMode::Doctor,
        reporter,
        ResolveProjectOptions::new(
            Some(&lockfile),
            Some(&lockfile),
            None,
            DependencyFailureMode::Strict,
        ),
    )?;

    Ok((resolution, lockfile))
}

impl Resolution {
    fn managed_migrations(&self) -> &[ManagedMappingMigration] {
        &self.managed_migrations
    }

    #[cfg_attr(not(test), allow(dead_code))]
    pub fn to_lockfile(
        &self,
        selected_adapters: Adapters,
        runtime_root: &Path,
    ) -> Result<Lockfile> {
        self.to_lockfile_with_options(selected_adapters, runtime_root, false)
    }

    pub fn to_lockfile_with_options(
        &self,
        selected_adapters: Adapters,
        runtime_root: &Path,
        codex_native_plugins_auto_enabled: bool,
    ) -> Result<Lockfile> {
        // Build the output plan ONCE. We feed it twice: once to attribute
        // per-package ownership (subtrees/prefixes/files), and once more (via
        // `output_plan.files`) to compute each package's `install_digest`.
        let package_roots = self
            .packages
            .iter()
            .map(|package| (package.clone(), package.root.clone()))
            .collect::<Vec<_>>();
        let output_plan = build_output_plan_with_options(
            runtime_root,
            &package_roots,
            selected_adapters,
            None,
            OutputPlanOptions {
                merge_existing_mcp: false,
                codex_native_plugins_auto_enabled,
                codex_user_config: None,
                ..OutputPlanOptions::default()
            },
        )?;

        self.to_lockfile_from_output_plan(runtime_root, &output_plan)
    }

    fn to_lockfile_from_output_plan(
        &self,
        runtime_root: &Path,
        output_plan: &OutputPlan,
    ) -> Result<Lockfile> {
        // Single-plan callers attribute ownership from, and hash the digest
        // over, the same plan.
        self.to_lockfile_from_plans(runtime_root, output_plan, &output_plan.files)
    }

    /// Build the lockfile attributing per-package ownership from `ownership_plan`
    /// while computing each `install_digest` over `digest_files`.
    ///
    /// `sync` and `doctor` build two plans: ownership is derived from the
    /// canonical, merge-free plan (so the owned-path set is stable regardless of
    /// the consumer's pre-existing config), but the digest must cover the merged
    /// bytes actually written to disk — the same content
    /// `install_digest_from_disk` reads back. Hashing the merge-free plan
    /// instead made `nodus sync --frozen` report perpetual drift on every
    /// merge-target config file.
    fn to_lockfile_from_plans(
        &self,
        runtime_root: &Path,
        ownership_plan: &OutputPlan,
        digest_files: &[ManagedFile],
    ) -> Result<Lockfile> {
        // BTreeMap (not HashMap) so attribute_file_to_package iterates aliases
        // in deterministic alphabetical order. With a HashMap, two packages
        // with overlapping ownership claims would attribute differently across
        // runs and silently shift install_digest contents, breaking the
        // byte-identical-idempotent guarantee.
        let mut per_package_owned: BTreeMap<String, PackageOwnedPaths> = ownership_plan
            .managed_files_by_package
            .iter()
            .cloned()
            .map(|owned| (owned.alias.clone(), owned))
            .collect();

        let per_package_install_digests =
            install_digests_by_package(runtime_root, digest_files, &per_package_owned)?;

        let mut packages = Vec::new();

        for package in &self.packages {
            let source = match &package.source {
                PackageSource::Root => LockedSource {
                    kind: "path".into(),
                    path: Some(".".into()),
                    url: None,
                    tag: None,
                    branch: None,
                    rev: None,
                },
                PackageSource::Path { path, tag } => LockedSource {
                    kind: "path".into(),
                    path: Some(display_path(path)),
                    url: None,
                    tag: tag.clone(),
                    branch: None,
                    rev: None,
                },
                PackageSource::Git {
                    url,
                    subpath,
                    tag,
                    branch,
                    rev,
                } => LockedSource {
                    kind: "git".into(),
                    path: subpath.as_ref().map(|path| display_path(path)),
                    url: Some(url.clone()),
                    tag: tag.clone(),
                    branch: branch.clone(),
                    rev: Some(rev.clone()),
                },
            };

            let package_role = match package.source {
                PackageSource::Root => PackageRole::Root,
                _ => PackageRole::Dependency,
            };
            let mut dependencies = package_dependency_aliases(package, package_role)?;
            dependencies.sort();

            let owned = per_package_owned.remove(&package.alias).unwrap_or_default();
            let install_digest = per_package_install_digests
                .get(&package.alias)
                .cloned()
                .or_else(|| Some(content_digest(&[])));

            packages.push(LockedPackage {
                alias: package.alias.clone(),
                name: package
                    .manifest
                    .effective_name_for_role(package_role == PackageRole::Root),
                version_tag: match &package.source {
                    PackageSource::Git { tag, .. } => package
                        .manifest
                        .effective_version()
                        .map(|v| v.to_string())
                        .or_else(|| tag.clone()),
                    PackageSource::Path { tag, .. } => package
                        .manifest
                        .effective_version()
                        .map(|v| v.to_string())
                        .or_else(|| tag.clone()),
                    PackageSource::Root => {
                        package.manifest.effective_version().map(|v| v.to_string())
                    }
                },
                source,
                digest: package.digest.clone(),
                selected_components: package.selected_components.clone(),
                skills: emitted_artifact_ids(
                    package,
                    DependencyComponent::Skills,
                    package
                        .manifest
                        .discovered
                        .skills
                        .iter()
                        .map(|item| &item.id),
                ),
                agents: emitted_artifact_ids(
                    package,
                    DependencyComponent::Agents,
                    package.manifest.discovered.unique_agent_ids().into_iter(),
                ),
                rules: emitted_artifact_ids(
                    package,
                    DependencyComponent::Rules,
                    package
                        .manifest
                        .discovered
                        .rules
                        .iter()
                        .map(|item| &item.id),
                ),
                commands: emitted_artifact_ids(
                    package,
                    DependencyComponent::Commands,
                    package
                        .manifest
                        .discovered
                        .commands
                        .iter()
                        .map(|item| &item.id),
                ),
                mcp_servers: emitted_artifact_ids(
                    package,
                    DependencyComponent::Mcp,
                    package.manifest.manifest.mcp_servers.keys(),
                ),
                dependencies,
                capabilities: package.manifest.manifest.capabilities.clone(),
                owned_subtrees: owned.subtrees,
                owned_prefixes: owned.prefixes,
                owned_runtime_adapters: Vec::new(),
                owned_files: owned.files,
                install_digest,
            });
        }

        compact_owned_runtime_adapter_ownership(&mut packages);

        Ok(Lockfile::new(packages))
    }

    #[allow(dead_code)]
    pub fn managed_paths(
        &self,
        runtime_root: &Path,
        selected_adapters: Adapters,
    ) -> Result<HashSet<PathBuf>> {
        self.managed_paths_with_options(runtime_root, selected_adapters, false)
    }

    pub fn managed_paths_with_options(
        &self,
        runtime_root: &Path,
        selected_adapters: Adapters,
        codex_native_plugins_auto_enabled: bool,
    ) -> Result<HashSet<PathBuf>> {
        let package_roots = self
            .packages
            .iter()
            .map(|package| (package.clone(), package.root.clone()))
            .collect::<Vec<_>>();
        let output_plan = build_output_plan_with_options(
            runtime_root,
            &package_roots,
            selected_adapters,
            None,
            OutputPlanOptions {
                merge_existing_mcp: false,
                codex_native_plugins_auto_enabled,
                codex_user_config: None,
                ..OutputPlanOptions::default()
            },
        )?;
        self.managed_paths_from_output_plan(runtime_root, &output_plan)
    }

    fn managed_paths_from_output_plan(
        &self,
        runtime_root: &Path,
        output_plan: &OutputPlan,
    ) -> Result<HashSet<PathBuf>> {
        // v10 lockfiles no longer populate `legacy_managed_files`, so
        // `Lockfile::managed_paths` returns an empty set on v10 input. Derive
        // the owned root paths directly from the per-package ownership view:
        // subtree roots, exact files, prefix dirs. Doctor and sync consume
        // this list to decide which on-disk paths they may inspect / write /
        // adopt.
        let lockfile = self.to_lockfile_from_output_plan(runtime_root, output_plan)?;
        let owned = lockfile.owned_set(runtime_root)?;
        let mut paths: HashSet<PathBuf> = owned.exact;
        paths.extend(owned.subtrees.iter().cloned());
        paths.extend(owned.prefixes.iter().map(|rule| rule.dir.clone()));

        // For each subtree we own, surface the immediate sub-directories
        // that hold one-artifact-per-subdir (skill folders inside a native
        // plugin: `.nodus/packages/<alias>/<runtime>-plugin/skills/`, agent
        // folders in similar positions). The pre-Slice-3 behavior compressed
        // these subdirs into `desired_paths` via `derivable_runtime_artifact_entries`
        // so `recover_runtime_owned_paths_from_disk` could match an
        // exactly-equivalent pre-written directory tree without needing the
        // whole plugin folder to already exist. We mirror that here by
        // recording any direct child of a subtree that the output plan plans
        // to populate, so the on-disk adoption logic keeps working through
        // the schema bump.
        for owned_subtree in &owned.subtrees {
            for file in &output_plan.files {
                let Some(rest) = file.path.strip_prefix(owned_subtree).ok() else {
                    continue;
                };
                // Capture only the IMMEDIATE child directory (e.g. `skills`,
                // `agents`, `commands`, `.codex-plugin` inside a plugin
                // folder). Deeper paths are still owned via the subtree.
                if let Some(first) = rest.components().next() {
                    let child = owned_subtree.join(first.as_os_str());
                    if child != file.path {
                        paths.insert(child);
                    }
                }
            }
        }
        Ok(paths)
    }
}

/// Outcome of evaluating the v10 install_digest drift fast-path.
///
/// `Hit` means the lockfile and disk agree exactly — the caller can return a
/// synthetic `SyncSummary` without doing any further work. `Miss(reason)`
/// surfaces a human-readable explanation of which gate condition failed; the
/// caller logs it under `--frozen` (where missing the fast-path is fatal) and
/// silently falls through under normal sync.
enum FastPathOutcome {
    Hit,
    Miss(String),
}

/// Decide whether the v10 install_digest drift fast-path can short-circuit a
/// sync.
///
/// The lockfile is already known to be v10 and the caller has already filtered
/// out modes that mutate the consumer manifest. This function checks the
/// per-package preconditions:
///
/// - **Freshness gate** (skipped under `--frozen`): every git source is
///   pinned to a `rev` and not tracking a `branch`. Branch-tracked deps can
///   have moved upstream, so the fast-path can't safely skip a re-resolve.
///   `--frozen` opts out of upstream-freshness checking by definition (it
///   uses the recorded `rev` verbatim), so this gate is bypassed there.
/// - **Integrity gate**: every package carries an `install_digest` and the
///   recomputed digest from disk matches it.
///
/// Any failure short-circuits with a descriptive `Miss`. The cost of the
/// disk-walk is bounded by the union of `owned_*` paths the lockfile names,
/// which is exactly the set the full resolve would re-render anyway.
fn evaluate_fast_path(
    lockfile: &Lockfile,
    project_root: &Path,
    sync_mode: SyncMode,
    cache_root: &Path,
    selected_adapters: Adapters,
) -> Result<FastPathOutcome> {
    let bypass_freshness_gate = sync_mode.installs_from_lockfile();
    let lockfile_mtime = if bypass_freshness_gate {
        None
    } else {
        std::fs::metadata(project_root.join(LOCKFILE_NAME))
            .and_then(|metadata| metadata.modified())
            .ok()
    };
    if !bypass_freshness_gate
        && selected_adapters_have_global_payloads(selected_adapters)
        && lockfile.packages.iter().any(locked_package_is_dependency)
    {
        return Ok(FastPathOutcome::Miss(
            "selected adapters use global package payloads outside the lockfile digest".into(),
        ));
    }
    for package in &lockfile.packages {
        if !bypass_freshness_gate {
            // Source-pin freshness gate. Float-y deps (branch tracking) can
            // change upstream between syncs; the disk content might match the
            // lockfile but the lockfile itself could be stale. Always
            // re-resolve those in non-frozen modes. Path deps are similarly
            // open-ended (the user can edit local files at any time), so we
            // check that nothing under the path source root is newer than
            // the lockfile as a cheap freshness proxy.
            match package.source.kind.as_str() {
                "path" => {
                    if let Some(lockfile_mtime) = lockfile_mtime {
                        let source_root = package
                            .source
                            .path
                            .as_deref()
                            .map(|raw| project_root.join(raw))
                            .unwrap_or_else(|| project_root.to_path_buf());
                        if path_dep_source_is_newer(&source_root, lockfile_mtime, project_root) {
                            return Ok(FastPathOutcome::Miss(format!(
                                "package `{}` has on-disk source newer than the lockfile",
                                package.alias
                            )));
                        }
                    } else {
                        return Ok(FastPathOutcome::Miss(format!(
                            "package `{}` is a path dependency but the lockfile mtime could not be read",
                            package.alias
                        )));
                    }
                }
                "git" => {
                    if package.source.rev.is_none() {
                        return Ok(FastPathOutcome::Miss(format!(
                            "package `{}` has no pinned git revision",
                            package.alias
                        )));
                    }
                    if package.source.branch.is_some() {
                        return Ok(FastPathOutcome::Miss(format!(
                            "package `{}` tracks branch `{}`; upstream may have moved",
                            package.alias,
                            package.source.branch.as_deref().unwrap_or(""),
                        )));
                    }
                }
                other => {
                    return Ok(FastPathOutcome::Miss(format!(
                        "package `{}` has unrecognized source kind `{}`",
                        package.alias, other
                    )));
                }
            }
        }

        // install_digest gate. Slice 3 always stamps a digest on v10
        // emissions (defaulting to `content_digest(&[])` for empty packages),
        // so `None` here means the lockfile was hand-edited or upgraded from
        // a pre-Slice-3 schema by a different tool.
        let Some(recorded) = package.install_digest.as_deref() else {
            return Ok(FastPathOutcome::Miss(format!(
                "package `{}` has no recorded install_digest",
                package.alias
            )));
        };

        // Disk-digest gate. `Ok(None)` means an `owned_files` entry is
        // missing on disk — drift, fall back to full sync.
        let Some(disk_digest) = install_digest_from_disk(project_root, lockfile, package)? else {
            return Ok(FastPathOutcome::Miss(format!(
                "package `{}` has an owned file missing on disk",
                package.alias
            )));
        };

        if disk_digest != recorded {
            return Ok(FastPathOutcome::Miss(format!(
                "package `{}` install_digest mismatch (disk drift)",
                package.alias
            )));
        }

        // Cache-presence gate. `nodus clean` plus a stale lockfile leaves
        // disk consistent but the shared cache empty; downstream commands
        // (`doctor`, `update`) need the cache present. Fall through so the
        // full resolve repopulates it.
        let snapshot_path = crate::store::snapshot_path(cache_root, &package.digest)?;
        if !snapshot_path.exists() {
            return Ok(FastPathOutcome::Miss(format!(
                "package `{}` snapshot is missing from the shared cache",
                package.alias
            )));
        }
    }

    Ok(FastPathOutcome::Hit)
}

fn selected_adapters_have_global_payloads(selected_adapters: Adapters) -> bool {
    selected_adapters.contains(Adapter::Claude)
        || selected_adapters.contains(Adapter::Codex)
        || selected_adapters.contains(Adapter::OpenCode)
}

fn locked_package_is_dependency(package: &LockedPackage) -> bool {
    package.source.kind != "path" || package.source.path.as_deref() != Some(".")
}

/// Cheap freshness probe for path-dep sources.
///
/// Walks the source root and returns `true` if any non-runtime file's mtime
/// is strictly newer than `lockfile_mtime`. We skip everything under
/// `project_root/.nodus`, `.claude`, `.codex`, etc. — those are the runtime
/// outputs Nodus writes during sync, which would always be at least as new
/// as the lockfile and would trip every fast-path check otherwise.
///
/// mtime-based detection is a heuristic, not a proof. False positives (mtime
/// bumped by an unrelated tool like a git checkout) cause an unneeded full
/// sync, which is correct-but-slow. False negatives (someone restored a
/// snapshot to an older mtime) cause a missed sync, which the user can
/// recover from via `nodus sync --no-fast-path`. The trade is acceptable
/// because the alternative — recomputing every path dep's source digest —
/// duplicates the bulk of a full resolve and erases the fast-path benefit.
fn path_dep_source_is_newer(
    source_root: &Path,
    lockfile_mtime: std::time::SystemTime,
    project_root: &Path,
) -> bool {
    use walkdir::WalkDir;

    // Names at the top of `project_root` we know Nodus writes during sync.
    // When the path-dep source root equals the project root (the common
    // "consumer = root package" case) we have to filter these out or the
    // freshness probe always trips on Nodus's own outputs.
    let nodus_owned_top_level = [
        ".nodus",
        ".claude",
        ".claude-plugin",
        ".codex",
        ".cursor",
        ".github",
        ".opencode",
        ".agents",
        "nodus.lock",
    ];
    let canonical_project_root = std::fs::canonicalize(project_root).ok();
    for entry in WalkDir::new(source_root).follow_links(false) {
        let Ok(entry) = entry else {
            // Walk errors don't disqualify the fast-path on their own —
            // the integrity gate's disk reads will surface real errors.
            continue;
        };
        let path = entry.path();
        // Skip Nodus-managed top-level dirs at the project root.
        if let Some(canonical_project_root) = canonical_project_root.as_ref()
            && let Ok(rel) = path.strip_prefix(canonical_project_root)
            && let Some(first) = rel.components().next()
            && let Some(first_str) = first.as_os_str().to_str()
            && nodus_owned_top_level.contains(&first_str)
        {
            continue;
        }
        if let Ok(rel) = path.strip_prefix(project_root)
            && let Some(first) = rel.components().next()
            && let Some(first_str) = first.as_os_str().to_str()
            && nodus_owned_top_level.contains(&first_str)
        {
            continue;
        }
        let Ok(metadata) = entry.metadata() else {
            continue;
        };
        if !metadata.is_file() {
            continue;
        }
        let Ok(modified) = metadata.modified() else {
            continue;
        };
        if modified > lockfile_mtime {
            return true;
        }
    }
    false
}

/// Approximate the `managed_file_count` summary field on a fast-path hit.
///
/// The pre-fast-path code derived this from the rendered `planned_files`
/// vector. On the fast-path we never render — we use the lockfile's
/// per-package `owned_*` rules instead. Counting subtrees / prefix rules / exact
/// files gives the user a sensible number for the "managed files" summary
/// line without forcing a disk walk just to count.
fn count_owned_files(lockfile: &Lockfile) -> usize {
    let names =
        crate::adapters::ManagedArtifactNames::from_locked_packages(lockfile.packages.iter());
    lockfile
        .packages
        .iter()
        .map(|package| {
            let runtime_owned_count = package
                .owned_runtime_adapters
                .iter()
                .map(|adapter| {
                    let paths = locked_runtime_adapter_owned_paths(&names, package, *adapter);
                    paths.files.len() + paths.subtrees.len()
                })
                .sum::<usize>();
            package.owned_files.len()
                + package.owned_subtrees.len()
                + package.owned_prefixes.len()
                + runtime_owned_count
        })
        .sum()
}

/// Compute per-package `install_digest` (`blake3:<hex>`) from the output plan.
///
/// Each emitted file is attributed to the owning package by consulting
/// `per_package_owned` (the same per-package ownership rules we emit into the
/// lockfile). Files are sorted by `target_relative_path` before hashing so the
/// digest is stable across equivalent resolutions. The digest covers
/// `(target_relative_path, contents)` for every attributed file.
///
/// Packages with no attributed files don't appear in the returned map; the
/// caller stamps `content_digest(&[])` on them so v10 lockfiles always carry a
/// digest (Slice 4's drift fast-path needs a stable empty-install baseline).
///
/// `files` are the bytes actually written to disk. Sync and doctor pass the
/// merged output plan here (not the merge-free ownership plan) so the digest
/// covers the same content `install_digest_from_disk` reads back; otherwise
/// merge-target config files (`.mcp.json`, `.codex/config.toml`,
/// `.claude/settings.json`, `opencode.json`) would always report drift under
/// `nodus sync --frozen`.
fn install_digests_by_package(
    runtime_root: &Path,
    files: &[ManagedFile],
    per_package_owned: &BTreeMap<String, PackageOwnedPaths>,
) -> Result<HashMap<String, String>> {
    let mut per_package_entries: BTreeMap<String, BTreeMap<PathBuf, Vec<u8>>> = BTreeMap::new();

    for file in files {
        let target_relative = file
            .path
            .strip_prefix(runtime_root)
            .unwrap_or(&file.path)
            .to_path_buf();
        let Some(alias) = attribute_file_to_package(&target_relative, per_package_owned) else {
            // Unattributed files exist in the on-disk plan but aren't part of
            // any package's ownership view. They don't contribute to a
            // per-package install_digest.
            continue;
        };
        per_package_entries
            .entry(alias)
            .or_default()
            .insert(target_relative, file.contents.clone());
    }

    let mut digests = HashMap::with_capacity(per_package_entries.len());
    for (alias, entries) in per_package_entries {
        let entries_for_digest: Vec<(String, Vec<u8>)> = entries
            .into_iter()
            .map(|(path, contents)| (display_path(&path), contents))
            .collect();
        let digest_input: Vec<(&str, &[u8])> = entries_for_digest
            .iter()
            .map(|(path, contents)| (path.as_str(), contents.as_slice()))
            .collect();
        digests.insert(alias, content_digest(&digest_input));
    }
    Ok(digests)
}

/// Return the package alias that owns `target_relative` according to the
/// per-package categorization we've already built. Mirrors
/// `OwnedSet::contains` (subtree starts_with, exact path match, prefix dir +
/// stem prefix) but returns the alias instead of a boolean so the install
/// digest computation can bucket files per package.
fn attribute_file_to_package(
    target_relative: &Path,
    per_package_owned: &BTreeMap<String, PackageOwnedPaths>,
) -> Option<String> {
    // Subtree match wins: a file living under a package's owned subtree is
    // attributed to that package regardless of whether another package also
    // declares an exact file match (the latter would be redundant).
    //
    // BTreeMap iteration is alphabetically deterministic — overlapping claims
    // resolve in a stable order so install_digest distribution stays
    // byte-identical across runs.
    for (alias, owned) in per_package_owned {
        if owned
            .subtrees
            .iter()
            .any(|subtree| target_relative.starts_with(Path::new(subtree)))
        {
            return Some(alias.clone());
        }
    }
    for (alias, owned) in per_package_owned {
        if owned.files.iter().any(|file| {
            let owned = Path::new(file);
            target_relative == owned || target_relative.starts_with(owned)
        }) {
            return Some(alias.clone());
        }
    }
    for (alias, owned) in per_package_owned {
        if owned.prefixes.iter().any(|rule| {
            target_relative.parent() == Some(Path::new(&rule.dir))
                && target_relative
                    .file_name()
                    .and_then(|name| name.to_str())
                    .is_some_and(|name| name.starts_with(&rule.prefix))
        }) {
            return Some(alias.clone());
        }
    }
    None
}

fn package_dependency_aliases(
    package: &ResolvedPackage,
    package_role: PackageRole,
) -> Result<Vec<String>> {
    let mut dependencies: Vec<_> = package
        .manifest
        .manifest
        .active_dependency_entries_for_role(package_role)
        .into_iter()
        .map(|entry| entry.alias.to_string())
        .collect();

    if package_role == PackageRole::Dependency
        && package.manifest.manifest.workspace.is_none()
        && package.manifest.discovered.is_empty()
    {
        let selected = package
            .selected_workspace_members
            .clone()
            .unwrap_or_default()
            .into_iter()
            .collect::<HashSet<_>>();
        dependencies.retain(|alias| selected.contains(alias));
    }

    let workspace_members = package.manifest.resolved_workspace_members()?;
    if !workspace_members.is_empty() {
        let selected = match &package.selected_workspace_members {
            Some(selected) => selected.iter().cloned().collect::<HashSet<_>>(),
            None if package_role == PackageRole::Root => workspace_members
                .iter()
                .map(|member| member.id.clone())
                .collect::<HashSet<_>>(),
            None => HashSet::new(),
        };
        dependencies.extend(
            workspace_members
                .into_iter()
                .filter(|member| selected.contains(&member.id))
                .map(|member| member.alias),
        );
    }

    dependencies.sort();
    dependencies.dedup();
    Ok(dependencies)
}

fn sorted_ids<'a>(ids: impl Iterator<Item = &'a String>) -> Vec<String> {
    let mut ids: Vec<_> = ids.cloned().collect();
    ids.sort();
    ids
}

fn emitted_artifact_ids<'a>(
    package: &ResolvedPackage,
    component: DependencyComponent,
    ids: impl Iterator<Item = &'a String>,
) -> Vec<String> {
    if package.emits_runtime_outputs() && package.selects_component(component) {
        sorted_ids(ids)
    } else {
        Vec::new()
    }
}

impl ResolvedPackage {
    pub fn emits_runtime_outputs(&self) -> bool {
        !matches!(self.source, PackageSource::Root) || self.manifest.manifest.publish_root
    }

    pub fn selects_component(&self, component: DependencyComponent) -> bool {
        self.selected_components
            .as_ref()
            .is_none_or(|components| components.contains(&component))
    }

    pub fn package_files(&self) -> Result<Vec<PathBuf>> {
        let mut files = self.manifest.package_files()?;
        files.extend(self.extra_package_files.iter().cloned());
        files.sort();
        files.dedup();
        Ok(files)
    }

    pub fn managed_paths(&self) -> &[ResolvedManagedPath] {
        &self.managed_paths
    }
}

impl SnapshotSource for ResolvedPackage {
    fn digest(&self) -> &str {
        &self.digest
    }

    fn package_root(&self) -> &Path {
        &self.manifest.root
    }

    fn package_files(&self) -> Result<Vec<PathBuf>> {
        ResolvedPackage::package_files(self)
    }

    fn read_package_file(&self, path: &Path) -> Result<Vec<u8>> {
        self.manifest.read_package_file(path)
    }
}

#[cfg(test)]
mod tests;