mechutil 0.8.13

Utility structures and functions for mechatronics applications.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
//! Engineering units and display scales — the ecosystem's single definition.
//!
//! Design plan: `autocore-server/UNITS_PLAN.md`. The governing rule is that **the
//! scale table is the only place units are defined, and everything else
//! references it**. There is no second notion of units anywhere, and no
//! general-purpose physics conversion engine.
//!
//! # Model
//!
//! A machine declares, per **quantity** (a row: `force`, `position`, …):
//!
//! * `backend` — the unit the control program, GM and GNV actually hold. Declared,
//!   never assumed: in automation you regularly find a machine whose fixed units
//!   are unreasonable and unchangeable.
//! * one entry per **system** (`Metric`, `Imperial`, … — named, not a fixed pair)
//!   giving the display `label`, the `scalar` and optional `offset` that convert
//!   backend → display, and the display `precision`.
//!
//! ```text
//! display = backend * scalar + offset      (offset only where kind == Absolute)
//! backend = (display - offset) / scalar
//! ```
//!
//! # Invariants
//!
//! 1. The backend never converts. Storage, GM and GNV are always in `backend`.
//! 2. `backend` is fixed for a commissioned machine; changing it is a migration.
//! 3. Conversion happens only at display and operator-entry boundaries.
//! 4. Rounding is a rendering step, never a storage step.
//!
//! Quantities are **rows in the table, not an enum in this crate**. A machine with
//! a channel nobody anticipated is a data edit, never a release — so nothing here
//! enumerates the legal quantity names. [`default_units`] supplies the set every
//! new project starts from.

use std::collections::BTreeMap;

use serde::{Deserialize, Serialize};

/// Sidecar filename, alongside `project.json` and `test_methods.json`.
///
/// A sidecar rather than a block in project.json because this file is edited by
/// the **operator**, through the UI, on a running machine — while project.json is
/// engineering's and gets rewritten and pushed for unrelated reasons. See
/// UNITS_PLAN.md §3; that decision is load-bearing.
pub const UNITS_FILE: &str = "units.json";

/// How a quantity's values convert: a plain multiplier, or an affine mapping.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum QuantityKind {
    /// `display = backend * scalar` — every quantity except absolute temperature.
    #[default]
    Delta,
    /// `display = backend * scalar + offset` — absolute temperature (°C ⇄ °F).
    ///
    /// Kept distinct from [`QuantityKind::Delta`] because a temperature
    /// *difference* does not convert like a temperature: a 10 °C rise is 18 °F,
    /// not 50 °F. A field measuring a rise, span or tolerance must reference a
    /// `delta` quantity (conventionally `temperature_delta`), never this one.
    Absolute,
}

/// How [`SystemScale::precision`] is interpreted.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum PrecisionMode {
    /// `precision` = decimal places. The common case.
    #[default]
    Decimals,
    /// `precision` = significant figures. For a channel spanning orders of
    /// magnitude, where fixed decimals read badly (0.001 N next to 5000 N).
    Significant,
}

/// One system's display treatment of one quantity.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SystemScale {
    /// Display label (`"mm"`, `"lbf"`, `"°C"`). Free text — nothing keys off it
    /// except the method-import lookup, so `in`, `in.` and `inches` are all fine.
    pub label: String,
    /// `display = backend * scalar (+ offset)`.
    pub scalar: f64,
    /// Additive term, absolute quantities only.
    #[serde(default, skip_serializing_if = "is_zero")]
    pub offset: f64,
    /// Digits, interpreted per [`PrecisionMode`].
    #[serde(default = "default_precision")]
    pub precision: u32,
    #[serde(default, skip_serializing_if = "is_default_precision_mode")]
    pub precision_mode: PrecisionMode,
}

fn is_zero(v: &f64) -> bool {
    *v == 0.0
}
fn default_precision() -> u32 {
    3
}
fn is_default_precision_mode(m: &PrecisionMode) -> bool {
    *m == PrecisionMode::Decimals
}

impl SystemScale {
    /// A plain multiplier entry.
    pub fn new(label: &str, scalar: f64, precision: u32) -> Self {
        Self {
            label: label.to_string(),
            scalar,
            offset: 0.0,
            precision,
            precision_mode: PrecisionMode::Decimals,
        }
    }

    /// An affine entry (absolute temperature).
    pub fn affine(label: &str, scalar: f64, offset: f64, precision: u32) -> Self {
        Self {
            label: label.to_string(),
            scalar,
            offset,
            precision,
            precision_mode: PrecisionMode::Decimals,
        }
    }

    /// Significant-figure display instead of fixed decimals.
    pub fn significant(mut self, digits: u32) -> Self {
        self.precision = digits;
        self.precision_mode = PrecisionMode::Significant;
        self
    }

    /// backend → display.
    pub fn to_display(&self, backend: f64) -> f64 {
        backend * self.scalar + self.offset
    }

    /// display → backend. Never used on stored values; only on operator entry.
    pub fn to_backend(&self, display: f64) -> f64 {
        (display - self.offset) / self.scalar
    }

    /// Render `backend` for display, honouring precision and mode.
    ///
    /// Caps precision without padding: a clean 0/1/2 axis stays "0", "1", "2"
    /// rather than becoming "0.000". Rounding here is a rendering step and never
    /// touches a stored value.
    pub fn format(&self, backend: f64) -> String {
        format_value(self.to_display(backend), self.precision, self.precision_mode)
    }
}

/// Shared number formatting, so every surface renders a value identically.
pub fn format_value(v: f64, precision: u32, mode: PrecisionMode) -> String {
    if !v.is_finite() {
        return v.to_string();
    }
    let s = match mode {
        PrecisionMode::Decimals => format!("{:.*}", precision as usize, v),
        PrecisionMode::Significant => {
            let digits = precision.max(1);
            if v == 0.0 {
                "0".to_string()
            } else {
                let exp = v.abs().log10().floor() as i32;
                let decimals = (digits as i32 - 1 - exp).max(0) as usize;
                format!("{:.*}", decimals, v)
            }
        }
    };
    // Trim trailing zeros so precision is a cap, not padding.
    if s.contains('.') {
        let t = s.trim_end_matches('0').trim_end_matches('.');
        if t.is_empty() || t == "-" {
            "0".to_string()
        } else {
            t.to_string()
        }
    } else {
        s
    }
}

/// One quantity row: what the backend holds, and how each system displays it.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Scale {
    /// The unit GM/GNV actually holds on this machine (`"mm"`, `"N"`, `"deg"`).
    pub backend: String,
    /// `delta` (default) or `absolute` — see [`QuantityKind`].
    #[serde(default, skip_serializing_if = "is_delta")]
    pub kind: QuantityKind,
    /// system name → display treatment.
    #[serde(flatten)]
    pub systems: BTreeMap<String, SystemScale>,
}

fn is_delta(k: &QuantityKind) -> bool {
    *k == QuantityKind::Delta
}

impl Scale {
    pub fn new(backend: &str, systems: impl IntoIterator<Item = (String, SystemScale)>) -> Self {
        Self {
            backend: backend.to_string(),
            kind: QuantityKind::Delta,
            systems: systems.into_iter().collect(),
        }
    }

    pub fn absolute(
        backend: &str,
        systems: impl IntoIterator<Item = (String, SystemScale)>,
    ) -> Self {
        Self {
            backend: backend.to_string(),
            kind: QuantityKind::Absolute,
            systems: systems.into_iter().collect(),
        }
    }

    /// The entry for `system`, or the entry whose label IS the backend, or any.
    /// Never `None` for a validated table.
    pub fn for_system(&self, system: &str) -> Option<&SystemScale> {
        self.systems
            .get(system)
            .or_else(|| self.systems.values().find(|s| s.label == self.backend))
            .or_else(|| self.systems.values().next())
    }

    /// Find an entry by display label — the method-import lookup (PLAN §4.2.3).
    ///
    /// This is how a machine converts a value authored against another machine's
    /// backend using nothing but its own table: if this machine stores metres and
    /// displays `mm` at scalar 1000, an incoming value stamped `mm` is
    /// `value / 1000`. Returns `None` when the label is absent — the caller must
    /// then refuse, never guess.
    pub fn by_label(&self, label: &str) -> Option<&SystemScale> {
        self.systems.values().find(|s| s.label == label)
    }
}

/// The whole `units.json` document.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Units {
    /// Named systems, in display order. Any names; not a fixed pair.
    pub systems: Vec<String>,
    /// Which system a machine starts in before an operator chooses.
    pub default_system: String,
    /// quantity name → row.
    pub scales: BTreeMap<String, Scale>,
    /// Per-hardware-build overrides, resolved by
    /// [`crate::config_overlay::resolve_active_config`] exactly like a module's.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub configurations: Option<serde_json::Value>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub default_configuration: Option<String>,
}

impl Units {
    /// Resolve a quantity + system to its display treatment.
    pub fn scale(&self, quantity: &str, system: &str) -> Option<&SystemScale> {
        self.scales.get(quantity)?.for_system(system)
    }

    /// The label a quantity displays as in `system`.
    pub fn label(&self, quantity: &str, system: &str) -> Option<&str> {
        self.scale(quantity, system).map(|s| s.label.as_str())
    }

    /// Format a stored (backend) value for display.
    pub fn format(&self, quantity: &str, system: &str, backend: f64) -> String {
        match self.scale(quantity, system) {
            Some(s) => s.format(backend),
            None => backend.to_string(),
        }
    }

    /// The backend unit map — what gets stamped into a run or a method so the
    /// numbers stay self-describing (PLAN §6.4, §4.2.3).
    pub fn backend_stamp(&self) -> BTreeMap<String, String> {
        self.scales
            .iter()
            .map(|(q, s)| (q.clone(), s.backend.clone()))
            .collect()
    }

    /// Convert a value authored against `from_label` into this machine's backend
    /// for `quantity` (PLAN §4.2.3).
    ///
    /// `Ok(None)` means no conversion was needed. `Err` means the label is not in
    /// this machine's table, so the caller must **refuse** — guessing here is how
    /// a 1000× load command reaches a press.
    pub fn convert_from_label(
        &self,
        quantity: &str,
        from_label: &str,
        value: f64,
    ) -> Result<Option<f64>, UnitsError> {
        let scale = self
            .scales
            .get(quantity)
            .ok_or_else(|| UnitsError::UnknownQuantity(quantity.to_string()))?;
        if scale.backend == from_label {
            return Ok(None); // already ours
        }
        let entry = scale
            .by_label(from_label)
            .ok_or_else(|| UnitsError::UnconvertibleLabel {
                quantity: quantity.to_string(),
                label: from_label.to_string(),
                backend: scale.backend.clone(),
            })?;
        Ok(Some(entry.to_backend(value)))
    }

    /// Semantic validation (PLAN §7). Returns human-readable findings; empty = ok.
    pub fn validate(&self) -> Vec<String> {
        let mut out = Vec::new();

        if self.systems.is_empty() {
            out.push("units: `systems` is empty — at least one system is required".into());
        }
        if !self.systems.iter().any(|s| s == &self.default_system) {
            out.push(format!(
                "units: default_system '{}' is not one of {:?}",
                self.default_system, self.systems
            ));
        }

        for (name, scale) in &self.scales {
            // An empty backend is legal for a genuinely unitless row
            // (`dimensionless`), but not for one whose systems carry labels —
            // that combination means somebody forgot to declare the backend.
            if scale.backend.trim().is_empty()
                && scale.systems.values().any(|s| !s.label.trim().is_empty())
            {
                out.push(format!(
                    "units.scales.{name}: `backend` is empty but its systems have \
                     labels — declare the unit GM actually holds"
                ));
            }
            for sys in &self.systems {
                let Some(entry) = scale.systems.get(sys) else {
                    out.push(format!(
                        "units.scales.{name}: no entry for system '{sys}'"
                    ));
                    continue;
                };
                if !entry.scalar.is_finite() || entry.scalar == 0.0 {
                    out.push(format!(
                        "units.scales.{name}.{sys}: scalar must be finite and non-zero (got {})",
                        entry.scalar
                    ));
                }
                if entry.offset != 0.0 && scale.kind != QuantityKind::Absolute {
                    out.push(format!(
                        "units.scales.{name}.{sys}: `offset` is only valid on an \
                         `absolute` quantity (a difference must not take the offset)"
                    ));
                }
                if entry.precision_mode == PrecisionMode::Significant && entry.precision == 0 {
                    out.push(format!(
                        "units.scales.{name}.{sys}: significant precision must be >= 1"
                    ));
                }
                // The entry that IS the backend must be the identity, or the
                // declared backend is a lie.
                if entry.label == scale.backend
                    && (entry.scalar != 1.0 || entry.offset != 0.0)
                {
                    out.push(format!(
                        "units.scales.{name}.{sys}: label '{}' equals the declared backend, \
                         so scalar must be 1.0 and offset 0 (got scalar {}, offset {})",
                        entry.label, entry.scalar, entry.offset
                    ));
                }
            }
        }
        out
    }
}

/// Errors from unit resolution / method import.
#[derive(Debug, Clone, PartialEq)]
pub enum UnitsError {
    UnknownQuantity(String),
    /// The label is not in this machine's table for that quantity, so the value
    /// cannot be converted. Refuse; do not guess.
    UnconvertibleLabel {
        quantity: String,
        label: String,
        backend: String,
    },
}

impl std::fmt::Display for UnitsError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            UnitsError::UnknownQuantity(q) => {
                write!(f, "no scale group named '{q}' in units.json")
            }
            UnitsError::UnconvertibleLabel { quantity, label, backend } => write!(
                f,
                "authored in '{label}'; this machine stores {quantity} in '{backend}' and has \
                 no '{label}' entry — add one to the units table, or convert by hand"
            ),
        }
    }
}

impl std::error::Error for UnitsError {}

/// The default table every new project starts from.
///
/// These are the backends audited across the existing projects (UNITS_PLAN §4.1a):
/// mm, N, mm/s, mm/s², deg, deg/s, deg/s², N·m. Uniform defaults mean the odd
/// machine is visibly odd in a diff.
pub fn default_units() -> Units {
    let m = "Metric".to_string();
    let i = "Imperial".to_string();
    let pair = |metric: SystemScale, imperial: SystemScale| {
        vec![(m.clone(), metric), (i.clone(), imperial)]
    };

    let mut scales = BTreeMap::new();

    scales.insert(
        "position".to_string(),
        Scale::new("mm", pair(
            SystemScale::new("mm", 1.0, 3),
            SystemScale::new("in", 1.0 / 25.4, 4),
        )),
    );
    scales.insert(
        "length".to_string(),
        Scale::new("mm", pair(
            SystemScale::new("mm", 1.0, 3),
            SystemScale::new("in", 1.0 / 25.4, 4),
        )),
    );
    scales.insert(
        "force".to_string(),
        Scale::new("N", pair(
            SystemScale::new("N", 1.0, 2),
            SystemScale::new("lbf", 0.224_808_943_099_71, 3),
        )),
    );
    scales.insert(
        "velocity".to_string(),
        Scale::new("mm/s", pair(
            SystemScale::new("mm/s", 1.0, 3),
            SystemScale::new("in/s", 1.0 / 25.4, 4),
        )),
    );
    scales.insert(
        "acceleration".to_string(),
        Scale::new("mm/s²", pair(
            SystemScale::new("mm/s²", 1.0, 2),
            SystemScale::new("in/s²", 1.0 / 25.4, 3),
        )),
    );
    scales.insert(
        "angle".to_string(),
        Scale::new("deg", pair(
            SystemScale::new("deg", 1.0, 2),
            SystemScale::new("deg", 1.0, 2),
        )),
    );
    scales.insert(
        "angular_velocity".to_string(),
        Scale::new("deg/s", pair(
            SystemScale::new("deg/s", 1.0, 2),
            SystemScale::new("deg/s", 1.0, 2),
        )),
    );
    scales.insert(
        "angular_acceleration".to_string(),
        Scale::new("deg/s²", pair(
            SystemScale::new("deg/s²", 1.0, 2),
            SystemScale::new("deg/s²", 1.0, 2),
        )),
    );
    scales.insert(
        "torque".to_string(),
        Scale::new("N·m", pair(
            SystemScale::new("N·m", 1.0, 3),
            SystemScale::new("lbf·in", 8.850_745_79, 3),
        )),
    );
    scales.insert(
        "pressure".to_string(),
        Scale::new("kPa", pair(
            SystemScale::new("kPa", 1.0, 2),
            SystemScale::new("psi", 0.145_037_738, 3),
        )),
    );
    scales.insert(
        "mass".to_string(),
        Scale::new("kg", pair(
            SystemScale::new("kg", 1.0, 3),
            SystemScale::new("lb", 2.204_622_62, 3),
        )),
    );
    scales.insert(
        "time".to_string(),
        Scale::new("s", pair(
            SystemScale::new("s", 1.0, 3),
            SystemScale::new("s", 1.0, 3),
        )),
    );
    scales.insert(
        "temperature".to_string(),
        Scale::absolute("degC", pair(
            SystemScale::affine("°C", 1.0, 0.0, 1),
            SystemScale::affine("°F", 1.8, 32.0, 1),
        )),
    );
    scales.insert(
        "temperature_delta".to_string(),
        Scale::new("degC", pair(
            SystemScale::new("°C", 1.0, 1),
            SystemScale::new("°F", 1.8, 1),
        )),
    );
    scales.insert(
        "dimensionless".to_string(),
        Scale::new("", pair(
            SystemScale::new("", 1.0, 3),
            SystemScale::new("", 1.0, 3),
        )),
    );

    Units {
        systems: vec![m, i],
        default_system: "Metric".to_string(),
        scales,
        configurations: None,
        default_configuration: None,
    }
}

// ── sidecar I/O ─────────────────────────────────────────────────────────────

/// Path of the units sidecar for a project file.
pub fn units_path(project_file: &std::path::Path) -> std::path::PathBuf {
    project_file
        .parent()
        .unwrap_or_else(|| std::path::Path::new("."))
        .join(UNITS_FILE)
}

/// Load `units.json` beside `project_file`, applying the active hardware-build
/// overlay if one is declared.
///
/// `Ok(None)` = the file is absent. That is **degraded, not fatal** (PLAN §3.1):
/// units being missing breaks display, not the machine, so the caller reports it
/// loudly and carries on rather than refusing to boot.
pub fn load_units(
    project_file: &std::path::Path,
    active_configuration: Option<&str>,
) -> Result<Option<Units>, String> {
    let path = units_path(project_file);
    if !path.exists() {
        return Ok(None);
    }
    let text = std::fs::read_to_string(&path)
        .map_err(|e| format!("read {}: {e}", path.display()))?;
    let raw: serde_json::Value = serde_json::from_str(&text)
        .map_err(|e| format!("parse {}: {e}", path.display()))?;

    // Same overlay mechanism module configs use, so a per-build backend override
    // needs no new machinery.
    let resolved = if raw.get("configurations").is_some() {
        crate::config_overlay::resolve_active_config(&raw, active_configuration)
            .map_err(|e| format!("{}: {e}", path.display()))?
    } else {
        raw
    };

    let units: Units = serde_json::from_value(resolved)
        .map_err(|e| format!("{}: {e}", path.display()))?;
    Ok(Some(units))
}

/// Write `units.json` beside `project_file`, atomically (temp + rename) with a
/// `.bak` of the previous contents — this file holds operator work.
pub fn save_units(project_file: &std::path::Path, units: &Units) -> Result<(), String> {
    let path = units_path(project_file);
    let text = serde_json::to_string_pretty(units)
        .map_err(|e| format!("serialize units: {e}"))?;

    if path.exists() {
        let _ = std::fs::copy(&path, path.with_extension("json.bak"));
    }
    let tmp = path.with_extension("json.tmp");
    std::fs::write(&tmp, text).map_err(|e| format!("write {}: {e}", tmp.display()))?;
    std::fs::rename(&tmp, &path).map_err(|e| format!("rename into {}: {e}", path.display()))?;
    Ok(())
}

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

    #[test]
    fn default_table_validates() {
        let findings = default_units().validate();
        assert!(findings.is_empty(), "{findings:#?}");
    }

    #[test]
    fn converts_backend_to_display_and_back() {
        let u = default_units();
        let imperial = u.scale("position", "Imperial").unwrap();
        assert!((imperial.to_display(25.4) - 1.0).abs() < 1e-9);
        assert!((imperial.to_backend(1.0) - 25.4).abs() < 1e-9);
    }

    /// Absolute temperature is affine; a temperature DELTA is not. 10 °C rise is
    /// 18 °F, not 50 °F — the bug this split exists to prevent.
    #[test]
    fn temperature_delta_does_not_take_the_offset() {
        let u = default_units();
        let abs = u.scale("temperature", "Imperial").unwrap();
        assert!((abs.to_display(100.0) - 212.0).abs() < 1e-9);
        assert!((abs.to_display(0.0) - 32.0).abs() < 1e-9);

        let delta = u.scale("temperature_delta", "Imperial").unwrap();
        assert!(
            (delta.to_display(10.0) - 18.0).abs() < 1e-9,
            "a 10 degC rise must read as 18 degF, not 50"
        );
    }

    #[test]
    fn precision_caps_without_padding() {
        assert_eq!(format_value(2.0, 3, PrecisionMode::Decimals), "2");
        assert_eq!(format_value(2.34567, 3, PrecisionMode::Decimals), "2.346");
        // The float-noise case that motivated the chart-axis fix.
        assert_eq!(
            format_value(0.30000000000000004, 2, PrecisionMode::Decimals),
            "0.3"
        );
    }

    #[test]
    fn significant_mode_tracks_magnitude() {
        assert_eq!(format_value(0.001234, 3, PrecisionMode::Significant), "0.00123");
        assert_eq!(format_value(5432.1, 3, PrecisionMode::Significant), "5432");
        assert_eq!(format_value(0.0, 3, PrecisionMode::Significant), "0");
    }

    /// PLAN §4.2.3: a machine converts a foreign method using ONLY its own table,
    /// by inverting the display entry whose label matches the stamp.
    #[test]
    fn imports_a_method_by_inverting_its_own_display_entry() {
        // This machine stores METRES but displays mm.
        let mut u = default_units();
        u.scales.insert(
            "position".to_string(),
            Scale::new("m", vec![
                ("Metric".to_string(), SystemScale::new("mm", 1000.0, 1)),
                ("Imperial".to_string(), SystemScale::new("in", 39.370_078_74, 3)),
            ]),
        );

        // A method authored on a mm-backend machine says 68.
        let converted = u.convert_from_label("position", "mm", 68.0).unwrap();
        assert!(
            (converted.unwrap() - 0.068).abs() < 1e-12,
            "68 mm must import as 0.068 m"
        );
    }

    #[test]
    fn import_is_a_noop_when_the_stamp_matches_the_backend() {
        let u = default_units();
        assert_eq!(u.convert_from_label("force", "N", 50.0).unwrap(), None);
    }

    /// The safety-critical half: an unconvertible label is REFUSED, never guessed.
    #[test]
    fn import_refuses_a_label_absent_from_this_machines_table() {
        let u = default_units(); // force: backend N, labels N + lbf — no kN
        let err = u.convert_from_label("force", "kN", 5.0).unwrap_err();
        match &err {
            UnitsError::UnconvertibleLabel { label, backend, .. } => {
                assert_eq!(label, "kN");
                assert_eq!(backend, "N");
            }
            other => panic!("expected UnconvertibleLabel, got {other:?}"),
        }
        // The message must name the fix.
        assert!(err.to_string().contains("add one to the units table"));
    }

    #[test]
    fn validation_rejects_a_backend_entry_that_is_not_the_identity() {
        let mut u = default_units();
        // Claim the backend is mm but give the mm entry a non-unity scalar.
        u.scales.get_mut("position").unwrap().systems.get_mut("Metric").unwrap().scalar = 2.0;
        let findings = u.validate();
        assert!(
            findings.iter().any(|f| f.contains("equals the declared backend")),
            "{findings:#?}"
        );
    }

    #[test]
    fn validation_rejects_an_offset_on_a_delta_quantity() {
        let mut u = default_units();
        u.scales
            .get_mut("temperature_delta")
            .unwrap()
            .systems
            .get_mut("Imperial")
            .unwrap()
            .offset = 32.0;
        let findings = u.validate();
        assert!(
            findings.iter().any(|f| f.contains("only valid on an")),
            "{findings:#?}"
        );
    }

    #[test]
    fn backend_stamp_covers_every_quantity() {
        let u = default_units();
        let stamp = u.backend_stamp();
        assert_eq!(stamp.get("force").map(String::as_str), Some("N"));
        assert_eq!(stamp.get("position").map(String::as_str), Some("mm"));
        assert_eq!(stamp.len(), u.scales.len());
    }

    #[test]
    fn sidecar_round_trips_and_absent_is_not_an_error() {
        let dir = tempfile::tempdir().unwrap();
        let project = dir.path().join("project.json");
        std::fs::write(&project, "{}").unwrap();

        // Absent is Ok(None) — degraded, not fatal.
        assert_eq!(load_units(&project, None).unwrap(), None);

        let u = default_units();
        save_units(&project, &u).unwrap();
        assert_eq!(load_units(&project, None).unwrap().as_ref(), Some(&u));
    }

    /// The odd machine: a per-build overlay swaps the declared backend without
    /// touching the portable table, using the same resolver module configs use.
    #[test]
    fn per_build_overlay_can_change_the_backend() {
        let dir = tempfile::tempdir().unwrap();
        let project = dir.path().join("project.json");
        std::fs::write(&project, "{}").unwrap();

        let mut raw = serde_json::to_value(default_units()).unwrap();
        raw["configurations"] = serde_json::json!({
            "kn_frame": { "scales": { "force": {
                "backend": "kN",
                "Metric": { "label": "kN", "scalar": 1.0, "precision": 3 }
            } } }
        });
        std::fs::write(units_path(&project), serde_json::to_string(&raw).unwrap()).unwrap();

        let base = load_units(&project, Some("kn_frame")).unwrap().unwrap();
        assert_eq!(base.scales["force"].backend, "kN");
        // Untouched quantities survive the overlay.
        assert_eq!(base.scales["position"].backend, "mm");
    }

    #[test]
    fn round_trips_through_json() {
        let u = default_units();
        let s = serde_json::to_string_pretty(&u).unwrap();
        let back: Units = serde_json::from_str(&s).unwrap();
        assert_eq!(u, back);
    }
}