use std::sync::Arc;
use agent_harness_adapter_core::{
Harness, harness,
hook::{Event, HookInput},
};
use schemars::JsonSchema;
use serde::Serialize;
use serde_json::Value;
use super::guard::{Guard, guard_key};
use crate::{
CacheMode, Config, Error, RepoRoot, Report, Result, ValidateOptions, config,
harness::HOOK_EVENTS, report,
};
pub use agent_harness_adapter_core::hook::Answer;
#[derive(Serialize, JsonSchema)]
#[serde(untagged)]
#[schemars(title = "sokf harness hook answer")]
pub enum HookAnswer {
Block {
decision: Decision,
reason: String,
},
#[schemars(extend("maxProperties" = 0))]
Allow {},
}
#[derive(Serialize, JsonSchema)]
pub enum Decision {
#[serde(rename = "block")]
Block,
}
const OLD_EVENTS: &[(&str, Event)] = &[("stop", Event::Stop)];
#[derive(Debug, Clone)]
pub struct HookCall {
pub harness: Arc<dyn Harness>,
pub event: Event,
}
pub fn hook_call(harness: &str, event: &str) -> Result<HookCall> {
let h = harness::find(harness)
.ok_or_else(|| Error::Harness(format!("no harness named `{harness}`")))?;
if h.hook_events().is_empty() {
return Err(Error::Harness(format!("harness `{harness}` runs no hooks")));
}
let parsed = event.parse::<Event>().ok().or_else(|| {
OLD_EVENTS
.iter()
.find(|(name, _)| *name == event)
.map(|(_, e)| *e)
});
match parsed {
Some(e) if HOOK_EVENTS.contains(&e) && h.hook_events().contains(&e) => Ok(HookCall {
harness: h,
event: e,
}),
_ => Err(Error::Harness(format!(
"sokf has no hook for the event `{event}`"
))),
}
}
fn holds_knowledge(root: &RepoRoot) -> bool {
config::config_path().to_fs(root).is_file()
|| Config::default()
.roots
.iter()
.any(|r| r.to_fs(root).is_dir())
}
fn reason(report: &Report, text: &str) -> String {
let n = report.errors.len();
let noun = if n == 1 {
"error remains"
} else {
"errors remain"
};
format!(
"sokf: {n} {noun} in the knowledge after `sokf validate --fix`. Fix them before you finish.\n{text}"
)
}
pub fn hook(root: &RepoRoot, call: &HookCall, input: &str, cache: CacheMode) -> Result<Answer> {
let input = HookInput::parse(call.harness.as_ref(), call.event, input)
.unwrap_or_else(|_| HookInput::new(call.harness.id(), call.event, Value::Null));
let guard = Guard::new(
root,
cache,
guard_key(call.harness.id(), input.session_id.as_deref()),
);
if !holds_knowledge(root) {
return Ok(Answer::Allow { stderr: None });
}
let opts = ValidateOptions {
paths: vec![],
cwd: root.as_path().to_path_buf(),
fix: true,
cache,
query: None,
changed: vec![],
};
let (report, _) = crate::validate(root, &opts)?;
if !report.has_errors() {
guard.clear();
return Ok(Answer::Allow { stderr: None });
}
let text = report::text(&report, false);
let mut errors_only = report.clone();
errors_only.fixes.clear();
let block = if guard.is_on() {
guard.should_block(&report::text(&errors_only, false))
} else {
!input.continuing
};
if !block {
return Ok(Answer::Allow { stderr: Some(text) });
}
let answer = Answer::Continue {
reason: reason(&report, &text),
};
if call.harness.answer(call.event, &answer).is_err() {
return Ok(Answer::Allow { stderr: Some(text) });
}
Ok(answer)
}
#[cfg(test)]
mod tests {
use agent_harness_adapter_core::hook::emit;
use super::*;
fn json(id: &str, answer: Answer) -> String {
let h = harness::find(id).unwrap();
let mut out = Vec::new();
let code = emit(
h.as_ref(),
Event::Stop,
Ok::<_, Error>(answer),
&mut out,
&mut Vec::new(),
)
.unwrap();
assert_eq!(code, 0);
String::from_utf8(out).unwrap().trim_end().to_string()
}
#[test]
fn each_answer_as_json() {
assert_eq!(json("claude", Answer::Allow { stderr: None }), "{}");
assert_eq!(
json(
"claude",
Answer::Allow {
stderr: Some("x".into())
}
),
"{}"
);
assert_eq!(
json(
"claude",
Answer::Continue {
reason: "sokf: 1 error remains".into()
}
),
"{\"decision\":\"block\",\"reason\":\"sokf: 1 error remains\"}"
);
let schema_form = |a: &HookAnswer| serde_json::to_string(a).unwrap();
for id in ["claude", "codex", "factory"] {
assert_eq!(
json(id, Answer::Allow { stderr: None }),
schema_form(&HookAnswer::Allow {})
);
assert_eq!(
json(id, Answer::Continue { reason: "r".into() }),
schema_form(&HookAnswer::Block {
decision: Decision::Block,
reason: "r".into()
})
);
}
}
#[test]
fn a_hook_call_names_a_harness_that_runs_hooks_and_the_stop_event() {
for id in [
"claude", "codex", "factory", "gemini", "copilot", "cursor", "pi", "opencode", "kilo",
"qwen", "devin",
] {
let call = hook_call(id, "stop").unwrap();
assert_eq!((call.harness.id(), call.event), (id, Event::Stop));
}
let e = |h: &str, ev: &str| hook_call(h, ev).unwrap_err().to_string();
assert_eq!(e("nope", "stop"), "harness: no harness named `nope`");
assert_eq!(
e("agents", "stop"),
"harness: harness `agents` runs no hooks"
);
assert_eq!(
e("claude", "pre-tool"),
"harness: sokf has no hook for the event `pre-tool`"
);
assert_eq!(
e("claude", "start"),
"harness: sokf has no hook for the event `start`"
);
}
#[test]
fn the_reason_counts_the_errors() {
let mut report = Report::default();
report.errors.push(crate::Finding::error(
crate::RepoPath::parse("/k/a.md").unwrap(),
None,
"SOKF_FORMAT_1",
"bad",
));
let r = reason(&report, "REPORT");
assert!(
r.starts_with("sokf: 1 error remains in the knowledge"),
"{r}"
);
assert!(r.ends_with("\nREPORT"), "{r}");
report.errors.push(report.errors[0].clone());
assert!(reason(&report, "").starts_with("sokf: 2 errors remain"));
}
}