Skip to main content

speccoder_runtime/tools/
mod.rs

1//! speccoder's tools: what an attempt may do to
2//! its worktree, served to agentplane as tool servers `fs`, `proc` and `git`.
3//!
4//! Domain failures (no such file, ambiguous edit, protected path) come back
5//! as ordinary results `{"ok": false, "error": …}` so the model can see them
6//! and recover; agentplane `ToolError`s are reserved for infrastructure.
7
8pub mod paths;
9pub mod policy;
10
11use std::fs;
12use std::path::{Path, PathBuf};
13use std::time::Duration;
14
15use agentplane::model::ToolDeclaration;
16use agentplane::tools::{Destination, ToolClient, ToolError, ToolId};
17use async_trait::async_trait;
18use schemars::JsonSchema;
19use serde::Deserialize;
20use serde_json::{Value, json};
21use sha2::{Digest, Sha256};
22
23use self::paths::{Protected, canonical_for_write, normalise, resolve_existing};
24use self::policy::{Decision, Object, Policy};
25use crate::git::{Git, nul_fields};
26use crate::verify::process::{Invocation, OUTPUT_CAP, scrubbed_env};
27
28/// `read_file` cap.
29pub const READ_CAP: usize = 256 * 1024;
30/// `list_files` cap.
31pub const LIST_CAP: usize = 500;
32/// `search_code` match cap.
33pub const SEARCH_CAP: usize = 200;
34/// Characters kept per search-result line.
35pub const LINE_CAP: usize = 500;
36/// Longest `run_command` timeout a model may ask for.
37pub const MAX_COMMAND_SECS: u64 = 600;
38
39// ── Inputs (their JSON schemas are what the model sees) ─────────────────────
40
41/// Read a text file in the workspace, optionally a range of lines.
42#[derive(Debug, Deserialize, JsonSchema)]
43#[serde(deny_unknown_fields)]
44pub struct ReadFile {
45    /// Path relative to the workspace root.
46    pub path: String,
47    /// First line to return (1-based).
48    pub start_line: Option<usize>,
49    /// Last line to return (inclusive).
50    pub end_line: Option<usize>,
51}
52
53/// List files (not ignored by .gitignore), optionally under a directory and matching a glob.
54#[derive(Debug, Deserialize, JsonSchema)]
55#[serde(deny_unknown_fields)]
56pub struct ListFiles {
57    /// Directory relative to the workspace root (default: the root).
58    pub path: Option<String>,
59    /// Glob such as `**/*.rs`.
60    pub glob: Option<String>,
61}
62
63/// Search file contents with a regular expression (respects .gitignore).
64#[derive(Debug, Deserialize, JsonSchema)]
65#[serde(deny_unknown_fields)]
66pub struct SearchCode {
67    /// Rust regex syntax.
68    pub pattern: String,
69    /// Directory relative to the workspace root (default: the root).
70    pub path: Option<String>,
71    /// Only files matching this glob.
72    pub glob: Option<String>,
73}
74
75/// Create or replace a whole file.
76#[derive(Debug, Deserialize, JsonSchema)]
77#[serde(deny_unknown_fields)]
78pub struct WriteFile {
79    /// Path relative to the workspace root.
80    pub path: String,
81    /// The complete new contents.
82    pub content: String,
83    /// Set by speccoder, not the model: the object a person's decision
84    /// covered, checked again before the write.
85    #[schemars(skip)]
86    #[serde(default, rename = "__expect")]
87    pub expect: Option<Object>,
88}
89
90/// Replace an exact string in a file: once (it must occur exactly once) or everywhere.
91#[derive(Debug, Deserialize, JsonSchema)]
92#[serde(deny_unknown_fields)]
93pub struct EditFile {
94    /// Path relative to the workspace root.
95    pub path: String,
96    /// Exact text to find, including whitespace.
97    pub old_string: String,
98    /// Replacement text.
99    pub new_string: String,
100    /// Replace every occurrence instead of exactly one (default: one).
101    pub replace_all: Option<bool>,
102    /// Set by speccoder, not the model: the object a person's decision
103    /// covered, checked again before the edit.
104    #[schemars(skip)]
105    #[serde(default, rename = "__expect")]
106    pub expect: Option<Object>,
107}
108
109/// Run a program (no shell) in the workspace with a timeout; stdin is closed.
110#[derive(Debug, Deserialize, JsonSchema)]
111#[serde(deny_unknown_fields)]
112pub struct RunCommand {
113    /// Program and arguments, e.g. ["cargo", "test", "-p", "core"].
114    pub argv: Vec<String>,
115    /// Working directory relative to the workspace root (default: the root).
116    pub cwd: Option<String>,
117    /// Seconds before the whole process group is killed (default 120, at most 600).
118    pub timeout_secs: Option<u64>,
119    /// Commands run without the network; `true` asks for it (a person decides).
120    pub network: Option<bool>,
121    /// Set by speccoder, not the model: the call's id, exported as
122    /// `SPECCODER_CALL_ID`.
123    #[schemars(skip)]
124    #[serde(default)]
125    pub call_id: Option<String>,
126    /// Set by speccoder, not the model: the object a person's decision
127    /// covered, checked again before the command starts.
128    #[schemars(skip)]
129    #[serde(default, rename = "__expect")]
130    pub expect: Option<Object>,
131}
132
133/// speccoder's own step, never offered to the model: the object a call
134/// would reach — the file a write lands in, the program a command runs.
135#[derive(Debug, Deserialize, JsonSchema)]
136#[serde(deny_unknown_fields)]
137pub struct Resolve {
138    /// The tool the model asked for.
139    pub tool: String,
140    /// Its arguments as the model sent them.
141    pub arguments: Value,
142}
143
144/// The internal field the tool loop sets on a call decided on an object.
145pub const EXPECT: &str = "__expect";
146
147/// Show changed, added and untracked files.
148#[derive(Debug, Deserialize, JsonSchema)]
149#[serde(deny_unknown_fields)]
150pub struct GitStatus {}
151
152/// Show the diff of the working tree against HEAD, optionally for one path.
153#[derive(Debug, Deserialize, JsonSchema)]
154#[serde(deny_unknown_fields)]
155pub struct GitDiff {
156    /// Limit the diff to this path.
157    pub path: Option<String>,
158}
159
160/// One tool as the model and agentplane see it.
161#[derive(Debug, Clone)]
162pub struct ToolSpec {
163    /// Name offered to the model, e.g. `read_file`.
164    pub name: &'static str,
165    /// agentplane tool server: `fs`, `proc` or `git`.
166    pub server: &'static str,
167    /// Whether calling it can change the world.
168    pub mutates: bool,
169    /// Argument pointers the model authors (declared on mutating grants).
170    pub model_fields: &'static [&'static str],
171    /// What the model is told.
172    pub description: &'static str,
173    /// JSON schema of the arguments.
174    pub parameters: fn() -> Value,
175}
176
177/// The schema of a tool's arguments, made strict-ready by agentplane: only
178/// what serde enforces is declared — an optional argument is an `Option`,
179/// so `null` is both allowed and readable.
180fn schema<T: JsonSchema>() -> Value {
181    agentplane::tools::strict_schema::<T>()
182}
183
184/// Every tool, in a stable order (the order is part of the cached prompt prefix).
185#[must_use]
186pub fn catalog() -> Vec<ToolSpec> {
187    vec![
188        ToolSpec {
189            name: "read_file",
190            server: "fs",
191            mutates: false,
192            model_fields: &[],
193            description: "Read a text file in the workspace, optionally a range of lines.",
194            parameters: schema::<ReadFile>,
195        },
196        ToolSpec {
197            name: "list_files",
198            server: "fs",
199            mutates: false,
200            model_fields: &[],
201            description: "List files not ignored by .gitignore, optionally under a directory and matching a glob.",
202            parameters: schema::<ListFiles>,
203        },
204        ToolSpec {
205            name: "search_code",
206            server: "fs",
207            mutates: false,
208            model_fields: &[],
209            description: "Search file contents with a regular expression; returns path:line: text.",
210            parameters: schema::<SearchCode>,
211        },
212        ToolSpec {
213            name: "write_file",
214            server: "fs",
215            mutates: true,
216            model_fields: &["/path", "/content"],
217            description: "Create or replace a whole file. Spec Kit files, CI and test configuration, speccoder.toml and .git are refused.",
218            parameters: schema::<WriteFile>,
219        },
220        ToolSpec {
221            name: "edit_file",
222            server: "fs",
223            mutates: true,
224            model_fields: &["/path", "/old_string", "/new_string"],
225            description: "Replace an exact string in a file: old_string is removed and new_string takes its place (exactly one occurrence unless replace_all). To add text without removing any, anchor on existing text and repeat it: old_string = an existing line, new_string = that same line followed by the new one.",
226            parameters: schema::<EditFile>,
227        },
228        ToolSpec {
229            name: "run_command",
230            server: "proc",
231            mutates: true,
232            model_fields: &["/argv"],
233            description: "Run a program without a shell in the workspace; stdin is closed, output is capped, the timeout kills the process group.",
234            parameters: schema::<RunCommand>,
235        },
236        ToolSpec {
237            name: "git_status",
238            server: "git",
239            mutates: false,
240            model_fields: &[],
241            description: "Show modified, added, deleted and untracked files.",
242            parameters: schema::<GitStatus>,
243        },
244        ToolSpec {
245            name: "git_diff",
246            server: "git",
247            mutates: false,
248            model_fields: &[],
249            description: "Show the working tree's diff against HEAD.",
250            parameters: schema::<GitDiff>,
251        },
252    ]
253}
254
255/// speccoder's own tools, which the tool loop calls and the model is never
256/// offered: `fs/resolve`.
257#[must_use]
258pub fn internal() -> Vec<ToolSpec> {
259    vec![ToolSpec {
260        name: "resolve",
261        server: "fs",
262        mutates: false,
263        model_fields: &[],
264        description: "Resolve the object a call would reach (speccoder's own step).",
265        parameters: schema::<Resolve>,
266    }]
267}
268
269/// The model-facing declarations, in catalog order.
270#[must_use]
271pub fn declarations() -> Vec<ToolDeclaration> {
272    catalog()
273        .into_iter()
274        .map(|t| ToolDeclaration::new(t.name, t.description, (t.parameters)()))
275        .collect()
276}
277
278// ── The tool server ─────────────────────────────────────────────────────────
279
280/// Tools bound to one worktree.
281#[derive(Debug, Clone)]
282pub struct WorkspaceTools {
283    root: PathBuf,
284    policy: Policy,
285    runner: crate::sandbox::Runner,
286    /// Variables every command gets (a hosted skill's current unit).
287    env: Vec<(String, String)>,
288}
289
290/// A write that would take tests away, refused before it happens: a test
291/// that passed before the attempt is evidence, and its removal fails the
292/// attempt whatever else it did. The model is told which, and what to do.
293fn removes_tests(path: &str, before: &str, after: &str) -> Option<Value> {
294    let gone = crate::integrity::removed_tests(before, after);
295    if gone.is_empty() {
296        return None;
297    }
298    let (s, them) = if gone.len() == 1 {
299        ("", "it")
300    } else {
301        ("s", "them")
302    };
303    Some(failure(format!(
304        "refused: this removes the test{s} {} from `{path}`. Tests that passed before the attempt are evidence: removing or renaming one fails the attempt. Keep {them} and add new tests beside {them}; if one contradicts the spec, report the task blocked and say which test and why.",
305        gone.iter()
306            .map(|n| format!("`{n}`"))
307            .collect::<Vec<_>>()
308            .join(", ")
309    )))
310}
311
312fn failure(error: impl Into<String>) -> Value {
313    json!({ "ok": false, "error": error.into() })
314}
315
316/// The refusal of a call whose object differs from the one a person
317/// decided on: the model is told, the record names both.
318fn changed(was: &str, now: &str) -> Value {
319    json!({
320        "ok": false,
321        "error": format!("the object changed since it was approved: {was} → {now}"),
322        "object_changed": { "expected": was, "found": now },
323    })
324}
325
326fn sha(bytes: &[u8]) -> String {
327    Sha256::digest(bytes)
328        .iter()
329        .map(|b| format!("{b:02x}"))
330        .collect()
331}
332
333fn parse<T: for<'de> Deserialize<'de>>(args: &Value) -> Result<T, Value> {
334    serde_json::from_value(args.clone()).map_err(|e| failure(format!("invalid arguments: {e}")))
335}
336
337impl WorkspaceTools {
338    /// Tools for the worktree at `root` under `policy`.
339    pub fn new(root: &Path, policy: Policy) -> std::io::Result<Self> {
340        Ok(Self {
341            root: fs::canonicalize(root)?,
342            policy,
343            runner: crate::sandbox::Runner::Plain,
344            env: Vec::new(),
345        })
346    }
347
348    /// Commands also get `env` (the policy's own variables still win).
349    #[must_use]
350    pub fn with_env(mut self, env: Vec<(String, String)>) -> Self {
351        self.env = env;
352        self
353    }
354
355    /// Runs commands with `runner` (the sandbox).
356    #[must_use]
357    pub fn with_runner(mut self, runner: crate::sandbox::Runner) -> Self {
358        self.runner = runner;
359        self
360    }
361
362    fn protected(&self) -> &Protected {
363        self.policy.protected()
364    }
365
366    /// Runs one tool by name; the result is what the model sees.
367    pub async fn run(&self, name: &str, args: &Value) -> Value {
368        if name == "resolve" {
369            return match parse::<Resolve>(args) {
370                Ok(a) => self.resolve(&a.tool, &a.arguments),
371                Err(e) => e,
372            };
373        }
374        // Denials are enforced here too, whatever the caller decided.
375        if let Decision::Deny(reason) = self.policy.classify(name, args, None) {
376            return failure(format!("denied: {reason}"));
377        }
378        let out = match name {
379            "read_file" => parse(args).map(|a| self.read_file(&a)),
380            "list_files" => parse(args).map(|a| self.list_files(&a)),
381            "search_code" => parse(args).map(|a| self.search_code(&a)),
382            "write_file" => parse(args).map(|a| self.write_file(&a)),
383            "edit_file" => parse(args).map(|a| self.edit_file(&a)),
384            "run_command" => match parse::<RunCommand>(args) {
385                Ok(a) => Ok(self.run_command(a).await),
386                Err(e) => Err(e),
387            },
388            "git_status" => parse::<GitStatus>(args).map(|_| self.git_status()),
389            "git_diff" => parse(args).map(|a| self.git_diff(&a)),
390            other => Err(failure(format!("unknown tool `{other}`"))),
391        };
392        out.unwrap_or_else(|e| e)
393    }
394
395    fn rel(&self, p: &Path) -> String {
396        p.strip_prefix(&self.root)
397            .unwrap_or(p)
398            .to_string_lossy()
399            .replace('\\', "/")
400    }
401
402    fn read_file(&self, a: &ReadFile) -> Value {
403        let path = match resolve_existing(&self.root, &a.path) {
404            Ok(p) => p,
405            Err(e) => return failure(e.0),
406        };
407        if self.protected().is_secret(&self.rel(&path)) {
408            return failure(format!("`{}` looks like a credential", a.path));
409        }
410        let bytes = match fs::read(&path) {
411            Ok(b) => b,
412            Err(e) => return failure(format!("`{}`: {e}", a.path)),
413        };
414        let Ok(text) = String::from_utf8(bytes.clone()) else {
415            return json!({ "ok": true, "path": a.path, "binary": true, "bytes": bytes.len() });
416        };
417        let lines: Vec<&str> = text.lines().collect();
418        let start = a.start_line.unwrap_or(1).max(1);
419        let end = a.end_line.unwrap_or(lines.len()).min(lines.len());
420        let mut content = if start > end {
421            String::new()
422        } else {
423            lines[start - 1..end].join("\n")
424        };
425        let truncated = content.len() > READ_CAP;
426        if truncated {
427            let mut cut = READ_CAP;
428            while !content.is_char_boundary(cut) {
429                cut -= 1;
430            }
431            content.truncate(cut);
432            content.push_str("\n[… truncated; read a line range …]");
433        }
434        json!({ "ok": true, "path": a.path, "start_line": start, "end_line": end, "total_lines": lines.len(), "truncated": truncated, "content": content })
435    }
436
437    fn walk(&self, dir: Option<&str>, glob: Option<&str>) -> Result<Vec<PathBuf>, Value> {
438        let base = match dir {
439            Some(d) => resolve_existing(&self.root, d).map_err(|e| failure(e.0))?,
440            None => self.root.clone(),
441        };
442        let matcher = glob
443            .map(|g| globset::Glob::new(g).map(|g| g.compile_matcher()))
444            .transpose()
445            .map_err(|e| failure(format!("invalid glob: {e}")))?;
446        let mut files: Vec<PathBuf> = ignore::WalkBuilder::new(&base)
447            .hidden(false)
448            .filter_entry(|e| e.file_name() != ".git")
449            .build()
450            .flatten()
451            .filter(|e| e.file_type().is_some_and(|t| t.is_file()))
452            .map(ignore::DirEntry::into_path)
453            .filter(|p| {
454                let rel = self.rel(p);
455                !self.protected().is_secret(&rel)
456                    && matcher.as_ref().is_none_or(|m| m.is_match(&rel))
457            })
458            .collect();
459        files.sort();
460        Ok(files)
461    }
462
463    fn list_files(&self, a: &ListFiles) -> Value {
464        match self.walk(a.path.as_deref(), a.glob.as_deref()) {
465            Ok(files) => {
466                let total = files.len();
467                let shown: Vec<String> = files.iter().take(LIST_CAP).map(|p| self.rel(p)).collect();
468                json!({ "ok": true, "files": shown, "total": total, "truncated": total > LIST_CAP })
469            }
470            Err(e) => e,
471        }
472    }
473
474    fn search_code(&self, a: &SearchCode) -> Value {
475        let re = match regex::Regex::new(&a.pattern) {
476            Ok(r) => r,
477            Err(e) => return failure(format!("invalid pattern: {e}")),
478        };
479        let files = match self.walk(a.path.as_deref(), a.glob.as_deref()) {
480            Ok(f) => f,
481            Err(e) => return e,
482        };
483        let mut matches = Vec::new();
484        let mut total = 0usize;
485        for f in files {
486            let Ok(bytes) = fs::read(&f) else { continue };
487            if bytes.len() > 1024 * 1024 || bytes.iter().take(8192).any(|b| *b == 0) {
488                continue;
489            }
490            let text = String::from_utf8_lossy(&bytes);
491            for (i, line) in text.lines().enumerate() {
492                if re.is_match(line) {
493                    total += 1;
494                    if matches.len() < SEARCH_CAP {
495                        let shown: String = line.chars().take(LINE_CAP).collect();
496                        matches.push(format!("{}:{}: {shown}", self.rel(&f), i + 1));
497                    }
498                }
499            }
500        }
501        json!({ "ok": true, "matches": matches, "total": total, "truncated": total > SEARCH_CAP })
502    }
503
504    /// The object `tool` would reach with `arguments`: what a person's
505    /// decision covers (`{ok, object}`; `object` is `null` for a tool
506    /// without one, `ok: false` with the refusal when it cannot be reached).
507    #[must_use]
508    pub fn resolve(&self, tool: &str, arguments: &Value) -> Value {
509        match tool {
510            "write_file" | "edit_file" => {
511                let asked = arguments["path"].as_str().unwrap_or_default();
512                match (canonical_for_write(&self.root, asked), normalise(asked)) {
513                    (Ok(canonical), Ok(asked)) => json!({
514                        "ok": true,
515                        "object": Object::Path { canonical, asked },
516                    }),
517                    (Err(e), _) | (_, Err(e)) => failure(e.0),
518                }
519            }
520            "run_command" => {
521                let argv = policy::argv_of(arguments);
522                match self.command_object(
523                    &argv,
524                    arguments["cwd"].as_str(),
525                    arguments["network"] == true,
526                ) {
527                    Ok(object) => json!({ "ok": true, "object": object }),
528                    Err(e) => e,
529                }
530            }
531            _ => json!({ "ok": true, "object": null }),
532        }
533    }
534
535    /// The directory a command runs in.
536    fn command_cwd(&self, cwd: Option<&str>) -> Result<PathBuf, Value> {
537        // `.`, `./` and an empty string mean the workspace root (models pass them).
538        match cwd.filter(|d| !matches!(d.trim(), "" | "." | "./")) {
539            None => Ok(self.root.clone()),
540            Some(d) => match resolve_existing(&self.root, d) {
541                Ok(p) if p.is_dir() => Ok(p),
542                Ok(_) => Err(failure(format!("`{d}` is not a directory"))),
543                Err(e) => Err(failure(e.0)),
544            },
545        }
546    }
547
548    /// The environment every command gets.
549    fn command_env(&self, call_id: Option<&str>) -> Vec<(String, String)> {
550        let mut env = scrubbed_env(std::env::vars());
551        for (k, v) in &self.env {
552            env.retain(|(name, _)| name != k);
553            env.push((k.clone(), v.clone()));
554        }
555        let rules = self.policy.protected().rules();
556        for (k, v) in rules.env {
557            env.retain(|(name, _)| name != k);
558            env.push(((*k).to_owned(), (*v).to_owned()));
559        }
560        // Found on this machine: never in place of a value already there.
561        let found = (rules.found_env)(&|k: &str| {
562            env.iter()
563                .find(|(name, _)| name == k)
564                .map(|(_, v)| v.clone())
565        });
566        for (k, v) in found {
567            if !env.iter().any(|(name, _)| *name == k) {
568                env.push((k, v));
569            }
570        }
571        if let Some(id) = call_id {
572            env.push(("SPECCODER_CALL_ID".to_owned(), id.to_owned()));
573        }
574        env
575    }
576
577    /// A command's object: its argv, the directory it runs in and the
578    /// executable that directory and environment resolve it to. An
579    /// executable inside the workspace is named with the digest of its
580    /// content: the model can rewrite it, and a rewritten one is another
581    /// object (asked again, and refused at use when it changed after the
582    /// decision).
583    fn command_object(
584        &self,
585        argv: &[String],
586        cwd: Option<&str>,
587        network: bool,
588    ) -> Result<Object, Value> {
589        let dir = self.command_cwd(cwd)?;
590        let rel = self.rel(&dir);
591        let executable = argv
592            .first()
593            .and_then(|p| crate::sandbox::resolve_executable(p, &dir, &self.command_env(None)))
594            .map_or_else(
595                || policy::NOT_FOUND.to_owned(),
596                |p| {
597                    if p.starts_with(&self.root) {
598                        let content = std::fs::read(&p).unwrap_or_default();
599                        format!(
600                            "{} (sha256 {})",
601                            p.display(),
602                            crate::integrity::sha256_hex(&content)
603                        )
604                    } else {
605                        p.display().to_string()
606                    }
607                },
608            );
609        Ok(Object::command(
610            argv.to_vec(),
611            if rel.is_empty() { ".".to_owned() } else { rel },
612            executable,
613            network,
614        ))
615    }
616
617    /// The file a write reaches, refused when protected — judged on the
618    /// file itself, so a symlinked directory cannot carry a write into the
619    /// protected set — or when it is not the object a person's decision
620    /// covered (resolved again now: it may have changed since).
621    fn write_checked(&self, rel: &str, expect: Option<&Object>) -> Result<PathBuf, Value> {
622        let canonical = canonical_for_write(&self.root, rel).map_err(|e| failure(e.0))?;
623        if let Some(class) = self.policy.write_protected(&canonical) {
624            return Err(failure(format!(
625                "denied: `{rel}` is protected: {}",
626                self.policy.protected().reason(class)
627            )));
628        }
629        match expect {
630            Some(Object::Path { canonical: was, .. }) if *was != canonical => {
631                return Err(changed(was, &canonical));
632            }
633            Some(_) => {}
634            // Allowed by a rule on the path as asked: the rules that need
635            // a person (a frozen test, a context file, a manifest) were
636            // judged on that spelling. One that reaches another file — a
637            // symlinked directory, another letter case — is written by
638            // the name of the file it reaches, and judged on that.
639            None => {
640                let asked = normalise(rel).map_err(|e| failure(e.0))?;
641                if asked != canonical {
642                    return Err(failure(format!(
643                        "refused: `{asked}` reaches `{canonical}`; write it by that path"
644                    )));
645                }
646            }
647        }
648        Ok(self.root.join(canonical))
649    }
650
651    fn write_file(&self, a: &WriteFile) -> Value {
652        let path = match self.write_checked(&a.path, a.expect.as_ref()) {
653            Ok(p) => p,
654            Err(e) => return e,
655        };
656        if path.is_dir() {
657            return failure(format!("`{}` is a directory", a.path));
658        }
659        let before = fs::read(&path)
660            .ok()
661            .map_or_else(|| "absent".to_owned(), |b| sha(&b));
662        if let Ok(old) = fs::read_to_string(&path)
663            && let Some(refused) = removes_tests(&a.path, &old, &a.content)
664        {
665            return refused;
666        }
667        if let Some(parent) = path.parent()
668            && let Err(e) = fs::create_dir_all(parent)
669        {
670            return failure(format!("`{}`: {e}", a.path));
671        }
672        if let Err(e) = fs::write(&path, &a.content) {
673            return failure(format!("`{}`: {e}", a.path));
674        }
675        json!({ "ok": true, "path": a.path, "before": before, "after": sha(a.content.as_bytes()), "bytes": a.content.len() })
676    }
677
678    fn edit_file(&self, a: &EditFile) -> Value {
679        let path = match self.write_checked(&a.path, a.expect.as_ref()) {
680            Ok(p) => p,
681            Err(e) => return e,
682        };
683        let Ok(text) = fs::read_to_string(&path) else {
684            return failure(format!("`{}` does not exist or is not text", a.path));
685        };
686        if a.old_string.is_empty() {
687            return failure("`old_string` is empty");
688        }
689        let count = text.matches(&a.old_string).count();
690        let replace_all = a.replace_all.unwrap_or(false);
691        let new = match (count, replace_all) {
692            (0, _) => return failure(format!("`old_string` not found in `{}`", a.path)),
693            (1, _) | (_, true) => text.replace(&a.old_string, &a.new_string),
694            (n, false) => {
695                return failure(format!(
696                    "`old_string` occurs {n} times in `{}`; add context to make it unique or set replace_all",
697                    a.path
698                ));
699            }
700        };
701        if let Some(refused) = removes_tests(&a.path, &text, &new) {
702            return refused;
703        }
704        if let Err(e) = fs::write(&path, &new) {
705            return failure(format!("`{}`: {e}", a.path));
706        }
707        json!({ "ok": true, "path": a.path, "replacements": if replace_all { count } else { 1 }, "before": sha(text.as_bytes()), "after": sha(new.as_bytes()) })
708    }
709
710    async fn run_command(&self, a: RunCommand) -> Value {
711        let cwd = match self.command_cwd(a.cwd.as_deref()) {
712            Ok(c) => c,
713            Err(e) => return e,
714        };
715        // A command decided on its object runs only as that object: the
716        // same directory, the same executable — resolved again now.
717        if let Some(Object::Command {
718            cwd: was_cwd,
719            executable: was_exe,
720            ..
721        }) = &a.expect
722        {
723            match self.command_object(&a.argv, a.cwd.as_deref(), a.network == Some(true)) {
724                Ok(Object::Command {
725                    cwd, executable, ..
726                }) if cwd != *was_cwd || executable != *was_exe => {
727                    return changed(
728                        &format!("{was_exe} in {was_cwd}"),
729                        &format!("{executable} in {cwd}"),
730                    );
731                }
732                Ok(_) => {}
733                Err(e) => return e,
734            }
735        }
736        let secs = a.timeout_secs.unwrap_or(120).clamp(1, MAX_COMMAND_SECS);
737        let env = self.command_env(a.call_id.as_deref());
738        let inv = Invocation {
739            argv: a.argv,
740            cwd,
741            env,
742            timeout: Duration::from_secs(secs),
743            output_cap: OUTPUT_CAP,
744        };
745        // Tests run model-written code: what a command changes among the
746        // judge's inputs is found now, not at the end of the attempt.
747        let judged_before = crate::integrity::JudgeSnapshot::take(&self.root, &self.policy);
748        let runner = self.runner.clone();
749        let network = a.network == Some(true);
750        let outcome =
751            match tokio::task::spawn_blocking(move || runner.run_with(&inv, network)).await {
752                Ok(o) => o,
753                Err(e) => return failure(format!("the command runner failed: {e}")),
754            };
755        if let Some(e) = outcome.spawn_error {
756            return failure(e);
757        }
758        let tail = |b: &[u8]| {
759            let start = b.len().saturating_sub(16 * 1024);
760            String::from_utf8_lossy(&b[start..]).into_owned()
761        };
762        let drift = judged_before.drift(
763            &crate::integrity::JudgeSnapshot::take(&self.root, &self.policy),
764            &self.policy,
765            &std::collections::BTreeSet::new(),
766        );
767        let mut result = json!({
768            "ok": outcome.exit_code == Some(0),
769            "exit_code": outcome.exit_code,
770            "timed_out": outcome.timed_out,
771            "duration_ms": u64::try_from(outcome.duration.as_millis()).unwrap_or(u64::MAX),
772            "stdout": tail(&outcome.stdout.kept),
773            "stderr": tail(&outcome.stderr.kept),
774            "truncated": outcome.stdout.truncated() || outcome.stderr.truncated(),
775        });
776        if !drift.is_empty() {
777            result["integrity"] = json!(drift);
778        }
779        result
780    }
781
782    fn git_status(&self) -> Value {
783        match Git::at(&self.root).run(&["status", "--porcelain=v1", "-z", "--untracked-files=all"])
784        {
785            Ok(out) => {
786                let entries: Vec<String> = nul_fields(&out);
787                json!({ "ok": true, "entries": entries })
788            }
789            Err(e) => failure(e.0),
790        }
791    }
792
793    fn git_diff(&self, a: &GitDiff) -> Value {
794        let mut args = vec!["diff", "--no-color", "HEAD"];
795        let path;
796        if let Some(p) = &a.path {
797            path = match paths::normalise(p) {
798                Ok(p) => p,
799                Err(e) => return failure(e.0),
800            };
801            args.extend(["--", path.as_str()]);
802        }
803        match Git::at(&self.root).run(&args) {
804            Ok(out) => {
805                let mut diff = String::from_utf8_lossy(&out).into_owned();
806                let truncated = diff.len() > READ_CAP;
807                if truncated {
808                    let mut cut = READ_CAP;
809                    while !diff.is_char_boundary(cut) {
810                        cut -= 1;
811                    }
812                    diff.truncate(cut);
813                }
814                json!({ "ok": true, "diff": diff, "truncated": truncated })
815            }
816            Err(e) => failure(e.0),
817        }
818    }
819}
820
821#[async_trait]
822impl ToolClient for WorkspaceTools {
823    async fn call(
824        &self,
825        tool: &ToolId,
826        arguments: &Value,
827        _provenance: Option<&agentplane::core::Provenance>,
828    ) -> Result<Value, ToolError> {
829        let known = catalog()
830            .into_iter()
831            .chain(internal())
832            .any(|t| t.server == tool.server && t.name == tool.tool);
833        if !known {
834            return Err(ToolError::Refused {
835                tool: tool.clone(),
836                detail: "not a speccoder tool".to_owned(),
837            });
838        }
839        Ok(self.run(&tool.tool, arguments).await)
840    }
841
842    /// The tools touch only the local worktree. (A command the model runs
843    /// may still use the network; that is the policy's and, in M6, the
844    /// sandbox's concern, not a transport this client opens.)
845    fn destination(&self, _tool: &ToolId) -> Destination {
846        Destination::Local
847    }
848}