1use std::{fmt::Write as _, path::PathBuf};
7
8use agent_harness_adapter_core::{Action, InstallOptions, Item, Scope, State, harness};
9use schemars::JsonSchema;
10use serde::Serialize;
11
12use crate::{
13 Error, RepoRoot, Result, config,
14 harness::{SokfTool, unvouched},
15};
16
17pub const ALL_HARNESSES: &str = "all";
19
20#[derive(Debug, Clone, Default, PartialEq, Eq)]
22pub struct HarnessDirs {
23 pub repo: Option<RepoRoot>,
25 pub home: Option<PathBuf>,
28}
29
30impl HarnessDirs {
31 pub fn repo(root: RepoRoot) -> Self {
33 HarnessDirs {
34 repo: Some(root),
35 home: None,
36 }
37 }
38
39 #[must_use]
41 pub fn home(mut self, home: impl Into<PathBuf>) -> Self {
42 self.home = Some(home.into());
43 self
44 }
45}
46
47#[derive(Debug, Clone, PartialEq, Eq)]
49pub struct HarnessOptions {
50 pub harnesses: Vec<String>,
52 pub scope: Scope,
54 pub force: Vec<String>,
57}
58
59impl HarnessOptions {
60 pub fn new<I: IntoIterator<Item = S>, S: Into<String>>(harnesses: I, scope: Scope) -> Self {
63 HarnessOptions {
64 harnesses: harnesses.into_iter().map(Into::into).collect(),
65 scope,
66 force: Vec::new(),
67 }
68 }
69
70 #[must_use]
73 pub fn force<I: IntoIterator<Item = S>, S: Into<String>>(mut self, parts: I) -> Self {
74 self.force = parts.into_iter().map(Into::into).collect();
75 self
76 }
77}
78
79#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)]
83#[schemars(rename = "Part")]
84pub struct PartResult {
85 pub part: String,
87 pub state: State,
90 #[serde(default, skip_serializing_if = "Option::is_none")]
94 #[schemars(with = "Action")]
95 pub action: Option<Action>,
96 pub path: String,
101 #[serde(default, skip_serializing_if = "Option::is_none")]
104 #[schemars(with = "String")]
105 pub by: Option<String>,
106}
107impl PartResult {
110 pub fn verb(&self) -> &'static str {
113 self.action
114 .map_or_else(|| self.state.as_str(), Action::as_str)
115 }
116
117 pub fn to_line(&self) -> String {
121 match &self.by {
122 Some(by) => format!("{:<7} {} ({}, by {by})", self.verb(), self.path, self.part),
123 None => format!("{:<7} {} ({})", self.verb(), self.path, self.part),
124 }
125 }
126}
127
128#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)]
130pub struct HarnessResult {
131 pub harness: String,
133 pub parts: Vec<PartResult>,
135 pub unsupported: Vec<Item>,
138 pub notes: Vec<String>,
140}
141
142#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)]
146#[schemars(title = "sokf harness report")]
147pub struct HarnessReport {
148 pub scope: Scope,
150 pub harnesses: Vec<HarnessResult>,
152 pub warnings: Vec<String>,
155}
156
157impl HarnessReport {
158 pub fn harness(&self, id: &str) -> Option<&HarnessResult> {
160 self.harnesses.iter().find(|h| h.harness == id)
161 }
162
163 pub fn to_text(&self) -> String {
169 let scope = match self.scope {
170 Scope::Project => String::new(),
171 other => format!(" --scope {other}"),
172 };
173 let mut out = String::new();
174 for h in &self.harnesses {
175 let _ = writeln!(out, "{}:", h.harness);
176 for p in &h.parts {
177 let _ = writeln!(out, " {}", p.to_line());
178 if p.state == State::Edited && p.action.is_none() {
179 let _ = writeln!(
180 out,
181 " next: `sokf harness diff {h}{scope}` shows the edit, and `sokf harness install {h}{scope} --force {p}` overwrites it",
182 h = h.harness,
183 p = p.part
184 );
185 }
186 }
187 if !h.unsupported.is_empty() {
188 let items: Vec<&str> = h.unsupported.iter().map(|i| i.as_str()).collect();
189 let _ = writeln!(out, " unsupported: {}", items.join(", "));
190 }
191 for n in &h.notes {
192 let _ = writeln!(out, " note: {n}");
193 }
194 }
195 for w in &self.warnings {
196 let _ = writeln!(out, "warning: {w}");
197 }
198 out
199 }
200}
201
202pub fn harness_ids(names: &[String]) -> Vec<String> {
206 let mut out: Vec<String> = Vec::new();
207 for name in names {
208 let ids = if name == ALL_HARNESSES {
209 harness::builtin()
210 .iter()
211 .map(|h| h.id().to_string())
212 .collect()
213 } else {
214 vec![name.clone()]
215 };
216 for id in ids {
217 if !out.contains(&id) {
218 out.push(id);
219 }
220 }
221 }
222 out
223}
224
225pub(super) fn shown(scope: Scope, path: &str) -> String {
229 if path.starts_with('/') || path.starts_with('~') {
230 return path.to_string();
231 }
232 match scope {
233 Scope::User => format!("~/{path}"),
234 _ => format!("/{path}"),
235 }
236}
237
238pub(super) fn tool(dirs: &HarnessDirs, scope: Scope) -> Result<SokfTool> {
244 let (config_root, prefix) = if scope == Scope::User {
245 let home = dirs
246 .home
247 .clone()
248 .ok_or_else(|| Error::Harness("the user scope needs the home directory".into()))?;
249 (RepoRoot::new(home), "~")
250 } else {
251 let repo = dirs
252 .repo
253 .clone()
254 .ok_or_else(|| Error::Harness(format!("the {scope} scope needs a repository")))?;
255 (repo, "")
256 };
257 let config = config::read_lenient(&config_root).map_err(|e| match e {
258 Error::Init(m) => Error::Harness(format!("{prefix}{m}")),
259 other => other,
260 })?;
261 Ok(SokfTool::new(
262 dirs.repo.as_ref().map(|r| r.as_path().to_path_buf()),
263 dirs.home.clone(),
264 config.hook_commands,
265 ))
266}
267
268pub(super) fn refusal(scope: Scope) -> impl Fn(agent_harness_adapter_core::Error) -> Error {
271 move |e| match e {
272 agent_harness_adapter_core::Error::File { file, message } => {
273 Error::Harness(format!("{}: {message}", shown(scope, &file)))
274 }
275 other => other.into(),
276 }
277}
278
279pub(super) fn report(result: agent_harness_adapter_core::InstallResult) -> HarnessReport {
283 let scope = result.scope;
284 let mut warnings = result.warnings.clone();
285 for u in unvouched(&result) {
286 warnings[u.warning] = u.words(&shown(scope, &u.path));
287 }
288 HarnessReport {
289 scope,
290 harnesses: result
291 .harnesses
292 .into_iter()
293 .map(|h| HarnessResult {
294 harness: h.harness,
295 parts: h
296 .parts
297 .into_iter()
298 .map(|p| PartResult {
299 path: shown(scope, &p.path),
300 part: p.part,
301 state: p.state,
302 action: p.action,
303 by: p.by,
304 })
305 .collect(),
306 unsupported: h.unsupported,
307 notes: h.notes,
308 })
309 .collect(),
310 warnings,
311 }
312}
313
314pub fn install(dirs: &HarnessDirs, opts: &HarnessOptions) -> Result<HarnessReport> {
360 let tool = tool(dirs, opts.scope)?;
361 refuse_forced_off_parts(&tool, opts)?;
362 let kit_opts = InstallOptions::new(harness_ids(&opts.harnesses), opts.scope)
363 .force_parts(opts.force.iter().cloned());
364 Ok(report(
365 agent_harness_adapter_core::install(&tool, &kit_opts).map_err(refusal(opts.scope))?,
366 ))
367}
368
369fn refuse_forced_off_parts(tool: &SokfTool, opts: &HarnessOptions) -> Result<()> {
374 if opts.force.is_empty() {
375 return Ok(());
376 }
377 let store = tool.declined_at(opts.scope).map_err(refusal(opts.scope))?;
378 for id in harness_ids(&opts.harnesses) {
379 let runs_hooks = harness::find(&id).is_some_and(|h| !h.hook_events().is_empty());
380 let without = store.without(&id).map_err(refusal(opts.scope))?;
383 for part in store.off_by_default(&id).map_err(refusal(opts.scope))? {
384 if (part == "hooks" && !runs_hooks) || without.contains(&part) {
385 continue;
386 }
387 if opts.force.contains(&part) {
388 return Err(Error::Harness(format!(
389 "harness `{id}` installs `{part}` only when `with` lists it; add `with = [\"{part}\"]` under `[harness.{id}]` in {} to install it",
390 store.shown()
391 )));
392 }
393 }
394 }
395 Ok(())
396}
397
398pub fn status(dirs: &HarnessDirs, harnesses: &[String], scope: Scope) -> Result<HarnessReport> {
404 let tool = tool(dirs, scope)?;
405 Ok(report(
406 agent_harness_adapter_core::status(&tool, harness_ids(harnesses), scope)
407 .map_err(refusal(scope))?,
408 ))
409}
410
411pub fn diff(dirs: &HarnessDirs, harnesses: &[String], scope: Scope) -> Result<String> {
421 let tool = tool(dirs, scope)?;
422 let edits = agent_harness_adapter_core::edits(&tool, harness_ids(harnesses), scope)
423 .map_err(refusal(scope))?;
424 let mut out = String::new();
425 for e in &edits {
426 out.push_str(&crate::git::diff(&e.path, &e.expected, &e.found).map_err(Error::Harness)?);
427 }
428 Ok(out)
429}
430
431pub(super) fn installed_status(
434 tool: &SokfTool,
435 scope: Scope,
436) -> Result<Option<agent_harness_adapter_core::InstallResult>> {
437 let installed = agent_harness_adapter_core::installed(tool, scope).map_err(refusal(scope))?;
438 if installed.is_empty() {
439 return Ok(None);
440 }
441 agent_harness_adapter_core::status(tool, &installed, scope)
442 .map(Some)
443 .map_err(refusal(scope))
444}
445
446#[cfg(test)]
447mod tests {
448 use std::fs;
449
450 use super::*;
451
452 fn temp(name: &str) -> PathBuf {
453 crate::test_support::fresh_dir(&format!("harness-api-{name}"))
454 }
455
456 fn opts(force: &[&str]) -> HarnessOptions {
457 HarnessOptions::new(["claude"], Scope::Project).force(force.iter().copied())
458 }
459
460 fn decline(dir: &std::path::Path, parts: &str) {
463 fs::create_dir_all(dir.join(".sokf")).unwrap();
464 fs::write(dir.join(".sokf/config.toml"), declining(parts)).unwrap();
465 }
466
467 fn declining(parts: &str) -> String {
468 format!("[harness.claude]\nwith = [\"hooks\"]\nwithout = [{parts}]\n")
469 }
470
471 fn verbs(r: &HarnessReport) -> Vec<&str> {
472 r.harnesses[0].parts.iter().map(PartResult::verb).collect()
473 }
474
475 #[test]
476 fn all_names_every_harness_once() {
477 let names =
478 |n: &[&str]| harness_ids(&n.iter().map(ToString::to_string).collect::<Vec<_>>());
479 assert_eq!(names(&["codex", "claude", "codex"]), ["codex", "claude"]);
480 let all = names(&["pi", "all"]);
481 assert_eq!(all[0], "pi");
482 assert_eq!(all.len(), harness::builtin().len());
483 assert_eq!(
484 shown(Scope::User, ".claude/settings.json"),
485 "~/.claude/settings.json"
486 );
487 assert_eq!(
488 shown(Scope::Local, ".claude/settings.local.json"),
489 "/.claude/settings.local.json"
490 );
491 assert_eq!(
492 shown(Scope::User, "~/.sokf/config.toml"),
493 "~/.sokf/config.toml"
494 );
495 }
496
497 #[test]
504 fn refuses_before_any_write() {
505 let dir = temp("refuse");
506 let dirs = HarnessDirs::repo(RepoRoot::new(dir.clone()));
507 let e = install(&dirs, &HarnessOptions::new(["cline"], Scope::Project)).unwrap_err();
508 assert_eq!(e.to_string(), "harness: no harness named `cline`");
509 let e = install(&dirs, &opts(&["mcp"])).unwrap_err();
510 assert_eq!(
511 e.to_string(),
512 "harness: harness `claude` has no part named `mcp`"
513 );
514 let e = install(&dirs, &HarnessOptions::new(["cursor"], Scope::Local)).unwrap_err();
515 assert_eq!(
516 e.to_string(),
517 "harness: harness `cursor` has no local scope"
518 );
519 let e = status(&dirs, &["claude".into()], Scope::User).unwrap_err();
520 assert_eq!(
521 e.to_string(),
522 "harness: the user scope needs the home directory"
523 );
524 assert!(status(&dirs, &["cline".into()], Scope::Project).is_err());
525 fs::create_dir_all(dir.join(".sokf")).unwrap();
526 fs::write(dir.join(".sokf/config.toml"), "[knowledge\n").unwrap();
527 let e = install(&dirs, &opts(&[])).unwrap_err();
528 assert!(
529 e.to_string().starts_with("harness: /.sokf/config.toml: "),
530 "{e}"
531 );
532 fs::remove_file(dir.join(".sokf/config.toml")).unwrap();
533 fs::write(dir.join(".sokf/harness.toml"), "x = [\n").unwrap();
534 let e = install(&dirs, &opts(&[])).unwrap_err();
535 assert!(
536 e.to_string().starts_with("harness: /.sokf/harness.toml: "),
537 "{e}"
538 );
539 fs::remove_file(dir.join(".sokf/harness.toml")).unwrap();
540 fs::create_dir_all(dir.join(".claude")).unwrap();
541 fs::write(dir.join(".claude/settings.json"), "{ nope").unwrap();
542 let e = install(&dirs, &opts(&[])).unwrap_err();
543 assert!(e.to_string().contains("does not parse"), "{e}");
544 assert!(
545 e.to_string()
546 .starts_with("harness: /.claude/settings.json: "),
547 "{e}"
548 );
549 assert!(!dir.join(".claude/skills").exists());
551 assert!(!dir.join("CLAUDE.md").exists());
552 assert!(!dir.join(".sokf/harness.toml").exists());
553 fs::remove_dir_all(&dir).unwrap();
554 }
555
556 #[test]
568 fn the_verbs_follow_the_states() {
569 let dir = temp("verbs");
570 let dirs = HarnessDirs::repo(RepoRoot::new(dir.clone()));
571 decline(&dir, "\"hooks\"");
572 let first = install(&dirs, &opts(&[])).unwrap();
573 assert_eq!(verbs(&first), ["created", "created", "skipped", "created"]);
574 let parts = &first.harnesses[0].parts;
575 assert_eq!(parts[0].state, State::Absent);
576 assert_eq!(parts[0].action, Some(Action::Created));
577 assert_eq!(parts[0].path, "/CLAUDE.md");
578 assert_eq!(parts[1].path, "/.claude/skills");
579 let second = install(&dirs, &opts(&[])).unwrap();
581 assert_eq!(verbs(&second), ["current", "current", "skipped", "current"]);
582 assert!(second.harnesses[0].parts.iter().all(|p| p.action.is_none()));
583 let record = fs::read_to_string(dir.join(".sokf/harness.toml")).unwrap();
584 assert!(record.contains("\n[claude.skills]\n"), "{record}");
585 assert!(!record.contains("hooks"), "{record}");
586 assert_eq!(
587 fs::read_to_string(dir.join(".sokf/config.toml")).unwrap(),
588 declining("\"hooks\"")
589 );
590 let claude_md = fs::read_to_string(dir.join("CLAUDE.md")).unwrap();
593 fs::write(
594 dir.join("CLAUDE.md"),
595 claude_md.replace("read the", "ignore the"),
596 )
597 .unwrap();
598 fs::write(dir.join(".claude/skills/sokf/SKILL.md"), "mine\n").unwrap();
599 let third = install(&dirs, &opts(&[])).unwrap();
600 assert_eq!(verbs(&third), ["edited", "edited", "skipped", "current"]);
601 assert_eq!(
602 fs::read_to_string(dir.join(".claude/skills/sokf/SKILL.md")).unwrap(),
603 "mine\n"
604 );
605 let skill = install(&dirs, &opts(&["skills"])).unwrap();
607 assert_eq!(verbs(&skill), ["edited", "rewrote", "skipped", "current"]);
608 assert!(
609 fs::read_to_string(dir.join("CLAUDE.md"))
610 .unwrap()
611 .contains("ignore the")
612 );
613 let before = fs::read_to_string(dir.join(".sokf/harness.toml")).unwrap();
615 let e = install(&dirs, &opts(&["hooks"])).unwrap_err();
616 assert_eq!(
617 e.to_string(),
618 "harness: harness `claude` declines `hooks` in /.sokf/config.toml; remove it from `without` there to force it"
619 );
620 assert_eq!(
621 fs::read_to_string(dir.join(".sokf/harness.toml")).unwrap(),
622 before
623 );
624 let forced = install(&dirs, &opts(&["all"])).unwrap();
626 assert_eq!(verbs(&forced), ["updated", "current", "skipped", "current"]);
627 assert_eq!(forced.harnesses[0].parts[0].state, State::Edited);
628 let st = status(&dirs, &["claude".into()], Scope::Project).unwrap();
629 assert_eq!(verbs(&st), ["current", "current", "skipped", "current"]);
630 assert_eq!(
632 fs::read_to_string(dir.join(".sokf/config.toml")).unwrap(),
633 declining("\"hooks\"")
634 );
635 fs::write(dir.join(".sokf/config.toml"), declining("")).unwrap();
638 let st = status(&dirs, &["claude".into()], Scope::Project).unwrap();
639 assert_eq!(st.harnesses[0].parts[2].verb(), "absent");
640 let fourth = install(&dirs, &opts(&[])).unwrap();
641 assert_eq!(fourth.harnesses[0].parts[2].verb(), "updated");
642 let record = fs::read_to_string(dir.join(".sokf/harness.toml")).unwrap();
643 assert!(record.contains("\nhooks = \""), "{record}");
644 decline(&dir, "\"hooks\"");
646 let fifth = install(&dirs, &opts(&[])).unwrap();
647 assert_eq!(fifth.harnesses[0].parts[2].verb(), "skipped");
648 assert_eq!(
649 fs::read_to_string(dir.join(".sokf/harness.toml")).unwrap(),
650 record
651 );
652 fs::remove_dir_all(&dir).unwrap();
653 }
654
655 #[test]
660 fn diff_gives_a_patch_for_each_edited_file_and_writes_nothing() {
661 let dir = temp("diff");
662 let dirs = HarnessDirs::repo(RepoRoot::new(dir.clone()));
663 let claude = ["claude".to_string()];
664 install(&dirs, &opts(&[])).unwrap();
665 assert_eq!(diff(&dirs, &claude, Scope::Project).unwrap(), "");
666 let skill = dir.join(".claude/skills/sokf/SKILL.md");
667 let text = fs::read_to_string(&skill).unwrap();
668 fs::write(&skill, format!("{text}mine\n")).unwrap();
669 let patch = diff(&dirs, &claude, Scope::Project).unwrap();
670 assert!(
671 patch.starts_with(
672 "diff --git a/.claude/skills/sokf/SKILL.md b/.claude/skills/sokf/SKILL.md\n"
673 ),
674 "{patch}"
675 );
676 assert!(patch.contains("\n+mine\n"), "{patch}");
677 assert_eq!(fs::read_to_string(&skill).unwrap(), format!("{text}mine\n"));
678 let st = status(&dirs, &claude, Scope::Project).unwrap().to_text();
680 assert!(
681 st.contains(" next: `sokf harness diff claude` shows the edit, and `sokf harness install claude --force skills` overwrites it\n"),
682 "{st}"
683 );
684 fs::remove_dir_all(&dir).unwrap();
685 }
686}