Craft Anything: understand how any software works, and craft your own.
Rust
Each project chooses what the builder's approvals get, per kind of action (#1022)
Tanish Manku3122cd1e6d35
diff --git a/apps/craft-anything-cli/src/main.rs b/apps/craft-anything-cli/src/main.rsindex 0c67b59c..00e4ef01 100644--- a/apps/craft-anything-cli/src/main.rs+++ b/apps/craft-anything-cli/src/main.rs@@ -229,7 +229,13 @@ fn open_or_create_project(dir: &Path) -> Result<Project, ToolError> {pub fn call_options(cli: &Cli, cancel: &CancelToken) -> CallOptions<'static> {let consent = if cli.allow_run { Consent::Granted } else { Consent::NotAsked };- CallOptions::new(Caller::Cli).with_consent(consent).with_cancel(cancel.clone())+ CallOptions::new(caller()).with_consent(consent).with_cancel(cancel.clone())+}++/// The person, unless a coding agent Craft Anything started is running this CLI (it then calls+/// tools as an agent, which can't loosen a project's approvals).+fn caller() -> Caller {+ if std::env::var_os(craft_anything_engine::AGENT_ENV).is_some() { Caller::Agent } else { Caller::Cli }}/// A cancel token that trips on Ctrl-C.diff --git a/apps/craft-anything-cli/tests/cli.rs b/apps/craft-anything-cli/tests/cli.rsindex d192b35b..c1340bde 100644--- a/apps/craft-anything-cli/tests/cli.rs+++ b/apps/craft-anything-cli/tests/cli.rs@@ -80,6 +80,31 @@ fn a_tools_own_project_option_reaches_the_tool() {assert_eq!(std::fs::read_dir(folder.path()).unwrap().count(), 0, "no investigation was created in the folder");}+/// A builder that runs our CLI from its shell is an agent to the tools, so it can't allow itself to+/// push; the person, running the same command, can.+#[test]+fn the_cli_inside_an_agent_cant_loosen_a_projects_approvals() {+ use craft_anything_engine::workspace::{ActionKind, Approval, TargetRef, Workspace};+ let cfg = tempfile::tempdir().unwrap();+ let dir = tempfile::tempdir().unwrap();+ let ws = Workspace::create(dir.path(), "Notes", "A notes app", TargetRef::None).unwrap();+ let project = ws.root.to_str().unwrap().to_string();+ let args = ["project-approvals-set", "--project", project.as_str(), "--kind", "publish", "--mode", "allow"];+ let run = |agent: bool| {+ let p = Process::new(env!("CARGO_BIN_EXE_craft-anything-cli")).args(args).env("CRAFT_ANYTHING_CONFIG_DIR", cfg.path());+ let p = if agent { p.env(craft_anything_engine::AGENT_ENV, "1") } else { p };+ p.timeout(Duration::from_secs(60)).run().unwrap()+ };+ let saved = || Workspace::open(&ws.root).unwrap().manifest.approvals.get(&ActionKind::Publish).copied();+ let refused = run(true);+ assert!(!refused.success, "{}", refused.stdout_text());+ assert!(refused.stdout_text().contains("can't loosen"), "{}", refused.stdout_text());+ assert_eq!(saved(), None, "nothing changed");+ let allowed = run(false);+ assert!(allowed.success, "{}{}", allowed.stdout_text(), allowed.stderr_text());+ assert_eq!(saved(), Some(Approval::Allow));+}+#[test]fn target_tools_open_then_close_and_project_journal() {let cfg = tempfile::tempdir().unwrap();diff --git a/crates/ai/src/cli_agents/acp.rs b/crates/ai/src/cli_agents/acp.rsindex 1a4909dc..cc4a3cd7 100644--- a/crates/ai/src/cli_agents/acp.rs+++ b/crates/ai/src/cli_agents/acp.rs@@ -673,6 +673,8 @@ impl AcpConversation {.process(&self.program).args(&self.args).cwd(&self.cwd)+ // Our own CLI, started from inside the agent, calls tools as an agent (not the person).+ .env(craft_anything_engine::AGENT_ENV, "1").stdin(StdinMode::Piped)// One process serves the whole chat; a builder turn may take hours..timeout(Duration::from_secs(24 * 3600))diff --git a/crates/ai/src/cli_agents/mod.rs b/crates/ai/src/cli_agents/mod.rsindex fa9383dd..95ddd72c 100644--- a/crates/ai/src/cli_agents/mod.rs+++ b/crates/ai/src/cli_agents/mod.rs@@ -750,6 +750,8 @@ fn agent_env(builder: bool, effort: Option<crate::model::Effort>) -> Vec<(&'stat// High effort for Claude Code unless chosen. An environment variable rather than// `--effort`: it ranks highest, and an older Claude Code that doesn't know it ignores it.("CLAUDE_CODE_EFFORT_LEVEL", crate::prompt::choose_effort(effort).as_str().into()),+ // Our own CLI, started from inside the agent, calls tools as an agent (not the person).+ (craft_anything_engine::AGENT_ENV, "1".into()),]}diff --git a/crates/engine/src/clean_room.rs b/crates/engine/src/clean_room.rsindex 23f04f68..de8b15ed 100644--- a/crates/engine/src/clean_room.rs+++ b/crates/engine/src/clean_room.rs@@ -59,6 +59,7 @@ pub const TOOLS: &[&str] = &["project_duplicate","project_delete","project_questions_set",+ "project_approvals_set","project_build_finish","project_pin_create","project_pins_list",diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rsindex 29bf1548..0137fecd 100644--- a/crates/engine/src/lib.rs+++ b/crates/engine/src/lib.rs@@ -41,7 +41,7 @@ pub use registry::Registry;pub use session::Session;pub use settings::{Mode, Settings};pub use target::{Target, TargetKind};-pub use tool::{Caller, CancelToken, Ctx, Effects, Progress, Requires, ToolOutput, ToolSpec, Toolset};+pub use tool::{AGENT_ENV, Caller, CancelToken, Ctx, Effects, Progress, Requires, ToolOutput, ToolSpec, Toolset};use craft_anything_evidence::{ErrorCode, ToolError};use craft_anything_platform::sync::{Mutex, MutexGuard};diff --git a/crates/engine/src/tool.rs b/crates/engine/src/tool.rsindex 193ab312..59764b97 100644--- a/crates/engine/src/tool.rs+++ b/crates/engine/src/tool.rs@@ -207,6 +207,11 @@ pub enum Caller {Agent,}+/// Set in the environment of every coding agent Craft Anything starts, and inherited by what it+/// runs, so a `craft-anything-cli` a builder starts calls tools as [`Caller::Agent`], not as the+/// person (it can't loosen a project's approvals that way).+pub const AGENT_ENV: &str = "CRAFT_ANYTHING_AGENT";+/// Cooperative cancellation, shared with long-running work (it lives in `platform`, so the/// transports below the engine can take it too).pub use craft_anything_platform::cancel::CancelToken;diff --git a/crates/engine/src/tools/interaction_tools.rs b/crates/engine/src/tools/interaction_tools.rsindex 54ab57b5..934eacb6 100644--- a/crates/engine/src/tools/interaction_tools.rs+++ b/crates/engine/src/tools/interaction_tools.rs@@ -6,15 +6,17 @@//! Approvals follow a small, explicit policy so ordinary building doesn't nag: editing files//! inside the workspace's `app/` folder and a fixed list of build commands are allowed; starting//! long-running dev servers is refused with a hint; anything else asks the person, who can allow-//! it once or for the rest of the project. In Auto mode (the default) nothing asks: those actions-//! go ahead, except a few that are never done unasked ([`never_unasked`]), which are refused so-//! the builder finds another way. Questions are shown to the person or answered with "decide-//! yourself", as the project chooses (`Manifest::questions`), else the app (`Settings::questions`,+//! it once or for the rest of the project. What's asked about falls into a kind ([`kind_of`]:+//! the web, commands, files outside the project, publishing…), and each project can choose what a+//! kind gets (allow, ask or refuse; `project_approvals_set`). A kind it hasn't chosen follows Auto+//! mode: with it on (the default) nothing asks, and what can be undone goes ahead while the rest+//! ([`never_unasked`]) is refused so the builder finds another way. Questions are shown to the+//! person or answered with "decide yourself", as the project chooses (`Manifest::questions`), else the app (`Settings::questions`,//! which follows Auto mode until the person picks).use crate::inbox::{Inbox, InboxDir, RequestKind};use crate::tool::{Ctx, Effects, Requires, ToolOutput, ToolSpec, Toolset, parse_params, schema_of};-use crate::workspace::{Questions, Workspace};+use crate::workspace::{ActionKind, Approval, Questions, Workspace};use craft_anything_evidence::{ErrorCode, ToolError};use schemars::JsonSchema;use serde::Deserialize;@@ -346,7 +348,20 @@ fn decide_command(cmd: &str, app: &Path) -> Decision {Decision::Allow}-/// The policy for one action. `ws` is the workspace the agent works in, if known.+/// Where a file tool's `target` may be opened: as written when it's absolute; else from the project+/// folder (where agents are started) and from app/ (where they may `cd`), so a check holds for+/// both. `None` for a path that climbs above the root.+fn opened_at(ws: Option<&Workspace>, target: &str) -> Vec<Option<PathBuf>> {+ let bases = match ws {+ Some(w) if Path::new(target).is_relative() => vec![w.root.clone(), w.app_dir()],+ Some(w) => vec![w.app_dir()],+ None => vec![PathBuf::from("/")],+ };+ bases.iter().map(|b| resolve_as_opened(b, target)).collect()+}++/// The policy for one action, before the project's choices and anything the person always allowed+/// ([`approve_with`] applies those). `ws` is the workspace the agent works in, if known.pub fn decide(ws: Option<&Workspace>, tool: &str, input: &Value) -> Decision {let s = |k: &str| input.get(k).and_then(Value::as_str).unwrap_or_default().to_string();let kind = match tool {@@ -355,9 +370,6 @@ pub fn decide(ws: Option<&Workspace>, tool: &str, input: &Value) -> Decision {"WebFetch" | "WebSearch" => "web".to_string(),other => other.to_string(),};- if ws.is_some_and(|w| w.manifest.allowed_actions.contains(&kind)) {- return Decision::Allow;- }let app = ws.map(Workspace::app_dir);match tool {"Read" | "Glob" | "Grep" | "LS" | "TodoWrite" => Decision::Allow,@@ -367,22 +379,26 @@ pub fn decide(ws: Option<&Workspace>, tool: &str, input: &Value) -> Decision {// approvals are answered), the manifest and the person's pictures stay out of reach,// also when the app is the project folder itself.let checks = ws.map(Workspace::checks_dir);- match (&app, resolve_as_opened(app.as_deref().unwrap_or(Path::new("/")), &target)) {- // Followed through links, so a link in app/ can't lead a write out of it.- (Some(app), Some(p))- if (really_inside(app, &p) || checks.as_ref().is_some_and(|c| really_inside(c, &p))) && !ws.is_some_and(|w| w.is_own_record(&p)) =>- {- Decision::Allow- }- _ => Decision::Ask { title: format!("Change a file outside the project: {target}"), kind },+ // Followed through links, so a link in app/ can't lead a write out of it; and wherever+ // the agent opens a relative path from, so `craft.json` isn't taken for app/craft.json.+ let ours = |p: &Path| {+ app.as_ref().is_some_and(|app| really_inside(app, p) || checks.as_ref().is_some_and(|c| really_inside(c, p)))+ && !ws.is_some_and(|w| w.is_own_record(p))+ };+ if opened_at(ws, &target).iter().all(|p| p.as_deref().is_some_and(ours)) {+ Decision::Allow+ } else {+ Decision::Ask { title: format!("Change a file outside the project: {target}"), kind }}}"Bash" => match &app {Some(app) => decide_command(&s("command"), app),None => Decision::Ask { title: format!("Run a command: `{}`", s("command")), kind },},- // Reading the web changes nothing (references, engine docs).- "WebFetch" | "WebSearch" => Decision::Allow,+ // Reading the web changes nothing (references, engine docs), so it's allowed unless the+ // project chose otherwise (`ActionKind::Web`).+ "WebFetch" => Decision::Ask { title: format!("Read a web page: {}", s("url")), kind },+ "WebSearch" => Decision::Ask { title: format!("Search the web: {}", s("query")), kind },other => Decision::Ask { title: format!("Use {other}"), kind },}}@@ -415,21 +431,16 @@ pub fn approve_with(if clean_room && let Some(why) = off_limits(ws.as_ref(), tool, input) {return Ok(Err(why));}- match decide(ws.as_ref(), tool, input) {- Decision::Allow => Ok(Ok(())),- Decision::Deny(m) => Ok(Err(m)),- // Auto mode: keep going; only what's never done unasked is refused, without stopping.- Decision::Ask { .. } if auto_mode => Ok(match never_unasked(ws.as_ref(), tool, input) {- Some(why) => Err(why),- None => Ok(()),- }),- Decision::Ask { title, kind } => {+ match outcome(ws.as_ref(), auto_mode, tool, input) {+ Outcome::Allow => Ok(Ok(())),+ Outcome::Refuse(why) => Ok(Err(why)),+ Outcome::Ask { title, remember } => {let Some(inbox) = inbox else {return Ok(Err("Nobody is available to approve this. Stay inside the project folder and use the build commands.".into()));};let detail = serde_json::to_string_pretty(input).unwrap_or_default().chars().take(4000).collect::<String>();waiting();- Ok(match wait_for_approval(&inbox, ws.as_mut(), &title, &detail, &kind, cancelled)? {+ Ok(match wait_for_approval(&inbox, ws.as_mut(), &title, &detail, remember, cancelled)? {Verdict::Yes => Ok(()),Verdict::No(text) => {Err(format!("The person said no{}. Find another way or ask them with core_person_ask.", text.map(|t| format!(": {t}")).unwrap_or_default()))@@ -440,6 +451,41 @@ pub fn approve_with(}}+/// What [`approve_with`] does with one action, before anyone is asked.+#[derive(Debug, PartialEq)]+enum Outcome {+ Allow,+ /// Not done; the builder is told why and keeps going.+ Refuse(String),+ /// A card for the person, and what "always for this project" on it keeps.+ Ask {+ title: String,+ remember: Remember,+ },+}++/// The policy ([`decide`]), then what the person always allowed, then the project's choice for+/// the action's kind, or Auto mode's default for it.+fn outcome(ws: Option<&Workspace>, auto_mode: bool, tool: &str, input: &Value) -> Outcome {+ let (title, action) = match decide(ws, tool, input) {+ Decision::Allow => return Outcome::Allow,+ Decision::Deny(m) => return Outcome::Refuse(m),+ Decision::Ask { title, kind } => (title, kind),+ };+ let kind = kind_of(ws, tool, input);+ let chosen = ws.and_then(|w| w.manifest.approvals.get(&kind).copied());+ // "Always" on an earlier card, for kinds where that was one action rather than the whole kind+ // (a `cd` before a push mustn't let the push through), unless the kind is refused now.+ if remembers_actions(kind) && chosen != Some(Approval::Refuse) && ws.is_some_and(|w| w.manifest.allowed_actions.contains(&action)) {+ return Outcome::Allow;+ }+ match chosen.unwrap_or_else(|| kind.default_in(auto_mode)) {+ Approval::Allow => Outcome::Allow,+ Approval::Refuse => Outcome::Refuse(refusal(kind, chosen.is_some())),+ Approval::Ask => Outcome::Ask { title, remember: if remembers_actions(kind) { Remember::Action(action) } else { Remember::Kind(kind) } },+ }+}+/// What a Clean room builder is told when it reaches for the original.const OFF_LIMITS: &str = "Clean room: the original (its files, its folder, its pages and its code) is off limits. Work from capture/, reference/ and what the person tells you; if you need to look inside, say so and the person can switch on Deep mode.";@@ -511,43 +557,150 @@ fn core_action_approve(ctx: &mut Ctx<'_>, params: Value) -> Result<ToolOutput, T})}-/// In Auto mode, what's still never done without the person: deleting outside the project,-/// changing system files or settings, shutting down, and publishing anywhere. `Some(why)` refuses it.-pub fn never_unasked(ws: Option<&Workspace>, tool: &str, input: &Value) -> Option<String> {+/// Which kind an action the policy asks about is, for the project's choices+/// (`Manifest::approvals`).+pub fn kind_of(ws: Option<&Workspace>, tool: &str, input: &Value) -> ActionKind {let s = |k: &str| input.get(k).and_then(Value::as_str).unwrap_or_default().to_string();- let refuse = |what: &str| Some(format!("Auto mode never {what} without the person. Find another way, or leave it and say so in your summary."));match tool {"Write" | "Edit" | "MultiEdit" | "NotebookEdit" => {let target = if tool == "NotebookEdit" { s("notebook_path") } else { s("file_path") };- let p = resolve_as_opened(ws.map(|w| w.root.clone()).as_deref().unwrap_or(Path::new("/")), &target)?;- // Followed through links: a link in app/ to a system folder is that folder.- let system = SYSTEM_DIRS.iter().any(|d| may_reach(Path::new(d), &p));- // The inbox (where answers are written), the manifest and the other records stay out of reach.- let ours = ws.is_some_and(|w| w.is_own_record(&p));- (system || ours).then(|| refuse("changes system files or Craft Anything's own records")).flatten()+ let system = |p: &Path| {+ // Followed through links: a link in app/ to a system folder is that folder.+ SYSTEM_DIRS.iter().any(|d| may_reach(Path::new(d), p))+ // The inbox (where answers are written), the manifest and the other records+ // stay out of reach.+ || ws.is_some_and(|w| w.is_own_record(p))+ };+ if opened_at(ws, &target).iter().flatten().any(|p| system(p)) { ActionKind::System } else { ActionKind::OutsideFiles }}"Bash" | "PowerShell" => {let command = s("command");let c = command.to_ascii_lowercase();- if PUBLISH.iter().any(|k| c.contains(k)) {- return refuse("publishes or pushes anything");- }- if SYSTEM_COMMANDS.iter().any(|k| c.contains(k)) {- return refuse("changes the system, its settings or its users, or shuts it down");- }+ if publishes(&c) {+ ActionKind::Publish+ } else if SYSTEM_COMMANDS.iter().any(|k| c.contains(k)) || names_records(&c, ws) {+ ActionKind::System// Paths keep their case: on a Mac or Linux `/Users/x` isn't `/users/x`.- if DELETES.iter().any(|k| c.contains(k)) && deletes_outside(&command, ws) {- return refuse("deletes anything outside the project or the temp folder");+ } else if DELETES.iter().any(|k| c.contains(k)) && deletes_outside(&command, ws) {+ ActionKind::DeleteOutside+ } else {+ ActionKind::Commands+ }+ }+ "WebFetch" | "WebSearch" => ActionKind::Web,+ _ => ActionKind::OtherTools,+ }+}++/// Whether "always for this project" on a card of this kind remembers that one action (`bash:npm`,+/// a tool's name) rather than allowing the whole kind. Pushes, deletes outside the project and+/// system changes are allowed whole: "always" on a push allows pushing, and an earlier "always" on+/// some other command that starts the same way (`cd`) doesn't.+fn remembers_actions(kind: ActionKind) -> bool {+ matches!(kind, ActionKind::Web | ActionKind::Commands | ActionKind::OutsideFiles | ActionKind::OtherTools)+}++/// What the builder is told when an action of `kind` is refused: by the project's own choice+/// (`chosen`), or by Auto mode's default.+fn refusal(kind: ActionKind, chosen: bool) -> String {+ let (what, name) = (kind.what(), kind.name());+ if chosen {+ format!(+ "This project refuses {what} (\"{name}\" in its approvals). Find another way, or leave it and say so in your summary; the person can change that choice."+ )+ } else {+ format!(+ "Auto mode never allows {what} without the person. Find another way, or leave it and say so in your summary. The person can choose to allow it, or to be asked, in this project's approvals (\"{name}\")."+ )+ }+}++/// In Auto mode with nothing chosen for the project, what's still never done without the person:+/// deleting outside the project, changing system files or settings, shutting down, publishing+/// anywhere, and tools with no rule. `Some(why)` refuses it.+pub fn never_unasked(ws: Option<&Workspace>, tool: &str, input: &Value) -> Option<String> {+ let kind = kind_of(ws, tool, input);+ (kind.default_in(true) == Approval::Refuse).then(|| refusal(kind, false))+}++/// Whether a lower-cased command pushes or publishes anywhere in it: `git push` (also+/// `git -C app push`), publishing a package or an image, and `gh` commands that change something+/// on GitHub. Each command the shell would run is read on its own: after `;`, `&&`, `|`, a newline,+/// inside `$(…)`, backticks or `bash -c "…"`. `gh … view`, `list`, `clone` and the like only read,+/// and are commands like any other.+fn publishes(c: &str) -> bool {+ c.split([';', '&', '|', '\n', '(', ')', '`', '{', '}', '<', '>']).any(|part| {+ let words: Vec<&str> = part.split_whitespace().map(|w| w.trim_matches(|ch: char| matches!(ch, '"' | '\'' | '$'))).filter(|w| !w.is_empty()).collect();+ words.iter().enumerate().any(|(i, w)| publishes_with(program_name(w), words.get(i + 1..).unwrap_or_default()))+ })+}++/// Whether a lower-cased command names what a builder mustn't change from the shell either: the+/// project's manifest (where its approvals are kept), its inbox (where answers are written), or the+/// tool that sets approvals (`craft-anything-cli` can call it). A command that reaches them without+/// naming them (a script that builds the path) isn't caught here.+fn names_records(c: &str, ws: Option<&Workspace>) -> bool {+ c.contains("craft.json") || c.contains("approvals_set") || c.contains("approvals-set") || ws.is_some_and(|w| mentions(c, &w.inbox_dir()))+}++/// A program's name as typed, without its folder or a Windows extension (`/usr/bin/npm`, `npm.cmd`).+fn program_name(word: &str) -> &str {+ let base = word.rsplit(['/', '\\']).next().unwrap_or(word);+ [".exe", ".cmd", ".bat", ".ps1"].iter().find_map(|x| base.strip_suffix(x)).unwrap_or(base)+}++/// Whether `program` followed by the words `rest` (to the end of its command) pushes or publishes.+fn publishes_with(program: &str, rest: &[&str]) -> bool {+ let has = |w: &str| rest.contains(&w);+ match program {+ "git" => {+ // Past git's own options to the subcommand; `-C dir` and `-c key=value` (both `-c`+ // here, lower-cased) take a value.+ let mut j = 0;+ while let Some(o) = rest.get(j).filter(|o| o.starts_with('-')) {+ j += if *o == "-c" { 2 } else { 1 };}- None+ rest.get(j) == Some(&"push")+ }+ "gh" => gh_publishes(rest),+ // Wherever the subcommand comes (`npm --registry x publish`, `cargo +nightly publish`).+ "npm" | "pnpm" | "yarn" | "bun" | "cargo" => has("publish"),+ "twine" => has("upload"),+ "docker" | "podman" | "gem" => has("push"),+ "dotnet" => has("nuget") && has("push"),+ _ => false,+ }+}++/// `gh` areas that don't change anything on GitHub.+const GH_LOCAL: &[&str] = &["auth", "browse", "search", "help", "config", "alias", "completion", "status", "version", "--version", "--help"];++/// `gh` verbs that only read, or only copy to this computer.+const GH_READS: &[&str] = &["view", "list", "status", "checks", "diff", "download", "clone", "checkout", "watch"];++/// Whether `gh` with these words changes something on GitHub: any verb that isn't one of+/// [`GH_READS`] (`gh issue create`, `gh gist create`, `gh pr merge`…), and `gh api` with a method+/// other than GET or any fields (`-f` and `-F`, lower-cased here, also written `-fkey=v`).+fn gh_publishes(rest: &[&str]) -> bool {+ match rest {+ ["api", args @ ..] => {+ let method = |m: &str| !m.is_empty() && m != "get";+ args.iter().any(|a| {+ (a.starts_with("-f") && !a.starts_with("--"))+ || matches!(*a, "--field" | "--raw-field" | "--input")+ || ["--field=", "--raw-field=", "--input="].iter().any(|p| a.starts_with(p))+ || a.strip_prefix("--method=").is_some_and(method)+ || a.strip_prefix("-x").is_some_and(method)+ }) || args.windows(2).any(|p| matches!(p, [flag, m] if matches!(*flag, "-x" | "--method") && method(m)))}- _ => refuse("uses a tool that has no automatic approval rule"),+ [area, ..] if GH_LOCAL.contains(area) => false,+ [_, verbs @ ..] => verbs.iter().find(|v| !v.starts_with('-')).is_some_and(|v| !GH_READS.contains(v)),+ [] => false,}}const SYSTEM_DIRS: &[&str] =&["C:/Windows", "C:/Program Files", "C:/Program Files (x86)", "C:/ProgramData", "/etc", "/usr", "/bin", "/sbin", "/System", "/Library"];-const PUBLISH: &[&str] = &["git push", "npm publish", "cargo publish", "gh release", "gh pr ", "gh repo", "twine upload", "docker push"];const SYSTEM_COMMANDS: &[&str] = &["shutdown","restart-computer",@@ -653,7 +806,16 @@ pub(crate) enum Verdict {pub(crate) fn ask_approval(ctx: &mut Ctx<'_>, inbox: &Inbox, ws: Option<&mut Workspace>, title: &str, detail: &str, kind: &str) -> Result<Verdict, ToolError> {ctx.report(None, "Waiting for your OK…");let cancel = ctx.cancel.clone();- wait_for_approval(inbox, ws, title, detail, kind, &|| cancel.is_cancelled())+ wait_for_approval(inbox, ws, title, detail, Remember::Action(kind.to_string()), &|| cancel.is_cancelled())+}++/// What "always for this project" on a card keeps.+#[derive(Debug, PartialEq)]+enum Remember {+ /// That one action, in `allowed_actions` (`bash:npm`).+ Action(String),+ /// The whole kind, as the project's choice (`approvals`).+ Kind(ActionKind),}fn wait_for_approval(@@ -661,18 +823,27 @@ fn wait_for_approval(ws: Option<&mut Workspace>,title: &str,detail: &str,- kind: &str,+ remember: Remember,cancelled: &dyn Fn() -> bool,) -> Result<Verdict, ToolError> {- let id = inbox.post(RequestKind::Approval, title, detail, Vec::new(), false, Some(kind.to_string()))?;+ let tag = match &remember {+ Remember::Action(a) => a.clone(),+ Remember::Kind(k) => k.name().to_string(),+ };+ let id = inbox.post(RequestKind::Approval, title, detail, Vec::new(), false, Some(tag))?;Ok(match inbox.wait(&id, WAIT, cancelled) {Some(a) if a.allow == Some(true) => {if a.always&& let Some(w) = ws{- let _ = w.set_person(|m| {- if !m.allowed_actions.iter().any(|k| k == kind) {- m.allowed_actions.push(kind.to_string());+ let _ = w.set_person(|m| match remember {+ Remember::Action(a) => {+ if !m.allowed_actions.contains(&a) {+ m.allowed_actions.push(a);+ }+ }+ Remember::Kind(k) => {+ m.approvals.insert(k, Approval::Allow);}});}@@ -942,8 +1113,10 @@ mod tests {#[test]fn web_reads_and_notes_go_ahead_the_inbox_never_does() {let (_d, w) = ws();- assert_eq!(decide(Some(&w), "WebFetch", &json!({"url": "https://docs.godotengine.org"})), Decision::Allow);- assert_eq!(decide(Some(&w), "WebSearch", &json!({"query": "unity batchmode build"})), Decision::Allow);+ for auto_mode in [true, false] {+ assert_eq!(outcome(Some(&w), auto_mode, "WebFetch", &json!({"url": "https://docs.godotengine.org"})), Outcome::Allow);+ assert_eq!(outcome(Some(&w), auto_mode, "WebSearch", &json!({"query": "unity batchmode build"})), Outcome::Allow);+ }let note = w.checks_dir().join("round-1/notes.md");assert_eq!(decide(Some(&w), "Write", &json!({"file_path": note.display().to_string()})), Decision::Allow);for off in [w.inbox_dir().join("1.answer.json"), w.root.join("craft.json"), w.root.join("reference/picture-1.png")] {@@ -955,18 +1128,173 @@ mod tests {fn remembered_kinds_and_reads() {let (_d, mut w) = ws();let cmd = json!({"command": "lsblk"});- assert!(matches!(decide(Some(&w), "Bash", &cmd), Decision::Ask { .. }));+ assert!(matches!(outcome(Some(&w), false, "Bash", &cmd), Outcome::Ask { remember: Remember::Action(_), .. }));w.manifest.allowed_actions.push("bash:lsblk".into());- assert_eq!(decide(Some(&w), "Bash", &cmd), Decision::Allow, "\"always for this project\" is remembered");- assert_eq!(decide(None, "Read", &json!({})), Decision::Allow);+ assert_eq!(outcome(Some(&w), false, "Bash", &cmd), Outcome::Allow, "\"always for this project\" is remembered");+ assert_eq!(outcome(None, false, "Read", &json!({})), Outcome::Allow);+ // A kind the person refuses later wins over what they always allowed before; asking keeps it.+ w.manifest.approvals.insert(ActionKind::Commands, Approval::Refuse);+ assert!(matches!(outcome(Some(&w), true, "Bash", &cmd), Outcome::Refuse(_)));+ w.manifest.approvals.insert(ActionKind::Commands, Approval::Ask);+ assert_eq!(outcome(Some(&w), true, "Bash", &cmd), Outcome::Allow);}#[test]- fn approval_round_trip_through_the_inbox() {+ fn a_shell_command_that_names_the_projects_records_is_a_system_change() {+ // Commands are allowed in Auto mode; these would let a builder loosen its own approvals.+ let (_d, w) = ws();+ let inbox = w.inbox_dir().display().to_string();+ for cmd in [+ "craft-anything-cli call project_approvals_set --project . --kind publish --mode allow",+ "craft-anything-cli project-approvals-set --kind publish --mode allow",+ "python -c \"import json; d=json.load(open('craft.json'))\"",+ "echo '{}' > ../craft.json",+ &format!("echo yes > \"{inbox}/1.answer.json\""),+ ] {+ assert_eq!(kind_of(Some(&w), "Bash", &json!({"command": cmd})), ActionKind::System, "{cmd}");+ assert!(matches!(outcome(Some(&w), true, "Bash", &json!({"command": cmd})), Outcome::Refuse(_)), "{cmd}");+ }+ assert_eq!(kind_of(Some(&w), "Bash", &json!({"command": "cat package.json"})), ActionKind::Commands);+ }++ #[test]+ fn a_relative_path_is_judged_wherever_the_agent_opens_it() {+ // Agents start in the project folder: `craft.json` there is the manifest, not app/craft.json.let (_d, w) = ws();+ let write = |p: &str| json!({"file_path": p});+ for record in ["craft.json", "inbox/1.answer.json", "./craft.json"] {+ assert!(matches!(decide(Some(&w), "Write", &write(record)), Decision::Ask { .. }), "{record}");+ assert_eq!(kind_of(Some(&w), "Write", &write(record)), ActionKind::System, "{record}");+ assert!(matches!(outcome(Some(&w), true, "Write", &write(record)), Outcome::Refuse(_)), "{record}");+ }+ // Inside app/ from either folder, or written in full, it's the builder's own work.+ assert_eq!(decide(Some(&w), "Write", &write("app/src/main.rs")), Decision::Allow);+ let full = w.app_dir().join("src/main.rs");+ assert_eq!(decide(Some(&w), "Write", &write(&full.display().to_string())), Decision::Allow);+ // A bare name could be the project folder's or app/'s: asked about, not refused.+ assert!(matches!(decide(Some(&w), "Write", &write("src/main.rs")), Decision::Ask { .. }));+ assert_eq!(kind_of(Some(&w), "Write", &write("src/main.rs")), ActionKind::OutsideFiles);+ }++ #[test]+ fn an_earlier_always_never_lets_a_push_through() {+ // "Always" on `cd app && npm i` was kept as `bash:cd`, and the same start let any later+ // command through, pushes included.+ let (_d, mut w) = ws();+ w.manifest.allowed_actions.push("bash:cd".into());+ let push = json!({"command": "cd app && git push origin main"});+ assert!(matches!(outcome(Some(&w), true, "Bash", &push), Outcome::Refuse(_)), "Auto mode still refuses it");+ assert!(matches!(outcome(Some(&w), false, "Bash", &push), Outcome::Ask { remember: Remember::Kind(ActionKind::Publish), .. }));+ assert_eq!(outcome(Some(&w), true, "Bash", &json!({"command": "cd app && lsblk"})), Outcome::Allow);+ }++ #[test]+ fn a_projects_choice_decides_each_kind() {+ let (_d, mut w) = ws();+ let push = json!({"command": "git push origin main"});+ let fetch = json!({"url": "https://example.com/"});+ // Nothing chosen: Auto mode refuses a push and asks nobody; without it, the person is asked.+ let Outcome::Refuse(why) = outcome(Some(&w), true, "Bash", &push) else { panic!("refused") };+ assert!(why.contains("Auto mode never") && why.contains("\"publish\""), "{why}");+ assert!(matches!(outcome(Some(&w), false, "Bash", &push), Outcome::Ask { .. }));+ // Pushes asked about, even in Auto mode: the card it was missing.+ w.manifest.approvals.insert(ActionKind::Publish, Approval::Ask);+ let Outcome::Ask { title, remember } = outcome(Some(&w), true, "Bash", &push) else { panic!("asked") };+ assert!(title.contains("git push"));+ assert_eq!(remember, Remember::Kind(ActionKind::Publish));+ // Allowed for this project: no card.+ w.manifest.approvals.insert(ActionKind::Publish, Approval::Allow);+ assert_eq!(outcome(Some(&w), true, "Bash", &push), Outcome::Allow);+ // Each kind on its own: the web can be refused while pushing is allowed.+ w.manifest.approvals.insert(ActionKind::Web, Approval::Refuse);+ let Outcome::Refuse(why) = outcome(Some(&w), true, "WebFetch", &fetch) else { panic!("refused") };+ assert!(why.contains("This project refuses reading the web"), "{why}");+ assert_eq!(outcome(Some(&w), true, "Bash", &push), Outcome::Allow);+ // Commands the build list allows aren't asked about, whatever "commands" gets.+ w.manifest.approvals.insert(ActionKind::Commands, Approval::Refuse);+ assert_eq!(outcome(Some(&w), true, "Bash", &json!({"command": "npm run build"})), Outcome::Allow);+ assert!(matches!(outcome(Some(&w), true, "Bash", &json!({"command": "lsblk"})), Outcome::Refuse(_)));+ }++ #[test]+ fn pushes_and_publishes_are_told_from_commands_that_only_read() {+ let kind = |c: &str| kind_of(None, "Bash", &json!({"command": c}));+ for publish in [+ "git push origin main",+ "cd app && git push -u origin feat/x 2>&1 | tail -4",+ "git -C app push",+ "git -c core.hooksPath=x push --tags",+ "ANICRAFT_FIRST_PUBLISH=1 git push origin main v0.1.0",+ "/usr/bin/git push",+ "npm publish --access public",+ "cargo publish",+ "gh pr create --fill",+ "gh pr merge 12 --squash",+ "gh repo create storytold/x --public",+ "gh release create v1.0.0",+ "gh api repos/o/r/pulls/1/merge -X PUT",+ "gh api repos/o/r/issues -f title=x",+ "docker push img:1",+ "twine upload dist/*",+ // Another command the shell runs, without spaces or inside another one.+ "x;git push",+ "cd app&&git push",+ "echo $(git push)",+ "echo `git push`",+ "bash -c \"git push origin main\"",+ "ls | git push",+ // Packages and images however they're started.+ "/usr/local/bin/npm publish",+ "npm.cmd publish",+ "npm --registry https://r.example publish",+ "cargo +nightly publish",+ "docker image push img:1",+ "dotnet nuget push x.nupkg",+ // Anything gh changes on GitHub, and gh api's attached flags.+ "gh issue create --title x",+ "gh issue comment 3 --body x",+ "gh gist create --public notes.md",+ "gh api repos/o/r/pulls/1/merge -XPUT",+ "gh api repos/o/r/issues -ftitle=x",+ "gh api repos/o/r/issues --method=POST",+ ] {+ assert_eq!(kind(publish), ActionKind::Publish, "{publish}");+ }+ for reads in [+ "gh repo view storytold/AniCraft --json name,visibility",+ "gh pr view 12",+ "gh pr list",+ "gh release list",+ "gh pr checks 12",+ "gh api repos/o/r/pulls",+ "gh auth status",+ "git ls-remote origin",+ "git log --oneline -5",+ "git status",+ "npm run publish-docs",+ "gh repo clone storytold/craft-anything",+ "gh pr checkout 12",+ "gh run watch 42",+ "gh api repos/o/r/pulls -XGET",+ "gh pr",+ "cd /d/repos/git && ls",+ "npm install && echo published",+ ] {+ assert_eq!(kind(reads), ActionKind::Commands, "{reads}");+ }+ }++ #[test]+ fn approval_round_trip_through_the_inbox() {+ let (_d, mut w) = ws();let e = std::sync::Arc::new(crate::Engine::new(crate::testing::session()));- // Asking is what Auto mode switches off.- e.session().settings.auto_mode = false;+ // Auto mode is on, and the project asks about pushes: the card reaches the person and+ // their OK reaches the builder.+ assert!(e.session().settings.auto_mode);+ w.set_person(|m| {+ m.approvals.insert(ActionKind::Publish, Approval::Ask);+ })+ .unwrap();e.session().ext.insert(std::sync::Arc::new(InboxDir(w.inbox_dir())));let inbox = Inbox::new(w.inbox_dir());let answerer = std::thread::spawn(move || {@@ -987,7 +1315,8 @@ mod tests {assert_eq!(v["result"]["behavior"], "allow");assert_eq!(v["result"]["updatedInput"]["command"], "git push");let reopened = Workspace::open(&w.root).unwrap();- assert!(reopened.manifest.allowed_actions.contains(&"bash:git".to_string()), "always-allow is remembered");+ assert_eq!(reopened.manifest.approvals.get(&ActionKind::Publish), Some(&Approval::Allow), "\"always\" allows pushing in this project");+ assert!(reopened.manifest.allowed_actions.is_empty(), "not as `bash:git`, which would let every git command through");// Without an inbox, a question is a clear, actionable error.let e2 = crate::Engine::new(crate::testing::session());e2.session().settings.auto_mode = false;@@ -995,6 +1324,40 @@ mod tests {assert!(err.remediation.unwrap_or_default().contains("sensible choice"));}+ #[test]+ fn the_person_chooses_approvals_and_an_agent_can_only_tighten_them() {+ let (_d, w) = ws();+ let e = crate::Engine::new(crate::testing::session());+ let call = |caller: crate::Caller, p: Value| e.call("project_approvals_set", p, crate::CallOptions::new(caller));+ let gets = |v: &Value, kind: &str| v["kinds"].as_array().unwrap().iter().find(|k| k["kind"] == kind).unwrap()["gets"].clone();+ // Read: every kind, with what Auto mode gives it.+ let read = call(crate::Caller::Ui, json!({"project": w.root})).unwrap().to_json()["result"].clone();+ assert_eq!(read["kinds"].as_array().unwrap().len(), crate::workspace::ACTION_KINDS.len());+ assert_eq!((gets(&read, "publish"), gets(&read, "web")), (json!("refuse"), json!("allow")));+ // The person allows pushes from the app; it's kept in craft.json.+ let set = call(crate::Caller::Ui, json!({"project": w.root, "kind": "publish", "mode": "allow"})).unwrap().to_json()["result"].clone();+ assert_eq!(gets(&set, "publish"), "allow");+ assert_eq!((set["set"]["kind"].as_str(), set["set"]["gets"].as_str()), (Some("publish"), Some("allow")), "says what changed");+ assert!(read["set"].is_null(), "a read changes nothing");+ assert_eq!(Workspace::open(&w.root).unwrap().manifest.approvals.get(&ActionKind::Publish), Some(&Approval::Allow));+ // A builder may make a kind stricter, not looser: not even back to a default that allows more.+ assert!(call(crate::Caller::Mcp, json!({"project": w.root, "kind": "publish", "mode": "ask"})).is_ok());+ call(crate::Caller::Ui, json!({"project": w.root, "kind": "commands", "mode": "refuse"})).unwrap();+ for (kind, mode) in [("publish", "allow"), ("other_tools", "ask"), ("commands", "default"), ("outside_files", "allow")] {+ let err = call(crate::Caller::Mcp, json!({"project": w.root, "kind": kind, "mode": mode})).unwrap_err();+ assert_eq!(err.code, ErrorCode::NoPermission, "{kind} {mode}");+ }+ assert!(call(crate::Caller::Agent, json!({"project": w.root, "kind": "web", "mode": "refuse"})).is_ok());+ let m = Workspace::open(&w.root).unwrap().manifest;+ assert_eq!((m.approvals.get(&ActionKind::Publish), m.approvals.get(&ActionKind::Web)), (Some(&Approval::Ask), Some(&Approval::Refuse)));+ // `default` takes the choice away; a mode needs a kind and the other way round.+ call(crate::Caller::Cli, json!({"project": w.root, "kind": "web", "mode": "default"})).unwrap();+ assert!(!Workspace::open(&w.root).unwrap().manifest.approvals.contains_key(&ActionKind::Web));+ assert!(call(crate::Caller::Ui, json!({"project": w.root, "kind": "web"})).is_err());+ assert!(call(crate::Caller::Ui, json!({"project": w.root, "mode": "allow"})).is_err());+ assert!(call(crate::Caller::Ui, json!({"project": w.root, "kind": "everything", "mode": "allow"})).is_err());+ }+#[test]fn a_projects_choice_decides_whether_questions_reach_the_person() {let (_d, w) = ws();diff --git a/crates/engine/src/tools/project_tools.rs b/crates/engine/src/tools/project_tools.rsindex 50ec14d0..70d2113b 100644--- a/crates/engine/src/tools/project_tools.rs+++ b/crates/engine/src/tools/project_tools.rs@@ -5,7 +5,7 @@use crate::feed;use crate::inbox::{Answer, Inbox};use crate::tool::{Ctx, Effects, Requires, ToolOutput, ToolSpec, Toolset, parse_params, schema_of};-use crate::workspace::Workspace;+use crate::workspace::{ACTION_KINDS, ActionKind, Approval, Workspace};use craft_anything_evidence::{ErrorCode, ToolError};use craft_anything_platform::sync::Mutex;use schemars::JsonSchema;@@ -141,6 +141,17 @@ pub fn specs() -> Vec<ToolSpec> {input_schema: schema_of::<QuestionsParams>,run: project_questions_set,},+ ToolSpec {+ id: "project_approvals_set",+ title: "Choose what the builder's approvals get",+ summary: "Choose, for one kind of builder action in a project, whether it goes ahead (`allow`), waits for the person's OK on a card (`ask`) or is refused (`refuse`); `default` follows Auto mode. Kinds: `web` (reading websites, searching), `commands` (outside the usual build commands), `outside_files` (changing files outside the project), `publish` (git push, npm publish, gh pr create…), `delete_outside`, `system` (system changes and files, Craft Anything's own records), `other_tools`. With no kind, says what every kind gets now. Takes effect from the builder's next action, also mid-build. Only the person changes these: an agent's call may only make a kind stricter.",+ beginner: "Chooses what the builder may do without asking you.",+ toolset: Toolset::Projects,+ effects: Effects::WRITES_FILESYSTEM,+ requires: Requires::Nothing,+ input_schema: schema_of::<ApprovalsParams>,+ run: project_approvals_set,+ },ToolSpec {id: "project_build_finish",title: "Call the build done",@@ -384,6 +395,86 @@ fn project_questions_set(ctx: &mut Ctx<'_>, params: Value) -> Result<ToolOutput,})))}+/// What one kind of a project's builder actions should get.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, JsonSchema)]+#[serde(rename_all = "snake_case")]+pub enum ApprovalChoice {+ Allow,+ Ask,+ Refuse,+ /// What Auto mode gives it.+ Default,+}++#[derive(Debug, Deserialize, JsonSchema)]+#[serde(deny_unknown_fields)]+pub struct ApprovalsParams {+ /// The project's folder.+ pub project: PathBuf,+ /// The kind of action (`publish`, `web`…); none just reads what every kind gets.+ #[serde(default)]+ pub kind: Option<ActionKind>,+ /// `allow`, `ask`, `refuse` or `default`; needed with `kind`.+ #[serde(default)]+ pub mode: Option<ApprovalChoice>,+}++fn project_approvals_set(ctx: &mut Ctx<'_>, params: Value) -> Result<ToolOutput, ToolError> {+ let p: ApprovalsParams = parse_params(params)?;+ let mut ws = open(&p.project)?;+ let auto_mode = ctx.session.settings.auto_mode;+ let mut set = None;+ match (p.kind, p.mode) {+ (Some(kind), Some(mode)) => {+ set = Some(kind);+ let chosen = match mode {+ ApprovalChoice::Allow => Some(Approval::Allow),+ ApprovalChoice::Ask => Some(Approval::Ask),+ ApprovalChoice::Refuse => Some(Approval::Refuse),+ ApprovalChoice::Default => None,+ };+ // A builder (or any agent) can't let itself do more: what it's held to is the person's+ // to loosen, from the app or the CLI. Checked with Auto mode on and off, so switching it+ // later doesn't hand over what the agent changed (an unchosen kind set to its default+ // now, or a refusal given back to a default that asks).+ let agent = matches!(ctx.caller, crate::Caller::Mcp | crate::Caller::Agent);+ let looser = [true, false]+ .into_iter()+ .any(|auto| chosen.unwrap_or_else(|| kind.default_in(auto)).strictness() < ws.manifest.approval(kind, auto).strictness());+ if agent && looser {+ return Err(ToolError::new(ErrorCode::NoPermission, format!("An agent can't loosen what \"{}\" gets in this project.", kind.name()))+ .with_remediation("Ask the person to change it in the app (the project's approvals) or with the CLI."));+ }+ ws.set_person(|m| match chosen {+ Some(a) => {+ m.approvals.insert(kind, a);+ }+ None => {+ m.approvals.remove(&kind);+ }+ })?;+ }+ (Some(_), None) => return Err(ToolError::invalid("mode is needed with kind: allow, ask, refuse or default")),+ (None, Some(_)) => return Err(ToolError::invalid("kind is needed with mode")),+ (None, None) => {}+ }+ let kinds: Vec<Value> = ACTION_KINDS+ .iter()+ .map(|r| {+ json!({+ "kind": r.kind,+ "what": r.what,+ "gets": ws.manifest.approval(r.kind, auto_mode),+ "chosen": ws.manifest.approvals.get(&r.kind),+ "default": r.kind.default_in(auto_mode),+ })+ })+ .collect();+ // The kind just set and what it gets now, so a client can say what changed.+ let set = set.map(|k| json!({"kind": k, "gets": ws.manifest.approval(k, auto_mode), "chosen": ws.manifest.approvals.get(&k)}));+ Ok(ToolOutput::Value(json!({"project": ws.root, "auto_mode": auto_mode, "set": set, "kinds": kinds})))+}+#[derive(Debug, Deserialize, JsonSchema)]#[serde(deny_unknown_fields)]pub struct PlayParams {diff --git a/crates/engine/src/workspace.rs b/crates/engine/src/workspace.rsindex 7075bd3f..464587a8 100644--- a/crates/engine/src/workspace.rs+++ b/crates/engine/src/workspace.rs@@ -78,10 +78,10 @@ fn copy_tree(from: &Path, to: &Path, skip: &dyn Fn(&Path) -> bool, depth: usize)}/// The current `craft.json` format version. Bumping it means appending a step to [`MANIFEST_STEPS`].-pub const MANIFEST_VERSION: u32 = 2;+pub const MANIFEST_VERSION: u32 = 3;/// The steps that bring an older `craft.json` forward; step `i` goes from version `i` to `i + 1`.-const MANIFEST_STEPS: &[versioned::Step<Value>] = &[manifest_v0_to_v1, manifest_v1_to_v2];+const MANIFEST_STEPS: &[versioned::Step<Value>] = &[manifest_v0_to_v1, manifest_v1_to_v2, manifest_v2_to_v3];const _: () = assert!(MANIFEST_STEPS.len() == MANIFEST_VERSION as usize, "one step per craft.json version");/// Version 0 (no `version` field) has the same shape as version 1; only the number is new.@@ -96,6 +96,13 @@ fn manifest_v1_to_v2(doc: &mut Value) -> Result<(), String> {if doc.is_object() { Ok(()) } else { Err("the manifest isn't a JSON object".into()) }}+/// Version 3 adds the person's approval choices (`approvals`), none by default. The number is new+/// so an older build, which would drop them when it saves (a refused kind would then follow Auto+/// mode again), opens such a project read-only instead.+fn manifest_v2_to_v3(doc: &mut Value) -> Result<(), String> {+ if doc.is_object() { Ok(()) } else { Err("the manifest isn't a JSON object".into()) }+}+/// Read a `craft.json` document of any version this build understands. A newer manifest is read/// as far as its fields are known and keeps its version, so [`Workspace::save`] refuses to write it.pub fn read_manifest(bytes: &[u8]) -> Result<Manifest, ToolError> {@@ -413,6 +420,11 @@ pub struct Manifest {/// (`Settings::questions`). The person's, like the budget.#[serde(default, skip_serializing_if = "Option::is_none")]pub questions: Option<Questions>,+ /// What the builder's approvals get in this project, by kind of action; a kind that isn't here+ /// follows Auto mode ([`ActionKind::default_in`]). The person's, like the budget.+ #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]+ #[schemars(schema_with = "approvals_schema")]+ pub approvals: std::collections::BTreeMap<ActionKind, Approval>,/// The builder finished its turn and the run's checks haven't reported on it yet, so a run/// that picks this up only needs to check: nothing is left to build.#[serde(default, skip_serializing_if = "std::ops::Not::not")]@@ -457,6 +469,7 @@ impl Manifest {start_files: Vec::new(),builder: None,questions: None,+ approvals: Default::default(),awaiting_check: false,not_working_checks: 0,}@@ -475,6 +488,7 @@ impl Manifest {self.allowed_actions = other.allowed_actions.clone();self.builder.clone_from(&other.builder);self.questions = other.questions;+ self.approvals.clone_from(&other.approvals);self.name.clone_from(&other.name);}}@@ -668,14 +682,15 @@ impl Workspace {// Ready stays ready; anything else can carry on (with a new conversation).copy.manifest.status = if m.status == Status::Ready { Status::Ready } else { Status::Stopped };copy.save()?;- let (budget, generate, builder, allowed, questions) =- (m.asset_budget_usd, m.generate_assets, m.builder.clone(), m.allowed_actions.clone(), m.questions);+ let (budget, generate, builder, allowed, questions, approvals) =+ (m.asset_budget_usd, m.generate_assets, m.builder.clone(), m.allowed_actions.clone(), m.questions, m.approvals.clone());copy.set_person(|c| {c.asset_budget_usd = budget;c.generate_assets = generate;c.builder = builder;c.allowed_actions = allowed;c.questions = questions;+ c.approvals = approvals;})?;Ok(copy)}@@ -1028,6 +1043,137 @@ pub enum Questions {Decide,}+/// A kind of builder action that asks for approval, which a project can decide about ahead of time+/// (`Manifest::approvals`).+#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, JsonSchema)]+#[serde(rename_all = "snake_case")]+pub enum ActionKind {+ /// Reading websites and searching the web.+ Web,+ /// Commands outside the usual build commands.+ Commands,+ /// Changing files outside the project.+ OutsideFiles,+ /// Pushing to a git server or publishing anywhere (`git push`, `npm publish`, `gh pr create`…).+ Publish,+ /// Deleting anything outside the project or the temp folder.+ DeleteOutside,+ /// Changing the system, its settings or users, system files, or Craft Anything's own records.+ System,+ /// Tools with no rule of their own.+ OtherTools,+}++/// What an action of one [`ActionKind`] gets.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]+#[serde(rename_all = "snake_case")]+pub enum Approval {+ /// Done without asking.+ Allow,+ /// A card for the person, and the builder waits for the answer.+ Ask,+ /// Not done, without asking: the builder is told to find another way.+ Refuse,+}++/// `Manifest::approvals` in the published schema: only the kinds' names as keys, which a map's+/// own schema leaves open.+fn approvals_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {+ let names: Vec<&str> = ACTION_KINDS.iter().map(|r| r.name).collect();+ schemars::json_schema!({+ "type": "object",+ "propertyNames": { "enum": names },+ "additionalProperties": generator.subschema_for::<Approval>(),+ })+}++/// One row of [`ACTION_KINDS`].+#[derive(Debug, Clone, Copy)]+pub struct KindRow {+ pub kind: ActionKind,+ /// Its name in tools and slash commands.+ pub name: &'static str,+ /// What it covers, as the builder is told when it's refused ("pushing or publishing anything").+ pub what: &'static str,+ /// What it gets when the project hasn't chosen, with Auto mode on and off.+ pub auto: Approval,+ pub manual: Approval,+}++/// Every kind. Auto mode lets through what can be undone and refuses the rest; without it,+/// everything but reading the web asks.+pub const ACTION_KINDS: &[KindRow] = &[+ KindRow { kind: ActionKind::Web, name: "web", what: "reading the web", auto: Approval::Allow, manual: Approval::Allow },+ KindRow { kind: ActionKind::Commands, name: "commands", what: "commands outside the usual build commands", auto: Approval::Allow, manual: Approval::Ask },+ KindRow { kind: ActionKind::OutsideFiles, name: "outside_files", what: "changing files outside the project", auto: Approval::Allow, manual: Approval::Ask },+ KindRow { kind: ActionKind::Publish, name: "publish", what: "pushing or publishing anything", auto: Approval::Refuse, manual: Approval::Ask },+ KindRow {+ kind: ActionKind::DeleteOutside,+ name: "delete_outside",+ what: "deleting anything outside the project or the temp folder",+ auto: Approval::Refuse,+ manual: Approval::Ask,+ },+ KindRow {+ kind: ActionKind::System,+ name: "system",+ what: "changing the system, its settings or users, system files, or Craft Anything's own records",+ auto: Approval::Refuse,+ manual: Approval::Ask,+ },+ KindRow {+ kind: ActionKind::OtherTools,+ name: "other_tools",+ what: "tools with no approval rule of their own",+ auto: Approval::Refuse,+ manual: Approval::Ask,+ },+];++impl ActionKind {+ fn row(self) -> Option<&'static KindRow> {+ ACTION_KINDS.iter().find(|r| r.kind == self)+ }++ /// Its name in tools and slash commands (`publish`).+ pub fn name(self) -> &'static str {+ self.row().map_or("", |r| r.name)+ }++ /// What it covers, in words for the builder.+ pub fn what(self) -> &'static str {+ self.row().map_or("", |r| r.what)+ }++ /// The kind named `name`, in any case.+ pub fn named(name: &str) -> Option<ActionKind> {+ ACTION_KINDS.iter().find(|r| r.name.eq_ignore_ascii_case(name)).map(|r| r.kind)+ }++ /// What it gets when the project hasn't chosen.+ pub fn default_in(self, auto_mode: bool) -> Approval {+ self.row().map_or(Approval::Ask, |r| if auto_mode { r.auto } else { r.manual })+ }+}++impl Approval {+ /// How much it holds back: allow, then ask, then refuse.+ pub fn strictness(self) -> u8 {+ match self {+ Approval::Allow => 0,+ Approval::Ask => 1,+ Approval::Refuse => 2,+ }+ }+}++impl Manifest {+ /// What an action of `kind` gets in this project.+ pub fn approval(&self, kind: ActionKind, auto_mode: bool) -> Approval {+ self.approvals.get(&kind).copied().unwrap_or_else(|| kind.default_in(auto_mode))+ }+}+/// What the files already in a picked folder are to a new project.#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]#[serde(rename_all = "snake_case")]@@ -1474,6 +1620,41 @@ mod tests {assert_eq!(Workspace::open(dir.path()).unwrap().manifest, ws.manifest);}+ #[test]+ fn approval_choices_survive_an_old_manifest_a_stale_save_and_a_copy() {+ // A version-2 craft.json (before approvals) opens with none chosen and is saved as version 3.+ let dir = tempfile::tempdir().unwrap();+ let v2 = MANIFEST_V0.replacen('{', r#"{ "version": 2,"#, 1);+ std::fs::write(dir.path().join(MANIFEST), &v2).unwrap();+ let mut run = Workspace::open(dir.path()).unwrap();+ assert_eq!((run.manifest.version, run.manifest.approvals.is_empty(), run.is_read_only()), (3, true, false));+ run.save().unwrap();+ let saved: Value = serde_json::from_slice(&std::fs::read(dir.path().join(MANIFEST)).unwrap()).unwrap();+ assert_eq!(saved["version"], 3);+ assert!(saved.get("approvals").is_none(), "nothing chosen, nothing written");+ // The person chooses while a run holds an older copy; the run's save keeps the choice.+ Workspace::open(dir.path())+ .unwrap()+ .set_person(|m| {+ m.approvals.insert(ActionKind::Publish, Approval::Ask);+ m.approvals.insert(ActionKind::Commands, Approval::Refuse);+ })+ .unwrap();+ run.manifest.note = "Building".into();+ run.save().unwrap();+ let disk = Workspace::open(dir.path()).unwrap().manifest;+ assert_eq!(disk.approvals.get(&ActionKind::Publish), Some(&Approval::Ask));+ assert_eq!(disk.approval(ActionKind::Commands, true), Approval::Refuse);+ let saved: Value = serde_json::from_slice(&std::fs::read(dir.path().join(MANIFEST)).unwrap()).unwrap();+ assert_eq!(saved["approvals"], serde_json::json!({"commands": "refuse", "publish": "ask"}));+ // A copy keeps them.+ let copy = Workspace::open(dir.path()).unwrap().duplicate("Example copy").unwrap();+ assert_eq!(Workspace::open(©.root).unwrap().manifest.approvals, disk.approvals);+ // An unknown kind isn't read as something else.+ let unknown = MANIFEST_V0.replacen('{', r#"{ "version": 3, "approvals": {"everything": "allow"},"#, 1);+ assert!(read_manifest(unknown.as_bytes()).is_err());+ }+#[test]fn newer_manifests_open_read_only_and_are_never_overwritten() {let dir = tempfile::tempdir().unwrap();diff --git a/crates/ui-egui/src/demo.rs b/crates/ui-egui/src/demo.rsindex 3021a0d4..89ae0753 100644--- a/crates/ui-egui/src/demo.rs+++ b/crates/ui-egui/src/demo.rs@@ -238,6 +238,7 @@ fn workspace(slug: &str, name: &str, request: &str, target: TargetRef, status: Sstart_files: Vec::new(),builder: None,questions: None,+ approvals: Default::default(),awaiting_check: false,not_working_checks: 0,},diff --git a/crates/ui-egui/src/fr.tsv b/crates/ui-egui/src/fr.tsvindex a5dac1be..9993ea0f 100644--- a/crates/ui-egui/src/fr.tsv+++ b/crates/ui-egui/src/fr.tsv@@ -1443,3 +1443,4 @@ yesterday hier… {} older … {} plus anciensDrag to give the plan more or less room; double-click to reset Faites glisser pour donner plus ou moins de place au plan ; double-cliquez pour rétablirCopy the message Copier le message+Choose what the builder's approvals get Choisir ce que reçoivent les autorisations du constructeurdiff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsvindex a21ff9b1..380dcf36 100644--- a/crates/ui-egui/src/i18n/cs.tsv+++ b/crates/ui-egui/src/i18n/cs.tsv@@ -1444,3 +1444,4 @@ Zoom ZvětšitBring all to front Vše do popředíDrag to give the plan more or less room; double-click to reset Přetažením dáte plánu víc nebo míň místa; dvojklikem vrátíte výchozí výškuCopy the message Zkopírovat zprávu+Choose what the builder's approvals get Vybrat, jak se naloží se schvalováním sestavovacího agentadiff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsvindex 3adb7dc7..945792d8 100644--- a/crates/ui-egui/src/i18n/de.tsv+++ b/crates/ui-egui/src/i18n/de.tsv@@ -1444,3 +1444,4 @@ Zoom ZoomenBring all to front Alle nach vorne bringenDrag to give the plan more or less room; double-click to reset Ziehen, um dem Plan mehr oder weniger Platz zu geben; Doppelklick setzt zurückCopy the message Die Nachricht kopieren+Choose what the builder's approvals get Festlegen, was die Freigaben des Builders erhaltendiff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsvindex 793662cb..e15e7b9c 100644--- a/crates/ui-egui/src/i18n/es.tsv+++ b/crates/ui-egui/src/i18n/es.tsv@@ -1444,3 +1444,4 @@ Zoom ZoomBring all to front Traer todo al frenteDrag to give the plan more or less room; double-click to reset Arrastra para darle al plan más o menos espacio; doble clic para restablecerCopy the message Copiar el mensaje+Choose what the builder's approvals get Elegir qué reciben las aprobaciones del constructordiff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsvindex 79306645..9721d5ee 100644--- a/crates/ui-egui/src/i18n/it.tsv+++ b/crates/ui-egui/src/i18n/it.tsv@@ -1446,3 +1446,4 @@ Zoom ZoomBring all to front Porta tutto in primo pianoCopy the message Copia il messaggioDrag to give the plan more or less room; double-click to reset Trascina per dare al piano più o meno spazio; doppio clic per ripristinare+Choose what the builder's approvals get Scegli cosa ricevono le approvazioni del costruttorediff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsvindex 7e6e594f..7862adfe 100644--- a/crates/ui-egui/src/i18n/ka.tsv+++ b/crates/ui-egui/src/i18n/ka.tsv@@ -1444,3 +1444,4 @@ Reasoning მსჯელობაShow model options მოდელის პარამეტრების ჩვენებაStandard სტანდარტულიWhere is your project? სად არის თქვენი პროექტი?+Choose what the builder's approvals get აირჩიეთ, რას იღებს ამწყობის ნებართვებიdiff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsvindex 01beea23..5496e7dc 100644--- a/crates/ui-egui/src/i18n/ko.tsv+++ b/crates/ui-egui/src/i18n/ko.tsv@@ -1444,3 +1444,4 @@ Zoom 확대/축소Bring all to front 모두 앞으로 가져오기Drag to give the plan more or less room; double-click to reset 끌어서 계획이 차지하는 공간을 조절하고, 두 번 클릭하면 원래대로 돌아갑니다Copy the message 메시지 복사+Choose what the builder's approvals get 빌더의 승인 요청을 어떻게 처리할지 고르기diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsvindex 3ff2aee2..1b7ae14d 100644--- a/crates/ui-egui/src/i18n/pt-br.tsv+++ b/crates/ui-egui/src/i18n/pt-br.tsv@@ -1444,3 +1444,4 @@ Bring all to front Trazer todas para a frenteDrag to give the plan more or less room; double-click to reset Arraste para ajustar o espaço do plano. Clique duas vezes para restaurar o tamanho originalCopy the message Copiar a mensagem{n} · ${spent} of ${budget} {n} · ${spent} de ${budget}+Choose what the builder's approvals get Escolher o que as aprovações do agente recebemdiff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsvindex 76b51e77..0df699d2 100644--- a/crates/ui-egui/src/i18n/ru.tsv+++ b/crates/ui-egui/src/i18n/ru.tsv@@ -1444,3 +1444,4 @@ Zoom Изменить масштабBring all to front Все окна — на передний планDrag to give the plan more or less room; double-click to reset Перетащите, чтобы дать плану больше или меньше места; двойной щелчок возвращает как былоCopy the message Скопировать сообщение+Choose what the builder's approvals get Выбрать, что получают разрешения конструктораdiff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsvindex 53b8363a..fc59d6f7 100644--- a/crates/ui-egui/src/i18n/tr.tsv+++ b/crates/ui-egui/src/i18n/tr.tsv@@ -1444,3 +1444,4 @@ Zoom YakınlaştırBring all to front Tümünü öne getirDrag to give the plan more or less room; double-click to reset Plana daha fazla veya daha az yer vermek için sürükleyin; sıfırlamak için çift tıklayınCopy the message Mesajı kopyala+Choose what the builder's approvals get Oluşturucunun onaylarına ne olacağını seçdiff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsvindex 135792a1..7e35db06 100644--- a/crates/ui-egui/src/i18n/vi.tsv+++ b/crates/ui-egui/src/i18n/vi.tsv@@ -1444,3 +1444,4 @@ Zoom Thu phóngBring all to front Đưa tất cả lên trướcDrag to give the plan more or less room; double-click to reset Kéo để mở rộng hoặc thu hẹp phần kế hoạch; nhấp đúp để đặt lạiCopy the message Sao chép tin nhắn+Choose what the builder's approvals get Chọn cách xử lý các phê duyệt của trình xây dựngdiff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsvindex f4353727..e92ae2a5 100644--- a/crates/ui-egui/src/i18n/zh-hans.tsv+++ b/crates/ui-egui/src/i18n/zh-hans.tsv@@ -1444,3 +1444,4 @@ Zoom 缩放Bring all to front 前置全部窗口Drag to give the plan more or less room; double-click to reset 拖动以调整计划占用的空间;双击恢复默认Copy the message 复制这条消息+Choose what the builder's approvals get 选择如何处理构建助手的审批diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsvindex d11f0972..c3ae49ca 100644--- a/crates/ui-egui/src/i18n/zh-hant.tsv+++ b/crates/ui-egui/src/i18n/zh-hant.tsv@@ -1444,3 +1444,4 @@ Zoom 縮放Bring all to front 將全部視窗移至最前Drag to give the plan more or less room; double-click to reset 拖曳以調整計畫佔用的空間;按兩下恢復預設Copy the message 複製這則訊息+Choose what the builder's approvals get 選擇如何處理建置助手的審核diff --git a/crates/ui-egui/src/ja.tsv b/crates/ui-egui/src/ja.tsvindex 2e9b1cb1..a194af95 100644--- a/crates/ui-egui/src/ja.tsv+++ b/crates/ui-egui/src/ja.tsv@@ -882,3 +882,4 @@ Zoom 拡大/縮小Bring all to front すべてを手前に移動Drag to give the plan more or less room; double-click to reset ドラッグでプランの高さを変更、ダブルクリックで元に戻すCopy the message メッセージをコピー+Choose what the builder's approvals get ビルダーの承認の扱いを選ぶdiff --git a/docs/ROADMAP.md b/docs/ROADMAP.mdindex 0ace5847..c9e7e95d 100644--- a/docs/ROADMAP.md+++ b/docs/ROADMAP.md@@ -197,6 +197,9 @@ only when it's green and a maintainer has fully reviewed it, code as well as worby then made a cancelled run, not a hand-off. The test now waits for the launcher's mark, anda kill that finds the program already exited reports its exit, not a cancel— claimed: 00xJS, branch test/r5.2-hand-off-race+- [ ] `website_tools::tests::a_browser_that_exits_at_once_is_reported_at_once` (engine) failed once+ on Windows with the whole engine suite running (66 s under load) and passes alone, three+ times in a row. Find what it times- [ ] `a_helper_is_judged_by_whether_it_runs` (ai crate) sometimes fails when several crates'tests run at once and passes alone: it writes a script and runs it straight away, which abusy machine can refuse while another test's child still holds the file open@@ -820,6 +823,23 @@ Owner: maintainers · Status: in progress### R2.9 Everyday use: typing, projects, settingsOwner: maintainers · Status: in progressGaps found while using the app for real projects.+- [x] Each project chooses, per kind of action, what the builder's approvals get (allow, ask or+ refuse): reading the web, commands, files outside the project, pushing and publishing,+ deleting outside the project, system changes, other tools. Unset kinds follow Auto mode as+ today. Found when Auto mode refused every `git push` without a card, so the person's OK in+ the prompt box never reached the check, and refused `gh repo view` as publishing too+ — claimed: tanish2k09, branch feature/r2.9-project-approvals+- [ ] Agents that don't ask our approval tool (OpenCode `--auto`, Hermes `-z`, Maki's `-p`) aren't+ held to a project's approval choices either; part of R2.2's approval decision+- [ ] While "commands" are allowed (Auto mode's default), a builder can run any program. Commands+ that name `craft.json`, the inbox or the approvals tool count as system changes, and our CLI+ started inside an agent calls tools as an agent, but a script that builds the path, or+ unsets `CRAFT_ANYTHING_AGENT`, isn't caught. Keep the person's choices where a builder's+ shell can't write them, or say plainly that "commands: allow" trusts the builder+- [ ] A typed note ("yes, push it") still reaches the builder only as text: say in the card's+ place, when the builder is refused, how the person can allow that kind+- [ ] The project page and a slash command change those choices (like `/btw`)+ — claimed: tanish2k09, branch feature/r2.9-approvals-ui- [x] Keep New project's content column fixed while the vertical scrollbar animates in or out,hiding it when there is nothing to scroll, so switching tabs never shifts the page horizontally— claimed: Codex, branch bugfix/r2.9-home-scrollbar-gutterdiff --git a/docs/STATUS.md b/docs/STATUS.mdindex 34d25bdc..3228a3c4 100644--- a/docs/STATUS.md+++ b/docs/STATUS.md@@ -86,7 +86,7 @@ workspace clippy, layers, fmt and the secret scan of all history were clean. Chi| Backend context budgets | `context_tokens` in `[[ai.backends]]` controls when an API conversation is trimmed and summarised. Zero or omission retains local/cloud defaults; a nonzero conversation override takes priority. Before each attempt, including a fallback, fitting adds estimated history growth since the last successful request to its reported input size. Trimming resets that reference, and successful requests refresh it; summary usage remains in message totals | Regressions cover settings and model construction, defaults/overrides, smaller fallback budgets, large-budget arithmetic and new tool output growing beyond a fallback budget even when the history estimate alone is below the reported input. The latest tool results are preserved, and a short follow-up does not count already-sent history twice. This does not set server context parameters or guarantee that a complete request fits; no live provider was used || Games | Engine detection for 12 engines (Unreal, Unity, Godot, Source, GameMaker, RPG Maker, Ren'Py, MonoGame, LÖVE, CryEngine, Cocos, Cube) with versions. Unreal and Godot games are rebuilt in the same engine, others in Unity; installed engines are found, Godot installs itself, others get guided installs. Picking an inner folder (Engine, Binaries, Paks…) finds the game's folder. Just look inside a game shows what it's made of (`core_target_triage` on its folder: engine and version, how its code ships, the libraries its Unity assembly names give away, its own code, scenes and size) and opens it in the chat to ask about it. The builder keeps `app/MECHANICS.md` and its structured twin `app/mechanics.json` (checked after each build), in Deep mode only, may reuse the original's readable files for private use (never decrypting; generated pictures and 3D models replace its art when the person turns them on; Clean room copies none of its files), lists them in `CREDITS.md` (checked, with the private-use line in `README.md`); a game is ready only when its `--self-test` shows the player moving, acting and the HUD drawn, and the result can be started from the project page | Unit tests; live runs on Windows || Clean room and Deep mode | Clean room (the default) runs only the tools in `engine/src/clean_room.rs`: ones that touch no target or watch from outside (the website as a visitor sees it, pictures of a window, its controls, recorded runs, a phone's screen). Every other tool, a plugin's included, is refused in the app, CLI, MCP and agents, with a way to turn on Deep mode. A Clean room build studies an app or a game only from the person's pictures and words (and a picture of its window when runtime study is on); its builder's reads and commands go through an approval rule that keeps it out of the original's folder and site (with Claude Code, and with ACP agents for what they ask about; other agents aren't held to it, see roadmap R2.2). Deep mode (`deep_mode` in Settings, `--deep` for one CLI run) uses every tool: the builder sees them all, and a website's study also reads its JavaScript and watches its start page for ten seconds (capture/how-it-works.md). Ghidra adds its decompiler in Deep mode when it's installed: it is found, or installed after asking. Study starts one analysis of the main program, saved and shared with the builder's tool server through a lock file (up to 8 h, Java gets half the machine's memory or the amount set in Settings → Engines, 4 to 31 GB, four slow passes skipped). The builder must decompile before the build is checked; addresses the built-in analysis can't place go to Ghidra, which makes a function on demand (for this run only) where its analysis has none, e.g. code reached only through tables of pointers. Without Ghidra, Deep mode uses the built-in engines | Live runs with Ghidra 12.1.4 on Windows (a shared analysis, and a decompile in seconds on a large program). Live runs with Ghidra 12.2 on Linux x86-64 (decompiles by name in position-independent programs and shared libraries, whose addresses Ghidra moves). The guided install of Ghidra and its Java is offered on Linux and macOS too, but has only been tried on Windows. Clean room and Deep mode: engine, AI, MCP, CLI and app tests; no live Clean room build run yet |-| Auto mode | Settings → Safety, on by default. Builder actions go ahead without asking, except a fixed set that is never done unasked (deleting outside the project, system changes, publishing…); questions get "decide yourself"; asset spending stops at the budget | Unit tests |+| Auto mode | Settings → Safety, on by default. Builder actions go ahead without asking, except a fixed set that is never done unasked (deleting outside the project, system changes, publishing…); questions get "decide yourself"; asset spending stops at the budget. Each project can choose allow, ask or refuse per kind of action instead (`project_approvals_set`; read-only `gh … view`/`list` count as commands, not publishing); the app's controls for it aren't there yet | Unit tests || Generated assets | Off until the person turns them on for a game (the switch on Make and on the project, `project_assets_allow`, `rebuild --generate-assets`, saved in craft.json; turning it on without a fal.ai key asks for one); the brief and the asset tools need both that and a key. `assets_image_generate` (Nano Banana Pro by default) and `assets_model_generate` (picture → Tripo P1 low-poly GLB with a face limit) through the person's key for each asset provider (fal.ai today), with agent apps and API-key builds alike; per-project budget, $5 by default (`[assets] budget_usd` in config.toml); models and prices from the `assets.toml` table (picture model selectable: Nano Banana Pro, FLUX dev or schnell; priced per picture or per megapixel); every call reports its cost | Unit tests; a live 3D generation with a real key (picture, then model) with FLUX dev; Nano Banana Pro not yet run with a real key; an API-key build not yet run with one || Claude Code builder | Runs the person's own `claude` in headless mode (Opus 5.5, high effort unless configured) with our MCP server, a permission-prompt tool and `core_person_ask`; preflights for our CLI (a build stops plainly if it's missing or won't start) and sign-in | Argument and stream-parser tests; live preflight; live builder turns; see [claude-code.md](claude-code.md) || DeepSeek Harness builder | Runs the person's own `dsh --profile headless "<task>"`, which answers one task and prints its last message as text. The harness takes its tool servers from profile patch layers and has no per-run flag for one, so our tool server arrives as a generated `--patch` overlay for that run (the run's project, inbox and mode included); the person's own profile is untouched, a question gets no tool server, and its headless profile keeps no session to resume. An npm `.cmd` shim is unwrapped to its interpreter, so `dsh` found on PATH runs as `node …/dsh/lib/bin.js` | Adapter and YAML-overlay tests; live preflight (`ai test`); live builder turns on a website (follow-up build, 3 min 10 s, 100% alike at 1440/768/390 px, Ready) where the builder's own journal entries show `rebuild_check`, `core_unknown_add`, `core_plan_update` and `core_handoff_write` going through our tool server, and that server started with the run's `--project`/`--inbox`. Not checked: resume (none exists) and a build with the harness's desktop profile. Also verified on macOS arm64 (2026-11-07, DSH 0.2.2-rc.1, stored sign-in restored for the headless profile as its README describes): a static website reached Ready with one check pass, and the builder called our MCP tools |diff --git a/docs/claude-code.md b/docs/claude-code.mdindex afc089b0..98a541ad 100644--- a/docs/claude-code.md+++ b/docs/claude-code.md@@ -23,8 +23,15 @@ integration does, why it is shaped this way, and what remains to confirm.Every other action (writing files, running commands, fetching the web) goes through`--permission-prompt-tool mcp__craft-anything__core_action_approve`. That tool allows editsinside the project's `app/` folder and a fixed list of build commands (`npm install`,- `npm run build`, `cargo build`…), refuses dev servers (they never exit), and asks the person- in the app for anything else ("Allow once / Always for this project / Don't allow").+ `npm run build`, `cargo build`…), refuses dev servers (they never exit), and decides the rest+ by its kind (the web, commands, files outside the project, pushing and publishing, deletes+ outside the project, system changes, other tools): each project can choose allow, ask or+ refuse per kind (`project_approvals_set`), and an unchosen kind follows Auto mode. Asking shows+ a card in the app ("Allow once / Always for this project / Don't allow"); "Always" on a push,+ delete or system change allows that whole kind for the project. A builder's own call to+ `project_approvals_set` can only make a kind stricter, also through `craft-anything-cli` run+ from its shell (agents we start have `CRAFT_ANYTHING_AGENT` set), and a command that names+ `craft.json`, the inbox or the approvals tool counts as a system change.- Questions: Claude Code's own question tool is disabled for these runs (`--disallowedToolsAskUserQuestion`); the agent uses our `core_person_ask` tool, which shows a card with buttons.- Before a build starts, `claude auth status` is checked. If Claude Code isn't signed in, the rundiff --git a/docs/file-formats.md b/docs/file-formats.mdindex 86312073..3cb6125d 100644--- a/docs/file-formats.md+++ b/docs/file-formats.md@@ -7,7 +7,7 @@ version up to the current one, then turn the document into Rust types. The step| File | Owner | Current version | Older files | Newer files ||---|---|---|---|---|-| `<project>/craft.json` | `engine::workspace` (`Manifest`) | `MANIFEST_VERSION` = 2 (`version`; missing = 0) | brought forward, saved as current | opened read-only: saving is refused |+| `<project>/craft.json` | `engine::workspace` (`Manifest`) | `MANIFEST_VERSION` = 3 (`version`; missing = 0; 3 adds `approvals`) | brought forward, saved as current | opened read-only: saving is refused || `<project>/inbox/build-progress.json` | `engine::workspace::progress` (`BuildProgress`; written only by the rebuild run) | `BUILD_PROGRESS_VERSION` = 1 (`version`; missing = 0) | brought forward; an absent file starts with no counted turns | the build stops and the record is left unchanged || `config.toml` (`settings::config_dir()`) | `engine::settings` (`Settings`) | `SETTINGS_VERSION` = 2 (`version`; missing = 0; 2 moved `[engines.ghidra] enabled` to `deep_mode`) | brought forward | loaded, never saved over || `<name>.cany/project.toml` | `engine::project` (`ProjectMeta`) | `FORMAT_VERSION` = 1 (`format_version`, required) | brought forward | refused, with "update Craft Anything" |diff --git a/docs/pitfalls.md b/docs/pitfalls.mdindex b3102a06..643b1119 100644--- a/docs/pitfalls.md+++ b/docs/pitfalls.md@@ -291,6 +291,14 @@ upstream providers, and a provider without tool calling answered 400 "Provider rwhat the provider must support (`provider.require_parameters` for tools), and show the provider'sown reason when it still fails (#542).+**A refusal that names a person nobody asks.** Auto mode refused `git push` with "never …+without the person", but never showed a card, so the person's "yes, push it" in the prompt box+reached only the builder, which retried and was refused again, five times. Its rule matched+`gh repo` anywhere, so `gh repo view` was "publishing" too, and "always" on `cd app && npm i` was+kept as `bash:cd`, which would have let `cd app && git push` through. A refusal says how the+person can allow it, and a way to allow it exists; read commands word by word; remember a+dangerous kind whole, never by a command's first word.+**A crash that no code can report.** Three Windows tickets (#33, #104, #74) said the app "doesnothing": a graphics driver crashed natively as the window opened, so no dialog, panic hook or logline ever ran, and each fix only covered the driver already seen. When a failure can't be caught,@@ -608,6 +616,11 @@ field what it counts, and test each producer with the case where they differ (heUpdate STATUS, the roadmap and generated docs (`cargo xtask tools`, `cargo xtask schemas`) in thesame PR as the change.+**A tool's title is a UI string.** A PR that added an engine tool and no UI passed every check run+for it locally, and CI's `cargo xtask i18n-coverage` failed: the app shows tool titles, so each+needs a translation in every catalog. Run `cargo xtask i18n-coverage` for any PR that adds a tool+or changes a title, not only for UI changes.+**A second lock in one statement.** `CliSpec { deep: !engine.session().clean_room(), logs: engine.session().config_dir(), … }`looked like two quick reads, but an unbound guard lives to the end of the statement, so the secondwaited on the first forever. Every build froze after studying its target while the card calmlydiff --git a/docs/schemas/craft.schema.json b/docs/schemas/craft.schema.jsonindex 3cc619f9..b3f662d6 100644--- a/docs/schemas/craft.schema.json+++ b/docs/schemas/craft.schema.json@@ -31,6 +31,24 @@"description": "The app is the project folder itself: the person's own files, which the builder edits in\nplace, instead of app/.","type": "boolean"},+ "approvals": {+ "description": "What the builder's approvals get in this project, by kind of action; a kind that isn't here\nfollows Auto mode ([`ActionKind::default_in`]). The person's, like the budget.",+ "type": "object",+ "additionalProperties": {+ "$ref": "#/$defs/Approval"+ },+ "propertyNames": {+ "enum": [+ "web",+ "commands",+ "outside_files",+ "publish",+ "delete_outside",+ "system",+ "other_tools"+ ]+ }+ },"asset_budget_usd": {"description": "What generated pictures and 3D models may cost before the person is asked (US dollars).","type": "number",@@ -139,6 +157,26 @@"updated_ms"],"$defs": {+ "Approval": {+ "description": "What an action of one [`ActionKind`] gets.",+ "oneOf": [+ {+ "description": "Done without asking.",+ "type": "string",+ "const": "allow"+ },+ {+ "description": "A card for the person, and the builder waits for the answer.",+ "type": "string",+ "const": "ask"+ },+ {+ "description": "Not done, without asking: the builder is told to find another way.",+ "type": "string",+ "const": "refuse"+ }+ ]+ },"CheckResult": {"description": "One check of the build: whether it works and, when it could be compared with the original,\nhow alike it is. Decisions read `passed` and `similarity`, never `note` (which is for people).","type": "object",diff --git a/docs/tools.md b/docs/tools.mdindex 32d8e02e..14d9daed 100644--- a/docs/tools.md+++ b/docs/tools.md@@ -2,7 +2,7 @@Generated by `cargo xtask tools`. Do not edit by hand.-**301 engine tools** in 17 toolsets. Each is an MCP tool, a CLI command (`craft-anything-cli <id with dashes>`) and a tool the agent can call. The AI and setup layers add their own on top (`rebuild_*`, `assets_key_*`, `ai_models_list`, `ai_model_set`, `setup_*`); `craft-anything-cli commands` lists them all. [OpenCode model and thinking selection](opencode.md) describes the AI model tools.+**302 engine tools** in 17 toolsets. Each is an MCP tool, a CLI command (`craft-anything-cli <id with dashes>`) and a tool the agent can call. The AI and setup layers add their own on top (`rebuild_*`, `assets_key_*`, `ai_models_list`, `ai_model_set`, `setup_*`); `craft-anything-cli commands` lists them all. [OpenCode model and thinking selection](opencode.md) describes the AI model tools.## Essentials (`core`, 35)@@ -312,7 +312,7 @@ Generated by `cargo xtask tools`. Do not edit by hand.- `db_sqlite_show`: SQLite database contents-## Projects (`projects`, 20)+## Projects (`projects`, 21)- `project_list`: List projects- `project_show`: Show a project@@ -325,6 +325,7 @@ Generated by `cargo xtask tools`. Do not edit by hand.- `project_duplicate`: Duplicate a project- `project_delete`: Delete a project- `project_questions_set`: Choose what the builder's questions get+- `project_approvals_set`: Choose what the builder's approvals get- `project_build_finish`: Call the build done- `project_assets_budget`: Set a project's asset budget- `project_assets_allow`: Let a project generate assets