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

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

use anyhow::{Context, Result};

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    // ── Sideload each staged dep via app.dev_load IPC ─────────────────────────
    // The platform's inotify watcher only fires on post-startup events, so
    // pre-staged apps would otherwise never be loaded — leaving them invisible
    // to /v2/node-apps and the UI. Call app.dev_load per-dep per-instance so
    // the daemon upserts the DB row and dlopens the artifact.
    if !all_dep_paths.is_empty() {
        tui::sys_log(
            log_tx_opt.as_ref(),
            format!(
                "→ sideloading {} dep(s) into {} instance(s) via app.dev_load…",
                all_dep_paths.len(),
                handles.len()
            ),
        );
        for handle in &handles {
            let mut daemon_down = false;
            for dep_path in &all_dep_paths {
                let dep_manifest = match load_manifest(dep_path) {
                    Ok(m) => m,
                    Err(e) => {
                        tui::sys_log(
                            log_tx_opt.as_ref(),
                            format!(
                                "⚠ skip dev_load — could not read manifest for {}: {:#}",
                                dep_path.display(),
                                e
                            ),
                        );
                        continue;
                    }
                };
                // platform-runtime deps repackage upstream binaries and aren't
                // loaded by the app manager — same skip rule as stage_with_status.
                if dep_manifest.app_type.eq_ignore_ascii_case("platform-runtime") {
                    continue;
                }
                // Standalone apps run as their own OS process; NodeAppManager
                // rejects them via ManagerError::StandaloneNotManaged. They get
                // spawned + supervised by spawn_standalones below instead.
                if dep_manifest.app_type.eq_ignore_ascii_case("standalone") {
                    continue;
                }
                let dest = handle.dev_dir.join(&dep_manifest.name);
                let label = if handle.name.is_empty() {
                    dep_manifest.name.clone()
                } else {
                    format!("{} [{}]", dep_manifest.name, handle.name)
                };
                match ipc_call(
                    &handle.socket_path,
                    "app.dev_load",
                    serde_json::json!({
                        "name": dep_manifest.name,
                        "path": dest.to_string_lossy(),
                    }),
                ) {
                    Ok(_) => tui::sys_log(
                        log_tx_opt.as_ref(),
                        format!("{} sideloaded", label),
                    ),
                    Err(e) => {
                        // "Connection refused" on the IPC socket means the
                        // daemon process has died (or never bound the
                        // socket). Hammering it for every remaining dep
                        // produces N identical errors and obscures the
                        // root cause. Bail out of the loop after a single
                        // clear diagnostic + cleanup hint — the next
                        // `node-app dev` invocation will rebuild + reboot
                        // from scratch.
                        let msg = format!("{:#}", e);
                        let connection_lost = msg.contains("Connection refused")
                            || msg.contains("Broken pipe")
                            || msg.contains("os error 61")
                            || msg.contains("os error 32");
                        tui::sys_log(
                            log_tx_opt.as_ref(),
                            format!("✗ dev_load {}: {}", label, msg),
                        );
                        if connection_lost {
                            // Best-effort: remove the orphaned socket so the
                            // next run's pre-boot cleanup doesn't trip over
                            // a dangling inode that points at no listener.
                            let _ = std::fs::remove_file(&handle.socket_path);
                            tui::sys_log(
                                log_tx_opt.as_ref(),
                                format!(
                                    "✗ daemon IPC unreachable for instance '{}' — skipping the remaining {} dev_load(s). \
                                     The daemon process died (check `{}/daemon.log` for the tail). \
                                     Run `node-app dev` again; the orphaned socket has been removed and the next boot will recover.",
                                    handle.name,
                                    all_dep_paths.len(),
                                    handle.dev_dir
                                        .parent()
                                        .map(|p| p.display().to_string())
                                        .unwrap_or_else(|| "<cache>".to_string()),
                                ),
                            );
                            daemon_down = true;
                            break;
                        }
                    }
                }
            }
            if daemon_down {
                // Other instances may still be alive — keep iterating.
                continue;
            }
        }
    }

    // ── Spawn standalone deps per instance ────────────────────────────────────
    // Standalone apps aren't sideloaded into the daemon — they're independent
    // processes. Spawn each (instance × standalone dep) with env vars pointing
    // at the per-instance daemon socket + per-instance UDS + staged manifest.
    // Children are tracked so we can kill them on shutdown.
    let mut spawned_standalones = spawn_standalones(
        &all_dep_paths,
        &handles,
        &args.config,
        log_tx_opt.as_ref(),
    );

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

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

    tui::sys_log(
        log_tx_opt.as_ref(),
        "→ platform running. Edit platform code in the monorepo and rerun to pick up changes. \
         Ctrl-C to stop.",
    );

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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