zc2 0.0.46

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
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
//! 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::events::EventBus;
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::jobs::{self, Journal};
use crate::agent::merge::{self, LocalView, MergeInput};
use crate::agent::offers::{self, GpuProbe, OfferApiError};
use crate::agent::plan::{self, Desired};
use crate::agent::summary::{HubStatus, MeshStatus, NetworkCapacity, Problem, Summary};
use crate::agent::summary_v2::{self, Ledger, LedgerPeriod, SummaryV2};
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)
    }
}

/// The used `zakuro://` action ids, next to `state.json`.
pub const HANDOFF_SEEN_FILE: &str = "handoff_seen.json";

/// How often `refresh_ledger` calls the hub's earnings route: the ledger
/// moves with jobs, but a minute-old figure is fine on a summary screen.
const LEDGER_POLL_INTERVAL: Duration = Duration::from_secs(60);

#[derive(Default)]
struct LedgerCache {
    last_good: Option<Ledger>,
    attempted_at: Option<Instant>,
}

/// What `publish_changes` last told `/v2/events` subscribers about.
#[derive(Default)]
struct Published {
    /// The last summary v2 published, minus its timestamps.
    summary: Option<serde_json::Value>,
    problems: Vec<String>,
}

/// 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>,
}

/// How old the hub summary may be when it decides admin-only access.
const ADMIN_FRESH: Duration = Duration::from_secs(60);

#[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,
    /// The `/v2/events` stream (ADR ZC-0019 §3).
    pub events: EventBus,
    /// Jobs this node ran or runs (`agent::jobs`).
    jobs: Mutex<Journal>,
    /// The hub's ledger totals for summary v2.
    ledger: Mutex<LedgerCache>,
    published: Mutex<Published>,
    /// How `/v2/offers` learns this machine's GPUs; replaceable in tests.
    gpu_probe: Arc<GpuProbe>,
    /// The last GPU enumeration that answered. A probe that times out is not
    /// cached, so the next call asks again.
    gpus: Mutex<Option<Vec<crate::bench_node::fingerprint::GpuId>>>,
    /// Verified `zakuro://` links waiting for their click, and the used ids
    /// (ADR ZC-0020 §4).
    handoffs: Mutex<crate::deeplink::Handoffs>,
    /// Tests only: the action keys and account to verify links against,
    /// instead of the profile and the hub.
    #[cfg(test)]
    handoff_test: Mutex<Option<(Vec<crate::deeplink::TrustedKey>, Option<String>)>>,
}

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,
            events: EventBus::new(),
            jobs: Mutex::new(Journal::load(&cfg.dir)),
            ledger: Mutex::new(LedgerCache::default()),
            published: Mutex::new(Published::default()),
            gpu_probe: Arc::new(offers::real_probe()),
            gpus: Mutex::new(None),
            handoffs: Mutex::new(crate::deeplink::Handoffs::new(Some(
                cfg.dir.join(HANDOFF_SEEN_FILE),
            ))),
            #[cfg(test)]
            handoff_test: Mutex::new(None),
            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
    }

    /// Summary v2 (ADR ZC-0019 §4): summary v1 plus nodes, jobs and ledger.
    pub fn summary_v2(&self) -> SummaryV2 {
        let since = chrono::Utc::now() - chrono::Duration::hours(24);
        let jobs = {
            let j = self.jobs.lock().unwrap();
            summary_v2::Jobs {
                live: j.live(),
                done_24h: j.done_since(since) as u32,
            }
        };
        summary_v2::build(
            self.summary(),
            summary_v2::Extras {
                backend: if self.container_workers {
                    "container"
                } else {
                    "host"
                },
                jobs,
                ledger: self.ledger.lock().unwrap().last_good.clone(),
            },
        )
    }

    /// The signed-in account's `zakuro_user_id`, as the hub last reported it.
    fn account_sub(&self) -> Option<String> {
        self.credentials()?;
        let hub = self.hub.lock().unwrap();
        hub.last_good
            .as_ref()
            .and_then(|h| h.account.zakuro_user_id.clone())
            .filter(|s| !s.trim().is_empty())
    }

    /// `POST /v2/handoff`: verify a `zakuro://` link and describe it.
    pub fn handoff(
        &self,
        link: &str,
    ) -> Result<crate::deeplink::Preview, crate::deeplink::LinkError> {
        use crate::deeplink::{self, Context, LinkError};
        let env = deeplink::env_for_api_url(Some(&self.api_url()));
        #[allow(unused_mut)]
        let mut keys = deeplink::keys_for(env).map_err(LinkError::KeyConfig)?;
        #[allow(unused_mut)]
        let mut sub = self.account_sub();
        #[cfg(test)]
        if let Some((k, s)) = self.handoff_test.lock().unwrap().clone() {
            keys = k;
            sub = s;
        }
        let node_fp = crate::broker::node_identity::fingerprint_of_pubkey_b64(&self.node_pubkey)
            .unwrap_or_default();
        let ctx = Context {
            keys: &keys,
            env: env.name(),
            account_sub: sub.as_deref(),
            node_fp: &node_fp,
            node_pubkey: &self.node_pubkey,
            now: chrono::Utc::now().timestamp(),
        };
        self.handoffs
            .lock()
            .unwrap()
            .open(link, &ctx, &deeplink::ISSUES)
    }

    #[cfg(test)]
    pub(crate) fn set_handoff_test(
        &self,
        keys: Vec<crate::deeplink::TrustedKey>,
        sub: Option<&str>,
    ) {
        *self.handoff_test.lock().unwrap() = Some((keys, sub.map(str::to_string)));
    }

    /// This node's base64 public key.
    pub fn node_pubkey(&self) -> &str {
        &self.node_pubkey
    }

    /// `POST /v2/handoff/{jti}/confirm`: run the verified action, once.
    pub fn handoff_confirm(
        &self,
        jti: &str,
    ) -> Result<crate::deeplink::Confirmed, crate::deeplink::ConfirmError> {
        self.handoffs
            .lock()
            .unwrap()
            .confirm(jti, chrono::Utc::now().timestamp())
    }

    /// `GET /v2/jobs`.
    pub fn jobs(&self, q: &jobs::Query) -> Vec<jobs::Job> {
        self.jobs.lock().unwrap().query(q)
    }

    /// Tell `/v2/events` subscribers what changed since the last call:
    /// `problem.raised` / `problem.cleared` per problem code, then one
    /// `summary.changed` carrying the new summary v2 when anything in it
    /// moved (timestamps aside). Called after every reconcile tick, hub poll
    /// and write, so a change reaches the app within one tick.
    pub fn publish_changes(&self) {
        let summary = self.summary_v2();
        let mut wire = serde_json::to_value(&summary).unwrap_or_default();
        let codes: Vec<String> = summary.problems.iter().map(|p| p.code.clone()).collect();
        let mut published = self.published.lock().unwrap();
        for p in &summary.problems {
            if !published.problems.contains(&p.code) {
                self.events.publish(
                    "problem.raised",
                    serde_json::to_value(p).unwrap_or_default(),
                );
            }
        }
        for code in &published.problems {
            if !codes.contains(code) {
                self.events
                    .publish("problem.cleared", serde_json::json!({ "code": code }));
            }
        }
        published.problems = codes;
        let full = wire.clone();
        if let Some(o) = wire.as_object_mut() {
            o.remove("as_of");
            if let Some(hub) = o.get_mut("hub").and_then(|h| h.as_object_mut()) {
                hub.remove("last_ok");
            }
            if let Some(l) = o.get_mut("ledger").and_then(|l| l.as_object_mut()) {
                l.remove("as_of");
            }
        }
        if published.summary.as_ref() != Some(&wire) {
            published.summary = Some(wire);
            self.events.publish("summary.changed", full);
        }
    }

    /// Poll the hub's `GET /api/provide/earnings` for the ledger totals, at
    /// most once every `LEDGER_POLL_INTERVAL`. A failure keeps the last good
    /// value: the ledger is informative, and `hub` already carries the error.
    pub async fn refresh_ledger(&self) {
        {
            let l = self.ledger.lock().unwrap();
            if l.attempted_at
                .is_some_and(|t| t.elapsed() < LEDGER_POLL_INTERVAL)
            {
                return;
            }
        }
        let Some(client) = self.client() else {
            self.ledger.lock().unwrap().attempted_at = Some(Instant::now());
            return;
        };
        let result = client.earnings(&self.tz_for_summary()).await;
        let mut l = self.ledger.lock().unwrap();
        l.attempted_at = Some(Instant::now());
        if let Ok(e) = result {
            l.last_good = Some(Ledger {
                unit: "jpy".into(),
                today: LedgerPeriod {
                    earned: e.today,
                    spent: None,
                    by_source: None,
                },
                month: LedgerPeriod {
                    earned: e.month.earned,
                    spent: Some(e.month.spent),
                    by_source: None,
                },
                tz: e.tz,
                days: e
                    .week
                    .iter()
                    .map(|d| summary_v2::LedgerDay {
                        date: d.date.clone(),
                        earned: d.earned,
                    })
                    .collect(),
                prev_month_earned: e.month.prev_month_earned,
                as_of: chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true),
            });
        }
    }

    /// 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
        self.publish_changes();
        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();
        self.publish_changes();
        Ok(self.summary())
    }

    /// This machine's GPUs, or `None` while unknown. Enumeration calls into
    /// the driver, so it runs off the async threads.
    async fn gpus(&self) -> Option<Vec<crate::bench_node::fingerprint::GpuId>> {
        if let Some(g) = self.gpus.lock().unwrap().clone() {
            return Some(g);
        }
        let probe = self.gpu_probe.clone();
        let found = tokio::task::spawn_blocking(move || probe()).await.ok()??;
        *self.gpus.lock().unwrap() = Some(found.clone());
        Some(found)
    }

    fn offers_client(&self) -> Result<HubClient, OfferApiError> {
        self.client().ok_or_else(|| {
            OfferApiError::new(
                409,
                "not_logged_in",
                "this Mac is not signed in: run `zc login`",
            )
        })
    }

    fn offer_error(e: hub::OfferError) -> OfferApiError {
        match e {
            hub::OfferError::Unreachable(m) => OfferApiError::new(
                502,
                "hub_unreachable",
                format!("could not reach the hub: {m}"),
            ),
            // The hub refusing our key is "not signed in", not an agent 401
            // (that status means the local token is wrong).
            hub::OfferError::Rejected { status: 401, .. } => OfferApiError::new(
                409,
                "not_logged_in",
                "the hub rejected this Mac's key: run `zc login`",
            ),
            hub::OfferError::Rejected {
                status,
                code,
                message,
            } => OfferApiError::new(
                status,
                code.unwrap_or_else(|| "hub_error".to_string()),
                message,
            ),
        }
    }

    /// Whether the signed-in hub account is an admin, as of the last minute.
    ///
    /// Fails closed. Signed out, or the hub's last answer was a 401 (key
    /// revoked): not an admin. Otherwise the cached summary counts only while
    /// it is younger than [`ADMIN_FRESH`]; an older one is re-fetched, and when
    /// that fetch doesn't succeed the answer is no. So a demotion, a revoked
    /// key or a logout closes `/v2/logs` within a minute, not at the next
    /// restart.
    pub async fn is_admin(&self) -> bool {
        if self.credentials().is_none() {
            return false;
        }
        let fresh_admin = |c: &Core| -> Option<bool> {
            let h = c.hub.lock().unwrap();
            if h.unauthorized {
                return Some(false);
            }
            let fresh = h.fetched_at.is_some_and(|t| t.elapsed() < ADMIN_FRESH);
            fresh.then(|| h.last_good.as_ref().is_some_and(|s| s.account.is_admin))
        };
        if let Some(a) = fresh_admin(self) {
            return a;
        }
        self.refresh_hub().await;
        fresh_admin(self).unwrap_or(false)
    }

    /// `GET /v2/offers`: the hub's catalogue for this node, each offer with
    /// `fits` / `fit_reason` for this machine's hardware.
    pub async fn offers(&self) -> Result<serde_json::Value, OfferApiError> {
        let client = self.offers_client()?;
        let mut body = client
            .offers(&self.node_pubkey)
            .await
            .map_err(Self::offer_error)?;
        offers::annotate_all(&mut body, self.gpus().await.as_deref());
        Ok(body)
    }

    /// `PUT /v2/offers/{template_id}`: forwards `body` with this node added.
    pub async fn put_offer(
        &self,
        template_id: &str,
        mut body: serde_json::Value,
    ) -> Result<serde_json::Value, OfferApiError> {
        let client = self.offers_client()?;
        body["node"] = serde_json::Value::String(self.node_pubkey.clone());
        let mut offer = client
            .put_offer(template_id, &body)
            .await
            .map_err(Self::offer_error)?;
        offers::annotate_offer(&mut offer, self.gpus().await.as_deref());
        Ok(offer)
    }

    /// 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;
        self.publish_changes();
        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 earned_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, earned_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 observed = sup.observed_workers();
        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;
        let job_events = self
            .jobs
            .lock()
            .unwrap()
            .observe(observed.as_deref(), chrono::Utc::now());
        for e in job_events {
            self.events
                .publish(e.kind, serde_json::to_value(&e.job).unwrap_or_default());
        }
        self.publish_changes();
    }

    /// 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)
    }

    /// Replace the GPU probe (a test must not enumerate the real machine).
    pub(crate) fn set_gpu_probe(core: &mut Arc<Core>, p: GpuProbe) {
        Arc::get_mut(core).expect("core not shared yet").gpu_probe = Arc::new(p);
    }

    /// 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()
    }

    /// A signed-in core whose hub says `is_admin: true` on the first summary
    /// and then answers each later one with `later(status, is_admin)`.
    fn admin_then(later: (u16, bool)) -> Arc<Core> {
        let core = core_with(0);
        let pk = core.cfg.node_pubkey();
        let body = move |admin: bool| {
            hub_json(&pk, "").replace(
                r#""balance":1240.5}"#,
                &format!(r#""balance":1240.5,"is_admin":{admin}}}"#),
            )
        };
        let (hub, _) = crate::agent::hub::tests::mock_hub(move |_, url, nth| {
            if !url.starts_with("/api/provide/summary") {
                return (404, "{}".into());
            }
            match nth {
                1 => (200, body(true)),
                _ => (
                    later.0,
                    if later.0 == 200 {
                        body(later.1)
                    } else {
                        "{}".into()
                    },
                ),
            }
        });
        sign_in(&core, &hub);
        core
    }

    /// Make the cached hub summary look `by` old.
    fn age_hub(core: &Core, by: Duration) {
        let mut h = core.hub.lock().unwrap();
        h.fetched_at = h.fetched_at.map(|t| t - by);
    }

    #[test]
    fn a_demoted_admin_loses_access_once_the_summary_is_a_minute_old() {
        let core = admin_then((200, false));
        assert!(block_on(core.is_admin()));
        assert!(block_on(core.is_admin()), "a fresh summary is reused");
        age_hub(&core, ADMIN_FRESH);
        assert!(!block_on(core.is_admin()));
    }

    #[test]
    fn a_revoked_key_or_an_unreachable_hub_is_not_an_admin() {
        for (status, what) in [(401, "revoked key"), (503, "hub down")] {
            let core = admin_then((status, true));
            assert!(block_on(core.is_admin()), "{what}");
            age_hub(&core, ADMIN_FRESH);
            assert!(
                !block_on(core.is_admin()),
                "{what}: stale cache must not count"
            );
        }
    }

    #[test]
    fn signing_out_ends_admin_access_at_once() {
        let core = admin_then((200, true));
        assert!(block_on(core.is_admin()));
        std::fs::remove_file(core.cfg.state_dir.join("credentials")).unwrap();
        assert!(!block_on(core.is_admin()));
    }

    /// 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","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 the_ledger_comes_from_the_hubs_earnings_and_survives_a_failure() {
        let core = core_with(3);
        assert!(
            core.summary_v2().ledger.is_none(),
            "null until the hub answers"
        );
        let fail = Arc::new(AtomicBool::new(false));
        let f = fail.clone();
        let (hub, seen) = mock_hub(move |_, url, _| {
            if url.starts_with("/api/provide/earnings") && !f.load(Ordering::Relaxed) {
                (
                    200,
                    r#"{"goal_per_day": null, "today": 4.5, "streak_days": 0, "always_on_days": 0,
                        "week": [], "month": {"earned": 120.25, "spent": 30.0, "balance": 900.0,
                        "prev_month_earned": 0.0}, "did": [], "tz": "UTC"}"#
                        .to_string(),
                )
            } else {
                (500, "{}".into())
            }
        });
        sign_in(&core, &hub);
        core.set_tz_source_for_test("UTC");
        block_on(core.refresh_ledger());
        let l = core
            .summary_v2()
            .ledger
            .expect("ledger after a good answer");
        assert_eq!((l.today.earned, l.today.spent), (4.5, None));
        assert_eq!((l.month.earned, l.month.spent), (120.25, Some(30.0)));
        assert_eq!((l.unit.as_str(), l.tz.as_str()), ("jpy", "UTC"));
        assert!(seen
            .lock()
            .unwrap()
            .iter()
            .any(|e| e.1 == "/api/provide/earnings?tz=UTC"));

        fail.store(true, Ordering::Relaxed);
        core.ledger.lock().unwrap().attempted_at = None;
        block_on(core.refresh_ledger());
        assert_eq!(
            core.summary_v2().ledger.map(|l| l.month.spent),
            Some(Some(30.0)),
            "a failed poll keeps the last good ledger"
        );
    }

    #[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:?}"
        );
    }
}