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