abstractcore-console 0.4.1

A terminal console for AbstractCore: configure models, providers and capability routes, browse, download and delete local models, and install local engines (Ollama, LM Studio, MLX, llama.cpp). Also a library of the shared Models/Engines screens, rendered by AbstractTUI.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
//! The `abstractcore` CLI subprocess client — the console's only lane
//! into Python-derived views (and, in M2, into every coupled write).
//!
//! Runs ONLY on the worker thread. Machine surfaces only: JSON stdout
//! from `config … --json` subcommands and exit codes; human output
//! (`--status`, wizard prose) is never scraped (risk-map fact #9).

use std::io::Read;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::time::{Duration, Instant};

use serde_json::Value;

/// The uv tool shim (`uv tool install abstractcore`), under `$HOME`.
const UV_TOOL_BIN: &str = ".local/bin/abstractcore";
/// A project virtualenv, relative to the CURRENT directory.
const LOCAL_VENV_BIN: &str = ".venv/bin/abstractcore";

#[derive(Clone, Debug, PartialEq)]
pub enum CliErrorKind {
    /// No abstractcore binary was found anywhere.
    NotFound,
    /// The process could not be spawned (permissions, broken venv).
    Spawn,
    /// The process outlived its deadline and was killed.
    Timeout,
    /// Nonzero exit; the message carries the CLI's own error line.
    Exit(i32),
    /// Exit 0 but stdout was not the JSON we asked for.
    BadJson,
}

#[derive(Clone, Debug)]
pub struct CliError {
    pub kind: CliErrorKind,
    pub message: String,
    /// Which binary failed — the chat lane's errors must not wear the
    /// core binary's name (M3 review P3-1: "abstractcore exited with
    /// 2" for an abstractcore-chat argparse refusal).
    pub program: &'static str,
}

impl CliError {
    pub fn core(kind: CliErrorKind, message: String) -> CliError {
        CliError {
            kind,
            message,
            program: "abstractcore",
        }
    }

    pub fn chat(kind: CliErrorKind, message: String) -> CliError {
        CliError {
            kind,
            message,
            program: "abstractcore-chat",
        }
    }

    pub fn headline(&self) -> String {
        let p = self.program;
        match self.kind {
            CliErrorKind::NotFound => format!("{p} CLI not found"),
            CliErrorKind::Spawn => format!("could not start {p}"),
            CliErrorKind::Timeout => format!("{p} timed out"),
            CliErrorKind::Exit(code) => format!("{p} exited with {code}"),
            CliErrorKind::BadJson => format!("{p} answered, but not with JSON"),
        }
    }

    /// What the operator can DO about it — refusals speak.
    pub fn hint(&self) -> &'static str {
        match self.kind {
            CliErrorKind::NotFound => {
                "set $ABSTRACTCORE_CLI, or install abstractcore on PATH — the file mirror still works"
            }
            CliErrorKind::Spawn => "check the binary is executable ($ABSTRACTCORE_CLI?)",
            CliErrorKind::Timeout => "the Python side hung — retry with r",
            CliErrorKind::Exit(_) => "the message above is the CLI's own error",
            CliErrorKind::BadJson => "an abstractcore too old for --json? check its version",
        }
    }
}

impl std::fmt::Display for CliError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}: {}", self.headline(), self.message)
    }
}

/// Where the binary came from — rendered in the header/overview so
/// "which abstractcore am I driving" is always answered.
#[derive(Clone, Debug)]
pub struct CliInfo {
    pub bin: PathBuf,
    pub source: &'static str,
}

/// How the console finds `abstractcore`, first hit wins:
///
/// 1. `$ABSTRACTCORE_CLI` — an explicit override (honored without an
///    existence check; a bad value fails loudly at spawn, naming it).
///    `$ABSTRACTCORE_BIN` is accepted as a legacy alias.
/// 2. `abstractcore` on `PATH`.
/// 3. `~/.local/bin/abstractcore` — the `uv tool install` shim, often
///    not on PATH in a fresh shell.
/// 4. `./.venv/bin/abstractcore` relative to the current directory.
///
/// None = not found (the mirror still works; derived views and writes
/// teach the fix).
pub fn resolve_bin(
    env: &dyn Fn(&str) -> Option<String>,
    home: &Path,
    cwd: &Path,
    exists: &dyn Fn(&Path) -> bool,
) -> Option<CliInfo> {
    for (var, source) in [
        ("ABSTRACTCORE_CLI", "$ABSTRACTCORE_CLI"),
        ("ABSTRACTCORE_BIN", "$ABSTRACTCORE_BIN (legacy alias)"),
    ] {
        if let Some(explicit) = env(var).filter(|v| !v.trim().is_empty()) {
            return Some(CliInfo {
                bin: PathBuf::from(explicit.trim()),
                source,
            });
        }
    }
    if let Some(paths) = env("PATH") {
        for dir in std::env::split_paths(&paths) {
            let candidate = dir.join("abstractcore");
            if exists(&candidate) {
                return Some(CliInfo {
                    bin: candidate,
                    source: "PATH",
                });
            }
        }
    }
    if !home.as_os_str().is_empty() {
        let shim = home.join(UV_TOOL_BIN);
        if exists(&shim) {
            return Some(CliInfo {
                bin: shim,
                source: "~/.local/bin (uv tool)",
            });
        }
    }
    let venv = cwd.join(LOCAL_VENV_BIN);
    if exists(&venv) {
        return Some(CliInfo {
            bin: venv,
            source: "./.venv",
        });
    }
    None
}

pub fn resolve_bin_from_env() -> Option<CliInfo> {
    let home = std::env::var("HOME").map(PathBuf::from).unwrap_or_default();
    let cwd = std::env::current_dir().unwrap_or_default();
    resolve_bin(&|k| std::env::var(k).ok(), &home, &cwd, &|p| p.is_file())
}

pub struct CoreCli {
    pub bin: PathBuf,
    /// `abstractcore-chat` — the one-shot generation lane (M3 test
    /// verbs). Resolved beside `bin` (same venv/bin dir) or on PATH;
    /// None = generation tests refuse with a teaching message.
    pub chat_bin: Option<PathBuf>,
    /// True when `chat_bin` came from the PATH fallback rather than
    /// beside `bin` — a different install may answer the generation
    /// test than the one serving discovery, and silence about it
    /// would contradict the sibling rationale (M3 review P3-2).
    pub chat_from_path: bool,
}

/// The chat binary ships in the same bin dir as `abstractcore`; a
/// sibling lookup keeps both binaries from the SAME install (a PATH
/// hit from a different venv would test a different abstractcore) —
/// the PATH fallback is flagged so the mismatch never goes silent.
pub fn resolve_chat_bin(
    core_bin: &Path,
    exists: &dyn Fn(&Path) -> bool,
) -> Option<(PathBuf, bool)> {
    let sibling = core_bin.with_file_name("abstractcore-chat");
    if exists(&sibling) {
        return Some((sibling, false));
    }
    if let Some(paths) = std::env::var_os("PATH") {
        for dir in std::env::split_paths(&paths) {
            let candidate = dir.join("abstractcore-chat");
            if exists(&candidate) {
                return Some((candidate, true));
            }
        }
    }
    None
}

/// A successful CLI run: the JSON payload PLUS any labeled degradation
/// the Python side printed to stderr while exiting 0. The
/// `#FALLBACK` lane is load-bearing (adversarial review P1-1): when
/// Python cannot load the config file it backs it up, runs on
/// DEFAULTS, prints one `#FALLBACK …` stderr line — and the JSON body
/// still says `ok: true`. Dropping that line made the mirror vouch
/// for a file Python refuses.
#[derive(Clone, Debug)]
pub struct CliOutput {
    pub value: Value,
    pub fallback_warnings: Vec<String>,
}

impl CoreCli {
    pub fn new(bin: PathBuf) -> CoreCli {
        let resolved = resolve_chat_bin(&bin, &|p| p.is_file());
        let chat_from_path = resolved.as_ref().is_some_and(|(_, from_path)| *from_path);
        CoreCli {
            bin,
            chat_bin: resolved.map(|(p, _)| p),
            chat_from_path,
        }
    }

    /// A CoreCli for tests: no chat sibling resolution.
    #[cfg(test)]
    pub fn bare(bin: PathBuf) -> CoreCli {
        CoreCli {
            bin,
            chat_bin: None,
            chat_from_path: false,
        }
    }

    /// Run `abstractcore-chat <args>` and return raw stdout + the
    /// stderr `#FALLBACK` lines. Exit-code truth only — the stdout
    /// verdict (reply vs `❌ Error:`) is the caller's fold
    /// (`probes::fold_generation`); this lane's argv never carries
    /// secrets (provider/model/prompt only).
    pub fn run_chat(
        &self,
        args: &[&str],
        timeout: Duration,
    ) -> Result<(String, Vec<String>), CliError> {
        let chat = self.chat_bin.as_ref().ok_or_else(|| {
            CliError::chat(
                CliErrorKind::NotFound,
                "abstractcore-chat not found beside abstractcore or on PATH".into(),
            )
        })?;
        let label = format!("abstractcore-chat {}", args.join(" "));
        let (status, stdout, stderr) =
            run_raw_at(chat, args, &label, timeout).map_err(|mut e| {
                e.program = "abstractcore-chat";
                e
            })?;
        if !status.success() {
            return Err(CliError::chat(
                CliErrorKind::Exit(status.code().unwrap_or(-1)),
                error_line(&stdout, &stderr),
            ));
        }
        Ok((stdout, fallback_lines(&stderr)))
    }

    /// Run a SETTER invocation (human output, no JSON). The flags CLI
    /// exits 0 on refused writes (live-probed: `--set-server-port
    /// 99999` prints `❌ Error:` and exits 0) — so an error line on
    /// stdout is a failure REGARDLESS of the exit code. Returns the
    /// stderr `#FALLBACK` lines like the JSON lane.
    /// `redacted_label` names the invocation in error messages — argv
    /// may carry secrets here, so the label comes from the caller's
    /// already-redacted rendering, never from the args.
    pub fn run_setter(
        &self,
        args: &[&str],
        redacted_label: &str,
        timeout: Duration,
    ) -> Result<Vec<String>, CliError> {
        let (status, stdout, stderr) = self.run_raw(args, redacted_label, timeout)?;
        if !status.success() {
            return Err(CliError::core(
                CliErrorKind::Exit(status.code().unwrap_or(-1)),
                error_line(&stdout, &stderr),
            ));
        }
        if let Some(l) = stdout
            .lines()
            .find(|l| l.contains("❌") || l.contains("Error:"))
        {
            return Err(CliError::core(
                CliErrorKind::Exit(0),
                format!("{} (the CLI still exited 0)", l.trim()),
            ));
        }
        Ok(fallback_lines(&stderr))
    }

    /// Run `abstractcore <args>` and parse stdout as JSON.
    ///
    /// Body over transport: a nonzero exit still tries to surface the
    /// CLI's own `❌ Error:` line (config subcommands print errors to
    /// stdout, main.py:1753-1760). Stdout/stderr are drained on reader
    /// threads so a large payload can never deadlock the pipe.
    pub fn run_json(&self, args: &[&str], timeout: Duration) -> Result<CliOutput, CliError> {
        // The read lane's argv never carries secrets — its own join is
        // an honest label.
        let label = format!("abstractcore {}", args.join(" "));
        let (status, stdout, stderr) = self.run_raw(args, &label, timeout)?;
        if !status.success() {
            let code = status.code().unwrap_or(-1);
            return Err(CliError::core(
                CliErrorKind::Exit(code),
                error_line(&stdout, &stderr),
            ));
        }
        let value = serde_json::from_str(&stdout).map_err(|e| {
            CliError::core(
                CliErrorKind::BadJson,
                format!("{e} — first bytes: {}", head(&stdout, 120)),
            )
        })?;
        Ok(CliOutput {
            value,
            fallback_warnings: fallback_lines(&stderr),
        })
    }

    /// Run a streaming `abstractcore <args> --json` verb and return its
    /// FINAL document.
    ///
    /// `models download <p> <a> --json` (and `engines install --json`)
    /// print one `host_job_v1` object per line while the job runs and the
    /// final job last; that last line also carries the legacy
    /// `ok`/`results` keys of the older one-document shape. A pretty-printed
    /// single document is accepted too. A nonzero exit reports the final
    /// job's own `error`/`message` when the last line is a job, else the
    /// CLI's error line.
    pub fn run_json_last(&self, args: &[&str], timeout: Duration) -> Result<CliOutput, CliError> {
        let label = format!("abstractcore {}", args.join(" "));
        let (status, stdout, stderr) = self.run_raw(args, &label, timeout)?;
        let last = last_json_object(&stdout);
        if !status.success() {
            let code = status.code().unwrap_or(-1);
            let msg = last
                .as_ref()
                .and_then(job_error_text)
                .unwrap_or_else(|| error_line(&stdout, &stderr));
            return Err(CliError::core(CliErrorKind::Exit(code), msg));
        }
        let value = last.ok_or_else(|| {
            CliError::core(
                CliErrorKind::BadJson,
                format!(
                    "no JSON object on stdout — first bytes: {}",
                    head(&stdout, 120)
                ),
            )
        })?;
        Ok(CliOutput {
            value,
            fallback_warnings: fallback_lines(&stderr),
        })
    }

    /// Shared subprocess mechanics: spawn, drain both pipes on reader
    /// threads (a large payload can never deadlock), wait with a
    /// deadline, kill on overrun.
    fn run_raw(
        &self,
        args: &[&str],
        redacted_label: &str,
        timeout: Duration,
    ) -> Result<(std::process::ExitStatus, String, String), CliError> {
        run_raw_at(&self.bin, args, redacted_label, timeout)
    }
}

pub(crate) fn run_raw_at(
    bin: &Path,
    args: &[&str],
    redacted_label: &str,
    timeout: Duration,
) -> Result<(std::process::ExitStatus, String, String), CliError> {
    let mut child = Command::new(bin)
        .args(args)
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .map_err(|e| CliError::core(CliErrorKind::Spawn, format!("{}: {e}", bin.display())))?;

    let stdout = child.stdout.take().expect("piped");
    let stderr = child.stderr.take().expect("piped");
    let out_h = std::thread::spawn(move || read_all(stdout));
    let err_h = std::thread::spawn(move || read_all(stderr));

    let deadline = Instant::now() + timeout;
    let status = loop {
        match child.try_wait() {
            Ok(Some(status)) => break status,
            Ok(None) => {
                if Instant::now() >= deadline {
                    let _ = child.kill();
                    let _ = child.wait();
                    // Join the readers so the threads never leak.
                    let _ = out_h.join();
                    let _ = err_h.join();
                    return Err(CliError::core(
                        CliErrorKind::Timeout,
                        format!("no answer within {}s: {redacted_label}", timeout.as_secs()),
                    ));
                }
                std::thread::sleep(Duration::from_millis(25));
            }
            Err(e) => return Err(CliError::core(CliErrorKind::Spawn, e.to_string())),
        }
    };
    let stdout = out_h.join().unwrap_or_default();
    let stderr = err_h.join().unwrap_or_default();
    Ok((status, stdout, stderr))
}

/// The labeled degradations an exit-0 abstractcore run prints to
/// stderr. `#FALLBACK` is the framework-wide convention; the
/// corrupt-config warning uses it (manager.py:495-566).
fn fallback_lines(stderr: &str) -> Vec<String> {
    stderr
        .lines()
        .filter(|l| l.contains("#FALLBACK"))
        .map(|l| l.trim().to_string())
        .collect()
}

fn read_all(mut r: impl Read) -> String {
    let mut buf = Vec::new();
    let _ = r.read_to_end(&mut buf);
    String::from_utf8_lossy(&buf).into_owned()
}

/// The most useful single error line from a failed CLI run: the CLI's
/// own `❌ Error:` line (stdout) first, else the first non-empty stderr
/// line, else a generic head of whatever was printed.
pub(crate) fn error_line(stdout: &str, stderr: &str) -> String {
    if let Some(l) = stdout.lines().find(|l| l.contains("Error:")) {
        return l.trim().to_string();
    }
    if let Some(l) = stderr.lines().rev().find(|l| !l.trim().is_empty()) {
        return l.trim().to_string();
    }
    if let Some(l) = stdout.lines().find(|l| !l.trim().is_empty()) {
        return l.trim().to_string();
    }
    "(no output)".into()
}

/// The whole stdout as one JSON object, else its LAST line that is one
/// (NDJSON streams end with the final document).
pub(crate) fn last_json_object(stdout: &str) -> Option<Value> {
    let trimmed = stdout.trim();
    if trimmed.is_empty() {
        return None;
    }
    if let Ok(v) = serde_json::from_str::<Value>(trimmed) {
        return v.is_object().then_some(v);
    }
    trimmed
        .lines()
        .rev()
        .find_map(|l| serde_json::from_str::<Value>(l.trim()).ok())
        .filter(Value::is_object)
}

/// A job document's own failure text: `error` (a string or `{message}`),
/// else `message`.
fn job_error_text(v: &Value) -> Option<String> {
    let err = v.get("error");
    let text = err
        .and_then(Value::as_str)
        .or_else(|| err.and_then(|e| e.get("message")).and_then(Value::as_str))
        .or_else(|| v.get("message").and_then(Value::as_str))?;
    let text = text.trim();
    (!text.is_empty()).then(|| text.to_string())
}

pub(crate) fn head(s: &str, n: usize) -> String {
    let t: String = s.chars().take(n).collect();
    t.replace('\n', " ")
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn bin_resolution_order() {
        let home = Path::new("/home/u");
        let cwd = Path::new("/work/proj");
        // Explicit override wins, even without an existence check —
        // and over the legacy alias when both are set.
        let info = resolve_bin(
            &|k| match k {
                "ABSTRACTCORE_CLI" => Some("/opt/ac".to_string()),
                "ABSTRACTCORE_BIN" => Some("/opt/legacy".to_string()),
                _ => None,
            },
            home,
            cwd,
            &|_| false,
        )
        .unwrap();
        assert_eq!(info.bin, PathBuf::from("/opt/ac"));
        assert_eq!(info.source, "$ABSTRACTCORE_CLI");
        let info = resolve_bin(
            &|k| (k == "ABSTRACTCORE_BIN").then(|| "/opt/legacy".to_string()),
            home,
            cwd,
            &|_| false,
        )
        .unwrap();
        assert_eq!(info.bin, PathBuf::from("/opt/legacy"));

        // PATH scan finds the first hit — before the shim and the venv.
        let info = resolve_bin(
            &|k| (k == "PATH").then(|| "/a:/b".to_string()),
            home,
            cwd,
            &|p| {
                p == Path::new("/b/abstractcore")
                    || p.starts_with("/home")
                    || p.starts_with("/work")
            },
        )
        .unwrap();
        assert_eq!(info.bin, PathBuf::from("/b/abstractcore"));
        assert_eq!(info.source, "PATH");

        // uv tool shim, then ./.venv relative to the CURRENT directory.
        let info = resolve_bin(&|_| None, home, cwd, &|p| {
            p == Path::new("/home/u/.local/bin/abstractcore")
                || p == Path::new("/work/proj/.venv/bin/abstractcore")
        })
        .unwrap();
        assert_eq!(info.bin, PathBuf::from("/home/u/.local/bin/abstractcore"));
        let info = resolve_bin(&|_| None, home, cwd, &|p| {
            p == Path::new("/work/proj/.venv/bin/abstractcore")
        })
        .unwrap();
        assert_eq!(info.bin, PathBuf::from("/work/proj/.venv/bin/abstractcore"));
        assert_eq!(info.source, "./.venv");

        // No personal-workspace path is probed any more.
        assert!(resolve_bin(&|_| None, home, cwd, &|p| {
            p == Path::new("/home/u/tmp/abstractframework/.venv/bin/abstractcore")
        })
        .is_none());

        // Nothing anywhere: honest None.
        assert!(resolve_bin(&|_| None, home, cwd, &|_| false).is_none());
    }

    #[test]
    fn error_line_prefers_the_cli_error() {
        let out = "some noise\n❌ Error: Unknown provider 'x'\nmore";
        assert_eq!(error_line(out, ""), "❌ Error: Unknown provider 'x'");
        assert_eq!(
            error_line("", "Traceback...\nValueError: boom"),
            "ValueError: boom"
        );
        assert_eq!(error_line("", ""), "(no output)");
    }

    /// Subprocess mechanics against real processes (no network, no
    /// abstractcore needed): /bin/echo emits JSON; a sleep overruns the
    /// deadline and is killed.
    #[test]
    fn run_json_parses_and_times_out() {
        let echo = CoreCli::new(PathBuf::from("/bin/echo"));
        let out = echo
            .run_json(&["{\"ok\": true}"], Duration::from_secs(5))
            .unwrap();
        assert_eq!(out.value.get("ok").and_then(Value::as_bool), Some(true));
        assert!(out.fallback_warnings.is_empty());

        let sleep = CoreCli::new(PathBuf::from("/bin/sleep"));
        let err = sleep
            .run_json(&["5"], Duration::from_millis(200))
            .unwrap_err();
        assert_eq!(err.kind, CliErrorKind::Timeout);

        let missing = CoreCli::new(PathBuf::from("/nonexistent/bin"));
        let err = missing.run_json(&[], Duration::from_secs(1)).unwrap_err();
        assert_eq!(err.kind, CliErrorKind::Spawn);
    }

    /// The streaming download verb prints `host_job_v1` NDJSON progress
    /// and the final job LAST; only that last line is the answer. A
    /// failed job exits 1 and its own error text is surfaced.
    #[test]
    fn run_json_last_takes_the_final_ndjson_line() {
        let sh = CoreCli::new(PathBuf::from("/bin/sh"));
        let ok = sh
            .run_json_last(
                &[
                    "-c",
                    r#"echo '{"schema":"host_job_v1","status":"running","percent":10.0}'
echo '{"schema":"host_job_v1","status":"running","percent":90.0}'
echo '{"schema":"host_job_v1","status":"completed","ok":true,"results":[{"status":"downloaded","message":"done"}]}'"#,
                ],
                Duration::from_secs(5),
            )
            .unwrap();
        assert_eq!(ok.value["status"], "completed");
        assert_eq!(ok.value["results"][0]["status"], "downloaded");

        // The old one-document reader would choke on exactly this stdout.
        assert_eq!(
            sh.run_json(
                &["-c", "echo '{\"a\":1}'; echo '{\"a\":2}'"],
                Duration::from_secs(5)
            )
            .unwrap_err()
            .kind,
            CliErrorKind::BadJson
        );

        let failed = sh
            .run_json_last(
                &[
                    "-c",
                    r#"echo '{"schema":"host_job_v1","status":"running"}'
echo '{"schema":"host_job_v1","status":"failed","error":"pull failed: manifest unknown"}'
exit 1"#,
                ],
                Duration::from_secs(5),
            )
            .unwrap_err();
        assert_eq!(failed.kind, CliErrorKind::Exit(1));
        assert!(failed.to_string().contains("manifest unknown"), "{failed}");

        let empty = sh
            .run_json_last(&["-c", "echo not json"], Duration::from_secs(5))
            .unwrap_err();
        assert_eq!(empty.kind, CliErrorKind::BadJson);
    }

    /// The P1-1 signal lane: an exit-0 run whose stderr carries a
    /// `#FALLBACK` line surfaces it — the one honest signal Python
    /// gives when it refuses the config file while answering ok:true.
    #[test]
    fn exit_zero_stderr_fallback_is_surfaced() {
        let sh = CoreCli::new(PathBuf::from("/bin/sh"));
        let out = sh
            .run_json(
                &[
                    "-c",
                    "echo '#FALLBACK abstractcore config could not be parsed; \
                     falling back to DEFAULTS' >&2; echo '{\"ok\": true}'",
                ],
                Duration::from_secs(5),
            )
            .unwrap();
        assert_eq!(out.value.get("ok").and_then(Value::as_bool), Some(true));
        assert_eq!(out.fallback_warnings.len(), 1);
        assert!(out.fallback_warnings[0].contains("falling back to DEFAULTS"));
    }
}