node-app-build 6.5.0

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
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
//! `--daemon monorepo` mode: launch the daemon from a checked-out copy of
//! `econ-v1/node`. Lets platform contributors edit BOTH app code AND
//! daemon code in a single inner-loop iteration.
//!
//! The CLI verifies the path is a workspace containing the `node-server`
//! crate, generates a per-(monorepo, instance) env file under
//! `$XDG_CACHE_HOME/node-app/monorepo-<hash>/`, and spawns
//! `cargo run -p node-server -- --env <env>` as a child process.
//!
//! The hash covers both the monorepo path AND the instance name so that
//! running alice and bob simultaneously does not collide on socket or db.
//!
//! When `log_tx` is `Some` (TUI active), the daemon and UI dev server
//! stdout/stderr are captured, prefixed with `[<instance>]`, and piped
//! into the split-pane log view instead of being inherited.

use std::collections::hash_map::DefaultHasher;
use std::fs;
use std::hash::{Hash, Hasher};
use std::io::BufRead;
use std::os::unix::net::UnixStream;
#[cfg(unix)]
use std::os::unix::process::CommandExt;
use std::path::{Path, PathBuf};
use std::process::{Child, Command, Stdio};
use std::sync::{Mutex, OnceLock};
use std::time::{Duration, Instant};

use anyhow::{anyhow, bail, Context, Result};
#[cfg(unix)]
use libc;
use serde_json;

use super::{DaemonHandle, DaemonHost, InstanceProfile};
use crate::tui::{self, LogSource, LogTx, ServiceStatus, TuiEvent};

// Bumped from 120s to 240s: cold cargo run can include a non-trivial link
// step + multi-app inotify scan, especially in multi-instance platform mode
// where alice and bob compete for the page cache.
const HEALTH_TIMEOUT: Duration = Duration::from_secs(240);
const HEALTH_POLL: Duration = Duration::from_secs(2);

/// Max time we'll wait for the daemon's HTTP server to answer /api/healthz
/// after the IPC socket comes up. Distinct from `HEALTH_TIMEOUT` because the
/// IPC socket can be live before axum binds the TCP port — a window where a
/// browser-loaded Vite proxy would fail with "connection refused".
const HTTP_READY_TIMEOUT: Duration = Duration::from_secs(60);

/// Max time we'll wait for Vite to bind its UI port and respond to a smoke
/// test through the proxy. Vite startup is typically 1–3s; 30s leaves margin
/// for cold node_modules / vite optimizer runs without hanging the TUI.
const VITE_READY_TIMEOUT: Duration = Duration::from_secs(30);

/// Return PIDs of processes listening on `port` (TCP, LISTEN state). Used to
/// reap stale Vite / daemon orphans before we try to bind. On non-unix or
/// when `lsof` is unavailable this returns an empty Vec (degrading to a
/// "best effort" cleanup — the subsequent spawn will simply fail loudly on
/// EADDRINUSE).
#[cfg(unix)]
fn pids_listening_on(port: u16) -> Vec<i32> {
    let arg = format!("-iTCP:{port}");
    Command::new("lsof")
        .args(["-sTCP:LISTEN", "-t", "-P", "-n", &arg])
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::null())
        .output()
        .ok()
        .filter(|o| o.status.success())
        .map(|o| {
            String::from_utf8_lossy(&o.stdout)
                .lines()
                .filter_map(|l| l.trim().parse::<i32>().ok())
                .collect()
        })
        .unwrap_or_default()
}

#[cfg(not(unix))]
fn pids_listening_on(_port: u16) -> Vec<i32> {
    Vec::new()
}

/// Tee a child stdio stream three ways: persistent log file (if open), TUI
/// sink (if active), and the controlling terminal (when no TUI). Each output
/// line is prefixed with the instance name so multi-instance log files stay
/// distinguishable on shared display paths.
fn tee_daemon_stream<R: std::io::Read + Send + 'static>(
    reader: R,
    prefix: String,
    log_file: Option<std::sync::Arc<std::sync::Mutex<std::fs::File>>>,
    tui_tx: Option<LogTx>,
    is_stderr: bool,
) {
    use std::io::Write as _;
    std::thread::spawn(move || {
        for line in std::io::BufReader::new(reader).lines().map_while(Result::ok) {
            let formatted = format!("{prefix}{line}");

            if let Some(file) = &log_file {
                if let Ok(mut f) = file.lock() {
                    let _ = writeln!(f, "{formatted}");
                }
            }
            if let Some(tx) = &tui_tx {
                let _ = tx.send(TuiEvent::Log(crate::tui::LogEntry {
                    source: LogSource::Daemon,
                    line: formatted,
                }));
            } else if is_stderr {
                eprintln!("{formatted}");
            } else {
                println!("{formatted}");
            }
        }
    });
}

/// Port offset applied to every instance's HTTP/HTTPS/UI/OTA/LDK-P2P port
/// when `--client-node` is set, so a PWA dev session can run isolated from
/// (and even alongside) a legacy `node-app dev` for the same instance name
/// without EADDRINUSE. Chosen so `alice --client-node` (http=3301) doesn't
/// collide with `bob` (http=3002) either. The LDK P2P port is fixed by the
/// instance's base env file (`LDK_LISTENING_ADDRESS` in alice.env/bob.env),
/// but `ensure_running()` writes a `LDK_LISTENING_ADDRESS` override derived
/// from `InstanceProfile::p2p_port` (offset here, same as the other ports)
/// so the two lanes don't contend for it (see #1529).
const CLIENT_NODE_PORT_OFFSET: u16 = 300;

pub struct MonorepoHost {
    monorepo_path: PathBuf,
    profile: InstanceProfile,
    socket_override: Option<PathBuf>,
    dev_dir_override: Option<PathBuf>,
    log_tx: Option<LogTx>,
    /// Serve the client-node PWA instead of the legacy `system/ui` bundle and
    /// isolate its ports. Platform dependency selection remains shared with
    /// normal mode and is completed by `platform::run` before this host exists.
    client_node: bool,
    child: Mutex<Option<Child>>,
    ui_child: Mutex<Option<Child>>,
    /// Env file path saved by ensure_running() so restart() can respawn.
    env_file: Mutex<Option<PathBuf>>,
}

impl MonorepoHost {
    pub fn new(
        monorepo_path: PathBuf,
        profile: InstanceProfile,
        socket_override: Option<PathBuf>,
        dev_dir_override: Option<PathBuf>,
        log_tx: Option<LogTx>,
        client_node: bool,
    ) -> Self {
        // Isolate the client-node PWA lane from a legacy dev session for the
        // same instance name: distinct display name (also namespaces the
        // per-(monorepo, instance) cache dir via monorepo_env_dir, since
        // that hash covers `profile.name`) + offset ports.
        let profile = if client_node {
            InstanceProfile {
                name: format!("{}-pwa", profile.name),
                http_port: profile.http_port + CLIENT_NODE_PORT_OFFSET,
                https_port: profile.https_port + CLIENT_NODE_PORT_OFFSET,
                p2p_port: profile.p2p_port + CLIENT_NODE_PORT_OFFSET,
                ui_port: profile.ui_port + CLIENT_NODE_PORT_OFFSET,
                env_file_name: profile.env_file_name,
            }
        } else {
            profile
        };
        Self {
            monorepo_path,
            profile,
            socket_override,
            dev_dir_override,
            log_tx,
            client_node,
            child: Mutex::new(None),
            ui_child: Mutex::new(None),
            env_file: Mutex::new(None),
        }
    }

    fn syslog(&self, msg: impl Into<String>) {
        tui::sys_log(self.log_tx.as_ref(), msg);
    }

    /// Spawn daemon child with stdio wired to:
    ///   1. A persistent log file at `<env_dir>/daemon.log` (always)
    ///   2. The TUI sink (when active)
    ///   3. stdout/stderr inheritance (when no TUI is attached)
    ///
    /// Persistence is the important one — without it, daemon output is lost
    /// the moment the TUI exits, which makes diagnosing startup failures
    /// (the "daemon did not come up within Ns" error) almost impossible.
    ///
    /// We exec the built binary at `target/debug/node-server` directly
    /// instead of `cargo run -p node-server`. The earlier `cargo build`
    /// step already produced that binary, and `cargo run` would otherwise
    /// re-acquire the build lock — which contends with stray cargo
    /// processes (rust-analyzer, leftover daemons from cancelled runs) and
    /// is exactly what caused the silent "Blocking waiting for file lock
    /// on build directory" hangs that manifested as health-check timeouts.
    fn spawn_daemon(&self, env_file: &Path) -> Result<Child> {
        let binary_path = self.monorepo_path.join("target/debug/node-server");
        if !binary_path.exists() {
            bail!(
                "daemon binary missing at {} — the earlier `cargo build -p node-server` \
                 step should have produced it. Run `cargo build -p node-server \
                 --features agentic_payments` in {} to recover.",
                binary_path.display(),
                self.monorepo_path.display()
            );
        }
        let mut cmd = Command::new(&binary_path);
        cmd.args(["--env"])
            .arg(env_file)
            .current_dir(&self.monorepo_path)
            .stdin(Stdio::null())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped());

        #[cfg(unix)]
        cmd.process_group(0);

        let mut child = cmd
            .spawn()
            .with_context(|| format!("spawn {}", binary_path.display()))?;

        // Open daemon.log next to the env file. Best-effort: failure to open
        // (e.g. permission denied) only loses persistence; we still tee to
        // TUI/terminal. Truncate on each spawn so the file always reflects
        // the *current* run rather than accumulating across restarts.
        let log_file_path = env_file
            .parent()
            .map(|d| d.join("daemon.log"))
            .unwrap_or_else(|| PathBuf::from("daemon.log"));
        let log_file: Option<std::sync::Arc<std::sync::Mutex<std::fs::File>>> =
            std::fs::OpenOptions::new()
                .create(true)
                .write(true)
                .truncate(true)
                .open(&log_file_path)
                .ok()
                .map(|f| std::sync::Arc::new(std::sync::Mutex::new(f)));
        if log_file.is_some() {
            self.syslog(format!("→ daemon log: {}", log_file_path.display()));
        } else {
            self.syslog(format!(
                "⚠ could not open daemon log file at {} — output will only show in TUI/terminal",
                log_file_path.display()
            ));
        }

        let prefix = format!("[{}] ", self.profile.name);
        if let Some(stdout) = child.stdout.take() {
            tee_daemon_stream(
                stdout,
                prefix.clone(),
                log_file.clone(),
                self.log_tx.clone(),
                false,
            );
        }
        if let Some(stderr) = child.stderr.take() {
            tee_daemon_stream(stderr, prefix, log_file, self.log_tx.clone(), true);
        }

        Ok(child)
    }

    /// Spawn UI dev server with stdio wired to TUI or terminal.
    ///
    /// Skipped entirely in `--client-node` mode: the client-node PWA has no
    /// Vite HMR dev server in this loop yet — it's served statically by the
    /// daemon itself from `CLIENT_NODE_PWA_STATIC_DIR_PATH`
    /// (`system/pwa/dist`), the same "backend-served" fallback path the
    /// legacy UI also supports (see the log line at the bottom of this
    /// method). Spawning the legacy `system/ui` Vite server here would also
    /// defeat the isolation `--client-node` is for.
    fn spawn_ui(&self) -> Option<Child> {
        if self.client_node {
            return None;
        }
        let ui_dir = self.monorepo_path.join("system/ui");
        if !ui_dir.join("package.json").exists() {
            return None;
        }
        let yarn = if which_bin("yarn") { "yarn" } else { "npm" };
        let ui_port = self.profile.ui_port;
        let api_port = self.profile.http_port;
        self.syslog(format!(
            "→ starting UI dev server ({yarn} dev --port {ui_port}) in {}",
            ui_dir.display()
        ));

        let mut cmd = Command::new(yarn);
        cmd.args(["dev", "--port", &ui_port.to_string()])
            .env("VITE_BACKEND_PORT", api_port.to_string())
            .current_dir(&ui_dir)
            .stdin(Stdio::null());

        if self.log_tx.is_some() {
            cmd.stdout(Stdio::piped()).stderr(Stdio::piped());
        } else {
            cmd.stdout(Stdio::inherit()).stderr(Stdio::inherit());
        }

        #[cfg(unix)]
        cmd.process_group(0);

        match cmd.spawn() {
            Ok(mut child) => {
                if let Some(tx) = &self.log_tx {
                    let prefix = format!("[{}] ", self.profile.name);
                    if let Some(stdout) = child.stdout.take() {
                        let tx = tx.clone();
                        let p = prefix.clone();
                        std::thread::spawn(move || {
                            for line in std::io::BufReader::new(stdout).lines().map_while(Result::ok) {
                                let _ = tx.send(TuiEvent::Log(crate::tui::LogEntry {
                                    source: LogSource::UiServer,
                                    line: format!("{p}{line}"),
                                }));
                            }
                        });
                    }
                    if let Some(stderr) = child.stderr.take() {
                        let tx = tx.clone();
                        let p = prefix.clone();
                        std::thread::spawn(move || {
                            for line in std::io::BufReader::new(stderr).lines().map_while(Result::ok) {
                                let _ = tx.send(TuiEvent::Log(crate::tui::LogEntry {
                                    source: LogSource::UiServer,
                                    line: format!("{p}{line}"),
                                }));
                            }
                        });
                    }
                }
                tui::update_status(
                    self.log_tx.as_ref(),
                    LogSource::UiServer,
                    ServiceStatus::Ready,
                    Some(format!("[{}] http://localhost:{ui_port}", self.profile.name)),
                );
                self.syslog(format!(
                    "✓ UI available at http://localhost:{ui_port} (Vite, hot reload) \
                     or http://localhost:{api_port} (backend-served, requires `yarn build` in system/ui)"
                ));
                Some(child)
            }
            Err(e) => {
                self.syslog(format!(
                    "⚠ could not start UI dev server: {e} — run manually: \
                     cd system/ui && VITE_BACKEND_PORT={api_port} {yarn} dev --port {ui_port}"
                ));
                tui::update_status(
                    self.log_tx.as_ref(),
                    LogSource::UiServer,
                    ServiceStatus::Disabled,
                    Some(format!("[{}]", self.profile.name)),
                );
                None
            }
        }
    }

    fn shutdown_daemon_only(&self) {
        if let Some(mut child) = self.child.lock().unwrap().take() {
            let pid = child.id() as i32;
            #[cfg(unix)]
            unsafe {
                libc::kill(-pid, libc::SIGTERM);
            }
            let t = Instant::now();
            loop {
                match child.try_wait() {
                    Ok(Some(_)) => break,
                    Ok(None) if t.elapsed() > Duration::from_secs(10) => {
                        #[cfg(unix)]
                        unsafe {
                            libc::kill(-pid, libc::SIGKILL);
                        }
                        let _ = child.wait();
                        break;
                    }
                    Ok(None) => std::thread::sleep(Duration::from_millis(200)),
                    Err(_) => break,
                }
            }
        }
    }
}

impl MonorepoHost {
    /// Reap any process listening on `port` (best-effort SIGTERM, escalating
    /// to SIGKILL after `grace`). Logged as "freeing <label>" so the TUI
    /// makes it obvious *which* port was contested.
    ///
    /// This is the antidote to the most common "node-app dev doesn't work"
    /// failure mode: a stale Vite or orphaned `node-server` from a previous
    /// run is still bound to the port the new launch wants, and the new
    /// process silently picks a different port (Vite) or fails to bind
    /// (axum) — either way the UI ends up calling a daemon that isn't there.
    #[cfg(unix)]
    fn free_port(&self, port: u16, label: &str) {
        let pids = pids_listening_on(port);
        if pids.is_empty() {
            return;
        }
        self.syslog(format!(
            "→ freeing {label} port {port} from stale pid(s) {}",
            pids.iter()
                .map(i32::to_string)
                .collect::<Vec<_>>()
                .join(",")
        ));
        for pid in &pids {
            unsafe {
                libc::kill(*pid, libc::SIGTERM);
            }
        }
        let deadline = Instant::now() + Duration::from_secs(5);
        while Instant::now() < deadline {
            if pids_listening_on(port).is_empty() {
                self.syslog(format!("{label} port {port} freed"));
                return;
            }
            std::thread::sleep(Duration::from_millis(200));
        }
        let remaining = pids_listening_on(port);
        if !remaining.is_empty() {
            self.syslog(format!(
                "{label} port {port} still held after SIGTERM — escalating to SIGKILL"
            ));
            for pid in &remaining {
                unsafe {
                    libc::kill(*pid, libc::SIGKILL);
                }
            }
        }
    }

    #[cfg(not(unix))]
    fn free_port(&self, _port: u16, _label: &str) {}

    /// Force the dev daemon onto plain HTTP for this run by pinning
    /// `settings.ssl_enabled = 'false'` in the per-instance dev DB before boot.
    ///
    /// node-app dev's readiness probe (`wait_http_ready`) and the Vite proxy
    /// both target the daemon's plain-HTTP `SERVER_ADDRESS` port. When the
    /// persisted dev DB has `ssl_enabled = 'true'` (e.g. a cert was provisioned
    /// in an earlier run), the daemon serves the API over HTTPS and the HTTP
    /// port becomes a redirect-only listener — so readiness never passes.
    ///
    /// Best-effort: a missing DB / `settings` table is fine (a fresh DB
    /// defaults to `ssl_enabled = 'false'`); we never fail the run over it.
    fn force_dev_http_only(&self, db_path: &Path) {
        if !db_path.exists() {
            return;
        }
        let conn = match rusqlite::Connection::open(db_path) {
            Ok(c) => c,
            Err(e) => {
                self.syslog(format!("⚠ could not open dev DB to pin HTTP: {e}"));
                return;
            }
        };
        let has_settings = conn
            .query_row(
                "SELECT 1 FROM sqlite_master WHERE type='table' AND name='settings'",
                [],
                |_| Ok(()),
            )
            .is_ok();
        if !has_settings {
            return;
        }
        match conn.execute(
            "UPDATE settings SET value='false' WHERE key='ssl_enabled' AND value!='false'",
            [],
        ) {
            Ok(n) if n > 0 => self
                .syslog("✓ pinned dev daemon to HTTP (ssl_enabled=false in dev DB)".to_string()),
            Ok(_) => {}
            Err(e) => self.syslog(format!("⚠ could not pin ssl_enabled=false: {e}")),
        }
    }

    /// Block until `http://127.0.0.1:<port>/api/healthz` answers (any status
    /// below 500 counts — we only care that the listener is up and routing).
    /// Returns Err on timeout so the caller can refuse to spawn Vite and
    /// surface a useful failure rather than letting the browser hit a dead
    /// proxy target.
    fn wait_http_ready(&self, port: u16) -> Result<()> {
        let url = format!("http://127.0.0.1:{port}/api/healthz");
        let started = Instant::now();
        self.syslog(format!("→ waiting for daemon HTTP on {url}"));
        loop {
            // ureq treats any HTTP status >= 400 as an Err — but for a
            // readiness check we want to accept those too (the listener is
            // up, that's what matters). Match both Ok and Err(Status).
            let ready = match ureq::get(&url)
                .timeout(Duration::from_secs(2))
                .call()
            {
                Ok(_) => true,
                Err(ureq::Error::Status(code, _)) => code < 500,
                Err(_) => false,
            };
            if ready {
                self.syslog(format!(
                    "✓ daemon HTTP ready ({}ms)",
                    started.elapsed().as_millis()
                ));
                return Ok(());
            }
            if let Some(child) = self.child.lock().unwrap().as_mut() {
                if let Ok(Some(status)) = child.try_wait() {
                    bail!(
                        "daemon exited with {status} while waiting for HTTP readiness on {url}"
                    );
                }
            }
            if started.elapsed() >= HTTP_READY_TIMEOUT {
                bail!(
                    "daemon HTTP server not responding on {} after {}s",
                    url,
                    HTTP_READY_TIMEOUT.as_secs()
                );
            }
            std::thread::sleep(Duration::from_millis(300));
        }
    }

    /// Verify the Vite WebSocket proxy by speaking raw HTTP upgrade and
    /// checking for `HTTP/1.1 101`. This catches path-mismatch bugs
    /// (frontend `/ws` vs backend `/api/ws`) that otherwise only surface as
    /// noisy ECONNRESET loops in the Vite log.
    fn verify_ws_proxy(&self, ui_port: u16) -> Result<()> {
        use std::io::{Read, Write};
        use std::net::TcpStream;
        // Vite usually binds IPv6 on macOS; resolve via the OS so we hit
        // whichever family it picked.
        let addr_candidates: Vec<std::net::SocketAddr> = std::net::ToSocketAddrs::to_socket_addrs(
            &format!("localhost:{ui_port}"),
        )
        .map(|iter| iter.collect())
        .unwrap_or_default();
        if addr_candidates.is_empty() {
            bail!("could not resolve localhost:{ui_port} for WS probe");
        }
        let req = format!(
            "GET /api/ws HTTP/1.1\r\n\
             Host: localhost:{ui_port}\r\n\
             Upgrade: websocket\r\n\
             Connection: Upgrade\r\n\
             Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n\
             Sec-WebSocket-Version: 13\r\n\
             \r\n"
        );
        let mut last_err = String::from("no candidate addresses tried");
        for addr in &addr_candidates {
            match TcpStream::connect_timeout(addr, Duration::from_secs(2)) {
                Ok(mut sock) => {
                    let _ = sock.set_read_timeout(Some(Duration::from_secs(2)));
                    let _ = sock.write_all(req.as_bytes());
                    let mut buf = [0u8; 256];
                    match sock.read(&mut buf) {
                        Ok(n) if n > 0 => {
                            let response = String::from_utf8_lossy(&buf[..n]);
                            let first_line =
                                response.lines().next().unwrap_or("").to_string();
                            if first_line.contains("101") {
                                self.syslog(format!(
                                    "✓ ws proxy verified: localhost:{ui_port}/api/ws → backend ({first_line})"
                                ));
                                return Ok(());
                            }
                            last_err = format!(
                                "{addr} replied {first_line} (expected 101 Switching Protocols)"
                            );
                        }
                        Ok(_) => last_err = format!("{addr} closed without responding"),
                        Err(e) => last_err = format!("{addr} read: {e}"),
                    }
                }
                Err(e) => last_err = format!("{addr} connect: {e}"),
            }
        }
        bail!("ws proxy probe failed: {last_err}");
    }

    /// Smoke-test the Vite proxy by issuing `/api/healthz` against the UI
    /// port and verifying we get a backend status (anything < 500 — the
    /// proxy forwarded successfully). Emits a clear ✓ or ⚠ line so the
    /// developer can tell at a glance whether the `/api` lane works.
    ///
    /// We try `localhost` first (which resolves to whichever family Vite
    /// bound — Vite 5+ defaults to IPv6 `::1` on macOS) and fall back to
    /// `127.0.0.1` then `[::1]` so a misconfigured /etc/hosts doesn't make
    /// us report a false negative.
    fn verify_proxy(&self, ui_port: u16, http_port: u16) -> Result<()> {
        let urls = [
            format!("http://localhost:{ui_port}/api/healthz"),
            format!("http://127.0.0.1:{ui_port}/api/healthz"),
            format!("http://[::1]:{ui_port}/api/healthz"),
        ];
        let started = Instant::now();
        let mut last_err = String::new();
        loop {
            for url in &urls {
                match ureq::get(url).timeout(Duration::from_secs(2)).call() {
                    Ok(resp) => {
                        self.syslog(format!(
                            "✓ proxy verified: {url} → 127.0.0.1:{http_port} (status {})",
                            resp.status()
                        ));
                        return Ok(());
                    }
                    Err(ureq::Error::Status(code, _)) if code < 500 => {
                        self.syslog(format!(
                            "✓ proxy verified: {url} → 127.0.0.1:{http_port} (status {code})"
                        ));
                        return Ok(());
                    }
                    Err(e) => last_err = format!("{url}: {e}"),
                }
            }
            if started.elapsed() >= VITE_READY_TIMEOUT {
                bail!(
                    "vite proxy unreachable on port {ui_port} after {}s (last: {last_err}) — \
                     check that VITE_BACKEND_PORT was set when vite started, \
                     and that the daemon is listening on 127.0.0.1:{http_port}",
                    VITE_READY_TIMEOUT.as_secs()
                );
            }
            std::thread::sleep(Duration::from_millis(400));
        }
    }

    /// Run a build command, streaming stderr to the TUI log (or to the
    /// terminal when no TUI is active).  Returns the exit status and all
    /// stderr lines collected — callers include them in error messages.
    fn run_build_cmd(
        &self,
        cmd: &mut Command,
        log_source: LogSource,
    ) -> Result<(std::process::ExitStatus, Vec<String>)> {
        use std::sync::mpsc;

        cmd.stdout(Stdio::null()).stderr(Stdio::piped());
        let mut child = cmd.spawn()?;
        let stderr = child.stderr.take().expect("piped");

        let log_tx = self.log_tx.clone();
        let (tx, rx) = mpsc::channel::<Vec<String>>();
        std::thread::spawn(move || {
            let mut lines = Vec::new();
            for line in std::io::BufReader::new(stderr).lines().map_while(Result::ok) {
                if let Some(ref ltx) = log_tx {
                    let _ = ltx.send(TuiEvent::Log(crate::tui::LogEntry {
                        source: log_source,
                        line: line.clone(),
                    }));
                } else {
                    eprintln!("{line}");
                }
                lines.push(line);
            }
            let _ = tx.send(lines);
        });

        let status = loop {
            match child.try_wait()? {
                Some(s) => break s,
                None => {
                    if crate::commands::dev::is_cancelled() {
                        let _ = child.kill();
                        let _ = child.wait();
                        let _lines = rx.recv().unwrap_or_default();
                        bail!("build cancelled");
                    }
                    std::thread::sleep(Duration::from_millis(50));
                }
            }
        };
        let lines = rx.recv().unwrap_or_default();
        Ok((status, lines))
    }
}


/// External control request, one JSON object per file. Today only
/// `action: "restart"` (optionally `build: "system"`) exists; the envelope
/// leaves room for more actions without a schema break.
#[derive(Debug, serde::Deserialize)]
pub struct ControlRequest {
    pub action: String,
    #[serde(default)]
    pub build: Option<String>,
    #[serde(default)]
    pub ts: u64,
}

impl DaemonHost for MonorepoHost {
    /// This instance's name (e.g. "alice") for log labels.
    fn instance_name(&self) -> &str {
        &self.profile.name
    }

    /// Rebuild the daemon binary (`cargo build -p node-server`) WITHOUT
    /// touching the running process — a follow-up `restart()` spawns the
    /// fresh binary. Used by the external `node-app restart --build` path.
    fn rebuild_daemon_binary(&self) -> Result<()> {
        // Delete first: relinking over the executable file of a live process
        // trips the macOS linker (same reason ensure_running deletes it).
        // The running daemon keeps its open inode either way.
        let binary_path = self.monorepo_path.join("target/debug/node-server");
        if binary_path.exists() {
            let _ = fs::remove_file(&binary_path);
        }
        self.syslog("→ rebuilding daemon: cargo build -p node-server");
        tui::update_status(
            self.log_tx.as_ref(),
            LogSource::Daemon,
            ServiceStatus::Building,
            Some("cargo build (external request)".into()),
        );
        let (status, errors) = self
            .run_build_cmd(
                Command::new("cargo")
                    .args(["build", "-p", "node-server", "--features", "agentic_payments"])
                    .current_dir(&self.monorepo_path)
                    .stdin(Stdio::null()),
                LogSource::Daemon,
            )
            .with_context(|| "spawn `cargo build -p node-server`")?;
        if !status.success() {
            tui::update_status(
                self.log_tx.as_ref(),
                LogSource::Daemon,
                ServiceStatus::Failed("cargo build failed".into()),
                None,
            );
            let detail = if errors.is_empty() {
                String::new()
            } else {
                format!("\n\n{}", errors.join("\n"))
            };
            bail!("cargo build -p node-server failed (exit {}){detail}", status);
        }
        Ok(())
    }

    /// Consume a pending external control request (written by
    /// `node-app restart` into `<env_dir>/control/request.json`). The file is
    /// deleted BEFORE acting so a slow handler can't double-fire.
    fn take_control_request(&self) -> Option<ControlRequest> {
        let env_dir = monorepo_env_dir(&self.monorepo_path, &self.profile.name).ok()?;
        let path = env_dir.join("control/request.json");
        let text = fs::read_to_string(&path).ok()?;
        let _ = fs::remove_file(&path);
        match serde_json::from_str::<ControlRequest>(&text) {
            Ok(req) => Some(req),
            Err(e) => {
                self.syslog(format!("⚠ ignoring malformed control request: {e}"));
                None
            }
        }
    }

    /// Report the outcome of an external control request. `ts` echoes the
    /// request's timestamp so the waiting CLI can match its own request.
    fn write_control_result(&self, ts: u64, ok: bool, message: &str) {
        let Ok(env_dir) = monorepo_env_dir(&self.monorepo_path, &self.profile.name) else {
            return;
        };
        let dir = env_dir.join("control");
        let _ = fs::create_dir_all(&dir);
        let body = serde_json::json!({ "ts": ts, "ok": ok, "message": message });
        let tmp = dir.join("last-result.json.tmp");
        if fs::write(&tmp, body.to_string()).is_ok() {
            let _ = fs::rename(&tmp, dir.join("last-result.json"));
        }
    }

    fn ensure_running(&self) -> Result<DaemonHandle> {
        // 1. Validate the path looks like the node monorepo.
        let cargo_toml = self.monorepo_path.join("Cargo.toml");
        if !cargo_toml.exists() {
            bail!(
                "{} doesn't look like a monorepo root (no Cargo.toml found)",
                self.monorepo_path.display()
            );
        }
        let manifest = fs::read_to_string(&cargo_toml)
            .with_context(|| format!("read {}", cargo_toml.display()))?;
        let has_server = manifest.contains("\"system/server\"")
            || manifest.contains("system/server")
            || manifest.contains("\"apps/server\"")
            || manifest.contains("apps/server");
        if !has_server {
            bail!(
                "{}/Cargo.toml does not include 'system/server' — is this the right path?",
                self.monorepo_path.display()
            );
        }

        // 2. Resolve cache dir (namespaced by monorepo path + instance name).
        let env_dir = monorepo_env_dir(&self.monorepo_path, &self.profile.name)?;
        fs::create_dir_all(&env_dir).ok();
        let pid_file = env_dir.join("daemon.pid");

        // 2a. Kill any previous instance.
        if let Ok(contents) = fs::read_to_string(&pid_file) {
            if let Ok(old_pid) = contents.trim().parse::<i32>() {
                let alive = unsafe { libc::kill(old_pid, 0) == 0 };
                if alive {
                    self.syslog(format!(
                        "→ previous instance found (PID {old_pid}), sending SIGTERM…"
                    ));
                    unsafe {
                        libc::kill(-old_pid, libc::SIGTERM);
                    }
                    let deadline = Instant::now();
                    loop {
                        std::thread::sleep(Duration::from_millis(200));
                        if unsafe { libc::kill(old_pid, 0) } != 0 {
                            self.syslog(format!(
                                "✓ previous instance exited ({}ms)",
                                deadline.elapsed().as_millis()
                            ));
                            break;
                        }
                        if deadline.elapsed() > Duration::from_secs(15) {
                            self.syslog("⚠ previous instance did not exit after 15s, SIGKILL");
                            unsafe {
                                libc::kill(-old_pid, libc::SIGKILL);
                            }
                            break;
                        }
                    }
                }
                let _ = fs::remove_file(&pid_file);
            }
        }

        // 2b. Belt-and-suspenders: reap any stray process still holding our
        // ports. Covers daemons started without writing a pid file (e.g.
        // `cargo run` from a separate shell), Vite servers left behind by a
        // killed `node-app dev`, and old `make dev-*` runs.
        self.free_port(self.profile.http_port, "backend");
        self.free_port(self.profile.https_port, "https");
        self.free_port(self.profile.ui_port, "ui");

        // 2c. Stale Vite pid file (mirrors the daemon.pid path above but
        // tracks the UI dev server, which we spawn in step 6).
        let vite_pid_file = env_dir.join("vite.pid");
        if let Ok(contents) = fs::read_to_string(&vite_pid_file) {
            if let Ok(old_pid) = contents.trim().parse::<i32>() {
                let alive = unsafe { libc::kill(old_pid, 0) == 0 };
                if alive {
                    self.syslog(format!(
                        "→ previous vite found (PID {old_pid}), sending SIGTERM…"
                    ));
                    unsafe {
                        libc::kill(-old_pid, libc::SIGTERM);
                    }
                }
            }
            let _ = fs::remove_file(&vite_pid_file);
        }

        let socket_path = self
            .socket_override
            .clone()
            .unwrap_or_else(|| env_dir.join("control.sock"));
        let dev_dir = self
            .dev_dir_override
            .clone()
            .unwrap_or_else(|| env_dir.join("dev-apps"));
        let db_path = env_dir.join("dev.db");
        fs::create_dir_all(&dev_dir).ok();

        // 3. Generate env file.
        // The instance-specific base env (alice.env / bob.env) is the
        // source of truth for everything except the per-instance isolation
        // paths and ports — bail clearly if the file is missing rather than
        // silently fall back to a near-empty env that leads to confusing
        // downstream failures.
        let env_file = env_dir.join("daemon.env");
        let base_env_path = self
            .monorepo_path
            .join("system/server")
            .join(&self.profile.env_file_name);
        if !base_env_path.exists() {
            bail!(
                "missing base env file for instance '{}' — expected {}.\n\
                 Create it (typically a copy of an example env), or pick a different \
                 instance via --instances.",
                self.profile.name,
                base_env_path.display()
            );
        }
        let base_env = fs::read_to_string(&base_env_path)
            .with_context(|| format!("read base env {}", base_env_path.display()))?;
        let log_dir = env_dir.join("logs");
        fs::create_dir_all(&log_dir).ok();
        let ldk_dir = env_dir.join("ldk_data");
        fs::create_dir_all(&ldk_dir).ok();
        let api_port = self.profile.http_port;
        // Point APT_APPS_DIR at the monorepo's `modules/` so the daemon loads
        // the built-in apps (ldk-node, core-storage, …) whose .dylib/.so was
        // staged there by `make builtin-apps`. Without this, the daemon falls
        // back to the production `/usr/lib/node/apps` path which is absent in
        // dev (especially on macOS), so no builtin capabilities ever register
        // and dep apps like `discovery` hit `capability.not_found` on every
        // `core.lightning.*` call.
        // Overrides we *must* inject because they depend on runtime values
        // the base env file can't know (cache-dir hash, monorepo path,
        // per-profile ports). Anything else — TLS settings, log verbosity,
        // bitcoin RPC, JWT secrets — comes from the base env file as
        // written. dotenvy::from_path (the server's env loader at
        // core/foundation/src/config.rs:170) is first-wins and never
        // overrides an already-set key, so writing overrides BEFORE the
        // base content is the only way they take effect.
        let apt_apps_dir = self.monorepo_path.join("modules");
        let static_dir = self.monorepo_path.join("system/ui/dist");
        let pwa_static_dir = self.monorepo_path.join("system/pwa/dist");
        let https_port = self.profile.https_port;
        let p2p_port = self.profile.p2p_port;
        let mut pairs: Vec<(&str, String, &str)> = vec![
            ("APT_APPS_DIR", apt_apps_dir.display().to_string(),
             "load builtin apps from the monorepo's modules/ instead of /usr/lib/node/apps"),
            ("NODE_DEV_APPS_DIR", dev_dir.display().to_string(),
             "stage dep apps into a per-instance cache dir so alice/bob don't collide"),
            ("DATABASE_URL", format!("sqlite://{}", db_path.display()),
             "per-instance dev DB under cache dir"),
            ("NODE_IPC_SOCKET", socket_path.display().to_string(),
             "per-instance IPC socket the orchestrator polls for readiness"),
            ("SERVER_ADDRESS", format!("0.0.0.0:{api_port}"),
             "profile-specific HTTP port (alice=3001, bob=3002, …) — bind 0.0.0.0 so peer-to-peer fetches via the LAN IP advertised through gossip resolve (loopback-only binding broke api_store catalog mirroring between alice and bob)"),
            ("HTTPS_SERVER_ADDRESS", format!("0.0.0.0:{https_port}"),
             "profile-specific HTTPS/TLS port (alice=4431, bob=4432, …) so two nodes don't both bind the default :443 and collide; the advertised port is derived from this, so peers resolve it via gossip"),
            ("LDK_LISTENING_ADDRESS", format!("127.0.0.1:{p2p_port}"),
             "profile-specific LDK P2P listen port (InstanceProfile::p2p_port, offset by CLIENT_NODE_PORT_OFFSET in --client-node mode) — without this override the daemon falls back to whatever LDK_LISTENING_ADDRESS the base env file hardcodes, so a --client-node lane and a legacy lane for the SAME instance would both try to bind the same LDK port (#1529)"),
            ("APPLICATION_LOG_DIR_PATH", log_dir.display().to_string(),
             "per-instance application logs under cache dir"),
            ("DATA_DIR_PATH", ldk_dir.display().to_string(),
             "per-instance LDK data dir under cache dir"),
            ("SIGNER_SEED_PATH", format!("{}/signer_seed.hex", ldk_dir.display()),
             "per-instance LDK signer seed under cache dir"),
            ("STATIC_DIR_PATH", static_dir.display().to_string(),
             "absolute path to monorepo/system/ui/dist so backend serves UI on its port"),
            ("NODE_ALLOW_DEV_SOCKET_PATH", "1".to_string(),
             "accept standalone socket paths outside /run/ (dev cache dirs aren't /run/-writable)"),
            ("AUTO_SELF_SIGNED_TLS", "false".to_string(),
             "keep the dev daemon on plain HTTP — the daemon otherwise auto-provisions a self-signed cert and sets ssl_enabled=true once it has a routable LAN IP, which makes the API HTTPS-only and turns the HTTP port (that node-app dev's health check + Vite proxy target) into a redirect-only listener. force_dev_http_only clears any stale flag; this stops it re-enabling on boot"),
            ("OTA_HTTP_PORT", (api_port + 10000).to_string(),
             "esp32-bridge's dedicated OTA HTTP listen port, per-instance (alice=13001, bob=13002). Its default (the node's main port, 3001) makes whichever node boots first squat the OTHER node's main port; the second node's pre-boot free_port(3001) then SIGTERMs the first node's whole daemon. Offset by 10000 so it never overlaps any instance's http/https/ui port (the ports free_port clears), so the two daemons can't kill each other"),
            ("ENABLE_TEST_HARNESS", "true".to_string(),
             "register the loopback-only /api/v2/internal/test/* routes (notably seed-peer). The harness cross-seeds each node's IP pool with the other's 127.0.0.1:<port> via POST /api/v2/internal/test/seed-peer; without this the route falls through to the SPA handler (HTML, not JSON) and the seed silently fails, so peer discovery finds no active HTTP endpoint and every inter-node flow (friend/conversation/L402 proxy — and cross-node trace propagation) breaks in the local harness"),
            ("NODE_HTTP_DIRECT_TCP", "true".to_string(),
             "node-server serves only over its Unix socket when fronted by node-provisioning (PR #1463); node-app dev runs the daemon alone, so bind TCP on SERVER_ADDRESS directly"),
        ];
        if self.client_node {
            // --client-node: serve system/pwa/dist instead of system/ui/dist.
            // select_static_assets_dir (core/adapters-system/src/runtime_bundles/build_app_state.rs)
            // picks CLIENT_NODE_PWA_STATIC_DIR_PATH over STATIC_DIR_PATH
            // whenever CLIENT_NODE_PWA_ENABLED is true — same seam production
            // boot reads, just pointed at a dev build. DEVELOPMENT_MODE=true
            // is required: parse_client_node_pwa_enabled
            // (core/foundation/src/config.rs) gates CLIENT_NODE_PWA_ENABLED
            // on is_development so the toggle can't be flipped in prod by env
            // var alone.
            pairs.push((
                "DEVELOPMENT_MODE",
                "true".to_string(),
                "required for CLIENT_NODE_PWA_ENABLED to take effect — parse_client_node_pwa_enabled gates on is_development",
            ));
            pairs.push((
                "CLIENT_NODE_PWA_ENABLED",
                "true".to_string(),
                "serve the client-node PWA (system/pwa/dist) instead of the legacy system/ui bundle, and apply its stricter CSP (core/adapters-network/src/http/server/ui.rs)",
            ));
            pairs.push((
                "CLIENT_NODE_PWA_STATIC_DIR_PATH",
                pwa_static_dir.display().to_string(),
                "absolute path to monorepo/system/pwa/dist — selected over STATIC_DIR_PATH via select_static_assets_dir when CLIENT_NODE_PWA_ENABLED=true",
            ));
        }

        let mut overrides = String::from(
            "# ============================================================\n\
             # node-app dev overrides (auto-generated — do not edit)\n\
             #\n\
             # These keys are computed at orchestrator startup and MUST win\n\
             # over the base env file below for per-instance isolation. The\n\
             # base env file (alice.env / bob.env) is the source of truth\n\
             # for everything else — edit it directly if you need to change\n\
             # other settings.\n\
             #\n\
             # dotenvy is first-wins, so this block has to come first.\n\
             # ============================================================\n",
        );
        for (key, _, reason) in &pairs {
            overrides.push_str(&format!("# {key}: {reason}\n"));
        }
        overrides.push('\n');
        for (key, value, _) in &pairs {
            overrides.push_str(&format!("{key}={value}\n"));
        }
        overrides.push_str(&format!(
            "\n# ============================================================\n\
             # Base config (system/server/{env_file_name})\n\
             # ============================================================\n",
            env_file_name = self.profile.env_file_name,
        ));
        fs::write(&env_file, overrides + &base_env)
            .with_context(|| format!("write {}", env_file.display()))?;
        *self.env_file.lock().unwrap() = Some(env_file.clone());
        // Publish the env file path to the TUI so developers can find the
        // generated config the running daemon is actually using.
        tui::update_daemon_env_file(
            self.log_tx.as_ref(),
            &self.profile.name,
            env_file.clone(),
        );

        // 3b. Remove stale socket.
        let _ = fs::remove_file(&socket_path);

        // 4. Build the platform — ONCE across all instances.
        //
        // The daemon binary and builtin-app cdylibs depend only on the monorepo
        // source, not on which instance is booting. Building them per-instance
        // both wastes time and — because every instance shares one
        // `target/debug/node-server` and one cargo target dir — lets a later
        // instance needlessly delete + relink the binary an earlier instance is
        // running from. Guard the whole build behind a process-wide OnceLock so
        // the first instance builds and every subsequent instance boots from the
        // same artifacts. (The UI-dist and builtin-cdylib background builds are
        // already OnceLock-guarded.) NOTE: this is an efficiency + robustness
        // win; it is NOT what made `--instances=alice,bob` leave one node dead —
        // that was esp32-bridge defaulting its OTA HTTP port to a sibling's main
        // port, fixed via the per-instance OTA_HTTP_PORT override above.

        // Background rebuilds self-guard (UI_BUILD_ONCE / PWA_BUILD_ONCE /
        // BUILTIN_APPS_BUILD_ONCE), so calling them per-instance is a cheap
        // no-op after the first. --client-node builds system/pwa/dist
        // instead of the legacy system/ui/dist — no reason to pay for both.
        if self.client_node {
            ensure_pwa_dist_built(&self.monorepo_path, self.log_tx.clone());
        } else {
            ensure_ui_dist_built(&self.monorepo_path, self.log_tx.clone());
        }
        ensure_builtin_apps_built(&self.monorepo_path, self.log_tx.clone());

        let binary_path = self.monorepo_path.join("target/debug/node-server");

        if DAEMON_BUILD_ONCE.get().is_none() {
            // 4a. Build mandatory builtin apps (blocking).
            let has_make = Command::new("make")
                .arg("--version")
                .stdout(Stdio::null())
                .stderr(Stdio::null())
                .status()
                .map(|s| s.success())
                .unwrap_or(false);
            if has_make {
                self.syslog("→ building mandatory builtin apps: make builtin-apps CARGO_PROFILE=debug");
                let t0 = Instant::now();
                let (status, _) = self.run_build_cmd(
                    Command::new("make")
                        .args(["builtin-apps", "CARGO_PROFILE=debug"])
                        .current_dir(&self.monorepo_path)
                        .stdin(Stdio::null()),
                    LogSource::System,
                )
                .with_context(|| "spawn `make builtin-apps`")?;
                let builtins_ms = t0.elapsed().as_millis() as u64;
                if !status.success() {
                    self.syslog(format!(
                        "⚠ `make builtin-apps` failed (exit {}) — some platform apps may not load",
                        status
                    ));
                }
                // Timing-only status update — no log lines go to the build tab for builtin-apps.
                tui::update_status(
                    self.log_tx.as_ref(),
                    LogSource::Build,
                    ServiceStatus::Ready,
                    Some(format!("builtins:{}ms", builtins_ms)),
                );
            } else {
                self.syslog("⚠ `make` not found — skipping builtin-apps build");
            }

            // 4b. Delete old binary to avoid macOS linker-replace issue.
            if binary_path.exists() {
                let _ = fs::remove_file(&binary_path);
            }

            self.syslog(format!(
                "→ building daemon: cargo build -p node-server (cwd={})",
                self.monorepo_path.display()
            ));
            tui::update_status(
                self.log_tx.as_ref(),
                LogSource::Daemon,
                ServiceStatus::Building,
                Some(format!("cargo build (cwd={})", self.monorepo_path.display())),
            );

            let (build_status, build_errors) = self
                .run_build_cmd(
                    Command::new("cargo")
                        .args(["build", "-p", "node-server", "--features", "agentic_payments"])
                        .current_dir(&self.monorepo_path)
                        .stdin(Stdio::null()),
                    LogSource::Daemon,
                )
                .with_context(|| "spawn `cargo build -p node-server`")?;
            if !build_status.success() {
                tui::update_status(
                    self.log_tx.as_ref(),
                    LogSource::Daemon,
                    ServiceStatus::Failed("cargo build failed".into()),
                    None,
                );
                let detail = if build_errors.is_empty() {
                    String::new()
                } else {
                    format!("\n\n{}", build_errors.join("\n"))
                };
                bail!(
                    "cargo build -p node-server failed (exit {}){detail}",
                    build_status
                );
            }

            // Mark the shared build done so sibling instances boot from this
            // binary instead of deleting + rebuilding it underneath us.
            let _ = DAEMON_BUILD_ONCE.set(());
        } else {
            // A sibling instance already built the daemon this run. Boot from
            // the shared binary rather than touching it (deleting/relinking it
            // would crash the already-running sibling daemon).
            self.syslog(format!(
                "→ reusing daemon binary built by a prior instance this run ({})",
                binary_path.display()
            ));
            if !binary_path.exists() {
                bail!(
                    "daemon binary missing at {} — the first instance's build should have \
                     produced it. Rerun `node-app dev`.",
                    binary_path.display()
                );
            }
        }

        // 4c. Launch daemon.
        self.syslog(format!(
            "→ spawning daemon (env={})",
            env_file.display()
        ));
        tui::update_status(
            self.log_tx.as_ref(),
            LogSource::Daemon,
            ServiceStatus::Starting,
            Some(format!("[{}] api=:{}  ipc={}", self.profile.name, self.profile.http_port, socket_path.display())),
        );

        // Pin the daemon to plain HTTP for this run (see force_dev_http_only):
        // node-app dev's readiness probe + Vite proxy target the HTTP port,
        // which TLS turns into a redirect-only listener.
        self.force_dev_http_only(&db_path);

        let child = self.spawn_daemon(&env_file)?;
        let child_pid = child.id();
        if let Err(e) = fs::write(&pid_file, child_pid.to_string()) {
            self.syslog(format!("⚠ could not write PID file: {e}"));
        }
        *self.child.lock().unwrap() = Some(child);

        // 5. Wait for IPC socket.
        let started = Instant::now();
        loop {
            if UnixStream::connect(&socket_path).is_ok() {
                self.syslog(format!(
                    "✓ IPC socket up at {} ({}s) — waiting for apps…",
                    socket_path.display(),
                    started.elapsed().as_secs()
                ));
                break;
            }
            if started.elapsed() >= HEALTH_TIMEOUT {
                self.shutdown();
                tui::update_status(
                    self.log_tx.as_ref(),
                    LogSource::Daemon,
                    ServiceStatus::Failed(format!(
                        "socket not connectable after {}s",
                        HEALTH_TIMEOUT.as_secs()
                    )),
                    None,
                );
                return Err(anyhow!(
                    "daemon did not come up within {}s (socket at {} not connectable).",
                    HEALTH_TIMEOUT.as_secs(),
                    socket_path.display()
                ));
            }
            if let Some(child) = self.child.lock().unwrap().as_mut() {
                if let Ok(Some(status)) = child.try_wait() {
                    tui::update_status(
                        self.log_tx.as_ref(),
                        LogSource::Daemon,
                        ServiceStatus::Failed(format!("exited {}", status)),
                        None,
                    );
                    return Err(anyhow!("daemon exited with {} before becoming ready", status));
                }
            }
            std::thread::sleep(HEALTH_POLL);
        }

        // 5b. Wait for the HTTP listener to actually answer. The IPC socket
        // can come up before axum binds its TCP port; spawning Vite before
        // that point produces "ECONNREFUSED" through the proxy and looks
        // exactly like a broken proxy config.
        self.wait_http_ready(self.profile.http_port)?;

        // 6. Start UI dev server (skipped in --client-node mode — see
        // spawn_ui doc comment).
        if self.client_node {
            self.syslog(format!(
                "✓ client-node PWA available at http://localhost:{} (backend-served from {})",
                self.profile.http_port,
                self.monorepo_path.join("system/pwa/dist").display()
            ));
            tui::update_status(
                self.log_tx.as_ref(),
                LogSource::UiServer,
                ServiceStatus::Disabled,
                Some("client-node PWA (backend-served, no Vite HMR)".into()),
            );
        }
        let ui_child = self.spawn_ui();
        if let Some(ref c) = ui_child {
            // Persist the Vite PID so the next `node-app dev` run can reap
            // this process even if we get killed without running our
            // shutdown handler (kill -9, panic, OOM).
            let _ = fs::write(&vite_pid_file, c.id().to_string());
            // Smoke-test the proxy: hit /api/healthz through Vite and verify
            // we got a response from the backend. A failure here is far more
            // useful than letting the user discover the broken proxy at
            // first page load.
            if let Err(e) = self.verify_proxy(self.profile.ui_port, self.profile.http_port) {
                self.syslog(format!("⚠ proxy verification failed: {e:#}"));
                tui::update_status(
                    self.log_tx.as_ref(),
                    LogSource::UiServer,
                    ServiceStatus::Failed("proxy not forwarding /api".into()),
                    None,
                );
            } else if let Err(e) = self.verify_ws_proxy(self.profile.ui_port) {
                // /api proxy works but WS upgrade doesn't — most likely a
                // path mismatch between vite.config.ts and the backend
                // route. Don't fail the whole launch (the UI will still
                // mostly work without realtime), but flag it loudly.
                self.syslog(format!("⚠ ws proxy verification failed: {e:#}"));
                tui::update_status(
                    self.log_tx.as_ref(),
                    LogSource::UiServer,
                    ServiceStatus::Failed("ws proxy /api/ws not upgrading".into()),
                    None,
                );
            }
        }
        *self.ui_child.lock().unwrap() = ui_child;

        // 7. Wait for critical apps.
        let apps_started = Instant::now();
        self.syslog("→ waiting for critical apps (device-registry, core-storage)…");
        loop {
            let all_ready = ipc_list_app_statuses(&socket_path)
                .map(|statuses| {
                    ["device-registry", "core-storage"].iter().all(|name| {
                        statuses
                            .get(*name)
                            .map(|s| s == "active" || s == "running" || s == "lazy")
                            .unwrap_or(false)
                    })
                })
                .unwrap_or(false);

            if all_ready {
                self.syslog(format!(
                    "✓ critical apps ready ({}s)",
                    apps_started.elapsed().as_secs()
                ));
                tui::update_status(
                    self.log_tx.as_ref(),
                    LogSource::Daemon,
                    ServiceStatus::Ready,
                    Some(format!(
                        "[{}] api=http://localhost:{}  ui=http://localhost:{}",
                        self.profile.name, self.profile.http_port, self.profile.ui_port
                    )),
                );
                break;
            }
            if apps_started.elapsed() >= Duration::from_secs(60) {
                self.syslog("⚠ critical apps not fully loaded after 60s — proceeding anyway");
                tui::update_status(
                    self.log_tx.as_ref(),
                    LogSource::Daemon,
                    ServiceStatus::Ready,
                    Some("api ready (some apps slow)".into()),
                );
                break;
            }
            if let Some(child) = self.child.lock().unwrap().as_mut() {
                if let Ok(Some(status)) = child.try_wait() {
                    return Err(anyhow!("daemon exited with {} while waiting for apps", status));
                }
            }
            std::thread::sleep(Duration::from_secs(2));
        }

        Ok(DaemonHandle {
            name: self.profile.name.clone(),
            banner: if self.client_node {
                format!(
                    "monorepo daemon [{}] (cargo run from {}, client-node PWA=http://localhost:{} \
                     [backend-served, no Vite HMR; shared platform deps], socket={})",
                    self.profile.name,
                    self.monorepo_path.display(),
                    self.profile.http_port,
                    socket_path.display()
                )
            } else {
                format!(
                    "monorepo daemon [{}] (cargo run from {}, api=http://localhost:{}, \
                     ui=http://localhost:{}, socket={})",
                    self.profile.name,
                    self.monorepo_path.display(),
                    self.profile.http_port,
                    self.profile.ui_port,
                    socket_path.display()
                )
            },
            socket_path,
            dev_dir,
            api_base_url: Some(format!("http://127.0.0.1:{}", self.profile.http_port)),
        })
    }

    fn tail_logs(&self, app_name: &str) {
        let log_tx = match &self.log_tx {
            Some(tx) => tx.clone(),
            None => return,
        };
        let env_dir = match monorepo_env_dir(&self.monorepo_path, &self.profile.name) {
            Ok(d) => d,
            Err(_) => return,
        };
        // App SDK logs: {DATA_DIR_PATH}/logs/apps/{app_name}/app.log
        let log_file = env_dir
            .join("ldk_data")
            .join("logs")
            .join("apps")
            .join(app_name)
            .join("app.log");
        // Prefix every log line with `[<node>][<app>] ` so AppState::push_log
        // routes it into both the per-node and per-app buffers. The outer
        // node prefix lets multi-instance platform mode show alice/bob's
        // logs separately; the inner app prefix preserves the existing
        // per-app filter. App-developer mode (no tracked_nodes) ignores
        // the node prefix since no name matches.
        let prefix = format!("[{node}][{app}] ", node = self.profile.name, app = app_name);

        std::thread::spawn(move || {
            use std::io::{BufRead, BufReader, Seek, SeekFrom};

            // Wait up to 5s for the log file to appear (created when daemon loads the app).
            let deadline = std::time::Instant::now();
            loop {
                if log_file.exists() {
                    break;
                }
                if deadline.elapsed() > std::time::Duration::from_secs(5) {
                    return;
                }
                std::thread::sleep(std::time::Duration::from_millis(200));
            }

            let file = match fs::File::open(&log_file) {
                Ok(f) => f,
                Err(_) => return,
            };
            let mut reader = BufReader::new(file);
            // Start from the beginning — app startup logs are already written by the time
            // tail_logs() is called (ipc_call for app.dev_load completes after init()).
            let _ = reader.seek(SeekFrom::Start(0));

            loop {
                let mut line = String::new();
                match reader.read_line(&mut line) {
                    Ok(0) => {
                        // EOF — file hasn't grown yet, poll.
                        std::thread::sleep(std::time::Duration::from_millis(100));
                    }
                    Ok(_) => {
                        let trimmed =
                            line.trim_end_matches('\n').trim_end_matches('\r');
                        if !trimmed.is_empty()
                            && log_tx
                                .send(TuiEvent::Log(crate::tui::LogEntry {
                                    source: LogSource::App,
                                    line: format!("{prefix}{trimmed}"),
                                }))
                                .is_err()
                        {
                            return; // TUI channel closed, exit cleanly
                        }
                    }
                    Err(_) => return,
                }
            }
        });
    }

    fn shutdown(&self) {
        if let Ok(env_dir) = monorepo_env_dir(&self.monorepo_path, &self.profile.name) {
            let _ = fs::remove_file(env_dir.join("daemon.pid"));
        }
        if let Some(mut child) = self.child.lock().unwrap().take() {
            let pid = child.id() as i32;
            self.syslog(format!("→ shutting down monorepo daemon (PID {pid})…"));
            #[cfg(unix)]
            unsafe {
                libc::kill(-pid, libc::SIGTERM);
            }
            let t = Instant::now();
            loop {
                match child.try_wait() {
                    Ok(Some(_)) => {
                        self.syslog(format!(
                            "✓ daemon exited ({}ms)",
                            t.elapsed().as_millis()
                        ));
                        break;
                    }
                    Ok(None) if t.elapsed() >= Duration::from_secs(10) => {
                        self.syslog("⚠ daemon did not exit after 10s, SIGKILL");
                        #[cfg(unix)]
                        unsafe {
                            libc::kill(-pid, libc::SIGKILL);
                        }
                        let _ = child.wait();
                        break;
                    }
                    Ok(None) => std::thread::sleep(Duration::from_millis(200)),
                    Err(e) => {
                        self.syslog(format!("⚠ daemon wait error: {e}"));
                        break;
                    }
                }
            }
        }
        if let Some(mut ui) = self.ui_child.lock().unwrap().take() {
            let pid = ui.id() as i32;
            self.syslog(format!("→ shutting down UI dev server (PID {pid})…"));
            #[cfg(unix)]
            unsafe {
                libc::kill(-pid, libc::SIGTERM);
            }
            let t = Instant::now();
            loop {
                match ui.try_wait() {
                    Ok(Some(_)) => break,
                    Ok(None) if t.elapsed() >= Duration::from_secs(5) => {
                        #[cfg(unix)]
                        unsafe {
                            libc::kill(-pid, libc::SIGKILL);
                        }
                        let _ = ui.wait();
                        break;
                    }
                    Ok(None) => std::thread::sleep(Duration::from_millis(200)),
                    Err(_) => break,
                }
            }
        }
    }

    fn restart(&self) -> Result<()> {
        let env_file = self
            .env_file
            .lock()
            .unwrap()
            .clone()
            .ok_or_else(|| anyhow!("daemon was never started — cannot restart"))?;

        self.syslog("→ restart: stopping daemon…");
        tui::update_status(
            self.log_tx.as_ref(),
            LogSource::Daemon,
            ServiceStatus::Starting,
            Some("restarting…".into()),
        );

        self.shutdown_daemon_only();

        // Reap any stale process still holding the backend port. Without
        // this, a daemon child that died unclean (panic, OOM) can leave its
        // socket in TIME_WAIT and the respawned daemon fails to bind.
        self.free_port(self.profile.http_port, "backend");

        // Remove stale socket.
        let socket_path = self
            .socket_override
            .clone()
            .unwrap_or_else(|| {
                monorepo_env_dir(&self.monorepo_path, &self.profile.name)
                    .ok()
                    .map(|d| d.join("control.sock"))
                    .unwrap_or_else(|| PathBuf::from("/tmp/node-control.sock"))
            });
        let _ = fs::remove_file(&socket_path);

        self.syslog("→ restart: spawning daemon…");
        let child = self.spawn_daemon(&env_file)?;
        let child_pid = child.id();
        *self.child.lock().unwrap() = Some(child);

        // Update PID file.
        if let Ok(env_dir) = monorepo_env_dir(&self.monorepo_path, &self.profile.name) {
            let _ = fs::write(env_dir.join("daemon.pid"), child_pid.to_string());
        }

        // Wait for socket.
        let t = Instant::now();
        loop {
            if UnixStream::connect(&socket_path).is_ok() {
                // Socket up — also confirm the HTTP listener answers before
                // declaring the restart successful. Otherwise the next /api
                // call from the browser races a half-booted daemon.
                if let Err(e) = self.wait_http_ready(self.profile.http_port) {
                    tui::update_status(
                        self.log_tx.as_ref(),
                        LogSource::Daemon,
                        ServiceStatus::Failed("HTTP not ready after restart".into()),
                        None,
                    );
                    bail!("daemon restart: HTTP readiness failed: {e:#}");
                }
                self.syslog(format!(
                    "✓ daemon restarted ({}s)",
                    t.elapsed().as_secs()
                ));
                tui::update_status(
                    self.log_tx.as_ref(),
                    LogSource::Daemon,
                    ServiceStatus::Ready,
                    Some("restarted".into()),
                );
                return Ok(());
            }
            if t.elapsed() > HEALTH_TIMEOUT {
                tui::update_status(
                    self.log_tx.as_ref(),
                    LogSource::Daemon,
                    ServiceStatus::Failed("socket not connectable after restart".into()),
                    None,
                );
                bail!("daemon did not come up after restart");
            }
            if let Some(child) = self.child.lock().unwrap().as_mut() {
                if let Ok(Some(status)) = child.try_wait() {
                    tui::update_status(
                        self.log_tx.as_ref(),
                        LogSource::Daemon,
                        ServiceStatus::Failed(format!("exited {}", status)),
                        None,
                    );
                    bail!("daemon exited with {} during restart", status);
                }
            }
            std::thread::sleep(HEALTH_POLL);
        }
    }

    fn pre_start_dev_dir(&self) -> Option<PathBuf> {
        monorepo_dev_dir(&self.monorepo_path, &self.profile.name, self.dev_dir_override.as_deref()).ok()
    }
}

/// Process-wide guard so the daemon binary + blocking builtin-apps build runs
/// exactly once across a multi-instance run. The binary and cdylibs are
/// instance-independent; building them per-instance lets a later instance
/// delete + relink the shared `target/debug/node-server` out from under an
/// earlier instance's running daemon (killing it). First instance builds; the
/// rest spawn from the same artifact. Mirrors [`UI_BUILD_ONCE`] /
/// [`BUILTIN_APPS_BUILD_ONCE`].
static DAEMON_BUILD_ONCE: OnceLock<()> = OnceLock::new();

/// Process-wide guard so multi-instance runs (alice + bob) trigger the UI
/// build exactly once. `OnceLock::get_or_init` runs the closure under a lock
/// the first time it's called and short-circuits on subsequent calls.
static UI_BUILD_ONCE: OnceLock<()> = OnceLock::new();

/// Run `yarn build` (or `npm run build`) in `<monorepo>/system/ui/` to refresh
/// `system/ui/dist/`. Spawned in a detached thread so it doesn't block daemon
/// boot — the daemon serves `dist/` via static-file middleware on each
/// request, so by the time the user actually opens a browser the bundle is
/// already swapped.
///
/// Output is streamed to the TUI under `LogSource::Build` so the user can see
/// progress (and any build failure) in real time. If no TUI is attached the
/// output is inherited so the user still sees it.
///
/// Skips silently when `system/ui/package.json` is missing — keeps the dev
/// loop usable on workspace layouts that don't include the UI.
fn ensure_ui_dist_built(monorepo_path: &Path, log_tx: Option<LogTx>) {
    if UI_BUILD_ONCE.set(()).is_err() {
        return; // already triggered by an earlier instance
    }

    let ui_dir = monorepo_path.join("system/ui");
    if !ui_dir.join("package.json").exists() {
        tui::sys_log(
            log_tx.as_ref(),
            format!(
                "→ skip UI dist build: {} not found",
                ui_dir.join("package.json").display()
            ),
        );
        return;
    }

    let pkg_mgr = if which_bin("yarn") { "yarn" } else { "npm" };
    let args: &[&str] = if pkg_mgr == "yarn" {
        &["build"]
    } else {
        &["run", "build"]
    };

    tui::sys_log(
        log_tx.as_ref(),
        format!(
            "→ rebuilding UI dist in background ({} {}) — daemon's port will serve fresh bundle once done",
            pkg_mgr,
            args.join(" ")
        ),
    );
    tui::update_status(
        log_tx.as_ref(),
        LogSource::Build,
        ServiceStatus::Building,
        Some(format!("{} build (ui)", pkg_mgr)),
    );

    let ui_dir_clone = ui_dir.clone();
    let log_tx_clone = log_tx.clone();
    std::thread::spawn(move || {
        let mut cmd = Command::new(pkg_mgr);
        cmd.args(args).current_dir(&ui_dir_clone).stdin(Stdio::null());

        if log_tx_clone.is_some() {
            cmd.stdout(Stdio::piped()).stderr(Stdio::piped());
        } else {
            cmd.stdout(Stdio::inherit()).stderr(Stdio::inherit());
        }

        let started = Instant::now();
        match cmd.spawn() {
            Ok(mut child) => {
                if let Some(tx) = &log_tx_clone {
                    if let Some(stdout) = child.stdout.take() {
                        let tx = tx.clone();
                        std::thread::spawn(move || {
                            for line in std::io::BufReader::new(stdout).lines().map_while(Result::ok) {
                                let _ = tx.send(TuiEvent::Log(crate::tui::LogEntry {
                                    source: LogSource::Build,
                                    line: format!("[ui-build] {line}"),
                                }));
                            }
                        });
                    }
                    if let Some(stderr) = child.stderr.take() {
                        let tx = tx.clone();
                        std::thread::spawn(move || {
                            for line in std::io::BufReader::new(stderr).lines().map_while(Result::ok) {
                                let _ = tx.send(TuiEvent::Log(crate::tui::LogEntry {
                                    source: LogSource::Build,
                                    line: format!("[ui-build] {line}"),
                                }));
                            }
                        });
                    }
                }
                match child.wait() {
                    Ok(status) if status.success() => {
                        tui::sys_log(
                            log_tx_clone.as_ref(),
                            format!(
                                "✓ UI dist rebuilt in {:.1}s",
                                started.elapsed().as_secs_f32()
                            ),
                        );
                        tui::update_status(
                            log_tx_clone.as_ref(),
                            LogSource::Build,
                            ServiceStatus::Ready,
                            Some("ui dist fresh".into()),
                        );
                    }
                    Ok(status) => {
                        tui::sys_log(
                            log_tx_clone.as_ref(),
                            format!(
                                "✗ UI dist build failed (exit {}); daemon port will serve stale bundle. \
                                 Use http://localhost:5173/5174 (Vite, HMR) until this is fixed.",
                                status
                            ),
                        );
                        tui::update_status(
                            log_tx_clone.as_ref(),
                            LogSource::Build,
                            ServiceStatus::Failed("ui build failed".into()),
                            None,
                        );
                    }
                    Err(e) => {
                        tui::sys_log(
                            log_tx_clone.as_ref(),
                            format!("✗ UI dist build wait error: {e}"),
                        );
                    }
                }
            }
            Err(e) => {
                tui::sys_log(
                    log_tx_clone.as_ref(),
                    format!(
                        "✗ could not spawn {} build for UI dist: {e}",
                        pkg_mgr
                    ),
                );
            }
        }
    });
}

/// Same shape as [`UI_BUILD_ONCE`], for the client-node PWA rebuild
/// (`--client-node`). Kept as a separate guard/thread rather than folding
/// into [`ensure_ui_dist_built`] because the two are mutually exclusive per
/// run (`ensure_running` calls exactly one of them) and each targets a
/// different subdirectory with a different build command.
static PWA_BUILD_ONCE: OnceLock<()> = OnceLock::new();

/// Run `yarn build` (or `npm run build`) in `<monorepo>/system/pwa/` to
/// refresh `system/pwa/dist/`. Spawned in a detached thread so it doesn't
/// block daemon boot — the daemon serves `dist/` via the same static-file
/// middleware the legacy UI uses (`select_static_assets_dir` swaps in
/// `CLIENT_NODE_PWA_STATIC_DIR_PATH` when `CLIENT_NODE_PWA_ENABLED=true`),
/// so by the time the user opens a browser the bundle is already swapped.
///
/// Output is streamed to the TUI under `LogSource::Build` so the user can
/// see progress (and any build failure) in real time. If no TUI is attached
/// the output is inherited so the user still sees it.
///
/// Skips silently when `system/pwa/package.json` is missing — keeps
/// `--client-node` a clean error path rather than a panic on workspace
/// layouts that don't include the PWA.
fn ensure_pwa_dist_built(monorepo_path: &Path, log_tx: Option<LogTx>) {
    if PWA_BUILD_ONCE.set(()).is_err() {
        return; // already triggered by an earlier instance
    }

    let pwa_dir = monorepo_path.join("system/pwa");
    if !pwa_dir.join("package.json").exists() {
        tui::sys_log(
            log_tx.as_ref(),
            format!(
                "→ skip PWA dist build: {} not found",
                pwa_dir.join("package.json").display()
            ),
        );
        return;
    }

    let pkg_mgr = if which_bin("yarn") { "yarn" } else { "npm" };
    let args: &[&str] = if pkg_mgr == "yarn" {
        &["build"]
    } else {
        &["run", "build"]
    };

    tui::sys_log(
        log_tx.as_ref(),
        format!(
            "→ rebuilding client-node PWA dist in background ({} {}) — daemon's port will serve fresh bundle once done",
            pkg_mgr,
            args.join(" ")
        ),
    );
    tui::update_status(
        log_tx.as_ref(),
        LogSource::Build,
        ServiceStatus::Building,
        Some(format!("{} build (pwa)", pkg_mgr)),
    );

    let pwa_dir_clone = pwa_dir.clone();
    let log_tx_clone = log_tx.clone();
    std::thread::spawn(move || {
        let mut cmd = Command::new(pkg_mgr);
        cmd.args(args).current_dir(&pwa_dir_clone).stdin(Stdio::null());

        if log_tx_clone.is_some() {
            cmd.stdout(Stdio::piped()).stderr(Stdio::piped());
        } else {
            cmd.stdout(Stdio::inherit()).stderr(Stdio::inherit());
        }

        let started = Instant::now();
        match cmd.spawn() {
            Ok(mut child) => {
                if let Some(tx) = &log_tx_clone {
                    if let Some(stdout) = child.stdout.take() {
                        let tx = tx.clone();
                        std::thread::spawn(move || {
                            for line in std::io::BufReader::new(stdout).lines().map_while(Result::ok) {
                                let _ = tx.send(TuiEvent::Log(crate::tui::LogEntry {
                                    source: LogSource::Build,
                                    line: format!("[pwa-build] {line}"),
                                }));
                            }
                        });
                    }
                    if let Some(stderr) = child.stderr.take() {
                        let tx = tx.clone();
                        std::thread::spawn(move || {
                            for line in std::io::BufReader::new(stderr).lines().map_while(Result::ok) {
                                let _ = tx.send(TuiEvent::Log(crate::tui::LogEntry {
                                    source: LogSource::Build,
                                    line: format!("[pwa-build] {line}"),
                                }));
                            }
                        });
                    }
                }
                match child.wait() {
                    Ok(status) if status.success() => {
                        tui::sys_log(
                            log_tx_clone.as_ref(),
                            format!(
                                "✓ PWA dist rebuilt in {:.1}s",
                                started.elapsed().as_secs_f32()
                            ),
                        );
                        tui::update_status(
                            log_tx_clone.as_ref(),
                            LogSource::Build,
                            ServiceStatus::Ready,
                            Some("pwa dist fresh".into()),
                        );
                    }
                    Ok(status) => {
                        tui::sys_log(
                            log_tx_clone.as_ref(),
                            format!(
                                "✗ PWA dist build failed (exit {}); daemon port will serve the stale (or missing) bundle.",
                                status
                            ),
                        );
                        tui::update_status(
                            log_tx_clone.as_ref(),
                            LogSource::Build,
                            ServiceStatus::Failed("pwa build failed".into()),
                            None,
                        );
                    }
                    Err(e) => {
                        tui::sys_log(
                            log_tx_clone.as_ref(),
                            format!("✗ PWA dist build wait error: {e}"),
                        );
                    }
                }
            }
            Err(e) => {
                tui::sys_log(
                    log_tx_clone.as_ref(),
                    format!(
                        "✗ could not spawn {} build for PWA dist: {e}",
                        pkg_mgr
                    ),
                );
            }
        }
    });
}

/// Same shape as [`UI_BUILD_ONCE`] for the cdylib builtin-apps rebuild.
static BUILTIN_APPS_BUILD_ONCE: OnceLock<()> = OnceLock::new();

/// Run `make builtin-apps` to rebuild every cdylib module under `modules/`
/// (ldk-node, cron, core-storage, etc.) and stage the compiled `.dylib`/`.so`
/// next to each app's manifest. Without this step, the daemon dlopens
/// whatever stale `.dylib` was last built, so newly-added capabilities or
/// signature changes in module source don't appear until you remember to
/// run `make builtin-apps` yourself.
///
/// The Makefile rule (a) calls `cargo build -p <app>` for every entry in
/// `BUILTIN_NATIVE_APPS`, then (b) does the copy-then-rename + codesign dance
/// that the daemon's mmap'd existing inodes require to avoid SIGBUS. We just
/// shell out to it instead of reimplementing the same logic in Rust.
///
/// Spawned in a detached thread so the daemon boot continues in parallel
/// (same rationale as [`ensure_ui_dist_built`]). cargo is incremental so the
/// common warm case where nothing changed is fast.
///
/// Skipped silently when there's no Makefile (app-developer mode running from
/// a non-monorepo path).
fn ensure_builtin_apps_built(monorepo_path: &Path, log_tx: Option<LogTx>) {
    if BUILTIN_APPS_BUILD_ONCE.set(()).is_err() {
        return; // already triggered by an earlier instance
    }

    let makefile = monorepo_path.join("Makefile");
    if !makefile.exists() {
        tui::sys_log(
            log_tx.as_ref(),
            format!("→ skip builtin-apps build: {} not found", makefile.display()),
        );
        return;
    }
    if !which_bin("make") {
        tui::sys_log(
            log_tx.as_ref(),
            "→ skip builtin-apps build: `make` not on PATH",
        );
        return;
    }

    tui::sys_log(
        log_tx.as_ref(),
        "→ rebuilding builtin apps in background (make builtin-apps) — cargo is incremental, only changed modules pay full cost",
    );
    tui::update_status(
        log_tx.as_ref(),
        LogSource::Build,
        ServiceStatus::Building,
        Some("make builtin-apps".into()),
    );

    let monorepo_clone = monorepo_path.to_path_buf();
    let log_tx_clone = log_tx.clone();
    std::thread::spawn(move || {
        let mut cmd = Command::new("make");
        cmd.arg("builtin-apps")
            .current_dir(&monorepo_clone)
            .stdin(Stdio::null());

        if log_tx_clone.is_some() {
            cmd.stdout(Stdio::piped()).stderr(Stdio::piped());
        } else {
            cmd.stdout(Stdio::inherit()).stderr(Stdio::inherit());
        }

        let started = Instant::now();
        match cmd.spawn() {
            Ok(mut child) => {
                if let Some(tx) = &log_tx_clone {
                    if let Some(stdout) = child.stdout.take() {
                        let tx = tx.clone();
                        std::thread::spawn(move || {
                            for line in std::io::BufReader::new(stdout).lines().map_while(Result::ok) {
                                let _ = tx.send(TuiEvent::Log(crate::tui::LogEntry {
                                    source: LogSource::Build,
                                    line: format!("[builtin-apps] {line}"),
                                }));
                            }
                        });
                    }
                    if let Some(stderr) = child.stderr.take() {
                        let tx = tx.clone();
                        std::thread::spawn(move || {
                            for line in std::io::BufReader::new(stderr).lines().map_while(Result::ok) {
                                let _ = tx.send(TuiEvent::Log(crate::tui::LogEntry {
                                    source: LogSource::Build,
                                    line: format!("[builtin-apps] {line}"),
                                }));
                            }
                        });
                    }
                }
                match child.wait() {
                    Ok(status) if status.success() => {
                        tui::sys_log(
                            log_tx_clone.as_ref(),
                            format!(
                                "✓ builtin apps rebuilt in {:.1}s — daemon will pick up changes on next start/reload",
                                started.elapsed().as_secs_f32()
                            ),
                        );
                        tui::update_status(
                            log_tx_clone.as_ref(),
                            LogSource::Build,
                            ServiceStatus::Ready,
                            Some("builtin apps fresh".into()),
                        );
                    }
                    Ok(status) => {
                        tui::sys_log(
                            log_tx_clone.as_ref(),
                            format!(
                                "✗ builtin-apps build failed (exit {}); daemon will dlopen the previously-built .dylibs and may be missing capabilities you've added since.",
                                status
                            ),
                        );
                        tui::update_status(
                            log_tx_clone.as_ref(),
                            LogSource::Build,
                            ServiceStatus::Failed("builtin-apps build failed".into()),
                            None,
                        );
                    }
                    Err(e) => {
                        tui::sys_log(
                            log_tx_clone.as_ref(),
                            format!("✗ builtin-apps build wait error: {e}"),
                        );
                    }
                }
            }
            Err(e) => {
                tui::sys_log(
                    log_tx_clone.as_ref(),
                    format!("✗ could not spawn make builtin-apps: {e}"),
                );
            }
        }
    });
}

fn monorepo_env_dir(monorepo_path: &Path, instance_name: &str) -> Result<PathBuf> {
    let cache_dir = cache_root()?;
    let path_hash = {
        let mut h = DefaultHasher::new();
        monorepo_path
            .canonicalize()
            .unwrap_or_else(|_| monorepo_path.to_path_buf())
            .hash(&mut h);
        instance_name.hash(&mut h);
        h.finish()
    };
    Ok(cache_dir.join(format!("monorepo-{:x}", path_hash)))
}

pub fn monorepo_dev_dir(monorepo_path: &Path, instance_name: &str, dev_dir_override: Option<&Path>) -> Result<PathBuf> {
    if let Some(override_path) = dev_dir_override {
        return Ok(override_path.to_path_buf());
    }
    Ok(monorepo_env_dir(monorepo_path, instance_name)?.join("dev-apps"))
}

fn ipc_list_app_statuses(
    socket_path: &std::path::Path,
) -> Result<std::collections::HashMap<String, String>> {
    use std::io::{BufRead, BufReader, Write};

    let mut stream = UnixStream::connect(socket_path)
        .with_context(|| "connect to IPC socket")?;
    stream.set_read_timeout(Some(Duration::from_secs(5))).ok();
    stream.set_write_timeout(Some(Duration::from_secs(5))).ok();

    let request = serde_json::json!({
        "jsonrpc": "2.0",
        "id": 1,
        "method": "app.list",
        "params": {}
    });
    let mut line = serde_json::to_string(&request).unwrap();
    line.push('\n');
    stream.write_all(line.as_bytes())?;

    let reader = BufReader::new(&stream);
    let response_line = reader
        .lines()
        .next()
        .ok_or_else(|| anyhow!("no response"))??;

    let v: serde_json::Value = serde_json::from_str(&response_line)?;
    let mut map = std::collections::HashMap::new();
    if let Some(apps) = v.pointer("/result/apps").and_then(|a| a.as_array()) {
        for app in apps {
            if let (Some(name), Some(status)) = (
                app.get("name").and_then(|n| n.as_str()),
                app.get("status").and_then(|s| s.as_str()),
            ) {
                map.insert(name.to_string(), status.to_string());
            }
        }
    }
    Ok(map)
}

fn which_bin(bin: &str) -> bool {
    std::env::var_os("PATH")
        .map(|path| std::env::split_paths(&path).any(|dir| dir.join(bin).is_file()))
        .unwrap_or(false)
}

fn cache_root() -> Result<PathBuf> {
    if let Ok(c) = std::env::var("XDG_CACHE_HOME") {
        if !c.is_empty() {
            return Ok(PathBuf::from(c).join("node-app"));
        }
    }
    let home = std::env::var_os("HOME").ok_or_else(|| anyhow!("$HOME not set"))?;
    Ok(PathBuf::from(home).join(".cache/node-app"))
}

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

    /// #1529 regression: `--client-node` must offset the LDK P2P port the
    /// same way it offsets HTTP/HTTPS/UI, so a legacy lane and a
    /// `--client-node` lane for the SAME instance derive distinct
    /// `InstanceProfile::p2p_port` values and don't collide on
    /// `LDK_LISTENING_ADDRESS` (see the override in `ensure_running()`).
    #[test]
    fn client_node_offsets_p2p_port_like_the_other_ports() {
        let legacy = MonorepoHost::new(
            PathBuf::from("/tmp/monorepo"),
            InstanceProfile::alice(),
            None,
            None,
            None,
            false,
        );
        let client_node = MonorepoHost::new(
            PathBuf::from("/tmp/monorepo"),
            InstanceProfile::alice(),
            None,
            None,
            None,
            true,
        );

        assert_eq!(legacy.profile.p2p_port, InstanceProfile::alice().p2p_port);
        assert_eq!(
            client_node.profile.p2p_port,
            InstanceProfile::alice().p2p_port + CLIENT_NODE_PORT_OFFSET
        );
        assert_ne!(
            legacy.profile.p2p_port, client_node.profile.p2p_port,
            "legacy and --client-node lanes for the same instance must derive \
             distinct LDK P2P ports or they'll contend for LDK_LISTENING_ADDRESS"
        );

        // Same offset applied consistently across every isolated port, not
        // just p2p — guards against a future edit that offsets one port but
        // forgets another.
        assert_eq!(
            client_node.profile.http_port,
            legacy.profile.http_port + CLIENT_NODE_PORT_OFFSET
        );
        assert_eq!(
            client_node.profile.https_port,
            legacy.profile.https_port + CLIENT_NODE_PORT_OFFSET
        );
        assert_eq!(
            client_node.profile.ui_port,
            legacy.profile.ui_port + CLIENT_NODE_PORT_OFFSET
        );
    }

    /// Two DIFFERENT instances (alice/bob) already derive distinct p2p ports
    /// from their base profiles — confirms the offset doesn't accidentally
    /// re-collide alice-pwa with plain bob (both must stay distinct too).
    #[test]
    fn client_node_alice_p2p_port_does_not_collide_with_plain_bob() {
        let alice_client_node = MonorepoHost::new(
            PathBuf::from("/tmp/monorepo"),
            InstanceProfile::alice(),
            None,
            None,
            None,
            true,
        );
        let bob_legacy = MonorepoHost::new(
            PathBuf::from("/tmp/monorepo"),
            InstanceProfile::bob(),
            None,
            None,
            None,
            false,
        );

        assert_ne!(
            alice_client_node.profile.p2p_port,
            bob_legacy.profile.p2p_port
        );
    }
}