wsb 0.251.6311

Workspace tools for every project under $PRJ: git across submodules, template stamping, GitHub, and the workbench
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
//! `wsb peer` — workspace continuity from the command line.
//!
//! Every verb here is the same operation the workbench performs, through the
//! daemon that performs it. The command line does not synchronise anything
//! itself: continuity is a long-lived service, and a process that exits cannot
//! hold one. What these do is tell the daemon what the operator wants, and
//! report what it observes.
//!
//! # Why this is not `wsb sync`
//!
//! `wsb sync` is the fleet's GIT operation and keeps its name. These two share
//! a word in English and nothing else — one moves history between repositories
//! through git, the other carries an unfinished working tree between machines
//! and never touches git at all. They share no module, no type and no code
//! path, and the vocabulary keeps them apart on purpose.

use crate::daemon::Client;
use crate::output::record::Record;
use crate::output::emit;

pub const USAGE: &str = "\
Usage: wsb peer <command> [options]

  (no command)           every peer, and what it is doing
  list                   the same, with fingerprints and addresses
  pair                   open a pairing window and print the code
  pair <code> --at <host:port>
                         take a code to the machine that issued it
  forget <peer>          end a peer relationship and its baselines
  sync <peer>            carry this worktree's working tree with that peer
  pause <peer>           stop converging, keep the relationship
  resume <peer>          converge again
  services <peer>        which services run with that machine
  service <peer> <service> <on|off>
                         switch one service on or off with that machine:
                         files, or a plugin's <plugin>.<service>
  mode <peer> [manual|auto]
                         whether changes ARRIVING from that machine are applied
                         here by themselves. One direction: what reaches the
                         peer is settled by the peer's own mode
  deltas <peer>          every difference, and what has been said about each
  take <peer> <path>     carry that machine's version of one path
  keep <peer> <path>     carry this machine's version of one path
  leave <peer> <path>    leave one difference alone until either side changes
  reconsider <peer> <path>
                         take back a take, a keep or a leave
  diff <peer>            what differs between this machine and that peer
  diff <peer> --path <path> [--repository <repo>]
                         both versions of one path, as a diff
  status <peer>          every repository of this worktree, in detail
  resolve <peer> <path> --keep here|there
                         settle one conflict

Continuity carries the WORKING TREE — the unfinished edit, the file not worth a
commit. Git carries history, and `wsb sync` is that: these never overlap, and
continuity never pulls, pushes, merges, rebases, commits or changes a branch.
When git state differs between the two machines it BLOCKS and says which, and
resumes by itself once both sides agree again.

Nothing crosses unasked until you ask for it. A workspace starts in
MANUAL mode — differences are found and listed, and each one waits for `take`,
`keep` or `leave`. `mode <peer> auto` is the other way — everything that is not a
conflict crosses by itself — and conflicts always wait for a person whichever
mode it is in.

Inside a workspace, these act on that workspace. From outside one, name it with
--workspace <id>.";

/// Exit statuses rather than a Result: `wsb peer status` answers with its
/// status when a relationship is blocked, which a caller scripts against.
pub fn dispatch(args: &[String]) -> u8 {
    let verb = args.get(2).map(String::as_str);
    let rest = if args.len() > 3 { &args[3..] } else { &[] };

    let result = match verb {
        None => overview(),
        Some("list") => list(),
        Some("pair") => pair(rest),
        Some("forget") => forget(rest),
        Some("sync") => set_desired(rest, "sync"),
        Some("pause") => set_desired(rest, "pause"),
        Some("resume") => set_desired(rest, "resume"),
        Some("services") => services(rest),
        Some("service") => set_service(rest),
        Some("mode") => mode(rest),
        Some("deltas") => deltas(rest),
        Some("take") => decide(rest, "there"),
        Some("keep") => decide(rest, "here"),
        Some("leave") => delta_action(rest, "dismiss"),
        Some("reconsider") => delta_action(rest, "reconsider"),
        Some("status") => status(rest),
        Some("diff") => diff(rest),
        Some("resolve") => resolve(rest),
        Some("help") | Some("--help") | Some("-h") => {
            crate::outln!("{USAGE}");
            return 0;
        }
        Some(other) => {
            crate::errln!("wsb peer: unknown command '{other}'\n\n{USAGE}");
            return 2;
        }
    };

    match result {
        Ok(status) => status,
        Err(message) => {
            crate::errln!("wsb peer: {message}");
            1
        }
    }
}

/// The daemon, started if it is not running.
///
/// Continuity lives in the daemon, so every one of these needs one. A machine
/// with no daemon is a machine with no peers, and the remedy is to start it
/// rather than to report a state that does not exist.
fn daemon() -> Result<Client, String> {
    let machine_dir = crate::daemon::machine_dir()?;
    let cwd = std::env::current_dir()
        .map_err(|e| format!("cannot determine the current directory: {e}"))?;
    let (client, _info, _started) = crate::daemon::ensure_running(
        &machine_dir,
        &cwd,
        &crate::daemon::Spawn::default(),
    )?;
    Ok(client)
}

/// Which worktree these commands are about, by what a peer knows it as.
///
/// The worktree containing the directory the command was run in, or the
/// continuity id named by `--workspace` (`<family>@<worktree>`). Never
/// guessed: a machine has several, and acting on the wrong one would carry
/// files nobody asked to move.
fn workspace(client: &Client, args: &[String]) -> Result<String, String> {
    if let Some(named) = flag_value(args, "--workspace") {
        return Ok(named.to_string());
    }
    let cwd = std::env::current_dir()
        .map_err(|e| format!("cannot determine the current directory: {e}"))?;
    let worktree = client.resolve_worktree(&cwd).map_err(|error| {
        format!(
            "{error}\n  Run this inside a worktree, or name one with \
             --workspace <family>@<worktree> (`wsb peer list` shows what this machine has)."
        )
    })?;
    match (worktree.workspace, worktree.no_continuity) {
        (Some(workspace), _) => Ok(workspace),
        (None, why) => Err(format!(
            "worktree {} cannot be carried to another machine: {}",
            worktree.id,
            why.unwrap_or_else(|| "it has no continuity id".to_string())
        )),
    }
}

/// Say in data what the prose says, once per peer.
///
/// The records carry what a consumer cannot recover from a rendered table:
/// the id it must use in the next call, and the fingerprint an operator
/// compares by eye.
fn emit_peers(peers: &[PeerView]) {
    for peer in peers {
        emit(Record::PeerState {
            peer: peer.id.clone(),
            name: peer.name.clone(),
            fingerprint: peer.fingerprint.clone(),
            address: peer.address.clone(),
            state: peer.state.clone(),
            detail: peer.detail.clone(),
        });
    }
}

fn overview() -> Result<u8, String> {
    let client = daemon()?;
    let peers: Vec<PeerView> = client.get_json(crate::peer::route::PEERS)?;
    emit_peers(&peers);
    if peers.is_empty() {
        crate::outln!("no peers yet — run `wsb peer pair` here, and on the other machine");
        return Ok(0);
    }
    let rows: Vec<crate::report::Row> = peers
        .iter()
        .map(|peer| {
            crate::report::Row::new(
                &peer.name,
                peer.state.to_uppercase(),
                format!(
                    "{} workspace(s) enabled{}",
                    peer.shared_workspaces,
                    peer.detail
                        .as_ref()
                        .map(|detail| format!(" — {detail}"))
                        .unwrap_or_default()
                ),
            )
        })
        .collect();
    crate::report::show("Peers", &rows, None);
    Ok(0)
}

fn list() -> Result<u8, String> {
    let client = daemon()?;
    let peers: Vec<PeerView> = client.get_json(crate::peer::route::PEERS)?;
    emit_peers(&peers);
    if peers.is_empty() {
        crate::outln!("no peers yet — run `wsb peer pair` here, and on the other machine");
        return Ok(0);
    }
    for peer in &peers {
        crate::outln!("{} ({})", peer.name, peer.id);
        crate::outln!("  fingerprint  {}", peer.fingerprint);
        crate::outln!("  address      {}", peer.address);
        crate::outln!("  state        {}", peer.state);
        if let Some(detail) = &peer.detail {
            crate::outln!("  detail       {detail}");
        }
    }
    Ok(0)
}

fn pair(args: &[String]) -> Result<u8, String> {
    let client = daemon()?;
    let code = args.iter().find(|arg| !arg.starts_with("--"));
    match code {
        // No code: open a window on this machine and say what to type.
        None => {
            let offer: PairingView = client.post_json("/api/v1/peers/pair", &serde_json::json!({}))?;
            crate::outln!("Pairing code: {}", offer.code);
            crate::outln!("");
            crate::outln!("  this machine   {}", offer.machine_name);
            crate::outln!("  fingerprint    {}", offer.fingerprint);
            crate::outln!("  peers reach it on port {}", offer.peer_port);
            crate::outln!("");
            crate::outln!(
                "On the other machine, within {} minutes:",
                offer.expires_in_seconds / 60
            );
            crate::outln!("      wsb peer pair {} --at <this-host>:{}", offer.code, offer.peer_port);
            Ok(0)
        }
        Some(code) => {
            let address = flag_value(args, "--at").ok_or_else(|| {
                "--at <host:port> is required: a code says WHO may pair, not where they are"
                    .to_string()
            })?;
            let peer: PeerView = client.post_json(
                "/api/v1/peers/pair/join",
                &serde_json::json!({ "code": code, "address": address }),
            )?;
            crate::outln!("paired with {} ({})", peer.name, peer.id);
            crate::outln!("  fingerprint  {}", peer.fingerprint);
            crate::outln!("");
            crate::outln!("Check that fingerprint on the other machine before you trust it.");
            crate::outln!("Then, in a workspace both machines have:");
            crate::outln!("      wsb peer sync {}", peer.name);
            Ok(0)
        }
    }
}

fn forget(args: &[String]) -> Result<u8, String> {
    let client = daemon()?;
    let name = positional(args, "peer")?;
    let peer = find_peer(&client, name)?;
    let _: serde_json::Value = client.delete_json(&format!("/api/v1/peers/{}", peer.id))?;
    crate::outln!("{} is no longer a peer; its baselines went with it", peer.name);
    Ok(0)
}

fn set_desired(args: &[String], verb: &str) -> Result<u8, String> {
    let client = daemon()?;
    let name = positional(args, "peer")?;
    let peer = find_peer(&client, name)?;
    let workspace = workspace(&client, args)?;
    let _: serde_json::Value = client.post_json(
        &format!("/api/v1/peers/{}/{}", peer.id, if verb == "sync" { "sync" } else { verb }),
        &serde_json::json!({ "workspace": workspace }),
    )?;
    match verb {
        "sync" => {
            crate::outln!("continuity is on between this workspace and {}", peer.name);
            // Report what it is doing right now rather than making the
            // operator ask a second question.
            report_status(&client, &peer, &workspace)
        }
        "pause" => {
            crate::outln!("paused: nothing converges with {} until you resume", peer.name);
            Ok(0)
        }
        _ => {
            crate::outln!("resumed with {}", peer.name);
            report_status(&client, &peer, &workspace)
        }
    }
}

/// Which services run with one machine.
fn services(args: &[String]) -> Result<u8, String> {
    let client = daemon()?;
    let name = positional(args, "peer")?;
    let peer = find_peer(&client, name)?;
    let view: crate::peer::model::PeerServices = client.get_json(&crate::peer::route::services(&peer.id))?;
    for service in &view.services {
        emit(Record::PeerService {
            peer: peer.id.clone(),
            service: service.service.clone(),
            switch: service.switch.as_str().to_string(),
        });
        crate::outln!(
            "{:<16}  {:<3}  {}",
            service.service,
            service.switch.as_str(),
            service.describes
        );
    }
    Ok(0)
}

/// Switch one service on or off, and say what that leaves running.
fn set_service(args: &[String]) -> Result<u8, String> {
    let client = daemon()?;
    let name = positional(args, "peer")?;
    let bare: Vec<&String> = args.iter().filter(|arg| !arg.starts_with("--")).collect();
    let service = bare
        .get(1)
        .ok_or_else(|| "which service: files, or a plugin's <plugin>.<service>".to_string())?;
    let switch = bare
        .get(2)
        .ok_or_else(|| format!("wsb peer service <peer> {service} on|off"))?;
    // Refused here as well as by the daemon: a typo should not travel.
    let service = crate::peer::model::Service::parse(service)?;
    let switch = crate::peer::model::Switch::parse(switch)?;
    let peer = find_peer(&client, name)?;

    let _: serde_json::Value = client.post_json(
        &format!("/api/v1/peers/{}/services/{}", peer.id, service.as_str()),
        &serde_json::json!({ "switch": switch.as_str() }),
    )?;
    crate::outln!(
        "{}: {} is {} — {}",
        peer.name,
        service.as_str(),
        switch.as_str(),
        service.describe()
    );
    // What is STILL running, because the point of separate switches is that
    // the others were not touched.
    let view: crate::peer::model::PeerServices = client.get_json(&crate::peer::route::services(&peer.id))?;
    let others: Vec<String> = view
        .services
        .iter()
        .filter(|other| other.service != service.as_str())
        .map(|other| format!("{} {}", other.service, other.switch.as_str()))
        .collect();
    if !others.is_empty() {
        crate::outln!("  unchanged: {}", others.join(", "));
    }
    Ok(0)
}

/// How this workspace is carried with one machine.
fn mode(args: &[String]) -> Result<u8, String> {
    let client = daemon()?;
    let name = positional(args, "peer")?;
    let peer = find_peer(&client, name)?;
    let workspace = workspace(&client, args)?;
    let bare: Vec<&String> = args.iter().filter(|arg| !arg.starts_with("--")).collect();

    let Some(wanted) = bare.get(1) else {
        let status: StatusView =
            client.get_json(&format!("/api/v1/peers/{}/status?workspace={workspace}", peer.id))?;
        crate::outln!("{}: {}", peer.name, status.mode);
        return Ok(0);
    };
    let wanted = crate::peer::model::SyncMode::parse(wanted)?;
    let _: serde_json::Value = client.post_json(
        &format!("/api/v1/peers/{}/mode", peer.id),
        &serde_json::json!({ "workspace": workspace, "mode": wanted.as_str() }),
    )?;
    // Said in one direction, because that is what it does. The mode is this
    // machine's statement about its own working tree; what reaches the peer is
    // settled by the peer's own mode, so the two may differ and changes can
    // travel automatically one way only.
    match wanted {
        crate::peer::model::SyncMode::Auto => crate::outln!(
            "{}: changes arriving FROM {} are now applied here by themselves \
             (conflicts still wait).\n  \
             Nothing is pushed the other way unasked — whether {} takes this machine's \
             changes is its own setting.",
            peer.name,
            peer.name,
            peer.name
        ),
        crate::peer::model::SyncMode::Manual => crate::outln!(
            "{}: differences are listed and nothing crosses until you say so, either way",
            peer.name
        ),
    }
    Ok(0)
}

/// Every difference with one machine, and what has been said about each.
fn deltas(args: &[String]) -> Result<u8, String> {
    let client = daemon()?;
    let name = positional(args, "peer")?;
    let peer = find_peer(&client, name)?;
    let workspace = workspace(&client, args)?;
    let view: DeltasView =
        client.get_json(&format!("/api/v1/peers/{}/deltas?workspace={workspace}", peer.id))?;

    crate::outln!("{} · {} · files {}", peer.name, view.continuity, view.files);
    let mut waiting = 0usize;
    for repository in &view.repositories {
        if !repository.compared {
            crate::outln!("{}: {} — nothing compared", repository.label, repository.observed);
            continue;
        }
        if repository.deltas.is_empty() {
            continue;
        }
        crate::outln!("{}:", repository.label);
        for delta in &repository.deltas {
            // What has been said about it, which is the whole point of this
            // listing: a difference nobody has spoken about is the one that
            // needs somebody.
            let said = match (delta.decision.as_deref(), delta.dismissed) {
                (Some("here"), _) => "keep mine",
                (Some("there"), _) => "take theirs",
                (Some(_), _) => "decided",
                (None, true) => "left alone",
                (None, false) => {
                    waiting += 1;
                    "waiting"
                }
            };
            emit(Record::SyncDiff {
                peer: peer.id.clone(),
                workspace: workspace.to_string(),
                repository: repository.repository.clone(),
                path: delta.path.clone(),
                direction: delta.direction.clone(),
                size: delta.size,
            });
            crate::outln!(
                "  {:<10}  {:<11}  {}",
                arrow(&delta.direction),
                said,
                delta.path
            );
        }
    }
    if waiting == 0 {
        crate::outln!("nothing is waiting for a decision");
        return Ok(0);
    }
    crate::outln!(
        "{waiting} difference{} waiting — wsb peer take|keep|leave {} <path>",
        if waiting == 1 { "" } else { "s" },
        peer.name
    );
    // A status a script can read: differences are waiting for a person.
    Ok(3)
}

/// Choose a side for one difference: `take` is theirs, `keep` is this
/// machine's.
fn decide(args: &[String], keep: &str) -> Result<u8, String> {
    let client = daemon()?;
    let name = positional(args, "peer")?;
    let path = delta_path(args)?;
    let repository = flag_value(args, "--repository").unwrap_or("");
    let peer = find_peer(&client, name)?;
    let workspace = workspace(&client, args)?;

    let _: serde_json::Value = client.post_json(
        &format!("/api/v1/peers/{}/deltas/decide", peer.id),
        &serde_json::json!({
            "workspace": workspace,
            "repository": repository,
            "path": path,
            "keep": keep,
        }),
    )?;
    let whose = if keep == "here" {
        "this machine's version".to_string()
    } else {
        format!("{}'s version", peer.name)
    };
    crate::outln!("{path}: carrying {whose} at the next pass");
    Ok(0)
}

/// Leave a difference alone, or take back whatever was said about it.
fn delta_action(args: &[String], action: &str) -> Result<u8, String> {
    let client = daemon()?;
    let name = positional(args, "peer")?;
    let path = delta_path(args)?;
    let repository = flag_value(args, "--repository").unwrap_or("");
    let peer = find_peer(&client, name)?;
    let workspace = workspace(&client, args)?;

    let _: serde_json::Value = client.post_json(
        &format!("/api/v1/peers/{}/deltas/{action}", peer.id),
        &serde_json::json!({
            "workspace": workspace,
            "repository": repository,
            "path": path,
        }),
    )?;
    if action == "dismiss" {
        crate::outln!("{path}: left alone — it comes back if either machine changes it");
    } else {
        crate::outln!("{path}: waiting for a decision again");
    }
    Ok(0)
}

/// The path argument of a delta command: the second bare word.
fn delta_path(args: &[String]) -> Result<&str, String> {
    args.iter()
        .filter(|arg| !arg.starts_with("--"))
        .nth(1)
        .map(String::as_str)
        .ok_or_else(|| "a path is required".to_string())
}

fn status(args: &[String]) -> Result<u8, String> {
    let client = daemon()?;
    let name = positional(args, "peer")?;
    let peer = find_peer(&client, name)?;
    let workspace = workspace(&client, args)?;
    report_status(&client, &peer, &workspace)
}

/// Print one relationship, and answer with a status a script can read.
fn report_status(client: &Client, peer: &PeerView, workspace: &str) -> Result<u8, String> {
    let status: StatusView =
        client.get_json(&format!("/api/v1/peers/{}/status?workspace={workspace}", peer.id))?;

    emit(Record::WorkspacePeerState {
        peer: peer.id.clone(),
        workspace: workspace.to_string(),
        presence: "shared".to_string(),
        desired: status.desired.clone(),
        repositories: status.repositories.len(),
        blocked: status
            .repositories
            .iter()
            .filter(|repository| repository.blocked.is_some())
            .count(),
        conflicts: status.repositories.iter().map(|r| r.conflicts).sum(),
    });
    for repository in &status.repositories {
        emit(Record::SyncState {
            peer: peer.id.clone(),
            workspace: workspace.to_string(),
            repository: repository.repository.as_str().to_string(),
            desired: repository.desired.as_str().to_string(),
            observed: repository.observed.as_str().to_string(),
            blocked: repository.blocked.as_ref().map(|reason| reason.code().to_string()),
            reason: repository.blocked.as_ref().map(|reason| reason.describe()),
            pending: repository.pending,
            conflicts: repository.conflicts,
            branch: repository.branch.clone(),
            head: repository.head.clone(),
        });
    }

    // What is still moving, in files and bytes. Only for a repository that IS
    // moving: a progress line for a settled repository would report a
    // denominator of zero as though something were underway.
    let moving: Vec<&crate::peer::model::RepositoryStatus> = status
        .repositories
        .iter()
        .filter(|repository| repository.observed == crate::peer::model::Observed::Syncing)
        .collect();
    if !moving.is_empty() {
        let diff: DiffView =
            client.get_json(&format!("/api/v1/peers/{}/diff?workspace={workspace}", peer.id))?;
        for repository in moving {
            let id = repository.repository.as_str();
            let bytes = diff
                .repositories
                .iter()
                .find(|entry| entry.repository == id)
                .map(|entry| entry.moves.iter().filter_map(|change| change.size).sum())
                .unwrap_or(0);
            emit(Record::SyncProgress {
                peer: peer.id.clone(),
                workspace: workspace.to_string(),
                repository: id.to_string(),
                files: repository.pending,
                bytes,
            });
        }
    }

    if status.repositories.is_empty() {
        crate::outln!("");
        crate::outln!("  peer     {}", status.peer_state);
        crate::outln!("  desired  {}", status.desired);
        crate::outln!("");
        crate::outln!(
            "Nothing observed yet. The daemon reconciles within a few seconds of \
             being enabled."
        );
        return Ok(0);
    }

    let rows: Vec<crate::report::Row> = status
        .repositories
        .iter()
        .map(|repository| {
            crate::report::Row::new(
                repository.repository.label(),
                repository.observed.as_str().to_uppercase(),
                match &repository.blocked {
                    Some(reason) => reason.describe(),
                    None => match (repository.pending, repository.conflicts) {
                        (0, 0) => repository
                            .branch
                            .clone()
                            .map(|branch| {
                                format!(
                                    "{branch} · {}",
                                    repository
                                        .head
                                        .as_deref()
                                        .map(crate::peer::model::short_commit)
                                        .unwrap_or_default()
                                )
                            })
                            .unwrap_or_default(),
                        (pending, 0) => format!("{pending} file(s) to carry"),
                        (0, conflicts) => format!("{conflicts} conflict(s)"),
                        (pending, conflicts) => {
                            format!("{pending} file(s) to carry, {conflicts} conflict(s)")
                        }
                    },
                },
            )
        })
        .collect();

    let blocked = status
        .repositories
        .iter()
        .filter(|repository| repository.blocked.is_some())
        .count();
    let conflicts: usize = status.repositories.iter().map(|r| r.conflicts).sum();
    let verdict = if blocked > 0 {
        (
            format!("{blocked} repository/repositories blocked"),
            crate::report::Verdict::Fail,
        )
    } else if conflicts > 0 {
        (
            format!("{conflicts} conflict(s) waiting for a decision"),
            crate::report::Verdict::Warn,
        )
    } else {
        ("converged".to_string(), crate::report::Verdict::Ok)
    };
    crate::report::show(
        &format!("{workspace} ↔ {}", peer.name),
        &rows,
        Some((verdict.0.as_str(), verdict.1)),
    );

    // The exit status IS the answer for a script: blocked is 1, a conflict is
    // 1, converged is 0.
    Ok(u8::from(blocked > 0 || conflicts > 0))
}

fn diff(args: &[String]) -> Result<u8, String> {
    let client = daemon()?;
    let name = positional(args, "peer")?;
    let peer = find_peer(&client, name)?;
    let workspace = workspace(&client, args)?;

    // One path, in full: what the two machines actually hold. The list below
    // says WHICH paths differ; this says how.
    if let Some(path) = flag_value(args, "--path") {
        return one_path(&client, &peer, &workspace, flag_value(args, "--repository").unwrap_or(""), path);
    }

    let diff: DiffView =
        client.get_json(&format!("/api/v1/peers/{}/diff?workspace={workspace}", peer.id))?;

    let mut any = false;
    for repository in &diff.repositories {
        if !repository.planned {
            // Blocked: this side does not know what differs, and printing an
            // empty list would say "nothing does".
            crate::outln!(
                "{}: {} — nothing compared",
                repository.label,
                repository.observed
            );
            any = true;
            continue;
        }
        if repository.moves.is_empty() {
            continue;
        }
        any = true;
        crate::outln!("{}:", repository.label);
        for change in &repository.moves {
            emit(Record::SyncDiff {
                peer: peer.id.clone(),
                workspace: workspace.to_string(),
                repository: repository.repository.clone(),
                path: change.path.clone(),
                direction: change.direction.clone(),
                size: change.size,
            });
            crate::outln!(
                "  {:<10}  {}{}",
                arrow(&change.direction),
                change.path,
                change
                    .size
                    .map(|size| format!("  ({size} bytes)"))
                    .unwrap_or_default()
            );
        }
    }

    let conflicts: ConflictsView =
        client.get_json(&format!("/api/v1/peers/{}/conflicts?workspace={workspace}", peer.id))?;
    for conflict in &conflicts.conflicts {
        any = true;
        emit(Record::SyncConflict {
            peer: peer.id.clone(),
            workspace: workspace.to_string(),
            repository: conflict.repository.clone(),
            path: conflict.path.clone(),
            here: conflict.here.clone(),
            there: conflict.there.clone(),
        });
        crate::outln!(
            "  CONFLICT    {}/{}  (here: {}, there: {})",
            if conflict.repository.is_empty() { "superproject" } else { &conflict.repository },
            conflict.path,
            conflict.here,
            conflict.there
        );
    }
    if !any {
        // The state this feature exists to produce, and it is worth saying
        // plainly: this is NOT the same as having no local git changes.
        crate::outln!("no differences between this machine and {}", peer.name);
    }
    // A difference is not a failure — it is the ordinary state of two machines
    // between passes — so this answers 0 either way. `status` is what answers
    // with a status.
    Ok(0)
}

/// Both versions of one conflicted path, as a diff.
///
/// The peer's version comes from the peer, over the same session a transfer
/// uses — so this can fail while everything else works, and it says so rather
/// than showing an empty diff, which would read as "these are the same".
fn one_path(
    client: &Client,
    peer: &PeerView,
    workspace: &str,
    repository: &str,
    path: &str,
) -> Result<u8, String> {
    let query = format!(
        "/api/v1/peers/{}/conflicts/versions?workspace={workspace}&repository={}&path={}",
        peer.id,
        urlencode(repository),
        urlencode(path)
    );
    let versions: VersionsView = client.get_json(&query)?;

    emit(Record::SyncDiff {
        peer: peer.id.clone(),
        workspace: workspace.to_string(),
        repository: versions.repository.clone(),
        path: versions.path.clone(),
        direction: "conflict".to_string(),
        size: Some(versions.here.size),
    });

    match (&versions.diff, &versions.reason) {
        (Some(diff), _) => {
            crate::outln!("- this machine   + {}", peer.name);
            crate::outln!("");
            crate::outln!("{diff}");
            Ok(0)
        }
        (None, Some(reason)) => {
            crate::outln!("{}", describe_undiffable(reason, &peer.name, &versions));
            // Not a failure: "one side deleted it" is an answer, and the two
            // versions still differ. The status is what a script reads for
            // whether anything is outstanding.
            Ok(0)
        }
        (None, None) => Err(format!("{path}: neither a diff nor a reason for there being none")),
    }
}

/// Why there is nothing to draw, in the words a person needs.
fn describe_undiffable(reason: &str, peer: &str, versions: &VersionsView) -> String {
    match reason {
        "deleted_here" => format!(
            "this machine deleted it; {peer} still has it ({} bytes)",
            versions.there.size
        ),
        "deleted_there" => format!(
            "{peer} deleted it; this machine still has it ({} bytes)",
            versions.here.size
        ),
        "binary" => "not text on at least one machine, so there is nothing to show line by line"
            .to_string(),
        "too_large" => format!(
            "too large to compare here ({} bytes here, {} there)",
            versions.here.size, versions.there.size
        ),
        "identical" => {
            "both machines now hold the same bytes; this conflict has resolved itself".to_string()
        }
        other => format!("the two versions could not be compared ({other})"),
    }
}

/// Percent-encode what goes in a query string.
///
/// A path carries spaces, and `+` and `&` are legal in a filename — a query
/// built by concatenation would ask about a different file, or none.
fn urlencode(value: &str) -> String {
    let mut out = String::with_capacity(value.len());
    for byte in value.as_bytes() {
        match byte {
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' | b'/' => {
                out.push(*byte as char)
            }
            other => out.push_str(&format!("%{other:02X}")),
        }
    }
    out
}

/// Which way a change would travel, in one glance.
fn arrow(direction: &str) -> &'static str {
    match direction {
        "send" => "→ peer",
        "receive" => "← peer",
        "send_deletion" => "→ delete",
        "receive_deletion" => "← delete",
        "conflict" => "CONFLICT",
        // The daemon's vocabulary is closed, so this is a version skew between
        // a running daemon and this binary rather than a shape to guess at.
        _ => "?",
    }
}


fn resolve(args: &[String]) -> Result<u8, String> {
    let client = daemon()?;
    let name = positional(args, "peer")?;
    let path = args
        .iter()
        .filter(|arg| !arg.starts_with("--"))
        .nth(1)
        .ok_or_else(|| "a path to resolve is required".to_string())?;
    let keep = flag_value(args, "--keep").ok_or_else(|| {
        "--keep here|there is required: a conflict is settled by choosing, and both \
         choices overwrite the other machine's version"
            .to_string()
    })?;
    let repository = flag_value(args, "--repository").unwrap_or("");
    let peer = find_peer(&client, name)?;
    let workspace = workspace(&client, args)?;

    let _: serde_json::Value = client.post_json(
        &format!("/api/v1/peers/{}/conflicts/resolve", peer.id),
        &serde_json::json!({
            "workspace": workspace,
            "repository": repository,
            "path": path,
            "keep": keep,
        }),
    )?;
    let kept = if keep == "here" {
        "this machine's version".to_string()
    } else {
        format!("{}'s version", peer.name)
    };
    crate::outln!("{path}: keeping {kept}");
    Ok(0)
}

/// A peer by name, id or unambiguous prefix.
fn find_peer(client: &Client, name: &str) -> Result<PeerView, String> {
    let peers: Vec<PeerView> = client.get_json(crate::peer::route::PEERS)?;
    // Exact first: a name that is also a prefix of another must not be
    // ambiguous, or a machine called `laptop` beside one called `laptop-2`
    // could never be named at all.
    let exact: Vec<&PeerView> = peers
        .iter()
        .filter(|peer| peer.name.eq_ignore_ascii_case(name) || peer.id == name)
        .collect();
    if let [one] = exact.as_slice() {
        return Ok((*one).clone());
    }
    let matches: Vec<&PeerView> = peers
        .iter()
        .filter(|peer| peer.id.starts_with(name) || peer.name.starts_with(name))
        .collect();
    match matches.as_slice() {
        [one] => Ok((*one).clone()),
        [] => Err(format!(
            "no peer called '{name}'. This machine knows: {}",
            if peers.is_empty() {
                "none — run `wsb peer pair`".to_string()
            } else {
                peers
                    .iter()
                    .map(|peer| peer.name.as_str())
                    .collect::<Vec<_>>()
                    .join(", ")
            }
        )),
        many => Err(format!(
            "'{name}' matches {} peers: {}. Name one exactly.",
            many.len(),
            many.iter().map(|peer| peer.name.as_str()).collect::<Vec<_>>().join(", ")
        )),
    }
}

fn positional<'a>(args: &'a [String], what: &str) -> Result<&'a str, String> {
    args.iter()
        .find(|arg| !arg.starts_with("--"))
        .map(String::as_str)
        .ok_or_else(|| format!("a {what} is required\n\n{USAGE}"))
}

fn flag_value<'a>(args: &'a [String], name: &str) -> Option<&'a str> {
    args.iter()
        .position(|arg| arg == name)
        .and_then(|index| args.get(index + 1))
        .map(String::as_str)
}

#[derive(Debug, Clone, serde::Deserialize)]
pub struct PeerView {
    pub id: String,
    pub name: String,
    pub fingerprint: String,
    pub address: String,
    pub state: String,
    pub detail: Option<String>,
    pub shared_workspaces: usize,
}

#[derive(Debug, serde::Deserialize)]
struct PairingView {
    code: String,
    expires_in_seconds: u64,
    machine_name: String,
    fingerprint: String,
    peer_port: u16,
}

#[derive(Debug, serde::Deserialize)]
struct StatusView {
    peer_state: String,
    desired: String,
    mode: String,
    repositories: Vec<crate::peer::model::RepositoryStatus>,
}

#[derive(Debug, serde::Deserialize)]
struct DeltasView {
    /// What the three switches come to: off, paused, manual or auto.
    continuity: String,
    files: String,
    repositories: Vec<RepositoryDeltasView>,
}

#[derive(Debug, serde::Deserialize)]
struct RepositoryDeltasView {
    repository: String,
    label: String,
    observed: String,
    /// False when the repository is blocked: nothing was compared, which is
    /// not the same as nothing differing.
    compared: bool,
    deltas: Vec<DeltaView>,
}

#[derive(Debug, serde::Deserialize)]
struct DeltaView {
    path: String,
    direction: String,
    size: Option<u64>,
    /// `here`, `there`, or nothing said yet.
    decision: Option<String>,
    dismissed: bool,
}

#[derive(Debug, serde::Deserialize)]
struct ConflictsView {
    conflicts: Vec<ConflictView>,
}

#[derive(Debug, serde::Deserialize)]
struct ConflictView {
    repository: String,
    path: String,
    /// `modified` or `deleted` — what this side holds for the path.
    here: String,
    there: String,
}

#[derive(Debug, serde::Deserialize)]
struct DiffView {
    repositories: Vec<RepositoryDiffView>,
}

#[derive(Debug, serde::Deserialize)]
struct RepositoryDiffView {
    repository: String,
    label: String,
    observed: String,
    /// False when the repository is blocked: there is no comparison to show,
    /// which is not the same as an empty one.
    planned: bool,
    moves: Vec<MoveView>,
}

#[derive(Debug, serde::Deserialize)]
struct VersionsView {
    repository: String,
    path: String,
    here: SideView,
    there: SideView,
    diff: Option<String>,
    reason: Option<String>,
}

/// One side's version. Only its size is read here — the CONTENT is what the
/// diff already shows, and printing a whole file twice beside its own diff is
/// not a thing anybody reads.
#[derive(Debug, serde::Deserialize)]
struct SideView {
    size: u64,
}

#[derive(Debug, serde::Deserialize)]
struct MoveView {
    path: String,
    direction: String,
    size: Option<u64>,
}

#[cfg(test)]
#[path = "peer_tests.rs"]
mod tests;