Skip to main content

abstractcore_console/
cli.rs

1//! The `abstractcore` CLI subprocess client — the console's only lane
2//! into Python-derived views (and, in M2, into every coupled write).
3//!
4//! Runs ONLY on the worker thread. Machine surfaces only: JSON stdout
5//! from `config … --json` subcommands and exit codes; human output
6//! (`--status`, wizard prose) is never scraped (risk-map fact #9).
7
8use std::io::Read;
9use std::path::{Path, PathBuf};
10use std::process::{Command, Stdio};
11use std::time::{Duration, Instant};
12
13use serde_json::Value;
14
15/// The uv tool shim (`uv tool install abstractcore`), under `$HOME`.
16const UV_TOOL_BIN: &str = ".local/bin/abstractcore";
17/// A project virtualenv, relative to the CURRENT directory.
18const LOCAL_VENV_BIN: &str = ".venv/bin/abstractcore";
19
20#[derive(Clone, Debug, PartialEq)]
21pub enum CliErrorKind {
22    /// No abstractcore binary was found anywhere.
23    NotFound,
24    /// The process could not be spawned (permissions, broken venv).
25    Spawn,
26    /// The process outlived its deadline and was killed.
27    Timeout,
28    /// Nonzero exit; the message carries the CLI's own error line.
29    Exit(i32),
30    /// Exit 0 but stdout was not the JSON we asked for.
31    BadJson,
32}
33
34#[derive(Clone, Debug)]
35pub struct CliError {
36    pub kind: CliErrorKind,
37    pub message: String,
38    /// Which binary failed — the chat lane's errors must not wear the
39    /// core binary's name (M3 review P3-1: "abstractcore exited with
40    /// 2" for an abstractcore-chat argparse refusal).
41    pub program: &'static str,
42}
43
44impl CliError {
45    pub fn core(kind: CliErrorKind, message: String) -> CliError {
46        CliError {
47            kind,
48            message,
49            program: "abstractcore",
50        }
51    }
52
53    pub fn chat(kind: CliErrorKind, message: String) -> CliError {
54        CliError {
55            kind,
56            message,
57            program: "abstractcore-chat",
58        }
59    }
60
61    pub fn headline(&self) -> String {
62        let p = self.program;
63        match self.kind {
64            CliErrorKind::NotFound => format!("{p} CLI not found"),
65            CliErrorKind::Spawn => format!("could not start {p}"),
66            CliErrorKind::Timeout => format!("{p} timed out"),
67            CliErrorKind::Exit(code) => format!("{p} exited with {code}"),
68            CliErrorKind::BadJson => format!("{p} answered, but not with JSON"),
69        }
70    }
71
72    /// What the operator can DO about it — refusals speak.
73    pub fn hint(&self) -> &'static str {
74        match self.kind {
75            CliErrorKind::NotFound => {
76                "set $ABSTRACTCORE_CLI, or install abstractcore on PATH — the file mirror still works"
77            }
78            CliErrorKind::Spawn => "check the binary is executable ($ABSTRACTCORE_CLI?)",
79            CliErrorKind::Timeout => "the Python side hung — retry with r",
80            CliErrorKind::Exit(_) => "the message above is the CLI's own error",
81            CliErrorKind::BadJson => "an abstractcore too old for --json? check its version",
82        }
83    }
84}
85
86impl std::fmt::Display for CliError {
87    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
88        write!(f, "{}: {}", self.headline(), self.message)
89    }
90}
91
92/// Where the binary came from — rendered in the header/overview so
93/// "which abstractcore am I driving" is always answered.
94#[derive(Clone, Debug)]
95pub struct CliInfo {
96    pub bin: PathBuf,
97    pub source: &'static str,
98}
99
100/// How the console finds `abstractcore`, first hit wins:
101///
102/// 1. `$ABSTRACTCORE_CLI` — an explicit override (honored without an
103///    existence check; a bad value fails loudly at spawn, naming it).
104///    `$ABSTRACTCORE_BIN` is accepted as a legacy alias.
105/// 2. `abstractcore` on `PATH`.
106/// 3. `~/.local/bin/abstractcore` — the `uv tool install` shim, often
107///    not on PATH in a fresh shell.
108/// 4. `./.venv/bin/abstractcore` relative to the current directory.
109///
110/// None = not found (the mirror still works; derived views and writes
111/// teach the fix).
112pub fn resolve_bin(
113    env: &dyn Fn(&str) -> Option<String>,
114    home: &Path,
115    cwd: &Path,
116    exists: &dyn Fn(&Path) -> bool,
117) -> Option<CliInfo> {
118    for (var, source) in [
119        ("ABSTRACTCORE_CLI", "$ABSTRACTCORE_CLI"),
120        ("ABSTRACTCORE_BIN", "$ABSTRACTCORE_BIN (legacy alias)"),
121    ] {
122        if let Some(explicit) = env(var).filter(|v| !v.trim().is_empty()) {
123            return Some(CliInfo {
124                bin: PathBuf::from(explicit.trim()),
125                source,
126            });
127        }
128    }
129    if let Some(paths) = env("PATH") {
130        for dir in std::env::split_paths(&paths) {
131            let candidate = dir.join("abstractcore");
132            if exists(&candidate) {
133                return Some(CliInfo {
134                    bin: candidate,
135                    source: "PATH",
136                });
137            }
138        }
139    }
140    if !home.as_os_str().is_empty() {
141        let shim = home.join(UV_TOOL_BIN);
142        if exists(&shim) {
143            return Some(CliInfo {
144                bin: shim,
145                source: "~/.local/bin (uv tool)",
146            });
147        }
148    }
149    let venv = cwd.join(LOCAL_VENV_BIN);
150    if exists(&venv) {
151        return Some(CliInfo {
152            bin: venv,
153            source: "./.venv",
154        });
155    }
156    None
157}
158
159pub fn resolve_bin_from_env() -> Option<CliInfo> {
160    let home = std::env::var("HOME").map(PathBuf::from).unwrap_or_default();
161    let cwd = std::env::current_dir().unwrap_or_default();
162    resolve_bin(&|k| std::env::var(k).ok(), &home, &cwd, &|p| p.is_file())
163}
164
165pub struct CoreCli {
166    pub bin: PathBuf,
167    /// `abstractcore-chat` — the one-shot generation lane (M3 test
168    /// verbs). Resolved beside `bin` (same venv/bin dir) or on PATH;
169    /// None = generation tests refuse with a teaching message.
170    pub chat_bin: Option<PathBuf>,
171    /// True when `chat_bin` came from the PATH fallback rather than
172    /// beside `bin` — a different install may answer the generation
173    /// test than the one serving discovery, and silence about it
174    /// would contradict the sibling rationale (M3 review P3-2).
175    pub chat_from_path: bool,
176}
177
178/// The chat binary ships in the same bin dir as `abstractcore`; a
179/// sibling lookup keeps both binaries from the SAME install (a PATH
180/// hit from a different venv would test a different abstractcore) —
181/// the PATH fallback is flagged so the mismatch never goes silent.
182pub fn resolve_chat_bin(
183    core_bin: &Path,
184    exists: &dyn Fn(&Path) -> bool,
185) -> Option<(PathBuf, bool)> {
186    let sibling = core_bin.with_file_name("abstractcore-chat");
187    if exists(&sibling) {
188        return Some((sibling, false));
189    }
190    if let Some(paths) = std::env::var_os("PATH") {
191        for dir in std::env::split_paths(&paths) {
192            let candidate = dir.join("abstractcore-chat");
193            if exists(&candidate) {
194                return Some((candidate, true));
195            }
196        }
197    }
198    None
199}
200
201/// A successful CLI run: the JSON payload PLUS any labeled degradation
202/// the Python side printed to stderr while exiting 0. The
203/// `#FALLBACK` lane is load-bearing (adversarial review P1-1): when
204/// Python cannot load the config file it backs it up, runs on
205/// DEFAULTS, prints one `#FALLBACK …` stderr line — and the JSON body
206/// still says `ok: true`. Dropping that line made the mirror vouch
207/// for a file Python refuses.
208#[derive(Clone, Debug)]
209pub struct CliOutput {
210    pub value: Value,
211    pub fallback_warnings: Vec<String>,
212}
213
214impl CoreCli {
215    pub fn new(bin: PathBuf) -> CoreCli {
216        let resolved = resolve_chat_bin(&bin, &|p| p.is_file());
217        let chat_from_path = resolved.as_ref().is_some_and(|(_, from_path)| *from_path);
218        CoreCli {
219            bin,
220            chat_bin: resolved.map(|(p, _)| p),
221            chat_from_path,
222        }
223    }
224
225    /// A CoreCli for tests: no chat sibling resolution.
226    #[cfg(test)]
227    pub fn bare(bin: PathBuf) -> CoreCli {
228        CoreCli {
229            bin,
230            chat_bin: None,
231            chat_from_path: false,
232        }
233    }
234
235    /// Run `abstractcore-chat <args>` and return raw stdout + the
236    /// stderr `#FALLBACK` lines. Exit-code truth only — the stdout
237    /// verdict (reply vs `❌ Error:`) is the caller's fold
238    /// (`probes::fold_generation`); this lane's argv never carries
239    /// secrets (provider/model/prompt only).
240    pub fn run_chat(
241        &self,
242        args: &[&str],
243        timeout: Duration,
244    ) -> Result<(String, Vec<String>), CliError> {
245        let chat = self.chat_bin.as_ref().ok_or_else(|| {
246            CliError::chat(
247                CliErrorKind::NotFound,
248                "abstractcore-chat not found beside abstractcore or on PATH".into(),
249            )
250        })?;
251        let label = format!("abstractcore-chat {}", args.join(" "));
252        let (status, stdout, stderr) =
253            run_raw_at(chat, args, &label, timeout).map_err(|mut e| {
254                e.program = "abstractcore-chat";
255                e
256            })?;
257        if !status.success() {
258            return Err(CliError::chat(
259                CliErrorKind::Exit(status.code().unwrap_or(-1)),
260                error_line(&stdout, &stderr),
261            ));
262        }
263        Ok((stdout, fallback_lines(&stderr)))
264    }
265
266    /// Run a SETTER invocation (human output, no JSON). The flags CLI
267    /// exits 0 on refused writes (live-probed: `--set-server-port
268    /// 99999` prints `❌ Error:` and exits 0) — so an error line on
269    /// stdout is a failure REGARDLESS of the exit code. Returns the
270    /// stderr `#FALLBACK` lines like the JSON lane.
271    /// `redacted_label` names the invocation in error messages — argv
272    /// may carry secrets here, so the label comes from the caller's
273    /// already-redacted rendering, never from the args.
274    pub fn run_setter(
275        &self,
276        args: &[&str],
277        redacted_label: &str,
278        timeout: Duration,
279    ) -> Result<Vec<String>, CliError> {
280        let (status, stdout, stderr) = self.run_raw(args, redacted_label, timeout)?;
281        if !status.success() {
282            return Err(CliError::core(
283                CliErrorKind::Exit(status.code().unwrap_or(-1)),
284                error_line(&stdout, &stderr),
285            ));
286        }
287        if let Some(l) = stdout
288            .lines()
289            .find(|l| l.contains("❌") || l.contains("Error:"))
290        {
291            return Err(CliError::core(
292                CliErrorKind::Exit(0),
293                format!("{} (the CLI still exited 0)", l.trim()),
294            ));
295        }
296        Ok(fallback_lines(&stderr))
297    }
298
299    /// Run `abstractcore <args>` and parse stdout as JSON.
300    ///
301    /// Body over transport: a nonzero exit still tries to surface the
302    /// CLI's own `❌ Error:` line (config subcommands print errors to
303    /// stdout, main.py:1753-1760). Stdout/stderr are drained on reader
304    /// threads so a large payload can never deadlock the pipe.
305    pub fn run_json(&self, args: &[&str], timeout: Duration) -> Result<CliOutput, CliError> {
306        // The read lane's argv never carries secrets — its own join is
307        // an honest label.
308        let label = format!("abstractcore {}", args.join(" "));
309        let (status, stdout, stderr) = self.run_raw(args, &label, timeout)?;
310        if !status.success() {
311            let code = status.code().unwrap_or(-1);
312            return Err(CliError::core(
313                CliErrorKind::Exit(code),
314                error_line(&stdout, &stderr),
315            ));
316        }
317        let value = serde_json::from_str(&stdout).map_err(|e| {
318            CliError::core(
319                CliErrorKind::BadJson,
320                format!("{e} — first bytes: {}", head(&stdout, 120)),
321            )
322        })?;
323        Ok(CliOutput {
324            value,
325            fallback_warnings: fallback_lines(&stderr),
326        })
327    }
328
329    /// Run a streaming `abstractcore <args> --json` verb and return its
330    /// FINAL document.
331    ///
332    /// `models download <p> <a> --json` (and `engines install --json`)
333    /// print one `host_job_v1` object per line while the job runs and the
334    /// final job last; that last line also carries the legacy
335    /// `ok`/`results` keys of the older one-document shape. A pretty-printed
336    /// single document is accepted too. A nonzero exit reports the final
337    /// job's own `error`/`message` when the last line is a job, else the
338    /// CLI's error line.
339    pub fn run_json_last(&self, args: &[&str], timeout: Duration) -> Result<CliOutput, CliError> {
340        let label = format!("abstractcore {}", args.join(" "));
341        let (status, stdout, stderr) = self.run_raw(args, &label, timeout)?;
342        let last = last_json_object(&stdout);
343        if !status.success() {
344            let code = status.code().unwrap_or(-1);
345            let msg = last
346                .as_ref()
347                .and_then(job_error_text)
348                .unwrap_or_else(|| error_line(&stdout, &stderr));
349            return Err(CliError::core(CliErrorKind::Exit(code), msg));
350        }
351        let value = last.ok_or_else(|| {
352            CliError::core(
353                CliErrorKind::BadJson,
354                format!(
355                    "no JSON object on stdout — first bytes: {}",
356                    head(&stdout, 120)
357                ),
358            )
359        })?;
360        Ok(CliOutput {
361            value,
362            fallback_warnings: fallback_lines(&stderr),
363        })
364    }
365
366    /// Shared subprocess mechanics: spawn, drain both pipes on reader
367    /// threads (a large payload can never deadlock), wait with a
368    /// deadline, kill on overrun.
369    fn run_raw(
370        &self,
371        args: &[&str],
372        redacted_label: &str,
373        timeout: Duration,
374    ) -> Result<(std::process::ExitStatus, String, String), CliError> {
375        run_raw_at(&self.bin, args, redacted_label, timeout)
376    }
377}
378
379pub(crate) fn run_raw_at(
380    bin: &Path,
381    args: &[&str],
382    redacted_label: &str,
383    timeout: Duration,
384) -> Result<(std::process::ExitStatus, String, String), CliError> {
385    let mut child = Command::new(bin)
386        .args(args)
387        .stdin(Stdio::null())
388        .stdout(Stdio::piped())
389        .stderr(Stdio::piped())
390        .spawn()
391        .map_err(|e| CliError::core(CliErrorKind::Spawn, format!("{}: {e}", bin.display())))?;
392
393    let stdout = child.stdout.take().expect("piped");
394    let stderr = child.stderr.take().expect("piped");
395    let out_h = std::thread::spawn(move || read_all(stdout));
396    let err_h = std::thread::spawn(move || read_all(stderr));
397
398    let deadline = Instant::now() + timeout;
399    let status = loop {
400        match child.try_wait() {
401            Ok(Some(status)) => break status,
402            Ok(None) => {
403                if Instant::now() >= deadline {
404                    let _ = child.kill();
405                    let _ = child.wait();
406                    // Join the readers so the threads never leak.
407                    let _ = out_h.join();
408                    let _ = err_h.join();
409                    return Err(CliError::core(
410                        CliErrorKind::Timeout,
411                        format!("no answer within {}s: {redacted_label}", timeout.as_secs()),
412                    ));
413                }
414                std::thread::sleep(Duration::from_millis(25));
415            }
416            Err(e) => return Err(CliError::core(CliErrorKind::Spawn, e.to_string())),
417        }
418    };
419    let stdout = out_h.join().unwrap_or_default();
420    let stderr = err_h.join().unwrap_or_default();
421    Ok((status, stdout, stderr))
422}
423
424/// The labeled degradations an exit-0 abstractcore run prints to
425/// stderr. `#FALLBACK` is the framework-wide convention; the
426/// corrupt-config warning uses it (manager.py:495-566).
427fn fallback_lines(stderr: &str) -> Vec<String> {
428    stderr
429        .lines()
430        .filter(|l| l.contains("#FALLBACK"))
431        .map(|l| l.trim().to_string())
432        .collect()
433}
434
435fn read_all(mut r: impl Read) -> String {
436    let mut buf = Vec::new();
437    let _ = r.read_to_end(&mut buf);
438    String::from_utf8_lossy(&buf).into_owned()
439}
440
441/// The most useful single error line from a failed CLI run: the CLI's
442/// own `❌ Error:` line (stdout) first, else the first non-empty stderr
443/// line, else a generic head of whatever was printed.
444pub(crate) fn error_line(stdout: &str, stderr: &str) -> String {
445    if let Some(l) = stdout.lines().find(|l| l.contains("Error:")) {
446        return l.trim().to_string();
447    }
448    if let Some(l) = stderr.lines().rev().find(|l| !l.trim().is_empty()) {
449        return l.trim().to_string();
450    }
451    if let Some(l) = stdout.lines().find(|l| !l.trim().is_empty()) {
452        return l.trim().to_string();
453    }
454    "(no output)".into()
455}
456
457/// The whole stdout as one JSON object, else its LAST line that is one
458/// (NDJSON streams end with the final document).
459pub(crate) fn last_json_object(stdout: &str) -> Option<Value> {
460    let trimmed = stdout.trim();
461    if trimmed.is_empty() {
462        return None;
463    }
464    if let Ok(v) = serde_json::from_str::<Value>(trimmed) {
465        return v.is_object().then_some(v);
466    }
467    trimmed
468        .lines()
469        .rev()
470        .find_map(|l| serde_json::from_str::<Value>(l.trim()).ok())
471        .filter(Value::is_object)
472}
473
474/// A job document's own failure text: `error` (a string or `{message}`),
475/// else `message`.
476fn job_error_text(v: &Value) -> Option<String> {
477    let err = v.get("error");
478    let text = err
479        .and_then(Value::as_str)
480        .or_else(|| err.and_then(|e| e.get("message")).and_then(Value::as_str))
481        .or_else(|| v.get("message").and_then(Value::as_str))?;
482    let text = text.trim();
483    (!text.is_empty()).then(|| text.to_string())
484}
485
486pub(crate) fn head(s: &str, n: usize) -> String {
487    let t: String = s.chars().take(n).collect();
488    t.replace('\n', " ")
489}
490
491#[cfg(test)]
492mod tests {
493    use super::*;
494
495    #[test]
496    fn bin_resolution_order() {
497        let home = Path::new("/home/u");
498        let cwd = Path::new("/work/proj");
499        // Explicit override wins, even without an existence check —
500        // and over the legacy alias when both are set.
501        let info = resolve_bin(
502            &|k| match k {
503                "ABSTRACTCORE_CLI" => Some("/opt/ac".to_string()),
504                "ABSTRACTCORE_BIN" => Some("/opt/legacy".to_string()),
505                _ => None,
506            },
507            home,
508            cwd,
509            &|_| false,
510        )
511        .unwrap();
512        assert_eq!(info.bin, PathBuf::from("/opt/ac"));
513        assert_eq!(info.source, "$ABSTRACTCORE_CLI");
514        let info = resolve_bin(
515            &|k| (k == "ABSTRACTCORE_BIN").then(|| "/opt/legacy".to_string()),
516            home,
517            cwd,
518            &|_| false,
519        )
520        .unwrap();
521        assert_eq!(info.bin, PathBuf::from("/opt/legacy"));
522
523        // PATH scan finds the first hit — before the shim and the venv.
524        let info = resolve_bin(
525            &|k| (k == "PATH").then(|| "/a:/b".to_string()),
526            home,
527            cwd,
528            &|p| {
529                p == Path::new("/b/abstractcore")
530                    || p.starts_with("/home")
531                    || p.starts_with("/work")
532            },
533        )
534        .unwrap();
535        assert_eq!(info.bin, PathBuf::from("/b/abstractcore"));
536        assert_eq!(info.source, "PATH");
537
538        // uv tool shim, then ./.venv relative to the CURRENT directory.
539        let info = resolve_bin(&|_| None, home, cwd, &|p| {
540            p == Path::new("/home/u/.local/bin/abstractcore")
541                || p == Path::new("/work/proj/.venv/bin/abstractcore")
542        })
543        .unwrap();
544        assert_eq!(info.bin, PathBuf::from("/home/u/.local/bin/abstractcore"));
545        let info = resolve_bin(&|_| None, home, cwd, &|p| {
546            p == Path::new("/work/proj/.venv/bin/abstractcore")
547        })
548        .unwrap();
549        assert_eq!(info.bin, PathBuf::from("/work/proj/.venv/bin/abstractcore"));
550        assert_eq!(info.source, "./.venv");
551
552        // No personal-workspace path is probed any more.
553        assert!(resolve_bin(&|_| None, home, cwd, &|p| {
554            p == Path::new("/home/u/tmp/abstractframework/.venv/bin/abstractcore")
555        })
556        .is_none());
557
558        // Nothing anywhere: honest None.
559        assert!(resolve_bin(&|_| None, home, cwd, &|_| false).is_none());
560    }
561
562    #[test]
563    fn error_line_prefers_the_cli_error() {
564        let out = "some noise\n❌ Error: Unknown provider 'x'\nmore";
565        assert_eq!(error_line(out, ""), "❌ Error: Unknown provider 'x'");
566        assert_eq!(
567            error_line("", "Traceback...\nValueError: boom"),
568            "ValueError: boom"
569        );
570        assert_eq!(error_line("", ""), "(no output)");
571    }
572
573    /// Subprocess mechanics against real processes (no network, no
574    /// abstractcore needed): /bin/echo emits JSON; a sleep overruns the
575    /// deadline and is killed.
576    #[test]
577    fn run_json_parses_and_times_out() {
578        let echo = CoreCli::new(PathBuf::from("/bin/echo"));
579        let out = echo
580            .run_json(&["{\"ok\": true}"], Duration::from_secs(5))
581            .unwrap();
582        assert_eq!(out.value.get("ok").and_then(Value::as_bool), Some(true));
583        assert!(out.fallback_warnings.is_empty());
584
585        let sleep = CoreCli::new(PathBuf::from("/bin/sleep"));
586        let err = sleep
587            .run_json(&["5"], Duration::from_millis(200))
588            .unwrap_err();
589        assert_eq!(err.kind, CliErrorKind::Timeout);
590
591        let missing = CoreCli::new(PathBuf::from("/nonexistent/bin"));
592        let err = missing.run_json(&[], Duration::from_secs(1)).unwrap_err();
593        assert_eq!(err.kind, CliErrorKind::Spawn);
594    }
595
596    /// The streaming download verb prints `host_job_v1` NDJSON progress
597    /// and the final job LAST; only that last line is the answer. A
598    /// failed job exits 1 and its own error text is surfaced.
599    #[test]
600    fn run_json_last_takes_the_final_ndjson_line() {
601        let sh = CoreCli::new(PathBuf::from("/bin/sh"));
602        let ok = sh
603            .run_json_last(
604                &[
605                    "-c",
606                    r#"echo '{"schema":"host_job_v1","status":"running","percent":10.0}'
607echo '{"schema":"host_job_v1","status":"running","percent":90.0}'
608echo '{"schema":"host_job_v1","status":"completed","ok":true,"results":[{"status":"downloaded","message":"done"}]}'"#,
609                ],
610                Duration::from_secs(5),
611            )
612            .unwrap();
613        assert_eq!(ok.value["status"], "completed");
614        assert_eq!(ok.value["results"][0]["status"], "downloaded");
615
616        // The old one-document reader would choke on exactly this stdout.
617        assert_eq!(
618            sh.run_json(
619                &["-c", "echo '{\"a\":1}'; echo '{\"a\":2}'"],
620                Duration::from_secs(5)
621            )
622            .unwrap_err()
623            .kind,
624            CliErrorKind::BadJson
625        );
626
627        let failed = sh
628            .run_json_last(
629                &[
630                    "-c",
631                    r#"echo '{"schema":"host_job_v1","status":"running"}'
632echo '{"schema":"host_job_v1","status":"failed","error":"pull failed: manifest unknown"}'
633exit 1"#,
634                ],
635                Duration::from_secs(5),
636            )
637            .unwrap_err();
638        assert_eq!(failed.kind, CliErrorKind::Exit(1));
639        assert!(failed.to_string().contains("manifest unknown"), "{failed}");
640
641        let empty = sh
642            .run_json_last(&["-c", "echo not json"], Duration::from_secs(5))
643            .unwrap_err();
644        assert_eq!(empty.kind, CliErrorKind::BadJson);
645    }
646
647    /// The P1-1 signal lane: an exit-0 run whose stderr carries a
648    /// `#FALLBACK` line surfaces it — the one honest signal Python
649    /// gives when it refuses the config file while answering ok:true.
650    #[test]
651    fn exit_zero_stderr_fallback_is_surfaced() {
652        let sh = CoreCli::new(PathBuf::from("/bin/sh"));
653        let out = sh
654            .run_json(
655                &[
656                    "-c",
657                    "echo '#FALLBACK abstractcore config could not be parsed; \
658                     falling back to DEFAULTS' >&2; echo '{\"ok\": true}'",
659                ],
660                Duration::from_secs(5),
661            )
662            .unwrap();
663        assert_eq!(out.value.get("ok").and_then(Value::as_bool), Some(true));
664        assert_eq!(out.fallback_warnings.len(), 1);
665        assert!(out.fallback_warnings[0].contains("falling back to DEFAULTS"));
666    }
667}