use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use crate::model::{ExecutionSpec, InvocationRecord, InvocationScopeKind, RecipeScopeKind};
pub(crate) const HOOK_DEPTH_LABEL: &str = "apoc.hook_depth";
pub(crate) fn execution_hook_depth(spec: &ExecutionSpec) -> u32 {
spec.labels
.get(HOOK_DEPTH_LABEL)
.and_then(|depth| depth.parse().ok())
.unwrap_or_default()
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum HookPhase {
Start,
Success,
Failure,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct Hook {
pub name: String,
pub command: String,
pub on_start: Option<String>,
pub on_success: Option<String>,
pub on_failure: Option<String>,
pub enabled: bool,
pub max_attempts: u32,
pub timeout_ms: u64,
pub scope_kind: RecipeScopeKind,
pub scope_key: Option<String>,
pub created_at: u64,
pub updated_at: u64,
pub generation: String,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum HookDeliveryStatus {
Pending,
Running,
Succeeded,
Failed,
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct HookDelivery {
pub id: String,
pub hook_name: String,
pub hook_generation: String,
pub invocation_id: String,
pub phase: HookPhase,
pub program: String,
pub invocation: InvocationRecord,
pub status: HookDeliveryStatus,
pub attempts: u32,
pub max_attempts: u32,
pub timeout_ms: u64,
pub next_attempt_at: u64,
pub execution_id: Option<String>,
pub error: Option<String>,
pub created_at: u64,
pub updated_at: u64,
}
pub(crate) fn hook_generation(hook: &Hook) -> Result<String, String> {
let value = serde_json::json!({
"name": hook.name,
"command": hook.command,
"on_start": hook.on_start,
"on_success": hook.on_success,
"on_failure": hook.on_failure,
"enabled": hook.enabled,
"max_attempts": hook.max_attempts,
"timeout_ms": hook.timeout_ms,
"scope_kind": hook.scope_kind,
"scope_key": hook.scope_key,
});
let encoded = serde_json::to_vec(&value).map_err(|error| error.to_string())?;
Ok(format!("sha256:{:x}", Sha256::digest(encoded)))
}
pub(crate) fn delivery_id(hook: &Hook, invocation: &InvocationRecord, phase: HookPhase) -> String {
let input = format!(
"{}\0{}\0{}\0{:?}",
hook.name, hook.generation, invocation.id, phase
);
format!("hook:{:x}", Sha256::digest(input.as_bytes()))
}
pub(crate) fn hook_storage_key(
scope_kind: RecipeScopeKind,
scope_key: Option<&str>,
name: &str,
) -> Result<String, String> {
match scope_kind {
RecipeScopeKind::Global => Ok(format!("global::{name}")),
RecipeScopeKind::GitWorktree => scope_key
.map(|key| format!("git_worktree:{key}::{name}"))
.ok_or_else(|| {
"HOOK_SCOPE_INVALID: Git worktree hooks require a scope key".to_string()
}),
RecipeScopeKind::Cwd => scope_key
.map(|key| format!("cwd:{key}::{name}"))
.ok_or_else(|| "HOOK_SCOPE_INVALID: Directory hooks require a scope key".to_string()),
}
}
pub(crate) fn matching_program<'a>(
hook: &'a Hook,
invocation: &InvocationRecord,
phase: HookPhase,
hook_depth: u32,
) -> Option<&'a str> {
let command = canonical_command_path(&invocation.command_path);
if !hook.enabled || hook_depth > 0 || command.starts_with("hook.") || hook.command != command {
return None;
}
let visible = match hook.scope_kind {
RecipeScopeKind::Global => hook.scope_key.is_none(),
RecipeScopeKind::GitWorktree => {
invocation.scope_kind == InvocationScopeKind::GitWorktree
&& hook.scope_key == invocation.scope_key
}
RecipeScopeKind::Cwd => {
invocation.scope_kind == InvocationScopeKind::Cwd
&& hook.scope_key == invocation.scope_key
}
};
if !visible {
return None;
}
let program = match phase {
HookPhase::Start => hook.on_start.as_deref(),
HookPhase::Success => hook.on_success.as_deref(),
HookPhase::Failure => hook.on_failure.as_deref(),
}?;
(!program.trim().is_empty()).then_some(program)
}
pub(crate) fn canonical_command_path(path: &str) -> String {
path.split_whitespace().collect::<Vec<_>>().join(".")
}
#[cfg(test)]
mod tests {
use serde_json::json;
use super::*;
use crate::model::{
InvocationScopeKind, InvocationSource, InvocationStatus, InvocationSurface,
};
fn invocation(command_path: &str, scope_key: Option<&str>) -> InvocationRecord {
InvocationRecord {
id: "invocation".to_string(),
parent_id: None,
execution_id: None,
source: InvocationSource::Native,
source_id: None,
source_order: None,
source_path: None,
accepted_sequence: 1,
surface: InvocationSurface::Code,
actor: Some("agent".to_string()),
agent: true,
command_path: command_path.to_string(),
purpose: Some("Test hook matching.".to_string()),
normalized_input: json!({}),
search_text: command_path.to_string(),
pattern_signature: String::new(),
variable_paths: Vec::new(),
cwd: scope_key.map(ToString::to_string),
scope_kind: InvocationScopeKind::Cwd,
scope_key: scope_key.map(ToString::to_string),
recording_id: None,
recording_take: None,
started_at: 1,
completed_at: None,
updated_at: 1,
status: InvocationStatus::Running,
exit_code: None,
error_code: None,
error: None,
}
}
fn hook(scope_kind: RecipeScopeKind, scope_key: Option<&str>) -> Hook {
Hook {
name: "build-followups".to_string(),
command: "execution.command".to_string(),
on_start: Some("return hook.phase;".to_string()),
on_success: Some("return hook.phase;".to_string()),
on_failure: Some("return hook.phase;".to_string()),
enabled: true,
max_attempts: 3,
timeout_ms: 300_000,
scope_kind,
scope_key: scope_key.map(ToString::to_string),
created_at: 1,
updated_at: 1,
generation: "generation".to_string(),
}
}
#[test]
fn selects_the_phase_program_for_an_exact_command_and_visible_scope() {
let invocation = invocation("execution command", Some("/workspace"));
let local = hook(RecipeScopeKind::Cwd, Some("/workspace"));
assert_eq!(
matching_program(&local, &invocation, HookPhase::Success, 0),
Some("return hook.phase;")
);
}
#[test]
fn rejects_other_commands_scopes_disabled_hooks_and_hook_originated_calls() {
let invocation = invocation("execution.command", Some("/workspace"));
let mut candidate = hook(RecipeScopeKind::Cwd, Some("/other"));
assert_eq!(
matching_program(&candidate, &invocation, HookPhase::Success, 0),
None
);
candidate.scope_key = Some("/workspace".to_string());
candidate.command = "process.list".to_string();
assert_eq!(
matching_program(&candidate, &invocation, HookPhase::Success, 0),
None
);
candidate.command = "execution.command".to_string();
candidate.enabled = false;
assert_eq!(
matching_program(&candidate, &invocation, HookPhase::Success, 0),
None
);
candidate.enabled = true;
assert_eq!(
matching_program(&candidate, &invocation, HookPhase::Success, 1),
None
);
}
#[test]
fn store_persists_hooks_and_enqueues_each_matching_phase_once() {
let directory = tempfile::tempdir().unwrap();
let store = crate::store::Store::open(directory.path().join("state.sqlite3")).unwrap();
let mut definition = hook(RecipeScopeKind::Global, None);
definition.generation = hook_generation(&definition).unwrap();
store.put_hook(&definition).unwrap();
assert_eq!(store.list_hooks().unwrap(), [definition.clone()]);
let invocation = invocation("execution.command", Some("/workspace"));
let first = store
.enqueue_hook_deliveries(&invocation, HookPhase::Success, 0)
.unwrap();
let replay = store
.enqueue_hook_deliveries(&invocation, HookPhase::Success, 0)
.unwrap();
assert_eq!(first.len(), 1);
assert_eq!(replay.len(), 1);
assert_eq!(first[0].id, replay[0].id);
assert_eq!(store.list_hook_deliveries(None, None).unwrap().len(), 1);
}
#[test]
fn concurrent_claims_own_each_delivery_once_and_recovery_requeues_it() {
let directory = tempfile::tempdir().unwrap();
let store = std::sync::Arc::new(
crate::store::Store::open(directory.path().join("state.sqlite3")).unwrap(),
);
let mut definition = hook(RecipeScopeKind::Global, None);
definition.generation = hook_generation(&definition).unwrap();
store.put_hook(&definition).unwrap();
let invocation = invocation("execution command", Some("/workspace"));
let delivery = store
.enqueue_hook_deliveries(&invocation, HookPhase::Success, 0)
.unwrap()
.remove(0);
let barrier = std::sync::Arc::new(std::sync::Barrier::new(3));
let handles = (0..2)
.map(|_| {
let store = std::sync::Arc::clone(&store);
let barrier = std::sync::Arc::clone(&barrier);
std::thread::spawn(move || {
barrier.wait();
store.claim_hook_deliveries(1, u64::MAX).unwrap()
})
})
.collect::<Vec<_>>();
barrier.wait();
let claims = handles
.into_iter()
.flat_map(|handle| handle.join().unwrap())
.collect::<Vec<_>>();
assert_eq!(claims.len(), 1);
assert_eq!(claims[0].id, delivery.id);
assert_eq!(claims[0].attempts, 1);
let recovered = store.recover_hook_deliveries().unwrap();
assert_eq!(recovered.len(), 1);
assert_eq!(recovered[0].status, HookDeliveryStatus::Pending);
let reclaimed = store.claim_hook_deliveries(1, u64::MAX).unwrap().remove(0);
assert_eq!(reclaimed.id, delivery.id);
assert_eq!(reclaimed.attempts, 2);
}
}