godmode-core 0.8.1

Core library for godmode: task graphs, session state, dispatch, and Claude Code plugin integrations.
Documentation
//! Policy enforcement: check tool calls and audit event I/O.

use std::path::Path;

use anyhow::Result;
use serde::{Deserialize, Serialize};

use crate::policy::{CheckResult, GovernancePolicy, PolicyAction};

/// Wildcard approval entry: every tool call requires human approval.
const APPROVAL_WILDCARD: &str = "*";

/// Determine which approval entry, if any, gates this tool call.
///
/// An entry matches in three ways:
/// - `*` — every call is gated.
/// - exact tool name (`Write`, `Edit`, `Bash`) — that tool is gated.
/// - command substring (`git push --force`, `cargo publish`) — the tool input
///   contains the listed command.
///
/// Approval entries are plain command strings, not patterns, so they are matched
/// as literal substrings. Over-matching is safe here: a false positive yields
/// Review (a human prompt), never Allow.
fn approval_trigger(
    approvals: &[String],
    tool_name: &str,
    content: Option<&str>,
) -> Option<String> {
    for entry in approvals {
        if entry == APPROVAL_WILDCARD {
            return Some(APPROVAL_WILDCARD.to_string());
        }
        if entry == tool_name {
            return Some(entry.clone());
        }
    }

    let text = content?;
    approvals
        .iter()
        .filter(|e| !e.is_empty() && e.as_str() != APPROVAL_WILDCARD && e.as_str() != tool_name)
        .find(|e| text.contains(e.as_str()))
        .cloned()
}

/// Check if a tool call is allowed by a resolved policy.
pub fn check_tool(
    policy: &GovernancePolicy,
    tool_name: &str,
    content: Option<&str>,
) -> CheckResult {
    // 1. Blocked tools
    if policy.blocked_tools.iter().any(|t| t == tool_name) {
        return CheckResult {
            action: PolicyAction::Deny,
            reason: format!("tool '{tool_name}' is in blocked_tools"),
        };
    }

    // 2. Allowed tools (if non-empty, tool must be in list)
    if !policy.allowed_tools.is_empty() && !policy.allowed_tools.iter().any(|t| t == tool_name) {
        return CheckResult {
            action: PolicyAction::Deny,
            reason: format!("tool '{tool_name}' not in allowed_tools"),
        };
    }

    // 3. Human approval.
    //
    // Checked before blocked patterns so an explicitly approval-gated command
    // surfaces as Review rather than being hard-denied by an overlapping
    // blocked pattern. Review still requires a human decision, so this trades
    // a silent deny for a visible prompt — it does not auto-allow.
    if let Some(trigger) = approval_trigger(&policy.require_human_approval, tool_name, content) {
        return CheckResult {
            action: PolicyAction::Review,
            reason: if trigger == APPROVAL_WILDCARD {
                format!("tool '{tool_name}' requires human approval")
            } else {
                format!("tool '{tool_name}' requires human approval: matches '{trigger}'")
            },
        };
    }

    // 4. Content patterns
    if let Some(text) = content {
        for pattern in &policy.blocked_patterns {
            match regex::Regex::new(pattern) {
                Ok(re) => {
                    if re.is_match(text) {
                        return CheckResult {
                            action: PolicyAction::Deny,
                            reason: format!("content matches blocked pattern: {pattern}"),
                        };
                    }
                }
                Err(_) => {
                    tracing::warn!("invalid regex in blocked_patterns: {pattern}");
                }
            }
        }
    }

    CheckResult {
        action: PolicyAction::Allow,
        reason: "passed all policy checks".to_string(),
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GovernanceEvent {
    pub ts: String,
    pub event: String,
    pub action: String,
    pub agent_id: String,
    pub tool_name: String,
    pub reason: String,
    #[serde(default)]
    pub pattern: String,
    #[serde(default)]
    pub session_id: String,
}

/// Append a governance audit event to the JSONL trail.
// qual:test_helper
pub fn emit_audit_event(root: &Path, event: &GovernanceEvent) -> Result<()> {
    let trace_dir = root.join(".ctx").join("godmode").join("traces");
    std::fs::create_dir_all(&trace_dir)?;
    let path = trace_dir.join("governance-audit.jsonl");
    let line = serde_json::to_string(event)?;
    use std::io::Write;
    let mut file = std::fs::OpenOptions::new()
        .create(true)
        .append(true)
        .open(path)?;
    writeln!(file, "{line}")?;
    Ok(())
}

/// Read governance audit events, optionally filtered by date prefix.
pub fn read_audit_events(root: &Path, date_filter: Option<&str>) -> Result<Vec<GovernanceEvent>> {
    let path = root
        .join(".ctx")
        .join("godmode")
        .join("traces")
        .join("governance-audit.jsonl");
    if !path.exists() {
        return Ok(vec![]);
    }
    let raw = std::fs::read_to_string(&path)?;
    let mut events = Vec::new();
    for line in raw.lines() {
        if line.trim().is_empty() {
            continue;
        }
        if let Ok(ev) = serde_json::from_str::<GovernanceEvent>(line) {
            if date_filter.is_some_and(|d| !ev.ts.starts_with(d)) {
                continue;
            }
            events.push(ev);
        }
    }
    Ok(events)
}