use std::path::Path;
use crate::types::hooks::HookAction;
use crate::types::hooks::NativeHooks;
use crate::types::manifest::PackManifest;
use crate::types::name::ItemName;
use crate::types::name::PackName;
use crate::types::name::ToolName;
use crate::types::pack::error::PackError;
use crate::types::pack::item::kind::ItemKind;
use crate::types::pack::key::KeyPath;
use crate::types::pack::layout::{MANIFEST_FILE, PackLayout, native_hooks_file};
use crate::types::report::Diagnostic;
use crate::types::report::Diagnostics;
use crate::types::report::DoesNotExist;
use crate::types::report::Location;
use crate::types::tokens::names_own_pack;
use crate::types::tree::TreePath;
#[derive(Debug, Clone, PartialEq, Eq)]
struct OwnRun {
file: TreePath,
index: usize,
written: String,
path: TreePath,
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct AgentRef {
index: usize,
position: usize,
name: ItemName,
}
#[derive(Debug, Clone)]
pub(super) struct HookTargets {
pack: PackName,
runs: Vec<OwnRun>,
agents: Vec<AgentRef>,
}
impl HookTargets {
#[must_use]
pub(super) fn collect(
pack: &PackName,
manifest: &PackManifest,
native: &[(&ToolName, &NativeHooks)],
) -> Self {
let mut runs = Vec::new();
let mut agents = Vec::new();
for (index, hook) in manifest.hooks().iter().enumerate() {
let file = TreePath::from_parts(&[MANIFEST_FILE]);
collect_run(&mut runs, pack, &file, index, hook.action());
for (position, name) in hook.agents().unwrap_or_default().iter().enumerate() {
agents.push(AgentRef {
index,
position,
name: name.clone(),
});
}
}
for (tool, hooks) in native {
let file = native_hooks_file(tool);
for (index, hook) in hooks.hooks().iter().enumerate() {
collect_run(&mut runs, pack, &file, index, hook.action());
}
}
Self {
pack: pack.clone(),
runs,
agents,
}
}
#[must_use]
pub(super) fn run_paths(&self) -> Vec<TreePath> {
self.runs.iter().map(|run| run.path.clone()).collect()
}
#[must_use]
pub(super) fn check(&self, dir: &Path, layout: &PackLayout) -> Diagnostics {
let mut refusals = Diagnostics::new();
for run in &self.runs {
let exists = layout.root_files().contains(&run.path);
if !exists && !layout.is_refused(&run.path) {
refusals.push(Diagnostic::new(
Location::at_key(
dir.join(run.file.as_str()),
KeyPath::new("hooks").item(run.index).key("run"),
),
PackError::from(DoesNotExist::new(run.written.as_str())),
));
}
}
for agent in &self.agents {
if layout.lacks_agent(&agent.name) {
refusals.push(Diagnostic::new(
Location::at_key(
dir.join(MANIFEST_FILE),
KeyPath::new("hooks")
.item(agent.index)
.key("agents")
.item(agent.position),
),
PackError::NoSuchItem {
pack: self.pack.clone(),
kind: ItemKind::Agent,
item: agent.name.clone(),
},
));
}
}
refusals
}
}
fn collect_run(
runs: &mut Vec<OwnRun>,
pack: &PackName,
file: &TreePath,
index: usize,
action: &HookAction,
) {
let HookAction::Lua(lua) = action else {
return;
};
let run = lua.run();
if names_own_pack(run.pack(), pack) {
runs.push(OwnRun {
file: file.clone(),
index,
written: run.written().to_owned(),
path: TreePath::from_parts(&[run.path().as_str()]),
});
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::types::pack::testing::{DIR, layout, manifest, shown};
use std::error::Error;
type TestResult = Result<(), Box<dyn Error>>;
const REQUIRES: &str = "[requires]\nairsl = \">=0.1.4\"\n";
fn lua_hook(run: &str) -> String {
format!("[[hooks]]\nkind = \"lua\"\nevent = \"session.end\"\nrun = \"{run}\"\n")
}
fn core() -> Result<PackName, Box<dyn Error>> {
Ok(PackName::new("core")?)
}
fn targets_of(hooks: &[String]) -> Result<HookTargets, Box<dyn Error>> {
let manifest = manifest(&format!("{REQUIRES}{}", hooks.join("")))?;
Ok(HookTargets::collect(&core()?, &manifest, &[]))
}
fn run_paths(targets: &HookTargets) -> Vec<String> {
targets
.run_paths()
.iter()
.map(ToString::to_string)
.collect()
}
#[test]
fn own_runs_resolve_in_all_three_forms() -> TestResult {
let targets = targets_of(&[
lua_hook("hooks/a.lua"),
lua_hook("{{root}}/hooks/a.lua"),
lua_hook("{{root core}}/hooks/a.lua"),
])?;
assert_eq!(
run_paths(&targets),
["hooks/a.lua", "hooks/a.lua", "hooks/a.lua"]
);
let found = targets.check(Path::new(DIR), &layout(&["hooks/a.lua", "pack.toml"]));
assert!(shown(found).is_empty());
Ok(())
}
#[test]
fn other_pack_runs_are_left_to_the_set_check() -> TestResult {
let targets = targets_of(&[lua_hook("{{root guideline}}/hooks/x.lua")])?;
assert!(run_paths(&targets).is_empty());
assert!(
targets
.check(Path::new(DIR), &layout(&["pack.toml"]))
.is_empty()
);
Ok(())
}
#[test]
fn missing_own_run_is_refused() -> TestResult {
let files = layout(&["hooks/a.lua", "pack.toml"]);
let targets = targets_of(&[lua_hook("hooks/a.lua"), lua_hook("hooks/missing.lua")])?;
assert_eq!(
shown(targets.check(Path::new(DIR), &files)),
[format!(
"{DIR}/pack.toml: hooks[1].run: \"hooks/missing.lua\" does not exist"
)]
);
let targets = targets_of(&[lua_hook("{{root}}/hooks/missing.lua")])?;
assert_eq!(
shown(targets.check(Path::new(DIR), &files)),
[format!(
"{DIR}/pack.toml: hooks[0].run: \"{{{{root}}}}/hooks/missing.lua\" does not exist"
)]
);
Ok(())
}
#[test]
fn a_run_or_agent_the_walk_refused_is_not_refused_again() -> TestResult {
use crate::types::pack::testing::refused_walk;
let walk = refused_walk(&["pack.toml"], &["hooks/a.lua", "agents/coder.md"]);
let (files, _) =
PackLayout::classify(Path::new(DIR), &walk).map_err(|refusal| refusal.to_string())?;
let stop = "[[hooks]]\nkind = \"message\"\nevent = \"agent.stop\"\ntext = \"t\"\nagents = [\"coder\", \"codr\"]\n";
let targets = targets_of(&[
lua_hook("hooks/a.lua"),
lua_hook("hooks/b.lua"),
stop.to_owned(),
])?;
assert_eq!(
shown(targets.check(Path::new(DIR), &files)),
[
format!("{DIR}/pack.toml: hooks[1].run: \"hooks/b.lua\" does not exist"),
format!("{DIR}/pack.toml: hooks[2].agents[1]: pack \"core\" has no agent \"codr\""),
]
);
Ok(())
}
#[test]
fn run_naming_a_skill_file_does_not_exist_under_root() -> TestResult {
let files = layout(&["pack.toml", "skills/a/SKILL.md", "skills/a/x.lua"]);
let targets = targets_of(&[lua_hook("skills/a/x.lua")])?;
assert_eq!(
shown(targets.check(Path::new(DIR), &files)),
[format!(
"{DIR}/pack.toml: hooks[0].run: \"skills/a/x.lua\" does not exist"
)]
);
Ok(())
}
#[test]
fn run_naming_a_native_file_does_not_exist_under_root() -> TestResult {
let files = layout(&["native/claude/x.lua", "pack.toml"]);
let targets = targets_of(&[lua_hook("native/claude/x.lua")])?;
assert_eq!(
shown(targets.check(Path::new(DIR), &files)),
[format!(
"{DIR}/pack.toml: hooks[0].run: \"native/claude/x.lua\" does not exist"
)]
);
Ok(())
}
#[test]
fn native_hook_runs_are_checked_as_own_pack_runs() -> TestResult {
let pack_manifest = manifest(REQUIRES)?;
let text =
"[[hooks]]\nkind = \"lua\"\nevent = \"PreToolUse\"\nrun = \"hooks/missing.lua\"\n";
let file = Path::new(DIR).join("native/claude/hooks.toml");
let native = NativeHooks::parse(&file, text, pack_manifest.requires())
.map_err(|d| format!("{:?}", d.into_sorted()))?;
let tool = ToolName::new("claude")?;
let targets = HookTargets::collect(&core()?, &pack_manifest, &[(&tool, &native)]);
assert_eq!(run_paths(&targets), ["hooks/missing.lua"]);
assert_eq!(
shown(targets.check(Path::new(DIR), &layout(&["pack.toml"]))),
[format!(
"{DIR}/native/claude/hooks.toml: hooks[0].run: \"hooks/missing.lua\" does not exist"
)]
);
Ok(())
}
#[test]
fn hook_agents_must_name_own_agents() -> TestResult {
let message = "[[hooks]]\nkind = \"message\"\nevent = \"session.end\"\ntext = \"t\"\n";
let stop = "[[hooks]]\nkind = \"message\"\nevent = \"agent.stop\"\ntext = \"t\"\nagents = [\"coder\", \"task-briefer\"]\n";
let targets = targets_of(&[
message.to_owned(),
message.to_owned(),
message.to_owned(),
stop.to_owned(),
])?;
let files = layout(&["agents/coder.md", "pack.toml"]);
assert_eq!(
shown(targets.check(Path::new(DIR), &files)),
[format!(
"{DIR}/pack.toml: hooks[3].agents[1]: pack \"core\" has no agent \"task-briefer\""
)]
);
Ok(())
}
}