quiddity 0.2.5

Manufacturing feature recognition from STEP B-rep models: holes, bosses, pockets, slots, steps, patterns and turned features, with measured sizes.
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
//! `quiddity <file.step>`: recognise a STEP file's features and print them as JSON: each
//! family's records at the top level, their `fingerprints`, and the versioned recognition
//! `document` (`quiddity::recognition`: per feature its family, Python record type, defining
//! faces and record). The part is recognised in its own frame and the records reported in the
//! file's coordinates; nonprincipal directions use vectors and record-owned origins. The
//! document gives the recognition frame as provenance. A part with no frame (no plane or cylinder, no material)
//! is recognised as placed in the file, with a warning on stderr.
//!
//! `quiddity correspond <old> <new>`: match two revisions and print the correspondence as JSON.
//! Each revision is a recognition result written by `quiddity <file.step>`, or a STEP file
//! (recognised on the spot).
//!
//! `quiddity parts <file.step>`: the file's distinct parts (index, name, face and edge counts,
//! placements) and the binding (the STEP text's sha256 and the PMI reader version) that face
//! and edge numbers refer to.
//!
//! `quiddity pmi read <file.step> [--part N]`: the semantic PMI of every part (or part N) and
//! the reader's findings, in the versioned JSON form of `quiddity::pmi_json`.
//!
//! `quiddity pmi check <file.step> <pmi.json>`: decodes a PMI document and checks it against
//! the file (binding, part indices and names, face and edge numbers, the model's invariants);
//! prints the document in its canonical form, or refuses naming the JSON path.
//!
//! `quiddity pmi write <file.step> <pmi.json> -o <out.step> [--mode add|replace|remove]
//! [--presentation refuse|remove]`: writes the document's parts (all in one `pmi::write`) into
//! the file as AP242 semantic PMI — beside each part's PMI (`add`, the default), in place of it
//! (`replace`), or removing it (`remove`, each part's `pmi` empty) — keeping every other byte.
//! The document must be bound to this file and reader (`pmi read`, `pmi check`). Replace and
//! remove take the presentation of the PMI they remove with it (`--presentation remove`, the
//! default) or refuse naming it (`--presentation refuse`). The output is written to a temporary
//! file beside `out.step` (gzipped when its name ends in `.gz`), read back with `pmi::read` and
//! compared semantically with what was written by `pmi::verify` (add: the part's PMI before plus exactly the
//! items written; replace and remove: exactly the items written, and nothing the reader consumed
//! for the part survives; every other part as before; no finding the input did not have), and
//! renamed to `out.step` only then; prints the write's report as JSON. On any refusal nothing is
//! created.
//!
//! Exit status: 0 with the JSON on stdout; 1 with the error on stderr when a file cannot be
//! read (an unreadable, truncated, incomplete or unsupported STEP file is refused, never
//! recognised as empty), a PMI document is refused, or a write is refused or does not verify;
//! 2 with the usage on stderr for bad arguments. `-h`/`--help` prints the usage on stdout and
//! exits 0.
//!
//! `quiddity brep <file.step> -o <out.step>`: writes the part's B-rep as read (an inverted
//! shell repaired) to a new AP242 file (`haecceity::brep_write`) with its semantic PMI, and
//! prints what the write reports as JSON, with the kernel's volume of each solid. A file of one
//! part carrying PMI is written in that part's own frame, where its PMI is anchored; PMI items
//! not carried (refused by the writer, or of a file of several parts) are listed with why. This
//! is new output, not an edit of the file (`pmi write` edits files in place).
//! `--pmi <pmi.json>` writes the PMI document's part PMI in place of the file's: the document
//! must be bound to this file (`pmi read`, `pmi check`), the file must have one part, and the
//! document must name it.
//!
//! `quiddity serve`: recognition and correspondence as a JSON-lines service on stdin and stdout
//! (`quiddity::serve` has the protocol); exits 0 at the end of the input.

use std::path::{Path, PathBuf};
use std::process::ExitCode;

use quiddity::kernel::p21;
use quiddity::kernel::pmi::write::{Mode, PresentationPolicy};
use quiddity::kernel::pmi::{self, PartId, PartPmi, Snapshot};
use quiddity::kernel::step::{PartDefinition, read_part_definitions};
use quiddity::part_input;
use quiddity::pmi_json::{self, Binding};
use quiddity::serve::{self, Failure};

const USAGE: &str = "usage: quiddity <file.step>
       quiddity correspond <old.json|old.step> <new.json|new.step>
       quiddity serve
       quiddity parts <file.step>
       quiddity pmi read <file.step> [--part N]
       quiddity pmi check <file.step> <pmi.json>
       quiddity pmi write <file.step> <pmi.json> -o <out.step> [--mode add|replace|remove]
                          [--presentation refuse|remove]
       quiddity brep <file.step> -o <out.step> [--pmi <pmi.json>]
                          (B-rep and PMI to a new AP242 file; --pmi: that PMI, not the file's)

`quiddity <file.step>` prints JSON: each family's records, their `fingerprints`, and the
versioned recognition `document`. `quiddity serve` answers JSON-lines requests on stdin
(`recognise`, `correspond`), one response line each on stdout.
With `--features f3d`, part inputs also accept .f3d (geometry only).";

const COMMANDS: [&str; 5] = ["correspond", "serve", "parts", "pmi", "brep"];

fn main() -> ExitCode {
    let args: Vec<String> = std::env::args().skip(1).collect();
    let result = match args.as_slice() {
        [flag] if flag == "-h" || flag == "--help" => {
            println!("{USAGE}");
            return ExitCode::SUCCESS;
        }
        [command] if command == "serve" => {
            return match serve::serve(std::io::stdin().lock(), std::io::stdout().lock()) {
                Ok(()) => ExitCode::SUCCESS,
                Err(error) => {
                    eprintln!("quiddity: serve: {error}");
                    ExitCode::FAILURE
                }
            };
        }
        [command, old, new] if command == "correspond" => {
            correspond(old, new).map_err(|failure| failure.to_string())
        }
        [command, path] if command == "parts" => parts(path),
        [command, rest @ ..] if command == "brep" => match BrepArgs::parse(rest) {
            Ok(b) => brep(&b),
            Err(e) => {
                eprintln!("quiddity: {e}\n{USAGE}");
                return ExitCode::from(2);
            }
        },
        [command, read, path] if command == "pmi" && read == "read" => pmi_read(path, None),
        [command, read, path, flag, n]
            if command == "pmi" && read == "read" && flag == "--part" =>
        {
            match n.parse::<usize>() {
                Ok(n) => pmi_read(path, Some(n)),
                Err(_) => {
                    eprintln!("quiddity: --part takes a part index, not {n:?}\n{USAGE}");
                    return ExitCode::from(2);
                }
            }
        }
        [command, check, path, json] if command == "pmi" && check == "check" => {
            pmi_check(path, json)
        }
        [command, write, rest @ ..] if command == "pmi" && write == "write" => {
            match WriteArgs::parse(rest) {
                Ok(w) => pmi_write(&w),
                Err(e) => {
                    eprintln!("quiddity: {e}\n{USAGE}");
                    return ExitCode::from(2);
                }
            }
        }
        [path] if !COMMANDS.contains(&path.as_str()) => {
            recognise(path).map_err(|failure| failure.to_string())
        }
        _ => {
            eprintln!("{USAGE}");
            return ExitCode::from(2);
        }
    };
    match result {
        Ok(json) => {
            println!("{json}");
            ExitCode::SUCCESS
        }
        Err(error) => {
            eprintln!("quiddity: {error}");
            ExitCode::FAILURE
        }
    }
}

/// Warnings, on stderr: geometry that did not resolve, a part frame that could not be inferred.
fn warn(warnings: Vec<String>) {
    for warning in warnings {
        eprintln!("quiddity: {warning}");
    }
}

fn recognise(path: &str) -> Result<String, Failure> {
    let (output, warning) = serve::recognise_file(path)?;
    warn(warning);
    Ok(serde_json::to_string_pretty(&output).expect("records serialise"))
}

fn correspond(old: &str, new: &str) -> Result<String, Failure> {
    let revision = |path| {
        let (fingerprints, warning) = serve::fingerprints_file(path)?;
        warn(warning);
        Ok::<_, Failure>(fingerprints)
    };
    let c = serve::correspond(&revision(old)?, &revision(new)?)?;
    Ok(serde_json::to_string_pretty(&c).expect("a correspondence serialises"))
}

/// Whether a file name says it is gzipped.
fn gzipped(path: &str) -> bool {
    path.to_lowercase().ends_with(".gz")
}

/// One source snapshot, with its STEP representation and original Fusion binding.
struct Input {
    step: Vec<u8>,
    fusion: Option<Vec<u8>>,
}

impl Input {
    fn binding_bytes(&self) -> &[u8] {
        self.fusion.as_deref().unwrap_or(&self.step)
    }
}

/// Geometry as STEP, gunzipped for STEP and converted for Fusion.
fn step_bytes(path: &str) -> Result<Input, String> {
    let raw = std::fs::read(path).map_err(|e| format!("{path}: {e}"))?;
    if part_input::is_f3d(path) {
        let step = part_input::fusion_step(&raw).map_err(|e| format!("{path}: {e}"))?;
        warn(vec![part_input::fusion_warning(path)]);
        return Ok(Input {
            step,
            fusion: Some(raw),
        });
    }
    if !gzipped(path) {
        return Ok(Input {
            step: raw,
            fusion: None,
        });
    }
    let mut out = Vec::new();
    std::io::Read::read_to_end(&mut flate2::read::GzDecoder::new(&raw[..]), &mut out)
        .map_err(|e| format!("{path}: not gzip ({e})"))?;
    Ok(Input {
        step: out,
        fusion: None,
    })
}

/// A STEP file's text and its distinct parts.
fn part_definitions(path: &str) -> Result<(Input, Vec<PartDefinition>), String> {
    let bytes = step_bytes(path)?;
    let defs = read_part_definitions(&bytes.step).map_err(|e| format!("{path}: {e}"))?;
    Ok((bytes, defs))
}

fn parts(path: &str) -> Result<String, String> {
    let (bytes, defs) = part_definitions(path)?;
    let json = pmi_json::parts_json(&defs, &Binding::of(bytes.binding_bytes()));
    Ok(serde_json::to_string_pretty(&json).expect("JSON serialises"))
}

fn pmi_read(path: &str, part: Option<usize>) -> Result<String, String> {
    let (bytes, defs) = part_definitions(path)?;
    if let Some(n) = part
        && n >= defs.len()
    {
        return Err(format!(
            "{path}: the file has {} parts (0 to {}); there is no part {n}",
            defs.len(),
            defs.len().saturating_sub(1)
        ));
    }
    let binding = Binding::of(bytes.binding_bytes());
    let doc = p21::Document::parse(bytes.step).map_err(|e| format!("{path}: {e}"))?;
    let read = quiddity::kernel::pmi::read(&doc, &defs).map_err(|e| format!("{path}: {e}"))?;
    let document = pmi_json::read_document(&read, &defs, binding, part);
    Ok(
        serde_json::to_string_pretty(&pmi_json::document_to_json(&document))
            .expect("JSON serialises"),
    )
}

fn pmi_check(path: &str, json: &str) -> Result<String, String> {
    let (bytes, defs) = part_definitions(path)?;
    let text = std::fs::read_to_string(json).map_err(|e| format!("{json}: {e}"))?;
    let value = pmi_json::parse(&text).map_err(|e| format!("{json}: not JSON ({e})"))?;
    let document = pmi_json::document_from_json(&value).map_err(|e| format!("{json}: {e}"))?;
    pmi_json::check_against(&document, bytes.binding_bytes(), &defs)
        .map_err(|e| format!("{json}: {e}"))?;
    Ok(
        serde_json::to_string_pretty(&pmi_json::document_to_json(&document))
            .expect("JSON serialises"),
    )
}

/// `brep`'s arguments.
struct BrepArgs {
    step: String,
    out: String,
    pmi: Option<String>,
}

impl BrepArgs {
    /// From the arguments after `brep`; a usage error names what is wrong.
    fn parse(args: &[String]) -> Result<BrepArgs, String> {
        let (mut step, mut out, mut pmi) = (None, None, None);
        let mut it = args.iter();
        while let Some(a) = it.next() {
            let slot = match a.as_str() {
                "-o" | "--output" => &mut out,
                "--pmi" => &mut pmi,
                s if s.starts_with('-') => return Err(format!("unknown option {s:?}")),
                _ => {
                    if step.replace(a.clone()).is_some() {
                        return Err("brep takes one STEP file".into());
                    }
                    continue;
                }
            };
            let v = it.next().ok_or_else(|| format!("{a} takes a value"))?;
            if slot.replace(v.clone()).is_some() {
                return Err(format!("{a} is given twice"));
            }
        }
        Ok(BrepArgs {
            step: step.ok_or("brep takes a STEP file")?,
            out: out.ok_or("brep needs -o <out.step>")?,
            pmi,
        })
    }
}

/// Write the part's B-rep to *out* (gzipped when its name ends in `.gz`); the write's report.
fn brep(args: &BrepArgs) -> Result<String, String> {
    use quiddity::kernel::brep_write::{WriteOptions, write_step};
    let (path, out) = (args.step.as_str(), args.out.as_str());
    let bytes = step_bytes(path)?;
    let items = |p: &PartPmi| pmi::write::differences_as_stated(&PartPmi::default(), p).len();
    // A PMI document given with --pmi is the written part's PMI, in place of the file's: it must
    // be bound to this file (`pmi read`, `pmi check`) and name its only part.
    let given = match &args.pmi {
        None => None,
        Some(json) => {
            let defs = read_part_definitions(&bytes.step).map_err(|e| format!("{path}: {e}"))?;
            let text = std::fs::read_to_string(json).map_err(|e| format!("{json}: {e}"))?;
            let value = pmi_json::parse(&text).map_err(|e| format!("{json}: not JSON ({e})"))?;
            let document =
                pmi_json::document_from_json(&value).map_err(|e| format!("{json}: {e}"))?;
            pmi_json::check_against(&document, bytes.binding_bytes(), &defs)
                .map_err(|e| format!("{json}: {e}"))?;
            if defs.len() != 1 {
                return Err(format!(
                    "{json}: {path} has {} parts; a write carries one part's PMI",
                    defs.len()
                ));
            }
            let [part] = <[_; 1]>::try_from(document.parts)
                .map_err(|_| format!("{json}: must name the file's one part (part 0)"))?;
            let read = quiddity::kernel::step::read_part(&bytes.step, &defs[0])
                .map_err(|e| format!("{path}: {e}"))?;
            Some((read, part.pmi))
        }
    };
    // Without --pmi, the file's PMI: a file of one part is written with it, in the part's own
    // frame; the PMI of a file of several parts is listed as not carried.
    let (given_part, given_pmi) = given.map_or((None, None), |(p, m)| (Some(p), Some(m)));
    let read = match given_part {
        Some(_) => None,
        None => read_part_definitions(&bytes.step).ok().and_then(|defs| {
            let doc = p21::Document::parse(bytes.step.clone()).ok()?;
            let read = quiddity::kernel::pmi::read(&doc, &defs).ok()?;
            Some((defs, read))
        }),
    };
    let mut not_carried = Vec::new();
    let (part, pmi) = match (given_part, &read) {
        (Some(part), _) => (part, given_pmi.as_ref()),
        (None, Some((defs, read))) if defs.len() == 1 && items(&read.parts[0]) > 0 => (
            quiddity::kernel::step::read_part(&bytes.step, &defs[0])
                .map_err(|e| format!("{path}: {e}"))?,
            Some(&read.parts[0]),
        ),
        (None, _) => {
            if let Some((_, read)) = &read {
                for (k, p) in read.parts.iter().enumerate() {
                    if items(p) > 0 {
                        not_carried.push(serde_json::json!({
                            "part": k,
                            "items": items(p),
                            "why": "the file has several parts; a write carries one part's PMI",
                        }));
                    }
                }
            }
            (
                quiddity::kernel::read_step(&bytes.step).map_err(|e| format!("{path}: {e}"))?,
                None,
            )
        }
    };
    let file_name = Path::new(path)
        .file_name()
        .map_or_else(|| "part".to_owned(), |n| n.to_string_lossy().into_owned());
    let lower = file_name.to_lowercase();
    let stem = [".step.gz", ".stp.gz", ".step", ".stp", ".f3d", ".gz"]
        .iter()
        .find(|s| lower.ends_with(*s))
        .map_or(file_name.as_str(), |s| {
            &file_name[..file_name.len() - s.len()]
        });
    let (written, report) =
        write_step(&part, &WriteOptions { name: stem, pmi }).map_err(|e| format!("{path}: {e}"))?;
    let file_bytes = if gzipped(out) {
        let mut enc = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
        std::io::Write::write_all(&mut enc, &written).map_err(|e| e.to_string())?;
        enc.finish().map_err(|e| e.to_string())?
    } else {
        written
    };
    std::fs::write(out, file_bytes).map_err(|e| format!("{out}: {e}"))?;
    let pmi_json = serde_json::json!({
        "carried_items": report.pmi.as_ref().map_or(0, |c| items(&c.written)),
        "refused": report.pmi.as_ref().map_or_else(Vec::new, |c| c
            .refused
            .iter()
            .map(|r| serde_json::json!({"item": format!("{:?}", r.item), "why": r.why}))
            .collect()),
        "parts_not_carried": not_carried,
    });
    let json = serde_json::json!({
        "solids": report.solids,
        "void_shells": report.void_shells,
        "faces": report.faces,
        "surface_model_faces": report.surface_model_faces,
        "edges": report.edges,
        "vertices": report.vertices,
        "pcurves_written": report.pcurves_written,
        "pcurves_not_written": report.pcurves_not_written,
        "surface_kinds_changed": report
            .surface_kinds_changed
            .iter()
            .map(|(face, kind)| serde_json::json!({"face": face, "kind": kind}))
            .collect::<Vec<_>>(),
        "face_order_preserved": report.face_order_preserved,
        "edge_order_preserved": report.edge_order_preserved,
        "placed_components": report.placed_components,
        "placements_flattened": report.placements_flattened,
        "products_renamed": report.products_renamed,
        "repairs_written": report.repairs_written,
        "pmi": pmi_json,
        // The kernel's volume of each solid, for checking the file against other readers.
        "solid_volumes": (0..part.solids.len())
            .map(|s| part.solid_mass(s).map(|(v, _)| v))
            .collect::<Vec<_>>(),
    });
    Ok(serde_json::to_string_pretty(&json).expect("JSON serialises"))
}

/// `pmi write`'s arguments.
struct WriteArgs {
    step: String,
    json: String,
    out: String,
    mode: Mode,
    policy: PresentationPolicy,
}

impl WriteArgs {
    /// From the arguments after `pmi write`; a usage error names what is wrong.
    fn parse(args: &[String]) -> Result<WriteArgs, String> {
        fn once<T>(slot: &mut Option<T>, flag: &str, v: T) -> Result<(), String> {
            if slot.replace(v).is_some() {
                return Err(format!("{flag} is given twice"));
            }
            Ok(())
        }
        let mut positional = Vec::new();
        let (mut out, mut mode, mut policy) = (None, None, None);
        let mut it = args.iter();
        while let Some(a) = it.next() {
            let mut value = || {
                it.next()
                    .cloned()
                    .ok_or_else(|| format!("{a} takes a value"))
            };
            match a.as_str() {
                "-o" | "--output" => once(&mut out, "-o", value()?)?,
                "--mode" => {
                    let v = value()?;
                    let m = match v.as_str() {
                        "add" => Mode::Add,
                        "replace" => Mode::Replace,
                        "remove" => Mode::Remove,
                        _ => return Err(format!("--mode takes add, replace or remove, not {v:?}")),
                    };
                    once(&mut mode, a, m)?;
                }
                "--presentation" => {
                    let v = value()?;
                    let p = match v.as_str() {
                        "refuse" => PresentationPolicy::Refuse,
                        "remove" => PresentationPolicy::RemovePresentation,
                        _ => {
                            return Err(format!(
                                "--presentation takes refuse or remove, not {v:?}"
                            ));
                        }
                    };
                    once(&mut policy, a, p)?;
                }
                s if s.starts_with('-') => return Err(format!("unknown option {s:?}")),
                _ => positional.push(a.clone()),
            }
        }
        let [step, json] = <[String; 2]>::try_from(positional)
            .map_err(|_| "pmi write takes a STEP file and a PMI document".to_string())?;
        let out = out.ok_or("pmi write needs -o <out.step>")?;
        let mode = mode.unwrap_or(Mode::Add);
        if mode == Mode::Add && policy.is_some() {
            return Err("--presentation applies to replace and remove, not add".into());
        }
        Ok(WriteArgs {
            step,
            json,
            out,
            mode,
            policy: policy.unwrap_or(PresentationPolicy::RemovePresentation),
        })
    }
}

fn pmi_write(w: &WriteArgs) -> Result<String, String> {
    if part_input::is_f3d(&w.step) {
        #[cfg(not(feature = "f3d"))]
        part_input::fusion_step(&[]).map_err(|e| format!("{}: {e}", w.step))?;
        return Err(format!(
            "{}: pmi write requires original STEP text; use `brep --pmi` to create a new AP242 STEP file from Fusion geometry",
            w.step
        ));
    }
    let (bytes, defs) = part_definitions(&w.step)?;
    let json = &w.json;
    let text = std::fs::read_to_string(json).map_err(|e| format!("{json}: {e}"))?;
    let value = pmi_json::parse(&text).map_err(|e| format!("{json}: not JSON ({e})"))?;
    let document = pmi_json::document_from_json(&value).map_err(|e| format!("{json}: {e}"))?;
    pmi_json::check_against(&document, bytes.binding_bytes(), &defs)
        .map_err(|e| format!("{json}: {e}"))?;
    if document.parts.is_empty() {
        return Err(format!("{json}: names no part; there is nothing to write"));
    }
    let input = Binding::of(bytes.binding_bytes());
    let step = &w.step;
    let doc = p21::Document::parse(bytes.step).map_err(|e| format!("{step}: {e}"))?;
    let before = quiddity::kernel::pmi::read(&doc, &defs).map_err(|e| format!("{step}: {e}"))?;
    // A standard is a set member, not an item: adding one the part already states (or stating
    // one twice) is that standard, so it is not written again.
    let pmi: Vec<(PartId, PartPmi)> = document
        .parts
        .iter()
        .map(|p| {
            let mut pmi = p.pmi.clone();
            if w.mode == Mode::Add {
                let mut stated = before
                    .parts
                    .get(p.part.0)
                    .map(|old| old.standards.clone())
                    .unwrap_or_default();
                pmi.standards.retain(|s| {
                    let new = !stated.contains(s);
                    if new {
                        stated.push(s.clone());
                    }
                    new
                });
            }
            (p.part, pmi)
        })
        .collect();
    let (edit, report) = quiddity::kernel::pmi::write(&doc, &defs, &pmi, w.mode, w.policy)
        .map_err(|e| format!("{step}: write refused: {e}"))?;
    let written = doc
        .apply(&edit)
        .map_err(|e| format!("{step}: write refused: {e}"))?;

    // Written beside the destination, read back from there, and renamed only when it verifies.
    let out = &w.out;
    // An existing destination is replaced in place: through a symbolic link to its target, and
    // keeping its permissions.
    let dest = Path::new(out);
    let target: PathBuf = match std::fs::symlink_metadata(dest) {
        Ok(m) if m.file_type().is_symlink() => {
            std::fs::canonicalize(dest).map_err(|e| format!("{out}: {e}"))?
        }
        _ => dest.to_path_buf(),
    };
    let name = target
        .file_name()
        .ok_or_else(|| format!("{out}: not a file name"))?
        .to_string_lossy();
    let tmp: PathBuf = target.with_file_name(format!(".{name}.{}.tmp", std::process::id()));
    let verified = (|| -> Result<(Binding, Vec<quiddity::kernel::pmi::Finding>), String> {
        let gz = gzipped(out);
        let file_bytes = if gz {
            let mut enc = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
            std::io::Write::write_all(&mut enc, &written.bytes).map_err(|e| e.to_string())?;
            enc.finish().map_err(|e| e.to_string())?
        } else {
            written.bytes.clone()
        };
        std::fs::write(&tmp, &file_bytes).map_err(|e| format!("{out}: {e}"))?;
        let raw = std::fs::read(&tmp).map_err(|e| format!("{out}: {e}"))?;
        let back = if gz {
            let mut v = Vec::new();
            std::io::Read::read_to_end(&mut flate2::read::GzDecoder::new(&raw[..]), &mut v)
                .map_err(|e| format!("{out}: {e}"))?;
            v
        } else {
            raw
        };
        if back != written.bytes {
            return Err("the file on disk is not what was written".into());
        }
        let defs1 = read_part_definitions(&back).map_err(|e| e.to_string())?;
        let doc1 = p21::Document::parse(back).map_err(|e| e.to_string())?;
        let after = quiddity::kernel::pmi::read(&doc1, &defs1).map_err(|e| e.to_string())?;
        let snapshot = |doc, defs, read| Snapshot { doc, defs, read };
        pmi::verify(
            snapshot(&doc, &defs, &before),
            &doc,
            &pmi,
            w.mode,
            snapshot(&doc1, &defs1, &after),
        )
        .into_result()?;
        Ok((Binding::of(doc1.bytes()), after.findings))
    })();
    let (output, findings) = match verified {
        Ok(v) => v,
        Err(e) => {
            let _ = std::fs::remove_file(&tmp);
            return Err(format!(
                "{out}: not written: the output does not verify: {e}"
            ));
        }
    };
    if let Ok(m) = std::fs::metadata(&target)
        && let Err(e) = std::fs::set_permissions(&tmp, m.permissions())
    {
        let _ = std::fs::remove_file(&tmp);
        return Err(format!("{out}: {e}"));
    }
    if let Err(e) = std::fs::rename(&tmp, &target) {
        let _ = std::fs::remove_file(&tmp);
        return Err(format!("{out}: {e}"));
    }
    let mut parts: Vec<PartId> = pmi.iter().map(|(p, _)| *p).collect();
    parts.sort();
    let json = pmi_json::write_report_json(
        w.mode, w.policy, &parts, &input, &output, &report, &findings,
    );
    Ok(serde_json::to_string_pretty(&json).expect("JSON serialises"))
}