zc2 0.0.42

P2P compute broker with credit-based 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
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
//! Shared state of one `zc agent` and the operations the local API and the
//! run loops call (spec ยง6.3-6.7).

use crate::agent::config::AgentConfig;
use crate::agent::files::{self, DesiredState, CHILDREN_FILE, HISTORY_FILE, STATE_FILE};
use crate::agent::history::History;
use crate::agent::hub::{self, CredWatch, Credentials, HubClient, HubError};
use crate::agent::hubwire::HubSummary;
use crate::agent::merge::{self, LocalView, MergeInput};
use crate::agent::plan::{self, Desired};
use crate::agent::summary::{HubStatus, MeshStatus, NetworkCapacity, Problem, Summary};
use crate::agent::supervisor::{self, HttpBrokerApi, SpawnSpec, Supervisor};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use tokio::sync::Notify;

/// A local-API error: `{"error":{"code","message"}}` with `status` (spec ยง6.3).
#[derive(Debug, Clone, PartialEq)]
pub struct ApiError {
    pub status: u16,
    pub code: &'static str,
    pub message: String,
}

impl ApiError {
    fn new(status: u16, code: &'static str, message: impl Into<String>) -> Self {
        Self {
            status,
            code,
            message: message.into(),
        }
    }
    pub fn invalid(m: impl Into<String>) -> Self {
        Self::new(400, "invalid_input", m)
    }
    pub fn conflict(m: impl Into<String>) -> Self {
        Self::new(409, "conflict", m)
    }
    pub fn hub(m: impl Into<String>) -> Self {
        Self::new(502, "hub_error", m)
    }
    pub fn prerequisite(m: impl Into<String>) -> Self {
        Self::new(503, "prerequisite_missing", m)
    }
    pub fn internal(m: impl Into<String>) -> Self {
        Self::new(500, "internal", m)
    }
}

/// How often `refresh_network` actually calls the hub: network capacity
/// changes slowly (network contract ยง5), so this is independent of, and much
/// slower than, `hub_poll`.
const NETWORK_POLL_INTERVAL: Duration = Duration::from_secs(60);

/// How long a good `network` answer is shown before `summary()` drops it: a
/// stale "4 busy" is worse than no number (network contract ยง5).
const NETWORK_STALE_AFTER: Duration = Duration::from_secs(5 * 60);

#[derive(Default)]
struct NetworkCache {
    /// The last successful answer, held through transient failures until it
    /// ages out (`NETWORK_STALE_AFTER`).
    last_good: Option<NetworkCapacity>,
    /// When `last_good` was fetched; drives the staleness check.
    fetched_at: Option<Instant>,
    /// When a poll was last attempted (success or failure); drives
    /// `NETWORK_POLL_INTERVAL` independently of whether it succeeded, so a
    /// failing hub is retried no more eagerly than a healthy one.
    attempted_at: Option<Instant>,
}

#[derive(Default)]
struct HubCache {
    last_good: Option<HubSummary>,
    fetched_at: Option<Instant>,
    last_ok: Option<String>,
    error: Option<String>,
    /// The next step for the last failure, when it has one (`HubError::detail`).
    error_detail: Option<String>,
    failures: u32,
    reachable: bool,
    unauthorized: bool,
    too_old: bool,
}

/// Lock order, where nested: `hub` before `desired`, `local_problems` and `mesh`.
/// `supervisor` is only ever taken alone, from the blocking reconcile thread.
pub struct Core {
    pub cfg: AgentConfig,
    node_pubkey: String,
    node_name: String,
    desired: Mutex<DesiredState>,
    hub: Mutex<HubCache>,
    /// The hub's `GET /api/status/network` answer (network contract ยง5),
    /// polled independently of, and far less often than, `hub`.
    network: Mutex<NetworkCache>,
    creds: Mutex<CredWatch>,
    local: Mutex<LocalView>,
    local_problems: Mutex<Vec<Problem>>,
    /// The mesh route and reachability from the last reconcile tick
    /// (`agent::mesh::mesh_status`).
    mesh: Mutex<MeshStatus>,
    /// The rolling hourly usage/earnings series behind the summary's
    /// `history` field (`agent::history`), sampled on every fresh hub poll.
    history: Mutex<History>,
    supervisor: Mutex<Supervisor>,
    /// Where the starting time zone for a summary poll comes from; a test can
    /// replace this with a fixed value instead of the real machine zone.
    tz_source: Mutex<Box<dyn Fn() -> String + Send + Sync>>,
    /// Once a summary poll gets a 422 for its zone, this session switches to
    /// `UTC` and every later poll goes straight there instead of trying again.
    tz_override: Mutex<Option<String>>,
    pub(crate) broker_unmanaged: AtomicBool,
    pub wake_reconcile: Notify,
    pub wake_hub: Notify,
    /// Shared with the `Supervisor` behind `supervisor` (see `Supervisor::stop_flag`).
    /// Set by `shutdown_children` before it takes the supervisor lock, so an
    /// in-flight reconcile tick blocked inside a `terminate` wait notices
    /// immediately and releases the lock instead of running out its grace
    /// period.
    stop_requested: Arc<AtomicBool>,
    /// True when this agent's workers are Docker containers rather than host
    /// processes (`ZAKURO_SHARE_RUNTIME`, issues #263, #387). Decided once, with the
    /// `SpawnSpec`, so a reconcile tick doesn't have to take the supervisor
    /// lock just to know which prerequisites apply.
    container_workers: bool,
}

impl Core {
    pub fn new(cfg: AgentConfig) -> std::io::Result<Arc<Self>> {
        files::ensure_dir(&cfg.dir)?;
        let desired =
            files::load_json::<DesiredState>(&cfg.dir.join(STATE_FILE)).unwrap_or_default();
        let spawn_spec = SpawnSpec::from_config(&cfg);
        let container_workers = spawn_spec.worker_backend != supervisor::WorkerBackend::Host;
        let mut sup = Supervisor::new(spawn_spec);
        if let Some(children) = files::load_json(&cfg.dir.join(CHILDREN_FILE)) {
            sup.adopt(&children, &supervisor::proc_start_time);
        }
        // Once, here, never per tick (#388). Container backend only: a host
        // backend agent must not remove a foreground `zc share`'s container.
        if container_workers {
            sup.sweep_orphans();
        }
        let stop_requested = sup.stop_flag();
        Ok(Arc::new(Self {
            node_pubkey: cfg.node_pubkey(),
            node_name: crate::broker::node_name_or_default(),
            desired: Mutex::new(desired),
            hub: Mutex::new(HubCache::default()),
            network: Mutex::new(NetworkCache::default()),
            creds: Mutex::new(CredWatch::new(cfg.state_dir.join("credentials"))),
            local: Mutex::new(LocalView::default()),
            local_problems: Mutex::new(vec![]),
            mesh: Mutex::new(MeshStatus::default()),
            history: Mutex::new(History::load(
                &cfg.dir.join(HISTORY_FILE),
                chrono::Utc::now(),
            )),
            supervisor: Mutex::new(sup),
            tz_source: Mutex::new(Box::new(hub::system_tz)),
            tz_override: Mutex::new(None),
            broker_unmanaged: AtomicBool::new(false),
            wake_reconcile: Notify::new(),
            wake_hub: Notify::new(),
            stop_requested,
            container_workers,
            cfg,
        }))
    }

    pub fn desired(&self) -> DesiredState {
        self.desired.lock().unwrap().clone()
    }

    pub fn hub_failures(&self) -> u32 {
        self.hub.lock().unwrap().failures
    }

    fn credentials(&self) -> Option<Credentials> {
        self.creds.lock().unwrap().current()
    }

    fn api_url(&self) -> String {
        self.credentials()
            .and_then(|c| c.api_url)
            .unwrap_or_else(|| self.cfg.api_url.clone())
    }

    fn client(&self) -> Option<HubClient> {
        let c = self.credentials()?;
        let base = c
            .api_url
            .clone()
            .unwrap_or_else(|| self.cfg.api_url.clone());
        Some(HubClient::new(
            &base,
            &c.api_key,
            self.cfg.timings.hub_timeout,
        ))
    }

    fn save_desired(&self, d: &DesiredState) -> Result<(), ApiError> {
        files::save_json(&self.cfg.dir.join(STATE_FILE), d)
            .map_err(|e| ApiError::internal(e.to_string()))
    }

    pub fn summary(&self) -> Summary {
        let logged_in = self.credentials().is_some();
        let api_url = self.api_url();
        let desired = self.desired();
        let mut local = self.local.lock().unwrap().clone();
        local.sharing = desired.sharing;
        local.workers.desired = desired.workers;
        local.workers.max = self.cfg.max_workers;

        let hub = self.hub.lock().unwrap();
        let mut problems = Vec::new();
        if !logged_in || hub.unauthorized {
            problems.push(Problem::new("not_logged_in"));
        } else if hub.too_old {
            problems.push(Problem::new("hub_too_old"));
        } else if hub.failures > 0 {
            let mut p = Problem::hub_unreachable(hub.last_good.is_some());
            p.detail = hub.error_detail.clone();
            problems.push(p);
        }
        for p in self.local_problems.lock().unwrap().iter() {
            if !problems.iter().any(|q| q.code == p.code) {
                problems.push(p.clone());
            }
        }
        let mut s = merge::build_summary(MergeInput {
            agent_version: env!("CARGO_PKG_VERSION"),
            now: chrono::Utc::now(),
            api_url: &api_url,
            hub: hub.last_good.as_ref(),
            hub_status: HubStatus {
                reachable: hub.reachable,
                last_ok: hub.last_ok.clone(),
                error: hub.error.clone(),
            },
            problems,
            node_pubkey: &self.node_pubkey,
            node_name: &self.node_name,
            local: &local,
            mesh: self.mesh.lock().unwrap().clone(),
        });
        s.history = self.history.lock().unwrap().to_wire();
        s.network = self.network_for_summary();
        s
    }

    /// The `network` field's value for `summary()`: the last good answer,
    /// unless it is older than `NETWORK_STALE_AFTER` (network contract ยง5) --
    /// a stale figure is dropped, not shown, and never zeroed either: absent
    /// is the only honest answer once it can no longer be trusted.
    fn network_for_summary(&self) -> Option<NetworkCapacity> {
        let n = self.network.lock().unwrap();
        let fresh = n
            .fetched_at
            .is_some_and(|t| t.elapsed() <= NETWORK_STALE_AFTER);
        fresh.then(|| n.last_good).flatten()
    }

    pub fn set_sharing(&self, on: bool) -> Result<Summary, ApiError> {
        if on && self.broker_unmanaged.load(Ordering::Relaxed) {
            return Err(ApiError::conflict(
                "a broker the agent didn't start is running on this Mac; run `zc down` so the agent can manage sharing",
            ));
        }
        {
            let mut d = self.desired.lock().unwrap();
            d.sharing = on;
            self.save_desired(&d)?;
        }
        self.wake_reconcile.notify_one();
        self.wake_hub.notify_one(); // spec ยง6.7: re-poll the hub right after every write
        Ok(self.summary())
    }

    /// A worker is draining: the run loop then ticks every `drain_poll` (1 s)
    /// instead of every `reconcile` (2 s), as spec ยง6.5 step 3 asks.
    pub fn is_draining(&self) -> bool {
        self.local.lock().unwrap().workers.draining > 0
    }

    pub fn set_workers(&self, count: u32) -> Result<Summary, ApiError> {
        if count > self.cfg.max_workers {
            return Err(ApiError::invalid(format!(
                "count must be between 0 and {}",
                self.cfg.max_workers
            )));
        }
        {
            let mut d = self.desired.lock().unwrap();
            d.workers = count;
            self.save_desired(&d)?;
        }
        self.wake_reconcile.notify_one();
        self.wake_hub.notify_one();
        Ok(self.summary())
    }

    /// Spec ยง6.7: `device` fans out to every one of this Mac's worker rows,
    /// `default` sets the account default. `None` clears the price.
    pub async fn set_price(&self, scope: &str, price: Option<f64>) -> Result<Summary, ApiError> {
        if scope != "device" && scope != "default" {
            return Err(ApiError::invalid(format!(
                r#"scope must be "device" or "default", got {scope:?}"#
            )));
        }
        let bounds = self
            .hub
            .lock()
            .unwrap()
            .last_good
            .as_ref()
            .map(HubSummary::bounds)
            .unwrap_or_default();
        if let Some(p) = price {
            if !p.is_finite() || p < bounds.min as f64 || p > bounds.max as f64 {
                return Err(ApiError::invalid(format!(
                    "price_per_hour must be between {} and {}",
                    bounds.min, bounds.max
                )));
            }
        }
        let client = self
            .client()
            .ok_or_else(|| ApiError::prerequisite("this Mac is not signed in: run `zc login`"))?;

        if scope == "default" {
            client
                .put_default_price(price)
                .await
                .map_err(|e| ApiError::hub(e.message()))?;
        } else {
            let stale = self
                .hub
                .lock()
                .unwrap()
                .fetched_at
                .is_none_or(|t| t.elapsed() > Duration::from_secs(120));
            if stale {
                self.refresh_hub().await;
            }
            let (ids, hub_error): (Vec<i64>, Option<String>) = {
                let h = self.hub.lock().unwrap();
                match h.last_good.as_ref() {
                    Some(summary) => (
                        summary
                            .this_mac_workers(&self.node_pubkey)
                            .iter()
                            .map(|w| w.id)
                            .collect(),
                        None,
                    ),
                    None => (vec![], h.error.clone()),
                }
            };
            if ids.is_empty() {
                // The hub never answered at all: say so, rather than telling
                // the owner to start sharing when this Mac may already be.
                if let Some(msg) = hub_error {
                    return Err(ApiError::hub(msg));
                }
                return Err(ApiError::conflict(
                    "this Mac has no workers on the hub yet: start sharing first",
                ));
            }
            hub::set_device_price(&client, &ids, price)
                .await
                .map_err(|failed| {
                    let detail: Vec<String> =
                        failed.iter().map(|(id, e)| format!("{id}: {e}")).collect();
                    ApiError::hub(format!(
                        "could not price {} worker(s): {}",
                        failed.len(),
                        detail.join("; ")
                    ))
                })?;
        }
        self.refresh_hub().await;
        Ok(self.summary())
    }

    /// The time zone this session sends with `GET /api/provide/summary`: the
    /// machine's own zone (or a test's stand-in) until the hub rejects it,
    /// then `UTC` for the rest of the run.
    fn tz_for_summary(&self) -> String {
        if let Some(tz) = self.tz_override.lock().unwrap().clone() {
            return tz;
        }
        (self.tz_source.lock().unwrap())()
    }

    /// Replace the starting time zone with a fixed value, so a test does not
    /// depend on the real machine's zone.
    #[cfg(test)]
    fn set_tz_source_for_test(&self, tz: &'static str) {
        *self.tz_source.lock().unwrap() = Box::new(move || tz.to_string());
    }

    /// Let a test drive a second `refresh_network` call immediately, instead
    /// of waiting out the real `NETWORK_POLL_INTERVAL`.
    #[cfg(test)]
    fn clear_network_poll_gate_for_test(&self) {
        self.network.lock().unwrap().attempted_at = None;
    }

    /// Let a test simulate a good `network` answer having aged past
    /// `NETWORK_STALE_AFTER`, without a real 5-minute wait.
    #[cfg(test)]
    fn age_network_fetch_for_test(&self, age: Duration) {
        if let Some(t) = self.network.lock().unwrap().fetched_at.as_mut() {
            *t = Instant::now() - age;
        }
    }

    /// Poll the hub once, fold the result into the cache, then seed prices on
    /// worker rows this Mac has never seen before (spec ยง6.7). A hub that
    /// answers a non-`UTC` zone with 422 is asked again, immediately, with
    /// `UTC`; once that happens every later poll in this run goes straight to
    /// `UTC`. A 422 on `UTC` itself is not retried.
    pub async fn refresh_hub(&self) {
        let Some(client) = self.client() else {
            let mut h = self.hub.lock().unwrap();
            h.reachable = false;
            h.error = Some("not signed in".to_string());
            return;
        };
        let tz = self.tz_for_summary();
        let mut result = client.summary(&tz).await;
        if tz != "UTC" && matches!(result, Err(HubError::Status(422, _))) {
            *self.tz_override.lock().unwrap() = Some("UTC".to_string());
            result = client.summary("UTC").await;
        }
        {
            let mut h = self.hub.lock().unwrap();
            match result {
                Ok(summary) => {
                    // Both gauges are known-fresh right here: this poll just
                    // reached the hub (`earnings.today`), and the local
                    // request count is read from the same snapshot the
                    // summary itself uses. Never sampled on the error branch
                    // below -- an unreachable hub must not invent a sample.
                    let requests_5h = self.local.lock().unwrap().requests.last_5h;
                    let credits_today = summary.earnings.today;
                    let path = self.cfg.dir.join(HISTORY_FILE);
                    let mut history = self.history.lock().unwrap();
                    history.record(chrono::Utc::now(), requests_5h, credits_today);
                    let _ = history.save(&path);
                    drop(history);

                    h.last_good = Some(summary);
                    h.fetched_at = Some(Instant::now());
                    h.last_ok =
                        Some(chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true));
                    h.error = None;
                    h.error_detail = None;
                    h.failures = 0;
                    h.reachable = true;
                    h.unauthorized = false;
                    h.too_old = false;
                }
                Err(e) => {
                    h.unauthorized = e == HubError::Unauthorized;
                    h.too_old = e == HubError::NotFound;
                    h.reachable = h.too_old; // a 404 is an old hub, not an unreachable one
                    h.error = Some(e.message());
                    h.error_detail = e.detail();
                    h.failures += 1;
                }
            }
        }
        self.seed_new_workers(&client).await;
    }

    /// Poll `GET /api/status/network` (network contract ยง5), at most once
    /// every `NETWORK_POLL_INTERVAL` regardless of whether that attempt
    /// succeeds -- a failing hub is not retried any more eagerly than a
    /// healthy one. Meant to be called from the same loop as `refresh_hub`
    /// (its cadence is already close to, and always at least,
    /// `NETWORK_POLL_INTERVAL`); this method enforces the interval itself so
    /// it stays correct even if that cadence ever changes.
    ///
    /// Any failure -- not signed in, unreachable, a non-2xx status (a 401
    /// from a hub that hasn't deployed this auth path yet included), or a
    /// body that doesn't parse -- leaves the cache exactly as it was: the
    /// last good value, if any, is held rather than blanked, and
    /// `network_for_summary` is the only place that ever drops it (once it
    /// is too old to trust).
    pub async fn refresh_network(&self) {
        {
            let n = self.network.lock().unwrap();
            if n.attempted_at
                .is_some_and(|t| t.elapsed() < NETWORK_POLL_INTERVAL)
            {
                return;
            }
        }
        let Some(client) = self.client() else {
            self.network.lock().unwrap().attempted_at = Some(Instant::now());
            return;
        };
        let result = client.network().await;
        let mut n = self.network.lock().unwrap();
        n.attempted_at = Some(Instant::now());
        if let Some(status) = result {
            n.last_good = Some(status);
            n.fetched_at = Some(Instant::now());
        }
    }

    /// A worker row this Mac has never seen before enters `known_worker_ids`
    /// once there is nothing left to do for it: either it was never a seed
    /// target (no agreed sibling price, or the row is already known), or its
    /// seed price write to the hub succeeded. A row whose seed write fails
    /// stays unknown, so the next poll tries to seed it again instead of
    /// quietly leaving it at the account default forever.
    async fn seed_new_workers(&self, client: &HubClient) {
        let (targets, all_ids) = {
            let h = self.hub.lock().unwrap();
            let Some(summary) = h.last_good.as_ref() else {
                return;
            };
            let mine = summary.this_mac_workers(&self.node_pubkey);
            let known = self.desired.lock().unwrap().known_worker_ids.clone();
            let min = summary.price_bounds.min;
            (
                hub::seed_targets(&mine, &known, min),
                mine.iter().map(|w| w.id).collect::<Vec<_>>(),
            )
        };
        let mut seeded = Vec::new();
        for (id, price) in &targets {
            match client.put_worker_price(*id, Some(*price)).await {
                Ok(()) => seeded.push(*id),
                Err(e) => eprintln!(
                    "  [AGENT] seeding price on worker row {id}: {}",
                    e.message()
                ),
            }
        }
        let target_ids: Vec<i64> = targets.iter().map(|(id, _)| *id).collect();
        let mut d = self.desired.lock().unwrap();
        let before = d.known_worker_ids.len();
        for id in all_ids {
            let now_known = !target_ids.contains(&id) || seeded.contains(&id);
            if now_known && !d.known_worker_ids.contains(&id) {
                d.known_worker_ids.push(id);
            }
        }
        if d.known_worker_ids.len() != before {
            let _ = files::save_json(&self.cfg.dir.join(STATE_FILE), &*d);
        }
        drop(d);
        if !seeded.is_empty() {
            self.wake_hub.notify_one(); // re-poll so the summary shows the seeded price
        }
    }

    /// One reconcile tick (spec ยง6.5). Blocking: run it on a blocking thread.
    ///
    /// Returns immediately, before touching the supervisor, once a shutdown
    /// has been requested: no tick may start (or restart) a child after
    /// `terminate_all` has begun taking them down.
    pub fn reconcile_once(&self) {
        if self.stop_requested.load(Ordering::Relaxed) {
            return;
        }
        let d = self.desired();
        let desired = Desired {
            sharing: d.sharing,
            workers: d.workers,
        };
        let path = std::env::var("PATH").unwrap_or_default();
        // Resolved fresh on every tick (a cheap file check), not once at
        // startup: a fresh clone, or an edited `<zc dir>/env`, must clear
        // `zakuro_dir_missing` on the very next tick, without a restart.
        // `state_dir` (never the process-global `credentials::dir()`),
        // `worker_dir_env` and `worker_dir_legacy_candidates` (all captured
        // once, from `from_env`) keep this independent of whatever the real
        // process environment or host `$HOME`/cwd/dev checkout happen to be.
        let zakuro_dir = crate::up::resolve_zakuro_dir_for(
            self.cfg.worker_dir_env.clone(),
            Some(&self.cfg.state_dir),
            &self.cfg.worker_dir_legacy_candidates,
        );
        let prerequisites = plan::prerequisite_problems(
            plan::find_in_path("uv", &path).is_some(),
            zakuro_dir.is_ok(),
            zakuro_dir.as_ref().err().and_then(|m| m.detail()),
            self.credentials().is_some(),
            self.cfg.worker_template_overridden,
            // Only probed at all on the container backend, and cached there:
            // `docker info` is a round trip to the daemon, and this runs
            // every two seconds.
            self.container_workers
                .then(crate::up::docker_cli_available_cached),
        );
        // Resolved every tick, like the zakuro dir: it's cheap (the host's
        // addresses, connection.json and one loopback connect), and a route
        // change must reach the broker without an agent restart.
        let route = crate::vpn::route();
        let now = Instant::now();
        let mut sup = self.supervisor.lock().unwrap();
        sup.set_worker_cwd(zakuro_dir.ok());
        sup.set_route(route.kind());
        let api = HttpBrokerApi {
            port: sup.broker_port(),
            worker_key: std::env::var("ZAKURO_WORKER_KEY").ok(),
        };
        sup.reconcile(&desired, &api, prerequisites.is_empty(), now);
        let mesh = crate::agent::mesh::mesh_status(&route, sup.broker_running(), sup.broker_port());
        let _ = files::save_json(&self.cfg.dir.join(CHILDREN_FILE), &sup.children());
        let mut problems = prerequisites;
        problems.extend(sup.problems(now));
        let view = sup.local_view(&desired, self.cfg.max_workers);
        self.broker_unmanaged
            .store(sup.broker_unmanaged(), Ordering::Relaxed);
        drop(sup);
        *self.local.lock().unwrap() = view;
        *self.local_problems.lock().unwrap() = problems;
        *self.mesh.lock().unwrap() = mesh;
    }

    /// Tell any in-flight reconcile tick to give up early on whatever
    /// `terminate` wait it is blocked in, instead of running out its full
    /// grace period. Safe to call repeatedly and from outside the supervisor
    /// lock; `shutdown_children` also sets this itself before it locks.
    pub fn request_stop(&self) {
        self.stop_requested.store(true, Ordering::Relaxed);
    }

    /// Agent SIGTERM: stop every child (no drain), then record that none remain.
    ///
    /// Sets the stop flag before taking the supervisor lock, so a reconcile
    /// tick that is currently blocked in a `terminate` wait (stopping the
    /// broker, killing a worker) returns immediately instead of running out
    /// its grace period, and this call does not sit behind it. The lock
    /// itself is taken with `unwrap_or_else` so a mutex a previous panic
    /// poisoned still yields its contents: children must still be signalled
    /// on the way out even after something else went wrong.
    pub fn shutdown_children(&self) {
        self.request_stop();
        let mut sup = self
            .supervisor
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        sup.terminate_all(self.cfg.timings.shutdown_wait);
        let _ = files::save_json(&self.cfg.dir.join(CHILDREN_FILE), &sup.children());
    }
}

#[cfg(test)]
pub(crate) mod tests {
    use super::*;
    use crate::agent::files::tests::tmp;
    use crate::agent::hub::tests::{mock_hub, Seen};

    fn block_on<F: std::future::Future>(f: F) -> F::Output {
        tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
            .unwrap()
            .block_on(f)
    }

    /// A Core on a fresh temp state dir, not signed in.
    pub(crate) fn core_with(max_workers: u32) -> Arc<Core> {
        let dir = tmp("core");
        std::fs::create_dir_all(&dir).unwrap();
        let mut cfg = AgentConfig::for_dirs(dir);
        cfg.max_workers = max_workers;
        Core::new(cfg).unwrap()
    }

    /// Write `~/.zakuro/credentials` pointing at `hub` (picked up by mtime).
    pub(crate) fn sign_in(core: &Core, hub: &str) {
        std::fs::write(
            core.cfg.state_dir.join("credentials"),
            format!("api_key=zk_1_test\napi_url={hub}\n"),
        )
        .unwrap();
    }

    /// A hub summary whose only device is the Mac with node key `pk`.
    pub(crate) fn hub_json(pk: &str, worker_rows: &str) -> String {
        format!(
            r#"{{"account":{{"username":"jean","email":"jean@zakuro-ai.com","credits_balance":1240.5}},"default_price_per_hour":null,"price_bounds":{{"min":1,"max":120,"step":1}},"earnings":{{"today":1.0,"last_7d":2.0,"tz":"UTC"}},"devices":[{{"node_pubkey":"{pk}","name":"mac","freshness":"fresh","last_seen_at":null,"workers":[{worker_rows}]}}],"web_base":"https://stg.hub.zakuro-ai.com"}}"#
        )
    }

    pub(crate) fn row(id: i64, price: Option<f64>) -> String {
        let p = price.map_or("null".to_string(), |p| p.to_string());
        let e = price.unwrap_or(3.6);
        format!(
            r#"{{"id":{id},"worker_id":"fp-w{id}","status":"online","last_seen":null,"price_per_hour":{p},"reported_price_per_hour":3.6,"effective_price_per_hour":{e},"disabled":false}}"#
        )
    }

    fn puts(seen: &Seen) -> Vec<(String, String)> {
        seen.lock()
            .unwrap()
            .iter()
            .filter(|e| e.0 == "PUT")
            .map(|e| (e.1.clone(), e.2.clone()))
            .collect()
    }

    #[test]
    fn workers_are_persisted_and_bounded_by_max() {
        let core = core_with(3);
        let s = core.set_workers(2).unwrap();
        assert_eq!((s.this_mac.workers.desired, s.this_mac.workers.max), (2, 3));
        let on_disk: DesiredState = files::load_json(&core.cfg.dir.join(STATE_FILE)).unwrap();
        assert_eq!(on_disk.workers, 2);
        let err = core.set_workers(4).unwrap_err();
        assert_eq!((err.status, err.code), (400, "invalid_input"));
    }

    #[test]
    fn sharing_on_is_refused_while_an_unmanaged_broker_runs() {
        let core = core_with(3);
        core.broker_unmanaged.store(true, Ordering::Relaxed);
        assert_eq!(core.set_sharing(true).unwrap_err().status, 409);
        assert!(!core.set_sharing(false).unwrap().this_mac.sharing);
        core.broker_unmanaged.store(false, Ordering::Relaxed);
        assert!(core.set_sharing(true).unwrap().this_mac.sharing);
    }

    #[test]
    fn before_sign_in_the_summary_says_not_logged_in() {
        let s = core_with(3).summary();
        assert!(s.account.is_none());
        assert_eq!(s.problems[0].code, "not_logged_in");
    }

    #[test]
    fn refresh_keeps_the_last_snapshot_and_names_the_problem() {
        let core = core_with(3);
        let pk = core.node_pubkey.clone();
        let status = Arc::new(Mutex::new(200u16));
        let st = status.clone();
        let (hub, _) = mock_hub(move |_, _, _| {
            let s = *st.lock().unwrap();
            (
                s,
                if s == 200 {
                    hub_json(&pk, &row(11, None))
                } else {
                    "{}".into()
                },
            )
        });
        sign_in(&core, &hub);

        block_on(core.refresh_hub());
        let s = core.summary();
        assert_eq!(s.account.as_ref().unwrap().username, "jean");
        assert!(s.devices.as_ref().unwrap()[0].this_mac);
        assert!(s.hub.reachable && s.problems.is_empty(), "{:?}", s.problems);

        *status.lock().unwrap() = 500;
        block_on(core.refresh_hub());
        let s = core.summary();
        assert!(!s.hub.reachable);
        assert!(s.account.is_some(), "the last good snapshot is kept");
        assert!(s.problems.iter().any(|p| p.code == "hub_unreachable"));
        assert_eq!(core.hub_failures(), 1);

        *status.lock().unwrap() = 404;
        block_on(core.refresh_hub());
        let s = core.summary();
        assert!(s.hub.reachable, "an old hub is still a reachable hub");
        assert!(s.problems.iter().any(|p| p.code == "hub_too_old"));

        *status.lock().unwrap() = 401;
        block_on(core.refresh_hub());
        assert!(core
            .summary()
            .problems
            .iter()
            .any(|p| p.code == "not_logged_in"));
    }

    /// A hub the agent can't connect to must say why, and what to do about
    /// it: the cause in `hub.error`, the next step in `problems[].detail`,
    /// which used to be null however the poll failed. A hub that answered is
    /// not a tunnel problem and keeps its detail null.
    #[test]
    fn an_unreachable_hub_carries_its_cause_and_its_next_step() {
        let core = core_with(3);
        sign_in(&core, "http://127.0.0.1:1");
        block_on(core.refresh_hub());
        let s = core.summary();
        let p = s
            .problems
            .iter()
            .find(|p| p.code == "hub_unreachable")
            .expect("the hub could not be reached");
        let detail = p.detail.as_deref().expect("a next step, not null");
        assert!(detail.to_lowercase().contains("vpn"), "{detail}");
        let error = s.hub.error.expect("the failure is recorded");
        assert!(
            error.to_lowercase().contains("connection refused"),
            "the cause, not just the url: {error}"
        );

        let answering = core_with(3);
        let (hub, _) = mock_hub(|_, _, _| (500, r#"{"detail":"boom"}"#.into()));
        sign_in(&answering, &hub);
        block_on(answering.refresh_hub());
        let s = answering.summary();
        let p = s
            .problems
            .iter()
            .find(|p| p.code == "hub_unreachable")
            .expect("a 500 is still an unreachable hub");
        assert_eq!(p.detail, None, "the hub answered: no tunnel to blame");
        assert_eq!(
            s.hub.error.as_deref(),
            Some("hub answered HTTP 500: boom"),
            "unchanged"
        );
    }

    /// "Showing the last known values" with an empty cache promises values
    /// that do not exist: this run has never had a good hub answer, so there
    /// is nothing but this Mac's own state. The hint says that instead, and
    /// goes back to the cached wording once one good answer has landed.
    #[test]
    fn the_unreachable_hint_promises_cached_values_only_when_there_are_some() {
        let fresh = core_with(3);
        sign_in(&fresh, "http://127.0.0.1:1");
        block_on(fresh.refresh_hub());
        let s = fresh.summary();
        let hint = s
            .problems
            .iter()
            .find(|p| p.code == "hub_unreachable")
            .and_then(|p| p.hint.clone())
            .expect("the hub could not be reached");
        assert!(
            hint.to_lowercase().contains("no cached values"),
            "nothing has ever been cached: {hint}"
        );
        assert!(
            s.account.is_none() && s.earnings.is_none() && s.devices.is_none(),
            "and there is indeed nothing to show"
        );

        let cached = core_with(3);
        let pk = cached.node_pubkey.clone();
        let status = Arc::new(Mutex::new(200u16));
        let st = status.clone();
        let (hub, _) = mock_hub(move |_, _, _| {
            let s = *st.lock().unwrap();
            (
                s,
                if s == 200 {
                    hub_json(&pk, &row(11, None))
                } else {
                    "{}".into()
                },
            )
        });
        sign_in(&cached, &hub);
        block_on(cached.refresh_hub());
        *status.lock().unwrap() = 500;
        block_on(cached.refresh_hub());
        let s = cached.summary();
        assert_eq!(
            s.problems
                .iter()
                .find(|p| p.code == "hub_unreachable")
                .and_then(|p| p.hint.as_deref()),
            Some("Showing the last known values"),
            "one good answer landed, and it is still shown"
        );
        assert!(s.account.is_some() && s.devices.is_some());
    }

    /// `refresh_network` fetches once, exposes the result as `summary().network`,
    /// and a second call inside the same poll interval makes no further
    /// request (network contract ยง5: "poll no more often than every 60s").
    #[test]
    fn network_is_polled_at_most_once_per_interval() {
        let core = core_with(3);
        let calls = Arc::new(Mutex::new(0u32));
        let c = calls.clone();
        let (hub, _) = mock_hub(move |_, url, _| match url {
            "/api/status/network" => {
                *c.lock().unwrap() += 1;
                (
                    200,
                    r#"{"workers": 5, "workers_busy": 2, "cpu_cores": 40, "cpu_cores_busy": 10,
                        "ram_gb": 200, "ram_gb_busy": 50, "gpus": 4, "gpus_busy": 1}"#
                        .to_string(),
                )
            }
            _ => (404, "{}".into()),
        });
        sign_in(&core, &hub);

        block_on(core.refresh_network());
        let network = core
            .summary()
            .network
            .expect("a successful poll populates network");
        assert_eq!((network.workers, network.workers_busy), (5, 2));
        assert_eq!((network.gpus, network.gpus_busy), (4, 1));

        block_on(core.refresh_network());
        assert_eq!(*calls.lock().unwrap(), 1, "the second call is within 60s");
    }

    /// A hub with no support for this endpoint yet (today's staging: a 401,
    /// since its side of this auth isn't deployed) must never break the rest
    /// of the summary, and must never surface as a `problems` entry the way
    /// `refresh_hub`'s 401 does -- an absent `network` section is not a
    /// login failure.
    #[test]
    fn a_network_401_is_silently_no_data_and_never_a_problem() {
        let core = core_with(3);
        let (hub, _) = mock_hub(|_, _, _| (401, "{}".into()));
        sign_in(&core, &hub);

        block_on(core.refresh_network());
        let s = core.summary();
        assert_eq!(s.network, None);
        assert!(!s.problems.iter().any(|p| p.code == "not_logged_in"));
    }

    /// A good answer survives a later transient failure (held, not blanked),
    /// then is dropped once it is more than 5 minutes old -- a stale "2 busy"
    /// is worse than no number (network contract ยง5).
    #[test]
    fn network_holds_the_last_good_value_then_drops_it_once_stale() {
        let core = core_with(3);
        let healthy = Arc::new(Mutex::new(true));
        let h = healthy.clone();
        let (hub, _) = mock_hub(move |_, url, _| match url {
            "/api/status/network" if *h.lock().unwrap() => (
                200,
                r#"{"workers": 10, "workers_busy": 3, "cpu_cores": 80, "cpu_cores_busy": 20,
                    "ram_gb": 400, "ram_gb_busy": 100, "gpus": 6, "gpus_busy": 2}"#
                    .to_string(),
            ),
            _ => (401, "{}".into()),
        });
        sign_in(&core, &hub);

        block_on(core.refresh_network());
        assert!(core.summary().network.is_some());

        // A later poll fails; the last good value is still shown.
        *healthy.lock().unwrap() = false;
        core.clear_network_poll_gate_for_test();
        block_on(core.refresh_network());
        let network = core
            .summary()
            .network
            .expect("a transient failure holds the last good value");
        assert_eq!(network.workers, 10);

        // Once that value is more than 5 minutes old, it is dropped instead
        // of being shown stale.
        core.age_network_fetch_for_test(Duration::from_secs(301));
        assert_eq!(
            core.summary().network,
            None,
            "a stale figure is worse than no number"
        );
    }

    #[test]
    fn device_price_fans_out_then_new_rows_are_seeded() {
        let core = core_with(3);
        let pk = core.node_pubkey.clone();
        let rows = Arc::new(Mutex::new(format!("{},{}", row(11, None), row(12, None))));
        let r = rows.clone();
        let (hub, seen) = mock_hub(move |method, url, _| match method {
            "GET" if url.starts_with("/api/provide/summary") => {
                (200, hub_json(&pk, &r.lock().unwrap()))
            }
            "PUT" => (200, "{}".into()),
            _ => (404, "{}".into()),
        });
        sign_in(&core, &hub);
        block_on(core.refresh_hub());
        assert_eq!(core.desired().known_worker_ids, vec![11, 12]);

        block_on(core.set_price("device", Some(18.0))).unwrap();
        let body = r#"{"price_per_hour":18.0}"#.to_string();
        // The fan-out is concurrent, so the rows arrive in either order.
        let mut fanned_out = puts(&seen);
        fanned_out.sort();
        assert_eq!(
            fanned_out,
            vec![
                ("/api/workers/11/price".to_string(), body.clone()),
                ("/api/workers/12/price".to_string(), body.clone()),
            ]
        );

        // A scale-up created row 13; the hub shows 11 and 12 priced.
        *rows.lock().unwrap() = format!(
            "{},{},{}",
            row(11, Some(18.0)),
            row(12, Some(18.0)),
            row(13, None)
        );
        block_on(core.refresh_hub());
        assert_eq!(
            puts(&seen).last().unwrap(),
            &("/api/workers/13/price".to_string(), body)
        );
        assert_eq!(core.desired().known_worker_ids, vec![11, 12, 13]);
    }

    #[test]
    fn price_writes_are_validated_before_touching_the_hub() {
        let core = core_with(3);
        let status = |r: Result<Summary, ApiError>| r.unwrap_err().status;
        assert_eq!(status(block_on(core.set_price("bogus", Some(10.0)))), 400);
        assert_eq!(
            status(block_on(core.set_price("device", Some(500.0)))),
            400,
            "outside {{1,120}}"
        );
        assert_eq!(status(block_on(core.set_price("default", Some(0.5)))), 400);
        assert_eq!(
            status(block_on(core.set_price("default", Some(10.0)))),
            503,
            "not signed in"
        );
        // A hub that can't even be reached or decoded leaves no snapshot at
        // all: that's a hub problem, not "this Mac has no workers yet".
        let (hub, _) = mock_hub(|_, _, _| (200, "{}".into()));
        sign_in(&core, &hub);
        assert_eq!(
            status(block_on(core.set_price("device", Some(10.0)))),
            502,
            "the hub never produced a usable snapshot"
        );
    }

    #[test]
    fn a_price_write_gets_409_only_once_the_hub_confirms_this_mac_has_no_workers() {
        let core = core_with(3);
        let pk = core.node_pubkey.clone();
        let (hub, _) = mock_hub(move |_, _, _| (200, hub_json(&pk, "")));
        sign_in(&core, &hub);
        let err = block_on(core.set_price("device", Some(10.0))).unwrap_err();
        assert_eq!(err.status, 409);
    }

    /// A row whose seed price write fails stays unknown, so the very next
    /// poll tries to seed it again instead of leaving it at the account
    /// default forever.
    #[test]
    fn a_failed_seed_put_keeps_the_row_unknown_until_it_succeeds() {
        let core = core_with(3);
        let pk = core.node_pubkey.clone();
        let rows = Arc::new(Mutex::new(format!(
            "{},{}",
            row(11, Some(18.0)),
            row(12, Some(18.0))
        )));
        let r = rows.clone();
        let (hub, seen) = mock_hub(move |method, url, nth| match method {
            "GET" if url.starts_with("/api/provide/summary") => {
                (200, hub_json(&pk, &r.lock().unwrap()))
            }
            "PUT" if url == "/api/workers/13/price" && nth == 1 => (500, "{}".into()),
            "PUT" => (200, "{}".into()),
            _ => (404, "{}".into()),
        });
        sign_in(&core, &hub);
        block_on(core.refresh_hub());
        assert_eq!(core.desired().known_worker_ids, vec![11, 12]);

        *rows.lock().unwrap() = format!(
            "{},{},{}",
            row(11, Some(18.0)),
            row(12, Some(18.0)),
            row(13, None)
        );
        block_on(core.refresh_hub());
        assert_eq!(
            core.desired().known_worker_ids,
            vec![11, 12],
            "the failed seed keeps row 13 unknown"
        );
        assert!(puts(&seen)
            .iter()
            .any(|(u, _)| u == "/api/workers/13/price"));

        block_on(core.refresh_hub());
        assert_eq!(
            core.desired().known_worker_ids,
            vec![11, 12, 13],
            "the retried seed succeeds and 13 becomes known"
        );
    }

    /// The mock starts by rejecting every zone but `UTC` with 422, mirroring
    /// a hub that has never heard of the local zone.
    #[test]
    fn a_422_on_the_local_zone_retries_once_with_utc_then_sticks_to_it() {
        let core = core_with(3);
        core.set_tz_source_for_test("Asia/Tokyo");
        let pk = core.node_pubkey.clone();
        let requested_tz: TzLog = Default::default();
        let seen = requested_tz.clone();
        let (hub, _) = mock_hub(move |_, url, _| {
            let raw = url.split("tz=").nth(1).unwrap_or("");
            let tz = raw.replace("%2F", "/");
            seen.lock().unwrap().push(tz.clone());
            if tz == "UTC" {
                (200, hub_json(&pk, &row(11, None)))
            } else {
                (422, "{}".into())
            }
        });
        sign_in(&core, &hub);

        block_on(core.refresh_hub());
        let s = core.summary();
        assert!(s.hub.reachable, "{:?}", s.problems);
        assert!(s.account.is_some());
        assert_eq!(
            *requested_tz.lock().unwrap(),
            vec!["Asia/Tokyo".to_string(), "UTC".to_string()],
            "exactly one retry, with UTC"
        );

        requested_tz.lock().unwrap().clear();
        block_on(core.refresh_hub());
        assert_eq!(
            *requested_tz.lock().unwrap(),
            vec!["UTC".to_string()],
            "later polls go straight to UTC"
        );
    }

    /// A hub that rejects `UTC` itself is not retried: there is nowhere left
    /// to fall back to.
    #[test]
    fn a_422_on_utc_itself_is_not_retried() {
        let core = core_with(3);
        core.set_tz_source_for_test("UTC");
        let calls = Arc::new(Mutex::new(0u32));
        let c = calls.clone();
        let (hub, _) = mock_hub(move |_, _, _| {
            *c.lock().unwrap() += 1;
            (422, "{}".into())
        });
        sign_in(&core, &hub);

        block_on(core.refresh_hub());
        assert_eq!(
            *calls.lock().unwrap(),
            1,
            "no retry when the zone is already UTC"
        );
        assert!(!core.summary().hub.reachable);
    }

    type TzLog = Arc<Mutex<Vec<String>>>;

    /// `zakuro_dir_missing` is resolved fresh on every reconcile tick, not
    /// once at startup: a fresh clone appearing under `<zc dir>/zak-zakuro`
    /// clears the problem on the very next tick, no restart needed.
    /// `sharing` stays off throughout, so this never spawns a real broker or
    /// worker -- `reconcile_once` only ever checks/records the prerequisite.
    #[test]
    fn zakuro_dir_missing_clears_on_the_next_tick_once_the_directory_appears() {
        // `AgentConfig::for_dirs` leaves `worker_dir_legacy_candidates` empty
        // and `reconcile_once` resolves against `cfg.state_dir` (never the
        // process-global `credentials::dir()`, `$HOME` or the cwd), so this
        // is deterministic on any host, whatever checkouts exist there, and
        // mutates no environment variable -- no `HOME_ENV_LOCK` needed.
        let dir = tmp("zakuro-dir-appears");
        std::fs::create_dir_all(&dir).unwrap();
        let cfg = AgentConfig::for_dirs(dir.clone());
        let core = Core::new(cfg).unwrap();

        core.reconcile_once();
        assert!(
            core.summary()
                .problems
                .iter()
                .any(|p| p.code == "zakuro_dir_missing"),
            "no zak-zakuro directory exists yet"
        );

        std::fs::create_dir_all(dir.join("zak-zakuro/zakuro/worker")).unwrap();
        std::fs::write(dir.join("zak-zakuro/zakuro/worker/server.py"), b"").unwrap();
        core.reconcile_once();
        assert!(
            !core
                .summary()
                .problems
                .iter()
                .any(|p| p.code == "zakuro_dir_missing"),
            "the very next tick must see the freshly cloned directory"
        );
    }

    /// On the container runtime the image carries the interpreter and the
    /// zakuro source, so a missing checkout is not a problem there. The
    /// runtime is forced to `container` (never left to Docker probing), so
    /// this holds whether or not the host has Docker.
    #[test]
    fn container_runtime_does_not_require_the_zakuro_dir() {
        let dir = tmp("zakuro-dir-container");
        std::fs::create_dir_all(&dir).unwrap();
        let mut cfg = AgentConfig::for_dirs(dir);
        cfg.child_env
            .push(("ZAKURO_SHARE_RUNTIME".into(), "container".into()));
        let core = Core::new(cfg).unwrap();
        core.reconcile_once();
        let codes: Vec<_> = core
            .summary()
            .problems
            .iter()
            .map(|p| p.code.clone())
            .collect();
        assert!(
            !codes
                .iter()
                .any(|c| c == "zakuro_dir_missing" || c == "uv_missing"),
            "{codes:?}"
        );
    }
}