#![allow(
clippy::disallowed_methods,
clippy::needless_range_loop,
clippy::format_collect,
clippy::format_push_string,
clippy::manual_assert,
clippy::uninlined_format_args,
clippy::unnecessary_debug_formatting,
clippy::unwrap_or_default,
clippy::expect_fun_call,
clippy::manual_repeat_n,
clippy::unnecessary_map_or
)]
use std::process::Command;
fn registered_commands() -> Vec<&'static str> {
vec![
"run",
"serve",
"chat",
"inspect",
"debug",
"validate",
"validate-manifest",
"lint",
"beat-run",
"manifest",
"explain",
"tensors",
"dataset",
"kernel",
"trace",
"diff",
"hex",
"tree",
"flow",
"export",
"import",
"convert",
"stamp",
"compile",
"merge",
"quantize",
"rosetta",
"pull",
"list",
"rm",
"registry",
"publish",
"finetune",
"prune",
"distill",
"train",
"pretrain",
"tokenize",
"tune",
"bench",
"eval",
"check",
"qa",
"qualify",
"canary",
"compare-hf",
"parity",
"gpu",
"profile",
"ptx",
"ptx-map",
"cbtop",
"data",
"pipeline",
"tui",
"monitor",
"runs",
"experiment",
"showcase",
"test",
"modelfile",
"diagnose",
"ollama-chat-lint",
"ollama-tools-lint",
"dry-sampling-lint",
"awq-lint",
"fp8-lint",
"nf4-lint",
"gptq-lint",
"oom-lint",
"tool-use-lint",
"gbnf-lint",
"typical-p-lint",
"registry-quota-lint",
"imatrix-lint",
"embeddings-lint",
"unified-search-lint",
"rm-gc-lint",
"shared-cache-lint",
"ppl",
"quant-preservation-lint",
"prometheus-lint",
"otlp-lint",
"kv-timeline-lint",
"gpu-memtrace-lint",
"explain-token-lint",
"check-finite-lint",
"attn-viz-lint",
"embed-viz-lint",
"nccl-diag-lint",
"react-trace-lint",
"hang-trace-lint",
"ddp-metrics-lint",
"audio-inspect-lint",
"attn-parity-lint",
"rerank",
"embed",
"shard",
"unshard",
"oracle",
"grad-norm",
"encrypt",
"decrypt",
"mcp",
"code",
"rag",
"zram",
"sim",
"cgp",
"pv",
]
}
fn apr_binary() -> Command {
let mut cmd = Command::new(env!("CARGO_BIN_EXE_apr"));
cmd.env("NO_COLOR", "1");
cmd
}
fn get_help_commands() -> Vec<String> {
let output = apr_binary()
.arg("--help")
.output()
.expect("failed to run apr --help");
let stdout = String::from_utf8_lossy(&output.stdout);
let mut commands = Vec::new();
let mut in_commands = false;
for line in stdout.lines() {
if line.starts_with("Commands:") {
in_commands = true;
continue;
}
if in_commands {
if line.starts_with("Options:") || line.is_empty() && commands.len() > 5 {
break;
}
let leading_spaces = line.chars().take_while(|c| *c == ' ').count();
if leading_spaces != 2 {
continue;
}
let trimmed = line.trim();
if let Some(cmd_name) = trimmed.split_whitespace().next() {
if !cmd_name.is_empty()
&& cmd_name
.chars()
.next()
.map_or(false, |c| c.is_ascii_lowercase())
&& !cmd_name.contains('(')
&& !cmd_name.contains(')')
{
commands.push(cmd_name.to_string());
}
}
}
}
commands
}
#[test]
fn test_all_commands_respond_to_help() {
let mut failures = Vec::new();
for cmd in registered_commands() {
let output = apr_binary()
.args([cmd, "--help"])
.output()
.unwrap_or_else(|e| panic!("failed to run apr {} --help: {}", cmd, e));
if !output.status.success() {
failures.push(format!(
"apr {} --help exited with {:?}",
cmd,
output.status.code()
));
}
}
assert!(
failures.is_empty(),
"FALSIFY-CLI-003: Commands that failed --help:\n{}",
failures.join("\n")
);
}
#[test]
fn test_all_contract_commands_exist() {
let help_commands = get_help_commands();
let mut missing = Vec::new();
for cmd in registered_commands() {
if !help_commands.iter().any(|h| h == cmd) {
missing.push(cmd);
}
}
assert!(
missing.is_empty(),
"FALSIFY-CLI-001: Commands in contract but missing from `apr --help`: {:?}",
missing
);
}
#[test]
fn test_no_unregistered_commands() {
let help_commands = get_help_commands();
let cmds = registered_commands();
let registered: std::collections::HashSet<&str> = cmds.iter().copied().collect();
let mut unregistered = Vec::new();
for cmd in &help_commands {
if !registered.contains(cmd.as_str()) {
if cmd != "help" {
unregistered.push(cmd.clone());
}
}
}
assert!(
unregistered.is_empty(),
"FALSIFY-CLI-002: Commands in `apr --help` but not in contract: {:?}\n\
Add them to contracts/apr-cli-commands-v1.yaml AND this test's registered_commands().",
unregistered
);
}
#[test]
fn test_command_count_matches() {
let help_commands = get_help_commands();
let help_count = help_commands
.iter()
.filter(|c| c.as_str() != "help")
.count();
let contract_count = registered_commands().len();
assert_eq!(
help_count, contract_count,
"FALSIFY-CLI-005: Command count mismatch.\n\
`apr --help` has {} commands, contract has {}.\n\
Help commands: {:?}",
help_count, contract_count, help_commands
);
}
#[test]
fn test_version_flag() {
let output = apr_binary()
.arg("--version")
.output()
.expect("failed to run apr --version");
assert!(output.status.success(), "apr --version should exit 0");
let stdout = String::from_utf8_lossy(&output.stdout);
assert!(
stdout.contains("apr"),
"apr --version should contain 'apr': got {:?}",
stdout
);
}
#[test]
fn test_no_args_exits_usage_error() {
let output = apr_binary()
.output()
.expect("failed to run apr with no args");
let code = output.status.code().unwrap_or(-1);
assert_eq!(
code, 2,
"apr with no args should exit 2 (usage error), got {}",
code
);
}
#[test]
fn pretrain_init_flag_registered() {
let output = apr_binary()
.args(["pretrain", "--help"])
.output()
.expect("failed to run apr pretrain --help");
assert!(
output.status.success(),
"apr pretrain --help should exit 0, got {:?}",
output.status.code()
);
let stdout = String::from_utf8_lossy(&output.stdout);
assert!(
stdout.contains("--init"),
"FALSIFY-APR-PRETRAIN-INIT-007: `--init` flag missing from `apr pretrain --help`.\n\
Either clap definition drifted, or pretrain subcommand wasn't built with the flag.\n\
Full --help output:\n{}",
stdout
);
}
#[test]
fn tokenize_import_hf_subcommand_registered() {
let output = apr_binary()
.args(["tokenize", "import-hf", "--help"])
.output()
.expect("failed to run apr tokenize import-hf --help");
assert!(
output.status.success(),
"FALSIFY-TOK-IMPORT-HF-001: `apr tokenize import-hf --help` should exit 0, got {:?}\nstderr:\n{}",
output.status.code(),
String::from_utf8_lossy(&output.stderr)
);
let stdout = String::from_utf8_lossy(&output.stdout);
for flag in ["--input", "--output", "--include-added-tokens"] {
assert!(
stdout.contains(flag),
"FALSIFY-TOK-IMPORT-HF-001: `{flag}` flag missing from `apr tokenize import-hf --help`.\n\
Either clap definition drifted, dispatch isn't wired, or the binary was built without the subcommand.\n\
Full --help output:\n{stdout}"
);
}
}
#[test]
fn backend_cuda_on_non_cuda_build_refuses_instead_of_falling_back() {
if cfg!(feature = "cuda") {
return;
}
let output = apr_binary()
.args([
"run",
"/nonexistent-model-path-for-backend-guard.gguf",
"--prompt",
"hi",
"--max-tokens",
"1",
"--backend",
"cuda",
])
.output()
.expect("failed to run apr");
let combined = format!(
"{}{}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
);
assert!(
!output.status.success(),
"FALSIFY-BACKEND-CUDA-HONESTY-001: `--backend cuda` exited 0 on a build with no \
CUDA compiled in. It must refuse rather than silently serve wgpu/CPU (~20x slower).\n\
Output:\n{combined}"
);
assert!(
combined.contains("built WITHOUT the `cuda` feature"),
"FALSIFY-BACKEND-CUDA-HONESTY-001: expected an explicit refusal naming the missing \
`cuda` feature, so the user is not left to infer it from a throughput number.\n\
Output:\n{combined}"
);
assert!(
!combined.contains("Backend: wgpu"),
"FALSIFY-BACKEND-CUDA-HONESTY-001: `--backend cuda` fell through to the wgpu \
backend — this is the exact silent-downgrade this gate exists to prevent.\n\
Output:\n{combined}"
);
}
fn report_says_gate_is_ok(stdout: &str, gate: &str) -> bool {
stdout.lines().any(|line| {
let line = line.trim();
match line.split_once(':') {
Some((label, verdict)) => label.trim() == gate && verdict.trim().starts_with("Ok"),
None => false,
}
})
}
#[test]
fn nan_threshold_never_reports_a_failing_lint_gate_as_ok() {
let dir = tempfile::tempdir().expect("tempdir");
let p = |name: &str, body: &str| -> String {
let path = dir.path().join(name);
std::fs::write(&path, body).expect("write fixture");
path.display().to_string()
};
let kv = p(
"kv.json",
r#"{"block_size_tokens":16,"total_blocks":100,"peak_used_pct":0.1,"preemption_count":3,
"timeline":[{"step":0,"t_ms":1.0,"used_blocks":10,"free_blocks":90,
"used_pct":0.10,"active_seqs":1,"preempted_seqs":3}]}"#,
);
let parity = p("parity.json", r#"{"max_abs_diff":999.0,"cosine_sim":-0.5}"#);
let attn = p("attn.json", "[[[[3.0,2.0],[0.5,0.5]]]]");
let explain = p(
"explain.jsonl",
"{\"step\":0,\"sampled_id\":7,\"candidates\":[\
{\"token_id\":7,\"pre_prob\":0.9,\"post_prob\":0.5,\"rank\":0},\
{\"token_id\":3,\"pre_prob\":0.1,\"post_prob\":0.1,\"rank\":1}]}\n",
);
let ddp1 = p("ddp1.json", r#"{"tokens_per_sec":1000.0,"final_loss":2.0}"#);
let ddpn = p(
"ddpn.json",
r#"{"tokens_per_sec":10.0,"final_loss":9.9,
"ddp_metrics":{"allreduce_bandwidth_gbps":[12.5]}}"#,
);
let cases: Vec<(Vec<String>, Vec<String>, &str)> = vec![
(
vec!["kv-timeline-lint".into(), "--timeline-file".into(), kv],
vec!["--preempt-threshold".into(), "nan".into()],
"preemption_trigger",
),
(
vec!["attn-parity-lint".into(), "--parity-file".into(), parity],
vec![
"--tol-abs".into(),
"nan".into(),
"--tol-cos".into(),
"nan".into(),
],
"parity_numerics",
),
(
vec!["attn-viz-lint".into(), "--attn-file".into(), attn],
vec![
"--tolerance".into(),
"nan".into(),
"--epsilon".into(),
"nan".into(),
],
"row_softmax",
),
(
vec!["explain-token-lint".into(), "--jsonl-file".into(), explain],
vec!["--tolerance".into(), "nan".into()],
"probs_normalize",
),
(
vec![
"ddp-metrics-lint".into(),
"--metrics-1gpu-file".into(),
ddp1,
"--metrics-ngpu-file".into(),
ddpn,
"--world-size".into(),
"4".into(),
],
vec![
"--scaling-floor".into(),
"nan".into(),
"--loss-tolerance".into(),
"nan".into(),
],
"scaling_efficiency",
),
];
for (base, disarm, gate) in cases {
let control = apr_binary().args(&base).output().expect("run apr");
assert!(
!control.status.success(),
"FALSIFY-CLI-THRESHOLD-NAN-001 control: `apr {}` must FAIL at the shipped \
defaults, otherwise the disarm case below proves nothing.\nstdout:\n{}",
base.join(" "),
String::from_utf8_lossy(&control.stdout)
);
let mut args = base.clone();
args.extend(disarm.iter().cloned());
let out = apr_binary().args(&args).output().expect("run apr");
let stdout = String::from_utf8_lossy(&out.stdout);
assert!(
!out.status.success(),
"FALSIFY-CLI-THRESHOLD-NAN-001: `apr {}` exited 0 — a NaN threshold disarmed \
the {gate} gate on a body that fails at the defaults.\nstdout:\n{stdout}",
args.join(" ")
);
assert!(
!report_says_gate_is_ok(&stdout, gate),
"FALSIFY-CLI-THRESHOLD-NAN-001: the report asserted `{gate} : Ok` for an \
observation it never actually checked.\nstdout:\n{stdout}"
);
}
}
fn help_subcommands(path: &[&str]) -> Vec<String> {
let mut cmd = apr_binary();
cmd.args(path).arg("--help");
let out = cmd.output().expect("apr --help");
let stdout = String::from_utf8_lossy(&out.stdout);
let mut subs = Vec::new();
let mut in_commands = false;
for line in stdout.lines() {
if line.starts_with("Commands:") {
in_commands = true;
continue;
}
if in_commands {
if line.starts_with("Options:") || line.starts_with("Arguments:") {
break;
}
if let Some(rest) = line.strip_prefix(" ") {
if !rest.starts_with(' ') {
if let Some(name) = rest.split_whitespace().next() {
if name != "help" {
subs.push(name.to_string());
}
}
}
}
}
}
subs
}
fn contract_subcommands() -> Vec<(String, Vec<String>)> {
let path = concat!(
env!("CARGO_MANIFEST_DIR"),
"/../../contracts/apr-cli-commands-v1.yaml"
);
let text = std::fs::read_to_string(path).expect("read the command contract");
let mut out = Vec::new();
let mut current: Option<String> = None;
for line in text.lines() {
if let Some(rest) = line.strip_prefix(" - name: ") {
current = Some(rest.trim().trim_matches('"').to_string());
} else if let Some(rest) = line.strip_prefix(" subcommands: [") {
let kids: Vec<String> = rest
.trim_end_matches(']')
.split(',')
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
.collect();
if let Some(parent) = current.clone() {
out.push((parent, kids));
}
}
}
out
}
#[test]
fn every_declared_subcommand_exists_in_the_binary() {
let declared = contract_subcommands();
assert!(
declared.len() >= 20,
"only {} parents parsed from the contract; the parser is broken, not the tree",
declared.len()
);
let total: usize = declared.iter().map(|(_, k)| k.len()).sum();
assert!(
total >= 105,
"only {total} depth-2 paths parsed; the contract parser is broken"
);
for (parent, kids) in &declared {
let actual = help_subcommands(&[parent.as_str()]);
let missing: Vec<&String> = kids.iter().filter(|k| !actual.contains(k)).collect();
assert!(
missing.is_empty(),
"FALSIFY-CLI-006: contract declares `apr {parent} {missing:?}` but the \
binary does not offer them.\nbinary has: {actual:?}"
);
}
}
#[test]
fn every_subcommand_in_the_binary_is_declared() {
let declared: std::collections::HashMap<String, Vec<String>> =
contract_subcommands().into_iter().collect();
let mut undeclared: Vec<String> = Vec::new();
let mut seen = 0usize;
for parent in registered_commands() {
let actual = help_subcommands(&[parent]);
if actual.is_empty() {
continue;
}
seen += actual.len();
let empty = Vec::new();
let kids = declared.get(parent).unwrap_or(&empty);
for a in &actual {
if !kids.contains(a) {
undeclared.push(format!("{parent} {a}"));
}
}
}
assert!(
seen >= 105,
"only {seen} depth-2 paths seen in the binary; the help parser is broken"
);
assert!(
undeclared.is_empty(),
"FALSIFY-CLI-006: the binary offers depth-2 commands the contract does not \
declare: {undeclared:?}\nAdd them to contracts/apr-cli-commands-v1.yaml \
under their parent's `subcommands:`."
);
}
#[cfg(unix)]
fn write_fake_serve_script(dir: &std::path::Path, pidfile: &std::path::Path) -> std::path::PathBuf {
use std::os::unix::fs::PermissionsExt;
let script = dir.join("fake-apr-serve.sh");
std::fs::write(
&script,
format!(
"#!/bin/sh\necho $$ > '{}'\nexec sleep 30 >/dev/null 2>&1 </dev/null\n",
pidfile.display()
),
)
.expect("write fake serve script");
let mut perms = std::fs::metadata(&script)
.expect("stat script")
.permissions();
perms.set_mode(0o755);
std::fs::set_permissions(&script, perms).expect("chmod script");
script
}
#[cfg(unix)]
fn write_reachable_serve_script(
dir: &std::path::Path,
handshake: &std::path::Path,
) -> std::path::PathBuf {
use std::os::unix::fs::PermissionsExt;
let script = dir.join("reachable-apr-serve.sh");
std::fs::write(
&script,
format!(
"#!/bin/sh\n\
trap '' TERM\n\
port=''\n\
prev=''\n\
for a in \"$@\"; do\n\
\tif [ \"$prev\" = \"--port\" ]; then port=\"$a\"; fi\n\
\tprev=\"$a\"\n\
done\n\
printf '%s %s\\n' \"$$\" \"$port\" > '{}'\n\
while : ; do sleep 1; done\n",
handshake.display()
),
)
.expect("write reachable serve script");
let mut perms = std::fs::metadata(&script)
.expect("stat script")
.permissions();
perms.set_mode(0o755);
std::fs::set_permissions(&script, perms).expect("chmod script");
script
}
#[cfg(unix)]
fn answer_completions_forever(listener: std::net::TcpListener) {
use std::io::{Read, Write};
const BODY: &str = concat!(
r#"{"choices":[{"message":{"role":"assistant","content":"ok"},"#,
r#""finish_reason":"stop"}],"#,
r#""usage":{"prompt_tokens":1,"completion_tokens":1,"total_tokens":2}}"#
);
for stream in listener.incoming() {
let Ok(mut sock) = stream else { break };
std::thread::spawn(move || {
let _ = sock.set_read_timeout(Some(std::time::Duration::from_millis(500)));
let mut buf = [0u8; 8192];
let _ = sock.read(&mut buf);
let resp = format!(
"HTTP/1.1 200 OK\r\ncontent-type: application/json\r\n\
content-length: {}\r\nconnection: close\r\n\r\n{BODY}",
BODY.len()
);
let _ = sock.write_all(resp.as_bytes());
let _ = sock.flush();
});
}
}
#[cfg(unix)]
fn pid_is_alive(pid: i32) -> bool {
std::process::Command::new("kill")
.args(["-0", &pid.to_string()])
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.status()
.map(|s| s.success())
.unwrap_or(false)
}
#[test]
#[cfg(unix)]
fn falsify_2607_bare_apr_code_with_closed_stdin_spawns_no_serve_child() {
let tmp = tempfile::tempdir().expect("tempdir");
let home = tmp.path();
let models = home.join("models");
std::fs::create_dir_all(&models).expect("create ./models");
std::fs::write(models.join("fake-30b-moe.gguf"), b"GGUF").expect("write fake gguf");
std::fs::create_dir_all(home.join(".apr").join("models")).expect("create ~/.apr/models");
std::fs::write(
home.join(".apr").join("models").join("fake-30b-moe.gguf"),
b"GGUF",
)
.expect("write fake gguf in HOME");
let pidfile = home.join("serve.pid");
let fake_serve = write_fake_serve_script(home, &pidfile);
let output = apr_binary()
.arg("code")
.current_dir(home)
.env("HOME", home)
.env("XDG_CONFIG_HOME", home.join(".config"))
.env("APR_BIN", &fake_serve)
.env("APR_SERVE_READY_TIMEOUT_S", "1")
.stdin(std::process::Stdio::null())
.output()
.expect("run apr code");
let spawned = std::fs::read_to_string(&pidfile).ok();
if let Some(ref raw) = spawned {
if let Ok(pid) = raw.trim().parse::<i32>() {
let alive = pid_is_alive(pid);
if alive {
let _ = std::process::Command::new("kill")
.args(["-9", &pid.to_string()])
.status();
}
panic!(
"#2607: bare `apr code` with stdin closed spawned an inference server \
(pid {pid}, still alive after the parent exited: {alive}). \
A no-argument invocation must print help, not pick a model off the disk."
);
}
}
assert!(
spawned.is_none(),
"#2607: bare `apr code` with stdin closed spawned a serve child ({spawned:?})"
);
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(
stderr.contains("Usage:"),
"#2607: bare `apr code` must print help. stderr was:\n{stderr}"
);
assert!(
stderr.contains("stdin is not a terminal"),
"#2607: help must say WHY nothing ran. stderr was:\n{stderr}"
);
assert_eq!(
output.status.code(),
Some(2),
"#2607: a usage refusal exits 2 (clap's usage-error code), not 0. stderr:\n{stderr}"
);
}
#[test]
#[cfg(unix)]
fn falsify_2607_non_interactive_p_run_leaves_no_serve_child() {
let tmp = tempfile::tempdir().expect("tempdir");
let home = tmp.path();
let models = home.join("models");
std::fs::create_dir_all(&models).expect("create ./models");
std::fs::write(models.join("fake-30b-moe.gguf"), b"GGUF").expect("write fake gguf");
let handshake = home.join("serve.handshake");
let fake_serve = write_reachable_serve_script(home, &handshake);
let mut child = apr_binary()
.args(["code", "-p", "hi"])
.current_dir(home)
.env("HOME", home)
.env("XDG_CONFIG_HOME", home.join(".config"))
.env("APR_BIN", &fake_serve)
.env("APR_SERVE_READY_TIMEOUT_S", "20")
.env("APR_AGENT_HTTP_TIMEOUT_S", "20")
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.spawn()
.expect("spawn apr code -p");
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30);
let (serve_pid, port) = loop {
if let Ok(raw) = std::fs::read_to_string(&handshake) {
let mut parts = raw.split_whitespace();
if let (Some(pid), Some(port)) = (parts.next(), parts.next()) {
if let (Ok(pid), Ok(port)) = (pid.parse::<i32>(), port.parse::<u16>()) {
break (pid, port);
}
}
}
assert!(
std::time::Instant::now() < deadline,
"#2607: `apr code -p` never spawned its inference backend — the fixture is not \
exercising the path this test exists for"
);
std::thread::sleep(std::time::Duration::from_millis(20));
};
let listener = std::net::TcpListener::bind(("127.0.0.1", port)).unwrap_or_else(|e| {
let _ = child.kill();
let _ = std::process::Command::new("kill")
.args(["-9", &serve_pid.to_string()])
.status();
panic!(
"#2607: could not bind 127.0.0.1:{port} to stand in for `apr serve` ({e}); \
another process is holding the port `apr code` derived from its own pid"
)
});
std::thread::spawn(move || answer_completions_forever(listener));
let output = child.wait_with_output().expect("wait for apr code");
let alive = pid_is_alive(serve_pid);
if alive {
let _ = std::process::Command::new("kill")
.args(["-9", &serve_pid.to_string()])
.status();
}
assert!(
!alive,
"#2607: `apr code -p` exited leaving its `apr serve` child (pid {serve_pid}) running. \
The `-p` branch ends in std::process::exit, which runs no destructors, so every owner \
of the driver Arc must be released explicitly first. stderr:\n{}",
String::from_utf8_lossy(&output.stderr)
);
}
#[test]
#[cfg(unix)]
fn falsify_2607_piped_prompt_is_not_refused_as_a_bare_invocation() {
let tmp = tempfile::tempdir().expect("tempdir");
let home = tmp.path();
let mut child = apr_binary()
.arg("code")
.current_dir(home)
.env("HOME", home)
.env("XDG_CONFIG_HOME", home.join(".config"))
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.spawn()
.expect("spawn apr code with a pipe");
{
use std::io::Write;
let mut stdin = child.stdin.take().expect("piped stdin");
stdin.write_all(b"hi\n").expect("write piped prompt");
std::thread::sleep(std::time::Duration::from_millis(50));
}
let output = child.wait_with_output().expect("wait for apr code");
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(
!stderr.contains("nothing to do"),
"#2607 follow-up: `echo \"hi\" | apr code` carries an instruction and must not be \
refused as a bare invocation. stderr:\n{stderr}"
);
assert_ne!(
output.status.code(),
Some(2),
"#2607 follow-up: a piped prompt must not exit with the usage-error code. \
stderr:\n{stderr}"
);
assert_eq!(
output.status.code(),
Some(5),
"#2607 follow-up: with a prompt on stdin and no model anywhere, the run must reach \
model resolution and stop at NO_MODEL — proof the guard let it through. stderr:\n{stderr}"
);
}