draftwright 0.6.0

Dimensioned engineering drawings from STEP, with SVG, PDF and editable DXF output.
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
//! Exact, whole-Spec identity migration. Saved keys without current evidence remain intact.
use crate::model::{Analysis, Invalid, Plan, SPEC_SCHEMA, SPEC_SCHEMAS, Spec};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::BTreeMap;

/// spec/1 and spec/2 are accepted for ten releases from 0.2.15, through 0.6.8, then refused.
/// Changing this single cutoff keeps the approved conversion route explicit.
pub const LAST_LEGACY_SPEC_READER: &str = "0.6.8";

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Migrated {
    /// RFC 6901 path in the saved document (without a leading slash).
    pub path: String,
    pub from: String,
    pub to: String,
}

pub(crate) struct Migration {
    pub spec: Spec,
    pub migrated: Vec<Migrated>,
    pub ids: BTreeMap<String, String>,
    unmapped: Vec<(String, String)>,
}
impl Migration {
    pub(crate) fn report(&self, plan: &mut Plan) {
        plan.migrated = self.migrated.clone();
        plan.ids = self.ids.clone();
        complete_ids(plan);
        for (path, id) in &self.unmapped {
            let problem = format!("p:id_not_migrated:{path}:{id}");
            if !plan.problems.iter().any(|p| p.id == problem) {
                plan.problems.push(crate::model::Problem {
                    id: problem, code: "id_not_migrated".into(), severity: "info".into(),
                    message: "A saved identity has no exact mapping in the current geometry; its key is retained.".into(),
                    subjects: vec![path.clone()], refs: vec![id.clone()], ..Default::default()
                });
            }
        }
    }
}

/// Assign final names after all recognition merges; rank assignment remains unchanged above
/// this boundary and is retained only for exact saved-Spec migration.
fn complete_ids(plan: &mut Plan) {
    let reverse = plan
        .ids
        .iter()
        .map(|(o, n)| (n.clone(), o.clone()))
        .collect();
    let names = crate::revision_rename::Renamer::new(&reverse);
    for id in plan
        .dimensions
        .iter()
        .map(|d| &d.id)
        .chain(plan.omitted.iter().map(|d| &d.id))
        .chain(plan.problems.iter().map(|p| &p.id))
    {
        let old = names.rename(id);
        if old != *id {
            plan.ids.insert(old, id.clone());
        }
    }
}

pub(crate) use crate::geometry_ids::feature_names;

pub(crate) fn anchor(
    features: &mut [crate::bridge::Feature],
    patterns: &mut [crate::bridge::HolePattern],
) -> Result<(), String> {
    let names = feature_names(features, patterns)?;
    let map: BTreeMap<_, _> = features
        .iter()
        .map(|f| &f.id)
        .chain(patterns.iter().map(|p| &p.id))
        .cloned()
        .zip(names.iter().cloned())
        .collect();
    for (i, f) in features.iter_mut().enumerate() {
        f.legacy_id = Some(std::mem::replace(&mut f.id, names[i].clone()));
        f.parameters = serde_json::from_value(crate::revision_rename::rename_spec(
            &Value::Object(f.parameters.clone()),
            &map,
        )?)
        .expect("parameter object");
    }
    for (i, p) in patterns.iter_mut().enumerate() {
        p.legacy_id = Some(std::mem::replace(
            &mut p.id,
            names[features.len() + i].clone(),
        ));
        for member in &mut p.members {
            *member = crate::revision_rename::rename_ids(member, &map);
        }
        p.parameters = serde_json::from_value(crate::revision_rename::rename_spec(
            &Value::Object(p.parameters.clone()),
            &map,
        )?)
        .expect("parameter object");
    }
    Ok(())
}

// Migration-only spelling map. Current identity, spans and drawing order never read it.
fn ladder_legacy_ids(a: &Analysis) -> BTreeMap<String, String> {
    let mut ids = BTreeMap::new();
    for z in crate::geometry_ids::heights(a) {
        ids.insert(
            format!(
                "step_height.length.h{}",
                crate::geometry_ids::coordinate_word(z - a.envelope[0][2])
            ),
            crate::geometry_ids::height_parameter(a, z),
        );
    }
    for r in &a.risers {
        for (axis, positions) in [(&r.axis, &r.positions), (&r.other_axis, &r.other_positions)] {
            let Some(k) = ["x", "y", "z"].iter().position(|x| *x == axis) else {
                continue;
            };
            for &at in positions {
                ids.insert(
                    format!(
                        "step_position.length.{axis}{}",
                        crate::geometry_ids::coordinate_word((at - a.envelope[0][k]).abs())
                    ),
                    crate::geometry_ids::position_parameter(a, k, at),
                );
            }
        }
    }
    ids
}

pub fn ids(a: &Analysis) -> BTreeMap<String, String> {
    crate::geometry_ids::with(a, || ids_indexed(a))
}

fn ids_indexed(a: &Analysis) -> BTreeMap<String, String> {
    let mut ids: BTreeMap<_, _> = a
        .features
        .iter()
        .filter_map(|f| Some((f.legacy_id.clone()?, f.id.clone())))
        .collect();
    if let Some(r) = &a.recognition {
        ids.extend(
            r.patterns
                .iter()
                .filter_map(|p| Some((p.legacy_id.clone()?, p.id.clone()))),
        );
    }
    ids.extend(
        ladder_legacy_ids(a)
            .iter()
            .map(|(o, n)| (o.clone(), n.clone())),
    );
    ids.retain(|old, new| old != new);
    ids
}

// The cutoff is a stable release. A prerelease of its core is still within
// the window; any larger release core (including its prereleases) is beyond it.
fn release_version(s: &str) -> Vec<u64> {
    s.split(['-', '+'])
        .next()
        .unwrap_or(s)
        .split('.')
        .map(|n| n.parse().expect("Cargo package version core"))
        .collect()
}
fn refusal(schema: &str, current: &str) -> Option<String> {
    (matches!(schema, "draftwright.spec/1" | "draftwright.spec/2")
        && release_version(current) > release_version(LAST_LEGACY_SPEC_READER)).then(|| format!(
        "This Spec is {schema}, which draftwright {current} no longer reads: it reads only draftwright.spec/3, whose feature and step IDs are named by faces rather than by rank or measured value. Convert it once with draftwright {LAST_LEGACY_SPEC_READER}, the last compatible release: run `draftwright plan PART.step --spec FILE` and keep the `spec` it prints. Then open the converted Spec here."
    ))
}
fn invalid(message: String) -> Invalid {
    Invalid {
        message,
        path: None,
        also: Vec::new(),
        choices: Vec::new(),
    }
}
fn escape(s: &str) -> String {
    s.replace('~', "~0").replace('/', "~1")
}

/// Report changes to keys and string values, including references nested in arrays.
fn changes(v: &Value, path: &str, map: &BTreeMap<String, String>, out: &mut Vec<Migrated>) {
    changes_indexed(v, path, &crate::revision_rename::Renamer::new(map), out);
}
fn changes_indexed(
    v: &Value,
    path: &str,
    names: &crate::revision_rename::Renamer<'_>,
    out: &mut Vec<Migrated>,
) {
    let mut changed = |s: &str, path: String| {
        let to = names.rename(s);
        if s != to {
            out.push(Migrated {
                path,
                from: s.into(),
                to,
            });
        }
    };
    match v {
        Value::String(s) => changed(s, path.into()),
        Value::Object(o) => {
            for (k, x) in o {
                let p = if path.is_empty() {
                    escape(k)
                } else {
                    format!("{path}/{}", escape(k))
                };
                let to = names.rename(k);
                if *k != to {
                    out.push(Migrated {
                        path: p.clone(),
                        from: k.clone(),
                        to,
                    });
                }
                changes_indexed(x, &p, names, out);
            }
        }
        Value::Array(a) => {
            for (i, x) in a.iter().enumerate() {
                changes_indexed(x, &format!("{path}/{i}"), names, out);
            }
        }
        _ => {}
    }
}

/// Fields of authored prose, which can look like an ID but never is one: note text, the
/// title block, table cells and annotation label text.
fn free_text(v: &Value, key: &dyn Fn(&str) -> String) -> Vec<String> {
    let mut out = vec!["/sheet/title".to_string()];
    let each = |key: &str, field: &str, out: &mut Vec<String>| {
        let n = v.get(key).and_then(Value::as_array).map_or(0, Vec::len);
        out.extend((0..n).map(|i| format!("/{key}/{i}/{field}")));
    };
    each("notes", "text", &mut out);
    each("tables", "rows", &mut out);
    if let Some(a) = v.get("annotations").and_then(Value::as_object) {
        out.extend(
            a.keys()
                .map(|k| format!("/annotations/{}/text", escape(&key(k)))),
        );
    }
    out
}
fn strip_text(v: &mut Value) {
    for p in free_text(&v.clone(), &|k| k.into()) {
        if let Some(x) = v.pointer_mut(&p) {
            *x = Value::Null;
        }
    }
}
/// Put the prose of *from* back into *to*, which was renamed and so keeps its shape.
fn restore_text(from: &Value, to: &mut Value, ids: &BTreeMap<String, String>) {
    let names = crate::revision_rename::Renamer::new(ids);
    for (p, q) in free_text(from, &|k| k.into())
        .into_iter()
        .zip(free_text(from, &|k| names.rename(k)))
    {
        if let (Some(x), Some(y)) = (from.pointer(&p), to.pointer_mut(&q)) {
            *y = x.clone();
        }
    }
}

fn unmapped(v: &Value, a: &Analysis) -> Vec<(String, String)> {
    fn visit(v: &Value, path: &str, a: &Analysis, out: &mut Vec<(String, String)>) {
        let scan = |s: &str, path: &str, out: &mut Vec<(String, String)>| {
            let mut rest = s;
            while let Some((start, end)) = crate::revision_rename::next_id(rest) {
                let id = &rest[start..end];
                if id.starts_with("f:")
                    && !id.starts_with("f:declared:")
                    && id
                        .rsplit(':')
                        .next()
                        .is_some_and(|n| n.bytes().all(|b| b.is_ascii_digit()))
                    && !a.features.iter().any(|f| f.id == id)
                    && !a
                        .recognition
                        .iter()
                        .flat_map(|r| &r.patterns)
                        .any(|p| p.id == id)
                {
                    out.push((path.into(), id.into()));
                }
                rest = &rest[end..];
            }
            for prefix in [
                "step_height.length.h",
                "step_position.length.x",
                "step_position.length.y",
            ] {
                if let Some(i) = s.find(prefix) {
                    let end = s[i..]
                        .find(|c: char| !(c.is_ascii_alphanumeric() || c == '_' || c == '.'))
                        .map_or(s.len(), |n| i + n);
                    let parameter = &s[i..end];
                    if crate::geometry_ids::parameter_span(a, parameter).is_none() {
                        out.push((path.into(), parameter.into()));
                    }
                }
            }
        };
        match v {
            Value::String(_) => {}
            Value::Object(o) => {
                for (k, x) in o {
                    let p = if path.is_empty() {
                        escape(k)
                    } else {
                        format!("{path}/{}", escape(k))
                    };
                    scan(k, &p, out);
                    visit(x, &p, a, out);
                }
            }
            Value::Array(list) => {
                for (i, x) in list.iter().enumerate() {
                    visit(x, &format!("{path}/{i}"), a, out);
                }
            }
            _ => {}
        }
    }
    let mut out = Vec::new();
    visit(v, "", a, &mut out);
    out.sort();
    out.dedup();
    out
}

fn rank_key(v: &Value) -> Option<String> {
    match v {
        Value::Object(o) => o.iter().find_map(|(key, value)| {
            let mut rest = key.as_str();
            while let Some((start, end)) = crate::revision_rename::next_id(rest) {
                let id = &rest[start..end];
                if id.starts_with("f:")
                    && !id.starts_with("f:declared:")
                    && id
                        .rsplit(':')
                        .next()
                        .is_some_and(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit()))
                {
                    return Some(key.clone());
                }
                rest = &rest[end..];
            }
            rank_key(value)
        }),
        Value::Array(values) => values.iter().find_map(rank_key),
        _ => None,
    }
}

// JSON serializes non-finite floats as null. Required numeric fields then fail
// deserialization, but optional numbers would silently become None. Reject those
// typed inputs before any whole-document rename can erase the author's value.
fn finite_optional_numbers(spec: &Spec) -> Result<(), Invalid> {
    let check = |path: String, number: Option<f64>| {
        if number.is_some_and(|n| !n.is_finite()) {
            let mut error = invalid(format!("{path} must be finite."));
            error.path = Some(path);
            Err(error)
        } else {
            Ok(())
        }
    };
    check("iso_scale_factor".into(), spec.iso_scale_factor)?;
    check("sheet/view_gutter".into(), spec.sheet.view_gutter)?;
    check("sheet/frame_gutter".into(), spec.sheet.frame_gutter)?;
    for (name, view) in &spec.views {
        if let Some(broken) = &view.broken {
            check(format!("views/{}/break/gap", escape(name)), broken.gap)?;
        }
    }
    for (id, feature) in &spec.features {
        if let Some(thread) = &feature.thread {
            check(
                format!("features/{}/thread/length", escape(id)),
                thread.length,
            )?;
        }
    }
    Ok(())
}

pub(crate) fn migrate(spec: &Spec, a: &Analysis) -> Result<Migration, Invalid> {
    let mut normal;
    let spec = if spec.schema == crate::engine_pins::SCHEMA && spec.engine_pins.is_none() {
        normal = spec.clone();
        normal.schema = SPEC_SCHEMA.into();
        &normal
    } else {
        spec
    };
    crate::geometry_ids::with(a, || migrate_indexed(spec, a))
}

fn migrate_indexed(spec: &Spec, a: &Analysis) -> Result<Migration, Invalid> {
    if let Some(message) = refusal(&spec.schema, env!("CARGO_PKG_VERSION")) {
        return Err(invalid(message));
    }
    if !SPEC_SCHEMAS.contains(&spec.schema.as_str()) {
        let mut error = invalid(format!(
            "The spec is {:?}, which this draftwright does not read.",
            spec.schema
        ));
        error.choices = SPEC_SCHEMAS.iter().map(|s| (*s).into()).collect();
        return Err(error);
    }
    finite_optional_numbers(spec)?;
    if matches!(
        spec.schema.as_str(),
        "draftwright.spec/1" | "draftwright.spec/2"
    ) && a
        .schema
        .strip_prefix("draftwright.analysis/")
        .and_then(|v| v.parse::<u32>().ok())
        .is_some_and(|v| v < 8)
        && let Some(key) = rank_key(&serde_json::to_value(spec).expect("Spec serializes"))
    {
        return Err(invalid(format!(
            "Cannot migrate {} key {key:?} using {}: it has rank IDs without current face identity evidence. Re-analyse the STEP with a current engine, then open the original {} Spec again. Keep its saved schema; no spec/3 has been written.",
            spec.schema, a.schema, spec.schema
        )));
    }
    let mut ids = ids(a);
    // Scheme IDs digest their station references. Recover both spellings exactly from
    // the same station-ID map, including refs expanded from automatic patterns.
    let stations: Vec<_> = ids
        .iter()
        .filter(|(old, _)| old.starts_with("f:"))
        .map(|(o, n)| (o.clone(), n.clone()))
        .collect();
    for name in spec.dimension_schemes.keys() {
        for (old, new) in &stations {
            for prefix in ["", "start:", "end:", "axis:"] {
                ids.insert(
                    crate::dimension_scheme::item_id(name, &format!("{prefix}{old}")),
                    crate::dimension_scheme::item_id(name, &format!("{prefix}{new}")),
                );
            }
        }
    }
    let mut out = crate::model::migrate_v1(spec, a)?;
    let mut migrated = Vec::new();
    if spec.schema != SPEC_SCHEMA || !ids.is_empty() {
        let mut map = ids.clone();
        if spec.schema == "draftwright.spec/1" {
            // This is the existing view/PMI migration, composed with the identity map.
            for old in spec.dimensions.keys() {
                let mut one = spec.clone();
                one.dimensions.retain(|k, _| k == old);
                let v1 = crate::model::migrate_v1(&one, a)?;
                if let Some(new) = v1.dimensions.keys().next() {
                    map.insert(old.clone(), crate::revision_rename::rename_ids(new, &ids));
                }
            }
        }
        let mut original = serde_json::to_value(spec).expect("Spec serializes");
        strip_text(&mut original);
        changes(&original, "", &map, &mut migrated);
        let before = serde_json::to_value(&out).expect("Spec serializes");
        let mut value = crate::revision_rename::rename_spec(&before, &ids).map_err(invalid)?;
        restore_text(&before, &mut value, &ids);
        // Apply the map on every schema, but preserve typed values and their ordinary
        // validation (including structured choices) when the rename changes nothing.
        if value != before {
            out = serde_json::from_value(value).map_err(|error| invalid(error.to_string()))?;
        }
    }
    out.schema = if out.engine_pins.is_some() {
        crate::engine_pins::SCHEMA.into()
    } else {
        SPEC_SCHEMA.into()
    };
    let mut checked = serde_json::to_value(&out).expect("Spec serializes");
    strip_text(&mut checked);
    let unmapped = unmapped(&checked, a);
    Ok(Migration {
        unmapped,
        spec: out,
        migrated,
        ids,
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn anchors_and_collision_suffixes_are_local_and_order_independent() {
        let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("tests/fixtures/parts/mounting_plate.step");
        let (_, a) = crate::model::analyse_native(&path).unwrap();
        let template = &a.features[0];
        let feature = |id: &str, faces: Vec<usize>| {
            let mut f = template.clone();
            f.kind = "section_recess".into();
            f.id = id.into();
            f.faces = faces;
            f
        };
        let original = vec![
            feature("f:section_recess:1", vec![9]),
            feature("f:section_recess:2", vec![146, 152, 166]),
            feature("f:section_recess:3", vec![146, 154, 164]),
        ];
        let mut fs = original.clone();
        anchor(&mut fs, &mut []).unwrap();
        assert_eq!(
            fs.iter().map(|f| f.id.as_str()).collect::<Vec<_>>(),
            [
                "f:section_recess:f9",
                "f:section_recess:f146_0",
                "f:section_recess:f146_1"
            ]
        );
        let mut reduced = original[1..].to_vec();
        reduced.reverse();
        anchor(&mut reduced, &mut []).unwrap();
        assert_eq!(reduced[0].id, fs[2].id);
        assert_eq!(reduced[1].id, fs[1].id);
        assert_eq!(fs[1].legacy_id.as_deref(), Some("f:section_recess:2"));
    }

    #[test]
    fn authored_patterns_reserve_automatic_face_names() {
        for name in ["12", "f12", "f12_0"] {
            let spec: Spec = serde_json::from_value(serde_json::json!({"features": {
                format!("f:hole_pattern:{name}"): {"pattern":{"arrangement":"linear","members":["f:hole:f6","f:hole:f7"]}}
            }})).unwrap();
            assert!(
                crate::recognition_corrections::check(&spec).is_err(),
                "{name}"
            );
        }
        let spec: Spec = serde_json::from_value(serde_json::json!({"features": {
            "f:hole_pattern:mounting": {"pattern":{"arrangement":"linear","members":["f:hole:f6","f:hole:f7"]}}
        }})).unwrap();
        crate::recognition_corrections::check(&spec).unwrap();
    }

    #[test]
    fn numeric_declared_names_remain_authored_not_unmigrated_ranks() {
        let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("tests/fixtures/parts/mounting_plate.step");
        let (_, a) = crate::model::analyse_native(&path).unwrap();
        let spec: Spec = serde_json::from_value(serde_json::json!({
            "feature_declarations":[{"id":"f:declared:123", "kind":"hole", "faces":["face:6"]}]
        }))
        .unwrap();
        let result = migrate(&spec, &a).unwrap();
        assert_eq!(result.spec.feature_declarations[0].id, "f:declared:123");
        assert!(result.migrated.is_empty());
        assert!(result.unmapped.is_empty());
        assert!(!result.ids.contains_key("f:declared:123"));
    }

    #[test]
    fn migration_refuses_nonfinite_optional_numbers_instead_of_erasing_them() {
        let a: Analysis = serde_json::from_str(include_str!(
            "../tests/fixtures/identity/m10020.analysis7.json"
        ))
        .unwrap();
        for schema in [
            "draftwright.spec/1",
            "draftwright.spec/2",
            "draftwright.spec/3",
        ] {
            for value in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
                for path in [
                    "iso_scale_factor",
                    "sheet/view_gutter",
                    "sheet/frame_gutter",
                    "views/front/break/gap",
                    "features/f:declared:thread/thread/length",
                ] {
                    let mut s: Spec = serde_json::from_value(serde_json::json!({"schema":schema,
                        "views":{"front":{"break":{"gap":6.}}},
                        "features":{"f:declared:thread":{"thread":{"designation":"M6","length":10.}}}
                    })).unwrap();
                    match path {
                        "iso_scale_factor" => s.iso_scale_factor = Some(value),
                        "sheet/view_gutter" => s.sheet.view_gutter = Some(value),
                        "sheet/frame_gutter" => s.sheet.frame_gutter = Some(value),
                        "views/front/break/gap" => {
                            s.views
                                .get_mut("front")
                                .unwrap()
                                .broken
                                .as_mut()
                                .unwrap()
                                .gap = Some(value)
                        }
                        _ => {
                            s.features
                                .get_mut("f:declared:thread")
                                .unwrap()
                                .thread
                                .as_mut()
                                .unwrap()
                                .length = Some(value)
                        }
                    }
                    let error = migrate(&s, &a)
                        .err()
                        .expect("non-finite authored value must be refused");
                    assert_eq!(error.path.as_deref(), Some(path));
                    assert!(error.message.contains(path), "{error}");
                    assert_eq!(s.schema, schema);
                }
            }
        }
    }

    #[test]
    fn stable_cutoff_compares_prereleases_by_their_release_core() {
        for schema in ["draftwright.spec/1", "draftwright.spec/2"] {
            for v in ["0.2.15", "0.6.0", "0.6.8", "0.6.8-alpha.1", "0.6.8+build.1"] {
                assert!(refusal(schema, v).is_none(), "{schema} at {v}");
            }
            for v in [
                "0.6.9-alpha.1",
                "0.6.9",
                "0.6.9+build.1",
                "0.7.0-alpha.1",
                "0.7.0",
                "0.7.9",
                "0.8.0-dev.1",
            ] {
                let message = refusal(schema, v).unwrap();
                assert!(message.contains(&format!("draftwright {v} no longer reads")));
                assert!(message.contains("draftwright 0.6.8, the last compatible release"));
                assert!(refusal("draftwright.spec/3", v).is_none());
            }
        }
    }

    #[test]
    fn a_live_faceless_ladder_key_in_spec3_is_not_an_unmigrated_identity() {
        let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("tests/fixtures/recognition/steps/stepped_block.step");
        let (_, mut a) = crate::model::analyse_native(&path).unwrap();
        a.features.clear();
        a.level_supports.clear();
        a.risers.clear();
        a.face_attachments.clear();
        a.edge_ink = None;
        let spec: Spec = serde_json::from_value(serde_json::json!({"schema":"draftwright.spec/3",
            "dimensions":{"d:step_level/step_height.length.h10":{}}}))
        .unwrap();
        let p = crate::model::plan(&a, &spec).unwrap();
        assert!(
            p.dimensions
                .iter()
                .any(|d| d.id == "d:step_level/step_height.length.h10")
        );
        assert!(!p.problems.iter().any(|p| p.code == "id_not_migrated"));
        assert!(migrate(&spec, &a).unwrap().unmapped.is_empty());
        let prose: Spec = serde_json::from_value(
            serde_json::json!({"notes":[{"id":"n:1","text":"step_height.length.h99"}]}),
        )
        .unwrap();
        assert!(
            migrate(&prose, &a).unwrap().unmapped.is_empty(),
            "prose is not an identity key"
        );
    }

    #[test]
    fn approved_refusal_and_window() {
        assert!(refusal("draftwright.spec/2", "0.6.8").is_none());
        assert_eq!(
            refusal("draftwright.spec/2", "0.6.9").unwrap(),
            "This Spec is draftwright.spec/2, which draftwright 0.6.9 no longer reads: it reads only draftwright.spec/3, whose feature and step IDs are named by faces rather than by rank or measured value. Convert it once with draftwright 0.6.8, the last compatible release: run `draftwright plan PART.step --spec FILE` and keep the `spec` it prints. Then open the converted Spec here."
        );
        assert_eq!(
            refusal("draftwright.spec/1", "0.6.9"),
            refusal("draftwright.spec/2", "0.6.9").map(|s| s.replacen(
                "draftwright.spec/2",
                "draftwright.spec/1",
                1
            ))
        );
    }
    #[test]
    fn migration_leaves_free_text_alone_and_both_entry_points_agree() {
        let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("tests/fixtures/parts/mounting_plate.step");
        let (_, a) = crate::model::analyse_native(&path).unwrap();
        let note = "DEBURR f:hole:1 AND f:hole:2 BEFORE PLATING";
        let doc = |schema: &str| -> Spec {
            serde_json::from_value(serde_json::json!({
                "schema": schema,
                "notes": [{"id": "n:1", "text": note}],
                "sheet": {"title": {"title": "BRACKET f:hole:3"}},
                "tables": [{"id": "t:1", "rows": [["ITEM"], ["f:hole:1"]]}],
                "annotations": {"n:1": {"text": {"template": "see f:hole:1"}}},
                "precision": {"d:f:hole:1/bore.diameter": 2}
            }))
            .unwrap()
        };
        // Current Spec: prose is untouched by either path; the open path still recovers a
        // rank key an older reader marked spec/3, which set_spec (already opened) does not.
        let current = doc("draftwright.spec/3");
        let new = &ids(&a)["f:hole:1"];
        let opened = migrate(&current, &a).unwrap().spec;
        let set = crate::model::migrate(&current, &a).unwrap();
        for out in [&opened, &set] {
            assert_eq!(out.notes, current.notes);
            assert_eq!(out.sheet.title, current.sheet.title);
            assert_eq!(out.tables, current.tables);
            assert_eq!(out.annotations, current.annotations);
        }
        assert!(
            opened
                .precision
                .contains_key(&format!("d:{new}/bore.diameter"))
        );
        assert_eq!(set, current);
        // Legacy Spec: ID keys move, prose does not, and the entry points agree.
        let legacy = doc("draftwright.spec/2");
        let opened = migrate(&legacy, &a).unwrap();
        let set = crate::model::migrate(&legacy, &a).unwrap();
        assert_eq!(opened.spec, set);
        let out = opened.spec;
        assert_eq!(out.notes[0].text, note);
        assert_eq!(out.sheet.title["title"], "BRACKET f:hole:3");
        assert_eq!(out.tables, legacy.tables);
        assert_eq!(out.annotations, legacy.annotations);
        assert!(
            out.precision
                .contains_key(&format!("d:{new}/bore.diameter"))
        );
        assert!(!out.precision.contains_key("d:f:hole:1/bore.diameter"));
        assert!(opened.migrated.iter().all(|m| !m.path.contains("notes")
            && !m.path.contains("title")
            && !m.path.contains("tables")
            && !m.path.contains("annotations/n:1/text")));
        assert!(opened.unmapped.is_empty(), "{:?}", opened.unmapped);
    }

    #[test]
    fn exact_whole_document_rename_and_collision() {
        let map = BTreeMap::from([("f:hole:1".into(), "f:hole:f21".into())]);
        let v = serde_json::json!({"dimensions":{"d:f:hole:1/bore.diameter":{}}, "sheet":{"origin":"f:hole:1"}, "notes":[{"text":"p:problem:d:f:hole:1/bore.diameter|f:hole:10"}]});
        let n = crate::revision_rename::rename_spec(&v, &map).unwrap();
        assert!(n["dimensions"].get("d:f:hole:f21/bore.diameter").is_some());
        assert_eq!(n["sheet"]["origin"], "f:hole:f21");
        assert_eq!(
            n["notes"][0]["text"],
            "p:problem:d:f:hole:f21/bore.diameter|f:hole:10"
        );
        assert!(
            crate::revision_rename::rename_spec(
                &serde_json::json!({"f:hole:1":1,"f:hole:f21":2}),
                &map
            )
            .is_err()
        );
    }
}