node-app-build 6.18.1

Mini app developer CLI: scaffold, validate, package node-app-* Debian packages
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
//! Platform-repo mode for `node-app dev`.
//!
//! When invoked from the node monorepo (detected by the presence of
//! `infra/debian/platform-depends`), boot the platform server here AND
//! auto-resolve every node-app the platform depends on, building & staging
//! each one before the daemon starts.
//!
//! The list of platform-side app deps is parsed from
//! `infra/debian/platform-depends`: any non-blank, non-comment line beginning
//! with `node-app-` becomes an app name (prefix stripped).
//!
//! Unlike the app-developer flow, this mode does NOT sideload via IPC and
//! does NOT watch source files — the platform's own inotify watcher picks up
//! pre-staged apps on boot, and contributor edits to the platform crates are
//! handled via their own cargo workflow.

use std::io::BufRead;
use std::path::{Path, PathBuf};
use std::sync::atomic::Ordering;
use std::time::{Duration, Instant};

use anyhow::{Context, Result};
use serde::Deserialize;

use super::host::{self, InstanceProfile};
use super::sources_resolver;
use super::{build_and_stage, ipc_call, load_manifest, DevArgs, Manifest, SHUTDOWN_REQUESTED};
use crate::tui::{self, BuildScope, DevSignals, LogSource, LogTx, ServiceStatus};

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PlatformDependency {
    pub key: String,
    pub package: String,
}

/// Entry point for platform-repo dev mode.
///
/// Returns once Ctrl-C / TUI quit is observed and the daemon has been asked
/// to shut down.
pub fn run(platform_root: &Path, args: &DevArgs<'_>) -> Result<()> {
    // ── Parse platform-depends FIRST so the TUI can seed its sidebar ──────────
    // (TUI runs in another thread; we have to know the app list before
    // constructing AppState. Errors here print to stderr — no TUI active yet.)
    let depends_path = platform_root.join("infra/debian/platform-depends");
    let dependencies = platform_dependencies(platform_root)
        .with_context(|| format!("parse {}", depends_path.display()))?;
    let dependency_keys: Vec<String> = dependencies.iter().map(|dep| dep.key.clone()).collect();

    // Install the OS signal handler up front so Ctrl+C interrupts in-flight
    // dep builds even before the TUI thread is running (no-TUI mode, or
    // before pre-boot staging completes in TUI mode).
    install_signal_handler();

    // ── TUI setup (mirrors app-mode in dev::run) ──────────────────────────────
    let use_tui = !args.no_tui && !args.once && tui::is_tty();
    let (log_tx_opt, signals_opt, tui_handle) = if use_tui {
        let (tx, rx, signals) = tui::setup();
        // Mirror dev::run line 147: register the TUI's quit flag globally so
        // build polling loops (`run_in_with_sink`, `run_build_cmd`) can
        // observe `q` / Ctrl+C-as-key and kill the cargo child. Without this
        // the TUI swallows Ctrl+C in raw mode and builds run to completion.
        let _ = super::QUIT_FLAG.set(signals.quit_requested.clone());
        // Repurpose `instance_names` as the dep-app list: MonorepoHost::tail_logs
        // tags each line with `[<app>] ` and AppState::push_log routes those
        // into per-app buffers. Mouse-click on an app in the sidebar sets
        // `instance_filter` so the App pane shows just that app's logs.
        let mut app_state = tui::state::AppState::new(
            "node-platform".to_string(),
            String::new(),
            dependency_keys.clone(),
        );
        app_state.seed_app_list(&dependency_keys);
        // Resolve node names up-front (same logic as the profile-resolution
        // block below) so the TUI's nodes sidebar can show every instance
        // immediately, even before the daemons have booted.
        let node_names: Vec<String> = if args.instances.is_empty() {
            vec!["alice".to_string()]
        } else {
            args.instances.clone()
        };
        // Single-instance runs don't need the nodes sidebar — it's just
        // visual noise. Skip seeding so the box stays hidden in that case.
        if node_names.len() > 1 {
            app_state.seed_node_list(&node_names);
        }
        let signals_clone = signals.clone();
        let handle = std::thread::spawn(move || {
            if let Err(e) = tui::run(rx, app_state, signals_clone) {
                eprintln!("TUI error: {e}");
            }
        });
        (Some(tx), Some(signals), Some(handle))
    } else {
        (None, None, None)
    };

    // Guard to flush TUI cleanly on every exit path.
    struct TuiGuard {
        signals: Option<DevSignals>,
        handle: Option<std::thread::JoinHandle<()>>,
    }
    impl Drop for TuiGuard {
        fn drop(&mut self) {
            if let Some(sigs) = &self.signals {
                sigs.mark_shutdown_complete();
            }
            if let Some(h) = self.handle.take() {
                let _ = h.join();
            }
        }
    }
    let _tui_guard = TuiGuard {
        signals: signals_opt.clone(),
        handle: tui_handle,
    };

    tui::sys_log(
        log_tx_opt.as_ref(),
        format!(
            "→ platform mode (cwd = {})  reading infra/debian/platform-depends…",
            platform_root.display()
        ),
    );
    if dependencies.is_empty() {
        tui::sys_log(
            log_tx_opt.as_ref(),
            "→ no node-app-* entries in platform-depends; will boot server with no extra apps.",
        );
    } else {
        tui::sys_log(
            log_tx_opt.as_ref(),
            format!(
                "{} node-app dep(s) declared: {}",
                dependencies.len(),
                dependency_keys.join(", ")
            ),
        );
    }

    // ── Resolve sources (sibling → cache → clone) ─────────────────────────────
    let mut resolved = sources_resolver::resolve(
        platform_root,
        &dependencies,
        &args.dep_paths,
        log_tx_opt.as_ref(),
    )?;

    // Merge explicit --dep flags, including overrides and extra apps, into
    // the same typed representation before validating or building anything.
    for path in &args.dep_paths {
        let manifest = load_manifest(path)
            .with_context(|| format!("load dependency manifest from {}", path.display()))?;
        let key = dependencies
            .iter()
            .find(|dependency| {
                path.file_name().and_then(|name| name.to_str())
                    == Some(dependency.package.as_str())
                    || manifest.name == dependency.key
            })
            .map(|dependency| dependency.key.clone())
            .unwrap_or_else(|| manifest.name.clone());
        resolved.push(sources_resolver::ResolvedDependency {
            key,
            runtime_name: manifest.name,
            source_path: path.clone(),
        });
    }
    sources_resolver::ensure_unique_runtime_names(&resolved)?;

    for dependency in &resolved {
        tui::update_app_identity(
            log_tx_opt.as_ref(),
            &dependency.key,
            &dependency.runtime_name,
        );
    }

    let all_dep_paths: Vec<PathBuf> = resolved
        .iter()
        .map(|dependency| dependency.source_path.clone())
        .collect();
    let runtime_names: Vec<String> = resolved
        .iter()
        .map(|dependency| dependency.runtime_name.clone())
        .collect();

    // Publish each dep's resolved on-disk path to the TUI so the apps
    // sidebar can show *where* each app lives (sibling vs cache vs --dep
    // override) and the log-pane title can show the full path when an app
    // is focused. Best-effort: a dep with an unparseable manifest just
    // shows up without a path.
    for p in &all_dep_paths {
        if let Ok(m) = load_manifest(p) {
            tui::update_app_path(log_tx_opt.as_ref(), &m.name, p.clone());
        }
    }

    // ── Resolve instance profiles ─────────────────────────────────────────────
    // Platform mode now honours --instances alice,bob so contributors can
    // exercise multi-node flows (gossip, P2P, payments). The TUI's app
    // sidebar still works as a single filter axis (apps); per-node logs are
    // distinguishable via the `[<node>] ` prefix MonorepoHost::spawn_daemon
    // already injects into stdout/stderr.
    let profiles: Vec<InstanceProfile> = if args.instances.is_empty() {
        vec![InstanceProfile::alice()]
    } else {
        args.instances
            .iter()
            .map(|n| InstanceProfile::from_name(n))
            .collect::<anyhow::Result<Vec<_>>>()?
    };
    tui::sys_log(
        log_tx_opt.as_ref(),
        format!(
            "→ booting {} instance(s): {}",
            profiles.len(),
            profiles.iter().map(|p| p.name.as_str()).collect::<Vec<_>>().join(", ")
        ),
    );

    // ── Build one MonorepoHost per instance, all targeted at the platform ────
    let mode = host::Mode::Monorepo {
        path: platform_root.to_path_buf(),
    };
    let hosts: Vec<Box<dyn host::DaemonHost>> = profiles
        .iter()
        .map(|p| {
            host::for_mode(
                mode.clone(),
                p.clone(),
                // socket_override / dev_dir_override only make sense for a
                // single instance — for multi-instance let MonorepoHost
                // derive its own per-instance paths.
                if profiles.len() == 1 { args.socket_override } else { None },
                if profiles.len() == 1 { args.dev_dir_override } else { None },
                log_tx_opt.clone(),
                args.client_node,
                None, // no pre-allocated lane ports outside `harness up` — deterministic default
            )
        })
        .collect();

    // ── Pre-boot dep staging ─────────────────────────────────────────────────
    // Stage into EVERY host's dev-dir so each node loads the same set of
    // dep apps on first boot. We only build each dep once and copy from the
    // canonical staging location to the other instance dev-dirs.
    if !all_dep_paths.is_empty() {
        let pre_start_dev_dirs: Vec<PathBuf> = hosts
            .iter()
            .filter_map(|h| h.pre_start_dev_dir())
            .collect();
        if !pre_start_dev_dirs.is_empty() {
            tui::sys_log(
                log_tx_opt.as_ref(),
                format!(
                    "→ staging {} dep(s) into {} instance dev-dir(s) (pre-boot)…",
                    all_dep_paths.len(),
                    pre_start_dev_dirs.len()
                ),
            );
            stage_with_status(&all_dep_paths, &pre_start_dev_dirs, log_tx_opt.as_ref())?;
            // Standalone deps need a manifest with a per-instance socket_path
            // staged into each dev_dir BEFORE the daemon boots — that's how
            // standalone_discovery picks them up with the right UDS path.
            stage_standalone_manifests(
                &all_dep_paths,
                &pre_start_dev_dirs,
                log_tx_opt.as_ref(),
            )?;
        }
    }

    // ── Boot the platform daemons sequentially ───────────────────────────────
    // Sequential boot avoids cargo build-lock contention; each daemon's
    // logs are prefixed `[alice] ` / `[bob] ` so they're distinguishable.
    // (Signal handler is installed at function entry.)
    let mut handles: Vec<host::DaemonHandle> = Vec::with_capacity(hosts.len());
    for host_impl in &hosts {
        let handle = host_impl.ensure_running().context("start platform daemon")?;
        tui::sys_log(
            log_tx_opt.as_ref(),
            format!("✓ platform up — {}", handle.banner),
        );
        handles.push(handle);
    }

    // Post-boot fallback (covers any host without a pre-start dev-dir).
    if !all_dep_paths.is_empty() {
        let post_start_dirs: Vec<PathBuf> = hosts
            .iter()
            .zip(&handles)
            .filter(|(h, _)| h.pre_start_dev_dir().is_none())
            .map(|(_, handle)| handle.dev_dir.clone())
            .collect();
        if !post_start_dirs.is_empty() {
            tui::sys_log(
                log_tx_opt.as_ref(),
                format!(
                    "→ staging {} dep(s) into {} instance(s) (post-boot)…",
                    all_dep_paths.len(),
                    post_start_dirs.len()
                ),
            );
            stage_with_status(&all_dep_paths, &post_start_dirs, log_tx_opt.as_ref())?;
            stage_standalone_manifests(
                &all_dep_paths,
                &post_start_dirs,
                log_tx_opt.as_ref(),
            )?;
        }
    }

    // ── Spawn standalone deps per instance ────────────────────────────────────
    // Standalone apps aren't sideloaded into the daemon — they're independent
    // processes. Spawn each (instance × standalone dep) with env vars pointing
    // at the per-instance daemon socket + per-instance UDS + staged manifest.
    // Children are tracked so we can kill them on shutdown.
    //
    // Spawned BEFORE the app.dev_load sideload loop below: standalone apps
    // (e.g. wifi, lcd, led) have no dependency on the sideload loop —
    // they only need the resolved dep paths, the booted daemon handles, the
    // config, and the per-instance standalone manifests staged above (either
    // pre-start or in the post-boot fallback block just above). Spawning them
    // this early registers their capabilities as soon as possible, instead of
    // waiting out the full (potentially minutes-long) sequential sideload
    // loop first.
    let mut spawned_standalones = spawn_standalones(
        &all_dep_paths,
        &handles,
        &args.config,
        log_tx_opt.as_ref(),
    );

    // ── Sideload each staged dep via app.dev_load IPC ─────────────────────────
    // The platform's inotify watcher only fires on post-startup events, so
    // pre-staged apps would otherwise never be loaded — leaving them invisible
    // to /v2/node-apps and the UI. Call app.dev_load per-dep per-instance so
    // the daemon upserts the DB row and dlopens the artifact.
    //
    // Native (cdylib) deps the daemon ALREADY loaded at boot as builtins from
    // its $APT_APPS_DIR (ldk-node, notifications, terminal, observability, …)
    // are the exception: an in-process app cannot be hot-swapped. Calling
    // app.dev_load on one unloads the running copy and then fails with
    // "requires a node restart" — the app is simply gone (no Lightning when
    // it was ldk-node), and until this pass learned to look first, bring-up
    // still printed "platform up" as if nothing happened. So for every native
    // dep we first ask the daemon (`app.status`) whether that app is already
    // loaded in-process and skip the dev_load when the staged dep is the same
    // version + same checkout (see `sideload_decision`). Bun apps keep their
    // existing hot-reload path untouched. Whatever still fails is collected
    // and reported in one ✗ summary after the pass instead of scrolling by.
    let mut sideload_failures: Vec<SideloadFailure> = Vec::new();
    if !all_dep_paths.is_empty() {
        tui::sys_log(
            log_tx_opt.as_ref(),
            format!(
                "→ sideloading {} dep(s) into {} instance(s) via app.dev_load…",
                all_dep_paths.len(),
                handles.len()
            ),
        );
        for handle in &handles {
            let mut daemon_down = false;
            for dep_path in &all_dep_paths {
                let dep_manifest = match load_manifest(dep_path) {
                    Ok(m) => m,
                    Err(e) => {
                        tui::sys_log(
                            log_tx_opt.as_ref(),
                            format!(
                                "⚠ skip dev_load — could not read manifest for {}: {:#}",
                                dep_path.display(),
                                e
                            ),
                        );
                        continue;
                    }
                };
                // platform-runtime deps repackage upstream binaries and aren't
                // loaded by the app manager — same skip rule as stage_with_status.
                if dep_manifest.app_type.eq_ignore_ascii_case("platform-runtime") {
                    continue;
                }
                // Standalone apps run as their own OS process; NodeAppManager
                // rejects them via ManagerError::StandaloneNotManaged. They get
                // spawned + supervised by spawn_standalones above instead.
                if dep_manifest.app_type.eq_ignore_ascii_case("standalone") {
                    continue;
                }
                let dest = handle.dev_dir.join(&dep_manifest.name);
                let label = if handle.name.is_empty() {
                    dep_manifest.name.clone()
                } else {
                    format!("{} [{}]", dep_manifest.name, handle.name)
                };
                let is_native = is_native_app_type(&dep_manifest.app_type);

                // Native deps only: look before leaping (one cheap IPC call).
                let loaded = if is_native {
                    match query_loaded_app(&handle.socket_path, &dep_manifest.name) {
                        Ok(loaded) => loaded,
                        Err(e) => {
                            tui::sys_log(
                                log_tx_opt.as_ref(),
                                format!(
                                    "{label}: could not query app.status before dev_load ({:#}) — attempting dev_load anyway",
                                    e
                                ),
                            );
                            None
                        }
                    }
                } else {
                    None
                };
                let decision = sideload_decision(
                    &dep_manifest,
                    loaded.as_ref(),
                    || checkout_match(dep_path, handle.builtin_apps_dir.as_deref(), &dep_manifest.name),
                    args.no_sideload_native_builtins,
                );
                match decision {
                    SideloadDecision::Skip(reason) => {
                        tui::sys_log(
                            log_tx_opt.as_ref(),
                            format!("{label} left as loaded — {reason}"),
                        );
                        continue;
                    }
                    SideloadDecision::RestartRequired(reason) => {
                        tui::sys_log(
                            log_tx_opt.as_ref(),
                            format!("{label} NOT loaded — {reason}"),
                        );
                        sideload_failures.push(SideloadFailure {
                            label,
                            instance: handle.name.clone(),
                            env_dir: handle.dev_dir.parent().map(Path::to_path_buf),
                            reason,
                            restart_class: true,
                        });
                        continue;
                    }
                    SideloadDecision::Load(Some(note)) => {
                        tui::sys_log(log_tx_opt.as_ref(), format!("{label}: {note}"));
                    }
                    SideloadDecision::Load(None) => {}
                }

                match ipc_call(
                    &handle.socket_path,
                    "app.dev_load",
                    serde_json::json!({
                        "name": dep_manifest.name,
                        "path": dest.to_string_lossy(),
                    }),
                ) {
                    Ok(_) => tui::sys_log(
                        log_tx_opt.as_ref(),
                        format!("{} sideloaded", label),
                    ),
                    Err(e) => {
                        // "Connection refused" on the IPC socket means the
                        // daemon process has died (or never bound the
                        // socket). Hammering it for every remaining dep
                        // produces N identical errors and obscures the
                        // root cause. Bail out of the loop after a single
                        // clear diagnostic + cleanup hint — the next
                        // `node-app dev` invocation will rebuild + reboot
                        // from scratch.
                        let msg = format!("{:#}", e);
                        let connection_lost = msg.contains("Connection refused")
                            || msg.contains("Broken pipe")
                            || msg.contains("os error 61")
                            || msg.contains("os error 32");
                        tui::sys_log(
                            log_tx_opt.as_ref(),
                            format!("✗ dev_load {}: {}", label, msg),
                        );
                        sideload_failures.push(SideloadFailure {
                            label,
                            instance: handle.name.clone(),
                            env_dir: handle.dev_dir.parent().map(Path::to_path_buf),
                            restart_class: is_restart_class_error(&msg, is_native),
                            reason: msg,
                        });
                        if connection_lost {
                            // Best-effort: remove the orphaned socket so the
                            // next run's pre-boot cleanup doesn't trip over
                            // a dangling inode that points at no listener.
                            let _ = std::fs::remove_file(&handle.socket_path);
                            tui::sys_log(
                                log_tx_opt.as_ref(),
                                format!(
                                    "✗ daemon IPC unreachable for instance '{}' — skipping the remaining {} dev_load(s). \
                                     The daemon process died (check `{}/daemon.log` for the tail). \
                                     Run `node-app dev` again; the orphaned socket has been removed and the next boot will recover.",
                                    handle.name,
                                    all_dep_paths.len(),
                                    handle.dev_dir
                                        .parent()
                                        .map(|p| p.display().to_string())
                                        .unwrap_or_else(|| "<cache>".to_string()),
                                ),
                            );
                            daemon_down = true;
                            break;
                        }
                    }
                }
            }
            if daemon_down {
                // Other instances may still be alive — keep iterating.
                continue;
            }
        }
    }
    // End-of-bring-up verdict. Printed AFTER the per-instance "✓ platform up"
    // banners so a dead app can't hide behind them.
    report_sideload_failures(&sideload_failures, log_tx_opt.as_ref());

    if args.once {
        // In --agent / --operation-mode, run the onboarding/login step before
        // shutting down so the harness up flow gets populated session files for
        // alice + bob.
        let needs_agent_session = args.agent || args.operation_mode;
        if needs_agent_session {
            tui::sys_log(
                log_tx_opt.as_ref(),
                "→ --agent/--operation-mode + --once: running onboarding for all instances…",
            );
            let _ = super::agent::run_agent_setup(&handles, log_tx_opt.as_ref(), false);
        }
        tui::sys_log(
            log_tx_opt.as_ref(),
            "✓ --once: platform booted and deps staged; shutting down.",
        );
        for s in spawned_standalones.iter_mut() {
            let _ = s.child.kill();
            let _ = s.child.wait();
        }
        for h in &hosts {
            h.shutdown();
        }
        return Ok(());
    }

    // Stream per-app logs from every node. tail_logs internally prefixes
    // lines with `[<app>] ` so the existing per-app routing aggregates
    // across nodes; the original `[<node>] ` prefix on daemon stdout keeps
    // node distinction visible in the unified Daemon pane.
    for h in &hosts {
        for name in &runtime_names {
            h.tail_logs(name);
        }
    }

    if sideload_failures.is_empty() {
        tui::sys_log(
            log_tx_opt.as_ref(),
            "→ platform running. Edit platform code in the monorepo and rerun to pick up changes. \
             Ctrl-C to stop.",
        );
    } else {
        tui::sys_log(
            log_tx_opt.as_ref(),
            format!(
                "⚠ platform running WITH {} app(s) NOT loaded (see the ✗ sideload summary above). \
                 Edit platform code in the monorepo and rerun to pick up changes. Ctrl-C to stop.",
                sideload_failures.len()
            ),
        );
    }

    // ── Owner bootstrap + client-node operation-mode coordinator ──────────────
    // The long-running platform path does not otherwise onboard an owner, so
    // operation mode (and plain `--agent`) trigger it here — after the daemons
    // are healthy and every required app is staged/sideloaded. The coordinator
    // then snapshots the owner's devices and auto-approves the next new browser
    // device. Its handle is held in scope until shutdown; the polling loop
    // observes the shared cancel flag, so teardown never waits for the full
    // approval timeout.
    let needs_agent_session = args.agent || args.operation_mode;
    if needs_agent_session {
        let _ = super::agent::run_agent_setup(&handles, log_tx_opt.as_ref(), false);
    }
    let _operation_mode_thread = if args.operation_mode {
        let session = super::load_operation_mode_session(&handles[0])?;
        Some(super::operation_mode::prepare(session)?.spawn(log_tx_opt.clone()))
    } else {
        None
    };

    // ── Block until shutdown is requested ────────────────────────────────────
    loop {
        if SHUTDOWN_REQUESTED.load(Ordering::SeqCst) {
            break;
        }
        // External control requests (`node-app restart [--build]`) — file
        // based, checked every tick, deliberately OUTSIDE the TUI-signal
        // scope so they also work in --no-tui sessions.
        for h in &hosts {
            let Some(req) = h.take_control_request() else {
                continue;
            };
            match req.action.as_str() {
                "restart" => {
                    let with_build = req.build.as_deref() == Some("system");
                    banner(
                        log_tx_opt.as_ref(),
                        format!(
                            "⟳ EXTERNAL RESTART — instance '{}'{}",
                            h.instance_name(),
                            if with_build { " (rebuild node-server)" } else { "" }
                        ),
                    );
                    let outcome: Result<()> = (|| {
                        if with_build {
                            h.rebuild_daemon_binary()?;
                        }
                        h.restart()
                    })();
                    match outcome {
                        Ok(()) => {
                            h.write_control_result(req.ts, true, "restart complete");
                            banner(
                                log_tx_opt.as_ref(),
                                format!("✓ EXTERNAL RESTART COMPLETE — '{}'", h.instance_name()),
                            );
                        }
                        Err(e) => {
                            let msg = format!("{e:#}");
                            h.write_control_result(req.ts, false, &msg);
                            tui::sys_log(
                                log_tx_opt.as_ref(),
                                format!("✗ external restart '{}' failed: {msg}", h.instance_name()),
                            );
                        }
                    }
                }
                other => {
                    let msg = format!("unknown control action '{other}'");
                    h.write_control_result(req.ts, false, &msg);
                    tui::sys_log(log_tx_opt.as_ref(), format!("{msg}"));
                }
            }
        }
        if let Some(sigs) = &signals_opt {
            if sigs.should_quit() {
                break;
            }
            if sigs.take_restart() {
                let started = Instant::now();
                banner(log_tx_opt.as_ref(), "⟳ RESTART REQUESTED (r) — system daemon");
                for h in &hosts {
                    if let Err(e) = h.restart() {
                        tui::sys_log(log_tx_opt.as_ref(), format!("✗ restart failed: {:#}", e));
                    }
                }
                banner(
                    log_tx_opt.as_ref(),
                    format!("✓ RESTART COMPLETE ({:.1}s)", started.elapsed().as_secs_f32()),
                );
            }
            if let Some(scope) = sigs.take_build_scope() {
                let started = Instant::now();
                banner(
                    log_tx_opt.as_ref(),
                    format!("⟳ MANUAL REBUILD ({}) TRIGGERED", scope_label(scope)),
                );

                let do_apps = matches!(scope, BuildScope::Apps | BuildScope::All);
                let do_system = matches!(scope, BuildScope::System | BuildScope::All);
                let do_ui = matches!(scope, BuildScope::Ui | BuildScope::All);

                // 1. Apps: restage every node-app dep (build_and_stage rebuilds each).
                if do_apps {
                    if all_dep_paths.is_empty() {
                        tui::sys_log(
                            log_tx_opt.as_ref(),
                            "→ apps: no node-app deps declared; nothing to rebuild.",
                        );
                    } else {
                        let dev_dirs: Vec<PathBuf> =
                            handles.iter().map(|h| h.dev_dir.clone()).collect();
                        tui::sys_log(
                            log_tx_opt.as_ref(),
                            format!("→ rebuilding {} app dep(s)…", all_dep_paths.len()),
                        );
                        if let Err(e) =
                            stage_with_status(&all_dep_paths, &dev_dirs, log_tx_opt.as_ref())
                        {
                            tui::sys_log(
                                log_tx_opt.as_ref(),
                                format!("✗ app rebuild failed: {:#}", e),
                            );
                        }
                    }
                }

                // 2. System daemon: host.restart() runs `cargo build -p node-server`
                //    and respawns the daemon, surfacing Daemon-pane status updates.
                if do_system {
                    for h in &hosts {
                        if let Err(e) = h.restart() {
                            tui::sys_log(
                                log_tx_opt.as_ref(),
                                format!("✗ system rebuild/restart failed: {:#}", e),
                            );
                        }
                    }
                }

                // 3. UI: Vite already hot-reloads on source changes, so a
                //    forced rebuild here would just churn the browser. For now
                //    we just acknowledge the lane in the UiServer tab; if a
                //    hard restart is needed later, restart the spawned UI
                //    child via MonorepoHost. We don't expose that yet because
                //    it would tear down the user's open Vite session.
                if do_ui {
                    tui::sys_log(
                        log_tx_opt.as_ref(),
                        "→ ui: Vite HMR is active — no rebuild needed. \
                         Touch a source file to trigger a hot reload.",
                    );
                    tui::update_status(
                        log_tx_opt.as_ref(),
                        LogSource::UiServer,
                        ServiceStatus::Ready,
                        Some("HMR — no rebuild needed".into()),
                    );
                }

                banner(
                    log_tx_opt.as_ref(),
                    format!(
                        "✓ REBUILD COMPLETE ({:.1}s)",
                        started.elapsed().as_secs_f32()
                    ),
                );
            }
        }
        std::thread::sleep(Duration::from_millis(200));
    }

    tui::sys_log(log_tx_opt.as_ref(), "→ shutting down…");
    for s in spawned_standalones.iter_mut() {
        tui::sys_log(
            log_tx_opt.as_ref(),
            format!("→ killing standalone {}", s.label),
        );
        let _ = s.child.kill();
        let _ = s.child.wait();
    }
    for h in &hosts {
        h.shutdown();
    }
    drop(log_tx_opt);
    Ok(())
}

/// Build & stage each dep, publishing per-app status to the TUI sidebar.
/// Building → Loaded { reloads: 1 } on success; Failed(message) on error.
///
/// `dev_dirs` is the list of all instance dev-dirs that should receive a
/// copy of the staged dep. Each dep is built ONCE (against the first dev-dir
/// via `build_and_stage`); the staged output is then mirrored byte-for-byte
/// into every subsequent dev-dir via `copy_dir_recursive`. Returns the first
/// error encountered (after marking that app failed).
fn stage_with_status(
    dep_paths: &[PathBuf],
    dev_dirs: &[PathBuf],
    log_tx: Option<&crate::tui::LogTx>,
) -> Result<()> {
    if dev_dirs.is_empty() {
        return Ok(());
    }
    for dep_path in dep_paths {
        // Best-effort read of the manifest name so per-app status events line
        // up with the sidebar entries seeded from platform-depends. If the
        // manifest is unreadable we still attempt the stage; build_and_stage
        // will surface the real error.
        let manifest = load_manifest(dep_path).ok();
        let app_name = manifest.as_ref().map(|m| m.name.clone());

        // platform-runtime deps (e.g. bun-runtime) are packaging-only targets
        // — nothing to build, stage, or mirror. Mark the sidebar entry as a
        // no-op and continue to the next dep.
        if manifest
            .as_ref()
            .map(|m| m.app_type.eq_ignore_ascii_case("platform-runtime"))
            .unwrap_or(false)
        {
            if let Some(ref n) = app_name {
                tui::update_app_status(
                    log_tx,
                    n,
                    ServiceStatus::Loaded { reloads: 0 },
                    Some("platform-runtime (not staged)".to_string()),
                );
            }
            continue;
        }

        if let Some(ref n) = app_name {
            tui::update_app_status(log_tx, n, ServiceStatus::Building, None);
        }

        // Build once + stage into the first dev-dir.
        let first_dir = &dev_dirs[0];
        if let Err(e) = build_and_stage(dep_path, first_dir, log_tx) {
            let label = app_name
                .clone()
                .unwrap_or_else(|| dep_path.display().to_string());
            let e = e.context(format!("build dep '{}' ({})", label, dep_path.display()));
            if let Some(ref n) = app_name {
                let short = e.to_string().chars().take(60).collect::<String>();
                tui::update_app_status(log_tx, n, ServiceStatus::Failed(short), None);
            }
            return Err(e);
        }

        // Mirror the staged output to every other dev-dir.
        if let Some(name) = &app_name {
            let src = first_dir.join(name);
            for dst_root in &dev_dirs[1..] {
                let dst = dst_root.join(name);
                if dst.exists() {
                    std::fs::remove_dir_all(&dst).ok();
                }
                if let Err(e) = super::copy_dir_recursive(&src, &dst) {
                    let short = e.to_string().chars().take(60).collect::<String>();
                    tui::update_app_status(log_tx, name, ServiceStatus::Failed(short), None);
                    return Err(e);
                }
            }
        }

        if let Some(ref n) = app_name {
            let detail = if dev_dirs.len() > 1 {
                format!("staged ×{}", dev_dirs.len())
            } else {
                "staged".into()
            };
            tui::update_app_status(
                log_tx,
                n,
                ServiceStatus::Loaded { reloads: 1 },
                Some(detail),
            );
        }
    }
    Ok(())
}

/// Tracks a standalone child spawned by `spawn_standalones` so we can kill
/// it on shutdown. `label` is "<app> [<instance>]" for log output.
pub(crate) struct SpawnedStandalone {
    pub(crate) label: String,
    pub(crate) child: std::process::Child,
}

/// For each standalone dep, write a per-instance copy of `manifest.json` into
/// `<dev_dir>/<app>/manifest.json` with `standalone.socket_path` rewritten to
/// `<env_dir>/<app>.sock` (env_dir = dev_dir.parent). Also copies the UI dist
/// for apps with `has_ui`. This is what makes the daemon's boot-time
/// `standalone_discovery` scan find dev-staged standalones with the correct
/// socket path (instead of the manifest's hardcoded `/run/...`).
///
/// `stage_with_status` already builds the binaries; this only handles the
/// metadata side. Non-standalone deps are silently skipped.
pub(crate) fn stage_standalone_manifests(
    dep_paths: &[PathBuf],
    dev_dirs: &[PathBuf],
    log_tx: Option<&LogTx>,
) -> Result<()> {
    for dep_path in dep_paths {
        let manifest_path = dep_path.join("manifest.json");
        let raw = match std::fs::read_to_string(&manifest_path) {
            Ok(s) => s,
            Err(e) => {
                tui::sys_log(
                    log_tx,
                    format!(
                        "⚠ standalone stage: read {} failed: {}",
                        manifest_path.display(),
                        e
                    ),
                );
                continue;
            }
        };
        let mut value: serde_json::Value = match serde_json::from_str(&raw) {
            Ok(v) => v,
            Err(e) => {
                tui::sys_log(
                    log_tx,
                    format!(
                        "⚠ standalone stage: parse {} failed: {}",
                        manifest_path.display(),
                        e
                    ),
                );
                continue;
            }
        };
        let app_type = value
            .get("app_type")
            .and_then(|v| v.as_str())
            .unwrap_or("")
            .to_string();
        if !app_type.eq_ignore_ascii_case("standalone") {
            continue;
        }
        let app_name = value
            .get("name")
            .and_then(|v| v.as_str())
            .unwrap_or("")
            .to_string();
        if app_name.is_empty() {
            continue;
        }
        let has_ui = value.get("has_ui").and_then(|v| v.as_bool()).unwrap_or(false);
        let ui_relpath = value
            .get("ui_path")
            .and_then(|v| v.as_str())
            .unwrap_or("dist")
            .to_string();

        for dev_dir in dev_dirs {
            let env_dir = match dev_dir.parent() {
                Some(p) => p.to_path_buf(),
                None => {
                    tui::sys_log(
                        log_tx,
                        format!(
                            "{}: dev_dir {} has no parent — can't derive socket path",
                            app_name,
                            dev_dir.display()
                        ),
                    );
                    continue;
                }
            };
            let socket_path = env_dir.join(format!("{app_name}.sock"));
            value["standalone"] = serde_json::json!({
                "socket_path": socket_path.display().to_string()
            });

            let dest_dir = dev_dir.join(&app_name);
            if let Err(e) = std::fs::create_dir_all(&dest_dir) {
                tui::sys_log(
                    log_tx,
                    format!("✗ mkdir {}: {}", dest_dir.display(), e),
                );
                continue;
            }
            let dest_manifest = dest_dir.join("manifest.json");
            let serialized = match serde_json::to_string_pretty(&value) {
                Ok(s) => s,
                Err(e) => {
                    tui::sys_log(
                        log_tx,
                        format!("✗ serialize manifest for {}: {}", app_name, e),
                    );
                    continue;
                }
            };
            if let Err(e) = std::fs::write(&dest_manifest, serialized) {
                tui::sys_log(
                    log_tx,
                    format!("✗ write {}: {}", dest_manifest.display(), e),
                );
                continue;
            }
            if has_ui {
                let src_ui = dep_path.join(&ui_relpath);
                if src_ui.exists() {
                    let dst_ui = dest_dir.join(&ui_relpath);
                    if dst_ui.exists() {
                        let _ = std::fs::remove_dir_all(&dst_ui);
                    }
                    if let Err(e) = super::copy_dir_recursive(&src_ui, &dst_ui) {
                        tui::sys_log(
                            log_tx,
                            format!("✗ copy UI {}{}: {}", src_ui.display(), dst_ui.display(), e),
                        );
                    }
                }
            }
        }
    }
    Ok(())
}

/// Spawn each standalone dep as a child process per instance, with env vars
/// pointing at the per-instance daemon socket + standalone UDS + staged
/// manifest. Returns the live child handles so the caller can kill them on
/// shutdown. Non-standalone deps are silently skipped.
pub(crate) fn spawn_standalones(
    dep_paths: &[PathBuf],
    handles: &[host::DaemonHandle],
    config: &[(String, String)],
    log_tx: Option<&LogTx>,
) -> Vec<SpawnedStandalone> {
    let mut spawned = Vec::new();
    for dep_path in dep_paths {
        let manifest_path = dep_path.join("manifest.json");
        let raw = match std::fs::read_to_string(&manifest_path) {
            Ok(s) => s,
            Err(_) => continue,
        };
        let value: serde_json::Value = match serde_json::from_str(&raw) {
            Ok(v) => v,
            Err(_) => continue,
        };
        let app_type = value
            .get("app_type")
            .and_then(|v| v.as_str())
            .unwrap_or("");
        if !app_type.eq_ignore_ascii_case("standalone") {
            continue;
        }
        let app_name = value
            .get("name")
            .and_then(|v| v.as_str())
            .unwrap_or("")
            .to_string();
        if app_name.is_empty() {
            continue;
        }

        let is_rust = dep_path.join("Cargo.toml").exists();
        let bin_name = format!("node-app-{}", app_name);
        let rust_bin = dep_path.join("target").join("debug").join(&bin_name);

        for handle in handles {
            let env_dir = match handle.dev_dir.parent() {
                Some(p) => p.to_path_buf(),
                None => continue,
            };
            let socket_path = env_dir.join(format!("{app_name}.sock"));
            // Remove stale socket so the new bind succeeds (UnixListener::bind
            // fails with EADDRINUSE on an existing path).
            let _ = std::fs::remove_file(&socket_path);
            let staged_manifest = handle.dev_dir.join(&app_name).join("manifest.json");

            let mut cmd = if is_rust {
                let mut c = std::process::Command::new(&rust_bin);
                c.current_dir(dep_path);
                c
            } else {
                let mut c = std::process::Command::new("bun");
                c.args(["run", "src/index.ts"]);
                c.current_dir(dep_path);
                c
            };

            cmd.env("NODE_APP_SOCKET", &socket_path);
            cmd.env("NODE_IPC_SOCKET", &handle.socket_path);
            cmd.env("NODE_APP_MANIFEST_PATH", &staged_manifest);
            // The standalone process itself doesn't validate socket paths, but
            // forwarding the flag keeps env parity with the daemon in case the
            // app calls back into shared validation code.
            cmd.env("NODE_ALLOW_DEV_SOCKET_PATH", "1");

            // Per-instance writable state dir. Apps that persist to disk
            // (node-app-ota's SQLite, node-app-lcd's storage.json, …) otherwise
            // fall back to the prod `/var/lib/node-app-<name>` path, which isn't
            // writable in dev (EACCES — fatal for OTA) and would collide across
            // instances. Honors the platform-wide NODE_APP_STATE_DIR contract.
            let state_dir = env_dir.join("app-state").join(&app_name);
            let _ = std::fs::create_dir_all(&state_dir);
            cmd.env("NODE_APP_STATE_DIR", &state_dir);

            // node-app-wifi predates the NODE_APP_STATE_DIR contract: its state root is
            // NODE_APP_WIFI_DATA_DIR (the exact env its production systemd unit sets).
            // Without it the daemon defaults to /var/lib/node and dies on EACCES in dev.
            if app_name == "wifi" {
                cmd.env("NODE_APP_WIFI_DATA_DIR", &state_dir);
            }

            // Assign a distinct HTTP port per (app, instance) so standalone
            // apps that serve a browser UI (lcd, led) don't both fall back to
            // their hardcoded default port and collide (EADDRINUSE) when alice
            // and bob run together. Apps without an HTTP server ignore it.
            let http_port = alloc_free_port();
            if let Some(port) = http_port {
                cmd.env("NODE_APP_HTTP_PORT", port.to_string());
            }

            // User `-c KEY=VALUE` overrides come last so they win over the
            // per-instance defaults computed above.
            for (k, v) in config {
                cmd.env(k, v);
            }

            cmd.stdin(std::process::Stdio::null());
            if log_tx.is_some() {
                cmd.stdout(std::process::Stdio::piped());
                cmd.stderr(std::process::Stdio::piped());
            } else {
                cmd.stdout(std::process::Stdio::inherit());
                cmd.stderr(std::process::Stdio::inherit());
            }

            let label = format!("{} [{}]", app_name, handle.name);
            match cmd.spawn() {
                Ok(mut child) => {
                    if let Some(tx) = log_tx.cloned() {
                        let prefix = format!("[{}][{}] ", handle.name, app_name);
                        if let Some(stdout) = child.stdout.take() {
                            tail_to_tui(stdout, prefix.clone(), tx.clone());
                        }
                        if let Some(stderr) = child.stderr.take() {
                            tail_to_tui(stderr, prefix, tx);
                        }
                    }
                    let http_note = http_port
                        .map(|p| format!(", http=:{p}"))
                        .unwrap_or_default();
                    tui::sys_log(
                        log_tx,
                        format!(
                            "{} spawned (pid {}, socket={}{})",
                            label,
                            child.id(),
                            socket_path.display(),
                            http_note
                        ),
                    );
                    spawned.push(SpawnedStandalone { label, child });
                }
                Err(e) => {
                    let hint = if is_rust && !rust_bin.exists() {
                        format!(
                            " — binary not found at {}; was the dep built?",
                            rust_bin.display()
                        )
                    } else {
                        String::new()
                    };
                    tui::sys_log(
                        log_tx,
                        format!("✗ spawn {}: {}{}", label, e, hint),
                    );
                }
            }
        }
    }
    spawned
}

/// Ask the kernel for a free loopback TCP port by binding `:0` and reading
/// back the assigned port. Best-effort: returns `None` if even an ephemeral
/// bind fails, in which case the spawned app falls back to its own default
/// port. There's a small TOCTOU window between the drop here and the child
/// binding, which is acceptable for an interactive dev loop (a racy collision
/// just makes the app fail to bind and the developer retries).
fn alloc_free_port() -> Option<u16> {
    use std::net::{Ipv4Addr, SocketAddrV4, TcpListener};
    let listener = TcpListener::bind(SocketAddrV4::new(Ipv4Addr::LOCALHOST, 0)).ok()?;
    let port = listener.local_addr().ok()?.port();
    drop(listener);
    Some(port)
}

/// Forward child stdio lines to the TUI as `LogSource::App` entries with the
/// `[<instance>][<app>] ` prefix that AppState::push_log already understands
/// (it peels both prefixes and routes lines into per-node + per-app buffers).
fn tail_to_tui<R: std::io::Read + Send + 'static>(reader: R, prefix: String, tx: LogTx) {
    std::thread::spawn(move || {
        for line in std::io::BufReader::new(reader).lines().map_while(Result::ok) {
            let _ = tx.send(crate::tui::TuiEvent::Log(crate::tui::LogEntry {
                source: LogSource::App,
                line: format!("{prefix}{line}"),
            }));
        }
    });
}

/// Parse `infra/debian/platform-depends`, preserving both the Debian package
/// identity and the repository lookup key. Blank lines and comments (`#`) are
/// ignored. Lines that don't start with `node-app-` are system packages.
pub fn parse_platform_depends(path: &Path) -> Result<Vec<PlatformDependency>> {
    let text = std::fs::read_to_string(path)
        .with_context(|| format!("read {}", path.display()))?;
    let mut out = Vec::new();
    for line in text.lines() {
        let line = line.trim();
        if line.is_empty() || line.starts_with('#') {
            continue;
        }
        // Strip dpkg version constraint trailers, e.g. "node-app-foo (>= 1.0)".
        let pkg = line
            .split_whitespace()
            .next()
            .unwrap_or("")
            .trim();
        if let Some(rest) = pkg.strip_prefix("node-app-") {
            if !rest.is_empty() {
                out.push(PlatformDependency {
                    key: rest.to_string(),
                    package: pkg.to_string(),
                });
            }
        }
    }
    Ok(out)
}

fn platform_dependencies(platform_root: &Path) -> Result<Vec<PlatformDependency>> {
    parse_platform_depends(&platform_root.join("infra/debian/platform-depends"))
}

#[cfg(unix)]
fn install_signal_handler() {
    use std::sync::atomic::AtomicBool;
    static INSTALLED: AtomicBool = AtomicBool::new(false);
    if INSTALLED.swap(true, Ordering::SeqCst) {
        return;
    }
    unsafe {
        libc::signal(
            libc::SIGINT,
            super::handle_shutdown_signal as *const () as libc::sighandler_t,
        );
        libc::signal(
            libc::SIGTERM,
            super::handle_shutdown_signal as *const () as libc::sighandler_t,
        );
    }
}

#[cfg(not(unix))]
fn install_signal_handler() {}

/// Short human label for a rebuild scope, used inside the banner line so the
/// user can tell at a glance which slice they asked for.
fn scope_label(scope: BuildScope) -> &'static str {
    match scope {
        BuildScope::All => "all",
        BuildScope::System => "system",
        BuildScope::Apps => "apps",
        BuildScope::Ui => "ui",
    }
}

// ── Native-builtin re-sideload guard ─────────────────────────────────────────

/// What the daemon reports for an app via `app.status` (a projection of
/// `AppStatusDetail` in `core/domain/src/ports/endpoints/app_control.rs`):
/// only the fields the sideload pass decides on.
#[derive(Debug, Clone, Default, Deserialize, PartialEq, Eq)]
pub(crate) struct LoadedApp {
    #[serde(default)]
    pub(crate) version: String,
    /// `AppLoadStatus` serialised `snake_case`: "active", "lazy",
    /// "requires_restart", …
    #[serde(default)]
    pub(crate) status: String,
    /// "in_process" (native cdylib) | "subprocess" (Bun / standalone).
    #[serde(default)]
    pub(crate) sandbox: String,
    /// "bundled" (builtin loaded from $APT_APPS_DIR) | "apt".
    #[serde(default)]
    pub(crate) source: String,
    /// Capability names the app currently has registered in the daemon's
    /// capability router. `None` = the daemon didn't report it (older host,
    /// or no registry wired) — treated as "unknown", which means dev_load.
    #[serde(default)]
    pub(crate) registered_capabilities: Option<Vec<String>>,
}

/// Ask the daemon whether `name` is a known app. `Ok(None)` when the daemon
/// has never heard of it (ERR_APP_NOT_FOUND, -32001); `Err` only for a
/// transport/IPC failure — callers fall back to today's behaviour (attempt
/// the dev_load) in that case.
fn query_loaded_app(socket_path: &Path, name: &str) -> Result<Option<LoadedApp>> {
    match ipc_call(socket_path, "app.status", serde_json::json!({ "name": name })) {
        Ok(value) => {
            let loaded: LoadedApp = serde_json::from_value(value)
                .with_context(|| format!("parse app.status reply for '{name}'"))?;
            Ok(Some(loaded))
        }
        Err(e) => {
            let msg = format!("{e:#}");
            if msg.contains("-32001") || msg.contains("not found") {
                Ok(None)
            } else {
                Err(e)
            }
        }
    }
}

/// Same spelling set `AppKindDetected::detect` (dev.rs) accepts for an in-process app.
fn is_native_app_type(app_type: &str) -> bool {
    app_type.eq_ignore_ascii_case("native") || app_type.eq_ignore_ascii_case("cdylib")
}

/// Is the staged dep the very checkout the daemon loaded its builtin from?
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum CheckoutMatch {
    /// Same directory (after canonicalisation).
    SamePath,
    /// Different directories at the same git HEAD (e.g. the `.node-app/
    /// sources.lock` cache clone vs the `modules/` clone the daemon booted).
    SameRev(String),
    /// Cannot tell: no builtin dir for this host, no matching builtin
    /// checkout, or git unavailable on one side.
    Unknown,
    /// Two checkouts at different git HEADs.
    Different { dep_rev: String, builtin_rev: String },
}

/// Locate the builtin checkout for `name` under the daemon's `$APT_APPS_DIR`.
/// Directory names are not uniform (`modules/ldk-node` but
/// `modules/node-app-notifications`), so try the two conventions first and
/// only then fall back to scanning every immediate child's manifest.
pub(crate) fn builtin_checkout_for(builtin_apps_dir: &Path, name: &str) -> Option<PathBuf> {
    for candidate in [
        builtin_apps_dir.join(name),
        builtin_apps_dir.join(format!("node-app-{name}")),
    ] {
        if sources_resolver::is_node_app_dir(&candidate)
            && sources_resolver::read_manifest_name(&candidate).ok().as_deref() == Some(name)
        {
            return Some(candidate);
        }
    }
    let entries = std::fs::read_dir(builtin_apps_dir).ok()?;
    entries
        .flatten()
        .map(|entry| entry.path())
        .filter(|path| sources_resolver::is_node_app_dir(path))
        .find(|path| sources_resolver::read_manifest_name(path).ok().as_deref() == Some(name))
}

pub(crate) fn checkout_match(
    dep_path: &Path,
    builtin_apps_dir: Option<&Path>,
    name: &str,
) -> CheckoutMatch {
    let Some(builtin_dir) = builtin_apps_dir else {
        return CheckoutMatch::Unknown;
    };
    let Some(builtin_checkout) = builtin_checkout_for(builtin_dir, name) else {
        return CheckoutMatch::Unknown;
    };
    if let (Ok(a), Ok(b)) = (dep_path.canonicalize(), builtin_checkout.canonicalize()) {
        if a == b {
            return CheckoutMatch::SamePath;
        }
    }
    match (
        sources_resolver::git_rev_at(dep_path),
        sources_resolver::git_rev_at(&builtin_checkout),
    ) {
        (Some(dep_rev), Some(builtin_rev)) if dep_rev == builtin_rev => CheckoutMatch::SameRev(dep_rev),
        (Some(dep_rev), Some(builtin_rev)) => CheckoutMatch::Different { dep_rev, builtin_rev },
        _ => CheckoutMatch::Unknown,
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum SideloadDecision {
    /// Call `app.dev_load`; the optional note is logged first.
    Load(Option<String>),
    /// Leave the daemon's loaded copy alone (reason is logged).
    Skip(String),
    /// Don't even try: the daemon already flagged the app as needing a
    /// restart, so the dev_load is guaranteed to fail and the app is down.
    RestartRequired(String),
}

/// Statuses under which an in-process app is genuinely resident in the daemon
/// (`AppLoadStatus` snake_case). `lazy` apps are loaded on first invocation
/// but are already registered as builtins; re-sideloading them trips the same
/// "one native load per process" rule.
fn is_resident_status(status: &str) -> bool {
    matches!(status, "active" | "lazy" | "degraded")
}

fn short_rev(rev: &str) -> &str {
    &rev[..rev.len().min(12)]
}

/// Declared `provides` the daemon does NOT currently have registered for the
/// app, or `None` when the daemon didn't report registration at all.
fn unregistered_provides(dep: &Manifest, loaded: &LoadedApp) -> Option<Vec<String>> {
    let registered = loaded.registered_capabilities.as_ref()?;
    Some(
        dep.declared_provides()
            .into_iter()
            .filter(|name| !registered.iter().any(|r| r == name))
            .collect(),
    )
}

/// Decide whether a staged dep should go through `app.dev_load`.
///
/// `checkout` is evaluated lazily — it may shell out to git — and only when
/// the version already matches AND the daemon reports the app's declared
/// `provides` as registered. Non-native deps and deps the daemon doesn't
/// know are always loaded (today's behaviour).
///
/// Why registration matters: on a warm boot the daemon auto-starts an
/// in-process app from its dev-root DB row, which makes it resident
/// (`active`) but registers NONE of its service capabilities — only builtin
/// registration and `dev_load` (whose same-manifest no-op path calls
/// `reregister_app_provides`) do. Skipping dev_load for such an app leaves
/// `core.did.*` / `core.lightning.*` / `core.cron.*` without a provider and
/// every authenticated request 503s. So "resident" alone is never enough to
/// skip; the cheap no-op dev_load is what puts the provides back.
pub(crate) fn sideload_decision(
    dep: &Manifest,
    loaded: Option<&LoadedApp>,
    checkout: impl FnOnce() -> CheckoutMatch,
    skip_every_loaded_native: bool,
) -> SideloadDecision {
    if !is_native_app_type(&dep.app_type) {
        return SideloadDecision::Load(None);
    }
    let Some(loaded) = loaded else {
        return SideloadDecision::Load(None);
    };
    if loaded.status == "requires_restart" {
        return SideloadDecision::RestartRequired(format!(
            "the daemon already flags v{} as requires_restart (a native app was unloaded earlier in this daemon's life); dev_load would fail the same way",
            loaded.version
        ));
    }
    // The daemon's own view of the sandbox wins over the dep manifest: a
    // subprocess app can be hot-reloaded, whatever the staged manifest says.
    if !loaded.sandbox.is_empty() && loaded.sandbox != "in_process" {
        return SideloadDecision::Load(None);
    }
    if !is_resident_status(&loaded.status) {
        return SideloadDecision::Load(None);
    }
    let origin = if loaded.source == "bundled" { "builtin" } else { "in-process app" };
    if skip_every_loaded_native {
        return SideloadDecision::Skip(format!(
            "--no-sideload-native-builtins: daemon already has {origin} v{} loaded ({})",
            loaded.version, loaded.status
        ));
    }
    if loaded.version != dep.version {
        return SideloadDecision::Load(Some(format!(
            "daemon has {origin} v{} loaded ({}) but the staged dep is v{} — attempting dev_load; \
             a loaded native app cannot be hot-swapped, so expect to restart the daemon if this fails",
            loaded.version, loaded.status, dep.version
        )));
    }
    match unregistered_provides(dep, loaded) {
        None => {
            return SideloadDecision::Load(Some(format!(
                "daemon has {origin} v{} loaded ({}) but does not report its registered capabilities — \
                 calling dev_load so its same-manifest no-op path re-registers provides",
                loaded.version, loaded.status
            )));
        }
        Some(missing) if !missing.is_empty() => {
            let registered = loaded
                .registered_capabilities
                .as_ref()
                .map(Vec::len)
                .unwrap_or(0);
            return SideloadDecision::Load(Some(format!(
                "daemon has {origin} v{} loaded ({}) with {registered} capabilit{} registered but {} declared \
                 provide(s) missing ({}) — calling dev_load so its same-manifest no-op path re-registers them",
                loaded.version,
                loaded.status,
                if registered == 1 { "y" } else { "ies" },
                missing.len(),
                missing.join(", ")
            )));
        }
        Some(_) => {}
    }
    match checkout() {
        CheckoutMatch::SamePath => SideloadDecision::Skip(format!(
            "daemon already loaded {origin} v{} ({}) from this same checkout; a loaded native app cannot be hot-swapped",
            loaded.version, loaded.status
        )),
        CheckoutMatch::SameRev(rev) => SideloadDecision::Skip(format!(
            "daemon already loaded {origin} v{} ({}) at the same git rev {}; a loaded native app cannot be hot-swapped",
            loaded.version,
            loaded.status,
            short_rev(&rev)
        )),
        CheckoutMatch::Unknown => SideloadDecision::Skip(format!(
            "daemon already loaded {origin} v{} ({}) — same version (checkout identity not verifiable); a loaded native app cannot be hot-swapped",
            loaded.version, loaded.status
        )),
        CheckoutMatch::Different { dep_rev, builtin_rev } => SideloadDecision::Load(Some(format!(
            "daemon has {origin} v{} loaded from a different checkout (git {} vs staged {}) — attempting dev_load; \
             a loaded native app cannot be hot-swapped, so expect to restart the daemon if this fails",
            loaded.version,
            short_rev(&builtin_rev),
            short_rev(&dep_rev)
        ))),
    }
}

/// One dep that is NOT loaded after the sideload pass.
#[derive(Debug, Clone)]
pub(crate) struct SideloadFailure {
    /// `<app> [<instance>]`.
    pub(crate) label: String,
    /// Instance name ("" for non-profile hosts).
    pub(crate) instance: String,
    /// `<cache>/<instance>` dir whose `control/request.json` the supervisor
    /// polls; `None` when the host has no such dir.
    pub(crate) env_dir: Option<PathBuf>,
    pub(crate) reason: String,
    /// The "a native app cannot load again until the daemon restarts" class
    /// — the only cure is a daemon restart, not a retry.
    pub(crate) restart_class: bool,
}

/// Does a dev_load error mean "restart the daemon"? Matches the host's
/// `ReloadAfterUnload::RequiresRestart` / `NativeLoaderError` wording
/// (`core/app-host/src/{manager_port_adapter,native_loader}.rs`) plus the
/// unload-timeout path a native app hits when its shutdown hook hangs.
pub(crate) fn is_restart_class_error(message: &str, native: bool) -> bool {
    let m = message.to_ascii_lowercase();
    m.contains("requires a node restart")
        || m.contains("requires_restart")
        || (native && (m.contains("timed out") || m.contains("timeout")))
}

/// The ✗ verdict printed once the sideload pass is over.
fn report_sideload_failures(failures: &[SideloadFailure], log_tx: Option<&LogTx>) {
    if failures.is_empty() {
        return;
    }
    tui::sys_log(
        log_tx,
        format!(
            "✗ SIDELOAD SUMMARY: {} app(s) failed to sideload and are NOT loaded:",
            failures.len()
        ),
    );
    for failure in failures {
        tui::sys_log(log_tx, format!("{}: {}", failure.label, failure.reason));
    }
    if !failures.iter().any(|f| f.restart_class) {
        return;
    }
    tui::sys_log(
        log_tx,
        "  ↳ a loaded native (cdylib) app cannot be hot-swapped in-process: the daemon unloaded it \
         and cannot load a native app again until it restarts. Restart the daemon, or stop and rerun `node-app dev`:",
    );
    let mut seen = std::collections::BTreeSet::new();
    for failure in failures.iter().filter(|f| f.restart_class) {
        if !seen.insert(failure.instance.clone()) {
            continue;
        }
        let hint = match (&failure.instance, &failure.env_dir) {
            (instance, Some(env_dir)) if !instance.is_empty() => format!(
                "      instance '{instance}': `node-app restart -i {instance}` — or write {{\"action\":\"restart\"}} to {}/control/request.json",
                env_dir.display()
            ),
            (instance, Some(env_dir)) => format!(
                "      write {{\"action\":\"restart\"}} to {}/control/request.json (instance '{instance}')",
                env_dir.display()
            ),
            (instance, None) => format!(
                "      restart the daemon serving instance '{instance}' by hand (this host has no control dir)"
            ),
        };
        tui::sys_log(log_tx, hint);
    }
}

/// Emit a bracketed banner via the TUI System pane so manual rebuild / restart
/// activity is impossible to miss in the log stream. Three lines (rule, label,
/// rule) keep the boundary visually distinct from regular `→` / `✓` lines.
fn banner(log_tx: Option<&crate::tui::LogTx>, label: impl Into<String>) {
    const RULE: &str =
        "════════════════════════════════════════════════════════════════════";
    tui::sys_log(log_tx, "");
    tui::sys_log(log_tx, RULE);
    tui::sys_log(log_tx, format!("  {}", label.into()));
    tui::sys_log(log_tx, RULE);
}

// ── Tests ────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use tempfile::TempDir;

    fn dependency(key: &str) -> PlatformDependency {
        PlatformDependency {
            key: key.to_string(),
            package: format!("node-app-{key}"),
        }
    }

    #[test]
    fn platform_dependency_selection_is_shell_independent() {
        let tmp = TempDir::new().unwrap();
        let infra = tmp.path().join("infra/debian");
        fs::create_dir_all(&infra).unwrap();
        fs::write(
            infra.join("platform-depends"),
            "node-app-core-storage\nnode-app-stage-home\n",
        )
        .unwrap();

        assert_eq!(
            platform_dependencies(tmp.path()).unwrap(),
            vec![dependency("core-storage"), dependency("stage-home")]
        );
    }

    #[test]
    fn parse_strips_prefix_and_skips_non_app_lines() {
        let tmp = TempDir::new().unwrap();
        let p = tmp.path().join("platform-depends");
        fs::write(
            &p,
            "# header comment\n\
             jq\n\
             curl\n\
             \n\
             # Built-in node apps\n\
             node-app-esp32-bridge\n\
             node-app-discovery\n\
             # trailing comment\n",
        )
        .unwrap();

        let dependencies = parse_platform_depends(&p).unwrap();
        assert_eq!(
            dependencies
                .iter()
                .map(|dep| dep.key.as_str())
                .collect::<Vec<_>>(),
            vec!["esp32-bridge", "discovery"]
        );
    }

    #[test]
    fn parse_handles_version_constraints() {
        let tmp = TempDir::new().unwrap();
        let p = tmp.path().join("platform-depends");
        fs::write(&p, "node-app-foo (>= 1.2.3)\n").unwrap();
        assert_eq!(parse_platform_depends(&p).unwrap()[0].key, "foo");
    }

    #[test]
    fn parse_preserves_package_identity_for_stage_apps() {
        let tmp = TempDir::new().unwrap();
        let p = tmp.path().join("platform-depends");
        fs::write(&p, "node-app-stage-home\n").unwrap();

        assert_eq!(
            parse_platform_depends(&p).unwrap(),
            vec![PlatformDependency {
                key: "stage-home".to_string(),
                package: "node-app-stage-home".to_string(),
            }]
        );
    }

    #[test]
    fn parse_skips_empty_node_app_prefix() {
        let tmp = TempDir::new().unwrap();
        let p = tmp.path().join("platform-depends");
        fs::write(&p, "node-app-\nnode-app-real\n").unwrap();
        assert_eq!(parse_platform_depends(&p).unwrap()[0].key, "real");
    }

    #[test]
    fn parse_missing_file_errors() {
        let tmp = TempDir::new().unwrap();
        let p = tmp.path().join("nope");
        assert!(parse_platform_depends(&p).is_err());
    }

    // ── native-builtin re-sideload guard ────────────────────────────────────

    fn manifest(name: &str, app_type: &str, version: &str) -> Manifest {
        serde_json::from_value(serde_json::json!({
            "name": name,
            "version": version,
            "app_type": app_type,
        }))
        .unwrap()
    }

    /// A resident app whose declared provides are all registered — the state
    /// a builtin is in right after the daemon's own boot-time registration.
    fn loaded(version: &str, status: &str, sandbox: &str, source: &str) -> LoadedApp {
        LoadedApp {
            version: version.to_string(),
            status: status.to_string(),
            sandbox: sandbox.to_string(),
            source: source.to_string(),
            registered_capabilities: Some(vec![
                "core.did.devices.list".to_string(),
                "core.did.sign".to_string(),
            ]),
        }
    }

    fn manifest_providing(name: &str, version: &str, provides: &[&str]) -> Manifest {
        let provides: serde_json::Map<String, serde_json::Value> = provides
            .iter()
            .map(|p| (p.to_string(), serde_json::json!({ "description": p })))
            .collect();
        serde_json::from_value(serde_json::json!({
            "name": name,
            "version": version,
            "app_type": "native",
            "provides": provides,
        }))
        .unwrap()
    }

    /// Field result on PR #2491: a warm boot auto-starts the native app from
    /// its dev-root DB row (resident, same version, same checkout) but
    /// registers NONE of its provides. Skipping dev_load then leaves
    /// core.did.* without a provider and every authenticated request 503s.
    /// Loaded-but-zero-capabilities MUST still sideload.
    #[test]
    fn loaded_native_with_zero_registered_capabilities_is_still_sideloaded() {
        let dep = manifest_providing("did", "0.5.0", &["core.did.devices.list", "core.did.sign"]);
        let mut auto_started = loaded("0.5.0", "active", "in_process", "apt");
        auto_started.registered_capabilities = Some(Vec::new());
        match sideload_decision(&dep, Some(&auto_started), never_checked, false) {
            SideloadDecision::Load(Some(note)) => {
                assert!(note.contains("0 capabilities registered"), "{note}");
                assert!(note.contains("core.did.devices.list"), "{note}");
                assert!(note.contains("re-registers"), "{note}");
            }
            other => panic!("expected Load(Some), got {other:?}"),
        }
    }

    #[test]
    fn partially_registered_provides_still_sideload() {
        let dep = manifest_providing("did", "0.5.0", &["core.did.devices.list", "core.did.sign"]);
        let mut partial = loaded("0.5.0", "active", "in_process", "bundled");
        partial.registered_capabilities = Some(vec!["core.did.sign".to_string()]);
        match sideload_decision(&dep, Some(&partial), never_checked, false) {
            SideloadDecision::Load(Some(note)) => {
                assert!(note.contains("1 capability registered"), "{note}");
                assert!(note.contains("core.did.devices.list") && !note.contains("core.did.sign)"), "{note}");
            }
            other => panic!("expected Load(Some), got {other:?}"),
        }
    }

    /// A daemon that predates the `registered_capabilities` field (or has no
    /// registry wired) cannot vouch for registration → dev_load, never skip.
    #[test]
    fn unknown_registration_state_is_still_sideloaded() {
        let dep = manifest_providing("did", "0.5.0", &["core.did.devices.list"]);
        let mut old_daemon = loaded("0.5.0", "active", "in_process", "bundled");
        old_daemon.registered_capabilities = None;
        match sideload_decision(&dep, Some(&old_daemon), never_checked, false) {
            SideloadDecision::Load(Some(note)) => {
                assert!(note.contains("does not report its registered capabilities"), "{note}")
            }
            other => panic!("expected Load(Some), got {other:?}"),
        }
    }

    #[test]
    fn fully_registered_provides_allow_the_skip() {
        let dep = manifest_providing("did", "0.5.0", &["core.did.devices.list", "core.did.sign"]);
        let resident = loaded("0.5.0", "active", "in_process", "bundled");
        assert!(matches!(
            sideload_decision(&dep, Some(&resident), || CheckoutMatch::SamePath, false),
            SideloadDecision::Skip(_)
        ));
        // v2 `capabilities.provides` spelling is honoured too.
        let v2: Manifest = serde_json::from_value(serde_json::json!({
            "name": "did",
            "version": "0.5.0",
            "app_type": "native",
            "capabilities": { "provides": ["core.did.sign"] },
        }))
        .unwrap();
        assert_eq!(v2.declared_provides(), vec!["core.did.sign".to_string()]);
        assert!(matches!(
            sideload_decision(&v2, Some(&resident), || CheckoutMatch::SamePath, false),
            SideloadDecision::Skip(_)
        ));
        // An app declaring no provides has nothing to register; resident is enough.
        let silent = manifest_providing("terminal", "0.5.0", &[]);
        let mut nothing = loaded("0.5.0", "active", "in_process", "bundled");
        nothing.registered_capabilities = Some(Vec::new());
        assert!(matches!(
            sideload_decision(&silent, Some(&nothing), || CheckoutMatch::SamePath, false),
            SideloadDecision::Skip(_)
        ));
    }

    /// The wire shape the daemon emits (`AppStatusDetail`): an absent field
    /// is `None`, a present empty list is `Some([])`.
    #[test]
    fn loaded_app_distinguishes_absent_from_empty_registration() {
        let absent: LoadedApp = serde_json::from_value(serde_json::json!({
            "version": "1.0.0", "status": "active", "sandbox": "in_process", "source": "bundled",
        }))
        .unwrap();
        assert_eq!(absent.registered_capabilities, None);
        let empty: LoadedApp = serde_json::from_value(serde_json::json!({
            "version": "1.0.0", "status": "active", "sandbox": "in_process", "source": "bundled",
            "registered_capabilities": [],
        }))
        .unwrap();
        assert_eq!(empty.registered_capabilities, Some(Vec::new()));
    }

    fn never_checked() -> CheckoutMatch {
        panic!("checkout identity must not be consulted on this path")
    }

    /// The observed bug: ldk-node v1.2.3 booted as a builtin from modules/,
    /// the same checkout is staged again → must NOT be dev_loaded.
    #[test]
    fn loaded_native_builtin_from_the_same_checkout_is_skipped() {
        let dep = manifest("ldk-node", "native", "1.2.3");
        let resident = loaded("1.2.3", "active", "in_process", "bundled");
        for (checkout, needle) in [
            (CheckoutMatch::SamePath, "same checkout"),
            (CheckoutMatch::SameRev("38d9ce5c34da2f7799c4df27a6badac5a7787115".into()), "38d9ce5c34da"),
            (CheckoutMatch::Unknown, "not verifiable"),
        ] {
            match sideload_decision(&dep, Some(&resident), || checkout.clone(), false) {
                SideloadDecision::Skip(reason) => {
                    assert!(reason.contains(needle), "{reason}");
                    assert!(reason.contains("builtin v1.2.3"), "{reason}");
                }
                other => panic!("expected Skip, got {other:?}"),
            }
        }
    }

    #[test]
    fn lazy_native_builtins_count_as_resident() {
        let dep = manifest("terminal", "native", "0.4.0");
        let resident = loaded("0.4.0", "lazy", "in_process", "bundled");
        assert!(matches!(
            sideload_decision(&dep, Some(&resident), || CheckoutMatch::SamePath, false),
            SideloadDecision::Skip(_)
        ));
    }

    #[test]
    fn a_different_version_or_checkout_is_still_attempted_with_a_warning() {
        let dep = manifest("ldk-node", "native", "1.3.0");
        let resident = loaded("1.2.3", "active", "in_process", "bundled");
        match sideload_decision(&dep, Some(&resident), never_checked, false) {
            SideloadDecision::Load(Some(note)) => {
                assert!(note.contains("v1.2.3") && note.contains("v1.3.0"), "{note}")
            }
            other => panic!("expected Load(Some), got {other:?}"),
        }

        let dep = manifest("ldk-node", "native", "1.2.3");
        let different = CheckoutMatch::Different {
            dep_rev: "aaaaaaaaaaaaaaaa".into(),
            builtin_rev: "bbbbbbbbbbbbbbbb".into(),
        };
        match sideload_decision(&dep, Some(&resident), || different.clone(), false) {
            SideloadDecision::Load(Some(note)) => {
                assert!(note.contains("bbbbbbbbbbbb") && note.contains("aaaaaaaaaaaa"), "{note}")
            }
            other => panic!("expected Load(Some), got {other:?}"),
        }
    }

    #[test]
    fn bun_apps_and_unknown_apps_keep_the_existing_hot_reload_path() {
        let bun = manifest("contest", "bun", "2.0.0");
        let resident = loaded("2.0.0", "active", "subprocess", "apt");
        assert_eq!(
            sideload_decision(&bun, Some(&resident), never_checked, false),
            SideloadDecision::Load(None)
        );
        // Even with the wide flag: it only ever touches native deps.
        assert_eq!(
            sideload_decision(&bun, Some(&resident), never_checked, true),
            SideloadDecision::Load(None)
        );
        let native = manifest("esp32-bridge", "native", "0.1.0");
        assert_eq!(
            sideload_decision(&native, None, never_checked, false),
            SideloadDecision::Load(None)
        );
        // The daemon says subprocess → its view wins over the staged manifest.
        let as_subprocess = loaded("0.1.0", "active", "subprocess", "apt");
        assert_eq!(
            sideload_decision(&native, Some(&as_subprocess), never_checked, false),
            SideloadDecision::Load(None)
        );
        // Not resident (stopped / errored / only installed) → load it.
        for status in ["stopped", "error", "installed", "awaiting_approval"] {
            let gone = loaded("0.1.0", status, "in_process", "bundled");
            assert_eq!(
                sideload_decision(&native, Some(&gone), never_checked, false),
                SideloadDecision::Load(None),
                "{status}"
            );
        }
    }

    #[test]
    fn an_app_already_flagged_requires_restart_is_reported_not_retried() {
        let dep = manifest("notifications", "native", "0.9.0");
        let flagged = loaded("0.9.0", "requires_restart", "in_process", "bundled");
        assert!(matches!(
            sideload_decision(&dep, Some(&flagged), never_checked, false),
            SideloadDecision::RestartRequired(_)
        ));
    }

    #[test]
    fn the_wide_flag_skips_every_loaded_native_regardless_of_version() {
        let dep = manifest("ldk-node", "native", "9.9.9");
        let resident = loaded("1.2.3", "active", "in_process", "bundled");
        match sideload_decision(&dep, Some(&resident), never_checked, true) {
            SideloadDecision::Skip(reason) => assert!(reason.contains("--no-sideload-native-builtins")),
            other => panic!("expected Skip, got {other:?}"),
        }
    }

    #[test]
    fn restart_class_errors_are_recognised() {
        assert!(is_restart_class_error(
            "daemon RPC error -32603: Native app 'notifications' requires a node restart before another native app can load",
            true
        ));
        assert!(is_restart_class_error(
            "daemon RPC error -32603: native app 'ldk-node' requires a node restart before reload",
            true
        ));
        assert!(is_restart_class_error("unload of 'ldk-node' timed out after 5s", true));
        assert!(!is_restart_class_error("unload of 'contest' timed out after 5s", false));
        assert!(!is_restart_class_error(
            "daemon RPC error -32602: tier validation refused dev_load of 'x'",
            true
        ));
    }

    /// Builtin dirs are not uniformly named (`modules/ldk-node` vs
    /// `modules/node-app-notifications`); the lookup must find both and must
    /// match on manifest name, not directory name.
    #[test]
    fn builtin_checkout_lookup_handles_both_directory_conventions() {
        let tmp = TempDir::new().unwrap();
        let modules = tmp.path().join("modules");
        for (dir, name) in [
            ("ldk-node", "ldk-node"),
            ("node-app-notifications", "notifications"),
            ("some-other-dir", "terminal"),
        ] {
            let d = modules.join(dir);
            fs::create_dir_all(&d).unwrap();
            fs::write(
                d.join("manifest.json"),
                serde_json::json!({ "name": name, "version": "1.0.0", "app_type": "native" }).to_string(),
            )
            .unwrap();
        }
        // A directory whose NAME matches but whose manifest says otherwise is
        // not the builtin.
        let decoy = modules.join("observability");
        fs::create_dir_all(&decoy).unwrap();
        fs::write(
            decoy.join("manifest.json"),
            serde_json::json!({ "name": "not-observability", "version": "1.0.0", "app_type": "native" }).to_string(),
        )
        .unwrap();

        assert_eq!(builtin_checkout_for(&modules, "ldk-node"), Some(modules.join("ldk-node")));
        assert_eq!(
            builtin_checkout_for(&modules, "notifications"),
            Some(modules.join("node-app-notifications"))
        );
        assert_eq!(builtin_checkout_for(&modules, "terminal"), Some(modules.join("some-other-dir")));
        assert_eq!(builtin_checkout_for(&modules, "observability"), None);
        assert_eq!(builtin_checkout_for(&modules, "missing"), None);
    }

    #[test]
    fn checkout_match_is_same_path_for_the_builtin_dir_itself_and_unknown_without_one() {
        let tmp = TempDir::new().unwrap();
        let modules = tmp.path().join("modules");
        let ldk = modules.join("ldk-node");
        fs::create_dir_all(&ldk).unwrap();
        fs::write(
            ldk.join("manifest.json"),
            serde_json::json!({ "name": "ldk-node", "version": "1.0.0", "app_type": "native" }).to_string(),
        )
        .unwrap();
        assert_eq!(checkout_match(&ldk, Some(&modules), "ldk-node"), CheckoutMatch::SamePath);
        assert_eq!(checkout_match(&ldk, None, "ldk-node"), CheckoutMatch::Unknown);
        // A different, non-git directory: neither side has a rev → Unknown.
        let elsewhere = tmp.path().join("elsewhere");
        fs::create_dir_all(&elsewhere).unwrap();
        assert_eq!(checkout_match(&elsewhere, Some(&modules), "ldk-node"), CheckoutMatch::Unknown);
    }
}