larust-cli 0.16.0

A Laravel-shaped web framework for Rust.
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
//! `xr dev` - watches the current app's source, rebuilds it on change, and
//! restarts the server, with the child process wired up (via
//! `LARUST_DEV_RELOAD=1`) so any open browser tab auto-refreshes once the
//! new build is back up. See `crates/larust-core/src/dev_reload.rs` and
//! `crates/larust-view/src/runtime.rs` for the server/client halves of the
//! reload signal this spawns into.
//!
//! Zero-downtime by construction: the running server is never killed
//! before a rebuild. Every successful build is copied to a fresh release
//! slot (see `release_slots.rs`) rather than spawned from the exact file
//! `cargo build`'s linker just wrote to - so the *next* build's linker
//! never finds that file held open by a running process (the Windows
//! constraint `docs/GOTCHAS.md` documents), and the previous, still-good
//! server keeps serving for the whole duration of every later build. Once
//! a server is actually up, later generations are handed off to via the
//! same admin-channel `RESTART`/`STOP` protocol `xr restart` speaks (see
//! `admin_client.rs`) - auto-enabled by `Application::serve()` itself
//! purely from `LARUST_DEV_RELOAD` being set, with no app-level opt-in
//! required.
//!
//! That "the previous build keeps serving" guarantee only ever applied
//! *after* some build had already succeeded once. The very first build of
//! a fresh session had nothing to fall back on - if it failed, nothing
//! was listening on the port at all, which looked indistinguishable from
//! the whole app being broken. `dev_placeholder` closes that gap: this
//! module binds the app's port itself, before ever running a build, and
//! hands that already-bound socket to the first successful build via the
//! exact same handoff mechanism (`larust_core::__internal::handoff`)
//! every later rebuild already uses between one app process and the next
//! - not a second, bespoke mechanism.

use crate::admin_client;
use crate::dev_placeholder;
use crate::dev_registry;
use crate::process_scan;
use crate::release_slots;
use anyhow::{Context, Result};
use larust_core::__internal::{admin, handoff, listener};
use notify_debouncer_mini::new_debouncer;
use std::io::{self, BufRead, BufReader};
use std::net::SocketAddr;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::sync::mpsc::channel;
use std::sync::{Arc, Mutex, MutexGuard};
use std::time::{Duration, Instant};
use tokio::sync::Notify;

/// `println!`/`eprintln!` alone aren't enough for a long-running process
/// like this one: `std::io::Stdout`/`Stderr`'s buffering is TTY-dependent,
/// line-buffered (flushed on every `\n`) only when actually attached to
/// a real console, and a much larger, flush-on-full-or-exit buffer
/// otherwise (piped through many IDE-integrated terminals, a wrapper
/// script, or anything else that isn't a raw terminal). A status line
/// printed just before a genuine hang (a stuck build, a stale process
/// still holding the port from an earlier session's closed terminal - see
/// `stop_any_previous_generation`'s own doc comment on that exact
/// scenario) can sit invisibly in that buffer forever, and a forced kill
/// discards it without ever flushing: reported directly as "`xr dev`
/// silently failed, no output at all," traced to this rather than any
/// single hang's root cause. Every user-facing status line in this file
/// goes through these instead of a bare `println!`/`eprintln!`, so
/// whatever already ran stays visible on screen even if whatever comes
/// next never finishes.
macro_rules! status {
    ($($arg:tt)*) => {{
        println!($($arg)*);
        let _ = ::std::io::Write::flush(&mut ::std::io::stdout());
    }};
}

macro_rules! status_err {
    ($($arg:tt)*) => {{
        eprintln!($($arg)*);
        let _ = ::std::io::Write::flush(&mut ::std::io::stderr());
    }};
}

/// `xr dev --debug`'s whole implementation: sets three env vars, in this
/// process, before anything is spawned - inherited by the first generation
/// (and every later one, transitively) exactly the way `LARUST_DEV_RELOAD`
/// itself already is, since `Command` inherits its parent's environment by
/// default and nothing here or in `lifecycle::handoff` ever clears it.
///
/// - `APP_DEBUG=true`: every `AppError::Internal`/`Config`/caught panic
///   renders full detail (message, source chain, panic message) as an HTML
///   page instead of a generic one - see `larust_core::error`'s own module
///   doc comment.
/// - `LOG_LEVEL=trace`: the most verbose tier `logging::build_filter`
///   supports - `sqlx`/`tower_sessions` stay capped at `warn` regardless
///   (see that function's own doc comment on why), everything else gets
///   maximum detail.
/// - `RUST_BACKTRACE=full`: a real Rust panic's own backtrace, printed by
///   the default panic hook before `CatchPanicLayer` ever gets a chance to
///   convert it into a response - `full` (not merely `1`) additionally
///   includes frames the default hook otherwise hides, worth having for a
///   deliberately-maximum-verbosity mode even though most of that noise is
///   framework/runtime internals rather than app code.
///
/// Each is set via `set_var` (not merged with, or deferred to, whatever
/// `.env` says) specifically so `--debug` always wins outright for this
/// session, the same "explicit CLI flag beats `.env`" precedent `--port`
/// already established for `APP_PORT`. `dotenvy::from_path` (loaded later,
/// inside the spawned app's own `Application::new()`) never overwrites an
/// already-set variable - confirmed by reading `dotenvy`'s own source, the
/// same behavior the original `dotenv` crate documents - so whatever
/// `.env` has for these three names is silently overridden for the
/// lifetime of this `xr dev` session, with no edit to the file itself.
///
/// Deliberately never touched by a plain `xr deploy`/`xr deploy --run` -
/// this is `xr dev`-only, reachable exclusively through this one explicit
/// flag, so a real deploy can never accidentally inherit maximum-verbosity,
/// full-error-detail mode the way a stray `.env` edit left uncommitted
/// might.
fn set_debug_env_vars() {
    // SAFETY: called from `run()`'s own opening block, before any other
    // thread or async task exists in this process - same justification as
    // the `LARUST_DEV_RELOAD` write immediately above this function's own
    // call site.
    unsafe {
        std::env::set_var("APP_DEBUG", "true");
        std::env::set_var("LOG_LEVEL", "trace");
        std::env::set_var("RUST_BACKTRACE", "full");
    }
}

const WATCH_DEBOUNCE: Duration = Duration::from_millis(300);

/// Mirrors (not imports - it's private to `larust_core::application`)
/// `Application`'s own `HANDOFF_READY_TIMEOUT`: how long to wait for the
/// first build's binary to announce it's actually serving before treating
/// the handoff as failed and leaving the placeholder up for another try.
const READY_TIMEOUT: Duration = Duration::from_secs(15);

/// Mirrors `larust_core::Config`'s own private `default_app_port()` - used
/// only if `.env`'s `APP_PORT` isn't set, the same fallback `dev_config()`
/// already applies to `app_name` for the same reason.
const DEFAULT_APP_PORT: u16 = 34187;

/// How long `bind_placeholder` keeps retrying a port bind after
/// `stop_any_previous_generation` asked a stale generation to stop -
/// generous relative to `Application::serve`'s own dev-mode drain timeout
/// (2s) so a slow-but-genuine drain still gets picked up, without hanging
/// indefinitely if the port turns out to be held by something else
/// entirely.
const PORT_RELEASE_RETRY_TIMEOUT: Duration = Duration::from_secs(5);
const PORT_RELEASE_RETRY_INTERVAL: Duration = Duration::from_millis(200);

/// How many ports above the app's configured one `bind_available_port`
/// will try before giving up - lets more than one Larust app run `xr dev`
/// at the same time (a different app's own dev server on the same
/// configured port, most commonly) without either needing to know the
/// other's port in advance.
const MAX_PORT_FALLBACK_ATTEMPTS: u16 = 20;

/// Real source subdirectories only - deliberately not a single recursive
/// watch over the whole app root. Registering `target/` (thousands of
/// incremental-build artifacts, churned by every build this same tool
/// triggers) with the OS watcher risks exhausting platform watch limits
/// (e.g. Linux's `fs.inotify.max_user_watches`, commonly 8192 by default
/// on a real project) and wastes work on self-inflicted events. Listing
/// the real source dirs explicitly also means `database/`'s own sqlite
/// file (a sibling of `database/migrations/`, not a descendant) is never
/// watched at all, rather than relying solely on runtime filtering to
/// exclude it.
const WATCHED_SUBDIRS: &[&str] = &[
    "app",
    "config",
    "database/migrations",
    "database/factories",
    "database/seeders",
    "resources",
    "routes",
    "src",
    "tests",
];

/// Static-asset directories - watched too, but a change confined entirely
/// to one of these never needs a rebuild: nothing under `public/` gets
/// compiled into the binary, `ServeDir` reads it straight off disk on
/// every request (`larust_core::Application::serve()`). Kept separate from
/// `WATCHED_SUBDIRS` so the watch loop in `run()` can tell "needs a
/// rebuild" apart from "just needs connected tabs told to refresh their
/// stylesheets" (`signal_asset_reload`) by which list a changed path falls
/// under, rather than re-deriving that classification some other way.
const WATCHED_ASSET_SUBDIRS: &[&str] = &["public"];

/// What's currently serving traffic, from `xr dev`'s own point of view.
enum ServerState {
    /// No successful build yet.
    NotStarted,
    /// `xr dev` itself spawned this process directly and holds its
    /// handle - true only for the very first generation, since every
    /// later generation is handed off to over the admin channel by the
    /// *previous* process, not spawned by `xr dev` itself. A
    /// `tokio::process::Child`, not `std::process::Child` - gen 1 is now
    /// spawned via `handoff::spawn_replacement_and_wait_for_ready`
    /// (async, needed to await its readiness marker the same way every
    /// later generation's handoff already does), which only ever hands
    /// back a `tokio` child.
    Direct(Box<tokio::process::Child>),
    /// A handoff has succeeded at least once - whatever's currently
    /// serving was spawned by its own predecessor, entirely outside
    /// `xr dev`'s own process tree. No handle to kill; reachable only via
    /// the address-based admin channel.
    HandedOff,
}

struct DevState {
    server: ServerState,
    generation: u64,
    /// The placeholder's own listening socket, not yet claimed by a real
    /// build - `Some` until `advance()`'s `NotStarted` arm hands it off to
    /// the first successful build, `None` forever after (every later
    /// generation is handed off directly between app processes, exactly
    /// as before this feature existed).
    placeholder_listener: Option<std::net::TcpListener>,
    /// Signaled once, the moment the first real generation is confirmed
    /// ready - tells the placeholder's accept loop to stop.
    placeholder_stop: Arc<Notify>,
    /// What the placeholder shows a request right now - updated on every
    /// build attempt for as long as `server` is still `NotStarted`.
    placeholder_message: dev_placeholder::SharedMessage,
}

pub fn run(port_override: Option<u16>, debug: bool) -> Result<()> {
    // SAFETY: the very first statement in `run()` - no other thread or
    // async task exists in this process yet, so nothing can be
    // concurrently reading the environment while this writes it. Needed
    // so the *first* generation, spawned further down via the same
    // `handoff` primitives every later generation already uses, inherits
    // `LARUST_DEV_RELOAD=1` the same way gen 2+ already does today: from
    // its parent's own environment (`Command` inherits by default), not
    // from an explicit `.env(...)` call this module makes on its behalf.
    unsafe {
        std::env::set_var("LARUST_DEV_RELOAD", "1");
    }

    if debug {
        set_debug_env_vars();
        status!(
            "xr dev: --debug is on for this session - full error detail pages (APP_DEBUG=true), \
             maximum log verbosity (LOG_LEVEL=trace), and full panic backtraces \
             (RUST_BACKTRACE=full). Never run a real deploy this way - see \
             docs/the-basics/error-handling.md's own APP_DEBUG warning."
        );
    }

    let app_root = std::env::current_dir().context("reading current directory")?;
    anyhow::ensure!(
        app_root.join("Cargo.toml").exists(),
        "no Cargo.toml in the current directory - run `xr dev` from inside a Larust app"
    );

    crate::build_cache::maybe_notify(&app_root);

    let (admin_address, app_name, app_port) = dev_config(port_override);
    crate::terminal_title::set(&format!("xr dev - {app_name}"));

    // One runtime, alive for this whole process: its worker threads drive
    // the placeholder's accept loop in the background for the entire
    // `xr dev` session, and `advance()` later uses `runtime.block_on(...)`
    // for the one-shot async handoff call that claims the placeholder's
    // socket - the same "sync `run()`, occasional async call" shape
    // `admin_client.rs`'s own Windows client already uses, just longer-
    // lived here since something needs to actually serve concurrently.
    let runtime = tokio::runtime::Runtime::new()
        .context("failed to start the placeholder server's async runtime")?;

    // Best-effort, before ever attempting to bind: a stale generation from
    // an earlier `xr dev` (e.g. one left running because closing a
    // terminal/IDE window doesn't reliably kill it - nothing on Windows
    // ties a spawned child's lifetime to the console that started it) may
    // already be holding this app's port. Asking it to stop first, rather
    // than immediately failing on `AddrInUse`, is what actually closes
    // that gap.
    let found_previous_generation = stop_any_previous_generation(&admin_address);

    let placeholder_message = dev_placeholder::initial_message();
    let placeholder_stop = Arc::new(Notify::new());
    let (placeholder_listener, bound_port) = bind_placeholder(
        &runtime,
        app_port,
        found_previous_generation,
        app_name.clone(),
        Arc::clone(&placeholder_message),
        Arc::clone(&placeholder_stop),
    )?;
    if bound_port != app_port {
        // Worded off `found_previous_generation`, not just "is the port
        // free" - reported directly: a previous generation of *this same
        // app*, left running by an ungraceful kill of an earlier `xr dev`
        // (ungraceful enough that nothing had a chance to ask it to stop
        // - a crash, a broken pipe, `kill -9`), can still be genuinely
        // alive and holding `app_port` with a perfectly responsive admin
        // channel; `stop_any_previous_generation` above already found and
        // signalled exactly that case (its own status line already said
        // so). Blaming "something else" there is actively wrong, not just
        // vague - the fix is a few seconds' patience (it's mid-drain), not
        // investigating a port conflict with some other app.
        if found_previous_generation {
            status!(
                "xr dev: port {app_port} is still held by this app's own previous generation - \
                 it was asked to stop but hasn't released the port yet, so using {bound_port} \
                 for now"
            );
        } else {
            status!(
                "xr dev: port {app_port} is already in use by something else (likely a different \
                 app's own `xr dev`) - using {bound_port} instead"
            );
        }
    }

    // Best-effort: `xr list`/`xr kill` degrade gracefully with no registry
    // entry at all (this session just doesn't show up / can't be reached
    // by id), the same tolerance a failed `release_slots::prune` attempt
    // already gets - never worth failing `xr dev`'s own startup over.
    if let Err(error) = dev_registry::register(&dev_registry::Session {
        pid: std::process::id(),
        app_name: app_name.clone(),
        project_dir: app_root.clone(),
        port: bound_port,
        admin_address: admin_address.clone(),
        started_at_unix: dev_registry::now_unix(),
    }) {
        status_err!("xr dev: couldn't register this session for `xr list`/`xr kill`: {error}");
    }

    let state: Arc<Mutex<DevState>> = Arc::new(Mutex::new(DevState {
        server: ServerState::NotStarted,
        generation: starting_generation(&app_root),
        placeholder_listener: Some(placeholder_listener),
        placeholder_stop,
        placeholder_message,
    }));
    register_ctrlc_handler(
        Arc::clone(&state),
        admin_address.clone(),
        runtime.handle().clone(),
    );

    // Unbounded: bounded strictly by how fast a human can save files, not
    // by build throughput - `notify-debouncer-mini` already coalesces
    // bursts on its own side before anything reaches this channel, so
    // there's no realistic way for this to grow unbounded in practice.
    let (tx, rx) = channel();
    let mut debouncer =
        new_debouncer(WATCH_DEBOUNCE, tx).context("failed to start file watcher")?;
    watch_source_dirs(&mut debouncer, &app_root)?;

    status!(
        "xr dev: watching {} - press Ctrl+C to stop",
        app_root.display()
    );
    status!("xr dev: serving a placeholder on port {bound_port} until the first build succeeds");
    rebuild_and_restart(&app_root, &state, &admin_address, &runtime);

    // Captured *after* the first build, not before - the app itself has
    // already read `.env` once by this point (that initial read is what
    // this baseline is meant to not react to), so only edits from here
    // on should ever trigger a rebuild.
    let mut last_env_mtime = env_mtime(&app_root);
    let mut last_prune = Instant::now();
    loop {
        // Checked every tick, whatever woke this loop up - see
        // `env_mtime`'s own doc comment for why `.env` is deliberately
        // polled here instead of registered with the OS-level watcher
        // every other watched path goes through.
        let current_env_mtime = env_mtime(&app_root);
        if current_env_mtime != last_env_mtime {
            last_env_mtime = current_env_mtime;
            status!("\nxr dev: change detected, rebuilding...");
            rebuild_and_restart(&app_root, &state, &admin_address, &runtime);
        }

        // Retry stale slots even without another rebuild: a draining Windows
        // process may have kept a previous deletion from succeeding.
        if last_prune.elapsed() >= Duration::from_secs(30) {
            let generation = lock_state(&state).generation;
            release_slots::prune(&app_root, "dev", generation);
            last_prune = Instant::now();
        }
        let result = match rx.recv_timeout(Duration::from_secs(1)) {
            Ok(result) => result,
            Err(std::sync::mpsc::RecvTimeoutError::Timeout) => continue,
            Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => break,
        };
        match result {
            Ok(events) => {
                let relevant: Vec<_> = events
                    .iter()
                    .filter(|e| is_relevant(&app_root, &e.path))
                    .collect();
                if relevant.is_empty() {
                    continue;
                }
                if relevant.iter().all(|e| is_asset_only(&app_root, &e.path)) {
                    status!("\nxr dev: asset change detected, refreshing connected browsers...");
                    signal_asset_reload(&state, &admin_address);
                } else {
                    status!("\nxr dev: change detected, rebuilding...");
                    rebuild_and_restart(&app_root, &state, &admin_address, &runtime);
                }
            }
            Err(error) => status_err!("xr dev: watch error: {error}"),
        }
    }

    Ok(())
}

/// Computed once, up front, by reading `APP_NAME`/`APP_PORT` straight from
/// `.env` relative to the current working directory, which is already
/// `app_root` here (`run()` derived `app_root` from
/// `std::env::current_dir()` itself) - the same values a real run of the
/// app itself would use, without going through `larust_core::Config`/the
/// app's own generated `config/app.rs` at all: this runs in a *separate*
/// `xr` process, outside the target app's compiled binary, so it can't
/// call a function only that binary's crate defines. Falls back to
/// [`app_name_default`]/`Config`'s own known `app_port` field default
/// (`34187`) for anything `.env` doesn't set - `xr dev` should still be
/// able to watch and rebuild (and the placeholder should still bind
/// *some* port) even then; a hard failure this early would be a worse
/// experience than either value simply not lining up in that unlikely
/// edge case.
///
/// `port_override` (`xr dev --port`) wins over `.env`'s `APP_PORT` for
/// *this run only* - deliberately not written back to `.env`, so it never
/// outlives the one invocation it was passed to. This only ever changes
/// what port `run()` binds *its own* placeholder/handoff listener on (see
/// this module's own doc comment) - the built app binary itself never
/// independently resolves a port at all, it just inherits whatever
/// already-bound socket the handoff hands it, so there's no separate
/// child-process env var to thread this through to.
fn dev_config(port_override: Option<u16>) -> (String, String, u16) {
    dotenvy::from_filename(".env").ok();
    let app_name = std::env::var("APP_NAME").unwrap_or_else(|_| app_name_default());
    let app_port = resolve_app_port(
        port_override,
        std::env::var("APP_PORT").ok().as_deref(),
        std::env::var("APP_URL").ok().as_deref(),
    );
    let address = admin::channel_address(&app_name);
    (address, app_name, app_port)
}

/// The actual override-precedence logic behind [`dev_config`]'s
/// `app_port`, split out so it's unit-testable without real `.env`/CWD
/// I/O - same "split out the pure logic" precedent as
/// [`app_name_default`]/`app_name_default_from_source`. `port_override`
/// beats `env_app_port` (a malformed `APP_PORT` value is treated the same
/// as an absent one, not a hard error - matching this whole function's
/// existing "still usable even when `.env` doesn't line up" tolerance),
/// which beats a port parsed out of `env_app_url` if it has one, which
/// beats [`DEFAULT_APP_PORT`]. The `APP_URL` tier mirrors
/// `larust_support::config_env::app_port_or`'s own identical addition to
/// the *compiled app's* own port resolution - requested directly, after a
/// real `xr convert`-ed project (whose own `.env` never had `APP_PORT` at
/// all, only an `APP_URL` carrying the intended dev port) landed on the
/// wrong port; `xr dev`'s own copy of this logic needs the same leniency,
/// since it resolves the port *before* ever building the app, from its
/// own separate read of `.env`.
pub(crate) fn resolve_app_port(
    port_override: Option<u16>,
    env_app_port: Option<&str>,
    env_app_url: Option<&str>,
) -> u16 {
    port_override
        .or_else(|| env_app_port.and_then(|p| p.parse().ok()))
        .or_else(|| env_app_url.and_then(port_from_url))
        .unwrap_or(DEFAULT_APP_PORT)
}

/// See `larust_support::config_env::port_from_url`'s own doc comment for
/// the exact shape and reasoning - duplicated here, not shared, since `xr
/// dev` runs in a separate process from the target app and can't depend
/// on `larust-support` just for this one small parse (the same
/// "duplicate the pure logic across this process boundary" precedent
/// [`app_name_default`] already sets for the identical constraint).
fn port_from_url(url: &str) -> Option<u16> {
    let without_scheme = url.split_once("://").map_or(url, |(_, rest)| rest);
    let authority_end = without_scheme
        .find(['/', '?', '#'])
        .unwrap_or(without_scheme.len());
    let (_, port) = without_scheme[..authority_end].rsplit_once(':')?;
    port.parse().ok()
}

/// Best-effort recovery of the `app_name` default the *running app itself*
/// would actually fall back to when `.env` doesn't set `APP_NAME` -
/// **not** a hardcoded guess.
///
/// Real bug this fixes: this function used to just hardcode `"Larust"`
/// (`larust_core::Config`'s own generic field default), on the assumption
/// that both sides - this `xr` process and the running app - would always
/// agree on it independently, matching `admin`'s own "no runtime
/// negotiation needed" design (see its module doc comment). That
/// assumption holds for an `xr new`-scaffolded app (its generated
/// `config/app.rs` uses that exact same generic default), but not for an
/// `xr convert`-ed one: `config_template::render_app_config_rs` fills in
/// whatever literal `app_name` the source Laravel app's own `config/
/// app.php` actually had (Laravel's own stock default is `"Laravel"`, not
/// `"Larust"`) - a real, deliberate difference, not an oversight (see that
/// module's own doc comment). So for any converted app with no explicit
/// `APP_NAME` in `.env`, this side computed `\\.\pipe\larust-Larust`
/// while the running server computed `\\.\pipe\larust-Laravel` - two
/// different channels that could never meet, silently forcing every `xr
/// dev` rebuild onto the "couldn't reach the admin channel, still serving
/// the last successful build" fallback path forever.
///
/// Both `xr new` and `xr convert` always generate `config/app.rs` with the
/// exact same `env_or("APP_NAME", "<default>")` shape (see
/// `config_template::render_app_config_rs`), so recovering the real
/// default is a plain substring search on that one well-known file -
/// deliberately not a real Rust parse: this runs outside the target app's
/// compiled binary (see this function's own caller), so there's no `syn`/
/// build-script machinery available or worth pulling in just for this.
/// Falls back to the old hardcoded `"Larust"` if the file is missing or
/// doesn't match the expected shape (a hand-edited `config/app.rs`, or a
/// pre-existing app from before this function existed) - the previous,
/// still-usually-correct behavior, not a hard failure.
pub(crate) fn app_name_default() -> String {
    match std::fs::read_to_string("config/app.rs") {
        Ok(source) => app_name_default_from_source(&source),
        Err(_) => FALLBACK_APP_NAME.to_string(),
    }
}

const FALLBACK_APP_NAME: &str = "Larust";

/// The actual extraction logic behind [`app_name_default`], split out so
/// it can be unit tested against a literal string - no real
/// `config/app.rs` file, no CWD manipulation (tests run in parallel and
/// CWD is process-global, so changing it in a test would race every other
/// test in this binary).
fn app_name_default_from_source(source: &str) -> String {
    const NEEDLE: &str = "env_or(\"APP_NAME\", \"";
    let Some(start) = source.find(NEEDLE) else {
        return FALLBACK_APP_NAME.to_string();
    };
    let rest = &source[start + NEEDLE.len()..];
    match rest.find('"') {
        Some(end) => rest[..end].to_string(),
        None => FALLBACK_APP_NAME.to_string(),
    }
}

/// The in-memory generation counter `DevState`/`rebuild_and_restart` bump
/// on every rebuild starts from here rather than a hardcoded `0` - a real,
/// empirically-confirmed bug this fixes: a hardcoded `0` meant *every*
/// fresh `xr dev` invocation (a new terminal, a restart after closing your
/// editor, anything short of one unbroken session) started renumbering
/// `dev-N` slots from `1` again, regardless of how far a previous session
/// had already gotten. Two compounding consequences, both real, not
/// theoretical: `release_slots::prune`'s own `current_generation -
/// KEEP_GENERATIONS` window is anchored to whatever this counter says
/// *right now* - a fresh session's own low numbers can never reach back far
/// enough to prune a previous session's now-orphaned leftovers, which then
/// linger on disk forever (confirmed directly: a real `demo/storage/
/// releases/` directory accumulated `dev-6`, `dev-31` through `dev-34`, and
/// `dev-37` through `dev-40` - three-or-so leftover slots per session
/// restart, never cleaned by any later session). Worse, `release_slots::
/// publish`'s own "never reuses a slot" safety guarantee (see that module's
/// doc comment - it's the entire reason a monotonic counter exists instead
/// of a fixed-size rotation) only actually holds *within* one session's own
/// counter; a fresh session's `dev-1` could silently overwrite a `dev-1`
/// slot a *previous*, not-yet-fully-drained session's own generation 1 was
/// still running from, if it happened to still exist. Reading the real
/// highest existing `dev-N` slot off disk - the same thing `xr deploy`'s
/// own one-shot process already has to do via this identical function,
/// for the identical "nothing in memory carries over between invocations"
/// reason - closes both gaps: numbering (and therefore pruning) picks up
/// exactly where the disk's own history actually left off, regardless of
/// how many `xr dev` sessions came and went in between.
fn starting_generation(app_root: &Path) -> u64 {
    release_slots::next_generation(app_root, "dev").saturating_sub(1)
}

/// Best-effort: asks whatever's already listening on this app's own admin
/// channel to gracefully stop, before `xr dev` ever tries to bind the
/// port itself. Safe to call unconditionally - the admin channel is a
/// separate, per-app-name address from the TCP port (see
/// `admin::channel_address`), never the port itself, so if nothing from
/// *this* app is still running, `send_command` simply fails to connect
/// and this is a silent no-op; it never reaches out to whatever else
/// might happen to be using the port for unrelated reasons.
///
/// Returns whether a previous generation was actually found and
/// signalled - `bind_available_port`'s caller needs this, not just this
/// function's own status line, to word the "port already in use"
/// fallback message correctly if the port still isn't free once binding
/// is actually attempted (see that message's own comment for why this
/// distinction, not just a yes/no on whether the port was free, is what
/// it needs).
fn stop_any_previous_generation(admin_address: &str) -> bool {
    let found = admin_client::send_command(admin_address, admin::STOP_COMMAND).is_ok();
    if found {
        status!("xr dev: found a previous generation of this app still running - stopping it...");
    }
    found
}

/// Retries a plain bind for a short window when the port is still in use -
/// covers the gap between `stop_any_previous_generation`'s `STOP` being
/// acknowledged and the old process actually finishing its graceful
/// drain and releasing the socket (bounded by `Application::serve`'s own
/// dev-mode drain timeout). Gives up once `PORT_RELEASE_RETRY_TIMEOUT`
/// elapses and reports `AddrInUse` back to the caller - the signal
/// `bind_available_port` uses to tell "this app's own stale generation,
/// still finishing its drain" apart from "something else entirely owns
/// this port", which get two different responses.
///
/// `retry` is `false` whenever `stop_any_previous_generation` found
/// nothing to signal in the first place - there's then nothing worth
/// waiting on: the port is held by something that was never asked to
/// stop and has no reason to release it on its own, so this makes exactly
/// one attempt instead of waiting out the full window for no reason.
fn bind_with_retry(addr: SocketAddr, retry: bool) -> io::Result<std::net::TcpListener> {
    if !retry {
        return listener::bind(addr);
    }
    let deadline = Instant::now() + PORT_RELEASE_RETRY_TIMEOUT;
    loop {
        match listener::bind(addr) {
            Ok(tcp_listener) => return Ok(tcp_listener),
            Err(error) if error.kind() == io::ErrorKind::AddrInUse && Instant::now() < deadline => {
                std::thread::sleep(PORT_RELEASE_RETRY_INTERVAL);
            }
            Err(error) => return Err(error),
        }
    }
}

/// Tries `starting_port` first (with `bind_with_retry`'s own short wait
/// when `found_previous_generation` is true, covering a stale generation
/// of *this same app* still finishing the graceful drain
/// `stop_any_previous_generation` just asked it to do), then
/// `starting_port + 1, + 2, ...` once each with no wait - reaching this
/// point means `starting_port` is held by something that was never asked
/// to stop (or was asked and still didn't let go in time) and has no
/// further reason to release it on its own: a different Larust app's own
/// `xr dev`, most likely. Incrementing past it rather than failing
/// outright is what lets more than one app run `xr dev` at the same time
/// without either needing to know the other's port up front - the same
/// experience running two unrelated dev servers side by side already
/// gives you. Returns the listener together with whichever port it
/// actually bound, since that may not be `starting_port`.
fn bind_available_port(
    starting_port: u16,
    found_previous_generation: bool,
) -> io::Result<(std::net::TcpListener, u16)> {
    match bind_with_retry(
        SocketAddr::from(([127, 0, 0, 1], starting_port)),
        found_previous_generation,
    ) {
        Ok(tcp_listener) => return Ok((tcp_listener, starting_port)),
        Err(error) if error.kind() != io::ErrorKind::AddrInUse => return Err(error),
        Err(_) => {}
    }

    let mut last_error = None;
    for offset in 1..=MAX_PORT_FALLBACK_ATTEMPTS {
        let port = starting_port.saturating_add(offset);
        match listener::bind(SocketAddr::from(([127, 0, 0, 1], port))) {
            Ok(tcp_listener) => return Ok((tcp_listener, port)),
            Err(error) if error.kind() == io::ErrorKind::AddrInUse => last_error = Some(error),
            Err(error) => return Err(error),
        }
    }
    Err(last_error.unwrap_or_else(|| {
        io::Error::new(
            io::ErrorKind::AddrInUse,
            format!(
                "no free port found in {starting_port}..={}",
                starting_port.saturating_add(MAX_PORT_FALLBACK_ATTEMPTS)
            ),
        )
    }))
}

/// Binds the placeholder's listener and spawns its accept loop onto
/// `runtime`, mirroring `Application::serve()`'s own clone-then-split
/// pattern exactly (`crates/larust-core/src/application.rs`): clone
/// *before* setting either handle non-blocking, so the handle kept for a
/// later handoff (`placeholder_listener`, returned here) stays a plain
/// blocking `std::net::TcpListener` - `prepare_for_handoff` only ever
/// needs a valid handle to extract/duplicate the underlying socket from,
/// never `accept()`s on it directly. The other handle is what actually
/// gets adopted into `tokio` and accepts real placeholder connections.
/// Returns the port actually bound (see `bind_available_port`) alongside
/// the listener - every later generation this session hands off to
/// inherits this exact socket, so whichever port is decided here is what
/// the whole `xr dev` session serves on, not necessarily `port`.
fn bind_placeholder(
    runtime: &tokio::runtime::Runtime,
    port: u16,
    found_previous_generation: bool,
    app_name: String,
    message: dev_placeholder::SharedMessage,
    stop: Arc<Notify>,
) -> Result<(std::net::TcpListener, u16)> {
    let (std_listener, bound_port) = bind_available_port(port, found_previous_generation)
        .with_context(|| format!("failed to bind a port for `xr dev` starting at {port}"))?;
    let placeholder_listener = std_listener
        .try_clone()
        .context("failed to clone the placeholder listener")?;
    std_listener
        .set_nonblocking(true)
        .context("failed to set the placeholder listener non-blocking")?;

    // `TcpListener::from_std` registers the socket with the *current*
    // async runtime's I/O driver - merely holding a `Runtime` value isn't
    // enough, since nothing has made it the ambient context on this
    // thread yet. `enter()` does exactly that for the scope of this one
    // call; `runtime.spawn(...)` right below doesn't need it (it's a
    // method on `Runtime` itself, not the free `tokio::spawn`, so it
    // already knows which runtime to hand the task to).
    let _guard = runtime.enter();
    let tokio_listener = tokio::net::TcpListener::from_std(std_listener)
        .context("failed to adopt the placeholder listener into tokio")?;

    runtime.spawn(dev_placeholder::serve(
        tokio_listener,
        app_name,
        message,
        stop,
    ));

    Ok((placeholder_listener, bound_port))
}

fn watch_source_dirs(
    debouncer: &mut notify_debouncer_mini::Debouncer<notify::RecommendedWatcher>,
    app_root: &Path,
) -> Result<()> {
    for subdir in WATCHED_SUBDIRS.iter().chain(WATCHED_ASSET_SUBDIRS) {
        let path = app_root.join(subdir);
        if !path.exists() {
            continue;
        }
        debouncer
            .watcher()
            .watch(&path, notify::RecursiveMode::Recursive)
            .with_context(|| format!("failed to watch {}", path.display()))?;
    }

    // `.env` is deliberately *not* registered with the OS-level watcher
    // here - see `env_mtime`'s own doc comment for why, and `run()`'s own
    // loop for how its edits are detected instead.
    Ok(())
}

/// `.env`'s current modification time, `None` if it doesn't exist (not
/// every app ships one) - `run()`'s own loop compares this against its
/// last-seen value on every tick to detect a real edit, instead of
/// registering `.env` with the OS-level watcher `watch_source_dirs`
/// otherwise uses for everything else.
///
/// **Why this exists, not a plain inotify watch on the file**: reported
/// directly, with a full reproduction - a fresh `xr new` app's `xr dev`
/// never settles, continuously "detecting a change" and rebuilding (the
/// generation counter climbing by itself, dozens of times, with no file
/// ever actually edited). Root cause, confirmed against `notify`'s own
/// Linux/inotify backend source: a plain *read* of `.env` (exactly what
/// `larust_core::Application` does on every app start, via `dotenvy::
/// from_path`) still generates a real `IN_OPEN` event, because `notify`'s
/// inotify backend subscribes to `WatchMask::OPEN` unconditionally for
/// every watch it registers - there is no "read-only" vs "write" event
/// filter available at that layer. Worse, `notify-debouncer-mini` (the
/// layer this module actually consumes events through) discards the
/// underlying `notify::EventKind` entirely before anything here ever
/// sees it - a `DebouncedEvent` carries only a path and a coarse `Any`/
/// `AnyContinuous` kind, so filtering on "was this a read or a write" is
/// not possible after the fact, only by never routing `.env` through
/// that watcher in the first place. Comparing `mtime` instead sidesteps
/// this structurally: a plain open-and-read never updates a file's own
/// modification time, only a real write does, so this can't produce the
/// same false positive regardless of how many times the app itself
/// re-reads the file on every restart.
fn env_mtime(app_root: &Path) -> Option<std::time::SystemTime> {
    std::fs::metadata(app_root.join(".env"))
        .ok()?
        .modified()
        .ok()
}

/// Never kills the previous server before rebuilding - the whole point of
/// copying each successful build to its own release slot (see
/// `release_slots.rs`) is that the previous, still-good process never
/// holds the file the next build's linker needs to write to, so it can
/// simply keep serving for the entire duration of the build. A build that
/// fails outright leaves the last known-good process serving, unaffected.
///
/// The lock is held for the *entire* function, same reason as before:
/// holding it means a concurrent Ctrl+C simply blocks until this rebuild
/// finishes (and then tears down whatever it produced) instead of racing
/// it.
fn rebuild_and_restart(
    app_root: &Path,
    state: &Arc<Mutex<DevState>>,
    admin_address: &str,
    runtime: &tokio::runtime::Runtime,
) {
    let mut guard = lock_state(state);
    notify_build_status(&guard, admin_address, "building");

    match build(app_root, false) {
        Ok(Some(binary)) => {
            let generation = guard.generation + 1;
            match release_slots::publish(app_root, &binary, "dev", generation) {
                Ok(slot) => {
                    guard.generation = generation;
                    release_slots::prune(app_root, "dev", generation);
                    advance(&mut guard, &slot, admin_address, generation, runtime);
                }
                Err(error) => {
                    let still_serving = still_serving_message(&guard);
                    status_err!(
                        "xr dev: build succeeded but failed to publish release slot: {error}\n\
                         xr dev: {still_serving}"
                    );
                    dev_placeholder::set_message(
                        &guard.placeholder_message,
                        format!("Build succeeded but failed to publish release slot:\n{error}"),
                    );
                    notify_build_status(&guard, admin_address, "failed");
                }
            }
        }
        Ok(None) => {
            let still_serving = still_serving_message(&guard);
            status_err!("xr dev: build produced no binary artifact\nxr dev: {still_serving}");
            dev_placeholder::set_message(
                &guard.placeholder_message,
                "Build produced no binary artifact - check your app's [[bin]] target.",
            );
            notify_build_status(&guard, admin_address, "failed");
        }
        Err(error) => {
            let still_serving = still_serving_message(&guard);
            status_err!("xr dev: build failed\n{error}\nxr dev: {still_serving}");
            dev_placeholder::set_message(
                &guard.placeholder_message,
                format!("Build failed:\n\n{error}"),
            );
            notify_build_status(&guard, admin_address, "failed");
        }
    }
}

/// The trailing status line a failed build reports - distinct wording for
/// "no server has ever come up yet" (the placeholder is still what's
/// serving) versus "a previous generation is still fine" (unchanged from
/// before this feature existed), since only one of those is reassuring.
fn still_serving_message(guard: &DevState) -> &'static str {
    match guard.server {
        ServerState::NotStarted => "no server has started yet - still serving the placeholder page",
        ServerState::Direct(_) | ServerState::HandedOff => {
            "still serving the last successful build"
        }
    }
}

/// Moves `state.server` forward for a freshly-published `slot`: for the
/// very first generation, claims the placeholder's own already-bound
/// socket via a real handoff (the same mechanism every later generation
/// already uses between one app process and the next - see this module's
/// own doc comment); for every later generation, hands off to the
/// already-running process over the admin channel exactly as before.
fn advance(
    guard: &mut MutexGuard<'_, DevState>,
    slot: &Path,
    admin_address: &str,
    generation: u64,
    runtime: &tokio::runtime::Runtime,
) {
    match std::mem::replace(&mut guard.server, ServerState::NotStarted) {
        ServerState::NotStarted => {
            let Some(listener) = guard.placeholder_listener.take() else {
                // Can only happen if a previous attempt already consumed
                // the listener and then failed to become `Direct` for
                // some reason other than the ones handled below - treat
                // as a transient failure rather than panicking.
                status_err!(
                    "xr dev: no placeholder listener available to hand off to {generation}"
                );
                return;
            };
            // `true`: `xr dev` itself is not a member of any job object
            // and needs generation 1 explicitly registered - see
            // `spawn_replacement_and_wait_for_ready`'s own doc comment.
            match runtime.block_on(handoff::spawn_replacement_and_wait_for_ready(
                &listener,
                slot,
                READY_TIMEOUT,
                true,
            )) {
                Ok(Some(child)) => {
                    guard.server = ServerState::Direct(Box::new(child));
                    guard.placeholder_stop.notify_one();
                    status!("xr dev: built and running (generation {generation})");
                }
                Ok(None) => {
                    guard.placeholder_listener = Some(listener);
                    dev_placeholder::set_message(
                        &guard.placeholder_message,
                        format!(
                            "{} built, but didn't report ready within {}s.",
                            slot.display(),
                            READY_TIMEOUT.as_secs()
                        ),
                    );
                    status_err!(
                        "xr dev: {} built but never reported ready - still serving the placeholder page",
                        slot.display()
                    );
                }
                Err(error) => {
                    guard.placeholder_listener = Some(listener);
                    dev_placeholder::set_message(
                        &guard.placeholder_message,
                        format!("Failed to start {}:\n{error}", slot.display()),
                    );
                    status_err!("xr dev: failed to start {}: {error}", slot.display());
                }
            }
        }
        ServerState::Direct(child) => {
            reap_in_background(*child, runtime.handle());
            request_handoff(guard, admin_address, generation);
        }
        ServerState::HandedOff => {
            request_handoff(guard, admin_address, generation);
        }
    }
}

/// Sends `RELOAD_ASSETS` directly to whichever process currently owns
/// `admin_address` - no build, no handoff, just a push to any connected
/// browser tab's dev-reload client (`larust_core::dev_reload::broadcast_asset_reload`).
/// A silent no-op while still on the placeholder (`ServerState::NotStarted`):
/// there's no admin channel to reach yet, and no compiled app for the
/// change to matter to anyway - the very next successful build will pick
/// up the asset change like normal.
fn signal_asset_reload(state: &Arc<Mutex<DevState>>, admin_address: &str) {
    if matches!(lock_state(state).server, ServerState::NotStarted) {
        return;
    }
    if let Err(error) = admin_client::send_command(admin_address, admin::RELOAD_ASSETS_COMMAND) {
        status_err!(
            "xr dev: couldn't reach the running server's admin channel to refresh assets: {error}"
        );
    }
}

/// Pushes a `build-status` SSE event (`"building"`/`"failed"`) to whatever
/// currently owns `admin_address`'s connected dev-reload clients - see
/// `larust_core::dev_reload`'s own module doc comment for why the ordinary
/// "connection drops and reconnects" reload signal alone doesn't cover this
/// case: the *old*, still-good process keeps serving throughout every
/// rebuild after the first one, by design, so its SSE connection to any
/// open tab never actually drops on its own. A silent no-op while still on
/// the placeholder (`ServerState::NotStarted`) - same guard
/// `signal_asset_reload` already uses, for the same reason: no admin
/// channel to reach yet, and the placeholder page has no dev-reload script
/// to receive this anyway.
fn notify_build_status(guard: &DevState, admin_address: &str, status: &str) {
    if matches!(guard.server, ServerState::NotStarted) {
        return;
    }
    let command = format!("{} {status}", admin::BUILD_STATUS_COMMAND);
    if let Err(error) = admin_client::send_command(admin_address, &command) {
        status_err!(
            "xr dev: couldn't reach the running server's admin channel to signal build \
             status: {error}"
        );
    }
}

/// Sends `RESTART` to whichever process currently owns `admin_address` -
/// reliable regardless of spawn lineage, since the channel is address-
/// based, not pid-based (see `admin::STOP_COMMAND`'s own doc comment for
/// why that matters). A failed attempt (the app not actually listening
/// yet, a transient pipe/socket hiccup) leaves `state.server` as
/// `HandedOff` anyway - the previous generation is still the one
/// genuinely running in that case, and the next successful build's own
/// `RESTART` will simply try again.
fn request_handoff(guard: &mut MutexGuard<'_, DevState>, admin_address: &str, generation: u64) {
    guard.server = ServerState::HandedOff;
    match admin_client::send_command(admin_address, admin::RESTART_COMMAND) {
        Ok(response) if response == admin::ACK_HANDOFF_STARTED => {
            status!("xr dev: rebuilt and restarted (generation {generation})");
        }
        Ok(response) if response == admin::ACK_HANDOFF_FAILED => {
            status_err!(
                "xr dev: restart handoff failed (the new build didn't come up in time) - \
                 still serving the last successful build"
            );
            notify_build_status(&*guard, admin_address, "failed");
        }
        Ok(other) => {
            status_err!("xr dev: unexpected response from the admin channel: {other:?}");
        }
        Err(error) => {
            status_err!(
                "xr dev: couldn't reach the running server's admin channel: {error}\n\
                 xr dev: still serving the last successful build"
            );
        }
    }
}

/// A `Child` that's already been hand-off'd away from doesn't need its
/// exit status for anything - but dropping a `tokio::process::Child`
/// without ever calling `wait()` on it leaves a zombie process entry on
/// Unix until `xr dev` itself exits (Windows has no equivalent concept;
/// the handle is simply closed). The old process is already busy
/// gracefully draining and will exit on its own shortly (bounded by the
/// dev-specific drain timeout) - reaped here on a background task so the
/// watch loop itself never blocks waiting for that drain to finish.
fn reap_in_background(mut child: tokio::process::Child, handle: &tokio::runtime::Handle) {
    handle.spawn(async move {
        let _ = child.wait().await;
    });
}

/// Runs `cargo build`, capturing its JSON `stdout` stream to find the built
/// binary's exact path (the robust way - not guessing `target/debug/<name>`,
/// which would get the wrong answer for a release build, a workspace-nested
/// target dir vs. a standalone app's own, etc.) while separately capturing
/// (and live-relaying to this process's own `stderr`) the human-readable
/// diagnostic text `--color=always` forces regardless of `stderr` being
/// piped rather than a real terminal. The captured text becomes a failed
/// build's actual `Err` content - see [`format_build_failure`]'s own doc
/// comment for why this reads `stderr`, not `--message-format`'s own JSON
/// `compiler-message` events: confirmed empirically (not assumed), a hard
/// parse/syntax error - the single most common class of error while
/// actively editing code - never reaches that JSON channel at all, only
/// `stderr`. A design that only read `compiler-message` events would give
/// real detail for a type error but silently fall back to nothing for a
/// missing semicolon, the exact gap that was actually reported.
///
/// Filters `compiler-artifact` messages to ones whose `target.kind`
/// includes `"bin"`, so a build script's or dependency's own artifact
/// (also emitted as `compiler-artifact` messages, in every generated app
/// today - sqlx's own macros crate has one) is never mistaken for the
/// app's server binary. Among bin artifacts this still takes the *last*
/// one, which is only unambiguous while a generated app has a single
/// `[[bin]]` target (true for every app this CLI scaffolds today); a
/// future multi-binary app (e.g. a queue-worker binary alongside the web
/// server) would need this to also match the target/package name against
/// the app's own `Cargo.toml`, not implemented here.
///
/// `release: true` adds `--release` - used by `deploy::run`'s own web-mode
/// build, sharing this exact artifact-discovery logic rather than
/// duplicating it (a naive `target/release/<name>` guess has the same
/// workspace-nesting/multi-binary problems this function's own doc comment
/// already describes for the debug case).
///
/// Wraps [`build_once`] with a bounded retry for one specific, previously
/// misdiagnosed failure shape - reported directly: `xr dev`'s rebuild on a
/// change failing outright with `error: failed to remove file
/// ...\target\debug\<name>.exe` / `Caused by: Access is denied. (os error
/// 5)`, even though this crate's own "zero-downtime by construction"
/// design (see this module's own top doc comment) means the running
/// server is never spawned from that exact path - it runs from a
/// `release_slots`-published *copy*, specifically so nothing in `xr dev`'s
/// own process tree ever holds `target/debug/<name>.exe` open while a
/// later build tries to overwrite it. Something *outside* that process
/// tree briefly held it instead - almost certainly the same root cause
/// already diagnosed for `xr upgrade`'s own "Access is denied" failure
/// moving a freshly-built binary (see `upgrade.rs`'s
/// `ensure_binary_not_locked` doc comment): Windows Defender (or another
/// antivirus/EDR product) scanning the just-linked `.exe` before
/// releasing its handle, not an `xr`-owned process - nothing this binary
/// itself can detect or wait on *before* the build the way
/// `ensure_binary_not_locked`'s own `xr`-process check can.
///
/// Retrying the *whole* build, not just the failed removal, is the only
/// option (cargo's linker owns that step internally), but it's not as
/// wasteful as it sounds: cargo's own incremental cache already has every
/// `.rlib`/object file up to date from the attempt that just failed, so a
/// retry re-does essentially nothing but the one failed link. In the
/// common case (a scan that clears in well under a second) this makes the
/// whole failure invisible - the rebuild just looks very slightly slower.
/// Deliberately narrow: only retries on Windows, and only when the
/// captured failure text matches this *exact* signature
/// ([`process_scan::looks_like_a_transient_windows_file_lock`] - shared
/// with `upgrade.rs`'s identical retry loop around `cargo install`, since
/// both are the same underlying Windows behavior reported against two
/// different commands) - retrying an ordinary compile error (a missing
/// semicolon, a type mismatch) would just delay the developer's feedback
/// by several seconds for no benefit, since those fail identically on
/// every attempt.
pub(crate) fn build(app_root: &Path, release: bool) -> Result<Option<PathBuf>> {
    let mut attempt = 0;
    loop {
        match build_once(app_root, release) {
            Ok(executable) => return Ok(executable),
            Err(error) => {
                attempt += 1;
                if !cfg!(windows)
                    || attempt > BUILD_LOCK_RETRY_ATTEMPTS
                    || !process_scan::looks_like_a_transient_windows_file_lock(&error.to_string())
                {
                    return Err(error);
                }
                std::thread::sleep(BUILD_LOCK_RETRY_INTERVAL);
            }
        }
    }
}

/// How many extra attempts [`build`] makes for the exact failure
/// [`process_scan::looks_like_a_transient_windows_file_lock`] matches -
/// see [`build`]'s own doc comment for the full reasoning. 5 attempts,
/// 400ms apart (2s total extra wait, worst case) comfortably covers an
/// ordinary antivirus scan of a small debug binary without meaningfully
/// slowing down an ordinary rebuild that hits this at all - this is the
/// uncommon path, not the normal one.
const BUILD_LOCK_RETRY_ATTEMPTS: u32 = 5;
const BUILD_LOCK_RETRY_INTERVAL: Duration = Duration::from_millis(400);

fn build_once(app_root: &Path, release: bool) -> Result<Option<PathBuf>> {
    let mut args = vec![
        "build",
        "--message-format=json-render-diagnostics",
        // Forces colored diagnostics even though `stderr` is about to be
        // piped (which would otherwise make cargo auto-detect "not a real
        // terminal" and emit plain text) - preserved for the live relay
        // below, then stripped back out of whatever gets captured for a
        // failed build's own `Err` (see `strip_ansi_codes`), since that
        // text can end up in the dev placeholder page's plain-text `<pre>`
        // block, where raw escape codes would render as garbled control
        // characters instead of clean text.
        "--color=always",
    ];
    if release {
        args.push("--release");
    }
    let mut child = Command::new("cargo")
        .args(&args)
        .current_dir(app_root)
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .context("failed to run `cargo build`")?;

    // Relayed live to this process's own `stderr` (one line at a time, as
    // it arrives - not buffered until the build finishes) so a developer
    // watching the terminal `xr dev` runs in sees cargo's real-time
    // compiler output exactly as before, on a background thread since
    // `stdout` is read concurrently, synchronously, on this one below.
    let stderr = child.stderr.take().expect("stderr was piped");
    let stderr_relay = std::thread::spawn(move || {
        let mut captured = String::new();
        for line in BufReader::new(stderr).lines() {
            let Ok(line) = line else { break };
            status_err!("{line}");
            captured.push_str(&line);
            captured.push('\n');
        }
        captured
    });

    let stdout = child.stdout.take().expect("stdout was piped");
    let mut executable = None;
    for line in BufReader::new(stdout).lines() {
        let line = line.context("reading `cargo build` output")?;
        let Ok(message) = serde_json::from_str::<serde_json::Value>(&line) else {
            continue;
        };
        if message.get("reason").and_then(|r| r.as_str()) != Some("compiler-artifact") {
            continue;
        }
        let is_bin = message
            .get("target")
            .and_then(|t| t.get("kind"))
            .and_then(|k| k.as_array())
            .is_some_and(|kinds| kinds.iter().any(|k| k.as_str() == Some("bin")));
        if !is_bin {
            continue;
        }
        if let Some(exe) = message.get("executable").and_then(|e| e.as_str()) {
            executable = Some(PathBuf::from(exe));
        }
    }

    let status = child.wait().context("waiting for `cargo build`")?;
    // however the relay thread exited (a clean EOF or a mid-stream read
    // error), whatever it captured before that is still worth using -
    // `.unwrap_or_default()` only ever triggers on the thread itself
    // panicking, not on a build failure.
    let captured_stderr = stderr_relay.join().unwrap_or_default();

    if !status.success() {
        anyhow::bail!(format_build_failure(&captured_stderr));
    }

    Ok(executable)
}

/// How much of a failed build's captured `stderr` [`format_build_failure`]
/// keeps, from the *end* - rustc prints each error as it's found and a
/// final one-line summary ("error: could not compile `...` due to N
/// errors") last, so the tail is where the actually-useful content lives;
/// the *start* of a long failing build's `stderr` is mostly unrelated
/// "Compiling X" progress lines from dependencies that built just fine.
const MAX_CAPTURED_BUILD_STDERR: usize = 4000;

/// What a failed `build()` call's `Err` actually says - previously just
/// "cargo build exited with a non-zero status", which was a real, reported
/// gap: neither the terminal `xr dev` runs in nor the dev placeholder page
/// (`dev_placeholder.rs`) said *why* a build failed, only *that* it did.
/// Real compiler errors already reached the terminal independently before
/// this existed (inherited `stderr`), but that's easy to miss scrolled
/// past, and the placeholder page/build-status banner had nothing at all
/// to show - this is what gives both of those real content instead.
/// `stderr` being empty (a build failure with no diagnostic output
/// whatsoever reached this process at all - genuinely never observed, but
/// not provably impossible) falls back to the old generic message rather
/// than an empty string.
fn format_build_failure(stderr: &str) -> String {
    let stderr = strip_ansi_codes(stderr.trim());
    if stderr.is_empty() {
        return "cargo build exited with a non-zero status".to_string();
    }
    if stderr.len() <= MAX_CAPTURED_BUILD_STDERR {
        return stderr;
    }
    let tail_start = stderr.len() - MAX_CAPTURED_BUILD_STDERR;
    // `floor_char_boundary` is nightly-only as of this Rust edition - walk
    // forward to the next real char boundary by hand instead of slicing
    // mid-UTF-8-sequence and panicking.
    let tail_start = (tail_start..stderr.len())
        .find(|&i| stderr.is_char_boundary(i))
        .unwrap_or(stderr.len());
    format!(
        "(truncated - showing the last {MAX_CAPTURED_BUILD_STDERR} characters)\n...\n{}",
        &stderr[tail_start..]
    )
}

/// Strips ANSI SGR escape sequences (`ESC [ ... m`) from `text` - cargo's
/// `--message-format=json-render-diagnostics` embeds the same colored
/// terminal text into each `compiler-message`'s own `rendered` field
/// regardless of whether stdout is a real terminal (this reads it from a
/// piped, non-terminal stdout), and that text can end up in the dev
/// placeholder page's plain-text `<pre>` block (`dev_placeholder.rs`) -
/// raw escape codes there would render as garbled control characters
/// instead of clean text. Deliberately not applied to what already reaches
/// the terminal via inherited `stderr` - that output keeps its color.
fn strip_ansi_codes(text: &str) -> String {
    let mut out = String::with_capacity(text.len());
    let mut chars = text.chars().peekable();
    while let Some(c) = chars.next() {
        if c == '\u{1b}' && chars.peek() == Some(&'[') {
            chars.next();
            for next in chars.by_ref() {
                if next.is_ascii_alphabetic() {
                    break;
                }
            }
        } else {
            out.push(c);
        }
    }
    out
}

/// Best-effort, but not silently so: an unexpected failure here (as
/// opposed to the process having already exited) means `xr dev`'s core
/// promise - no orphaned server left holding the port - may not hold,
/// which is worth the user seeing rather than discarding outright.
/// `child` is a `tokio::process::Child` (gen 1 only ever spawns that way
/// now - see `ServerState::Direct`'s own doc comment), so killing/reaping
/// it needs a runtime; `handle` lets this run from the Ctrl+C signal
/// thread, which isn't itself a tokio worker thread.
fn kill(child: &mut tokio::process::Child, handle: &tokio::runtime::Handle) {
    handle.block_on(async {
        if let Err(error) = child.kill().await {
            status_err!("xr dev: failed to stop the previous server process: {error}");
        }
        if let Err(error) = child.wait().await {
            status_err!("xr dev: failed to reap the previous server process: {error}");
        }
    });
}

fn register_ctrlc_handler(
    state: Arc<Mutex<DevState>>,
    admin_address: String,
    handle: tokio::runtime::Handle,
) {
    let result = ctrlc::set_handler(move || {
        let mut guard = lock_state(&state);
        match std::mem::replace(&mut guard.server, ServerState::NotStarted) {
            ServerState::NotStarted => {}
            ServerState::Direct(mut child) => kill(&mut child, &handle),
            ServerState::HandedOff => {
                // Best-effort: `xr dev` is exiting either way. If this
                // fails (the app already went down on its own, a
                // transient IPC hiccup), there's nothing more useful to
                // do than exit anyway.
                let _ = admin_client::send_command(&admin_address, admin::STOP_COMMAND);
            }
        }
        dev_registry::unregister(std::process::id());
        std::process::exit(0);
    });
    if let Err(error) = result {
        status_err!("xr dev: failed to register a Ctrl+C handler: {error}");
    }
}

/// A poisoned lock here means some *other* interaction with `state`
/// panicked - not something `build`/`spawn`/`kill` themselves do in
/// normal operation. Recovering the guard rather than propagating the
/// panic keeps the watch loop (and the Ctrl+C handler's ability to clean
/// up) alive rather than taking the whole supervisor down over an
/// unrelated failure.
fn lock_state(state: &Arc<Mutex<DevState>>) -> MutexGuard<'_, DevState> {
    state
        .lock()
        .unwrap_or_else(|poisoned| poisoned.into_inner())
}

/// Excludes VCS metadata and - importantly - the dev SQLite database
/// itself: without this, any request that writes to the database (any
/// `POST`) would be seen by the watcher and trigger a rebuild, which would
/// look like the server rebuilding itself in an endless loop the moment a
/// real user interacts with it. `target/`/`storage/` don't need an entry
/// here - `watch_source_dirs` never registers them with the OS watcher in
/// the first place, so no event for them ever reaches this function - but
/// `.git/` and the sqlite file are checked defensively in case a future
/// watched subdirectory ever nests something unexpected.
fn is_relevant(app_root: &Path, path: &Path) -> bool {
    let Ok(relative) = path.strip_prefix(app_root) else {
        return true;
    };

    if let Some(std::path::Component::Normal(first)) = relative.components().next() {
        if first == ".git" {
            return false;
        }
    }

    if let Some(name) = path.file_name().and_then(|n| n.to_str()) {
        if name.contains(".sqlite") {
            return false;
        }
    }

    true
}

/// True when `path` falls under one of `WATCHED_ASSET_SUBDIRS` (currently
/// just `public/`) - used to classify an already-`is_relevant` change as
/// "needs a rebuild" vs "just needs connected tabs refreshed". A path
/// outside `app_root` entirely defaults to `false` (i.e. "treat as needing
/// a rebuild"), the safer default for a watcher - the mirror image of
/// `is_relevant`'s own default-to-true for the same case.
fn is_asset_only(app_root: &Path, path: &Path) -> bool {
    let Ok(relative) = path.strip_prefix(app_root) else {
        return false;
    };
    matches!(
        relative.components().next(),
        Some(std::path::Component::Normal(first))
            if WATCHED_ASSET_SUBDIRS.iter().any(|dir| Path::new(dir) == Path::new(first))
    )
}

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

    #[test]
    fn starting_generation_is_zero_with_no_prior_dev_slots_on_disk() {
        let app_root = tempfile::tempdir().unwrap();
        assert_eq!(starting_generation(app_root.path()), 0);
    }

    #[test]
    fn starting_generation_continues_from_a_previous_sessions_leftover_slots() {
        // The exact scenario `starting_generation`'s own doc comment
        // describes: a *previous* `xr dev` session got all the way to
        // generation 34 before exiting, leaving its last few slots behind
        // (real, observed leftovers, not hypothetical - see that doc
        // comment). A fresh session must pick up from 34, not restart at 0
        // and leave those slots permanently unreachable by its own prune.
        let app_root = tempfile::tempdir().unwrap();
        let source = app_root.path().join("built.exe");
        std::fs::write(&source, b"x").unwrap();
        release_slots::publish(app_root.path(), &source, "dev", 32).unwrap();
        release_slots::publish(app_root.path(), &source, "dev", 33).unwrap();
        release_slots::publish(app_root.path(), &source, "dev", 34).unwrap();

        assert_eq!(starting_generation(app_root.path()), 34);
    }

    #[test]
    fn starting_generation_ignores_a_release_prefixed_slot_from_a_real_deploy() {
        // A production `xr deploy` release living in the same directory
        // must never influence `xr dev`'s own counter - the entire reason
        // `release_slots` keeps `"dev"`/`"release"` in separate counting
        // namespaces to begin with (see that module's own doc comment).
        let app_root = tempfile::tempdir().unwrap();
        let source = app_root.path().join("built.exe");
        std::fs::write(&source, b"x").unwrap();
        release_slots::publish(app_root.path(), &source, "release", 99).unwrap();

        assert_eq!(starting_generation(app_root.path()), 0);
    }

    #[test]
    fn strip_ansi_codes_removes_color_sequences_but_keeps_the_text() {
        let colored = "\u{1b}[0m\u{1b}[1m\u{1b}[38;5;9merror\u{1b}[0m: mismatched types";
        assert_eq!(strip_ansi_codes(colored), "error: mismatched types");
    }

    #[test]
    fn strip_ansi_codes_leaves_plain_text_untouched() {
        assert_eq!(strip_ansi_codes("no escapes here"), "no escapes here");
    }

    #[test]
    fn format_build_failure_falls_back_to_a_generic_message_when_stderr_was_empty() {
        // A build failing with genuinely no diagnostic output at all isn't
        // something this codebase has actually observed, but the fallback
        // still has to say *something* useful rather than render blank.
        let message = format_build_failure("");
        assert!(message.contains("non-zero status"));
    }

    #[test]
    fn format_build_failure_includes_the_real_captured_error_text() {
        // The exact class of error that motivated this fix: a hard parse
        // error never reaches cargo's own `compiler-message` JSON channel
        // at all (confirmed empirically against a real broken build, not
        // assumed) - only `stderr`, which is what `build()` now captures
        // instead of relying on that channel.
        let message =
            format_build_failure("error: expected one of `!` or `::`, found `is`\n\nerror: could not compile `blog` (lib) due to 1 previous error\n");
        assert!(message.contains("expected one of `!` or `::`"));
    }

    #[test]
    fn format_build_failure_strips_ansi_color_codes() {
        let colored = "\u{1b}[1m\u{1b}[38;5;9merror\u{1b}[0m: mismatched types";
        let message = format_build_failure(colored);
        assert_eq!(message, "error: mismatched types");
    }

    #[test]
    fn format_build_failure_truncates_a_very_long_capture_to_its_tail() {
        let huge = "x".repeat(MAX_CAPTURED_BUILD_STDERR * 2);
        let message = format_build_failure(&huge);
        assert!(message.contains("truncated"));
        assert!(message.len() < huge.len());
        assert!(message.ends_with(&"x".repeat(50)));
    }

    #[test]
    fn format_build_failure_leaves_a_short_capture_untouched_beyond_trimming() {
        let message = format_build_failure("  error: a short one  \n");
        assert_eq!(message, "error: a short one");
        assert!(!message.contains("truncated"));
    }

    // The transient-Windows-file-lock detection `build`'s retry loop uses
    // is shared with `upgrade.rs` and tested once, directly, in
    // `process_scan`'s own test module - not duplicated here.

    #[test]
    fn app_name_default_recovers_a_converted_apps_real_default() {
        // Real bug this fixes: a converted app's own `config/app.rs`
        // faithfully carries over whatever `app_name` the *source*
        // Laravel app's `config/app.php` had - Laravel's own stock
        // default is "Laravel", not "Larust" - so this must recover
        // *that*, not the framework's own generic scaffold default.
        let source = r#"config["app_name"] = json!(larust_support::config_env::env_or("APP_NAME", "Laravel"));"#;
        assert_eq!(app_name_default_from_source(source), "Laravel");
    }

    #[test]
    fn app_name_default_recovers_a_scaffolded_apps_generic_default() {
        let source = r#"config["app_name"] = json!(larust_support::config_env::env_or("APP_NAME", "Larust"));"#;
        assert_eq!(app_name_default_from_source(source), "Larust");
    }

    #[test]
    fn app_name_default_falls_back_when_the_pattern_is_absent() {
        // A hand-edited or unusual `config/app.rs` - degrade to the old
        // hardcoded behavior rather than fail outright.
        let source = "// no app_name field written this way";
        assert_eq!(app_name_default_from_source(source), "Larust");
    }

    #[test]
    fn app_name_default_falls_back_on_an_unterminated_literal() {
        let source = r#"env_or("APP_NAME", "Laravel"#; // missing closing quote
        assert_eq!(app_name_default_from_source(source), "Larust");
    }

    #[test]
    fn resolve_app_port_prefers_the_override_over_env_and_default() {
        assert_eq!(
            resolve_app_port(Some(8001), Some("9000"), Some("http://127.0.0.1:7000")),
            8001
        );
    }

    #[test]
    fn resolve_app_port_falls_back_to_env_when_no_override_is_given() {
        assert_eq!(
            resolve_app_port(None, Some("9000"), Some("http://127.0.0.1:7000")),
            9000
        );
    }

    #[test]
    fn resolve_app_port_falls_back_to_the_url_port_when_app_port_is_unset() {
        // The real, reported scenario: a converted Laravel project whose
        // own `.env` only ever had `APP_URL`, never `APP_PORT`.
        assert_eq!(
            resolve_app_port(None, None, Some("http://127.0.0.1:7000")),
            7000
        );
    }

    #[test]
    fn resolve_app_port_falls_back_to_the_default_when_nothing_is_set() {
        assert_eq!(resolve_app_port(None, None, None), DEFAULT_APP_PORT);
    }

    #[test]
    fn resolve_app_port_falls_back_to_the_default_when_the_url_has_no_port() {
        assert_eq!(
            resolve_app_port(None, None, Some("http://localhost")),
            DEFAULT_APP_PORT
        );
    }

    #[test]
    fn resolve_app_port_treats_a_malformed_env_value_as_absent() {
        // Consistent with this module's own "still usable even when .env
        // doesn't line up" tolerance elsewhere (see `dev_config`'s own
        // doc comment) - a bad `APP_PORT` value degrades to the next
        // tier (the URL's port here), not a hard failure.
        assert_eq!(
            resolve_app_port(None, Some("not-a-port"), Some("http://127.0.0.1:7000")),
            7000
        );
    }

    #[test]
    fn port_from_url_extracts_an_explicit_port() {
        assert_eq!(port_from_url("http://127.0.0.1:1234"), Some(1234));
        assert_eq!(port_from_url("https://example.com:8443/path"), Some(8443));
    }

    #[test]
    fn port_from_url_returns_none_without_an_explicit_port() {
        assert_eq!(port_from_url("http://localhost"), None);
    }

    #[test]
    fn is_relevant_excludes_git_metadata() {
        let root = Path::new("/app");
        assert!(!is_relevant(root, Path::new("/app/.git/HEAD")));
    }

    #[test]
    fn is_relevant_excludes_the_sqlite_database_and_its_journal_files() {
        let root = Path::new("/app");
        assert!(!is_relevant(
            root,
            Path::new("/app/database/database.sqlite")
        ));
        assert!(!is_relevant(
            root,
            Path::new("/app/database/database.sqlite-wal")
        ));
        assert!(!is_relevant(
            root,
            Path::new("/app/database/database.sqlite-shm")
        ));
    }

    #[test]
    fn is_relevant_allows_real_source_changes() {
        let root = Path::new("/app");
        assert!(is_relevant(root, Path::new("/app/src/main.rs")));
        assert!(is_relevant(
            root,
            Path::new("/app/resources/views/posts/index.blade.xr")
        ));
        assert!(is_relevant(
            root,
            Path::new("/app/database/migrations/0001_create_posts_table.sql")
        ));
    }

    #[test]
    fn is_relevant_defaults_to_true_for_paths_outside_app_root() {
        // strip_prefix fails; treated as relevant rather than silently
        // dropped, since that's the safer default for a watcher.
        assert!(is_relevant(Path::new("/app"), Path::new("/elsewhere/x.rs")));
    }

    #[test]
    fn is_asset_only_true_for_paths_under_public() {
        let root = Path::new("/app");
        assert!(is_asset_only(
            root,
            Path::new("/app/public/styles/style.css")
        ));
        assert!(is_asset_only(root, Path::new("/app/public/logo.png")));
    }

    #[test]
    fn is_asset_only_false_for_source_changes() {
        let root = Path::new("/app");
        assert!(!is_asset_only(root, Path::new("/app/src/main.rs")));
        assert!(!is_asset_only(
            root,
            Path::new("/app/resources/views/welcome.blade.xr")
        ));
    }

    #[test]
    fn is_asset_only_defaults_to_false_for_paths_outside_app_root() {
        assert!(!is_asset_only(
            Path::new("/app"),
            Path::new("/elsewhere/style.css")
        ));
    }

    #[test]
    fn env_mtime_is_none_when_env_file_is_absent() {
        let app_root = tempfile::tempdir().unwrap();
        assert_eq!(env_mtime(app_root.path()), None);
    }

    #[test]
    fn env_mtime_is_some_once_env_exists() {
        let app_root = tempfile::tempdir().unwrap();
        std::fs::write(app_root.path().join(".env"), b"APP_NAME=demo").unwrap();
        assert!(env_mtime(app_root.path()).is_some());
    }

    #[test]
    fn env_mtime_changes_when_env_is_rewritten() {
        // The whole premise `run()`'s loop relies on: a real edit must be
        // distinguishable from the baseline, not just "present vs absent".
        // Set two explicit, distinct modification times (rather than two
        // real writes back-to-back, which could land in the same tick on a
        // filesystem with coarse mtime resolution and flake this test)
        // to prove the comparison itself is sound.
        let app_root = tempfile::tempdir().unwrap();
        let env_path = app_root.path().join(".env");
        let file = std::fs::File::create(&env_path).unwrap();
        let first = std::time::SystemTime::UNIX_EPOCH + Duration::from_secs(1_000_000);
        file.set_modified(first).unwrap();
        let baseline = env_mtime(app_root.path());
        assert_eq!(baseline, Some(first));

        let second = first + Duration::from_secs(1);
        file.set_modified(second).unwrap();

        assert_ne!(env_mtime(app_root.path()), baseline);
    }

    /// A free ephemeral port (asking the OS for one via `:0`, then
    /// dropping the listener that reserved it) - used by the
    /// `bind_with_retry`/`bind_available_port` tests below so they never
    /// collide with anything else already bound on this machine, unlike
    /// hardcoding a fixed port number would.
    fn free_port() -> u16 {
        std::net::TcpListener::bind(("127.0.0.1", 0))
            .unwrap()
            .local_addr()
            .unwrap()
            .port()
    }

    #[test]
    fn bind_with_retry_fails_immediately_when_retry_is_false() {
        let port = free_port();
        let addr = SocketAddr::from(([127, 0, 0, 1], port));
        let _occupying = std::net::TcpListener::bind(addr).unwrap();

        let started = Instant::now();
        let result = bind_with_retry(addr, false);

        assert_eq!(
            result.err().map(|error| error.kind()),
            Some(io::ErrorKind::AddrInUse)
        );
        // Well under `PORT_RELEASE_RETRY_INTERVAL` (200ms) - proves no
        // retry loop ran at all, not just that it happened to finish fast.
        assert!(started.elapsed() < Duration::from_millis(100));
    }

    #[test]
    fn bind_with_retry_recovers_once_the_port_is_released_when_retry_is_true() {
        let port = free_port();
        let addr = SocketAddr::from(([127, 0, 0, 1], port));
        let occupying = std::net::TcpListener::bind(addr).unwrap();

        std::thread::spawn(move || {
            std::thread::sleep(Duration::from_millis(150));
            drop(occupying);
        });

        // Proves the retry loop itself works: the first attempt still
        // hits `AddrInUse` (the spawned thread above hasn't run yet), but
        // `retry: true` keeps trying until the port frees up instead of
        // giving up on that first failure.
        assert!(bind_with_retry(addr, true).is_ok());
    }

    #[test]
    fn bind_available_port_skips_the_retry_window_when_nothing_was_found_to_stop() {
        // The exact case `stop_any_previous_generation` returning `false`
        // is meant to short-circuit: nothing responded to the `STOP`, so
        // whatever holds `starting_port` was never asked to let go and
        // has no reason to any moment soon - waiting out the full several-
        // second retry window before falling back to the next port would
        // just be dead time on every single `xr dev` startup next to a
        // different app's own dev server.
        let starting_port = free_port();
        let addr = SocketAddr::from(([127, 0, 0, 1], starting_port));
        let _occupying = std::net::TcpListener::bind(addr).unwrap();

        let started = Instant::now();
        let (_listener, bound_port) = bind_available_port(starting_port, false).unwrap();

        // Not asserted as exactly `starting_port + 1`: `cargo test`'s
        // default parallelism means another test's own `free_port()` can
        // legitimately land on and hold that exact next port at the same
        // moment - this only needs to confirm the fallback moved past the
        // occupied port at all, not which of the free ones it landed on.
        assert!(bound_port > starting_port);
        assert!(started.elapsed() < Duration::from_millis(500));
    }

    /// Guards `set_debug_env_vars_sets_every_debug_variable` against
    /// `cargo test`'s default parallel execution racing real, process-wide
    /// environment state - same `OnceLock`-backed `std::sync::Mutex`
    /// pattern `larust_core::application`'s own `env_lock` uses, for the
    /// identical reason (see that module's own doc comment).
    fn env_lock() -> &'static std::sync::Mutex<()> {
        static LOCK: std::sync::OnceLock<std::sync::Mutex<()>> = std::sync::OnceLock::new();
        LOCK.get_or_init(|| std::sync::Mutex::new(()))
    }

    #[test]
    fn set_debug_env_vars_sets_every_debug_variable() {
        let _guard = env_lock()
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        for var in ["APP_DEBUG", "LOG_LEVEL", "RUST_BACKTRACE"] {
            std::env::remove_var(var);
        }

        set_debug_env_vars();

        assert_eq!(std::env::var("APP_DEBUG").as_deref(), Ok("true"));
        assert_eq!(std::env::var("LOG_LEVEL").as_deref(), Ok("trace"));
        assert_eq!(std::env::var("RUST_BACKTRACE").as_deref(), Ok("full"));

        for var in ["APP_DEBUG", "LOG_LEVEL", "RUST_BACKTRACE"] {
            std::env::remove_var(var);
        }
    }
}