supercode-harness 0.4.14

The optional native Supercode agent and tool harness
Documentation
//! The controlled tier's substrate: one harness command, ready to run and
//! ready to narrate.
//!
//! Every controlled-tier noun (ORCH-18 scheduled jobs, ORCH-21 profiles, …)
//! mutates through the HARNESS'S OWN verb, executed as a subprocess. The three
//! mechanics that are identical for every one of them live here so each noun
//! implements only its own harness semantics:
//!
//! 1. **Narration.** [`HarnessCommand::narrate`] renders the exact argv that
//!    ran, with every credential as `<redacted>` — tokens are never printed,
//!    logged, or stored.
//! 2. **Execution.** [`HarnessCommand::run`] returns the harness's stdout on
//!    success and the harness's OWN stderr as the failure message, never a
//!    supercode-invented sentence.
//! 3. **Location.** [`harness_program`] finds the harness's executable from
//!    the compiled registry, with a `SUPERCODE_<HARNESS>_BIN` override so a
//!    fake CLI can stand in under test without touching PATH.

use std::process::Command;

/// Environment variable overriding the `hermes` executable (tests).
pub const HERMES_BIN_ENV: &str = "SUPERCODE_HERMES_BIN";

/// Test-only stand-in for the `SUPERCODE_*_BIN` override: thread-local, so a
/// test that points one harness at a fake CLI cannot leak that fake into the
/// sibling tests `cargo test` runs on other threads (process env is global).
#[cfg(test)]
thread_local! {
    pub(crate) static TEST_PROGRAM_OVERRIDE: std::cell::RefCell<Option<(String, String)>> =
        const { std::cell::RefCell::new(None) };
}
/// Environment variable overriding the `openclaw` executable (tests).
pub const OPENCLAW_BIN_ENV: &str = "SUPERCODE_OPENCLAW_BIN";

/// One argument of a harness command, tracking whether it is a secret.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum Arg {
    Plain(String),
    Secret,
}

/// A harness command, ready to run and ready to narrate.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct HarnessCommand {
    pub(crate) program: String,
    /// Rendered arguments; secrets are carried out of band.
    pub(crate) args: Vec<Arg>,
    /// The real value of each [`Arg::Secret`], in order.
    pub(crate) secrets: Vec<String>,
    pub(crate) env: Vec<(String, String)>,
}

impl HarnessCommand {
    pub(crate) fn new(program: impl Into<String>) -> Self {
        Self {
            program: program.into(),
            args: Vec::new(),
            secrets: Vec::new(),
            env: Vec::new(),
        }
    }

    pub(crate) fn arg(&mut self, value: impl Into<String>) -> &mut Self {
        self.args.push(Arg::Plain(value.into()));
        self
    }

    pub(crate) fn args<I: IntoIterator<Item = S>, S: Into<String>>(
        &mut self,
        values: I,
    ) -> &mut Self {
        for value in values {
            self.arg(value);
        }
        self
    }

    /// Push a credential: never rendered, never stored on the narration.
    pub(crate) fn secret(&mut self, value: impl Into<String>) -> &mut Self {
        self.args.push(Arg::Secret);
        self.secrets.push(value.into());
        self
    }

    pub(crate) fn env(&mut self, key: impl Into<String>, value: impl Into<String>) -> &mut Self {
        self.env.push((key.into(), value.into()));
        self
    }

    /// The narration: exactly what ran, with credentials as `<redacted>`.
    pub(crate) fn narrate(&self) -> String {
        let mut line = shell_quote(&self.program);
        for arg in &self.args {
            line.push(' ');
            match arg {
                Arg::Plain(value) => line.push_str(&shell_quote(value)),
                Arg::Secret => line.push_str("<redacted>"),
            }
        }
        line
    }

    /// Run it, returning stdout on success and a failure message carrying the
    /// harness's own stderr otherwise.
    pub(crate) fn run(&self) -> Result<String, String> {
        let mut secrets = self.secrets.iter();
        let mut command = Command::new(&self.program);
        for arg in &self.args {
            match arg {
                Arg::Plain(value) => command.arg(value),
                Arg::Secret => command.arg(secrets.next().expect("one secret per Arg::Secret")),
            };
        }
        for (key, value) in &self.env {
            command.env(key, value);
        }
        command.stdin(std::process::Stdio::null());
        let output = command
            .output()
            .map_err(|error| format!("`{}` could not be executed: {error}", self.narrate()))?;
        if output.status.success() {
            return Ok(String::from_utf8_lossy(&output.stdout).into_owned());
        }
        let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
        let stdout = String::from_utf8_lossy(&output.stdout).trim().to_string();
        let detail = if stderr.is_empty() { stdout } else { stderr };
        Err(format!(
            "`{}` failed ({}): {}",
            self.narrate(),
            output.status,
            if detail.is_empty() {
                "the harness printed nothing".to_string()
            } else {
                detail
            }
        ))
    }
}

pub(crate) fn shell_quote(value: &str) -> String {
    if !value.is_empty()
        && value
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || "-_./:@=+,".contains(c))
    {
        return value.to_string();
    }
    format!("'{}'", value.replace('\'', "'\\''"))
}

/// The harness's own executable.
///
/// The compiled registry names each harness's binary family in its runtime
/// launch (`hermes-acp`, `openclaw`); the mutating verbs live on the base CLI,
/// so an `-acp` bridge suffix is stripped. `SUPERCODE_HERMES_BIN` /
/// `SUPERCODE_OPENCLAW_BIN` override it so a fake CLI can stand in under test
/// without touching PATH.
///
/// `Err(None)` means the harness has no controlled-tier CLI at all, which each
/// noun words in its own vocabulary; `Err(Some(message))` is a registry gap.
pub(crate) fn harness_program(harness: &str) -> Result<String, Option<String>> {
    #[cfg(test)]
    if let Some(program) = TEST_PROGRAM_OVERRIDE.with(|slot| {
        slot.borrow()
            .as_ref()
            .filter(|(id, _)| id == harness)
            .map(|(_, program)| program.clone())
    }) {
        return Ok(program);
    }
    let variable = match harness {
        crate::HarnessId::HERMES => HERMES_BIN_ENV,
        crate::HarnessId::OPENCLAW => OPENCLAW_BIN_ENV,
        _ => return Err(None),
    };
    if let Some(over) = std::env::var_os(variable) {
        let over = over.to_string_lossy().trim().to_string();
        if !over.is_empty() {
            return Ok(over);
        }
    }
    let registry = crate::harness_support_registry();
    let program = registry
        .harnesses
        .iter()
        .find(|descriptor| descriptor.id.as_str() == harness)
        .and_then(|descriptor| descriptor.runtime.default_launch.as_ref())
        .map(|launch| launch.program.clone())
        .ok_or_else(|| {
            Some(format!(
                "the registry has no launch for `{harness}`, so its CLI cannot be located"
            ))
        })?;
    Ok(program.strip_suffix("-acp").unwrap_or(&program).to_string())
}