Skip to content

armgit / xerj

Public Imported from GitHub
0

AI search engine and MCP server for bots and agents. One Rust binary indexes code, docs, logs, JSONL/CSV and PDFs for BM25 full-text, vector and hybrid search, code search without grep, agent memory and RAG. Elasticsearch-compatible API; Corpus Hub serves hundreds of reference memory corpora.

feat(help): ask for bug reports and UX feedback, on by default

bugerd61e0b31dc0c
diff --git a/engine/crates/xerj-autoindex/src/cli.rs b/engine/crates/xerj-autoindex/src/cli.rs
index 70ad07712..290c4d811 100644
--- a/engine/crates/xerj-autoindex/src/cli.rs
+++ b/engine/crates/xerj-autoindex/src/cli.rs
@@ -109,9 +109,16 @@ pub fn print_help() {
/// The help text as a value, so tests can assert that a documented flag is
/// still documented instead of trusting a `println!`.
pub fn help_text() -> String {
+ help_text_with(xerj_common::feedback::enabled())
+}
+
+/// [`help_text`] with the feedback invitation forced on or off, so a test does
+/// not have to mutate the process environment to see both shapes.
+pub fn help_text_with(feedback: bool) -> String {
format!(
"xerj autoindex — point it at any folder and make the contents AI-searchable, zero config\n\
\n\
+ {feedback_block}\
USAGE:\n\
xerj autoindex <folder> [OPTIONS] discover + index a folder\n\
xerj autoindex map [OPTIONS] print the discovered data map\n\
@@ -178,6 +185,9 @@ pub fn help_text() -> String {
exactly like an agent-driven run. See ESTIMATE + DECISION\n\
GATE.\n\
--dataset <SLUG> (map) show a single dataset\n\
+ --disable-feedback do not print the feedback invitation above; honoured in\n\
+ any position, including after --help (env\n\
+ XERJ_DISABLE_FEEDBACK=true)\n\
--help, -h this help\n\
\n\
IGNORE RULES:\n\
@@ -334,6 +344,7 @@ pub fn help_text() -> String {
nothing was indexed; a JSON decision request is on stdout;\n\
2 usage; 1 endpoint/journal failure, a refused corpus removal, or a\n\
refused unsafe state transition\n",
+ feedback_block = xerj_common::feedback::block(feedback),
fresh_help = FRESH_HELP,
resume_policy_help = RESUME_POLICY_HELP,
defaults = crate::ignore_rules::DEFAULT_IGNORE_PATTERNS.join(" ")
@@ -552,6 +563,9 @@ pub fn parse(args: Vec<String>) -> Result<Cmd, String> {
}
"--quiet" => quiet = true,
"--dataset" => dataset = it.next(),
+ // Read out of band by `xerj_common::feedback`, which scans the
+ // whole argument list; accepted here so it is not "unknown".
+ xerj_common::feedback::DISABLE_FLAG => {}
"--help" | "-h" => return Ok(Cmd::Help),
"map" if sub.is_none() && folder.is_none() => sub = Some("map".into()),
"status" if sub.is_none() && folder.is_none() => sub = Some("status".into()),
@@ -1155,6 +1169,60 @@ mod tests {
}
}
+ /// The invitation is on by default and near the top — at the bottom of a
+ /// 200-line help body it would never be read. Position is the requirement,
+ /// so position is what is asserted.
+ #[test]
+ fn the_help_invites_a_bug_report_near_the_top_by_default() {
+ let help = super::help_text_with(true);
+ let line = help
+ .lines()
+ .position(|l| l.contains("Hit a bug, or a flow that confused you?"))
+ .expect("no invitation in the help");
+ assert!(line < 10, "invitation sits on line {}", line + 1);
+ for expected in [
+ "https://github.com/xerj-org/xerj/issues",
+ "GitHub tool",
+ "Discussion",
+ "secrets, API keys and private data",
+ // The off-switch belongs on the same screen as the thing it turns
+ // off.
+ "--disable-feedback",
+ ] {
+ assert!(help.contains(expected), "help is missing {expected:?}");
+ }
+ }
+
+ #[test]
+ fn the_invitation_is_gone_when_it_is_turned_off() {
+ let help = super::help_text_with(false);
+ assert!(!help.contains("Hit a bug"), "invitation was not silenced");
+ assert!(
+ !help.contains("\n\n\n"),
+ "silencing it left a blank gap:\n{help}"
+ );
+ // Silencing the invitation must not silence the rest of the help.
+ assert!(help.contains("USAGE:") && help.contains("--disable-feedback"));
+ }
+
+ /// `--disable-feedback` is consumed wherever it appears, on every
+ /// subcommand — it must never be an "unknown argument".
+ #[test]
+ fn disable_feedback_is_accepted_in_any_position() {
+ for args in [
+ vec!["data", "--disable-feedback"],
+ vec!["--disable-feedback", "data"],
+ vec!["map", "--disable-feedback"],
+ vec!["--disable-feedback", "map"],
+ vec!["status", "--disable-feedback"],
+ vec!["--disable-feedback", "--help"],
+ vec!["--help", "--disable-feedback"],
+ ] {
+ parse(args.iter().map(|s| s.to_string()).collect())
+ .unwrap_or_else(|e| panic!("{args:?} was rejected: {e}"));
+ }
+ }
+
#[test]
fn bulk_timeout_is_rejected_for_non_index_subcommands_in_any_position() {
for args in [
diff --git a/engine/crates/xerj-common/src/feedback.rs b/engine/crates/xerj-common/src/feedback.rs
new file mode 100644
index 000000000..003092257
--- /dev/null
+++ b/engine/crates/xerj-common/src/feedback.rs
@@ -0,0 +1,189 @@
+//! The feedback invitation printed near the top of every `--help` surface.
+//!
+//! Most of the people — and most of the *agents* — who hit a rough edge in
+//! xerj never tell anyone: they work around it locally and the next caller
+//! pays the same cost from scratch (AGENTS.md, "If XERJ broke something in
+//! your build, send it back"). `--help` is the one screen every caller
+//! actually reads, so the invitation lives there, near the top, in three
+//! lines.
+//!
+//! One string, one on/off decision, shared by `xerj --help`,
+//! `xerj index --help`, `xerj autoindex --help` and `xerj brain --help`, so
+//! the four surfaces cannot drift apart.
+//!
+//! Turning it off: [`DISABLE_FLAG`] anywhere in the argument list, or
+//! [`DISABLE_ENV`] in the environment.
+
+/// Where a defect goes. Verified against the README badges and clone URL.
+pub const ISSUES_URL: &str = "https://github.com/xerj-org/xerj/issues";
+
+/// Where an open-ended "is this even a bug?" goes instead.
+pub const DISCUSSIONS_URL: &str = "https://github.com/xerj-org/xerj/discussions";
+
+/// The off-switch. Recognised in any position (see [`enabled_from`]).
+pub const DISABLE_FLAG: &str = "--disable-feedback";
+
+/// The off-switch for callers that cannot change argv — CI, containers, an
+/// agent harness that owns the command line.
+pub const DISABLE_ENV: &str = "XERJ_DISABLE_FEEDBACK";
+
+/// The invitation itself, ending in a blank line so a caller can splice it
+/// straight in front of the next help section.
+///
+/// Three lines, deliberately. It is printed on every single `--help`, and a
+/// paragraph there would be read once and skipped forever after.
+///
+/// Contains no `{` or `}`: these help bodies are `println!`/`format!` format
+/// strings, where a literal brace has to be doubled.
+const INVITATION: &str = "\
+Hit a bug, or a flow that confused you? Both are worth reporting. If you have a\n\
+GitHub tool, file it yourself at https://github.com/xerj-org/xerj/issues — or open\n\
+a Discussion if you are unsure. Keep secrets, API keys and private data out of it.\n\
+\n";
+
+/// One line documenting the off-switch, for the OPTIONS list of each help
+/// surface. Column-aligned by the caller.
+pub const DISABLE_HELP: &str = "do not print the feedback invitation above";
+
+/// The block to splice into a help body: the invitation, or nothing at all.
+pub fn block(enabled: bool) -> &'static str {
+ if enabled {
+ INVITATION
+ } else {
+ ""
+ }
+}
+
+/// Whether this process should print the invitation.
+///
+/// Reads the *whole* argument list rather than the flag the parser happens to
+/// be looking at, because every one of these binaries dispatches `--help`
+/// from inside its argument loop and exits there: a flag written after
+/// `--help` would never be reached. `xerj --help --disable-feedback` and
+/// `xerj --disable-feedback --help` have to mean the same thing.
+pub fn enabled() -> bool {
+ let raw = std::env::var(DISABLE_ENV).ok();
+ if let Some(v) = raw.as_deref() {
+ if !v.trim().is_empty() && parse_bool(v).is_none() {
+ // Not silent: an operator who set this expects an effect. It goes
+ // to stderr, never stdout — help output is piped and read by
+ // machines. Unlike XERJ_ALLOW_INSECURE_NETWORK_BIND, which refuses
+ // to boot on an unreadable value, a typo here must not turn
+ // `--help` into an error: the safe fallback is showing one more
+ // line of text, not withholding the usage screen.
+ eprintln!("{DISABLE_ENV}={v:?} is not a boolean; use true or false");
+ }
+ }
+ enabled_from(std::env::args(), raw)
+}
+
+/// The decision as a pure function, so it can be tested without a process.
+///
+/// The flag wins over the environment (an explicit argument beats ambient
+/// configuration, as `--bind` does over `XERJ_BIND_ADDRESS`). Anything the
+/// environment variable cannot be read as a boolean leaves the invitation on.
+pub fn enabled_from<I>(args: I, env: Option<String>) -> bool
+where
+ I: IntoIterator,
+ I::Item: AsRef<str>,
+{
+ if args.into_iter().any(|a| a.as_ref() == DISABLE_FLAG) {
+ return false;
+ }
+ match env.as_deref().and_then(parse_bool) {
+ Some(disable) => !disable,
+ None => true,
+ }
+}
+
+/// The repo's boolean-environment convention, as used by
+/// `XERJ_ALLOW_INSECURE_NETWORK_BIND` in `xerj-server`.
+fn parse_bool(raw: &str) -> Option<bool> {
+ match raw.trim().to_ascii_lowercase().as_str() {
+ "1" | "true" | "yes" | "on" => Some(true),
+ "0" | "false" | "no" | "off" => Some(false),
+ _ => None,
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn on_by_default() {
+ assert!(enabled_from(["xerj", "--help"], None));
+ assert!(block(true).contains(ISSUES_URL));
+ }
+
+ /// The flag is dispatched from inside each binary's argument loop, so
+ /// position must not matter — before or after `--help`.
+ #[test]
+ fn the_flag_is_position_independent() {
+ assert!(!enabled_from(["xerj", "--help", DISABLE_FLAG], None));
+ assert!(!enabled_from(["xerj", DISABLE_FLAG, "--help"], None));
+ assert!(!enabled_from(
+ ["xerj", "autoindex", "map", DISABLE_FLAG, "--json"],
+ None
+ ));
+ }
+
+ #[test]
+ fn the_env_var_follows_the_repo_boolean_convention() {
+ for on in ["1", "true", "TRUE", "yes", "on", " true "] {
+ assert!(
+ !enabled_from(["xerj"], Some(on.into())),
+ "{on:?} should disable"
+ );
+ }
+ for off in ["0", "false", "no", "off"] {
+ assert!(
+ enabled_from(["xerj"], Some(off.into())),
+ "{off:?} should leave it on"
+ );
+ }
+ }
+
+ /// A value nobody can read is not a licence to hide the invitation — and
+ /// it must not swallow the help screen either. It stays on; `enabled()`
+ /// says so on stderr.
+ #[test]
+ fn an_unreadable_env_value_keeps_the_invitation() {
+ assert!(enabled_from(["xerj"], Some("maybe".into())));
+ assert!(enabled_from(["xerj"], Some(String::new())));
+ }
+
+ #[test]
+ fn disabled_is_empty_not_blank_lines() {
+ assert_eq!(block(false), "");
+ }
+
+ /// These strings are spliced into `format!`/`println!` bodies, where a
+ /// literal brace must be doubled. Keeping the invitation brace-free means
+ /// no caller can get that wrong.
+ #[test]
+ fn the_invitation_carries_no_braces() {
+ assert!(!INVITATION.contains('{') && !INVITATION.contains('}'));
+ }
+
+ /// The three things the invitation exists to say.
+ #[test]
+ fn the_invitation_says_what_it_must() {
+ let text = block(true);
+ assert!(
+ text.contains("confused"),
+ "unclear UX counts, not just bugs"
+ );
+ assert!(
+ text.contains("GitHub tool"),
+ "agents can file it themselves"
+ );
+ assert!(text.contains("Discussion"), "the unsure path");
+ assert!(text.contains("secrets, API keys and private data"));
+ assert_eq!(
+ text.lines().filter(|l| !l.trim().is_empty()).count(),
+ 3,
+ "it prints on every --help; three lines is the budget"
+ );
+ }
+}
diff --git a/engine/crates/xerj-common/src/lib.rs b/engine/crates/xerj-common/src/lib.rs
index c21b38555..0e2a5d523 100644
--- a/engine/crates/xerj-common/src/lib.rs
+++ b/engine/crates/xerj-common/src/lib.rs
@@ -14,6 +14,7 @@
//! ## Modules
//!
//! - [`config`] — TOML-based configuration (105 settings)
+//! - [`feedback`] — the bug/UX-report invitation shared by every `--help`
//! - [`error`] — Unified error type ([`XerjError`])
//! - [`types`] — Core domain types (documents, fields, IDs)
//! - [`schema`] — Index schema management and mapping evolution
@@ -23,6 +24,7 @@
pub mod config;
pub mod error;
+pub mod feedback;
pub mod fsio;
pub mod metrics;
pub mod net;
diff --git a/engine/crates/xerj-server/src/brain.rs b/engine/crates/xerj-server/src/brain.rs
index 501bc9620..34e5d70fa 100644
--- a/engine/crates/xerj-server/src/brain.rs
+++ b/engine/crates/xerj-server/src/brain.rs
@@ -59,7 +59,13 @@ pub fn run_cli() -> i32 {
}
pub fn print_help() {
- println!(
+ println!("{}", help_text(xerj_common::feedback::enabled()));
+}
+
+/// The help text as a value, so tests can assert on it — presence *and*
+/// position of the feedback invitation — instead of trusting a `println!`.
+pub fn help_text(feedback: bool) -> String {
+ format!(
"xerj brain — turn a folder into a running, browsable second brain, in one command\n\
\n\
Point it at a folder. xerj starts its local server (or attaches to a running\n\
@@ -67,6 +73,7 @@ pub fn print_help() {
relative links, section order, shared folders), and opens your knowledge in\n\
the browser. Safe to re-run any time — re-runs converge, nothing duplicates.\n\
\n\
+ {}\
USAGE:\n\
xerj brain <folder> [OPTIONS]\n\
\n\
@@ -83,11 +90,15 @@ pub fn print_help() {
re-walking everything (ids stay idempotent). It never\n\
deletes documents for notes you removed\n\
--no-open print the links but do not open a browser\n\
+ --disable-feedback do not print the feedback invitation above; honoured in\n\
+ any position, including after --help (env\n\
+ XERJ_DISABLE_FEEDBACK=true)\n\
--help, -h this help\n\
\n\
EXIT CODES: 0 ready; 3 ready-with-junk (unreadable files recorded, never\n\
- fatal); 1 nothing indexable / server failure; 2 usage\n"
- );
+ fatal); 1 nothing indexable / server failure; 2 usage\n",
+ xerj_common::feedback::block(feedback),
+ )
}
pub struct BrainCfg {
@@ -125,6 +136,9 @@ fn parse(args: Vec<String>) -> Result<Option<BrainCfg>, String> {
"--api-key" => api_key = Some(it.next().ok_or("--api-key needs a value")?),
"--fresh" => fresh = true,
"--no-open" => no_open = true,
+ // Read out of band by `xerj_common::feedback`, which scans the
+ // whole argument list; accepted here so it is not "unknown".
+ xerj_common::feedback::DISABLE_FLAG => {}
"--help" | "-h" => return Ok(None),
other if !other.starts_with('-') && root.is_none() => root = Some(PathBuf::from(other)),
other => return Err(format!("unknown argument: {other}")),
diff --git a/engine/crates/xerj-server/src/main.rs b/engine/crates/xerj-server/src/main.rs
index 12ac6c373..ccb62d3f9 100644
--- a/engine/crates/xerj-server/src/main.rs
+++ b/engine/crates/xerj-server/src/main.rs
@@ -153,6 +153,10 @@ fn parse_args() -> CliArgs {
"--onnx-tokenizer" => onnx_tokenizer = args.next(),
"--compat-distribution" => compat_distribution = args.next(),
"--compat-version" => compat_version = args.next(),
+ // Read out of band by `xerj_common::feedback` (which scans the
+ // whole argument list, so its position never matters); accepted
+ // here only so it is not an "unknown argument".
+ xerj_common::feedback::DISABLE_FLAG => {}
"--help" | "-h" => {
print_help();
std::process::exit(0);
@@ -183,16 +187,17 @@ fn parse_args() -> CliArgs {
}
fn print_help() {
- println!("{}", help_text());
+ println!("{}", help_text(xerj_common::feedback::enabled()));
}
/// The help text as a value, so tests can assert that a documented behaviour is
-/// still documented instead of trusting a `println!`. Same house style as
-/// `xerj_autoindex::cli::help_text`.
-fn help_text() -> String {
+/// still documented — including *where* the feedback invitation lands — instead
+/// of trusting a `println!`. Same house style as `xerj_autoindex::cli::help_text`.
+fn help_text(feedback: bool) -> String {
format!(
"xerj v{} — the unified search engine for AI (Elasticsearch wire-compatible)\n\
\n\
+ {}\
USAGE:\n\
xerj [OPTIONS] start the server (options below)\n\
xerj autoindex <folder> [OPTIONS] zero-config discovery + indexing — the\n\
@@ -256,6 +261,9 @@ fn help_text() -> String {
Also claims PORT+1 for the native REST API and PORT+2\n\
for gRPC, so a second instance needs only this one flag:\n\
xerj --insecure --port 9300 -d ./other-data\n\
+ --disable-feedback Do not print the feedback invitation above. Honoured in any\n\
+ position, including after --help. Env:\n\
+ XERJ_DISABLE_FEEDBACK=true\n\
--help, -h Show this help\n\
--version, -V Print version and exit\n\
\n\
@@ -284,6 +292,8 @@ fn help_text() -> String {
\n\
ENVIRONMENT:\n\
XERJ_LOG Log level filter (default: info)\n\
+ XERJ_DISABLE_FEEDBACK true/false — same as --disable-feedback, for callers that\n\
+ cannot change the command line (CI, containers, agents)\n\
XERJ_CONFIG Config file path\n\
XERJ_EMBED_MODE Embedding backend (lexical|neural|proxy|auto|onnx-experimental)\n\
XERJ_ONNX_MODEL FP32 ONNX model path\n\
@@ -316,7 +326,8 @@ fn help_text() -> String {
xerj -d ./data --compat-distribution opensearch\n\
(or set only XERJ_COMPAT_VERSION and leave distribution to auto-detect — the two\n\
settings are resolved independently, mix and match as needed.)\n",
- env!("CARGO_PKG_VERSION")
+ env!("CARGO_PKG_VERSION"),
+ xerj_common::feedback::block(feedback),
)
}
@@ -1101,6 +1112,7 @@ fn parse_index_args() -> IndexCmdArgs {
}
"--config" | "-c" => config = args.next().map(PathBuf::from),
"--data-dir" | "-d" => data_dir = args.next(),
+ xerj_common::feedback::DISABLE_FLAG => {}
"--help" | "-h" => {
print_index_help();
std::process::exit(0);
@@ -1133,9 +1145,14 @@ fn parse_index_args() -> IndexCmdArgs {
}
fn print_index_help() {
- println!(
+ println!("{}", index_help_text(xerj_common::feedback::enabled()));
+}
+
+fn index_help_text(feedback: bool) -> String {
+ format!(
"xerj index — ingest an NDJSON file directly into the engine\n\
\n\
+ {}\
USAGE:\n\
xerj index --index <name> --file <ndjson> [OPTIONS]\n\
\n\
@@ -1147,13 +1164,16 @@ fn print_index_help() {
--limit, -l <N> Ingest only the first N lines (default: all)\n\
--config, -c <PATH> Path to TOML config file\n\
--data-dir, -d <PATH> Override data directory\n\
+ --disable-feedback Do not print the feedback invitation above\n\
+ (env XERJ_DISABLE_FEEDBACK=true)\n\
--help, -h Show this help\n\
\n\
Bypasses HTTP/axum entirely. Bytes are pushed straight into\n\
index_batch_turbo_raw via rayon workers. Use this for maximum\n\
single-node ingest throughput — it's the xerj equivalent of\n\
- Lucene's IndexWriter fed from a file."
- );
+ Lucene's IndexWriter fed from a file.",
+ xerj_common::feedback::block(feedback),
+ )
}
/// Run the `xerj index` subcommand — direct NDJSON → engine ingest.
diff --git a/engine/crates/xerj-server/tests/feedback_invite.rs b/engine/crates/xerj-server/tests/feedback_invite.rs
new file mode 100644
index 000000000..55069c365
--- /dev/null
+++ b/engine/crates/xerj-server/tests/feedback_invite.rs
@@ -0,0 +1,211 @@
+//! The feedback invitation, checked on the real binary.
+//!
+//! Every help surface a caller actually meets — `xerj --help`,
+//! `xerj index --help`, `xerj autoindex --help`, `xerj brain --help` — must
+//! carry the bug/confusing-UX invitation by default, near the top, and must
+//! drop it when `--disable-feedback` is given in *either* position or when
+//! `XERJ_DISABLE_FEEDBACK` is set.
+//!
+//! These drive the built binary rather than the library functions on purpose:
+//! `--help` is dispatched from inside each argument loop and exits there, so
+//! only a real process proves that a flag written *after* `--help` still
+//! counts.
+
+use std::process::Command;
+
+/// The first words of the invitation. One needle, so a reworded second or
+/// third line does not fail the position check.
+const NEEDLE: &str = "Hit a bug, or a flow that confused you?";
+
+/// The issues URL is the load-bearing part: an invitation without a
+/// destination is decoration.
+const ISSUES_URL: &str = "https://github.com/xerj-org/xerj/issues";
+
+/// "Near the top" is the requirement, not "somewhere in the file" — at the
+/// bottom of a 200-line help body nothing would ever read it.
+const MAX_LINE: usize = 10;
+
+/// Every surface, as the argv a caller would type.
+const SURFACES: [&[&str]; 4] = [
+ &["--help"],
+ &["index", "--help"],
+ &["autoindex", "--help"],
+ &["brain", "--help"],
+];
+
+fn help(args: &[&str], env: Option<&str>) -> String {
+ let mut cmd = Command::new(env!("CARGO_BIN_EXE_xerj"));
+ cmd.args(args);
+ match env {
+ Some(v) => cmd.env("XERJ_DISABLE_FEEDBACK", v),
+ // The developer's own shell must not decide the default case.
+ None => cmd.env_remove("XERJ_DISABLE_FEEDBACK"),
+ };
+ let out = cmd.output().expect("run xerj");
+ assert!(
+ out.status.success(),
+ "xerj {args:?} exited {:?}: {}",
+ out.status.code(),
+ String::from_utf8_lossy(&out.stderr)
+ );
+ String::from_utf8(out.stdout).expect("help is utf-8")
+}
+
+/// 1-based line number of the invitation, or `None` if it is not there.
+fn invite_line(help: &str) -> Option<usize> {
+ help.lines().position(|l| l.contains(NEEDLE)).map(|i| i + 1)
+}
+
+#[test]
+fn every_help_surface_invites_a_report_by_default() {
+ for args in SURFACES {
+ let text = help(args, None);
+ let line = invite_line(&text)
+ .unwrap_or_else(|| panic!("xerj {args:?} printed no invitation:\n{text}"));
+ assert!(
+ line <= MAX_LINE,
+ "xerj {args:?} put the invitation on line {line}; it has to be within the \
+ first {MAX_LINE} lines or nobody reads it:\n{text}"
+ );
+ assert!(
+ text.contains(ISSUES_URL),
+ "xerj {args:?} invites a report without saying where:\n{text}"
+ );
+ // Bugs AND confusing flows; file it yourself if you can; a Discussion
+ // when unsure; and never paste secrets into either.
+ for needle in [
+ "confused you",
+ "GitHub tool",
+ "Discussion",
+ "secrets, API keys and private data",
+ ] {
+ assert!(
+ text.contains(needle),
+ "xerj {args:?} help is missing {needle:?}:\n{text}"
+ );
+ }
+ // The way out has to be discoverable from the same screen.
+ assert!(
+ text.contains("--disable-feedback"),
+ "xerj {args:?} never documents the off-switch:\n{text}"
+ );
+ }
+}
+
+/// `--help` is handled inside the argument loop and exits there, so a naive
+/// implementation would never see a flag typed after it. Both orders, every
+/// surface.
+#[test]
+fn disable_feedback_works_in_either_argument_order() {
+ for args in SURFACES {
+ let mut after: Vec<&str> = args.to_vec();
+ after.push("--disable-feedback");
+
+ // Before `--help`, but after any subcommand — argv[1] is the
+ // subcommand selector for `index`/`autoindex`/`brain`.
+ let mut before: Vec<&str> = args.to_vec();
+ before.insert(before.len() - 1, "--disable-feedback");
+
+ for variant in [after, before] {
+ let text = help(&variant, None);
+ assert_eq!(
+ invite_line(&text),
+ None,
+ "xerj {variant:?} still printed the invitation:\n{text}"
+ );
+ // Silencing it must not leave a hole where it stood.
+ assert!(
+ !text.contains("\n\n\n"),
+ "xerj {variant:?} left a blank gap behind:\n{text}"
+ );
+ }
+ }
+}
+
+/// CI and agent harnesses often cannot change argv, only the environment.
+#[test]
+fn the_env_var_silences_every_surface() {
+ for args in SURFACES {
+ for value in ["1", "true", "yes", "on"] {
+ let text = help(args, Some(value));
+ assert_eq!(
+ invite_line(&text),
+ None,
+ "XERJ_DISABLE_FEEDBACK={value} left the invitation on xerj {args:?}:\n{text}"
+ );
+ }
+ // A false-y value is not an off-switch, and a value nobody can read
+ // must not silently hide it either.
+ for value in ["0", "false", "off", "maybe", ""] {
+ let text = help(args, Some(value));
+ assert!(
+ invite_line(&text).is_some(),
+ "XERJ_DISABLE_FEEDBACK={value:?} hid the invitation on xerj {args:?}:\n{text}"
+ );
+ }
+ }
+}
+
+/// An unreadable value is reported on stderr — never on stdout, which is the
+/// help text itself — and never by refusing to print the help.
+#[test]
+fn an_unreadable_env_value_is_reported_on_stderr_only() {
+ let out = Command::new(env!("CARGO_BIN_EXE_xerj"))
+ .args(["--help"])
+ .env("XERJ_DISABLE_FEEDBACK", "maybe")
+ .output()
+ .expect("run xerj");
+ assert!(out.status.success());
+ let stderr = String::from_utf8_lossy(&out.stderr);
+ assert!(
+ stderr.contains("XERJ_DISABLE_FEEDBACK") && stderr.contains("not a boolean"),
+ "an unreadable value was swallowed; stderr was: {stderr}"
+ );
+ assert!(!String::from_utf8_lossy(&out.stdout).contains("not a boolean"));
+}
+
+/// The help bodies are `println!`/`format!` format strings, so a literal brace
+/// has to be doubled — get that wrong and either the build breaks or the JSON
+/// example in the help stops being JSON. Every balanced brace group in every
+/// help surface must still parse.
+#[test]
+fn json_examples_in_help_still_parse() {
+ for args in SURFACES {
+ for text in [help(args, None), help(args, Some("true"))] {
+ for candidate in brace_groups(&text) {
+ serde_json::from_str::<serde_json::Value>(&candidate).unwrap_or_else(|e| {
+ panic!("xerj {args:?} help contains unparseable JSON {candidate:?}: {e}")
+ });
+ }
+ }
+ }
+}
+
+/// Balanced `{…}` groups, and a hard failure on an unbalanced one — a stray
+/// brace is exactly what a mis-escaped format string leaves behind.
+fn brace_groups(text: &str) -> Vec<String> {
+ let mut groups = Vec::new();
+ let mut depth = 0usize;
+ let mut start = 0usize;
+ for (i, c) in text.char_indices() {
+ match c {
+ '{' => {
+ if depth == 0 {
+ start = i;
+ }
+ depth += 1;
+ }
+ '}' => {
+ depth = depth
+ .checked_sub(1)
+ .unwrap_or_else(|| panic!("unbalanced '}}' in help at byte {i}"));
+ if depth == 0 {
+ groups.push(text[start..=i].to_string());
+ }
+ }
+ _ => {}
+ }
+ }
+ assert_eq!(depth, 0, "unclosed '{{' in help text");
+ groups
+}