aKode: robustezza dell'agente (punto 4, blocco B)

- Compattazione: prima del riassunto l'output degli strumenti più vecchi
  (tutti tranne gli ultimi 3, sopra i 400 caratteri) diventa un segnaposto
  breve; le chiamate restano. La compattazione usa sempre il provider
  configurato: verificato, con un test sulle capacità dei provider.
- Protezione dai loop in stile Gemini CLI, accanto a max_repeated_failures:
  [agent] max_identical_tool_calls (5 risposte di fila con la stessa chiamata,
  qualunque sia il risultato; esclusi write_stdin e wait_agent; le chiamate
  parallele di una risposta contano una volta) e [agent] max_repeated_text
  (lo stesso testo ripetuto 10 volte di seguito mentre arriva, nella risposta
  o nel ragionamento; esclusi blocchi di codice e separatori).
- Cancellazioni ricorsive protette (rm -r, rm -rf, find -delete): radice,
  home, radice del repository, cartella di lavoro, percorsi fuori da essa o
  calcolati a runtime ($VAR, $(...), xargs) chiedono sempre la conferma
  dell'utente, anche con regole che li permetterebbero; in accesso completo
  vengono rifiutati.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
andrea.difonzo
2026-11-16 17:59:19 +01:00
parent 4e1f551b84
commit 0460c74f38
15 changed files with 1014 additions and 8 deletions

View File

@@ -6,4 +6,5 @@ mod powershell_parser;
mod powershell_tree_sitter;
pub mod is_dangerous_command;
pub mod recursive_deletion;
pub(crate) use powershell_tree_sitter::try_parse_powershell_commands;

View File

@@ -0,0 +1,358 @@
//! Path protection for recursive deletions (`rm -r`, `rm -rf`, `find ... -delete`).
//!
//! The worst documented agent accidents are recursive deletions generated by the agent itself:
//! a wrong `~` expansion, an empty variable (`rm -rf $DIR/`), a cleanup that climbs out of the
//! project. Pattern blocklists do not see variables; this check resolves each target against
//! the working directory and protects, whatever the sandbox or approval mode:
//! - the filesystem root and the home directory (and their ancestors);
//! - the repository root and the working directory itself (and their ancestors);
//! - anything outside the working directory;
//! - targets that are only known at run time (variables, command substitution, `xargs`).
use std::path::Component;
use std::path::Path;
use std::path::PathBuf;
use crate::bash::extract_bash_command;
/// Where the command runs.
#[derive(Debug, Clone)]
pub struct DeletionContext {
pub cwd: PathBuf,
pub home: Option<PathBuf>,
pub repo_root: Option<PathBuf>,
}
/// Returns why the command needs an explicit confirmation (or must be refused when nobody can
/// confirm), or `None` when it does not recursively delete a protected path.
pub fn protected_recursive_deletion(command: &[String], context: &DeletionContext) -> Option<String> {
let script = match extract_bash_command(command) {
Some((_, script)) => script.to_string(),
None => shlex::try_join(command.iter().map(String::as_str))
.unwrap_or_else(|_| command.join(" ")),
};
for segment in split_segments(&script) {
let words = shlex::split(&segment).unwrap_or_else(|| {
segment
.split_whitespace()
.map(ToString::to_string)
.collect()
});
for targets in deletion_targets(&words) {
if let Some(reason) = protected_targets(&targets, context) {
return Some(reason);
}
}
}
None
}
/// Targets of the recursive deletions in one simple command. An empty list means the targets
/// are not in the command line (for example `xargs rm -rf`).
fn deletion_targets(words: &[String]) -> Vec<Vec<String>> {
let mut found = Vec::new();
for (index, word) in words.iter().enumerate() {
match executable_name(strip_substitution(word)) {
"rm" => {
let args = &words[index + 1..];
let mut recursive = false;
let mut targets = Vec::new();
let mut options_done = false;
for arg in args {
if !options_done && arg == "--" {
options_done = true;
} else if !options_done && arg == "--recursive" {
recursive = true;
} else if !options_done && arg.starts_with("--") {
} else if !options_done && arg.starts_with('-') && arg.len() > 1 {
recursive |= arg.contains('r') || arg.contains('R');
} else {
targets.push(arg.clone());
}
}
if recursive {
found.push(targets);
}
}
"find" => {
let args = &words[index + 1..];
let deletes = args.iter().enumerate().any(|(position, arg)| {
arg == "-delete"
|| (matches!(arg.as_str(), "-exec" | "-execdir" | "-ok" | "-okdir")
&& args
.get(position + 1)
.is_some_and(|next| executable_name(next) == "rm"))
});
if deletes {
let roots: Vec<String> = args
.iter()
.take_while(|arg| !arg.starts_with('-') && *arg != "(" && *arg != "!")
.cloned()
.collect();
found.push(if roots.is_empty() {
vec![".".to_string()]
} else {
roots
});
}
}
_ => {}
}
}
found
}
fn protected_targets(targets: &[String], context: &DeletionContext) -> Option<String> {
if targets.is_empty() {
return Some(
"cancellazione ricorsiva di percorsi non indicati nel comando (calcolati a runtime)"
.to_string(),
);
}
for target in targets {
if target.starts_with('~') && target != "~" && !target.starts_with("~/") {
return Some(format!(
"cancellazione ricorsiva di `{target}`: colpisce la cartella home di un altro utente"
));
}
let Some(path) = resolve(target, context) else {
return Some(format!(
"cancellazione ricorsiva di `{target}`, un percorso calcolato a runtime (variabile o sottocomando)"
));
};
let cwd = normalize(&context.cwd);
let what = if path == Path::new("/") {
Some("la radice del filesystem".to_string())
} else if context
.home
.as_ref()
.is_some_and(|home| normalize(home).starts_with(&path))
{
Some("la cartella home".to_string())
} else if context
.repo_root
.as_ref()
.is_some_and(|root| normalize(root).starts_with(&path))
{
Some("la radice del repository".to_string())
} else if cwd.starts_with(&path) {
Some("la cartella di lavoro".to_string())
} else if !path.starts_with(&cwd) {
Some(format!("un percorso fuori dalla cartella di lavoro ({})", cwd.display()))
} else {
None
};
if let Some(what) = what {
return Some(format!(
"cancellazione ricorsiva di `{target}`: colpisce {what}"
));
}
}
None
}
/// Absolute, lexically normalized target; `None` when it depends on run-time values. A glob
/// stands for the directory whose contents it matches (`~/*` is the home directory).
fn resolve(target: &str, context: &DeletionContext) -> Option<PathBuf> {
let home = context.home.as_ref();
let expanded = if target == "~" {
home?.clone()
} else if let Some(rest) = target.strip_prefix("~/") {
home?.join(rest)
} else if let Some(rest) = target
.strip_prefix("$HOME")
.or_else(|| target.strip_prefix("${HOME}"))
&& (rest.is_empty() || rest.starts_with('/'))
{
home?.join(rest.trim_start_matches('/'))
} else {
PathBuf::from(target)
};
let text = expanded.to_string_lossy();
if text.contains('$') || text.contains('`') {
return None;
}
let absolute = if expanded.is_absolute() {
expanded
} else {
context.cwd.join(expanded)
};
// Cut at the first component with a glob: the deletion empties that directory.
let mut path = PathBuf::new();
for component in absolute.components() {
let text = component.as_os_str().to_string_lossy();
if text.contains(['*', '?', '[', '{']) {
break;
}
path.push(component);
}
Some(normalize(&path))
}
fn normalize(path: &Path) -> PathBuf {
let mut out = PathBuf::new();
for component in path.components() {
match component {
Component::CurDir => {}
Component::ParentDir => {
out.pop();
}
other => out.push(other),
}
}
if out.as_os_str().is_empty() {
PathBuf::from("/")
} else {
out
}
}
fn executable_name(word: &str) -> &str {
word.rsplit('/').next().unwrap_or(word)
}
/// `$(rm`, `` `rm ``, `(rm` and `{rm` start a command too.
fn strip_substitution(word: &str) -> &str {
word.trim_start_matches(['$', '(', '`', '{'])
}
/// Splits a script into simple commands at `;`, `&`, `|`, newlines and parentheses outside
/// quotes. Coarse on purpose: when in doubt it splits, and every piece is checked.
fn split_segments(script: &str) -> Vec<String> {
let mut segments = Vec::new();
let mut current = String::new();
let mut quote: Option<char> = None;
let mut escaped = false;
// Inside `${...}`: its closing brace does not end a command.
let mut in_parameter = false;
for ch in script.chars() {
if escaped {
current.push(ch);
escaped = false;
continue;
}
if in_parameter {
current.push(ch);
in_parameter = ch != '}';
continue;
}
if ch == '{' && quote != Some('\'') && current.ends_with('$') {
current.push(ch);
in_parameter = true;
continue;
}
match (quote, ch) {
(_, '\\') if quote != Some('\'') => {
current.push(ch);
escaped = true;
}
(Some(open), _) if ch == open => {
current.push(ch);
quote = None;
}
(Some(_), _) => current.push(ch),
(None, '\'' | '"') => {
current.push(ch);
quote = Some(ch);
}
(None, ';' | '&' | '|' | '\n' | ')' | '}') => {
segments.push(std::mem::take(&mut current));
}
(None, _) => current.push(ch),
}
}
segments.push(current);
segments
.into_iter()
.filter(|segment| !segment.trim().is_empty())
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
use pretty_assertions::assert_eq;
fn context() -> DeletionContext {
DeletionContext {
cwd: PathBuf::from("/Users/andrea/progetto/sub"),
home: Some(PathBuf::from("/Users/andrea")),
repo_root: Some(PathBuf::from("/Users/andrea/progetto")),
}
}
fn zsh(script: &str) -> Vec<String> {
vec!["/bin/zsh".to_string(), "-lc".to_string(), script.to_string()]
}
fn check(script: &str) -> Option<String> {
protected_recursive_deletion(&zsh(script), &context())
}
#[test]
fn protects_root_home_repo_and_cwd() {
for (script, what) in [
("rm -rf /", "la radice del filesystem"),
("rm -rf ~", "la cartella home"),
("rm -rf ~/", "la cartella home"),
("rm -rf $HOME", "la cartella home"),
("rm -fr ${HOME}/", "la cartella home"),
("rm -r /Users", "la cartella home"),
("rm -rf ~/*", "la cartella home"),
("rm -rf /Users/andrea/progetto", "la radice del repository"),
("rm -rf ..", "la radice del repository"),
("rm -rf .", "la cartella di lavoro"),
("rm -rf *", "la cartella di lavoro"),
("rm -rf ./", "la cartella di lavoro"),
("sudo rm -Rf /", "la radice del filesystem"),
("/bin/rm --recursive --force ~", "la cartella home"),
("find ~ -name '*.tmp' -delete", "la cartella home"),
("find / -exec rm -rf {} +", "la radice del filesystem"),
] {
let reason = check(script).unwrap_or_else(|| panic!("{script} not protected"));
assert!(reason.contains(what), "{script}: {reason}");
}
}
#[test]
fn protects_outside_cwd_and_run_time_targets() {
for script in [
"rm -rf /tmp/build",
"rm -rf ../../altro",
"rm -rf ~/Documenti",
"rm -rf ~utente",
"rm -rf $DIR/",
"rm -rf \"$BUILD_DIR\"",
"rm -rf `pwd`/x",
"cd x && rm -rf $(dirname a)/b",
"ls | xargs rm -rf",
"echo $(rm -rf ~)",
"true; rm -rf /etc",
] {
assert!(check(script).is_some(), "{script} not protected");
}
}
#[test]
fn allows_deletions_inside_the_working_directory() {
for script in [
"rm -rf target",
"rm -rf ./build dist/*.o",
"rm -rf /Users/andrea/progetto/sub/cache",
"rm -f file.txt /tmp/x",
"rm -r -- node_modules",
"find . -name '*.pyc' -print",
"find build -name '*.o' -delete",
"cargo clean && rm -rf out",
"echo 'rm -rf /'",
] {
assert_eq!(check(script), None, "{script}");
}
}
#[test]
fn direct_argv_is_checked_too() {
let command: Vec<String> = ["rm", "-rf", "/"].iter().map(ToString::to_string).collect();
assert!(protected_recursive_deletion(&command, &context()).is_some());
}
}