sapphire-framework-server 0.29.0

App server skeleton for sapphire-framework: owns a workspace's cache and serves it over IPC
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
//! The app server skeleton.
//!
//! An application builds one of these, adds its own methods, and runs it. Everything a
//! sapphire app needs on the server side — owning its workspace, answering `workspace.*`,
//! pushing events — is here. A server serves one workspace at a time (#215): see
//! [`Current`].
//!
//! See `docs/superpowers/specs/2026-09-16-process-architecture-design.md` §4.
//!
//! ```rust,ignore
//! static CTX: AppContext = AppContext::new("sapphire-journal");
//!
//! AppServer::new(&CTX, env!("CARGO_PKG_VERSION"))
//!     .extend(|router| router.method("journal.create_entry", create_entry))
//!     .run()
//!     .await?;
//! ```
//!
//! Application methods are named `<app>.<method>`. The framework owns `workspace.*` and
//! `server.*`; anything else is the application's.

#![warn(missing_docs)]

use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;

use corundum_framework_service::ServiceSpec;
use sapphire_backend::protocol as proto;
use sapphire_ipc::{Endpoint, ManagedBy, Router, ServerInfo, serve};
use sapphire_workspace::AppContext;
use tokio::sync::Notify;

use crate::restart::Exit;

/// How long a server's shutdown waits for its open connections to wind down on their own.
///
/// The shutdown acknowledgement is one of those connections; a moment is all a well-behaved
/// client needs. Whatever still holds on after this is cancelled, so a connection kept open
/// past shutdown cannot pin the router — and through it the sync runtime's replica stores —
/// after the server has answered its own shutdown call.
const SERVE_GRACE: Duration = Duration::from_secs(2);

pub mod api_keys;
mod command;
mod config;
mod config_methods;
mod current;
mod error;
mod events;
#[cfg(feature = "metrics")]
mod exporter;
mod fs_methods;
mod handlers;
mod host;
#[cfg(feature = "http")]
mod http;
mod instrument;
mod relay;
mod restart;
mod selection;
mod settings;
pub mod sync;
#[cfg(test)]
mod test_support;
mod update;

pub use command::{
    AppConfigCommand, AppScopeFlags, AppUpdateArgs, FrameworkCommand, LegacyExternalDevice,
    StatusReport, StatusRow, WorkspaceCommand, WorkspaceSyncCommand, render_workspace,
    render_workspace_show, update_bridge,
};
pub use config::{
    HttpConfig, HttpMcpConfig, HttpMetricsConfig, SERVER_CONFIG_FILE, ServerConfig, UpdateConfig,
};
pub use current::Current;
pub use error::{Error, Result};
pub use events::subscribe_method;
pub use fs_methods::{LOCAL_PRINCIPAL, OWN_FOLDER, SapphireApp, actor_for};
pub use handlers::workspace_router;
pub use host::WorkspaceHost;
pub use restart::serve_restarting;
pub use sapphire_framework_settings::{
    Apply, FieldError, Kind, Process, Scope, SettingDef, Staged, Value,
};
pub use sapphire_framework_update::{ReleaseSource, UpdateArgs};
pub use selection::{SELECTION_FILE, Selection, SelectionFile};
pub use settings::{AppFiles, AppSettings, FromValue, HttpEndpoint, Settings};
pub use sync::{BackfillTiming, BridgeConnector, SyncRuntime, SyncStatus, sync_router};

/// The MCP tools an application serves, and how (feature `mcp`).
#[cfg(feature = "mcp")]
pub use sapphire_framework_mcp as mcp;

/// The `metrics` crate, for an application's own metrics: the macros it records with, and
/// the types [`AppServer::metrics_collector`] sets them from.
pub use metrics;

/// An application's server.
pub struct AppServer {
    ctx: &'static AppContext,
    version: &'static str,
    endpoint: Option<Endpoint>,
    /// Where `workspace.toml` lives; `None` is the config directory's.
    selection_file: Option<PathBuf>,
    host: Arc<WorkspaceHost>,
    sync: Option<Arc<SyncRuntime>>,
    /// How the relay reaches the bridge when there is no sync runtime to share; `None` is
    /// the host's own bridge.
    bridge_connector: Option<BridgeConnector>,
    extend: Option<Box<dyn FnOnce(Router) -> Router + Send>>,
    /// The application's own status rows, shown after the framework's in `status` and in
    /// the `server.info` report.
    status_rows: Option<Arc<dyn Fn() -> Vec<StatusRow> + Send + Sync>>,
    /// The version of the application's own API, reported in the handshake.
    app_api: Option<u32>,
    /// The framework's settings, when given rather than read from `config.toml`.
    config: Option<ServerConfig>,
    /// The settings `config.*` reads and writes, and `config` comes from unless given;
    /// `None` reads the framework's alone when `run` starts.
    pub(crate) settings: Option<Settings>,
    /// Where the application's releases are published: what the server looks for newer
    /// ones in, and what `update` installs from.
    releases: Option<ReleaseSource>,
    /// Whether `run` stops on SIGTERM and ctrl-c. Off where the server is not the process's
    /// own (a phone app hosting it in-process).
    signals: bool,
    /// What the application sets on every scrape of `/metrics`. Kept in a build without
    /// feature `metrics` too, so the builder method needs no gate; `run` never calls them there.
    metrics_collectors: Vec<Arc<dyn Fn() + Send + Sync>>,
    /// Where the HTTP listener binds when `config.toml` does not say.
    #[cfg(feature = "http")]
    http_listen: Option<std::net::SocketAddr>,
    /// The application's own HTTP routes.
    #[cfg(feature = "http")]
    http_routes: Option<axum::Router>,
    /// The application's switchable HTTP endpoints, by name.
    #[cfg(feature = "http")]
    http_endpoints: Vec<(String, axum::Router)>,
    /// How the HTTP routes check a token; `None`: the served workspace's API keys.
    #[cfg(feature = "http")]
    http_auth: Option<sapphire_framework_keys::AuthConfig>,
    /// The profiles an API key may act as, and what each may do.
    key_profiles: sapphire_framework_keys::KeyProfiles,
    /// The application's MCP handler, for the `mcp` subcommand and `/mcp`.
    #[cfg(feature = "mcp")]
    mcp: sapphire_framework_mcp::McpService,
}

/// The SIGTERM end of the server's select loop, in a shape every platform shares.
///
/// [`AppServer::run`]'s select arm awaits `recv()` on one of these, exactly as the
/// plan writes it for Unix. Unix backs it with the `SignalKind::terminate()`
/// stream; Windows has no SIGTERM, so there the future never resolves and the arm
/// exists for the macro's sake and never fires. Without the common shape the arm
/// would need a `#[cfg]` of its own, which tokio's `select!` rejects once the
/// attribute removes the arm.
#[cfg(unix)]
struct Sigterm(tokio::signal::unix::Signal);

/// The never-firing stand-in for the Unix `Sigterm` where there is no SIGTERM.
#[cfg(not(unix))]
struct Sigterm;

impl Sigterm {
    /// The stream a server that listens for signals awaits SIGTERM on.
    ///
    /// Registered before the listener binds, so a signal arriving the instant the socket
    /// is up is queued by tokio instead of killing the process with the default handler.
    /// SIGINT is listened to only through `ctrl_c` (which swallows the default handler on
    /// both platforms): a Unix `SignalKind::interrupt()` stream would double-fire for ^C.
    fn register() -> Result<Option<Sigterm>> {
        #[cfg(unix)]
        return Ok(Some(Sigterm::new()?));
        #[cfg(not(unix))]
        return Ok(Some(Sigterm));
    }
}

#[cfg(unix)]
impl Sigterm {
    /// Register interest in SIGTERM: see [`register`](Self::register).
    fn new() -> Result<Self> {
        Ok(Self(tokio::signal::unix::signal(
            tokio::signal::unix::SignalKind::terminate(),
        )?))
    }

    /// Wait for the next SIGTERM.
    ///
    /// Never returns `None`: the stream is infinite, as its documentation states.
    async fn recv(&mut self) {
        self.0.recv().await;
    }
}

#[cfg(not(unix))]
impl Sigterm {
    /// A future that is never ready — the arm awaits it for the macro's sake only.
    ///
    /// There is no `new`: this platform has no SIGTERM to register interest in, so
    /// [`register`](Self::register) makes the unit value directly.
    async fn recv(&mut self) {
        std::future::pending::<()>().await
    }
}

/// The file the selected workspace is kept in: at `path` when a fixture moved it, in the
/// config directory otherwise.
fn selection_at(ctx: &AppContext, path: Option<PathBuf>) -> SelectionFile {
    match path {
        Some(path) => SelectionFile::at(path),
        None => SelectionFile::for_app(ctx),
    }
}

/// ctrl-c, when the server listens for signals; never otherwise.
async fn interrupted(signals: bool) {
    if signals {
        // An error means no handler could be installed: nothing will arrive.
        if tokio::signal::ctrl_c().await.is_ok() {
            return;
        }
    }
    std::future::pending::<()>().await
}

/// SIGTERM, when the server listens for signals; never otherwise.
async fn terminated(sigterm: &mut Option<Sigterm>) {
    match sigterm {
        Some(sigterm) => sigterm.recv().await,
        None => std::future::pending::<()>().await,
    }
}

impl AppServer {
    /// A server for `ctx`'s application, reporting `version` in its handshake.
    pub fn new(ctx: &'static AppContext, version: &'static str) -> AppServer {
        AppServer {
            ctx,
            version,
            endpoint: None,
            selection_file: None,
            host: Arc::new(WorkspaceHost::new(ctx)),
            sync: None,
            bridge_connector: None,
            extend: None,
            status_rows: None,
            app_api: None,
            config: None,
            settings: None,
            releases: None,
            signals: true,
            metrics_collectors: Vec::new(),
            #[cfg(feature = "http")]
            http_listen: None,
            #[cfg(feature = "http")]
            http_routes: None,
            #[cfg(feature = "http")]
            http_endpoints: Vec::new(),
            #[cfg(feature = "http")]
            http_auth: None,
            key_profiles: sapphire_framework_keys::KeyProfiles::standard(),
            #[cfg(feature = "mcp")]
            mcp: sapphire_framework_mcp::McpService::framework(),
        }
    }

    /// The application this server serves, as its [`AppContext`] names it.
    pub fn app_name(&self) -> &'static str {
        self.ctx.app_name
    }

    /// Listen somewhere other than the application's default endpoint. Used by tests.
    pub fn endpoint(mut self, endpoint: Endpoint) -> AppServer {
        self.endpoint = Some(endpoint);
        self
    }

    /// Stop on SIGTERM and ctrl-c (`true`, the default), or leave signals to the process.
    ///
    /// A host that runs the server inside a larger process — a phone app, with the bridge
    /// and the GUI beside it — turns this off: the signals are the process's to handle,
    /// and the server stops when the task running it is dropped.
    pub fn signals(mut self, on: bool) -> AppServer {
        self.signals = on;
        self
    }

    /// Report `version` as the application's own API version in the handshake: the major
    /// of the application's API crate, which carries the methods it adds with
    /// [`extend`](Self::extend). A client that calls those methods names the version it
    /// expects, and the handshake refuses a server that speaks another.
    pub fn app_api(mut self, version: u32) -> AppServer {
        self.app_api = Some(version);
        self
    }

    /// Use `config` rather than the one `<config dir>/config.toml` gives: for fixtures.
    /// `config.*` still reads and writes the file.
    pub fn config(mut self, config: ServerConfig) -> AppServer {
        self.config = Some(config);
        self
    }

    /// Serve the application's settings `app` beside the framework's, read now: for
    /// fixtures. Called after [`selection_file`](Self::selection_file), whose selected
    /// workspace holds the workspace scope.
    #[cfg(feature = "test-util")]
    #[doc(hidden)]
    pub fn app_settings(mut self, app: Arc<dyn AppSettings>) -> Result<AppServer> {
        let selection = self.selection();
        self.settings = Some(Settings::load_with(self.ctx, app, selection)?);
        Ok(self)
    }

    /// The settings `config.*` serves, once [`app_settings`](Self::app_settings) has read
    /// them: for fixtures.
    #[cfg(feature = "test-util")]
    #[doc(hidden)]
    pub fn settings(&self) -> Option<&Settings> {
        self.settings.as_ref()
    }

    /// The endpoint this server listens on: the one [`endpoint`](Self::endpoint) gave, or
    /// the application's own.
    fn endpoint_or_default(&self) -> Result<Endpoint> {
        match &self.endpoint {
            Some(e) => Ok(e.clone()),
            None => Ok(Endpoint::for_app(self.ctx.app_name)?),
        }
    }

    /// The file the selected workspace is kept in.
    #[cfg(feature = "test-util")]
    fn selection(&self) -> SelectionFile {
        selection_at(self.ctx, self.selection_file.clone())
    }

    /// Where the HTTP listener binds unless `config.toml` says otherwise: the application's
    /// own port. Without it, a host that serves anything over HTTP names the address in
    /// `[http] listen`.
    #[cfg(feature = "http")]
    pub fn http_listen(mut self, addr: std::net::SocketAddr) -> AppServer {
        self.http_listen = Some(addr);
        self
    }

    /// Serve the application's own HTTP routes on the server's listener, behind the same
    /// API key's token as `/mcp`. The routes are served whenever they are given;
    /// `/mcp` only when `config.toml` turns it on. For routes a setting turns on and off,
    /// see [`http_endpoint`](Self::http_endpoint).
    ///
    /// Every route but `/metrics` is behind the token. While `[http.metrics]` is on, the
    /// public `/metrics` answers first, so an application route at `/metrics` is shadowed.
    #[cfg(feature = "http")]
    pub fn http(mut self, routes: axum::Router) -> AppServer {
        self.http_routes = Some(routes);
        self
    }

    /// Serve `routes` at `/<name>` on the server's listener, behind the same token as
    /// `/mcp`, while `http.<name>.enabled` is on; it is off by default.
    ///
    /// `name` is one the application's settings declare
    /// ([`AppSettings::http_endpoints`]), which gives the switch its help text: one they
    /// do not declare stops [`run`](Self::run) with an error.
    #[cfg(feature = "http")]
    pub fn http_endpoint(mut self, name: impl Into<String>, routes: axum::Router) -> AppServer {
        self.http_endpoints.push((name.into(), routes));
        self
    }

    /// Check HTTP tokens with `auth` rather than with the served workspace's API keys: for
    /// fixtures, or for an application whose own [`Verifier`](sapphire_framework_keys::Verifier)
    /// wraps [`api_keys::WorkspaceKeyVerifier`] to map a key to something of its own.
    #[cfg(feature = "http")]
    pub fn http_auth(mut self, auth: sapphire_framework_keys::AuthConfig) -> AppServer {
        self.http_auth = Some(auth);
        self
    }

    /// The profiles an API key may act as, and the access each gives: the framework's
    /// `read-only`, `read-write` and `admin` unless the application has its own
    /// (sapphire-agent's room profiles). `api-key add --profile` takes one of them, and the
    /// HTTP routes hold a key to its access: a read-only key calls only `/mcp`'s read-only
    /// tools, and only `GET` the application's routes.
    pub fn key_profiles(mut self, profiles: sapphire_framework_keys::KeyProfiles) -> AppServer {
        self.key_profiles = profiles;
        self
    }

    /// The profiles an API key may act as ([`key_profiles`](Self::key_profiles)).
    pub fn profiles(&self) -> &sapphire_framework_keys::KeyProfiles {
        &self.key_profiles
    }

    /// Answer MCP with the application's own handler, rather than the framework's tools
    /// alone: on stdio for the `mcp` subcommand, and at `/mcp` when `config.toml` turns it
    /// on.
    #[cfg(feature = "mcp")]
    pub fn mcp(mut self, service: sapphire_framework_mcp::McpService) -> AppServer {
        self.mcp = service;
        self
    }

    /// Serve the application's MCP tools on this process's stdio, until the agent closes
    /// it: the `mcp` subcommand.
    ///
    /// This is the client side: the tools reach the running server over its IPC endpoint,
    /// as the CLI does, and nothing here starts one.
    #[cfg(feature = "mcp")]
    pub async fn serve_mcp_stdio(self, version: &'static str) -> Result<()> {
        let endpoint = match self.endpoint {
            Some(e) => e,
            None => Endpoint::for_app(self.ctx.app_name)?,
        };
        let ctx = sapphire_framework_mcp::ToolContext::dial(
            self.ctx.app_name,
            version,
            self.app_api,
            endpoint,
        );
        self.mcp
            .serve_stdio(ctx)
            .await
            .map_err(|e| Error::Mcp(e.to_string()))
    }

    /// Keep the selected workspace (`workspace.toml`) at `path` rather than in the
    /// application's config directory: for fixtures that run several hosts in one process.
    pub fn selection_file(mut self, path: PathBuf) -> AppServer {
        self.selection_file = Some(path);
        self
    }

    /// Serve `sync.enable`, `sync.disable`, `sync.map` and `sync.status`, and keep a replica
    /// of the workspace in step with its files while it is synced.
    ///
    /// Without this the server has no sync at all: an application that does not call it
    /// never talks to the bridge. The runtime is built by the caller because it needs the
    /// bridge connection, which is the caller's to open and to close.
    pub fn sync(mut self, runtime: Arc<SyncRuntime>) -> AppServer {
        // The runtime re-indexes what a session writes, and the index belongs to this host:
        // tell it where the workspace lives before anything can arrive.
        runtime.set_host(Arc::clone(&self.host));
        self.sync = Some(runtime);
        self
    }

    /// Sync through the host's `sapphire-bridge`: [`sync`](Self::sync) with a runtime that
    /// reaches the bridge itself, and reaches it again whenever it is lost (#244).
    ///
    /// [`run`](Self::run) makes the first attempt. No bridge running is not fatal — the
    /// server serves without sync and picks the bridge up once it starts, and `sync.*`
    /// answers that it is not connected meanwhile — but any other failure, such as a bridge
    /// of another API version, stops the start.
    pub fn sync_via_bridge(self) -> Result<AppServer> {
        let runtime = SyncRuntime::connecting(
            self.ctx,
            BridgeConnector::standard(self.ctx.app_name, self.version),
            std::env::current_exe()?,
            ManagedBy::Service,
        );
        Ok(self.sync(Arc::new(runtime)))
    }

    /// Reach the bridge with `connector` for the relayed `bridge.*`, `embed.*` and
    /// `config.*` methods, rather than at the host's standard
    /// endpoint.
    ///
    /// Used only without [`sync`](Self::sync): a server with a sync runtime relays over the
    /// runtime's connection. The connection is made on the first relayed call, and made
    /// again on the next call after it drops.
    pub fn bridge_connector(mut self, connector: BridgeConnector) -> AppServer {
        self.bridge_connector = Some(connector);
        self
    }

    /// The application's own rows for the status report: shown after the framework's
    /// `running` / `version` / `pid` / `managed_by` lines.
    ///
    /// The closure is called once per report, so an application's rows may read live
    /// state; the CLI's `status` and the IPC `server.info` method render the same call's
    /// output.
    pub fn status_rows(mut self, rows: Arc<dyn Fn() -> Vec<StatusRow> + Send + Sync>) -> AppServer {
        self.status_rows = Some(rows);
        self
    }

    /// Set the application's own gauges on every scrape of `/metrics`.
    ///
    /// `collect` runs once per scrape, after the framework has refreshed its own state and
    /// before the response is rendered; collectors run in the order they were added. It runs
    /// inside the async `/metrics` handler, so keep it cheap and non-blocking — read values
    /// already held rather than doing I/O or waiting on a lock — and it must not panic. Set
    /// state with `sapphire_framework::metrics::gauge!`, and prefix each name with the
    /// application's own, as in `sapphire_journal_entries`, so it cannot collide with the
    /// framework's `sapphire_*` names. Labels carry no identifiers, paths or names: the
    /// endpoint is served without a token, so anything in a label is public.
    ///
    /// A build without feature `metrics`, or a server whose `config.toml` leaves
    /// `[http.metrics]` off, never calls it.
    pub fn metrics_collector(mut self, collect: Arc<dyn Fn() + Send + Sync>) -> AppServer {
        self.metrics_collectors.push(collect);
        self
    }

    /// Where this application's releases are published.
    ///
    /// The server looks there for newer ones once at start and once a day after, unless
    /// `config.toml` says `[update] check = false`; `status` and the GUI show what it found.
    /// The `update` command installs from there, when `source` names the release's
    /// [asset](ReleaseSource::asset), and only a file signed with sapphire-turtle's key
    /// ([`UPDATE_PUBKEY`](sapphire_framework_update::UPDATE_PUBKEY)), unless `source` names
    /// another ([`ReleaseSource::pubkey`]) (#402). The release must carry `<file>.sig`:
    /// sapphire-turtle/.github's `release-binary.yml` with `sign: true`.
    pub fn releases(mut self, source: ReleaseSource) -> AppServer {
        self.releases = Some(match source.update_pubkey() {
            Some(_) => source,
            None => source.pubkey(sapphire_framework_update::UPDATE_PUBKEY),
        });
        self
    }

    /// Where this application's releases are published, if it said.
    pub fn release_source(&self) -> Option<&ReleaseSource> {
        self.releases.as_ref()
    }

    /// What this application's service is: the arguments a service manager starts it with.
    ///
    /// `["serve"]`: a service manager starts the executable directly with
    /// [`FrameworkCommand::Serve`](crate::FrameworkCommand::Serve) — the bare invocation
    /// prints the help in the CLI version and opens the window in the desktop one. A CLI
    /// that wants its service installed hands this to
    /// [`ServiceCommand`](corundum_framework_service::ServiceCommand), which registers the
    /// running executable (the AppImage, inside one).
    pub fn service_spec(&self) -> ServiceSpec {
        app_service_spec(self.ctx.app_name, self.version)
    }

    /// Add the application's own methods.
    pub fn extend(mut self, f: impl FnOnce(Router) -> Router + Send + 'static) -> AppServer {
        self.extend = Some(Box::new(f));
        self
    }

    /// The workspace this server has open. An application's own handlers use it to reach
    /// the workspace the same way the framework's do: [`WorkspaceHost::backend`].
    pub fn host(&self) -> &Arc<WorkspaceHost> {
        &self.host
    }

    /// The sync runtime, once [`sync`](Self::sync) or [`sync_via_bridge`](Self::sync_via_bridge)
    /// has set one (#250): for an application's own code that reads sync state — status
    /// rows, or which device is the workspace's primary.
    pub fn sync_runtime(&self) -> Option<&Arc<SyncRuntime>> {
        self.sync.as_ref()
    }

    /// Listen until told to stop, or until a signal arrives.
    ///
    /// A server run this way answers `server.restart` with an error: nothing would bring it
    /// back. [`serve_restarting`] runs one that can.
    pub async fn run(self) -> Result<()> {
        // Before anything is bound: a mistake in the application, not in the files.
        #[cfg(feature = "http")]
        undeclared_endpoints(self.settings.as_ref(), &self.http_endpoints)?;
        let endpoint = self.endpoint_or_default()?;
        // The app's log file, held for as long as this server serves: the guard's drop
        // flushes the writer thread, so the last lines of a clean shutdown land in the file.
        // The subscriber itself was installed by `ctx.init`; this is what routes the file
        // layer at `<data dir>/logs/`.
        let _log = sapphire_workspace::logging::install(self.ctx)?;
        // Registered before the bind: see `Sigterm::register`.
        let mut sigterm = if self.signals {
            Sigterm::register()?
        } else {
            None
        };
        #[cfg(unix)]
        let mut listener = sapphire_ipc::bind(&endpoint).await?;
        #[cfg(windows)]
        let mut listener = sapphire_ipc::bind(&endpoint)?;
        let exit = self.serve_on(&mut listener, None, &mut sigterm).await;
        drop(listener); // removes the socket file on Unix
        debug_assert!(
            !matches!(exit, Ok(Exit::Restart)),
            "nothing can ask for one"
        );
        exit.map(|_| ())
    }

    /// Serve on `listener` until told to stop, a signal arrives, or `restart` fires.
    ///
    /// `restart` is what `server.restart` fires; `None` answers it with an error.
    /// `sigterm` is the caller's, so it outlives one server: see [`serve_restarting`].
    /// The listener, the log and the process stay with the caller; everything else this
    /// server started is stopped before it returns — on [`Exit::Restart`] down to the last
    /// task that held the sync runtime, so the next server's runtime can open the replica
    /// store.
    pub(crate) async fn serve_on(
        self,
        listener: &mut sapphire_ipc::Listener,
        restart: Option<Arc<Notify>>,
        sigterm: &mut Option<Sigterm>,
    ) -> Result<Exit> {
        let AppServer {
            ctx,
            version,
            endpoint: _,
            selection_file,
            host,
            sync,
            bridge_connector,
            extend,
            status_rows,
            app_api,
            config,
            settings,
            releases,
            signals,
            metrics_collectors,
            #[cfg(feature = "http")]
            http_listen,
            #[cfg(feature = "http")]
            http_routes,
            #[cfg(feature = "http")]
            http_endpoints,
            #[cfg(feature = "http")]
            http_auth,
            key_profiles,
            #[cfg(feature = "mcp")]
            mcp,
        } = self;
        // Only the HTTP routes check a key.
        #[cfg(not(feature = "http"))]
        let _ = key_profiles;
        // Without the exporter nothing scrapes, so there is nothing to call them from.
        #[cfg(not(feature = "metrics"))]
        let _ = metrics_collectors;

        // A server is always-on from here on: only `serve` and the service manager start
        // one, and the service manager starts it for keeps. There is no spawned mode left
        // to report.
        let info = ServerInfo {
            version: version.to_owned(),
            api: proto::API_VERSION,
            app_api,
            pid: std::process::id(),
            managed_by: ManagedBy::Service,
        };

        let file = selection_at(ctx, selection_file);
        // A context whose config directory was never resolved has no file to read, and
        // gets the defaults — as it gets no log file — and no settings of its own to serve.
        let settings = match settings {
            Some(settings) => Some(settings),
            None if ctx.try_config_dir().is_some() => {
                Some(Settings::load_with(ctx, Arc::new(()), file.clone())?)
            }
            None => None,
        };
        let config = match (config, &settings) {
            (Some(config), _) => config,
            (None, Some(settings)) => ServerConfig::from_settings(settings)?,
            (None, None) => ServerConfig::default(),
        };
        #[cfg(feature = "http")]
        undeclared_endpoints(settings.as_ref(), &http_endpoints)?;
        #[cfg(feature = "http")]
        let http_routes = http_endpoints
            .into_iter()
            .filter(|(name, _)| config.http.endpoints.contains(name))
            .fold(http_routes, |routes, (name, endpoint)| {
                let endpoint = axum::Router::new().nest(&format!("/{name}"), endpoint);
                Some(match routes {
                    Some(routes) => routes.merge(endpoint),
                    None => endpoint,
                })
            });
        // A read-only key may only `GET` the application's routes; `/mcp`, all `POST`,
        // checks each tool instead.
        #[cfg(feature = "http")]
        let http_routes = http_routes.map(sapphire_framework_keys::read_only_by_method);
        #[cfg(not(feature = "mcp"))]
        if config.http.mcp.enabled {
            tracing::warn!(
                "config.toml turns MCP over HTTP on, but this build of {} has no MCP",
                ctx.app_name
            );
        }
        #[cfg(not(feature = "metrics"))]
        if config.http.metrics.enabled {
            tracing::warn!(
                "config.toml turns metrics on, but this build of {} has no metrics",
                ctx.app_name
            );
        }

        let (stop_tx, mut stop_rx) = tokio::sync::watch::channel(false);

        // What `server.update` answers; the looking task fills it in once the server serves.
        let update_status = update::SharedStatus::default();
        let update_check = releases.filter(|_| config.update.check);

        // The first attempt to reach the bridge, before the selected workspace comes back
        // and asks it for sync.
        if let Some(runtime) = &sync {
            runtime.connect().await?;
        }

        // Workspace keys follow the selection and the marker's `config.toml` as sync or an
        // edit changes it.
        let mut current = Current::new(ctx, Arc::clone(&host), sync.clone(), file);
        if let Some(settings) = &settings {
            current = current.with_settings(settings.clone());
        }
        if let Some(runtime) = &sync {
            runtime.set_settings(settings.clone());
        }
        let current = Arc::new(current);
        // Back to the workspace this host had, before the first client can ask for it.
        let restoring = current.restore().await;

        let mut router = subscribe_method(
            Arc::clone(&host),
            current::current_methods(
                Arc::clone(&current),
                // `fs.*` and `journal.*`: the explorer's methods, beside `workspace.*`.
                fs_methods::fs_methods(
                    Arc::clone(&current),
                    workspace_router(Arc::clone(&current)),
                ),
            ),
        );
        if sync.is_some() {
            // `sync_router` is applied *under* the application's own methods so a later
            // `extend` can still replace one, and after `subscribe_method` so the
            // `workspace.*` namespace is complete.
            router = sync_router(Arc::clone(&current), router);
        }
        // The bridge's client-facing methods, over the sync runtime's connection when there
        // is one. Like `sync_router`, under the application's own methods.
        let link = match &sync {
            Some(runtime) => relay::BridgeLink::Sync(Arc::clone(runtime)),
            None => relay::BridgeLink::own(
                bridge_connector
                    .unwrap_or_else(|| BridgeConnector::standard(ctx.app_name, version)),
            ),
        };
        let relay = Arc::new(relay::Relay::new(link));
        router = Arc::clone(&relay).routes(router);
        // `config.*`: this server's settings merged with the bridge's. Without settings of
        // its own, the bridge's alone, relayed.
        router = match settings {
            Some(settings) => config_methods::routes(router, settings, relay),
            None => relay.routes_for(router, sapphire_bridge_api::ANSWERED_BY_APP_SERVER),
        };
        // `server.info` answers the typed [`StatusReport`] — the same shape the CLI's
        // `status` renders — so the CLI and a future GUI read one record. The rows come
        // from the application's builder, called once per report.
        router = router
            .method(proto::SERVER_INFO, {
                let info = info.clone();
                let status_rows = status_rows.clone();
                move |_| {
                    let info = info.clone();
                    let status_rows = status_rows.clone();
                    async move {
                        let app = status_rows.as_ref().map(|rows| rows()).unwrap_or_default();
                        let report = StatusReport {
                            running: true,
                            version: Some(info.version),
                            pid: Some(info.pid),
                            managed_by: Some(match info.managed_by {
                                ManagedBy::Service => proto::ManagedBy::Service,
                                ManagedBy::Spawned => proto::ManagedBy::Spawned,
                            }),
                            app,
                        };
                        serde_json::to_value(report)
                            .map_err(|e| sapphire_ipc::RpcError::internal(e.to_string()))
                    }
                }
            })
            .method(proto::SERVER_UPDATE, {
                let update_status = Arc::clone(&update_status);
                move |_| {
                    let status = update_status.lock().expect("update status lock").clone();
                    async move {
                        serde_json::to_value(status)
                            .map_err(|e| sapphire_ipc::RpcError::internal(e.to_string()))
                    }
                }
            })
            .method(proto::SERVER_RESTART, {
                let restart = restart.clone();
                move |_| {
                    let answer = restart::request(restart.clone());
                    async move {
                        answer?;
                        serde_json::to_value(proto::Ack {})
                            .map_err(|e| sapphire_ipc::RpcError::internal(e.to_string()))
                    }
                }
            })
            .method(sapphire_ipc::SHUTDOWN_METHOD, {
                let stop_tx = stop_tx.clone();
                move |_| {
                    let stop_tx = stop_tx.clone();
                    async move {
                        let _ = stop_tx.send(true);
                        serde_json::to_value(proto::Ack {})
                            .map_err(|e| sapphire_ipc::RpcError::internal(e.to_string()))
                    }
                }
            });
        if let Some(extend) = extend {
            router = extend(router);
        }
        let router = Arc::new(router);

        // The caller's SIGTERM stream, unless this server leaves signals to the process.
        let mut no_sigterm = None;
        let sigterm = if signals { sigterm } else { &mut no_sigterm };
        // What `server.restart` fires; never, where there is no restarting.
        let restarted = async {
            match &restart {
                Some(restart) => restart.notified().await,
                None => std::future::pending().await,
            }
        };
        tokio::pin!(restarted);
        let mut exit = Exit::Stopped;

        let mut connections = tokio::task::JoinSet::new();

        // The HTTP listener, when anything is served over it. Started with the IPC socket
        // bound, for the same reason as the sync tasks below. `/mcp`'s tools reach this
        // server the way the `mcp` subcommand's do — over IPC — on an in-process connection
        // served like any other. `/metrics` is the one public route, served without a token.
        #[cfg(feature = "http")]
        let http_stop = tokio_util::sync::CancellationToken::new();
        #[cfg(feature = "http")]
        let http_task = {
            #[cfg(feature = "mcp")]
            let routes = if config.http.mcp.enabled {
                let (ours, theirs) = sapphire_ipc::Connection::pair();
                {
                    let router = Arc::clone(&router);
                    let info = info.clone();
                    let app = ctx.app_name;
                    connections.spawn(async move {
                        let _ = serve(theirs, router, app, info).await;
                    });
                }
                let client_info = sapphire_ipc::ClientInfo {
                    kind: sapphire_framework_mcp::CLIENT_KIND.to_owned(),
                    version: version.to_owned(),
                    api: proto::API_VERSION,
                    app_api,
                    pid: std::process::id(),
                };
                let (client, _) =
                    sapphire_ipc::Client::handshake(ours, ctx.app_name, client_info).await?;
                let tools = sapphire_framework_mcp::ToolContext::connected(
                    ctx.app_name,
                    version,
                    Arc::new(client),
                );
                let mcp_routes =
                    mcp.http_router(tools, &config.http.allowed_hosts, http_stop.child_token());
                Some(match http_routes {
                    Some(routes) => routes.merge(mcp_routes),
                    None => mcp_routes,
                })
            } else {
                http_routes
            };
            #[cfg(not(feature = "mcp"))]
            let routes = http_routes;
            #[cfg(feature = "metrics")]
            let public = if config.http.metrics.enabled
                && let Some(handle) = exporter::install()
            {
                metrics::gauge!(
                    instrument::BUILD_INFO,
                    "app" => ctx.app_name,
                    "version" => version,
                )
                .set(1.0);
                let scrape = Arc::new(exporter::Scrape {
                    process: metrics_process::Collector::default(),
                    current: Arc::clone(&current),
                    update: Arc::clone(&update_status),
                    collectors: metrics_collectors,
                });
                Some(exporter::routes(handle, scrape))
            } else {
                None
            };
            #[cfg(not(feature = "metrics"))]
            let public: Option<axum::Router> = None;
            match (
                routes.is_some() || public.is_some(),
                config.http.listen.or(http_listen),
            ) {
                (false, _) => None,
                (true, None) => {
                    tracing::error!(
                        "nothing to bind HTTP to: set `[http] listen` in {SERVER_CONFIG_FILE}"
                    );
                    None
                }
                (true, Some(addr)) => {
                    let auth = http_auth.unwrap_or_else(|| {
                        sapphire_framework_keys::AuthConfig::new(Arc::new(
                            api_keys::WorkspaceKeyVerifier::for_app(ctx)
                                .profiles(key_profiles.clone()),
                        ))
                    });
                    http::start(addr, routes, public, auth, http_stop.clone()).await
                }
            }
        };

        // The watcher, the bridge announcement loop, the dialer and the bridge connection, if
        // sync is on. Started only once the socket is bound, so an early `?` above cannot
        // leave tasks running for a server that never served. All of them are allowed to
        // fail: only sync stops when they do, and the app server keeps serving files
        // (spec §10). They are aborted with the server.
        let sync_tasks = match &sync {
            Some(runtime) => {
                let driver = Arc::clone(runtime);
                let announcements = tokio::spawn(async move {
                    if let Err(err) = driver.run().await {
                        tracing::warn!("the bridge announcement loop ended: {err}");
                    }
                });
                let changing = Arc::clone(runtime);
                let watching = tokio::spawn(async move {
                    if let Err(err) = changing.watch_changes().await {
                        tracing::warn!("the file watcher ended: {err}");
                    }
                });
                // The dialer is what keeps a session open after the initial exchange, so a
                // commit reaches a peer without waiting for the next one (spec §4.2).
                let dialling = Arc::clone(runtime);
                let dialling = tokio::spawn(async move {
                    if let Err(err) = dialling.dial_loop().await {
                        tracing::warn!("the live dial loop ended: {err}");
                    }
                });
                // Reaching the bridge again whenever it is lost (#244).
                let connected = tokio::spawn(Arc::clone(runtime).keep_connected());
                Some([announcements, watching, dialling, connected])
            }
            None => None,
        };

        // Looking for newer releases, once the socket is bound for the same reason. Ends
        // with the server, when this is dropped.
        let _update_checking = update_check.and_then(|check| {
            update::start(check, ctx.app_name, version, Arc::clone(&update_status))
        });

        loop {
            tokio::select! {
                changed = stop_rx.changed() => {
                    if changed.is_err() || *stop_rx.borrow() {
                        break;
                    }
                }
                _ = interrupted(signals) => {
                    tracing::info!("interrupted; shutting down");
                    break;
                }
                _ = terminated(sigterm) => {
                    tracing::info!("terminated; shutting down");
                    break;
                }
                () = &mut restarted => {
                    tracing::info!("stopping to restart");
                    exit = Exit::Restart;
                    break;
                }
                accepted = listener.accept() => {
                    let conn = accepted?;
                    // Moved into the task, so the connection stops counting as open when it
                    // ends, or when the reaping below aborts it.
                    let counted = instrument::IpcConnection::open();
                    let router = Arc::clone(&router);
                    let app = ctx.app_name;
                    let info = info.clone();
                    connections.spawn(async move {
                        let _counted = counted;
                        let _ = serve(conn, router, app, info).await;
                    });
                }
            }
        }

        // Awaited, not only aborted: the restoring task holds `Current`, and with it the
        // sync runtime, until it is dropped — which a restart must see done before the
        // next server opens the replica store.
        if let Some(restoring) = restoring {
            restoring.abort();
            let _ = restoring.await;
        }
        // HTTP first: its sessions hold a connection to this server, which the reaping
        // below waits for. Awaited after the abort too, for the same reason as above.
        #[cfg(feature = "http")]
        {
            http_stop.cancel();
            if let Some((_, mut task)) = http_task
                && tokio::time::timeout(SERVE_GRACE, &mut task).await.is_err()
            {
                tracing::debug!("the HTTP listener did not stop in time");
                task.abort();
                let _ = task.await;
            }
        }
        if let Some(tasks) = sync_tasks {
            // Each loop pins the sync runtime, and with it the replica stores. An aborted task
            // is only dropped once its current poll returns — which, mid-scan, can take a
            // while — so wait for that rather than return with a loop still holding a store
            // the next server in this process would fail to open (#235).
            for task in tasks {
                task.abort();
                let _ = task.await;
            }
        }
        if let Some(runtime) = &sync {
            // The first dials after an enable pin the runtime the same way, and so do the
            // inbound sessions, the live-session readers and the embedding passes.
            runtime.stop_dials().await;
            runtime.stop_background().await;
            // Close every live sync session. A session's reader task holds the replica, and
            // the session itself sits in the runtime's table until it is cleared, so leaving
            // one open pins the runtime — and the redb replica stores in it — after the
            // server is gone (spec §2.2: cancellation is disconnection).
            runtime.drop_connections().await;
        }
        host.close();
        // The listener is the caller's: it stays bound, and a client that connects now waits
        // in its backlog for the next server of a restart.

        // Reap the per-connection serve tasks. Each one pins the router, the router pins
        // the sync runtime, and the runtime's replica stores are redb databases that stay
        // locked until the last pin is dropped — a server that left them running would
        // lock its own successor out of its state (spec §2.2: cancellation is
        // disconnection). Connections get a grace period to wind down on their own — the
        // shutdown acknowledgement among them — then the rest are cancelled: a client
        // that keeps its connection open past shutdown is holding a server that is gone.
        let _ = tokio::time::timeout(SERVE_GRACE, async {
            while connections.join_next().await.is_some() {}
        })
        .await;
        connections.abort_all();
        while connections.join_next().await.is_some() {}
        // Everything else of this server — the router, the relay, `Current`, the host and
        // the sync runtime — goes as this returns, before a restart builds the next one.
        Ok(exit)
    }
}

/// An error for the first of `endpoints` the settings do not declare: it has no switch to
/// turn it on.
#[cfg(feature = "http")]
fn undeclared_endpoints(
    settings: Option<&Settings>,
    endpoints: &[(String, axum::Router)],
) -> Result<()> {
    let Some(settings) = settings else {
        return Ok(());
    };
    match endpoints.iter().find(|(name, _)| {
        settings
            .registry()
            .def(&settings::endpoint_key(name))
            .is_err()
    }) {
        Some((name, _)) => Err(Error::Config(format!(
            "the HTTP endpoint `{name}` is not one the application's settings declare"
        ))),
        None => Ok(()),
    }
}

/// The app server's service for `app_name` at `version`: what [`AppServer::service_spec`]
/// returns, for a desktop package to name its service without an `AppServer` (#357).
///
/// `["serve"]`, under the label sapphire first registered on macOS; corundum retires its own
/// earlier one (net.sapphire-turtle.<app>) by itself (#385).
pub fn app_service_spec(app_name: &'static str, version: &str) -> ServiceSpec {
    ServiceSpec {
        app_name,
        description: format!("{app_name} server {version}"),
        args: vec!["serve".to_owned()],
        legacy_labels: vec![format!("net.fireturtle.sapphire.{app_name}")],
        post_install: None,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use sapphire_ipc::{ClientInfo, Endpoint, ManagedBy};
    use sapphire_workspace::{AppContext, AppKind};
    use std::ffi::OsString;

    use crate::test_support;

    static CTX: AppContext = AppContext::new("sapphire-appservertest");

    /// The env vars `init_ctx` writes, in the order the guard restores them.
    const DIR_VARS: [&str; 3] = [
        "SAPPHIRE_APPSERVERTEST_CACHE_DIR",
        "SAPPHIRE_APPSERVERTEST_DATA_DIR",
        "SAPPHIRE_APPSERVERTEST_CONFIG_DIR",
    ];

    fn client_info() -> ClientInfo {
        ClientInfo {
            kind: "test".into(),
            version: "0.0.0".into(),
            api: sapphire_backend::protocol::API_VERSION,
            app_api: None,
            pid: std::process::id(),
        }
    }

    /// Point the context's directories at `tmp` and restore the previous values (present
    /// or absent) when dropped — including while unwinding from a panic. Without the
    /// unconditional restore, a panicking assertion would leave the variables pointing at
    /// a temp directory the test then deletes, and the context of a later test would
    /// resolve into the void.
    struct EnvGuard {
        previous: [Option<OsString>; 3],
        _lock: std::sync::MutexGuard<'static, ()>,
    }

    impl EnvGuard {
        /// Write the three directory vars while holding the environment lock.
        fn set(lock: std::sync::MutexGuard<'static, ()>, tmp: &std::path::Path) -> EnvGuard {
            let previous = DIR_VARS.map(std::env::var_os);
            let dirs = ["cache", "data", "config"].map(|cat| tmp.join(cat));
            // SAFETY (via `test_support::set`): `lock` serialises every read and write of
            // the process environment in this test binary — the `host`, `handlers` and
            // `events` modules' tests share the same lock — and it is held until `drop`
            // has restored the old values.
            for (name, dir) in DIR_VARS.iter().zip(dirs) {
                test_support::set(name, &dir);
            }
            EnvGuard {
                previous,
                _lock: lock,
            }
        }
    }

    impl Drop for EnvGuard {
        fn drop(&mut self) {
            // SAFETY: `self._lock` still serialises the environment; it is dropped only
            // after this method returns.
            for (name, previous) in DIR_VARS.iter().zip(self.previous.iter_mut()) {
                match previous.take() {
                    Some(value) => unsafe { std::env::set_var(name, value) },
                    None => test_support::remove(name),
                }
            }
        }
    }

    /// Everything one test needs, held for the test's whole body.
    ///
    /// `_tmp` is declared before `_env` so the scratch tree is deleted while the
    /// environment lock is still held: a sibling test that wakes on the lock must never
    /// observe the tree mid-deletion, nor env vars pointing at a deleted directory.
    struct Fixture {
        _tmp: tempfile::TempDir,
        _env: EnvGuard,
        endpoint: Endpoint,
    }

    /// A listening endpoint in a scratch directory, with the context's directories
    /// pointed at the same scratch tree.
    ///
    /// The caller must keep the fixture (and with it the environment lock) alive for the
    /// whole test: the static [`CTX`] is first-writer-wins, so while one test runs, every
    /// other test that would re-point the context's directories must wait.
    fn prepared() -> Fixture {
        let lock = test_support::lock();
        let tmp = tempfile::tempdir().unwrap();
        let env = EnvGuard::set(lock, tmp.path());
        CTX.init(AppKind::Server);
        let endpoint = Endpoint::in_dir("sapphire-appservertest", tmp.path().to_path_buf());
        Fixture {
            _tmp: tmp,
            _env: env,
            endpoint,
        }
    }

    /// Wait until something is listening on `endpoint`.
    ///
    /// `tokio::spawn(server.run())` only schedules the server; without this wait a fast
    /// `connect_or_absent` probe can run before `run` has bound the socket, and with
    /// nothing listening that single unlucky probe is the whole test failing.
    async fn wait_until_listening(endpoint: &Endpoint) {
        let deadline = tokio::time::Instant::now() + Duration::from_secs(5);
        while !sapphire_ipc::probe(endpoint).await.unwrap() {
            assert!(
                tokio::time::Instant::now() < deadline,
                "the server never started listening"
            );
            tokio::time::sleep(Duration::from_millis(10)).await;
        }
    }

    /// A running server writes its log file: the framework's `logging` module
    /// routes the app's log to `<data dir>/logs/app.log`, and `run()` holds the
    /// guard for as long as it serves. The event is emitted by this test — the
    /// subscriber and the file layer are the process's, installed by `CTX.init`
    /// and `run` — so what lands in the file is exactly what a journald-less
    /// host would otherwise never see.
    #[test]
    fn the_runtime_sync_via_bridge_mounts_is_the_applications_to_read() {
        // #250: an application reads sync state (status rows, placement) from the
        // runtime `sync_via_bridge` built, rather than building its own to keep one.
        assert!(AppServer::new(&CTX, "0.0.0").sync_runtime().is_none());
        let server = AppServer::new(&CTX, "0.0.0").sync_via_bridge().unwrap();
        let runtime = server.sync_runtime().expect("a runtime");
        assert!(!runtime.is_connected(), "nothing connects before `run`");
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn a_running_server_writes_its_log_file() {
        let f = prepared();
        let endpoint = f.endpoint.clone();
        let server = AppServer::new(&CTX, "0.0.0").endpoint(endpoint.clone());
        let handle = tokio::spawn(async move { server.run().await });
        wait_until_listening(&endpoint).await;

        tracing::info!("the server is serving, and this line belongs in its log");

        let (client, _) = sapphire_ipc::connect_or_absent(&endpoint, CTX.app_name, client_info())
            .await
            .unwrap()
            .expect("the server is listening");
        let _: serde_json::Value = client
            .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
            .await
            .unwrap();
        // The guard flushes as `run` unwinds; awaiting it is what makes the
        // file complete before it is read.
        handle.await.unwrap().unwrap();

        let text = std::fs::read_to_string(CTX.log_dir().join("app.log")).unwrap();
        assert!(
            text.contains("the server is serving, and this line belongs in its log"),
            "{text}"
        );
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn a_server_reports_itself_as_service_managed() {
        let f = prepared();
        let endpoint = f.endpoint.clone();
        let server = AppServer::new(&CTX, "0.0.0").endpoint(endpoint.clone());
        let handle = tokio::spawn(async move { server.run().await });
        wait_until_listening(&endpoint).await;

        let (client, info) =
            sapphire_ipc::connect_or_absent(&endpoint, CTX.app_name, client_info())
                .await
                .unwrap()
                .expect("the server is listening");
        assert_eq!(info.managed_by, ManagedBy::Service);

        let _: serde_json::Value = client
            .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
            .await
            .unwrap();
        handle.await.unwrap().unwrap();
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn a_server_reports_its_app_api_and_the_handshake_gates_on_it() {
        let f = prepared();
        let endpoint = f.endpoint.clone();
        let server = AppServer::new(&CTX, "0.0.0")
            .endpoint(endpoint.clone())
            .app_api(7);
        let handle = tokio::spawn(async move { server.run().await });
        wait_until_listening(&endpoint).await;

        let wants = |app_api| ClientInfo {
            app_api,
            ..client_info()
        };
        let err = sapphire_ipc::connect_or_absent(&endpoint, CTX.app_name, wants(Some(8)))
            .await
            .unwrap_err();
        assert!(
            matches!(
                err,
                sapphire_ipc::Error::AppApiVersionMismatch {
                    running: Some(7),
                    ours: 8,
                    ..
                }
            ),
            "{err:?}"
        );

        let (client, info) =
            sapphire_ipc::connect_or_absent(&endpoint, CTX.app_name, wants(Some(7)))
                .await
                .unwrap()
                .expect("the server is listening");
        assert_eq!(info.app_api, Some(7));

        let _: serde_json::Value = client
            .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
            .await
            .unwrap();
        handle.await.unwrap().unwrap();
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn a_running_server_answers_server_info() {
        let f = prepared();
        let endpoint = f.endpoint.clone();

        let server = AppServer::new(&CTX, "1.2.3").endpoint(endpoint.clone());
        let handle = tokio::spawn(async move { server.run().await });
        wait_until_listening(&endpoint).await;

        let (client, info) = sapphire_ipc::connect_or_absent(
            &endpoint,
            CTX.app_name,
            ClientInfo {
                version: "1.2.3".into(),
                ..client_info()
            },
        )
        .await
        .unwrap()
        .expect("the server is listening");
        assert_eq!(info.version, "1.2.3");

        // `server.info` answers the whole typed report, not the bare handshake record:
        // the CLI reads one shape, and so would a GUI.
        let report: StatusReport = client
            .call(
                sapphire_backend::protocol::SERVER_INFO,
                serde_json::json!({}),
            )
            .await
            .unwrap();
        assert!(report.running);
        assert_eq!(report.version.as_deref(), Some("1.2.3"));
        assert_eq!(report.pid, Some(std::process::id()));
        assert_eq!(report.managed_by, Some(proto::ManagedBy::Service));
        assert!(report.app.is_empty(), "no status rows were configured");

        let _: serde_json::Value = client
            .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
            .await
            .unwrap();
        handle.await.unwrap().unwrap();
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn shutdown_stops_the_server() {
        let f = prepared();
        let endpoint = f.endpoint.clone();

        let server = AppServer::new(&CTX, "0.0.0").endpoint(endpoint.clone());
        let handle = tokio::spawn(async move { server.run().await });
        wait_until_listening(&endpoint).await;

        let (client, _) = sapphire_ipc::connect_or_absent(&endpoint, CTX.app_name, client_info())
            .await
            .unwrap()
            .expect("the server is listening");
        let _: serde_json::Value = client
            .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
            .await
            .unwrap();

        tokio::time::timeout(Duration::from_secs(5), handle)
            .await
            .expect("the server must stop")
            .unwrap()
            .unwrap();
        assert!(!sapphire_ipc::probe(&endpoint).await.unwrap());
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn an_application_can_add_its_own_methods() {
        let f = prepared();
        let endpoint = f.endpoint.clone();

        let server = AppServer::new(&CTX, "0.0.0")
            .endpoint(endpoint.clone())
            .extend(|r| {
                r.method("sapphire-appservertest.greet", |_| async move {
                    Ok(serde_json::json!("hello"))
                })
            });
        let handle = tokio::spawn(async move { server.run().await });
        wait_until_listening(&endpoint).await;

        let (client, _) = sapphire_ipc::connect_or_absent(&endpoint, CTX.app_name, client_info())
            .await
            .unwrap()
            .expect("the server is listening");
        let greeting: String = client
            .call("sapphire-appservertest.greet", serde_json::json!({}))
            .await
            .unwrap();
        assert_eq!(greeting, "hello");

        let _: serde_json::Value = client
            .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
            .await
            .unwrap();
        handle.await.unwrap().unwrap();
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn workspace_init_creates_the_marker() {
        let f = prepared();
        let endpoint = f.endpoint.clone();
        let server = AppServer::new(&CTX, "0.0.0").endpoint(endpoint.clone());
        let handle = tokio::spawn(async move { server.run().await });
        wait_until_listening(&endpoint).await;
        let (client, _) = sapphire_ipc::connect_or_absent(&endpoint, CTX.app_name, client_info())
            .await
            .unwrap()
            .unwrap();

        let dir = tempfile::tempdir().unwrap();
        let result: proto::WorkspaceInitResult = client
            .call(
                proto::WORKSPACE_INIT,
                proto::WorkspaceInitParams {
                    dir: dir.path().to_owned(),
                },
            )
            .await
            .unwrap();
        assert!(result.created);
        assert!(dir.path().join(format!(".{}", CTX.app_name)).is_dir());

        // Idempotent: the second init is a success that did not create.
        let again: proto::WorkspaceInitResult = client
            .call(
                proto::WORKSPACE_INIT,
                proto::WorkspaceInitParams {
                    dir: dir.path().to_owned(),
                },
            )
            .await
            .unwrap();
        assert!(!again.created);

        let _: serde_json::Value = client
            .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
            .await
            .unwrap();
        handle.await.unwrap().unwrap();
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn server_info_carries_the_app_rows() {
        let f = prepared();
        let endpoint = f.endpoint.clone();
        let server = AppServer::new(&CTX, "0.0.0")
            .endpoint(endpoint.clone())
            .status_rows(std::sync::Arc::new(|| {
                vec![StatusRow {
                    name: "sync".into(),
                    value: "enabled".into(),
                }]
            }));
        let handle = tokio::spawn(async move { server.run().await });
        wait_until_listening(&endpoint).await;
        let (client, _) = sapphire_ipc::connect_or_absent(&endpoint, CTX.app_name, client_info())
            .await
            .unwrap()
            .unwrap();
        let report: StatusReport = client
            .call(
                sapphire_backend::protocol::SERVER_INFO,
                serde_json::json!({}),
            )
            .await
            .unwrap();
        assert!(report.running);
        assert_eq!(report.app.len(), 1);
        assert_eq!(report.app[0].name, "sync");

        let _: serde_json::Value = client
            .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
            .await
            .unwrap();
        handle.await.unwrap().unwrap();
    }
}