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
//! 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())
}