Skip to main content

sokf_core/api/
harness.rs

1//! This module carries out `sokf harness install`, `sokf harness status`, and `sokf harness diff`
2//! (CLI-3), through `install`, `status`, and `edits` of agent-harness-adapter. It reads the config, presents sokf to the adapter
3//! as a `Tool`, and turns the adapter's result and refusals into sokf's report and errors, with
4//! paths from the repository root, or from the home directory at the user scope.
5
6use 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
17/// `ALL_HARNESSES` is the harness name that stands for every harness that sokf supports.
18pub const ALL_HARNESSES: &str = "all";
19
20/// The directories that `install` and `status` work in.
21#[derive(Debug, Clone, Default, PartialEq, Eq)]
22pub struct HarnessDirs {
23    /// The repository: the root of the project and local scopes.
24    pub repo: Option<RepoRoot>,
25    /// The home directory: the root of the user scope. At the project scope, a harness
26    /// can read a setting there.
27    pub home: Option<PathBuf>,
28}
29
30impl HarnessDirs {
31    /// `repo` returns the directories of the repository `root`, without a home directory.
32    pub fn repo(root: RepoRoot) -> Self {
33        HarnessDirs {
34            repo: Some(root),
35            home: None,
36        }
37    }
38
39    /// `home` returns the directories with the home directory `home`.
40    #[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/// The options of `install`.
48#[derive(Debug, Clone, PartialEq, Eq)]
49pub struct HarnessOptions {
50    /// The harness names, for example `claude`, or `all`.
51    pub harnesses: Vec<String>,
52    /// The scope: `project`, `user`, or `local`.
53    pub scope: Scope,
54    /// The parts that `--force` names, which `install` writes whatever their state, or `all`
55    /// for every part that the configuration doesn't decline. Empty without `--force`.
56    pub force: Vec<String>,
57}
58
59impl HarnessOptions {
60    /// `new` returns the options that install `harnesses` at `scope`, with the declined parts
61    /// in the configuration and without `--force`.
62    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    /// `force` writes `parts` whatever their state, or every part that the configuration
71    /// doesn't decline when `parts` holds `all`.
72    #[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// sokf:begin part-result
80/// One part of a harness.
81// sokf-implements: CLI-3_AC-61
82#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)]
83#[schemars(rename = "Part")]
84pub struct PartResult {
85    /// The name of the part, for example `skills` or `hooks`.
86    pub part: String,
87    /// The state in which the command found the part, before it wrote anything: `skipped`,
88    /// `shared`, `absent`, `current`, `stale`, or `edited`.
89    pub state: State,
90    /// For `install`, what the command did to the part: `created`, `rewrote`, or `updated`.
91    /// The key is absent when the command left the part as it found it, and always for
92    /// `status`.
93    #[serde(default, skip_serializing_if = "Option::is_none")]
94    #[schemars(with = "Action")]
95    pub action: Option<Action>,
96    /// The file or directory to which the command writes the part: a path from the
97    /// repository root, which starts with `/`, or at the user scope a path from the home
98    /// directory, which starts with `~/`. For a shared part, the location that another
99    /// harness writes.
100    pub path: String,
101    /// For a shared part, the harness whose part writes it. The key is absent for every
102    /// other part.
103    #[serde(default, skip_serializing_if = "Option::is_none")]
104    #[schemars(with = "String")]
105    pub by: Option<String>,
106}
107// sokf:end part-result
108
109impl PartResult {
110    /// `verb` returns the word that the text report shows for the part: the action, or else
111    /// the state.
112    pub fn verb(&self) -> &'static str {
113        self.action
114            .map_or_else(|| self.state.as_str(), Action::as_str)
115    }
116
117    /// `to_line` returns the part's line of the text report: the verb in a column seven
118    /// characters wide, the path, and the name of the part in parentheses, with the harness
119    /// that writes a shared part.
120    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/// The parts of one harness.
129#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)]
130pub struct HarnessResult {
131    /// The name of the harness, for example `claude`.
132    pub harness: String,
133    /// The parts, in the harness's order.
134    pub parts: Vec<PartResult>,
135    /// The items of sokf's integration that the harness has no place for at the scope, for
136    /// example `permissions`.
137    pub unsupported: Vec<Item>,
138    /// What the user still has to do in the agent, for example trust the folder.
139    pub notes: Vec<String>,
140}
141
142/// The report of `sokf harness install --json` and `sokf harness status --json`: one entry
143/// for each harness named, in sokf's order of the harnesses, with one entry for each part
144/// (CLI-3_AC-20).
145#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)]
146#[schemars(title = "sokf harness report")]
147pub struct HarnessReport {
148    /// The scope: `project`, `user`, or `local`.
149    pub scope: Scope,
150    /// The harnesses, in sokf's order.
151    pub harnesses: Vec<HarnessResult>,
152    /// What the user should know of the parts, such as content that an agent may load twice,
153    /// or a part that may not be an edit.
154    pub warnings: Vec<String>,
155}
156
157impl HarnessReport {
158    /// `harness` returns the result of the harness `id`.
159    pub fn harness(&self, id: &str) -> Option<&HarnessResult> {
160        self.harnesses.iter().find(|h| h.harness == id)
161    }
162
163    /// `to_text` returns the text report: for each harness, `<name>:`, one indented line for
164    /// each part, with a `next:` line after each part that is edited and stays as it is,
165    /// then `unsupported:` and `note:` lines; then a `warning:` line for each warning.
166    // sokf-implements: CLI-3_AC-19
167    // sokf-implements: CLI-3_AC-77
168    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
202/// `harness_ids` returns the harnesses that `names` names, in the order given, with `all`
203/// in place of every harness that sokf supports, each once.
204// sokf-implements: CLI-3_AC-65
205pub 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
225/// `shown` returns `path`, which the adapter gives relative to the root of `scope`, as the
226/// report shows it: from the repository root with `/`, or from the home directory with
227/// `~/`. A path that already starts with either stays as it is.
228pub(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
238/// `tool` reads the configuration of the scope and returns sokf as the adapter's `Tool`, with
239/// the program that the repository, or at the user scope the home directory, configures
240/// for the hook line of each harness (CONF-4_AC-2, CONF-4_AC-3).
241// sokf-implements: CONF-4_AC-2
242// sokf-implements: CONF-4_AC-3
243pub(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
268/// `refusal` turns an error of the adapter into a sokf error, naming a file by its path from the
269/// root of `scope` (CLI-9_AC-2).
270pub(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
279/// `report` turns the adapter's result into sokf's report, with the warning at each part
280/// that may not be an edit in sokf's words.
281// sokf-implements: CLI-3_AC-113
282pub(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
314/// `install` makes the tree match sokf's integration for each harness named, as CLI-3
315/// describes. The adapter writes nothing until every check has passed, writes the parts, then
316/// the record, and never the configuration. The adapter carries out the part kinds, the states, the
317/// hashes, the shared locations, and the record, so this call implements their criteria.
318// sokf-implements: CLI-3_AC-12
319// sokf-implements: CLI-3_AC-13
320// sokf-implements: CLI-3_AC-15
321// sokf-implements: CLI-3_AC-16
322// sokf-implements: CLI-3_AC-17
323// sokf-implements: CLI-3_AC-18
324// sokf-implements: CLI-3_AC-39
325// sokf-implements: CLI-3_AC-40
326// sokf-implements: CLI-3_AC-41
327// sokf-implements: CLI-3_AC-43
328// sokf-implements: CLI-3_AC-44
329// sokf-implements: CLI-3_AC-45
330// sokf-implements: CLI-3_AC-46
331// sokf-implements: CLI-3_AC-47
332// sokf-implements: CLI-3_AC-48
333// sokf-implements: CLI-3_AC-49
334// sokf-implements: CLI-3_AC-53
335// sokf-implements: CLI-3_AC-56
336// sokf-implements: CLI-3_AC-59
337// sokf-implements: CLI-3_AC-60
338// sokf-implements: CLI-3_AC-62
339// sokf-implements: CLI-3_AC-66
340// sokf-implements: CLI-3_AC-67
341// sokf-implements: CONF-4_AC-4
342// sokf-implements: CLI-3_AC-1
343// sokf-implements: CLI-3_AC-2
344// sokf-implements: CLI-3_AC-3
345// sokf-implements: CLI-3_AC-4
346// sokf-implements: CLI-3_AC-5
347// sokf-implements: CLI-3_AC-7
348// sokf-implements: CLI-3_AC-22
349// sokf-implements: CLI-3_AC-23
350// sokf-implements: CLI-3_AC-24
351// sokf-implements: CLI-9_AC-1
352// sokf-implements: CLI-9_AC-2
353// sokf-implements: CLI-3_AC-54
354// sokf-implements: CLI-3_AC-55
355// sokf-implements: CLI-3_AC-21
356// sokf-implements: CLI-3_AC-6
357// sokf-implements: CLI-3_AC-75
358// sokf-implements: CLI-3_AC-76
359pub 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
369/// `refuse_forced_off_parts` refuses a `--force` that names a part that is off by default for
370/// a harness whose `with` doesn't list it, and says to add the part to `with`, because the
371/// adapter's refusal of a declined part would say to remove it from `without`.
372// sokf-implements: CLI-3_AC-86
373fn 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        // A part that `without` also declines gets the adapter's refusal, which says to
381        // remove it from `without`.
382        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
398/// `status` returns the state of every part of each harness named, and writes nothing.
399// sokf-implements: CLI-3_AC-11
400// sokf-implements: CLI-3_AC-9
401// sokf-implements: CLI-3_AC-10
402// sokf-implements: CLI-3_AC-21
403pub 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
411/// `diff` returns a patch for each file of each part in the state `edited` of each harness
412/// named, from the text that `install` would write to the text on disk, with the paths
413/// `a/<path>` and `b/<path>` from the root of `scope`, in the order of `status`. A `file` part
414/// gives each file whole; a `region` part gives the block between its markers, and a `merge`
415/// part its entries as JSON, so their line numbers count from the block or the entries. It returns
416/// an empty text when no part is edited, and writes nothing.
417// sokf-implements: CLI-3_AC-78
418// sokf-implements: CLI-3_AC-79
419// sokf-implements: CLI-3_AC-80
420pub 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
431/// `installed_status` returns the state of every part of each harness installed at `scope`,
432/// or `None` when no harness is installed there. It writes nothing.
433pub(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    /// `decline` writes the configuration of `dir` so that it opts `claude` in to its hooks,
461    /// which are off by default, and declines `parts` of it.
462    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    // sokf-tests: CLI-3_AC-22
498    // sokf-tests: CLI-3_AC-23
499    // sokf-tests: CLI-3_AC-24
500    // sokf-tests: CONF-1_AC-3
501    // sokf-tests: CLI-9_AC-1
502    // sokf-tests: CLI-9_AC-2
503    #[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        // No refusal wrote anything.
550        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    // sokf-tests: CLI-3_AC-1
557    // sokf-tests: CLI-3_AC-3
558    // sokf-tests: CLI-3_AC-4
559    // sokf-tests: CLI-3_AC-5
560    // sokf-tests: CLI-3_AC-7
561    // sokf-tests: CLI-3_AC-8
562    // sokf-tests: CLI-3_AC-9
563    // sokf-tests: CLI-3_AC-54
564    // sokf-tests: CLI-3_AC-55
565    // sokf-tests: CLI-3_AC-75
566    // sokf-tests: CLI-3_AC-76
567    #[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        // A second run reports `current` and `skipped`, and the record has no hooks key.
580        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        // Edit the block and the skill: `install` leaves them unchanged, and `--force` then
591        // rewrites them.
592        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        // `--force skills` rewrites the skill alone, and the block keeps its edit.
606        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        // `--force` on a declined part refuses, names the config, and writes nothing.
614        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        // `--force all` covers every part that the config doesn't decline.
625        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        // No install changed the config.
631        assert_eq!(
632            fs::read_to_string(dir.join(".sokf/config.toml")).unwrap(),
633            declining("\"hooks\"")
634        );
635        // Turn the hooks back on by editing the config: `install` writes them into the
636        // settings file, which exists, so it reports `updated`.
637        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        // Declining the hooks again skips them and keeps their hash.
645        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    // sokf-tests: CLI-3_AC-77
656    // sokf-tests: CLI-3_AC-78
657    // sokf-tests: CLI-3_AC-79
658    // sokf-tests: CLI-3_AC-80
659    #[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        // The text report names both next steps beside the edited part.
679        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}