zc2 0.0.48

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
//! `policy.toml` (ADR ZC-0017, zc#514): the one place that says what this
//! node will run for other people.
//!
//! The file lives at `$ZAKURO_HOME/policy.toml`. The agent, the CLI and the
//! broker all read and write it through this module, under one OS file lock
//! (`policy.lock`), with an atomic replace and a `revision` that only goes up.
//!
//! | module | what |
//! |---|---|
//! | [`schedule`] | `sharing.schedule` windows (`"mon-fri 19:00-08:00"`, local time) |
//! | [`migrate`] | the first-load migration from the old switches (ADR §6) |
//! | [`admit`] | the one admission check and the refusal counters (ADR §5) |
//! | [`sync`] | the hub round trip: `policy` in the register payload and reply |
//! | [`cli`] | `zc policy`, `zc budget` |

pub mod admit;
pub mod cli;
pub mod migrate;
pub mod owner;
pub mod schedule;
pub mod sync;

use crate::sandbox::{self, Amount, Gpus, HostResources};
use serde::de::Deserializer;
use serde::{Deserialize, Serialize, Serializer};
use serde_json::{json, Value};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant, SystemTime};

pub use admit::Admission;

/// The one public squad (ADR ZC-0017, MKT zak-marketplace#714).
pub const PUBLIC_SQUAD: &str = "public";
pub const POLICY_FILE: &str = "policy.toml";
const LOCK_FILE: &str = "policy.lock";

/// The Atelier backends a list may name.
pub const ATELIER_BACKENDS: [&str; 2] = ["peft", "ludwig"];

pub fn path(home: &Path) -> PathBuf {
    home.join(POLICY_FILE)
}

// ---- the document -----------------------------------------------------------

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct Policy {
    pub version: u32,
    /// Bumped on every change; the hub compares it (ADR §4).
    pub revision: u64,
    pub sharing: Sharing,
    pub budget: BudgetSpec,
    pub workloads: Workloads,
    pub runtime: RuntimeCfg,
    pub cleanup: Cleanup,
    pub upstreams: Upstreams,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct Sharing {
    /// Squad ids this node serves; `"public"` is the one public squad. Empty
    /// = no foreign work.
    pub squads: Vec<String>,
    /// `idle` | `always` | `schedule`.
    pub when: String,
    /// Windows for `when = "schedule"`, local time.
    pub schedule: Vec<String>,
    pub min_price: MinPrice,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct BudgetSpec {
    /// Cores, or a percentage of logical CPUs.
    #[serde(deserialize_with = "string_or_number")]
    pub cpu: String,
    /// A size or a percentage. On Apple Silicon this covers RAM and GPU
    /// memory together.
    #[serde(deserialize_with = "string_or_number")]
    pub memory: String,
    pub gpu: bool,
    /// The VRAM ceiling the hub may place against (`"0"` = none).
    #[serde(deserialize_with = "string_or_number")]
    pub vram: String,
    #[serde(deserialize_with = "string_or_number")]
    pub disk: String,
    /// Take jobs only on AC power (enforced by the host-runner watchdog).
    pub on_ac_only: bool,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct Workloads {
    pub environments: bool,
    pub spaces: bool,
    pub hub_serving: bool,
    pub atelier: Atelier,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct RuntimeCfg {
    pub prefer: Vec<String>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct Cleanup {
    /// Images unused for this long are removed (`7d`, `36h`, `90m`).
    pub idle_ttl: String,
}

/// Reserved for later (ADR 0017 is the contract): where jobs may come from.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct Upstreams {
    pub hub: bool,
    pub peers: Vec<String>,
}

/// `"default"` (the account default) | a number of yen per hour | `-1`
/// (withdrawn: no foreign work at any price).
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum MinPrice {
    Default,
    PerHour(f64),
    Withdrawn,
}

impl Serialize for MinPrice {
    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
        match self {
            MinPrice::Default => s.serialize_str("default"),
            MinPrice::PerHour(p) => s.serialize_f64(*p),
            MinPrice::Withdrawn => s.serialize_i64(-1),
        }
    }
}

impl<'de> Deserialize<'de> for MinPrice {
    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
        #[derive(Deserialize)]
        #[serde(untagged)]
        enum Raw {
            S(String),
            I(i64),
            F(f64),
        }
        match Raw::deserialize(d)? {
            Raw::S(s) if s.trim().eq_ignore_ascii_case("default") => Ok(MinPrice::Default),
            Raw::S(s) => Err(serde::de::Error::custom(format!(
                "min_price {s:?}: use \"default\", a price per hour, or -1"
            ))),
            Raw::I(-1) => Ok(MinPrice::Withdrawn),
            Raw::I(n) => Ok(MinPrice::PerHour(n as f64)),
            Raw::F(-1.0) => Ok(MinPrice::Withdrawn),
            Raw::F(f) => Ok(MinPrice::PerHour(f)),
        }
    }
}

/// `workloads.atelier`: `true | false | "gpu-only" | [backend names]`.
#[derive(Debug, Clone, PartialEq)]
pub enum Atelier {
    On,
    Off,
    /// On, but only when the budget grants a GPU.
    GpuOnly,
    Backends(Vec<String>),
}

impl Serialize for Atelier {
    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
        match self {
            Atelier::On => s.serialize_bool(true),
            Atelier::Off => s.serialize_bool(false),
            Atelier::GpuOnly => s.serialize_str("gpu-only"),
            Atelier::Backends(v) => v.serialize(s),
        }
    }
}

impl<'de> Deserialize<'de> for Atelier {
    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
        #[derive(Deserialize)]
        #[serde(untagged)]
        enum Raw {
            B(bool),
            S(String),
            L(Vec<String>),
        }
        match Raw::deserialize(d)? {
            Raw::B(true) => Ok(Atelier::On),
            Raw::B(false) => Ok(Atelier::Off),
            Raw::S(s) if s == "gpu-only" => Ok(Atelier::GpuOnly),
            Raw::S(s) => Err(serde::de::Error::custom(format!(
                "workloads.atelier {s:?}: use true, false, \"gpu-only\" or a list of backends"
            ))),
            Raw::L(v) => Ok(Atelier::Backends(v)),
        }
    }
}

fn string_or_number<'de, D: Deserializer<'de>>(d: D) -> Result<String, D::Error> {
    #[derive(Deserialize)]
    #[serde(untagged)]
    enum Raw {
        S(String),
        I(i64),
        F(f64),
    }
    Ok(match Raw::deserialize(d)? {
        Raw::S(s) => s,
        Raw::I(n) => n.to_string(),
        Raw::F(f) => f.to_string(),
    })
}

fn default_prefer() -> Vec<String> {
    let v: &[&str] = if cfg!(target_os = "macos") {
        &["lima", "docker"]
    } else {
        &["lxc", "docker"]
    };
    v.iter().map(|s| s.to_string()).collect()
}

impl Default for Policy {
    fn default() -> Self {
        Self {
            version: 1,
            revision: 0,
            sharing: Sharing::default(),
            budget: BudgetSpec::default(),
            workloads: Workloads::default(),
            runtime: RuntimeCfg::default(),
            cleanup: Cleanup::default(),
            upstreams: Upstreams::default(),
        }
    }
}

impl Default for Sharing {
    fn default() -> Self {
        Self {
            squads: vec![PUBLIC_SQUAD.to_string()],
            when: "idle".into(),
            schedule: Vec::new(),
            min_price: MinPrice::Default,
        }
    }
}

impl Default for BudgetSpec {
    fn default() -> Self {
        Self {
            cpu: "50%".into(),
            memory: "50%".into(),
            // On by default (approved desktop hosted-runners design D2,
            // 2026-11-10; amends ZC-0017 §3). Only hardware that has a GPU
            // lends one, and admission still applies per job.
            gpu: true,
            vram: "0".into(),
            disk: "50G".into(),
            on_ac_only: true,
        }
    }
}

impl Default for Workloads {
    fn default() -> Self {
        Self {
            environments: true,
            spaces: true,
            hub_serving: true,
            // Every Atelier backend this machine supports (design D2).
            atelier: Atelier::On,
        }
    }
}

impl Default for RuntimeCfg {
    fn default() -> Self {
        Self {
            prefer: default_prefer(),
        }
    }
}

impl Default for Cleanup {
    fn default() -> Self {
        Self {
            idle_ttl: "7d".into(),
        }
    }
}

impl Default for Upstreams {
    fn default() -> Self {
        Self {
            hub: true,
            peers: Vec::new(),
        }
    }
}

// ---- validation and conversions ---------------------------------------------

/// `0`, or a size such as `8G`.
fn parse_vram(v: &str) -> Result<u64, String> {
    let t = v.trim();
    if t == "0" || t.is_empty() {
        return Ok(0);
    }
    match sandbox::parse_memory(t)? {
        Amount::Absolute(n) => Ok(n as u64),
        Amount::Percent(_) => Err(format!("{t:?}: give a size such as 8G, not a percentage")),
    }
}

/// `7d`, `36h`, `90m`, `600s`.
pub fn parse_ttl(v: &str) -> Result<Duration, String> {
    let v = v.trim();
    let (num, unit) = v.split_at(v.len().saturating_sub(1));
    let mult = match unit {
        "d" => 86_400,
        "h" => 3_600,
        "m" => 60,
        "s" => 1,
        _ => return Err(format!("{v:?}: use 7d, 36h, 90m or 600s")),
    };
    num.parse::<u64>()
        .ok()
        .filter(|n| *n > 0)
        .map(|n| Duration::from_secs(n * mult))
        .ok_or_else(|| format!("{v:?}: use 7d, 36h, 90m or 600s"))
}

impl Policy {
    /// Everything that can be checked without the hardware. The error names
    /// the key.
    pub fn validate(&self) -> Result<(), String> {
        if self.version != 1 {
            return Err(format!(
                "version = {}: only version 1 is known",
                self.version
            ));
        }
        let mut seen = std::collections::HashSet::new();
        for s in &self.sharing.squads {
            if s.trim().is_empty() || s.len() > 64 || s.contains(char::is_whitespace) {
                return Err(format!("sharing.squads: {s:?} is not a squad id"));
            }
            if !seen.insert(s) {
                return Err(format!("sharing.squads: {s:?} is listed twice"));
            }
        }
        if !matches!(self.sharing.when.as_str(), "idle" | "always" | "schedule") {
            return Err(format!(
                "sharing.when = {:?}: use idle, always or schedule",
                self.sharing.when
            ));
        }
        for w in &self.sharing.schedule {
            schedule::parse_window(w).map_err(|e| format!("sharing.schedule: {e}"))?;
        }
        if let MinPrice::PerHour(p) = self.sharing.min_price {
            if !p.is_finite() || p < 0.0 {
                return Err(format!(
                    "sharing.min_price = {p}: a price per hour is >= 0 (or -1 to withdraw)"
                ));
            }
        }
        sandbox::parse_cpu(&self.budget.cpu).map_err(|e| format!("budget.cpu: {e}"))?;
        sandbox::parse_memory(&self.budget.memory).map_err(|e| format!("budget.memory: {e}"))?;
        parse_vram(&self.budget.vram).map_err(|e| format!("budget.vram: {e}"))?;
        match sandbox::parse_memory(&self.budget.disk).map_err(|e| format!("budget.disk: {e}"))? {
            Amount::Absolute(n) if n >= (1u64 << 30) as f64 => {}
            Amount::Absolute(_) => {
                return Err("budget.disk: below the 1 GiB minimum for the sandbox disk".into())
            }
            Amount::Percent(_) => {
                return Err("budget.disk: give a size such as 50G, not a percentage".into())
            }
        }
        if let Atelier::Backends(list) = &self.workloads.atelier {
            for b in list {
                if !ATELIER_BACKENDS.contains(&b.as_str()) {
                    return Err(format!(
                        "workloads.atelier: unknown backend {b:?} (known: {})",
                        ATELIER_BACKENDS.join(", ")
                    ));
                }
            }
        }
        for r in &self.runtime.prefer {
            if sandbox::RuntimeKind::parse(r).is_none() {
                return Err(format!("runtime.prefer: unknown runtime {r:?}"));
            }
        }
        parse_ttl(&self.cleanup.idle_ttl).map_err(|e| format!("cleanup.idle_ttl: {e}"))?;
        for p in &self.upstreams.peers {
            if p.trim().is_empty() {
                return Err("upstreams.peers: an empty entry".into());
            }
        }
        Ok(())
    }

    /// [`validate`](Self::validate), plus what this hardware cannot give: a
    /// budget past the machine is refused (a hub-staged policy is checked
    /// the same way before it is applied).
    pub fn validate_for(&self, host: &HostResources) -> Result<(), String> {
        self.validate()?;
        if let Amount::Absolute(c) = sandbox::parse_cpu(&self.budget.cpu)? {
            if c > host.logical_cpus.max(1) as f64 {
                return Err(format!(
                    "budget.cpu = {}: this machine has {} logical CPUs",
                    self.budget.cpu, host.logical_cpus
                ));
            }
        }
        if let (Amount::Absolute(m), Some(total)) = (
            sandbox::parse_memory(&self.budget.memory)?,
            host.memory_bytes,
        ) {
            if m > total as f64 {
                return Err(format!(
                    "budget.memory = {}: this machine has {} bytes",
                    self.budget.memory, total
                ));
            }
        }
        Ok(())
    }

    /// The `[budget]` section as the sandbox's [`sandbox::Budget`].
    pub fn sandbox_budget(&self) -> Result<sandbox::Budget, String> {
        let disk_bytes = match sandbox::parse_memory(&self.budget.disk)
            .map_err(|e| format!("budget.disk: {e}"))?
        {
            Amount::Absolute(n) => n as u64,
            Amount::Percent(_) => {
                return Err("budget.disk: give a size such as 50G, not a percentage".into())
            }
        };
        Ok(sandbox::Budget {
            cpu: sandbox::parse_cpu(&self.budget.cpu).map_err(|e| format!("budget.cpu: {e}"))?,
            memory: sandbox::parse_memory(&self.budget.memory)
                .map_err(|e| format!("budget.memory: {e}"))?,
            gpu: if self.budget.gpu {
                Gpus::All
            } else {
                Gpus::None
            },
            disk_bytes,
        })
    }

    /// The effective budget: this file, then the deprecated `ZAKURO_BUDGET_*`
    /// variables over it (they still win when set).
    pub fn effective_budget(
        &self,
        get: &dyn Fn(&str) -> Option<String>,
    ) -> Result<sandbox::Budget, String> {
        sandbox::Budget::from_env_over(self.sandbox_budget()?, get)
    }

    /// `workloads.atelier` as the backends it enables, given the ones this
    /// machine supports.
    pub fn atelier_backends(&self, supported: &[String]) -> Vec<String> {
        match &self.workloads.atelier {
            Atelier::Off => Vec::new(),
            Atelier::On | Atelier::GpuOnly => supported.to_vec(),
            Atelier::Backends(v) => v.clone(),
        }
    }

    /// The document as the hub's `policy` object (register payload). The
    /// hub knows `atelier` as `true | false | "gpu-only"` only, so a backend
    /// list is sent as on/off.
    pub fn to_hub_json(&self) -> Value {
        let atelier = match &self.workloads.atelier {
            Atelier::Backends(v) if v.is_empty() => json!(false),
            Atelier::Backends(_) => json!(true),
            other => serde_json::to_value(other).unwrap_or(json!(false)),
        };
        json!({
            "version": self.version,
            "revision": self.revision,
            "sharing": {
                "squads": self.sharing.squads,
                "when": self.sharing.when,
                "schedule": self.sharing.schedule,
                "min_price": self.sharing.min_price,
            },
            "budget": {
                "cpu": self.budget.cpu,
                "memory": self.budget.memory,
                "gpu": self.budget.gpu,
                "vram": self.budget.vram,
                "disk": self.budget.disk,
            },
            "workloads": {
                "environments": self.workloads.environments,
                "spaces": self.workloads.spaces,
                "hub_serving": self.workloads.hub_serving,
                "atelier": atelier,
            },
            "runtime": { "prefer": self.runtime.prefer },
        })
    }

    pub fn idle_ttl(&self) -> Result<Duration, String> {
        parse_ttl(&self.cleanup.idle_ttl).map_err(|e| format!("cleanup.idle_ttl={e}"))
    }

    /// The policy with `patch` merged over it: objects merge key by key,
    /// everything else replaces. An unknown key is an error naming it. A
    /// `revision` in the patch is the caller's expectation, not a value to
    /// set, and is left to the caller to compare.
    pub fn merged(&self, patch: &Value) -> Result<Policy, String> {
        let mut base = serde_json::to_value(self).map_err(|e| e.to_string())?;
        let mut patch = patch.clone();
        if let Some(o) = patch.as_object_mut() {
            o.remove("revision");
        }
        merge_json(&mut base, &patch);
        serde_json::from_value(base).map_err(|e| e.to_string())
    }

    /// Equal apart from the revision.
    pub fn same_content(&self, other: &Policy) -> bool {
        let mut a = self.clone();
        a.revision = other.revision;
        a == *other
    }
}

fn merge_json(base: &mut Value, patch: &Value) {
    match (base, patch) {
        (Value::Object(b), Value::Object(p)) => {
            for (k, v) in p {
                match b.get_mut(k) {
                    Some(slot) if slot.is_object() && v.is_object() => merge_json(slot, v),
                    _ => {
                        b.insert(k.clone(), v.clone());
                    }
                }
            }
        }
        (b, p) => *b = p.clone(),
    }
}

/// `body` reduced to the keys this version knows, for a policy a newer hub
/// staged: the node itself refuses unknown keys in its own file, but a hub
/// that learned a key first must not stall the node (ADR 0017 / hub notes).
pub fn known_keys_only(body: &Value) -> Value {
    fn walk(template: &Value, v: &Value) -> Value {
        match (template, v) {
            (Value::Object(t), Value::Object(o)) => {
                let mut out = serde_json::Map::new();
                for (k, val) in o {
                    if let Some(sub) = t.get(k) {
                        out.insert(k.clone(), walk(sub, val));
                    }
                }
                Value::Object(out)
            }
            _ => v.clone(),
        }
    }
    let template = serde_json::to_value(Policy::default()).unwrap_or(Value::Null);
    walk(&template, body)
}

// ---- the store --------------------------------------------------------------

/// The advisory lock every writer holds (agent, CLI, broker).
pub struct Lock {
    #[cfg(unix)]
    file: std::fs::File,
}

#[cfg(unix)]
impl Drop for Lock {
    fn drop(&mut self) {
        use std::os::unix::io::AsRawFd;
        // SAFETY: flock on a descriptor this struct owns.
        unsafe { libc::flock(self.file.as_raw_fd(), libc::LOCK_UN) };
    }
}

/// Take the policy lock, waiting up to five seconds. Non-unix builds have no
/// agent and a single writer, so they do not lock.
pub fn lock(home: &Path) -> Result<Lock, String> {
    std::fs::create_dir_all(home).map_err(|e| format!("{}: {e}", home.display()))?;
    #[cfg(unix)]
    {
        use std::os::unix::io::AsRawFd;
        let p = home.join(LOCK_FILE);
        let file = std::fs::OpenOptions::new()
            .create(true)
            .truncate(false)
            .write(true)
            .open(&p)
            .map_err(|e| format!("{}: {e}", p.display()))?;
        let deadline = Instant::now() + Duration::from_secs(5);
        loop {
            // SAFETY: flock on a descriptor this function owns.
            let rc = unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) };
            if rc == 0 {
                return Ok(Lock { file });
            }
            if Instant::now() >= deadline {
                return Err(format!(
                    "{}: another zc process holds the policy lock",
                    p.display()
                ));
            }
            std::thread::sleep(Duration::from_millis(25));
        }
    }
    #[cfg(not(unix))]
    {
        Ok(Lock {})
    }
}

fn read_file(home: &Path) -> Result<Option<Policy>, String> {
    let p = path(home);
    match std::fs::read_to_string(&p) {
        Ok(s) => toml::from_str::<Policy>(&s)
            .map(Some)
            .map_err(|e| format!("{}: {e}", p.display())),
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
        Err(e) => Err(format!("{}: {e}", p.display())),
    }
}

/// The saved policy without creating anything: `None` before the first load.
pub fn peek(home: &Path) -> Option<Policy> {
    read_file(home).ok().flatten()
}

const HEADER: &str =
    "# Zakuro sharing policy (ADR ZC-0017). One file decides what this node runs\n\
# for other people. Change it with `zc policy set <key>=<value>`, `zc budget`\n\
# or the app; `revision` is bumped by every change.\n\n";

/// Atomic write (temp file + rename), mode 0600. The caller holds the lock.
fn write_file(home: &Path, p: &Policy) -> Result<(), String> {
    let dest = path(home);
    let body = toml::to_string_pretty(p).map_err(|e| e.to_string())?;
    let tmp = home.join(format!(".policy.toml.{}", std::process::id()));
    {
        use std::io::Write;
        let mut opts = std::fs::OpenOptions::new();
        opts.write(true).create(true).truncate(true);
        #[cfg(unix)]
        {
            use std::os::unix::fs::OpenOptionsExt;
            opts.mode(0o600);
        }
        let mut f = opts
            .open(&tmp)
            .map_err(|e| format!("{}: {e}", tmp.display()))?;
        f.write_all(HEADER.as_bytes()).map_err(|e| e.to_string())?;
        f.write_all(body.as_bytes()).map_err(|e| e.to_string())?;
        f.sync_all().map_err(|e| e.to_string())?;
    }
    std::fs::rename(&tmp, &dest).map_err(|e| format!("{}: {e}", dest.display()))
}

/// The policy at `home`. With no file yet, one is generated from what the
/// node already has (ADR §6, [`migrate`]) and saved at revision 1.
pub fn load(home: &Path) -> Result<Policy, String> {
    if let Some(p) = read_file(home)? {
        return Ok(p);
    }
    let _guard = lock(home)?;
    // Another process may have created it while this one waited.
    if let Some(p) = read_file(home)? {
        return Ok(p);
    }
    let mut p = migrate::from_legacy(&migrate::Legacy::read(home, &|k| std::env::var(k).ok()))?;
    p.revision = 1;
    write_file(home, &p)?;
    migrate::retire_hosting_toml(home);
    Ok(p)
}

#[derive(Debug, Clone, PartialEq)]
pub enum UpdateError {
    /// The caller's `revision` is not the current one.
    Stale {
        current: u64,
    },
    Invalid(String),
    Io(String),
}

impl std::fmt::Display for UpdateError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            UpdateError::Stale { current } => write!(
                f,
                "the policy changed since you read it (revision is now {current}); read it again"
            ),
            UpdateError::Invalid(m) | UpdateError::Io(m) => f.write_str(m),
        }
    }
}

/// Change the policy under the lock: `f` edits a copy, the result is
/// validated (and checked against `host` when given), and when it differs the
/// revision goes up by one and the file is replaced atomically. Returns the
/// stored policy and whether anything changed. `expected` is the revision the
/// caller read, `None` for "whatever is there".
pub fn update(
    home: &Path,
    expected: Option<u64>,
    host: Option<&HostResources>,
    f: impl FnOnce(&mut Policy) -> Result<(), String>,
) -> Result<(Policy, bool), UpdateError> {
    // `load` takes the lock itself on first use; do it before ours.
    let current = load(home).map_err(UpdateError::Io)?;
    let _guard = lock(home).map_err(UpdateError::Io)?;
    // Re-read under the lock: this is the value the revision check is about.
    let current = read_file(home).map_err(UpdateError::Io)?.unwrap_or(current);
    if let Some(e) = expected {
        if e != current.revision {
            return Err(UpdateError::Stale {
                current: current.revision,
            });
        }
    }
    let mut next = current.clone();
    f(&mut next).map_err(UpdateError::Invalid)?;
    match host {
        Some(h) => next.validate_for(h),
        None => next.validate(),
    }
    .map_err(UpdateError::Invalid)?;
    if next.same_content(&current) {
        return Ok((current, false));
    }
    next.revision = current.revision + 1;
    write_file(home, &next).map_err(UpdateError::Io)?;
    Ok((next, true))
}

/// [`update`] with a partial JSON document (the `PUT /v2/policy` body). Its
/// `revision`, when present, is the expected one.
pub fn update_partial(
    home: &Path,
    patch: &Value,
    host: Option<&HostResources>,
) -> Result<(Policy, bool), UpdateError> {
    let expected = patch.get("revision").and_then(Value::as_u64);
    update(home, expected, host, |p| {
        *p = p.merged(patch)?;
        Ok(())
    })
}

/// Store a policy the hub staged: it must carry a revision above the local
/// one and pass validation against `host`. The revision is kept as the hub
/// sent it, so the next register reports it back and the hub clears its
/// desired copy. `Ok(None)` when it is not newer.
pub fn apply_desired(
    home: &Path,
    desired: &Value,
    host: &HostResources,
) -> Result<Option<Policy>, String> {
    let Some(rev) = desired.get("revision").and_then(Value::as_u64) else {
        return Err("the staged policy has no revision".into());
    };
    let current = load(home)?;
    if rev <= current.revision {
        return Ok(None);
    }
    let _guard = lock(home)?;
    let current = read_file(home)?.unwrap_or(current);
    if rev <= current.revision {
        return Ok(None);
    }
    let mut next = current.merged(&known_keys_only(desired))?;
    next.revision = rev;
    next.validate_for(host)?;
    write_file(home, &next)?;
    Ok(Some(next))
}

// ---- the live view ------------------------------------------------------------

/// The policy as the long-running processes read it: cached, re-read when the
/// file's mtime moves (a stat at most once a second), and the last good value
/// kept when the file stops parsing.
pub struct Live {
    home: Mutex<PathBuf>,
    inner: Mutex<LiveInner>,
    pinned: Mutex<Option<Arc<Policy>>>,
}

struct LiveInner {
    policy: Option<Arc<Policy>>,
    mtime: Option<SystemTime>,
    home: Option<PathBuf>,
    checked: Option<Instant>,
    warned: bool,
}

const RECHECK: Duration = Duration::from_secs(1);

impl Live {
    /// Reads `credentials::dir()` on every call, so a process that moves
    /// `ZAKURO_HOME` is followed.
    pub fn process() -> Self {
        Self::at(PathBuf::new())
    }

    pub fn at(home: PathBuf) -> Self {
        Self {
            home: Mutex::new(home),
            inner: Mutex::new(LiveInner {
                policy: None,
                mtime: None,
                home: None,
                checked: None,
                warned: false,
            }),
            pinned: Mutex::new(None),
        }
    }

    /// Tests: serve exactly this policy, never the file.
    pub fn pin(&self, p: Policy) {
        *self.pinned.lock().unwrap_or_else(|e| e.into_inner()) = Some(Arc::new(p));
    }

    fn home(&self) -> Option<PathBuf> {
        let h = self.home.lock().unwrap_or_else(|e| e.into_inner()).clone();
        if h.as_os_str().is_empty() {
            crate::credentials::dir()
        } else {
            Some(h)
        }
    }

    pub fn current(&self) -> Arc<Policy> {
        if let Some(p) = self
            .pinned
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .clone()
        {
            return p;
        }
        let Some(home) = self.home() else {
            return Arc::new(Policy::default());
        };
        let mut g = self.inner.lock().unwrap_or_else(|e| e.into_inner());
        let moved = g.home.as_deref() != Some(home.as_path());
        let due = g.checked.is_none_or(|t| t.elapsed() >= RECHECK);
        if g.policy.is_some() && !moved && !due {
            return g.policy.clone().unwrap();
        }
        g.checked = Some(Instant::now());
        let mtime = std::fs::metadata(path(&home))
            .and_then(|m| m.modified())
            .ok();
        if g.policy.is_some() && !moved && mtime == g.mtime {
            return g.policy.clone().unwrap();
        }
        match load(&home) {
            Ok(p) => {
                g.policy = Some(Arc::new(p));
                g.mtime = std::fs::metadata(path(&home))
                    .and_then(|m| m.modified())
                    .ok();
                g.home = Some(home);
                g.warned = false;
            }
            Err(e) => {
                if !g.warned {
                    eprintln!("  [POLICY] {e} -- keeping the last good policy");
                    g.warned = true;
                }
                if g.policy.is_none() || moved {
                    g.policy = Some(Arc::new(Policy::default()));
                    g.home = Some(home);
                }
            }
        }
        g.policy.clone().unwrap()
    }
}

/// The node budget from the policy file at `home` and the environment over
/// it, as one [`sandbox::Limits`]. A deprecated `ZAKURO_BUDGET_*` that is set
/// is mentioned once.
pub fn node_budget(
    home: Option<&Path>,
    get: &dyn Fn(&str) -> Option<String>,
) -> Result<sandbox::Budget, String> {
    let base = match home {
        Some(h) => load(h)?,
        None => Policy::default(),
    };
    warn_env_budget_once(get);
    base.effective_budget(get)
}

/// Env names that still override `[budget]`.
pub const ENV_BUDGET: [&str; 4] = [
    "ZAKURO_BUDGET_CPU",
    "ZAKURO_BUDGET_MEMORY",
    "ZAKURO_BUDGET_GPU",
    "ZAKURO_BUDGET_DISK",
];

pub fn env_budget_overrides(get: &dyn Fn(&str) -> Option<String>) -> Vec<&'static str> {
    ENV_BUDGET
        .iter()
        .copied()
        .filter(|k| get(k).is_some_and(|v| !v.trim().is_empty()))
        .collect()
}

fn warn_env_budget_once(get: &dyn Fn(&str) -> Option<String>) {
    static ONCE: std::sync::Once = std::sync::Once::new();
    let set = env_budget_overrides(get);
    if !set.is_empty() {
        ONCE.call_once(|| {
            eprintln!(
                "  [POLICY] {} set: deprecated, [budget] in policy.toml is the setting now \
                 (the variable still wins while it is set)",
                set.join(", ")
            );
        });
    }
}

// ---- tests ----------------------------------------------------------------

#[cfg(test)]
pub(crate) fn test_home() -> PathBuf {
    let d = std::env::temp_dir().join(format!(
        "zc-policy-{}-{}",
        std::process::id(),
        SystemTime::now()
            .duration_since(SystemTime::UNIX_EPOCH)
            .unwrap()
            .as_nanos()
    ));
    std::fs::create_dir_all(&d).unwrap();
    d
}

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

    fn host() -> HostResources {
        HostResources {
            logical_cpus: 8,
            memory_bytes: Some(16 << 30),
        }
    }

    #[test]
    fn a_fresh_node_gets_the_adr_defaults() {
        let home = test_home();
        let p = load(&home).unwrap();
        assert_eq!(p.revision, 1);
        assert_eq!(p.sharing.squads, vec!["public".to_string()]);
        assert_eq!(p.sharing.when, "idle");
        assert_eq!(p.sharing.min_price, MinPrice::Default);
        assert_eq!(
            (p.budget.cpu.as_str(), p.budget.memory.as_str()),
            ("50%", "50%")
        );
        assert!(p.budget.gpu, "design D2: GPU sharing on by default");
        assert!(p.workloads.environments && p.workloads.spaces && p.workloads.hub_serving);
        assert_eq!(p.workloads.atelier, Atelier::On);
        assert!(p.upstreams.hub && p.upstreams.peers.is_empty());
        // And it is on disk, readable back.
        assert_eq!(read_file(&home).unwrap().unwrap(), p);
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let mode = std::fs::metadata(path(&home)).unwrap().permissions().mode();
            assert_eq!(mode & 0o777, 0o600);
        }
    }

    #[test]
    fn the_defaults_file_round_trips_as_toml() {
        let text = toml::to_string_pretty(&Policy::default()).unwrap();
        let back: Policy = toml::from_str(&text).unwrap();
        assert_eq!(back, Policy::default());
        assert!(text.contains("atelier = true"), "{text}");
        assert!(text.contains("min_price = \"default\""), "{text}");
    }

    #[test]
    fn an_unknown_key_is_an_error_naming_it() {
        for (doc, key) in [
            ("version = 1\nfoo = 2\n", "foo"),
            ("[sharing]\nsquad = [\"public\"]\n", "squad"),
            ("[budget]\ncores = 2\n", "cores"),
            ("[upstreams]\nmesh = true\n", "mesh"),
        ] {
            let e = toml::from_str::<Policy>(doc).unwrap_err().to_string();
            assert!(e.contains(key), "{e}");
        }
        let home = test_home();
        std::fs::write(path(&home), "[workloads]\nbogus = true\n").unwrap();
        let e = load(&home).unwrap_err();
        assert!(e.contains("bogus") && e.contains("policy.toml"), "{e}");
    }

    #[test]
    fn min_price_and_atelier_accept_every_documented_form() {
        let p: Policy =
            toml::from_str("[sharing]\nmin_price = 2.5\n[workloads]\natelier = [\"peft\"]\n")
                .unwrap();
        assert_eq!(p.sharing.min_price, MinPrice::PerHour(2.5));
        assert_eq!(p.workloads.atelier, Atelier::Backends(vec!["peft".into()]));
        let p: Policy =
            toml::from_str("[sharing]\nmin_price = -1\n[workloads]\natelier = false\n").unwrap();
        assert_eq!(p.sharing.min_price, MinPrice::Withdrawn);
        assert_eq!(p.workloads.atelier, Atelier::Off);
        let p: Policy =
            toml::from_str("[sharing]\nmin_price = 3\n[workloads]\natelier = true\n").unwrap();
        assert_eq!(p.sharing.min_price, MinPrice::PerHour(3.0));
        assert_eq!(p.workloads.atelier, Atelier::On);
        assert!(toml::from_str::<Policy>("[sharing]\nmin_price = \"cheap\"\n").is_err());
        assert!(toml::from_str::<Policy>("[workloads]\natelier = \"sometimes\"\n").is_err());
    }

    #[test]
    fn a_budget_given_as_a_number_is_kept_as_text() {
        let p: Policy = toml::from_str("[budget]\ncpu = 4\nmemory = 8589934592\n").unwrap();
        assert_eq!(p.budget.cpu, "4");
        assert!(p.validate().is_ok());
    }

    #[test]
    fn validation_names_the_key() {
        let mut p = Policy::default();
        p.sharing.when = "sometimes".into();
        assert!(p.validate().unwrap_err().contains("sharing.when"));
        let mut p = Policy::default();
        p.sharing.schedule = vec!["mon 25:00-26:00".into()];
        assert!(p.validate().unwrap_err().contains("sharing.schedule"));
        let mut p = Policy::default();
        p.budget.cpu = "lots".into();
        assert!(p.validate().unwrap_err().contains("budget.cpu"));
        let mut p = Policy::default();
        p.budget.disk = "50%".into();
        assert!(p.validate().unwrap_err().contains("budget.disk"));
        let mut p = Policy::default();
        p.sharing.min_price = MinPrice::PerHour(-3.0);
        assert!(p.validate().unwrap_err().contains("min_price"));
        let mut p = Policy::default();
        p.workloads.atelier = Atelier::Backends(vec!["tensorflow".into()]);
        assert!(p.validate().unwrap_err().contains("tensorflow"));
        let mut p = Policy::default();
        p.sharing.squads = vec!["public".into(), "public".into()];
        assert!(p.validate().unwrap_err().contains("twice"));
    }

    #[test]
    fn a_budget_past_the_hardware_is_refused_for_this_host() {
        let mut p = Policy::default();
        p.budget.cpu = "64".into();
        assert!(p.validate().is_ok());
        assert!(p.validate_for(&host()).unwrap_err().contains("8 logical"));
        p.budget.cpu = "4".into();
        p.budget.memory = "64G".into();
        assert!(p
            .validate_for(&host())
            .unwrap_err()
            .contains("budget.memory"));
        p.budget.memory = "8G".into();
        assert!(p.validate_for(&host()).is_ok());
    }

    #[test]
    fn update_bumps_the_revision_only_when_something_changed() {
        let home = test_home();
        let r0 = load(&home).unwrap().revision;
        let (p, changed) = update(&home, None, None, |p| {
            p.sharing.when = "always".into();
            Ok(())
        })
        .unwrap();
        assert!(changed);
        assert_eq!(p.revision, r0 + 1);
        let (p2, changed) = update(&home, None, None, |p| {
            p.sharing.when = "always".into();
            Ok(())
        })
        .unwrap();
        assert!(!changed);
        assert_eq!(p2.revision, p.revision);
        assert_eq!(load(&home).unwrap().sharing.when, "always");
    }

    #[test]
    fn a_stale_revision_is_refused_and_nothing_is_written() {
        let home = test_home();
        let r = load(&home).unwrap().revision;
        update(&home, Some(r), None, |p| {
            p.budget.gpu = false;
            Ok(())
        })
        .unwrap();
        let e = update(&home, Some(r), None, |p| {
            p.budget.gpu = true;
            Ok(())
        })
        .unwrap_err();
        assert_eq!(e, UpdateError::Stale { current: r + 1 });
        assert!(!load(&home).unwrap().budget.gpu);
    }

    #[test]
    fn an_invalid_edit_is_refused_and_leaves_the_file_alone() {
        let home = test_home();
        let before = load(&home).unwrap();
        let e = update(&home, None, None, |p| {
            p.budget.memory = "plenty".into();
            Ok(())
        })
        .unwrap_err();
        assert!(matches!(e, UpdateError::Invalid(m) if m.contains("budget.memory")));
        assert_eq!(load(&home).unwrap(), before);
    }

    #[test]
    fn a_partial_document_merges_and_an_unknown_key_is_named() {
        let home = test_home();
        let r = load(&home).unwrap().revision;
        let (p, changed) = update_partial(
            &home,
            &json!({"revision": r, "sharing": {"min_price": 2.0}, "workloads": {"spaces": false}}),
            None,
        )
        .unwrap();
        assert!(changed);
        assert_eq!(p.sharing.min_price, MinPrice::PerHour(2.0));
        assert!(!p.workloads.spaces);
        assert_eq!(
            p.sharing.squads,
            vec!["public".to_string()],
            "untouched keys stay"
        );
        let e = update_partial(&home, &json!({"sharing": {"squad": []}}), None).unwrap_err();
        assert!(matches!(e, UpdateError::Invalid(m) if m.contains("squad")));
        let e = update_partial(&home, &json!({"revision": r}), None).unwrap_err();
        assert!(matches!(e, UpdateError::Stale { .. }));
    }

    #[test]
    fn concurrent_writers_never_lose_an_update() {
        let home = test_home();
        load(&home).unwrap();
        let handles: Vec<_> = (0..8)
            .map(|i| {
                let home = home.clone();
                std::thread::spawn(move || {
                    update(&home, None, None, |p| {
                        p.sharing.squads = vec![format!("squad-{i}")];
                        Ok(())
                    })
                    .unwrap()
                })
            })
            .collect();
        for h in handles {
            h.join().unwrap();
        }
        // Every writer got its own revision: 1 (created) + 8.
        assert_eq!(load(&home).unwrap().revision, 9);
    }

    #[test]
    fn a_staged_policy_applies_only_when_newer_and_valid() {
        let home = test_home();
        let r = load(&home).unwrap().revision;
        let desired = json!({"revision": r + 5, "sharing": {"min_price": 4.0},
                             "from_the_future": {"x": 1}});
        let p = apply_desired(&home, &desired, &host()).unwrap().unwrap();
        assert_eq!(p.revision, r + 5, "the hub's revision is kept");
        assert_eq!(p.sharing.min_price, MinPrice::PerHour(4.0));
        // Equal or lower: ignored.
        assert!(apply_desired(&home, &json!({"revision": r + 5}), &host())
            .unwrap()
            .is_none());
        assert!(apply_desired(&home, &json!({"revision": 1}), &host())
            .unwrap()
            .is_none());
        // Past the hardware: refused, local policy kept.
        let e = apply_desired(
            &home,
            &json!({"revision": r + 9, "budget": {"cpu": "99"}}),
            &host(),
        )
        .unwrap_err();
        assert!(e.contains("budget.cpu"), "{e}");
        assert_eq!(load(&home).unwrap().revision, r + 5);
    }

    #[test]
    fn the_live_view_follows_the_file_and_keeps_the_last_good_policy() {
        let home = test_home();
        let live = Live::at(home.clone());
        assert_eq!(live.current().sharing.when, "idle");
        update(&home, None, None, |p| {
            p.sharing.when = "always".into();
            Ok(())
        })
        .unwrap();
        // Force the recheck.
        live.inner.lock().unwrap().checked = None;
        assert_eq!(live.current().sharing.when, "always");
        std::fs::write(path(&home), "this is = not [valid").unwrap();
        live.inner.lock().unwrap().checked = None;
        live.inner.lock().unwrap().mtime = None;
        assert_eq!(live.current().sharing.when, "always", "last good kept");
    }

    #[test]
    fn env_budget_overrides_the_file_and_is_listed() {
        let mut p = Policy::default();
        p.budget.memory = "8G".into();
        let env = |k: &str| match k {
            "ZAKURO_BUDGET_MEMORY" => Some("2g".to_string()),
            _ => None,
        };
        let b = p.effective_budget(&env).unwrap();
        assert_eq!(b.memory, Amount::Absolute(2.0 * 1024.0 * 1024.0 * 1024.0));
        assert_eq!(b.cpu, Amount::Percent(50.0));
        assert_eq!(b.disk_bytes, 50 << 30, "the file's disk is the base");
        let none = |_: &str| None;
        assert_eq!(
            p.effective_budget(&none).unwrap().memory,
            Amount::Absolute(8.0 * 1024.0 * 1024.0 * 1024.0)
        );
        assert_eq!(env_budget_overrides(&env), vec!["ZAKURO_BUDGET_MEMORY"]);
        // A bad variable is still an error, not a silent default.
        let bad = |k: &str| (k == "ZAKURO_BUDGET_CPU").then(|| "lots".to_string());
        assert!(p.effective_budget(&bad).is_err());
    }

    #[test]
    fn gpu_in_the_file_becomes_all_gpus_and_a_deploy_pin_still_wins() {
        let mut p = Policy::default();
        p.budget.gpu = true;
        let none = |_: &str| None;
        assert_eq!(p.effective_budget(&none).unwrap().gpu, Gpus::All);
        let pin = |k: &str| (k == "ZAKURO_DEPLOY_GPUS").then(|| "device=0".to_string());
        assert_eq!(
            p.effective_budget(&pin).unwrap().gpu,
            Gpus::Spec("device=0".into())
        );
        let off = |k: &str| (k == "ZAKURO_BUDGET_GPU").then(|| "0".to_string());
        assert_eq!(p.effective_budget(&off).unwrap().gpu, Gpus::None);
    }

    #[test]
    fn the_hub_object_has_the_documented_shape() {
        let mut p = Policy {
            revision: 7,
            ..Default::default()
        };
        p.workloads.atelier = Atelier::Backends(vec!["peft".into()]);
        p.sharing.min_price = MinPrice::Withdrawn;
        let v = p.to_hub_json();
        assert_eq!(v["revision"], 7);
        assert_eq!(v["sharing"]["squads"], json!(["public"]));
        assert_eq!(v["sharing"]["min_price"], -1);
        assert_eq!(v["budget"]["vram"], "0");
        assert_eq!(v["workloads"]["atelier"], true, "a list is sent as on");
        assert!(v["runtime"]["prefer"].is_array());
        assert!(v.get("upstreams").is_none() && v.get("cleanup").is_none());
    }
}