koi-embedded 0.3.0

Embed local network discovery, DNS, health, and TLS directly in your Rust application
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
mod config;
mod events;
mod handle;
pub(crate) mod http;
mod mdns_browse_adapter;

use std::sync::Arc;

use tokio::sync::broadcast;
use tokio::task::JoinHandle;
use tokio_util::sync::CancellationToken;

use koi_client::KoiClient;

pub use config::{DnsConfigBuilder, KoiConfig, ServiceMode};
pub use events::KoiEvent;
pub use handle::{CertmeshHandle, DnsHandle, HealthHandle, KoiHandle, MdnsHandle, ProxyHandle};

// Re-export types needed by downstream consumers (registration, discovery, DNS, proxy, health)
pub use koi_common::firewall::{FirewallPort, FirewallProtocol};
pub use koi_common::types::ServiceRecord;
pub use koi_config::state::DnsEntry;
pub use koi_health::{HealthCheck, HealthSnapshot, ServiceCheckKind};
pub use koi_mdns::protocol::{RegisterPayload, RegistrationResult};
pub use koi_mdns::MdnsEvent;
pub use koi_proxy::ProxyEntry;

// Vault: general-purpose encrypted secret storage
pub use koi_crypto::vault::{Vault, VaultError};

// Runtime adapter re-exports
pub use koi_runtime::{RuntimeBackendKind, RuntimeConfig};

pub type Result<T> = std::result::Result<T, KoiError>;

#[derive(Debug, thiserror::Error)]
pub enum KoiError {
    #[error("capability disabled: {0}")]
    DisabledCapability(&'static str),
    #[error("mdns error: {0}")]
    Mdns(#[from] koi_mdns::MdnsError),
    #[error("dns error: {0}")]
    Dns(#[from] koi_dns::DnsError),
    #[error("health error: {0}")]
    Health(#[from] koi_health::HealthError),
    #[error("proxy error: {0}")]
    Proxy(#[from] koi_proxy::ProxyError),
    #[error("certmesh error: {0}")]
    Certmesh(#[from] koi_certmesh::CertmeshError),
    #[error("runtime error: {0}")]
    Runtime(#[from] koi_runtime::RuntimeError),
    #[error("client error: {0}")]
    Client(#[from] koi_client::ClientError),
    #[error("io error: {0}")]
    Io(#[from] std::io::Error),
}

pub struct Builder {
    config: KoiConfig,
    event_handler: Option<Arc<dyn Fn(KoiEvent) + Send + Sync>>,
    extra_firewall_ports: Vec<koi_common::firewall::FirewallPort>,
}

impl Builder {
    pub fn new() -> Self {
        Self {
            config: KoiConfig::default(),
            event_handler: None,
            extra_firewall_ports: Vec::new(),
        }
    }

    pub fn data_dir(mut self, path: impl Into<std::path::PathBuf>) -> Self {
        self.config.data_dir = Some(path.into());
        self
    }

    pub fn service_endpoint(mut self, endpoint: impl Into<String>) -> Self {
        self.config.service_endpoint = endpoint.into();
        self
    }

    pub fn service_mode(mut self, mode: ServiceMode) -> Self {
        self.config.service_mode = mode;
        self
    }

    pub fn http(mut self, enabled: bool) -> Self {
        self.config.http_enabled = enabled;
        self
    }

    pub fn mdns(mut self, enabled: bool) -> Self {
        self.config.mdns_enabled = enabled;
        self
    }

    pub fn dns<F>(mut self, configure: F) -> Self
    where
        F: FnOnce(DnsConfigBuilder) -> DnsConfigBuilder,
    {
        let builder = DnsConfigBuilder::new(self.config.dns_config.clone());
        self.config.dns_config = configure(builder).build();
        self
    }

    pub fn dns_enabled(mut self, enabled: bool) -> Self {
        self.config.dns_enabled = enabled;
        self
    }

    pub fn dns_auto_start(mut self, enabled: bool) -> Self {
        self.config.dns_auto_start = enabled;
        self
    }

    pub fn health(mut self, enabled: bool) -> Self {
        self.config.health_enabled = enabled;
        self
    }

    pub fn health_auto_start(mut self, enabled: bool) -> Self {
        self.config.health_auto_start = enabled;
        self
    }

    pub fn certmesh(mut self, enabled: bool) -> Self {
        self.config.certmesh_enabled = enabled;
        self
    }

    pub fn proxy(mut self, enabled: bool) -> Self {
        self.config.proxy_enabled = enabled;
        self
    }

    pub fn proxy_auto_start(mut self, enabled: bool) -> Self {
        self.config.proxy_auto_start = enabled;
        self
    }

    pub fn udp(mut self, enabled: bool) -> Self {
        self.config.udp_enabled = enabled;
        self
    }

    /// Enable the runtime adapter with the specified backend kind.
    ///
    /// Runtime is opt-in for embedded (unlike daemon where capabilities
    /// are enabled by default).
    pub fn runtime(mut self, kind: koi_runtime::RuntimeBackendKind) -> Self {
        self.config.runtime_enabled = true;
        self.config.runtime_backend = kind;
        self
    }

    /// Enable the runtime adapter with auto-detection.
    pub fn runtime_auto(mut self) -> Self {
        self.config.runtime_enabled = true;
        self.config.runtime_backend = koi_runtime::RuntimeBackendKind::Auto;
        self
    }

    pub fn http_port(mut self, port: u16) -> Self {
        self.config.http_port = port;
        self
    }

    pub fn dashboard(mut self, enabled: bool) -> Self {
        self.config.dashboard_enabled = enabled;
        self
    }

    pub fn api_docs(mut self, enabled: bool) -> Self {
        self.config.api_docs_enabled = enabled;
        self
    }

    pub fn mdns_browser(mut self, enabled: bool) -> Self {
        self.config.mdns_browser_enabled = enabled;
        self
    }

    pub fn announce_http(mut self, enabled: bool) -> Self {
        self.config.announce_http = enabled;
        self
    }

    pub fn events<F>(mut self, handler: F) -> Self
    where
        F: Fn(KoiEvent) + Send + Sync + 'static,
    {
        self.event_handler = Some(Arc::new(handler));
        self
    }

    /// Register additional firewall ports that the host application needs
    /// opened (e.g. Moss discovery UDP, HTTP API).  These are merged with
    /// the ports from enabled Koi capabilities when `ensure_firewall_rules`
    /// is called.
    pub fn extra_firewall_ports(mut self, ports: Vec<koi_common::firewall::FirewallPort>) -> Self {
        self.extra_firewall_ports = ports;
        self
    }

    /// Best-effort ensure that Windows Firewall inbound-allow rules exist
    /// for every port required by the enabled capabilities **plus** any
    /// extra ports registered by the host application.
    ///
    /// * Idempotent — safe to call on every startup.
    /// * Non-fatal  — logs warnings but never fails the build.
    /// * No-op on non-Windows platforms.
    ///
    /// `prefix` is used in the firewall rule display-names
    /// (e.g. `"Zen Garden"` → `"Zen Garden mDNS (UDP 5353)"`).
    pub fn ensure_firewall_rules(self, prefix: &str) -> Self {
        let mut all_ports = self.config.firewall_ports();
        all_ports.extend(self.extra_firewall_ports.iter().cloned());

        let count = koi_common::firewall::ensure_firewall_rules(prefix, &all_ports);
        if count > 0 {
            tracing::info!(count, "Firewall rules ensured");
        }
        self
    }

    pub fn build(self) -> Result<KoiEmbedded> {
        Ok(KoiEmbedded {
            config: self.config,
            event_handler: self.event_handler,
        })
    }
}

impl Default for Builder {
    fn default() -> Self {
        Self::new()
    }
}

pub struct KoiEmbedded {
    config: KoiConfig,
    event_handler: Option<Arc<dyn Fn(KoiEvent) + Send + Sync>>,
}

impl KoiEmbedded {
    pub async fn start(self) -> Result<KoiHandle> {
        let cancel = CancellationToken::new();
        let (event_tx, _) = broadcast::channel(256);
        let mut tasks: Vec<JoinHandle<()>> = Vec::new();

        if self.config.service_mode != ServiceMode::EmbeddedOnly {
            let client = Arc::new(KoiClient::new(&self.config.service_endpoint));
            match self.config.service_mode {
                ServiceMode::ClientOnly => {
                    tokio::task::spawn_blocking({
                        let client = Arc::clone(&client);
                        move || client.health()
                    })
                    .await
                    .map_err(map_join_error)??;
                    return Ok(KoiHandle::new_remote(client, event_tx, cancel, tasks));
                }
                ServiceMode::Auto => {
                    let health = tokio::task::spawn_blocking({
                        let client = Arc::clone(&client);
                        move || client.health()
                    })
                    .await;
                    if matches!(health, Ok(Ok(()))) {
                        return Ok(KoiHandle::new_remote(client, event_tx, cancel, tasks));
                    }
                }
                ServiceMode::EmbeddedOnly => {}
            }
        }

        let mdns = if self.config.mdns_enabled {
            Some(Arc::new(koi_mdns::MdnsCore::with_cancel(cancel.clone())?))
        } else {
            None
        };

        let certmesh = if self.config.certmesh_enabled {
            let data_dir = self.config.data_dir.clone();
            tokio::task::spawn_blocking(move || init_certmesh_core(data_dir.as_deref()))
                .await
                .map_err(|e| std::io::Error::other(format!("certmesh init: {e}")))?
        } else {
            None
        };

        // Integration bridges for cross-domain communication
        let mdns_bridge: Option<Arc<dyn koi_common::integration::MdnsSnapshot>> =
            if let Some(ref core) = mdns {
                Some(MdnsBridgeEmbedded::spawn(core.clone()).await)
            } else {
                None
            };

        let certmesh_bridge: Option<Arc<dyn koi_common::integration::CertmeshSnapshot>> =
            certmesh.as_ref().map(|core| {
                CertmeshBridgeEmbedded::new(core.clone())
                    as Arc<dyn koi_common::integration::CertmeshSnapshot>
            });

        let alias_feedback: Option<Arc<dyn koi_common::integration::AliasFeedback>> =
            certmesh.as_ref().map(|core| {
                AliasFeedbackBridgeEmbedded::new(core.clone())
                    as Arc<dyn koi_common::integration::AliasFeedback>
            });

        let dns = if self.config.dns_enabled {
            let mut dns_config = self.config.dns_config.clone();
            // Pin the state path to the data dir captured at construction time
            // so it is immune to KOI_DATA_DIR env var races in parallel tests.
            if let Some(dir) = &self.config.data_dir {
                dns_config.state_path = Some(dir.join("state").join("dns.json"));
            }
            let core = koi_dns::DnsCore::new(
                dns_config,
                mdns_bridge.clone(),
                certmesh_bridge.clone(),
                alias_feedback,
            )
            .await?;
            Some(Arc::new(koi_dns::DnsRuntime::new(core)))
        } else {
            None
        };

        let proxy = if self.config.proxy_enabled {
            let core = if let Some(dir) = &self.config.data_dir {
                Arc::new(koi_proxy::ProxyCore::with_data_dir(dir)?)
            } else {
                Arc::new(koi_proxy::ProxyCore::new()?)
            };
            Some(Arc::new(koi_proxy::ProxyRuntime::new(core)))
        } else {
            None
        };

        let dns_bridge: Option<Arc<dyn koi_common::integration::DnsProbe>> =
            dns.as_ref().map(|rt| {
                DnsBridgeEmbedded::new(rt.clone()) as Arc<dyn koi_common::integration::DnsProbe>
            });

        let proxy_bridge: Option<Arc<dyn koi_common::integration::ProxySnapshot>> =
            proxy.as_ref().map(|rt| {
                ProxyBridgeEmbedded::new(rt.core())
                    as Arc<dyn koi_common::integration::ProxySnapshot>
            });

        let health = if self.config.health_enabled {
            let core = koi_health::HealthCore::new(
                mdns_bridge.clone(),
                dns_bridge,
                certmesh_bridge,
                proxy_bridge,
            )
            .await;
            Some(Arc::new(koi_health::HealthRuntime::new(Arc::new(core))))
        } else {
            None
        };

        if let Some(runtime) = &dns {
            if self.config.dns_auto_start {
                let _ = runtime.start().await?;
            }
        }

        if let Some(runtime) = &health {
            if self.config.health_auto_start {
                let _ = runtime.start().await?;
            }
        }

        if let Some(runtime) = &proxy {
            if self.config.proxy_auto_start {
                runtime.start_all().await?;
            }
        }

        let udp = if self.config.udp_enabled {
            Some(Arc::new(koi_udp::UdpRuntime::new(cancel.clone())))
        } else {
            None
        };

        let runtime = if self.config.runtime_enabled {
            let config = koi_runtime::RuntimeConfig {
                backend_kind: self.config.runtime_backend,
                socket_path: None,
            };
            let core = Arc::new(koi_runtime::RuntimeCore::new(config));
            match core.start_watching(cancel.clone()).await {
                Ok(()) => {
                    tracing::info!("Runtime adapter started");
                    Some(core)
                }
                Err(e) => {
                    tracing::warn!(error = %e, "Runtime backend unavailable — continuing without runtime adapter");
                    None
                }
            }
        } else {
            None
        };

        // Build dashboard state if enabled
        let dashboard_state = if self.config.dashboard_enabled && self.config.http_enabled {
            let started_at = std::time::Instant::now();
            let snap_mdns = mdns.clone();
            let snap_certmesh = certmesh.clone();
            let snap_dns = dns.clone();
            let snap_health = health.clone();
            let snap_proxy = proxy.clone();
            let snap_udp = udp.clone();
            let snap_runtime = runtime.clone();

            let snapshot_fn: koi_common::dashboard::SnapshotFn = Arc::new(move || {
                let m = snap_mdns.clone();
                let cm = snap_certmesh.clone();
                let d = snap_dns.clone();
                let h = snap_health.clone();
                let p = snap_proxy.clone();
                let u = snap_udp.clone();
                let rt = snap_runtime.clone();
                Box::pin(async move { build_embedded_snapshot(m, cm, d, h, p, u, rt).await })
            });

            let (dash_event_tx, _) = broadcast::channel(256);
            let ds = koi_common::dashboard::DashboardState {
                identity: koi_common::dashboard::DashboardIdentity {
                    version: env!("CARGO_PKG_VERSION").to_string(),
                    platform: std::env::consts::OS.to_string(),
                },
                mode: "embedded",
                snapshot_fn,
                event_tx: dash_event_tx.clone(),
                started_at,
            };

            // Spawn event forwarder for dashboard SSE
            {
                let mut mdns_rx = mdns.as_ref().map(|c| c.subscribe());
                let mut health_rx = health.as_ref().map(|r| r.core().subscribe());
                let mut dns_rx = dns.as_ref().map(|r| r.core().subscribe());
                let mut certmesh_rx = certmesh.as_ref().map(|c| c.subscribe());
                let mut proxy_rx = proxy.as_ref().map(|r| r.core().subscribe());
                let mut runtime_rx = runtime.as_ref().map(|r| r.subscribe());
                let tx = dash_event_tx;
                let token = cancel.clone();
                tasks.push(tokio::spawn(async move {
                    loop {
                        let sse_event: Option<koi_common::dashboard::DashboardSseEvent> = tokio::select! {
                            _ = token.cancelled() => break,
                            Some(Ok(ev)) = async { match mdns_rx.as_mut() { Some(rx) => Some(rx.recv().await), None => None } } => {
                                let id = uuid::Uuid::now_v7().to_string();
                                match ev {
                                    koi_mdns::MdnsEvent::Found(record) => Some(koi_common::dashboard::DashboardSseEvent {
                                        event_type: "mdns.found".to_string(), id,
                                        data: serde_json::to_value(record).unwrap_or_default(),
                                    }),
                                    koi_mdns::MdnsEvent::Resolved(record) => Some(koi_common::dashboard::DashboardSseEvent {
                                        event_type: "mdns.resolved".to_string(), id,
                                        data: serde_json::to_value(record).unwrap_or_default(),
                                    }),
                                    koi_mdns::MdnsEvent::Removed { name, service_type } => Some(koi_common::dashboard::DashboardSseEvent {
                                        event_type: "mdns.removed".to_string(), id,
                                        data: serde_json::json!({ "name": name, "service_type": service_type }),
                                    }),
                                }
                            },
                            Some(Ok(ev)) = async { match health_rx.as_mut() { Some(rx) => Some(rx.recv().await), None => None } } => {
                                let id = uuid::Uuid::now_v7().to_string();
                                match ev {
                                    koi_health::HealthEvent::StatusChanged { name, status } => Some(koi_common::dashboard::DashboardSseEvent {
                                        event_type: "health.changed".to_string(), id,
                                        data: serde_json::json!({ "name": name, "status": status }),
                                    }),
                                }
                            },
                            Some(Ok(ev)) = async { match dns_rx.as_mut() { Some(rx) => Some(rx.recv().await), None => None } } => {
                                let id = uuid::Uuid::now_v7().to_string();
                                match ev {
                                    koi_dns::DnsEvent::EntryUpdated { name, ip } => Some(koi_common::dashboard::DashboardSseEvent {
                                        event_type: "dns.updated".to_string(), id,
                                        data: serde_json::json!({ "name": name, "ip": ip }),
                                    }),
                                    koi_dns::DnsEvent::EntryRemoved { name } => Some(koi_common::dashboard::DashboardSseEvent {
                                        event_type: "dns.removed".to_string(), id,
                                        data: serde_json::json!({ "name": name }),
                                    }),
                                }
                            },
                            Some(Ok(ev)) = async { match certmesh_rx.as_mut() { Some(rx) => Some(rx.recv().await), None => None } } => {
                                let id = uuid::Uuid::now_v7().to_string();
                                match ev {
                                    koi_certmesh::CertmeshEvent::MemberJoined { hostname, fingerprint } => Some(koi_common::dashboard::DashboardSseEvent {
                                        event_type: "certmesh.joined".to_string(), id,
                                        data: serde_json::json!({ "hostname": hostname, "fingerprint": fingerprint }),
                                    }),
                                    koi_certmesh::CertmeshEvent::MemberRevoked { hostname } => Some(koi_common::dashboard::DashboardSseEvent {
                                        event_type: "certmesh.revoked".to_string(), id,
                                        data: serde_json::json!({ "hostname": hostname }),
                                    }),
                                    koi_certmesh::CertmeshEvent::Destroyed => Some(koi_common::dashboard::DashboardSseEvent {
                                        event_type: "certmesh.destroyed".to_string(), id,
                                        data: serde_json::json!({}),
                                    }),
                                }
                            },
                            Some(Ok(ev)) = async { match proxy_rx.as_mut() { Some(rx) => Some(rx.recv().await), None => None } } => {
                                let id = uuid::Uuid::now_v7().to_string();
                                match ev {
                                    koi_proxy::ProxyEvent::EntryUpdated { entry } => Some(koi_common::dashboard::DashboardSseEvent {
                                        event_type: "proxy.updated".to_string(), id,
                                        data: serde_json::to_value(entry).unwrap_or_default(),
                                    }),
                                    koi_proxy::ProxyEvent::EntryRemoved { name } => Some(koi_common::dashboard::DashboardSseEvent {
                                        event_type: "proxy.removed".to_string(), id,
                                        data: serde_json::json!({ "name": name }),
                                    }),
                                }
                            },
                            Some(Ok(ev)) = async { match runtime_rx.as_mut() { Some(rx) => Some(rx.recv().await), None => None } } => {
                                let id = uuid::Uuid::now_v7().to_string();
                                match ev {
                                    koi_runtime::RuntimeEvent::Started(instance) => Some(koi_common::dashboard::DashboardSseEvent {
                                        event_type: "runtime.started".to_string(), id,
                                        data: serde_json::to_value(instance).unwrap_or_default(),
                                    }),
                                    koi_runtime::RuntimeEvent::Stopped { id: inst_id, name } => Some(koi_common::dashboard::DashboardSseEvent {
                                        event_type: "runtime.stopped".to_string(), id,
                                        data: serde_json::json!({ "id": inst_id, "name": name }),
                                    }),
                                    koi_runtime::RuntimeEvent::Updated(instance) => Some(koi_common::dashboard::DashboardSseEvent {
                                        event_type: "runtime.updated".to_string(), id,
                                        data: serde_json::to_value(instance).unwrap_or_default(),
                                    }),
                                    koi_runtime::RuntimeEvent::BackendDisconnected { backend, reason } => Some(koi_common::dashboard::DashboardSseEvent {
                                        event_type: "runtime.disconnected".to_string(), id,
                                        data: serde_json::json!({ "backend": backend, "reason": reason }),
                                    }),
                                    koi_runtime::RuntimeEvent::BackendReconnected { backend } => Some(koi_common::dashboard::DashboardSseEvent {
                                        event_type: "runtime.reconnected".to_string(), id,
                                        data: serde_json::json!({ "backend": backend }),
                                    }),
                                }
                            },
                        };
                        if let Some(ev) = sse_event {
                            let _ = tx.send(ev);
                        }
                    }
                }));
            }

            Some(ds)
        } else {
            None
        };

        // Build browser state if enabled (requires mDNS)
        let browser_state = if self.config.mdns_browser_enabled && self.config.http_enabled {
            if let Some(ref mdns_core) = mdns {
                let adapter =
                    mdns_browse_adapter::MdnsBrowseAdapter::new(mdns_core.clone(), cancel.clone());
                let cache = koi_common::browser::BrowserCache::new();
                let source = adapter.clone() as Arc<dyn koi_common::browser::BrowseSource>;
                let bc = cache.clone();
                let token = cancel.clone();
                tasks.push(tokio::spawn(async move {
                    koi_common::browser::worker(source, bc, token).await;
                }));
                Some(koi_common::browser::BrowserState {
                    source: adapter,
                    cache,
                })
            } else {
                tracing::warn!("mdns_browser enabled but mDNS is disabled — skipping browser");
                None
            }
        } else {
            None
        };

        // Spawn embedded HTTP adapter if enabled
        if self.config.http_enabled {
            let http_port = self.config.http_port;
            let http_cancel = cancel.clone();
            let http_mdns = mdns.clone();
            let http_dns = dns.clone();
            let http_health = health.clone();
            let http_certmesh = certmesh.clone();
            let http_proxy = proxy.clone();
            let http_udp = udp.clone();
            let http_runtime = runtime.clone();
            let http_api_docs = self.config.api_docs_enabled;
            tasks.push(tokio::spawn(async move {
                http::serve(
                    http_port,
                    http_mdns,
                    http_dns,
                    http_health,
                    http_certmesh,
                    http_proxy,
                    http_udp,
                    http_runtime,
                    dashboard_state,
                    browser_state,
                    http_api_docs,
                    http_cancel,
                )
                .await;
            }));
        }

        // ── HTTP mDNS announcement (opt-in) ──
        let http_announce_id =
            if self.config.announce_http && self.config.http_enabled && self.config.mdns_enabled {
                if let Some(ref mdns_core) = mdns {
                    let hostname = hostname::get()
                        .ok()
                        .and_then(|os| os.into_string().ok())
                        .unwrap_or_else(|| "unknown".to_string());

                    let mut txt = std::collections::HashMap::new();
                    txt.insert("path".to_string(), "/".to_string());
                    txt.insert("version".to_string(), env!("CARGO_PKG_VERSION").to_string());
                    txt.insert("api".to_string(), "v1".to_string());
                    txt.insert(
                        "dashboard".to_string(),
                        self.config.dashboard_enabled.to_string(),
                    );

                    let payload = koi_mdns::protocol::RegisterPayload {
                        name: format!("Koi ({hostname})"),
                        service_type: "_http._tcp".to_string(),
                        port: self.config.http_port,
                        ip: None,
                        lease_secs: None,
                        txt,
                    };
                    match mdns_core.register(payload) {
                        Ok(result) => {
                            tracing::info!(
                                id = %result.id,
                                port = self.config.http_port,
                                "HTTP server announced via mDNS"
                            );
                            Some(result.id)
                        }
                        Err(e) => {
                            tracing::warn!(error = %e, "Failed to announce HTTP server via mDNS");
                            None
                        }
                    }
                } else {
                    None
                }
            } else {
                None
            };

        if let Some(core) = &mdns {
            let mut rx = core.subscribe();
            let tx = event_tx.clone();
            let token = cancel.clone();
            let handler = self.event_handler.clone();
            tasks.push(tokio::spawn(async move {
                loop {
                    tokio::select! {
                        _ = token.cancelled() => break,
                        msg = rx.recv() => {
                            let Ok(event) = msg else { continue; };
                            let mapped = map_mdns_event(event);
                            if let Some(mapped) = mapped {
                                emit_event(&tx, handler.as_ref(), mapped);
                            }
                        }
                    }
                }
            }));
        }

        if self.config.health_enabled {
            if let Some(runtime) = &health {
                let mut rx = runtime.core().subscribe();
                let tx = event_tx.clone();
                let token = cancel.clone();
                let handler = self.event_handler.clone();
                tasks.push(tokio::spawn(async move {
                    loop {
                        tokio::select! {
                            _ = token.cancelled() => break,
                            msg = rx.recv() => {
                                let Ok(event) = msg else { continue; };
                                let mapped = map_health_event(event);
                                emit_event(&tx, handler.as_ref(), mapped);
                            }
                        }
                    }
                }));
            }
        }

        if self.config.dns_enabled {
            if let Some(runtime) = &dns {
                let mut rx = runtime.core().subscribe();
                let tx = event_tx.clone();
                let token = cancel.clone();
                let handler = self.event_handler.clone();
                tasks.push(tokio::spawn(async move {
                    loop {
                        tokio::select! {
                            _ = token.cancelled() => break,
                            msg = rx.recv() => {
                                let Ok(event) = msg else { continue; };
                                let mapped = map_dns_event(event);
                                emit_event(&tx, handler.as_ref(), mapped);
                            }
                        }
                    }
                }));
            }
        }

        if self.config.certmesh_enabled {
            if let Some(core) = &certmesh {
                let mut rx = core.subscribe();
                let tx = event_tx.clone();
                let token = cancel.clone();
                let handler = self.event_handler.clone();
                tasks.push(tokio::spawn(async move {
                    loop {
                        tokio::select! {
                            _ = token.cancelled() => break,
                            msg = rx.recv() => {
                                let Ok(event) = msg else { continue; };
                                let mapped = map_certmesh_event(event);
                                emit_event(&tx, handler.as_ref(), mapped);
                            }
                        }
                    }
                }));
            }
        }

        if self.config.proxy_enabled {
            if let Some(runtime_proxy) = &proxy {
                let mut rx = runtime_proxy.core().subscribe();
                let tx = event_tx.clone();
                let token = cancel.clone();
                let handler = self.event_handler.clone();
                tasks.push(tokio::spawn(async move {
                    loop {
                        tokio::select! {
                            _ = token.cancelled() => break,
                            msg = rx.recv() => {
                                let Ok(event) = msg else { continue; };
                                let mapped = map_proxy_event(event);
                                emit_event(&tx, handler.as_ref(), mapped);
                            }
                        }
                    }
                }));
            }
        }

        if let Some(ref runtime_core) = runtime {
            let mut rx = runtime_core.subscribe();
            let tx = event_tx.clone();
            let token = cancel.clone();
            let handler = self.event_handler.clone();
            tasks.push(tokio::spawn(async move {
                loop {
                    tokio::select! {
                        _ = token.cancelled() => break,
                        msg = rx.recv() => {
                            let Ok(event) = msg else { continue; };
                            if let Some(mapped) = map_runtime_event(event) {
                                emit_event(&tx, handler.as_ref(), mapped);
                            }
                        }
                    }
                }
            }));
        }

        Ok(KoiHandle::new_embedded(
            mdns,
            dns,
            health,
            certmesh,
            proxy,
            udp,
            runtime,
            self.config.data_dir.clone(),
            event_tx,
            cancel,
            tasks,
            http_announce_id,
        ))
    }
}

fn init_certmesh_core(
    data_dir: Option<&std::path::Path>,
) -> Option<Arc<koi_certmesh::CertmeshCore>> {
    let paths = match data_dir {
        Some(dir) => koi_certmesh::CertmeshPaths::with_data_dir(dir.to_path_buf()),
        None => koi_certmesh::CertmeshPaths::default(),
    };
    if !paths.is_ca_initialized() {
        return Some(Arc::new(koi_certmesh::CertmeshCore::uninitialized()));
    }

    let roster_path = paths.roster_path();
    let roster = match koi_certmesh::roster::load_roster(&roster_path) {
        Ok(r) => r,
        Err(_) => {
            return Some(Arc::new(koi_certmesh::CertmeshCore::uninitialized()));
        }
    };

    let profile = roster.metadata.trust_profile;

    // ── Auto-unlock at init: single source of truth ─────────────
    // If the auto-unlock key file exists, boot the core already
    // unlocked.  This collapses the "create locked -> read key ->
    // unlock" three-step into a single atomic construction.
    let resolved_data_dir = koi_common::paths::koi_data_dir_with_override(data_dir);
    let auto_key_path = resolved_data_dir.join("auto-unlock-key");
    if let Ok(pp) = std::fs::read_to_string(&auto_key_path) {
        if !pp.is_empty() {
            match koi_certmesh::ca::load_ca(&pp, &paths) {
                Ok(ca_state) => {
                    // Reload roster (fresh copy for the new Arc)
                    if let Ok(fresh_roster) = koi_certmesh::roster::load_roster(&roster_path) {
                        let auth_path = paths.auth_path();
                        let auth = if auth_path.exists() {
                            std::fs::read_to_string(&auth_path)
                                .ok()
                                .and_then(|json| {
                                    serde_json::from_str::<koi_crypto::auth::StoredAuth>(&json).ok()
                                })
                                .and_then(|stored| stored.unlock(&pp).ok())
                        } else {
                            None
                        };

                        tracing::info!("Certmesh CA auto-unlocked at init");
                        return Some(Arc::new(koi_certmesh::CertmeshCore::new(
                            ca_state,
                            fresh_roster,
                            auth,
                            profile,
                        )));
                    }
                }
                Err(e) => {
                    tracing::warn!(
                        error = %e,
                        "Auto-unlock key exists but decryption failed"
                    );
                }
            }
        }
    }

    // No auto-unlock key - boot locked
    let core = koi_certmesh::CertmeshCore::locked(roster, profile);
    Some(Arc::new(core))
}

fn map_mdns_event(event: MdnsEvent) -> Option<KoiEvent> {
    match event {
        MdnsEvent::Found(record) => Some(KoiEvent::MdnsFound(record)),
        MdnsEvent::Resolved(record) => Some(KoiEvent::MdnsResolved(record)),
        MdnsEvent::Removed { name, service_type } => {
            Some(KoiEvent::MdnsRemoved { name, service_type })
        }
    }
}

fn map_health_event(event: koi_health::HealthEvent) -> KoiEvent {
    match event {
        koi_health::HealthEvent::StatusChanged { name, status } => {
            KoiEvent::HealthChanged { name, status }
        }
    }
}

fn map_dns_event(event: koi_dns::DnsEvent) -> KoiEvent {
    match event {
        koi_dns::DnsEvent::EntryUpdated { name, ip } => KoiEvent::DnsEntryUpdated { name, ip },
        koi_dns::DnsEvent::EntryRemoved { name } => KoiEvent::DnsEntryRemoved { name },
    }
}

fn map_certmesh_event(event: koi_certmesh::CertmeshEvent) -> KoiEvent {
    match event {
        koi_certmesh::CertmeshEvent::MemberJoined {
            hostname,
            fingerprint,
        } => KoiEvent::CertmeshMemberJoined {
            hostname,
            fingerprint,
        },
        koi_certmesh::CertmeshEvent::MemberRevoked { hostname } => {
            KoiEvent::CertmeshMemberRevoked { hostname }
        }
        koi_certmesh::CertmeshEvent::Destroyed => KoiEvent::CertmeshDestroyed,
    }
}

fn map_proxy_event(event: koi_proxy::ProxyEvent) -> KoiEvent {
    match event {
        koi_proxy::ProxyEvent::EntryUpdated { entry } => KoiEvent::ProxyEntryUpdated { entry },
        koi_proxy::ProxyEvent::EntryRemoved { name } => KoiEvent::ProxyEntryRemoved { name },
    }
}

fn map_runtime_event(event: koi_runtime::RuntimeEvent) -> Option<KoiEvent> {
    match event {
        koi_runtime::RuntimeEvent::Started(instance) => Some(KoiEvent::RuntimeInstanceStarted {
            name: instance.name,
            backend: instance.backend,
        }),
        koi_runtime::RuntimeEvent::Stopped { name, .. } => {
            Some(KoiEvent::RuntimeInstanceStopped { name })
        }
        // Updated, BackendDisconnected, BackendReconnected are operational events
        // not surfaced as KoiEvents (dashboard SSE covers them)
        _ => None,
    }
}

fn emit_event(
    tx: &broadcast::Sender<KoiEvent>,
    handler: Option<&Arc<dyn Fn(KoiEvent) + Send + Sync>>,
    event: KoiEvent,
) {
    if let Some(handler) = handler {
        handler(event.clone());
    }
    let _ = tx.send(event);
}

pub(crate) fn map_join_error(err: tokio::task::JoinError) -> KoiError {
    KoiError::Io(std::io::Error::other(err.to_string()))
}

/// Build a dashboard snapshot from the embedded domain cores.
async fn build_embedded_snapshot(
    mdns: Option<Arc<koi_mdns::MdnsCore>>,
    certmesh: Option<Arc<koi_certmesh::CertmeshCore>>,
    dns: Option<Arc<koi_dns::DnsRuntime>>,
    health: Option<Arc<koi_health::HealthRuntime>>,
    proxy: Option<Arc<koi_proxy::ProxyRuntime>>,
    udp: Option<Arc<koi_udp::UdpRuntime>>,
    runtime: Option<Arc<koi_runtime::RuntimeCore>>,
) -> serde_json::Value {
    use koi_common::capability::Capability;

    let mut capabilities = Vec::new();

    if let Some(ref core) = mdns {
        let s = core.status();
        capabilities.push(serde_json::json!({
            "name": s.name, "enabled": true, "healthy": s.healthy, "summary": s.summary,
        }));
    } else {
        capabilities.push(serde_json::json!({
            "name": "mdns", "enabled": false, "healthy": false, "summary": "disabled",
        }));
    }

    if let Some(ref core) = certmesh {
        let s = core.status();
        capabilities.push(serde_json::json!({
            "name": s.name, "enabled": true, "healthy": s.healthy, "summary": s.summary,
        }));
    } else {
        capabilities.push(serde_json::json!({
            "name": "certmesh", "enabled": false, "healthy": false, "summary": "disabled",
        }));
    }

    if let Some(ref runtime) = dns {
        let running = runtime.status().await.running;
        if running {
            let s = runtime.core().status();
            capabilities.push(serde_json::json!({
                "name": s.name, "enabled": true, "healthy": s.healthy, "summary": s.summary,
            }));
        } else {
            capabilities.push(serde_json::json!({
                "name": "dns", "enabled": true, "healthy": false, "summary": "stopped",
            }));
        }
    } else {
        capabilities.push(serde_json::json!({
            "name": "dns", "enabled": false, "healthy": false, "summary": "disabled",
        }));
    }

    if let Some(ref runtime) = health {
        let running = runtime.status().await.running;
        if running {
            let s = runtime.core().status();
            capabilities.push(serde_json::json!({
                "name": s.name, "enabled": true, "healthy": s.healthy, "summary": s.summary,
            }));
        } else {
            capabilities.push(serde_json::json!({
                "name": "health", "enabled": true, "healthy": false, "summary": "stopped",
            }));
        }
    } else {
        capabilities.push(serde_json::json!({
            "name": "health", "enabled": false, "healthy": false, "summary": "disabled",
        }));
    }

    if let Some(ref runtime) = proxy {
        let status = runtime.status().await;
        capabilities.push(serde_json::json!({
            "name": "proxy", "enabled": true, "healthy": true,
            "summary": if status.is_empty() { "no listeners".to_string() } else { format!("{} listeners", status.len()) },
        }));
    } else {
        capabilities.push(serde_json::json!({
            "name": "proxy", "enabled": false, "healthy": false, "summary": "disabled",
        }));
    }

    if let Some(ref runtime) = udp {
        let s = Capability::status(runtime.as_ref());
        capabilities.push(serde_json::json!({
            "name": s.name, "enabled": true, "healthy": s.healthy, "summary": s.summary,
        }));
    } else {
        capabilities.push(serde_json::json!({
            "name": "udp", "enabled": false, "healthy": false, "summary": "disabled",
        }));
    }

    if let Some(ref rt) = runtime {
        let s = rt.capability_status().await;
        capabilities.push(serde_json::json!({
            "name": s.name, "enabled": true, "healthy": s.healthy, "summary": s.summary,
        }));
    } else {
        capabilities.push(serde_json::json!({
            "name": "runtime", "enabled": false, "healthy": false, "summary": "disabled",
        }));
    }

    serde_json::json!({ "capabilities": capabilities })
}

// ── Embedded integration bridges ───────────────────────────────────
// Duplicated from the binary crate's integrations.rs because koi-embedded
// is a separate crate that directly imports all domain crates.

struct CertmeshBridgeEmbedded(#[allow(dead_code)] Arc<koi_certmesh::CertmeshCore>);

impl CertmeshBridgeEmbedded {
    fn new(core: Arc<koi_certmesh::CertmeshCore>) -> Arc<Self> {
        Arc::new(Self(core))
    }
}

impl koi_common::integration::CertmeshSnapshot for CertmeshBridgeEmbedded {
    fn active_members(&self) -> Vec<koi_common::integration::MemberSummary> {
        let roster_path = koi_certmesh::CertmeshPaths::default().roster_path();
        let Ok(roster) = koi_certmesh::roster::load_roster(&roster_path) else {
            return Vec::new();
        };
        roster
            .members
            .into_iter()
            .filter(|m| m.status == koi_certmesh::roster::MemberStatus::Active)
            .map(|m| koi_common::integration::MemberSummary {
                hostname: m.hostname,
                sans: m.cert_sans,
                cert_expires: Some(m.cert_expires),
                last_seen: m.last_seen,
                status: "active".to_string(),
                proxy_entries: m
                    .proxy_entries
                    .into_iter()
                    .map(|p| koi_common::integration::ProxyConfigSummary {
                        name: p.name,
                        listen_port: p.listen_port,
                        backend: p.backend,
                        allow_remote: p.allow_remote,
                    })
                    .collect(),
            })
            .collect()
    }
}

struct MdnsBridgeEmbedded {
    records: Arc<
        std::sync::RwLock<
            std::collections::HashMap<String, std::collections::HashMap<String, ServiceRecord>>,
        >,
    >,
    cancel: CancellationToken,
}

impl MdnsBridgeEmbedded {
    async fn spawn(core: Arc<koi_mdns::MdnsCore>) -> Arc<Self> {
        use koi_common::types::META_QUERY;
        let records = Arc::new(std::sync::RwLock::new(std::collections::HashMap::new()));
        let cancel = CancellationToken::new();

        let meta_core = Arc::clone(&core);
        let meta_records = Arc::clone(&records);
        let meta_cancel = cancel.clone();
        tokio::spawn(async move {
            if let Ok(handle) = meta_core.browse(META_QUERY).await {
                run_meta_browse_embedded(meta_core, handle, meta_records, meta_cancel).await;
            }
        });

        Arc::new(Self { records, cancel })
    }
}

impl Drop for MdnsBridgeEmbedded {
    fn drop(&mut self) {
        self.cancel.cancel();
    }
}

impl koi_common::integration::MdnsSnapshot for MdnsBridgeEmbedded {
    fn host_ips(&self) -> std::collections::HashMap<String, std::net::IpAddr> {
        let guard = self.records.read().unwrap_or_else(|e| e.into_inner());
        let mut map = std::collections::HashMap::new();
        for type_map in guard.values() {
            for record in type_map.values() {
                let Some(host) = record.host.as_deref() else {
                    continue;
                };
                let Some(ip) = record.ip.as_deref().and_then(|ip| ip.parse().ok()) else {
                    continue;
                };
                let hostname = host.trim_end_matches('.').trim_end_matches(".local");
                if !hostname.is_empty() {
                    map.insert(hostname.to_string(), ip);
                }
            }
        }
        map
    }

    fn cached_records(&self) -> Vec<ServiceRecord> {
        let guard = self.records.read().unwrap_or_else(|e| e.into_inner());
        guard.values().flat_map(|m| m.values().cloned()).collect()
    }
}

struct DnsBridgeEmbedded(Arc<koi_dns::DnsRuntime>);

impl DnsBridgeEmbedded {
    fn new(runtime: Arc<koi_dns::DnsRuntime>) -> Arc<Self> {
        Arc::new(Self(runtime))
    }
}

impl koi_common::integration::DnsProbe for DnsBridgeEmbedded {
    fn resolve_local(&self, name: &str) -> Option<Vec<std::net::IpAddr>> {
        use hickory_proto::rr::RecordType;
        let core = self.0.core();
        let result = core
            .resolve_local(name, RecordType::A)
            .or_else(|| core.resolve_local(name, RecordType::AAAA));
        result.map(|r| r.ips)
    }
}

struct ProxyBridgeEmbedded(#[allow(dead_code)] Arc<koi_proxy::ProxyCore>);

impl ProxyBridgeEmbedded {
    fn new(core: Arc<koi_proxy::ProxyCore>) -> Arc<Self> {
        Arc::new(Self(core))
    }
}

impl koi_common::integration::ProxySnapshot for ProxyBridgeEmbedded {
    fn entries(&self) -> Vec<koi_common::integration::ProxyEntrySummary> {
        let Ok(entries) = koi_proxy::config::load_entries() else {
            return Vec::new();
        };
        entries
            .into_iter()
            .map(|e| koi_common::integration::ProxyEntrySummary {
                name: e.name,
                listen_port: e.listen_port,
                backend: e.backend,
            })
            .collect()
    }
}

struct AliasFeedbackBridgeEmbedded(Arc<koi_certmesh::CertmeshCore>);

impl AliasFeedbackBridgeEmbedded {
    fn new(core: Arc<koi_certmesh::CertmeshCore>) -> Arc<Self> {
        Arc::new(Self(core))
    }
}

impl koi_common::integration::AliasFeedback for AliasFeedbackBridgeEmbedded {
    fn record_alias(&self, hostname: &str, alias: &str) {
        let core = Arc::clone(&self.0);
        let hostname = hostname.to_string();
        let alias = alias.to_string();
        tokio::spawn(async move {
            let _ = core.add_alias_sans(&hostname, &[alias]).await;
        });
    }
}

async fn run_meta_browse_embedded(
    core: Arc<koi_mdns::MdnsCore>,
    handle: koi_mdns::BrowseHandle,
    records: Arc<
        std::sync::RwLock<
            std::collections::HashMap<String, std::collections::HashMap<String, ServiceRecord>>,
        >,
    >,
    cancel: CancellationToken,
) {
    let active = Arc::new(tokio::sync::Mutex::new(
        std::collections::HashSet::<String>::new(),
    ));
    loop {
        tokio::select! {
            _ = cancel.cancelled() => break,
            event = handle.recv() => {
                let Some(event) = event else { break; };
                if let koi_mdns::events::MdnsEvent::Found(record) = event {
                    let service_type = record.name;
                    let mut guard = active.lock().await;
                    if guard.insert(service_type.clone()) {
                        let c = Arc::clone(&core);
                        let r = Arc::clone(&records);
                        let t = service_type.clone();
                        let cancel_child = cancel.clone();
                        tokio::spawn(async move {
                            if let Ok(handle) = c.browse(&t).await {
                                run_type_browse_embedded(handle, r, cancel_child).await;
                            }
                        });
                    }
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use koi_common::types::ServiceRecord;
    use std::collections::HashMap;

    fn sample_record() -> ServiceRecord {
        ServiceRecord {
            name: "Test Service".to_string(),
            service_type: "_http._tcp".to_string(),
            host: Some("host.local".to_string()),
            ip: Some("10.0.0.1".to_string()),
            port: Some(8080),
            txt: HashMap::new(),
        }
    }

    // ── KoiError Display ───────────────────────────────────────────

    #[test]
    fn koi_error_disabled_capability_display() {
        let err = KoiError::DisabledCapability("mdns");
        assert_eq!(err.to_string(), "capability disabled: mdns");
    }

    #[test]
    fn koi_error_io_from_impl() {
        let io_err = std::io::Error::new(std::io::ErrorKind::NotFound, "file missing");
        let err: KoiError = io_err.into();
        assert!(matches!(err, KoiError::Io(_)));
        assert!(err.to_string().contains("file missing"));
    }

    #[test]
    fn koi_error_debug_does_not_panic() {
        let err = KoiError::DisabledCapability("proxy");
        let debug = format!("{err:?}");
        assert!(debug.contains("DisabledCapability"));
    }

    // ── map_mdns_event ─────────────────────────────────────────────

    #[test]
    fn map_mdns_found() {
        let record = sample_record();
        let event = koi_mdns::MdnsEvent::Found(record.clone());
        let mapped = map_mdns_event(event);
        assert!(mapped.is_some());
        match mapped.unwrap() {
            KoiEvent::MdnsFound(r) => assert_eq!(r.name, "Test Service"),
            other => panic!("expected MdnsFound, got {other:?}"),
        }
    }

    #[test]
    fn map_mdns_resolved() {
        let record = sample_record();
        let event = koi_mdns::MdnsEvent::Resolved(record);
        let mapped = map_mdns_event(event);
        assert!(mapped.is_some());
        match mapped.unwrap() {
            KoiEvent::MdnsResolved(r) => {
                assert_eq!(r.port, Some(8080));
                assert_eq!(r.service_type, "_http._tcp");
            }
            other => panic!("expected MdnsResolved, got {other:?}"),
        }
    }

    #[test]
    fn map_mdns_removed() {
        let event = koi_mdns::MdnsEvent::Removed {
            name: "Gone Service".to_string(),
            service_type: "_http._tcp".to_string(),
        };
        let mapped = map_mdns_event(event);
        assert!(mapped.is_some());
        match mapped.unwrap() {
            KoiEvent::MdnsRemoved { name, service_type } => {
                assert_eq!(name, "Gone Service");
                assert_eq!(service_type, "_http._tcp");
            }
            other => panic!("expected MdnsRemoved, got {other:?}"),
        }
    }

    // ── map_health_event ───────────────────────────────────────────

    #[test]
    fn map_health_status_changed_up() {
        let event = koi_health::HealthEvent::StatusChanged {
            name: "api".to_string(),
            status: koi_health::HealthStatus::Up,
        };
        let mapped = map_health_event(event);
        match mapped {
            KoiEvent::HealthChanged { name, status } => {
                assert_eq!(name, "api");
                assert!(matches!(status, koi_health::HealthStatus::Up));
            }
            other => panic!("expected HealthChanged, got {other:?}"),
        }
    }

    #[test]
    fn map_health_status_changed_down() {
        let event = koi_health::HealthEvent::StatusChanged {
            name: "db".to_string(),
            status: koi_health::HealthStatus::Down,
        };
        let mapped = map_health_event(event);
        match mapped {
            KoiEvent::HealthChanged { name, status } => {
                assert_eq!(name, "db");
                assert!(matches!(status, koi_health::HealthStatus::Down));
            }
            other => panic!("expected HealthChanged, got {other:?}"),
        }
    }

    // ── map_dns_event ──────────────────────────────────────────────

    #[test]
    fn map_dns_entry_updated() {
        let event = koi_dns::DnsEvent::EntryUpdated {
            name: "grafana".to_string(),
            ip: "10.0.0.5".to_string(),
        };
        let mapped = map_dns_event(event);
        match mapped {
            KoiEvent::DnsEntryUpdated { name, ip } => {
                assert_eq!(name, "grafana");
                assert_eq!(ip, "10.0.0.5");
            }
            other => panic!("expected DnsEntryUpdated, got {other:?}"),
        }
    }

    #[test]
    fn map_dns_entry_removed() {
        let event = koi_dns::DnsEvent::EntryRemoved {
            name: "old-host".to_string(),
        };
        let mapped = map_dns_event(event);
        match mapped {
            KoiEvent::DnsEntryRemoved { name } => {
                assert_eq!(name, "old-host");
            }
            other => panic!("expected DnsEntryRemoved, got {other:?}"),
        }
    }

    // ── map_certmesh_event ─────────────────────────────────────────

    #[test]
    fn map_certmesh_member_joined() {
        let event = koi_certmesh::CertmeshEvent::MemberJoined {
            hostname: "node-a".to_string(),
            fingerprint: "sha256:abc".to_string(),
        };
        let mapped = map_certmesh_event(event);
        match mapped {
            KoiEvent::CertmeshMemberJoined {
                hostname,
                fingerprint,
            } => {
                assert_eq!(hostname, "node-a");
                assert_eq!(fingerprint, "sha256:abc");
            }
            other => panic!("expected CertmeshMemberJoined, got {other:?}"),
        }
    }

    #[test]
    fn map_certmesh_member_revoked() {
        let event = koi_certmesh::CertmeshEvent::MemberRevoked {
            hostname: "node-b".to_string(),
        };
        let mapped = map_certmesh_event(event);
        match mapped {
            KoiEvent::CertmeshMemberRevoked { hostname } => {
                assert_eq!(hostname, "node-b");
            }
            other => panic!("expected CertmeshMemberRevoked, got {other:?}"),
        }
    }

    #[test]
    fn map_certmesh_destroyed() {
        let event = koi_certmesh::CertmeshEvent::Destroyed;
        let mapped = map_certmesh_event(event);
        assert!(matches!(mapped, KoiEvent::CertmeshDestroyed));
    }

    // ── map_proxy_event ────────────────────────────────────────────

    #[test]
    fn map_proxy_entry_updated() {
        let entry = koi_proxy::ProxyEntry {
            name: "web".to_string(),
            listen_port: 443,
            backend: "http://localhost:3000".to_string(),
            allow_remote: true,
        };
        let event = koi_proxy::ProxyEvent::EntryUpdated {
            entry: entry.clone(),
        };
        let mapped = map_proxy_event(event);
        match mapped {
            KoiEvent::ProxyEntryUpdated { entry } => {
                assert_eq!(entry.name, "web");
                assert_eq!(entry.listen_port, 443);
                assert!(entry.allow_remote);
            }
            other => panic!("expected ProxyEntryUpdated, got {other:?}"),
        }
    }

    #[test]
    fn map_proxy_entry_removed() {
        let event = koi_proxy::ProxyEvent::EntryRemoved {
            name: "old-proxy".to_string(),
        };
        let mapped = map_proxy_event(event);
        match mapped {
            KoiEvent::ProxyEntryRemoved { name } => {
                assert_eq!(name, "old-proxy");
            }
            other => panic!("expected ProxyEntryRemoved, got {other:?}"),
        }
    }

    // ── map_join_error ─────────────────────────────────────────────

    #[test]
    fn map_join_error_produces_io_error() {
        // We can't easily create a real JoinError, but we can test the function
        // signature exists and the KoiError::Io variant wraps correctly.
        let io_err = std::io::Error::other("simulated join error");
        let koi_err = KoiError::Io(io_err);
        assert!(koi_err.to_string().contains("simulated join error"));
    }

    // ── Builder defaults ───────────────────────────────────────────

    #[test]
    fn builder_default_config() {
        let builder = Builder::new();
        let embedded = builder.build().expect("build should succeed");
        assert!(embedded.config.mdns_enabled);
        assert!(!embedded.config.http_enabled);
        assert_eq!(embedded.config.http_port, 5641);
    }

    #[test]
    fn builder_default_trait() {
        let builder = Builder::default();
        let embedded = builder.build().expect("build should succeed");
        assert_eq!(embedded.config.service_endpoint, "http://127.0.0.1:5641");
    }

    #[test]
    fn builder_fluent_overrides() {
        let embedded = Builder::new()
            .http(true)
            .mdns(false)
            .dns_enabled(false)
            .health(true)
            .certmesh(true)
            .proxy(true)
            .udp(true)
            .http_port(9000)
            .dashboard(true)
            .api_docs(true)
            .mdns_browser(true)
            .announce_http(true)
            .dns_auto_start(true)
            .health_auto_start(true)
            .proxy_auto_start(true)
            .service_endpoint("http://10.0.0.1:8080")
            .service_mode(ServiceMode::EmbeddedOnly)
            .data_dir("/tmp/koi-test")
            .build()
            .expect("build should succeed");

        assert!(embedded.config.http_enabled);
        assert!(!embedded.config.mdns_enabled);
        assert!(!embedded.config.dns_enabled);
        assert!(embedded.config.health_enabled);
        assert!(embedded.config.certmesh_enabled);
        assert!(embedded.config.proxy_enabled);
        assert!(embedded.config.udp_enabled);
        assert_eq!(embedded.config.http_port, 9000);
        assert!(embedded.config.dashboard_enabled);
        assert!(embedded.config.api_docs_enabled);
        assert!(embedded.config.mdns_browser_enabled);
        assert!(embedded.config.announce_http);
        assert!(embedded.config.dns_auto_start);
        assert!(embedded.config.health_auto_start);
        assert!(embedded.config.proxy_auto_start);
        assert_eq!(embedded.config.service_endpoint, "http://10.0.0.1:8080");
        assert_eq!(embedded.config.service_mode, ServiceMode::EmbeddedOnly);
        assert_eq!(
            embedded.config.data_dir,
            Some(std::path::PathBuf::from("/tmp/koi-test"))
        );
    }

    #[test]
    fn builder_dns_configure_closure() {
        let embedded = Builder::new()
            .dns(|b| b.port(5353).zone("home").local_ttl(120))
            .build()
            .expect("build should succeed");

        assert_eq!(embedded.config.dns_config.port, 5353);
        assert_eq!(embedded.config.dns_config.zone, "home");
        assert_eq!(embedded.config.dns_config.local_ttl, 120);
    }

    #[test]
    fn builder_event_handler() {
        use std::sync::atomic::{AtomicBool, Ordering};
        let called = Arc::new(AtomicBool::new(false));
        let called_clone = called.clone();

        let embedded = Builder::new()
            .events(move |_event| {
                called_clone.store(true, Ordering::SeqCst);
            })
            .build()
            .expect("build should succeed");

        assert!(embedded.event_handler.is_some());
    }

    #[test]
    fn builder_extra_firewall_ports() {
        use koi_common::firewall::{FirewallPort, FirewallProtocol};
        let extra = vec![FirewallPort::new("Custom", FirewallProtocol::Tcp, 12345)];
        let _builder = Builder::new().extra_firewall_ports(extra);
        // Just verifying the method compiles and does not panic.
    }

    // ── Result type alias ──────────────────────────────────────────

    #[test]
    fn result_type_works_with_ok() {
        let result: Result<i32> = Ok(42);
        assert_eq!(result.unwrap(), 42);
    }

    #[test]
    fn result_type_works_with_err() {
        let result: Result<i32> = Err(KoiError::DisabledCapability("test"));
        assert!(result.is_err());
    }
}

async fn run_type_browse_embedded(
    handle: koi_mdns::BrowseHandle,
    records: Arc<
        std::sync::RwLock<
            std::collections::HashMap<String, std::collections::HashMap<String, ServiceRecord>>,
        >,
    >,
    cancel: CancellationToken,
) {
    loop {
        tokio::select! {
            _ = cancel.cancelled() => break,
            event = handle.recv() => {
                let Some(event) = event else { break; };
                match event {
                    koi_mdns::events::MdnsEvent::Resolved(record) => {
                        let mut guard = records.write().unwrap_or_else(|e| e.into_inner());
                        let entry = guard.entry(record.service_type.clone()).or_default();
                        entry.insert(record.name.clone(), record);
                    }
                    koi_mdns::events::MdnsEvent::Removed { name, service_type } => {
                        let mut guard = records.write().unwrap_or_else(|e| e.into_inner());
                        let st = if service_type.is_empty() {
                            name.find("._").map(|idx| {
                                let rest = &name[idx + 1..];
                                rest.trim_end_matches('.').trim_end_matches(".local").to_string()
                            })
                        } else {
                            Some(service_type)
                        };
                        if let Some(st) = st {
                            if let Some(map) = guard.get_mut(&st) {
                                let instance = name.find("._").map(|idx| name[..idx].to_string());
                                if let Some(instance) = instance {
                                    map.remove(&instance);
                                }
                            }
                        }
                    }
                    _ => {}
                }
            }
        }
    }
}