zc2 0.0.49

P2P compute broker with yen-denominated billing, WAL, and broker mesh support
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
//! Mesh directory: the CLI's view of "which brokers are on the mesh".
//!
//! The hub's node roster (`GET /api/broker/node/roster`) is the deployment-wide
//! list of authorized broker signing keys, each with the `mesh_endpoint`
//! (`ip:port`) the broker last advertised. A broker's public identity is its
//! key fingerprint — `zc://node-<fp>` with `fp = sha256(pubkey)[..8]` (see
//! `broker::node_identity`) — so the roster is enough to resolve a `zc://node-…`
//! target to an address, and to enumerate the mesh, WITHOUT a local broker and
//! WITHOUT the fleet's shared `ZAKURO_PEER_KEY` (only `/peer/*` needs that;
//! `/health` and `/workers` are open client surfaces).
//!
//! Sources, in order: the hub (credentials from `~/.zakuro/credentials` /
//! env), then the on-disk roster cache a local broker may have written
//! (`~/.zakuro/roster.json`) so the directory keeps working offline.
//!
//! IP-FREE RULE: this module returns endpoints to *callers that dial them*; the
//! user-facing renderers (`zc brokers`) print only `zc://node-<fp>`, the
//! broker's self-reported `node_name`, and reachability — never an address.

use std::time::Duration;

/// One authorized broker as the roster describes it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MeshBroker {
    /// 16-hex key fingerprint (bare, no `zc://node-` prefix).
    pub fp: String,
    /// `ip:port` the broker advertised, if it has a tunnel up.
    pub endpoint: Option<String>,
    pub revoked: bool,
    /// The zc build the node registered with the hub (`zc_build` on the
    /// roster). Shown when the broker itself cannot be asked.
    pub hub_build: Option<crate::build_id::BuildId>,
}

impl MeshBroker {
    pub fn node_uri(&self) -> String {
        format!("zc://node-{}", self.fp)
    }
}

/// Result of probing one broker's `/health`.
#[derive(Debug, Clone)]
pub struct BrokerProbe {
    pub broker: MeshBroker,
    pub reachable: bool,
    pub node_name: Option<String>,
    pub mesh_tunnel: Option<String>,
    /// The zc binary that broker answered with (zc#305). `None` when the
    /// probe failed or the broker predates build disclosure — the two are
    /// distinguished by `reachable`.
    pub build: Option<crate::build_id::BuildId>,
    /// The account that owns this node. `None` when the probe failed, the
    /// broker predates owner disclosure, or it genuinely has no owner set —
    /// the last of which is worth seeing, since an unowned node cannot be
    /// paid for the work it runs.
    pub owner_user_id: Option<String>,
}

/// Parse a roster body (`[{node_pubkey, revoked, mesh_endpoint}]`) into
/// fingerprinted entries. Entries whose pubkey does not decode are dropped.
pub fn parse_roster(body: &str) -> Vec<MeshBroker> {
    let v: serde_json::Value = match serde_json::from_str(body) {
        Ok(v) => v,
        Err(_) => return Vec::new(),
    };
    v.as_array()
        .map(|arr| {
            arr.iter()
                .filter_map(|e| {
                    let pk = e.get("node_pubkey")?.as_str()?;
                    let fp = crate::broker::node_identity::fingerprint_of_pubkey_b64(pk)?;
                    let revoked = e.get("revoked").and_then(|r| r.as_bool()).unwrap_or(false);
                    let endpoint = e
                        .get("mesh_endpoint")
                        .and_then(|m| m.as_str())
                        .map(str::trim)
                        .filter(|s| !s.is_empty())
                        .map(str::to_string);
                    let hub_build = e
                        .get("zc_build")
                        .cloned()
                        .and_then(|b| serde_json::from_value(b).ok())
                        .filter(crate::build_id::BuildId::is_known);
                    Some(MeshBroker {
                        fp,
                        endpoint,
                        revoked,
                        hub_build,
                    })
                })
                .collect()
        })
        .unwrap_or_default()
}

/// Fetch the roster from the hub. Needs an API key (zk_ or a `zc login`
/// session token) — loaded from the saved credentials when not in the env.
pub fn fetch_from_hub() -> Result<Vec<MeshBroker>, String> {
    crate::credentials::load_into_env();
    let api_key = std::env::var("ZAKURO_API_KEY")
        .ok()
        .filter(|k| !k.trim().is_empty())
        .ok_or_else(|| "not signed in (run `zc login` or set ZAKURO_API_KEY)".to_string())?;
    let api_url = crate::credentials::default_api_url();
    let endpoint = format!("{}/api/broker/node/roster", api_url.trim_end_matches('/'));
    let resp = ureq::get(&endpoint)
        .config()
        .timeout_global(Some(Duration::from_secs(10)))
        .http_status_as_error(false)
        .build()
        .header("X-Broker-Api-Key", &api_key)
        .call()
        .map_err(|e| format!("roster request failed: {e}"))?;
    let status = resp.status().as_u16();
    if status != 200 {
        return Err(format!("roster HTTP {status} from {api_url}"));
    }
    let body = resp
        .into_body()
        .read_to_string()
        .map_err(|e| format!("roster read failed: {e}"))?;
    Ok(parse_roster(&body))
}

/// The roster a local broker cached on disk (`~/.zakuro/roster.json`), if any.
pub fn load_cached() -> Vec<MeshBroker> {
    let cache = crate::broker::roster_cache::RosterCache::load();
    cache
        .entries()
        .into_iter()
        .filter_map(|(pk, revoked)| {
            let fp = crate::broker::node_identity::fingerprint_of_pubkey_b64(&pk)?;
            let endpoint = cache.endpoint_for_fingerprint(&fp);
            Some(MeshBroker {
                fp,
                endpoint,
                revoked,
                hub_build: None,
            })
        })
        .collect()
}

/// Hub first, cached roster as the offline fallback. `Err` only when neither
/// source yields anything; the message names the hub failure.
pub fn directory() -> Result<Vec<MeshBroker>, String> {
    match fetch_from_hub() {
        Ok(list) => Ok(list),
        Err(e) => {
            let cached = load_cached();
            if cached.is_empty() {
                Err(e)
            } else {
                crate::vpn::vlog(&format!(
                    "hub roster unavailable ({e}); using cached roster"
                ));
                Ok(cached)
            }
        }
    }
}

/// Resolve a bare fingerprint (or `zc://node-<fp>` / `node-<fp>`) to the
/// broker's advertised `ip:port`. `None` when unknown, revoked, or off-mesh.
pub fn endpoint_for(arg: &str) -> Option<String> {
    let fp = crate::broker::node_identity::strip_node_arg(arg);
    directory()
        .ok()?
        .into_iter()
        .find(|b| b.fp == fp && !b.revoked)
        .and_then(|b| b.endpoint)
}

/// True when `s` has the shape of a key fingerprint: 16 lowercase hex chars.
pub fn looks_like_fingerprint(s: &str) -> bool {
    s.len() == 16
        && s.bytes()
            .all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase())
}

/// A peer's owner from `/peer/identity`, for brokers too old to put it on
/// `/health`. Needs the mesh peer key; `None` without one, or on any failure.
fn owner_via_peer_identity(agent: &ureq::Agent, endpoint: &str) -> Option<String> {
    let key = crate::credentials::load_mesh_peer_key()?;
    let url = format!("http://{}/peer/identity", endpoint);
    let body = agent
        .get(&url)
        .header("X-Peer-Key", &key)
        .call()
        .ok()?
        .into_body()
        .read_to_string()
        .ok()?;
    let json: serde_json::Value = serde_json::from_str(&body).ok()?;
    json.get("owner_user_id")?
        .as_str()
        .filter(|s| !s.trim().is_empty())
        .map(str::to_string)
}

/// Probe every broker that advertises an endpoint, concurrently, through the
/// mesh-aware HTTP agent (sidecar proxy when the host is not routable).
/// Brokers without an endpoint are returned unreachable without a probe.
pub fn probe_all(brokers: Vec<MeshBroker>, timeout: Duration) -> Vec<BrokerProbe> {
    probe_all_within(brokers, timeout, timeout)
}

/// How long a listing waits for the mesh. A healthy broker answers `/health`
/// in about one mesh round trip (≈0.75 s from a laptop through the sidecar
/// proxy, 2026-10); this is twice that, so a live broker is never cut off
/// and a dead one costs 1.5 s instead of the 4 s request timeout.
pub const LISTING_DEADLINE: Duration = Duration::from_millis(1500);

/// [`probe_all`], but stop waiting at `deadline`: whatever has not answered
/// by then is reported unreachable. Without it one dead broker holds every
/// listing for the full `timeout`, however fast the rest answered. The
/// stragglers' threads are left to finish on their own; nothing reads them.
pub fn probe_all_within(
    brokers: Vec<MeshBroker>,
    timeout: Duration,
    deadline: Duration,
) -> Vec<BrokerProbe> {
    let started = std::time::Instant::now();
    let (tx, rx) = std::sync::mpsc::channel::<BrokerProbe>();
    let expected: Vec<MeshBroker> = brokers.clone();
    for b in brokers {
        let tx = tx.clone();
        std::thread::spawn(move || {
            let _ = tx.send((move || {
                let Some(ep) = b.endpoint.clone() else {
                    return BrokerProbe {
                        broker: b,
                        reachable: false,
                        node_name: None,
                        mesh_tunnel: None,
                        build: None,
                        owner_user_id: None,
                    };
                };
                let url = format!("http://{}/health", ep);
                let agent = crate::vpn::mesh_agent_for(&url, timeout);
                let json: Option<serde_json::Value> = agent
                    .get(&url)
                    .call()
                    .ok()
                    .and_then(|r| r.into_body().read_to_string().ok())
                    .and_then(|t| serde_json::from_str(&t).ok());
                let is_broker = json
                    .as_ref()
                    .and_then(|j| j.get("service"))
                    .and_then(|s| s.as_str())
                    == Some("zakuro-broker");
                BrokerProbe {
                    node_name: json
                        .as_ref()
                        .and_then(|j| j.get("node_name"))
                        .and_then(|s| s.as_str())
                        .map(str::to_string),
                    mesh_tunnel: json
                        .as_ref()
                        .and_then(|j| j.get("mesh_tunnel"))
                        .and_then(|s| s.as_str())
                        .map(str::to_string),
                    build: json
                        .as_ref()
                        .and_then(|j| j.get("build"))
                        .cloned()
                        .and_then(|b| serde_json::from_value(b).ok())
                        .filter(crate::build_id::BuildId::is_known),
                    // `/health` carries the owner only on brokers new enough
                    // to disclose it. For an older peer, fall back to
                    // `/peer/identity`, which has carried it for far longer —
                    // at the cost of needing the mesh peer key, which is why
                    // it is the fallback and not the source. Without a key the
                    // column simply reads "owner unset", which is honest:
                    // this broker does not know.
                    owner_user_id: json
                        .as_ref()
                        .and_then(|j| j.get("owner_user_id"))
                        .and_then(|s| s.as_str())
                        .filter(|s| !s.trim().is_empty())
                        .map(str::to_string)
                        .or_else(|| {
                            is_broker
                                .then(|| owner_via_peer_identity(&agent, &ep))
                                .flatten()
                        }),
                    reachable: is_broker,
                    broker: b,
                }
            })());
        });
    }
    drop(tx);
    let mut out: Vec<BrokerProbe> = Vec::new();
    while out.len() < expected.len() {
        let left = deadline.saturating_sub(started.elapsed());
        match rx.recv_timeout(left) {
            Ok(p) => out.push(p),
            Err(_) => break,
        }
    }
    for b in expected {
        if !out.iter().any(|p| p.broker.fp == b.fp) {
            out.push(BrokerProbe {
                broker: b,
                reachable: false,
                node_name: None,
                mesh_tunnel: None,
                build: None,
                owner_user_id: None,
            });
        }
    }
    out.sort_by(|a, b| {
        b.reachable
            .cmp(&a.reachable)
            .then_with(|| a.broker.fp.cmp(&b.broker.fp))
    });
    out
}

/// Width of the node-name column in [`render`].
const NAME_WIDTH: usize = 24;

/// Width of the owner column. An account id is a short opaque number; long
/// enough for the ids in use, ellipsized rather than allowed to shift the
/// columns after it.
const OWNER_WIDTH: usize = 13;

/// `s` cut to at most `width` chars, the last one replaced by `…` when it had
/// to be cut. Counts chars, not bytes, so a non-ASCII name cannot panic or
/// silently overflow the column.
fn truncate_to(s: &str, width: usize) -> String {
    if s.chars().count() <= width {
        return s.to_string();
    }
    s.chars().take(width.saturating_sub(1)).collect::<String>() + "…"
}

/// One line reconciling the builds across the reachable brokers (zc#305).
///
/// Empty when nothing is reachable. Otherwise it either confirms the mesh is
/// uniform or names how far apart it is — the question `zc brokers` exists to
/// answer once brokers stopped agreeing on a version.
///
/// Brokers that disclose no build are counted separately rather than lumped
/// in as a distinct build: "we do not know" and "a different binary" are
/// different findings, and conflating them would report skew that may not be
/// there.
pub fn reconcile_builds(probes: &[BrokerProbe]) -> String {
    use colored::Colorize;

    let reachable: Vec<&BrokerProbe> = probes.iter().filter(|p| p.reachable).collect();
    if reachable.is_empty() {
        return String::new();
    }
    let mut labels: Vec<String> = reachable
        .iter()
        .filter_map(|p| p.build.as_ref())
        .map(|b| b.label())
        .collect();
    let undisclosed = reachable.len() - labels.len();
    labels.sort();
    labels.dedup();

    let mut line = match labels.len() {
        0 => format!(
            "  {} none of the {} reachable broker(s) disclose a build\n",
            "⚠".yellow(),
            reachable.len()
        ),
        1 => format!(
            "  {} all {} reachable broker(s) on {}\n",
            "✓".green(),
            reachable.len() - undisclosed,
            labels[0].bold()
        ),
        n => {
            let mut s = format!(
                "  {} {} distinct builds across {} reachable broker(s):\n",
                "⚠".yellow(),
                n,
                reachable.len()
            );
            for l in &labels {
                let count = reachable
                    .iter()
                    .filter(|p| p.build.as_ref().map(|b| b.label()).as_deref() == Some(l))
                    .count();
                s.push_str(&format!("      {:>2} × {}\n", count, l));
            }
            s
        }
    };
    if undisclosed > 0 && !labels.is_empty() {
        line.push_str(&format!(
            "      {:>2} × {}\n",
            undisclosed,
            "build undisclosed".dimmed()
        ));
    }
    line
}

/// Render the directory for `zc brokers`. IP-free by construction: only the
/// key-derived id, the broker's own display name, liveness and the zc build
/// it reports are printed.
pub fn render(
    probes: &[BrokerProbe],
    self_fp: Option<&str>,
    offline_without_endpoint: usize,
) -> String {
    use colored::Colorize;
    let mut out = String::new();
    let live: Vec<&BrokerProbe> = probes
        .iter()
        .filter(|p| p.broker.endpoint.is_some())
        .collect();
    if live.is_empty() {
        out.push_str("  No brokers currently advertise a mesh endpoint.\n");
    } else {
        out.push_str(&format!(
            "  {} broker(s) on the mesh:\n",
            live.iter().filter(|p| p.reachable).count()
        ));
        for p in live {
            let mark = if p.reachable {
                "✓".green().to_string()
            } else {
                "✗".red().to_string()
            };
            let me = if self_fp == Some(p.broker.fp.as_str()) {
                "  (this machine)".dimmed().to_string()
            } else {
                String::new()
            };
            // A broker self-reports its display name and some are long enough
            // to shove every following column out of line (an EC2
            // `ip-…​.compute.internal` is 50 chars). Ellipsize to the column.
            let name = truncate_to(p.node_name.as_deref().unwrap_or("-"), NAME_WIDTH);
            let tunnel = match p.mesh_tunnel.as_deref() {
                Some("up") => "tunnel up".to_string(),
                Some("down") => "tunnel down".yellow().to_string(),
                _ if p.reachable => String::new(),
                _ => "unreachable".dimmed().to_string(),
            };
            // Plain text, never colored: `{:<32}` pads by chars and would
            // count ANSI escapes as width, knocking the column out of line.
            let build = match (&p.build, p.reachable, &p.broker.hub_build) {
                (Some(b), _, _) => b.label(),
                (None, true, _) => "build undisclosed".to_string(),
                // Not answering: what the node last told the hub.
                (None, false, Some(h)) => format!("{} (hub)", h.label()),
                (None, false, None) => "-".to_string(),
            };
            // The account that owns the node. Plain text for the same reason
            // as `build`: `{:<12}` pads by chars and would miscount ANSI.
            let owner = match (&p.owner_user_id, p.reachable) {
                (Some(o), _) => truncate_to(o, OWNER_WIDTH),
                (None, true) => "owner unset".to_string(),
                (None, false) => "-".to_string(),
            };
            out.push_str(&format!(
                "    {} {}  {:<name_w$} {:<32} {:<owner_w$} {}{}\n",
                mark,
                p.broker.node_uri().bold(),
                name,
                build,
                owner,
                tunnel,
                me,
                name_w = NAME_WIDTH,
                owner_w = OWNER_WIDTH
            ));
        }
        out.push_str(&reconcile_builds(probes));
    }
    if offline_without_endpoint > 0 {
        out.push_str(&format!(
            "  {} registered node(s) without a mesh endpoint (offline).\n",
            offline_without_endpoint
        ));
    }
    out
}

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

    // A valid 32-byte Ed25519 public key, base64 (any 32 bytes decode fine for
    // fingerprinting; the value is arbitrary).
    const PK_A: &str = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=";
    const PK_B: &str = "//////////////////////////////////////////8=";

    #[test]
    fn parses_roster_rows_into_fingerprints_and_endpoints() {
        let body = format!(
            r#"[{{"node_pubkey":"{PK_A}","revoked":false,"mesh_endpoint":"10.13.13.33:9000"}},
                {{"node_pubkey":"{PK_B}","revoked":true,"mesh_endpoint":null}},
                {{"node_pubkey":"not base64!!","revoked":false}}]"#
        );
        let list = parse_roster(&body);
        assert_eq!(list.len(), 2, "undecodable pubkeys are dropped");
        let a = &list[0];
        assert!(looks_like_fingerprint(&a.fp), "fp={}", a.fp);
        assert_eq!(a.endpoint.as_deref(), Some("10.13.13.33:9000"));
        assert!(!a.revoked);
        assert_eq!(
            a.fp,
            crate::broker::node_identity::fingerprint_of_pubkey_b64(PK_A).unwrap()
        );
        assert!(list[1].revoked);
        assert!(list[1].endpoint.is_none());
        assert_eq!(a.node_uri(), format!("zc://node-{}", a.fp));
    }

    #[test]
    fn fingerprint_shape() {
        assert!(looks_like_fingerprint("13a9551e881f7f8c"));
        assert!(!looks_like_fingerprint("13A9551E881F7F8C"));
        assert!(!looks_like_fingerprint("13a9551e881f7f8"));
        assert!(!looks_like_fingerprint("localhost"));
        assert!(!looks_like_fingerprint("zc-broker-1"));
    }

    #[test]
    fn probe_marks_endpointless_nodes_unreachable_without_dialing() {
        let list = vec![MeshBroker {
            fp: "0123456789abcdef".into(),
            endpoint: None,
            revoked: false,
            hub_build: None,
        }];
        let probes = probe_all(list, Duration::from_millis(50));
        assert_eq!(probes.len(), 1);
        assert!(!probes[0].reachable);
        assert!(probes[0].node_name.is_none());
    }

    #[test]
    fn probe_accepts_only_a_zakuro_broker_health_body() {
        use std::io::{Read, Write};
        use std::net::TcpListener;
        // Fake "broker" that answers /health with the right service tag.
        let good = TcpListener::bind("127.0.0.1:0").unwrap();
        let good_addr = good.local_addr().unwrap();
        std::thread::spawn(move || {
            if let Ok((mut s, _)) = good.accept() {
                let mut buf = [0u8; 1024];
                let _ = s.read(&mut buf);
                let body = r#"{"status":"healthy","service":"zakuro-broker","node_name":"fake-1","mesh_tunnel":"up","build":{"version":"0.0.33","git":"0447049","binary_sha256":"aaaaaaaaaaaabbbbbbbbbbbbccccccccccccddddddddddddeeeeeeeeeeeeffff"}}"#;
                let _ = write!(
                    s,
                    "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
                    body.len(),
                    body
                );
            }
        });
        // Something else (a MinIO-console-shaped HTML 200) must NOT count.
        let bad = TcpListener::bind("127.0.0.1:0").unwrap();
        let bad_addr = bad.local_addr().unwrap();
        std::thread::spawn(move || {
            if let Ok((mut s, _)) = bad.accept() {
                let mut buf = [0u8; 1024];
                let _ = s.read(&mut buf);
                let body = "<!doctype html><html></html>";
                let _ = write!(
                    s,
                    "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
                    body.len(),
                    body
                );
            }
        });
        // Not a mesh IP, so the mesh agent dials directly (no proxy involved).
        let list = vec![
            MeshBroker {
                fp: "aaaaaaaaaaaaaaaa".into(),
                endpoint: Some(good_addr.to_string()),
                revoked: false,
                hub_build: None,
            },
            MeshBroker {
                fp: "bbbbbbbbbbbbbbbb".into(),
                endpoint: Some(bad_addr.to_string()),
                revoked: false,
                hub_build: None,
            },
        ];
        let probes = probe_all(list, Duration::from_secs(3));
        let good_p = probes
            .iter()
            .find(|p| p.broker.fp == "aaaaaaaaaaaaaaaa")
            .unwrap();
        let bad_p = probes
            .iter()
            .find(|p| p.broker.fp == "bbbbbbbbbbbbbbbb")
            .unwrap();
        assert!(good_p.reachable);
        assert_eq!(good_p.node_name.as_deref(), Some("fake-1"));
        assert_eq!(good_p.mesh_tunnel.as_deref(), Some("up"));
        // zc#305: the build travels on the same /health probe.
        let build = good_p.build.as_ref().expect("health disclosed a build");
        assert_eq!(build.version, "0.0.33");
        assert_eq!(build.git.as_deref(), Some("0447049"));
        assert_eq!(build.short_hash(), Some("aaaaaaaaaaaa"));
        assert!(!bad_p.reachable, "an HTML 200 is not a broker");
        assert!(bad_p.build.is_none());
        // reachable rows sort first
        assert_eq!(probes[0].broker.fp, "aaaaaaaaaaaaaaaa");
    }

    #[test]
    fn render_is_ip_free() {
        let probes = vec![BrokerProbe {
            owner_user_id: None,
            broker: MeshBroker {
                fp: "0123456789abcdef".into(),
                endpoint: Some("10.13.13.33:9000".into()),
                revoked: false,
                hub_build: None,
            },
            reachable: true,
            node_name: Some("zc-broker-1".into()),
            mesh_tunnel: Some("up".into()),
            build: None,
        }];
        let text = render(&probes, Some("0123456789abcdef"), 3);
        assert!(text.contains("zc://node-0123456789abcdef"));
        assert!(text.contains("zc-broker-1"));
        assert!(text.contains("(this machine)"));
        assert!(text.contains("3 registered node(s) without a mesh endpoint"));
        assert!(
            !text.contains("10.13.13"),
            "must never print an address: {text}"
        );
    }

    // --- zc#305: build disclosure and reconciliation -----------------------

    /// The owner column is the point of the change: a marketplace, and anyone
    /// reading `zc brokers`, has to be able to say whose machine a node is.
    /// A node with no owner configured is called out rather than blank —
    /// an unowned node cannot be paid for the work it runs.
    #[test]
    fn the_table_names_the_owner_of_every_reachable_node() {
        let mut owned = probe("aaaaaaaaaaaaaaaa", true, None);
        owned.owner_user_id = Some("5492316032".into());
        owned.broker.endpoint = Some("10.13.13.35:9000".into());

        let mut unowned = probe("bbbbbbbbbbbbbbbb", true, None);
        unowned.owner_user_id = None;
        unowned.broker.endpoint = Some("10.13.13.36:9000".into());

        let text = render(&[owned, unowned], None, 0);
        assert!(text.contains("5492316032"), "owner id must appear: {text}");
        assert!(
            text.contains("owner unset"),
            "an unowned node says so: {text}"
        );
        // The IP-FREE RULE still holds with the new column.
        assert!(!text.contains("10.13.13."), "no addresses: {text}");
    }

    fn probe(fp: &str, reachable: bool, build: Option<crate::build_id::BuildId>) -> BrokerProbe {
        BrokerProbe {
            owner_user_id: None,
            broker: MeshBroker {
                fp: fp.into(),
                endpoint: Some("10.13.13.33:9000".into()),
                revoked: false,
                hub_build: None,
            },
            reachable,
            node_name: Some(format!("zc-broker-{fp}")),
            mesh_tunnel: Some("up".into()),
            build,
        }
    }

    fn build(version: &str, git: &str, hash_byte: &str) -> Option<crate::build_id::BuildId> {
        Some(crate::build_id::BuildId {
            version: version.into(),
            git: Some(git.into()),
            binary_sha256: Some(hash_byte.repeat(32)),
        })
    }

    /// A broker that never answers costs the deadline, not the timeout.
    #[test]
    fn a_silent_broker_costs_the_deadline_not_the_timeout() {
        // Accepts and never replies.
        let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let ep = l.local_addr().unwrap().to_string();
        let held = std::thread::spawn(move || {
            let _c = l.accept();
            std::thread::sleep(Duration::from_secs(3));
        });
        let started = std::time::Instant::now();
        let probes = probe_all_within(
            vec![MeshBroker {
                fp: "aaaaaaaaaaaaaaaa".into(),
                endpoint: Some(ep),
                revoked: false,
                hub_build: None,
            }],
            Duration::from_secs(5),
            Duration::from_millis(300),
        );
        assert!(
            started.elapsed() < Duration::from_secs(2),
            "{:?}",
            started.elapsed()
        );
        assert_eq!(probes.len(), 1);
        assert!(!probes[0].reachable);
        drop(held);
    }

    #[test]
    fn a_uniform_mesh_is_reported_as_uniform() {
        let probes = vec![
            probe("aaaaaaaaaaaaaaaa", true, build("0.0.33", "0447049", "ab")),
            probe("bbbbbbbbbbbbbbbb", true, build("0.0.33", "0447049", "ab")),
        ];
        let text = reconcile_builds(&probes);
        assert!(text.contains("all 2 reachable broker(s) on"), "{text}");
        assert!(text.contains("0.0.33 (0447049) sha:ababababab"), "{text}");
        assert!(!text.contains("distinct builds"), "{text}");
    }

    #[test]
    fn differing_builds_are_counted_and_listed() {
        let probes = vec![
            probe("aaaaaaaaaaaaaaaa", true, build("0.0.33", "0447049", "ab")),
            probe("bbbbbbbbbbbbbbbb", true, build("0.0.33", "0447049", "ab")),
            probe("cccccccccccccccc", true, build("0.0.31", "9911223", "cd")),
        ];
        let text = reconcile_builds(&probes);
        assert!(
            text.contains("2 distinct builds across 3 reachable broker(s)"),
            "{text}"
        );
        assert!(text.contains(" 2 × 0.0.33 (0447049)"), "{text}");
        assert!(text.contains(" 1 × 0.0.31 (9911223)"), "{text}");
    }

    /// Same version and commit, different artifact — the case a semver alone
    /// cannot see, and the reason the hash is disclosed at all.
    #[test]
    fn two_artifacts_of_one_commit_count_as_two_builds() {
        let probes = vec![
            probe("aaaaaaaaaaaaaaaa", true, build("0.0.33", "0447049", "ab")),
            probe("bbbbbbbbbbbbbbbb", true, build("0.0.33", "0447049", "cd")),
        ];
        let text = reconcile_builds(&probes);
        assert!(text.contains("2 distinct builds"), "{text}");
    }

    /// "We do not know" must not be reported as "a different binary".
    #[test]
    fn undisclosed_builds_are_counted_apart_from_real_skew() {
        let probes = vec![
            probe("aaaaaaaaaaaaaaaa", true, build("0.0.33", "0447049", "ab")),
            probe("bbbbbbbbbbbbbbbb", true, None),
        ];
        let text = reconcile_builds(&probes);
        assert!(text.contains("all 1 reachable broker(s) on"), "{text}");
        assert!(text.contains("1 × build undisclosed"), "{text}");
        assert!(!text.contains("distinct builds"), "{text}");
    }

    #[test]
    fn unreachable_brokers_do_not_count_towards_skew() {
        let probes = vec![
            probe("aaaaaaaaaaaaaaaa", true, build("0.0.33", "0447049", "ab")),
            probe("bbbbbbbbbbbbbbbb", false, build("0.0.31", "9911223", "cd")),
        ];
        let text = reconcile_builds(&probes);
        assert!(text.contains("all 1 reachable broker(s) on"), "{text}");
        assert!(!text.contains("0.0.31"), "{text}");
    }

    #[test]
    fn nothing_reachable_reconciles_to_nothing() {
        let probes = vec![probe("aaaaaaaaaaaaaaaa", false, None)];
        assert_eq!(reconcile_builds(&probes), "");
    }

    #[test]
    fn a_long_node_name_is_ellipsized_so_the_build_column_stays_put() {
        let mut long = probe("aaaaaaaaaaaaaaaa", true, build("0.0.33", "0447049", "ab"));
        long.node_name = Some("ip-192-168-120-124.ap-northeast-1.compute.internal".into());
        let short = probe("bbbbbbbbbbbbbbbb", true, build("0.0.33", "0447049", "ab"));
        let text = render(&[long, short], None, 0);

        let col = |line: &str| line.find("0.0.33 (0447049)").expect("build on the row");
        // Broker rows only — the reconciliation summary names the build too.
        let rows: Vec<&str> = text.lines().filter(|l| l.contains("zc://node-")).collect();
        assert_eq!(rows.len(), 2, "{text}");
        assert_eq!(
            col(rows[0]),
            col(rows[1]),
            "the build column must line up:\n{text}"
        );
        assert!(
            text.contains('…'),
            "the long name was not ellipsized: {text}"
        );
    }

    #[test]
    fn truncate_to_leaves_a_short_name_alone_and_counts_chars() {
        assert_eq!(truncate_to("zc-broker-1", 24), "zc-broker-1");
        assert_eq!(truncate_to("abcdef", 4), "abc…");
        // Multi-byte: cutting by bytes here would panic or split a char.
        assert_eq!(truncate_to("ノードいちにさん", 4), "ノード…");
    }

    #[test]
    fn render_prints_the_build_column_and_the_summary() {
        let probes = vec![
            probe("aaaaaaaaaaaaaaaa", true, build("0.0.33", "0447049", "ab")),
            probe("bbbbbbbbbbbbbbbb", true, build("0.0.31", "9911223", "cd")),
        ];
        let text = render(&probes, None, 0);
        assert!(text.contains("0.0.33 (0447049) sha:ababababab"), "{text}");
        assert!(text.contains("0.0.31 (9911223) sha:cdcdcdcdcd"), "{text}");
        assert!(text.contains("2 distinct builds"), "{text}");
        assert!(!text.contains("10.13.13"), "still IP-free: {text}");
    }

    /// The hub's roster says what build each node registered with; a node that
    /// does not answer is shown with it, marked as the hub's word. A node that
    /// answers is shown what it said itself.
    #[test]
    fn a_silent_node_shows_the_build_it_registered_with_the_hub() {
        let pk = "AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE=";
        let body = format!(
            r#"[{{"node_pubkey":"{pk}","revoked":false,"mesh_endpoint":"10.13.13.9:9000","zc_build":{{"version":"0.0.47","git":"abc1234"}}}}]"#
        );
        let brokers = parse_roster(&body);
        assert_eq!(brokers.len(), 1);
        let hub = brokers[0].hub_build.clone().expect("zc_build read");
        assert_eq!(hub.version, "0.0.47");

        let mut dark = probe(&brokers[0].fp, false, None);
        dark.broker = brokers[0].clone();
        let text = render(&[dark.clone()], None, 0);
        assert!(text.contains("0.0.47 (abc1234) (hub)"), "{text}");
        assert!(!text.contains("10.13.13"), "still IP-free: {text}");

        // answering: its own build wins, the hub's is not shown
        let mut live = dark;
        live.reachable = true;
        live.build = build("0.0.46", "9911223", "cd");
        let text = render(&[live], None, 0);
        assert!(
            text.contains("0.0.46 (9911223)") && !text.contains("(hub)"),
            "{text}"
        );

        // a hub without zc_build: nothing invented
        let old =
            parse_roster(&body.replace(r#","zc_build":{"version":"0.0.47","git":"abc1234"}"#, ""));
        assert!(old[0].hub_build.is_none());
    }
}