Enhancement proposalEPR-0004The command line, configuration and the agent skill○ proposed
● 0 of 2 decisions settled○ 1 assumption to confirmpinned at 4fcfb4apull request #133tracking issue: none (a baseline proposal describes code that already ships, so there is no milestone to track)started: 2026-10-04feature name: command_line_and_configurationdecides: the owner, who alone sets the status to accepted
EPR-0004● 0 of 2 settled○ 1 to confirm
Enhancement proposalEPR-0004The command line, configuration and the agent skill○ proposed
pinned at 4fcfb4apull request #133tracking issue: none (a baseline proposal describes code that already ships, so there is no milestone to track)started: 2026-10-04feature name: command_line_and_configurationdecides: the owner, who alone sets the status to accepted
There is one matra command line, written in Rust as the library module
matra::cli, whose whole surface is cli::run(args, out, err) -> u8. Two
launchers call it: the Rust binary and the Python entry point that pip and
uvx install. Every --json result is one envelope with a version number.
Where things live and what the defaults are come from Config, which
resolves each key from an explicit argument, then the environment, then a
TOML file, then defaults compiled into the crate, and records which of those
each value came from. Configuration never decides what a call computes. The
binary prints its own agent instructions with matra --skill, embedded from
the same files a plugin distributes, and a test runs every command in them.
This is a baseline proposal. It describes the code at the pinned commit and
carries forward the reasons that still hold from RFC-0011, RFC-0012,
RFC-0020, EP-0010 and EP-0011. A later proposal that changes any of it says
so. Unmarked statements about the code are observed at the pinned commit
through the link beside them; a claim that is inferred or assumed says so.
One program, not two that agree by inspection. 0.1.0 shipped two command
lines: the Rust binary and a Python re-implementation in click and rich so
that uvx matra worked. They drifted: the Python one grew a flag the Rust
one lacked, lacked one the Rust one had, and had earlier re-implemented
passive detection and got it wrong
(RFC-0011). The command line now
lives in the library because a binary target cannot be reached from PyO3,
and maturin's own guidance for a crate that is both a library and a tool is
a Python entry point that calls into the extension.
Working with no setup, on every surface. Before 0.2.0 the library
required a model directory every caller re-derived, under a path
(~/.matra) no developer tool on Linux or macOS uses
(RFC-0011). Config gives every
surface one resolution order and the XDG locations.
Configuration is where things are, not what happens. A config format
that reaches into the library would put pipeline policy in a file the
library parses. So the file carries only what a caller could pass as an
argument; which metrics run and how output looks stay with the caller and
the binary (RFC-0011, option B over option C).
An agent's instructions should match the installed binary. An agent
reaches the docsite by link and prior knowledge; --help carries no
semantics. Instructions printed by the program they describe cannot be
stale against it (RFC-0012).
matra analyze notes.md # a table of metricsmatra analyze notes.md --json # the same, as JSONmatra summarize report.txt -n 3 --method textrankmatra keyphrases - --stdin-filename draft.md < draft.mdmatra config show # every setting and where it came frommatra --skill # the agent skill
The commands are analyze (with --sections), summarize, keyphrases, config show, config init [--force] and completions <bash|zsh|fish>● observedcli/mod.rs:112-242.
The global flags are --json, --model-dir, --quiet, --color, --stdin-filename, --skill and --reference● observedcli/mod.rs:112-242.
- reads stdin, and --stdin-filename both labels it and chooses its
decomposer by extension.
src/cli/mod.rs lines 112 to 242, at 4fcfb4a
112 #[derive(Parser)]
113 #[command(
114 about = "Text in, structured analysis out.",
115 long_about = "matra parses text into CoNLL-U structure and measures it. \
116 It reports what is there; interpretation is yours."
117 )]
118 struct Cli {
119 /// Emit JSON instead of a human-readable table.
120 #[arg(long, global = true)]
121 json: bool,
122123 /// Directory holding the UDPipe model. Downloads on first use.
124 #[arg(long, global = true, value_name = "DIR")]
125 model_dir: Option<PathBuf>,
126127 /// Suppress the human-readable output. Exit codes are unchanged, and
128 /// `--json` is unaffected.
129 #[arg(long, short, global = true)]
130 quiet: bool,
131132 /// When to colorize output. `auto` also honors NO_COLOR.
133 #[arg(long, global = true, value_enum, default_value_t = ColorWhen::Auto, value_name = "WHEN")]
134 color: ColorWhen,
135136 /// Name to report for input read from stdin. Its extension selects
137 /// the decomposer, so `notes.md` is read as markdown.
138 #[arg(long, global = true, value_name = "NAME", default_value = "<stdin>")]
139 stdin_filename: String,
140141 /// Print the agent skill: what matra is for, every command with its
142 /// JSON shape, and how to read the numbers. Outranks a subcommand.
143 #[arg(long, global = true)]
144 skill: bool,
145146 /// With `--skill`: print one reference, or list them all when no name
147 /// is given.
148 #[arg(
149 long,
150 short = 'r',
151 global = true,
152 value_name = "NAME",
153 num_args = 0..=1,
154 )]
155 reference: Option<Option<String>>,
156157 #[command(subcommand)]
158 command: Option<Command>,
159 }
160161 #[derive(Subcommand)]
162 enum Command {
163 /// Parse a document and report its metrics.
164 Analyze {
165 /// File to analyze, or `-` for stdin.
166 path: PathBuf,
167 /// Also print a per-section breakdown.
168 #[arg(long, short)]
169 sections: bool,
170 },
171 /// Extract the most representative sentences.
172 Summarize {
173 /// File to summarize, or `-` for stdin.
174 path: PathBuf,
175 /// Number of sentences to return. Defaults to `summarize.n`.
176 #[arg(short)]
177 n: Option<usize>,
178 /// Ranking algorithm. Defaults to `summarize.algorithm`.
179 #[arg(long, value_enum)]
180 method: Option<SummaryMethod>,
181 },
182 /// Extract keyphrases.
183 Keyphrases {
184 /// File to extract from, or `-` for stdin.
185 path: PathBuf,
186 /// Maximum number of phrases to return. Defaults to `keyphrases.n`.
187 #[arg(short)]
188 n: Option<usize>,
189 /// Extraction algorithm. Defaults to `keyphrases.algorithm`.
190 #[arg(long, value_enum)]
191 method: Option<KeyphraseMethod>,
192 },
193 /// Inspect and create the configuration file.
194 Config {
195 #[command(subcommand)]
196 action: ConfigAction,
197 },
198 /// Print a shell completion script.
199 Completions {
200 /// Shell to generate for.
201 #[arg(value_enum)]
202 shell: CompletionShell,
203 },
204 }
205206 #[derive(Subcommand)]
207 enum ConfigAction {
208 /// Print every resolved value with the rung it came from.
209 Show,
210 /// Write the shipped defaults to the resolved config path.
211 Init {
212 /// Overwrite an existing file.
213 #[arg(long)]
214 force: bool,
215 },
216 }
217218 #[derive(Copy, Clone, PartialEq, Eq, ValueEnum)]
219 enum SummaryMethod {
220 Tfidf,
221 Textrank,
222 }
223224 #[derive(Copy, Clone, PartialEq, Eq, ValueEnum)]
225 enum KeyphraseMethod {
226 Rake,
227 Yake,
228 }
229230 #[derive(Copy, Clone, PartialEq, Eq, ValueEnum)]
231 enum ColorWhen {
232 Auto,
233 Always,
234 Never,
235 }
236237 #[derive(Copy, Clone, PartialEq, Eq, ValueEnum)]
238 enum CompletionShell {
239 Bash,
240 Zsh,
241 Fish,
242 }
Exit codes follow ripgrep: 0 when something was found, 1 when the command succeeded and found nothing, 2 on an error; a broken pipe is 0 ● observedcli/mod.rs:1-19.
src/cli/mod.rs lines 1 to 19, at 4fcfb4a
1 //! The matra command line, as a library module.
2 //!
3 //! Application tier, compiled into the library so both launchers run the
4 //! same program. The library returns typed errors and structured data;
5 //! this module decides how to render them, which exit code to use, and
6 //! what to do when a single file in a batch fails.
7 //!
8 //! [`run`] is the whole surface. It never calls `std::process::exit` and
9 //! never touches the process's own stdout or stderr handles: the caller
10 //! passes both, so `src/bin/matra.rs` can hand it a locked stdout while
11 //! the Python launcher hands it a buffer.
12 //!
13 //! Exit codes follow the ripgrep convention:
14 //! 0 success, and (where applicable) something was found
15 //! 1 success, but nothing was found
16 //! 2 an error occurred
17 //!
18 //! A broken pipe is exit 0: the reader went away, which is what
19 //! `matra analyze x | head` does on purpose.
Every --json invocation emits one object with four keys ● observedcli/mod.rs:677-709:
src/cli/mod.rs lines 677 to 709, at 4fcfb4a
677 /// The one shape every `--json` invocation emits.
678 ///
679 /// `result` is the serde form of the domain value, unchanged. Everything
680 /// that identifies the run sits beside it rather than inside it, so a
681 /// consumer can dispatch on `command` without inspecting `result` first.
682 ///
683 /// `input` is null rather than absent for a command that reads no
684 /// document, which `--skill` is. The four keys are the envelope, and a
685 /// consumer that reads them positionally should not have to discover that
686 /// one of them is sometimes missing.
687 #[derive(serde::Serialize)]
688 struct Envelope<'a, T> {
689 format_version: u32,
690 command: &'a str,
691 input: Option<&'a str>,
692 result: T,
693 }
694695 fn write_envelope<T: serde::Serialize>(
696 out: &mut dyn Write,
697 command: &str,
698 input: Option<&str>,
699 result: T,
700 ) -> Fallible<()> {
701 let envelope = Envelope {
702 format_version: FORMAT_VERSION,
703 command,
704 input,
705 result,
706 };
707 writeln!(out, "{}", serde_json::to_string_pretty(&envelope)?)?;
708 Ok(())
709 }
result is the serialized domain value unchanged
(EPR-0002). input is null for a command that
reads no document.
format_version increments on any change to the envelope's shape or to the meaning of a field in result● observedcli/mod.rs:34-39.
Both launchers are held to spec/tests/cli/envelope.json● observedenvelope.json:1-19.
src/cli/mod.rs lines 34 to 39, at 4fcfb4a
34 /// The envelope's version integer. It increments on any change to the
35 /// envelope's own shape or to the meaning of a field inside `result`.
36 ///
37 /// cargo's precedent: `cargo metadata --format-version` is a versioned
38 /// integer with a compatibility policy rather than a published schema.
39 const FORMAT_VERSION: u32 = 1;
(config/default.toml.) Three environment variables name
what they override: MATRA_CONFIG_FILE, MATRA_DATA_DIR, MATRA_MODEL_DIR.
--model-dir on the command line, or Config::with_model_dir in Rust,
outranks all three.
A file written by an earlier config init may also set models.udpipe or
semantic.threshold. Both still load, both are ignored, and config show
names each one on stderr so the line can be removed.
uvx matra --skill prints SKILL.md: what matra is for, every command with
its JSON shape, how to read the numbers, and the limits. --skill -r lists
the references (errors, json, metrics, python, semantic,
structure) and --skill -r <name> prints one. With --json each is the
same envelope, with command set to "skill" and input null.
cli::run parses, dispatches and renders, never calls std::process::exit, and never touches the process's own streams: the caller passes both ● observedcli/mod.rs:50-106.
It returns a u8 because ExitCode cannot be read back for the Python launcher ● observedcli/mod.rs:50-106.
src/bin/matra.rs locks stdout and stderr, calls it, and converts with ExitCode::from● observedbin/matra.rs:1-26.
python/matra/cli.py passes sys.argv[1:] to _core.cli_main and exits with the result; cli_main passes each argument through os.fsencode so a non-UTF-8 path on Unix reaches the command line as the same bytes the Rust binary would see ● observedcli.py:1-10lib.rs:776-829.
pyproject.toml installs that launcher as the matra
script (scripts), and the python feature enables cli,
which enables udpipe (features).
src/cli/mod.rs lines 50 to 106, at 4fcfb4a
50 /// Run the command line.
51 ///
52 /// `args` is the full argument vector including the program name, the
53 /// way `std::env::args_os()` yields it. `out` receives everything a
54 /// reader is meant to consume (the rendered tables, the JSON, the
55 /// completion script, the help and version text); `err` receives
56 /// diagnostics.
57 ///
58 /// Returns the process exit code. It is a `u8` rather than a
59 /// [`std::process::ExitCode`] because `ExitCode` is opaque: there is no
60 /// public way to read the number back out of one, so the Python launcher
61 /// could not turn it into an `int`. `src/bin/matra.rs` converts with
62 /// `ExitCode::from`.
63 ///
64 /// Never panics on a caller's behalf and never exits the process. A
65 /// write failure on `out` is reported through the return code, not by
66 /// unwinding.
67 ///
68 /// ```no_run
69 /// let mut out = Vec::new();
70 /// let mut err = Vec::new();
71 /// let code = matra::cli::run(
72 /// ["matra", "--version"].into_iter().map(Into::into),
73 /// &mut out,
74 /// &mut err,
75 /// );
76 /// assert_eq!(code, 0);
77 /// ```
78 pub fn run(
79 args: impl IntoIterator<Item = OsString>,
80 out: &mut dyn Write,
81 err: &mut dyn Write,
82 ) -> u8 {
83 let cli = match parse(args) {
84 Ok(cli) => cli,
85 Err(early) => {
86 // clap renders `--help` and `--version` as an "error" that is
87 // not one. `use_stderr` is what separates them from a genuine
88 // usage failure, and it decides both the stream and the code.
89 let sink: &mut dyn Write = if early.to_stderr { err } else { out };
90 let _ = write!(sink, "{}", early.text);
91 return early.code;
92 }
93 };
94 95 match execute(&cli, out, err) {
96 Ok(Outcome::Found) => EXIT_FOUND,
97 Ok(Outcome::Empty) => EXIT_EMPTY,
98 Err(e) => {
99 if is_broken_pipe(e.as_ref()) {
100 return EXIT_FOUND;
101 }
102 let _ = writeln!(err, "matra: {e}");
103 EXIT_ERROR
104 }
105 }
106 }
50 /// Run the command line.
51 ///
52 /// `args` is the full argument vector including the program name, the
53 /// way `std::env::args_os()` yields it. `out` receives everything a
54 /// reader is meant to consume (the rendered tables, the JSON, the
55 /// completion script, the help and version text); `err` receives
56 /// diagnostics.
57 ///
58 /// Returns the process exit code. It is a `u8` rather than a
59 /// [`std::process::ExitCode`] because `ExitCode` is opaque: there is no
60 /// public way to read the number back out of one, so the Python launcher
61 /// could not turn it into an `int`. `src/bin/matra.rs` converts with
62 /// `ExitCode::from`.
63 ///
64 /// Never panics on a caller's behalf and never exits the process. A
65 /// write failure on `out` is reported through the return code, not by
66 /// unwinding.
67 ///
68 /// ```no_run
69 /// let mut out = Vec::new();
70 /// let mut err = Vec::new();
71 /// let code = matra::cli::run(
72 /// ["matra", "--version"].into_iter().map(Into::into),
73 /// &mut out,
74 /// &mut err,
75 /// );
76 /// assert_eq!(code, 0);
77 /// ```
78 pub fn run(
79 args: impl IntoIterator<Item = OsString>,
80 out: &mut dyn Write,
81 err: &mut dyn Write,
82 ) -> u8 {
83 let cli = match parse(args) {
84 Ok(cli) => cli,
85 Err(early) => {
86 // clap renders `--help` and `--version` as an "error" that is
87 // not one. `use_stderr` is what separates them from a genuine
88 // usage failure, and it decides both the stream and the code.
89 let sink: &mut dyn Write = if early.to_stderr { err } else { out };
90 let _ = write!(sink, "{}", early.text);
91 return early.code;
92 }
93 };
94 95 match execute(&cli, out, err) {
96 Ok(Outcome::Found) => EXIT_FOUND,
97 Ok(Outcome::Empty) => EXIT_EMPTY,
98 Err(e) => {
99 if is_broken_pipe(e.as_ref()) {
100 return EXIT_FOUND;
101 }
102 let _ = writeln!(err, "matra: {e}");
103 EXIT_ERROR
104 }
105 }
106 }
1 //! Launcher for the `matra` command line.
2 //!
3 //! Everything the command does lives in [`matra::cli`], which is compiled
4 //! into the library so the Rust binary and the Python entry point run the
5 //! same program rather than two that agree by inspection. This file does
6 //! the three things a launcher does: collect the arguments, lock the
7 //! streams, and turn the returned code into the process's own.
8 9 use std::io::Write;
10 use std::process::ExitCode;
1112 fn main() -> ExitCode {
13 let stdout = std::io::stdout();
14 let stderr = std::io::stderr();
15 let mut out = stdout.lock();
16 let mut err = stderr.lock();
1718 let code = matra::cli::run(std::env::args_os(), &mut out, &mut err);
1920 // A flush failure here is a broken pipe in almost every case, which
21 // the CLI already treats as success; there is nowhere left to report
22 // it to in any case.
23 let _ = out.flush();
24 let _ = err.flush();
25 ExitCode::from(code)
26 }
1 """Launcher for the matra command line. The command itself is Rust."""
2 3 import sys
4 5 from matra._core import cli_main
6 7 8 def main() -> None:
9 """Run the matra CLI and exit with the code it returns."""
10 raise SystemExit(cli_main(sys.argv[1:]))
776 /// Run the matra command line and return its exit code.
777 ///
778 /// `argv` is the argument vector *without* the program name, which
779 /// `cli::run` supplies itself so `--help` reads the same from this
780 /// launcher and from the Rust binary.
781 ///
782 /// The command renders into byte buffers, which are then written to
783 /// Python's own `sys.stdout` and `sys.stderr` and flushed. Handing
784 /// `cli::run` the real file descriptors would interleave badly with
785 /// anything Python has already buffered on the same stream; going
786 /// through `sys` keeps one writer per stream.
787 ///
788 /// A failure writing those buffers out is swallowed rather than
789 /// raised. It is a broken pipe in practice (`matra ... | head`), and
790 /// the Rust launcher treats that as success too; there is nowhere
791 /// left to report it to in any case.
792 ///
793 /// The arguments arrive as arbitrary Python objects and go through
794 /// `os.fsencode`, not through `String`. A `sys.argv` entry is not
795 /// guaranteed to be text: on unix a path is bytes, and Python decodes
796 /// an undecodable one with surrogate escapes rather than failing.
797 /// Extracting a `String` would reject exactly those arguments, so a
798 /// file the Rust binary opens without comment would be unreachable
799 /// through this launcher. `os.fsencode` reverses the escape and hands
800 /// back the original bytes, which become an `OsString` unchanged. A
801 /// conversion failure is raised rather than swallowed: an argument
802 /// that is not a string, bytes, or a path is a caller's error, and
803 /// silently dropping it would run a different command than the one
804 /// that was asked for.
805 #[pyfunction]
806 #[allow(unreachable_pub)] // pyo3 macro requirement, same as _core below.
807 pub fn cli_main(py: Python<'_>, argv: Vec<Bound<'_, PyAny>>) -> PyResult<i32> {
808 use std::ffi::OsString;
809810 let fsencode = py.import("os")?.getattr("fsencode")?;
811 let mut args: Vec<OsString> = Vec::with_capacity(argv.len() + 1);
812 args.push(OsString::from("matra"));
813 for arg in argv {
814 let bytes: Vec<u8> = fsencode.call1((arg,))?.extract()?;
815 args.push(os_string_of(bytes));
816 }
817818 // stdout is buffered and written at the end, so the rendered
819 // result arrives as one piece. stderr is written through as it
820 // is produced, because the first thing a cold run writes there
821 // is "downloading the model", and a diagnostic that explains a
822 // twenty-second wait is worthless once the wait is over.
823 let mut out: Vec<u8> = Vec::new();
824 let mut err = PyStream { py, name: "stderr" };
825 let code = crate::cli::run(args, &mut out, &mut err);
826827 let _ = write_stream(py, "stdout", &out);
828 Ok(i32::from(code))
829 }
src/cli/ is the application tier. Boundary rule 7 holds it to the public
surface (Engine, Ingest, extraction, config, domain) and never a
port or an adapter; a semgrep rule checks the imports
(EPR-0001).
It validates an input path before building the engine, so a missing file is reported before a 16 MB download ● observedcli/mod.rs:372-430.
The download notice goes to stderr so --json stdout stays one object, and --quiet silences it ● observedcli/mod.rs:486-530.
src/cli/mod.rs lines 372 to 430, at 4fcfb4a
372 fn execute(cli: &Cli, out: &mut dyn Write, err: &mut dyn Write) -> Fallible<Outcome> {
373 // `--skill` is a property of the program rather than an action on a
374 // document, so it outranks a subcommand: `matra analyze x --skill`
375 // prints the skill and ignores the analysis. Dispatching it first is
376 // what makes that true, and it is also what lets the flag stand alone
377 // with no subcommand at all.
378 if cli.skill {
379 return skill::run(cli, out);
380 }
381 if cli.reference.is_some() {
382 return Err(
383 "--reference names a section of the agent skill; pass --skill with it, \
384 or run `matra --skill -r` to list the references"
385 .into(),
386 );
387 }
388389 // `parse` refuses a run with neither a subcommand nor `--skill`, so
390 // there is one by the time execution reaches here.
391 let Some(command) = &cli.command else {
392 return Err("no command given; run `matra --help` for the list".into());
393 };
394395 // The two config actions and the completion script touch neither the
396 // model nor any input, so they are dispatched before anything is
397 // loaded.
398 match command {
399 Command::Config { action } => return config_cmd::run(cli, action, out, err),
400 Command::Completions { shell } => {
401 let shell = match shell {
402 CompletionShell::Bash => clap_complete::Shell::Bash,
403 CompletionShell::Zsh => clap_complete::Shell::Zsh,
404 CompletionShell::Fish => clap_complete::Shell::Fish,
405 };
406 let mut command = Cli::command().name("matra").bin_name("matra");
407 clap_complete::generate(shell, &mut command, "matra", out);
408 return Ok(Outcome::Found);
409 }
410 _ => {}
411 }
412413 let path = match command {
414 Command::Analyze { path, .. }
415 | Command::Summarize { path, .. }
416 | Command::Keyphrases { path, .. } => path,
417 Command::Config { .. } | Command::Completions { .. } => unreachable!("dispatched above"),
418 };
419 let input = Input::of(path);
420421 // Validate the input before touching the model. Downloading 16 MB to
422 // then report that the file does not exist is a poor trade for the
423 // reader.
424 if let Input::Path(p) = &input {
425 check_input(p)?;
426 }
427428 let cfg = resolve_config(cli)?;
429 let engine = build_engine(cli, &cfg, err)?;
430 let doc = document_of(&input, &cli.stdin_filename, &engine)?;
486 /// The standard pipeline, saying so on stderr before it downloads a
487 /// model it does not have.
488 ///
489 /// The first run fetches 16 MB from a university server in Prague.
490 /// Measured cold starts ran from 3 to 35 seconds, and until this line
491 /// existed every one of them wrote zero bytes to either stream before
492 /// the result: a blank terminal, indistinguishable from a hung process,
493 /// under a README section titled "No setup". The notice fires only when
494 /// the model is not already on disk, so a warm run is as quiet as it
495 /// ever was.
496 ///
497 /// It goes to stderr, which keeps `--json` stdout a single object, and
498 /// `--quiet` silences it: that flag means "no human-readable output",
499 /// and this is human-readable output.
500 fn build_engine(cli: &Cli, cfg: &Config, err: &mut dyn Write) -> domain::Result<crate::Engine> {
501 if cli.quiet {
502 return crate::Engine::from_config(cfg);
503 }
504 crate::Engine::from_config_with_notice(cfg, |notice| {
505 // A diagnostic that cannot be written is not worth failing a
506 // run over, and there is nowhere left to report it to.
507 let _ = err.write_all(notice_text(notice).as_bytes());
508 let _ = err.flush();
509 })
510 }
511512 /// What a first run writes to stderr before the fetch: the artifact,
513 /// its size and destination, then the license it is published under.
514 ///
515 /// The second line exists because the model is a separate work from
516 /// matra with terms of its own, and the download is the one moment
517 /// every user of the command line passes through. The license and its
518 /// URL come from the notice, pinned beside the model's URL, so a change
519 /// of model cannot leave this line naming the old terms.
520 fn notice_text(notice: &domain::ProvisionNotice) -> String {
521 format!(
522 "matra: downloading {} ({}) into {}\n\
523 matra: the model is licensed {}, separately from matra: {}\n",
524 notice.artifact,
525 human_bytes(notice.bytes),
526 notice.destination.display(),
527 notice.license,
528 notice.license_url
529 )
530 }
--skill outranks a subcommand: matra analyze x --skill prints the skill ● observedcli/mod.rs:372-430.
Bare matra with neither is a usage error, exit 2 ● observedcli/mod.rs:252-288.
src/cli/mod.rs lines 372 to 430, at 4fcfb4a
372 fn execute(cli: &Cli, out: &mut dyn Write, err: &mut dyn Write) -> Fallible<Outcome> {
373 // `--skill` is a property of the program rather than an action on a
374 // document, so it outranks a subcommand: `matra analyze x --skill`
375 // prints the skill and ignores the analysis. Dispatching it first is
376 // what makes that true, and it is also what lets the flag stand alone
377 // with no subcommand at all.
378 if cli.skill {
379 return skill::run(cli, out);
380 }
381 if cli.reference.is_some() {
382 return Err(
383 "--reference names a section of the agent skill; pass --skill with it, \
384 or run `matra --skill -r` to list the references"
385 .into(),
386 );
387 }
388389 // `parse` refuses a run with neither a subcommand nor `--skill`, so
390 // there is one by the time execution reaches here.
391 let Some(command) = &cli.command else {
392 return Err("no command given; run `matra --help` for the list".into());
393 };
394395 // The two config actions and the completion script touch neither the
396 // model nor any input, so they are dispatched before anything is
397 // loaded.
398 match command {
399 Command::Config { action } => return config_cmd::run(cli, action, out, err),
400 Command::Completions { shell } => {
401 let shell = match shell {
402 CompletionShell::Bash => clap_complete::Shell::Bash,
403 CompletionShell::Zsh => clap_complete::Shell::Zsh,
404 CompletionShell::Fish => clap_complete::Shell::Fish,
405 };
406 let mut command = Cli::command().name("matra").bin_name("matra");
407 clap_complete::generate(shell, &mut command, "matra", out);
408 return Ok(Outcome::Found);
409 }
410 _ => {}
411 }
412413 let path = match command {
414 Command::Analyze { path, .. }
415 | Command::Summarize { path, .. }
416 | Command::Keyphrases { path, .. } => path,
417 Command::Config { .. } | Command::Completions { .. } => unreachable!("dispatched above"),
418 };
419 let input = Input::of(path);
420421 // Validate the input before touching the model. Downloading 16 MB to
422 // then report that the file does not exist is a poor trade for the
423 // reader.
424 if let Input::Path(p) = &input {
425 check_input(p)?;
426 }
427428 let cfg = resolve_config(cli)?;
429 let engine = build_engine(cli, &cfg, err)?;
430 let doc = document_of(&input, &cli.stdin_filename, &engine)?;
252 fn parse(args: impl IntoIterator<Item = OsString>) -> Result<Cli, EarlyExit> {
253 // The program name is set here rather than taken from argv[0], so
254 // `--help` reads the same whether the launcher was the Rust binary or
255 // the Python entry point.
256 //
257 // Color is off in clap's own output because the two launchers must
258 // produce the same bytes, and the Python launcher renders into a
259 // buffer where a terminal check would be meaningless.
260 let mut command = Cli::command()
261 .name("matra")
262 .bin_name("matra")
263 .version(version_line())
264 .color(clap::ColorChoice::Never);
265266 let matches = command.try_get_matches_from_mut(args).map_err(early_exit)?;
267 let cli = Cli::from_arg_matches(&matches).map_err(early_exit)?;
268269 // The subcommand is optional in the derive because `--skill` is a
270 // whole invocation on its own. It is still required of every other
271 // run, and the refusal is the one clap gave when the field was not an
272 // `Option`: the short help on stderr, exit 2. Rebuilding it here
273 // rather than letting a `None` fall through keeps `matra` with no
274 // arguments printing what it has always printed.
275 //
276 // A bare `-r` is exempt so that it reaches the one message that says
277 // what it is missing. Answering "you gave me no subcommand" to
278 // someone who reached for the skill and forgot half the incantation
279 // would be true and useless.
280 if cli.command.is_none() && !cli.skill && cli.reference.is_none() {
281 return Err(EarlyExit {
282 text: command.render_help().to_string(),
283 to_stderr: true,
284 code: EXIT_ERROR,
285 });
286 }
287 Ok(cli)
288 }
Config is a composition-root value beside Engine,
#[non_exhaustive] with private fields. Config::resolve
reads the process environment and the file; Config::from_sources takes
both injected, which is how tests avoid the developer's home.
matra never creates ~/.matra; the fallback only keeps an existing cache
working. Environment values are used as paths unchanged, with no ~
expansion, and an empty variable counts as unset.
The file is capped at 64 KiB by its metadata before it is read (InputTooLarge, what = "config_file"), and may be a symlink, since dotfiles repositories commonly link it ● observedconfig.rs:49config.rs:703-720.
Unknown keys are rejected (deny_unknown_fields), so a setting a user believes is in force cannot be silently ignored ● observedconfig.rs:467-503.
An unknown algorithm name fails at resolve time.
models.embedding must be a single ordinary path component, because the embedding provisioner sweeps aged temporaries inside the directory it names ● observedconfig.rs:588-606.
703 /// Read the config file if it is there. Absent is `Ok(None)`; oversized,
704 /// unreadable and non-UTF-8 are all loud.
705 fn read_config_file(path: &Path) -> domain::Result<Option<String>> {
706 // A config file under the user's own home is routinely a symlink into
707 // a dotfiles repository, so unlike `source/file.rs` (which reads paths
708 // chosen by whoever calls matra) this path does not reject symlinks.
709 let metadata = match std::fs::metadata(path) {
710 Ok(m) => m,
711 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
712 Err(e) => return Err(Error::Io(e)),
713 };
714 if metadata.len() > MAX_CONFIG_BYTES {
715 return Err(Error::InputTooLarge {
716 limit: MAX_CONFIG_BYTES as usize,
717 actual: metadata.len() as usize,
718 what: "config_file",
719 });
720 }
467 // Unknown keys are rejected rather than ignored. A file matra half-reads
468 // is a file whose author believes a setting is in force when it is not,
469 // and the silence lasts until someone measures. Every field is optional,
470 // so a partial file overrides key by key.
471472 #[derive(Debug, Default, serde::Deserialize)]
473 #[serde(deny_unknown_fields)]
474 struct FileConfig {
475 models: Option<ModelsSection>,
476 semantic: Option<SemanticSection>,
477 summarize: Option<CountAndAlgorithm>,
478 keyphrases: Option<CountAndAlgorithm>,
479 }
480481 #[derive(Debug, Default, serde::Deserialize)]
482 #[serde(deny_unknown_fields)]
483 struct ModelsSection {
484 /// Deprecated (RFC-0020): accepted so an old file loads, read by nothing.
485 udpipe: Option<String>,
486 embedding: Option<String>,
487 }
488489 /// The whole section is deprecated (RFC-0020) and no longer in
490 /// `config/default.toml`. It stays in the schema so a file that carries it
491 /// loads.
492 #[derive(Debug, Default, serde::Deserialize)]
493 #[serde(deny_unknown_fields)]
494 struct SemanticSection {
495 threshold: Option<f32>,
496 }
497498 #[derive(Debug, Default, serde::Deserialize)]
499 #[serde(deny_unknown_fields)]
500 struct CountAndAlgorithm {
501 n: Option<usize>,
502 algorithm: Option<String>,
503 }
588 fn check_path_component(
589 key: &'static str,
590 value: &str,
591 sources: &[(&'static str, ValueSource)],
592 file_path: &Path,
593 ) -> domain::Result<()> {
594 let mut components = Path::new(value).components();
595 let single =
596 matches!(components.next(), Some(Component::Normal(_))) && components.next().is_none();
597 if single && !value.contains('\\') {
598 return Ok(());
599 }
600 Err(Error::InvalidInput(format!(
601 "{}: {key} is `{value}`, which is not a single path component. It names a directory \
602 inside the model directory, so it cannot be empty, absolute, or contain `/`, `\\`, \
603 `.` or `..`",
604 origin_of(key, sources, file_path),
605 )))
606 }
RFC-0020 deprecated
models.udpipe and semantic.threshold, because neither selected anything:
the UDPipe model is pinned in the adapter beside its digest, and every
clustering call takes its threshold as an argument. They left
config/default.toml; the schema still accepts them so a 0.2.x file loads;
Config::udpipe_model and Config::semantic_threshold carry
#[deprecated] and return the file's value or the former default;
Config::deprecated_keys lists which ones the file set; and
Config::sources omits them (accessors).
config show writes one stderr line per deprecated key, naming the file, unless --quiet● observedcli/config_cmd.rs:82-111.
Removing them is a breaking change and takes its own proposal.
src/cli/config_cmd.rs lines 82 to 111, at 4fcfb4a
82 /// One stderr line per deprecated key the config file set (RFC-0020).
83 ///
84 /// The keys are accepted so an old file keeps loading, and that is the
85 /// silence `deny_unknown_fields` exists to prevent: a setting the author
86 /// believes is in force when nothing reads it. `config show` is where
87 /// matra reports where its configuration came from, so it is where the
88 /// file is named and the line called out. Stdout stays the settings in
89 /// force, so `--json` is still one object. `--quiet` silences it, as it
90 /// silences the download notice: it is human-readable output.
91 fn write_deprecation_notes(cfg: &Config, err: &mut dyn Write) {
92 let file = cfg.config_file().map_or_else(
93 || "the config file".to_string(),
94 |p| p.display().to_string(),
95 );
96 for key in cfg.deprecated_keys() {
97 let why = match key {
98 "models.udpipe" => {
99 "the UDPipe model is pinned in matra, and another one loads by path from the library"
100 }
101 "semantic.threshold" => "every clustering call takes its threshold as an argument",
102 _ => "nothing reads it",
103 };
104 // A diagnostic that cannot be written is not worth failing the
105 // command over, and there is nowhere left to report it to.
106 let _ = writeln!(
107 err,
108 "matra: {file} sets `{key}`, which is deprecated and ignored; {why}. Remove the line."
109 );
110 }
111 }
config init writes atomically: a temporary file in the same directory, then a hard link when not forced (which fails if the target appeared in the meantime) or a rename when forced ● observedcli/config_cmd.rs:213-293.
src/cli/config_cmd.rs lines 213 to 293, at 4fcfb4a
213 /// Write the shipped defaults to `path`, atomically.
214 ///
215 /// The bytes land in a temporary file in the same directory and arrive
216 /// at `path` under one rename, so a concurrent reader sees either the
217 /// old file or the whole new one and never a half-written config.
218 ///
219 /// Without `force` the arrival is a hard link instead, because
220 /// `hard_link` fails when the destination exists and `rename` does not.
221 /// Checking `exists()` and then renaming would leave a window in which
222 /// another process creates the file and this one silently destroys it;
223 /// the link closes that window in the kernel rather than narrowing it.
224 fn write_defaults(path: &Path, force: bool) -> Fallible<()> {
225 // The early check exists for the message, not for the guarantee. The
226 // guarantee is the link below.
227 if !force && path.exists() {
228 return Err(format!(
229 "{} already exists; pass --force to overwrite it",
230 path.display()
231 )
232 .into());
233 }
234235 let parent = path
236 .parent()
237 .filter(|p| !p.as_os_str().is_empty())
238 .unwrap_or(Path::new("."));
239 std::fs::create_dir_all(parent)
240 .map_err(|e| io_at("create the config directory", parent, &e))?;
241242 let temp = parent.join(format!(
243 ".{}.{}.tmp",
244 path.file_name()
245 .and_then(|n| n.to_str())
246 .unwrap_or("config.toml"),
247 std::process::id()
248 ));
249 // `create_new` refuses a leftover temp from a crashed run rather than
250 // overwriting whatever is there.
251 let mut file = std::fs::OpenOptions::new()
252 .write(true)
253 .create_new(true)
254 .open(&temp)
255 .map_err(|e| io_at("create the temporary file", &temp, &e))?;
256 let written = file
257 .write_all(DEFAULT_TOML.as_bytes())
258 .and_then(|()| file.sync_all());
259 drop(file);
260 if let Err(e) = written {
261 let _ = std::fs::remove_file(&temp);
262 return Err(Box::new(io_at("write the config to", &temp, &e)));
263 }
264265 let arrived = if force {
266 std::fs::rename(&temp, path)
267 } else {
268 std::fs::hard_link(&temp, path)
269 };
270 if let Err(e) = arrived {
271 let _ = std::fs::remove_file(&temp);
272 if e.kind() == std::io::ErrorKind::AlreadyExists {
273 return Err(format!(
274 "{} already exists; pass --force to overwrite it",
275 path.display()
276 )
277 .into());
278 }
279 return Err(Box::new(io_at("move the config into place at", path, &e)));
280 }
281282 // `rename` consumed the temp; `hard_link` left it behind as a second
283 // name for the same inode. Removing it is tidying after the fact,
284 // not part of the arrival: the config is already at `path` and
285 // already correct. Reporting a failure here would tell the caller
286 // the write failed when it succeeded, which is the one thing an exit
287 // code must never do. The cost of ignoring it is a stray dotfile
288 // beside a working config, and `--force` overwrites it.
289 if !force {
290 let _ = std::fs::remove_file(&temp);
291 }
292 Ok(())
293 }
SKILL.md and six references under skills/matra/ are embedded with include_str!● observedcli/skill.rs:1-70.
Each reference's summary is read from its own frontmatter rather than kept
in a second list, and a test holds the table of names equal to the
directory.
The frontmatter's version matches the crate's ● observedSKILL.md:1-5Cargo.toml:1-14.
tests/skill.rs extracts every fenced block whose first line is a matra command, runs it through cli::run (or as a subprocess with a clean environment, for config), and asserts the annotated exit code and, for --json, the envelope; the block count is checked against a fence-aware scan so an unfenced command cannot hide ● observedtests/skill.rs:1-37.
Alongside the flag: AGENTS.md for contributing agents,
.claude-plugin/plugin.json so the repository installs as a plugin, and
site/content/llms.txt, generated from the docsite's SUMMARY.md and held
current by a docs gate.
src/cli/skill.rs lines 1 to 70, at 4fcfb4a
1 //! `matra --skill`, the agent-facing surface.
2 //!
3 //! The text an agent needs is embedded in the program it describes, so
4 //! the instructions always match the installed version rather than a
5 //! copy that may have drifted (RFC-0012). The same files under
6 //! `skills/matra/` are what a plugin distributes, so there is one source
7 //! and not two.
8 //!
9 //! Three shapes, all exit 0:
10 //!
11 //! ```text
12 //! matra --skill SKILL.md, verbatim
13 //! matra --skill -r every reference, one per line, name then summary
14 //! matra --skill -r <name> that reference, verbatim
15 //! ```
16 //!
17 //! An unknown name is exit 2 and names the ones that exist.
18 //!
19 //! Neither the model nor any input is touched, which is why this is
20 //! dispatched before the engine is built, ahead even of the subcommand.
2122 use std::io::Write;
2324 use super::{Cli, Fallible, Outcome, write_envelope};
2526 /// The top level, embedded. `--skill` writes these bytes and nothing
27 /// else, so the output is byte-identical to the file on disk and to the
28 /// other launcher.
29 const SKILL: &str = include_str!("../../skills/matra/SKILL.md");
3031 /// The name the top level answers to in `--json`. It is not a reference,
32 /// so it cannot collide with one.
33 const SKILL_NAME: &str = "SKILL";
3435 /// Every reference, in the order `--skill -r` lists them: alphabetical by
36 /// file name, which is also the name a reader passes back.
37 ///
38 /// The name is the file name because that is the pair `-r <name>` looks
39 /// up. The summary is not here: it is parsed from each file's own
40 /// frontmatter by [`summary_of`], so the list a reader sees cannot drift
41 /// from the file it points at. A test below asserts this table's names
42 /// against the directory, so a reference added without an entry here
43 /// fails the suite rather than going missing from the list.
44 const REFERENCES: &[(&str, &str)] = &[
45 (
46 "errors",
47 include_str!("../../skills/matra/references/errors.md"),
48 ),
49 (
50 "json",
51 include_str!("../../skills/matra/references/json.md"),
52 ),
53 (
54 "metrics",
55 include_str!("../../skills/matra/references/metrics.md"),
56 ),
57 (
58 "python",
59 include_str!("../../skills/matra/references/python.md"),
60 ),
61 (
62 "semantic",
63 include_str!("../../skills/matra/references/semantic.md"),
64 ),
65 (
66 "structure",
67 include_str!("../../skills/matra/references/structure.md"),
68 ),
69 ];
70
1 ---
2 name: matra
3 description: Parses text into a typed structure tree, measures it, and ranks what is in it. Reach for it on questions of passive voice, density, repetition, keyphrases, summaries, or dependency arcs.
4 version: 0.2.1
5 ---
1 //! The executed-incantation test for the agent skill.
2 //!
3 //! A skill whose commands do not run is a defect, not a documentation nit
4 //! (RFC-0012). Every fenced `console` or `bash` block in
5 //! `skills/matra/SKILL.md` and its references whose first line is a
6 //! `matra ...` command is extracted here and driven through
7 //! [`matra::cli::run`] against the fixtures in `tests/fixtures/skill/`.
8 //! Drift between the skill text and the command line fails CI the way a
9 //! stale type name fails the docsite.
10 //!
11 //! Two annotations may sit directly above a block:
12 //!
13 //! ```text
14 //! <!-- expect: exit 2 --> the exit code the block should produce (default 0)
15 //! <!-- needs: model --> run only in the model-gated lane
16 //! ```
17 //!
18 //! The model-gated blocks run under the existing convention:
19 //!
20 //! cargo test --features cli --test skill -- --ignored
21 //!
22 //! A block takes one of two routes. Any block whose first argument is
23 //! `config` is run as a subprocess with `MATRA_CONFIG_FILE`,
24 //! `MATRA_DATA_DIR`, `MATRA_MODEL_DIR`, `XDG_CONFIG_HOME` and
25 //! `XDG_DATA_HOME` removed and `HOME` pointed at an empty temporary
26 //! directory, because `config show` resolves its answer out of the
27 //! process environment and would otherwise report the contributor's own
28 //! config file. Every other block runs in process through
29 //! [`matra::cli::run`]. Both routes are held to the same exit code and
30 //! the same `format_version` rule.
31 //!
32 //! The block count is asserted against a fence-aware scan of the same
33 //! files, so an incantation written outside a block the runner reads
34 //! cannot hide from it. The scan trims leading whitespace, so an
35 //! indented `matra ...` line counts, and a command-shaped line that no
36 //! fence encloses fails the law by name rather than by an off-by-one in
37 //! the totals.
semantic.threshold and models.udpipe as settings.RFC-0011 and
EP-0010 list both among the defaults
Config carries; RFC-0020
deprecated them (above).
book/src/llms.txt.RFC-0012
and EP-0011 place it under the
mdBook source; the docsite moved, and the file is
site/content/llms.txt, generated by scripts/gen-llms-txt.sh.
CITATION.cff as blocked. EP-0011 records it as waiting on the
attribution decision; RFC-0013
settled it and the file exists (EPR-0003).
The config schema is public surface, versioned with the crate, and
deny_unknown_fields means a key can only leave by deprecation.
The python feature compiles clap, and the wheel carries the whole
command line.
The skill is public surface. A wording change that alters an
incantation is breaking for agents and goes through the CHANGELOG like an
API change.
A deprecated key is accepted and ignored outside config show, which
is the silence deny_unknown_fields exists to prevent, narrowed rather
than closed (RFC-0020).
The legacy ~/.matra/models fallback keeps capturing downloads for a
user who has one, until they create the new location or set
MATRA_MODEL_DIR.
Configuration in the application only: every library caller keeps
writing the path, and "works out of the box" is true only of the binary.
Rejected in RFC-0011 (option A).
A configuration schema that drives the pipeline: puts policy in a file
the library parses and couples the library to a presentation vocabulary.
Rejected in RFC-0011 (option C).
Two command lines with a parity test: catches drift after it happens,
for a second implementation a launcher replaces. Rejected in RFC-0011
(option D).
Docs and llms.txt only, or a skill file only, or an MCP server: the
first two drift from the installed binary and nothing runs their
commands; an MCP server is a second protocol surface beside a CLI and JSON
that already are the tool interface. Rejected in
RFC-0012.
matra skill get <name> as a subcommand: rejected for a flag, because
the hand-off to an agent is uvx matra --skill and a flag reads as a
property of the program (RFC-0012).
Delete the unread keys, accept them silently, or make them act: the
first breaks every 0.2.x file, the second leaves users editing keys that
do nothing, and the third would load an unpinned model or let
configuration decide a computation. Rejected in
RFC-0020.
uv documents that it follows the XDG conventions on Linux and macOS; gh
resolves $XDG_CONFIG_HOME/gh before ~/.config/gh. UV_CONFIG_FILE,
UV_CACHE_DIR and OLLAMA_MODELS name the thing they override, as the
MATRA_* variables do.
ruff and uv ship their Rust command lines to uvx; maturin recommends a
Python entry point into the extension for a crate that is both library
and tool.
cargo metadata --format-version is the precedent for a versioned
integer on a JSON output rather than a published schema; cargo config get --show-origin for printing where each value came from; Cargo's "unused
manifest key" warning for a deprecated key that still loads.
ripgrep's exit codes (0 found, 1 nothing found, 2 error), and
no-color.org for NO_COLOR.
Vercel Labs' agent-browser prints its own agent instructions with a
second tier of detail, for the same reason: they cannot drift from the
installed binary (RFC-0012's survey).
For the owner to settle in this proposal's review. Each is a decision of its
own.
The exit code type.cli::run returns u8● observedcli/mod.rs:50-106grounds for decision 1;
whether that is the permanent shape was left open by RFC-0011 and is still
open. Changing it is a breaking change.
src/cli/mod.rs lines 50 to 106, at 4fcfb4a
50 /// Run the command line.
51 ///
52 /// `args` is the full argument vector including the program name, the
53 /// way `std::env::args_os()` yields it. `out` receives everything a
54 /// reader is meant to consume (the rendered tables, the JSON, the
55 /// completion script, the help and version text); `err` receives
56 /// diagnostics.
57 ///
58 /// Returns the process exit code. It is a `u8` rather than a
59 /// [`std::process::ExitCode`] because `ExitCode` is opaque: there is no
60 /// public way to read the number back out of one, so the Python launcher
61 /// could not turn it into an `int`. `src/bin/matra.rs` converts with
62 /// `ExitCode::from`.
63 ///
64 /// Never panics on a caller's behalf and never exits the process. A
65 /// write failure on `out` is reported through the return code, not by
66 /// unwinding.
67 ///
68 /// ```no_run
69 /// let mut out = Vec::new();
70 /// let mut err = Vec::new();
71 /// let code = matra::cli::run(
72 /// ["matra", "--version"].into_iter().map(Into::into),
73 /// &mut out,
74 /// &mut err,
75 /// );
76 /// assert_eq!(code, 0);
77 /// ```
78 pub fn run(
79 args: impl IntoIterator<Item = OsString>,
80 out: &mut dyn Write,
81 err: &mut dyn Write,
82 ) -> u8 {
83 let cli = match parse(args) {
84 Ok(cli) => cli,
85 Err(early) => {
86 // clap renders `--help` and `--version` as an "error" that is
87 // not one. `use_stderr` is what separates them from a genuine
88 // usage failure, and it decides both the stream and the code.
89 let sink: &mut dyn Write = if early.to_stderr { err } else { out };
90 let _ = write!(sink, "{}", early.text);
91 return early.code;
92 }
93 };
94 95 match execute(&cli, out, err) {
96 Ok(Outcome::Found) => EXIT_FOUND,
97 Ok(Outcome::Empty) => EXIT_EMPTY,
98 Err(e) => {
99 if is_broken_pipe(e.as_ref()) {
100 return EXIT_FOUND;
101 }
102 let _ = writeln!(err, "matra: {e}");
103 EXIT_ERROR
104 }
105 }
106 }
run keeps returning u8, and its documentation says the shape is permanent and names the three codes.
B No; a named exit status
run returns a type that names its three codes and converts to both u8 and ExitCode.
Claude recommends A, Yes; keep u8. ◐ inferred, a judgment
The reason it is a u8 still holds: ExitCode cannot be read back, and the Python launcher needs the number. The three codes are documented beside run already, and a second type would wrap one integer to name three values.
The strongest case against it
A bare u8 admits codes the command line never returns, and only review keeps a new return path to 0, 1 or 2; a type would hold it. The change is breaking whenever it lands, so it costs less before more callers depend on the integer.
The owner's decision: open. Answer with accept, accept with a reservation, object or redirect, in a comment on this block or on the pull request; Claude then records your ruling here, as a named step in a pull request. A comment is never read as a ruling. Silence is not assent.
No error envelope under --json.A failure writes text to stderr and nothing to stdout, so a JSON consumer reads text for every failure ● observedcli/mod.rs:50-106grounds for decision 2.
The command line's own refusals are untyped strings, so an error envelope
needs a kind vocabulary for the application tier or a move of src/cli/
onto domain::Error.
RFC-0015 deferred it as
worth doing on its own.
src/cli/mod.rs lines 50 to 106, at 4fcfb4a
50 /// Run the command line.
51 ///
52 /// `args` is the full argument vector including the program name, the
53 /// way `std::env::args_os()` yields it. `out` receives everything a
54 /// reader is meant to consume (the rendered tables, the JSON, the
55 /// completion script, the help and version text); `err` receives
56 /// diagnostics.
57 ///
58 /// Returns the process exit code. It is a `u8` rather than a
59 /// [`std::process::ExitCode`] because `ExitCode` is opaque: there is no
60 /// public way to read the number back out of one, so the Python launcher
61 /// could not turn it into an `int`. `src/bin/matra.rs` converts with
62 /// `ExitCode::from`.
63 ///
64 /// Never panics on a caller's behalf and never exits the process. A
65 /// write failure on `out` is reported through the return code, not by
66 /// unwinding.
67 ///
68 /// ```no_run
69 /// let mut out = Vec::new();
70 /// let mut err = Vec::new();
71 /// let code = matra::cli::run(
72 /// ["matra", "--version"].into_iter().map(Into::into),
73 /// &mut out,
74 /// &mut err,
75 /// );
76 /// assert_eq!(code, 0);
77 /// ```
78 pub fn run(
79 args: impl IntoIterator<Item = OsString>,
80 out: &mut dyn Write,
81 err: &mut dyn Write,
82 ) -> u8 {
83 let cli = match parse(args) {
84 Ok(cli) => cli,
85 Err(early) => {
86 // clap renders `--help` and `--version` as an "error" that is
87 // not one. `use_stderr` is what separates them from a genuine
88 // usage failure, and it decides both the stream and the code.
89 let sink: &mut dyn Write = if early.to_stderr { err } else { out };
90 let _ = write!(sink, "{}", early.text);
91 return early.code;
92 }
93 };
94 95 match execute(&cli, out, err) {
96 Ok(Outcome::Found) => EXIT_FOUND,
97 Ok(Outcome::Empty) => EXIT_EMPTY,
98 Err(e) => {
99 if is_broken_pipe(e.as_ref()) {
100 return EXIT_FOUND;
101 }
102 let _ = writeln!(err, "matra: {e}");
103 EXIT_ERROR
104 }
105 }
106 }
A An envelope, with kinds of the command line's own recommended
A failure under --json writes the envelope with an error in place of result. Its kind is Error::kind for a failure from the library, and a word from a small vocabulary of the command line's own for its refusals.
B An envelope, on domain::Error
src/cli/ reports its refusals as domain::Error variants, so every failure carries a library kind.
C No envelope
Failures stay text on stderr, as now.
Claude recommends A, An envelope, with kinds of the command line's own. ◐ inferred, a judgment
Failures from the library already have kinds, pinned for every binding, so only the command line's own refusals need new words. Putting those words in domain::Error would grow the library's vocabulary with application-tier failures the library never raises. Once a consumer branches on the envelope's kinds, removing or renaming one breaks it, so this is costly to reverse.○ assumedgrounds for decision 2
The strongest case against it
Two vocabularies behind one envelope means a consumer reads two lists, and the library's is the one a conformance fixture already pins. Option B keeps a single list.
The owner's decision: open. Answer with accept, accept with a reservation, object or redirect, in a comment on this block or on the pull request; Claude then records your ruling here, as a named step in a pull request. A comment is never read as a ruling. Silence is not assent.
○ 1 claim stands on no grounds yet. Confirm or strike each with a comment on it.
Once a consumer branches on the envelope's kinds, removing or renaming one breaks it, so this is costly to reverse.where: Unresolved questionsbears on decision 2