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        for (k, v) in self.policy.protected().rules().env {
556            env.retain(|(name, _)| name != k);
557            env.push(((*k).to_owned(), (*v).to_owned()));
558        }
559        if let Some(id) = call_id {
560            env.push(("SPECCODER_CALL_ID".to_owned(), id.to_owned()));
561        }
562        env
563    }
564
565    /// A command's object: its argv, the directory it runs in and the
566    /// executable that directory and environment resolve it to. An
567    /// executable inside the workspace is named with the digest of its
568    /// content: the model can rewrite it, and a rewritten one is another
569    /// object (asked again, and refused at use when it changed after the
570    /// decision).
571    fn command_object(
572        &self,
573        argv: &[String],
574        cwd: Option<&str>,
575        network: bool,
576    ) -> Result<Object, Value> {
577        let dir = self.command_cwd(cwd)?;
578        let rel = self.rel(&dir);
579        let executable = argv
580            .first()
581            .and_then(|p| crate::sandbox::resolve_executable(p, &dir, &self.command_env(None)))
582            .map_or_else(
583                || policy::NOT_FOUND.to_owned(),
584                |p| {
585                    if p.starts_with(&self.root) {
586                        let content = std::fs::read(&p).unwrap_or_default();
587                        format!(
588                            "{} (sha256 {})",
589                            p.display(),
590                            crate::integrity::sha256_hex(&content)
591                        )
592                    } else {
593                        p.display().to_string()
594                    }
595                },
596            );
597        Ok(Object::command(
598            argv.to_vec(),
599            if rel.is_empty() { ".".to_owned() } else { rel },
600            executable,
601            network,
602        ))
603    }
604
605    /// The file a write reaches, refused when protected — judged on the
606    /// file itself, so a symlinked directory cannot carry a write into the
607    /// protected set — or when it is not the object a person's decision
608    /// covered (resolved again now: it may have changed since).
609    fn write_checked(&self, rel: &str, expect: Option<&Object>) -> Result<PathBuf, Value> {
610        let canonical = canonical_for_write(&self.root, rel).map_err(|e| failure(e.0))?;
611        if let Some(class) = self.policy.write_protected(&canonical) {
612            return Err(failure(format!(
613                "denied: `{rel}` is protected: {}",
614                self.policy.protected().reason(class)
615            )));
616        }
617        match expect {
618            Some(Object::Path { canonical: was, .. }) if *was != canonical => {
619                return Err(changed(was, &canonical));
620            }
621            Some(_) => {}
622            // Allowed by a rule on the path as asked: the rules that need
623            // a person (a frozen test, a context file, a manifest) were
624            // judged on that spelling. One that reaches another file — a
625            // symlinked directory, another letter case — is written by
626            // the name of the file it reaches, and judged on that.
627            None => {
628                let asked = normalise(rel).map_err(|e| failure(e.0))?;
629                if asked != canonical {
630                    return Err(failure(format!(
631                        "refused: `{asked}` reaches `{canonical}`; write it by that path"
632                    )));
633                }
634            }
635        }
636        Ok(self.root.join(canonical))
637    }
638
639    fn write_file(&self, a: &WriteFile) -> Value {
640        let path = match self.write_checked(&a.path, a.expect.as_ref()) {
641            Ok(p) => p,
642            Err(e) => return e,
643        };
644        if path.is_dir() {
645            return failure(format!("`{}` is a directory", a.path));
646        }
647        let before = fs::read(&path)
648            .ok()
649            .map_or_else(|| "absent".to_owned(), |b| sha(&b));
650        if let Ok(old) = fs::read_to_string(&path)
651            && let Some(refused) = removes_tests(&a.path, &old, &a.content)
652        {
653            return refused;
654        }
655        if let Some(parent) = path.parent()
656            && let Err(e) = fs::create_dir_all(parent)
657        {
658            return failure(format!("`{}`: {e}", a.path));
659        }
660        if let Err(e) = fs::write(&path, &a.content) {
661            return failure(format!("`{}`: {e}", a.path));
662        }
663        json!({ "ok": true, "path": a.path, "before": before, "after": sha(a.content.as_bytes()), "bytes": a.content.len() })
664    }
665
666    fn edit_file(&self, a: &EditFile) -> Value {
667        let path = match self.write_checked(&a.path, a.expect.as_ref()) {
668            Ok(p) => p,
669            Err(e) => return e,
670        };
671        let Ok(text) = fs::read_to_string(&path) else {
672            return failure(format!("`{}` does not exist or is not text", a.path));
673        };
674        if a.old_string.is_empty() {
675            return failure("`old_string` is empty");
676        }
677        let count = text.matches(&a.old_string).count();
678        let replace_all = a.replace_all.unwrap_or(false);
679        let new = match (count, replace_all) {
680            (0, _) => return failure(format!("`old_string` not found in `{}`", a.path)),
681            (1, _) | (_, true) => text.replace(&a.old_string, &a.new_string),
682            (n, false) => {
683                return failure(format!(
684                    "`old_string` occurs {n} times in `{}`; add context to make it unique or set replace_all",
685                    a.path
686                ));
687            }
688        };
689        if let Some(refused) = removes_tests(&a.path, &text, &new) {
690            return refused;
691        }
692        if let Err(e) = fs::write(&path, &new) {
693            return failure(format!("`{}`: {e}", a.path));
694        }
695        json!({ "ok": true, "path": a.path, "replacements": if replace_all { count } else { 1 }, "before": sha(text.as_bytes()), "after": sha(new.as_bytes()) })
696    }
697
698    async fn run_command(&self, a: RunCommand) -> Value {
699        let cwd = match self.command_cwd(a.cwd.as_deref()) {
700            Ok(c) => c,
701            Err(e) => return e,
702        };
703        // A command decided on its object runs only as that object: the
704        // same directory, the same executable — resolved again now.
705        if let Some(Object::Command {
706            cwd: was_cwd,
707            executable: was_exe,
708            ..
709        }) = &a.expect
710        {
711            match self.command_object(&a.argv, a.cwd.as_deref(), a.network == Some(true)) {
712                Ok(Object::Command {
713                    cwd, executable, ..
714                }) if cwd != *was_cwd || executable != *was_exe => {
715                    return changed(
716                        &format!("{was_exe} in {was_cwd}"),
717                        &format!("{executable} in {cwd}"),
718                    );
719                }
720                Ok(_) => {}
721                Err(e) => return e,
722            }
723        }
724        let secs = a.timeout_secs.unwrap_or(120).clamp(1, MAX_COMMAND_SECS);
725        let env = self.command_env(a.call_id.as_deref());
726        let inv = Invocation {
727            argv: a.argv,
728            cwd,
729            env,
730            timeout: Duration::from_secs(secs),
731            output_cap: OUTPUT_CAP,
732        };
733        // Tests run model-written code: what a command changes among the
734        // judge's inputs is found now, not at the end of the attempt.
735        let judged_before = crate::integrity::JudgeSnapshot::take(&self.root, &self.policy);
736        let runner = self.runner.clone();
737        let network = a.network == Some(true);
738        let outcome =
739            match tokio::task::spawn_blocking(move || runner.run_with(&inv, network)).await {
740                Ok(o) => o,
741                Err(e) => return failure(format!("the command runner failed: {e}")),
742            };
743        if let Some(e) = outcome.spawn_error {
744            return failure(e);
745        }
746        let tail = |b: &[u8]| {
747            let start = b.len().saturating_sub(16 * 1024);
748            String::from_utf8_lossy(&b[start..]).into_owned()
749        };
750        let drift = judged_before.drift(
751            &crate::integrity::JudgeSnapshot::take(&self.root, &self.policy),
752            &self.policy,
753            &std::collections::BTreeSet::new(),
754        );
755        let mut result = json!({
756            "ok": outcome.exit_code == Some(0),
757            "exit_code": outcome.exit_code,
758            "timed_out": outcome.timed_out,
759            "duration_ms": u64::try_from(outcome.duration.as_millis()).unwrap_or(u64::MAX),
760            "stdout": tail(&outcome.stdout.kept),
761            "stderr": tail(&outcome.stderr.kept),
762            "truncated": outcome.stdout.truncated() || outcome.stderr.truncated(),
763        });
764        if !drift.is_empty() {
765            result["integrity"] = json!(drift);
766        }
767        result
768    }
769
770    fn git_status(&self) -> Value {
771        match Git::at(&self.root).run(&["status", "--porcelain=v1", "-z", "--untracked-files=all"])
772        {
773            Ok(out) => {
774                let entries: Vec<String> = nul_fields(&out);
775                json!({ "ok": true, "entries": entries })
776            }
777            Err(e) => failure(e.0),
778        }
779    }
780
781    fn git_diff(&self, a: &GitDiff) -> Value {
782        let mut args = vec!["diff", "--no-color", "HEAD"];
783        let path;
784        if let Some(p) = &a.path {
785            path = match paths::normalise(p) {
786                Ok(p) => p,
787                Err(e) => return failure(e.0),
788            };
789            args.extend(["--", path.as_str()]);
790        }
791        match Git::at(&self.root).run(&args) {
792            Ok(out) => {
793                let mut diff = String::from_utf8_lossy(&out).into_owned();
794                let truncated = diff.len() > READ_CAP;
795                if truncated {
796                    let mut cut = READ_CAP;
797                    while !diff.is_char_boundary(cut) {
798                        cut -= 1;
799                    }
800                    diff.truncate(cut);
801                }
802                json!({ "ok": true, "diff": diff, "truncated": truncated })
803            }
804            Err(e) => failure(e.0),
805        }
806    }
807}
808
809#[async_trait]
810impl ToolClient for WorkspaceTools {
811    async fn call(
812        &self,
813        tool: &ToolId,
814        arguments: &Value,
815        _provenance: Option<&agentplane::core::Provenance>,
816    ) -> Result<Value, ToolError> {
817        let known = catalog()
818            .into_iter()
819            .chain(internal())
820            .any(|t| t.server == tool.server && t.name == tool.tool);
821        if !known {
822            return Err(ToolError::Refused {
823                tool: tool.clone(),
824                detail: "not a speccoder tool".to_owned(),
825            });
826        }
827        Ok(self.run(&tool.tool, arguments).await)
828    }
829
830    /// The tools touch only the local worktree. (A command the model runs
831    /// may still use the network; that is the policy's and, in M6, the
832    /// sandbox's concern, not a transport this client opens.)
833    fn destination(&self, _tool: &ToolId) -> Destination {
834        Destination::Local
835    }
836}