Skip to main content

rustqec_cli/
lib.rs

1use std::ffi::OsString;
2use std::fs;
3use std::io::{Read, Write};
4use std::path::PathBuf;
5
6use clap::{Parser, Subcommand, ValueEnum, error::ErrorKind};
7use serde::Serialize;
8
9mod decode;
10mod pipeline;
11
12pub const SCHEMA_VERSION: &str = "rustqec.cli.v1";
13const CIRCUIT_STATS_COMMAND: &str = "circuit.stats";
14
15#[derive(Debug, Parser)]
16#[command(
17    name = "rustqec",
18    version,
19    about = "Unified RustQEC command line interface"
20)]
21pub struct Cli {
22    /// Select the error channel independently of command output
23    #[arg(long, global = true, value_enum)]
24    error_format: Option<ErrorFormat>,
25    #[command(subcommand)]
26    command: Command,
27}
28
29#[derive(Debug, Subcommand)]
30enum Command {
31    /// Inspect and operate on Stim-like circuits
32    Circuit {
33        #[command(subcommand)]
34        command: CircuitCommand,
35    },
36    /// Discover the commands and contracts implemented by this binary
37    Capabilities {
38        #[arg(long, value_enum)]
39        format: CapabilitiesFormat,
40    },
41    /// Decode a public loss-visible decoder dataset
42    Decode {
43        /// Loss-aware decoder implementation
44        #[arg(long, value_enum)]
45        decoder: DecodeDecoder,
46        /// Directory containing manifest.json, circuit.stim, and shots.b8
47        #[arg(long)]
48        dataset: PathBuf,
49        /// Destination bit-packed observable predictions
50        #[arg(long)]
51        out: PathBuf,
52        /// Destination structured decode statistics
53        #[arg(long = "stats-out")]
54        stats_out: PathBuf,
55        /// Per-shot Envelope-MLE time limit
56        #[arg(long = "shot-timeout-ms")]
57        shot_timeout_ms: Option<u64>,
58    },
59    /// Produce decoder-ready datasets
60    Dataset {
61        #[command(subcommand)]
62        command: DatasetCommand,
63    },
64}
65
66#[derive(Debug, Subcommand)]
67enum DatasetCommand {
68    /// Export a public decoder dataset and private answer bundle
69    Export {
70        /// Circuit file to sample (loss-visible circuits supported)
71        #[arg(long)]
72        circuit: PathBuf,
73        /// Number of shots to sample into the dataset
74        #[arg(long)]
75        shots: u64,
76        /// Dataset mode: detectors or measurements_blinded
77        #[arg(long)]
78        mode: String,
79        /// Destination directory for the public dataset bundle
80        #[arg(long = "public-out")]
81        public_out: PathBuf,
82        /// Destination directory for the private answer bundle
83        #[arg(long = "private-out")]
84        private_out: PathBuf,
85        /// Sampling seed for reproducible datasets
86        #[arg(long)]
87        seed: Option<u64>,
88        /// Apply a logical-X flip on the given data qubits before export
89        #[arg(long = "logical-x-qubits")]
90        logical_x_qubits: Option<String>,
91        /// Apply a logical-Z flip on the given data qubits before export
92        #[arg(long = "logical-z-qubits")]
93        logical_z_qubits: Option<String>,
94        /// Also write a per-shot rstim.error-trace.v1 trace.jsonl into the private bundle
95        #[arg(long = "error-trace")]
96        error_trace: bool,
97        /// Select human-readable or versioned JSON output
98        #[arg(long, value_enum, default_value_t = pipeline::PipelineFormat::Json)]
99        format: pipeline::PipelineFormat,
100    },
101    /// Package a third-party circuit and shot payload into a public dataset
102    Import {
103        /// Loss-visible circuit file (must satisfy subset v1)
104        #[arg(long)]
105        circuit: PathBuf,
106        /// Shot payload file produced by an external sampler
107        #[arg(long)]
108        shots: PathBuf,
109        /// Shot payload encoding: 01 (text rows) or b8 (packed binary)
110        #[arg(long = "shots-format", default_value = "01")]
111        shots_format: String,
112        /// Destination directory for the public dataset bundle
113        #[arg(long)]
114        out: PathBuf,
115        /// Optional rustqec.loss-log.v1 sidecar to cross-check flag bits
116        #[arg(long = "loss-log")]
117        loss_log: Option<PathBuf>,
118        /// Select human-readable or versioned JSON output
119        #[arg(long, value_enum, default_value_t = pipeline::PipelineFormat::Json)]
120        format: pipeline::PipelineFormat,
121    },
122}
123
124#[derive(Debug, Subcommand)]
125enum CircuitCommand {
126    /// Summarize circuit structure and counts
127    Stats {
128        /// Read the circuit from a file instead of stdin
129        #[arg(long = "in")]
130        input: Option<PathBuf>,
131        /// Select human-readable or versioned JSON output
132        #[arg(long, value_enum, default_value_t = StatsFormat::Human)]
133        format: StatsFormat,
134    },
135    /// Generate a built-in QEC circuit (common families and Mid-SWAP)
136    Gen {
137        /// Code family, e.g. surface_code
138        #[arg(long)]
139        code: String,
140        /// Task within the family, e.g. rotated_memory_z_midswap
141        #[arg(long)]
142        task: String,
143        /// Code distance
144        #[arg(long)]
145        distance: usize,
146        /// Number of syndrome-extraction rounds
147        #[arg(long)]
148        rounds: usize,
149        /// After-Clifford depolarization probability
150        #[arg(long, default_value = "0")]
151        noise: f64,
152        /// Depolarization applied to data qubits at the start of each round
153        #[arg(long, default_value = "0")]
154        before_round_data_depolarization: f64,
155        /// Atom loss applied to data qubits at the start of each Mid-SWAP round
156        #[arg(
157            long = "before-round-data-loss-probability",
158            visible_alias = "before-round-data-loss",
159            default_value = "0"
160        )]
161        before_round_data_loss_probability: f64,
162        /// Bit-flip probability applied immediately before each measurement
163        #[arg(long, default_value = "0")]
164        before_measure_flip_probability: f64,
165        /// Bit-flip probability applied immediately after each reset
166        #[arg(long, default_value = "0")]
167        after_reset_flip_probability: f64,
168        /// Loss probability after Clifford gates (non-Mid-SWAP families)
169        #[arg(long, default_value = "0")]
170        after_clifford_loss_probability: f64,
171        /// Operation-loss probability for gates and resets (Mid-SWAP and loss-visible rotated_memory_z)
172        #[arg(long, default_value = "0")]
173        operation_loss_probability: f64,
174        /// Measurement-loss probability (Mid-SWAP and loss-visible rotated_memory_z)
175        #[arg(long, default_value = "0")]
176        measurement_loss_probability: f64,
177        /// Destination circuit file
178        #[arg(long)]
179        out: PathBuf,
180        /// Select human-readable or versioned JSON output
181        #[arg(long, value_enum, default_value_t = pipeline::PipelineFormat::Json)]
182        format: pipeline::PipelineFormat,
183    },
184    /// Sample measurement results from a circuit
185    Sample {
186        /// Number of shots
187        #[arg(long)]
188        shots: u64,
189        /// Read the circuit from a file instead of stdin
190        #[arg(long = "in")]
191        input: Option<PathBuf>,
192        /// Destination shot file
193        #[arg(long)]
194        out: PathBuf,
195        /// Shot output format: 01, b8, r8, hits, ptb64
196        #[arg(long = "out-format", default_value = "01")]
197        out_format: String,
198        /// Sampling seed
199        #[arg(long)]
200        seed: Option<u64>,
201        /// Skip the reference noiseless sample (requires a noiseless circuit)
202        #[arg(long = "skip-reference-sample")]
203        skip_reference_sample: bool,
204        /// Select human-readable or versioned JSON output
205        #[arg(long, value_enum, default_value_t = pipeline::PipelineFormat::Json)]
206        format: pipeline::PipelineFormat,
207    },
208    /// Sample detection events and observable flips from a circuit
209    Detect {
210        /// Number of shots
211        #[arg(long)]
212        shots: u64,
213        /// Read the circuit from a file instead of stdin
214        #[arg(long = "in")]
215        input: Option<PathBuf>,
216        /// Destination detection-event file
217        #[arg(long)]
218        out: PathBuf,
219        /// Detection output format: 01, b8, r8, hits, dets, ptb64
220        #[arg(long = "out-format", default_value = "01")]
221        out_format: String,
222        /// Sampling seed
223        #[arg(long)]
224        seed: Option<u64>,
225        /// Append observable flips after the detection events
226        #[arg(long = "append-observables")]
227        append_observables: bool,
228        /// Write observable flips to a separate file
229        #[arg(long = "obs-out")]
230        obs_out: Option<PathBuf>,
231        /// Observable output format when --obs-out is set
232        #[arg(long = "obs-out-format", default_value = "01")]
233        obs_out_format: String,
234        /// Select human-readable or versioned JSON output
235        #[arg(long, value_enum, default_value_t = pipeline::PipelineFormat::Json)]
236        format: pipeline::PipelineFormat,
237    },
238    /// Convert a circuit into a detector error model
239    Dem {
240        /// Read the circuit from a file instead of stdin
241        #[arg(long = "in")]
242        input: Option<PathBuf>,
243        /// Destination detector error model file
244        #[arg(long)]
245        out: PathBuf,
246        /// Allow statistical approximation of disjoint errors
247        #[arg(long = "approximate-disjoint-errors")]
248        approximate_disjoint_errors: bool,
249        /// Allow gauge detectors with ambiguous observables
250        #[arg(long = "allow-gauge-detectors")]
251        allow_gauge_detectors: bool,
252        /// Decompose errors into graphlike components
253        #[arg(long = "decompose-errors")]
254        decompose_errors: bool,
255        /// Select human-readable or versioned JSON output
256        #[arg(long, value_enum, default_value_t = pipeline::PipelineFormat::Json)]
257        format: pipeline::PipelineFormat,
258    },
259}
260
261#[derive(Clone, Copy, Debug, ValueEnum)]
262enum StatsFormat {
263    Human,
264    Json,
265}
266
267#[derive(Clone, Copy, Debug, ValueEnum)]
268enum CapabilitiesFormat {
269    Json,
270}
271
272#[derive(Clone, Copy, Debug, ValueEnum)]
273enum ErrorFormat {
274    Human,
275    Json,
276}
277
278#[derive(Clone, Copy, Debug, ValueEnum)]
279enum DecodeDecoder {
280    EnvelopeMatching,
281    #[cfg(feature = "ilp")]
282    EnvelopeMle,
283}
284
285impl From<DecodeDecoder> for decode::DecoderKind {
286    fn from(value: DecodeDecoder) -> Self {
287        match value {
288            DecodeDecoder::EnvelopeMatching => Self::EnvelopeMatching,
289            #[cfg(feature = "ilp")]
290            DecodeDecoder::EnvelopeMle => Self::EnvelopeMle,
291        }
292    }
293}
294
295fn available_decoders() -> Vec<&'static str> {
296    let decoders = vec!["envelope-matching"];
297    #[cfg(feature = "ilp")]
298    let decoders = {
299        let mut decoders = decoders;
300        decoders.push("envelope-mle");
301        decoders
302    };
303    decoders
304}
305
306#[derive(Debug)]
307pub enum RunError {
308    Clap {
309        error: clap::Error,
310        command: &'static str,
311        json: bool,
312    },
313    Command(CommandError),
314}
315
316#[derive(Debug)]
317pub struct CommandError {
318    pub command: &'static str,
319    pub code: &'static str,
320    pub message: String,
321    json: bool,
322    exit_code: u8,
323}
324
325#[derive(Serialize)]
326struct SuccessEnvelope<T> {
327    schema_version: &'static str,
328    status: &'static str,
329    command: &'static str,
330    result: T,
331    warnings: Vec<String>,
332    artifacts: Vec<String>,
333}
334
335#[derive(Serialize)]
336struct ErrorEnvelope<'a> {
337    schema_version: &'static str,
338    status: &'static str,
339    command: &'static str,
340    error: ErrorBody<'a>,
341}
342
343#[derive(Serialize)]
344struct ErrorBody<'a> {
345    code: &'static str,
346    message: &'a str,
347}
348
349#[derive(Serialize)]
350struct CapabilitiesDocument {
351    schema_version: &'static str,
352    global_arguments: Vec<ArgumentCapability>,
353    commands: Vec<Capability>,
354}
355
356#[derive(Serialize)]
357struct Capability {
358    name: &'static str,
359    argv: Vec<&'static str>,
360    input_sources: Vec<&'static str>,
361    formats: Vec<&'static str>,
362    output_schema: &'static str,
363    arguments: Vec<ArgumentCapability>,
364    success_exit_code: u8,
365    errors: Vec<ErrorCapability>,
366    #[serde(skip_serializing_if = "Vec::is_empty")]
367    decoders: Vec<&'static str>,
368    #[serde(skip_serializing_if = "Vec::is_empty")]
369    artifacts: Vec<ArtifactCapability>,
370}
371
372#[derive(Serialize)]
373struct ArtifactCapability {
374    name: &'static str,
375    flag: &'static str,
376    format: &'static str,
377}
378
379#[derive(Serialize)]
380struct ArgumentCapability {
381    name: &'static str,
382    flag: &'static str,
383    required: bool,
384    values: Vec<&'static str>,
385    default: Option<&'static str>,
386}
387
388#[derive(Serialize)]
389struct ErrorCapability {
390    code: &'static str,
391    exit_code: u8,
392    channel: &'static str,
393}
394
395pub fn run<I, T>(args: I, stdin: &mut dyn Read, stdout: &mut dyn Write) -> Result<(), RunError>
396where
397    I: IntoIterator<Item = T>,
398    T: Into<OsString> + Clone,
399{
400    let args = args.into_iter().map(Into::into).collect::<Vec<OsString>>();
401    let (parse_command, parse_json) = parse_error_context(&args);
402    let cli = Cli::try_parse_from(&args).map_err(|error| RunError::Clap {
403        error,
404        command: parse_command,
405        json: parse_json,
406    })?;
407    let error_format = cli.error_format;
408    match cli.command {
409        Command::Circuit {
410            command: CircuitCommand::Stats { input, format },
411        } => {
412            run_circuit_stats(input, format, error_format, stdin, stdout).map_err(RunError::Command)
413        }
414        Command::Circuit {
415            command:
416                CircuitCommand::Gen {
417                    code,
418                    task,
419                    distance,
420                    rounds,
421                    noise,
422                    before_round_data_depolarization,
423                    before_round_data_loss_probability,
424                    before_measure_flip_probability,
425                    after_reset_flip_probability,
426                    after_clifford_loss_probability,
427                    operation_loss_probability,
428                    measurement_loss_probability,
429                    out,
430                    format,
431                },
432        } => {
433            let options = pipeline::GenOptions {
434                code,
435                task,
436                distance,
437                rounds,
438                noise,
439                before_round_data_depolarization,
440                before_round_data_loss_probability,
441                before_measure_flip_probability,
442                after_reset_flip_probability,
443                after_clifford_loss_probability,
444                operation_loss_probability,
445                measurement_loss_probability,
446                out,
447                format,
448            };
449            let artifacts = vec![options.out.display().to_string()];
450            pipeline::run_gen(&options, error_format)
451                .and_then(|result| {
452                    write_pipeline_success(
453                        pipeline::CIRCUIT_GEN_COMMAND,
454                        &result,
455                        artifacts,
456                        format,
457                        error_format,
458                        stdout,
459                    )
460                })
461                .map_err(RunError::Command)
462        }
463        Command::Circuit {
464            command:
465                CircuitCommand::Sample {
466                    shots,
467                    input,
468                    out,
469                    out_format,
470                    seed,
471                    skip_reference_sample,
472                    format,
473                },
474        } => {
475            let options = pipeline::SampleOptions {
476                shots,
477                input,
478                out,
479                out_format,
480                seed,
481                skip_reference_sample,
482                format,
483            };
484            let artifacts = vec![options.out.display().to_string()];
485            pipeline::run_sample(&options, error_format, stdin)
486                .and_then(|result| {
487                    write_pipeline_success(
488                        pipeline::CIRCUIT_SAMPLE_COMMAND,
489                        &result,
490                        artifacts,
491                        format,
492                        error_format,
493                        stdout,
494                    )
495                })
496                .map_err(RunError::Command)
497        }
498        Command::Circuit {
499            command:
500                CircuitCommand::Detect {
501                    shots,
502                    input,
503                    out,
504                    out_format,
505                    seed,
506                    append_observables,
507                    obs_out,
508                    obs_out_format,
509                    format,
510                },
511        } => {
512            let mut artifacts = vec![out.display().to_string()];
513            if let Some(obs_out) = &obs_out {
514                artifacts.push(obs_out.display().to_string());
515            }
516            let options = pipeline::DetectOptions {
517                shots,
518                input,
519                out,
520                out_format,
521                seed,
522                append_observables,
523                obs_out,
524                obs_out_format,
525                format,
526            };
527            pipeline::run_detect(&options, error_format, stdin)
528                .and_then(|result| {
529                    write_pipeline_success(
530                        pipeline::CIRCUIT_DETECT_COMMAND,
531                        &result,
532                        artifacts,
533                        format,
534                        error_format,
535                        stdout,
536                    )
537                })
538                .map_err(RunError::Command)
539        }
540        Command::Circuit {
541            command:
542                CircuitCommand::Dem {
543                    input,
544                    out,
545                    approximate_disjoint_errors,
546                    allow_gauge_detectors,
547                    decompose_errors,
548                    format,
549                },
550        } => {
551            let options = pipeline::DemOptions {
552                input,
553                out,
554                approximate_disjoint_errors,
555                allow_gauge_detectors,
556                decompose_errors,
557                format,
558            };
559            let artifacts = vec![options.out.display().to_string()];
560            pipeline::run_dem(&options, error_format, stdin)
561                .and_then(|result| {
562                    write_pipeline_success(
563                        pipeline::CIRCUIT_DEM_COMMAND,
564                        &result,
565                        artifacts,
566                        format,
567                        error_format,
568                        stdout,
569                    )
570                })
571                .map_err(RunError::Command)
572        }
573        Command::Dataset {
574            command:
575                DatasetCommand::Export {
576                    circuit,
577                    shots,
578                    mode,
579                    public_out,
580                    private_out,
581                    seed,
582                    logical_x_qubits,
583                    logical_z_qubits,
584                    error_trace,
585                    format,
586                },
587        } => {
588            let artifacts = vec![
589                public_out.display().to_string(),
590                private_out.display().to_string(),
591            ];
592            let options = pipeline::DatasetExportOptions {
593                circuit,
594                shots,
595                mode,
596                public_out,
597                private_out,
598                seed,
599                logical_x_qubits,
600                logical_z_qubits,
601                error_trace,
602                format,
603            };
604            pipeline::run_dataset_export(&options, error_format)
605                .and_then(|result| {
606                    write_pipeline_success(
607                        pipeline::DATASET_EXPORT_COMMAND,
608                        &result,
609                        artifacts,
610                        format,
611                        error_format,
612                        stdout,
613                    )
614                })
615                .map_err(RunError::Command)
616        }
617        Command::Dataset {
618            command:
619                DatasetCommand::Import {
620                    circuit,
621                    shots,
622                    shots_format,
623                    out,
624                    loss_log,
625                    format,
626                },
627        } => {
628            let artifacts = vec![out.display().to_string()];
629            let options = pipeline::DatasetImportOptions {
630                circuit,
631                shots,
632                shots_format,
633                out,
634                loss_log,
635                format,
636            };
637            pipeline::run_dataset_import(&options, error_format)
638                .and_then(|result| {
639                    write_pipeline_success(
640                        pipeline::DATASET_IMPORT_COMMAND,
641                        &result,
642                        artifacts,
643                        format,
644                        error_format,
645                        stdout,
646                    )
647                })
648                .map_err(RunError::Command)
649        }
650        Command::Capabilities { format } => {
651            write_capabilities(format, error_format, stdout).map_err(RunError::Command)
652        }
653        Command::Decode {
654            decoder,
655            dataset,
656            out,
657            stats_out,
658            shot_timeout_ms,
659        } => decode::run(&decode::DecodeOptions {
660            decoder: decoder.into(),
661            dataset,
662            predictions_out: out,
663            stats_out,
664            shot_timeout_ms,
665        })
666        .map(|_| ())
667        .map_err(|failure| {
668            RunError::Command(CommandError {
669                command: decode::COMMAND,
670                code: failure.code,
671                message: failure.message,
672                json: !matches!(error_format, Some(ErrorFormat::Human)),
673                exit_code: if matches!(failure.code, "decode_timeout" | "decode_infeasible") {
674                    3
675                } else {
676                    2
677                },
678            })
679        }),
680    }
681}
682
683fn run_circuit_stats(
684    input: Option<PathBuf>,
685    format: StatsFormat,
686    error_format: Option<ErrorFormat>,
687    stdin: &mut dyn Read,
688    stdout: &mut dyn Write,
689) -> Result<(), CommandError> {
690    let json = match error_format {
691        Some(ErrorFormat::Human) => false,
692        Some(ErrorFormat::Json) => true,
693        None => matches!(format, StatsFormat::Json),
694    };
695    let text = match input {
696        Some(path) => fs::read_to_string(&path).map_err(|error| CommandError {
697            command: CIRCUIT_STATS_COMMAND,
698            code: "input_error",
699            message: format!("failed to read {}: {error}", path.display()),
700            json,
701            exit_code: 2,
702        })?,
703        None => {
704            let mut text = String::new();
705            stdin
706                .read_to_string(&mut text)
707                .map_err(|error| CommandError {
708                    command: CIRCUIT_STATS_COMMAND,
709                    code: "input_error",
710                    message: format!("failed to read stdin: {error}"),
711                    json,
712                    exit_code: 2,
713                })?;
714            text
715        }
716    };
717
718    let summary = rstim::stats::summarize_text(&text).map_err(|message| CommandError {
719        command: CIRCUIT_STATS_COMMAND,
720        code: "invalid_circuit",
721        message,
722        json,
723        exit_code: 2,
724    })?;
725
726    match format {
727        StatsFormat::Human => rstim::stats::write_human(&summary, stdout),
728        StatsFormat::Json => write_json(
729            stdout,
730            &SuccessEnvelope {
731                schema_version: SCHEMA_VERSION,
732                status: "ok",
733                command: CIRCUIT_STATS_COMMAND,
734                result: summary,
735                warnings: Vec::new(),
736                artifacts: Vec::new(),
737            },
738        ),
739    }
740    .map_err(|message| CommandError {
741        command: CIRCUIT_STATS_COMMAND,
742        code: "output_error",
743        message,
744        json,
745        exit_code: 2,
746    })
747}
748
749fn write_pipeline_success<T: Serialize>(
750    command: &'static str,
751    result: &T,
752    artifacts: Vec<String>,
753    format: pipeline::PipelineFormat,
754    error_format: Option<ErrorFormat>,
755    stdout: &mut dyn Write,
756) -> Result<(), CommandError> {
757    let json = format.is_json(error_format);
758    let outcome = match format {
759        pipeline::PipelineFormat::Json => write_json(
760            stdout,
761            &SuccessEnvelope {
762                schema_version: SCHEMA_VERSION,
763                status: "ok",
764                command,
765                result,
766                warnings: Vec::new(),
767                artifacts,
768            },
769        ),
770        pipeline::PipelineFormat::Human => serde_json::to_value(result)
771            .map_err(|error| error.to_string())
772            .and_then(|value| {
773                let mut text = String::from("status: ok\n");
774                if let serde_json::Value::Object(fields) = value {
775                    for (key, field) in fields {
776                        let rendered = match field {
777                            serde_json::Value::String(text) => text,
778                            serde_json::Value::Null => continue,
779                            other => other.to_string(),
780                        };
781                        text.push_str(&format!("{key}: {rendered}\n"));
782                    }
783                }
784                for artifact in &artifacts {
785                    text.push_str(&format!("artifact: {artifact}\n"));
786                }
787                stdout
788                    .write_all(text.as_bytes())
789                    .map_err(|error| error.to_string())
790            }),
791    };
792    outcome.map_err(|message| CommandError {
793        command,
794        code: "output_error",
795        message,
796        json,
797        exit_code: 2,
798    })
799}
800
801fn write_capabilities(
802    _format: CapabilitiesFormat,
803    error_format: Option<ErrorFormat>,
804    stdout: &mut dyn Write,
805) -> Result<(), CommandError> {
806    let json = !matches!(error_format, Some(ErrorFormat::Human));
807    write_json(
808        stdout,
809        &CapabilitiesDocument {
810            schema_version: SCHEMA_VERSION,
811            global_arguments: vec![ArgumentCapability {
812                name: "error_format",
813                flag: "--error-format",
814                required: false,
815                values: vec!["human", "json"],
816                default: None,
817            }],
818            commands: vec![
819                Capability {
820                    name: CIRCUIT_STATS_COMMAND,
821                    argv: vec!["circuit", "stats"],
822                    input_sources: vec!["stdin", "file"],
823                    formats: vec!["human", "json"],
824                    output_schema: SCHEMA_VERSION,
825                    arguments: vec![
826                        ArgumentCapability {
827                            name: "input",
828                            flag: "--in",
829                            required: false,
830                            values: vec!["path"],
831                            default: Some("stdin"),
832                        },
833                        ArgumentCapability {
834                            name: "format",
835                            flag: "--format",
836                            required: false,
837                            values: vec!["human", "json"],
838                            default: Some("human"),
839                        },
840                    ],
841                    success_exit_code: 0,
842                    errors: vec![
843                        ErrorCapability {
844                            code: "invalid_arguments",
845                            exit_code: 2,
846                            channel: "stderr",
847                        },
848                        ErrorCapability {
849                            code: "invalid_circuit",
850                            exit_code: 2,
851                            channel: "stderr",
852                        },
853                        ErrorCapability {
854                            code: "input_error",
855                            exit_code: 2,
856                            channel: "stderr",
857                        },
858                        ErrorCapability {
859                            code: "output_error",
860                            exit_code: 2,
861                            channel: "stderr",
862                        },
863                    ],
864                    decoders: Vec::new(),
865                    artifacts: Vec::new(),
866                },
867                Capability {
868                    name: pipeline::CIRCUIT_GEN_COMMAND,
869                    argv: vec!["circuit", "gen"],
870                    input_sources: vec!["built_in_generators"],
871                    formats: vec!["human", "json"],
872                    output_schema: SCHEMA_VERSION,
873                    arguments: vec![
874                        ArgumentCapability {
875                            name: "code",
876                            flag: "--code",
877                            required: true,
878                            values: vec!["surface_code", "repetition_code", "color_code"],
879                            default: None,
880                        },
881                        ArgumentCapability {
882                            name: "task",
883                            flag: "--task",
884                            required: true,
885                            values: vec![
886                                "rotated_memory_z_midswap",
887                                "rotated_memory_x",
888                                "rotated_memory_z",
889                                "unrotated_memory_x",
890                                "unrotated_memory_z",
891                                "memory",
892                                "memory_xyz",
893                            ],
894                            default: None,
895                        },
896                        ArgumentCapability {
897                            name: "distance",
898                            flag: "--distance",
899                            required: true,
900                            values: vec!["positive_integer"],
901                            default: None,
902                        },
903                        ArgumentCapability {
904                            name: "rounds",
905                            flag: "--rounds",
906                            required: true,
907                            values: vec!["non_negative_integer"],
908                            default: None,
909                        },
910                        ArgumentCapability {
911                            name: "noise",
912                            flag: "--noise",
913                            required: false,
914                            values: vec!["probability"],
915                            default: Some("0"),
916                        },
917                        ArgumentCapability {
918                            name: "before_round_data_depolarization",
919                            flag: "--before-round-data-depolarization",
920                            required: false,
921                            values: vec!["probability"],
922                            default: Some("0"),
923                        },
924                        ArgumentCapability {
925                            name: "before_round_data_loss_probability",
926                            flag: "--before-round-data-loss-probability",
927                            required: false,
928                            values: vec!["probability"],
929                            default: Some("0"),
930                        },
931                        ArgumentCapability {
932                            name: "before_measure_flip_probability",
933                            flag: "--before-measure-flip-probability",
934                            required: false,
935                            values: vec!["probability"],
936                            default: Some("0"),
937                        },
938                        ArgumentCapability {
939                            name: "after_reset_flip_probability",
940                            flag: "--after-reset-flip-probability",
941                            required: false,
942                            values: vec!["probability"],
943                            default: Some("0"),
944                        },
945                        ArgumentCapability {
946                            name: "after_clifford_loss_probability",
947                            flag: "--after-clifford-loss-probability",
948                            required: false,
949                            values: vec!["probability"],
950                            default: Some("0"),
951                        },
952                        ArgumentCapability {
953                            name: "operation_loss_probability",
954                            flag: "--operation-loss-probability",
955                            required: false,
956                            values: vec!["probability"],
957                            default: Some("0"),
958                        },
959                        ArgumentCapability {
960                            name: "measurement_loss_probability",
961                            flag: "--measurement-loss-probability",
962                            required: false,
963                            values: vec!["probability"],
964                            default: Some("0"),
965                        },
966                        ArgumentCapability {
967                            name: "out",
968                            flag: "--out",
969                            required: true,
970                            values: vec!["path"],
971                            default: None,
972                        },
973                        ArgumentCapability {
974                            name: "format",
975                            flag: "--format",
976                            required: false,
977                            values: vec!["human", "json"],
978                            default: Some("json"),
979                        },
980                    ],
981                    success_exit_code: 0,
982                    errors: vec![
983                        ErrorCapability {
984                            code: "invalid_arguments",
985                            exit_code: 2,
986                            channel: "stderr",
987                        },
988                        ErrorCapability {
989                            code: "output_error",
990                            exit_code: 2,
991                            channel: "stderr",
992                        },
993                    ],
994                    decoders: Vec::new(),
995                    artifacts: vec![ArtifactCapability {
996                        name: "circuit",
997                        flag: "--out",
998                        format: "stim",
999                    }],
1000                },
1001                Capability {
1002                    name: pipeline::CIRCUIT_SAMPLE_COMMAND,
1003                    argv: vec!["circuit", "sample"],
1004                    input_sources: vec!["stdin", "file"],
1005                    formats: vec!["human", "json"],
1006                    output_schema: SCHEMA_VERSION,
1007                    arguments: vec![
1008                        ArgumentCapability {
1009                            name: "shots",
1010                            flag: "--shots",
1011                            required: true,
1012                            values: vec!["non_negative_integer"],
1013                            default: None,
1014                        },
1015                        ArgumentCapability {
1016                            name: "input",
1017                            flag: "--in",
1018                            required: false,
1019                            values: vec!["path"],
1020                            default: Some("stdin"),
1021                        },
1022                        ArgumentCapability {
1023                            name: "out",
1024                            flag: "--out",
1025                            required: true,
1026                            values: vec!["path"],
1027                            default: None,
1028                        },
1029                        ArgumentCapability {
1030                            name: "out_format",
1031                            flag: "--out-format",
1032                            required: false,
1033                            values: vec!["01", "b8", "r8", "hits", "ptb64"],
1034                            default: Some("01"),
1035                        },
1036                        ArgumentCapability {
1037                            name: "seed",
1038                            flag: "--seed",
1039                            required: false,
1040                            values: vec!["non_negative_integer"],
1041                            default: None,
1042                        },
1043                        ArgumentCapability {
1044                            name: "skip_reference_sample",
1045                            flag: "--skip-reference-sample",
1046                            required: false,
1047                            values: vec!["flag"],
1048                            default: None,
1049                        },
1050                        ArgumentCapability {
1051                            name: "format",
1052                            flag: "--format",
1053                            required: false,
1054                            values: vec!["human", "json"],
1055                            default: Some("json"),
1056                        },
1057                    ],
1058                    success_exit_code: 0,
1059                    errors: vec![
1060                        ErrorCapability {
1061                            code: "invalid_arguments",
1062                            exit_code: 2,
1063                            channel: "stderr",
1064                        },
1065                        ErrorCapability {
1066                            code: "invalid_circuit",
1067                            exit_code: 2,
1068                            channel: "stderr",
1069                        },
1070                        ErrorCapability {
1071                            code: "input_error",
1072                            exit_code: 2,
1073                            channel: "stderr",
1074                        },
1075                        ErrorCapability {
1076                            code: "execution_error",
1077                            exit_code: 2,
1078                            channel: "stderr",
1079                        },
1080                        ErrorCapability {
1081                            code: "output_error",
1082                            exit_code: 2,
1083                            channel: "stderr",
1084                        },
1085                    ],
1086                    decoders: Vec::new(),
1087                    artifacts: vec![ArtifactCapability {
1088                        name: "measurements",
1089                        flag: "--out",
1090                        format: "01|b8|r8|hits|ptb64",
1091                    }],
1092                },
1093                Capability {
1094                    name: pipeline::CIRCUIT_DETECT_COMMAND,
1095                    argv: vec!["circuit", "detect"],
1096                    input_sources: vec!["stdin", "file"],
1097                    formats: vec!["human", "json"],
1098                    output_schema: SCHEMA_VERSION,
1099                    arguments: vec![
1100                        ArgumentCapability {
1101                            name: "shots",
1102                            flag: "--shots",
1103                            required: true,
1104                            values: vec!["non_negative_integer"],
1105                            default: None,
1106                        },
1107                        ArgumentCapability {
1108                            name: "input",
1109                            flag: "--in",
1110                            required: false,
1111                            values: vec!["path"],
1112                            default: Some("stdin"),
1113                        },
1114                        ArgumentCapability {
1115                            name: "out",
1116                            flag: "--out",
1117                            required: true,
1118                            values: vec!["path"],
1119                            default: None,
1120                        },
1121                        ArgumentCapability {
1122                            name: "out_format",
1123                            flag: "--out-format",
1124                            required: false,
1125                            values: vec!["01", "b8", "r8", "hits", "dets", "ptb64"],
1126                            default: Some("01"),
1127                        },
1128                        ArgumentCapability {
1129                            name: "seed",
1130                            flag: "--seed",
1131                            required: false,
1132                            values: vec!["non_negative_integer"],
1133                            default: None,
1134                        },
1135                        ArgumentCapability {
1136                            name: "append_observables",
1137                            flag: "--append-observables",
1138                            required: false,
1139                            values: vec!["flag"],
1140                            default: None,
1141                        },
1142                        ArgumentCapability {
1143                            name: "obs_out",
1144                            flag: "--obs-out",
1145                            required: false,
1146                            values: vec!["path"],
1147                            default: None,
1148                        },
1149                        ArgumentCapability {
1150                            name: "obs_out_format",
1151                            flag: "--obs-out-format",
1152                            required: false,
1153                            values: vec!["01", "b8", "r8", "hits", "dets", "ptb64"],
1154                            default: Some("01"),
1155                        },
1156                        ArgumentCapability {
1157                            name: "format",
1158                            flag: "--format",
1159                            required: false,
1160                            values: vec!["human", "json"],
1161                            default: Some("json"),
1162                        },
1163                    ],
1164                    success_exit_code: 0,
1165                    errors: vec![
1166                        ErrorCapability {
1167                            code: "invalid_arguments",
1168                            exit_code: 2,
1169                            channel: "stderr",
1170                        },
1171                        ErrorCapability {
1172                            code: "invalid_circuit",
1173                            exit_code: 2,
1174                            channel: "stderr",
1175                        },
1176                        ErrorCapability {
1177                            code: "input_error",
1178                            exit_code: 2,
1179                            channel: "stderr",
1180                        },
1181                        ErrorCapability {
1182                            code: "execution_error",
1183                            exit_code: 2,
1184                            channel: "stderr",
1185                        },
1186                        ErrorCapability {
1187                            code: "output_error",
1188                            exit_code: 2,
1189                            channel: "stderr",
1190                        },
1191                    ],
1192                    decoders: Vec::new(),
1193                    artifacts: vec![
1194                        ArtifactCapability {
1195                            name: "detection_events",
1196                            flag: "--out",
1197                            format: "01|b8|r8|hits|dets|ptb64",
1198                        },
1199                        ArtifactCapability {
1200                            name: "observable_flips",
1201                            flag: "--obs-out",
1202                            format: "01|b8|r8|hits|dets|ptb64",
1203                        },
1204                    ],
1205                },
1206                Capability {
1207                    name: pipeline::CIRCUIT_DEM_COMMAND,
1208                    argv: vec!["circuit", "dem"],
1209                    input_sources: vec!["stdin", "file"],
1210                    formats: vec!["human", "json"],
1211                    output_schema: SCHEMA_VERSION,
1212                    arguments: vec![
1213                        ArgumentCapability {
1214                            name: "input",
1215                            flag: "--in",
1216                            required: false,
1217                            values: vec!["path"],
1218                            default: Some("stdin"),
1219                        },
1220                        ArgumentCapability {
1221                            name: "out",
1222                            flag: "--out",
1223                            required: true,
1224                            values: vec!["path"],
1225                            default: None,
1226                        },
1227                        ArgumentCapability {
1228                            name: "approximate_disjoint_errors",
1229                            flag: "--approximate-disjoint-errors",
1230                            required: false,
1231                            values: vec!["flag"],
1232                            default: None,
1233                        },
1234                        ArgumentCapability {
1235                            name: "allow_gauge_detectors",
1236                            flag: "--allow-gauge-detectors",
1237                            required: false,
1238                            values: vec!["flag"],
1239                            default: None,
1240                        },
1241                        ArgumentCapability {
1242                            name: "decompose_errors",
1243                            flag: "--decompose-errors",
1244                            required: false,
1245                            values: vec!["flag"],
1246                            default: None,
1247                        },
1248                        ArgumentCapability {
1249                            name: "format",
1250                            flag: "--format",
1251                            required: false,
1252                            values: vec!["human", "json"],
1253                            default: Some("json"),
1254                        },
1255                    ],
1256                    success_exit_code: 0,
1257                    errors: vec![
1258                        ErrorCapability {
1259                            code: "invalid_arguments",
1260                            exit_code: 2,
1261                            channel: "stderr",
1262                        },
1263                        ErrorCapability {
1264                            code: "invalid_circuit",
1265                            exit_code: 2,
1266                            channel: "stderr",
1267                        },
1268                        ErrorCapability {
1269                            code: "input_error",
1270                            exit_code: 2,
1271                            channel: "stderr",
1272                        },
1273                        ErrorCapability {
1274                            code: "execution_error",
1275                            exit_code: 2,
1276                            channel: "stderr",
1277                        },
1278                        ErrorCapability {
1279                            code: "output_error",
1280                            exit_code: 2,
1281                            channel: "stderr",
1282                        },
1283                    ],
1284                    decoders: Vec::new(),
1285                    artifacts: vec![ArtifactCapability {
1286                        name: "detector_error_model",
1287                        flag: "--out",
1288                        format: "dem",
1289                    }],
1290                },
1291                Capability {
1292                    name: pipeline::DATASET_EXPORT_COMMAND,
1293                    argv: vec!["dataset", "export"],
1294                    input_sources: vec!["file"],
1295                    formats: vec!["human", "json"],
1296                    output_schema: SCHEMA_VERSION,
1297                    arguments: vec![
1298                        ArgumentCapability {
1299                            name: "circuit",
1300                            flag: "--circuit",
1301                            required: true,
1302                            values: vec!["path"],
1303                            default: None,
1304                        },
1305                        ArgumentCapability {
1306                            name: "shots",
1307                            flag: "--shots",
1308                            required: true,
1309                            values: vec!["non_negative_integer"],
1310                            default: None,
1311                        },
1312                        ArgumentCapability {
1313                            name: "mode",
1314                            flag: "--mode",
1315                            required: true,
1316                            values: vec!["detectors", "measurements_blinded"],
1317                            default: None,
1318                        },
1319                        ArgumentCapability {
1320                            name: "public_out",
1321                            flag: "--public-out",
1322                            required: true,
1323                            values: vec!["path"],
1324                            default: None,
1325                        },
1326                        ArgumentCapability {
1327                            name: "private_out",
1328                            flag: "--private-out",
1329                            required: true,
1330                            values: vec!["path"],
1331                            default: None,
1332                        },
1333                        ArgumentCapability {
1334                            name: "seed",
1335                            flag: "--seed",
1336                            required: false,
1337                            values: vec!["non_negative_integer"],
1338                            default: None,
1339                        },
1340                        ArgumentCapability {
1341                            name: "logical_x_qubits",
1342                            flag: "--logical-x-qubits",
1343                            required: false,
1344                            values: vec!["qubit_index_list"],
1345                            default: None,
1346                        },
1347                        ArgumentCapability {
1348                            name: "logical_z_qubits",
1349                            flag: "--logical-z-qubits",
1350                            required: false,
1351                            values: vec!["qubit_index_list"],
1352                            default: None,
1353                        },
1354                        ArgumentCapability {
1355                            name: "error_trace",
1356                            flag: "--error-trace",
1357                            required: false,
1358                            values: vec!["boolean"],
1359                            default: Some("false"),
1360                        },
1361                        ArgumentCapability {
1362                            name: "format",
1363                            flag: "--format",
1364                            required: false,
1365                            values: vec!["human", "json"],
1366                            default: Some("json"),
1367                        },
1368                    ],
1369                    success_exit_code: 0,
1370                    errors: vec![
1371                        ErrorCapability {
1372                            code: "invalid_arguments",
1373                            exit_code: 2,
1374                            channel: "stderr",
1375                        },
1376                        ErrorCapability {
1377                            code: "invalid_circuit",
1378                            exit_code: 2,
1379                            channel: "stderr",
1380                        },
1381                        ErrorCapability {
1382                            code: "input_error",
1383                            exit_code: 2,
1384                            channel: "stderr",
1385                        },
1386                        ErrorCapability {
1387                            code: "execution_error",
1388                            exit_code: 2,
1389                            channel: "stderr",
1390                        },
1391                    ],
1392                    decoders: Vec::new(),
1393                    artifacts: vec![
1394                        ArtifactCapability {
1395                            name: "public_dataset",
1396                            flag: "--public-out",
1397                            format: "directory",
1398                        },
1399                        ArtifactCapability {
1400                            name: "private_answers",
1401                            flag: "--private-out",
1402                            format: "directory",
1403                        },
1404                    ],
1405                },
1406                Capability {
1407                    name: pipeline::DATASET_IMPORT_COMMAND,
1408                    argv: vec!["dataset", "import"],
1409                    input_sources: vec!["file"],
1410                    formats: vec!["human", "json"],
1411                    output_schema: SCHEMA_VERSION,
1412                    arguments: vec![
1413                        ArgumentCapability {
1414                            name: "circuit",
1415                            flag: "--circuit",
1416                            required: true,
1417                            values: vec!["path"],
1418                            default: None,
1419                        },
1420                        ArgumentCapability {
1421                            name: "shots",
1422                            flag: "--shots",
1423                            required: true,
1424                            values: vec!["path"],
1425                            default: None,
1426                        },
1427                        ArgumentCapability {
1428                            name: "shots_format",
1429                            flag: "--shots-format",
1430                            required: false,
1431                            values: vec!["01", "b8"],
1432                            default: Some("01"),
1433                        },
1434                        ArgumentCapability {
1435                            name: "out",
1436                            flag: "--out",
1437                            required: true,
1438                            values: vec!["path"],
1439                            default: None,
1440                        },
1441                        ArgumentCapability {
1442                            name: "loss_log",
1443                            flag: "--loss-log",
1444                            required: false,
1445                            values: vec!["path"],
1446                            default: None,
1447                        },
1448                        ArgumentCapability {
1449                            name: "format",
1450                            flag: "--format",
1451                            required: false,
1452                            values: vec!["human", "json"],
1453                            default: Some("json"),
1454                        },
1455                    ],
1456                    success_exit_code: 0,
1457                    errors: vec![
1458                        ErrorCapability {
1459                            code: "invalid_arguments",
1460                            exit_code: 2,
1461                            channel: "stderr",
1462                        },
1463                        ErrorCapability {
1464                            code: "invalid_circuit",
1465                            exit_code: 2,
1466                            channel: "stderr",
1467                        },
1468                        ErrorCapability {
1469                            code: "input_error",
1470                            exit_code: 2,
1471                            channel: "stderr",
1472                        },
1473                        ErrorCapability {
1474                            code: "invalid_dataset",
1475                            exit_code: 2,
1476                            channel: "stderr",
1477                        },
1478                        ErrorCapability {
1479                            code: "unsupported_circuit",
1480                            exit_code: 2,
1481                            channel: "stderr",
1482                        },
1483                        ErrorCapability {
1484                            code: "loss_log_mismatch",
1485                            exit_code: 2,
1486                            channel: "stderr",
1487                        },
1488                        ErrorCapability {
1489                            code: "output_error",
1490                            exit_code: 2,
1491                            channel: "stderr",
1492                        },
1493                    ],
1494                    decoders: Vec::new(),
1495                    artifacts: vec![ArtifactCapability {
1496                        name: "public_dataset",
1497                        flag: "--out",
1498                        format: "directory",
1499                    }],
1500                },
1501                Capability {
1502                    name: decode::COMMAND,
1503                    argv: vec!["decode"],
1504                    input_sources: vec!["public_decoder_dataset_directory"],
1505                    formats: vec!["b8", "json"],
1506                    output_schema: decode::STATS_SCHEMA_VERSION,
1507                    arguments: vec![
1508                        ArgumentCapability {
1509                            name: "decoder",
1510                            flag: "--decoder",
1511                            required: true,
1512                            values: available_decoders(),
1513                            default: None,
1514                        },
1515                        ArgumentCapability {
1516                            name: "dataset",
1517                            flag: "--dataset",
1518                            required: true,
1519                            values: vec!["path"],
1520                            default: None,
1521                        },
1522                        ArgumentCapability {
1523                            name: "predictions",
1524                            flag: "--out",
1525                            required: true,
1526                            values: vec!["path"],
1527                            default: None,
1528                        },
1529                        ArgumentCapability {
1530                            name: "stats",
1531                            flag: "--stats-out",
1532                            required: true,
1533                            values: vec!["path"],
1534                            default: None,
1535                        },
1536                        ArgumentCapability {
1537                            name: "shot_timeout_ms",
1538                            flag: "--shot-timeout-ms",
1539                            required: false,
1540                            values: vec!["non_negative_integer"],
1541                            default: None,
1542                        },
1543                    ],
1544                    success_exit_code: 0,
1545                    errors: vec![
1546                        ErrorCapability {
1547                            code: "invalid_arguments",
1548                            exit_code: 2,
1549                            channel: "stderr",
1550                        },
1551                        ErrorCapability {
1552                            code: "missing_dataset_file",
1553                            exit_code: 2,
1554                            channel: "stderr",
1555                        },
1556                        ErrorCapability {
1557                            code: "invalid_dataset",
1558                            exit_code: 2,
1559                            channel: "stderr",
1560                        },
1561                        ErrorCapability {
1562                            code: "unsupported_dataset_mode",
1563                            exit_code: 2,
1564                            channel: "stderr",
1565                        },
1566                        ErrorCapability {
1567                            code: "unsupported_circuit",
1568                            exit_code: 2,
1569                            channel: "stderr",
1570                        },
1571                        ErrorCapability {
1572                            code: "decode_timeout",
1573                            exit_code: 3,
1574                            channel: "stderr",
1575                        },
1576                        ErrorCapability {
1577                            code: "decode_infeasible",
1578                            exit_code: 3,
1579                            channel: "stderr",
1580                        },
1581                        ErrorCapability {
1582                            code: "decode_error",
1583                            exit_code: 2,
1584                            channel: "stderr",
1585                        },
1586                        ErrorCapability {
1587                            code: "output_error",
1588                            exit_code: 2,
1589                            channel: "stderr",
1590                        },
1591                    ],
1592                    decoders: available_decoders(),
1593                    artifacts: vec![
1594                        ArtifactCapability {
1595                            name: "predictions",
1596                            flag: "--out",
1597                            format: "b8",
1598                        },
1599                        ArtifactCapability {
1600                            name: "stats",
1601                            flag: "--stats-out",
1602                            format: "rustqec.decode-stats.v1+json",
1603                        },
1604                    ],
1605                },
1606            ],
1607        },
1608    )
1609    .map_err(|message| CommandError {
1610        command: "capabilities",
1611        code: "output_error",
1612        message,
1613        json,
1614        exit_code: 2,
1615    })
1616}
1617
1618fn write_json(out: &mut dyn Write, value: &impl Serialize) -> Result<(), String> {
1619    serde_json::to_writer_pretty(&mut *out, value).map_err(|error| error.to_string())?;
1620    out.write_all(b"\n").map_err(|error| error.to_string())
1621}
1622
1623pub fn write_error(error: &RunError, stdout: &mut dyn Write, stderr: &mut dyn Write) {
1624    match error {
1625        RunError::Clap { error, .. }
1626            if matches!(
1627                error.kind(),
1628                ErrorKind::DisplayHelp | ErrorKind::DisplayVersion
1629            ) =>
1630        {
1631            let _ = write!(stdout, "{error}");
1632        }
1633        RunError::Clap {
1634            error,
1635            command,
1636            json: true,
1637        } => {
1638            let message = error.to_string();
1639            let envelope = ErrorEnvelope {
1640                schema_version: SCHEMA_VERSION,
1641                status: "error",
1642                command,
1643                error: ErrorBody {
1644                    code: "invalid_arguments",
1645                    message: &message,
1646                },
1647            };
1648            let _ = write_json(stderr, &envelope);
1649        }
1650        RunError::Clap { error, .. } => {
1651            let _ = write!(stderr, "{error}");
1652        }
1653        RunError::Command(error) if error.json => {
1654            let envelope = ErrorEnvelope {
1655                schema_version: SCHEMA_VERSION,
1656                status: "error",
1657                command: error.command,
1658                error: ErrorBody {
1659                    code: error.code,
1660                    message: &error.message,
1661                },
1662            };
1663            let _ = write_json(stderr, &envelope);
1664        }
1665        RunError::Command(error) => {
1666            let _ = writeln!(stderr, "{}", error.message);
1667        }
1668    }
1669}
1670
1671pub fn exit_code(error: &RunError) -> u8 {
1672    match error {
1673        RunError::Clap { error, .. } => error.exit_code() as u8,
1674        RunError::Command(error) => error.exit_code,
1675    }
1676}
1677
1678fn parse_error_context(args: &[OsString]) -> (&'static str, bool) {
1679    let words = args
1680        .iter()
1681        .skip(1)
1682        .map(|value| value.to_string_lossy())
1683        .collect::<Vec<_>>();
1684    let command_words = words_without_global_options(&words);
1685    let is_stats = command_words
1686        .windows(2)
1687        .any(|pair| pair[0] == "circuit" && pair[1] == "stats");
1688    let pipeline_command = ["gen", "sample", "detect", "dem"].iter().find_map(|verb| {
1689        command_words
1690            .windows(2)
1691            .any(|pair| pair[0] == "circuit" && pair[1] == *verb)
1692            .then_some(match *verb {
1693                "gen" => pipeline::CIRCUIT_GEN_COMMAND,
1694                "sample" => pipeline::CIRCUIT_SAMPLE_COMMAND,
1695                "detect" => pipeline::CIRCUIT_DETECT_COMMAND,
1696                _ => pipeline::CIRCUIT_DEM_COMMAND,
1697            })
1698    });
1699    let is_dataset_export = command_words
1700        .windows(2)
1701        .any(|pair| pair[0] == "dataset" && pair[1] == "export");
1702    let is_capabilities = command_words.contains(&"capabilities");
1703    let is_decode = command_words.contains(&"decode");
1704    let command = if is_stats {
1705        CIRCUIT_STATS_COMMAND
1706    } else if let Some(pipeline_command) = pipeline_command {
1707        pipeline_command
1708    } else if is_dataset_export {
1709        pipeline::DATASET_EXPORT_COMMAND
1710    } else if is_capabilities {
1711        "capabilities"
1712    } else if is_decode {
1713        decode::COMMAND
1714    } else {
1715        "rustqec"
1716    };
1717
1718    let explicit_error_format = option_value(&words, "--error-format");
1719    let explicit_output_format = option_value(&words, "--format");
1720    let json = match explicit_error_format {
1721        Some(Some("human")) => false,
1722        Some(_) => true,
1723        None if is_capabilities || is_decode => true,
1724        None if pipeline_command.is_some() || is_dataset_export => {
1725            !matches!(explicit_output_format, Some(Some("human")))
1726        }
1727        None if is_stats => match explicit_output_format {
1728            Some(Some("human")) => false,
1729            Some(_) => true,
1730            None => false,
1731        },
1732        None => false,
1733    };
1734    (command, json)
1735}
1736
1737fn words_without_global_options<'a>(words: &'a [std::borrow::Cow<'a, str>]) -> Vec<&'a str> {
1738    let mut command_words = Vec::new();
1739    let mut index = 0;
1740    while index < words.len() {
1741        let word = words[index].as_ref();
1742        if word == "--error-format" {
1743            index += 2;
1744        } else if word.starts_with("--error-format=") {
1745            index += 1;
1746        } else {
1747            command_words.push(word);
1748            index += 1;
1749        }
1750    }
1751    command_words
1752}
1753
1754fn option_value<'a>(words: &'a [std::borrow::Cow<'a, str>], flag: &str) -> Option<Option<&'a str>> {
1755    for (index, word) in words.iter().enumerate() {
1756        if word == flag {
1757            return Some(words.get(index + 1).map(|value| value.as_ref()));
1758        }
1759        if let Some(value) = word
1760            .strip_prefix(flag)
1761            .and_then(|rest| rest.strip_prefix('='))
1762        {
1763            return Some(Some(value));
1764        }
1765    }
1766    None
1767}