use std::{fmt::Write as _, path::PathBuf};
use agent_harness_adapter_core::{Action, InstallOptions, Item, Scope, State, harness};
use schemars::JsonSchema;
use serde::Serialize;
use crate::{Error, RepoRoot, Result, config, harness::SokfTool};
pub const ALL_HARNESSES: &str = "all";
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct HarnessDirs {
pub repo: Option<RepoRoot>,
pub home: Option<PathBuf>,
}
impl HarnessDirs {
pub fn repo(root: RepoRoot) -> Self {
HarnessDirs {
repo: Some(root),
home: None,
}
}
#[must_use]
pub fn home(mut self, home: impl Into<PathBuf>) -> Self {
self.home = Some(home.into());
self
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HarnessOptions {
pub harnesses: Vec<String>,
pub scope: Scope,
pub force: Vec<String>,
}
impl HarnessOptions {
pub fn new<I: IntoIterator<Item = S>, S: Into<String>>(harnesses: I, scope: Scope) -> Self {
HarnessOptions {
harnesses: harnesses.into_iter().map(Into::into).collect(),
scope,
force: Vec::new(),
}
}
#[must_use]
pub fn force<I: IntoIterator<Item = S>, S: Into<String>>(mut self, parts: I) -> Self {
self.force = parts.into_iter().map(Into::into).collect();
self
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)]
#[schemars(rename = "Part")]
pub struct PartResult {
pub part: String,
pub state: State,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[schemars(with = "Action")]
pub action: Option<Action>,
pub path: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[schemars(with = "String")]
pub by: Option<String>,
}
impl PartResult {
pub fn verb(&self) -> &'static str {
self.action
.map_or_else(|| self.state.as_str(), Action::as_str)
}
pub fn to_line(&self) -> String {
match &self.by {
Some(by) => format!("{:<7} {} ({}, by {by})", self.verb(), self.path, self.part),
None => format!("{:<7} {} ({})", self.verb(), self.path, self.part),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)]
pub struct HarnessResult {
pub harness: String,
pub parts: Vec<PartResult>,
pub unsupported: Vec<Item>,
pub notes: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)]
#[schemars(title = "sokf harness report")]
pub struct HarnessReport {
pub scope: Scope,
pub harnesses: Vec<HarnessResult>,
pub warnings: Vec<String>,
}
impl HarnessReport {
pub fn harness(&self, id: &str) -> Option<&HarnessResult> {
self.harnesses.iter().find(|h| h.harness == id)
}
pub fn to_text(&self) -> String {
let scope = match self.scope {
Scope::Project => String::new(),
other => format!(" --scope {other}"),
};
let mut out = String::new();
for h in &self.harnesses {
let _ = writeln!(out, "{}:", h.harness);
for p in &h.parts {
let _ = writeln!(out, " {}", p.to_line());
if p.state == State::Edited && p.action.is_none() {
let _ = writeln!(
out,
" next: `sokf harness diff {h}{scope}` shows the edit, and `sokf harness install {h}{scope} --force {p}` overwrites it",
h = h.harness,
p = p.part
);
}
}
if !h.unsupported.is_empty() {
let items: Vec<&str> = h.unsupported.iter().map(|i| i.as_str()).collect();
let _ = writeln!(out, " unsupported: {}", items.join(", "));
}
for n in &h.notes {
let _ = writeln!(out, " note: {n}");
}
}
for w in &self.warnings {
let _ = writeln!(out, "warning: {w}");
}
out
}
}
pub fn harness_ids(names: &[String]) -> Vec<String> {
let mut out: Vec<String> = Vec::new();
for name in names {
let ids = if name == ALL_HARNESSES {
harness::builtin()
.iter()
.map(|h| h.id().to_string())
.collect()
} else {
vec![name.clone()]
};
for id in ids {
if !out.contains(&id) {
out.push(id);
}
}
}
out
}
pub(super) fn shown(scope: Scope, path: &str) -> String {
if path.starts_with('/') || path.starts_with('~') {
return path.to_string();
}
match scope {
Scope::User => format!("~/{path}"),
_ => format!("/{path}"),
}
}
pub(super) fn tool(dirs: &HarnessDirs, scope: Scope) -> Result<SokfTool> {
let (config_root, prefix) = if scope == Scope::User {
let home = dirs
.home
.clone()
.ok_or_else(|| Error::Harness("the user scope needs the home directory".into()))?;
(RepoRoot::new(home), "~")
} else {
let repo = dirs
.repo
.clone()
.ok_or_else(|| Error::Harness(format!("the {scope} scope needs a repository")))?;
(repo, "")
};
let config = config::read_lenient(&config_root).map_err(|e| match e {
Error::Init(m) => Error::Harness(format!("{prefix}{m}")),
other => other,
})?;
Ok(SokfTool::new(
dirs.repo.as_ref().map(|r| r.as_path().to_path_buf()),
dirs.home.clone(),
config.hook_commands,
))
}
pub(super) fn refusal(scope: Scope) -> impl Fn(agent_harness_adapter_core::Error) -> Error {
move |e| match e {
agent_harness_adapter_core::Error::File { file, message } => {
Error::Harness(format!("{}: {message}", shown(scope, &file)))
}
other => other.into(),
}
}
pub(super) fn report(result: agent_harness_adapter_core::InstallResult) -> HarnessReport {
let scope = result.scope;
HarnessReport {
scope,
harnesses: result
.harnesses
.into_iter()
.map(|h| HarnessResult {
harness: h.harness,
parts: h
.parts
.into_iter()
.map(|p| PartResult {
path: shown(scope, &p.path),
part: p.part,
state: p.state,
action: p.action,
by: p.by,
})
.collect(),
unsupported: h.unsupported,
notes: h.notes,
})
.collect(),
warnings: result.warnings,
}
}
pub fn install(dirs: &HarnessDirs, opts: &HarnessOptions) -> Result<HarnessReport> {
let tool = tool(dirs, opts.scope)?;
refuse_forced_off_parts(&tool, opts)?;
let kit_opts = InstallOptions::new(harness_ids(&opts.harnesses), opts.scope)
.force_parts(opts.force.iter().cloned());
Ok(report(
agent_harness_adapter_core::install(&tool, &kit_opts).map_err(refusal(opts.scope))?,
))
}
fn refuse_forced_off_parts(tool: &SokfTool, opts: &HarnessOptions) -> Result<()> {
if opts.force.is_empty() {
return Ok(());
}
let store = tool.declined_at(opts.scope).map_err(refusal(opts.scope))?;
for id in harness_ids(&opts.harnesses) {
let runs_hooks = harness::find(&id).is_some_and(|h| !h.hook_events().is_empty());
let without = store.without(&id).map_err(refusal(opts.scope))?;
for part in store.off_by_default(&id).map_err(refusal(opts.scope))? {
if (part == "hooks" && !runs_hooks) || without.contains(&part) {
continue;
}
if opts.force.contains(&part) {
return Err(Error::Harness(format!(
"harness `{id}` installs `{part}` only when `with` lists it; add `with = [\"{part}\"]` under `[harness.{id}]` in {} to install it",
store.shown()
)));
}
}
}
Ok(())
}
pub fn status(dirs: &HarnessDirs, harnesses: &[String], scope: Scope) -> Result<HarnessReport> {
let tool = tool(dirs, scope)?;
Ok(report(
agent_harness_adapter_core::status(&tool, harness_ids(harnesses), scope)
.map_err(refusal(scope))?,
))
}
pub fn diff(dirs: &HarnessDirs, harnesses: &[String], scope: Scope) -> Result<String> {
let tool = tool(dirs, scope)?;
let edits = agent_harness_adapter_core::edits(&tool, harness_ids(harnesses), scope)
.map_err(refusal(scope))?;
let mut out = String::new();
for e in &edits {
out.push_str(&crate::git::diff(&e.path, &e.expected, &e.found).map_err(Error::Harness)?);
}
Ok(out)
}
pub(super) fn installed_status(
tool: &SokfTool,
scope: Scope,
) -> Result<Option<agent_harness_adapter_core::InstallResult>> {
let installed = agent_harness_adapter_core::installed(tool, scope).map_err(refusal(scope))?;
if installed.is_empty() {
return Ok(None);
}
agent_harness_adapter_core::status(tool, &installed, scope)
.map(Some)
.map_err(refusal(scope))
}
#[cfg(test)]
mod tests {
use std::fs;
use super::*;
fn temp(name: &str) -> PathBuf {
crate::test_support::fresh_dir(&format!("harness-api-{name}"))
}
fn opts(force: &[&str]) -> HarnessOptions {
HarnessOptions::new(["claude"], Scope::Project).force(force.iter().copied())
}
fn decline(dir: &std::path::Path, parts: &str) {
fs::create_dir_all(dir.join(".sokf")).unwrap();
fs::write(dir.join(".sokf/config.toml"), declining(parts)).unwrap();
}
fn declining(parts: &str) -> String {
format!("[harness.claude]\nwith = [\"hooks\"]\nwithout = [{parts}]\n")
}
fn verbs(r: &HarnessReport) -> Vec<&str> {
r.harnesses[0].parts.iter().map(PartResult::verb).collect()
}
#[test]
fn all_names_every_harness_once() {
let names =
|n: &[&str]| harness_ids(&n.iter().map(ToString::to_string).collect::<Vec<_>>());
assert_eq!(names(&["codex", "claude", "codex"]), ["codex", "claude"]);
let all = names(&["pi", "all"]);
assert_eq!(all[0], "pi");
assert_eq!(all.len(), harness::builtin().len());
assert_eq!(
shown(Scope::User, ".claude/settings.json"),
"~/.claude/settings.json"
);
assert_eq!(
shown(Scope::Local, ".claude/settings.local.json"),
"/.claude/settings.local.json"
);
assert_eq!(
shown(Scope::User, "~/.sokf/config.toml"),
"~/.sokf/config.toml"
);
}
#[test]
fn refuses_before_any_write() {
let dir = temp("refuse");
let dirs = HarnessDirs::repo(RepoRoot::new(dir.clone()));
let e = install(&dirs, &HarnessOptions::new(["cline"], Scope::Project)).unwrap_err();
assert_eq!(e.to_string(), "harness: no harness named `cline`");
let e = install(&dirs, &opts(&["mcp"])).unwrap_err();
assert_eq!(
e.to_string(),
"harness: harness `claude` has no part named `mcp`"
);
let e = install(&dirs, &HarnessOptions::new(["cursor"], Scope::Local)).unwrap_err();
assert_eq!(
e.to_string(),
"harness: harness `cursor` has no local scope"
);
let e = status(&dirs, &["claude".into()], Scope::User).unwrap_err();
assert_eq!(
e.to_string(),
"harness: the user scope needs the home directory"
);
assert!(status(&dirs, &["cline".into()], Scope::Project).is_err());
fs::create_dir_all(dir.join(".sokf")).unwrap();
fs::write(dir.join(".sokf/config.toml"), "[knowledge\n").unwrap();
let e = install(&dirs, &opts(&[])).unwrap_err();
assert!(
e.to_string().starts_with("harness: /.sokf/config.toml: "),
"{e}"
);
fs::remove_file(dir.join(".sokf/config.toml")).unwrap();
fs::write(dir.join(".sokf/harness.toml"), "x = [\n").unwrap();
let e = install(&dirs, &opts(&[])).unwrap_err();
assert!(
e.to_string().starts_with("harness: /.sokf/harness.toml: "),
"{e}"
);
fs::remove_file(dir.join(".sokf/harness.toml")).unwrap();
fs::create_dir_all(dir.join(".claude")).unwrap();
fs::write(dir.join(".claude/settings.json"), "{ nope").unwrap();
let e = install(&dirs, &opts(&[])).unwrap_err();
assert!(e.to_string().contains("does not parse"), "{e}");
assert!(
e.to_string()
.starts_with("harness: /.claude/settings.json: "),
"{e}"
);
assert!(!dir.join(".claude/skills").exists());
assert!(!dir.join("CLAUDE.md").exists());
assert!(!dir.join(".sokf/harness.toml").exists());
fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn the_verbs_follow_the_states() {
let dir = temp("verbs");
let dirs = HarnessDirs::repo(RepoRoot::new(dir.clone()));
decline(&dir, "\"hooks\"");
let first = install(&dirs, &opts(&[])).unwrap();
assert_eq!(verbs(&first), ["created", "created", "skipped", "created"]);
let parts = &first.harnesses[0].parts;
assert_eq!(parts[0].state, State::Absent);
assert_eq!(parts[0].action, Some(Action::Created));
assert_eq!(parts[0].path, "/CLAUDE.md");
assert_eq!(parts[1].path, "/.claude/skills");
let second = install(&dirs, &opts(&[])).unwrap();
assert_eq!(verbs(&second), ["current", "current", "skipped", "current"]);
assert!(second.harnesses[0].parts.iter().all(|p| p.action.is_none()));
let record = fs::read_to_string(dir.join(".sokf/harness.toml")).unwrap();
assert!(record.contains("skills = \"fnv1a64:"), "{record}");
assert!(!record.contains("hooks"), "{record}");
assert_eq!(
fs::read_to_string(dir.join(".sokf/config.toml")).unwrap(),
declining("\"hooks\"")
);
let claude_md = fs::read_to_string(dir.join("CLAUDE.md")).unwrap();
fs::write(
dir.join("CLAUDE.md"),
claude_md.replace("read the", "ignore the"),
)
.unwrap();
fs::write(dir.join(".claude/skills/sokf/SKILL.md"), "mine\n").unwrap();
let third = install(&dirs, &opts(&[])).unwrap();
assert_eq!(verbs(&third), ["edited", "edited", "skipped", "current"]);
assert_eq!(
fs::read_to_string(dir.join(".claude/skills/sokf/SKILL.md")).unwrap(),
"mine\n"
);
let skill = install(&dirs, &opts(&["skills"])).unwrap();
assert_eq!(verbs(&skill), ["edited", "rewrote", "skipped", "current"]);
assert!(
fs::read_to_string(dir.join("CLAUDE.md"))
.unwrap()
.contains("ignore the")
);
let before = fs::read_to_string(dir.join(".sokf/harness.toml")).unwrap();
let e = install(&dirs, &opts(&["hooks"])).unwrap_err();
assert_eq!(
e.to_string(),
"harness: harness `claude` declines `hooks` in /.sokf/config.toml; remove it from `without` there to force it"
);
assert_eq!(
fs::read_to_string(dir.join(".sokf/harness.toml")).unwrap(),
before
);
let forced = install(&dirs, &opts(&["all"])).unwrap();
assert_eq!(verbs(&forced), ["updated", "current", "skipped", "current"]);
assert_eq!(forced.harnesses[0].parts[0].state, State::Edited);
let st = status(&dirs, &["claude".into()], Scope::Project).unwrap();
assert_eq!(verbs(&st), ["current", "current", "skipped", "current"]);
assert_eq!(
fs::read_to_string(dir.join(".sokf/config.toml")).unwrap(),
declining("\"hooks\"")
);
fs::write(dir.join(".sokf/config.toml"), declining("")).unwrap();
let st = status(&dirs, &["claude".into()], Scope::Project).unwrap();
assert_eq!(st.harnesses[0].parts[2].verb(), "absent");
let fourth = install(&dirs, &opts(&[])).unwrap();
assert_eq!(fourth.harnesses[0].parts[2].verb(), "updated");
let record = fs::read_to_string(dir.join(".sokf/harness.toml")).unwrap();
assert!(record.contains("hooks = \"fnv1a64:"), "{record}");
decline(&dir, "\"hooks\"");
let fifth = install(&dirs, &opts(&[])).unwrap();
assert_eq!(fifth.harnesses[0].parts[2].verb(), "skipped");
assert_eq!(
fs::read_to_string(dir.join(".sokf/harness.toml")).unwrap(),
record
);
fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn diff_gives_a_patch_for_each_edited_file_and_writes_nothing() {
let dir = temp("diff");
let dirs = HarnessDirs::repo(RepoRoot::new(dir.clone()));
let claude = ["claude".to_string()];
install(&dirs, &opts(&[])).unwrap();
assert_eq!(diff(&dirs, &claude, Scope::Project).unwrap(), "");
let skill = dir.join(".claude/skills/sokf/SKILL.md");
let text = fs::read_to_string(&skill).unwrap();
fs::write(&skill, format!("{text}mine\n")).unwrap();
let patch = diff(&dirs, &claude, Scope::Project).unwrap();
assert!(
patch.starts_with(
"diff --git a/.claude/skills/sokf/SKILL.md b/.claude/skills/sokf/SKILL.md\n"
),
"{patch}"
);
assert!(patch.contains("\n+mine\n"), "{patch}");
assert_eq!(fs::read_to_string(&skill).unwrap(), format!("{text}mine\n"));
let st = status(&dirs, &claude, Scope::Project).unwrap().to_text();
assert!(
st.contains(" next: `sokf harness diff claude` shows the edit, and `sokf harness install claude --force skills` overwrites it\n"),
"{st}"
);
fs::remove_dir_all(&dir).unwrap();
}
}