apoc 0.9.1

Agentic process control for LLMs
Documentation
//! Durable command hooks and delivery matching.

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()
}

/// Lifecycle point at which a hook program runs.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum HookPhase {
    /// The typed invocation was accepted and its normalized input was recorded.
    Start,
    /// The typed invocation completed successfully.
    Success,
    /// The typed invocation failed or ended without a complete verdict.
    Failure,
}

/// One named hook over an exact canonical apoc command path.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct Hook {
    /// Stable name within the selected scope.
    pub name: String,
    /// Exact canonical command path, such as `execution.command`.
    pub command: String,
    /// JavaScript Code Mode program run when the invocation starts.
    pub on_start: Option<String>,
    /// JavaScript Code Mode program run after a successful invocation.
    pub on_success: Option<String>,
    /// JavaScript Code Mode program run after a failed invocation.
    pub on_failure: Option<String>,
    /// Whether new deliveries may be created.
    pub enabled: bool,
    /// Maximum delivery attempts, including the first.
    pub max_attempts: u32,
    /// Maximum time allowed for one delivery attempt.
    pub timeout_ms: u64,
    /// Visibility namespace.
    pub scope_kind: RecipeScopeKind,
    /// Canonical worktree or directory key for local state.
    pub scope_key: Option<String>,
    /// Definition creation timestamp in Unix milliseconds.
    pub created_at: u64,
    /// Definition update timestamp in Unix milliseconds.
    pub updated_at: u64,
    /// Digest of the executable definition.
    pub generation: String,
}

/// Durable state of one hook delivery.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum HookDeliveryStatus {
    /// Waiting for an available Code Mode worker or retry deadline.
    Pending,
    /// One attempt currently owns the delivery.
    Running,
    /// The hook program completed successfully.
    Succeeded,
    /// Every configured attempt failed.
    Failed,
}

/// One durable attempt sequence created from a matching hook and invocation.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct HookDelivery {
    /// Stable identifier derived from hook generation, invocation, and phase.
    pub id: String,
    /// Hook name at delivery creation.
    pub hook_name: String,
    /// Hook generation at delivery creation.
    pub hook_generation: String,
    /// Source invocation identifier.
    pub invocation_id: String,
    /// Lifecycle point that matched.
    pub phase: HookPhase,
    /// Immutable JavaScript program snapshot.
    pub program: String,
    /// Source invocation snapshot exposed to the hook program.
    pub invocation: InvocationRecord,
    /// Current durable delivery state.
    pub status: HookDeliveryStatus,
    /// Number of attempts claimed so far.
    pub attempts: u32,
    /// Maximum attempts copied from the hook definition.
    pub max_attempts: u32,
    /// Per-attempt deadline copied from the hook definition.
    pub timeout_ms: u64,
    /// Earliest time a pending retry may be claimed.
    pub next_attempt_at: u64,
    /// Code Mode execution for the current or final attempt.
    pub execution_id: Option<String>,
    /// Last failure detail.
    pub error: Option<String>,
    /// Creation timestamp in Unix milliseconds.
    pub created_at: u64,
    /// Update timestamp in Unix milliseconds.
    pub updated_at: u64,
}

/// Computes the immutable digest for one executable hook definition.
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)))
}

/// Builds one replay-stable delivery identifier.
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()))
}

/// Returns the durable storage key for one hook namespace and name.
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()),
    }
}

/// Returns the program selected by one hook for an invocation phase.
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)
}

/// Normalizes the shared typed graph's display path into its dotted method identity.
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);
    }
}