use super::{Because, Fix, fix_for};
use crate::ReachReason;
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum GateKind {
NotYet,
Boundary,
TooLarge,
}
pub fn gate_kind(
command: &str,
explanation: &crate::cst::Explanation,
approved: &dyn Fn(&str) -> bool,
approved_by_default: &dyn Fn(&str) -> bool,
) -> GateKind {
let Some(_guard) = crate::cst::check::ClassifyGuard::enter(command.len()) else {
return GateKind::Boundary;
};
if text_is_opaque(command) || words_name_a_boundary(command) || reaches_a_boundary(command) {
return GateKind::Boundary;
}
let refused: Vec<&str> = explanation
.segments
.iter()
.map(|s| s.text.as_str())
.filter(|text| !explanation.parsed || !approved(text))
.collect();
if refused.is_empty() {
return GateKind::Boundary;
}
let any_boundary = refused.iter().any(|segment| {
text_is_opaque(segment)
|| words_name_a_boundary(segment)
|| segment_kind(segment, approved, approved_by_default(segment)) == GateKind::Boundary
});
if any_boundary {
GateKind::Boundary
} else if crate::cst::classify_budget::classify_budget_spent() {
GateKind::TooLarge
} else {
GateKind::NotYet
}
}
pub fn segment_kind(segment: &str, approved: &dyn Fn(&str) -> bool, approved_by_default: bool) -> GateKind {
let Some(_guard) = crate::cst::check::ClassifyGuard::enter(segment.len()) else {
return GateKind::Boundary;
};
let kind = match fix_for(segment, approved, approved_by_default) {
Fix::Nothing(Because::ProtectedPath { reason, .. }) if is_boundary_reason(reason) => GateKind::Boundary,
Fix::Nothing(Because::RunsAnAgent { .. } | Because::Unconfined { .. }) => GateKind::Boundary,
Fix::Nothing(Because::RunsLater { path }) => {
if reads_only(segment, &path, approved) {
GateKind::NotYet
} else {
GateKind::Boundary
}
}
_ => GateKind::NotYet,
};
if kind != GateKind::Boundary && crate::cst::classify_budget::classify_budget_spent() { GateKind::TooLarge } else { kind }
}
fn is_boundary_reason(reason: ReachReason) -> bool {
match reason {
ReachReason::Credential
| ReachReason::OtherUsersHome
| ReachReason::RawDevice
| ReachReason::FrozenTrustFile
| ReachReason::FrozenTrustRoot
| ReachReason::FrozenSystemIntegrity
| ReachReason::Unconfined => true,
ReachReason::RepositorySnapshot | ReachReason::OutsideWorkspace | ReachReason::ForeignTemp => false,
}
}
fn reaches_a_boundary(command: &str) -> bool {
crate::operands::operand_words(command).is_none() || crate::workspace_reaches(command).any(|(_, reason)| is_boundary_reason(reason))
}
fn leads_out_through_a_link(word: &str) -> bool {
let Some(cwd) = crate::pathctx::folder_on_disk() else {
return false;
};
let root = match crate::pathctx::root() {
crate::pathctx::Root::Known(root) => std::path::PathBuf::from(root),
crate::pathctx::Root::Unknown => std::path::PathBuf::from(&cwd),
};
let expanded = expand_home(word);
let full = std::path::Path::new(&cwd).join(&expanded);
let mut at = std::path::PathBuf::from("/");
let mut crossed = false;
for part in full.components() {
match part {
std::path::Component::ParentDir => {
at.pop();
}
std::path::Component::Normal(name) => {
at.push(name);
crossed |=
at.starts_with(&root) && at != root && std::fs::symlink_metadata(&at).is_ok_and(|meta| meta.file_type().is_symlink());
}
_ => {}
}
}
if !crossed || !at.starts_with(&root) {
return false;
}
let (Ok(real), Ok(workspace)) = (std::fs::canonicalize(&full), std::fs::canonicalize(&root)) else {
return true;
};
let text = real.to_string_lossy();
names_a_protected_place(&text)
|| !(real.starts_with(&workspace) || crate::pathctx::under_temp_root(&text) || crate::pathctx::in_session_scratchpad(&text))
}
fn reads_only(segment: &str, path: &str, approved: &dyn Fn(&str) -> bool) -> bool {
let resolved = crate::pathctx::place(path, None).into_judged();
crate::engine::resolve::regions::hypothetical::with_hypothetical_grant(&resolved, true, false, || approved(segment))
}
const OPAQUE: &[char] = &['$', '`', '*', '?', '[', ']', '{', '}'];
const OPAQUE_PROGRAMS: &[&str] = &[
"cd", "pushd", "popd", "eval", "source", "exec", "sh", "bash", "zsh", "dash", "ksh", "mksh", "fish", "csh", "tcsh", "python",
"python3", "perl", "ruby", "node", "deno", "bun", "php", "lua", "osascript", "tclsh", "xargs", "env", "nohup", "timeout", "nice",
"awk", "gawk", "mawk", "nawk", "npx", "bunx", "pnpx", "uvx", "pipx", "dlx", "-exec", "-execdir", "-ok", "-okdir", "-P",
"--absolute-names",
];
const DIRECTORY_PREFIXES: &[&str] = &["-C"];
const DIRECTORY_OPTIONS: &[&str] = &["-C", "--directory", "--chdir", "--cwd", "--work-tree", "--git-dir"];
fn keeps_absolute_names(word: &str) -> bool {
word.strip_prefix('-')
.is_some_and(|flags| !flags.starts_with('-') && flags.chars().all(|c| c.is_ascii_alphabetic()) && flags.contains('P'))
}
fn text_is_opaque(text: &str) -> bool {
text.contains(OPAQUE)
|| words(text).any(|word| {
let name = word.rsplit('/').next().unwrap_or(&word);
(word.starts_with('~') && word != "~" && !word.starts_with("~/"))
|| OPAQUE_PROGRAMS.contains(&name)
|| DIRECTORY_OPTIONS.contains(&word.as_str())
|| DIRECTORY_PREFIXES.iter().any(|prefix| word.starts_with(prefix))
|| keeps_absolute_names(&word)
})
}
fn words(text: &str) -> impl Iterator<Item = String> + '_ {
let dequoted: String = text.chars().filter(|c| !matches!(c, '\'' | '"' | '\\')).collect();
dequoted
.split(|c: char| c.is_whitespace() || matches!(c, ';' | '|' | '&' | '(' | ')' | '<' | '>' | '=' | ',' | ':'))
.filter(|word| !word.is_empty())
.map(str::to_string)
.collect::<Vec<_>>()
.into_iter()
}
fn words_name_a_boundary(text: &str) -> bool {
words(text).any(|word| {
let name = word.rsplit('/').next().unwrap_or(&word);
name == "safe-chains"
|| crate::userconfig::runs_an_agent(name)
|| names_an_agent_package(&word)
|| path_parts(&word).any(|path| names_a_protected_place(path) || leaves_the_workspace(path))
|| path_parts(&word).any(names_a_place_that_runs_later_here)
|| path_parts(&word).chain(option_cluster_suffixes(&word)).any(leads_out_through_a_link)
})
}
const RUNS_LATER_HERE: &[&str] = &[
".git", ".envrc", ".env", ".claude", ".grok", ".gemini", ".codex", ".qwen", ".cursor", ".factory", ".agy", ".antigravity", ".opencode",
".vscode", ".idea", ".husky", ".mise.toml", "mise.toml", ".tool-versions", ".github", ".devcontainer",
];
fn names_a_place_that_runs_later_here(path: &str) -> bool {
path.split('/').any(|part| RUNS_LATER_HERE.contains(&part))
}
fn names_an_agent_package(word: &str) -> bool {
let word = word.to_ascii_lowercase();
crate::userconfig::agent_commands()
.iter()
.filter(|name| name.len() >= 5)
.any(|name| word.contains(name))
}
fn option_cluster_suffixes(word: &str) -> impl Iterator<Item = &str> {
let cluster = word.strip_prefix('-').filter(|rest| !rest.starts_with('-')).unwrap_or("");
cluster.char_indices().skip(1).map(move |(at, _)| &cluster[at..])
}
fn path_parts(word: &str) -> impl Iterator<Item = &str> {
let attached = word
.strip_prefix('-')
.filter(|rest| !rest.starts_with('-'))
.and_then(|rest| rest.find(['/', '.', '~']).map(|at| &rest[at..]));
let after_at = word
.match_indices('@')
.map(|(at, _)| &word[at + 1..])
.filter(|part| !part.starts_with('~') || part.starts_with("~/"));
std::iter::once(word).chain(attached).chain(after_at)
}
fn leaves_the_workspace(word: &str) -> bool {
if !(word.starts_with(['~', '/', '.']) || word.contains('/')) {
return false;
}
let expanded = expand_home(word);
let resolved = crate::pathctx::place(&expanded, None).into_judged();
let outside = resolved.starts_with(['/', '~']) || resolved == ".." || resolved.starts_with("../");
outside && !crate::pathctx::under_temp_root(&resolved) && !crate::pathctx::in_session_scratchpad(&resolved)
}
fn expand_home(word: &str) -> String {
let home = crate::process_home::var().unwrap_or_default();
match word.strip_prefix('~') {
Some(rest) if rest.is_empty() || rest.starts_with('/') => format!("{home}{rest}"),
_ => word.to_string(),
}
}
fn names_a_protected_place(word: &str) -> bool {
let path = if word.starts_with('~') || word.starts_with('/') {
word.to_string()
} else if word.contains('/') || word.starts_with('.') {
crate::pathctx::place(word, None).into_judged()
} else {
return false;
};
let home = crate::process_home::var().unwrap_or_default();
let trimmed = path.trim_end_matches('/');
if trimmed.is_empty() || trimmed == "~" || (!home.is_empty() && trimmed == home.trim_end_matches('/')) {
return true;
}
matches!(crate::userconfig::grantable_path(&path), Err(crate::userconfig::EditError::Protected(_, _)))
}
#[cfg(test)]
mod tests;