Skip to main content

locode_exec/
lib.rs

1//! locode-exec — the minimal headless CLI (Task 14, ADR-0009), as a library.
2//!
3//! The crate ships both a binary (the stock CLI) and this lib target so
4//! downstream binary crates can reuse the *entire* CLI — flags, session
5//! assembly, stdout discipline, exit codes — while injecting custom providers
6//! (ADR-0015):
7//!
8//! ```no_run
9//! use locode_exec::{ProviderRegistry, main_with};
10//!
11//! fn main() -> std::process::ExitCode {
12//!     main_with(ProviderRegistry::builtin() /* .register("my-wire", …) */)
13//! }
14//! ```
15//!
16//! Stdout discipline: stdout carries exactly one machine-readable artifact
17//! (the JSON report, the final message, or the JSONL event stream — by
18//! `--output-format`), enforced structurally: the workspace denies
19//! `print_stdout`/`print_stderr`, and the ONLY allows live in `output.rs`
20//! (Codex-exec's pattern). All diagnostics go to stderr; exit codes map the
21//! run's terminal status (0 = structured, 1 = fatal, 2 = usage via clap).
22
23use std::process::ExitCode;
24
25use clap::Parser;
26
27pub mod cli;
28mod logging;
29mod output;
30pub mod run;
31#[cfg(unix)]
32mod signal;
33
34pub use locode_core::ProviderRegistry;
35
36/// Parse the CLI, install logging, and drive one session to its exit code —
37/// the whole binary, minus `fn main`. Custom providers come in through
38/// `registry`; the stock binary passes [`ProviderRegistry::builtin`].
39#[must_use]
40// By-value on purpose: the downstream `fn main` is a single expression
41// (`main_with(builtin().register(…))`) with no borrow to scope.
42#[allow(clippy::needless_pass_by_value)]
43pub fn main_with(registry: ProviderRegistry) -> ExitCode {
44    let cli = cli::Cli::parse(); // clap usage errors exit 2 on their own
45    logging::init();
46
47    // `ExitCode` return (not `process::exit`) so buffered stdout is flushed —
48    // the "exactly one JSON document" contract survives (plan §3.2).
49    let runtime = match tokio::runtime::Builder::new_multi_thread()
50        .enable_all()
51        .build()
52    {
53        Ok(rt) => rt,
54        Err(e) => {
55            output::error_line(&format!("tokio runtime: {e}"));
56            return ExitCode::from(1);
57        }
58    };
59    match runtime.block_on(run::run(cli, &registry)) {
60        Ok(code) => code,
61        Err(pre_run) => {
62            // Config/setup failed before a run existed: no report, exit 1
63            // (Codex's pre-run pattern). Never a partial report on stdout.
64            output::error_line(&pre_run.0);
65            ExitCode::from(1)
66        }
67    }
68}