use std::sync::Arc;
pub use agent_harness_adapter_core::hook::Answer;
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,
};
#[derive(Serialize, JsonSchema)]
#[serde(untagged)]
#[schemars(title = "sokf harness hook answer")]
pub enum HookAnswer {
Note {
#[serde(rename = "hookSpecificOutput")]
output: NoteOutput,
},
#[schemars(extend("maxProperties" = 0))]
Allow {},
}
#[derive(Serialize, JsonSchema)]
pub struct NoteOutput {
#[serde(rename = "hookEventName")]
pub event: EventName,
#[serde(rename = "additionalContext")]
pub note: String,
}
#[derive(Serialize, JsonSchema)]
pub enum EventName {
#[serde(rename = "UserPromptSubmit")]
UserPromptSubmit,
}
const OLD_EVENTS: &[Event] = &[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();
let known = |e: &Event| HOOK_EVENTS.contains(e) || OLD_EVENTS.contains(e);
match parsed {
Some(e) if known(&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 note(n: usize) -> String {
let errors = tramlines_core::text::count(n, "error", "errors");
format!("sokf: {errors}. Fix before finishing the work.")
}
pub fn hook(root: &RepoRoot, call: &HookCall, input: &str, cache: CacheMode) -> Result<Answer> {
let nothing = Answer::Allow { stderr: None };
if call.event == Event::Stop {
return Ok(nothing);
}
let probe = Answer::Context {
text: String::new(),
};
if call.harness.answer(call.event, &probe).is_err() {
return Ok(nothing);
}
if !holds_knowledge(root) {
return Ok(nothing);
}
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()),
);
let opts = ValidateOptions {
paths: vec![],
cwd: root.as_path().to_path_buf(),
fix: false,
cache,
query: None,
changed: vec![],
home: None,
};
let (report, _) = crate::validate(root, &opts)?;
if !report.has_errors() {
guard.clear();
return Ok(nothing);
}
let n = report.errors.len();
let errors = Report {
errors: report.errors,
..Report::default()
};
if !guard.should_note(&report::text(&errors, false)) {
return Ok(nothing);
}
Ok(Answer::Context { text: note(n) })
}
#[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::PromptSubmit,
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::Context {
text: "sokf: 1 error. Fix before finishing the work.".into()
}
),
"{\"hookSpecificOutput\":{\"hookEventName\":\"UserPromptSubmit\",\"additionalContext\":\"sokf: 1 error. Fix before finishing the work.\"}}"
);
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::Context { text: "n".into() }),
schema_form(&HookAnswer::Note {
output: NoteOutput {
event: EventName::UserPromptSubmit,
note: "n".into()
}
})
);
}
}
#[test]
fn a_hook_call_names_a_harness_that_runs_hooks_and_a_hook_event() {
for id in [
"claude", "codex", "factory", "gemini", "copilot", "cursor", "pi", "opencode", "kilo",
"qwen", "devin",
] {
let call = hook_call(id, "prompt-submit").unwrap();
assert_eq!((call.harness.id(), call.event), (id, Event::PromptSubmit));
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", "prompt-submit"),
"harness: no harness named `nope`"
);
assert_eq!(
e("agents", "prompt-submit"),
"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_note_counts_the_errors() {
assert_eq!(note(1), "sokf: 1 error. Fix before finishing the work.");
assert_eq!(note(3), "sokf: 3 errors. Fix before finishing the work.");
}
}