use agent_harness_adapter_core::hook::LoopGuard;
use crate::{CacheMode, RepoRoot, cache::CACHE_DIR};
pub fn guard_key(harness: &str, session: Option<&str>) -> String {
match session {
Some(s) if !s.is_empty() => format!("harness-stop-{harness}-{s}"),
_ => format!("harness-stop-{harness}"),
}
}
pub struct Guard {
guard: Option<LoopGuard>,
key: String,
}
impl Guard {
pub fn new(root: &RepoRoot, mode: CacheMode, key: String) -> Self {
let guard = (mode == CacheMode::On).then(|| LoopGuard::new(root.as_path().join(CACHE_DIR)));
Guard { guard, key }
}
pub fn should_block(&self, text: &str) -> bool {
self.guard
.as_ref()
.is_none_or(|g| g.should_block(&self.key, text))
}
pub fn clear(&self) {
if let Some(g) = &self.guard {
g.clear(&self.key);
}
}
pub fn is_on(&self) -> bool {
self.guard.is_some()
}
}
#[cfg(test)]
mod tests {
use std::fs;
use super::*;
#[test]
fn blocks_once_per_text_and_never_records_with_the_cache_off() {
let dir = crate::test_support::fresh_dir("harness-guard");
let root = RepoRoot::new(dir.clone());
let key = guard_key("claude", Some("s1"));
assert_eq!(key, "harness-stop-claude-s1");
let file = dir.join(".sokf/cache/harness-stop-claude-s1.hash");
let off = Guard::new(&root, CacheMode::Off, key.clone());
assert!(!off.is_on());
assert!(off.should_block("report"));
assert!(!file.exists());
let on = Guard::new(&root, CacheMode::On, key.clone());
assert!(on.should_block("report"));
let kept = fs::read_to_string(&file).unwrap();
assert!(
kept.starts_with("fnv1a64:") && kept.len() == "fnv1a64:".len() + 17,
"{kept:?}"
);
assert_eq!(
fs::read_to_string(dir.join(".sokf/cache/.gitignore")).unwrap(),
"*\n"
);
assert!(!on.should_block("report"));
assert!(
Guard::new(&root, CacheMode::On, guard_key("claude", Some("s2")))
.should_block("report")
);
assert!(Guard::new(&root, CacheMode::On, guard_key("codex", None)).should_block("report"));
assert!(off.should_block("report"));
off.clear();
assert_eq!(fs::read_to_string(&file).unwrap(), kept);
assert!(on.should_block("other"));
assert_ne!(fs::read_to_string(&file).unwrap(), kept);
on.clear();
assert!(!file.exists());
assert!(on.should_block("other"));
fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn a_missing_session_keys_by_the_harness() {
assert_eq!(guard_key("pi", None), "harness-stop-pi");
assert_eq!(guard_key("pi", Some("")), "harness-stop-pi");
}
}