sapphire-framework-server 0.19.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
//! The framework-provided half of an application's CLI.

use std::fmt::Write as _;
use std::path::PathBuf;

use sapphire_backend::protocol as proto;
use sapphire_bridge_api::{
    DevicePrioritySetParams, DeviceRetireParams, InviteParams, JoinParams, WorkgroupCreateParams,
};
use sapphire_bridge_client::BridgeClient;
use sapphire_framework_service::{Environment, ServiceCommand, SystemManager};
use sapphire_ipc::{ClientInfo, Endpoint};

use crate::AppServer;
use crate::error::{Error, Result};

pub use sapphire_backend::protocol::{StatusReport, StatusRow};

/// The framework's commands, flattened into an application's CLI (spec decision 2).
///
/// An application composes these beside its own verbs by giving its subcommand enum a
/// `#[command(flatten)] Framework(FrameworkCommand)` variant, so every verb — the app's and
/// the framework's — sits at the same top level. The parse tests below pin that shape.
#[derive(Debug, Default, clap::Subcommand)]
pub enum FrameworkCommand {
    /// Run the server in this process until SIGTERM or SIGINT (the bare invocation).
    #[default]
    Serve,
    /// Report whether a server is running, and which version.
    Status,
    /// Install, remove or report this application's operating-system service.
    #[command(subcommand)]
    Service(ServiceCommand),
    /// Create, select, show and map this application's workspace. The server serves one
    /// at a time.
    #[command(subcommand)]
    Workspace(WorkspaceCommand),
    /// Found, show or join the workgroup this device belongs to.
    #[command(subcommand)]
    Workgroup(WorkgroupCommand),
    /// List the workgroup's devices, invite one or retire one.
    #[command(subcommand)]
    Device(DeviceCommand),
    /// Show or change the embedding models (the workgroup's local and remote one), this
    /// device's switches, and its API key. Needs the running bridge.
    #[command(subcommand)]
    Embedding(sapphire_bridge_api::EmbeddingCommand),
    /// Add, list, retire, restore and rotate the workgroup's external devices — clients
    /// that reach this application with a key. `add` allows this application unless told
    /// otherwise. Needs the running bridge.
    #[command(subcommand)]
    ExternalDevice(sapphire_bridge_api::ExternalDeviceCommand),
    /// Serve this application's tools to an AI agent over MCP on stdin/stdout. Talks to the
    /// running server, which it does not start; register this command with the agent.
    #[cfg(feature = "mcp")]
    Mcp,
}

impl FrameworkCommand {
    /// Carry out the command, returning the process exit code.
    ///
    /// The application matches its own variants first, then hands the framework's here;
    /// the app name and the service spec come from `server` itself.
    pub async fn dispatch(self, server: AppServer, version: &'static str) -> Result<i32> {
        match self {
            FrameworkCommand::Serve => {
                server.run().await?;
                Ok(0)
            }
            FrameworkCommand::Status => crate::command::status(&server, version).await,
            FrameworkCommand::Service(command) => {
                let spec = server.service_spec();
                command
                    .run(&spec, &Environment::detect(), &SystemManager)
                    .map_err(Error::from)
            }
            FrameworkCommand::Workspace(command) => {
                command.dispatch(server.app_name(), version).await
            }
            FrameworkCommand::Workgroup(command) => command.dispatch(version).await,
            FrameworkCommand::Device(command) => command.dispatch(version).await,
            FrameworkCommand::Embedding(command) => embedding(command, version).await,
            FrameworkCommand::ExternalDevice(command) => {
                external_device(command, server.app_name(), version).await
            }
            #[cfg(feature = "mcp")]
            FrameworkCommand::Mcp => {
                server.serve_mcp_stdio(version).await?;
                Ok(0)
            }
        }
    }
}

/// The `workspace` subcommands (#215: one workspace per server).
///
/// `init`, `select`, `sync`, `move`, `remove` and `map`'s write go to the app's server over IPC,
/// because the server owns the marker directories, the sync ids and which workspace it
/// serves; `show` asks the server for its workspace and then the bridge for the workgroup's
/// ledger; `map`'s selector resolution is the workgroup's word, so it goes to the bridge
/// first. These are the only verbs that take a path: everything else acts on the server's
/// workspace.
#[derive(Debug, clap::Subcommand)]
pub enum WorkspaceCommand {
    /// Create this app's workspace home in the given directory, and switch the server to it.
    Init {
        /// Where the workspace root goes. Defaults to the current directory.
        dir: Option<PathBuf>,
        /// Also start syncing it, which publishes it into the workgroup ledger.
        #[arg(long)]
        sync: bool,
    },
    /// Switch the server to an existing workspace of this app.
    Select {
        /// The workspace's root. Defaults to the current directory.
        dir: Option<PathBuf>,
        /// Also start syncing it, which publishes it into the workgroup ledger. A
        /// workspace that has synced before turns sync back on by itself.
        #[arg(long)]
        sync: bool,
    },
    /// Turn sync on or off for the server's workspace, or show its sync state.
    #[command(subcommand)]
    Sync(WorkspaceSyncCommand),
    /// Show the server's workspace, then the workgroup's workspaces of this app.
    Show,
    /// Move the server's workspace folder to a new path on this host, keeping its sync.
    Move {
        /// The new root. It must not exist yet; its parent must.
        dir: PathBuf,
    },
    /// Stop serving the server's workspace on this host. Other devices keep their copies.
    Remove {
        /// Also delete the workspace's folder and every file in it.
        #[arg(long)]
        delete: bool,
    },
    /// Bring a workspace the workgroup knows to a local directory, and switch to it.
    Map {
        /// The workspace, by name or id, as the workgroup lists it.
        selector: String,
        /// The local directory to map it to. Defaults to the current one.
        dir: Option<PathBuf>,
    },
}

impl WorkspaceCommand {
    /// Carry out the command, returning the process exit code.
    ///
    /// `app` names the endpoint to open (`Endpoint::for_app`); `version` is this
    /// process's own, for the handshake.
    pub async fn dispatch(self, app: &'static str, version: &'static str) -> Result<i32> {
        match self {
            WorkspaceCommand::Init { dir, sync } => workspace_init(app, version, dir, sync).await,
            WorkspaceCommand::Select { dir, sync } => {
                workspace_select(app, version, dir, sync).await
            }
            WorkspaceCommand::Sync(command) => workspace_sync(app, version, command).await,
            WorkspaceCommand::Show => workspace_show(app, version).await,
            WorkspaceCommand::Move { dir } => workspace_move(app, version, dir).await,
            WorkspaceCommand::Remove { delete } => workspace_remove(app, version, delete).await,
            WorkspaceCommand::Map { selector, dir } => {
                workspace_map(app, version, &selector, dir).await
            }
        }
    }
}

/// The `workspace sync` subcommands: the server's workspace's sync, switched after the fact.
#[derive(Debug, clap::Subcommand)]
pub enum WorkspaceSyncCommand {
    /// Start syncing the server's workspace, which publishes it into the workgroup ledger.
    Enable,
    /// Stop syncing the server's workspace on this host. It keeps its sync id, so enabling
    /// it again picks up where it left off; other devices keep their copies.
    Disable,
    /// Show the server's workspace's sync state.
    Status,
}

/// The `workgroup` subcommands.
///
/// The workgroup's ledger is the bridge's business end to end, so these go to the bridge's
/// endpoint directly, including `create`, which goes through the running bridge.
#[derive(Debug, clap::Subcommand)]
pub enum WorkgroupCommand {
    /// Found a workgroup on this host.
    Create {
        /// The workgroup's name.
        name: String,
        /// This host's device name inside it.
        #[arg(long)]
        device_name: String,
    },
    /// Show the workgroup this host belongs to.
    List,
    /// Join the workgroup a ticket names.
    Join {
        /// The ticket the inviting device printed.
        ticket: String,
        /// The name this device will carry. Defaults to this host's name.
        #[arg(long)]
        device_name: Option<String>,
    },
}

impl WorkgroupCommand {
    /// Carry out the command, returning the process exit code.
    pub async fn dispatch(self, version: &'static str) -> Result<i32> {
        match self {
            WorkgroupCommand::Create { name, device_name } => {
                let client = connect_running(version).await?;
                let created = client
                    .workgroup_create(WorkgroupCreateParams { name, device_name })
                    .await?;
                println!(
                    "created workgroup {} ({}); this device is {}",
                    created.name, created.workgroup_id, created.device_id
                );
                Ok(0)
            }
            WorkgroupCommand::List => {
                let client = connect_running(version).await?;
                match client.status().await?.workgroup {
                    Some(workgroup) => {
                        println!("{} ({})", workgroup.name, workgroup.workgroup_id);
                        Ok(0)
                    }
                    None => {
                        println!("this host has not joined a workgroup");
                        Ok(1)
                    }
                }
            }
            WorkgroupCommand::Join {
                ticket,
                device_name,
            } => {
                let client = connect_running(version).await?;
                let joined = client
                    .join(JoinParams {
                        ticket,
                        device_name,
                    })
                    .await?;
                println!(
                    "joined workgroup {} ({}); this device is {}",
                    joined.workgroup_name, joined.workgroup_id, joined.device_id
                );
                Ok(0)
            }
        }
    }
}

/// The `device` subcommands.
///
/// The ledger's word for taking a device out is `retire` — a device id is written into
/// synced content and must keep resolving, so its record stays as a tombstone — and this
/// command goes through the running bridge to retire a device.
#[derive(Debug, clap::Subcommand)]
pub enum DeviceCommand {
    /// List the workgroup's devices, and which are reachable.
    List,
    /// Create an invite ticket for a device that is about to join.
    Invite {
        /// What the joining device will be called.
        #[arg(long)]
        name: String,
        /// How long the invite stays good, in seconds.
        #[arg(long)]
        ttl: Option<u64>,
        /// The workgroup to invite into, by name or id.
        #[arg(long)]
        workgroup: Option<String>,
    },
    /// Retire a device, so it may no longer connect.
    Retire {
        /// The device's name or id.
        selector: String,
    },
    /// Show or set a device's election priority (0-255; 0 = never primary or secondary).
    /// The election is non-preemptive: raising a priority does not move a role already held.
    Priority {
        /// The device's name or id.
        selector: String,
        /// The new priority. Omit to show the current one.
        priority: Option<u8>,
    },
}

impl DeviceCommand {
    /// Carry out the command, returning the process exit code.
    pub async fn dispatch(self, version: &'static str) -> Result<i32> {
        match self {
            DeviceCommand::List => {
                let client = connect_running(version).await?;
                let peers = client.peers().await?;
                if peers.peers.is_empty() {
                    println!("no devices");
                    return Ok(0);
                }
                for peer in peers.peers {
                    println!(
                        "{} {} p{}{}{}",
                        peer.name,
                        peer.device_id,
                        peer.priority,
                        peer.availability
                            .map(|a| format!(" a{a}"))
                            .unwrap_or_default(),
                        if peer.connected { " (online)" } else { "" }
                    );
                }
                Ok(0)
            }
            DeviceCommand::Invite {
                name,
                ttl,
                workgroup,
            } => {
                let client = connect_running(version).await?;
                let invite = client
                    .invite(InviteParams {
                        name,
                        ttl,
                        workgroup,
                    })
                    .await?;
                // The ticket on its own line, and nothing else on it: this is the one
                // output a user pipes to the joining device.
                println!("{}", invite.ticket);
                Ok(0)
            }
            DeviceCommand::Retire { selector } => {
                let client = connect_running(version).await?;
                let retired = client
                    .device_retire(DeviceRetireParams { selector })
                    .await?;
                println!("retired device {} ({})", retired.name, retired.device_id);
                Ok(0)
            }
            DeviceCommand::Priority { selector, priority } => {
                let client = connect_running(version).await?;
                match priority {
                    Some(priority) => {
                        let set = client
                            .device_priority_set(DevicePrioritySetParams { selector, priority })
                            .await?;
                        println!("{} ({}) priority {}", set.name, set.device_id, set.priority);
                    }
                    None => {
                        let peers = client.peers().await?;
                        match peers
                            .peers
                            .iter()
                            .find(|p| p.name == selector || p.device_id.to_string() == selector)
                        {
                            Some(p) => {
                                println!("{} ({}) priority {}", p.name, p.device_id, p.priority)
                            }
                            None => {
                                println!("no device {selector:?}");
                                return Ok(1);
                            }
                        }
                    }
                }
                Ok(0)
            }
        }
    }
}

/// Connect to the running bridge, or fail with the message the command layer prints.
///
/// One wrapper for every arm that talks to the bridge: the error's text is what the
/// `main` prints, so the absence case reads "no sapphire-bridge is running" without each
/// arm repeating it.
async fn connect_running(version: &str) -> Result<BridgeClient> {
    BridgeClient::connect_running("cli", version)
        .await
        .map_err(Error::from)
}

/// `embedding …`: always through the running bridge, whose files these are.
async fn embedding(command: sapphire_bridge_api::EmbeddingCommand, version: &str) -> Result<i32> {
    // Connect first: `key set` asks for the key, which is pointless with no bridge to take it.
    let client = connect_running(version).await?;
    let request = command.request()?;
    let report = client.embed_request(request).await?;
    for line in sapphire_bridge_api::describe(&report) {
        println!("{line}");
    }
    Ok(0)
}

/// `external-device …`: always through the running bridge, which owns the ledger.
async fn external_device(
    command: sapphire_bridge_api::ExternalDeviceCommand,
    app: &str,
    version: &str,
) -> Result<i32> {
    let client = connect_running(version).await?;
    let outcome = client
        .external_device_request(command.request(Some(app)))
        .await?;
    for line in sapphire_bridge_api::describe_external_outcome(&outcome) {
        println!("{line}");
    }
    Ok(0)
}

/// `workspace init`: the server does the creating, over IPC.
///
/// The server owns the marker, the registry and the sync ids, so a workspace created
/// here is one the server already knows and a GUI sharing the registry sees. Nothing is
/// listening → the one line and exit 1; nothing is ever started (Global Constraints).
/// `--sync` rides the server's existing `sync.enable` path on the same connection, and
/// its state is printed after, so an unjoined host's "no workgroup knows it yet" is
/// plain.
async fn workspace_init(
    app: &'static str,
    version: &'static str,
    dir: Option<PathBuf>,
    sync: bool,
) -> Result<i32> {
    let endpoint = Endpoint::for_app(app)?;
    let client_info = ClientInfo {
        kind: "cli".to_owned(),
        version: version.to_owned(),
        api: proto::API_VERSION,
        app_api: None,
        pid: std::process::id(),
    };
    let Some((client, _)) = sapphire_ipc::connect_or_absent(&endpoint, app, client_info).await?
    else {
        println!("no {app} server is running");
        return Ok(1);
    };

    // Resolved here: the server's cwd is not the user's.
    let dir = std::env::current_dir()?.join(dir.unwrap_or_else(|| PathBuf::from(".")));
    let result: proto::WorkspaceInitResult = client
        .call(proto::WORKSPACE_INIT, proto::WorkspaceInitParams { dir })
        .await?;
    if result.created {
        println!("initialized {app} workspace in {}", result.root.display());
    } else {
        println!(
            "{} already exists (workspace {})",
            result.root.display(),
            result.workspace_id
        );
    }
    println!("the {app} server now serves {}", result.root.display());

    if sync {
        enable_sync(&client).await?;
    }
    Ok(0)
}

/// Turn sync on for the server's workspace over `client`, and print what it syncs as.
///
/// The one path behind `init --sync`, `select --sync` and `sync enable`: the server's
/// `sync.enable`, then its status, printed after, so an unjoined host's "no workgroup knows
/// it yet" is plain.
async fn enable_sync(client: &sapphire_ipc::Client) -> Result<()> {
    let enabled: proto::SyncEnableResult = client
        .call(proto::SYNC_ENABLE, serde_json::json!({}))
        .await?;
    // Never fails on account of the bridge: the workspace is synced either way, and the
    // status is the user's word for what the workgroup does not know yet.
    let status: proto::SyncStatusResult = client
        .call(proto::SYNC_STATUS, serde_json::json!({}))
        .await
        .unwrap_or(proto::SyncStatusResult {
            enabled: true,
            workspace_id: Some(enabled.workspace_id),
            ..proto::SyncStatusResult::not_synced()
        });
    println!(
        "syncing as {} ({} peer{})",
        enabled.workspace_id,
        status.peers,
        if status.peers == 1 { "" } else { "s" }
    );
    Ok(())
}

/// `workspace sync …`: the server's workspace's sync, switched after the fact.
async fn workspace_sync(
    app: &'static str,
    version: &'static str,
    command: WorkspaceSyncCommand,
) -> Result<i32> {
    let Some(client) = connect_app(app, version).await? else {
        return Ok(1);
    };
    match command {
        WorkspaceSyncCommand::Enable => enable_sync(&client).await?,
        WorkspaceSyncCommand::Disable => {
            let _: proto::Ack = client
                .call(proto::SYNC_DISABLE, serde_json::json!({}))
                .await?;
            println!("sync is off for the {app} workspace on this host; it keeps its sync id");
        }
        WorkspaceSyncCommand::Status => {
            let status: proto::SyncStatusResult = client
                .call(proto::SYNC_STATUS, serde_json::json!({}))
                .await?;
            for line in describe_sync(&status) {
                println!("{line}");
            }
        }
    }
    Ok(0)
}

/// `workspace sync status`, line by line.
fn describe_sync(status: &proto::SyncStatusResult) -> Vec<String> {
    let mut lines = vec![format!(
        "sync: {}",
        if status.enabled { "on" } else { "off" }
    )];
    if let Some(id) = status.workspace_id {
        lines.push(format!("workspace id: {id}"));
    }
    if status.enabled {
        lines.push(format!(
            "peers: {}{}",
            status.peers,
            if matches!(status.topology, proto::Topology::Star { .. }) {
                " (star)"
            } else {
                ""
            }
        ));
        lines.push(format!(
            "bridge: {}",
            if status.bridge_available {
                "reachable"
            } else {
                "not reachable"
            }
        ));
    }
    if let Some(paused) = &status.paused {
        lines.push(format!("paused: {paused}"));
    }
    if let Some(error) = &status.last_error {
        lines.push(format!("last error: {error}"));
    }
    lines
}

/// Render the server's workspace as the CLI prints it: `root state`.
///
/// Public so the integration tests can capture it; `workspace show` writes it to standard
/// output.
pub async fn render_workspace(client: &sapphire_ipc::Client, out: &mut String) -> Result<i32> {
    let current: proto::WorkspaceCurrentResult = client
        .call(proto::WORKSPACE_CURRENT, serde_json::json!({}))
        .await?;
    let Some(ws) = current.workspace else {
        writeln!(
            out,
            "no workspace yet; run `workspace init <dir>` or `workspace select <dir>`"
        )
        .expect("writing to a String cannot fail");
        return Ok(1);
    };
    writeln!(out, "{} {}", ws.root.display(), describe_state(&ws))
        .expect("writing to a String cannot fail");
    Ok(0)
}

/// `synced (star), embedding 3 pending` and the like.
fn describe_state(ws: &proto::CurrentWorkspace) -> String {
    let state = if !ws.reachable {
        "unreachable"
    } else if ws.sync.enabled {
        "synced"
    } else {
        "not synced"
    };
    let star = if matches!(ws.sync.topology, proto::Topology::Star { .. }) {
        " (star)"
    } else {
        ""
    };
    let pending = match &ws.sync.embedding {
        Some(e) if e.pending > 0 => format!(", embedding {} pending", e.pending),
        _ => String::new(),
    };
    format!("{state}{star}{pending}")
}

/// Connect to `app`'s server, or say none is running.
async fn connect_app(app: &str, version: &str) -> Result<Option<sapphire_ipc::Client>> {
    let endpoint = Endpoint::for_app(app)?;
    let client_info = ClientInfo {
        kind: "cli".to_owned(),
        version: version.to_owned(),
        api: proto::API_VERSION,
        app_api: None,
        pid: std::process::id(),
    };
    let client = sapphire_ipc::connect_or_absent(&endpoint, app, client_info).await?;
    if client.is_none() {
        println!("no {app} server is running");
    }
    Ok(client.map(|(c, _)| c))
}

/// `workspace select`: switch the server to an existing workspace, syncing it with `--sync`.
async fn workspace_select(
    app: &'static str,
    version: &'static str,
    dir: Option<PathBuf>,
    sync: bool,
) -> Result<i32> {
    let Some(client) = connect_app(app, version).await? else {
        return Ok(1);
    };
    // Resolved here: the server's cwd is not the user's.
    let dir = std::env::current_dir()?.join(dir.unwrap_or_else(|| PathBuf::from(".")));
    let ws: proto::CurrentWorkspace = client
        .call(
            proto::WORKSPACE_SELECT,
            proto::WorkspaceSelectParams { dir },
        )
        .await?;
    println!("{} {}", ws.root.display(), describe_state(&ws));
    // A workspace that has synced before is synced again by the select itself.
    if sync && !ws.sync.enabled {
        enable_sync(&client).await?;
    }
    Ok(0)
}

/// `workspace move`: move the server's workspace folder.
async fn workspace_move(app: &'static str, version: &'static str, dir: PathBuf) -> Result<i32> {
    let Some(client) = connect_app(app, version).await? else {
        return Ok(1);
    };
    // Resolved here: the server's cwd is not the user's.
    let dir = std::env::current_dir()?.join(dir);
    let ws: proto::CurrentWorkspace = client
        .call(proto::WORKSPACE_MOVE, proto::WorkspaceMoveParams { dir })
        .await?;
    println!("{} {}", ws.root.display(), describe_state(&ws));
    Ok(0)
}

/// `workspace remove`: let go of the server's workspace, deleting it with `--delete`.
async fn workspace_remove(app: &'static str, version: &'static str, delete: bool) -> Result<i32> {
    let Some(client) = connect_app(app, version).await? else {
        return Ok(1);
    };
    let _: proto::Ack = client
        .call(
            proto::WORKSPACE_REMOVE,
            proto::WorkspaceRemoveParams { delete },
        )
        .await?;
    println!(
        "{}",
        if delete {
            "removed and deleted"
        } else {
            "removed; the files stay"
        }
    );
    Ok(0)
}

/// `workspace show`: the server's workspace, then the workgroup's workspaces of this app.
///
/// The workgroup's ledger is the bridge's to answer, and the bridge being down is not the
/// server half's failure: the ledger's absence is one line, and the exit is the server
/// half's.
async fn workspace_show(app: &'static str, version: &'static str) -> Result<i32> {
    let Some(client) = connect_app(app, version).await? else {
        return Ok(1);
    };
    let mut out = String::new();
    let code = render_workspace(&client, &mut out).await?;
    for line in out.lines() {
        println!("{line}");
    }

    let Some(client) = BridgeClient::connect_running("cli", version).await.ok() else {
        println!("no sapphire-bridge is running");
        return Ok(code);
    };
    let workspaces = client.workspaces().await.map_err(Error::from)?;
    let mine: Vec<_> = workspaces
        .workspaces
        .into_iter()
        .filter(|w| w.app_name == app)
        .collect();
    if !mine.is_empty() {
        println!();
        println!("in the workgroup:");
        for workspace in mine {
            println!("{} {}", workspace.name, workspace.workspace_id);
        }
    }
    Ok(code)
}

/// `workspace map`: the bridge resolves the selector, the server takes the write.
///
/// The resolution is the workgroup's word (which workspace, by what id), the write is the
/// server's (`sync.map` places the id and starts the replica). The bridge is required —
/// without it there is nothing to resolve against, so exit 1 — and so is the server,
/// because the write and the replica are its.
async fn workspace_map(
    app: &'static str,
    version: &'static str,
    selector: &str,
    dir: Option<PathBuf>,
) -> Result<i32> {
    let Some(client) = BridgeClient::connect_running("cli", version).await.ok() else {
        println!("no sapphire-bridge is running");
        return Ok(1);
    };
    let workspaces = client.workspaces().await.map_err(Error::from)?;
    let wanted = workspaces
        .workspaces
        .iter()
        // A name is the user-facing handle; the id is the exact one.
        .find(|w| w.name == selector || w.workspace_id.to_string() == selector)
        .ok_or_else(|| Error::UnknownWorkspaceName(selector.to_owned()))?;

    let endpoint = Endpoint::for_app(app)?;
    let client_info = ClientInfo {
        kind: "cli".to_owned(),
        version: version.to_owned(),
        api: proto::API_VERSION,
        app_api: None,
        pid: std::process::id(),
    };
    let Some((client, _)) = sapphire_ipc::connect_or_absent(&endpoint, app, client_info).await?
    else {
        println!("no {app} server is running");
        return Ok(1);
    };

    let dir = std::env::current_dir()?.join(dir.unwrap_or_else(|| PathBuf::from(".")));
    let mapped: proto::SyncEnableResult = client
        .call(
            proto::SYNC_MAP,
            proto::SyncMapParams {
                workspace: wanted.workspace_id.to_string(),
                dir,
            },
        )
        .await?;
    println!(
        "mapped {} as {}; the {app} server now serves it",
        wanted.name, mapped.workspace_id
    );
    Ok(0)
}

/// The status command's face: render and return the exit code, going to the process's
/// standard output.
async fn status(server: &AppServer, version: &str) -> Result<i32> {
    let endpoint = Endpoint::for_app(server.app_name())?;
    run_status(&endpoint, server.app_name(), version).await
}

/// Probe, handshake and call `SERVER_INFO` in one go, or report absence.
///
/// Every step the CLI needs — liveness and the API gate — is inside
/// [`connect_or_absent`], so the command is that call plus one `SERVER_INFO` round trip.
/// The API gate doubles as the liveness check here: a live server of another API version
/// is `ApiVersionMismatch`, which names both API versions and advises upgrading and
/// restarting the service. The report goes through [`run_status_into`] so tests can
/// capture it.
async fn run_status(endpoint: &Endpoint, app: &str, version: &str) -> Result<i32> {
    let mut out = String::new();
    let code = run_status_into(endpoint, app, version, &mut out).await?;
    for line in out.lines() {
        println!("{line}");
    }
    Ok(code)
}

/// [`run_status`], writing the rendered lines into `out` instead of the process's
/// standard output.
async fn run_status_into(
    endpoint: &Endpoint,
    app: &str,
    version: &str,
    out: &mut String,
) -> Result<i32> {
    let client_info = ClientInfo {
        kind: "cli".to_owned(),
        version: version.to_owned(),
        api: proto::API_VERSION,
        app_api: None,
        pid: std::process::id(),
    };
    let Some((client, _)) = sapphire_ipc::connect_or_absent(endpoint, app, client_info).await?
    else {
        // Nothing is listening: the framework's half is only the one line, and the
        // application's rows are skipped (there is no server to have configured them).
        writeln!(out, "no {app} server is running").expect("writing to a String cannot fail");
        return Ok(1);
    };
    let report: StatusReport = client
        .call(
            sapphire_backend::protocol::SERVER_INFO,
            serde_json::json!({}),
        )
        .await?;
    writeln!(out, "running: {}", report.running).expect("writing to a String cannot fail");
    if let Some(version) = &report.version {
        writeln!(out, "version: {version}").expect("writing to a String cannot fail");
    }
    if let Some(pid) = report.pid {
        writeln!(out, "pid: {pid}").expect("writing to a String cannot fail");
    }
    if let Some(managed_by) = &report.managed_by {
        writeln!(out, "managed_by: {managed_by:?}").expect("writing to a String cannot fail");
    }
    for row in &report.app {
        writeln!(out, "{}: {}", row.name, row.value).expect("writing to a String cannot fail");
    }
    Ok(0)
}
#[cfg(test)]
mod tests {
    use super::*;
    use clap::Parser;

    /// The composition every app binary uses: an app-owned subcommand enum whose framework
    /// verbs ride in on a flattened variant (spec decision 2).
    ///
    /// clap 4 rejects `#[command(flatten)]` on a struct field beside a
    /// `#[command(subcommand)]` field — two subcommand enums cannot share one level, and a
    /// flattened field must implement `clap::Args`, which the `Subcommand` derive does not
    /// provide. The plan's Risks section names this probe as the decision, and the flat
    /// fallback is what it decided: one subcommand enum, every verb at the top level.
    #[derive(Parser)]
    struct Probe {
        #[command(subcommand)]
        command: Command,
    }

    #[derive(Debug, clap::Subcommand)]
    enum Command {
        /// An app-specific verb that must parse beside the framework's.
        Greet,
        #[command(flatten)]
        Framework(FrameworkCommand),
    }

    #[test]
    fn app_and_framework_commands_parse_side_by_side() {
        let probe = Probe::try_parse_from(["app", "greet"]).unwrap();
        assert!(matches!(probe.command, Command::Greet));
        let probe = Probe::try_parse_from(["app", "serve"]).unwrap();
        assert!(matches!(
            probe.command,
            Command::Framework(FrameworkCommand::Serve)
        ));
        let probe = Probe::try_parse_from(["app", "status"]).unwrap();
        assert!(matches!(
            probe.command,
            Command::Framework(FrameworkCommand::Status)
        ));
    }

    #[cfg(feature = "mcp")]
    #[test]
    fn the_mcp_command_parses_beside_the_apps() {
        let probe = Probe::try_parse_from(["app", "mcp"]).unwrap();
        assert!(matches!(
            probe.command,
            Command::Framework(FrameworkCommand::Mcp)
        ));
    }

    #[test]
    fn the_service_subcommands_parse() {
        for args in [
            vec!["app", "service", "install"],
            vec!["app", "service", "uninstall"],
            vec!["app", "service", "status"],
        ] {
            assert!(Probe::try_parse_from(&args).is_ok(), "{args:?}");
        }
    }

    #[test]
    fn the_workspace_and_bridge_commands_parse() {
        for args in [
            vec!["app", "workspace", "init"],
            vec!["app", "workspace", "init", "papers"],
            vec!["app", "workspace", "init", "--sync"],
            vec!["app", "workspace", "show"],
            vec!["app", "workspace", "select", "papers"],
            vec!["app", "workspace", "select", "--sync"],
            vec!["app", "workspace", "select", "papers", "--sync"],
            vec!["app", "workspace", "sync", "enable"],
            vec!["app", "workspace", "sync", "disable"],
            vec!["app", "workspace", "sync", "status"],
            vec!["app", "workspace", "map", "papers", "papers-remote"],
            vec!["app", "workspace", "move", "../papers"],
            vec!["app", "workspace", "remove"],
            vec!["app", "workspace", "remove", "--delete"],
            vec![
                "app",
                "workgroup",
                "create",
                "--device-name",
                "laptop",
                "home",
            ],
            vec!["app", "workgroup", "list"],
            vec![
                "app",
                "workgroup",
                "join",
                "--device-name",
                "laptop",
                "TICKET",
            ],
            vec!["app", "device", "list"],
            vec!["app", "device", "invite", "--name", "phone"],
            vec!["app", "device", "retire", "phone"],
        ] {
            assert!(Probe::try_parse_from(&args).is_ok(), "{args:?}");
        }
    }

    #[test]
    fn bare_invocation_defaults_to_serve() {
        // <app> with no subcommand at all means serve (spec decision 1). An app CLI
        // achieves it by `Option<Command>` and handing the framework's default here; this
        // probe pins the framework half.
        #[derive(Parser)]
        struct Bare {
            #[command(subcommand)]
            command: Option<Command>,
        }
        let bare = Bare::try_parse_from(["app"]).unwrap();
        assert!(bare.command.is_none());
        assert!(matches!(
            FrameworkCommand::default(),
            FrameworkCommand::Serve
        ));
    }
}

#[cfg(test)]
mod status_tests {
    use super::*;
    use sapphire_workspace::AppContext;

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

    /// Wait until something is listening on `endpoint`.
    ///
    /// `tokio::spawn(server.run())` only schedules the server; without this wait a fast
    /// `run_status` 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() + std::time::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(std::time::Duration::from_millis(10)).await;
        }
    }

    #[tokio::test]
    async fn status_reports_no_server_when_none_is_running() {
        let tmp = tempfile::tempdir().unwrap();
        let endpoint = sapphire_ipc::Endpoint::in_dir("status-test", tmp.path().to_path_buf());
        let code = run_status(&endpoint, "status-test", "0.0.0").await.unwrap();
        assert_eq!(code, 1, "no server is a non-zero exit");
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn status_shows_the_extension_rows_of_a_running_server() {
        let tmp = tempfile::tempdir().unwrap();
        let endpoint = sapphire_ipc::Endpoint::in_dir("status-test", tmp.path().to_path_buf());
        let server = AppServer::new(&CTX, "0.0.0")
            .endpoint(endpoint.clone())
            // This context's directories are never initialised here.
            .selection_file(tmp.path().join("workspace.toml"))
            .status_rows(std::sync::Arc::new(|| {
                vec![StatusRow {
                    name: "sync".into(),
                    value: "on".into(),
                }]
            }));
        let handle = tokio::spawn(async move { server.run().await });
        wait_until_listening(&endpoint).await;

        // The report goes through the sink face so the rendering is asserted, not just
        // the exit code.
        let mut out = String::new();
        let code = run_status_into(&endpoint, CTX.app_name, "0.0.0", &mut out)
            .await
            .unwrap();
        assert_eq!(code, 0);
        assert!(out.contains("running: true"), "output was: {out}");
        assert!(out.contains("sync: on"), "output was: {out}");

        let (client, _) = sapphire_ipc::connect_or_absent(
            &endpoint,
            CTX.app_name,
            sapphire_ipc::ClientInfo {
                kind: "test".into(),
                version: "0.0.0".into(),
                api: sapphire_backend::protocol::API_VERSION,
                app_api: None,
                pid: std::process::id(),
            },
        )
        .await
        .unwrap()
        .expect("the server is listening");
        let _: serde_json::Value = client
            .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
            .await
            .unwrap();
        handle.await.unwrap().unwrap();
    }
}

#[cfg(test)]
mod service_spec_tests {
    use super::*;
    use sapphire_workspace::AppContext;

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

    #[test]
    fn the_generated_spec_runs_the_server_not_the_cli() {
        // A service manager starts the executable directly, and the executable's bare
        // invocation is `serve`: the unit's argv must be exactly that, so the server that
        // starts has no CLI verbs on its command line to misparse.
        let spec = AppServer::new(&CTX, "0.0.0").service_spec();
        assert_eq!(spec.args, vec!["serve".to_owned()]);
    }

    #[test]
    fn the_generated_spec_names_this_application() {
        let spec = AppServer::new(&CTX, "0.0.0").service_spec();
        assert_eq!(spec.app_name, CTX.app_name);
    }

    #[test]
    fn the_generated_spec_describes_the_server() {
        let spec = AppServer::new(&CTX, "0.0.0").service_spec();
        assert!(
            spec.description.contains(CTX.app_name),
            "the unit's description should name the application: {:?}",
            spec.description
        );
        assert!(spec.description.contains("0.0.0"));
    }
}