quiddity 0.5.2

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
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
//! `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` (`crate::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 `crate::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. The command line is parsed by clap:
//! `-h`/`--help` (on any command) prints the help on stdout and exits 0, `--version` the version.
//!
//! `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
//! (`crate::serve` has the protocol); exits 0 at the end of the input.
//!
//! `quiddity completions <SHELL>`: a completion script for bash, zsh, fish, powershell or
//! elvish, on stdout.

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

use clap::{Args, CommandFactory, Parser, Subcommand};

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

#[cfg(feature = "json-import")]
#[path = "bin/quiddity/pmi_interchange.rs"]
mod pmi_interchange;

const AFTER_HELP: &str =
    "`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).

Exit status: 0 with the JSON on stdout; 1 with the error on stderr when a file cannot be read
or an operation is refused; 2 for wrong usage. `quiddity <command> --help` gives a command's
arguments.";

/// The command line. Values that were always checked here (`--part`, `--mode`,
/// `--presentation`) are kept as text and checked by [`main`], with their own messages; only the
/// shape of the command line is clap's.
#[derive(Parser)]
#[command(
    name = "quiddity",
    bin_name = "quiddity",
    version,
    about = "Manufacturing feature recognition from STEP B-rep models",
    after_help = AFTER_HELP,
    args_conflicts_with_subcommands = true,
    arg_required_else_help = true,
    disable_help_subcommand = true
)]
struct Cli {
    /// recognise the part's features and print them as JSON
    #[arg(value_name = "FILE.STEP", allow_hyphen_values = true)]
    file: Option<String>,
    #[command(subcommand)]
    command: Option<Command>,
}

#[derive(Subcommand)]
enum Command {
    /// scan STEP product ranges and write only the requested manifest
    Manifest {
        #[arg(value_name = "FILE.STEP")]
        file: String,
        #[arg(short = 'o', long = "output", value_name = "MANIFEST.JSON")]
        out: String,
        /// directory for a temporary mapped index (deleted after scanning)
        #[arg(long, value_name = "DIR")]
        index_dir: Option<PathBuf>,
    },
    /// recognise selected products in their own coordinates through a manifest
    Recognise {
        #[arg(value_name = "FILE.STEP")]
        file: String,
        #[arg(long, value_name = "MANIFEST.JSON")]
        manifest: String,
        #[arg(long, value_name = "DIR")]
        out_dir: PathBuf,
        #[arg(long, value_delimiter = ',', value_name = "p0,p7,…")]
        parts: Option<Vec<String>>,
        /// also read and hash the entire source
        #[arg(long)]
        verify_source: bool,
        /// use size-only staleness checks (also skips common/header hashes)
        #[arg(long)]
        no_product_hashes: bool,
        /// parse the whole source for shared geometry; memory grows with the entire file
        #[arg(long)]
        fallback_whole_file: bool,
    },
    /// match two revisions' features and print the correspondence as JSON
    Correspond {
        /// the old revision: a recognition result written by `quiddity <file.step>`, or a STEP
        /// file
        #[arg(value_name = "OLD.JSON|OLD.STEP", allow_hyphen_values = true)]
        old: String,
        /// the new revision, likewise
        #[arg(value_name = "NEW.JSON|NEW.STEP", allow_hyphen_values = true)]
        new: String,
    },
    /// print the part's recognition evidence as JSON
    Evidence {
        #[arg(value_name = "FILE.STEP", allow_hyphen_values = true)]
        file: String,
        /// in the part's own frame, with the frame given
        #[arg(long)]
        framed: bool,
    },
    /// print the part's feature fingerprints as JSON
    Fingerprints {
        #[arg(value_name = "FILE.STEP", allow_hyphen_values = true)]
        file: String,
    },
    /// print this build's versioned capabilities as JSON
    Capabilities,
    /// answer JSON-lines requests (`recognise`, `correspond`) on stdin, one response line each on
    /// stdout
    Serve,
    /// list the file's distinct parts and the binding that face and edge numbers refer to
    Parts {
        #[arg(value_name = "FILE.STEP", allow_hyphen_values = true)]
        file: String,
    },
    /// read, check and write AP242 semantic PMI
    #[command(subcommand_required = true, arg_required_else_help = true)]
    Pmi {
        #[command(subcommand)]
        command: Pmi,
    },
    /// write the B-rep and its PMI to a new AP242 file
    Brep(BrepArgs),
    /// print a shell completion script to stdout
    Completions {
        #[arg(value_enum)]
        shell: clap_complete::Shell,
    },
}

#[derive(Subcommand)]
enum Pmi {
    /// print the semantic PMI of every part (or part N) and the reader's findings
    Read {
        #[arg(value_name = "FILE.STEP", allow_hyphen_values = true)]
        file: String,
        /// only part N, as `quiddity parts` lists them
        #[arg(long, value_name = "N", allow_hyphen_values = true)]
        part: Option<String>,
    },
    /// check a PMI document against the file and print it in its canonical form
    Check {
        #[arg(value_name = "FILE.STEP", allow_hyphen_values = true)]
        file: String,
        #[arg(value_name = "PMI.JSON", allow_hyphen_values = true)]
        json: String,
    },
    /// write a PMI document's parts into the file as AP242 semantic PMI, verified by reading it
    /// back
    Write(WriteArgs),
    /// PMI interchange: the versioned semantic and presentation JSON schemas
    #[cfg(feature = "json-import")]
    #[command(subcommand_required = true, arg_required_else_help = true)]
    Json {
        #[command(subcommand)]
        command: pmi_interchange::JsonCommand,
    },
}

/// Prints *message* as a usage error of the command at *path*, with that command's usage; 2.
fn usage_error(path: &[&str], message: &str) -> u8 {
    let mut command = Cli::command();
    command.build();
    let mut sub = &mut command;
    for name in path {
        sub = sub
            .find_subcommand_mut(name)
            .expect("the command line has the command");
    }
    eprintln!("quiddity: {message}\n{}", sub.render_usage());
    2
}

/// Run the Rust command line on arguments after the program name.
pub fn main(args: &[String]) -> u8 {
    let argv = std::iter::once("quiddity").chain(args.iter().map(String::as_str));
    let cli = match Cli::try_parse_from(argv) {
        Ok(cli) => cli,
        Err(e) => {
            let _ = e.print();
            return u8::try_from(e.exit_code()).unwrap_or(2);
        }
    };
    let command = match (cli.file, cli.command) {
        (Some(path), _) => {
            return print(recognise(&path).map_err(|failure| failure.to_string()));
        }
        (None, Some(command)) => command,
        (None, None) => return usage_error(&[], "a STEP file or a command is needed"),
    };
    let result = match command {
        Command::Manifest {
            file,
            out,
            index_dir,
        } => {
            return finish(manifest_write(&file, &out, index_dir));
        }
        Command::Recognise {
            file,
            manifest,
            out_dir,
            parts,
            verify_source,
            no_product_hashes,
            fallback_whole_file,
        } => {
            return finish(manifest_recognise(
                &file,
                &manifest,
                &out_dir,
                parts.as_deref(),
                verify_source,
                no_product_hashes,
                fallback_whole_file,
            ));
        }
        Command::Serve => {
            return match serve::serve(std::io::stdin().lock(), std::io::stdout().lock()) {
                Ok(()) => 0,
                Err(error) => {
                    eprintln!("quiddity: serve: {error}");
                    1
                }
            };
        }
        Command::Completions { shell } => {
            clap_complete::generate(
                shell,
                &mut Cli::command(),
                "quiddity",
                &mut std::io::stdout(),
            );
            return 0;
        }
        Command::Capabilities => Ok(crate::file_api::capabilities()),
        Command::Fingerprints { file } => crate::file_api::fingerprints_file(&file),
        Command::Evidence { file, framed } => crate::file_api::evidence_file(&file, framed),
        Command::Correspond { old, new } => {
            correspond(&old, &new).map_err(|failure| failure.to_string())
        }
        Command::Parts { file } => parts(&file),
        Command::Brep(b) => brep(&b),
        #[cfg(feature = "json-import")]
        Command::Pmi {
            command: Pmi::Json { command },
        } => pmi_interchange::run(command),
        Command::Pmi {
            command: Pmi::Read { file, part },
        } => match part.map(|n| n.parse::<usize>().map_err(|_| n)).transpose() {
            Ok(part) => pmi_read(&file, part),
            Err(n) => {
                return usage_error(
                    &["pmi", "read"],
                    &format!("--part takes a part index, not {n:?}"),
                );
            }
        },
        Command::Pmi {
            command: Pmi::Check { file, json },
        } => pmi_check(&file, &json),
        Command::Pmi {
            command: Pmi::Write(w),
        } => match w.options() {
            Ok((mode, policy)) => pmi_write(&w, mode, policy),
            Err(e) => return usage_error(&["pmi", "write"], &e),
        },
    };
    print(result)
}

/// The JSON on stdout (0), or the error on stderr (1).
fn print(result: Result<String, String>) -> u8 {
    match result {
        Ok(json) => {
            println!("{json}");
            0
        }
        Err(error) => {
            eprintln!("quiddity: {error}");
            1
        }
    }
}

/// 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 = step_bytes(path)?;
    crate::file_api::parts(&bytes.step, bytes.binding_bytes()).map_err(|e| format!("{path}: {e}"))
}

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 = crate::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.
#[derive(Args)]
struct BrepArgs {
    #[arg(value_name = "FILE.STEP")]
    step: String,
    /// the new AP242 file (gzipped when its name ends in .gz)
    #[arg(
        short = 'o',
        long = "output",
        value_name = "OUT.STEP",
        allow_hyphen_values = true
    )]
    out: String,
    /// write this PMI document's part PMI in place of the file's (bound to this file by `pmi
    /// read` or `pmi check`; the file must have one part)
    #[arg(long, value_name = "PMI.JSON", allow_hyphen_values = true)]
    pmi: Option<String>,
}

/// 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 crate::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 = crate::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 = crate::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 => (
            crate::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",
                        }));
                    }
                }
            }
            (
                crate::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::new(stem).with_pmi(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 mut 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<_>>(),
    });
    if !report.long_strings.is_empty() {
        json["long_strings"] = serde_json::json!(report.long_strings.iter().map(|w|
            serde_json::json!({"record": w.record, "encoded_bytes": w.encoded_bytes, "byte_offset": w.byte_offset, "message": w.to_string()})
        ).collect::<Vec<_>>());
    }
    Ok(serde_json::to_string_pretty(&json).expect("JSON serialises"))
}

/// `pmi write`'s arguments.
#[derive(Args)]
struct WriteArgs {
    #[arg(value_name = "FILE.STEP")]
    step: String,
    #[arg(value_name = "PMI.JSON")]
    json: String,
    /// the output file (gzipped when its name ends in .gz), written only when it verifies
    #[arg(
        short = 'o',
        long = "output",
        value_name = "OUT.STEP",
        allow_hyphen_values = true
    )]
    out: String,
    /// add (the default) beside each part's PMI, replace it, or remove it
    #[arg(long, value_name = "add|replace|remove", allow_hyphen_values = true)]
    mode: Option<String>,
    /// for replace and remove: remove the presentation of the PMI removed (the default), or
    /// refuse naming it
    #[arg(long, value_name = "refuse|remove", allow_hyphen_values = true)]
    presentation: Option<String>,
    /// a presentation JSON document to draw the written PMI from
    #[cfg(feature = "json-import")]
    #[arg(long, value_name = "FILE", allow_hyphen_values = true)]
    source_presentation: Option<String>,
}

impl WriteArgs {
    /// The mode and presentation policy; a usage error names what is wrong.
    fn options(&self) -> Result<(Mode, PresentationPolicy), String> {
        let mode = match self.mode.as_deref() {
            None | Some("add") => Mode::Add,
            Some("replace") => Mode::Replace,
            Some("remove") => Mode::Remove,
            Some(v) => return Err(format!("--mode takes add, replace or remove, not {v:?}")),
        };
        let policy = match self.presentation.as_deref() {
            None => None,
            Some("refuse") => Some(PresentationPolicy::Refuse),
            Some("remove") => Some(PresentationPolicy::RemovePresentation),
            Some(v) => return Err(format!("--presentation takes refuse or remove, not {v:?}")),
        };
        if mode == Mode::Add && policy.is_some() {
            return Err("--presentation applies to replace and remove, not add".into());
        }
        Ok((
            mode,
            policy.unwrap_or(PresentationPolicy::RemovePresentation),
        ))
    }
}

fn pmi_write(w: &WriteArgs, mode: Mode, policy: PresentationPolicy) -> 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 = crate::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 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();
    #[cfg(feature = "json-import")]
    let source = if let Some(path) = &w.source_presentation {
        if pmi.len() != 1 {
            return Err("--source-presentation requires exactly one selected part".into());
        }
        let text = std::fs::read_to_string(path).map_err(|e| format!("{path}: {e}"))?;
        let value = crate::kernel::json::parse(&text).map_err(|e| format!("{path}: {e}"))?;
        let presentation = crate::kernel::json::presentation::from_value(value)
            .map_err(|e| format!("{path}: {e}"))?;
        vec![(pmi[0].0, presentation)]
    } else {
        Vec::new()
    };
    #[cfg(feature = "json-import")]
    let result = crate::kernel::pmi::write::write_with_presentation(
        &doc, &defs, &pmi, mode, policy, &source,
    );
    #[cfg(not(feature = "json-import"))]
    let result = crate::kernel::pmi::write(&doc, &defs, &pmi, mode, policy);
    let (edit, report) = result.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<crate::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 = crate::kernel::pmi::read(&doc1, &defs1).map_err(|e| e.to_string())?;
        let snapshot = Snapshot::new;
        pmi::verify(
            snapshot(&doc, &defs, &before),
            &doc,
            &pmi,
            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(mode, policy, &parts, &input, &output, &report, &findings);
    Ok(serde_json::to_string_pretty(&json).expect("JSON serialises"))
}

/// File-producing commands have no stdout payload.
fn finish(result: Result<(), String>) -> u8 {
    match result {
        Ok(()) => 0,
        Err(error) => {
            eprintln!("quiddity: {error}");
            1
        }
    }
}

fn manifest_write(path: &str, out: &str, index_dir: Option<PathBuf>) -> Result<(), String> {
    let mut options = crate::kernel::step::manifest::ScanOptions::default();
    options.index_dir = index_dir;
    let manifest = crate::file_api::manifest(path, &options)?;
    std::fs::write(out, crate::file_api::json(&manifest)?).map_err(|e| format!("{out}: {e}"))
}

#[derive(serde::Serialize)]
struct ProductRefusal {
    product: String,
    reason: String,
    /// True only when a shared-geometry range refusal was recovered by an explicit fallback.
    recovered: bool,
}

/// Replace an output atomically; every temporary file stays inside the output directory.
fn atomic_json(path: &Path, json: &str) -> Result<(), String> {
    use std::io::Write;
    let parent = path
        .parent()
        .ok_or_else(|| format!("{}: no parent directory", path.display()))?;
    let mut temp = tempfile::Builder::new()
        .prefix(".quiddity-")
        .tempfile_in(parent)
        .map_err(|e| format!("{}: {e}", path.display()))?;
    temp.write_all(json.as_bytes())
        .map_err(|e| format!("{}: {e}", path.display()))?;
    temp.persist(path)
        .map_err(|e| format!("{}: {e}", path.display()))?;
    Ok(())
}

fn remove_output(path: &Path) -> Result<(), String> {
    match std::fs::remove_file(path) {
        Ok(()) => Ok(()),
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
        Err(e) => Err(format!("{}: {e}", path.display())),
    }
}

/// Pretty output identical to the full assembly JSON, retaining one instance only.
struct AssemblyStream<W: std::io::Write> {
    out: W,
    first: bool,
}
impl<W: std::io::Write> AssemblyStream<W> {
    fn new(mut out: W) -> Result<Self, String> {
        out.write_all(b"{\n  \"instances\": [")
            .map_err(|e| e.to_string())?;
        Ok(Self { out, first: true })
    }
    fn instance(&mut self, i: &crate::kernel::step::manifest::Instance) -> Result<(), String> {
        if !self.first {
            self.out.write_all(b",").map_err(|e| e.to_string())?;
        }
        self.out.write_all(b"\n").map_err(|e| e.to_string())?;
        self.first = false;
        let value = serde_json::to_value(i).map_err(|e| e.to_string())?;
        for (n, line) in serde_json::to_string_pretty(&value)
            .map_err(|e| e.to_string())?
            .lines()
            .enumerate()
        {
            if n > 0 {
                self.out.write_all(b"\n").map_err(|e| e.to_string())?;
            }
            write!(self.out, "    {line}").map_err(|e| e.to_string())?;
        }
        Ok(())
    }
    fn finish(mut self, source: &crate::kernel::step::manifest::Source) -> Result<(), String> {
        if !self.first {
            self.out.write_all(b"\n  ").map_err(|e| e.to_string())?;
        }
        self.out
            .write_all(b"],\n  \"source\": ")
            .map_err(|e| e.to_string())?;
        let value = serde_json::to_value(source).map_err(|e| e.to_string())?;
        for (n, line) in serde_json::to_string_pretty(&value)
            .map_err(|e| e.to_string())?
            .lines()
            .enumerate()
        {
            if n > 0 {
                self.out.write_all(b"\n  ").map_err(|e| e.to_string())?;
            }
            self.out
                .write_all(line.as_bytes())
                .map_err(|e| e.to_string())?;
        }
        self.out.write_all(b"\n}\n").map_err(|e| e.to_string())?;
        self.out.flush().map_err(|e| e.to_string())
    }
}

fn manifest_recognise(
    path: &str,
    manifest_path: &str,
    out: &Path,
    parts: Option<&[String]>,
    verify_source: bool,
    no_product_hashes: bool,
    fallback: bool,
) -> Result<(), String> {
    use crate::kernel::step::{StepFile, manifest::Manifest};
    use std::collections::HashMap;
    // Stage beside the nearest existing output ancestor, on the destination's
    // filesystem, without creating an output directory for an invalid manifest.
    let parent = out
        .ancestors()
        .find(|p| p.is_dir())
        .unwrap_or_else(|| Path::new("."));
    let mut assembly_temp = tempfile::Builder::new()
        .prefix(".quiddity-assembly-")
        .tempfile_in(parent)
        .map_err(|e| e.to_string())?;
    let mut assembly_stream = AssemblyStream::new(std::io::BufWriter::new(&mut assembly_temp))?;
    let input = std::io::BufReader::new(
        std::fs::File::open(manifest_path).map_err(|e| format!("{manifest_path}: {e}"))?,
    );
    let mut manifest: Manifest = if let Some(parts) = parts {
        Manifest::read_selected(input, parts, |i| {
            assembly_stream
                .instance(&i)
                .map_err(crate::kernel::step::StepError::Unsupported)
        })
        .map_err(|e| format!("{manifest_path}: {e}"))?
    } else {
        let m: Manifest =
            serde_json::from_reader(input).map_err(|e| format!("{manifest_path}: {e}"))?;
        for i in &m.instances {
            assembly_stream.instance(i)?;
        }
        m
    };
    assembly_stream.finish(&manifest.source)?;
    let ids = crate::file_api::product_ids(&manifest, parts)?;
    let file = std::fs::File::open(path).map_err(|e| format!("{path}: {e}"))?;
    let mut magic = [0; 2];
    let mut input = &file;
    let n = std::io::Read::read(&mut input, &mut magic).map_err(|e| e.to_string())?;
    if manifest.source.compressed || (n == 2 && magic == [31, 139]) {
        return Err(format!(
            "{path}: compressed source cannot be read by ranges; supply an uncompressed source and rescan"
        ));
    }
    if file.metadata().map_err(|e| e.to_string())?.len() != manifest.source.size {
        return Err(format!("{path}: source size mismatch"));
    }
    if no_product_hashes {
        manifest.common.sha256 = None;
        for p in &mut manifest.products {
            p.sha256 = None;
        }
    }
    let mut shared_by_product: HashMap<&str, Vec<_>> = HashMap::new();
    for refusal in &manifest.refusals {
        for id in &refusal.products {
            shared_by_product
                .entry(id.as_str())
                .or_default()
                .push(refusal);
        }
    }
    let needs_fallback = fallback
        && ids
            .iter()
            .any(|id| shared_by_product.contains_key(id.as_str()));
    // When fallback needs the entire snapshot, hash those exact bytes once and reuse them.
    // Without fallback the explicit verification remains a streaming whole-source read.
    let mut verified_snapshot = if verify_source && needs_fallback {
        let bytes = std::fs::read(path).map_err(|e| format!("{path}: {e}"))?;
        manifest
            .verify_source(std::io::Cursor::new(&bytes))
            .map_err(|e| format!("{path}: {e}"))?;
        Some(bytes)
    } else {
        if verify_source {
            manifest
                .verify_source(&file)
                .map_err(|e| format!("{path}: {e}"))?;
        }
        None
    };
    for directory in ["products", "refusals"] {
        std::fs::create_dir_all(out.join(directory))
            .map_err(|e| format!("{}: {e}", out.display()))?;
    }
    assembly_temp
        .persist(out.join("assembly.json"))
        .map_err(|e| e.to_string())?;
    let mut whole = None;
    let mut failed = false;
    for id in &ids {
        let shared: Vec<_> = shared_by_product
            .get(id.as_str())
            .into_iter()
            .flatten()
            .map(|r| format!("{} (shared entity #{})", r.reason, r.entity))
            .collect();
        let mut recovered = false;
        let result = if shared.is_empty() {
            crate::file_api::recognise_product_with_warnings(path, &manifest, id)
        } else if fallback {
            if whole.is_none() {
                whole = Some((|| -> Result<_, String> {
                    let bytes = match verified_snapshot.take() {
                        Some(bytes) => bytes,
                        None => std::fs::read(path).map_err(|e| format!("{path}: {e}"))?,
                    };
                    if bytes.len() as u64 != manifest.source.size {
                        return Err(format!("{path}: source size mismatch"));
                    }
                    if !no_product_hashes && !verify_source {
                        manifest
                            .verify_source(std::io::Cursor::new(&bytes))
                            .map_err(|e| format!("{path}: {e}"))?;
                    }
                    let whole = StepFile::read(&bytes).map_err(|e| format!("{path}: {e}"))?;
                    let indices: HashMap<_, _> = whole
                        .parts
                        .iter()
                        .enumerate()
                        .map(|(i, p)| (p.product_definition, i))
                        .collect();
                    Ok((whole, indices))
                })());
            }
            let product = manifest.product(id).map_err(|e| e.to_string())?;
            whole
                .as_ref()
                .expect("fallback attempted")
                .as_ref()
                .map_err(|e| format!("product {id}: whole-file fallback failed: {e}"))
                .and_then(|(whole, indices)| {
                    let index = *indices.get(&product.product_definition).ok_or_else(|| {
                        format!("product {id}: definition missing from whole source")
                    })?;
                    let definition = &whole.parts[index];
                    if definition.faces != product.faces
                        || definition.edges.len() as u64 != product.edge_count
                    {
                        return Err(format!(
                            "product {id}: face order or edge count differs from manifest"
                        ));
                    }
                    whole.part(index).map_err(|e| format!("product {id}: {e}"))
                })
                .and_then(|part| {
                    crate::file_api::recognise_part_with_warnings(
                        &part,
                        &manifest.source.sha256,
                        path,
                    )
                })
                .inspect(|_| recovered = true)
        } else {
            Err(format!(
                "product {id}: {}; retry with --fallback-whole-file (parses the entire source)",
                shared.join("; ")
            ))
        };
        let dest = out.join("products").join(format!("{id}.json"));
        let refusal = match result {
            Ok((json, warnings)) => {
                for warning in warnings {
                    eprintln!("quiddity: product {id}: {warning}");
                }
                atomic_json(&dest, &json)?;
                recovered.then(|| ProductRefusal {
                    product: id.clone(),
                    reason: shared.join("; "),
                    recovered: true,
                })
            }
            Err(reason) => {
                remove_output(&dest)?;
                eprintln!("quiddity: {reason}");
                failed = true;
                Some(ProductRefusal {
                    product: id.clone(),
                    reason,
                    recovered: false,
                })
            }
        };
        let dest = out.join("refusals").join(format!("{id}.json"));
        if let Some(refusal) = refusal {
            atomic_json(&dest, &crate::file_api::json(&refusal)?)?;
        } else {
            remove_output(&dest)?;
        }
    }
    if failed {
        return Err(format!(
            "product recognition refused; see {}",
            out.join("refusals").display()
        ));
    }
    Ok(())
}