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-prompt-{harness}-{s}"),
_ => format!("harness-prompt-{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_note(&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);
}
}
}
#[cfg(test)]
mod tests {
use std::fs;
use super::*;
#[test]
fn notes_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 name = guard_key("claude", Some("s1"));
assert_eq!(name, "harness-prompt-claude-s1");
let file = dir.join(".sokf/cache/harness-prompt-claude-s1.hash");
let off = Guard::new(&root, CacheMode::Off, name.clone());
assert!(off.should_note("report"));
assert!(!file.exists());
let on = Guard::new(&root, CacheMode::On, name.clone());
assert!(on.should_note("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_note("report"));
assert!(
Guard::new(&root, CacheMode::On, guard_key("claude", Some("s2"))).should_note("report")
);
assert!(Guard::new(&root, CacheMode::On, guard_key("codex", None)).should_note("report"));
assert!(off.should_note("report"));
off.clear();
assert_eq!(fs::read_to_string(&file).unwrap(), kept);
assert!(on.should_note("other"));
assert_ne!(fs::read_to_string(&file).unwrap(), kept);
on.clear();
assert!(!file.exists());
assert!(on.should_note("other"));
fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn a_missing_session_keys_by_the_harness() {
assert_eq!(guard_key("pi", None), "harness-prompt-pi");
assert_eq!(guard_key("pi", Some("")), "harness-prompt-pi");
}
}