Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.
Rust ai-agentsai-assistantai-botautomationbotbots-teamchatbotclaude-duetgrokgrok-botgrok-bot-alternativeharnessllmmulti-agentopenai-dotsopenbotpersonal-agentrustself-hostedselfhosted-ai
File steps keep their path; run-check flags a rowless file step outside the bot's folder (29c) (#825)
Oleksandr Ivanchenkodb9c47db0bed
diff --git a/src/drivers/activity.rs b/src/drivers/activity.rsindex 43366b0a..33786de7 100644--- a/src/drivers/activity.rs+++ b/src/drivers/activity.rs@@ -1029,7 +1029,7 @@ fn tool_part(name: &str) -> &str {}/// A short title for a tool call, and the detail to show when the step is opened (the whole-/// command, address or query). Neither is redacted here.+/// command, address, query or file path). Neither is redacted here.pub fn summarize(name: &str, args: &Value) -> (String, Option<String>) {if is_shell_tool(name) {return match command_line(args) {@@ -1044,7 +1044,7 @@ pub fn summarize(name: &str, args: &Value) -> (String, Option<String>) {None => (None, name),};let lower = tool.to_ascii_lowercase();- let path = || arg(args, &["file_path", "path", "filePath", "notebook_path", "target_file"]).map(short_path);+ let path = arg(args, &["file_path", "path", "filePath", "notebook_path", "target_file"]);let url = arg(args, &["url", "href", "uri"]);if let Some(kind) = WordsTool::of(&lower) {let title = match kind {@@ -1055,7 +1055,10 @@ pub fn summarize(name: &str, args: &Value) -> (String, Option<String>) {return (title.unwrap_or_else(|| kind.bare().to_string()), None);}if let Some(kind) = FileTool::of(&lower) {- return (path().map_or(kind.bare().into(), |p| format!("{} {p}", kind.verb())), None);+ // 29c: the whole path is the detail (the title keeps the last two parts), so the step+ // opens to it and `kwnt run-check` can tell a file inside the bot's folder from one outside+ let title = path.map(short_path).map_or(kind.bare().into(), |p| format!("{} {p}", kind.verb()));+ return (title, path.map(str::to_string));}match lower.as_str() {"webfetch" | "fetch" | "web_fetch" | "browser_open" | "browser_navigate" | "navigate" | "open_url" => match url {@@ -1417,6 +1420,42 @@ mod tests {}}+ /// 29c: a read, edit or write step keeps its whole path as the detail (Unix and Windows, any+ /// of the path arguments), so the step opens to it and run-check can judge it; the title keeps+ /// the last two parts as before, and a call with no path keeps no detail.+ #[test]+ fn file_steps_keep_their_whole_path_as_detail() {+ let unix = "/home/maus/clients/acme-layoffs/plan.txt";+ let win = "C:\\Users\\ann\\clients\\acme\\contract.md";+ let cases = [+ ("Read", json!({"file_path": unix}), unix, "Reading …/acme-layoffs/plan.txt"),+ ("Write", json!({"file_path": unix, "content": "x"}), unix, "Writing …/acme-layoffs/plan.txt"),+ ("Edit", json!({"file_path": win, "old_string": "a", "new_string": "b"}), win, "Editing …\\acme\\contract.md"),+ ("MultiEdit", json!({"file_path": unix, "edits": []}), unix, "Editing …/acme-layoffs/plan.txt"),+ ("NotebookEdit", json!({"notebook_path": "/srv/nb/acme/model.ipynb"}), "/srv/nb/acme/model.ipynb", "Editing …/acme/model.ipynb"),+ ("apply_patch", json!({"path": win}), win, "Editing …\\acme\\contract.md"),+ ("mcp__files__read_file", json!({"path": unix}), unix, "Reading …/acme-layoffs/plan.txt"),+ ("Write", json!({"file_path": "notes.md"}), "notes.md", "Writing notes.md"),+ ];+ for (name, args, path, title) in cases {+ assert_eq!(summarize(name, &args), (title.to_string(), Some(path.to_string())), "{name}");+ }+ assert_eq!(summarize("Write", &json!({"content": "x"})), ("Writing a file".to_string(), None));+ assert_eq!(summarize("Read", &Value::Null), ("Reading a file".to_string(), None));+ // Search tools keep no detail, as before+ assert_eq!(summarize("Grep", &json!({"pattern": "x", "path": unix})).1, None);+ assert_eq!(summarize("Glob", &json!({"pattern": "*.md", "path": unix})).1, None);+ // Saved like every detail: redacted and cut to MAX_DETAIL+ let mut log = ActivityLog::default();+ let long = format!("/srv/{}/a.md", "d".repeat(600));+ let s = log.observe(&pending("1", "Write", json!({"file_path": long})));+ let detail = s[0].detail.clone().unwrap();+ assert_eq!(detail.chars().count(), MAX_DETAIL);+ assert!(detail.ends_with('…'));+ let s = log.observe(&pending("2", "Read", json!({"file_path": unix})));+ assert_eq!(s[0].detail.as_deref(), Some(unix));+ }+#[test]fn summaries_are_short_and_human() {let cases = [diff --git a/src/mcp/builtin_tools.rs b/src/mcp/builtin_tools.rsindex b11f69a1..87912af7 100644--- a/src/mcp/builtin_tools.rs+++ b/src/mcp/builtin_tools.rs@@ -471,6 +471,11 @@ fn target_path(input: &Value) -> Option<String> {.map(str::to_string)}+/// 29c: the key in a saved reply's meta holding the folder the turn's file tools were judged+/// against ([`canonical_folder`] of the turn's working folder), for `kwnt run-check`. Replies saved+/// before 0.9.25, and turns with no tools or no steps, have none.+pub const GATE_FOLDER_KEY: &str = "gate_folder";+/// The canonical working folder a bot's file tools are measured against.pub fn canonical_folder(folder: Option<&Path>) -> Option<PathBuf> {folder.and_then(|f| f.canonicalize().ok())diff --git a/src/run_check.rs b/src/run_check.rsindex 895f689f..17e3f5fa 100644--- a/src/run_check.rs+++ b/src/run_check.rs@@ -12,9 +12,12 @@//! How a step is judged://! - kwnt's own tools (`mcp__kwnt_tools__*`) run without a card by design;//! - claude's look-ups (web search, to-do list, tool search) and file tools run without a card by-//! design (file tools only inside the bot's folder; the step keeps no path to check that). A-//! WebFetch of this computer or the local network is the exception: kwnt asks for it, so it-//! needs a row (judged from the saved address, with no name lookups);+//! design. A WebFetch of this computer or the local network is the exception: kwnt asks for it,+//! so it needs a row (judged from the saved address, with no name lookups). File tools run+//! without one only inside the bot's folder: a read, edit or write step whose saved path is+//! outside the folder its reply records ([`GATE_FOLDER_KEY`]) needs a row. A step with no path,+//! a cut path, a failed step (its detail is the failure) or a reply with no folder (all history+//! before 0.9.25) counts as inside, as before. Glob and Grep are judged as before;//! - another engine's own tools (codex, grok) have no card hook: their sandbox holds them;//! - everything else (Bash, MCP tools, any tool on an API engine) needs an approvals row in the//! step's time window, for the same bot, tool and chat. A read-only command claude didn't ask@@ -22,6 +25,7 @@//! person chose "Always allow" for earlier in the same chat don't count as findings.//!//! [`families`]: crate::mcp::declined::families+//! [`GATE_FOLDER_KEY`]: crate::mcp::builtin_tools::GATE_FOLDER_KEYuse crate::drivers::activity::redact;use crate::mcp::builtin_tools::{self, ToolGroup};@@ -65,6 +69,8 @@ pub struct Reply {pub chat_label: String,/// `meta.ran_on.engine`: "claude", "codex", "grok", "anthropic_api", …pub engine: Option<String>,+ /// `meta.gate_folder`: the folder kwnt's gate judged the turn's file tools against (29c).+ pub folder: Option<String>,pub steps: Vec<Step>,}@@ -201,7 +207,7 @@ enum Gate {OtherEngine,}-fn gate(engine: Option<&str>, tool: &str, key: &str, step: &Step) -> Gate {+fn gate(engine: Option<&str>, folder: Option<&str>, tool: &str, key: &str, step: &Step) -> Gate {if key.starts_with("kwnt_tools_") {return Gate::KwantTool;}@@ -214,6 +220,8 @@ fn gate(engine: Option<&str>, tool: &str, key: &str, step: &Step) -> Gate {// kwnt asks before a WebFetch of this computer or the local network (`fetches_kwnt`)Some(ToolGroup::Lookup) if tool == "WebFetch" && fetch_address(step).is_some_and(|url| fetch_asks(&url)) => Gate::Card,Some(ToolGroup::Lookup) => Gate::Lookup,+ // kwnt asks before a file tool outside the bot's folder (`builtin_tools::decide`)+ Some(ToolGroup::Read | ToolGroup::Write) if file_outside(tool, step, folder) => Gate::Card,Some(ToolGroup::Read | ToolGroup::Write) => Gate::FolderFile,Some(ToolGroup::Shell) | None => Gate::Card,},@@ -223,6 +231,20 @@ fn gate(engine: Option<&str>, tool: &str, key: &str, step: &Step) -> Gate {}}+/// Whether a claude file step's saved path is outside `folder`, judged with the gate's own+/// [`builtin_tools::is_inside`] (29c). Only a whole absolute path counts: no folder, no detail, a+/// cut detail ("…"), a relative path or a failed step (whose detail is usually the failure) is+/// `false`, so history saved before 0.9.25 reads as before. Glob, Grep and LS keep no path.+fn file_outside(tool: &str, step: &Step, folder: Option<&str>) -> bool {+ let (Some(folder), Some(path)) = (folder.filter(|f| !f.is_empty()), step.detail.as_deref()) else {+ return false;+ };+ if matches!(tool, "Glob" | "Grep" | "LS") || step.status == "failed" || path.ends_with('…') || !Path::new(path).is_absolute() {+ return false;+ }+ !builtin_tools::is_inside(Path::new(folder), path)+}+/// The address a WebFetch step opened: its `detail` (the URL as the call gave it, redacted and cut),/// else the host in its title ("Opening 10.0.0.5"), which has lost the port and path. `None` when/// the step keeps neither ("Opening a page"). A failed step's `detail` is usually the failure reason@@ -311,7 +333,7 @@ pub fn check_since(}steps += 1;let key = tool_key(tool);- match gate(reply.engine.as_deref(), tool, &key, step) {+ match gate(reply.engine.as_deref(), reply.folder.as_deref(), tool, &key, step) {Gate::FolderFile => by_design.folder_files += 1,Gate::KwantTool => by_design.kwant_tools += 1,Gate::Lookup => by_design.lookups += 1,@@ -780,6 +802,7 @@ async fn read_all(pool: &sqlx::SqlitePool, cutoff: Option<DateTime<Utc>>) -> Reschat_label: chat.as_deref().map(label).unwrap_or_else(|| "a chat".into()),chat,engine: meta.pointer("/ran_on/engine").and_then(Value::as_str).map(str::to_string),+ folder: meta.get(builtin_tools::GATE_FOLDER_KEY).and_then(Value::as_str).map(str::to_string),steps: steps_of(&meta),})})@@ -959,6 +982,7 @@ mod tests {chat: Some("direct:b1".into()),chat_label: "chat with Forge".into(),engine: Some(engine.into()),+ folder: None,steps,}}@@ -992,7 +1016,7 @@ mod tests {#[test]fn gate_by_engine_and_tool() {- let g = |e: Option<&str>, tool: &str| gate(e, tool, &tool_key(tool), &Step::default());+ let g = |e: Option<&str>, tool: &str| gate(e, None, tool, &tool_key(tool), &Step::default());assert_eq!(g(Some("claude"), "Bash"), Gate::Card);assert_eq!(g(Some("claude"), "Write"), Gate::FolderFile);assert_eq!(g(None, "Read"), Gate::FolderFile);@@ -1186,6 +1210,86 @@ mod tests {assert_eq!(fetch_address(&s).as_deref(), Some("http://127.0.0.1/"));}+ /// A bot folder in a temp dir, canonical as the gate keeps it, and a path outside it.+ fn bot_folder() -> (tempfile::TempDir, std::path::PathBuf, String) {+ let dir = tempfile::tempdir().unwrap();+ std::fs::create_dir(dir.path().join("bot")).unwrap();+ let folder = builtin_tools::canonical_folder(Some(&dir.path().join("bot"))).unwrap();+ let outside = dir.path().join("elsewhere").join("plan.txt").display().to_string();+ (dir, folder, outside)+ }++ fn file_reply(at: &str, folder: Option<&std::path::Path>, steps: Vec<Step>) -> Reply {+ Reply { folder: folder.map(|f| f.display().to_string()), ..reply(at, "claude", steps) }+ }++ /// 29c: a claude write or read whose saved path is outside the folder its reply records ran+ /// with no card: kwnt asks for it (`builtin_tools::decide`), so it is a finding unless a row+ /// covers it. Inside the folder (an existing or a new file) it stays "in the bot's own folder".+ #[test]+ fn a_rowless_file_step_outside_the_bots_folder_is_a_finding() {+ let (_dir, folder, outside) = bot_folder();+ let inside = folder.join("plan.txt").display().to_string();+ let new_inside = folder.join("notes").join("new").join("draft.md").display().to_string();+ let sep = std::path::MAIN_SEPARATOR;+ let climbs_out = format!("{}{sep}..{sep}escape.txt", folder.display());+ let steps = vec![+ tool_step("Write", "2026-11-18T05:00:00.000Z", "Writing …/bot/plan.txt", Some(&inside)),+ tool_step("Edit", "2026-11-18T05:00:01.000Z", "Editing …/new/draft.md", Some(&new_inside)),+ tool_step("Write", "2026-11-18T05:00:02.000Z", "Writing …/elsewhere/plan.txt", Some(&outside)),+ tool_step("Read", "2026-11-18T05:00:03.000Z", "Reading …/elsewhere/plan.txt", Some(&outside)),+ tool_step("Write", "2026-11-18T05:00:04.000Z", "Writing …/../escape.txt", Some(&climbs_out)),+ ];+ let report = check(&[file_reply("2026-11-18T05:00:00.000Z", Some(&folder), steps)], &[], &[]);+ let found: Vec<(&str, &str)> = report.findings.iter().map(|f| (f.tool.as_str(), f.title.as_str())).collect();+ assert_eq!(+ found,+ [("Write", "Writing …/elsewhere/plan.txt"), ("Read", "Reading …/elsewhere/plan.txt"), ("Write", "Writing …/../escape.txt")]+ );+ assert!(report.findings.iter().all(|f| f.rule == Rule::RanWithNoCard));+ assert_eq!(report.by_design.folder_files, 2);++ // The card kwnt showed for it covers it+ let steps = vec![tool_step("Write", "2026-11-18T05:00:02.000Z", "Writing …/elsewhere/plan.txt", Some(&outside))];+ let rows = vec![row("w1", "Write", "allowed_once", "2026-11-18 05:00:02", Some("direct:b1"))];+ let report = check(&[file_reply("2026-11-18T05:00:00.000Z", Some(&folder), steps)], &[], &rows);+ assert!(report.findings.is_empty(), "{:?}", report.findings);+ assert_eq!(report.with_card, 1);+ }++ /// 29c: only a whole absolute path judged against a recorded folder counts. No path, a cut+ /// path, a relative path, a failed step (its detail is the failure), a search tool, a reply+ /// with no folder (all history before 0.9.25) and another engine read as before.+ #[test]+ fn a_file_step_with_no_path_a_cut_path_or_no_folder_counts_as_today() {+ let (_dir, folder, outside) = bot_folder();+ let at = "2026-11-18T05:00:00.000Z";+ let cut = format!("{}…", &outside[..outside.len() - 4]);+ let failed = Step { status: "failed".into(), ..tool_step("Write", at, "Writing …/elsewhere/plan.txt", Some(&outside)) };+ let steps = vec![+ tool_step("Write", at, "Writing a file", None),+ tool_step("Write", at, "Writing …/elsewhere/plan.txt", Some(&cut)),+ tool_step("Edit", at, "Editing ../plan.txt", Some("../plan.txt")),+ failed,+ tool_step("Glob", at, "Searching files", Some(&outside)),+ tool_step("Grep", at, "Searching files", Some(&outside)),+ ];+ let report = check(&[file_reply(at, Some(&folder), steps)], &[], &[]);+ assert!(report.findings.is_empty(), "{:?}", report.findings);+ assert_eq!(report.by_design.folder_files, 6);++ let write_outside = || vec![tool_step("Write", at, "Writing …/elsewhere/plan.txt", Some(&outside))];+ let report = check(&[file_reply(at, None, write_outside())], &[], &[]);+ assert!(report.findings.is_empty(), "{:?}", report.findings);+ assert_eq!(report.by_design.folder_files, 1);+ let empty = Reply { folder: Some(String::new()), ..reply(at, "claude", write_outside()) };+ assert!(check(&[empty], &[], &[]).findings.is_empty());+ let codex = Reply { folder: Some(folder.display().to_string()), ..reply(at, "codex", write_outside()) };+ let report = check(&[codex], &[], &[]);+ assert!(report.findings.is_empty());+ assert_eq!(report.by_design.other_engines, 1);+ }+#[test]fn a_local_fetch_with_its_row_is_covered() {let r = reply(diff --git a/src/server/routes.rs b/src/server/routes.rsindex 8a1eefd2..27c8335d 100644--- a/src/server/routes.rs+++ b/src/server/routes.rs@@ -4097,6 +4097,8 @@ async fn run_kwant_turn_inner(if let Some(delivery) = super::delivery_check::meta(&verdict, expect.as_ref(), checked) {meta.get_or_insert_with(|| serde_json::json!({}))["delivery"] = delivery;}+ // 29c: the folder kwnt's gate judged this turn's file tools against (see `note_gate_folder`)+ note_gate_folder(&mut meta, activity.as_ref(), mcp_turn.is_some(), workspace_dir.as_deref());// 0.9.4: a reply that ends with `Blocked: <what>. <what unblocks it>` says so in its meta// 13a: with no such line, a turn whose last tool step failed (or was declined, or whose// link didn't open and it ran no tool) and whose reply ends waiting on the person in@@ -4336,6 +4338,21 @@ async fn idea_from_chat(}}+/// 29c: records on a reply's meta the folder kwnt's gate judged the turn's file tools against+/// ([`crate::mcp::builtin_tools::GATE_FOLDER_KEY`]), so `kwnt run-check` can tell a file step outside it+/// from one inside. Only for a turn that had the gate (`gated`) and saved steps. Kept out of+/// `run_kwant_turn_inner` (`inline(never)`) so its temporaries don't grow that function's frame.+#[inline(never)]+fn note_gate_folder(meta: &mut Option<serde_json::Value>, activity: Option<&serde_json::Value>, gated: bool, workspace_dir: Option<&std::path::Path>) {+ let ran_steps = activity.and_then(|a| a["steps"].as_array()).is_some_and(|s| !s.is_empty());+ if !gated || !ran_steps {+ return;+ }+ if let Some(folder) = crate::mcp::builtin_tools::canonical_folder(workspace_dir) {+ meta.get_or_insert_with(|| json!({}))[crate::mcp::builtin_tools::GATE_FOLDER_KEY] = json!(folder.display().to_string());+ }+}+/// Adds the server-set `extra` keys to a message's meta.fn merge_meta(meta: &mut Option<serde_json::Value>, extra: Option<&serde_json::Value>) {let Some(serde_json::Value::Object(extra)) = extra else { return };@@ -7471,6 +7488,41 @@ mod tests {assert_eq!(handoff_title("@QA run `cargo test` on staging.", "QA").as_deref(), Some("Run `cargo test` on staging."));}+ #[test]+ fn a_gated_turn_with_steps_records_the_canonical_folder_and_no_other_turn_does() {+ use super::note_gate_folder;+ use crate::mcp::builtin_tools::GATE_FOLDER_KEY;+ let dir = tempfile::tempdir().unwrap();+ let folder = dir.path().join("bot");+ std::fs::create_dir(&folder).unwrap();+ let canon = folder.canonicalize().unwrap().display().to_string();+ let steps = json!({ "steps": [{ "title": "Wrote plan.md" }] });+ let none = json!({ "steps": [] });+ let missing = dir.path().join("missing");++ let mut meta = Some(json!({ "ran_on": { "engine": "claude" } }));+ note_gate_folder(&mut meta, Some(&steps), true, Some(&folder));+ let meta = meta.unwrap();+ assert_eq!(meta[GATE_FOLDER_KEY], json!(canon));+ assert_eq!(meta["ran_on"]["engine"], "claude", "other keys stay");++ let mut fresh = None;+ note_gate_folder(&mut fresh, Some(&steps), true, Some(&folder.join(".")));+ assert_eq!(fresh.unwrap()[GATE_FOLDER_KEY], json!(canon), "a meta-less reply gets one, canonical");++ for (activity, gated, at) in [+ (Some(&steps), false, Some(folder.as_path())),+ (Some(&none), true, Some(folder.as_path())),+ (None, true, Some(folder.as_path())),+ (Some(&steps), true, None),+ (Some(&steps), true, Some(missing.as_path())),+ ] {+ let mut meta = None;+ note_gate_folder(&mut meta, activity, gated, at);+ assert_eq!(meta, None, "{activity:?} gated={gated} at={at:?}");+ }+ }+use super::{is_persons, is_reply_by, person_words, scrub_urls, turn_failed_text, turn_plan, with_failure_meta, Carried, TurnOpts,};