use std::collections::BTreeMap;
use agent_harness_adapter_core::{
EntryMatch, Integration,
hook::Event,
integration::{Hook, Skill},
};
const SKILL: &str = include_str!(concat!(env!("OUT_DIR"), "/harness/skills/sokf/SKILL.md"));
const INSTRUCTIONS: &str = include_str!(concat!(env!("OUT_DIR"), "/harness/instructions.md"));
#[cfg(test)]
const EMBEDDED: &[&str] = &["skills/sokf/SKILL.md", "instructions.md"];
pub const HOOK_COMMAND_MARK: &str = " harness hook ";
pub const ALLOWED_COMMAND: &str = "sokf";
pub const HOOK_EVENTS: &[Event] = &[Event::Stop];
fn version_line() -> String {
format!(
"<!-- Written by sokf {} with sokf harness install. Do not edit it: sokf harness install overwrites it. -->",
env!("CARGO_PKG_VERSION")
)
}
fn frontmatter(skill: &str) -> (&str, &str, &str) {
let rest = skill
.strip_prefix("---\n")
.expect("the embedded skill has frontmatter");
let close = rest
.find("\n---\n")
.expect("the embedded skill closes its frontmatter");
let (head, body) = (&rest[..close], &rest[close + 5..]);
let value = |key: &str| {
head.lines()
.find_map(|l| l.strip_prefix(key)?.strip_prefix(": "))
.unwrap_or_else(|| panic!("the embedded skill has no `{key}`"))
};
(value("name"), value("description"), body)
}
pub fn skill() -> Skill {
let (name, description, body) = frontmatter(SKILL);
let body = body.strip_prefix('\n').unwrap_or(body);
Skill::new(name, description, format!("{}\n\n{body}", version_line()))
}
pub fn hook_command(program: &str) -> String {
let program = program.replace('{', "{{").replace('}', "}}");
format!("{program}{HOOK_COMMAND_MARK}{{harness}} {{event}}")
}
pub fn instructions(fragments: &[(String, String)]) -> String {
let mut out = INSTRUCTIONS.to_string();
for (name, text) in fragments {
if !out.ends_with('\n') {
out.push('\n');
}
out.push_str(&format!("\n<!-- pack: {name} -->\n\n"));
out.push_str(text.trim_start_matches('\n'));
}
if !out.ends_with('\n') {
out.push('\n');
}
out
}
pub fn instructions_only(fragments: &[(String, String)]) -> Integration {
Integration::new().instructions(instructions(fragments))
}
pub fn integration(
programs: &BTreeMap<String, String>,
fragments: &[(String, String)],
) -> Integration {
let mut i = Integration::new()
.instructions(instructions(fragments))
.skill(skill())
.hook_match(EntryMatch::Contains(HOOK_COMMAND_MARK.into()))
.allow_command(ALLOWED_COMMAND);
for event in HOOK_EVENTS {
let hook = programs.iter().fold(
Hook::new(*event, hook_command(super::DEFAULT_HOOK_PROGRAM)),
|hook, (harness, program)| hook.command_for(harness, hook_command(program)),
);
i = i.hook(hook);
}
i
}
#[cfg(test)]
mod tests {
use std::path::{Path, PathBuf};
use agent_harness_adapter_core::Item;
use super::*;
#[test]
fn the_integration_has_four_items_and_the_stop_hook() {
let i = integration(&BTreeMap::new(), &[]);
assert_eq!(
i.items(),
[
Item::Instructions,
Item::Skills,
Item::Hooks,
Item::Permissions
]
);
assert_eq!(i.allowed_commands(), ["sokf"]);
assert_eq!(i.hooks().len(), 1);
assert_eq!(i.hooks()[0].event(), Event::Stop);
assert_eq!(
i.hooks()[0].command("claude"),
"sokf harness hook claude stop"
);
assert_eq!(
i.hook_owner(&i.hooks()[0]).unwrap(),
EntryMatch::Contains(" harness hook ".into())
);
let i = integration(
&[("codex".to_string(), "./target/debug/sokf".to_string())].into(),
&[],
);
assert_eq!(
i.hooks()[0].command("codex"),
"./target/debug/sokf harness hook codex stop"
);
assert_eq!(
i.hooks()[0].command("claude"),
"sokf harness hook claude stop"
);
assert_eq!(
Hook::new(Event::Stop, hook_command("${DIR}/sokf")).command("pi"),
"${DIR}/sokf harness hook pi stop"
);
}
#[test]
fn each_fragment_follows_the_comment_that_names_its_pack() {
assert_eq!(instructions(&[]), INSTRUCTIONS);
let block = instructions(&[
("method".into(), "Write the issue first.\n".into()),
("style".into(), "Write short sentences.".into()),
]);
assert_eq!(
block,
format!(
"{INSTRUCTIONS}\n<!-- pack: method -->\n\nWrite the issue first.\n\n<!-- pack: style -->\n\nWrite short sentences.\n"
)
);
assert_eq!(instructions_only(&[]).items(), [Item::Instructions]);
}
#[test]
fn the_skill_carries_the_version_line_after_its_frontmatter() {
let files = skill().dir_files();
assert_eq!(files.len(), 1);
let (path, text) = &files[0];
assert_eq!(path, "sokf/SKILL.md");
assert!(text.starts_with("---\nname: sokf\ndescription: "), "{text}");
let expected = format!("---\n\n{}\n\n# SOKF", version_line());
assert!(text.contains(&expected), "{text}");
assert!(text.contains(env!("CARGO_PKG_VERSION")));
assert_eq!(text.matches("# SOKF v0.6").count(), 1);
}
#[test]
fn every_file_under_harness_is_listed() {
let dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../../harness");
if !dir.is_dir() {
return;
}
let mut found = Vec::new();
walk(&dir, &dir, &mut found);
found.sort();
let mut listed: Vec<String> = EMBEDDED.iter().map(|s| s.to_string()).collect();
listed.sort();
assert_eq!(found, listed, "every file under harness/ must be embedded");
}
fn walk(root: &Path, dir: &Path, out: &mut Vec<String>) {
for entry in std::fs::read_dir(dir).unwrap() {
let entry = entry.unwrap();
let path: PathBuf = entry.path();
if path.is_dir() {
walk(root, &path, out);
} else {
out.push(
path.strip_prefix(root)
.unwrap()
.to_string_lossy()
.replace('\\', "/"),
);
}
}
}
}