moadim 3.2.6

Loop engine for AI agents — routines over REST, MCP, and a built-in web UI
//! Tests for JSON shape, spawn, and coverage paths.

use std::io::{Read as _, Write as _};
use std::net::TcpListener;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::Duration;

use super::*;

const UNREACHABLE_ADDR: &str = "127.0.0.1:1";

struct EnvGuard {
    name: &'static str,
    previous: Option<std::ffi::OsString>,
}

impl EnvGuard {
    fn set(name: &'static str, value: &str) -> Self {
        let previous = std::env::var_os(name);
        // SAFETY: tests in this crate run single-threaded per binary.
        unsafe {
            std::env::set_var(name, value);
        }
        Self { name, previous }
    }
}

impl Drop for EnvGuard {
    fn drop(&mut self) {
        // SAFETY: single-threaded test execution.
        unsafe {
            match self.previous.take() {
                Some(value) => std::env::set_var(self.name, value),
                None => std::env::remove_var(self.name),
            }
        }
    }
}

fn temp_home(tag: &str) -> std::path::PathBuf {
    let dir = std::env::temp_dir().join(format!("moadim-cli-{tag}-{}", uuid::Uuid::new_v4()));
    std::fs::create_dir_all(&dir).expect("create temp home");
    dir
}

struct FakeServer {
    addr: String,
    alive: Arc<AtomicBool>,
    stop: Arc<AtomicBool>,
    handle: Option<std::thread::JoinHandle<()>>,
}

impl FakeServer {
    fn start(status: u16, body: String) -> Self {
        Self::start_with_liveness(status, body, true)
    }

    fn start_after(status: u16, body: String, delay: Duration) -> Self {
        let server = Self::start_with_liveness(status, body, false);
        let alive = Arc::clone(&server.alive);
        std::thread::spawn(move || {
            std::thread::sleep(delay);
            alive.store(true, Ordering::SeqCst);
        });
        server
    }

    fn start_with_liveness(status: u16, body: String, initial_alive: bool) -> Self {
        let listener = TcpListener::bind("127.0.0.1:0").expect("bind ephemeral port");
        let addr = listener.local_addr().expect("local addr").to_string();
        listener.set_nonblocking(true).expect("set nonblocking");
        let alive = Arc::new(AtomicBool::new(initial_alive));
        let stop = Arc::new(AtomicBool::new(false));
        let alive_loop = Arc::clone(&alive);
        let stop_loop = Arc::clone(&stop);
        let handle = std::thread::spawn(move || {
            let response = format!(
                "HTTP/1.1 {status} OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
                body.len()
            );
            while !stop_loop.load(Ordering::SeqCst) {
                match listener.accept() {
                    Ok((mut stream, _)) => {
                        let mut buf = [0_u8; 1024];
                        let _ = stream.read(&mut buf);
                        if alive_loop.load(Ordering::SeqCst) {
                            let _ = stream.write_all(response.as_bytes());
                        }
                    }
                    Err(ref err) if err.kind() == std::io::ErrorKind::WouldBlock => {
                        std::thread::sleep(Duration::from_millis(2));
                    }
                    Err(_) => break,
                }
            }
        });
        Self {
            addr,
            alive,
            stop,
            handle: Some(handle),
        }
    }
}

impl Drop for FakeServer {
    fn drop(&mut self) {
        self.stop.store(true, Ordering::SeqCst);
        if let Some(handle) = self.handle.take() {
            let _ = handle.join();
        }
    }
}

// ─── README `--json` shape drift guard ─────────────────────────────────────────
//
// The README documents the exact `--json` object shape for `status`/`cleanup`/`stop` as a
// script-facing stability promise (see the "Scripting" table). Nothing previously pinned those
// documented key sets to the *actual* keys the `*_json` formatters emit, so a field renamed, added,
// or removed in code (or in the README) could drift silently. The tests below parse the documented
// shape literal straight out of README.md and assert it names exactly the same keys the formatter
// produces; the exit-code half of the same contract is already locked by
// `status_reports_down_when_no_server`/`status_reports_running_with_pid` and their `stop`/`cleanup`
// counterparts.

/// Return the top-level object keys named by a `--json` shape literal, e.g. turn
/// `{"running":bool,"pid":N\|null,"address":"127.0.0.1:5784"}` into `["running", "pid", "address"]`.
/// The shapes documented in README.md never nest an object/array or embed a comma inside a string
/// value, so splitting on top-level commas and taking each field's pre-colon, quote-trimmed key is
/// sufficient (no JSON parser needed).
fn shape_keys(shape: &str) -> Vec<String> {
    shape
        .trim_start_matches('{')
        .trim_end_matches('}')
        .split(',')
        .map(|field| {
            field
                .split(':')
                .next()
                .unwrap_or_default()
                .trim()
                .trim_matches('"')
                .to_string()
        })
        .collect()
}

/// Extract the documented `--json` shape literal (the `{...}` text) from the README "Scripting"
/// table row whose first cell is `` `moadim <command> --json` ``.
fn readme_json_shape(command: &str) -> String {
    let readme = include_str!("../../README.md");
    let marker = format!("`moadim {command} --json`");
    let line = readme
        .lines()
        .find(|line| line.contains(&marker))
        .unwrap_or_else(|| panic!("README scripting table has no row for {marker}"));
    let start = line.find('{').expect("shape literal starts with `{`");
    let end = line[start..]
        .find('}')
        .map(|offset| start + offset)
        .expect("shape literal ends with `}`");
    line[start..=end].to_string()
}
include!("actual_keys_tests.rs");