Skip to main content

mermaid_cli/providers/tool/
filesystem.rs

1//! Filesystem tools ported to `ToolExecutor`.
2//!
3//! This is the proof-of-pattern tool impl for C3: `ReadFileTool` and
4//! `WriteFileTool`. They hook the `ExecContext::token` so Ctrl+C
5//! cancels mid-read (relevant for large files on slow storage), and
6//! they emit `ProgressEvent::Status` breadcrumbs for multi-file
7//! operations the old code couldn't surface without an observer
8//! callback.
9//!
10//! The implementations don't try to out-clever the existing tool
11//! behavior in `src/agents/filesystem.rs`. Same semantics, same error
12//! shapes — just wrapped in the new trait so future tools only have
13//! to learn this surface.
14
15use std::path::{Path, PathBuf};
16
17use async_trait::async_trait;
18
19use crate::constants::MAX_RESPONSE_CHARS as MAX_FILE_READ_BYTES;
20use crate::domain::{ToolDefinition, ToolMetadata, ToolOutcome, ToolRunMetadata};
21
22use super::super::ctx::{ExecContext, ProgressEvent};
23use super::ToolExecutor;
24use super::path_safety::{
25    AllowedRoots, ResolvedInRoot, relative_within, resolve_in_roots, resolve_path_within,
26};
27
28/// Small helper for building a `ToolDefinition` with a typical
29/// JSON-schema-shaped input_schema. Keeps the per-tool definitions
30/// readable.
31fn defn(name: &str, description: &str, input_schema: serde_json::Value) -> ToolDefinition {
32    ToolDefinition {
33        name: name.to_string(),
34        description: description.to_string(),
35        input_schema,
36    }
37}
38
39/// Aggregate cap for a multi-file `read_file` result (#F45). Each file is
40/// individually bounded at `MAX_RESPONSE_CHARS` by `read_one`, but a batch of up
41/// to `MAX_BATCH_TOOL_ITEMS` files could otherwise sum to ~12.8 MB in a single
42/// tool result — far past any sane model-context budget. This bounds the
43/// combined total; single-file reads are already bounded and unaffected.
44const MAX_READ_AGGREGATE_CHARS: usize = crate::constants::MAX_RESPONSE_CHARS;
45
46/// `read_file` — read one or more files and return their contents
47/// joined with section markers.
48pub struct ReadFileTool;
49
50#[async_trait]
51impl ToolExecutor for ReadFileTool {
52    fn name(&self) -> &'static str {
53        "read_file"
54    }
55
56    fn schema(&self) -> ToolDefinition {
57        defn(
58            "read_file",
59            "Read the contents of one or more files from disk. Prefer relative paths; absolute paths must resolve inside the project directory, the session scratchpad, or the memory directories, or the call is rejected.",
60            serde_json::json!({
61                "type": "object",
62                "properties": {
63                    "path": { "type": "string", "description": "File to read (single)." },
64                    "paths": {
65                        "type": "array",
66                        "items": { "type": "string" },
67                        "description": "Multiple files to read sequentially, in order."
68                    }
69                },
70                "oneOf": [
71                    { "required": ["path"] },
72                    { "required": ["paths"] }
73                ]
74            }),
75        )
76    }
77
78    async fn execute(&self, args: serde_json::Value, ctx: ExecContext) -> ToolOutcome {
79        let paths = match extract_paths(&args) {
80            Ok(p) => p,
81            Err(e) => return ToolOutcome::error(e, 0.0),
82        };
83        if paths.is_empty() {
84            return ToolOutcome::error("read_file requires at least one path", 0.0);
85        }
86
87        let start = std::time::Instant::now();
88        let roots = AllowedRoots::new(&ctx.workdir, ctx.scratchpad.as_deref());
89        let mut combined = String::new();
90        let mut any_truncated = false;
91
92        for (idx, raw_path) in paths.iter().enumerate() {
93            // Race the file read against the turn's cancel token. If
94            // the user Ctrl+C's mid-read, we bail immediately.
95            tokio::select! {
96                biased;
97                _ = ctx.token.cancelled() => {
98                    return ToolOutcome::cancelled();
99                },
100                read = read_one(&roots, raw_path) => {
101                    match read {
102                        Ok((content, was_truncated)) => {
103                            any_truncated |= was_truncated;
104                            if paths.len() > 1 {
105                                let _ = ctx.progress.send(ProgressEvent::Status(
106                                    format!("read {}/{}: {}", idx + 1, paths.len(), raw_path),
107                                )).await;
108                                combined.push_str(&format!(
109                                    "=== {} ===\n{}\n\n",
110                                    raw_path, content
111                                ));
112                            } else {
113                                combined = content;
114                            }
115                        },
116                        Err(e) => {
117                            return ToolOutcome::error(
118                                format!("{}: {}", raw_path, e),
119                                start.elapsed().as_secs_f64(),
120                            );
121                        },
122                    }
123                },
124            }
125        }
126
127        // F45: bound the COMBINED multi-file result. Each file is already capped
128        // at MAX_RESPONSE_CHARS by read_one, but a batch of files can still sum to
129        // ~12.8 MB in one tool result — past any sane context budget. Only the
130        // multi-file accumulation needs this (single-file output is already
131        // bounded); truncate_middle keeps the head AND tail with an elision marker.
132        if paths.len() > 1 && combined.len() > MAX_READ_AGGREGATE_CHARS {
133            combined = crate::utils::truncate_middle(&combined, MAX_READ_AGGREGATE_CHARS);
134            any_truncated = true;
135        }
136
137        let duration_secs = start.elapsed().as_secs_f64();
138        let line_count = combined.lines().count();
139        let byte_count = combined.len();
140        // The REAL truncation flag from the bounded read — not a sniff for the
141        // marker string, which a file containing that literal text would
142        // falsely trip (#78).
143        let truncated = any_truncated;
144        ToolOutcome::success(
145            combined,
146            format!(
147                "{} {} read",
148                line_count,
149                plural(line_count, "line", "lines")
150            ),
151            duration_secs,
152        )
153        .with_metadata(ToolRunMetadata {
154            detail: ToolMetadata::ReadFile {
155                paths,
156                line_count,
157                byte_count,
158                truncated,
159            },
160            line_count: Some(line_count),
161            byte_count: Some(byte_count),
162            ..ToolRunMetadata::default()
163        })
164    }
165}
166
167/// `delete_file` — unlink a file. Errors on directories (use
168/// `execute_command rm -rf` for those — the model shouldn't be
169/// blowing away directories as a routine op).
170pub struct DeleteFileTool;
171
172#[async_trait]
173impl ToolExecutor for DeleteFileTool {
174    fn name(&self) -> &'static str {
175        "delete_file"
176    }
177
178    fn schema(&self) -> ToolDefinition {
179        defn(
180            "delete_file",
181            "Remove a file from disk. Paths must resolve inside the project directory or the session scratchpad. Fails on directories — use `execute_command rm -rf` for those.",
182            serde_json::json!({
183                "type": "object",
184                "properties": { "path": { "type": "string" } },
185                "required": ["path"]
186            }),
187        )
188    }
189
190    async fn execute(&self, args: serde_json::Value, ctx: ExecContext) -> ToolOutcome {
191        let Some(raw_path) = args.get("path").and_then(|v| v.as_str()) else {
192            return err("delete_file requires 'path'", 0.0);
193        };
194        let start = std::time::Instant::now();
195        let roots = AllowedRoots::new(&ctx.workdir, ctx.scratchpad.as_deref());
196        let ResolvedInRoot {
197            abs,
198            rel,
199            root,
200            in_scratchpad,
201        } = match resolve_in_roots(&roots, raw_path) {
202            Ok(r) => r,
203            Err(e) => return err(&format!("delete_file: {}", e), 0.0),
204        };
205        let pending_action = serde_json::json!({
206            "tool": "delete_file",
207            "args": { "path": raw_path },
208            "workdir": ctx.workdir.display().to_string(),
209            "turn_id": ctx.turn.0,
210            "call_id": ctx.call_id.0,
211            "task_id": ctx.task_id.clone(),
212        });
213        if let Some(outcome) = mutation_policy_outcome(
214            &ctx,
215            "delete_file",
216            raw_path,
217            std::slice::from_ref(&abs),
218            pending_action,
219            in_scratchpad,
220        )
221        .await
222        {
223            return outcome;
224        }
225        // Serialize writers to this canonical path: sibling tool calls in the same
226        // turn run concurrently, so without this the checkpoint + delete could race
227        // another writer to the same file. Distinct paths still overlap. Raced
228        // against cancellation so a contended lock stays Ctrl+C-responsive.
229        let _write_guard = tokio::select! {
230            biased;
231            _ = ctx.token.cancelled() => return ToolOutcome::cancelled(),
232            g = super::path_lock::lock_path(&abs) => g,
233        };
234        // Scratchpad files are session-private and ephemeral — never
235        // checkpointed into the project's restore history.
236        if ctx.config.safety.checkpoint_on_mutation
237            && !in_scratchpad
238            && let Err(e) = crate::runtime::create_checkpoint_for_task(
239                &ctx.workdir,
240                std::slice::from_ref(&abs),
241                Some(serde_json::json!({
242                    "tool": "delete_file",
243                    "path": raw_path,
244                })),
245                ctx.checkpoint_origin(),
246            )
247        {
248            return err(&format!("delete_file checkpoint failed: {}", e), 0.0);
249        }
250        let display = raw_path.to_string();
251
252        tokio::select! {
253            biased;
254            _ = ctx.token.cancelled() => ToolOutcome::cancelled(),
255            result = tokio::task::spawn_blocking(move || crate::runtime::remove_file_beneath(&root, &rel)) => {
256                match result {
257                    Ok(Ok(())) => {
258                        let duration_secs = start.elapsed().as_secs_f64();
259                        after_file_mutation(&ctx, "delete_file", &display);
260                        ToolOutcome::success(
261                            format!("Deleted {}", display),
262                            "file deleted",
263                            duration_secs,
264                        )
265                        .with_metadata(ToolRunMetadata {
266                            detail: ToolMetadata::DeleteFile { path: display },
267                            ..ToolRunMetadata::default()
268                        })
269                    },
270                    Ok(Err(e)) => err(&format!("delete_file({}): {}", display, e),
271                                       start.elapsed().as_secs_f64()),
272                    Err(e) => err(&format!("delete_file join error: {}", e),
273                                   start.elapsed().as_secs_f64()),
274                }
275            }
276        }
277    }
278}
279
280/// `create_directory` — `mkdir -p` semantics.
281pub struct CreateDirectoryTool;
282
283#[async_trait]
284impl ToolExecutor for CreateDirectoryTool {
285    fn name(&self) -> &'static str {
286        "create_directory"
287    }
288
289    fn schema(&self) -> ToolDefinition {
290        defn(
291            "create_directory",
292            "Create a directory (and any missing parents) at the given path, inside the project directory or the session scratchpad.",
293            serde_json::json!({
294                "type": "object",
295                "properties": { "path": { "type": "string" } },
296                "required": ["path"]
297            }),
298        )
299    }
300
301    async fn execute(&self, args: serde_json::Value, ctx: ExecContext) -> ToolOutcome {
302        let Some(raw_path) = args.get("path").and_then(|v| v.as_str()) else {
303            return err("create_directory requires 'path'", 0.0);
304        };
305        let start = std::time::Instant::now();
306        let roots = AllowedRoots::new(&ctx.workdir, ctx.scratchpad.as_deref());
307        let ResolvedInRoot {
308            abs,
309            rel,
310            root,
311            in_scratchpad,
312        } = match resolve_in_roots(&roots, raw_path) {
313            Ok(r) => r,
314            Err(e) => return err(&format!("create_directory: {}", e), 0.0),
315        };
316        let pending_action = serde_json::json!({
317            "tool": "create_directory",
318            "args": { "path": raw_path },
319            "workdir": ctx.workdir.display().to_string(),
320            "turn_id": ctx.turn.0,
321            "call_id": ctx.call_id.0,
322            "task_id": ctx.task_id.clone(),
323        });
324        if let Some(outcome) = mutation_policy_outcome(
325            &ctx,
326            "create_directory",
327            raw_path,
328            std::slice::from_ref(&abs),
329            pending_action,
330            in_scratchpad,
331        )
332        .await
333        {
334            return outcome;
335        }
336        // Serialize writers to this canonical path (see delete_file). mkdir -p is
337        // idempotent, but a uniform gate keeps ordering consistent and cheap.
338        let _write_guard = tokio::select! {
339            biased;
340            _ = ctx.token.cancelled() => return ToolOutcome::cancelled(),
341            g = super::path_lock::lock_path(&abs) => g,
342        };
343        // Scratchpad dirs are session-private and ephemeral — never checkpointed.
344        if ctx.config.safety.checkpoint_on_mutation
345            && !in_scratchpad
346            && let Err(e) = crate::runtime::create_checkpoint_for_task(
347                &ctx.workdir,
348                std::slice::from_ref(&abs),
349                Some(serde_json::json!({
350                    "tool": "create_directory",
351                    "path": raw_path,
352                })),
353                ctx.checkpoint_origin(),
354            )
355        {
356            return err(&format!("create_directory checkpoint failed: {}", e), 0.0);
357        }
358        let display = raw_path.to_string();
359
360        tokio::select! {
361            biased;
362            _ = ctx.token.cancelled() => ToolOutcome::cancelled(),
363            result = tokio::task::spawn_blocking(move || crate::runtime::create_dir_all_beneath(&root, &rel)) => {
364                match result {
365                    Ok(Ok(())) => {
366                        let duration_secs = start.elapsed().as_secs_f64();
367                        after_file_mutation(&ctx, "create_directory", &display);
368                        ToolOutcome::success(
369                            format!("Created directory {}", display),
370                            "directory created",
371                            duration_secs,
372                        )
373                        .with_metadata(ToolRunMetadata {
374                            detail: ToolMetadata::CreateDirectory { path: display },
375                            ..ToolRunMetadata::default()
376                        })
377                    },
378                    Ok(Err(e)) => err(&format!("create_directory({}): {}", display, e),
379                                       start.elapsed().as_secs_f64()),
380                    Err(e) => err(&format!("create_directory join error: {}", e),
381                                   start.elapsed().as_secs_f64()),
382                }
383            }
384        }
385    }
386}
387
388/// `write_file` — write a single file, creating parent dirs as needed.
389pub struct WriteFileTool;
390
391#[async_trait]
392impl ToolExecutor for WriteFileTool {
393    fn name(&self) -> &'static str {
394        "write_file"
395    }
396
397    fn schema(&self) -> ToolDefinition {
398        defn(
399            "write_file",
400            "Write (overwrite) a file at `path` with `content`. Creates parent directories automatically. Paths must resolve inside the project directory or the session scratchpad. Prefer `apply_patch` for small targeted changes.",
401            serde_json::json!({
402                "type": "object",
403                "properties": {
404                    "path": { "type": "string" },
405                    "content": { "type": "string" }
406                },
407                "required": ["path", "content"]
408            }),
409        )
410    }
411
412    async fn execute(&self, args: serde_json::Value, ctx: ExecContext) -> ToolOutcome {
413        let Some(path) = args.get("path").and_then(|v| v.as_str()) else {
414            return ToolOutcome::error("write_file requires 'path' (string)", 0.0);
415        };
416        let Some(content) = args.get("content").and_then(|v| v.as_str()) else {
417            return ToolOutcome::error("write_file requires 'content' (string)", 0.0);
418        };
419
420        let start = std::time::Instant::now();
421        let roots = AllowedRoots::new(&ctx.workdir, ctx.scratchpad.as_deref());
422        // `rel` is the root-relative name for the confined fd write (the actual
423        // byte path).
424        let ResolvedInRoot {
425            abs: abs_path,
426            rel,
427            root,
428            in_scratchpad,
429        } = match resolve_in_roots(&roots, path) {
430            Ok(r) => r,
431            Err(e) => return ToolOutcome::error(format!("write_file: {}", e), 0.0),
432        };
433        let pending_action = serde_json::json!({
434            "tool": "write_file",
435            "args": { "path": path, "content": content },
436            "workdir": ctx.workdir.display().to_string(),
437            "turn_id": ctx.turn.0,
438            "call_id": ctx.call_id.0,
439            "task_id": ctx.task_id.clone(),
440        });
441        if let Some(outcome) = mutation_policy_outcome(
442            &ctx,
443            "write_file",
444            path,
445            std::slice::from_ref(&abs_path),
446            pending_action,
447            in_scratchpad,
448        )
449        .await
450        {
451            return outcome;
452        }
453        // Serialize writers to this canonical path: two write_file/edit calls to
454        // the same file in one turn run concurrently, so without this the last
455        // atomic rename silently wins (lost update). Distinct paths still overlap.
456        // The owned guard is Send and held across the spawn_blocking below.
457        let _write_guard = tokio::select! {
458            biased;
459            _ = ctx.token.cancelled() => return ToolOutcome::cancelled(),
460            g = super::path_lock::lock_path(&abs_path) => g,
461        };
462        // Scratchpad files are session-private and ephemeral — never checkpointed.
463        if ctx.config.safety.checkpoint_on_mutation
464            && !in_scratchpad
465            && let Err(e) = crate::runtime::create_checkpoint_for_task(
466                &ctx.workdir,
467                std::slice::from_ref(&abs_path),
468                Some(serde_json::json!({
469                    "tool": "write_file",
470                    "path": path,
471                })),
472                ctx.checkpoint_origin(),
473            )
474        {
475            return ToolOutcome::error(format!("write_file checkpoint failed: {}", e), 0.0);
476        }
477        let display_path = path.to_string();
478        let line_count = content.lines().count();
479        let byte_count = content.len();
480        let content = content.to_string();
481
482        tokio::select! {
483            biased;
484            _ = ctx.token.cancelled() => ToolOutcome::cancelled(),
485            // The prior-content read (for the display diff) now happens INSIDE
486            // this blocking job and BOUNDED (#F44/RC-L) — never a synchronous
487            // unbounded `read_to_string` on the async worker thread.
488            result = tokio::task::spawn_blocking(move || write_with_diff_blocking(&root, &abs_path, &rel, &content)) => {
489                match result {
490                    Ok(Ok(write)) => {
491                        let duration_secs = start.elapsed().as_secs_f64();
492                        after_file_mutation(&ctx, "write_file", &display_path);
493                        ToolOutcome::success(
494                            format!("Wrote {} ({} lines)", display_path, write.line_count),
495                            format!("{} {} written", write.line_count, plural(write.line_count, "line", "lines")),
496                            duration_secs,
497                        )
498                        .with_metadata(ToolRunMetadata {
499                            detail: ToolMetadata::WriteFile {
500                                path: display_path,
501                                line_count,
502                                byte_count,
503                                created: Some(write.created),
504                            },
505                            line_count: Some(line_count),
506                            byte_count: Some(byte_count),
507                            display_diff: Some(write.diff.display_diff),
508                            diff_truncated: write.diff.truncated,
509                            lines_added: write.diff.added,
510                            lines_removed: write.diff.removed,
511                            ..ToolRunMetadata::default()
512                        })
513                    },
514                    Ok(Err(e)) => ToolOutcome::error(
515                        format!("write_file({}): {}", display_path, e),
516                        start.elapsed().as_secs_f64(),
517                    ),
518                    Err(e) => ToolOutcome::error(
519                        format!("write_file join error: {}", e),
520                        start.elapsed().as_secs_f64(),
521                    ),
522                }
523            }
524        }
525    }
526}
527
528// ─── helpers ────────────────────────────────────────────────────────
529
530fn extract_paths(args: &serde_json::Value) -> Result<Vec<String>, String> {
531    // Accept both shapes: `{path: "x"}` and `{paths: ["x", "y"]}`.
532    if let Some(p) = args.get("path").and_then(|v| v.as_str()) {
533        return Ok(vec![p.to_string()]);
534    }
535    if let Some(arr) = args.get("paths").and_then(|v| v.as_array()) {
536        if arr.len() > crate::constants::MAX_BATCH_TOOL_ITEMS {
537            return Err(format!(
538                "read_file: too many paths ({}); cap is {} per call — split the request",
539                arr.len(),
540                crate::constants::MAX_BATCH_TOOL_ITEMS
541            ));
542        }
543        let mut out = Vec::with_capacity(arr.len());
544        for v in arr {
545            let Some(s) = v.as_str() else {
546                return Err("read_file 'paths' must be an array of strings".to_string());
547            };
548            out.push(s.to_string());
549        }
550        return Ok(out);
551    }
552    Err("read_file requires 'path' or 'paths'".to_string())
553}
554
555/// Read-only carve-out for memory facts. Global and project-private memory
556/// live under the OS data dir — outside both allowed roots — and the memory
557/// index tells the model to `read_file` the fact's path, so reads resolve
558/// against the memory roots too. Absolute paths only, with the same
559/// canonical (symlink-resolving) containment as the scratchpad arm. The
560/// write tools never consult this: memory mutation goes through the `memory`
561/// tool, where the policy gate can see it.
562fn resolve_in_memory_roots(workdir: &Path, raw: &str) -> Option<(PathBuf, PathBuf)> {
563    if !Path::new(raw).is_absolute() {
564        return None;
565    }
566    for (root, _scope) in crate::app::memory::memory_roots(workdir) {
567        if let Ok((_abs, true)) = resolve_path_within(&root, raw)
568            && let Ok(rel) = relative_within(&root, raw)
569        {
570            return Some((root, rel));
571        }
572    }
573    None
574}
575
576/// Read one file (bounded). Returns the (possibly marker-footed) text and the
577/// REAL truncation flag from the bounded read, so the caller propagates that
578/// rather than sniffing the output for the marker string — which a file whose
579/// own content contains that literal text would otherwise falsely trip (#78).
580async fn read_one(roots: &AllowedRoots<'_>, raw: &str) -> std::io::Result<(String, bool)> {
581    // Canonical containment gate — rejects escapes (incl. existing symlinks
582    // that resolve outside the allowed roots) before we touch the file, and
583    // names the root-relative path for the confined fd read, so the bytes come
584    // from the inode the kernel resolved under RESOLVE_BENEATH rather than
585    // whatever a concurrently-swapped symlink now points at (#77).
586    let ResolvedInRoot { rel, root, .. } = match resolve_in_roots(roots, raw) {
587        Ok(resolved) => resolved,
588        Err(msg) => {
589            let (root, rel) = resolve_in_memory_roots(roots.workdir, raw)
590                .ok_or_else(|| std::io::Error::new(std::io::ErrorKind::PermissionDenied, msg))?;
591            ResolvedInRoot {
592                abs: root.join(&rel),
593                rel,
594                root,
595                in_scratchpad: false,
596            }
597        },
598    };
599    let result = tokio::task::spawn_blocking(move || {
600        let file = crate::runtime::open_beneath(&root, &rel, crate::runtime::OpenIntent::Read)?;
601        // Bounded read: never pull more than the cap (+1 probe byte) into RAM,
602        // so a model pointing `read_file` at a multi-gigabyte file can't OOM the
603        // process — a full read would have slurped the whole thing first (#15).
604        let (data, truncated) = crate::utils::read_capped(file, MAX_FILE_READ_BYTES)?;
605        let mut s = String::from_utf8_lossy(&data).into_owned();
606        if truncated {
607            // Char-boundary-safe truncation with a marker footer.
608            let cut = s.floor_char_boundary(MAX_FILE_READ_BYTES);
609            s.truncate(cut);
610            s.push_str("\n\n[TRUNCATED: file exceeded read cap]");
611        }
612        Ok::<_, std::io::Error>((s, truncated))
613    })
614    .await
615    .map_err(|e| std::io::Error::other(e.to_string()))??;
616    Ok(result)
617}
618
619/// Write `content` to `rel` beneath `root` (the project workdir or the session
620/// scratchpad) through the symlink-confined *atomic* writer, creating parent
621/// dirs the same confined way. The bytes are written to a temp and
622/// `renameat`-swapped over the target, all beneath the directory fd the kernel
623/// resolved under `RESOLVE_BENEATH`: a parent dir swapped for an escaping
624/// symlink can't redirect the write (#77), and a crash/kill/disk-full
625/// mid-write leaves the previous file intact rather than a truncated or
626/// half-written one.
627fn write_one_blocking(root: &Path, rel: &Path, content: &str) -> std::io::Result<usize> {
628    if let Some(parent) = rel.parent()
629        && !parent.as_os_str().is_empty()
630    {
631        crate::runtime::create_dir_all_beneath(root, parent)?;
632    }
633    crate::runtime::write_atomic_beneath(root, rel, content.as_bytes())?;
634    Ok(content.lines().count())
635}
636
637struct WriteResult {
638    line_count: usize,
639    created: bool,
640    diff: crate::render::diff::DisplayDiff,
641}
642
643/// Write `content` and build the display diff against the prior file in ONE
644/// blocking job (#F44/RC-L). The prior content is read BOUNDED via
645/// [`crate::utils::read_file_capped`] — overwriting a multi-gigabyte file must
646/// not slurp it into RAM on the async worker just to render a diff. A prior file
647/// larger than the read cap (or otherwise unreadable) is elided from the diff
648/// rather than read whole.
649fn write_with_diff_blocking(
650    root: &Path,
651    abs_path: &Path,
652    rel: &Path,
653    content: &str,
654) -> std::io::Result<WriteResult> {
655    let (old_content, created, elide_diff) =
656        match crate::utils::read_file_capped(abs_path, MAX_FILE_READ_BYTES) {
657            Ok((data, false)) => (String::from_utf8_lossy(&data).into_owned(), false, false),
658            // Existing file is past the read cap — don't pull it all into RAM.
659            Ok((_, true)) => (String::new(), false, true),
660            // Missing file → a fresh create; the diff shows the whole content added.
661            Err(e) if e.kind() == std::io::ErrorKind::NotFound => (String::new(), true, false),
662            // Any other read error: don't fail the write over a diff preview.
663            Err(_) => (String::new(), false, true),
664        };
665    let diff = if elide_diff {
666        crate::render::diff::DisplayDiff {
667            display_diff: format!(
668                "[diff preview skipped: existing file exceeds the {}-byte cap]",
669                MAX_FILE_READ_BYTES
670            ),
671            added: 0,
672            removed: 0,
673            truncated: true,
674        }
675    } else {
676        crate::render::diff::generate_display_diff(&old_content, content)
677    };
678    let line_count = write_one_blocking(root, rel, content)?;
679    Ok(WriteResult {
680        line_count,
681        created,
682        diff,
683    })
684}
685
686/// `scratch_contained` is true when the mutation touches ONLY the session
687/// scratchpad (`ResolvedInRoot::in_scratchpad`). The gate downgrades an
688/// `Ask`/`Classify` on such a mutation to proceed — scratch files are
689/// session-private and ephemeral — while read-only mode and `Deny` overrides
690/// still block it.
691pub(super) async fn mutation_policy_outcome(
692    ctx: &ExecContext,
693    tool: &str,
694    path: &str,
695    checkpoint_paths: &[PathBuf],
696    pending_action: serde_json::Value,
697    scratch_contained: bool,
698) -> Option<ToolOutcome> {
699    let mut request = crate::runtime::ActionRequest::new(
700        tool,
701        crate::runtime::ToolCategory::Edit,
702        format!("{} {}", tool, path),
703    );
704    request.path = Some(path.to_string());
705    // File mutations are replayable: an Ask decision checkpoints, records an
706    // approval, and blocks (handled inside the gate).
707    match super::policy_gate::gate(
708        ctx,
709        request,
710        checkpoint_paths,
711        pending_action,
712        true,
713        scratch_contained,
714    )
715    .await
716    {
717        super::policy_gate::Gate::Block(outcome) => Some(outcome),
718        super::policy_gate::Gate::Proceed { .. } => {
719            let _ = crate::runtime::run_plugin_hooks(
720                "before_file_mutation",
721                &serde_json::json!({
722                    "task_id": ctx.task_id.clone(),
723                    "turn_id": ctx.turn.0,
724                    "call_id": ctx.call_id.0,
725                    "tool": tool,
726                    "path": path,
727                }),
728            );
729            None
730        },
731    }
732}
733
734pub(super) fn after_file_mutation(ctx: &ExecContext, tool: &str, path: &str) {
735    let _ = crate::runtime::run_plugin_hooks(
736        "after_file_mutation",
737        &serde_json::json!({
738            "task_id": ctx.task_id.clone(),
739            "turn_id": ctx.turn.0,
740            "call_id": ctx.call_id.0,
741            "tool": tool,
742            "path": path,
743        }),
744    );
745}
746
747fn err(msg: &str, duration_secs: f64) -> ToolOutcome {
748    ToolOutcome::error(msg, duration_secs)
749}
750
751fn plural(count: usize, singular: &'static str, plural: &'static str) -> &'static str {
752    if count == 1 { singular } else { plural }
753}
754
755pub(super) fn diff_summary(added: usize, removed: usize, duration_secs: f64) -> String {
756    format!(
757        "+{} -{}, took {}",
758        added,
759        removed,
760        format_duration_for_diff(duration_secs)
761    )
762}
763
764fn format_duration_for_diff(seconds: f64) -> String {
765    if seconds < 1.0 {
766        format!("{}ms", (seconds * 1000.0).round().max(1.0) as u64)
767    } else if seconds < 10.0 {
768        format!("{:.1}s", seconds)
769    } else {
770        format!("{}s", seconds.round() as u64)
771    }
772}
773
774#[cfg(test)]
775mod tests {
776    use super::*;
777    use crate::domain::{ToolCallId, TurnId};
778    use crate::providers::ctx::test_exec_context;
779    use std::fs;
780
781    /// Memory facts live outside the project/scratchpad roots and the index
782    /// tells the model to `read_file` them — reads must resolve against the
783    /// memory roots (here the ProjectShared root, reached by putting the
784    /// workdir in a subdir of the git root), while unrelated outside paths
785    /// stay rejected.
786    #[tokio::test]
787    async fn read_file_resolves_memory_roots_read_only() {
788        let base = std::env::temp_dir().join(format!("mermaid_memread_{}", std::process::id()));
789        let _ = fs::remove_dir_all(&base);
790        let repo = base.join("repo");
791        let workdir = repo.join("src");
792        fs::create_dir_all(&workdir).unwrap();
793        fs::create_dir_all(repo.join(".git")).unwrap();
794        let mem_dir = repo.join(".mermaid").join("memory");
795        fs::create_dir_all(&mem_dir).unwrap();
796        let fact = mem_dir.join("fact.md");
797        fs::write(&fact, "the fact body").unwrap();
798
799        let roots = AllowedRoots::new(&workdir, None);
800        let (content, truncated) = read_one(&roots, fact.to_str().unwrap()).await.unwrap();
801        assert!(!truncated);
802        assert_eq!(content, "the fact body");
803
804        // Still confined: an outside path that is NOT under a memory root
805        // rejects exactly as before.
806        let stray = base.join("stray.txt");
807        fs::write(&stray, "nope").unwrap();
808        assert!(read_one(&roots, stray.to_str().unwrap()).await.is_err());
809
810        let _ = fs::remove_dir_all(&base);
811    }
812
813    #[test]
814    fn resolve_in_roots_contains_to_workdir() {
815        let root = std::env::temp_dir().join(format!("mermaid_rps_{}", std::process::id()));
816        let _ = fs::remove_dir_all(&root);
817        fs::create_dir_all(root.join("sub")).unwrap();
818        let roots = AllowedRoots::new(&root, None);
819
820        // In-root existing + not-yet-existing targets resolve inside root.
821        assert!(resolve_in_roots(&roots, "sub").is_ok());
822        let resolved = resolve_in_roots(&roots, "sub/new.txt").unwrap();
823        let canon_root = fs::canonicalize(&root).unwrap();
824        assert!(resolved.abs.starts_with(&canon_root));
825
826        // `..` escape and absolute outside are rejected.
827        assert!(resolve_in_roots(&roots, "../escape.txt").is_err());
828        assert!(resolve_in_roots(&roots, "../../etc/passwd").is_err());
829        let outside = std::env::temp_dir().join("definitely_outside.txt");
830        assert!(resolve_in_roots(&roots, &outside.display().to_string()).is_err());
831
832        let _ = fs::remove_dir_all(&root);
833    }
834
835    fn temp_root(name: &str) -> PathBuf {
836        let p = std::env::temp_dir().join(format!("mermaid_providers_fs_{}", name));
837        let _ = fs::remove_dir_all(&p);
838        fs::create_dir_all(&p).expect("create tmpdir");
839        p
840    }
841
842    #[tokio::test]
843    async fn read_file_returns_content() {
844        let dir = temp_root("read_ok");
845        fs::write(dir.join("a.txt"), "hello").expect("write");
846        let (ctx, _rx) = test_exec_context(TurnId(1), ToolCallId(1), dir.clone());
847
848        let tool = ReadFileTool;
849        let outcome = tool
850            .execute(serde_json::json!({"path": "a.txt"}), ctx)
851            .await;
852        assert!(outcome.is_success(), "expected success: {:?}", outcome);
853        assert_eq!(outcome.output(), "hello");
854        let _ = fs::remove_dir_all(&dir);
855    }
856
857    #[tokio::test]
858    async fn read_file_missing_path_errors() {
859        let dir = temp_root("read_missing_path");
860        let (ctx, _rx) = test_exec_context(TurnId(1), ToolCallId(1), dir.clone());
861        let outcome = ReadFileTool.execute(serde_json::json!({}), ctx).await;
862        assert_eq!(outcome.status, crate::domain::ToolStatus::Error);
863        let _ = fs::remove_dir_all(&dir);
864    }
865
866    #[tokio::test]
867    async fn read_file_nonexistent_errors() {
868        let dir = temp_root("read_nonex");
869        let (ctx, _rx) = test_exec_context(TurnId(1), ToolCallId(1), dir.clone());
870        let outcome = ReadFileTool
871            .execute(serde_json::json!({"path": "does_not_exist.txt"}), ctx)
872            .await;
873        assert_eq!(outcome.status, crate::domain::ToolStatus::Error);
874        let _ = fs::remove_dir_all(&dir);
875    }
876
877    #[tokio::test]
878    async fn read_file_with_multiple_paths_joins_contents() {
879        let dir = temp_root("read_multi");
880        fs::write(dir.join("a.txt"), "alpha").expect("write");
881        fs::write(dir.join("b.txt"), "beta").expect("write");
882        let (ctx, _rx) = test_exec_context(TurnId(1), ToolCallId(1), dir.clone());
883        let outcome = ReadFileTool
884            .execute(serde_json::json!({"paths": ["a.txt", "b.txt"]}), ctx)
885            .await;
886        assert!(outcome.is_success(), "expected success: {:?}", outcome);
887        let output = outcome.output();
888        assert!(output.contains("=== a.txt ==="));
889        assert!(output.contains("alpha"));
890        assert!(output.contains("=== b.txt ==="));
891        assert!(output.contains("beta"));
892        let _ = fs::remove_dir_all(&dir);
893    }
894
895    #[tokio::test]
896    async fn read_file_multi_aggregate_is_capped() {
897        // F45: many files in one call can't blow past the aggregate cap. Each
898        // file is under the per-file cap, but their sum exceeds the aggregate.
899        let dir = temp_root("read_aggregate_cap");
900        let chunk = "a".repeat(MAX_READ_AGGREGATE_CHARS * 2 / 3);
901        fs::write(dir.join("a.txt"), &chunk).expect("write a");
902        fs::write(dir.join("b.txt"), &chunk).expect("write b");
903        let (ctx, _rx) = test_exec_context(TurnId(1), ToolCallId(1), dir.clone());
904        let outcome = ReadFileTool
905            .execute(serde_json::json!({"paths": ["a.txt", "b.txt"]}), ctx)
906            .await;
907        assert!(outcome.is_success(), "expected success: {:?}", outcome);
908        let output = outcome.output();
909        assert!(
910            output.len() <= MAX_READ_AGGREGATE_CHARS + 64,
911            "combined must be capped, got {} bytes",
912            output.len()
913        );
914        assert!(
915            output.contains("elided"),
916            "expected aggregate head+tail elision marker"
917        );
918        match &outcome.metadata.detail {
919            ToolMetadata::ReadFile { truncated, .. } => {
920                assert!(*truncated, "aggregate truncation must set truncated")
921            },
922            other => panic!("expected ReadFile metadata, got {:?}", other),
923        }
924        let _ = fs::remove_dir_all(&dir);
925    }
926
927    #[tokio::test]
928    async fn write_file_elides_diff_for_oversized_existing_file() {
929        // F44: overwriting a file larger than the read cap must NOT slurp it into
930        // RAM for a diff — the diff is elided with a marker instead.
931        let dir = temp_root("write_oversized_diff");
932        let big = "a".repeat(MAX_FILE_READ_BYTES + 1);
933        fs::write(dir.join("big.txt"), &big).expect("write fixture");
934        let (ctx, _rx) = test_exec_context(TurnId(1), ToolCallId(1), dir.clone());
935        let outcome = WriteFileTool
936            .execute(
937                serde_json::json!({"path": "big.txt", "content": "small\n"}),
938                ctx,
939            )
940            .await;
941        assert!(outcome.is_success(), "expected success: {:?}", outcome);
942        let diff = outcome
943            .metadata
944            .display_diff
945            .as_deref()
946            .expect("display diff");
947        assert!(
948            diff.contains("diff preview skipped"),
949            "expected elision marker, got: {diff}"
950        );
951        assert!(
952            outcome.metadata.diff_truncated,
953            "oversized diff must set diff_truncated"
954        );
955        match &outcome.metadata.detail {
956            ToolMetadata::WriteFile { created, .. } => {
957                assert_eq!(*created, Some(false), "existing file is not 'created'")
958            },
959            other => panic!("expected WriteFile metadata, got {:?}", other),
960        }
961        // The file was actually overwritten despite the elided diff.
962        let written = fs::read_to_string(dir.join("big.txt")).expect("read");
963        assert_eq!(written, "small\n");
964        let _ = fs::remove_dir_all(&dir);
965    }
966
967    #[tokio::test]
968    async fn read_file_with_marker_in_content_is_not_flagged_truncated() {
969        // #78: a small file whose own content contains the truncation-marker
970        // string must NOT be reported as truncated — the flag comes from the
971        // bounded read now, not a substring sniff of the output.
972        let dir = temp_root("read_marker_content");
973        fs::write(
974            dir.join("a.txt"),
975            "before\n\n[TRUNCATED: file exceeded read cap]\nafter",
976        )
977        .expect("write");
978        let (ctx, _rx) = test_exec_context(TurnId(1), ToolCallId(1), dir.clone());
979
980        let outcome = ReadFileTool
981            .execute(serde_json::json!({"path": "a.txt"}), ctx)
982            .await;
983        assert!(outcome.is_success(), "expected success: {:?}", outcome);
984        match &outcome.metadata.detail {
985            ToolMetadata::ReadFile { truncated, .. } => assert!(
986                !truncated,
987                "a file whose content contains the marker must not be flagged truncated"
988            ),
989            other => panic!("expected ReadFile metadata, got {:?}", other),
990        }
991        let _ = fs::remove_dir_all(&dir);
992    }
993
994    #[tokio::test]
995    async fn read_file_respects_cancellation() {
996        let dir = temp_root("read_cancel");
997        // Write a huge file so the read is slow enough to race cancel.
998        // Actually spawn_blocking on read is fast on tmpfs — this test
999        // just verifies the select! arm compiles + the token trips
1000        // the cancel path when pre-cancelled.
1001        let (ctx, _rx) = test_exec_context(TurnId(1), ToolCallId(1), dir.clone());
1002        ctx.token.cancel();
1003        let outcome = ReadFileTool
1004            .execute(serde_json::json!({"path": "x.txt"}), ctx)
1005            .await;
1006        assert!(outcome.was_cancelled());
1007        let _ = fs::remove_dir_all(&dir);
1008    }
1009
1010    #[tokio::test]
1011    async fn write_file_creates_and_counts_lines() {
1012        let dir = temp_root("write_ok");
1013        let (ctx, _rx) = test_exec_context(TurnId(1), ToolCallId(1), dir.clone());
1014        let outcome = WriteFileTool
1015            .execute(
1016                serde_json::json!({"path": "out.txt", "content": "line1\nline2\nline3\n"}),
1017                ctx,
1018            )
1019            .await;
1020        assert!(outcome.is_success(), "expected success: {:?}", outcome);
1021        assert!(outcome.output().contains("3 lines"));
1022        let written = fs::read_to_string(dir.join("out.txt")).expect("read");
1023        assert!(written.contains("line1"));
1024        let _ = fs::remove_dir_all(&dir);
1025    }
1026
1027    #[tokio::test]
1028    async fn concurrent_write_file_same_path_serializes_cleanly() {
1029        // The per-path write gate must let two writes to the same file in one turn
1030        // both succeed and leave the file as exactly one clean write (never a
1031        // corrupt interleave), and must not deadlock.
1032        let dir = temp_root("write_race");
1033        let (ctx1, _r1) = test_exec_context(TurnId(1), ToolCallId(1), dir.clone());
1034        let (ctx2, _r2) = test_exec_context(TurnId(1), ToolCallId(2), dir.clone());
1035        let a = "AAAA\nAAAA\n";
1036        let b = "BBBB\nBBBB\n";
1037        let (o1, o2) = tokio::join!(
1038            WriteFileTool.execute(serde_json::json!({"path": "race.txt", "content": a}), ctx1),
1039            WriteFileTool.execute(serde_json::json!({"path": "race.txt", "content": b}), ctx2),
1040        );
1041        assert!(o1.is_success(), "first write failed: {o1:?}");
1042        assert!(o2.is_success(), "second write failed: {o2:?}");
1043        let final_content = fs::read_to_string(dir.join("race.txt")).expect("read");
1044        assert!(
1045            final_content == a || final_content == b,
1046            "file must be exactly one clean write, got {final_content:?}"
1047        );
1048        let _ = fs::remove_dir_all(&dir);
1049    }
1050
1051    #[tokio::test]
1052    async fn write_file_new_file_records_added_display_diff() {
1053        let dir = temp_root("write_new_diff");
1054        let (ctx, _rx) = test_exec_context(TurnId(1), ToolCallId(1), dir.clone());
1055        let outcome = WriteFileTool
1056            .execute(
1057                serde_json::json!({"path": "out.txt", "content": "alpha\nbeta\n"}),
1058                ctx,
1059            )
1060            .await;
1061        assert!(outcome.is_success(), "expected success: {:?}", outcome);
1062        let diff = outcome
1063            .metadata
1064            .display_diff
1065            .as_deref()
1066            .expect("display diff");
1067        assert!(diff.contains("+ alpha"));
1068        assert!(diff.contains("+ beta"));
1069        // No unified-diff header clutter (`---`/`+++`/`@@`).
1070        assert!(
1071            !diff.contains("@@"),
1072            "diff should not carry hunk headers: {diff}"
1073        );
1074        assert!(!diff.contains("/dev/null"));
1075        let _ = fs::remove_dir_all(&dir);
1076    }
1077
1078    #[tokio::test]
1079    async fn write_file_existing_file_records_added_and_removed_display_diff() {
1080        let dir = temp_root("write_existing_diff");
1081        fs::write(dir.join("out.txt"), "alpha\nold\nomega\n").expect("write fixture");
1082        let (ctx, _rx) = test_exec_context(TurnId(1), ToolCallId(1), dir.clone());
1083        let outcome = WriteFileTool
1084            .execute(
1085                serde_json::json!({"path": "out.txt", "content": "alpha\nnew\nomega\n"}),
1086                ctx,
1087            )
1088            .await;
1089        assert!(outcome.is_success(), "expected success: {:?}", outcome);
1090        let diff = outcome
1091            .metadata
1092            .display_diff
1093            .as_deref()
1094            .expect("display diff");
1095        assert!(diff.contains("- old"));
1096        assert!(diff.contains("+ new"));
1097        let _ = fs::remove_dir_all(&dir);
1098    }
1099
1100    #[tokio::test]
1101    async fn write_file_creates_parent_dirs() {
1102        let dir = temp_root("write_parents");
1103        let (ctx, _rx) = test_exec_context(TurnId(1), ToolCallId(1), dir.clone());
1104        let outcome = WriteFileTool
1105            .execute(
1106                serde_json::json!({
1107                    "path": "sub/nested/out.txt",
1108                    "content": "deep",
1109                }),
1110                ctx,
1111            )
1112            .await;
1113        assert!(outcome.is_success(), "expected success: {:?}", outcome);
1114        assert!(dir.join("sub/nested/out.txt").exists());
1115        let _ = fs::remove_dir_all(&dir);
1116    }
1117
1118    #[tokio::test]
1119    async fn write_file_missing_content_errors() {
1120        let dir = temp_root("write_missing");
1121        let (ctx, _rx) = test_exec_context(TurnId(1), ToolCallId(1), dir.clone());
1122        let outcome = WriteFileTool
1123            .execute(serde_json::json!({"path": "x.txt"}), ctx)
1124            .await;
1125        assert_eq!(outcome.status, crate::domain::ToolStatus::Error);
1126        let _ = fs::remove_dir_all(&dir);
1127    }
1128
1129    // ─── F10: absolute-path block ───────────────────────────────────
1130
1131    /// Reading `/etc/passwd` (or any absolute path outside workdir)
1132    /// must fail with a clear "outside the project" error. The tool
1133    /// schema advertises this contract; before F10 it was a lie.
1134    #[tokio::test]
1135    async fn read_file_rejects_absolute_path_outside_workdir() {
1136        let dir = temp_root("read_abs_escape");
1137        let (ctx, _rx) = test_exec_context(TurnId(1), ToolCallId(1), dir.clone());
1138        // Pick a path that's definitely outside a fresh /tmp/* workdir.
1139        let outcome = ReadFileTool
1140            .execute(serde_json::json!({"path": "/etc/passwd"}), ctx)
1141            .await;
1142        let error = outcome.error_message().expect("expected error");
1143        assert!(
1144            error.contains("outside the project"),
1145            "expected security reject, got: {}",
1146            error
1147        );
1148        let _ = fs::remove_dir_all(&dir);
1149    }
1150
1151    /// Absolute path that lives INSIDE the workdir is allowed.
1152    #[tokio::test]
1153    async fn read_file_accepts_absolute_path_inside_workdir() {
1154        let dir = temp_root("read_abs_inside");
1155        let file = dir.join("hello.txt");
1156        fs::write(&file, "ok").expect("write fixture");
1157        let (ctx, _rx) = test_exec_context(TurnId(1), ToolCallId(1), dir.clone());
1158        let outcome = ReadFileTool
1159            .execute(
1160                serde_json::json!({"path": file.to_string_lossy().to_string()}),
1161                ctx,
1162            )
1163            .await;
1164        assert!(outcome.is_success(), "expected success: {:?}", outcome);
1165        let _ = fs::remove_dir_all(&dir);
1166    }
1167
1168    /// Relative `..`-escape must also be blocked — they resolve against
1169    /// the workdir and land outside it, so the lexical normalization
1170    /// in `resolve_in_roots` catches them.
1171    #[tokio::test]
1172    async fn write_file_rejects_relative_parent_escape() {
1173        let dir = temp_root("write_dotdot_escape");
1174        let (ctx, _rx) = test_exec_context(TurnId(1), ToolCallId(1), dir.clone());
1175        let outcome = WriteFileTool
1176            .execute(
1177                serde_json::json!({
1178                    "path": "../escape.txt",
1179                    "content": "should not write",
1180                }),
1181                ctx,
1182            )
1183            .await;
1184        let error = outcome.error_message().expect("expected error");
1185        assert!(
1186            error.contains("outside the project"),
1187            "expected security reject, got: {}",
1188            error
1189        );
1190        let _ = fs::remove_dir_all(&dir);
1191    }
1192
1193    /// `create_directory` needs the lexical-normalization fallback
1194    /// because the target doesn't exist yet (can't canonicalize).
1195    /// Verify the escape check still fires for non-existent targets.
1196    #[tokio::test]
1197    async fn create_directory_rejects_absolute_path_outside_workdir() {
1198        let dir = temp_root("mkdir_abs_escape");
1199        let (ctx, _rx) = test_exec_context(TurnId(1), ToolCallId(1), dir.clone());
1200        let outcome = CreateDirectoryTool
1201            .execute(
1202                serde_json::json!({"path": "/tmp/mermaid_fs_escape_target"}),
1203                ctx,
1204            )
1205            .await;
1206        let error = outcome.error_message().expect("expected error");
1207        assert!(
1208            error.contains("outside the project"),
1209            "expected security reject, got: {}",
1210            error
1211        );
1212        let _ = fs::remove_dir_all(&dir);
1213    }
1214
1215    // ─── session-scratchpad dual root ────────────────────────────────
1216
1217    /// Build an `ExecContext` with an explicit safety mode, NO approval
1218    /// broker, and (optionally) a materialized scratchpad. Unlike
1219    /// `test_exec_context` (pinned to FullAccess) this exercises the gate.
1220    fn scratch_ctx(
1221        mode: crate::runtime::SafetyMode,
1222        workdir: PathBuf,
1223        scratchpad: Option<PathBuf>,
1224    ) -> (ExecContext, tokio::sync::mpsc::Receiver<ProgressEvent>) {
1225        let mut config = crate::app::Config::default();
1226        config.safety.mode = mode;
1227        let (tx, rx) = tokio::sync::mpsc::channel(8);
1228        let mut ctx = ExecContext::new(
1229            tokio_util::sync::CancellationToken::new(),
1230            tx,
1231            ToolCallId(1),
1232            TurnId(1),
1233            workdir,
1234            std::sync::Arc::new(config),
1235            String::new(),
1236            None,
1237            None,
1238            None,
1239            mode,
1240            None,
1241            None,
1242            None,
1243            None,
1244            None,
1245        );
1246        ctx.scratchpad = scratchpad;
1247        (ctx, rx)
1248    }
1249
1250    /// Project + scratch fixture pair with a unique, greppable name.
1251    fn scratch_fixture(name: &str) -> (PathBuf, PathBuf) {
1252        let base = std::env::temp_dir().join(format!(
1253            "mermaid_fs_scratch_{}_{}",
1254            name,
1255            std::process::id()
1256        ));
1257        let _ = fs::remove_dir_all(&base);
1258        let project = base.join("project");
1259        let scratch = base.join("scratch");
1260        fs::create_dir_all(&project).unwrap();
1261        fs::create_dir_all(&scratch).unwrap();
1262        (project, scratch)
1263    }
1264
1265    /// True when any checkpoint manifest on disk references `marker`. The
1266    /// fixture paths are unique per test+pid, so a hit can only come from
1267    /// the mutation under test.
1268    fn any_checkpoint_mentions(marker: &str) -> bool {
1269        let Ok(data) = crate::runtime::data_dir() else {
1270            return false;
1271        };
1272        let Ok(entries) = fs::read_dir(data.join("checkpoints")) else {
1273            return false;
1274        };
1275        entries.flatten().any(|entry| {
1276            fs::read_to_string(entry.path().join("manifest.json"))
1277                .is_ok_and(|manifest| manifest.contains(marker))
1278        })
1279    }
1280
1281    /// Scratchpad mutations proceed in Ask mode with NO approval broker
1282    /// bound (the gate is bypassed entirely) and never take a checkpoint.
1283    #[tokio::test]
1284    async fn scratch_mutations_are_ungated_and_never_checkpointed() {
1285        let (project, scratch) = scratch_fixture("ungated");
1286        let marker = scratch.display().to_string();
1287
1288        // write_file into the scratchpad via absolute path.
1289        let file = scratch.join("notes.txt");
1290        let (ctx, _rx) = scratch_ctx(
1291            crate::runtime::SafetyMode::Ask,
1292            project.clone(),
1293            Some(scratch.clone()),
1294        );
1295        let outcome = WriteFileTool
1296            .execute(
1297                serde_json::json!({
1298                    "path": file.to_str().unwrap(),
1299                    "content": "scratch note\n",
1300                }),
1301                ctx,
1302            )
1303            .await;
1304        assert!(outcome.is_success(), "scratch write: {outcome:?}");
1305        assert_eq!(fs::read_to_string(&file).unwrap(), "scratch note\n");
1306
1307        // create_directory inside the scratchpad.
1308        let subdir = scratch.join("work/area");
1309        let (ctx, _rx) = scratch_ctx(
1310            crate::runtime::SafetyMode::Ask,
1311            project.clone(),
1312            Some(scratch.clone()),
1313        );
1314        let outcome = CreateDirectoryTool
1315            .execute(serde_json::json!({"path": subdir.to_str().unwrap()}), ctx)
1316            .await;
1317        assert!(outcome.is_success(), "scratch mkdir: {outcome:?}");
1318        assert!(subdir.is_dir());
1319
1320        // delete_file inside the scratchpad.
1321        let (ctx, _rx) = scratch_ctx(
1322            crate::runtime::SafetyMode::Ask,
1323            project.clone(),
1324            Some(scratch.clone()),
1325        );
1326        let outcome = DeleteFileTool
1327            .execute(serde_json::json!({"path": file.to_str().unwrap()}), ctx)
1328            .await;
1329        assert!(outcome.is_success(), "scratch delete: {outcome:?}");
1330        assert!(!file.exists());
1331
1332        // None of the mutations checkpointed the ephemeral scratch paths.
1333        assert!(
1334            !any_checkpoint_mentions(&marker),
1335            "scratch mutation must not create a checkpoint"
1336        );
1337        let _ = fs::remove_dir_all(project.parent().unwrap());
1338    }
1339
1340    /// ReadOnly still blocks scratchpad mutations — the bypass only skips
1341    /// the approval flow, never the mode's mutation ban.
1342    #[tokio::test]
1343    async fn scratch_mutation_blocked_in_read_only() {
1344        let (project, scratch) = scratch_fixture("readonly");
1345        let file = scratch.join("blocked.txt");
1346        let (ctx, _rx) = scratch_ctx(
1347            crate::runtime::SafetyMode::ReadOnly,
1348            project.clone(),
1349            Some(scratch.clone()),
1350        );
1351        let outcome = WriteFileTool
1352            .execute(
1353                serde_json::json!({
1354                    "path": file.to_str().unwrap(),
1355                    "content": "nope",
1356                }),
1357                ctx,
1358            )
1359            .await;
1360        let error = outcome.error_message().expect("expected block");
1361        assert!(
1362            error.contains("blocked by policy"),
1363            "expected policy block, got: {error}"
1364        );
1365        assert!(!file.exists());
1366        let _ = fs::remove_dir_all(project.parent().unwrap());
1367    }
1368
1369    /// A path outside BOTH roots is rejected at resolution — before the gate.
1370    #[tokio::test]
1371    async fn write_outside_both_roots_is_rejected() {
1372        let (project, scratch) = scratch_fixture("outside");
1373        let outside = project.parent().unwrap().join("elsewhere/out.txt");
1374        let (ctx, _rx) = scratch_ctx(
1375            crate::runtime::SafetyMode::Ask,
1376            project.clone(),
1377            Some(scratch.clone()),
1378        );
1379        let outcome = WriteFileTool
1380            .execute(
1381                serde_json::json!({
1382                    "path": outside.to_str().unwrap(),
1383                    "content": "should not write",
1384                }),
1385                ctx,
1386            )
1387            .await;
1388        let error = outcome.error_message().expect("expected error");
1389        assert!(
1390            error.contains("outside the project"),
1391            "expected containment reject, got: {error}"
1392        );
1393        assert!(!outside.exists());
1394        let _ = fs::remove_dir_all(project.parent().unwrap());
1395    }
1396
1397    /// read_file follows a materialized scratchpad too.
1398    #[tokio::test]
1399    async fn read_file_reads_from_scratchpad() {
1400        let (project, scratch) = scratch_fixture("read");
1401        let file = scratch.join("stash.txt");
1402        fs::write(&file, "stashed").unwrap();
1403        let (ctx, _rx) = scratch_ctx(
1404            crate::runtime::SafetyMode::Ask,
1405            project.clone(),
1406            Some(scratch.clone()),
1407        );
1408        let outcome = ReadFileTool
1409            .execute(serde_json::json!({"path": file.to_str().unwrap()}), ctx)
1410            .await;
1411        assert!(outcome.is_success(), "scratch read: {outcome:?}");
1412        assert_eq!(outcome.output(), "stashed");
1413        let _ = fs::remove_dir_all(project.parent().unwrap());
1414    }
1415}