Skip to main content

safe_chains/targets/
mod.rs

1use std::path::{Path, PathBuf};
2
3use crate::verdict::{SafetyLevel, Verdict};
4
5pub mod agy;
6pub mod claude;
7pub mod codex;
8pub mod copilot;
9pub mod cursor;
10pub mod droid;
11pub mod gemini;
12pub mod grok;
13pub mod opencode;
14pub mod qwen;
15
16pub trait Target: Send + Sync {
17    fn name(&self) -> &'static str;
18
19    fn display_name(&self) -> &'static str;
20
21    fn detect_paths(&self, home: &Path) -> Vec<PathBuf>;
22
23    fn install(&self, home: &Path) -> Result<InstallOutcome, String>;
24
25    fn hook_format(&self) -> Option<&dyn HookFormat> {
26        None
27    }
28}
29
30pub trait HookFormat: Send + Sync {
31    fn parse_input(&self, stdin: &str) -> Result<HookInput, ParseError>;
32
33    fn render_response(&self, verdict: Verdict) -> HookResponse;
34
35    /// Surface explanatory context to the model on a non-approval *without*
36    /// changing the permission decision (the command still flows through the
37    /// tool's normal approval path, and the user's own allowlist still applies).
38    ///
39    /// The default abstains silently — same as today's empty deny body. A target
40    /// overrides this only when its hook schema has a verified field for
41    /// injecting model-visible context without a permission decision.
42    fn render_context(&self, _context: &str) -> HookResponse {
43        HookResponse {
44            stdout: String::new(),
45            exit_code: 0,
46        }
47    }
48
49    /// How this harness's hook must handle a GATED command (one safe-chains does not auto-approve),
50    /// derived from its capabilities (`docs/design/harness-capability-model.md`):
51    /// - `Defer` — stay silent; the harness's own per-command human review is the check (Claude).
52    /// - `Deny` — veto it; the harness has no human review and no escalate (Codex).
53    /// - `Ask` — escalate to an in-the-moment human prompt (Antigravity's `ask`).
54    fn gated_policy(&self) -> GatedPolicy {
55        GatedPolicy::Defer
56    }
57
58    /// The hook output that VETOES a gated command, for a `Deny` harness. Default abstains (so a
59    /// stray call can't fail open). The shape must be exactly what the harness supports, or a
60    /// harness that "continues on malformed output" (e.g. Codex) fails open.
61    fn render_deny(&self, _reason: &str) -> HookResponse {
62        HookResponse {
63            stdout: String::new(),
64            exit_code: 0,
65        }
66    }
67
68    /// The hook output that ESCALATES a gated command to a human prompt, for an `Ask` harness.
69    /// Default abstains. (Antigravity fails CLOSED on a malformed/absent decision, so an Ask target
70    /// must always emit a valid decision.)
71    fn render_ask(&self, _reason: &str) -> HookResponse {
72        HookResponse {
73            stdout: String::new(),
74            exit_code: 0,
75        }
76    }
77}
78
79/// How a harness's hook handles a gated command — see `HookFormat::gated_policy`.
80#[derive(Clone, Copy, PartialEq, Eq, Debug)]
81pub enum GatedPolicy {
82    Defer,
83    Deny,
84    Ask,
85}
86
87#[derive(Debug)]
88pub struct ParseError {
89    pub message: String,
90}
91
92impl std::fmt::Display for ParseError {
93    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
94        f.write_str(&self.message)
95    }
96}
97
98impl std::error::Error for ParseError {}
99
100pub struct HookInput {
101    pub command: String,
102    pub cwd: Option<String>,
103    /// The project root, when the harness supplies one (HP-19) — a `*_PROJECT_DIR` env var
104    /// for most, `workspace_roots` in the payload for cursor. Absent for codex/copilot.
105    pub root: Option<String>,
106}
107
108/// Read a harness project-root env var from the hook process environment (set by the
109/// harness, not the agent's shell — see HARNESS-BEHAVIORS.md). Empty → `None`.
110pub(crate) fn env_root(var: &str) -> Option<String> {
111    std::env::var(var).ok().filter(|s| !s.is_empty())
112}
113
114pub struct HookResponse {
115    pub stdout: String,
116    pub exit_code: i32,
117}
118
119pub enum InstallOutcome {
120    Installed { path: PathBuf },
121    AlreadyConfigured { path: PathBuf },
122    Skipped { reason: String },
123}
124
125impl InstallOutcome {
126    pub fn message(&self, target_display: &str) -> String {
127        match self {
128            InstallOutcome::Installed { path } => {
129                format!("{target_display}: installed → {}", path.display())
130            }
131            InstallOutcome::AlreadyConfigured { path } => {
132                format!("{target_display}: already configured at {}", path.display())
133            }
134            InstallOutcome::Skipped { reason } => {
135                format!("{target_display}: skipped — {reason}")
136            }
137        }
138    }
139}
140
141pub fn registry() -> Vec<Box<dyn Target>> {
142    vec![
143        Box::new(claude::ClaudeTarget),
144        Box::new(codex::CodexTarget),
145        Box::new(agy::AntigravityTarget),
146        Box::new(cursor::CursorTarget),
147        Box::new(gemini::GeminiTarget),
148        Box::new(grok::GrokTarget),
149        Box::new(copilot::CopilotTarget),
150        Box::new(qwen::QwenTarget),
151        Box::new(droid::DroidTarget),
152        Box::new(opencode::OpenCodeTarget),
153    ]
154}
155
156pub fn find(name: &str) -> Option<Box<dyn Target>> {
157    registry().into_iter().find(|t| t.name() == name)
158}
159
160pub fn detect_installed(home: &Path) -> Vec<Box<dyn Target>> {
161    registry()
162        .into_iter()
163        .filter(|t| t.detect_paths(home).iter().any(|p| p.exists()))
164        .collect()
165}
166
167pub fn allow_reason(verdict: Verdict) -> &'static str {
168    match verdict {
169        Verdict::Allowed(SafetyLevel::SafeWrite) => {
170            "All commands in chain are safe utilities (includes file writes)"
171        }
172        Verdict::Allowed(SafetyLevel::SafeRead) => {
173            "All commands in chain are safe utilities (includes code execution)"
174        }
175        _ => "All commands in chain are safe utilities",
176    }
177}