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        // A value copied from the person's secret files never reaches the
393        // model, nor the journal its results are kept in.
394        let mut out = out.unwrap_or_else(|e| e);
395        crate::secrets::mask_json(&mut out);
396        out
397    }
398
399    fn rel(&self, p: &Path) -> String {
400        p.strip_prefix(&self.root)
401            .unwrap_or(p)
402            .to_string_lossy()
403            .replace('\\', "/")
404    }
405
406    fn read_file(&self, a: &ReadFile) -> Value {
407        let path = match resolve_existing(&self.root, &a.path) {
408            Ok(p) => p,
409            Err(e) => return failure(e.0),
410        };
411        if self.protected().is_secret(&self.rel(&path)) {
412            return failure(format!("`{}` looks like a credential", a.path));
413        }
414        let bytes = match fs::read(&path) {
415            Ok(b) => b,
416            Err(e) => return failure(format!("`{}`: {e}", a.path)),
417        };
418        let Ok(text) = String::from_utf8(bytes.clone()) else {
419            return json!({ "ok": true, "path": a.path, "binary": true, "bytes": bytes.len() });
420        };
421        let lines: Vec<&str> = text.lines().collect();
422        let start = a.start_line.unwrap_or(1).max(1);
423        let end = a.end_line.unwrap_or(lines.len()).min(lines.len());
424        // Masked before any cut: a cut value would leave its start shown.
425        let mut content = if start > end {
426            String::new()
427        } else {
428            crate::secrets::mask(&lines[start - 1..end].join("\n"))
429        };
430        let truncated = content.len() > READ_CAP;
431        if truncated {
432            let mut cut = READ_CAP;
433            while !content.is_char_boundary(cut) {
434                cut -= 1;
435            }
436            content.truncate(cut);
437            content.push_str("\n[… truncated; read a line range …]");
438        }
439        json!({ "ok": true, "path": a.path, "start_line": start, "end_line": end, "total_lines": lines.len(), "truncated": truncated, "content": content })
440    }
441
442    fn walk(&self, dir: Option<&str>, glob: Option<&str>) -> Result<Vec<PathBuf>, Value> {
443        let base = match dir {
444            Some(d) => resolve_existing(&self.root, d).map_err(|e| failure(e.0))?,
445            None => self.root.clone(),
446        };
447        let matcher = glob
448            .map(|g| globset::Glob::new(g).map(|g| g.compile_matcher()))
449            .transpose()
450            .map_err(|e| failure(format!("invalid glob: {e}")))?;
451        let mut files: Vec<PathBuf> = ignore::WalkBuilder::new(&base)
452            .hidden(false)
453            .filter_entry(|e| e.file_name() != ".git")
454            .build()
455            .flatten()
456            .filter(|e| e.file_type().is_some_and(|t| t.is_file()))
457            .map(ignore::DirEntry::into_path)
458            .filter(|p| {
459                let rel = self.rel(p);
460                !self.protected().is_secret(&rel)
461                    && matcher.as_ref().is_none_or(|m| m.is_match(&rel))
462            })
463            .collect();
464        files.sort();
465        Ok(files)
466    }
467
468    fn list_files(&self, a: &ListFiles) -> Value {
469        match self.walk(a.path.as_deref(), a.glob.as_deref()) {
470            Ok(files) => {
471                let total = files.len();
472                let shown: Vec<String> = files.iter().take(LIST_CAP).map(|p| self.rel(p)).collect();
473                json!({ "ok": true, "files": shown, "total": total, "truncated": total > LIST_CAP })
474            }
475            Err(e) => e,
476        }
477    }
478
479    fn search_code(&self, a: &SearchCode) -> Value {
480        let re = match regex::Regex::new(&a.pattern) {
481            Ok(r) => r,
482            Err(e) => return failure(format!("invalid pattern: {e}")),
483        };
484        let files = match self.walk(a.path.as_deref(), a.glob.as_deref()) {
485            Ok(f) => f,
486            Err(e) => return e,
487        };
488        let mut matches = Vec::new();
489        let mut total = 0usize;
490        for f in files {
491            let Ok(bytes) = fs::read(&f) else { continue };
492            if bytes.len() > 1024 * 1024 || bytes.iter().take(8192).any(|b| *b == 0) {
493                continue;
494            }
495            let text = String::from_utf8_lossy(&bytes);
496            for (i, line) in text.lines().enumerate() {
497                if re.is_match(line) {
498                    total += 1;
499                    if matches.len() < SEARCH_CAP {
500                        let shown: String =
501                            crate::secrets::mask(line).chars().take(LINE_CAP).collect();
502                        matches.push(format!("{}:{}: {shown}", self.rel(&f), i + 1));
503                    }
504                }
505            }
506        }
507        json!({ "ok": true, "matches": matches, "total": total, "truncated": total > SEARCH_CAP })
508    }
509
510    /// The object `tool` would reach with `arguments`: what a person's
511    /// decision covers (`{ok, object}`; `object` is `null` for a tool
512    /// without one, `ok: false` with the refusal when it cannot be reached).
513    #[must_use]
514    pub fn resolve(&self, tool: &str, arguments: &Value) -> Value {
515        match tool {
516            "write_file" | "edit_file" => {
517                let asked = arguments["path"].as_str().unwrap_or_default();
518                match (canonical_for_write(&self.root, asked), normalise(asked)) {
519                    (Ok(canonical), Ok(asked)) => json!({
520                        "ok": true,
521                        "object": Object::Path { canonical, asked },
522                    }),
523                    (Err(e), _) | (_, Err(e)) => failure(e.0),
524                }
525            }
526            "run_command" => {
527                let argv = policy::argv_of(arguments);
528                match self.command_object(
529                    &argv,
530                    arguments["cwd"].as_str(),
531                    arguments["network"] == true,
532                ) {
533                    Ok(object) => json!({ "ok": true, "object": object }),
534                    Err(e) => e,
535                }
536            }
537            _ => json!({ "ok": true, "object": null }),
538        }
539    }
540
541    /// The directory a command runs in.
542    pub(crate) fn command_cwd(&self, cwd: Option<&str>) -> Result<PathBuf, Value> {
543        // `.`, `./` and an empty string mean the workspace root (models pass them).
544        match cwd.filter(|d| !matches!(d.trim(), "" | "." | "./")) {
545            None => Ok(self.root.clone()),
546            Some(d) => match resolve_existing(&self.root, d) {
547                Ok(p) if p.is_dir() => Ok(p),
548                Ok(_) => Err(failure(format!("`{d}` is not a directory"))),
549                Err(e) => Err(failure(e.0)),
550            },
551        }
552    }
553
554    /// The environment every command gets.
555    pub(crate) fn command_env(&self, call_id: Option<&str>) -> Vec<(String, String)> {
556        let mut env = scrubbed_env(std::env::vars());
557        for (k, v) in &self.env {
558            env.retain(|(name, _)| name != k);
559            env.push((k.clone(), v.clone()));
560        }
561        let rules = self.policy.protected().rules();
562        for (k, v) in rules.env {
563            env.retain(|(name, _)| name != k);
564            env.push(((*k).to_owned(), (*v).to_owned()));
565        }
566        // Found on this machine: never in place of a value already there.
567        let found = (rules.found_env)(&|k: &str| {
568            env.iter()
569                .find(|(name, _)| name == k)
570                .map(|(_, v)| v.clone())
571        });
572        for (k, v) in found {
573            if !env.iter().any(|(name, _)| *name == k) {
574                env.push((k, v));
575            }
576        }
577        if let Some(id) = call_id {
578            env.push(("SPECCODER_CALL_ID".to_owned(), id.to_owned()));
579        }
580        env
581    }
582
583    /// A command's object: its argv, the directory it runs in and the
584    /// executable that directory and environment resolve it to. An
585    /// executable inside the workspace is named with the digest of its
586    /// content: the model can rewrite it, and a rewritten one is another
587    /// object (asked again, and refused at use when it changed after the
588    /// decision).
589    fn command_object(
590        &self,
591        argv: &[String],
592        cwd: Option<&str>,
593        network: bool,
594    ) -> Result<Object, Value> {
595        let dir = self.command_cwd(cwd)?;
596        let rel = self.rel(&dir);
597        let executable = argv
598            .first()
599            .and_then(|p| crate::sandbox::resolve_executable(p, &dir, &self.command_env(None)))
600            .map_or_else(
601                || policy::NOT_FOUND.to_owned(),
602                |p| {
603                    if p.starts_with(&self.root) {
604                        let content = std::fs::read(&p).unwrap_or_default();
605                        format!(
606                            "{} (sha256 {})",
607                            p.display(),
608                            crate::integrity::sha256_hex(&content)
609                        )
610                    } else {
611                        p.display().to_string()
612                    }
613                },
614            );
615        Ok(Object::command(
616            argv.to_vec(),
617            if rel.is_empty() { ".".to_owned() } else { rel },
618            executable,
619            network,
620        ))
621    }
622
623    /// The file a write reaches, refused when protected — judged on the
624    /// file itself, so a symlinked directory cannot carry a write into the
625    /// protected set — or when it is not the object a person's decision
626    /// covered (resolved again now: it may have changed since).
627    fn write_checked(&self, rel: &str, expect: Option<&Object>) -> Result<PathBuf, Value> {
628        let canonical = canonical_for_write(&self.root, rel).map_err(|e| failure(e.0))?;
629        if let Some(class) = self.policy.write_protected(&canonical) {
630            return Err(failure(format!(
631                "denied: `{rel}` is protected: {}",
632                self.policy.protected().reason(class)
633            )));
634        }
635        match expect {
636            Some(Object::Path { canonical: was, .. }) if *was != canonical => {
637                return Err(changed(was, &canonical));
638            }
639            Some(_) => {}
640            // Allowed by a rule on the path as asked: the rules that need
641            // a person (a frozen test, a context file, a manifest) were
642            // judged on that spelling. One that reaches another file — a
643            // symlinked directory, another letter case — is written by
644            // the name of the file it reaches, and judged on that.
645            None => {
646                let asked = normalise(rel).map_err(|e| failure(e.0))?;
647                if asked != canonical {
648                    return Err(failure(format!(
649                        "refused: `{asked}` reaches `{canonical}`; write it by that path"
650                    )));
651                }
652            }
653        }
654        Ok(self.root.join(canonical))
655    }
656
657    fn write_file(&self, a: &WriteFile) -> Value {
658        let path = match self.write_checked(&a.path, a.expect.as_ref()) {
659            Ok(p) => p,
660            Err(e) => return e,
661        };
662        if path.is_dir() {
663            return failure(format!("`{}` is a directory", a.path));
664        }
665        let before = fs::read(&path)
666            .ok()
667            .map_or_else(|| "absent".to_owned(), |b| sha(&b));
668        if let Ok(old) = fs::read_to_string(&path)
669            && let Some(refused) = removes_tests(&a.path, &old, &a.content)
670        {
671            return refused;
672        }
673        if let Some(parent) = path.parent()
674            && let Err(e) = fs::create_dir_all(parent)
675        {
676            return failure(format!("`{}`: {e}", a.path));
677        }
678        if let Err(e) = fs::write(&path, &a.content) {
679            return failure(format!("`{}`: {e}", a.path));
680        }
681        json!({ "ok": true, "path": a.path, "before": before, "after": sha(a.content.as_bytes()), "bytes": a.content.len() })
682    }
683
684    fn edit_file(&self, a: &EditFile) -> Value {
685        let path = match self.write_checked(&a.path, a.expect.as_ref()) {
686            Ok(p) => p,
687            Err(e) => return e,
688        };
689        let Ok(text) = fs::read_to_string(&path) else {
690            return failure(format!("`{}` does not exist or is not text", a.path));
691        };
692        if a.old_string.is_empty() {
693            return failure("`old_string` is empty");
694        }
695        let count = text.matches(&a.old_string).count();
696        let replace_all = a.replace_all.unwrap_or(false);
697        let new = match (count, replace_all) {
698            (0, _) => return failure(format!("`old_string` not found in `{}`", a.path)),
699            (1, _) | (_, true) => text.replace(&a.old_string, &a.new_string),
700            (n, false) => {
701                return failure(format!(
702                    "`old_string` occurs {n} times in `{}`; add context to make it unique or set replace_all",
703                    a.path
704                ));
705            }
706        };
707        if let Some(refused) = removes_tests(&a.path, &text, &new) {
708            return refused;
709        }
710        if let Err(e) = fs::write(&path, &new) {
711            return failure(format!("`{}`: {e}", a.path));
712        }
713        json!({ "ok": true, "path": a.path, "replacements": if replace_all { count } else { 1 }, "before": sha(text.as_bytes()), "after": sha(new.as_bytes()) })
714    }
715
716    async fn run_command(&self, a: RunCommand) -> Value {
717        let cwd = match self.command_cwd(a.cwd.as_deref()) {
718            Ok(c) => c,
719            Err(e) => return e,
720        };
721        // A command decided on its object runs only as that object: the
722        // same directory, the same executable — resolved again now.
723        if let Some(Object::Command {
724            cwd: was_cwd,
725            executable: was_exe,
726            ..
727        }) = &a.expect
728        {
729            match self.command_object(&a.argv, a.cwd.as_deref(), a.network == Some(true)) {
730                Ok(Object::Command {
731                    cwd, executable, ..
732                }) if cwd != *was_cwd || executable != *was_exe => {
733                    return changed(
734                        &format!("{was_exe} in {was_cwd}"),
735                        &format!("{executable} in {cwd}"),
736                    );
737                }
738                Ok(_) => {}
739                Err(e) => return e,
740            }
741        }
742        let secs = a.timeout_secs.unwrap_or(120).clamp(1, MAX_COMMAND_SECS);
743        let env = self.command_env(a.call_id.as_deref());
744        let inv = Invocation {
745            argv: a.argv,
746            cwd,
747            env,
748            timeout: Duration::from_secs(secs),
749            output_cap: OUTPUT_CAP,
750        };
751        // Tests run model-written code: what a command changes among the
752        // judge's inputs is found now, not at the end of the attempt.
753        let judged_before = crate::integrity::JudgeSnapshot::take(&self.root, &self.policy);
754        let runner = self.runner.clone();
755        let network = a.network == Some(true);
756        let outcome =
757            match tokio::task::spawn_blocking(move || runner.run_with(&inv, network)).await {
758                Ok(o) => o,
759                Err(e) => return failure(format!("the command runner failed: {e}")),
760            };
761        if let Some(e) = outcome.spawn_error {
762            return failure(e);
763        }
764        let tail = |b: &[u8]| {
765            let start = b.len().saturating_sub(16 * 1024);
766            String::from_utf8_lossy(&b[start..]).into_owned()
767        };
768        let drift = judged_before.drift(
769            &crate::integrity::JudgeSnapshot::take(&self.root, &self.policy),
770            &self.policy,
771            &std::collections::BTreeSet::new(),
772        );
773        let mut result = json!({
774            "ok": outcome.exit_code == Some(0),
775            "exit_code": outcome.exit_code,
776            "timed_out": outcome.timed_out,
777            "duration_ms": u64::try_from(outcome.duration.as_millis()).unwrap_or(u64::MAX),
778            "stdout": tail(&outcome.stdout.kept),
779            "stderr": tail(&outcome.stderr.kept),
780            "truncated": outcome.stdout.truncated() || outcome.stderr.truncated(),
781        });
782        if !drift.is_empty() {
783            result["integrity"] = json!(drift);
784        }
785        result
786    }
787
788    fn git_status(&self) -> Value {
789        match Git::at(&self.root).run(&["status", "--porcelain=v1", "-z", "--untracked-files=all"])
790        {
791            Ok(out) => {
792                let entries: Vec<String> = nul_fields(&out);
793                json!({ "ok": true, "entries": entries })
794            }
795            Err(e) => failure(e.0),
796        }
797    }
798
799    fn git_diff(&self, a: &GitDiff) -> Value {
800        let mut args = vec!["diff", "--no-color", "HEAD"];
801        let path;
802        if let Some(p) = &a.path {
803            path = match paths::normalise(p) {
804                Ok(p) => p,
805                Err(e) => return failure(e.0),
806            };
807            args.extend(["--", path.as_str()]);
808        }
809        match Git::at(&self.root).run(&args) {
810            Ok(out) => {
811                let mut diff = crate::secrets::mask(&String::from_utf8_lossy(&out));
812                let truncated = diff.len() > READ_CAP;
813                if truncated {
814                    let mut cut = READ_CAP;
815                    while !diff.is_char_boundary(cut) {
816                        cut -= 1;
817                    }
818                    diff.truncate(cut);
819                }
820                json!({ "ok": true, "diff": diff, "truncated": truncated })
821            }
822            Err(e) => failure(e.0),
823        }
824    }
825}
826
827#[async_trait]
828impl ToolClient for WorkspaceTools {
829    async fn call(
830        &self,
831        tool: &ToolId,
832        arguments: &Value,
833        _provenance: Option<&agentplane::core::Provenance>,
834    ) -> Result<Value, ToolError> {
835        let known = catalog()
836            .into_iter()
837            .chain(internal())
838            .any(|t| t.server == tool.server && t.name == tool.tool);
839        if !known {
840            return Err(ToolError::Refused {
841                tool: tool.clone(),
842                detail: "not a speccoder tool".to_owned(),
843            });
844        }
845        Ok(self.run(&tool.tool, arguments).await)
846    }
847
848    /// The tools touch only the local worktree. (A command the model runs
849    /// may still use the network; that is the policy's and, in M6, the
850    /// sandbox's concern, not a transport this client opens.)
851    fn destination(&self, _tool: &ToolId) -> Destination {
852        Destination::Local
853    }
854}