use std::path::{Path, PathBuf};
use std::time::Duration;
use serde_json::Value;
pub mod claude;
pub mod codex;
pub mod omp;
pub mod opencode;
pub mod sim;
pub mod wiring;
pub trait Harness: Sync {
fn name(&self) -> &'static str;
fn caps(&self) -> Caps;
fn wiring(&self) -> Wiring;
fn target(&self, home: &Path, var: &dyn Fn(&str) -> Option<PathBuf>) -> PathBuf;
fn probe(&self) -> Probe;
fn hidden(&self) -> bool {
false
}
fn normalise(&self, raw: Value) -> Value {
raw
}
fn checks(&self, _target: &Path) -> Vec<(Level, String)> {
Vec::new()
}
fn install_notes(&self) -> Vec<String> {
Vec::new()
}
fn sub_runs(&self, _home: &Path, _session: Option<&str>, _since: Option<i64>) -> Vec<Run> {
Vec::new()
}
}
#[derive(Debug, Clone, Default)]
pub struct SubAgent {
pub id: String,
pub parent: String,
pub label: String,
pub phase: String,
pub kind: String,
pub started: i64,
pub cwd: String,
pub prompt: String,
pub work: String,
pub final_text: String,
pub output: Option<Value>,
}
impl SubAgent {
pub fn called(&mut self, input: &Value) {
self.work.push_str(&format!("{input}\n"));
}
pub fn said(&mut self, t: &str) {
self.work.push_str(&format!("{t}\n"));
self.final_text = t.to_string();
}
}
#[derive(Debug, Clone, Default)]
pub struct Run {
pub id: String,
pub session: String,
pub name: String,
pub started: i64,
pub loose: bool,
pub agents: Vec<SubAgent>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Caps {
pub prompt_context: bool,
pub tool_context: bool,
pub early_delivery: bool,
pub question_dialog: bool,
pub transcript: Transcript,
pub deny_capture: bool,
pub sends_pid: bool,
pub stop_budget: Option<Duration>,
pub session_env: Option<&'static str>,
pub pid_env: Option<&'static str>,
pub drone_wake: DroneWake,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DroneWake {
Model,
Plugin,
Queue,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Transcript {
Claude,
None,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Wiring {
CommandHooks {
events: &'static [(&'static str, &'static str)],
timeouts: &'static [(&'static str, u64)],
retired: &'static [(&'static str, &'static str)],
through_links: bool,
},
AdapterFile { source: &'static str },
}
impl Wiring {
pub fn adapter(self) -> &'static str {
match self {
Wiring::AdapterFile { source } => source,
Wiring::CommandHooks { .. } => "",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Probe {
pub cli: &'static str,
pub tested: &'static str,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum Level {
Ok,
Warn,
Fail,
}
pub const DEFAULT_STOP_BUDGET: Duration = Duration::from_secs(60);
pub const TEST_ENV: &str = "BORG_TEST_HARNESS";
pub static ALL: &[&dyn Harness] = &[&claude::Claude, &omp::Omp, &opencode::Opencode, &codex::Codex, &sim::Sim];
pub fn by_name(name: &str) -> Option<&'static dyn Harness> {
let hidden_too = std::env::var_os(TEST_ENV).is_some();
ALL.iter().copied().find(|h| h.name() == name && (hidden_too || !h.hidden()))
}
pub fn visible() -> impl Iterator<Item = &'static dyn Harness> {
ALL.iter().copied().filter(|h| !h.hidden())
}
pub fn names(sep: &str) -> String {
visible().map(|h| h.name()).collect::<Vec<_>>().join(sep)
}
pub fn current() -> &'static dyn Harness {
named_current().unwrap_or(ALL[0])
}
pub fn named_current() -> Option<&'static dyn Harness> {
std::env::var("BORG_HARNESS").ok().and_then(|n| by_name(&n))
}
pub fn session_vars() -> Vec<(&'static str, &'static str)> {
ALL.iter().filter_map(|h| h.caps().session_env.map(|v| (v, h.name()))).collect()
}
pub fn env_sessions() -> Vec<(String, &'static str)> {
let var = |k: &str| std::env::var(k).ok().map(|v| v.trim().to_string()).filter(|v| !v.is_empty());
session_vars().into_iter().filter_map(|(k, h)| var(k).map(|v| (v, h))).collect()
}
pub fn env_pids() -> Vec<(u32, &'static str)> {
let pid = |k: &str| std::env::var(k).ok().and_then(|v| v.trim().parse::<u32>().ok());
ALL.iter().filter_map(|h| h.caps().pid_env.and_then(pid).map(|p| (p, h.name()))).collect()
}
pub fn transcript(caps: Caps, ev: &Value) -> Option<&str> {
match caps.transcript {
Transcript::Claude => ev.get("transcript_path").and_then(Value::as_str).filter(|t| !t.is_empty()),
Transcript::None => None,
}
}
pub fn work_so_far(caps: Caps, ev: &Value, turn_log: &Path, cap: usize) -> String {
if let Some(t) = transcript(caps, ev).filter(|t| std::fs::metadata(t).is_ok()) {
return claude::turn_so_far(t.as_ref(), cap);
}
let text = std::fs::read_to_string(turn_log).unwrap_or_default();
let n = text.chars().count();
text.chars().skip(n.saturating_sub(cap)).collect()
}
pub fn last_message(caps: Caps, ev: &Value) -> String {
match given(ev) {
Some(t) => t.to_string(),
None => claude::last_assistant_full(transcript(caps, ev).unwrap_or_default().as_ref()),
}
}
pub fn plan(caps: Caps, ev: &Value) -> String {
match given(ev) {
Some(t) => t.to_string(),
None => claude::last_assistant_text(transcript(caps, ev).unwrap_or_default().as_ref()),
}
}
fn given(ev: &Value) -> Option<&str> {
ev.get("last_assistant_message").and_then(Value::as_str).filter(|t| !t.trim().is_empty())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn caps_are_todays() {
let row = |n: &str| {
let c = by_name(n).unwrap().caps();
(c.prompt_context, c.tool_context, c.early_delivery, c.question_dialog, c.transcript, c.deny_capture, c.sends_pid)
};
assert_eq!(row("claude"), (true, true, true, true, Transcript::Claude, true, false));
for n in ["omp", "opencode"] {
assert_eq!(row(n), (true, true, false, false, Transcript::None, true, true), "{n}");
}
assert_eq!(row("codex"), (true, true, false, false, Transcript::None, false, false));
let budgets = [("claude", None), ("omp", None), ("opencode", None), ("codex", Some(90)), ("sim", None)];
let got: Vec<(&str, Option<u64>)> = ALL.iter().map(|h| (h.name(), h.caps().stop_budget.map(|d| d.as_secs()))).collect();
assert_eq!(got, budgets, "every harness's stop budget");
let Wiring::CommandHooks { timeouts, through_links, .. } = by_name("claude").unwrap().wiring() else { panic!("claude has command hooks") };
assert_eq!((timeouts, through_links), (&[("stop", 90)][..], true), "a timeout on the stop only");
}
#[test]
fn names_are_unique_and_found_and_sim_is_hidden() {
for h in visible() {
assert_eq!(by_name(h.name()).map(|x| x.name()), Some(h.name()));
}
assert_eq!(ALL.iter().filter(|h| ALL.iter().filter(|x| x.name() == h.name()).count() > 1).count(), 0);
assert_eq!(names("|"), "claude|omp|opencode|codex");
assert!(ALL.iter().any(|h| h.name() == "sim" && h.hidden()));
assert_eq!(by_name("sim").is_some(), std::env::var_os(TEST_ENV).is_some());
assert!(by_name("nope").is_none());
}
#[test]
fn the_transcript_is_read_only_where_the_harness_writes_one() {
let ev = serde_json::json!({"transcript_path": "/nonexistent/t.jsonl", "last_assistant_message": ""});
assert_eq!(transcript(by_name("claude").unwrap().caps(), &ev), Some("/nonexistent/t.jsonl"));
assert_eq!(transcript(by_name("omp").unwrap().caps(), &ev), None);
let msg = serde_json::json!({"last_assistant_message": "done"});
assert_eq!(last_message(by_name("opencode").unwrap().caps(), &msg), "done");
}
#[test]
fn a_plan_from_a_transcript_is_its_tail_and_a_given_message_is_whole() {
let dir = std::env::temp_dir().join(format!("borg-harness-plan-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let t = dir.join("t.jsonl");
let long = "x".repeat(2500);
let line = serde_json::json!({"type": "assistant", "message": {"content": [{"type": "text", "text": long}]}});
std::fs::write(&t, format!("{line}\n")).unwrap();
let caps = by_name("claude").unwrap().caps();
let ev = serde_json::json!({"transcript_path": t, "last_assistant_message": ""});
assert_eq!((last_message(caps, &ev).len(), plan(caps, &ev).len()), (2500, 2000));
let given = serde_json::json!({"transcript_path": t, "last_assistant_message": long});
assert_eq!(plan(caps, &given).len(), 2500, "the event's own message is the plan, whole");
let _ = std::fs::remove_dir_all(dir);
}
}